Cocos 预备篇

从零基础开始,用一个计分回合练习代码、异步和调试,再把这些规则带进 Cocos 项目。

1. 值、引用与 TypeScript 类型

学完这一篇,你能独立写一个计分回合,预测状态怎样变化,并用断点找出重复计分的原因。

数字赋值会复制值。对象赋值会让两个变量指向同一个对象。TypeScript 可用 type 描述对象形状,用联合类型限制有效状态。

type Round = { score: number };
const first: Round = { score: 0 };
const alias = first;
alias.score += 1;
console.log(first.score);

在控制台里,可去掉类型声明和 : Round 后运行。再试 const alias = { ...first },比较输出。对象展开只复制最外层。

2. 数组、Map 与事件

数组适合保存有顺序的记录,例如一局按什么顺序接到了物品。要通过物品 ID 查它的分值,可用 Map。

const points = new Map([['star', 1], ['bonus', 3]]);
const caught = ['star', 'bonus', 'star'];
let score = 0;
for (const item of caught) {
    score += points.get(item) ?? 0;
}

事件把「发生了什么」交给已经注册的回调。以游戏里的点击为例,一个按钮发出事件,回调更新分数,再把新值显示到 HUD。把注册和注销配对,重开时就能检查是否多挂了一份监听。

  1. 按钮发出事件
  2. 回调更新状态
  3. HUD 显示新值

3. 模块、Promise 与异步顺序

用 export 暴露一段逻辑,再用 import 复用。把计分放在独立模块后,可以单独执行和验证计分规则。

async function startRound() {
    console.log('准备');
    const score = await Promise.resolve(0);
    console.log('开始', score);
}
void startRound();
console.log('已请求开始');

await 让当前异步函数等结果,同时外层代码可以继续执行。以后加载资源时,同样要在成功后才开始回合,并处理加载失败。

4. Git、断点与调用栈

用 git status 看改动范围,用 git diff 看具体变化。调试时先复现一次异常,再在你能确定发生了错误的位置打断点。

  1. 把下面代码粘进浏览器开发者工具控制台运行。保持开发者工具打开。
  2. 暂停时看 score,然后看调用栈的上一层是谁。
  3. 继续执行,比较第二次暂停的调用栈。删掉重复的调用,重新验证只加一次。
(() => {
    let score = 0;
    function addPoint() {
        debugger;
        score += 1;
    }
    function onCatch() {
        addPoint();
        addPoint();
    }
    onCatch();
    console.log(score);
})();

5. 用状态机写出计分回合

先定义合法状态,再决定每个状态接受哪些操作。比如「暂停」只接受恢复,「游玩中」可以接到物品并计分。把这些规则集中在一个函数里,就能逐个验证。

  1. 待开始
  2. 游玩中
  3. 已结束

先预测「开始 → 接到 → 暂停 → 接到 → 恢复 → 结束 → 开始」的分数,再操作下方示例检查。

完整 TypeScript 练习

保存为 round.ts。在本机 Node.js 24 环境运行 node round.ts,逐行对照输出。

type Phase = 'ready' | 'playing' | 'paused' | 'finished';
type Round = { phase: Phase; score: number };
type Action = 'start' | 'catch' | 'pause' | 'resume' | 'finish';

function reduce(round: Round, action: Action): Round {
    if (action === 'start' && (round.phase === 'ready' || round.phase === 'finished')) {
        return { phase: 'playing', score: 0 };
    }
    if (round.phase === 'playing') {
        if (action === 'catch') return { ...round, score: round.score + 1 };
        if (action === 'pause') return { ...round, phase: 'paused' };
        if (action === 'finish') return { ...round, phase: 'finished' };
    }
    if (round.phase === 'paused' && action === 'resume') {
        return { ...round, phase: 'playing' };
    }
    return round;
}

let round: Round = { phase: 'ready', score: 0 };
const actions: Action[] = ['start', 'catch', 'pause', 'catch', 'resume', 'finish', 'start'];
for (const action of actions) {
    round = reduce(round, action);
    console.log(action, round.phase, round.score);
}

6. 独立应用

现在换成限时答题。计时结束时,可能还有一次点击已经进入事件队列。按钮处理函数和回合状态需要怎样配合,才能避免结算后加分?

7. 隔天回想

在不翻前面代码的情况下,写出「开始 → 暂停 → 接到 → 恢复 → 接到 → 结束 → 重开」每次计分和重开后的结果。

刷新会清空本页作答。可以收藏本节地址,隔天再做。

进入 Cocos 开发篇