返回

EVA.js学习笔记:用管道增强Flappy Bird游戏

前端

导言

在上一篇文章中,我们创建了Flappy Bird游戏的基本流程。现在,是时候添加一些激动人心的元素了——管道!

管道将成为小鸟逃避的障碍,躲避成功即可得分。随着游戏进行,管道的速度和难度将不断增加,让游戏更具挑战性。

创建管道

  1. 定义管道类:
class Pipe {
  constructor() {
    // 管道位置和大小
    this.x = canvas.width;
    this.y = Math.random() * (canvas.height - PIPE_GAP) + PIPE_GAP / 2;
    this.width = PIPE_WIDTH;
    this.height = PIPE_HEIGHT;

    // 管道颜色
    this.fillStyle = "#008000";

    // 得分检测标志
    this.scored = false;
  }
}
  1. 绘制管道:
Pipe.prototype.draw = function() {
  // 绘制上管道
  context.fillStyle = this.fillStyle;
  context.fillRect(this.x, 0, this.width, this.y);

  // 绘制下管道
  context.fillRect(this.x, this.y + PIPE_GAP, this.width, canvas.height - this.y - PIPE_GAP);
}
  1. 更新管道:
Pipe.prototype.update = function() {
  // 向左移动管道
  this.x -= PIPE_SPEED;

  // 重置管道
  if (this.x < -this.width) {
    this.x = canvas.width;
    this.y = Math.random() * (canvas.height - PIPE_GAP) + PIPE_GAP / 2;
    this.scored = false;
  }
}

游戏逻辑

  1. 检测碰撞:
function detectCollision(bird, pipes) {
  for (let i = 0; i < pipes.length; i++) {
    if (
      bird.x + bird.width >= pipes[i].x &&
      bird.x <= pipes[i].x + pipes[i].width &&
      (bird.y <= pipes[i].y || bird.y >= pipes[i].y + pipes[i].height + PIPE_GAP)
    ) {
      return true;
    }
  }

  return false;
}
  1. 增加分数:
function scorePoint(bird, pipes) {
  for (let i = 0; i < pipes.length; i++) {
    if (!pipes[i].scored && bird.x > pipes[i].x + pipes[i].width) {
      pipes[i].scored = true;
      score++;
    }
  }
}

完整代码

完整代码请见:https://gist.github.com/codebunker/608e1c43db73c082a6757b40f6a26434

结论

添加管道后,我们的Flappy Bird游戏变得更加有趣和具有挑战性。通过添加更多的游戏元素,比如敌人或道具,我们可以让游戏变得更加丰富。欢迎在评论区分享你对本教程的看法和改进建议!