The Wayback Machine - https://web.archive.org/web/20240902035608/https://www.geeksforgeeks.org/finding-optimal-move-in-tic-tac-toe-using-minimax-algorithm-in-game-theory/
Open In App

Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Topics:
Solve Problem
Hard
31.88%
999

Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game Theory
Let us combine what we have learnt so far about minimax and evaluation function to write a proper Tic-Tac-Toe AI (Artificial Intelligence) that plays a perfect game. This AI will consider all possible scenarios and makes the most optimal move.

Finding the Best Move :

We shall be introducing a new function called findBestMove(). This function evaluates all the available moves using minimax() and then returns the best move the maximizer can make. The pseudocode is as follows : 

function findBestMove(board):
    bestMove = NULL
    for each move in board :
        if current move is better than bestMove
            bestMove = current move
    return bestMove

Minimax :

To check whether or not the current move is better than the best move we take the help of minimax() function which will consider all the possible ways the game can go and returns the best value for that move, assuming the opponent also plays optimally 

The code for the maximizer and minimizer in the minimax() function is similar to findBestMove(), the only difference is, instead of returning a move, it will return a value. Here is the pseudocode :  

function minimax(board, depth, isMaximizingPlayer):

    if current board state is a terminal state :
        return value of the board
    
    if isMaximizingPlayer :
        bestVal = -INFINITY 
        for each move in board :
            value = minimax(board, depth+1, false)
            bestVal = max( bestVal, value) 
        return bestVal

    else :
        bestVal = +INFINITY 
        for each move in board :
            value = minimax(board, depth+1, true)
            bestVal = min( bestVal, value) 
        return bestVal 

Checking for GameOver state :

To check whether the game is over and to make sure there are no moves left we use isMovesLeft() function. It is a simple straightforward function which checks whether a move is available or not and returns true or false respectively. Pseudocode is as follows :

function isMovesLeft(board):
    for each cell in board:
        if current cell is empty:
            return true
    return false

Making our AI smarter :

One final step is to make our AI a little bit smarter. Even though the following AI plays perfectly, it might choose to make a move which will result in a slower victory or a faster loss. Lets take an example and explain it.
Assume that there are 2 possible ways for X to win the game from a given board state.

  • Move A : X can win in 2 move
  • Move B : X can win in 4 moves

Our evaluation function will return a value of +10 for both moves A and B. Even though the move A is better because it ensures a faster victory, our AI may choose B sometimes. To overcome this problem we subtract the depth value from the evaluated score. This means that in case of a victory it will choose a the victory which takes least number of moves and in case of a loss it will try to prolong the game and play as many moves as possible. So the new evaluated value will be

  • Move A will have a value of +10 – 2 = 8
  • Move B will have a value of +10 – 4 = 6

Now since move A has a higher score compared to move B our AI will choose move A over move B. The same thing must be applied to the minimizer. Instead of subtracting the depth we add the depth value as the minimizer always tries to get, as negative a value as possible. We can subtract the depth either inside the evaluation function or outside it. Anywhere is fine. I have chosen to do it outside the function. Pseudocode implementation is as follows. 

if maximizer has won:
    return WIN_SCORE – depth

else if minimizer has won:
    return LOOSE_SCORE + depth

Below is implementation of above idea.  

C++




// C++ program to find the next optimal move for
// a player
#include<bits/stdc++.h>
using namespace std;
  
struct Move
{
    int row, col;
};
  
char player = 'x', opponent = 'o';
  
// This function returns true if there are moves
// remaining on the board. It returns false if
// there are no moves left to play.
bool isMovesLeft(char board[3][3])
{
    for (int i = 0; i<3; i++)
        for (int j = 0; j<3; j++)
            if (board[i][j]=='_')
                return true;
    return false;
}
  
// This is the evaluation function as discussed
// in the previous article ( http://goo.gl/sJgv68 )
int evaluate(char b[3][3])
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row<3; row++)
    {
        if (b[row][0]==b[row][1] &&
            b[row][1]==b[row][2])
        {
            if (b[row][0]==player)
                return +10;
            else if (b[row][0]==opponent)
                return -10;
        }
    }
  
    // Checking for Columns for X or O victory.
    for (int col = 0; col<3; col++)
    {
        if (b[0][col]==b[1][col] &&
            b[1][col]==b[2][col])
        {
            if (b[0][col]==player)
                return +10;
  
            else if (b[0][col]==opponent)
                return -10;
        }
    }
  
    // Checking for Diagonals for X or O victory.
    if (b[0][0]==b[1][1] && b[1][1]==b[2][2])
    {
        if (b[0][0]==player)
            return +10;
        else if (b[0][0]==opponent)
            return -10;
    }
  
    if (b[0][2]==b[1][1] && b[1][1]==b[2][0])
    {
        if (b[0][2]==player)
            return +10;
        else if (b[0][2]==opponent)
            return -10;
    }
  
    // Else if none of them have won then return 0
    return 0;
}
  
