Sure! Below is a Python implementation of a Tic Tac Toe game where two AIs play against each other. Both AIs use the Minimax algorithm to determine their optimal moves, ensuring that the game plays out correctly. The board is displayed in the format you specified after each move.
Overview
- Board Representation: The board is represented as a list of 9 elements, corresponding to the 9 cells in Tic Tac Toe.
- Display Function: A function to print the board in the desired format.
- Game Logic: Functions to check for a winner, determine available moves, and execute the game loop.
- AI Implementation: Both AIs use the Minimax algorithm to choose their best possible moves.
Code Implementation
import math
import copy
import random
# Define players
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '
def print_board(board):
"""
Prints the current state of the board in a formatted manner.
"""
def cell_content(i):
return board[i] if board[i] != EMPTY else ' '
print(f" {cell_content(0)} | {cell_content(1)} | {cell_content(2)} ")
print("---|---|---")
print(f" {cell_content(3)} | {cell_content(4)} | {cell_content(5)} ")
print("---|---|---")
print(f" {cell_content(6)} | {cell_content(7)} | {cell_content(8)} ")
print()
def check_winner(board):
"""
Checks if there's a winner or the game is a tie.
Returns 'X', 'O' if there's a winner, 'Tie' if it's a tie, or None otherwise.
"""
win_combinations = [
[0,1,2], [3,4,5], [6,7,8], # Horizontal
[0,3,6], [1,4,7], [2,5,8], # Vertical
[0,4,8], [2,4,6] # Diagonal
]
for combo in win_combinations:
a, b, c = combo
if board[a] == board[b] == board[c] != EMPTY:
return board[a]
if EMPTY not in board:
return 'Tie'
return None
def get_available_moves(board):
"""
Returns a list of indexes of available moves on the board.
"""
return [i for i, spot in enumerate(board) if spot == EMPTY]
def minimax(board, depth, is_maximizing, player, opponent):
"""
Minimax algorithm to determine the best move.
"""
winner = check_winner(board)
if winner == player:
return 10 - depth
elif winner == opponent:
return depth - 10
elif winner == 'Tie':
return 0
if is_maximizing:
best_score = -math.inf
for move in get_available_moves(board):
board[move] = player
score = minimax(board, depth + 1, False, player, opponent)
board[move] = EMPTY
best_score = max(best_score, score)
return best_score
else:
best_score = math.inf
for move in get_available_moves(board):
board[move] = opponent
score = minimax(board, depth + 1, True, player, opponent)
board[move] = EMPTY
best_score = min(best_score, score)
return best_score
def get_best_move(board, player, opponent):
"""
Determines the best move for the current player using the Minimax algorithm.
"""
best_score = -math.inf
best_move = None
for move in get_available_moves(board):
board[move] = player
score = minimax(board, 0, False, player, opponent)
board[move] = EMPTY
if score > best_score:
best_score = score
best_move = move
return best_move
def ai_move(board, player, opponent):
"""
Executes the AI's move.
"""
move = get_best_move(board, player, opponent)
if move is not None:
board[move] = player
print(f"AI '{player}' chooses position {move}")
else:
print(f"AI '{player}' has no moves left!")
def play_game():
"""
Main function to play the game between two AIs.
"""
board = [EMPTY] * 9
current_player = PLAYER_X
opponent = PLAYER_O
print("Initial Board:")
print_board(board)
while True:
ai_move(board, current_player, opponent)
print_board(board)
result = check_winner(board)
if result:
if result == 'Tie':
print("It's a tie!")
else:
print(f"Player '{result}' wins!")
break
# Switch players
current_player, opponent = opponent, current_player
if __name__ == "__main__":
play_game()
How It Works
-
Board Representation: The board is a list of 9 elements, initialized with spaces to represent empty cells. Each index corresponds to a cell on the board:
0 | 1 | 2
---|---|---
3 | 4 | 5
---|---|---
6 | 7 | 8
-
Display Function (print_board): This function prints the board in a formatted way, replacing empty cells with spaces.
-
Checking for a Winner (check_winner): This function checks all possible winning combinations to determine if a player has won or if the game is a tie.
-
Available Moves (get_available_moves): Returns a list of indices that are not yet occupied.
-
Minimax Algorithm (minimax): This recursive function evaluates the board and assigns scores based on the potential outcomes. It tries to maximize the score for the current player and minimize it for the opponent.
-
Determining the Best Move (get_best_move): Iterates through all available moves, uses the Minimax algorithm to evaluate each move, and selects the move with the highest score.
-
AI Move Execution (ai_move): The AI determines and makes its move, then prints which position it chose.
-
Game Loop (play_game): Alternates between the two AIs, making moves until there's a winner or a tie. After each move, the board is printed, and the game state is evaluated.
Example Output
When you run the script, you'll see an output similar to the following, showing each move by the AIs and the final result:
Initial Board:
| |
---|---|---
| |
---|---|---
| |
AI 'X' chooses position 0
X | |
---|---|---
| |
---|---|---
| |
AI 'O' chooses position 4
X | |
---|---|---
| O |
---|---|---
| |
AI 'X' chooses position 2
X | | X
---|---|---
| O |
---|---|---
| |
AI 'O' chooses position 6
X | | X
---|---|---
| O |
---|---|---
O | |
AI 'X' chooses position 1
X | X | X
---|---|---
| O |
---|---|---
O | |
Player 'X' wins!
Notes
-
Optimal Play: Since both AIs use the Minimax algorithm, they play optimally. This means that if both AIs play perfectly, the game will always end in a tie.
-
Move Choices: The AI will always choose the best possible move. If multiple moves have the same score, it selects the first one it evaluates. You can modify the get_best_move function to add randomness when multiple moves have the same score to make the games more varied.
-
Customization: You can enhance this script by adding different AI strategies, allowing human players to interact, or improving the UI.
Feel free to run and modify this code to suit your needs!