-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeCanvas
More file actions
416 lines (361 loc) · 9.93 KB
/
SnakeCanvas
File metadata and controls
416 lines (361 loc) · 9.93 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
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import javax.swing.JOptionPane;
public class SnakeCanvas extends Canvas implements Runnable, KeyListener {
private final int BOX_HEIGHT = 15;
private final int BOX_WIDTH = 15;
private final int GRID_WIDTH = 25;
private final int GRID_HEIGHT = 25;
private LinkedList<Point> snake; // Point is for x,y coordinate
private Point fruit;
private int direction = Direction.NO_DIRECTION;
private Thread runThread;
private int score = 0;
private String highScore = "";
private Image menuImage = null;
private boolean isInMenu = true;
private boolean isAtEndGame = false;
private boolean won = false;
public void paint(Graphics g) {
setBackground(Color.YELLOW);
if (runThread == null) {
this.setPreferredSize(new Dimension(640, 480));
this.addKeyListener(this);
runThread = new Thread(this);
runThread.start();
}
if (isInMenu) {
// Things to do when menus displayed
drawMenu(g);
}
else if (isAtEndGame) {
// draw end game screen
drawEndGame(g);
}
else {
// things to do when menu is not being displayed
if (snake == null) {
snake = new LinkedList<Point>();
generateDefaultSnake();
placeFruit();
}
if (highScore.equals("")) {
// initialize highscore
highScore = this.getHighScoreValue();
}
drawGrid(g);
drawSnake(g);
drawFruit(g);
drawScore(g);
}
}
public void drawEndGame(Graphics g) {
BufferedImage endGameImage = new BufferedImage(
this.getPreferredSize().width, this.getPreferredSize().height,
BufferedImage.TYPE_INT_ARGB);
Graphics endGameGraphics = endGameImage.getGraphics();
endGameGraphics.setColor(Color.BLACK);
if (won)
endGameGraphics.drawString("WINNER WINNER",
this.getPreferredSize().width / 2,
this.getPreferredSize().height / 2);
else
endGameGraphics.drawString("You LOST",
this.getPreferredSize().width / 2,
this.getPreferredSize().height / 2);
endGameGraphics.drawString("Your score: " + this.score, this
.getPreferredSize().width / 2,
(this.getPreferredSize().height / 2) + 20); // moves 20 px below
endGameGraphics.drawString("Press \"space\" to start a new game!", this
.getPreferredSize().width / 2,
(this.getPreferredSize().height / 2) + 40);
g.drawImage(endGameImage, 0, 0, this);
}
public void drawMenu(Graphics g) {
if (menuImage == null) {
try {
URL imagePath = SnakeCanvas.class.getResource("menuImage.png");
menuImage = Toolkit.getDefaultToolkit().getImage(imagePath);
} catch (Exception e) {
// error would occur if image does not exist
e.printStackTrace();
}
}
g.drawImage(menuImage, 0, 0, 640, 480, this);
}
public void update(Graphics g) {
// default update method which contains double buffering
Graphics offScreenGraphics;// graphics to draw off screen
BufferedImage offScreen = null;
Dimension d = this.getSize();
offScreen = new BufferedImage(d.width, d.height,
BufferedImage.TYPE_INT_ARGB);
offScreenGraphics = offScreen.getGraphics();
offScreenGraphics.setColor(this.getBackground());
offScreenGraphics.fillRect(0, 0, d.width, d.height);
offScreenGraphics.setColor(this.getForeground());
paint(offScreenGraphics);
// flip
g.drawImage(offScreen, 0, 0, this);
}
public void generateDefaultSnake() {
score = 0;
snake.clear();
snake.add(new Point(0, 2));
snake.add(new Point(0, 1));
snake.add(new Point(0, 0));
direction = Direction.NO_DIRECTION;
}
public void move() {
if (direction == Direction.NO_DIRECTION)
return;
Point head = snake.peekFirst(); // gets first point on LinkedList
Point newPoint = head;
switch (direction) {
case Direction.NORTH:
newPoint = new Point(head.x, head.y - 1); // y typically goes down
// from bottom of
// screen, so reverse
break;
case Direction.SOUTH:
newPoint = new Point(head.x, head.y + 1);
break;
case Direction.WEST:
newPoint = new Point(head.x - 1, head.y);
break;
case Direction.EAST:
newPoint = new Point(head.x + 1, head.y);
break;
}
if (this.direction != Direction.NO_DIRECTION)
snake.remove(snake.peekLast()); // removes last box of the snake
// when moves
if (newPoint.equals(fruit)) {
// the snake has hit the fruit
score += 10;
Point addPoint = (Point) newPoint.clone();
switch (direction) {
case Direction.NORTH:
newPoint = new Point(head.x, head.y - 1); // y typically goes
// down from bottom
// of screen, so
// reverse
break;
case Direction.SOUTH:
newPoint = new Point(head.x, head.y + 1);
break;
case Direction.WEST:
newPoint = new Point(head.x - 1, head.y);
break;
case Direction.EAST:
newPoint = new Point(head.x + 1, head.y);
break;
}
snake.push(addPoint);
placeFruit();
} else if (newPoint.x < 0 || newPoint.x > (GRID_WIDTH - 1))// w/out -1
// you would
// be able
// to go one
// space
// into
// empty out
// of border
{
// the snake went out of bounds,resets the game
// checkScore();
won = false;
isAtEndGame = true;
return;
} else if (newPoint.y < 0 || newPoint.y > (GRID_HEIGHT - 1)) {
// the snake went out of bounds,resets the game
// checkScore();//if I remove these there is not a null point error
// anymore
won = false;
isAtEndGame = true;
return;
} else if (snake.contains(newPoint)) {
// the snake ran into itself,resets the game
if (direction != Direction.NO_DIRECTION) {
// checkScore();
won = false;
isAtEndGame = true;
return;
}
} else if (snake.size() == (GRID_WIDTH * GRID_HEIGHT)) {
// player wins!
// checkScore();
won = true;
isAtEndGame = true;
return;
}
// if player reaches this point, they're still fine
snake.push(newPoint);
}
public void drawScore(Graphics g) {
g.drawString("Score: " + score, 0, BOX_HEIGHT * GRID_HEIGHT + 10);
g.drawString("Highscore: " + highScore, 0, BOX_HEIGHT * GRID_HEIGHT
+ 20);
}
public void checkScore() {
if (highScore.equals(""))
return;
// format Noah/:/100 have to split b/c highscore is a string. Splitting
// it makes it into an array
if (score > Integer.parseInt((highScore.split(":")[2]))) {
// user set a new record
String name = JOptionPane
.showInputDialog("You set a new high score! Type your name.");
highScore = name + ":" + score;
File scoreFile = new File("highscore.dat");
if (!scoreFile.exists()) {
try {
scoreFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter writeFile = null;
BufferedWriter writer = null;
try {
writeFile = new FileWriter(scoreFile);
writer = new BufferedWriter(writeFile);
writer.write(this.highScore);
} catch (Exception e) {
// errors
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
}
}
}
}
public void drawGrid(Graphics g) {
// drawing an outside rectangle
g.drawRect(0, 0, GRID_WIDTH * BOX_WIDTH, GRID_HEIGHT * BOX_HEIGHT);
}
public void drawSnake(Graphics g) {
g.setColor(Color.GREEN);
for (Point p : snake) {
g
.fillOval(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT);
}
g.setColor(Color.BLACK);
}
public void drawFruit(Graphics g) {
g.setColor(Color.RED);
g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT);
g.setColor(Color.BLACK);
}
public void placeFruit() {
Random rand = new Random();
int randomX = rand.nextInt(GRID_WIDTH);
int randomY = rand.nextInt(GRID_HEIGHT);
Point randomPoint = new Point(randomX, randomY);
while (snake.contains(randomPoint)) {
randomX = rand.nextInt(GRID_WIDTH);
randomY = rand.nextInt(GRID_HEIGHT);
randomPoint = new Point(randomX, randomY);
}
fruit = randomPoint;
}
@Override
public void run() {
while (true) {
// runs indefinitley
repaint();
if (!isInMenu && !isAtEndGame)
move();
try {
Thread.currentThread();
Thread.sleep(100); // game updates every 10th of a second for
// speed of snake
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getHighScoreValue() {
// format: @random: 100
FileReader readFile = null;
BufferedReader reader = null;
try {
readFile = new FileReader("highscore.dat");
reader = new BufferedReader(readFile);
return reader.readLine();
} catch (Exception e) {
return "Nobody:0";
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (direction != Direction.SOUTH)
direction = Direction.NORTH;
break;
case KeyEvent.VK_DOWN:
if (direction != Direction.NORTH)
direction = Direction.SOUTH;
break;
case KeyEvent.VK_RIGHT:
if (direction != Direction.WEST)
direction = Direction.EAST;
break;
case KeyEvent.VK_LEFT:
if (direction != Direction.EAST)
direction = Direction.WEST;
break;
case KeyEvent.VK_ENTER:
if (isInMenu) {
isInMenu = false;
repaint();
}
break;
case KeyEvent.VK_ESCAPE:
isInMenu = true;
case KeyEvent.VK_SPACE:
if (isAtEndGame) {
isAtEndGame = false;
won = false;
generateDefaultSnake();
repaint();
}
break;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
}