tic tac toe using minimax in python

Here's a code snippet that implements the minimax algorithm for Tic-Tac-Toe in Python:

main.py
import math

def minimax(board, depth, is_maximizing):
    if check_winner(board, "O"):
        return -1
    elif check_winner(board, "X"):
        return 1
    elif check_tie(board):
        return 0

    if is_maximizing:
        best_score = -math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == "":
                    board[i][j] = "X"
                    score = minimax(board, depth+1, False)
                    board[i][j] = ""
                    best_score = max(score, best_score)
        return best_score
    else:
        best_score = math.inf
        for i in range(3):
            for j in range(3):
                if board[i][j] == "":
                    board[i][j] = "O"
                    score = minimax(board, depth+1, True)
                    board[i][j] = ""
                    best_score = min(score, best_score)
        return best_score
919 chars
31 lines

The minimax function takes a Tic-Tac-Toe board as input, along with the current depth and whether it is maximizing or minimizing. If the function has reached a terminal state (either a win for X or a win for O, or a tie), it returns the corresponding score of -1, 1, or 0, respectively.

If it is maximizing, it tests each possible move for X and returns the maximum score found. If it is minimizing, it tests each possible move for O and returns the minimum score found. The math.inf constants are used to initialize the best_score variables to negative and positive infinity, respectively.

You can then use the minimax function to make moves in the game. Here is an example game loop:

main.py
board = [["", "", ""],
         ["", "", ""],
         ["", "", ""]]

while not check_game_over(board):
    print_board(board)

    # Player's turn
    row = int(input("Enter row: "))
    col = int(input("Enter column: "))
    if board[row][col] == "":
        board[row][col] = "O"

    # Computer's turn
    best_score = -math.inf
    best_move = None
    for i in range(3):
        for j in range(3):
            if board[i][j] == "":
                board[i][j] = "X"
                score = minimax(board, 0, False)
                board[i][j] = ""
                if score > best_score:
                    best_score = score
                    best_move = (i, j)
    board[best_move[0]][best_move[1]] = "X"

print_board(board)
winner = check_winner(board, "O")
if winner:
    print("You win!")
else:
    print("Computer wins!")
836 chars
34 lines

In this game loop, the program prompts the user to enter a row and column for their move. If the move is valid, it places an "O" on the board. Then, it uses the minimax function to find the best move for the computer, and places an "X" on the board in that location.

The game ends when either X or O wins or the game is tied. The check_game_over, print_board, and check_winner functions are left as exercises for the reader.

gistlibby LogSnag