-
Notifications
You must be signed in to change notification settings - Fork 50
/
SnakeGame.java
209 lines (187 loc) · 5.41 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
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
package examples.snake;
import io.termd.core.function.BiConsumer;
import io.termd.core.function.Consumer;
import io.termd.core.tty.TtyConnection;
import io.termd.core.tty.TtyEvent;
import io.termd.core.util.Vector;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* The snake game implementation, fully non blocking, one thread to handle all players : massive scalability
*/
public class SnakeGame implements Consumer<TtyConnection> {
@Override
public void accept(final TtyConnection conn) {
if (conn.size() != null) {
new Game(conn).execute();
} else {
conn.setSizeHandler(new Consumer<Vector>() {
@Override
public void accept(Vector size) {
new Game(conn).execute();
}
});
}
}
enum Direction {
LEFT, RIGHT, UP, DOWN
}
/**
* The game automaton state
*/
class GameState {
final int width, height;
HashSet<Vector> tiles;
LinkedList<Vector> snake = new LinkedList<Vector>();
Direction direction;
GameState(int width, int height, int size) {
this.width = width;
this.height = height;
tiles = new HashSet<Vector>();
while (size > 0) {
int x = new Random().nextInt(width);
int y = new Random().nextInt(height);
Vector tile = new Vector(x, y);
if (tiles.add(tile)) {
size--;
}
}
snake.addFirst(new Vector(0, 0));
snake.addFirst(new Vector(1, 0));
snake.addFirst(new Vector(2, 0));
snake.addFirst(new Vector(3, 0));
direction = Direction.RIGHT;
}
/**
* Update the state with one game iteration
*
* @throws Exception when user lose
*/
void update() throws Exception {
Vector curr = snake.peekFirst();
Vector next = null;
switch (direction) {
case RIGHT:
next = new Vector(curr.x() + 1, curr.y());
break;
case LEFT:
next = new Vector(curr.x() - 1, curr.y());
break;
case UP:
next = new Vector(curr.x(), curr.y() - 1);
break;
case DOWN:
next = new Vector(curr.x(), curr.y() + 1);
break;
}
if (next.x() < 0 || next.x() >= width || next.y() < 0 || next.y() >= height || snake.contains(next)) {
throw new Exception("lost");
}
if (!tiles.remove(next)) {
// Eat a tile : grow
snake.removeLast();
}
snake.addFirst(next);
}
}
/**
* The game itself.
*/
class Game {
final TtyConnection conn;
GameState game;
boolean interrupted;
public Game(final TtyConnection conn) {
this.conn = conn;
// When user resize the screen : launch a new game
conn.setSizeHandler(new Consumer<Vector>() {
@Override
public void accept(Vector size) {
reset(size);
}
});
// Ctrl-C ends the game
conn.setEventHandler(new BiConsumer<TtyEvent, Integer>() {
@Override
public void accept(TtyEvent event, Integer ch) {
switch (event) {
case INTR:
interrupted = true;
conn.close();
break;
}
}
});
// Keyboard handling
conn.setStdinHandler(new Consumer<int[]>() {
@Override
public void accept(int[] keys) {
if (keys.length == 3) {
if (keys[0] == 27 && keys[1] == '[') {
switch (keys[2]) {
case 'A':
game.direction = Direction.UP;
break;
case 'B':
game.direction = Direction.DOWN;
break;
case 'C':
game.direction = Direction.RIGHT;
break;
case 'D':
game.direction = Direction.LEFT;
break;
}
}
}
}
});
// Init current game
reset(conn.size());
}
/**
* Execute one iteration of the game, at the end schedule the next iteration until user lose or hits Ctrl-C
*/
void execute() {
if (interrupted) {
return;
}
GameState game = this.game;
// Compute the ANSI magic string that draws the game
StringBuilder buf = new StringBuilder();
for (int y = 0;y < game.height;y++) {
buf.append("\033[").append(y + 1).append(";1H\033[K");
}
for (Vector tile : game.tiles) {
buf.append("\033[").append(tile.y() + 1).append(";").append(tile.x() + 1).append("H").append("X");
}
for (Vector tile : game.snake) {
buf.append("\033[").append(tile.y() + 1).append(";").append(tile.x() + 1).append("H").append('0');
}
buf.append("\033[").append(game.height).append(";").append(game.width).append("H\033[K");
// Update screen
conn.write(buf.toString());
// Now update game and handle losing the game
try {
game.update();
} catch (Exception e) {
conn.write("YOU LOST");
conn.close();
return;
}
// Schedule a new execution of the game
conn.schedule(new Runnable() {
@Override
public void run() {
execute();
}
}, 500, TimeUnit.MILLISECONDS);
}
private void reset(Vector size) {
// Fill factory area / 25
game = new GameState(size.x(), size.y(), (size.x() * size.y()) / 10);
}
}
}