-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
79 lines (71 loc) · 1.87 KB
/
app.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
const width = 16;
const positions = document.querySelectorAll('.position');
const title = document.querySelector('.title');
const snake = [2, 1, 0]; // init snake; head at index 2
let appleIndex,
score = 0,
speed = 700,
direction = 1;
snake.forEach(index => positions[index].classList.add('snake'));
generateApple();
document.addEventListener('keydown', setDirection);
let interval = setInterval(gameStep, speed);
function gameStep() {
const nextIndex = snake[0] + direction;
if (isGameOver(nextIndex)) {
showText(`Game over. Score: ${score}`);
clearInterval(interval);
return;
}
if (nextIndex != appleIndex) {
positions[snake.pop()].classList.remove('snake'); //remove last
} else {
score++;
positions[appleIndex].classList.remove('apple');
showText(`Score: ${score}`);
generateApple();
increaseSpeed();
}
snake.unshift(nextIndex); // move head to next position
positions[nextIndex].classList.add('snake');
}
function setDirection(e) {
switch (e.key) {
case "ArrowLeft":
direction = -1;
break;
case "ArrowRight":
direction = +1;
break;
case "ArrowUp":
direction = -width;
break;
case "ArrowDown":
direction = width;
break;
}
}
function generateApple() {
do {
appleIndex = Math.floor(Math.random() * width * width);
}
while (snake.includes(appleIndex))
positions[appleIndex].classList.add('apple');
}
function isGameOver(nextIndex) {
return nextIndex < 0 ||
nextIndex >= width * width ||
nextIndex % width === width - 1 && direction === -1 ||
nextIndex % width === 0 && direction === 1 ||
snake.includes(nextIndex)
}
function increaseSpeed() {
if (speed > 30) {
speed = speed > 200 ? speed - 50 : speed - 10;
clearInterval(interval);
interval = setInterval(gameStep, speed);
}
}
function showText(text) {
title.innerHTML = text;
}