-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
112 lines (98 loc) · 2.43 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("gameCanvas");
const context = canvas.getContext("2d");
const gridSize = 20;
let snake = [{ x: 3, y: 3 }];
let food = { x: 10, y: 10 };
let dx = 1;
let dy = 0;
function drawSnake() {
context.fillStyle = "#00f";
snake.forEach(segment => {
context.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
});
}
function drawFood() {
context.fillStyle = "#f00";
context.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}
function moveSnake() {
const newHead = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(newHead);
if (newHead.x === food.x && newHead.y === food.y) {
generateFood();
} else {
snake.pop();
}
}
function generateFood() {
food.x = Math.floor(Math.random() * canvas.width / gridSize);
food.y = Math.floor(Math.random() * canvas.height / gridSize);
}
function checkCollision() {
const head = snake[0];
if (head.x < 0 || head.x >= canvas.width / gridSize ||
head.y < 0 || head.y >= canvas.height / gridSize) {
return true;
}
for (let i = 1; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
return true;
}
}
return false;
}
function gameLoop() {
if (checkCollision()) {
alert("Game Over!");
location.reload();
return;
}
context.clearRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
moveSnake();
setTimeout(gameLoop, 100);
}
document.addEventListener("keydown", event => {
if (event.key === "ArrowUp" && dy !== 1) {
dx = 0;
dy = -1;
} else if (event.key === "ArrowDown" && dy !== -1) {
dx = 0;
dy = 1;
} else if (event.key === "ArrowLeft" && dx !== 1) {
dx = -1;
dy = 0;
} else if (event.key === "ArrowRight" && dx !== -1) {
dx = 1;
dy = 0;
}
});
generateFood();
gameLoop();
</script>
</body>
</html>