import math
# Initialize the board
def create_board():
return [' ' for _ in range(9)]
# Display the board
def print_board(board):
for i in range(3):
print(' | '.join(board[i * 3:(i + 1) * 3]))
if i < 2:
print('---------')
# Check if a player has won
def check_winner(board, player):
win_conditions = [
[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 condition in win_conditions:
if all(board[i] == player for i in condition):
return True
return False
# Check if the board is full
def is_full(board):
return ' ' not in board
# Get available moves
def get_available_moves(board):
return [i for i, cell in enumerate(board) if cell == ' ']
# Minimax algorithm
def minimax(board, depth, is_maximizing):
if check_winner(board, 'O'): # AI wins
return 10 - depth
if check_winner(board, 'X'): # Human wins
return depth - 10
if is_full(board): # Draw
return 0
if is_maximizing: # AI's turn
max_eval = -math.inf
for move in get_available_moves(board):
board[move] = 'O'
eval = minimax(board, depth + 1, False)
board[move] = ' '
max_eval = max(max_eval, eval)
return max_eval
else: # Human's turn
min_eval = math.inf
for move in get_available_moves(board):
board[move] = 'X'
eval = minimax(board, depth + 1, True)
board[move] = ' '
min_eval = min(min_eval, eval)
return min_eval
# Get the best move for the AI
def get_best_move(board):
best_score = -math.inf
best_move = None
for move in get_available_moves(board):
board[move] = 'O'
score = minimax(board, 0, False)
board[move] = ' '
if score > best_score:
best_score = score
best_move = move
return best_move
# Main game loop
def play_game():
board = create_board()
while True:
# Print the board
print_board(board)
# Check for game over
if check_winner(board, 'O'):
print("AI wins!")
break
if check_winner(board, 'X'):
print("You win!")
break
if is_full(board):
print("It's a draw!")
break
# Human's turn
try:
move = int(input("Enter your move (1-9): ")) - 1
if board[move] != ' ' or move not in range(9):
print("Invalid move. Try again.")
continue
except ValueError:
print("Invalid input. Enter a number between 1 and 9.")
continue
board[move] = 'X'
# AI's turn
if not check_winner(board, 'X') and not is_full(board):
ai_move = get_best_move(board)
board[ai_move] = 'O'
# Run the game
if __name__ == "__main__":
play_game()
Comments
Post a Comment