TicTacToe Class
TheTicTacToe class manages the game board state, move validation, and win condition checking for a 3x3 Tic-Tac-Toe game.
Constructor
__init__()
Initializes a new Tic-Tac-Toe game with an empty board.
Returns: None
board: List of 9 strings representing the game board (indices 0-8)current_winner: String (‘X’ or ‘O’) if there’s a winner, otherwiseNone
Methods
print_board()
Displays the current state of the game board in a formatted grid.
Parameters: None
Returns: None (prints to console)
This method prints the board with the current moves (‘X’, ‘O’, or empty spaces).
print_board_nums()
Displays a reference board showing the position numbers (0-8) for each square.
Parameters: None
Returns: None (prints to console)
This static method helps players understand which number corresponds to which board position.
available_moves()
Returns a list of all empty positions on the board.
Parameters: None
Returns: list[int] - List of indices (0-8) where moves can be made
empty_squares()
Checks if there are any empty squares remaining on the board.
Parameters: None
Returns: bool - True if there are empty squares, False otherwise
num_empty_squares()
Counts the number of empty squares on the board.
Parameters: None
Returns: int - Number of empty squares (0-9)
make_move(square, letter)
Attempts to place a letter (‘X’ or ‘O’) at the specified square.
The board position (0-8) where the move should be made
The player’s letter (‘X’ or ‘O’)
bool - True if the move was successful, False if the square is occupied
This method automatically checks for a winner after each move and updates
current_winner if applicable.winner(square, letter)
Checks if the move at the specified square creates a winning condition.
The board position (0-8) where the last move was made
The player’s letter (‘X’ or ‘O’) to check for a win
bool - True if the move creates three in a row, False otherwise
Win Condition Logic
Win Condition Logic
The method checks three possible win conditions:
- Row: All three squares in the same row match the letter
- Column: All three squares in the same column match the letter
- Diagonal: All three squares in either diagonal match the letter (only checked for even-numbered squares: 0, 2, 4, 6, 8)
play() Function
The main game loop that manages turn-taking and game flow.An instance of the TicTacToe class
Player instance for ‘X’ (can be HumanPlayer, RandomComputerPlayer, or GeniusComputerPlayer)
Player instance for ‘O’ (can be HumanPlayer, RandomComputerPlayer, or GeniusComputerPlayer)
Whether to print the game board and moves to the console
str | None - The winning letter (‘X’ or ‘O’) if there’s a winner, None for a tie
Usage Example
The play() function includes a 0.8 second delay between moves for better user experience.