Python (AI vs Human Using Minimax Algorithm)
Python (AI vs Human Using Minimax Algorithm)
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 5)
def empty_cells(board):
return [(r, c) for r in range(3) for c in range(3) if board[r][c] == " "]
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)]