-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
95 lines (77 loc) · 2.48 KB
/
Copy pathscript.js
File metadata and controls
95 lines (77 loc) · 2.48 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
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
const box = 20;
let snake = [];
snake[0] = { x: 9 * box, y: 10 * box };
let food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
let score = 0;
let d;
let speed = 150; // Độ trễ của game - giảm số này để rắn di chuyển nhanh hơn
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 collision(newHead, snake) {
for (let i = 0; i < snake.length; i++) {
if (newHead.x === snake[i].x && newHead.y === snake[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? "#4CAF50" : "#c8e6c9";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "#388e3c";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = "#d32f2f";
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() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
} else {
snake.pop();
}
let 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);
document.getElementById('score').innerHTML = "Score: " + score;
}
function startGame() {
d = undefined;
snake = [{ x: 9 * box, y: 10 * box }];
score = 0;
food = {
x: Math.floor(Math.random() * 19 + 1) * box,
y: Math.floor(Math.random() * 19 + 1) * box
};
game = setInterval(draw, speed); // Đặt tốc độ rắn theo biến "speed"
}