-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeBoard.java
More file actions
630 lines (540 loc) · 17.8 KB
/
SnakeBoard.java
File metadata and controls
630 lines (540 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
@SuppressWarnings("serial")
public class SnakeBoard extends JPanel implements ActionListener
{
// Height and width of the window
private final static int BOARDWIDTH = 720;
private final static int BOARDHEIGHT = 720 ;
// Pixel size of snake and joints
private final static int PIXELSIZE = 10;
// The total amount of pixels of the game
private final static int TOTALPIXELS = (BOARDWIDTH * BOARDHEIGHT) / (PIXELSIZE * PIXELSIZE);
// Check to see if the game just started
private boolean startGame = true;
// Check to see if the game is running for both snakes
private boolean inGame1 = true;
private boolean inGame2 = true;
// Timer
private Timer timer;
// Used to set game speed, the lower the #, the faster the snake travels
private static int speed = 50;
// Instantiates snakes
// Snake = Red
// Snake2 = Blue
private Snake snake = new Snake();
private Snake snake2 = new Snake();
// Variable that stores if game is over or not
private boolean gameOver = false;
// Scores of both snakes
private int snakeOneScore = 0;
private int snakeTwoScore = 0;
public SnakeBoard()
{
InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "RightArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "LeftArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "UpArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "DownArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "D");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "A");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "W");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "S");
am.put("RightArrow", new ArrowAction("RightArrow"));
am.put("LeftArrow", new ArrowAction("LeftArrow"));
am.put("UpArrow", new ArrowAction("UpArrow"));
am.put("DownArrow", new ArrowAction("DownArrow"));
am.put("D", new ArrowAction("D"));
am.put("A", new ArrowAction("A"));
am.put("W", new ArrowAction("W"));
am.put("S", new ArrowAction("S"));
setBackground(Color.BLACK);
setFocusable(true);
setPreferredSize(new Dimension(BOARDWIDTH, BOARDHEIGHT));
initializeGame();
}
static void setDifficulty(int d)
{
if (d==1)
{
speed = 20;
}
else if (d==2)
{
speed = 35;
}
else
{
speed = 50;
}
}
/**
* Paints components to screen
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (startGame)
{
try
{
drawStart(g);
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else
{
draw(g);
}
}
/**
* Draws snake
* Uses repaint method
* @param g
* @throws InterruptedException
*/
void drawStart(Graphics g)
{
startGame(g);
startGame = false;
}
void draw(Graphics g)
{
// Only draw if the game is running / the snake is alive
if (inGame1 == true && inGame2 == true)
{
// Draw snake 1.
for (int i = 0; i < snake.getJoints(); i++)
{
// Snake's head
if (i == 0)
{
g.setColor(Color.WHITE);
g.fillRect(snake.getSnakeX(i), snake.getSnakeY(i), PIXELSIZE, PIXELSIZE);
// Body of snake
}
else
{
g.setColor(Color.RED);
g.fillRect(snake.getSnakeX(i), snake.getSnakeY(i), PIXELSIZE, PIXELSIZE);
}
}
// Draw snake 2.
for (int i = 0; i < snake2.getJoints(); i++)
{
// Snake's head
if (i == 0)
{
g.setColor(Color.WHITE);
g.fillRect(snake2.getSnakeX(i), snake2.getSnakeY(i), PIXELSIZE, PIXELSIZE);
// Body of snake
}
else {
g.setColor(Color.BLUE);
g.fillRect(snake2.getSnakeX(i), snake2.getSnakeY(i), PIXELSIZE, PIXELSIZE);
}
}
// Syncs graphics
Toolkit.getDefaultToolkit().sync();
}
// Ends game if both die at same time
else if (!inGame1 && !inGame2)
{
endGame(g);
}
// Ends game if Red dies first
else if (!inGame1)
{
endGame1(g);
}
// Ends game if Blue dies first
else if (!inGame2)
{
endGame2(g);
}
}
/**
* Creates the two snakes, starts game
*/
void initializeGame()
{
snake.reset();
snake2.reset();
// Set game running
inGame1 = true;
inGame2 = true;
// set snake1 initial size
snake.setJoints(1);
// set snake2 initial size
snake2.setJoints(1);
// Create snake1 body
for (int i = 0; i < snake.getJoints(); i++)
{
snake.setSnakeX((BOARDWIDTH / 2) - 20);
snake.setSnakeY(BOARDHEIGHT / 2);
}
// Create snake2 body
for (int i = 0; i < snake2.getJoints(); i++)
{
snake2.setSnakeX((BOARDWIDTH / 2) + 20);
snake2.setSnakeY(BOARDHEIGHT / 2);
}
// Set snakes moving up
snake.setMovingUp(true);
snake.setMovingDown(false);
snake.setMovingLeft(false);
snake.setMovingRight(false);
snake2.setMovingUp(true);
snake2.setMovingDown(false);
snake2.setMovingLeft(false);
snake2.setMovingRight(false);
// set the timer to record game's speed, animate
timer = new Timer(speed, this);
// Allows time before starting
timer.setInitialDelay(2000);
timer.start();
}
/**
* Check collisions between snake and itself and edges of game board
*/
void checkCollisions()
{
// If the snake1 hits its own joints
for (int i = snake.getJoints(); i > 0; i--)
{
if ((snake.getSnakeX(0) == snake.getSnakeX(i) && (snake.getSnakeY(0) == snake.getSnakeY(i))))
{
inGame1 = false;
System.out.println("snake 1 hit own joints");
}
}
// If the snake2 hits its own joints
for (int i = snake2.getJoints(); i > 0; i--)
{
if ((snake2.getSnakeX(0) == snake2.getSnakeX(i) && (snake2.getSnakeY(0) == snake2.getSnakeY(i))))
{
inGame2 = false;
System.out.println("snake 2 hit own joints");
}
}
// If the snake1 hits snake2 joints
for (int i = snake.getJoints(); i > 0; i--)
{
if (
(snake.getSnakeX(0) == snake2.getSnakeX(i) && snake.getSnakeY(0) == snake2.getSnakeY(i))
||
(snake.getSnakeX(0) == snake2.getSnakeX(0) && snake.getSnakeY(0) == snake2.getSnakeY(0))
)
{
inGame1 = false;
System.out.println("snake 1 hit snake 2 joints");
}
}
// If the snake2 hits snake1 joints
for (int i = snake2.getJoints(); i > 0; i--)
{
if (
(snake2.getSnakeX(0) == snake.getSnakeX(i) && snake2.getSnakeY(0) == snake.getSnakeY(i))
||
(snake2.getSnakeX(0) == snake.getSnakeX(0) && snake2.getSnakeY(0) == snake.getSnakeY(0))
)
{
inGame2 = false;
System.out.println("Snake 2 hit snake 1 joints");
}
}
// If the snake1 hits board edges
if (snake.getSnakeY(0) >= BOARDHEIGHT || snake.getSnakeY(0)<0
|| snake.getSnakeX(0) >= BOARDWIDTH || snake.getSnakeX(0) < 0)
{
inGame1 = false;
System.out.println("snake 1 hit own board edges");
}
// If the snake2 hits board edges
if (snake2.getSnakeY(0) >= BOARDHEIGHT || snake2.getSnakeY(0)<0
|| snake2.getSnakeX(0) >= BOARDWIDTH || snake2.getSnakeX(0)<0)
{
inGame2 = false;
System.out.println("snake 2 hit own board edges");
}
// If the game ends, end timer
if (!inGame1 || !inGame2)
{
timer.stop();
}
}
/**
* Starts off the game with messages
* @param g
* @throws InterruptedException
*/
void startGame(Graphics g)
{
// Start off messages
String message = "GET READY...";
Font font = new Font("Times New Roman", Font.BOLD, 40);
FontMetrics metrics = getFontMetrics(font);
g.setColor(Color.WHITE);
g.setFont(font);
g.drawString(message, (BOARDWIDTH - metrics.stringWidth(message)) / 2, BOARDHEIGHT / 2);
}
/**
* If both die at same time
* @param g
*/
void endGame(Graphics g)
{
String message3 = "";
String message5 = "";
// Create a message telling the player the game is over
String message = "TIE!";
String message2 = "Press the enter key to replay";
message3 += snakeOneScore;
String message4 = "-";
message5 += snakeTwoScore;
// Creates font
Font font = new Font("Times New Roman", Font.BOLD, 40);
Font font2 = new Font("Times New Roman", Font.BOLD,12);
Font font3 = new Font("Times New Roman", Font.BOLD, 40);
Font font4 = new Font("Times New Roman", Font.BOLD, 40);
Font font5 = new Font("Times New Roman", Font.BOLD, 40);
FontMetrics metrics = getFontMetrics(font);
FontMetrics metrics2 = getFontMetrics(font2);
FontMetrics metrics3 = getFontMetrics(font3);
FontMetrics metrics4 = getFontMetrics(font4);
FontMetrics metrics5 = getFontMetrics(font5);
// Sets the color and creates font
g.setColor(Color.MAGENTA);
g.setFont(font);
g.drawString(message, (BOARDWIDTH - metrics.stringWidth(message)) / 2, (BOARDHEIGHT / 2));
g.setFont(font2);
g.drawString(message2, (BOARDWIDTH - metrics2.stringWidth(message2)) / 2, (BOARDHEIGHT / 2)+30);
g.setColor(Color.RED);
g.setFont(font3);
g.drawString(message3, ((BOARDWIDTH - metrics3.stringWidth(message3)) / 2)-15, (BOARDHEIGHT / 2)+80);
g.setColor(Color.WHITE);
g.setFont(font4);
g.drawString(message4, ((BOARDWIDTH - metrics4.stringWidth(message4)) / 2), (BOARDHEIGHT / 2)+80);
g.setColor(Color.BLUE);
g.setFont(font5);
g.drawString(message5, ((BOARDWIDTH - metrics5.stringWidth(message5)) / 2)+15, (BOARDHEIGHT / 2)+80);
gameOver = true;
InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "Enter");
am.put("Enter", new ArrowAction("Enter"));
}
/**
* If Red dies first
* @param g
*/
void endGame1(Graphics g)
{
snakeTwoScore++;
String message3 = "";
String message5 = "";
// Create a message telling the player the game is over
String message = "BLUE WINS!";
String message2 = "Press the enter key to replay";
message3 += snakeOneScore;
String message4 = "-";
message5 += snakeTwoScore;
// Creates font
Font font = new Font("Times New Roman", Font.BOLD, 40);
Font font2 = new Font("Times New Roman", Font.BOLD,12);
Font font3 = new Font("Times New Roman", Font.BOLD, 40);
Font font4 = new Font("Times New Roman", Font.BOLD, 40);
Font font5 = new Font("Times New Roman", Font.BOLD, 40);
FontMetrics metrics = getFontMetrics(font);
FontMetrics metrics2 = getFontMetrics(font2);
FontMetrics metrics3 = getFontMetrics(font3);
FontMetrics metrics4 = getFontMetrics(font4);
FontMetrics metrics5 = getFontMetrics(font5);
// Sets the color and creates font
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(message, (BOARDWIDTH - metrics.stringWidth(message)) / 2, (BOARDHEIGHT / 2));
g.setFont(font2);
g.drawString(message2, (BOARDWIDTH - metrics2.stringWidth(message2)) / 2, (BOARDHEIGHT / 2)+30);
g.setColor(Color.RED);
g.setFont(font3);
g.drawString(message3, ((BOARDWIDTH - metrics3.stringWidth(message3)) / 2)-15, (BOARDHEIGHT / 2)+80);
g.setColor(Color.WHITE);
g.setFont(font4);
g.drawString(message4, ((BOARDWIDTH - metrics4.stringWidth(message4)) / 2), (BOARDHEIGHT / 2)+80);
g.setColor(Color.BLUE);
g.setFont(font5);
g.drawString(message5, ((BOARDWIDTH - metrics5.stringWidth(message5)) / 2)+15, (BOARDHEIGHT / 2)+80);
gameOver = true;
InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "Enter");
am.put("Enter", new ArrowAction("Enter"));
}
/**
* If Blue dies first
* @param g
*/
void endGame2(Graphics g)
{
snakeOneScore++;
String message3 = "";
String message5 = "";
// Create a message telling the player the game is over
String message = "RED WINS!";
String message2 = "Press the enter key to replay";
message3 += snakeOneScore;
String message4 = "-";
message5 += snakeTwoScore;
// Creates font
Font font = new Font("Times New Roman", Font.BOLD, 40);
Font font2 = new Font("Times New Roman", Font.BOLD,12);
Font font3 = new Font("Times New Roman", Font.BOLD, 40);
Font font4 = new Font("Times New Roman", Font.BOLD, 40);
Font font5 = new Font("Times New Roman", Font.BOLD, 40);
FontMetrics metrics = getFontMetrics(font);
FontMetrics metrics2 = getFontMetrics(font2);
FontMetrics metrics3 = getFontMetrics(font3);
FontMetrics metrics4 = getFontMetrics(font4);
FontMetrics metrics5 = getFontMetrics(font5);
// Sets the color and creates font
g.setColor(Color.RED);
g.setFont(font);
g.drawString(message, (BOARDWIDTH - metrics.stringWidth(message)) / 2, (BOARDHEIGHT / 2));
g.setFont(font2);
g.drawString(message2, (BOARDWIDTH - metrics2.stringWidth(message2)) / 2, (BOARDHEIGHT / 2)+30);
g.setColor(Color.RED);
g.setFont(font3);
g.drawString(message3, ((BOARDWIDTH - metrics3.stringWidth(message3)) / 2)-15, (BOARDHEIGHT / 2)+80);
g.setColor(Color.WHITE);
g.setFont(font4);
g.drawString(message4, ((BOARDWIDTH - metrics4.stringWidth(message4)) / 2), (BOARDHEIGHT / 2)+80);
g.setColor(Color.BLUE);
g.setFont(font5);
g.drawString(message5, ((BOARDWIDTH - metrics5.stringWidth(message5)) / 2)+15, (BOARDHEIGHT / 2)+80);
gameOver = true;
InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "Enter");
am.put("Enter", new ArrowAction("Enter"));
}
/**
* Runs constantly if game is running
* Checks for collisions and reanimates
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (inGame1 == true && inGame2 == true)
{
checkCollisions();
snake.move();
snake2.move();
repaint();
}
}
public class ArrowAction extends AbstractAction
{
private String cmd;
public ArrowAction(String cmd)
{
this.cmd = cmd;
}
@Override
public void actionPerformed(ActionEvent e)
{
// Directs movement for snake1
if (cmd.equalsIgnoreCase("A") && (!snake.isMovingRight()))
{
snake.setMovingLeft(true);
snake.setMovingUp(false);
snake.setMovingDown(false);
}
else if (cmd.equalsIgnoreCase("D") && (!snake.isMovingLeft()))
{
snake.setMovingRight(true);
snake.setMovingUp(false);
snake.setMovingDown(false);
}
else if (cmd.equalsIgnoreCase("W") && (!snake.isMovingDown()))
{
snake.setMovingUp(true);
snake.setMovingRight(false);
snake.setMovingLeft(false);
}
else if (cmd.equalsIgnoreCase("S") && (!snake.isMovingUp()))
{
snake.setMovingDown(true);
snake.setMovingRight(false);
snake.setMovingLeft(false);
}
// Directs movement for snake2
else if (cmd.equalsIgnoreCase("LeftArrow") && (!snake2.isMovingRight()))
{
snake2.setMovingLeft(true);
snake2.setMovingUp(false);
snake2.setMovingDown(false);
}
else if (cmd.equalsIgnoreCase("RightArrow") && (!snake2.isMovingLeft()))
{
snake2.setMovingRight(true);
snake2.setMovingUp(false);
snake2.setMovingDown(false);
}
else if (cmd.equalsIgnoreCase("UpArrow") && (!snake2.isMovingDown()))
{
snake2.setMovingUp(true);
snake2.setMovingRight(false);
snake2.setMovingLeft(false);
}
else if (cmd.equalsIgnoreCase("DownArrow") && (!snake2.isMovingUp()))
{
snake2.setMovingDown(true);
snake2.setMovingRight(false);
snake2.setMovingLeft(false);
}
else if (cmd.equalsIgnoreCase("Enter") && (gameOver))
{
startGame = true;
repaint();
revalidate();
initializeGame();
}
}
}
/**
* Returns total amount of pixels
* @return
*/
public static int getAllDots()
{
return TOTALPIXELS;
}
/**
* Returns size of joints
* @return
*/
public static int getDotSize()
{
return PIXELSIZE;
}
}