用 HTML Canvas 和 JavaScript 创建一个简单的捕捉小怪兽游戏

本教程将引导你使用 HTML Canvas 和 JavaScript 创建一个简单的捕捉小怪兽游戏。学习如何创建画布、加载图片、处理用户输入以及更新游戏状态。

1. 创建一个 HTML canvas 元素

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

2. 加载背景图片

let bgReady = false;
const bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = 'images/background.png';

3. 加载英雄图片

let heroReady = false;
const heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = 'images/hero.png';

4. 加载怪物图片

let monsterReady = false;
const monsterImage = new Image();
monsterImage.onload = function () {
  monsterReady = true;
};
monsterImage.src = 'images/monster.png';

5. 定义游戏对象

const hero = {
  speed: 256, // 每秒移动的像素数
  x: 0,
  y: 0,
};
const monster = {
  x: 0,
  y: 0,
};

let monstersCaught = 0;

6. 处理用户输入

const keysDown = {};
addEventListener('keydown', function (e) {
  keysDown[e.keyCode] = true;
}, false);
addEventListener('keyup', function (e) {
  delete keysDown[e.keyCode];
}, false);

7. 重置游戏对象

const reset = function () {
  hero.x = canvas.width / 2;
  hero.y = canvas.height / 2;

  // 把怪物放到画布的任意位置
  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

8. 更新游戏对象的状态

const update = function (modifier) {
  if (keysDown[38]) { // 用户按的是↑
    hero.y -= hero.speed * modifier;
  }
  if (keysDown[40]) { // 用户按的是↓
    hero.y += hero.speed * modifier;
  }
  if (keysDown[37]) { // 用户按的是←
    hero.x -= hero.speed * modifier;
  }
  if (keysDown[39]) { // 用户按的是→
    hero.x += hero.speed * modifier;
  }

  // 判断是否接触到怪物
  if (
    hero.x <= (monster.x + 32)
    && monster.x <= (hero.x + 32)
    && hero.y <= (monster.y + 32)
    && monster.y <= (hero.y + 32)
  ) {
    ++monstersCaught;
    reset();
  }
};

9. 渲染物体

const render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }
  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }
  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  // 显示分数
  ctx.fillStyle = 'rgb(250, 250, 250)';
  ctx.font = '24px Helvetica';
  ctx.textAlign = 'left';
  ctx.textBaseline = 'top';
  ctx.fillText('Goblins caught: ' + monstersCaught, 32, 32);
};

10. 主游戏循环

const main = function () {
  const now = Date.now();
  const delta = now - then;

  update(delta / 1000);
  render();

  then = now;

  // 立即调用主游戏循环
  requestAnimationFrame(main);
};

// 兼容不同浏览器的 requestAnimationFrame
const w = window;
const requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// 开始游戏
let then = Date.now();
reset();
main();

11. 允许用户点击按钮来重置游戏

const resetButton = document.createElement('button');
resetButton.textContent = 'Reset Game';
resetButton.addEventListener('click', function() {
  monstersCaught = 0;
  reset();
});
document.body.appendChild(resetButton);

12. 如果出现错误,打印错误信息

window.onerror = function(message, source, lineno, colno, error) {
  console.log('Error:', message, 'at', source, lineno, colno);
};

没有错误。

这个代码是一个简单的 HTML Canvas 游戏,允许用户控制一个英雄角色,捕捉随机出现在画布上的怪物。用户可以使用方向键控制英雄角色移动,每捕捉到一个怪物,分数就会增加。用户也可以点击“Reset Game”按钮重置游戏。

游戏代码分析:

  • 创建画布: 使用 document.createElement('canvas') 创建一个 HTML Canvas 元素,并获取它的 2D 绘图上下文 canvas.getContext('2d')。* 加载图片: 使用 Image 对象加载背景图片、英雄图片和怪物图片。在图片加载完成后,设置对应的标志位 bgReady, heroReady, monsterReadytrue,表示图片已加载完成,可以开始绘制。* 定义游戏对象: 定义了 heromonster 对象,分别存储英雄和怪物的位置信息。* 处理用户输入: 使用 addEventListener 监听键盘事件,根据用户按下不同的键,更新英雄的位置。* 重置游戏对象: 使用 reset 函数重置英雄和怪物的位置,并将分数归零。* 更新游戏对象的状态: 使用 update 函数根据用户输入和游戏规则,更新英雄和怪物的位置信息。* 渲染物体: 使用 render 函数将游戏中的背景、英雄和怪物绘制到画布上。* 主游戏循环: 使用 requestAnimationFrame 函数创建一个循环,每帧执行一次 update 函数和 render 函数,从而更新游戏状态并渲染游戏画面。* 重置按钮: 创建一个按钮,用户点击该按钮可以重置游戏。* 错误处理: 使用 window.onerror 函数捕获并打印错误信息,方便调试。

这个游戏代码仅仅是一个简单的示例,你可以根据自己的想法添加更多功能,比如:

  • 添加更多的怪物类型
  • 添加游戏关卡
  • 添加音效和背景音乐
  • 添加排行榜功能

希望本教程能帮助你入门 HTML Canvas 游戏开发。

HTML Canvas 游戏开发:用 JavaScript 创建简单的捕捉小怪兽游戏

原文地址: https://www.cveoy.top/t/topic/lMhC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录