Canvas 进阶(三):使用 TypeScript 与 Canvas 重写“辨色”小游戏

作者:KAKAKA2024.04.15 16:10浏览量:7

简介:在本文中,我们将使用 TypeScript 和 Canvas API 来重写经典的“辨色”小游戏。我们将介绍如何使用 TypeScript 来编写更加健壮和可维护的代码,以及如何利用 Canvas 来实现游戏的图形界面和交互功能。

Canvas 进阶(三):使用 TypeScript 与 Canvas 重写“辨色”小游戏

在前面的文章中,我们已经介绍了如何使用 Canvas 来绘制图形和进行基础的动画效果。今天,我们将进一步探索 Canvas 的应用,结合 TypeScript 来重写一个“辨色”小游戏。通过这个游戏,我们可以练习 TypeScript 的基础语法,同时深入了解 Canvas 的事件处理和绘图功能。

游戏规则简介

“辨色”游戏是一个简单而有趣的小游戏,玩家需要在规定的时间内尽可能多地点击与指定颜色相同的小方块。每个小方块的颜色都是随机生成的,而指定颜色会在游戏开始时显示给玩家。玩家需要在有限的时间内尽可能多地点击正确颜色的方块,以获得更高的分数。

环境准备

在开始编写代码之前,请确保您的开发环境中已经安装了 Node.js 和 TypeScript。您可以使用 npm 来安装 TypeScript 的相关依赖。另外,为了运行和测试代码,您还需要一个支持 Canvas 的浏览器。

初始化项目

首先,创建一个新的文件夹来存放项目文件,并在该文件夹中初始化一个新的 TypeScript 项目。可以使用以下命令来初始化项目:

  1. mkdir color-game
  2. cd color-game
  3. npm init -y
  4. npm install typescript --save-dev
  5. npx tsc --init

接下来,在项目根目录下创建一个名为 index.ts 的 TypeScript 文件,作为游戏的主入口文件。同时,创建一个名为 styles.css 的 CSS 文件来设置游戏的样式。

编写游戏逻辑

index.ts 文件中,我们首先引入必要的库和模块:

  1. import * as canvas from 'canvas';
  2. import { randomColor } from './utils'; // 假设我们有一个生成随机颜色的工具函数

然后,我们定义游戏的主要逻辑:

```typescript
const canvasWidth = 800;
const canvasHeight = 600;
const targetColor = randomColor(); // 生成随机目标颜色
let score = 0; // 初始化分数
let gameOver = false; // 游戏是否结束

const canvas = canvas.createCanvas(canvasWidth, canvasHeight);
const ctx = canvas.getContext(‘2d’);

// 绘制游戏界面
function drawGame() {
// 清除画布
ctx.clearRect(0, 0, canvasWidth, canvasHeight);

// 绘制目标颜色方块
ctx.fillStyle = targetColor;
ctx.fillRect(canvasWidth / 4, canvasHeight / 4, canvasWidth / 2, canvasHeight / 2);

// 绘制随机颜色方块
for (let i = 0; i < 20; i++) {
const x = Math.random() (canvasWidth - 50) + 25;
const y = Math.random()
(canvasHeight - 50) + 25;
const color = randomColor();
ctx.fillStyle = color;
ctx.fillRect(x, y, 50, 50);
}

// 绘制分数
ctx.fillStyle = ‘black’;
ctx.font = ‘20px Arial’;
ctx.fillText(Score: ${score}, 10, 30);

// 检查游戏是否结束
if (gameOver) {
ctx.fillStyle = ‘red’;
ctx.font = ‘30px Arial’;
ctx.fillText(‘Game Over!’, canvasWidth / 4, canvasHeight / 2);
}
}

// 处理鼠标点击事件
function handleClick(event: MouseEvent) {
if (gameOver) return; // 如果游戏已经结束,不再处理点击事件

const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;

// 检查点击位置是否在方块上
for (let i = 0; i < 20; i++) {
if (
x >= canvasWidth / 4 + i 60 &&
x <= canvasWidth / 4 + (i + 1)
60 &&
y >= 25 &&
y <= 75
) {
const color = ctx.getImageData(x