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

如何使用for循环重写Phaser游戏中得分触发炸弹生成的重复代码

方案1:单次触发生成1个炸弹(匹配原代码逻辑)

你原代码是得分刚好达到2/4/6等2的正整数倍时生成1个炸弹,不需要写重复的if判断,直接用取模运算即可实现,后续得分涨到8、10也不需要新增分支:

if (this.score > 0 && this.score % 2 === 0) {
  this.bomb.create(Phaser.Math.RND.between(0, 3200), Phaser.Math.RND.between(0, 2200), 'bomba2');
}

如果这段逻辑是在帧更新函数中执行,需要额外加变量记录上次生成炸弹的得分,避免同个分数重复生成:

// 实例上存储上次生成炸弹的分数,初始值为0
this.lastBombScore = this.lastBombScore || 0;
if (this.score > this.lastBombScore && this.score % 2 === 0) {
  this.bomb.create(Phaser.Math.RND.between(0, 3200), Phaser.Math.RND.between(0, 2200), 'bomba2');
  this.lastBombScore = this.score;
}

方案2:按得分生成对应数量炸弹(匹配「每增加2分额外多1个炸弹」需求)

如果需要得2分时生成1个炸弹、得4分时累计生成2个炸弹、得6分时累计生成3个炸弹,直接用for循环实现即可:

// 计算当前得分对应的炸弹总数量
const bombTotal = Math.floor(this.score / 2);
for (let i = 0; i < bombTotal; i++) {
  this.bomb.create(Phaser.Math.RND.between(0, 3200), Phaser.Math.RND.between(0, 2200), 'bomba2');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:36:06