-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.java
More file actions
106 lines (92 loc) · 2.53 KB
/
SnakeGame.java
File metadata and controls
106 lines (92 loc) · 2.53 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
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 int turnDelay;
private Apple apple;
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 i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
setCellValueEx(i, j, Color.PINK, "");
}
}
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.BLACK, "GAME OVER", Color.PINK, 70);
}
private void win(){
stopTurnTimer();
isGameStopped = true;
showMessageDialog(Color.BLACK, "YOU WIN", Color.PINK, 70);
}
@Override
public void onTurn(int a){
snake.move(apple);
if(apple.isAlive==false){
createNewApple();
score = score + 5;
setScore(score);
turnDelay = turnDelay - 10;
setTurnTimer(turnDelay);
}
if(snake.isAlive==false){
gameOver();
}
if(snake.getLength()>GOAL){
win();
}
drawScene();
}
@Override
public void onKeyPress(Key key){
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);
break;
}
if(key==Key.SPACE && isGameStopped==true) {
createGame();
}
}
}