javaScript中的minimax算法无法按预期工作,并返回错误的动作

问题描述

我正在尝试使用minimax算法在javaScript中制作井字游戏,但似乎我做错了什么,并且minimax算法没有检测到最佳动作。这是代码:

const board = ["X",null,"X","O","O"];
/*
    X   _   _
    _   _   X
    X   O   O

*/

// duplicate passed board and return the new board state
const makeAIMove = (currentBoard,square,player) => {
    const nextBoard = [...currentBoard];
    nextBoard[square] = player;
    return nextBoard;
};

// find empty squares
const emptySquares = (sqBoard) =>
    sqBoard
        .map((sq,idx) => (sq === null ? idx : null))
        .filter((sq) => sq !== null);

// check if no empty squares are available
const isFinished = (sqBoard) => (emptySquares(sqBoard).length ? false : true);

// check winner
const checkWinner = (sqBoard) => {
    const winConditions = [
        [0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,7],[2,5,];

    for (const winCondition of winConditions) {
        [a,b,c] = winCondition;
        if (sqBoard[a] && sqBoard[a] === sqBoard[b] && sqBoard[a] === sqBoard[c])
            return sqBoard[a];
    }

    return false;
};

// minimax algorithm
const minimax = (sqBoard,depth,isMaximizer) => {
    // terminal checker
    const theWinner = checkWinner(sqBoard);
    // we have a winner
    if (theWinner) {
        return theWinner === "X" ? -10 : 10;
    }
    // it's a tie
    if (isFinished(sqBoard)) {
        return 0;
    }

    let bestScore;
    if (isMaximizer) {
        bestScore = -1000;
        emptySquares(sqBoard).forEach((square) => {
            // make a sample move
            let nextBoard = makeAIMove(sqBoard,"O");

            // recursion
            let score = minimax(nextBoard,depth + 1,false);
            bestScore = Math.max(bestScore,score);
        });
    } else {
        bestScore = 1000;
        emptySquares(sqBoard).forEach((square) => {
            let nextBoard = makeAIMove(sqBoard,"X");
            let score = minimax(nextBoard,true);
            bestScore = Math.min(bestScore,score);
        });
    }
    return bestScore;
};

// find the best move
const nextBestMove = (sqBoard) => {
    let nextMoveArray = [];
    let remainedSquares = emptySquares(sqBoard);
    remainedSquares.forEach((square) => {
        let nextBoard = makeAIMove(sqBoard,"O");
        let theScore = minimax(nextBoard,true);
        nextMoveArray.push({
            sq: square,sc: theScore,});
    });

    nextMoveSorted = nextMoveArray.sort((a,b) => (a.sc < b.sc ? 1 : -1));
    return nextMoveSorted[0].sq;
};

console.log(nextBestMove(board));

在上述情况下,最好的举动是通过在板[3]上加一个“ O”来阻止X获胜,但它总是会检测到另一个得分更高的举动。

谁能帮助我了解我的代码出了什么问题?

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)