-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (83 loc) · 2.65 KB
/
Copy pathscript.js
File metadata and controls
89 lines (83 loc) · 2.65 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
window.snakeBoard = document.getElementById("snake-board");
let i;
let j;
for (i = 0; i < 2500; i++) {
const row = document.createElement("div");
for (j = 0; j < 50; j++) {
const square = document.createElement("div");
square.style.backgroundColor = "white";
row.appendChild(square);
}
window.snakeBoard.appendChild(row);
}
window.snake = [[10,10]];
window.currDirection = "right"
this.generateApple();
this.drawCurrentPosition();
this.moveSnake();
document.onkeydown = (e) => {
switch (e.key) {
case 'ArrowUp':
window.currDirection = "up";
break;
case 'ArrowRight':
window.currDirection = "right";
break;
case 'ArrowDown':
window.currDirection = "down";
break;
case 'ArrowLeft':
window.currDirection = "left";
break;
}
}
function drawCurrentPosition() {
window.snakeBoard.childNodes.forEach((row, i) => {
row.childNodes.forEach((square, j) => {
if (window.snake.some((s) => s[0] == i && s[1] == j)) {
square.style.backgroundColor = "green";
} else if (window.apple[0] == i && window.apple[1] == j) {
square.style.backgroundColor = "red";
} else {
square.style.backgroundColor = "white";
}
});
});
}
function moveSnake() {
let nextPosition = [];
switch (window.currDirection) {
case 'up':
nextPosition = [window.snake[0][0]-1, window.snake[0][1]];
break;
case 'down':
nextPosition = [window.snake[0][0]+1, window.snake[0][1]];
break;
case 'left':
nextPosition = [window.snake[0][0], window.snake[0][1]-1];
break;
case 'right':
nextPosition = [window.snake[0][0], window.snake[0][1]+1];
break;
}
if (nextPosition[0] < 0 || nextPosition[0] >= 50 || nextPosition[1] < 0 || nextPosition[1] >= 50) {
// snake crashed into wall
} else if (window.snake.some((s) => s[0] == nextPosition[0] && s[1] == nextPosition[1])) {
// snake crashed into self
} else {
window.snake.unshift(nextPosition);
if (nextPosition[0] == window.apple[0] && nextPosition[1] == window.apple[1]) {
this.generateApple();
} else {
window.snake.pop();
}
this.drawCurrentPosition();
setTimeout(() => this.moveSnake(), 100 - window.snake.length * 5);
}
}
function generateApple() {
j = Math.floor(Math.random() * 50);
i = Math.floor(Math.random() * 50);
window.apple = [i,j];
console
}