Tic Tac Toe with (Player vs. AI Opponent) Using Minmax Algorithm
Here's a breakdown of the code:
- Initialization :
- A dictionary
scores
is initialized to keep track of the number of wins for the player, AI, and ties.
- Board Creation :
create_board()
: Creates a 3x3 game board represented as a list of lists filled with spaces (' ').
- Printing the Board :
print_board(board)
: Prints the current state of the board to the console.
- Winner Checking :
check_winner(board, player)
: Checks if the specified player ('X' for player, 'O' for AI) has won by having a full row, column, or diagonal.
- Board Full Check :
is_full(board)
: Checks if the board is full (i.e., no empty spaces left).
- Minimax Algorithm :
minimax(board, is_maximizing)
: Implements the minimax algorithm to determine the best move for the AI. It recursively evaluates all possible moves and assigns scores based on the outcome (win, lose, tie).
- AI Move :
ai_move(board)
: Uses the minimax algorithm to find the best move for the AI and updates the board accordingly.
- Player Move :
player_move(board)
: Prompts the player to enter their move in the format "row column" (e.g., 1 1), checks for validity, and updates the board. If the input is invalid or the cell is occupied, it prompts the player to try again.
- Main Game Loop :
main()
: The main function that runs the game loop. It alternates between the player's and AI's moves, checks for a winner or a full board, and updates the scores. After the game ends, it displays the scoreboard and asks if the player wants to play again.
- Game Execution :
- The game starts by calling
main()
if the script is run directly.
The game continues until the player decides to stop playing. The scores are updated and displayed after each game.