-
Notifications
You must be signed in to change notification settings - Fork 0
/
SnakeGame.js
365 lines (350 loc) · 10.5 KB
/
SnakeGame.js
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
(function(){
/*
* The magic happens in runGameFrame()
*/
function SnakeGame() {
var timePerFrame = 0;
var gameOn = undefined;
var gameIsOn = false;
var canvas = document.getElementById("snake");
var ctx = canvas.getContext("2d");
var start = undefined;
var apple = {
"radius" : 5,
"resetLocation" : function() {
this.x = Math.floor(Math.random() * canvas.width);
this.y = Math.floor(Math.random() * canvas.height);
// Don't allow any part of apple to load offscreen
if (this.x < this.radius) {
this.x += this.radius;
} else if (this.x > (canvas.width - this.radius)) {
this.x -= this.radius;
} else if (this.y < this.radius) {
this.y += this.radius;
} else if (this.y > (canvas.height - this.radius)) {
this.y -= this.radius;
}
},
"drawAt" : function(x, y) {
ctx.moveTo(x + this.radius, y);
ctx.arc(x, y, this.radius, 0, 2 * Math.PI);
ctx.fillStyle = "white";
ctx.fill();
}
};
var snake = {
"getLength" : function() {
var actualLength = 0;
var old = {
"x" : this.tail.x,
"y" : this.tail.y
}
this.body.forEach(function(obj) {
actualLength += getDistance(old, obj);
old.x = obj.x;
old.y = obj.y;
});
return actualLength;
},
"tryToEat" : function(apple) {
var snakeHead = {
"x" : this.body[this.body.length - 1].x,
"y" : this.body[this.body.length - 1].y,
}
if (
snakeHead.x >= (apple.x - apple.radius) &&
snakeHead.x <= (apple.x + apple.radius) &&
snakeHead.y >= (apple.y - apple.radius) &&
snakeHead.y <= (apple.y + apple.radius)
) {
apple.resetLocation();
return true;
}
return false;
},
"chopTailEnd" : function() {
var tailEnd = this.body.shift();
this.tail.x = tailEnd.x;
this.tail.y = tailEnd.y;
},
"shrinkTail" : function() {
if (this.body[0].direction === "up") {
this.tail.y -= 1;
} else if (this.body[0].direction === "right") {
this.tail.x += 1;
} else if (this.body[0].direction === "down") {
this.tail.y += 1;
} else { //Left
this.tail.x -= 1;
}
},
/**
* Called each time snake moves if it does not
* eat an apple.
*/
"shrink" : function() {
if (getDistance(this.tail, this.body[0]) > 1) {
this.shrinkTail();
} else {
this.chopTailEnd();
}
},
/**
* After eating an apple, grow this.growLength - 1
* Moving the snake grows it one pixel, so we don't need to grow the
* full growLength.
*/
"grow" : function() {
var head = this.body[this.body.length - 1];
if (head.direction === "up") {
head.y -= (this.growLength - 1);
} else if (head.direction === "right") {
head.x += (this.growLength - 1);
} else if (head.direction === "down") {
head.y += (this.growLength - 1);
} else { //Left
head.x -= (this.growLength - 1);
}
},
/**
* @param direction, e.g. "up", "right", "down", "left"
* @param x, e.g. -1
* @param y, e.g. 0
*/
"move" : function(direction, x, y) {
var headSegment = this.body[this.body.length - 1];
if (headSegment.direction === direction) {
headSegment.x = headSegment.x + x;
headSegment.y = headSegment.y + y;
} else {
this.body.push(
{
"direction" : direction,
"x" : headSegment.x + x,
"y" : headSegment.y + y
}
);
}
},
"hasCrashed" : function() {
var snakeFrom = {
"x" : this.tail.x,
"y" : this.tail.y,
};
var head = {
"x" : this.body[this.body.length - 1].x,
"y" : this.body[this.body.length - 1].y
};
//If crashed into walls
if (
head.y < 0 ||
head.x > canvas.width ||
head.y > canvas.height ||
head.x < 0
) {
return true;
} else {
return this.body.some(function(snakeTo) {
// Crashed into a horizontal segment of itself
if (
(
(head.y === snakeTo.y)
&&
(head.x < snakeTo.x && head.x > snakeFrom.x)
)
||
// Crashed into a vertical segment of itself
(
(head.x === snakeTo.x)
&&
(head.y < snakeTo.y && head.y > snakeFrom.y)
)
) {
return true;
} else {
snakeFrom.x = snakeTo.x;
snakeFrom.y = snakeTo.y;
}
});
}
},
"draw" : function (isEatingApple) {
var body_i;
var headSegment = this.body[this.body.length - 1];
ctx.beginPath();
/*
If the snake eats an apple and therefore keeps its tail,
we don't need to refresh the entire view.
*/
if (!isEatingApple) {
ctx.clearRect(0,0, canvas.width, canvas.height);
apple.drawAt(apple.x, apple.y);
// drawing snake happens async, so apple must get drawn
// here so as not to get cleared
ctx.moveTo(this.tail.x, this.tail.y);
for (body_i = 0; body_i < this.body.length; body_i++) {
ctx.lineTo(this.body[body_i].x, this.body[body_i].y);
}
} else if (this.body.length > 1) {
apple.drawAt(apple.x, apple.y);
ctx.moveTo(this.body[this.body.length - 2].x, this.body[this.body.length - 2].y);
ctx.lineTo(headSegment.x, headSegment.y);
} else {
apple.drawAt(apple.x, apple.y);
ctx.moveTo(this.tail.x, this.tail.y);
ctx.lineTo(headSegment.x, headSegment.y);
}
ctx.stroke();
}
};
function initialize(input) {
if (!document.querySelector("main").classList.contains("game")) {
document.querySelector("main").classList.add("game");
document.querySelector("main").appendChild(
document.querySelector(".templates #snake")
);
}
snake.growLength = 5;
timePerFrame =
input === undefined || input.timePerFrame === undefined
?
10 : input.timePerFrame;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
start = {
"x" : canvas.clientWidth / 2,
"y" : canvas.clientHeight / 2
}
apple.eaten = false;
apple.resetLocation();
snake.direction = "right";
snake.body = [{
"direction" : "right",
"x" : start.x + 50,
"y" : start.y
}];
snake.tail = {
"x" : start.x,
"y" : start.y
};
ctx.strokeStyle = "white";
window.addEventListener("keydown", catchUserEvents);
togglePlayPause();
}
/**
* Gets distance between two points on a horizontal or
* vertical line.
*/
function getDistance(loc1, loc2) {
return Math.abs(loc2.x - loc1.x) + Math.abs(loc2.y - loc1.y);
}
function togglePlayPause() {
if (gameIsOn) {
window.clearInterval(gameOn);
gameIsOn = false;
} else {
gameOn = window.setInterval(runGameFrame, timePerFrame);
gameIsOn = true;
}
}
function exitGame() {
endGame();
document.querySelector("main").classList.remove("game");
document.querySelector(".templates").appendChild(
document.querySelector("#snake")
);
window.SnakeGame.homepage.initialize();
}
function endGame() {
gameIsOn = false;
window.clearInterval(gameOn);
window.removeEventListener("keydown", catchUserEvents);
}
function killSnake() {
endGame();
alert("Game over");
initialize({"timePerFrame" : timePerFrame});
}
/*
* Helps users by preventing "opposite" movements—
* if the snake is going right, cannot hit the left arrow.
*/
function catchUserEvents(e) {
if (gameIsOn && (e.keyCode === 38 || e.which === 38)) {
if (snake.direction !== "down") {
snake.direction = "up";
}
} else if (gameIsOn && (e.keyCode === 39 || e.which === 39)) {
if (snake.direction !== "left") {
snake.direction = "right";
}
} else if (gameIsOn && (e.keyCode === 40 || e.which === 40)) {
if (snake.direction !== "up") {
snake.direction = "down";
}
} else if (gameIsOn && (e.keyCode === 37 || e.which === 37)) {
if (snake.direction !== "right") {
snake.direction = "left";
}
// Spacebar pauses game
} else if (e.keyCode === 32 || e.which === 32) {
togglePlayPause();
} else if (e.keyCode === 27 || e.which === 27) {
exitGame();
}
}
function runGameFrame(e) {
var ateApple = false;
/*
* Moving the snake grows it, whether or not it
* has eaten an apple.
*/
if (snake.direction === "up") {
snake.move("up", 0, -1);
} else if (snake.direction === "right") {
snake.move("right", 1, 0);
} else if (snake.direction === "down") {
snake.move("down", 0, 1);
} else { // "left"
snake.move("left", -1, 0);
}
ateApple = snake.tryToEat(apple);
/*
If their new position is inside an apple
they grow, so there's no need to shrink the tail.
*/
if (!ateApple) {
/*
If they didn't eat an apple, we have to shrink the tail
one frame length, given the move.
*/
snake.shrink();
} else {
/*
If they ate an apple, they have to grow
snake.growLength - 1
*/
snake.grow();
}
/*
Draw snake given new coordinates, and apple
Redraw entire snake if apple uneaten
*/
snake.draw(ateApple);
// If snake crashes into itself or end of board
if (snake.hasCrashed()) {
killSnake();
}
}
return {
"initialize" : initialize
}
}
if (window.SnakeGame === undefined) {
window.SnakeGame = {
"player" : SnakeGame()
};
} else {
window.SnakeGame.player = SnakeGame();
}
}());