simplest MiniMax algorithm for TicTacToe AI in Java

jdoe picture jdoe · Jul 18, 2017 · Viewed 7.2k times · Source

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?

Answer

maraca picture maraca · Jul 18, 2017

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