0% found this document useful (0 votes)
38 views4 pages

Tic-Tac-Toe AI with Minimax Algorithm

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

Tic-Tac-Toe AI with Minimax Algorithm

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

Code:

# Constants
PLAYER = 'X'
AI = 'O'
EMPTY = ' '

# Initialize the board


def initialize_board():
return [EMPTY] * 9 # 3x3 board flattened

# Print the board


def print_board(board):
print(f"{board[0]} | {board[1]} | {board[2]}")
print("--+---+--")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("--+---+--")
print(f"{board[6]} | {board[7]} | {board[8]}")
print() # Add a blank line after printing the board for spacing

# Check for winner


def check_winner(board, player):
winning_combinations = [
(0, 1, 2), (3, 4, 5), (6, 7, 8), # rows
(0, 3, 6), (1, 4, 7), (2, 5, 8), # columns
(0, 4, 8), (2, 4, 6) # diagonals
]
for combo in winning_combinations:
if board[combo[0]] == board[combo[1]] == board[combo[2]] == player:
return True
return False

# Check if the board is full


def is_full(board):
return all(spot != EMPTY for spot in board)

# Get available moves


def available_moves(board):
return [i for i, spot in enumerate(board) if spot == EMPTY]

# Minimax algorithm to evaluate the best move for AI


def minimax(board, depth, is_maximizing):
if check_winner(board, AI):
return 1 # AI wins
if check_winner(board, PLAYER):
return -1 # Player wins
if is_full(board):
return 0 # Draw

if is_maximizing:
best_score = -float('inf')
for move in available_moves(board):
board[move] = AI
score = minimax(board, depth + 1, False)
board[move] = EMPTY
best_score = max(score, best_score)
return best_score
else:
best_score = float('inf')
for move in available_moves(board):
board[move] = PLAYER
score = minimax(board, depth + 1, True)
board[move] = EMPTY
best_score = min(score, best_score)
return best_score

# AI's move using the minimax algorithm


def ai_move(board):
best_move = None
best_score = -float('inf')

for move in available_moves(board):


board[move] = AI
score = minimax(board, 0, False)
board[move] = EMPTY
if score > best_score:
best_score = score
best_move = move
return best_move

# Player's move
def player_move(board):
while True:
try:
move = int(input("Enter your move (1-9): ")) - 1
if board[move] == EMPTY:
return move
else:
print("Cell is already occupied. Try again.")
except (ValueError, IndexError):
print("Invalid move. Please enter a number between 1 and 9.")

# Main game loop


def play_game():
board = initialize_board()
print_board(board)

while True:
# Player's move
move = player_move(board)
board[move] = PLAYER

# Check for winner or draw after the player's move


if check_winner(board, PLAYER):
print_board(board)
print("You win!")
break
if is_full(board):
print_board(board)
print("It's a draw!")
break

# AI's move
move = ai_move(board)
board[move] = AI

# Print the board after both the player and AI have moved
print_board(board)

# Check for winner or draw after the AI's move


if check_winner(board, AI):
print("AI wins!")
break
if is_full(board):
print("It's a draw!")
break
play_game()
Output:

You might also like