tic tac toe ai in python

To create a Tic Tac Toe AI in Python, we can use the minimax algorithm. Here is a basic implementation:

main.py
# Tic Tac Toe board is represented as a list of strings
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

# The minimax algorithm function
def minimax(board, depth, is_maximizing):
    # Base case: If someone has won or it's a tie, return the score
    if check_win(board) == "X":
        return 10 - depth
    elif check_win(board) == "O":
        return depth - 10
    elif check_tie(board):
        return 0

    # If it's the AI player's turn
    if is_maximizing:
        best_score = -float("inf")
        for i in range(len(board)):
            if board[i] == " ":
                board[i] = "X"
                score = minimax(board, depth+1, False)
                board[i] = " "
                best_score = max(score, best_score)
        return best_score

    # If it's the human player's turn
    else:
        best_score = float("inf")
        for i in range(len(board)):
            if board[i] == " ":
                board[i] = "O"
                score = minimax(board, depth+1, True)
                board[i] = " "
                best_score = min(score, best_score)
        return best_score

# The function to make the AI move
def ai_move(board):
    best_score = -float("inf")
    best_move = None
    for i in range(len(board)):
        if board[i] == " ":
            board[i] = "X"
            score = minimax(board, 0, False)
            board[i] = " "
            if score > best_score:
                best_score = score
                best_move = i
    board[best_move] = "X"
1511 chars
49 lines

In this implementation, the board variable represents the Tic Tac Toe board as a list of strings, where "X" represents the AI player, "O" represents the human player, and " " represents an empty space.

The minimax function recursively evaluates all possible moves and returns the best score for the AI player. The ai_move function uses the minimax function to determine the best move for the AI player and updates the board variable accordingly.

Note: This implementation does not include the functions to check for a win or tie. You'll need to implement those separately.

gistlibby LogSnag