C#井字游戏Minimax

时间:2020-04-15 09:04:45

标签: c# tic-tac-toe minimax

我正在尝试用MiniMax Ai创建一个tictactoe游戏,我迷恋上minimax函数,它总是返回0,但我不知道为什么。

    namespace TicTacToeMiniMax
{
    class AiBrain
    {
        int Score;
        int BestMoveStorage;
        Board BoardCopy;

    public void BestMove(Board board)
    {
        BoardCopy = board;

        for(int x = BoardCopy.BoardList.Count(); x > 0; x--)
        {
            if (BoardCopy.ReturnBoardValue(x) == "Z")
            {
                BoardCopy.MakeMove(x, "X", true);
                int TempScore = Minimax(0, false);
                BoardCopy.MakeMove(x, "Z", true);
                if (TempScore > Score)
                {
                    Score = TempScore;
                    BestMoveStorage = x;
                }
            }
        }
    }
    private int Minimax(int depth, bool IsMax)
    {
        string Result = BoardCopy.CheckWinAi();
        if(Result != "Z")
        {
            switch (Result)
            {
                case "X":
                    return 1;
                case "O":
                    return -1;
                case "Gelijk":
                    return 0;
            }
        }
        if (IsMax)
        {
            int BestScore = -0;
            for (int x = BoardCopy.BoardList.Count(); x > 0; x--)
            {
                if (BoardCopy.ReturnBoardValue(x) == "Z")
                {
                    BoardCopy.MakeMove(x, "X", true);
                    int Score = Minimax(depth + 1, false);
                    BoardCopy.MakeMove(x, "Z", true);
                    if (Score > BestScore)
                    {
                        BestScore = Score;
                    }
                }
            }
            return BestScore;
        }
        else
        {
            int BestScore = 0;
            for (int x = BoardCopy.BoardList.Count(); x > 0; x--)
            {
                if (BoardCopy.ReturnBoardValue(x) == "Z")
                {
                    BoardCopy.MakeMove(x, "O", true);
                    int Score = Minimax(depth + 1, true);
                    BoardCopy.MakeMove(x, "Z", true);
                    if (Score < BestScore)
                    {
                        BestScore = Score;
                    }
                }
            }
            return BestScore;
        }
    }

    public int MakeMove()
    {
        return BestMoveStorage;
    }
}
}

上面是我的AI类,但它仅返回0。Board类仅包含一个包含9个字符串的列表(“ X”,“ O”和“ Z”表示空白)。它还具有用于检查现货是否为空的类,并且具有检查获胜功能。

谢谢。

0 个答案:

没有答案