如何使这个minimax算法完美运行

时间:2018-06-16 05:59:49

标签: c# algorithm unity3d tic-tac-toe minimax

我一直在尝试在井下游戏中实现minimax(negamax)C#算法,unity3d,它在几乎终端状态下工作得非常好(每个玩家预先放置在板上约2件)在开始的时候,我不能让它在开始时从空板上做出完美的决定。

//recursive function call
internal AIMove GetBestMove(char[] board, char player)
{
    // testboard = board;
    AIMove bestMove = null;

    for (int i = 0; i < moveTile.emptyPoints.Count; i++)
    {
        AIMove move = new AIMove();
        move.point = System.Convert.ToInt32(moveTile.emptyPoints[i].name);

        board[System.Convert.ToInt32(moveTile.emptyPoints[i].name)] = player == GameManager.Player2Piece ? GameManager.Player2Piece : GameManager.Player1Piece; // If player is O use O else use X

        var rv = CheckVictorySim(board, player, System.Convert.ToInt32(moveTile.emptyPoints[i].name));
        // print(rv);

        if (rv == 10) //AI wins
        {
            move.score = 1;
        }
        else if (rv == -10) // AI loses
        {
            move.score = -1;
        }
        else if (rv == 0) // draw
        {
            move.score = 0;
        }

        else if (rv == -1) //other
        {
            char[] newboard = new char[9]; //System.Array.Copy(umpire.board, newboard, 9); //board state
            move.score = -GetBestMove(newboard, player == GameManager.Player2Piece ? GameManager.Player1Piece : GameManager.Player2Piece).score; // if player is O use X else use O
        }

        if (bestMove == null || move.score > bestMove.score)
        {
            bestMove = move;
        }
        //aiMoves.Add(bestMove);
        print(bestMove.point);
    }


    //return the best move
    return bestMove;
}

1 个答案:

答案 0 :(得分:1)

我认为一个问题是您正在将一个空的(刚刚创建的)木板传递给GetBestMove的递归调用:

char[] newboard = new char[9];
move.score = -GetBestMove(newboard, /*other args*/)

因此,基本上所有有关先前在板上发生的举动的信息都将丢失。您应该使用实际电路板的副本调用GetBestMove函数。

另一件事是,一旦设置好

move.point = System.Convert.ToInt32(moveTile.emptyPoints[i].name);

您可以使用move.point代替System.Convert.ToInt32(moveTile.emptyPoints[i].name)  在适当的地方避免重复并提高代码的可读性。