TicTacToe is a classic two-player game where opponents take turns marking the spaces of a three-by-three grid, one playing as X and the other as O.
This implementation uses an algorithm called Minimax. In the hardest mode, the AI evaluates every possible move to determine the best outcome, always aiming for a win or, at worst, a draw.
How does MINIMAX work? You can learn more about how the Minimax algorithm is applied to TicTacToe in this article.
- Clone the repository and navigate into it:
$ git clone https://github.com/vicnetto/TicTacToeWithAI
$ cd TicTacToeWithAI
- Then, just run the Python file:
$ python main.py
When you start the program, the first line displayed will be:
Input Command >
The available commands are start and exit. Here’s what they do:
- start <user/easy/medium/hard> <user/easy/medium/hard>:
This command starts the game. The two arguments that follow represent the X and O players, respectively. You can choose from four types of players: user, easy, medium, and hard.- user – A human player. An input is necessary for each move.
- easy – The simplest AI level. The computer makes random moves without any strategy.
- medium – A more challenging AI. In this mode, the computer checks two conditions before making a move:
- If it can win in the next move.
- If the opponent can win in their next move.
If neither condition is true, it makes a random move (like in easy mode).
- hard – This level is impossible to beat. It uses the Minimax algorithm, which evaluates all possible moves for both players and chooses the one that guarantees a win or, at worst, a draw.
- exit: Exits the game.
Example: To start a game between a user and the hard AI, enter:
Input Command > start user hard # If you want to be the "O" player, insert: start hard user
--------- # -------------------
| | # | 1 3 | 2 3 | 3 3 |
| | # | 1 2 | 2 2 | 3 2 | < Positions numbers!
| | # | 1 1 | 2 1 | 3 1 |
--------- # -------------------
Enter the coordinates: > 1 1
---------
| |
| |
| X |
---------
Making move level "hard"
---------
| |
| O |
| X |
---------
Enter the coordinates: >