-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.java
More file actions
104 lines (90 loc) · 2.59 KB
/
SnakeGame.java
File metadata and controls
104 lines (90 loc) · 2.59 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
package com.javarush.games.snake;
import com.javarush.engine.cell.*;
public class SnakeGame extends Game {
public static final int WIDTH = 15;
public static final int HEIGHT = 15;
private Snake snake;
private Apple apple;
private int turnDelay;
private boolean isGameStopped;
private static final int GOAL = 28;
private int score;
@Override
public void initialize() {
setScreenSize(WIDTH, HEIGHT);
createGame();
}
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);
}
@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() > 28)
win();
drawScene();
}
@Override
public void onKeyPress(Key key) {
if (key == Key.SPACE && isGameStopped)
createGame();
switch (key)
{
case LEFT:
snake.setDirection(Direction.LEFT);
break;
case RIGHT:
snake.setDirection(Direction.RIGHT);
break;
case UP:
snake.setDirection(Direction.UP);
break;
case DOWN:
snake.setDirection(Direction.DOWN);
}
}
private void createNewApple() {
while (true) {
int x = getRandomNumber(WIDTH);
int y = getRandomNumber(HEIGHT);
apple = new Apple(x, y);
if (!snake.checkCollision(apple))
break;
}
}
private void gameOver() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.BLACK, "GAME OVER", Color.WHITE, 55);
}
private void win() {
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.BLACK, "YOU WIN", Color.WHITE, 55);
}
}