Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (66 loc) · 1.76 KB
/
Copy pathscript.js
File metadata and controls
79 lines (66 loc) · 1.76 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
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [{ x: 200, y: 200 }];
let score= 0;
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
let dx = box;
let dy = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move the snake
const newHead = {
x: snake[0].x + dx,
y: snake[0].y + dy
};
snake.unshift(newHead);
// Eat food logic
if (newHead.x === food.x && newHead.y === food.y) {
score++;
document.getElementById("score").textContent = "Score: " + score;
food = {
x: Math.floor(Math.random() * (canvas.width / box)) * box,
y: Math.floor(Math.random() * (canvas.height / box)) * box
};
} else {
snake.pop(); // no food? remove tail
}
if (
newHead.x<0 || newHead.x >=canvas.width||
newHead.y<0 || newHead.y >=canvas.height
) {
alert("Game Over! Final score:"+ score);
document.location.reload();
clearInterval(gameloop);
}
// Draw the snake
snake.forEach((segment, index) => {
ctx.fillStyle = index === 0 ? "blue" : "pink";
ctx.fillRect(segment.x, segment.y, box, box);
});
// Draw the food (just once!)
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, box, box);
}
// ⏲️ Game loop
const gameloop = setInterval(draw, 100);
// 🕹️ Keyboard controls (outside draw!)
document.addEventListener("keydown", (event) => {
const key = event.key;
if (key === "ArrowUp" && dy === 0) {
dx = 0;
dy = -box;
} else if (key === "ArrowDown" && dy === 0) {
dx = 0;
dy = box;
} else if (key === "ArrowLeft" && dx === 0) {
dx = -box;
dy = 0;
} else if (key === "ArrowRight" && dx === 0) {
dx = box;
dy = 0;
}
});