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

Angular Scrabble项目网格Tile随机奖励功能始终激活故障排查

问题根因

1. 开关变量未正常初始化

你在GridTile类中定义的开关变量test处于注释状态,没有实际声明也没有赋初始值。未初始化的变量值为undefined,执行undefined <= 0判断时结果恒为false,所以永远会走随机奖励的分支,导致功能始终激活。

2. 按钮点击逻辑未生效

ParamGameComponent中的activeRandomBonus方法被注释,点击按钮不会执行任何逻辑,开关状态根本不会被修改。

3. 开关状态不统一

你现在的开关变量是每个GridTile实例单独持有,即使修改单个实例的状态也无法全局生效;且你在GridTile类中直接new ParamGameService()创建的服务实例,和组件中注入的服务实例不是同一个,状态无法共享。

4. 开关逻辑错误

randomButton方法中写的this.test = +1只能把变量设为1,没有切换开关的能力,触发后就无法再关闭随机效果。


修复方案

步骤1:全局共享开关状态

在你的ParamGameService中添加全局开关,统一管理随机奖励的激活状态:

// param-game.service.ts
@Injectable({ providedIn: 'root' })
export class ParamGameService {
  // 新增全局开关,默认关闭随机奖励
  isRandomBonusActive = false;
  // 原有逻辑保持不变
}

步骤2:调整GridTile类的逻辑

取消原来的test变量,直接使用全局服务的开关状态,同时修改构造函数接收外部注入的服务实例,保证状态统一:

// grid-tile.ts
export class GridTile {
  arrayOps: ArrayOperations = new ArrayOperations();
  // 删掉自行new服务的逻辑,改由外部传入
  constructor(
    context: CanvasRenderingContext2D, 
    x: number, 
    y: number,
    // 新增参数:接收共享的服务实例
    public paramGameService: ParamGameService
  ) {
    // 原有构造逻辑保持不变
  }

  // 删掉原来的test变量声明和randomButton方法

  // 修改drawTile中的判断逻辑,用全局开关判断
  drawTile() {
    // 原有绘制逻辑不变,只修改switch中的判断条件
    switch (this.multiplier) {
      case defaults.Multipliers.ThreeW: {
        // 开关关闭时显示固定奖励
        if (!this.paramGameService.isRandomBonusActive) this.idOfTile('Mot', 'Triple');
        // 开关开启时显示随机奖励
        else this.idOfTile('Mot', this.randBonusName());
        break;
      }
      case defaults.Multipliers.TwoW: {
        if (!this.paramGameService.isRandomBonusActive) this.idOfTile('Mot', 'Double');
        else this.idOfTile('Mot', this.randBonusName());
        break;
      }
      case defaults.Multipliers.ThreeL: {
        if (!this.paramGameService.isRandomBonusActive) this.idOfTile('Lettre', 'Triple');
        else this.idOfTile('Lettre', this.randBonusName());
        break;
      }
      case defaults.Multipliers.TwoL: {
        if (!this.paramGameService.isRandomBonusActive) this.idOfTile('Lettre', 'Double');
        else this.idOfTile('Lettre', this.randBonusName());
        break;
      }
      // 其余case保持不变
    }
  }
  // 其余方法保持不变
}

注意:你在创建GridTile实例的位置,需要把组件中注入的ParamGameService实例传入构造函数。

步骤3:修复按钮点击逻辑

取消组件中点击方法的注释,修改为切换全局开关,同时触发画布重绘更新界面:

// param-game.component.ts
export class ParamGameComponent {
  // 原有变量保持不变

  // 取消注释,修改点击逻辑
  activeRandomBonus(): void {
    // 切换开关状态
    this.paramGameService.isRandomBonusActive = !this.paramGameService.isRandomBonusActive;
    // 此处添加你原有触发画布重绘的逻辑,重新绘制所有格子即可看到效果
  }
}

内容的提问来源于stack exchange,提问作者Mohamed Sameh Sellami

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:45:03