c# - 我怎样才能使这个极小极大算法完美地工作

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

我一直在尝试在 tic-tac-toe 游戏 unity3d 中实现 minimax(negamax) C# 算法,它在几乎最终状态下运行良好(每个玩家在开始时预先放置在棋盘上大约 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;
}

最佳答案

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

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

所以基本上所有关于棋盘上发生的 Action 的信息都丢失了。您应该使用实际棋盘的副本调用 GetBestMove 函数。

另一件事是一旦你设置好了

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

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

关于c# - 我怎样才能使这个极小极大算法完美地工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885394/

相关文章:

unity3d - 欧拉角约定变换

c# - Publishesettings 告诉该位置是保留的系统名称或磁盘不可写?

algorithm - Bellman-Ford 算法空间复杂度

c# - 使用 JAVA 访问动态 AX 方法

algorithm - 为 sha256 创建 2 路映射。

algorithm - 外层循环执行 log(n) 次的双 while 循环算法的渐近增长率

c# - 我使用 Firebase 的统一登录不起作用

c# - 使用 Animator.StringtoHash (""有什么好处)?

c# - 将 Kinect 的彩色摄像头视频流保存为 .avi 视频

c# - 如何通过代码在运行时添加迁移