Minimax game search
Minimax 博弈搜索
Solve every legal tic-tac-toe position, derive a guarantee against all replies, and keep score perspectives and cache keys consistent.
minimaxA move is only as safe as the reply it allows
Suppose a game offers two moves. After A, your opponent can leave you 3 or 8 points. After B, the opponent can leave you −2 or 11. You prefer more points; the opponent prefers you to have fewer. Choosing B because 11 is the largest number overlooks who makes the next choice. A guarantees 3; B guarantees only −2. Minimax compares those guarantees and chooses A.
The calculation alternates with the player: maximize your score on your turn, minimize that same score on the opponent’s turn. Keep the scoring perspective fixed. A negative number need not mean that the player whose turn it is is losing; it means a bad result for the player whose utility the number represents. The terminal-utility and alternating-backup rules are also presented in Berkeley CS188, section 3.2.
We will solve three-by-three tic-tac-toe. X moves first; players place one mark in an empty square on each turn. Three matching marks in a row, column or diagonal end the game immediately. A full board without a winner is a draw. Score every outcome from X’s perspective: X wins +1, a draw is 0, and O wins −1. X maximizes; O minimizes.
After X opens in a corner, O must take the center to preserve a draw against optimal play. The first board below shows why. Each empty square contains the value of the position after O plays there, including every possible subsequent reply. These are computed guarantees, not guesses about which square looks promising.
One score scale, two directions of choice
Large numbers in empty squares give X’s utility after that move and optimal replies: +1 for an X win, 0 for a draw, −1 for an O win.
O takes the minimum: square 4 preserves a draw.
X takes the maximum: square 2 wins now; square 5 only guarantees a draw.
The second board contains a different choice. X can win immediately at square 2. Blocking O at square 5 only guarantees a draw. A rule such as “always block a threat first” misses the winning move; searching the consequences distinguishes them.
Backward induction and a guarantee against every reply
The model here has two players with opposite preferences, a known deterministic transition rule, full observation of the state and alternating turns. Every play ends after finitely many moves. There are no dice, hidden cards or simultaneous actions. Let be the legal actions, the resulting state and X’s utility at a terminal state. Define
Evaluate a terminal state before asking for actions: a win ends the game even when empty squares remain. At any other state, the rules must supply at least one action. A pass, if allowed by a different game, is an action that needs explicit modeling. An empty list is not automatically a draw.
Why does this recurrence work? Use induction on the maximum number of moves remaining. At a terminal state the utility is known. Assume that each child’s value has already been established. At an X node, X can choose a child with the largest value, and the guarantees inside that child still apply. O cannot force anything smaller against that choice. Conversely, whatever child X selects, O has a continuation that keeps X’s outcome no larger than that child’s value, hence no larger than the maximum. The argument reverses at an O node. Finite depth supplies the base case and makes the induction valid.
A strategy specifies an action at every decision state where that player might need to act; it is more than a single predicted sequence. If is the terminal X utility under two strategies, the induction constructs strategies satisfying
When both follow those strategies, the outcome equals . From the empty tic-tac-toe board, the computed value is 0: either player can prevent a loss, and two optimal players draw. An opponent’s mistake can improve your outcome. It cannot defeat the guarantee of an exact optimal strategy under these rules. A value of 0 is not a 50% win probability and does not promise a win.
The recurrence needs one consistent utility scale, not a fresh sign convention at every layer. An alternative called negamax uses the current player’s perspective and negates each child’s value when the turn changes. Mixing negamax’s sign reversal with the fixed-X min/max recurrence would count the perspective change twice. The fixed-X code below makes no such sign reversal.
Solve a legal board, including the terminal cases
This complete Python 3.10+ program uses a nine-character string in row order. . means empty; X........ has X in the upper-left corner. Squares are numbered 0,1,2 across the first row, then 3,4,5 and 6,7,8. solve(board) returns (value_for_X, chosen_square). A terminal board returns its utility and None, since no move remains legal.
validate checks the alphabet, length, turn counts and winner/count consistency. For this exact three-by-three rule set, these conditions characterize reachable boards: the repository checks all strings against a separate graph generated only by legal moves that stop on a win. This finite verification does not establish that the same shortcut works for larger boards or other winning rules. It checks whether some legal history reaches the supplied board, not whether an unrecorded actual history respected the rules.
The internal outcome and _minimax helpers assume validated boards. Public callers use solve and play; neither mutates the supplied string. play rejects occupied squares, out-of-range indices, Boolean indices and attempts to continue a finished game.
Memoization stores the result for each board. For this game, turn counts determine whose move it is, no move removes a mark, and the future depends only on the board. Thus a board is a sufficient cache key. At equal values, the strict comparison keeps the smallest square index. This tie rule chooses a reproducible optimal move without claiming it is the only optimal move.
from functools import cache
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 winners(board):
return {board[a] for a, b, c in LINES
if board[a] != '.' and board[a] == board[b] == board[c]}
def validate(board):
if not isinstance(board, str) or len(board) != 9 or set(board) - set('.XO'):
raise ValueError('board must be a nine-character string using . X O')
x, o = board.count('X'), board.count('O')
won = winners(board)
if (x not in (o, o + 1) or len(won) > 1
or ('X' in won and x != o + 1) or ('O' in won and x != o)):
raise ValueError('board is not reachable under X-first, stop-on-win rules')
def outcome(board):
# Internal helper: board has already passed validate().
won = winners(board)
if won:
return 1 if 'X' in won else -1
return 0 if '.' not in board else None
@cache
def _minimax(board):
terminal = outcome(board)
if terminal is not None:
return terminal, None
player = 'X' if board.count('X') == board.count('O') else 'O'
best, chosen = (-2, None) if player == 'X' else (2, None)
for move, mark in enumerate(board):
if mark != '.':
continue
child = board[:move] + player + board[move + 1:]
value, _ = _minimax(child)
if (player == 'X' and value > best) or (player == 'O' and value < best):
best, chosen = value, move
return best, chosen
def solve(board):
validate(board)
return _minimax(board)
def play(board, move):
validate(board)
if outcome(board) is not None:
raise ValueError('the game has ended')
if type(move) is not int or not 0 <= move < 9 or board[move] != '.':
raise ValueError('move must name an empty square in 0..8')
player = 'X' if board.count('X') == board.count('O') else 'O'
return board[:move] + player + board[move + 1:]
_minimax.cache_clear()
print('empty:', solve('.........'))
print('distinct cached boards:', _minimax.cache_info().currsize)
print('O reply to X in corner:', solve('X........'))
board, moves = '.........', []
while outcome(board) is None:
_, move = solve(board)
moves.append(move)
board = play(board, move)
print('moves:', moves)
print('final:', board, outcome(board))
The output is:
empty: (0, 0)
distinct cached boards: 5478
O reply to X in corner: (0, 4)
moves: [0, 4, 1, 2, 6, 3, 5, 7, 8]
final: XXOOOXXOX 0
The root search examines every continuation because it has no pruning or depth cutoff. After clearing the cache, solving the empty board therefore stores every reachable board, including terminal boards. There are 5,478 distinct boards, without merging rotations or reflections: 4,520 nonterminal boards and 958 terminal boards. The latter comprise 626 X wins, 316 O wins and 16 draws.
The independent test builds positions with two bitmasks and works backward from more occupied boards to less occupied boards. It checks every value and selected action against the recursive program, as well as legality over all 19,683 board strings. Grouping the 5,478 reachable positions by their exact fixed-X values gives:
| Value | Meaning under optimal continuation | Positions |
|---|---|---|
| +1 | X can force a win | 2,936 |
| 0 | Both players can secure a draw | 1,068 |
| −1 | O can force a win | 1,474 |
These are counts of distinct positions, including terminals. They are not counts of complete games or win rates under random play. Multiple move orders can reach the same position; a distribution over games need not sample positions uniformly.
For a full tree with branching factor bounded by and maximum depth , ordinary minimax can visit nodes. With children generated one at a time, a recursive traversal needs stack frames, excluding state storage; eagerly saving all children can raise that to . Our code also stores a cache. If its reachable acyclic state graph has states and legal edges, each state is evaluated once and each edge consulted once, giving work under constant-cost state operations. Storing keys and results requires memory, plus the recursion stack. For strings of variable length , copying/hashing states and storing keys must be charged as well; a conservative bound is time and space. Here is fixed. The cached program is not an -space algorithm.
What changes when the model changes
Full search supplies exact values only when the rules and terminal utilities are correct and the search actually reaches terminal states. Replace the bottom of the tree with estimates and you solve that estimated tree. You have not automatically solved the original game. The evaluation-functions chapter constructs a small counterexample where an extra search layer makes the selected move worse.
For random outcomes with known conditional probabilities, use Expectimax to average utilities at chance nodes. Calling every non-optimal opponent “uniformly random” is an extra modeling assumption. With hidden information, a strategy must choose the same action at histories the player cannot distinguish; a separate full-information search of each hidden state can recommend an impossible contingent plan. With simultaneous actions or non-opposing payoffs, the simple alternating min/max model also needs replacement. The backward-induction guarantee above concerns the model we explicitly defined.
A repeated board may not always be the same state. A game can depend on whose turn it is, a repetition count, special move rights or a move clock. Omitting such information can merge positions with different futures. A depth-limited search also depends on remaining depth and the evaluation convention. Transposition tables must track the information needed by their particular search; the small board-only cache here is justified by tic-tac-toe’s rules.
Memoization alone does not resolve cycles. A function decorated with cache stores its answer after returning; a recursive call that revisits an unfinished state can recurse forever. Our game avoids this because every move fills one empty square. A cyclic game needs explicit draw/termination rules and a solver that handles them.
The utilities +1, 0 and −1 express outcome preference only. They do not reward faster wins, slower losses or an attractive-looking board. Any strictly increasing transformation applied consistently to all terminal values preserves min/max choices, because it preserves their ordering. A time preference needs an explicitly defined utility and state representation. Choosing arbitrary large “mate scores” in a partly heuristic engine creates additional scale and overflow questions; those are not properties of this exact three-outcome example.
Make a prediction before running the search
- A MAX root chooses between two MIN children with leaves
(3,8)and(-2,11). Compute the root value. Would maximizing at every layer solve the same game? - Inspect
XX.OO..... Which moves win, draw or lose under optimal continuation? Explain why terminal testing must come before trying O’s next move. - The empty board has value 0, and 626 reachable terminal boards are X wins. Can those facts determine X’s win probability against a random opponent? Specify what information is missing.
- Rotate the empty board by a quarter turn. Must the selected square rotate with it? Explain the difference between value invariance, the set of optimal moves and the program’s tie rule. Then name two rule changes that would invalidate a board-only cache.
Check your reasoning
-
Answer: The MIN values are 3 and −2, so the root value is 3. Maximizing at every layer returns 11, as if the opponent cooperated with MAX. A single favorable terminal path does not establish a strategy that can force it.
-
Answer: Square 2 wins (+1), square 5 draws (0), and squares 6, 7 and 8 lose (−1). At square 2, X completes the first row. The rules end the game immediately, even though O could complete its own row if incorrectly allowed another move.
solve('XXXOO....')must return(1,None);playmust reject a continuation. -
Answer: No. Specify which side is using which policy, how each random choice is distributed conditional on the history, and the starting position. Counted terminal boards have unequal numbers of histories leading to them and unequal probabilities under a policy. Minimax provides worst-case guarantees; it does not supply the missing probability model.
-
Answer: The board is unchanged by rotation, so the deterministic program still chooses square 0, even though rotating that square gives another corner. All nine opening moves have value 0; the optimal-move set is symmetric, but “smallest index” is not rotation-equivariant. Allowing either player to move next on the same board requires a turn key; making draws depend on repeated positions requires relevant history. Further changes such as special move rights can add state as well.
Compare conventions before comparing implementations
Read the terminal/max/min rules in CS188 section 3.2, then inspect minmax_decision in the pinned AIMA Python games module. AIMA fixes the utility perspective to the player at the root and makes that player MAX. This article fixes the perspective to X, so an O root is MIN. Both conventions can implement the same preferences. AIMA’s public function returns only an action; solve here also returns X’s value. To compare utility numbers inside the two implementations, first account for the perspective. The original flat-board code above was written for this article and uses memoization; it is not a copied AIMA implementation.
Continue with Alpha–Beta pruning to avoid inspecting branches that cannot change the decision. The browser experiment lets you change a leaf value and traversal order while comparing the root value with the amount of work. Run the Python program for the complete tic-tac-toe model. Those are different experiments: the browser tree teaches backup and pruning, while the program verifies an entire small game.
Make a prediction, then check
After X opens in a corner, the solver returns (0,4) for O. What does this establish?
Learning objectives
- Prove strategy guarantees by backward induction and distinguish a fixed utility perspective, mover, state value and win probability.
- Solve tic-tac-toe completely and verify legality, terminal priority, tied actions and the time and space costs of caching.
Prerequisites & connections
Explore related knowledge →References
- CS188 — 3.2 Minimax
University of California, Berkeley; CS188 course staff - AIMA Python: aima/games.py at f104e03
AIMA Python contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable examples, independent finite-game oracles, bilingual review and a second Codex agent cross-check; not independent human peer review.
- Eight checks passed: legality for all 19,683 boards against legal expansion; values and first best moves for all 5,478 positions against bitmask retrograde analysis; arbitrary opponent replies, terminal/input boundaries, 43,824 D4 value comparisons, every illustrated candidate, and paired code/formulas/anchors.
- Root authored and reread fixed-X scoring, finite-depth induction, existence of a legal history, cache keys and state-length costs. Cross-review identified that AIMA’s public interface returns only an action; both languages now explicitly distinguish its internal utility perspective.
- A second AI agent reread both complete articles: finite-depth induction, the two strategy guarantees against arbitrary replies, fixed-X versus negamax perspectives, an O root minimizing, reachability as existence of a legal history, cache-key sufficiency, conditional cached complexity, strictly increasing terminal transforms, all nine tied opening moves and D4 value symmetry are consistent. The parent corrected the identified AIMA public-API wording, and the peer reread and confirmed both revised paragraphs.
- Beyond the repository bitmask oracle, independently enumerated all9! move orderings, stopping on the first win or full board; its5478 positions exactly match validate’s accepted set over all19683 ternary strings. A separate mover-perspective W/L/D propagation verified every value and first-index optimal action. Counts4520/626/316/16 and2936/1474/1068 match. This extra check did not reuse the repository bitmask graph or its max/min oracle.
- Independently explored all legal opposing replies from the empty board against one fixed program strategy:185 states for fixed X end only in X wins or draws;786 states for fixed O end only in O wins or draws. All43824 D4 value comparisons passed. The non-loss statement is scoped to the empty-board rule model, not arbitrary positions already lost under optimal play.
- After the articles were written, reran all8 repository tests successfully; both Python blocks exactly match the temporary code previously checked independently. Also confirmed all nine opening child values are0, and tested two non-affine strictly increasing terminal maps on all5478 states, preserving transformed values and first optimal actions.
- Inspected MinimaxFigure.astro and minimax-illustration.json: every legal action value, selected square, X/O extremum direction, bilingual caption and aria label agrees with the full solution. This peer review covers data, component source and content; it does not claim browser visual QA, independent human peer review or reproduction of large game-system performance.
- All 79 search checks, 105 article Python programs and the prose scan passed. Migration-stage written-status notes describe that earlier phase; this record registers the checked files after source review and binds their current hashes. All reviews are AI technical checks, not independent human peer review.
- Static link checking found no published transposition-table article. Root reread both paragraphs and explicitly linked the directory entry labeled article pending. Cache-context claims and code are unchanged; hashes were updated after this actual correction.
- Desktop screenshot revealed unrendered emphasis delimiters in the Chinese opening. Replaced them with a strong tag, reread unchanged wording and meaning, and added static/browser regression checks for visible delimiters.
- After the transposition-table article was written and technically checked, root reread the context and replaced both pending-directory links with the formal article. Cache-identity claims, formulas and code are unchanged.
Source locations checked:
- CS188 — 3.2 Minimax · Read section 3.2, lines 87–111: terminal utilities, fixed utility perspective, alternating extrema and postorder evaluation. The authored tic-tac-toe model, induction, code, exact counts and diagrams were independently constructed and checked. Does not reuse the course game examples or unconditional claims about deeper search.
- AIMA Python: aima/games.py at f104e03 · Retrieved pinned raw file and verified SHA256. Read lines 20–41 minmax_decision, 283–314 Game and 427–478 TicTacToe. The root-player utility convention is correctly distinguished from fixed-X scoring. Public minmax_decision returns only an action; comparisons of values refer to its internal utilities. Original board/cache code here is not copied from AIMA.
- CS188 — 3.2 Minimax · Independently reopened and read §3.2, lines94–111, on known terminal utility and fixed-perspective alternating max/min; reviewed §3.2.2 lines127–139 for the limitation of cutoff estimates. The article correctly states its own fixed-X convention and does not borrow course branch-factor estimates or promise that deeper search always improves play.
- AIMA Python: aima/games.py at f104e03 · Independently inspected /tmp/aiwiki-aima-games-current.py lines20–43: captures game.to_move(state) as the fixed utility player, alternates max_value/min_value, checks terminals before children, and returns only an action from minmax_decision. Local file SHA25632466ac8925bcea48529d50be809a4fd26e9491f3e25aae4b98e0fa3389438f3. Peer web raw refresh returned cache miss; no peer remote-byte comparison claimed. Re-read the corrected bilingual research paragraph, which now distinguishes the action-only AIMA API from solve’s value/action tuple.
Related topics