Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
85 lines (71 loc) · 2.26 KB
/
Copy pathscript.js
File metadata and controls
85 lines (71 loc) · 2.26 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
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const box = 20;
const rows = canvas.height / box;
const columns = canvas.width / box;
let snake = [];
let direction = "RIGHT";
let score = 0;
let gameInterval;
let food;
function randomFood() {
return {
x: Math.floor(Math.random() * columns) * box,
y: Math.floor(Math.random() * rows) * box,
};
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw Snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "#0f0" : "#fff";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
// Move Snake
let head = { ...snake[0] };
if (direction === "LEFT") head.x -= box;
if (direction === "RIGHT") head.x += box;
if (direction === "UP") head.y -= box;
if (direction === "DOWN") head.y += box;
// Check collision with wall
if (
head.x < 0 || head.x >= canvas.width ||
head.y < 0 || head.y >= canvas.height ||
snake.some((seg, idx) => idx !== 0 && seg.x === head.x && seg.y === head.y)
) {
clearInterval(gameInterval);
document.getElementById("game-over").innerText = "Game Over!";
document.getElementById("restart-btn").style.display = "block";
return;
}
snake.unshift(head);
// Check food collision
if (head.x === food.x && head.y === food.y) {
score++;
food = randomFood();
document.getElementById("score").innerText = score;
} else {
snake.pop();
}
// Draw Food
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
}
function startGame() {
snake = [{ x: 10 * box, y: 10 * box }];
direction = "RIGHT";
score = 0;
food = randomFood();
document.getElementById("score").innerText = score;
document.getElementById("game-over").innerText = "";
document.getElementById("restart-btn").style.display = "none";
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(draw, 100);
}
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
else if (e.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
else if (e.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
else if (e.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
});
startGame();