返回

用面向对象编程写贪吃蛇游戏

前端

  1. 创建一个贪吃蛇类

我们的第一个步骤是创建一个贪吃蛇类。这个类将包含有关蛇的所有信息,例如它的位置、长度和方向。它还将包含所有控制蛇运动的方法。

class Snake {
  constructor() {
    this.x = 0;
    this.y = 0;
    this.length = 3;
    this.direction = 'right';
  }

  move() {
    switch (this.direction) {
      case 'right':
        this.x++;
        break;
      case 'left':
        this.x--;
        break;
      case 'up':
        this.y--;
        break;
      case 'down':
        this.y++;
        break;
    }
  }

  grow() {
    this.length++;
  }

  turn(direction) {
    this.direction = direction;
  }
}

2. 创建一个食物类

我们的下一个步骤是创建一个食物类。这个类将包含有关食物的所有信息,例如它的位置和类型。

class Food {
  constructor() {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    this.type = 'apple';
  }
}

3. 创建一个游戏类

我们的最后一个步骤是创建一个游戏类。这个类将包含有关游戏的所有信息,例如得分、游戏状态和游戏循环。

class Game {
  constructor() {
    this.score = 0;
    this.gameState = 'running';
    this.snake = new Snake();
    this.food = new Food();
  }

  start() {
    this.gameLoop();
  }

  gameLoop() {
    // 检查游戏状态
    if (this.gameState === 'running') {
      // 更新游戏状态
      this.snake.move();
      this.checkCollisions();
      this.draw();

      // 重新启动游戏循环
      setTimeout(this.gameLoop, 100);
    }
  }

  checkCollisions() {
    // 检查蛇是否撞到自己
    for (let i = 4; i < this.snake.length; i++) {
      if (this.snake.x === this.snake.body[i].x && this.snake.y === this.snake.body[i].y) {
        this.gameState = 'game over';
        break;
      }
    }

    // 检查蛇是否撞到墙
    if (this.snake.x < 0 || this.snake.x > canvas.width || this.snake.y < 0 || this.snake.y > canvas.height) {
      this.gameState = 'game over';
    }

    // 检查蛇是否吃到食物
    if (this.snake.x === this.food.x && this.snake.y === this.food.y) {
      this.score++;
      this.snake.grow();
      this.food = new Food();
    }
  }

  draw() {
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制蛇
    for (let i = 0; i < this.snake.length; i++) {
      ctx.fillStyle = 'green';
      ctx.fillRect(this.snake.body[i].x, this.snake.body[i].y, 10, 10);
    }

    // 绘制食物
    ctx.fillStyle = 'red';
    ctx.fillRect(this.food.x, this.food.y, 10, 10);

    // 绘制得分
    ctx.fillStyle = 'black';
    ctx.font = '16px Arial';
    ctx.fillText('得分: ' + this.score, 10, 20);
  }
}

4. 启动游戏

现在我们已经创建了所有必要的类,我们就可以启动游戏了。为此,我们只需创建一个新的游戏对象并调用它的 start() 方法。

const game = new Game();
game.start();

这将启动游戏循环,并且游戏将继续运行,直到蛇撞到自己、撞到墙或吃到食物。