-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
102 lines (82 loc) · 2 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const BG_COLOUR = '#1B1B1B';
const SNAKE_COLOUR = '#f2ECE4';
const FOOD_COLOUR = '#F15951';
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = canvas.height = 400;
const FR = 10;
const S = 20;
const T = canvas.width / S;
let pos, vel, snake, food;
init();
function init() {
pos = { x: 10, y: 10 };
vel = { x: 0, y: 0 };
snake = [
{ x: 8, y: 10 },
{ x: 9, y: 10 },
{ x: 10, y: 10 },
]
randomFood();
}
function randomFood() {
food = {
x: Math.floor(Math.random() * T),
y: Math.floor(Math.random() * T),
}
for (let cell of snake) {
if (cell.x === food.x && food.y === cell.y) {
return randomFood();
}
}
}
document.addEventListener('keydown', keydown);
function keydown(e) {
switch (e.keyCode) {
case 37: {
return vel = { x: -1, y: 0 }
}
case 38: {
return vel = { x: 0, y: -1 }
}
case 39: {
return vel = { x: 1, y: 0 }
}
case 40: {
return vel = { x: 0, y: 1 }
}
}
}
setInterval(() => {
requestAnimationFrame(gameLoop);
}, 1000 / FR);
function gameLoop() {
ctx.fillStyle = BG_COLOUR;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = SNAKE_COLOUR;
for (let cell of snake) {
ctx.fillRect(cell.x * S, cell.y * S, S, S);
}
ctx.fillStyle = FOOD_COLOUR;
ctx.fillRect(food.x * S, food.y * S, S, S);
pos.x += vel.x;
pos.y += vel.y;
if (pos.x < 0 || pos.x > T || pos.y < 0 || pos.y > T) {
init();
}
if (food.x === pos.x && food.y === pos.y) {
snake.push({ ...pos });
pos.x += vel.x;
pos.y += vel.y;
randomFood();
}
if (vel.x || vel.y) {
for (let cell of snake) {
if (cell.x === pos.x && cell.y === pos.y) {
return init();
}
}
snake.push({ ...pos });
snake.shift();
}
}