-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
517 lines (435 loc) · 16.1 KB
/
script.js
File metadata and controls
517 lines (435 loc) · 16.1 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
class SnakeGame {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.scoreElement = document.getElementById('score');
this.highScoreElement = document.getElementById('highScore');
this.gameStatusElement = document.getElementById('gameStatus');
this.levelElement = document.getElementById('level');
this.foodInfoElement = document.getElementById('food-info');
this.levelCompleteModal = document.getElementById('levelCompleteModal');
this.levelCompleteText = document.getElementById('levelCompleteText');
this.continueBtn = document.getElementById('continueBtn');
this.quitBtn = document.getElementById('quitBtn');
// 游戏设置
this.gridSize = 20;
this.tileCount = this.canvas.width / this.gridSize;
this.maxLevel = 10; // 最大关卡数
// 游戏状态
this.gameRunning = false;
this.gamePaused = false;
this.score = 0;
this.highScore = localStorage.getItem('snakeHighScore') || 0;
this.level = 1;
this.foodEaten = 0;
this.baseSpeed = 150;
this.currentSpeed = 150;
// 蛇的初始状态
this.snake = [
{ x: 10, y: 10 }
];
this.direction = { x: 0, y: 0 };
this.nextDirection = { x: 0, y: 0 };
// 食物
this.food = { x: 15, y: 15 };
this.init();
}
init() {
this.updateHighScoreDisplay();
this.updateLevelDisplay();
this.updateFoodCountDisplay();
this.setupModalEvents();
this.setupEventListeners();
this.generateFood();
this.draw();
}
setupEventListeners() {
// 键盘控制
document.addEventListener('keydown', (e) => {
if (!this.gameRunning && e.code === 'Space') {
this.startGame();
return;
}
if (this.gameRunning) {
switch(e.code) {
case 'ArrowUp':
case 'KeyW':
if (this.direction.y !== 1) {
this.nextDirection = { x: 0, y: -1 };
}
break;
case 'ArrowDown':
case 'KeyS':
if (this.direction.y !== -1) {
this.nextDirection = { x: 0, y: 1 };
}
break;
case 'ArrowLeft':
case 'KeyA':
if (this.direction.x !== 1) {
this.nextDirection = { x: -1, y: 0 };
}
break;
case 'ArrowRight':
case 'KeyD':
if (this.direction.x !== -1) {
this.nextDirection = { x: 1, y: 0 };
}
break;
case 'Space':
this.togglePause();
break;
}
}
e.preventDefault();
});
// 按钮控制
document.getElementById('startBtn').addEventListener('click', () => {
this.startGame();
});
document.getElementById('pauseBtn').addEventListener('click', () => {
this.togglePause();
});
document.getElementById('restartBtn').addEventListener('click', () => {
this.restartGame();
});
}
startGame() {
if (!this.gameRunning) {
this.gameRunning = true;
this.gamePaused = false;
this.direction = { x: 1, y: 0 };
this.nextDirection = { x: 1, y: 0 };
this.updateGameStatus('游戏进行中 - 按空格键暂停');
this.gameLoop();
}
}
togglePause() {
if (this.gameRunning) {
this.gamePaused = !this.gamePaused;
if (this.gamePaused) {
this.updateGameStatus('游戏已暂停 - 按空格键继续');
} else {
this.updateGameStatus('游戏进行中 - 按空格键暂停');
this.gameLoop();
}
}
}
restartGame() {
this.gameRunning = false;
this.gamePaused = false;
this.score = 0;
this.level = 1;
this.foodEaten = 0;
this.currentSpeed = this.baseSpeed;
this.snake = [{ x: 10, y: 10 }];
this.direction = { x: 0, y: 0 };
this.nextDirection = { x: 0, y: 0 };
this.generateFood();
this.updateScore();
this.updateLevelDisplay();
this.updateFoodCountDisplay();
this.updateGameStatus('按空格键开始游戏');
this.draw();
}
gameLoop() {
if (!this.gameRunning || this.gamePaused) return;
setTimeout(() => {
this.update();
this.draw();
if (this.gameRunning && !this.gamePaused) {
this.gameLoop();
}
}, this.currentSpeed);
}
update() {
// 更新方向
this.direction = { ...this.nextDirection };
// 移动蛇头
const head = { ...this.snake[0] };
head.x += this.direction.x;
head.y += this.direction.y;
// 检查墙壁碰撞
if (head.x < 0 || head.x >= this.tileCount || head.y < 0 || head.y >= this.tileCount) {
this.gameOver();
return;
}
// 检查自身碰撞
for (let segment of this.snake) {
if (head.x === segment.x && head.y === segment.y) {
this.gameOver();
return;
}
}
this.snake.unshift(head);
// 检查食物碰撞
if (head.x === this.food.x && head.y === this.food.y) {
this.score += 10;
this.foodEaten++;
this.updateScore();
this.updateFoodCountDisplay();
this.generateFood();
this.animateScore();
// 检查是否通过关卡
if (this.foodEaten >= 12) {
this.levelUp();
}
} else {
this.snake.pop();
}
}
generateFood() {
let newFood;
do {
newFood = {
x: Math.floor(Math.random() * this.tileCount),
y: Math.floor(Math.random() * this.tileCount)
};
} while (this.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
this.food = newFood;
}
draw() {
// 清空画布
this.ctx.fillStyle = '#1a202c';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// 绘制网格
this.drawGrid();
// 绘制蛇
this.drawSnake();
// 绘制食物
this.drawFood();
}
drawGrid() {
this.ctx.strokeStyle = '#2d3748';
this.ctx.lineWidth = 1;
for (let i = 0; i <= this.tileCount; i++) {
this.ctx.beginPath();
this.ctx.moveTo(i * this.gridSize, 0);
this.ctx.lineTo(i * this.gridSize, this.canvas.height);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(0, i * this.gridSize);
this.ctx.lineTo(this.canvas.width, i * this.gridSize);
this.ctx.stroke();
}
}
drawSnake() {
this.snake.forEach((segment, index) => {
if (index === 0) {
// 蛇头
this.ctx.fillStyle = '#48bb78';
this.ctx.fillRect(
segment.x * this.gridSize + 1,
segment.y * this.gridSize + 1,
this.gridSize - 2,
this.gridSize - 2
);
// 蛇头眼睛
this.ctx.fillStyle = '#1a202c';
const eyeSize = 3;
const eyeOffset = 5;
this.ctx.fillRect(
segment.x * this.gridSize + eyeOffset,
segment.y * this.gridSize + eyeOffset,
eyeSize,
eyeSize
);
this.ctx.fillRect(
segment.x * this.gridSize + this.gridSize - eyeOffset - eyeSize,
segment.y * this.gridSize + eyeOffset,
eyeSize,
eyeSize
);
} else {
// 蛇身
this.ctx.fillStyle = '#68d391';
this.ctx.fillRect(
segment.x * this.gridSize + 2,
segment.y * this.gridSize + 2,
this.gridSize - 4,
this.gridSize - 4
);
}
});
}
drawFood() {
this.ctx.fillStyle = '#e53e3e';
this.ctx.beginPath();
this.ctx.arc(
this.food.x * this.gridSize + this.gridSize / 2,
this.food.y * this.gridSize + this.gridSize / 2,
this.gridSize / 2 - 2,
0,
2 * Math.PI
);
this.ctx.fill();
// 食物高光
this.ctx.fillStyle = '#fc8181';
this.ctx.beginPath();
this.ctx.arc(
this.food.x * this.gridSize + this.gridSize / 2 - 3,
this.food.y * this.gridSize + this.gridSize / 2 - 3,
3,
0,
2 * Math.PI
);
this.ctx.fill();
}
updateScore() {
this.scoreElement.textContent = this.score;
if (this.score > this.highScore) {
this.highScore = this.score;
localStorage.setItem('snakeHighScore', this.highScore);
this.updateHighScoreDisplay();
}
}
updateHighScoreDisplay() {
this.highScoreElement.textContent = this.highScore;
}
updateGameStatus(message) {
this.gameStatusElement.textContent = message;
}
animateScore() {
this.scoreElement.classList.add('score-animation');
setTimeout(() => {
this.scoreElement.classList.remove('score-animation');
}, 500);
}
levelUp() {
// 检查是否已达到最大关卡
if (this.level >= this.maxLevel) {
this.gameComplete();
return;
}
this.level++;
this.foodEaten = 0;
this.currentSpeed = Math.max(50, this.baseSpeed - (this.level - 1) * 15);
this.updateLevelDisplay();
this.updateFoodCountDisplay();
// 显示关卡通过提示
this.showLevelUpMessage();
}
updateLevelDisplay() {
this.levelElement.textContent = this.level;
}
updateFoodCountDisplay() {
this.foodInfoElement.textContent = `食物:${this.foodCount}/12`;
// 添加食物计数动画
this.foodInfoElement.classList.add('food-count-animation');
setTimeout(() => {
this.foodInfoElement.classList.remove('food-count-animation');
}, 300);
}
setupModalEvents() {
// 继续按钮事件
this.continueBtn.addEventListener('click', () => {
this.hideModal();
this.startNewLevel();
});
// 放弃按钮事件
this.quitBtn.addEventListener('click', () => {
this.hideModal();
this.gameOver();
});
}
hideModal() {
this.levelCompleteModal.style.display = 'none';
}
startNewLevel() {
// 如果是通关后重新挑战,重置所有游戏状态
if (this.level >= this.maxLevel) {
this.level = 1;
this.currentSpeed = this.baseSpeed;
this.score = 0;
this.updateScoreDisplay();
}
// 重置蛇的长度为1
this.snake = [{x: 200, y: 200}];
// 重置食物计数
this.foodCount = 0;
this.updateFoodCountDisplay();
// 生成新食物
this.generateFood();
// 更新游戏状态
this.updateGameStatus('游戏进行中 - 按空格键暂停');
// 重新开始游戏
this.gameRunning = true;
this.gameLoop();
}
gameComplete() {
// 暂停游戏
this.gameRunning = false;
// 更新弹窗文本为通关祝贺
this.levelCompleteText.textContent = `🎉 恭喜您!已成功通关所有10关!🎉`;
// 修改弹窗内容
const modalBody = this.levelCompleteModal.querySelector('.modal-body');
const levelInfo = modalBody.querySelector('.level-info');
const snakeResetInfo = modalBody.querySelector('.snake-reset-info');
levelInfo.textContent = '您已完成了所有挑战,成为贪吃蛇大师!';
snakeResetInfo.textContent = '感谢您的游戏,可以重新开始挑战或结束游戏。';
// 修改按钮文本
this.continueBtn.textContent = '重新挑战';
this.quitBtn.textContent = '结束游戏';
// 显示弹窗
this.levelCompleteModal.style.display = 'block';
// 添加通关庆祝动画
this.levelElement.classList.add('level-up-animation');
this.progressFill.style.boxShadow = '0 4px 20px rgba(72, 187, 120, 0.6)';
// 2秒后移除动画类
setTimeout(() => {
this.levelElement.classList.remove('level-up-animation');
}, 2000);
}
showLevelUpMessage() {
// 暂停游戏
this.gameRunning = false;
// 更新弹窗文本
this.levelCompleteText.textContent = `您已成功通过第${this.level - 1}关!`;
// 重置弹窗内容(防止通关后的修改影响普通关卡)
const modalBody = this.levelCompleteModal.querySelector('.modal-body');
const levelInfo = modalBody.querySelector('.level-info');
const snakeResetInfo = modalBody.querySelector('.snake-reset-info');
levelInfo.textContent = '下一关游戏速度将会更快,挑战更大!';
snakeResetInfo.textContent = '新关卡开始时,贪吃蛇长度将重置为1';
// 重置按钮文本
this.continueBtn.textContent = '继续下一关';
this.quitBtn.textContent = '放弃游戏';
// 显示弹窗
this.levelCompleteModal.style.display = 'block';
// 添加关卡升级动画
this.levelElement.classList.add('level-up-animation');
// 2秒后移除动画类
setTimeout(() => {
this.levelElement.classList.remove('level-up-animation');
}, 2000);
}
gameOver() {
this.gameRunning = false;
this.gamePaused = false;
this.updateGameStatus(`游戏结束!得分: ${this.score} - 按空格键重新开始`);
// 游戏结束动画
this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = '#ffffff';
this.ctx.font = 'bold 24px Arial';
this.ctx.textAlign = 'center';
this.ctx.fillText('游戏结束!', this.canvas.width / 2, this.canvas.height / 2 - 20);
this.ctx.font = '16px Arial';
this.ctx.fillText(`最终得分: ${this.score}`, this.canvas.width / 2, this.canvas.height / 2 + 10);
this.ctx.fillText('按空格键重新开始', this.canvas.width / 2, this.canvas.height / 2 + 35);
// 重置游戏状态以便重新开始
setTimeout(() => {
this.restartGame();
}, 100);
}
}
// 初始化游戏
window.addEventListener('DOMContentLoaded', () => {
new SnakeGame();
});
// 防止页面滚动
window.addEventListener('keydown', (e) => {
if(['Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);