返回

Canvas进阶(三)用TypeScript重构“辨色”小游戏,轻松应对各种bug

前端

前言

在上一篇文章中,我们用ES6手写了一个“辨色”小游戏,获得了不错的反响。但在评论区,有大神指出,这个游戏存在一个bug:打开控制台,输入以下代码即可破解,分数蹭蹭上涨。

const colors = document.querySelectorAll('.color');
for (let i = 0; i < colors.length; i++) {
  colors[i].style.color = '#000';
}

这个bug确实存在,而且很容易被发现。为了解决这个问题,我们决定用Canvas来重构这个游戏。Canvas是一个非常强大的绘图工具,可以轻松实现各种图形和动画效果。

重构游戏

首先,我们需要创建一个Canvas元素。

<canvas id="canvas" width="500" height="500"></canvas>

然后,我们需要获取这个Canvas元素并创建一个绘图上下文。

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

接下来,我们需要创建一个颜色数组。这个数组包含了游戏中所有可能出现的颜色。

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

然后,我们需要创建一个随机函数来随机选择一个颜色。

function randomColor() {
  return colors[Math.floor(Math.random() * colors.length)];
}

现在,我们可以开始绘制游戏界面了。首先,我们需要绘制一个背景。

ctx.fillStyle = 'white';
ctx.fillRect(0, 0, 500, 500);

接下来,我们需要绘制一个圆圈。这个圆圈就是我们要辨认的颜色。

ctx.fillStyle = randomColor();
ctx.beginPath();
ctx.arc(250, 250, 100, 0, 2 * Math.PI);
ctx.fill();

最后,我们需要绘制一些文字。这些文字包括游戏的标题、得分和提示。

ctx.fillStyle = 'black';
ctx.font = 'bold 30px Arial';
ctx.fillText('辨色游戏', 100, 50);

ctx.fillStyle = 'black';
ctx.font = 'bold 20px Arial';
ctx.fillText('得分:0', 350, 50);

ctx.fillStyle = 'black';
ctx.font = 'bold 15px Arial';
ctx.fillText('提示:用鼠标点击颜色方块来选择颜色', 50, 450);

添加交互

现在,我们需要添加一些交互来让游戏可以玩。首先,我们需要监听鼠标点击事件。

canvas.addEventListener('click', function(e) {
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 检查鼠标点击的位置是否在圆圈内
  const dx = x - 250;
  const dy = y - 250;
  const distance = Math.sqrt(dx * dx + dy * dy);
  if (distance < 100) {
    // 鼠标点击在圆圈内,增加得分
    score++;
    ctx.fillStyle = 'black';
    ctx.font = 'bold 20px Arial';
    ctx.fillText('得分:' + score, 350, 50);
  } else {
    // 鼠标点击不在圆圈内,扣除得分
    score--;
    ctx.fillStyle = 'black';
    ctx.font = 'bold 20px Arial';
    ctx.fillText('得分:' + score, 350, 50);
  }
});

结语

现在,我们的“辨色”游戏就重构完成