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

棋盘游戏movePiece/buySquare逻辑错误:玩家1误购玩家2地块

问题排查与修复方案

核心问题梳理

  1. checkIfOwned逻辑片面:该函数只检查地块是否被玩家1拥有,完全忽略当前玩家为玩家2的场景,且无论谁操作,都固定用pieceOne的位置判断地块,玩家2的地块归属判断完全缺失。
  2. buySquare调用未传参:调用buySquare()时没传入当前玩家参数,导致函数内currentPlayer参数无值,默认走else分支(玩家2逻辑),这就是玩家1收到错误购买提示的直接原因。
  3. 地块归属判断未关联当前玩家:没有根据当前玩家身份,对应检查其专属的已拥有地块列表。

修复代码

修正checkIfOwned函数

function checkIfOwned() {
    // 根据当前玩家获取对应棋子的地块类型
    const currentSquareType = currentPlayer === players[0] 
        ? pieceOne.parentElement.getAttribute('data-type') 
        : pieceTwo.parentElement.getAttribute('data-type');
    
    // 分玩家判断地块是否已被拥有
    if (currentPlayer === players[0] && player1Owned.includes(currentSquareType)) {
        squareOwned = true;
    } else if (currentPlayer === players[1] && player2Owned.includes(currentSquareType)) {
        squareOwned = true;
    } else {
        // 传入当前玩家参数给buySquare
        buySquare(currentPlayer);
    }
}

给buySquare增加参数容错(可选)

避免参数缺失引发异常,增加基础校验:

async function buySquare(currentPlayer) {
    if (!currentPlayer) {
        console.error("buySquare缺少当前玩家参数");
        return;
    }
    await sleep(4000);
    if (currentPlayer === players[0]) {
        const squareType = pieceOne.parentElement.getAttribute('data-type');
        message.innerHTML = `<p>Would you like to buy ${squareType} for 5 people?`;
        let input = await getUserInput();
        if (input === 'y') {
            player1Owned.push(squareType);
        } else {
            console.log('you have not bought this square');
        }
    } else {
        const squareType = pieceTwo.parentElement.getAttribute('data-type');
        message.innerHTML = `<p>Would you like to buy ${squareType} for 5 people?`;
        let input = await getUserInput();
        if (input === 'y') {
            player2Owned.push(squareType);
        } else {
            console.log('you have not bought this square');
        }
    }
}

额外优化建议

  • 抽象当前玩家对应的棋子和已拥有列表,减少重复代码:
    const currentPiece = currentPlayer === players[0] ? pieceOne : pieceTwo;
    const currentOwnedList = currentPlayer === players[0] ? player1Owned : player2Owned;
    
    后续逻辑修改只需维护一处,降低出错概率。
  • movePiece函数中currentPlayer = players[0];这类重复赋值可以删除,因为进入分支时已经通过条件判断确认了当前玩家身份。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 19:23:11