# ai_logic.
py
import random
def minimax(board, depth, is_maximizing_player):
if check_winner(board):
return 1 if is_maximizing_player else -1
elif ' ' not in board:
return 0
if is_maximizing_player:
best_score = -float('inf')
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, depth + 1, False)
board[i] = ' '
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for i in range(9):
if board[i] == ' ':
board[i] = 'X'
score = minimax(board, depth + 1, True)
board[i] = ' '
best_score = min(score, best_score)
return best_score
def ai_move(board):
best_score = -float('inf')
best_move = None
for i in range(9):
if board[i] == ' ':
board[i] = 'O'
score = minimax(board, 0, False)
board[i] = ' '
if score > best_score:
best_score = score
best_move = i
return best_move