-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.js
More file actions
89 lines (72 loc) · 1.92 KB
/
snake.js
File metadata and controls
89 lines (72 loc) · 1.92 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
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
let score = 0;
const snake = [];
snake[0] = { x: 10 * box, y: 10 * box };
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
let d;
document.addEventListener("keydown", direction);
function direction(event) {
if (event.keyCode === 37 && d !== "RIGHT") {
d = "LEFT";
} else if (event.keyCode === 38 && d !== "DOWN") {
d = "UP";
} else if (event.keyCode === 39 && d !== "LEFT") {
d = "RIGHT";
} else if (event.keyCode === 40 && d !== "UP") {
d = "DOWN";
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "black";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (d === "LEFT") snakeX -= box;
if (d === "UP") snakeY -= box;
if (d === "RIGHT") snakeX += box;
if (d === "DOWN") snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
score++;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
} else {
snake.pop();
}
const newHead = { x: snakeX, y: snakeY };
if (
snakeX < 0 ||
snakeY < 0 ||
snakeX >= canvas.width ||
snakeY >= canvas.height ||
collision(newHead)
) {
clearInterval(game);
}
snake.unshift(newHead);
ctx.fillStyle = "white";
ctx.font = "20px Arial";
ctx.fillText("Score: " + score, 20, 30);
}
function collision(head) {
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
const game = setInterval(draw, 100);