Skip to content
Java project #16Intermediate

Tic-Tac-Toe with an Unbeatable AI

Play against a minimax AI with alpha-beta pruning that never loses, prefers quick wins, and reports how many positions it searched.

Estimated time
~5 hours to build
Files
6 files · 381 lines
Technologies
Java 21, Recursion, Arrays

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

Let a human (X) play repeated games against the computer (O), choosing who moves first each game. Validate moves (numbers 1–9 on free cells). The AI must never lose, should win as fast as possible and lose as slowly as possible when it can't win, and should choose deterministically among equal moves. Show the board after each move, the number of positions the AI searched, the result of each game and a final tally.

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

TextProject tree
tic-tac-toe-ai/
├── README.md
├── src/Ai.java
├── src/Board.java
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Ai.java

58 lines
Javasrc/Ai.java
/**
* An unbeatable tic-tac-toe player using minimax with alpha-beta pruning.
*
* Scores are from the AI's point of view: +10 - depth for a win (faster wins are better),
* depth - 10 for a loss (slower losses are better), 0 for a draw. Among equally good moves
* the lowest-numbered cell is chosen, so the AI is deterministic.
*/
public class Ai {
private final char me, opponent;
private int nodes;
public Ai(char me) {
this.me = me;
this.opponent = me == 'X' ? 'O' : 'X';
}
public int lastSearchNodes() { return nodes; }
public int bestMove(Board b) {
nodes = 0;
int best = -1, bestScore = Integer.MIN_VALUE;
for (int cell : b.freeCells()) {
b.place(cell, me);
int score = minimax(b, 1, false, Integer.MIN_VALUE, Integer.MAX_VALUE);
b.clear(cell);
if (score > bestScore) {
bestScore = score;
best = cell;
}
}
return best;
}
private int minimax(Board b, int depth, boolean myTurn, int alpha, int beta) {
nodes++;
char r = b.result();
if (r == me) return 10 - depth;
if (r == opponent) return depth - 10;
if (r == 'D') return 0;
int best = myTurn ? Integer.MIN_VALUE : Integer.MAX_VALUE;
for (int cell : b.freeCells()) {
b.place(cell, myTurn ? me : opponent);
int score = minimax(b, depth + 1, !myTurn, alpha, beta);
b.clear(cell);
if (myTurn) {
best = Math.max(best, score);
alpha = Math.max(alpha, score);
} else {
best = Math.min(best, score);
beta = Math.min(beta, score);
}
if (beta <= alpha) break; // the other player would never allow this line: prune it
}
return best;
}
}

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

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
New game - who goes first? (me/ai/quit): me
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Your move (1-9): 5
AI plays 1 (searched 8465 positions)
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Your move (1-9): 1
That cell isn't available.
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Your move (1-9): x
Type a number from 1 to 9.
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Your move (1-9): 9
AI plays 3 (searched 491 positions)
O | 2 | O
---+---+---
4 | X | 6
---+---+---
7 | 8 | X
Your move (1-9): 2
AI plays 8 (searched 44 positions)
O | X | O
---+---+---
4 | X | 6
---+---+---
7 | O | X
Your move (1-9): 4
AI plays 6 (searched 4 positions)
O | X | O
---+---+---
X | X | O
---+---+---
7 | O | X
Your move (1-9): 7
O | X | O
---+---+---
X | X | O
---+---+---
X | O | X
It's a draw.
New game - who goes first? (me/ai/quit): ai
AI plays 1 (searched 34202 positions)
O | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Your move (1-9): 2
AI plays 4 (searched 2765 positions)
O | X | 3
---+---+---
O | 5 | 6
---+---+---
7 | 8 | 9
Your move (1-9): 3
AI plays 7 (searched 78 positions)
O | X | X
---+---+---
O | 5 | 6
---+---+---
O | 8 | 9
The AI wins.
New game - who goes first? (me/ai/quit): maybe
Please answer me, ai or quit.
New game - who goes first? (me/ai/quit): quit
Games: 2 You: 0 AI: 1 Draws: 1
Input
me
5
1
x
9
2
4
7
ai
2
3
maybe
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/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

  1. 1Measure how many nodes pruning saves for every first move.
  2. 2Let two AIs play each other and verify every game is a draw.
  3. 3Implement Connect Four with depth-limited minimax.

Built and tested it yourself? Mark it to update your dashboard.