Algorithms · Visualized
Game Theory & Minimax
Game Theory & Minimax
Two-player games — who wins with perfect play, and by how much.
Big-O: Winning positions, DP over states, and minimax evaluation.
Game Theory & Minimax
Positions, optimal play and the mathematics of taking the last stone.
Combinatorial game theory classifies positions of perfect-information games with no chance. For impartial games (both players have identical moves, like Nim), each position is winning (N-position: the mover can force a win) or losing (P-position: every move hands the opponent a win). The recursive rule: a position is winning iff some move leads to a losing position. Nim has a closed form — XOR all pile sizes; a zero XOR is losing with perfect play — which generalizes via the Sprague–Grundy theorem: every impartial game is equivalent to a Nim pile of size grundy(position), computed as the mex of the options. Adversarial two-player games with different move sets (chess-like) are searched with minimax: MAX maximizes the score, MIN minimizes, and alpha–beta pruning skips branches that cannot influence the root decision.
The general recipe
- Define the position (piles, board, score) and whose turn it is.
- Classify terminal positions — the mover with no move usually loses (normal play).
- Apply the recursion: winning iff ∃ move to a losing position; memoize by position.
- For Nim-like games, compute the XOR (Grundy) value instead of exploring all positions.
- For adversarial scoring games, run minimax over the game tree with alpha–beta pruning to search deeper.
Vocabulary you'll meet everywhere here
- N / P positions
- Next-player-win versus Previous-player-win under optimal play
- Nim-sum
- XOR of pile sizes; zero means the position is losing for the mover
- Grundy value
- mex of the options’ Grundy values — the position’s Nim-equivalent pile size
- mex
- minimum excluded non-negative integer of a set
- Minimax + alpha–beta
- adversarial search maximizing your best case while pruning provably irrelevant branches
Where this family shows up
- Puzzle games: stone piles, coin rows, subtraction games
- Game AI: tic-tac-toe, connect-four engines via minimax/alpha–beta
- Strategy analysis: “who wins with perfect play?” answers for interview brainteasers
Common pitfalls
- Wrong terminal convention (misère play inverts winning/losing positions)
- Exploring exponential game trees without memoization or alpha–beta cutoffs
- Forgetting the opponent also plays optimally — greedy self-play is not minimax
- Applying the Nim XOR to games that are not sums of independent piles
def nim_game(piles):
xor_all = 0
for p in piles:
xor_all ^= p
# first player wins unless xor of all piles is 0
return xor_all != 0Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.