-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.js
More file actions
331 lines (327 loc) · 9.88 KB
/
snake.js
File metadata and controls
331 lines (327 loc) · 9.88 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
const getDefaults = () => {
return {
squareH: 16, squareW: 16, totalAreaH: 800, totalAreaW: 800, rows: 0, cols: 0
, snakeLength: 10, snakeDirection: 0, //0=right,1=left,2=top,3=bottom,4=blocked
snakeCoordinates: [], // object of {x:int,y:int}
crawlSpeed: 100, crawlerTimer: null, foodType: null, // 0= simple food, 1=spacial food
foodCoords: null, tailHistory: [], foodTimer: null, paused: false,
foodTimeout: [4, 10], spacialFoodTimeout: [1, 5], hideFoodTimer: null,
totalScore: 0, maxScore: 0, simpleFoodPoint: 1, spacialFoodPoint: 9, simpleScore: 0, spacialScore: 0// of type {x,y}
};
}
let { squareH, squareW, totalAreaH, totalAreaW, rows, cols, foodTimeout, spacialFoodTimeout, hideFoodTimer,
snakeLength, snakeDirection, snakeCoordinates, crawlSpeed, crawlerTimer, foodTimer, foodType, foodCoords, totalScore, maxScore,
simpleFoodPoint, spacialFoodPoint, simpleScore, spacialScore, tailHistory, paused } = getDefaults();
const resetSettings = () => {
let _defaults = getDefaults();
snakeLength = _defaults.snakeLength;
snakeDirection = _defaults.snakeDirection;
snakeCoordinates = _defaults.snakeCoordinates;
crawlSpeed = _defaults.crawlSpeed;
crawlerTimer = _defaults.crawlerTimer;
foodType = _defaults.foodType;
foodCoords = _defaults.foodCoords;
totalScore = _defaults.totalScore;
crawlerTimer = _defaults.crawlerTimer;
simpleScore = _defaults.simpleScore;
spacialScore = _defaults.spacialScore;
tailHistory = _defaults.tailHistory;
foodTimer = _defaults.foodTimer;
foodTimeout = _defaults.foodTimeout;
spacialFoodTimeout = _defaults.spacialFoodTimeout;
hideFoodTimer = _defaults.hideFoodTimer;
paused = _defaults.paused;
showScore();
$('#food-icon').remove();
$('.snake').removeClass('snake');
$('#startBtn').prop("disabled", false);
$("#pauseBtn").prop("disabled", true);
$("#cancelBtn").prop("disabled", true);
}
const randomInt = (min, max) => {
return min + Math.floor((max - min) * Math.random());
}
const getSquareCountsinCol = () => {
return Math.floor(totalAreaW / squareW);
}
const getSquareCountsinRow = () => {
return Math.floor(totalAreaH / squareH);
}
const renderSquares = (rows, cols) => {
let mainDiv = $('#main-area');
mainDiv.html('');
let html = '';
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
html += `<div id='${i}-${j}' class='square'></div>`;
}
}
mainDiv.html(html);
}
const getSnakeStartPoint = () => {
return randomInt(0, rows - 1);
}
const generateSnakeDefaultCoordinates = () => {
snakeCoordinates = [];
let y = 0, x = getSnakeStartPoint();
snakeCoordinates.push({ x, y });
addSnakePoint(x, y);
}
const addSnakePoint = (x, y) => {
let el = $(`#${x}-${y}`);
if (el)
el.addClass("snake");
}
const removeSnakePoint = (x, y) => {
let el = $(`#${x}-${y}`);
if (el)
el.removeClass('snake');
}
const nextPosiblePoint = (head) => {
switch (snakeDirection) {
case 0: { // right side
let x = head.x, y = -1;
if ((head.y + 1) <= (cols - 1)) {
y = head.y + 1;
}
else {
y = 0
}
return { x, y };
}
case 1: { // left side
let x = head.x, y;
if ((head.y - 1) >= 0) {
y = head.y - 1;
}
else {
y = (cols - 1);
}
return { x, y };
}
case 2: { // up side
let x, y = head.y;
if ((head.x - 1) >= 0) {
x = head.x - 1;
}
else {
x = (rows - 1);
}
return { x, y };
}
case 3: { // down side
let x, y = head.y;
if ((head.x + 1) <= (rows - 1)) {
x = head.x + 1;
} else {
x = 0;
}
return { x, y };
}
case 4: {
return null;
}
}
}
const getFoodRandomCoords = () => {
let point = null;
while (true) {
let pointX = randomInt(0, rows - 1);
let pointY = randomInt(0, cols - 1);
let insideSnake = !!snakeCoordinates.find((m) => m.x === pointX && m.y === pointY);
if (!insideSnake) {
point = { x: pointX, y: pointY };
break;
}
}
return point;
}
const addFood = () => {
let point = foodCoords = getFoodRandomCoords();
let el = $(`#${point.x}-${point.y}`);
if (el) {
el.html('<i id="food-icon" class="fas fa-cookie-bite"></i>');
}
}
const addSpacialFood = () => {
let point = foodCoords = getFoodRandomCoords();
let el = $(`#${point.x}-${point.y}`);
if (el) {
el.html('<i id="food-icon" class="fas fa-apple-alt fa-2x"></i>');
}
}
const showFoods = () => {
if (snakeDirection !== 4 && foodTimer) {
let type = randomInt(0, 2);
if (type === 2) {
type = 1;
}
foodType = type;
if (foodType === 0) {
addFood();
} else {
addSpacialFood();
}
timeoutFoodMarker();
}
}
const timeoutFoodMarker = () => {
let _timer = foodType === 0 ? randomInt(foodTimeout[0], foodTimeout[1] + 1)
: randomInt(spacialFoodTimeout[0], spacialFoodTimeout[1] + 1);
console.log(_timer);
if (hideFoodTimer) {
clearTimeout(hideFoodTimer);
}
hideFoodTimer = setTimeout(() => {
hideFood();
}, _timer * 1000);
}
const hideFood = () => {
let point = foodCoords;
let el = $(`#${point.x}-${point.y}`);
if (el) {
el.html('');
}
showFoods();
}
const consumeFood = (head) => {
if (foodCoords && head.x === foodCoords.x && head.y === foodCoords.y) {
hideFood();
let snakeIncreament = 0;
if (foodType === 0) {
totalScore += simpleFoodPoint;
simpleScore++;
snakeIncreament = 1;
} else {
totalScore += spacialFoodPoint;
spacialScore++;
snakeIncreament = 2;
}
if (totalScore > maxScore) {
maxScore = totalScore;
}
while (snakeIncreament--) {
snakeLength++;
let lastInHistory = tailHistory.pop();
if (lastInHistory) {
snakeCoordinates.push(lastInHistory);
}
}
showScore();
}
}
const showScore = () => {
$('#maxScore').html(maxScore);
$('#totalScore').html(totalScore);
$('#simpleScore').html(simpleScore);
$('#spacialScore').html(spacialScore);
}
const startCrawling = () => {
if (foodTimer) {
clearTimeout(foodTimer);
}
foodTimer = setTimeout(() => {
showFoods();
}, 1000 * snakeLength);
crawlerTimer = setInterval(() => {
let head = snakeCoordinates[0], tail = null; // last item removed and will be added to top head
let nextCoords = nextPosiblePoint(head);
if (nextCoords) {
let insideSnake = !!snakeCoordinates.find((m) => m.x === nextCoords.x && m.y === nextCoords.y);
if (insideSnake) {
clearTimers();
alert('GAME OVER!!!');
resetSettings();
return;
}
tail = snakeCoordinates.pop()
consumeFood({ ...nextCoords });
snakeCoordinates.splice(0, 0, nextCoords); // added tail to head
tailHistory.push(tail);
addSnakePoint(nextCoords.x, nextCoords.y); // reflect on DOM
if (snakeCoordinates.length < snakeLength) { // if snake is not fully rendered it will add up remaining tails
snakeCoordinates.push(tail);
addSnakePoint(tail.x, tail.y);
} else {
removeSnakePoint(tail.x, tail.y);
}
} else {
cancelGame();
}
}, crawlSpeed);
}
const startGame = () => {
generateSnakeDefaultCoordinates();
startCrawling();
$('#startBtn').text('Start Again').prop("disabled", true);
$("#pauseBtn").text('Pause').prop("disabled", false);
$("#cancelBtn").prop("disabled", false);
}
const pauseGame = () => {
paused = !paused;
$('#startBtn').prop("disabled", true);
if (!paused) {
resumeGame();
$("#pauseBtn").text('Pause').prop("disabled", false);
} else {
$("#pauseBtn").text('Resume').prop("disabled", false);
if (crawlerTimer) {
clearInterval(crawlerTimer);
}
if (foodTimer) {
clearTimeout(foodTimer);
}
}
}
const resumeGame = () => {
startCrawling();
}
const clearTimers = () => {
if (crawlerTimer) {
clearInterval(crawlerTimer);
}
if (foodTimer) {
clearTimeout(foodTimer);
}
}
const cancelGame = () => {
clearTimers();
resetSettings();
}
const onNavigationKey = (e) => {
switch (e.keyCode) {
case 37: { // array left
if (snakeDirection === 2 || snakeDirection === 3) {
snakeDirection = 1;
}
break;
}
case 38: { // array up
if (snakeDirection === 0 || snakeDirection === 1) {
snakeDirection = 2;
}
break;
}
case 39: { // array right
if (snakeDirection === 2 || snakeDirection === 3) {
snakeDirection = 0;
}
break;
}
case 40: { // array down
if (snakeDirection === 0 || snakeDirection === 1) {
snakeDirection = 3;
}
break;
}
}
}
$(() => {
rows = getSquareCountsinRow();
cols = getSquareCountsinCol();
renderSquares(rows, cols);
document.onkeydown = onNavigationKey;
$('#startBtn').text('Start').prop("disabled", false);
$("#pauseBtn").prop("disabled", true);
$("#cancelBtn").prop("disabled", true);
});