import random

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    for i in range(3):
        if all([cell == player for cell in board[i]]) or all([board[j][i] == player for j in range(3)]):
            return True
    if board[0][0] == board[1][1] == board[2][2] == player or board[0][2] == board[1][1] == board[2][0] == player:
        return True
    return False

def get_empty_cells(board):
    empty_cells = []
    for i in range(3):
        for j in range(3):
            if board[i][j] == " ":
                empty_cells.append((i, j))
    return empty_cells

def minimax(board, depth, maximizing_player):
    if check_winner(board, "X"):
        return -1
    if check_winner(board, "O"):
        return 1
    if not get_empty_cells(board):
        return 0

    if maximizing_player:
        max_eval = float('-inf')
        for cell in get_empty_cells(board):
            x, y = cell
            board[x][y] = "O"
            eval = minimax(board, depth + 1, False)
            board[x][y] = " "
            max_eval = max(max_eval, eval)
        return max_eval
    else:
        min_eval = float('inf')
        for cell in get_empty_cells(board):
            x, y = cell
            board[x][y] = "X"
            eval = minimax(board, depth + 1, True)
            board[x][y] = " "
            min_eval = min(min_eval, eval)
        return min_eval

def best_move(board):
    max_eval = float('-inf')
    move = None
    for cell in get_empty_cells(board):
        x, y = cell
        board[x][y] = "O"
        eval = minimax(board, 0, False)
        board[x][y] = " "
        if eval > max_eval:
            max_eval = eval
            move = (x, y)
    return move

def main():
    board = [[" " for _ in range(3)] for _ in range(3)]
    print_board(board)

    while True:
        try:
            row, col = map(int, input("Enter your move (row and column separated by a space): ").split())
            if board[row - 1][col - 1] == " ":
                board[row - 1][col - 1] = "X"
                break
            else:
                print("Invalid move. Try again.")
        except ValueError:
            print("Invalid input. Try again.")
        except IndexError:
            print("Invalid coordinates. Try again.")

    while not check_winner(board, "X") and get_empty_cells(board):
        ai_move = best_move(board)
        board[ai_move[0]][ai_move[1]] = "O"
        print_board(board)

        if check_winner(board, "O"):
            print("AI wins!")
            break

        while True:
            try:
                row, col = map(int, input("Enter your move (row and column separated by a space): ").split())
                if board[row - 1][col - 1] == " ":
                    board[row - 1][col - 1] = "X"
                    break
                else:
                    print("Invalid move. Try again.")
            except ValueError:
                print("Invalid input. Try again.")
            except IndexError:
                print("Invalid coordinates. Try again.")

        if check_winner(board, "X"):
            print_board(board)
            print("You win!")
            break

    if not get_empty_cells(board) and not check_winner(board, "X") and not check_winner(board, "O"):
        print_board(board)
        print("It's a draw!")

if __name__ == "__main__":
    main()
import random

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    for i in range(3):
        if all([cell == player for cell in board[i]]) or all([board[j][i] == player for j in range(3)]):
            return True
    if board[0][0] == board[1][1] == board[2][2] == player or board[0][2] == board[1][1] == board[2][0] == player:
        return True
    return False

def get_empty_cells(board):
    empty_cells = []
    for i in range(3):
        for j in range(3):
            if board[i][j] == " ":
                empty_cells.append((i, j))
    return empty_cells

def minimax(board, depth, maximizing_player):
    if check_winner(board, "X"):
        return -1
    if check_winner(board, "O"):
        return 1
    if not get_empty_cells(board):
        return 0

    if maximizing_player:
        max_eval = float('-inf')
        for cell in get_empty_cells(board):
            x, y = cell
            board[x][y] = "O"
            eval = minimax(board, depth + 1, False)
            board[x][y] = " "
            max_eval = max(max_eval, eval)
        return max_eval
    else:
        min_eval = float('inf')
        for cell in get_empty_cells(board):
            x, y = cell
            board[x][y] = "X"
            eval = minimax(board, depth + 1, True)
            board[x][y] = " "
            min_eval = min(min_eval, eval)
        return min_eval

def best_move(board):
    max_eval = float('-inf')
    move = None
    for cell in get_empty_cells(board):
        x, y = cell
        board[x][y] = "O"
        eval = minimax(board, 0, False)
        board[x][y] = " "
        if eval > max_eval:
            max_eval = eval
            move = (x, y)
    return move

def main():
    board = [[" " for _ in range(3)] for _ in range(3)]
    print_board(board)

    while True:
        try:
            row, col = map(int, input("Enter your move (row and column separated by a space): ").split())
            if board[row - 1][col - 1] == " ":
                board[row - 1][col - 1] = "X"
                break
            else:
                print("Invalid move. Try again.")
        except ValueError:
            print("Invalid input. Try again.")
        except IndexError:
            print("Invalid coordinates. Try again.")

    while not check_winner(board, "X") and get_empty_cells(board):
        ai_move = best_move(board)
        board[ai_move[0]][ai_move[1]] = "O"
        print_board(board)

        if check_winner(board, "O"):
            print("AI wins!")
            break

        while True:
            try:
                row, col = map(int, input("Enter your move (row and column separated by a space): ").split())
                if board[row - 1][col - 1] == " ":
                    board[row - 1][col - 1] = "X"
                    break
                else:
                    print("Invalid move. Try again.")
            except ValueError:
                print("Invalid input. Try again.")
            except IndexError:
                print("Invalid coordinates. Try again.")

        if check_winner(board, "X"):
            print_board(board)
            print("You win!")
            break

    if not get_empty_cells(board) and not check_winner(board, "X") and not check_winner(board, "O"):
        print_board(board)
        print("It's a draw!")

if __name__ == "__main__":
    main()