Contents
Figure 1: Minimax and Alpha-Beta Pruning Explained: Build a Tic-Tac-Toe AI — a retro gaming setup, the right frame of mind for a search that assumes the opponent is out to get you
Tic-tac-toe looks like a children's game, but it hides one of the most important ideas in AI: how to choose a move when an opponent fights back. The algorithm that solves it, minimax, also underlies chess engines, and a clever trick called alpha-beta pruning makes it practical. I will build both in Python, test the result against every possible opponent, and show exactly how much pruning saves. I ran all the code and numbers below.
The Setup: Two-Player Zero-Sum Games
Minimax applies to games with two players who alternate turns, where both see the whole board, and one player's gain is the other's loss. We call the players MAX (who wants a high score) and MIN (who wants a low one). In tic-tac-toe, X plays MAX and O plays MIN, and terminal positions get utilities: win (+1), loss (−1), draw (0).
The game tree shows every possible sequence of moves. At the start, X has nine options, then O has eight, and so on, so the branching factor shrinks by one each turn. That is why tic-tac-toe works as a teaching game: the whole tree fits in memory.
Minimax: Assume the Opponent Plays Well
The idea fits in one sentence: pick the move that gives you the best outcome, assuming your opponent always replies with the move that is worst for you. Algorithmically:
- If the game is over, return its score.
- If it is MAX's turn, return the maximum of the children's values.
- If it is MIN's turn, return the minimum of the children's values.
Here is the code I used. The board is a tuple of nine cells, and scores subtract depth so that earlier wins score higher:
LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def winner(b):
for i, j, k in LINES:
if b[i] != " " and b[i] == b[j] and b[i] == b[k]:
return b[i]
return None
def moves(b, order=range(9)):
return [i for i in order if b[i] == " "]
def play(b, i, p):
return b[:i] + (p,) + b[i+1:]
def turn(b):
return "X" if b.count("X") == b.count("O") else "O"
nodes = 0
def minimax(b, depth=0):
global nodes
nodes += 1
w = winner(b)
if w == "X": return 10 - depth
if w == "O": return depth - 10
if " " not in b: return 0
p = turn(b)
vals = [minimax(play(b, i, p), depth + 1) for i in moves(b)]
return max(vals) if p == "X" else min(vals)
nodes = 0
print(minimax((" ",) * 9), nodes) # 0 549946
Run it on the empty board, and the value comes out as 0: with perfect play from both sides, tic-tac-toe is a draw. Minimax visited 549,946 nodes to figure that out.
Why Tic-Tac-Toe Is Easy and Chess Isn't
Half a million nodes is trivial. Chess is not. A branching factor of about 35 and a game length of about 100 moves gives a search tree of roughly 10^154 nodes, against about 10^80 atoms in the observable universe. Minimax's time cost grows as O(b^d), so you cannot search chess to the end. That is where pruning and depth limits come in.
Alpha-Beta Pruning: Skip What Can't Matter
Alpha-beta keeps the same answer as minimax while skipping branches that cannot change the decision. It carries two numbers down the tree:
alpha: the best value MAX can already guarantee elsewhere.beta: the best value MIN can already guarantee elsewhere.
When alpha ≥ beta, the current branch cannot influence the final result, so you stop exploring it. Two facts sum up the guarantees: pruning does not affect the final result, and entire subtrees can be pruned. Here is the full implementation, including node counts for three move orders:
ORDER = (4, 0, 2, 6, 8, 1, 3, 5, 7) # center, corners, edges
def alphabeta(b, alpha, beta, depth=0, order=ORDER):
global nodes
nodes += 1
w = winner(b)
if w == "X": return 10 - depth
if w == "O": return depth - 10
if " " not in b: return 0
p = turn(b)
if p == "X":
v = -99
for i in moves(b, order):
v = max(v, alphabeta(play(b, i, p), alpha, beta, depth + 1, order))
alpha = max(alpha, v)
if alpha >= beta: break # MIN would never allow this line
return v
v = 99
for i in moves(b, order):
v = min(v, alphabeta(play(b, i, p), alpha, beta, depth + 1, order))
beta = min(beta, v)
if alpha >= beta: break # MAX already has something better
return v
def count(order):
global nodes
nodes = 0
value = alphabeta((" ",) * 9, -99, 99, 0, order)
return value, nodes
for name, order in [("natural", tuple(range(9))),
("edges first", (1, 3, 5, 7, 0, 2, 6, 8, 4)),
("center first", ORDER)]:
print(name, count(order))
The only new lines are the two break statements and the order parameter.
The Payoff: Counting Nodes
I counted nodes visited from the empty board with X to move:
| Search | Value | Nodes visited |
|---|---|---|
| Minimax | 0 | 549,946 |
| Alpha-beta, natural order | 0 | 20,866 |
| Alpha-beta, edges-first order | 0 | 46,965 |
| Alpha-beta, center-first order | 0 | 7,865 |
Every method returns the same value, but alpha-beta with a sensible move order visits about 70 times fewer nodes than plain minimax. Notice how much the move order matters, which brings us to the next point.
Move Ordering Is Everything
Alpha-beta prunes more when it examines the best moves first. With the worst ordering, alpha-beta effectively equals minimax with no pruning, while with perfect ordering the complexity drops to about O(b^(m/2)), roughly the square root of the branching factor. For chess, that is an effective branching factor of about 6 instead of 35, which lets alpha-beta look twice as deep in the same time.
I tried three orderings:
- Natural (squares 0 through 8): 20,866 nodes.
- Edges first: 46,965 nodes — worse than natural, because it delays the strong central lines.
- Center, then corners, then edges: 7,865 nodes.
The center-first order wins because the center and corners are the strongest squares, so the algorithm reaches good lines early and cuts off weaker ones sooner. Be aware that my "edges first" order is just a poor ordering, not the theoretical worst case.
IMO, move ordering is the single most important practical lever in game search. Real engines use killer moves, history tables, and the previous iteration's best move to order moves cleverly.
Remembering Positions: Transposition Tables
Different move sequences can reach the same board. Storing each position's value in a dictionary, called a transposition table, avoids re-searching it. In tic-tac-toe, the effect is dramatic. The full tree has 549,946 nodes, but the game has only 5,478 distinct reachable positions:
seen, stack = {(" ",) * 9}, [(" ",) * 9]
while stack:
b = stack.pop()
if winner(b) or " " not in b:
continue
p = turn(b)
for i in moves(b):
nb = play(b, i, p)
if nb not in seen:
seen.add(nb)
stack.append(nb)
print(len(seen)) # 5478
With memoization, minimax evaluates each position once, a hundredfold reduction in work. Transposition tables are widely reported to effectively double the search depth in bigger games, though I have not tested that claim myself.
Win Fast, Lose Slowly
Notice that my scores subtract the depth: a win at depth 3 scores 7, and a win at depth 5 scores 5. This prevents a subtle flaw. Without depth adjustment, an AI that sees a forced win might wander around, since every winning line scores the same.
Take this position, where X has X X _ / O O _ / _ _ _ and can win immediately at square 2. Running minimax on each legal move gives:
| Move | Value | Result |
|---|---|---|
| Square 2 | +5 | X wins now |
| Square 5 | 0 | blocks O, leads to a draw |
| Squares 6, 7, 8 | −4 | O wins next move |
The AI picks square 2, the immediate win. With depth-adjusted scoring, it prefers faster wins and, when losing, slower losses. The exact values depend on the formula: this position has four stones played, so a win on the next ply scores 10 - 5 = 5, and a loss one ply later scores 6 - 10 = -4.
Prove the AI Is Unbeatable
Testing a game AI by playing a few games proves little. For tic-tac-toe, you can test exhaustively. I let the AI play as each side against every possible opponent move sequence:
def best_move(b, order=ORDER):
p = turn(b)
best, choice = (-99 if p == "X" else 99), None
for i in moves(b, order):
v = alphabeta(play(b, i, p), -99, 99, 1)
if (p == "X" and v > best) or (p == "O" and v < best):
best, choice = v, i
return choice
def exhaustive(ai):
wins = draws = losses = 0
def rec(b):
nonlocal wins, draws, losses
w = winner(b)
if w or " " not in b:
if w == ai: wins += 1
elif w is None: draws += 1
else: losses += 1
return
p = turn(b)
if p == ai:
rec(play(b, best_move(b), p))
else:
for i in moves(b):
rec(play(b, i, p))
rec((" ",) * 9)
return wins, draws, losses
print("AI as X:", exhaustive("X")) # (82, 10, 0)
print("AI as O:", exhaustive("O")) # (368, 153, 0)
- AI as X vs all opponent strategies: 82 wins, 10 draws, 0 losses.
- AI as O vs all opponent strategies: 368 wins, 153 draws, 0 losses.
Zero losses in all cases. The counts reflect distinct opponent-choice lines in the tree, not separate games with equal probability. I also checked that alpha-beta gave the same value as plain minimax on all 5,478 reachable positions, with zero disagreements.
Then simulations, as sanity checks (random seed 7):
- AI (X) vs random (O), 2,000 games: 1,988 wins, 0 losses, 12 draws.
- Random vs random, 2,000 games: X wins 1,169, O wins 587, draws 244.
- AI vs AI, 200 games: 200 draws.
The AI never loses and wins almost every game against a random opponent. Two perfect players always draw, matching the game's theoretical value. FYI, random vs random shows how much the first-move advantage matters even without skill.
Playing Against It
A minimal game loop for a human against the AI looks like this. I wrote it for illustration and have not run this exact interactive version, so test it:
def show(b):
for r in range(3):
print(" | ".join(b[3*r:3*r+3]))
if r < 2: print("--+---+--")
def human_vs_ai(human="X"):
b = (" ",) * 9
while not winner(b) and " " in b:
show(b)
if turn(b) == human:
i = int(input("Your move (0-8): "))
if i not in moves(b): continue
else:
i = best_move(b)
b = play(b, i, turn(b))
show(b); print("Winner:", winner(b) or "draw")
Here best_move tries each legal move, scores it with alphabeta, and picks the best one for the current player.
Beyond Tic-Tac-Toe
Real games cannot be searched to the end, so engines modify the recipe:
- Depth-limited search with an evaluation function. Stop at a fixed depth and estimate the position's value with a heuristic. Shannon proposed this idea in 1950, and the evaluation function replaces the exact game result.
- Iterative deepening. Search depth 1, then 2, then 3, until time runs out, which also improves move ordering.
- Quiescence search. Keep searching "noisy" positions, such as mid-capture in chess, so the evaluation does not misjudge them.
- Negamax. A neater version of minimax for zero-sum games: negate the child values so you do not need separate max and min branches.
For games with enormous branching factors, like Go, researchers moved to Monte Carlo tree search instead. The AlphaGo self-play work is the famous example.
Common Pitfalls
- Forgetting to alternate maximizing and minimizing. The AI will play against itself.
- Ignoring depth in the score. The AI delays wins and may toy with drawing lines.
- Returning alpha-beta values and treating them as exact at pruned nodes. Pruned branches give bounds, not exact values.
- Bad move ordering. You lose most of the pruning benefit.
- Mutating the board without undoing. Use immutable boards, like my tuples, or undo moves carefully.
- Testing on a handful of games. Exhaustive checks catch rare bugs.
- Applying minimax to games with chance or hidden information. You need expectiminimax or other methods.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Artificial Intelligence: A Modern Approach (4th Edition) | Chapter 6 covers minimax, alpha-beta, evaluation functions, MCTS, stochastic games, and partially observable games, with pseudocode that maps directly onto the code above. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after you have made the node counts move. The chapter's treatment of move ordering and pruning is much easier to absorb once you have watched center-first search beat natural order on your own machine.
Wrapping Up
Minimax finds the best move against a perfect opponent by assuming they always pick the reply that is worst for you. Alpha-beta pruning returns the same answer while skipping branches that cannot matter, and move ordering decides how much it skips.
In my tic-tac-toe tests, plain minimax needed 549,946 nodes, alpha-beta with center-first ordering needed 7,865, and memoization showed that only 5,478 distinct positions exist. The resulting AI never lost in an exhaustive test. Copy the code, play against it, and try to beat it. You cannot, but you will learn a lot trying. Then change the move order and watch the node count move. What game will you solve next?
Frequently Asked Questions
What is minimax in simple terms?
Minimax chooses the move that maximizes your score while assuming the opponent always replies with the move that minimizes it. Terminal positions get utilities such as +1 for a win and -1 for a loss, and the value of a position is the best you can guarantee against perfect play.
How does alpha-beta pruning work?
Alpha-beta carries two bounds down the tree: alpha, the best value MAX already guarantees, and beta, the best value MIN already guarantees. When alpha is at least beta, the current branch cannot change the decision, so it is skipped. The final value is identical to plain minimax.
Why does move ordering matter in alpha-beta pruning?
Alpha-beta prunes more when strong moves are examined first, because good bounds appear sooner. With perfect ordering the effective branching factor drops to roughly the square root, which lets the search go about twice as deep in the same time. With the worst ordering, pruning gains nothing.
Can tic-tac-toe be solved by minimax?
Yes. The full game tree has 549,946 nodes and only 5,478 distinct reachable positions, so minimax can search it completely. A correct player never loses: in an exhaustive test against every opponent line it records zero losses whether it plays X or O.
What do real game engines add beyond minimax?
Depth-limited search with an evaluation function, iterative deepening, quiescence search, transposition tables, and negamax. Systems for huge branching factors such as Go moved to Monte Carlo tree search, which samples playouts instead of enumerating the tree.
Sources
[1]Russell and Norvig, Artificial Intelligence: A Modern Approach (4th edition) — minimax, alpha-beta, evaluation functions, MCTS, and stochastic games: aima.cs.berkeley.edu[2]Knuth and Moore, An Analysis of Alpha-Beta Pruning (1975) — the formal analysis of pruning, move ordering, and the O(b^(m/2)) bound: doi.org[3]Chess Programming Wiki, Alpha-Beta — practical pruning, fail-soft variants, and why move ordering dominates: chessprogramming.org[4]Chess Programming Wiki, Move Ordering — killer moves, history tables, and iterative-deepening ordering: chessprogramming.org[5]Silver et al., Mastering the Game of Go with Deep Neural Networks and Tree Search (2016) — Monte Carlo tree search combined with learned networks: nature.com
