-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
286 lines (235 loc) · 7.46 KB
/
Copy pathscript.js
File metadata and controls
286 lines (235 loc) · 7.46 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// ===== 游戏初始化变量和常量 =====
// 获取所有需要的DOM元素
const gameBoard = document.getElementById('game-board');
const scoreElement = document.getElementById('score');
const gameOverText = document.getElementById('game-over-text');
const restartButton = document.getElementById('restart-button');
// 游戏配置常量
const gridSize = 20; // 游戏区域20x20格子
const gameSpeed = 150; // 游戏速度(毫秒)
// 游戏状态变量
let snake = [{ x: 10, y: 10 }]; // 蛇的初始位置(数组,每个元素是坐标对象)
let food = { x: 15, y: 15 }; // 食物的初始位置
let direction = 'right'; // 初始移动方向
let nextDirection = 'right'; // 下一步移动方向(防止快速按键导致的反向移动)
let score = 0; // 当前分数
let isGameOver = false; // 游戏是否结束
let gameInterval; // 游戏主循环定时器
// ===== 游戏主循环 =====
function main() {
if (isGameOver) {
clearInterval(gameInterval);
showGameOver();
return;
}
// 更新方向
direction = nextDirection;
// 移动蛇
moveSnake();
// 检查碰撞
if (checkCollision()) {
isGameOver = true;
return;
}
// 绘制游戏画面
draw();
}
// ===== 绘制功能 =====
function draw() {
// 清空游戏区域
gameBoard.innerHTML = '';
// 绘制蛇身
snake.forEach((segment, index) => {
const snakeElement = document.createElement('div');
// 第一个元素是蛇头,添加特殊样式
if (index === 0) {
snakeElement.classList.add('snake', 'snake-head');
} else {
snakeElement.classList.add('snake');
}
// 设置格子位置(CSS Grid定位)
snakeElement.style.gridColumn = segment.x;
snakeElement.style.gridRow = segment.y;
gameBoard.appendChild(snakeElement);
});
// 绘制食物
const foodElement = document.createElement('div');
foodElement.classList.add('food');
foodElement.style.gridColumn = food.x;
foodElement.style.gridRow = food.y;
gameBoard.appendChild(foodElement);
// 更新分数显示
scoreElement.textContent = `得分: ${score}`;
}
// ===== 移动逻辑 =====
function moveSnake() {
// 获取当前蛇头位置
const head = { ...snake[0] };
// 根据方向计算新的蛇头位置
switch (direction) {
case 'up':
head.y -= 1;
break;
case 'down':
head.y += 1;
break;
case 'left':
head.x -= 1;
break;
case 'right':
head.x += 1;
break;
}
// 将新蛇头添加到蛇身前端
snake.unshift(head);
// 检查是否吃到食物
if (head.x === food.x && head.y === food.y) {
// 吃到食物:增加分数,生成新食物,蛇身变长(不移除尾巴)
score += 10;
generateFood();
} else {
// 没吃到食物:移除蛇尾,保持长度不变
snake.pop();
}
}
// ===== 控制逻辑 =====
function handleKeyPress(event) {
// 防止游戏结束后仍能控制
if (isGameOver) return;
// 防止方向键导致页面滚动
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) {
event.preventDefault();
}
// 根据按键设置移动方向,同时防止反向移动
switch (event.key) {
case 'ArrowUp':
if (direction !== 'down') {
nextDirection = 'up';
}
break;
case 'ArrowDown':
if (direction !== 'up') {
nextDirection = 'down';
}
break;
case 'ArrowLeft':
if (direction !== 'right') {
nextDirection = 'left';
}
break;
case 'ArrowRight':
if (direction !== 'left') {
nextDirection = 'right';
}
break;
}
}
// ===== 碰撞检测 =====
function checkCollision() {
const head = snake[0];
// 检查撞墙:蛇头超出边界
if (head.x < 1 || head.x > gridSize ||
head.y < 1 || head.y > gridSize) {
return true;
}
// 检查撞自己:蛇头与身体其他部分重合
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
return true;
}
}
return false;
}
// ===== 食物生成 =====
function generateFood() {
let newFood;
// 循环生成新食物位置,直到不与蛇身重合
do {
newFood = {
x: Math.floor(Math.random() * gridSize) + 1,
y: Math.floor(Math.random() * gridSize) + 1
};
} while (isSnakePosition(newFood));
food = newFood;
}
// 检查指定位置是否在蛇身上
function isSnakePosition(position) {
return snake.some(segment =>
segment.x === position.x && segment.y === position.y
);
}
// ===== 游戏结束逻辑 =====
function showGameOver() {
// 显示游戏结束提示和重启按钮
gameOverText.classList.remove('hidden');
restartButton.classList.remove('hidden');
// 更新游戏结束文本,显示最终分数
gameOverText.innerHTML = `游戏结束!<br>最终得分: ${score}`;
}
// ===== 游戏重启逻辑 =====
function restartGame() {
// 重置所有游戏变量到初始状态
snake = [{ x: 10, y: 10 }];
food = { x: 15, y: 15 };
direction = 'right';
nextDirection = 'right';
score = 0;
isGameOver = false;
// 隐藏游戏结束提示和重启按钮
gameOverText.classList.add('hidden');
restartButton.classList.add('hidden');
// 确保没有重复的定时器
if (gameInterval) {
clearInterval(gameInterval);
}
// 重新生成食物(确保不与蛇重合)
generateFood();
// 重新绘制游戏
draw();
// 重新启动游戏循环
startGame();
}
// ===== 启动游戏 =====
function startGame() {
gameInterval = setInterval(main, gameSpeed);
}
// ===== 事件监听器设置 =====
function setupEventListeners() {
// 监听键盘按键
document.addEventListener('keydown', handleKeyPress);
// 监听重启按钮点击
restartButton.addEventListener('click', restartGame);
}
// ===== 游戏初始化 =====
function initGame() {
console.log('贪食蛇游戏初始化开始...');
// 设置事件监听器
setupEventListeners();
// 生成初始食物
generateFood();
// 绘制初始游戏状态
draw();
// 启动游戏循环
startGame();
console.log('贪食蛇游戏启动成功!使用方向键控制移动');
}
// ===== 页面加载完成后启动游戏 =====
document.addEventListener('DOMContentLoaded', function() {
console.log('页面加载完成,准备初始化游戏...');
initGame();
});
// ===== 工具函数 =====
// 获取随机整数(包含最小值和最大值)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 调试函数:打印当前游戏状态
function debugGameState() {
console.log('=== 游戏状态调试信息 ===');
console.log('蛇的位置:', snake);
console.log('食物位置:', food);
console.log('当前方向:', direction);
console.log('当前分数:', score);
console.log('游戏是否结束:', isGameOver);
console.log('========================');
}