Introduction
Tic-tac-toe is small enough to search completely, which makes it the perfect introduction to game-tree search. The computer player tries every possible future and never loses.
Problem statement
Objectives
- Represent a board compactly as a string
- Detect wins with a table of lines
- Implement recursive minimax
- Speed up recursion with functools.lru_cache
Features
- Two-player and versus-computer modes
- Input validation for cells
- Win and draw detection
- Unbeatable minimax opponent
- Score across games
Concepts demonstrated
- Game-tree search
- Minimax
- Memoisation
- Immutable state as strings
System architecture
The board is a 9-character string, which is immutable and hashable, so minimax can be cached with lru_cache. winner checks the eight lines in LINES. minimax returns the best (score, move) for the player to move: +1 if O can force a win, −1 if X can, 0 for a draw. play runs one game and main handles the menu and score.
Folder structure
Complete source code
main.py
What each file does
- main.py
- Board helpers, the cached minimax search, the game loop and the menu.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
3 1 1 5 2 4 3 2 5 1 9 2 4 7 q
Testing
- Run
python main.py < tests/sample-input.txtand compare withtests/expected-output.txt. - Menu choice 3 is rejected; in the two-player game X wins with cells 1, 2 and 3 after a taken-cell error.
- Against the computer, X opens in the centre, the computer answers in a corner and blocks every threat.
- The second game ends in a draw and the final score is X 1, O 0, draws 1.
Common errors
The computer is very slow
Cache minimax results (the board is a string, so lru_cache works) to avoid re-searching positions.
Moves overwrite taken cells
Check board[move] before placing a mark.
Possible improvements
- Add an easy mode that sometimes plays randomly
- Let the computer play X as well
- Generalise to 4×4 with depth-limited search
Additional challenges
- 1Count how many positions minimax evaluates with and without the cache.
- 2Add alpha-beta pruning.
- 3Show the computer's evaluation of every free cell.
Built and tested it yourself? Mark it to update your dashboard.