Search code examples
python-3.xpygameartificial-intelligencetic-tac-toeminimax

incorrect output from minimax algorithm for Tic Tac Toe


There are no errors in the code execution , but the output of the minimax algorithm in incorrect , please have a look,` the AI_makemove function is called from the main loop, and the board_state is the copy of the actual board. The function AI_makemove is supposed to return the best move for the computer against the user , board_state is the current state of the board, depth is the number of positions filled in the board , check_if_won function returns true if the state is a win state for the current player .

def AI_makemove(board_state , isAI , depth):

temp_board = copy.deepcopy(board_state)

depth+=1
print(temp_board , depth , isAI)

if isAI:
    bestVal = -9999
    a = b = 0
    for i in range(0,3):
        for j in range(0,3):
            if temp_board[i][j] == 0:
                temp_board1  = copy.deepcopy(temp_board)
                temp_board1[i][j] = 2
                if check_if_won(2,temp_board1):
                    return [1 , i, j]
                if depth == 9:
                    return [bestVal , a ,b]
                l = AI_makemove(temp_board1,False,depth)
                if int(l[0]) > bestVal:
                    bestVal = int(l[0])
                    a = int(l[1])
                    b = int(l[2])

else:
    bestVal = +9999
    a = b = 0
    for i in range(0, 3):
        for j in range(0, 3):
            if temp_board[i][j] == 0:
                temp_board1  = copy.deepcopy(temp_board)
                temp_board1[i][j] = 1
                if check_if_won(1,temp_board1):
                    return [-1 , i, j]
                if depth == 9:
                    return [bestVal , a ,b]
                l = AI_makemove(temp_board1,True,depth)
                if int(l[0]) < bestVal:
                    bestVal = int(l[0])
                    a = int(l[1])
                    b = int(l[2])


return [bestVal , a ,b]

Solution

  • I tried a couple of times to debug the code , but wasn't able to fix it , so i wrote the code again with a different approach and it worked. Here's the code