下载地址:https://download.csdn.net/download/mosquito_lover1/90308956
游戏玩法:
点击"开始游戏"按钮开始 使用键盘方向键控制蛇的移动 吃到红色食物可以得分 撞到墙壁或自己会结束游戏
核心源码:
class SnakeGame {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.canvas.width = 400;
this.canvas.height = 400;
this.gridSize = 20;
this.snake = [];
this.food = {};
this.direction = 'right';
this.score = 0;
this.gameLoop = null;
this.gameSpeed = 150;
this.startButton = document.getElementById('startButton');
this.scoreElement = document.getElementById('scoreValue');
this.startButton.addEventListener('click', () => this.startGame());
document.addEventListener('keydown', (e) => this.handleKeyPress(e));
// 新增属性
this.isPaused = false;
this.highScore = localStorage.getItem('snakeHighScore') || 0;
this.difficultySelect = document.getElementById('difficulty');
this.pauseButton = document.getElementById('pauseButton');
this.highScoreElement = document.getElementById('highScoreValue');
this.eatSound = document.getElementById('eatSound');
this.gameOverSound = document.getElementById('gameOverSound');
// 设置最高分显示
this.highScoreElement.textContent = this.highScore;
// 添加暂停按钮事件监听
this.pauseButton.addEventListener('click', () => this.togglePause());
// 添加触摸控制
this.setupTouchControls();
// 更新游戏速度
this.difficultySelect.addEventListener('change', () => {
this.gameSpeed = parseInt(this.difficultySelect.value);
if (this.gameLoop) {
clearInterval(this.gameLoop);