simplest MiniMax algorithm for TicTacToe AI in Java

时光毁灭记忆、已成空白 提交于 2019-12-24 04:51:50

问题


I was trying to get a grasp of MiniMax algorithm, and have read up on it. My initial approach was to implement a simple MiniMax algorithm, and then to add alpha-beta pruning. However this is my current code:

public int miniMax(char[] node, int playerNum)
{
    int victor = checkWin(node); // returns 0 if game is ongoing, 1 for p1, 2 for p2, 3 for tie.
    if(victor != 0) //game over .
        return score(victor);   

    if(playerNum == 2) //AI
    {
        int bestVal = Integer.MIN_VALUE;
        int bestSpot = 0;
        for(int i = 0; i < node.length; i++)
        {
            if(node[i] != '-')
                continue;
            node[i] = getSymbol(playerNum);
            int value = miniMax(node, 1); 
            if(value > bestVal)
            {
                bestVal = value;
                bestSpot = i;
            }

            node[i] = '-';
        }
        return bestSpot;
    }
    else
    {
        int bestVal = Integer.MAX_VALUE;
        int bestSpot = 0;
        for(int i = 0; i < node.length; i++)
        {
            if(node[i] != '-')
                continue;
            node[i] = getSymbol(playerNum);
            int value = miniMax(node, 2); 
            if(value < bestVal)
            {
                bestVal = value;
                bestSpot = i;
            }
            node[i] = '-';
        }
        return bestSpot;
    }
}

And my score function

private int Score(int gameState)
{
    if(gameState ==2) //O wins.
        return 10;
    else if(gameState==1) //X wins
        return -10;
    return 0;
}

Now, I have a working AI that tries to block my move and win, however sometimes it is making non-intelligent choices for instance this is the output I get if my input read from console is 6,7,8 in that order. It does not attempt to block my win. But in other cases it does.


| O | O | |


| | | |


| X | X | X |


In my second attempt I tried 4,3 and it blocked my winning move.


| | O | |


| X | X | O |


| | | |


I was wondering anyone could point out what is wrong with my implementation?


回答1:


The behavior of the code for the shown examples is correct!

So why is the threat in the following position not blocked? Why does the program play move 1 instead of 6?

O . .                                    O 1 2
. . .     numbering available moves:     3 4 5
X X .                                    X X 6

It is because if the game is lost on perfect play the program just plays the first available move.

The algorithm only cares about win or loss and not in how many moves.

See what happens if the threat is blocked:

O . .     O . .
. . .     . X .     and X wins on his next move
X X O     X X O


来源:https://stackoverflow.com/questions/45168697/simplest-minimax-algorithm-for-tictactoe-ai-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!