import math
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def is_winner(board, player):
for row in board:
if all(s == player for s in row): return True
for col in range(3):
if all(board[row][col] == player for row in range(3)): return True
if all(board[i][i] == player for i in range(3)): return True
if all(board[i][2 - i] == player for i in range(3)): return True
return False
def empty_cells(board):
return [(r, c) for r in range(3) for c in range(3) if board[r][c] == " "]
def minimax(board, depth, is_maximizing):
if is_winner(board, "O"): return 1
if is_winner(board, "X"): return -1
if not empty_cells(board): return 0
if is_maximizing:
best = -math.inf
for r, c in empty_cells(board):
board[r][c] = "O"
best = max(best, minimax(board, depth + 1, False))
board[r][c] = " "
return best
else:
best = math.inf
for r, c in empty_cells(board):
board[r][c] = "X"
best = min(best, minimax(board, depth + 1, True))
board[r][c] = " "
return best
def best_move(board):
best_score = -math.inf
move = None
for r, c in empty_cells(board):
board[r][c] = "O"
score = minimax(board, 0, False)
board[r][c] = " "
if score > best_score:
best_score = score
move = (r, c)
return move
def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]