-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsnakeGame.html
430 lines (397 loc) · 13.6 KB
/
snakeGame.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="author" content="Manos Paterakis">
<link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAGFBMVEUAAACAqlV2s1R4s1V2sVQpLzN3slXdLkStZgv6AAAABXRSTlMABkN1ee5NLt8AAABDSURBVAgdBcExDQIAFESxTicFCUhh/iTkzWzYp4XVgV51+FUdvngEWICFsAiWvWHZKUu3uqWrWrpuLdWtsrrV0Ydn/jIdGZnjcut/AAAAAElFTkSuQmCC">
<title>SNEK SOULS</title>
<style>
body {
/* Prevent drag-to-reload */
overflow-y: hidden;
}
.grid-container {
display: grid;
position: absolute;
box-shadow: 0px 0px 25px 5px black;
width: 100%;
height: 100%;
top: 0;
left: 0;
margin: 0 auto;
}
.grid-container > div {
background-color: rgba(255, 255, 255, 0.9);
box-shadow: inset 0px 0px 30px 0px rgba(0,0,0,0.35);
border: 1px solid black;
text-align: center;
font-size: 30px;
}
#scoreboard {
position: fixed;
z-index: 999;
padding: 5px;
font: bold 15px Arial;
border: 1px solid black;
border-radius: 3px;
background: rgba(255,255,255, 0.6);
}
#modal {
position: fixed;
z-index: 99;
background: lightcyan;
text-align: center;
width: 300px;
height: 450px;
display: block;
font-family: 'Arial';
box-shadow: 0px 0px 25px 5px black;
padding: 20px;
top: 50%;
left: 50%;
margin: 0 auto;
margin-left: -170px;
margin-top: -245px;
}
#modal > button {
margin: 0 auto;
display: block;
font-size: 20px;
width: 100px;
}
</style>
</head>
<body>
<div id="modal"></div>
<div class="grid-container"></div>
<div id='scoreboard'>Snek Souls</div>
<script>
var snakeGame = (function() {
// Editable variables
var snakeColor = 'green';
var snakeHeadColor = 'darkgreen';
var foodColor = 'yellow';
var biteColor = 'red';
var gridSize = 49;
var scoreIncrement = 50;
var interval = 750;
// Uneditable variables
var grid = document.getElementsByClassName("grid-container")[0];
var direction = -1;
var foodPosition = -1;
var lastFoodEaten = true;
var score = 0;
var touchDevice = false;
var snakeTail = [];
var previousPos = -1;
var snakeIsDead = false;
var gridSqRoot = Math.sqrt(gridSize);
var snakePosition = (gridSize + gridSqRoot) / 2;
var touchY = -1;
var touchX = -1;
var snakeMoving = false;
// Adjust the game grid to the window
window.addEventListener("resize", function(e) {
resizeGrid();
});
window.addEventListener("load", function(e) {
// Set random background color [https://css-tricks.com/snippets/javascript/random-hex-color/]
document.body.style.background = '#' + Math.floor(Math.random()*16777215).toString(16);
createCSScolumns();
createBlocks();
resizeGrid();
if (is_touch_device()) {
touchDevice = true;
}
_game.resetModal();
});
// Detect touch start (for swipe)
document.addEventListener("touchstart", function(e) {
touchX = e.touches[0].pageX;
touchY = e.touches[0].pageY;
});
// Change direction on touch end (for swipe)
document.addEventListener("touchend", function(e) {
// Calculate swipe
var swipeX = touchX - e.changedTouches[0].pageX;
var swipeY = touchY - e.changedTouches[0].pageY;
// If swipe was significant enough
if (Math.abs(swipeX) > window.innerWidth / 10 || Math.abs(swipeY) > window.innerHeight / 10) {
// If X swipe was bigger than Y swipe
if (Math.abs(swipeX) > Math.abs(swipeY)) {
// Horizontal swipe
if (swipeX > 0) {
// Left swipe
_game.changeDirection(0);
} else {
// Right swipe
_game.changeDirection(1);
}
} else {
// Vertical swipe
if (swipeY > 0) {
// Up swipe
_game.changeDirection(3);
} else {
// Down swipe
_game.changeDirection(2);
}
}
}
});
// Change direction on key press
document.addEventListener("keydown", function(e) {
if (e.keyCode == '38') {
// up arrow
_game.changeDirection(3);
}
else if (e.keyCode == '40') {
// down arrow
_game.changeDirection(2);
}
else if (e.keyCode == '37') {
// left arrow
_game.changeDirection(0);
}
else if (e.keyCode == '39') {
// right arrow
_game.changeDirection(1);
}
});
// Resize grid
function resizeGrid() {
if (window.innerWidth > window.innerHeight) {
grid.style.width = window.innerHeight + 'px';
grid.style.height = '';
grid.style.marginLeft = (window.innerWidth - grid.clientWidth)/2 + 'px';
grid.style.marginTop = 0;
} else {
grid.style.height = window.innerWidth + 'px';
grid.style.width = '';
grid.style.marginTop = (window.innerHeight - grid.clientHeight)/2 + 'px';
grid.style.marginLeft = 0;
}
}
// Create grid blocks
function createBlocks() {
for (var i = 0; i < gridSize; i++) {
var blockDiv = document.createElement("div");
blockDiv.id = 'block' + i;
grid.appendChild(blockDiv);
}
}
// Create columns with CSS
function createCSScolumns() {
var columnsString = '';
for (var i = 0; i < gridSqRoot; i++) {
columnsString+= (100/gridSqRoot) + '% ';
}
grid.style.gridTemplateColumns = columnsString;
}
// Check if touch device [https://ctrlq.org/code/19616-detect-touch-screen-javascript]
function is_touch_device() {
return (('ontouchstart' in window)
|| (navigator.MaxTouchPoints > 0)
|| (navigator.msMaxTouchPoints > 0));
}
var _game = {
getInterval: function() {
return interval;
},
setInterval: function(val) {
interval = val;
},
// Draw the snake on the grid
drawBoard: function() {
for (var i = 0; i < grid.children.length; i++) {
grid.children[i].style.background = '';
}
// Draw tail
for (var i = 0; i < snakeTail.length; i++) {
document.getElementById('block' + snakeTail[i]).style.background = snakeColor;
}
// Draw snake head
if (!snakeIsDead) {
document.getElementById('block' + snakePosition).style.background = snakeHeadColor;
} else {
document.getElementById('block' + snakePosition).style.background = biteColor;
}
// Draw food
document.getElementById('block' + foodPosition).style.background = foodColor;
// Draw score
document.getElementById('scoreboard').textContent = 'Souls = ' + score;
},
// Play a round
play: function() {
_game.moveSnake();
_game.checkForDeath();
_game.tryToEatFood();
if (lastFoodEaten) {
_game.placeFood();
}
_game.drawBoard();
if (!snakeIsDead) {
setTimeout(_game.play,_game.getInterval());
}
},
// Move snake to a new tile
moveSnake: function() {
snakeMoving = true;
previousPos = snakePosition;
switch (direction) {
// left
case 0: {
if (snakePosition >= 0) {
if ((snakePosition % gridSqRoot) === 0) {
snakePosition += (gridSqRoot - 1);
} else {
snakePosition--;
}
} else {
_game.moveSnake();
}
break;
}
// right
case 1: {
if (snakePosition + 1 <= gridSize) {
if ((snakePosition % gridSqRoot) === (gridSqRoot - 1)) {
snakePosition -= (gridSqRoot - 1);
} else {
snakePosition++;
}
} else {
_game.moveSnake();
}
break;
}
// down
case 2: {
if (snakePosition + gridSqRoot < gridSize) {
snakePosition+= gridSqRoot;
} else {
snakePosition-= (gridSize - gridSqRoot);
}
break;
}
// up
case 3: {
if (snakePosition - gridSqRoot >= 0) {
snakePosition-= gridSqRoot;
} else {
snakePosition+= (gridSize - gridSqRoot);
}
break;
}
default: break;
}
// Update snake tail
snakeTail.unshift(previousPos);
snakeTail.pop();
snakeMoving = false;
},
// Change snake direction
changeDirection: function(newDirection) {
if (_game.checkLegalMove(newDirection)) {
direction = newDirection;
}
},
// Try eating food
tryToEatFood: function() {
// Eat food
if (snakePosition === foodPosition) {
lastFoodEaten = true;
score += scoreIncrement;
if (snakeTail.length > 0) {
snakeTail.push(snakeTail[snakeTail.length - 1]);
} else {
snakeTail.unshift(previousPos);
}
if (score === 150) {
interval = 500;
} else if (score === 300) {
interval = 350;
} else if (score === 500) {
interval = 250;
} else if (score === 750) {
interval = 200;
} else if (score === 1000) {
interval = 175;
} else if (score === 1500) {
document.getElementById('modal').innerHTML = "<h1>Teriyaki Sauce Chicken Dinner!</h1><button onclick='snakeGame.hideModal();'>Play Again</button>";
snakeIsDead = true;
_game.changeDirection(-1);
_game.showModal();
}
}
},
// Place food on the grid
placeFood: function() {
lastFoodEaten = false;
foodPosition = Math.floor(Math.random() * 36);
while (foodPosition === snakePosition || snakeTail.indexOf(foodPosition) > -1) {
foodPosition = Math.floor(Math.random() * 36);
}
},
// Check for death
checkForDeath: function() {
if (snakeTail.indexOf(snakePosition) > -1) {
snakeIsDead = true;
_game.changeDirection(-1);
setTimeout(_game.showModal,2000);
}
},
// Check for legal move
checkLegalMove: function(newDirection) {
if (snakeMoving) {
return false;
}
var legalMove = true;
// left
if (newDirection === 0 && (snakeTail[0] === snakePosition-1 || snakeTail[0] === snakePosition+gridSqRoot-1)) {
legalMove = false;
}
// right
if (newDirection === 1 && (snakeTail[0] === snakePosition+1 || snakeTail[0] === snakePosition-gridSqRoot+1)) {
legalMove = false;
}
// down
if (newDirection === 2 && (snakeTail[0] === snakePosition+gridSqRoot || snakeTail[0] === snakePosition- gridSize+gridSqRoot)) {
legalMove = false;
}
// up
if (newDirection === 3 && (snakeTail[0] === snakePosition-gridSqRoot || snakeTail[0] === snakePosition+gridSize-gridSqRoot)) {
legalMove = false;
}
return legalMove;
},
// Hide modal
hideModal: function() {
document.getElementById('modal').style.display = 'none';
// Reset values
snakeIsDead = false;
snakePosition = 21;
snakeTail = [];
interval = 750;
score = 0;
direction = -1;
_game.placeFood();
_game.resetModal();
// Start playing
_game.play();
},
// Show modal
showModal: function() {
document.getElementById('modal').style.display = '';
},
// Reset modal
resetModal: function() {
document.getElementById('modal').innerHTML = "<h1 class=\"font-weight-bold\">How to play</h1><h2 class=\"font-weight-bold\">Keyboard Buttons</h2><div>Press Up-Down-Right-Left arrows to change your snek's direction</div><br><h2 class=\"font-weight-bold\">Touchscreen Buttons</h2><div>Swipe on the screen to change your snek's direction</div><br><h2 class=\"font-weight-bold\">Game goal</h2><div>Try eating the food blocks (yellow) to get as big as possible</div><br><button onclick='snakeGame.hideModal();'>Start</button>";
}
};
return _game;
})();
</script>
</body>
</html>