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

武器购买函数else块失效及代码冗余问题求助

问题修复与代码优化方案

问题根源

  1. else块失效:当前buyW()函数进入购买界面时就立刻检查所有武器的金币条件,只要有一个不满足就直接return false,导致后续武器的逻辑完全无法执行,还会提前弹出"金币不足"的提示,不符合用户点击对应武器才判断的交互逻辑。同时,若金币不足时未定义对应的武器函数(比如shield),后续绑定事件会抛出未定义错误。
  2. 代码重复:每个武器的购买逻辑(扣金币、更新UI、添加背包、刷新武器列表)完全重复,新增或修改武器时需要重复修改多段代码,维护成本极高。

修复与优化方案

1. 抽象通用购买逻辑

把重复的购买操作抽成独立函数,统一处理扣钱、背包更新、界面刷新等流程:

// 刷新当前武器列表的通用函数
function refreshCurrentWeaponList() {
    currentWeapon = "";
    inv.forEach((item, index) => {
        currentWeapon += `${index + 1}. ${item.name}<br>`;
    });
}

// 通用武器购买函数
function purchaseWeapon(weaponIndex) {
    const weapon = weapons[weaponIndex];
    // 点击武器时才检查金币是否足够
    if (coins < weapon.price) {
        alert("Not enough coins!");
        return;
    }
    // 执行购买流程
    alert(`${weapon.name} bought!`);
    coins -= weapon.price;
    coinsNum.innerHTML = coins;
    inv.push(weapon);
    refreshCurrentWeaponList();
    textbox.innerHTML = `Spiderman currently has :<br> ${currentWeapon} Which weapon should he buy?`;
}

2. 重构buyW函数

移除提前判断金币的逻辑,改为点击对应武器按钮时再执行检查,同时利用数组索引绑定事件,彻底消除重复代码:

function buyW(){
    update(scenes[2]);
    textbox2.style.display = "block";
    textbox2.innerHTML = scenes[2].text2;

    // 绑定武器购买事件,通过索引对应武器数组
    button1.onclick = () => purchaseWeapon(0);
    button2.onclick = () => purchaseWeapon(1);
    button3.onclick = () => purchaseWeapon(2);
    button4.onclick = exitBuy;
}

3. 完善场景配置与辅助函数

修复场景中按钮函数的绑定问题(避免函数立即执行),同时实现退出购买界面的逻辑:

// 更新scenes中的购买场景配置
const scenes = [
    // ... 其他场景保持不变
    // 购买武器场景
    {
        scene: "buy",
        text: `Spiderman currently has :<br> ${currentWeapon} Which weapon should he buy?`,
        btnT: ["Shield - 50 coins","Gun - 100 coins","Trident - 200 coins","Exit Buy"],
        btnF: [() => purchaseWeapon(0), () => purchaseWeapon(1), () => purchaseWeapon(2), exitBuy],
        text2 : weaponsList 
    }
];

// 实现退出购买界面的函数
function exitBuy(){
    update(scenes[1]); // 返回商店界面
    textbox2.style.display = "none";
}

优化后优势

  • 交互逻辑合理:用户点击对应武器时才检查金币,避免提前弹出错误提示,符合正常操作预期。
  • 代码复用性高:新增武器只需在weapons数组添加配置,无需修改购买逻辑。
  • 可维护性强:拆分后的函数职责单一,便于调试和后续扩展功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:43:09