// This is the minimax function. It considers all
// the possible ways the game can go and returns
// the value of the board
int minimax(char board[3][3], int depth, bool isMax)
{
    int score = evaluate(board);
  
    // If Maximizer has won the game return his/her
    // evaluated score
    if (score == 10)
        return score;
  
    // If Minimizer has won the game return his/her
    // evaluated score
    if (score == -10)
        return score;
  
    // If there are no more moves and no winner then
    // it is a tie
    if (isMovesLeft(board)==false)
        return 0;
  
    // If this maximizer's move
    if (isMax)
    {
        int best = -1000;
  
        // Traverse all cells
        for (int i = 0; i<3; i++)
        {
            for (int j = 0; j<3; j++)
            {
                // Check if cell is empty
                if (board[i][j]=='_')
                {
                    // Make the move
                    board[i][j] = player;
  
                    // Call minimax recursively and choose
                    // the maximum value
                    best = max( best,
                        minimax(board, depth+1, !isMax) );
  
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
  
    // If this minimizer's move
    else
    {
        int best = 1000;
  
        // Traverse all cells
        for (int i = 0; i<3; i++)
        {
            for (int j = 0; j<3; j++)
            {
                // Check if cell is empty
                if (board[i][j]=='_')
                {
                    // Make the move
                    board[i][j] = opponent;
  
                    // Call minimax recursively and choose
                    // the minimum value
                    best = min(best,
                           minimax(board, depth+1, !isMax));
  
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
}
  
// This will return the best possible move for the player
Move findBestMove(char board[3][3])
{
    int bestVal = -1000;
    Move bestMove;
    bestMove.row = -1;
    bestMove.col = -1;
  
    // Traverse all cells, evaluate minimax function for
    // all empty cells. And return the cell with optimal
    // value.
    for (int i = 0; i<3; i++)
    {
        for (int j = 0; j<3; j++)
        {
            // Check if cell is empty
            if (board[i][j]=='_')
            {
                // Make the move
                board[i][j] = player;
  
                // compute evaluation function for this
                // move.
                int moveVal = minimax(board, 0, false);
  
                // Undo the move
                board[i][j] = '_';
  
                // If the value of the current move is
                // more than the best value, then update
                // best/
                if (moveVal > bestVal)
                {
                    bestMove.row = i;
                    bestMove.col = j;
                    bestVal = moveVal;
                }
            }
        }
    }
  
    printf("The value of the best Move is : %d\n\n",
            bestVal);
  
    return bestMove;
}
  
// Driver code
int main()
{
    char board[3][3] =
    {
        { 'x', 'o', 'x' },
        { 'o', 'o', 'x' },
        { '_', '_', '_' }
    };
  
    Move bestMove = findBestMove(board);
  
    printf("The Optimal Move is :\n");
    printf("ROW: %d COL: %d\n\n", bestMove.row,
                                  bestMove.col );
    return 0;
}


Java




// Java program to find the 
// next optimal move for a player
class GFG
{
static class Move
{
    int row, col;
};
  
static char player = 'x', opponent = 'o';
  
// This function returns true if there are moves
// remaining on the board. It returns false if
// there are no moves left to play.
static Boolean isMovesLeft(char board[][])
{
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            if (board[i][j] == '_')
                return true;
    return false;
}
  
// This is the evaluation function as discussed
// in the previous article ( http://goo.gl/sJgv68 )
static int evaluate(char b[][])
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row < 3; row++)
    {
        if (b[row][0] == b[row][1] &&
            b[row][1] == b[row][2])
        {
            if (b[row][0] == player)
                return +10;
            else if (b[row][0] == opponent)
                return -10;
        }
    }
  
    // Checking for Columns for X or O victory.
    for (int col = 0; col < 3; col++)
    {
        if (b[0][col] == b[1][col] &&
            b[1][col] == b[2][col])
        {
            if (b[0][col] == player)
                return +10;
  
            else if (b[0][col] == opponent)
                return -10;
        }
    }
  
    // Checking for Diagonals for X or O victory.
    if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
    {
        if (b[0][0] == player)
            return +10;
        else if (b[0][0] == opponent)
            return -10;
    }
  
    if (b[0][2] == b[1][1] && b[1][1] == b[2][0])
    {
        if (b[0][2] == player)
            return +10;
        else if (b[0][2] == opponent)
            return -10;
    }
  
    // Else if none of them have won then return 0
    return 0;
}
  
// This is the minimax function. It considers all
// the possible ways the game can go and returns
// the value of the board
static int minimax(char board[][], 
                    int depth, Boolean isMax)
{
    int score = evaluate(board);
  
    // If Maximizer has won the game 
    // return his/her evaluated score
    if (score == 10)
        return score;
  
    // If Minimizer has won the game 
    // return his/her evaluated score
    if (score == -10)
        return score;
  
    // If there are no more moves and 
    // no winner then it is a tie
    if (isMovesLeft(board) == false)
        return 0;
  
    // If this maximizer's move
    if (isMax)
    {
        int best = -1000;
  
        // Traverse all cells
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                // Check if cell is empty
                if (board[i][j]=='_')
                {
                    // Make the move
                    board[i][j] = player;
  
                    // Call minimax recursively and choose
                    // the maximum value
                    best = Math.max(best, minimax(board, 
                                    depth + 1, !isMax));
  
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
  
    // If this minimizer's move
    else
    {
        int best = 1000;
  
        // Traverse all cells
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                // Check if cell is empty
                if (board[i][j] == '_')
                {
                    // Make the move
                    board[i][j] = opponent;
  
                    // Call minimax recursively and choose
                    // the minimum value
                    best = Math.min(best, minimax(board, 
                                    depth + 1, !isMax));
  
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
}
  
// This will return the best possible
// move for the player
static Move findBestMove(char board[][])
{
    int bestVal = -1000;
    Move bestMove = new Move();
    bestMove.row = -1;
    bestMove.col = -1;
  
    // Traverse all cells, evaluate minimax function 
    // for all empty cells. And return the cell 
    // with optimal value.
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // Check if cell is empty
            if (board[i][j] == '_')
            {
                // Make the move
                board[i][j] = player;
  
                // compute evaluation function for this
                // move.
                int moveVal = minimax(board, 0, false);
  
                // Undo the move
                board[i][j] = '_';
  
                // If the value of the current move is
                // more than the best value, then update
                // best/
                if (moveVal > bestVal)
                {
                    bestMove.row = i;
                    bestMove.col = j;
                    bestVal = moveVal;
                }
            }
        }
    }
  
    System.out.printf("The value of the best Move " + 
                             "is : %d\n\n", bestVal);
  
    return bestMove;
}
  
// Driver code
public static void main(String[] args)
{
    char board[][] = {{ 'x', 'o', 'x' },
                      { 'o', 'o', 'x' },
                      { '_', '_', '_' }};
  
    Move bestMove = findBestMove(board);
  
    System.out.printf("The Optimal Move is :\n");
    System.out.printf("ROW: %d COL: %d\n\n", 
               bestMove.row, bestMove.col );
}
  
}
  
// This code is contributed by PrinciRaj1992


Python3




# Python3 program to find the next optimal move for a player 
player, opponent = 'x', 'o' 
  
# This function returns true if there are moves 
# remaining on the board. It returns false if 
# there are no moves left to play. 
def isMovesLeft(board) : 
  
    for i in range(3) :
        for j in range(3) :
            if (board[i][j] == '_') :
                return True 
    return False
  
# This is the evaluation function as discussed 
# in the previous article ( http://goo.gl/sJgv68 ) 
def evaluate(b) : 
    
    # Checking for Rows for X or O victory. 
    for row in range(3) :     
        if (b[row][0] == b[row][1] and b[row][1] == b[row][2]) :        
            if (b[row][0] == player) :
                return 10
            elif (b[row][0] == opponent) :
                return -10
  
    # Checking for Columns for X or O victory. 
    for col in range(3) :
       
        if (b[0][col] == b[1][col] and b[1][col] == b[2][col]) :
          
            if (b[0][col] == player) : 
                return 10
            elif (b[0][col] == opponent) :
                return -10
  
    # Checking for Diagonals for X or O victory. 
    if (b[0][0] == b[1][1] and b[1][1] == b[2][2]) :
      
        if (b[0][0] == player) :
            return 10
        elif (b[0][0] == opponent) :
            return -10
  
    if (b[0][2] == b[1][1] and b[1][1] == b[2][0]) :
      
        if (b[0][2] == player) :
            return 10
        elif (b[0][2] == opponent) :
            return -10
  
    # Else if none of them have won then return 0 
    return 0
  
# This is the minimax function. It considers all 
# the possible ways the game can go and returns 
# the value of the board 
def minimax(board, depth, isMax) : 
    score = evaluate(board)
  
    # If Maximizer has won the game return his/her 
    # evaluated score 
    if (score == 10) : 
        return score
  
    # If Minimizer has won the game return his/her 
    # evaluated score 
    if (score == -10) :
        return score
  
    # If there are no more moves and no winner then 
    # it is a tie 
    if (isMovesLeft(board) == False) :
        return 0
  
    # If this maximizer's move 
    if (isMax) :     
        best = -1000 
  
        # Traverse all cells 
        for i in range(3) :         
            for j in range(3) :
               
                # Check if cell is empty 
                if (board[i][j]=='_') :
                  
                    # Make the move 
                    board[i][j] = player 
  
                    # Call minimax recursively and choose 
                    # the maximum value 
                    best = max( best, minimax(board,
                                              depth + 1,
                                              not isMax) )
  
                    # Undo the move 
                    board[i][j] = '_'
        return best
  
    # If this minimizer's move 
    else :
        best = 1000 
  
        # Traverse all cells 
        for i in range(3) :         
            for j in range(3) :
               
                # Check if cell is empty 
                if (board[i][j] == '_') :
                  
                    # Make the move 
                    board[i][j] = opponent 
  
                    # Call minimax recursively and choose 
                    # the minimum value 
                    best = min(best, minimax(board, depth + 1, not isMax))
  
                    # Undo the move 
                    board[i][j] = '_'
        return best
  
# This will return the best possible move for the player 
def findBestMove(board) : 
    bestVal = -1000 
    bestMove = (-1, -1) 
  
    # Traverse all cells, evaluate minimax function for 
    # all empty cells. And return the cell with optimal 
    # value. 
    for i in range(3) :     
        for j in range(3) :
          
            # Check if cell is empty 
            if (board[i][j] == '_') : 
              
                # Make the move 
                board[i][j] = player
  
                # compute evaluation function for this 
                # move. 
                moveVal = minimax(board, 0, False) 
  
                # Undo the move 
                board[i][j] = '_' 
  
                # If the value of the current move is 
                # more than the best value, then update 
                # best/ 
                if (moveVal > bestVal) :                
                    bestMove = (i, j)
                    bestVal = moveVal
  
    print("The value of the best Move is :", bestVal)
    print()
    return bestMove
# Driver code
board = [
    [ 'x', 'o', 'x' ], 
    [ 'o', 'o', 'x' ], 
    [ '_', '_', '_' ] 
]
  
bestMove = findBestMove(board) 
  
print("The Optimal Move is :") 
print("ROW:", bestMove[0], " COL:", bestMove[1])
  
# This code is contributed by divyesh072019


C#




// C# program to find the 
// next optimal move for a player
using System;
using System.Collections.Generic;
  
class GFG
{
class Move
{
    public int row, col;
};
  
static char player = 'x', opponent = 'o';
  
// This function returns true if there are moves
// remaining on the board. It returns false if
// there are no moves left to play.
static Boolean isMovesLeft(char [,]board)
{
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            if (board[i, j] == '_')
                return true;
    return false;
}
  
// This is the evaluation function as discussed
// in the previous article ( http://goo.gl/sJgv68 )
static int evaluate(char [,]b)
{
    // Checking for Rows for X or O victory.
    for (int row = 0; row < 3; row++)
    {
        if (b[row, 0] == b[row, 1] &&
            b[row, 1] == b[row, 2])
        {
            if (b[row, 0] == player)
                return +10;
            else if (b[row, 0] == opponent)
                return -10;
        }
    }
  
    // Checking for Columns for X or O victory.
    for (int col = 0; col < 3; col++)
    {
        if (b[0, col] == b[1, col] &&
            b[1, col] == b[2, col])
        {
            if (b[0, col] == player)
                return +10;
  
            else if (b[0, col] == opponent)
                return -10;
        }
    }
  
    // Checking for Diagonals for X or O victory.
    if (b[0, 0] == b[1, 1] && b[1, 1] == b[2, 2])
    {
        if (b[0, 0] == player)
            return +10;
        else if (b[0, 0] == opponent)
            return -10;
    }
  
    if (b[0, 2] == b[1, 1] && b[1, 1] == b[2, 0])
    {
        if (b[0, 2] == player)
            return +10;
        else if (b[0, 2] == opponent)
            return -10;
    }
  
    // Else if none of them have won then return 0
    return 0;
}
  
// This is the minimax function. It considers all
// the possible ways the game can go and returns
// the value of the board
static int minimax(char [,]board, 
                   int depth, Boolean isMax)
{
    int score = evaluate(board);
  
    // If Maximizer has won the game 
    // return his/her evaluated score
    if (score == 10)
        return score;
  
    // If Minimizer has won the game 
    // return his/her evaluated score
    if (score == -10)
        return score;
  
    // If there are no more moves and 
    // no winner then it is a tie
    if (isMovesLeft(board) == false)
        return 0;
  
    // If this maximizer's move
    if (isMax)
    {
        int best = -1000;
  
        // Traverse all cells
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                // Check if cell is empty
                if (board[i, j] == '_')
                {
                    // Make the move
                    board[i, j] = player;
  
                    // Call minimax recursively and choose
                    // the maximum value
                    best = Math.Max(best, minimax(board, 
                                    depth + 1, !isMax));
  
                    // Undo the move
                    board[i, j] = '_';
                }
            }
        }
        return best;
    }
  
    // If this minimizer's move
    else
    {
        int best = 1000;
  
        // Traverse all cells
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                // Check if cell is empty
                if (board[i, j] == '_')
                {
                    // Make the move
                    board[i, j] = opponent;
  
                    // Call minimax recursively and choose
                    // the minimum value
                    best = Math.Min(best, minimax(board, 
                                    depth + 1, !isMax));
  
                    // Undo the move
                    board[i, j] = '_';
                }
            }
        }
        return best;
    }
}
  
// This will return the best possible
// move for the player
static Move findBestMove(char [,]board)
{
    int bestVal = -1000;
    Move bestMove = new Move();
    bestMove.row = -1;
    bestMove.col = -1;
  
    // Traverse all cells, evaluate minimax function 
    // for all empty cells. And return the cell 
    // with optimal value.
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            // Check if cell is empty
            if (board[i, j] == '_')
            {
                // Make the move
                board[i, j] = player;
  
                // compute evaluation function for this
                // move.
                int moveVal = minimax(board, 0, false);
  
                // Undo the move
                board[i, j] = '_';
  
                // If the value of the current move is
                // more than the best value, then update
                // best/
                if (moveVal > bestVal)
                {
                    bestMove.row = i;
                    bestMove.col = j;
                    bestVal = moveVal;
                }
            }
        }
    }
  
    Console.Write("The value of the best Move " + 
                        "is : {0}\n\n", bestVal);
  
    return bestMove;
}
  
// Driver code
public static void Main(String[] args)
{
    char [,]board = {{ 'x', 'o', 'x' },
                     { 'o', 'o', 'x' },
                     { '_', '_', '_' }};
  
    Move bestMove = findBestMove(board);
  
    Console.Write("The Optimal Move is :\n");
    Console.Write("ROW: {0} COL: {1}\n\n", 
            bestMove.row, bestMove.col );
}
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
  
// Javascript program to find the
// next optimal move for a player
class Move
{
    constructor()
    {
        let row,col;
    }
}
  
let player = 'x', opponent = 'o';
  
// This function returns true if there are moves
// remaining on the board. It returns false if
// there are no moves left to play.
function isMovesLeft(board)
{
    for(let i = 0; i < 3; i++)
        for(let j = 0; j < 3; j++)
            if (board[i][j] == '_')
                return true;
                  
    return false;
}
  
// This is the evaluation function as discussed
// in the previous article ( http://goo.gl/sJgv68 )
function evaluate(b)
{
      
    // Checking for Rows for X or O victory.
    for(let row = 0; row < 3; row++)
    {
        if (b[row][0] == b[row][1] &&
            b[row][1] == b[row][2])
        {
            if (b[row][0] == player)
                return +10;
                  
            else if (b[row][0] == opponent)
                return -10;
        }
    }
   
    // Checking for Columns for X or O victory.
    for(let col = 0; col < 3; col++)
    {
        if (b[0][col] == b[1][col] &&
            b[1][col] == b[2][col])
        {
            if (b[0][col] == player)
                return +10;
   
            else if (b[0][col] == opponent)
                return -10;
        }
    }
   
    // Checking for Diagonals for X or O victory.
    if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
    {
        if (b[0][0] == player)
            return +10;
              
        else if (b[0][0] == opponent)
            return -10;
    }
   
    if (b[0][2] == b[1][1] && 
        b[1][1] == b[2][0])
    {
        if (b[0][2] == player)
            return +10;
              
        else if (b[0][2] == opponent)
            return -10;
    }
   
    // Else if none of them have
    // won then return 0
    return 0;
}
  
// This is the minimax function. It 
// considers all the possible ways 
// the game can go and returns the 
// value of the board
function minimax(board, depth, isMax)
{
    let score = evaluate(board);
   
    // If Maximizer has won the game
    // return his/her evaluated score
    if (score == 10)
        return score;
   
    // If Minimizer has won the game
    // return his/her evaluated score
    if (score == -10)
        return score;
   
    // If there are no more moves and
    // no winner then it is a tie
    if (isMovesLeft(board) == false)
        return 0;
   
    // If this maximizer's move
    if (isMax)
    {
        let best = -1000;
   
        // Traverse all cells
        for(let i = 0; i < 3; i++)
        {
            for(let j = 0; j < 3; j++)
            {
                  
                // Check if cell is empty
                if (board[i][j]=='_')
                {
                      
                    // Make the move
                    board[i][j] = player;
   
                    // Call minimax recursively 
                    // and choose the maximum value
                    best = Math.max(best, minimax(board,
                                    depth + 1, !isMax));
   
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
   
    // If this minimizer's move
    else
    {
        let best = 1000;
   
        // Traverse all cells
        for(let i = 0; i < 3; i++)
        {
            for(let j = 0; j < 3; j++)
            {
                  
                // Check if cell is empty
                if (board[i][j] == '_')
                {
                      
                    // Make the move
                    board[i][j] = opponent;
   
                    // Call minimax recursively and 
                    // choose the minimum value
                    best = Math.min(best, minimax(board,
                                    depth + 1, !isMax));
   
                    // Undo the move
                    board[i][j] = '_';
                }
            }
        }
        return best;
    }
}
  
// This will return the best possible
// move for the player
function findBestMove(board)
{
    let bestVal = -1000;
    let bestMove = new Move();
    bestMove.row = -1;
    bestMove.col = -1;
   
    // Traverse all cells, evaluate 
    // minimax function for all empty 
    // cells. And return the cell
    // with optimal value.
    for(let i = 0; i < 3; i++)
    {
        for(let j = 0; j < 3; j++)
        {
              
            // Check if cell is empty
            if (board[i][j] == '_')
            {
                  
                // Make the move
                board[i][j] = player;
   
                // compute evaluation function 
                // for this move.
                let moveVal = minimax(board, 0, false);
   
                // Undo the move
                board[i][j] = '_';
   
                // If the value of the current move 
                // is more than the best value, then 
                // update best
                if (moveVal > bestVal)
                {
                    bestMove.row = i;
                    bestMove.col = j;
                    bestVal = moveVal;
                }
            }
        }
    }
   
    document.write("The value of the best Move " +
                   "is : ", bestVal + "<br><br>");
   
    return bestMove;
}
  
// Driver code
let board = [ [ 'x', 'o', 'x' ],
              [ 'o', 'o', 'x' ],
              [ '_', '_', '_' ] ];
let bestMove = findBestMove(board);
  
document.write("The Optimal Move is :<br>");
document.write("ROW: " + bestMove.row + 
               " COL: "+ bestMove.col + "<br>");
  
// This code is contributed by rag2127
  
</script>


Output : 

The value of the best Move is : 10

The Optimal Move is :
ROW: 2 COL: 2 

Explanation :

Tic-Tac-Toe Game Tree

This image depicts all the possible paths that the game can take from the root board state. It is often called the Game Tree. 

The 3 possible scenarios in the above example are : 

  • Left Move : If X plays [2,0]. Then O will play [2,1] and win the game. The value of this move is -10
  • Middle Move : If X plays [2,1]. Then O will play [2,2] which draws the game. The value of this move is 0
  • Right Move : If X plays [2,2]. Then he will win the game. The value of this move is +10;

Remember, even though X has a possibility of winning if he plays the middle move, O will never let that happen and will choose to draw instead.
Therefore the best choice for X, is to play [2,2], which will guarantee a victory for him.
We do encourage our readers to try giving various inputs and understanding why the AI choose to play that move. Minimax may confuse programmers as it thinks several moves in advance and is very hard to debug at times. Remember this implementation of minimax algorithm can be applied any 2 player board game with some minor changes to the board structure and how we iterate through the moves. Also sometimes it is impossible for minimax to compute every possible game state for complex games like Chess. Hence we only compute upto a certain depth and use the evaluation function to calculate the value of the board.
Stay tuned for next weeks article where we shall be discussing about Alpha-Beta pruning that can drastically improve the time taken by minimax to traverse a game tree.

 



Similar Reads

Implementation of Tic-Tac-Toe for 2 person game (User vs. User)
For 1-Person game (User vs. CPU), please refer Implementation of Tic-Tac-Toe game Rules of the Game The game is to be played between two people (in this program between HUMAN to HUMAN).First the game will take the names of the two players as input.One of the player chooses ‘O’ and the other ‘X’ to mark their respective cells.There would be a game t
9 min read
Implementation of Tic-Tac-Toe game
[GFGTABS] C++ #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; // Set up the game board as an array vector&lt;string&gt; board = {&quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;, &quot;-&quot;}; // Define a function to print the g
15+ min read
Validity of a given Tic-Tac-Toe board configuration
A Tic-Tac-Toe board is given after some moves are played. Find out if the given board is valid, i.e., is it possible to reach this board position after some moves or not.Note that every arbitrary filled grid of 9 spaces isn't valid e.g. a grid filled with 3 X and 6 O isn't valid situation because each player needs to take alternate turns. Input is
15+ min read
Minimax Algorithm in Game Theory | Set 1 (Introduction)
Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the two players are called maximizer and minimizer. The
9 min read
Introduction to Evaluation Function of Minimax Algorithm in Game Theory
Prerequisite: Minimax Algorithm in Game TheoryAs seen in the above article, each leaf node had a value associated with it. We had stored this value in an array. But in the real world when we are creating a program to play Tic-Tac-Toe, Chess, Backgammon, etc. we need to implement a function that calculates the value of the board depending on the pla
8 min read
Minimax Algorithm in Game Theory | Set 4 (Alpha-Beta Pruning)
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryAlpha-Beta pruning is not actually a new algorithm, but rather an optimization technique for the minimax algorithm. It reduces the computation time by a huge factor. This allows us to search much faster and even go into deeper levels in the game tree. It cuts off bra
11 min read
Minimax Algorithm in Game Theory | Set 5 (Zobrist Hashing)
Previous posts on this topic : Minimax Algorithm in Game Theory, Evaluation Function in Game Theory, Tic-Tac-Toe AI – Finding optimal move, Alpha-Beta Pruning.Zobrist Hashing is a hashing function that is widely used in 2 player board games. It is the most common hashing function used in transposition table. Transposition tables basically store the
12 min read
Game Theory (Normal form game) | Set 2 (Game with Pure Strategy)
Game Theory (Normal – form game) | Set 1 (Introduction) Please go through the above article before proceeding. Given a payoff matrix. The task is to find the optimum strategies of the players. Solution: Player A is having 3 strategies - 1, 2 and 3, and player B is also having 3 strategies - 1, 2 and 3. Step 1: Find row minimum values for each row a
2 min read
Game Theory (Normal-form game) | Set 3 (Game with Mixed Strategy)
Consider the following payoff matrix with respect to player A and solve it optimally. Solution: If a game has no saddle point then the game is said to have mixed strategy. Step 1: Find out the row minimum and column maximum. Step 2: Find out the minimax and maximin values. Since minimax and maximin value of this game are not equal, this game has no
4 min read
Game Theory (Normal-form Game) | Set 7 (Graphical Method [M X 2] Game)
The payoff matrix of an M * 2 game consists of M rows and two columns. This article will discuss how to solve an M * 2 game by graphical method. Also, this article will discuss if more than two lines intersect the same point in the graph then how can a 2 * 2 payoff matrix be formed. Consider the below problem: Solution: First check whether the prob
3 min read
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
The payoff matrix of a 2 * N game consists of 2 rows and N columns . This article will discuss how to solve a 2 * N game by graphical method. Consider the below 2 * 5 game: Solution: First check the saddle point of the game. This game has no saddle point. Step 1: Reduce the size of the payoff matrix by applying dominance property, if it exists. Thi
3 min read
Game Theory (Normal - form game) | Set 1 (Introduction)
Game theory is a mathematical model used for decision making. It has applications in all fields of social science, as well as in logic and computer science. Game theory has come to play an increasingly important role in logic and in computer science. To be fully defined, a game must specify the following elements: the players of the game, the infor
4 min read
Game Theory (Normal-form Game) | Set 5 (Dominance Property-Mixed Strategy)
This article discusses how to solve a game by the dominance property with mixed strategy. Consider the below game: Solution: Find out the row minimum and column maximum values. Here Minimax value is not equal to Maximin so this game has no saddle point. Now proceed with dominance property to reduce the rows and the columns. Reducing the row and the
2 min read
Combinatorial Game Theory | Set 2 (Game of Nim)
We strongly recommend to refer below article as a prerequisite of this. Combinatorial Game Theory | Set 1 (Introduction) In this post, Game of Nim is discussed. The Game of Nim is described by the following rules- “ Given a number of piles in which each pile contains some numbers of stones/coins. In each turn, a player can choose only one pile and
15+ min read
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
In some of the games, it is possible to reduce the size of the payoff matrix by eliminating rows (or columns) that are dominated by other rows (or columns) respectively. Dominance property for rows: X ≤ Y i.e. if all the elements of a particular row X are less than or equal to the corresponding elements of another row Y then delete row X (row X is
4 min read
Optimal Strategy for the Divisor game using Dynamic Programming
Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game
9 min read
Expectimax Algorithm in Game Theory
The Expectimax search algorithm is a game theory algorithm used to maximize the expected utility. It is a variation of the Minimax algorithm. While Minimax assumes that the adversary(the minimizer) plays optimally, the Expectimax doesn't. This is useful for modelling environments where adversary agents are not optimal, or their actions are based on
8 min read
Optimal Strategy for a Game | Set 2
Problem statement: Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can defini
15+ min read
Optimal Strategy for a Game | Set 3
Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move
15+ min read
Optimal Strategy for a Game | DP-31
Consider a row of N coins of values V1 . . . Vn, where N is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move
15+ min read
Optimal strategy for a Game with modifications
It is strongly recommended to first refer Optimal Strategy for a Game problem as a prerequisite. Let us now talk about a variation problem. Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player performs the following operation K times.The player selects eith
10 min read
Optimal Page Replacement Algorithm
Prerequisite: Page Replacement Algorithms In operating systems, whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to
15+ min read
Check if a king can move a valid move or not when N nights are there in a modified chessboard
Given an infinite chessboard with the same rules as that of chess. Also given are N knights coordinates on the infinite chessboard(-10^9 &lt;= x, y &lt;= 10^9) and the king's coordinate, the task is to check if the King is checkmate or not. Examples: Input: a[] = { {1, 0}, {0, 2}, {2, 5}, {4, 4}, {5, 0}, {6, 2} } king -&gt; {3, 2} Output: Yes The k
10 min read
Number of ways for playing first move optimally in a NIM game
Two players A and B are playing NIM Game with each other. Both are playing optimally. Player A starts the game. The task is to find the number of ways of playing 1st move for A to ensure a winning strategy for A if possible, otherwise, print -1. Examples: Input: arr[] = {1, 2, 3} Output: -1 There is no winning strategy for A no matter how optimally
8 min read
Find the winner of a game of donating i candies in every i-th move
Given two integers X and Y representing the number of candies allocated to players A and B respectively, where both the players indulge in a game of donating i candies to the opponent in every ith move. Starting with player A, the game continues with alternate turns until a player is unable to donate the required amount of candies and loses the gam
6 min read
Find winner in game of N balls, in which a player can remove any balls in range [A, B] in a single move
Given two integers A and B, and also given that Alice and Bob are playing a game starting with a bag containing N balls, in which, in a single move, a player can remove any number of balls between the range [A, B] and if the player cannot remove any balls, then the player loses, the task is to find the winner of the game if Alice and Bob play the g
5 min read
Find winner of game where simultaneous decrement and increment of two elements done in one move
Given an arr[] of positive integers of length N. Player X and Y plays a game where in each move one person chooses two elements of arr[] (say arr[i] and arr[j]) such that 0 ? i &lt; j ? N - 1 and arri should be greater than 0 and Then decrement arri and increment arrj. When one player is unable to make such a move the player loses. The task is to f
7 min read
Find winner of game where in each move division of N or subtraction is done
Jon and Arya are playing a game. The rules of the game are as follows: They have a single number N initially.Both will play an alternate move. Jon starts first.Both will play each move optimally.In each move, they can perform only one of these operations:Divide that number by 2, 3, 4, or 5 and take the floor of the result.Subtract that number by 2,
10 min read
Find winner of the game when any set bit is removed in each move
Two players, Player 1 and Player 2, are given an integer N to play a game. The rules of the game are as follows : In one turn, a player can remove any set bit of N in its binary representation to make a new N. Player 1 always takes the first turn. If a player cannot make a move, he loses.Examples: Input: N = 8Output: 1Explanation: N = 8N = 1000 (bi
8 min read
CSES Solutions - Letter Pair Move Game
There are 2n boxes in a line. Two adjacent boxes are empty, and all other boxes have a letter "A" or "B". Both letters appear in exactly n-1 boxes. Your task is to move the letters so that all letters "A" appear before any letter "B". On each turn you can choose any two adjacent boxes that have a letter and move the letters to the two adjacent empt
13 min read
Article Tags :
Practice Tags :