You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rune游戏开发求助:TypeScript变量未识别及组件交互问题

Rune游戏开发TypeScript变量识别问题排查

我在给Rune游戏开发添加接口时,受TypeScript规则限制出现变量无法识别的问题,现在游戏逻辑、App组件和主组件没法正常配合运行,找不到问题根源。相关代码如下:

定义的接口与类型

export interface GameState {
  scores: Record<string, number>;
  punches: number;
  jumps: number;
  fighting: boolean;
  dodging: boolean;
}
type GameActions = {
  incrementScore: (params: { playerWhoGotPoints: string }) => void;
  incrementPunches: (params: { playerId: string }) => void;
  incrementJumps: (params: { playerId: string }) => void;
  startFight: () => void;
  startDodge: () => void;
  endFightOrDodge: () => void;
};

游戏逻辑初始化代码

Rune.initLogic({
  minPlayers: 1,
  maxPlayers: 4,
  setup: (allPlayerIds: string[]) => {
    const scores: Record<string, number> = {};
    for (let playerId of allPlayerIds) {
      scores[playerId] = 0;
    }
    const game: GameState = {
      scores,
      punches: 0,
      jumps: 0,
      fighting: false,
      dodging: false,
    };
    return game;
  },
  actions: {
    incrementScore(playerWhoGotPoints: string, { game }) {
      game.scores[playerWhoGotPoints]++;
    },
    incrementPunches({ playerId: string }, { game }) {
      game.punches++;
      game.scores[playerId]++;
    },
    incrementJumps({ playerId: string }, { game }) {
      game.jumps++;
      game.scores[playerId]++;
    },
    startFight({}, { game }) {
      game.fighting = true;
    },
    startDodge({}, { game }) {
      game.dodging = true;
    },
    endFightOrDodge({}, { game }) {
      game.fighting = false;
      game.dodging = false;
    },
  },
  events: {
    playerJoined: (playerId: string, { game }) => {
      game.scores[playerId] = 0;
    },
  },
})

问题定位与修复

核心问题出在incrementPunches和incrementJumps的参数解构写法上:

  • 错误写法里{ playerId: string }是把传入的playerId重命名为string变量,而非声明类型,导致TypeScript无法识别playerId,还会引发语法冲突。

正确的写法应该是先解构变量,再单独声明类型:

// 修复incrementPunches
incrementPunches({ playerId }: { playerId: string }, { game }) {
  game.punches++;
  game.scores[playerId]++;
}

// 修复incrementJumps
incrementJumps({ playerId }: { playerId: string }, { game }) {
  game.jumps++;
  game.scores[playerId]++;
}

另外,为了和GameActions类型定义保持一致,建议把incrementScore也改成解构参数的写法:

incrementScore({ playerWhoGotPoints }: { playerWhoGotPoints: string }, { game }) {
  game.scores[playerWhoGotPoints]++;
}

修改后TypeScript就能正确识别变量,游戏逻辑与组件的配合问题即可解决。

内容的提问来源于stack exchange,提问作者LearningLittleByLittle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:00:06