Introduction
Tic-tac-toe is small enough to search completely, which makes it the perfect introduction to game-tree search. The minimax algorithm assumes both players play perfectly; alpha-beta pruning skips branches that can't affect the decision, cutting the work dramatically.
Problem statement
Objectives
- Implement minimax recursively
- Add alpha-beta pruning and measure its effect
- Separate the board model, the AI and the game loop
- Score terminal positions to prefer faster wins
Features
- Perfect play: the AI never loses
- Depth-aware scores (quick wins, slow losses)
- Node counts show the cost of search
- Choice of who goes first; tally of results
Concepts demonstrated
- Game trees
- Minimax
- Alpha-beta pruning
- Separation of concerns
- Determinism
System architecture
Board stores nine cells in a char array and reports the result using the eight winning lines. Ai.bestMove tries each free cell, evaluates it with minimax, and keeps the first best score (so ties go to the lowest cell). minimax returns 10 − depth for an AI win, depth − 10 for a loss and 0 for a draw, maximising on the AI's turns and minimising on the human's; alpha and beta track the best guaranteed scores and the loop stops when beta <= alpha. Main runs games and keeps the tally.
Folder structure
Complete source code
src/Ai.java
What each file does
- src/Board.java
- Board state, winner detection and drawing.
- src/Ai.java
- Minimax with alpha-beta pruning and node counting.
- src/Main.java
- The game loop, input validation and the tally.
How to run it
Compile
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.
me 5 1 x 9 2 4 7 ai 2 3 maybe quit
Testing
- Run with
tests/sample-input.txtand compare withtests/expected-output.txt. - Game 1 ends in a draw even though the human starts in the centre.
- In game 2 the AI starts, the human makes a mistake, and the AI wins on its fourth move.
- The AI's first move with an empty board searches 34,202 positions with pruning, compared with 549,945 without it.
Common errors
The AI plays a slow win or ignores an immediate win
Subtract the depth from winning scores so faster wins score higher.
The board is corrupted after the AI thinks
Undo every trial move (clear the cell) after evaluating it.
Possible improvements
- Add difficulty levels that sometimes play a random move
- Support a 4×4 board with a depth limit
- Cache evaluated positions in a HashMap (transposition table)
Additional challenges
- 1Measure how many nodes pruning saves for every first move.
- 2Let two AIs play each other and verify every game is a draw.
- 3Implement Connect Four with depth-limited minimax.
Built and tested it yourself? Mark it to update your dashboard.