-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
81 lines (66 loc) · 2.39 KB
/
script.js
File metadata and controls
81 lines (66 loc) · 2.39 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
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const box = 20;
let snake = [
{x: 10, y: 10},
{x: 10, y: 11},
{x: 10, y: 12}
];
let direction = 'RIGHT';
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
document.addEventListener('keydown', directionControl);
function directionControl(event) {
if (event.keyCode == 37 && direction !== 'RIGHT') direction = 'LEFT';
else if (event.keyCode == 38 && direction !== 'DOWN') direction = 'UP';
else if (event.keyCode == 39 && direction !== 'LEFT') direction = 'RIGHT';
else if (event.keyCode == 40 && direction !== 'UP') direction = 'DOWN';
}
function changeDirection(newDirection) {
if (newDirection === 'left' && direction !== 'RIGHT') direction = 'LEFT';
else if (newDirection === 'up' && direction !== 'DOWN') direction = 'UP';
else if (newDirection === 'right' && direction !== 'LEFT') direction = 'RIGHT';
else if (newDirection === 'down' && direction !== 'UP') direction = 'DOWN';
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, box, box);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? 'green' : 'lightgreen';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = 'darkgreen';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
let snakeX = snake[0].x;
let snakeY = snake[0].y;
if (direction === 'LEFT') snakeX -= box;
if (direction === 'UP') snakeY -= box;
if (direction === 'RIGHT') snakeX += box;
if (direction === 'DOWN') snakeY += box;
if (snakeX === food.x && snakeY === food.y) {
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, snake)) {
clearInterval(game);
alert('Game Over!');
}
snake.unshift(newHead);
}
function collision(head, array) {
for (let i = 0; i < array.length; i++) {
if (head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
let game = setInterval(draw, 200);