forked from alibaba/termd
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.java
More file actions
Latest commit
209 lines (187 loc) · 5.41 KB
/
Copy pathSnakeGame.java
File metadata and controls
209 lines (187 loc) · 5.41 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
packageexamples.snake;
importio.termd.core.function.BiConsumer;
importio.termd.core.function.Consumer;
importio.termd.core.tty.TtyConnection;
importio.termd.core.tty.TtyEvent;
importio.termd.core.util.Vector;
importjava.util.HashSet;
importjava.util.LinkedList;
importjava.util.Random;
importjava.util.concurrent.TimeUnit;
/**
* The snake game implementation, fully non blocking, one thread to handle all players : massive scalability
*/
publicclassSnakeGameimplementsConsumer<TtyConnection> {
@Override
publicvoidaccept(finalTtyConnectionconn) {
if (conn.size() != null) {
newGame(conn).execute();
} else {
conn.setSizeHandler(newConsumer<Vector>() {
@Override
publicvoidaccept(Vectorsize) {
newGame(conn).execute();
}
});
}
}
enumDirection {
LEFT, RIGHT, UP, DOWN
}
/**
* The game automaton state
*/
classGameState {
finalintwidth, height;
HashSet<Vector> tiles;
LinkedList<Vector> snake = newLinkedList<Vector>();
Directiondirection;
GameState(intwidth, intheight, intsize) {
this.width = width;
this.height = height;
tiles = newHashSet<Vector>();
while (size > 0) {
intx = newRandom().nextInt(width);
inty = newRandom().nextInt(height);
Vectortile = newVector(x, y);
if (tiles.add(tile)) {
size--;
}
}
snake.addFirst(newVector(0, 0));
snake.addFirst(newVector(1, 0));
snake.addFirst(newVector(2, 0));
snake.addFirst(newVector(3, 0));
direction = Direction.RIGHT;
}
/**
* Update the state with one game iteration
*
* @throws Exception when user lose
*/
voidupdate() throwsException {
Vectorcurr = snake.peekFirst();
Vectornext = null;
switch (direction) {
caseRIGHT:
next = newVector(curr.x() + 1, curr.y());
break;
caseLEFT:
next = newVector(curr.x() - 1, curr.y());
break;
caseUP:
next = newVector(curr.x(), curr.y() - 1);
break;
caseDOWN:
next = newVector(curr.x(), curr.y() + 1);
break;
}
if (next.x() < 0 || next.x() >= width || next.y() < 0 || next.y() >= height || snake.contains(next)) {
thrownewException("lost");
}
if (!tiles.remove(next)) {
// Eat a tile : grow
snake.removeLast();
}
snake.addFirst(next);
}
}
/**
* The game itself.
*/
classGame {
finalTtyConnectionconn;
GameStategame;
booleaninterrupted;
publicGame(finalTtyConnectionconn) {
this.conn = conn;
// When user resize the screen : launch a new game
conn.setSizeHandler(newConsumer<Vector>() {
@Override
publicvoidaccept(Vectorsize) {
reset(size);
}
});
// Ctrl-C ends the game
conn.setEventHandler(newBiConsumer<TtyEvent, Integer>() {
@Override
publicvoidaccept(TtyEventevent, Integerch) {
switch (event) {
caseINTR:
interrupted = true;
conn.close();
break;
}
}
});
// Keyboard handling
conn.setStdinHandler(newConsumer<int[]>() {
@Override
publicvoidaccept(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
*/
voidexecute() {
if (interrupted) {
return;
}
GameStategame = this.game;
// Compute the ANSI magic string that draws the game
StringBuilderbuf = newStringBuilder();
for (inty = 0;y < game.height;y++) {
buf.append("\033[").append(y + 1).append(";1H\033[K");
}
for (Vectortile : game.tiles) {
buf.append("\033[").append(tile.y() + 1).append(";").append(tile.x() + 1).append("H").append("X");
}
for (Vectortile : 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 (Exceptione) {
conn.write("YOU LOST");
conn.close();
return;
}
// Schedule a new execution of the game
conn.schedule(newRunnable() {
@Override
publicvoidrun() {
execute();
}
}, 500, TimeUnit.MILLISECONDS);
}
privatevoidreset(Vectorsize) {
// Fill factory area / 25
game = newGameState(size.x(), size.y(), (size.x() * size.y()) / 10);
}
}
}