0% found this document useful (0 votes)
11 views

ai_logic.py

The document contains a Python script implementing a minimax algorithm for a Tic-Tac-Toe game. It defines two functions: 'minimax' to evaluate the best score for the current player and 'ai_move' to determine the optimal move for the AI. The AI plays as 'O' and aims to maximize its score while minimizing the opponent's score.

Uploaded by

miway26248
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

ai_logic.py

The document contains a Python script implementing a minimax algorithm for a Tic-Tac-Toe game. It defines two functions: 'minimax' to evaluate the best score for the current player and 'ai_move' to determine the optimal move for the AI. The AI plays as 'O' and aims to maximize its score while minimizing the opponent's score.

Uploaded by

miway26248
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

# 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

You might also like