-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnakeGame.java
106 lines (90 loc) · 2.55 KB
/
SnakeGame.java
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
package com.javarush.games.snake;
import com.javarush.engine.cell.Color;
import com.javarush.engine.cell.Game;
import com.javarush.engine.cell.Key;
public class SnakeGame extends Game {
public static final int WIDTH = 15;
public static final int HEIGHT = 15;
private static final int GOAL = 28;
private Snake snake;
private Apple apple;
private int turnDelay;
private int score;
private boolean isGameStopped;
@Override
public void initialize() {
setScreenSize(WIDTH, HEIGHT);
createGame();
}
@Override
public void onTurn(int step) {
snake.move(apple);
if (!apple.isAlive) {
createNewApple();
score += 5;
setScore(score);
turnDelay -= 10;
setTurnTimer(turnDelay);
}
if (!snake.isAlive) {
gameOver();
}
if (snake.getLength() > GOAL) {
win();
}
drawScene();
}
@Override
public void onKeyPress(Key key) {
if (key == Key.SPACE && isGameStopped) {
createGame();
}
if (key == Key.LEFT) {
snake.setDirection(Direction.LEFT);
} else if (key == Key.RIGHT) {
snake.setDirection(Direction.RIGHT);
} else if (key == Key.UP) {
snake.setDirection(Direction.UP);
} else if (key == Key.DOWN) {
snake.setDirection(Direction.DOWN);
}
}
private void createGame() {
snake = new Snake(WIDTH / 2, HEIGHT / 2);
createNewApple();
isGameStopped = false;
drawScene();
turnDelay = 300;
setTurnTimer(turnDelay);
score = 0;
setScore(score);
}
private void drawScene() {
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < HEIGHT; y++) {
setCellValueEx(x, y, Color.DARKSEAGREEN, "");
}
}
snake.draw(this);
apple.draw(this);
}
private void createNewApple() {
Apple newApple;
do {
int x = getRandomNumber(WIDTH);
int y = getRandomNumber(HEIGHT);
newApple = new Apple(x, y);
} while (snake.checkCollision(newApple));
apple = newApple;
}
private void gameOver() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.NONE, "Game over!", Color.RED, 50);
}
private void win() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.NONE, "You win!", Color.GREEN, 50);
}
}