Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
119 lines (101 loc) · 3.11 KB
/
Copy pathindex.html
File metadata and controls
119 lines (101 loc) · 3.11 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<html>
<head>
<title>Snake</title>
</head>
<body>
<canvas width="400" height="400" id="snake-canvas"></canvas>
</body>
<script>
const canvas = document.getElementById("snake-canvas");
const context = canvas.getContext('2d');
const size = 40;
const delta = {x: 1, y: 0};
const apple = {x: 3, y: 5};
const snake = [
{x: 3, y: 2},
{x: 3, y: 4},
{x: 4, y: 4},
];
function randomizeApple() {
apple.x = 9 * Math.random() | 0;
apple.y = 9 * Math.random() | 0;
}
function moveSnake(delta) {
const pos = snake.pop();
pos.x = snake[0].x + delta.x;
pos.y = snake[0].y + delta.y;
snake.unshift(pos);
draw();
}
function draw() {
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
drawGrid();
drawSnake(snake);
drawApple(apple);
}
function drawApple(apple) {
context.fillStyle = 'red';
context.fillRect(apple.x * size - 10, apple.y * size - 10, 20, 20);
}
function drawGrid() {
context.fillStyle = 'white';
for (let y = size; y < canvas.height; y += size) {
context.fillRect(0, y, canvas.width, 1);
}
for (let x = size; x < canvas.width; x += size) {
context.fillRect(x, 0, 1, canvas.height);
}
}
function drawSnake(snake) {
context.beginPath();
context.moveTo(snake[0].x * size, snake[0].y * size);
for (let pos of snake) {
context.lineTo(pos.x * size, pos.y * size);
}
context.lineWidth = 10;
context.strokeStyle = 'green';
context.stroke();
}
function update() {
const head = snake[0];
snake.forEach((pos, index) => {
if (index > 0) {
if (pos.x === head.x && pos.y === head.y) {
snake.splice(3, Infinity);
}
}
});
if (head.x === apple.x && head.y === apple.y) {
randomizeApple();
snake.push({
x: head.x,
y: head.y,
});
}
moveSnake(delta);
draw();
}
update();
setInterval(update, 300);
window.addEventListener("keydown", event => {
const code = event.code;
if (code === "ArrowRight") {
delta.x = 1;
delta.y = 0;
}
if (code === "ArrowLeft") {
delta.x = -1;
delta.y = 0;
}
if (code === "ArrowUp") {
delta.x = 0;
delta.y = -1;
}
if (code === "ArrowDown") {
delta.x = 0;
delta.y = 1;
}
});
</script>
</html>