返回

滚动的月饼,跳跃的死神:复刻经典月饼版地狱死神小游戏

前端

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

先放出游戏截图馋一下你们 🙂

滚动的月饼,跳跃的死神,尽全力跳起,又在重力的作用下回落。。。这不正是人生奋斗的写照吗?只是我们现在要做的,是控制死神跳跃,尽可能吃掉更多的月饼。

游戏规则

  • 点击屏幕控制死神跳跃。
  • 跳起吃掉月饼,得分增加。
  • 碰到障碍物,游戏结束。
  • 随着游戏进行,难度会逐渐增加。

所需工具

  • jQuery
  • HTML
  • CSS

实现步骤

  1. 创建游戏画布
<canvas id="canvas"></canvas>
  1. 获取画布上下文
const ctx = canvas.getContext("2d");
  1. 创建死神角色
const death = {
  x: 100,
  y: 200,
  width: 50,
  height: 50
};
  1. 创建月饼障碍物
const obstacles = [];
  1. 创建键盘事件监听器
document.addEventListener("keydown", function(e) {
  if (e.keyCode === 32) {
    death.y -= 50;
  }
});
  1. 游戏循环
function gameLoop() {
  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 更新死神位置
  death.y += 5;

  // 绘制死神
  ctx.fillRect(death.x, death.y, death.width, death.height);

  // 更新月饼位置
  for (let i = 0; i < obstacles.length; i++) {
    obstacles[i].y += 5;
  }

  // 绘制月饼
  for (let i = 0; i < obstacles.length; i++) {
    ctx.fillRect(obstacles[i].x, obstacles[i].y, obstacles[i].width, obstacles[i].height);
  }

  // 判断碰撞
  for (let i = 0; i < obstacles.length; i++) {
    if (death.x < obstacles[i].x + obstacles[i].width &&
        death.x + death.width > obstacles[i].x &&
        death.y < obstacles[i].y + obstacles[i].height &&
        death.y + death.height > obstacles[i].y) {
      // 游戏结束
    }
  }

  // 请求下一次动画帧
  requestAnimationFrame(gameLoop);
}
  1. 开始游戏
gameLoop();

完整的代码

请访问以下链接获取完整的代码:
[代码链接]

结语

恭喜你!现在你已经成功复刻了月饼版地狱死神小游戏。你可以进一步扩展游戏,添加更多功能和关卡。通过这个项目,你不仅提升了编程技能,还重温了经典游戏的乐趣。希望你享受这个过程!