A classic 3x3 Tic-Tac-Toe game built in Python, featuring an unbeatable AI opponent powered by the Minimax algorithm. The game has a graphical interface built with Pygame, letting you play as X or O against the computer.
- Playable GUI built with Pygame
- Choose to play as X or O
- AI opponent that uses the Minimax algorithm to always play optimally (win or draw, never lose)
- "Play Again" option to restart the game after it ends
The project is split into two files:
-
tictactoe.py— Contains all the core game logic:initial_state()— sets up an empty boardplayer(board)— determines whose turn it isactions(board)— returns all valid movesresult(board, action)— returns the resulting board after a movewinner(board)— checks rows, columns, and diagonals for a winnerterminal(board)— checks if the game has endedutility(board)— scores a finished game (1 for X win, -1 for O win, 0 for tie)minimax(board)— recursively explores possible moves to find the optimal one
-
runner.py— Handles the graphical interface using Pygame:- Lets the user pick a side (X or O)
- Renders the board and handles click events for user moves
- Calls into
tictactoe.pyfor the AI's moves - Displays game status (whose turn it is, thinking state, win/tie) and a restart button
- Python 3
- Pygame
Install Pygame with:
pip install pygame- Clone the repository:
git clone https://github.com/testing-user-prog/TicTacToe.git cd TicTacToe - Make sure you have an
OpenSans-Regular.ttffont file in the project directory (used for rendering text in the game window). Add it if it's missing. - Run the game:
python runner.py
- Launch the game — you'll be prompted to choose to play as X or O.
- Click on an empty tile to make your move.
- The AI will respond automatically using the Minimax algorithm.
- The game announces a winner or a tie when it ends.
- Click "Play Again" to start a new round.
This project is open source and available for anyone to use or modify.