-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.html
More file actions
595 lines (546 loc) · 22.4 KB
/
Copy pathsnake.html
File metadata and controls
595 lines (546 loc) · 22.4 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
img#hawk, img#mouse, img#babymouse {display: none;}
canvas#gameCanvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
div#scoreRow {}
span#currentScore {
padding-right: 50px;
}
span#highScore {}
</style>
<script>
function loadAlternateImage(img, url) {
//Used to load hosted image if local image is not found
img.onerror = "";
img.src = url;
}
</script>
</head>
<body onload="welcomeMessage()">
<img id="hawk" src="hawk_20x20.png" alt="Hawk"
onerror="loadAlternateImage(this,'https://raw.githubusercontent.com/kriscode1/SnakeGame/master/hawk_20x20.png')">
</img>
<img id="mouse" src="mouse_20x20.png" alt="Mouse"
onerror="loadAlternateImage(this,'https://raw.githubusercontent.com/kriscode1/SnakeGame/master/mouse_20x20.png')">
</img>
<img id="babymouse" src="babymouse_20x20.png" alt="Baby Mouse"
onerror="loadAlternateImage(this,'https://raw.githubusercontent.com/kriscode1/SnakeGame/master/babymouse_20x20.png')">
</img>
<div align="center">
<header><h1>Snake</h1></header>
<canvas id="gameCanvas" width="600", height="400" onclick="startGame()">
HTML5 canvas tag not supported by this browser.
</canvas>
</div>
<div id="scoreRow" align="center">
Score:
<span id="currentScore">0</span>
High Score:
<span id="highScore">0</span>
</div>
<div align="center">
<br>
<br>
Use arrow keys or mouse clicks to move the snake. Eat mice to grow. Don't run into the hawks or eat your own tail.
</div>
<br>
<br>
<footer><div align="center"><small>Kristofer Christakos</small></div></footer>
<script>
var canvas, ctx;
var gameRunning = false;
var highScore = 0;
var canvasCenter;
function welcomeMessage() {
//Sets some common variables and tells the user to play the game
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
canvasCenter = coords(canvas.width/2, canvas.height/2);
//Tell the user to click or press enter
textToDisplay = "Click or press enter to play snake.";
ctx.textAlign = "center";
ctx.font = "30px Verdana";
ctx.fillStyle = "#302921";//dark grayish brown
ctx.fillText(textToDisplay, canvasCenter.x, canvasCenter.y);
//Listen for "enter" to start/reset the game
var keyupListener = function(event) {
if (event.keyCode == 13) {
//Enter key was released
if (!gameRunning) {
startGame();
}
}
}
window.addEventListener("keyup", keyupListener);
}
function clearMovementArea() {
ctx.clearRect(20, 20, canvas.width-40, canvas.height-40);
}
//Simple object for managing 2D coordinates
function coords(xcoord, ycoord) {
return {x: xcoord, y: ycoord};
}
function coordsCopy(coordsToCopy) {
return coords(coordsToCopy.x, coordsToCopy.y);
}
function indexOfCoord(coordsArray, coordToFind) {
//Searches coordsArray for coordToFind and returns the index or -1
var numCoordsToCheck = coordsArray.length;
for (var n = 0; n < numCoordsToCheck; n++) {
if ((coordsArray[n].x === coordToFind.x) &&
(coordsArray[n].y === coordToFind.y)) {
return n;
}
}
return -1;
}
function checkIfCollision(collideCoordinatesArray, coordinateToCheck) {
//Converts indexOfCoord to a bool
if (indexOfCoord(collideCoordinatesArray, coordinateToCheck) === -1) {
return false;
}
else {
return true;
}
}
function listSuroundingCoords(centerCoords) {
//Returns an array of the 8 surrounding coords, if they are not hawks
var ret = [];
var x = centerCoords.x;
var y = centerCoords.y;
if ((x > 1) && (y > 1)) ret.push(coords(x-1, y-1));
if (x > 1) ret.push(coords(x-1, y));
if ((x > 1) && (y <= 17)) ret.push(coords(x-1, y+1));
if (y > 1) ret.push(coords(x, y-1));
if (y <= 17) ret.push(coords(x, y+1));
if ((x <= 27) && (y > 1)) ret.push(coords(x+1, y-1));
if (x <= 27) ret.push(coords(x+1, y));
if ((x <= 27) && (y <= 17)) ret.push(coords(x+1, y+1));
return ret;
}
function trimSurroundingCoords(surroundingCoords, occupiedCoords) {
var ret = [];
for (var n = 0; n < surroundingCoords.length; ++n) {
if (!checkIfCollision(occupiedCoords, surroundingCoords[n])) ret.push(surroundingCoords[n]);
}
return ret;
}
function getUnoccupiedSurroundingCoords(occupiedCoords, centerCoords) {
return trimSurroundingCoords(listSuroundingCoords(centerCoords), occupiedCoords);
}
function startGame() {
"use strict";
if (gameRunning) return;
else gameRunning = true;
console.log("Game start.");
//canvas = document.getElementById("gameCanvas");
//ctx = canvas.getContext("2d");
/* Canvas is 600x400px, with 20x20px hawk on all sides.
Divide into coordinates of 20x20px.
So the board is 30x20 units.
*/
var hawkImg = document.getElementById("hawk");
var mouseImg = document.getElementById("mouse");
var babyMouseImg = document.getElementById("babymouse");
//Create hawk border
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = ctx.createPattern(hawkImg, "repeat");
ctx.fill();
clearMovementArea();
//Initialize snake
var snake = {
headCoord: coords(8, 8),
bodyCoords: [coords(7, 8), coords(6, 8), coords(5, 8)],
//Index 0 is near the head, the end of the array is the tail
addHeadToBody: function() {
this.bodyCoords.unshift(this.headCoord);
},
shiftBodyCoords: function() {
this.bodyCoords.pop();
}
}
var hawks = [];
//Add left and right sides of board
for (var y = 0; y < 20; y++) {
hawks.push(coords(0, y));
hawks.push(coords(29, y));
}
//Add top and bottom sides of board
for (var x = 0; x < 30; x++) {
hawks.push(coords(x, 0));
hawks.push(coords(x, 19));
}
var foods = [];
var superFoods = [];
function addFood() {
//Returns true if a coordinate is added to foods
//Otherwise returns false, implying victory
var occupiedCoords = snake.bodyCoords.concat(foods);
occupiedCoords.concat(superFoods);
occupiedCoords.push(snake.headCoord);
//Already know the border coords are occupied
var numOccupiedCoords = occupiedCoords.length;
var maxNumberOfCoords = 504;//30x20 board --> 28x18 non-hawk coords
if (numOccupiedCoords == maxNumberOfCoords) {
//Implied victory
return false;
}
else {
//Find a random empty coordinate to place food
var randCoordIndex = Math.floor(Math.random() *
(maxNumberOfCoords - numOccupiedCoords));
//Loop to figure out which coord this is
var coordIndexCounter = 0;
for (x = 1; x < 29; x++) {
for (y = 1; y < 19; y++) {
if (checkIfCollision(occupiedCoords, coords(x, y))) {
//This coord can't be new food
}
else if (coordIndexCounter == randCoordIndex) {
//Determine if this mouse is next to another mouse
//If so, they create a nearby superfood
if (checkIfCollision(foods, coords(x-1,y-1)) ||
checkIfCollision(foods, coords(x-1,y)) ||
checkIfCollision(foods, coords(x-1,y+1)) ||
checkIfCollision(foods, coords(x,y-1)) ||
checkIfCollision(foods, coords(x,y+1)) ||
checkIfCollision(foods, coords(x+1,y-1)) ||
checkIfCollision(foods, coords(x+1,y)) ||
checkIfCollision(foods, coords(x+1,y+1))) {
//Create superfood if there is a nearby space available
var potentialSuperFoodCoords = getUnoccupiedSurroundingCoords(occupiedCoords, coords(x, y));
if (potentialSuperFoodCoords.length > 0) {
var superFoodsCoordsIndex = Math.floor(Math.random() * potentialSuperFoodCoords.length);
superFoods.push(potentialSuperFoodCoords[superFoodsCoordsIndex]);
}
}
//Finally add the new normal mouse
foods.push(coords(x, y));
return true;
} else {
//Could be food, but not the randCoordIndex-th coordinate
coordIndexCounter++;
}
}
}
}
return false;//This should never happen
}
addFood();
//Initialize controllers
var lastDirection = "right";
var lastDirectionKey = "right";
var keydownListener = function(event) {
switch (event.keyCode) {
case 37:
//Left arrow
if (lastDirection != "right") lastDirectionKey = "left";
break;
case 39:
//Right arrow
if (lastDirection != "left") lastDirectionKey = "right";
break;
case 38:
//Up arrow
if (lastDirection != "down") lastDirectionKey = "up";
break;
case 40:
//Down arrow
if (lastDirection != "up") lastDirectionKey = "down";
break;
default:
break;
}
}
window.addEventListener("keydown", keydownListener);
function clickListener(event) {
var clickX = event.offsetX;
var clickY = event.offsetY;
console.log("click " + event.offsetX + " " + event.offsetY);
var snakeX = (snake.headCoord.x * 20) + 10;
var snakeY = (snake.headCoord.y * 20) + 10;
if (clickX >= snakeX) {
if (clickY >= snakeY) {
//Clicked bottom right
if ((lastDirection == "right") || (lastDirection == "left")) {
lastDirectionKey = "down";
}
else lastDirectionKey = "right";
}
else {
//Clicked top right
if ((lastDirection == "right") || (lastDirection == "left")) {
lastDirectionKey = "up";
}
else lastDirectionKey = "right";
}
}
else {
if (clickY >= snakeY) {
//Clicked bottom left
if ((lastDirection == "right") || (lastDirection == "left")) {
lastDirectionKey = "down";
}
else lastDirectionKey = "left";
}
else {
//Clicked top left
if ((lastDirection == "right") || (lastDirection == "left")) {
lastDirectionKey = "up";
}
else lastDirectionKey = "left";
}
}
}
window.addEventListener("click", clickListener);
function cleanUp() {
window.removeEventListener("keydown", keydownListener);
window.removeEventListener("click", clickListener);
gameRunning = false;
}
var currentScore;
var currentScoreTag = document.getElementById("currentScore");
var highScoreTag = document.getElementById("highScore");
function updateGame() {
//Main game loop with all of the logic and drawing
//Updating score here instead of after more drawing
//This saves a variable or two so I can draw the dead
//snake however I'd like, and use snake.bodyCoords.length
//for score keeping.
currentScore = snake.bodyCoords.length - 3;
if (currentScore > highScore) {
highScore = currentScore;
highScoreTag.innerHTML = highScore;
}
currentScoreTag.innerHTML = currentScore;
var gameOver = false;
var newHeadCoord = coordsCopy(snake.headCoord);
//Adjust head coordinates based on last keypress
switch (lastDirectionKey) {
case "right":
newHeadCoord.x++;
break;
case "left":
newHeadCoord.x--;
break;
case "up":
newHeadCoord.y--;
break;
case "down":
newHeadCoord.y++;
break;
default:
alert("No key pressed to move snake. This shouldn't happen.");
break;
}
lastDirection = lastDirectionKey;
//Check if head coordinates collides with anything
var collidedWithFood = false;
var collidedWithSuperFood = false;
if (checkIfCollision(foods, newHeadCoord)) collidedWithFood = true;
else if (checkIfCollision(superFoods, newHeadCoord)) collidedWithSuperFood = true;
if (collidedWithFood || collidedWithSuperFood) {
//Collide with food, extend snake body
snake.addHeadToBody();
snake.headCoord = newHeadCoord;
//Don't shift body because it is growing
if (collidedWithFood) {
var foodIndex = indexOfCoord(foods, newHeadCoord);
if (foodIndex == -1) {
alert("Serious error, collidedWithFood, foodsIndex = -1.");
}
foods.splice(foodIndex, 1);
//Add an extra food as the snake gets larger
var foodAdded = addFood();
if (foodAdded) {
var snakeSize = snake.bodyCoords.length;
var bonusFood = [10, 20, 30, 45, 60, 80, 110, 200, 300, 400];
if (bonusFood.indexOf(snakeSize) != -1) foodAdded = addFood();
}
if (!foodAdded) {
//Can't add more food because the player won.
var textToDisplay = "You actually won???";
ctx.textAlign = "center";
ctx.font = "30px Verdana";
ctx.strokeStyle = "white";
ctx.strokeText(textToDisplay, canvasCenter.x, canvasCenter.y);
var gradient = ctx.createRadialGradient(canvasCenter.x,
canvasCenter.y,
0,
canvasCenter.x,
canvasCenter.y,
200);
gradient.addColorStop("0.0", "green");
gradient.addColorStop("1.0", "black");
ctx.fillStyle = gradient;
ctx.fillText(textToDisplay, canvasCenter.x, canvasCenter.y);
//Fix score
currentScore = snake.bodyCoords.length - 3 + 1;
if (currentScore > highScore) {
highScore = currentScore;
highScoreTag.innerHTML = highScore;
}
currentScoreTag.innerHTML = currentScore;
//Finish and exit function
cleanUp();
gameOver = true;
return;
}
} else {
var foodIndex = indexOfCoord(superFoods, newHeadCoord);
if (foodIndex == -1) {
alert("Serious error, collidedWithFood==false, foodsIndex = -1.");
}
superFoods.splice(foodIndex, 1);
}
}
else if (checkIfCollision(hawks, newHeadCoord)) {
//Collide with hawks, game over
console.log("Game over, hit hawks.");
snake.addHeadToBody();//Updating for final animation
snake.headCoord = newHeadCoord;
snake.shiftBodyCoords();
gameOver = true;
}
else if (checkIfCollision(snake.bodyCoords, newHeadCoord)) {
//Collide with self, game over
console.log("Game over, ate self.")
snake.addHeadToBody();
snake.headCoord = newHeadCoord;
//snake.shiftBodyCoords();
//Won't shift to emphasize how the player lost
gameOver = true;
}
else {
//No collisions, update body coordinates
snake.addHeadToBody();
snake.headCoord = newHeadCoord;
snake.shiftBodyCoords();
}
//Clear area for drawing
clearMovementArea(canvas, ctx);
//Draw snake
var snakeBodyLength = snake.bodyCoords.length;
for (var bodyPart = 0; bodyPart < snakeBodyLength; bodyPart++) {
ctx.beginPath();
var bodyPartC = snake.bodyCoords[bodyPart];
ctx.arc((20 * bodyPartC.x) + 10,
(20 * bodyPartC.y) + 10,
9,
0,
2 * Math.PI);
ctx.fillStyle = "black";
ctx.fill();
}
ctx.beginPath();
ctx.arc((20 * snake.headCoord.x) + 10,
(20 * snake.headCoord.y) + 10,
9,
0,
2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
//Draw food
//ctx.fillStyle = "pink";
var foodCount = foods.length;
for (var foodPiece = 0; foodPiece < foodCount; foodPiece++) {
/*ctx.fillRect((20 * foods[foodPiece].x) + 3,
(20 * foods[foodPiece].y) + 3,
14, 14);//20-3-3=14*/
ctx.drawImage(mouseImg,
20 * foods[foodPiece].x,
20 * foods[foodPiece].y);
}
//Attempt to move super foods
var occupiedCoords = snake.bodyCoords.concat(foods);
occupiedCoords.concat(superFoods);
occupiedCoords.push(snake.headCoord);
//clone array
var newSuperFoods = [];
for (var n = 0; n < superFoods.length; ++n) {
newSuperFoods.push(coordsCopy(superFoods[n]));
}
for (var n = 0; n < superFoods.length; n++) {
var potentialMovement = getUnoccupiedSurroundingCoords(occupiedCoords, superFoods[n]);
if (potentialMovement.length > 0) {
var newLocationIndex = Math.floor(Math.random() * potentialMovement.length);
newSuperFoods.push(potentialMovement[newLocationIndex]);
newSuperFoods.splice(superFoods[n], 1);
occupiedCoords.push((potentialMovement[newLocationIndex]));
occupiedCoords.splice(superFoods[n], 1);
}
}
superFoods = newSuperFoods;
//Draw superFoods
var superFoodsCount = superFoods.length;
for (var foodPiece = 0; foodPiece < superFoodsCount; foodPiece++) {
/*ctx.fillRect((20 * superFoods[foodPiece].x) + 3,
(20 * superFoods[foodPiece].y) + 3,
14, 14);//20-3-3=14*/
ctx.drawImage(babyMouseImg,
20 * superFoods[foodPiece].x,
20 * superFoods[foodPiece].y);
}
if (gameOver) {
//Display Game Over message and clean up
var textToDisplay = "GAME OVER";
ctx.textAlign = "center";
ctx.font = "20px Verdana";
ctx.strokeStyle = "white";
ctx.strokeText(textToDisplay, canvasCenter.x, canvasCenter.y);
var gradient = ctx.createRadialGradient(canvasCenter.x,
canvasCenter.y,
0,
canvasCenter.x,
canvasCenter.y,
200);
gradient.addColorStop("0.0", "red");
gradient.addColorStop("1.0", "black");
ctx.fillStyle = gradient;
ctx.fillText(textToDisplay, canvasCenter.x, canvasCenter.y);
textToDisplay = "Click or press enter to play again.";
ctx.font = "15px Verdana";
ctx.strokeStyle = "white";
var textDisplayCoordY = canvas.height * 0.75;
ctx.strokeText(textToDisplay, canvasCenter.x, textDisplayCoordY);
ctx.fillStyle = "blue";
ctx.fillText(textToDisplay, canvasCenter.x, textDisplayCoordY);
cleanUp();
}
else {
//Insert delay for next update
var delay;
var startDelay = 200;
var finalDelay = 85;
var snakeLen1 = 80;//Linear 1:1 until here
var snakeLen2 = 200;//More gradual slope until here, then cap the delay
if (snakeBodyLength <= snakeLen1) {
//Linear 1:1 decrease in delay
delay = startDelay - snakeBodyLength;
}
else if (snakeBodyLength <= snakeLen2) {
//Linear decrease in delay, more slowly
var m = (finalDelay - (startDelay-snakeLen1))/(snakeLen2 - snakeLen1);
//Calculate intercept using (length, delay) = (snakeLen1, (startDelay-snakeLen1))
var b = (startDelay-snakeLen1) - (m * snakeLen1);
delay = Math.floor(m*snakeBodyLength + b);
}
else {
//Cap delay at fixed value
delay = finalDelay;
}
//console.log("delay = " + delay);
setTimeout(updateGame, delay);
}
}
//Insert delay for first update
setTimeout(updateGame, 200);
}
</script>
</body>
</html>