Module contents
Lesson 5 of 23Core 100 min

Zero-sum games: minimax and alpha-beta pruning

Deterministic two-player perfect-information games can in principle be solved with minimax. Alpha-beta returns the same value while exploring roughly the square root of the nodes with good ordering. Prove correctness, derive Knuth and Moore’s analysis and build a Connect 4 player on bitboards.

After this lesson you can

  • Formalize a perfect-information zero-sum game and compute its value with minimax and negamax.
  • Prove alpha-beta correctness and interpret returns outside the window as bounds.
  • Derive Knuth and Moore’s minimal-tree leaf count and estimate reachable depth.
  • Implement a bitboard Connect 4 player with negamax, alpha-beta and move ordering.
  • Empirically verify the effect of ordering on effective branching factor.

Before you start

Searching when someone searches against you

So far in this module the world stood still: a state-space search problem has one agent choosing every action. In a two-player game an opponent with exactly the opposite objective chooses half the actions. You no longer seek a path to a goal: you seek a strategy, a rule telling you what to do in every possible position and working against any response.

In 1950 Claude Shannon published “Programming a computer for playing chess,” the foundational text of game programming. His starting point is that chess, like any finite game of this kind, has an exact solution in principle: traverse the tree of all possible games from leaves upward. His conclusion is that this solution is unattainable: with about 30 legal moves in a typical position and games of around 40 moves per side, he estimated on the order of 1012010^{120} distinct games. Hence his two proposals: search only to a fixed depth and evaluate positions there with an approximate function (his “type A strategy”), or examine only plausible moves (type B). Seventy years later, the strongest chess engines follow the first line with two refinements this lesson builds from scratch:

  1. Minimax, the algorithm computing a game’s value by traversing its tree, and its compact version, negamax.
  2. Alpha-beta pruning, which computes exactly the same value while ignoring branches that cannot affect the result. With good move ordering it explores on the order of the square root of the nodes, doubling reachable depth at the same budget.

The lesson proves alpha-beta’s correctness, derives Knuth and Moore’s (1975) analysis of exactly how much it prunes, and ends with a Connect 4 player on bitboards whose node counters verify the theory. It is also the starting point for what follows: the next lesson’s game engine, Monte Carlo Tree Search, and later AlphaZero, which replaces handcrafted evaluation and ordering with trained networks.

Start with a game you can solve completely in your browser.

InteractiveTic-tac-toe oracle
  • +1: player to move wins
  • 0: draw
  • −1: loses
  • mm / αβ: nodes without pruning / with alpha-beta
Mode
You play as
Value for X (to move)0
Minimax nodes from here549 946
Alpha-beta nodes from here18 297
Ratio30.1 times fewer
X to move. With perfect play by both, the game is drawn.
Each empty cell shows the value of playing there for the player to move, with perfect play by both afterward: +1+1 wins, 00 draws, −1-1 loses. Below are nodes visited for that move without pruning (mm) and with alpha-beta (αβ), traversing cells in fixed order 0 to 8. From the empty board every cell is worth 0: perfect play always draws. Play the computer, deliberately make a mistake and see −1-1 appear; switch to ‘Place pieces’ to build positions and check who wins.

Three things the oracle shows and the lesson explains:

  1. A position’s value is well defined. It does not depend on how anyone plays: it is the outcome if both play perfectly from there. From the empty board it is 0.
  2. Computing it without pruning costs the whole tree. From the empty board minimax visits 549 946 nodes, one per legal game prefix.
  3. Alpha-beta gives the same values with far fewer nodes, increasingly so with better move ordering.

Perfect-information zero-sum games

Each word excludes something. Two players: no coalitions. Zero-sum: one player’s gain is the other’s loss, so one number per leaf suffices; if utilities did not sum to a constant, analysis would require Nash equilibria (see extensive-form games). Deterministic: transitions contain no randomness; backgammon with dice needs expectiminimax. Perfect information: both see the entire position; poker does not satisfy this. Chess, checkers, Go, Connect 4 and tic-tac-toe do satisfy all conditions (with a rule ending infinite games, such as chess’s threefold repetition or fifty-move rule).

The difference between the tree and position graph already matters. The same board is reached by many different move orders (a transposition), so the tree repeats entire subtrees. Tic-tac-toe has 5 478 reachable legal positions but its tree has 549 946 nodes. This lesson’s algorithms traverse the tree, like the first lesson’s depth-first search; exploiting transpositions with a transposition table is the next lesson’s topic.

A game’s value and Zermelo’s theorem

A MAX strategy is a function assigning a move to every position where MAX is to play; likewise for MIN. A strategy pair (σ,τ)(\sigma, \tau) determines a complete game and thus a utility u(σ,τ)u(\sigma, \tau).

Proof

Define V(s)V(s) for each tree node by structural induction from the leaves:

V(s)={u(s)s∈T,max⁡a∈A(s)V(res(s,a))turno(s)=MAX,min⁡a∈A(s)V(res(s,a))turno(s)=MIN.V(s) = \begin{cases} u(s) & s \in T, \\ \max_{a \in A(s)} V(\text{res}(s, a)) & \text{turno}(s) = \text{MAX}, \\ \min_{a \in A(s)} V(\text{res}(s, a)) & \text{turno}(s) = \text{MIN}. \end{cases}

This is well-defined because the tree is finite: all games terminate and each position has finitely many moves, so by König’s lemma the tree has bounded depth and recursion always reaches leaves. Let σ∗\sigma^* be MAX’s strategy choosing a maximizing move at each MAX node, and τ∗\tau^* MIN’s strategy choosing a minimizing move. Prove by induction on node ss height that, from ss, σ∗\sigma^* guarantees at least V(s)V(s) against any τ\tau. At a leaf this is the definition. If MAX moves, σ∗\sigma^* goes to a child s′s' with V(s′)=V(s)V(s') = V(s) and, by induction, from s′s' gets at least V(s′)V(s'). If MIN moves, any child s′s' chosen by τ\tau satisfies V(s′)≥min⁡=V(s)V(s') \ge \min = V(s), and from it σ∗\sigma^* gets at least V(s′)≥V(s)V(s') \ge V(s). The symmetric claim for τ∗\tau^* is identical with maxima replaced by minima. With V=V(s0)V = V(s_0) both inequalities follow. For the last sentence, take utilities +1+1, 00 and −1-1: if V=1V = 1 MAX wins, if V=−1V = -1 MIN wins, and if V=0V = 0 each can force at least a draw.

∎

The proof is an algorithm: backward induction, which reappears in dynamic programming for Markov decision processes. It also says something worth remembering: optimal strategy is optimal only against an optimal opponent. If the opponent errs, σ∗\sigma^* still guarantees VV, but may not exploit the mistake as much as another strategy. Minimax does not model its opponent: it assumes perfection.

Minimax and negamax

If each internal node has bb children and all leaves are at depth dd, minimax evaluates bdb^d leaves and visits 1+b+⋯+bd=(bd+1−1)/(b−1)1 + b + \cdots + b^d = (b^{d+1} - 1)/(b - 1) nodes. Its memory is depth-first search’s: the current branch and, if moves are generated one by one, O(d)\bigO(d) positions; O(bd)\bigO(bd) if every level’s moves are generated at once.

Writing two cases, one for MAX and one for MIN, doubles code and errors. Identity max⁡(a,b)=−min⁡(−a,−b)\max(a, b) = -\min(-a, -b) permits one case if each node scores from the perspective of the player to move.

The check takes one line. If MAX moves, the child belongs to MIN and −N(s′)=V(s′)-N(s') = V(s'), so N(s)=max⁡V(s′)=V(s)N(s) = \max V(s') = V(s). If MIN moves, −N(s′)=−V(s′)-N(s') = -V(s') and N(s)=max⁡(−V(s′))=−min⁡V(s′)=−V(s)N(s) = \max(-V(s')) = -\min V(s') = -V(s). Both agree with color(s)V(s)\text{color}(s)V(s). Negamax requires alternating turns (or, if they do not alternate, changing sign only when the player changes) and zero-sum utility.

[ ]Minimax and negamax on an explicit treeBrowser
import math

# un nodo es una lista de hijos; cualquier otra cosa es una hoja con la utilidad de MAX
arbol = [[[[19, 12], [8, 11]], [[14, 20], [18, 1]]],
         [[[16, 13], [16, 3]], [[5, 18], [7, 4]]]]

def minimax(nodo, juega_max=True):
    if not isinstance(nodo, list):
        return nodo
    valores = [minimax(h, not juega_max) for h in nodo]
    return max(valores) if juega_max else min(valores)

def negamax(nodo, color=1):
    """Valor para el jugador al turno: color = +1 si juega MAX, -1 si juega MIN."""
    if not isinstance(nodo, list):
        return color * nodo
    return max(-negamax(h, -color) for h in nodo)

print("minimax:", minimax(arbol), "  negamax:", negamax(arbol))

# negamax devuelve color * V en cada nodo: en un hijo de la raíz (le toca a MIN), el signo cambia
print("primer hijo:", minimax(arbol[0], juega_max=False), "  negamax del primer hijo:", negamax(arbol[0], color=-1))

def contar_hojas(nodo):
    return 1 if not isinstance(nodo, list) else sum(contar_hojas(h) for h in nodo)
print("hojas que evalúa minimax:", contar_hojas(arbol))

The cell’s tree is the alpha-beta figure’s, coming shortly: binary, depth 4 and value 12.

Limited depth and evaluation function

In real games the full tree is unreachable, so do what Shannon proposed: cut search at depth dd and replace leaf utility with an evaluation function eval(s)\text{eval}(s) estimating V(s)V(s) (or in negamax, N(s)N(s): value for the player to move). Recursion is unchanged with one extra base case: if remaining depth is 0, return eval(s)\text{eval}(s).

The algorithm now computes not the game’s value but the limited-search minimax value, only as good as the evaluation. Two known pathologies: the horizon effect (an unavoidable disaster is pushed beyond depth dd by delaying moves, so search misses it), and evaluation of volatile positions such as the middle of a chess piece exchange, which quiescence search handles by extending those branches. Designing the evaluation function and iterative deepening with a clock belong to the next lesson. Here it suffices to know negamax evaluation must be relative to the player to move: this is the easiest mistake to make and hardest to see (you will check it in exercises).

Alpha-beta: skip what cannot matter

Look at the previous cell’s tree. The root is MAX; its first child, MIN, is worth 12. When search enters the second child, also MIN, MAX has already guaranteed 12. Suppose inside the second child MIN finds a response leaving MAX 10 or less. Then that child is worth at most 10 to MAX, who will never choose it: the remaining branches of that child no longer matter. They can be pruned.

To make this systematic, each call receives a window (α,β)(\alpha, \beta):

  • α\alpha is the best MAX has already guaranteed somewhere on the path from the root;
  • β\beta is the best (lowest) MIN has guaranteed on the path.

While exploring a node, only values strictly between α\alpha and β\beta matter: if the node is worth ≤α\le \alpha, MAX will avoid it higher up; if ≥β\ge \beta, MIN will avoid it. As soon as a MIN node finds a child worth ≤α\le \alpha (or a MAX node one worth ≥β\ge \beta), remaining children are irrelevant: a cutoff.

In negamax the window changes sign and order when descending a level. The parent seeks values vv with α<v<β\alpha < v < \beta; since v=−N(s′)v = -N(s'), the child seeks N(s′)N(s') with −β<N(s′)<−α-\beta < N(s') < -\alpha. The entire algorithm is then:

funcioˊn AB(s,d,α,β):si s∈T o d=0: devuelve eval(s)(o color(s) u(s) si es terminal)m←−∞para cada a∈A(s):v←−AB(res(s,a),d−1,−β,−α)si v>m: m←vα←max⁡(α,m)si α≥β: sal del bucle(corte)devuelve m\begin{aligned} &\textbf{función } \text{AB}(s, d, \alpha, \beta): \\ &\quad \textbf{si } s \in T \text{ o } d = 0: \ \textbf{devuelve } \text{eval}(s) \quad \text{(o } \text{color}(s)\,u(s) \text{ si es terminal)} \\ &\quad m \leftarrow -\infty \\ &\quad \textbf{para cada } a \in A(s): \\ &\qquad v \leftarrow -\text{AB}(\text{res}(s, a), d - 1, -\beta, -\alpha) \\ &\qquad \textbf{si } v > m: \ m \leftarrow v \\ &\qquad \alpha \leftarrow \max(\alpha, m) \\ &\qquad \textbf{si } \alpha \ge \beta: \ \textbf{sal del bucle} \quad \text{(corte)} \\ &\quad \textbf{devuelve } m \end{aligned}
InteractiveAlpha-beta step by step
1212≤712≥1413≤712≤8≥1413≤3≤5≤719128111420181161316351874[12, +∞]
step 43 / 43
  • MAX (▲)
  • MIN (▼)
  • evaluated leaf
  • cutoff: crossed branch (×) and descendants are not evaluated
  • active node window [α, β]
Child order
Returned value
0
Leaves evaluated so far11 of 11 (of 16)
Root value12
Leaves: original · best · worst11 · 7 · 16
Knuth and Moore minimum, 22+22−12^2 + 2^2 - 17
The root returns 12 (exact value).
The previous cell's tree, with MAX (▲) at the root. Initially the traversal is finished: red crosses mark pruned branches and text explains each cutoff; return to step 1 and advance to see them constructed. The active node shows its [α,β][\alpha, \beta] window; resolved nodes show returns, with ≤\le or ≥\ge when only a bound. Find the two deep cutoffs in the right branch, whose α=12\alpha = 12 comes from the root three levels above. Then press ‘Best first’, ‘Worst first’ and ‘Shuffle’: evaluated leaves change but the root value does not. Click a leaf and change its value to see cutoffs appear or disappear.

Two details are visible step by step. First, α\alpha or β\beta can come from far above: in the right branch’s deep cutoff, a MIN node at depth 3 cuts off because the root, three levels above, already guaranteed 12. A version comparing each node only to its parent (what Knuth and Moore call without deep cutoffs) would lose these prunings. Second, values returned by pruned nodes below are not their minimax values: MIN 2.2.1 (path from root: second child, second child, first child) returns “≤ 5,” and its true value could be lower. This does not spoil the root result, exactly as the correctness theorem states.

Correctness: exact values inside the window, bounds outside

The proof is structural induction: at each node use the hypothesis for children with the windows they receive, distinguishing three cases: the loop cuts off, finishes without exceeding α\alpha, or finishes with a value inside the window. You will do it step by step in the final guided exercise. For now retain the lemma making pruning safe: if a node already has a child giving m≥βm \ge \beta, unexplored children can only raise the maximum, so the node is worth at least mm, all its parent needs to discard it.

Fail-hard and fail-soft

The theorem concerns the version returning mm, the best value found even outside the window. Another widespread version clips the result to the window.

Both prune exactly the same branches because they pass the same windows to children; only their failure returns differ. Fail-soft returns a tighter bound: if it fails low with m<αm < \alpha, you know N(s)≤mN(s) \le m, more informative than N(s)≤αN(s) \le \alpha. As long as only the full-window root value is used, the difference is invisible. It becomes visible when a result is reused: stored in a transposition table for another search with a different window, or when a narrow-window search is repeated and adjusted according to failure (next lesson’s aspiration windows and null-window search).

InteractiveWindows and bounds
αβ02040608099fail-soft: 62fail-hard: 40
  • true value V
  • fail-soft and what it reveals about V
  • fail-hard and what it reveals about V
  • window (α, β)
Leaves needed for null window (α,α+1)(\alpha, \alpha + 1) by α\alpha; the vertical line marks VV
  • null window
  • full window
20
40
True root value VV74
fail-soft returns62 (lower bound)
fail-hard returns40 (lower bound)
Leaves evaluated with this window13 of 243
With full window82 of 243
Fail-high: all you know is V≥62V \ge 62 (fail-soft) or V≥40V \ge 40 (fail-hard). The fail-soft bound is tighter.
A uniform tree with b=3b = 3, d=5d = 5 and 243 integer leaves from 0 to 99. Move α\alpha and β\beta: the diamond is true value VV; points are fail-soft (magenta) and fail-hard (orange) returns; each bar shows what that value reveals about VV. With initial window (20,40)(20, 40) the search fails high: fail-hard says only V≥40V \ge 40, fail-soft gives a better bound. Move the window to both sides of VV. Below is the cost of a null window (α,α+1)(\alpha, \alpha + 1) for each α\alpha: any question like ‘V>αV > \alpha?’ costs a fraction of computing VV.

The lower curve anticipates an idea engines exploit: a null window never returns an exact value (with integers, V≤αV \le \alpha or V≥α+1V \ge \alpha + 1), but answers a yes/no question with far fewer leaves than a full window. Principal variation search searches the first move with a full window and checks the rest with null windows.

How much alpha-beta prunes: Knuth and Moore’s analysis

Alpha-beta never evaluates more leaves than minimax, but how many fewer? Entirely dependent on child exploration order. At worst it may prune nothing. At best, Knuth and Moore (1975) gave the exact answer. To state it, number each node’s children 1,…,b1, \dots, b in exploration order and name each node by its path from the root, a1a2⋯aℓa_1 a_2 \cdots a_\ell with aj∈{1,…,b}a_j \in \{1, \dots, b\}.

Counting critical leaves is direct. Those with aj=1a_j = 1 in every odd position vary only in the ⌊d/2⌋\lfloor d/2 \rfloor even positions: b⌊d/2⌋b^{\lfloor d/2 \rfloor}. Those with aj=1a_j = 1 in every even position vary in the ⌈d/2⌉\lceil d/2 \rceil odd positions: b⌈d/2⌉b^{\lceil d/2 \rceil}. Only leaf 11⋯111\cdots1 belongs to both groups. To see why alpha-beta evaluates exactly these leaves, it is more instructive to classify nodes.

Three node types and a recurrence

With perfect order and distinct values, every alpha-beta visited node is one of three types (in modern engine terminology PV, CUT and ALL nodes):

  • Type 1 (PV). Called with a window containing its value. Its first child, the best, is type 1 and returns the exact value, which becomes the new α\alpha. Other children are strictly worse and therefore fail: type 2. The root is type 1.
  • Type 2 (CUT). Its value exceeds β\beta (from its perspective). Its first and best child already proves this: the node cuts off after that single child, which is type 3.
  • Type 3 (ALL). Its value is below α\alpha. To prove it, all children must be seen to be bad: it explores every child without cutoff, each type 2.

If Lt(d)L_t(d) is the number of leaves alpha-beta evaluates under a node of type tt with remaining depth dd, with Lt(0)=1L_t(0) = 1, the three types give a system of linear recurrences:

L1(d)=L1(d−1)+(b−1) L2(d−1),L2(d)=L3(d−1),L3(d)=b L2(d−1).L_1(d) = L_1(d-1) + (b - 1)\,L_2(d-1), \qquad L_2(d) = L_3(d - 1), \qquad L_3(d) = b\,L_2(d - 1).
L2(d)=b L2(d−2)L_2(d) = b\,L_2(d-2)
The last two equations combine, L₂(d) = L₃(d − 1) = b L₂(d − 2): a CUT node has one ALL child, which has b CUT children. Initial conditions: L₂(0) = 1 y L₂(1) = L₃(0) = 1.
1/6

This is a nonhomogeneous recurrence solved by expansion, matching the critical-leaf count: the PV node at depth dd is the root, and leaves under type 2 and 3 nodes are exactly the critical ones.

Why nobody can do better

The lower bound is the theorem’s most beautiful part because it concerns any algorithm, not just alpha-beta. A MAX strategy viewed as a subtree chooses one child at every MAX node and retains all children at every MIN node; it has b⌊d/2⌋b^{\lfloor d/2 \rfloor} leaves because there are ⌊d/2⌋\lfloor d/2 \rfloor MIN levels above leaves. A MIN strategy conversely has b⌈d/2⌉b^{\lceil d/2 \rceil}. By minimax recursion,

V=max⁡σ min⁡ℓ∈hojas(σ)u(ℓ),V = \max_{\sigma} \ \min_{\ell \in \text{hojas}(\sigma)} u(\ell),

the value is the best MAX can guarantee with some strategy.

Proof

Suppose a deterministic algorithm returns VV after evaluating leaf set SS. If no MAX strategy has all its leaves in SS, change every leaf outside SS to a number less than VV. The algorithm never looked at them, so behaves identically and returns VV again. But now every MAX strategy contains a leaf worth less than VV, and by the preceding formula the new value is below VV: the algorithm is wrong. Thus SS contains every leaf of some MAX strategy σ\sigma, and by the symmetric argument (raising unseen leaves above VV), all leaves of some MIN strategy τ\tau. A MAX and MIN strategy share exactly one leaf: the game played when both follow them (at each MAX node the path is forced by σ\sigma, at each MIN node by τ\tau). Therefore ∣S∣≥∣σ∣+∣τ∣−1=b⌊d/2⌋+b⌈d/2⌉−1\abs{S} \ge \abs{\sigma} + \abs{\tau} - 1 = b^{\lfloor d/2 \rfloor} + b^{\lceil d/2 \rceil} - 1.

∎

With perfect order, alpha-beta evaluates exactly the union of one MAX strategy (nodes with aj=1a_j = 1 in MAX positions) and one MIN strategy: it is optimal. Two qualifications. The bound requires leaves to take any value; if utility is bounded (in tic-tac-toe ±1\pm 1), an algorithm finding +1+1 can stop immediately; alpha-beta does so when given the utility range (−1,1)(-1, 1) as initial window instead of (−∞,+∞)(-\infty, +\infty), and can then fall below L(b,d)L(b, d). The argument holds for each particular tree, including ties: any algorithm correct for arbitrary real leaves, alpha-beta included, evaluates at least L(b,d)L(b, d) leaves in any uniform tree. Distinct values ensure that perfect order evaluates exactly critical leaves; with ties the α≥β\alpha \ge \beta cutoff can change which are evaluated but cannot go below the bound.

Random order and worst order

With worst possible order, alpha-beta may prune nothing: trees exist (for example, worst child first with strictly improving values at each node) where it evaluates all bdb^d leaves. The intermediate case, random child order, is difficult. Knuth and Moore bounded it; Pearl (1982) solved it for uniform trees with independent identically distributed leaves from a continuous distribution: expected leaf count grows as Rb dR_b^{\,d}, with

Rb=ξb1−ξb,ξb la raıˊz positiva de xb+x−1=0,R_b = \frac{\xi_b}{1 - \xi_b}, \qquad \xi_b \text{ la raíz positiva de } x^b + x - 1 = 0,

and proved no directional algorithm (examining leaves left to right) can improve that rate. For b=2b = 2, ξ2=(5−1)/2\xi_2 = (\sqrt5 - 1)/2 and R2R_2 is the golden ratio 1.6181.618. For usual bb, RbR_b resembles b3/4b^{3/4}, Russell and Norvig’s rule for “moderate bb”; as b→∞b \to \infty, RbR_b grows as b/ln⁡bb / \ln b, so the comparison with b3/4b^{3/4} no longer holds for enormous bb.

InteractiveHow much alpha-beta prunes
  • minimax: bdb^d
  • random order, measured
  • rule b3d/4b^{3d/4}
  • perfect order: b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2\rceil} + b^{\lfloor d/2\rfloor} - 1
  • budget
Random order: mean alpha-beta over 13 to 16 uniform trees (more when cheaper) with iid uniform leaves in [0,1)[0, 1), measured in your browser up to d=7d = 7.
8
1e6
Depth with minimax6
With alpha-beta and perfect order12
With random order (b3d/4b^{3d/4} rule)8
Measured exponent, log⁡b(leaves)/d\log_b(\text{leaves})/d0.790 (d = 7)
Measured slope in last levels0.730
Pearl, log⁡bRb\log_b R_b (asymptotic)0.702
With 10⁶ leaves, perfect order reaches depth 12 versus 6 for minimax: 2.00 times deeper.
Leaves evaluated versus depth, logarithmic scale: minimax (bdb^d), alpha-beta with perfect order (Knuth and Moore's formula), and alpha-beta with random order, measured in your browser on uniform trees with iid uniform leaves. The horizontal line is the budget. With b=8b = 8 and 10610^6 leaves, minimax reaches depth 6 and perfect order 12: twice as deep. Move bb and the budget: the ratio stays near 2 for any bb. Compare the measured random-order slope with Pearl's asymptotic exponent: at these depths the measurement is somewhat higher and decreases slowly toward it.

The practical consequence is the statement opening the lesson. With a budget of NN leaves, minimax reaches d≈log⁡bNd \approx \log_b N; alpha-beta with perfect order d≈2log⁡bNd \approx 2\log_b N; with random order d≈43log⁡bNd \approx \tfrac{4}{3}\log_b N. Everything gained from good move ordering turns into depth.

Move ordering

Perfect order requires knowing each child’s value, exactly what is being computed. Move ordering is a set of heuristics cheaply approximating it: try likely best moves first so cutoffs occur early. By the three-node-type theory, what matters is choosing the first move well: at a CUT node one cutting child suffices and the others’ order is irrelevant.

  • Domain knowledge. In chess, captures first, ordered by most valuable victim and least valuable attacker; in Connect 4, central columns, which participate in more four-lines. These static rules learn nothing during search.
  • Killer moves. A move causing a cutoff at a node of a certain depth often refutes its siblings too: if the opponent did something irrelevant, the same threat still works. Store one or two killers per depth and try them just after domain rules.
  • History heuristic (Schaeffer, 1983 and 1989). A table indexed by move (in Connect 4, the cell where the piece lands) accumulates weight, typically d2d^2 or 2d2^d, whenever that move causes a cutoff with remaining depth dd. It generalizes killers across the tree.
  • Iterative deepening as oracle. Search to depth 1,2,…,d1, 2, \dots, d, as in the first lesson’s iterative deepening, and each iteration try first the best move the previous one found at that position. Previous iterations are cheap (in a tree with effective branching b∗b^*, together they cost at most a factor b∗/(b∗−1)b^*/(b^* - 1) of the last) and ordering information usually more than repays them. Engines store this in the transposition table; here use a simple dictionary.

Lab: a Connect 4 player on bitboards

Connect 4 is played on a board 7 columns by 6 rows; each move drops a piece into a column and the first to align four horizontally, vertically or diagonally wins. It has branching factor at most 7 and at most 42 moves: small enough for Python experiments and large enough for pruning to matter.

The board in two integers

This representation is used by fast solvers (John Tromp’s Fhourstones and Pascal Pons’s solver): each column occupies 7 bits, 6 for cells and one guard above, so the cell at column cc and row ff (from the bottom) is bit 7c+f7c + f. Position is stored in two integers: actual, the player-to-move pieces, and mascara, all pieces. Opponent pieces are actual ^ mascara.

  • Play in column cc: mascara + abajo(c) adds 1 at the column’s lowest bit and carry rises to the first free cell, so mascara | (mascara + abajo(c)) adds the new piece. Before that, actual ^= mascara changes player: the next player is the opponent, whose pieces are the old mask’s pieces that did not belong to the mover.
  • Detect four in a row: m = p & (p >> s) marks cells whose neighbor in direction ss also belongs to the player, and m & (m >> 2*s) is nonzero if four are consecutive. Directions are s=1s = 1 (vertical), 7 (horizontal), 6 and 8 (both diagonals). The guard bit prevents a line crossing from one column into the next.
[ ]Connect 4 in two integersBrowser
W, H = 7, 6                      # columnas y filas
H1 = H + 1                       # bits por columna: 6 casillas y un bit de guarda
ABAJO = [1 << (c * H1) for c in range(W)]
ARRIBA = [1 << (H - 1 + c * H1) for c in range(W)]
COLUMNA = [((1 << H) - 1) << (c * H1) for c in range(W)]
FONDO = sum(ABAJO)               # la fila de abajo entera
TABLERO = FONDO * ((1 << H) - 1) # las 42 casillas

def alineado(p):
    """¿Tiene el conjunto de fichas p cuatro en línea?"""
    for s in (1, H1, H, H + 2):          # vertical, horizontal y las dos diagonales
        m = p & (p >> s)
        if m & (m >> (2 * s)):
            return True
    return False

def jugar(actual, mascara, c):
    """Ficha en la columna c. Devuelve la posición vista por el siguiente jugador."""
    return actual ^ mascara, mascara | (mascara + ABAJO[c])

def desde_cadena(jugadas):
    """Posición tras una cadena de columnas numeradas de 1 a 7, como '4453'."""
    actual = mascara = 0
    for ch in jugadas:
        actual, mascara = jugar(actual, mascara, int(ch) - 1)
    return actual, mascara, len(jugadas)

def dibujar(actual, mascara, n):
    x, o = (actual, actual ^ mascara) if n % 2 == 0 else (actual ^ mascara, actual)
    filas = []
    for f in range(H - 1, -1, -1):
        filas.append(" ".join("X" if x >> (c * H1 + f) & 1 else "O" if o >> (c * H1 + f) & 1 else "." for c in range(W)))
    return "\n".join(filas) + "\n1 2 3 4 5 6 7"

a, m, n = desde_cadena("4453354")
print(dibujar(a, m, n))
print("bits ocupados:", bin(m).count("1"), "  ¿cuatro del que acaba de mover?", alineado(a ^ m))
a, m, n = desde_cadena("4455667")        # X juega 4, 5, 6 y 7 en la fila de abajo
print("\n" + dibujar(a, m, n))
print("¿cuatro del que acaba de mover?", alineado(a ^ m))

Search needs one more thing: knowing which empty cells would complete a four-line for the player. Function amenazas calculates this for all 42 cells at once using similar shifts: for each direction it finds three consecutive own pieces with a gap at an end or in the middle. Then “the player to move wins in one move” is amenazas(actual, mascara) & (mascara + FONDO) & TABLERO because mascara + FONDO marks each column’s playable cell. It also serves as evaluation: own threats minus opponent threats, plus a small bonus for center-column pieces. Notice evaluation uses actual, the player-to-move pieces: negamax requires this.

[ ]Negamax with alpha-beta for Connect 4Browser
import time

CENTRO = COLUMNA[3]
GANA = 1000                            # ganar en la jugada n vale GANA - n: mejor cuanto antes

def amenazas(p, mascara):
    """Casillas vacías donde p completaría cuatro en línea."""
    r = (p << 1) & (p << 2) & (p << 3)                 # vertical: tres debajo
    for s in (H1, H, H + 2):
        q = (p << s) & (p << 2 * s)
        r |= q & (p << 3 * s)                          # tres a un lado
        r |= q & (p >> s)                              # dos a un lado y una al otro
        q = (p >> s) & (p >> 2 * s)
        r |= q & (p << s)
        r |= q & (p >> 3 * s)
    return r & (TABLERO ^ mascara)

def evaluar(actual, mascara):
    """Estimación para el jugador AL TURNO (requisito de negamax)."""
    rival = actual ^ mascara
    return (3 * (amenazas(actual, mascara).bit_count() - amenazas(rival, mascara).bit_count())
            + (actual & CENTRO).bit_count() - (rival & CENTRO).bit_count())

class Busqueda:
    """Negamax con alfa-beta fail-soft, contador de nodos y ordenación configurable."""
    def __init__(self, orden=(3, 2, 4, 1, 5, 0, 6), poda=True, asesinas=False, historia=False, iterativa=False):
        self.base, self.poda = orden, poda
        self.usar_asesinas, self.usar_historia, self.iterativa = asesinas, historia, iterativa
        self.nodos = self.hojas = self.victorias = 0          # victorias: nodos cerrados por ganar ya
        self.asesina = [[-1, -1] for _ in range(W * H + 1)]   # dos por profundidad
        self.hist = {}                                        # (columna, casilla) -> peso
        self.mejor = {}                                       # posición -> mejor columna (iterativa)

    def ordenar(self, actual, mascara, n):
        cols = [c for c in self.base if not mascara & ARRIBA[c]]
        primero = []
        if self.iterativa and (actual, mascara) in self.mejor:
            primero.append(self.mejor[(actual, mascara)])
        if self.usar_asesinas:
            primero += [c for c in self.asesina[n] if c in cols and c not in primero]
        resto = [c for c in cols if c not in primero]
        if self.usar_historia:          # sort es estable: a igual peso, se respeta el orden base
            resto.sort(key=lambda c: -self.hist.get((c, (mascara + ABAJO[c]) & COLUMNA[c]), 0))
        return primero + resto

    def negamax(self, actual, mascara, n, d, alfa, beta):
        self.nodos += 1
        if n == W * H:
            return 0                                          # tablero lleno: tablas
        mias = amenazas(actual, mascara)
        if mias & (mascara + FONDO) & TABLERO:
            self.victorias += 1
            return GANA - n                                   # gana en esta jugada
        if d == 0:
            self.hojas += 1
            return evaluar(actual, mascara)
        mejor, mj = -10**9, -1
        for c in self.ordenar(actual, mascara, n):
            v = -self.negamax(actual ^ mascara, mascara | (mascara + ABAJO[c]), n + 1, d - 1, -beta, -alfa)
            if v > mejor:
                mejor, mj = v, c
                if v > alfa:
                    alfa = v
                    if self.poda and alfa >= beta:            # corte
                        if self.usar_asesinas:
                            k = self.asesina[n]
                            if k[0] != c:
                                k[1], k[0] = k[0], c
                        if self.usar_historia:
                            clave = (c, (mascara + ABAJO[c]) & COLUMNA[c])
                            self.hist[clave] = self.hist.get(clave, 0) + d * d
                        break
        if self.iterativa:
            self.mejor[(actual, mascara)] = mj
        return mejor

    def buscar(self, actual, mascara, n, d):
        if self.iterativa:                                    # 1, 2, ..., d; se cuentan todos los nodos
            for dd in range(1, d + 1):
                v = self.negamax(actual, mascara, n, dd, -10**9, 10**9)
            return v
        return self.negamax(actual, mascara, n, d, -10**9, 10**9)

print(" d   valor sin poda   valor con poda   nodos sin poda   nodos con poda")
for d in range(1, 6):
    s, p = Busqueda(poda=False), Busqueda()
    vs, vp = s.buscar(0, 0, 0, d), p.buscar(0, 0, 0, d)
    print(f"{d:2d}   {vs:14d}   {vp:14d}   {s.nodos:14d}   {p.nodos:14d}")

Values with and without pruning agree at each depth, as correctness requires, and the node difference is already large at depth 5. At depth 8 unpruned minimax is too slow in pure Python for the browser, but its nodes can be counted without traversing the tree: count game prefixes of length up to 8 (cutting off at immediate wins) using dynamic programming on positions, because two paths reaching the same position have the same subtree below. The cell first checks the count against actual depth-5 search.

[ ]Depth 8: with and without pruningBrowser
from functools import lru_cache

@lru_cache(maxsize=None)
def nodos_sin_poda(actual, mascara, n, d):
    """Nodos que visita negamax sin poda desde esta posición a profundidad d (cuenta caminos, no posiciones)."""
    if n == W * H or d == 0 or amenazas(actual, mascara) & (mascara + FONDO) & TABLERO:
        return 1
    return 1 + sum(nodos_sin_poda(actual ^ mascara, mascara | (mascara + ABAJO[c]), n + 1, d - 1)
                   for c in range(W) if not mascara & ARRIBA[c])

s = Busqueda(poda=False); s.buscar(0, 0, 0, 5)
print("profundidad 5: búsqueda real", s.nodos, "  recuento", nodos_sin_poda(0, 0, 0, 5))

def b_efectivo(N, d):
    """b* con N = 1 + b* + ... + b*^d (N nodos visitados, raíz incluida)."""
    lo, hi = 1.0, 50.0
    for _ in range(60):
        m = (lo + hi) / 2
        lo, hi = (m, hi) if sum(m ** k for k in range(d + 1)) < N else (lo, m)
    return lo

d = 8
N0 = nodos_sin_poda(0, 0, 0, d)
uniforme = sum(7 ** k for k in range(d + 1))
minimo = sum(7 ** -(-k // 2) + 7 ** (k // 2) - 1 for k in range(d + 1))
print(f"\nprofundidad {d} desde el tablero vacío")
print(f"  sin poda:             {N0:9d} nodos   (árbol uniforme con b = 7: {uniforme}; b* = {b_efectivo(N0, d):.2f})")
for nombre, orden in (("izquierda a derecha", (0, 1, 2, 3, 4, 5, 6)), ("centro primero", (3, 2, 4, 1, 5, 0, 6))):
    t = time.perf_counter()
    B = Busqueda(orden=orden)
    v = B.buscar(0, 0, 0, d)
    print(f"  alfa-beta, {nombre:20s} {B.nodos:7d} nodos ({B.hojas} hojas), valor {v}, b* = {b_efectivo(B.nodos, d):.2f}, "
          f"{N0 / B.nodos:.0f} veces menos que sin poda")
    print(f"      de ellos, {B.victorias} cerrados sin hijos porque el jugador al turno gana en una jugada")
print(f"  árbol mínimo de Knuth y Moore para b = 7, d = 8: {7**4 + 7**4 - 1} hojas y {minimo} nodos")

The numbers tell the previous sections’ story. Without pruning, depth-8 search from the empty board visits 5 784 535 nodes; fewer than the uniform tree’s 6 725 601 with b=7b = 7, because search stops at immediate wins. Alpha-beta with columns left to right drops to 130 793 nodes (44 times fewer), and center first to 6 760: about 856 times fewer than unpruned and even below the 8 793 nodes in a uniform tree’s minimal tree with b=7b = 7. This does not contradict Knuth and Moore because this tree is not uniform: 2 367 of those 6 760 nodes are positions where the player to move wins in one move, and search closes them without generating children. A MAX or MIN strategy passing through them has far fewer leaves than in a uniform tree, and Knuth and Moore’s lower bound applied here is lower. (Evaluation ties explain nothing: the lower bound holds with ties too.) The comparison does show that “center first” puts alpha-beta on the scale of the best possible case. Effective branching factor, defined as in A* but using visited nodes, changes from 6.87 without pruning to 4.22 with blind order and 2.85 center first.

Endgames solved to completion

With few empty cells evaluation is unnecessary: search reaches terminal positions and the value is the exact game value. The cell’s five positions were obtained by dropping random seeded pieces until 28 or 30 cells were filled, discarding those with an immediate win. Value and unpruned tree size are computed by dynamic programming over positions with minimax’s recursion; the two smallest are also checked with real unpruned search.

[ ]Endgames solved to completionBrowser
@lru_cache(maxsize=None)
def exacto(actual, mascara, n):
    """(valor negamax exacto, nodos del árbol sin poda) hasta el final de la partida."""
    if n == W * H:
        return 0, 1
    if amenazas(actual, mascara) & (mascara + FONDO) & TABLERO:
        return GANA - n, 1
    mejor, total = -10**9, 1
    for c in range(W):
        if not mascara & ARRIBA[c]:
            v, k = exacto(actual ^ mascara, mascara | (mascara + ABAJO[c]), n + 1)
            mejor, total = max(mejor, -v), total + k
    return mejor, total

def resultado(v, n):
    """v = ±(GANA - k): la ficha ganadora es la número k + 1 de la partida."""
    if v == 0:
        return "tablas"
    return f"gana quien juega (ficha {GANA - v + 1})" if v > 0 else f"pierde quien juega (ficha {GANA + v + 1})"

finales = ["674663213275455554564176631114", "367236127366152334636747724111", "217467121661732222574475153166",
           "3743423277752562255311577561", "7661763454661773323322652757"]
for f in finales:
    a, m, n = desde_cadena(f)
    v_exacto, N = exacto(a, m, n)
    B = Busqueda()
    v = B.buscar(a, m, n, W * H - n)
    print(f"{n} fichas: {resultado(v, n):34s} sin poda {N:7d} nodos, alfa-beta {B.nodos:5d} "
          f"({N / B.nodos:5.0f} veces menos), mismo valor: {v == v_exacto}")

for f in finales[1:3]:
    a, m, n = desde_cadena(f)
    s = Busqueda(poda=False)
    v = s.buscar(a, m, n, W * H - n)
    print("comprobación con la búsqueda sin poda real:", s.nodos == exacto(a, m, n)[1], v == exacto(a, m, n)[0])

An endgame value is of the form “the player to move wins with the game’s 33rd piece”: score 1000−k1000 - k, where kk is the number of pieces just before the winning move, rewards winning earlier and penalizes losing early, so alpha-beta must establish not just who wins but in how many moves. Even so, it prunes by factors of 12 to 129 compared with the complete tree, always returning the same value.

The effect of ordering

Now the lesson’s goal: measure each ordering heuristic’s contribution. Compare six configurations on eight opening and middlegame positions (6 to 14 pieces, also seeded random and without immediate wins), at depth 7: blind left-to-right order, that order with killers and history, with iterative deepening, with all three, center order, and center with killers and history. Iterative deepening counts nodes in all iterations.

[ ]Move ordering: nodes and effective branching factorBrowser
import random, statistics

def posiciones_aleatorias(k, semilla=7):
    rnd, out = random.Random(semilla), []
    while len(out) < k:
        a = m = 0; jugadas = ""; ok = True
        for _ in range(rnd.randint(6, 14)):
            c = rnd.choice([c for c in range(W) if not m & ARRIBA[c]])
            if alineado(a | ((m + ABAJO[c]) & COLUMNA[c])):
                ok = False; break
            a, m = jugar(a, m, c); jugadas += str(c + 1)
        gana_ya = lambda p: any(not m & ARRIBA[c] and alineado(p | ((m + ABAJO[c]) & COLUMNA[c])) for c in range(W))
        if ok and not gana_ya(a) and not gana_ya(a ^ m):
            out.append(jugadas)
    return out

def medir(configuraciones, posiciones, d=7):
    for nombre, kw in configuraciones.items():
        nodos, valores = [], []
        for p in posiciones:
            a, m, n = desde_cadena(p)
            B = Busqueda(**kw)
            valores.append(B.buscar(a, m, n, d))
            nodos.append(B.nodos)
        g = statistics.geometric_mean(nodos)
        print(f"{nombre:34s} media geométrica {g:7.0f} nodos   b* = {b_efectivo(g, d):.2f}   valores {valores}")

IZQ = (0, 1, 2, 3, 4, 5, 6)
posiciones = posiciones_aleatorias(8)
print("posiciones:", posiciones)
medir({
    "izquierda a derecha":              dict(orden=IZQ),
    "izq. + asesinas + historia":       dict(orden=IZQ, asesinas=True, historia=True),
    "izq. + iterativa":                 dict(orden=IZQ, iterativa=True),
}, posiciones)

The second half of the comparison, in another cell so each fits the browser time budget:

[ ]Move ordering: more configurationsBrowser
medir({
    "izq. + iterativa + asesinas + h.": dict(orden=IZQ, iterativa=True, asesinas=True, historia=True),
    "centro primero":                   dict(),
    "centro + asesinas + historia":     dict(asesinas=True, historia=True),
}, posiciones)

All six configurations give the same values on all eight positions (ordering changes cost, not result), and node counts change greatly:

  • With blind order, the geometric mean is about 18 000 nodes and b∗≈3.9b^* \approx 3.9.
  • Killers and history, knowing nothing about Connect 4, divide it by 3.1 (about 5 800 nodes); iterative deepening alone by 2.6 (about 6 900, paying for six previous iterations); together by 3.7 (about 4 900).
  • Center order, which knows something about the game, is best: about 4 600 nodes and b∗≈3.2b^* \approx 3.2. Adding killers and history barely changes anything (about 4 570): the domain rule almost always picks the first move correctly, and history sometimes errs when contradicting it.

The lesson is general. Dynamic heuristics (killers, history, iterative deepening) recover most losses from poor static order, but do not beat good domain knowledge. Real engines combine layers: first the transposition-table move (in practice the previous iteration’s best), then domain and killer moves, and history to order the rest.

Empirical verification of Knuth and Moore’s analysis

Theory makes three testable predictions: alpha-beta and minimax always give the same value; with perfect order leaves are exactly L(b,d)L(b, d); with random order the growth exponent lies between 1/21/2 and 11, near Pearl’s. First, agreement on trees with ties (integer leaves between −5-5 and 55), where implementation errors appear.

[ ]Alpha-beta and minimax always agreeBrowser
import numpy as np

def minimax_uniforme(hojas, b, d):
    v = hojas
    for k in range(d - 1, -1, -1):            # de abajo arriba; la raíz (k = 0) es MAX
        v = v.reshape(-1, b)
        v = v.max(axis=1) if k % 2 == 0 else v.min(axis=1)
    return v[0]

def alfabeta_uniforme(hojas, b, d):
    """Alfa-beta (forma MAX/MIN, fail-soft) en un árbol uniforme dado por sus hojas. Devuelve (valor, hojas evaluadas)."""
    cuenta = 0
    def ab(i, k, alfa, beta):
        nonlocal cuenta
        if k == d:
            cuenta += 1
            return hojas[i]
        if k % 2 == 0:
            v = -np.inf
            for j in range(b):
                v = max(v, ab(i * b + j, k + 1, alfa, beta))
                alfa = max(alfa, v)
                if alfa >= beta:
                    break
        else:
            v = np.inf
            for j in range(b):
                v = min(v, ab(i * b + j, k + 1, alfa, beta))
                beta = min(beta, v)
                if alfa >= beta:
                    break
        return v
    return ab(0, 0, -np.inf, np.inf), cuenta

rng = np.random.default_rng(0)
fallos, ahorro = 0, []
for _ in range(400):
    b, d = int(rng.integers(2, 6)), int(rng.integers(1, 7))
    hojas = rng.integers(-5, 6, size=b ** d)
    v, k = alfabeta_uniforme(hojas.tolist(), b, d)
    fallos += v != minimax_uniforme(hojas, b, d)
    ahorro.append(k / b ** d)
print("árboles con valor distinto:", fallos, "de 400")
print(f"fracción media de hojas evaluadas: {np.mean(ahorro):.3f}")

Now exponents. For b=3b = 3 and d=2,…,10d = 2, \dots, 10, generate trees with leaves uniform on [0,1)[0, 1) (distinct values with probability 1). Perfect order is constructed by sorting each node’s children by exact minimax value bottom up; “worst” is the reverse (worst child first at each node); random is the order in which leaves are generated.

[ ]Exponents: perfect, random and worst orderBrowser
def reordenar(hojas, b, d, mejor_primero=True):
    """Reordena los hijos de cada nodo por su valor minimax: el mejor (o el peor) para quien juega, primero."""
    x = hojas.copy()
    for k in range(d - 1, -1, -1):
        v = x
        for kk in range(d - 1, k, -1):        # valores de los nodos de profundidad k + 1
            v = v.reshape(-1, b)
            v = v.max(axis=1) if kk % 2 == 0 else v.min(axis=1)
        hijos = v.reshape(-1, b)
        descendente = (k % 2 == 0) == mejor_primero
        orden = np.argsort(-hijos if descendente else hijos, axis=1, kind="stable")
        x = np.take_along_axis(x.reshape(-1, b, b ** (d - k - 1)), orden[:, :, None], axis=1).reshape(-1)
    return x

def L(b, d):
    return b ** -(-d // 2) + b ** (d // 2) - 1

b = 3
rng = np.random.default_rng(1)
filas = []
print(" d   L(b,d)  perfecto  aleatorio (media de 10)  pésimo    b^d")
for d in range(2, 11):
    alea, perf, pes = [], None, None
    for r in range(10):
        h = rng.random(b ** d)
        alea.append(alfabeta_uniforme(h.tolist(), b, d)[1])
        if r == 0:
            vp, perf = alfabeta_uniforme(reordenar(h, b, d, True).tolist(), b, d)
            vq, pes = alfabeta_uniforme(reordenar(h, b, d, False).tolist(), b, d)
            assert vp == vq == minimax_uniforme(h, b, d)
    filas.append((d, perf, np.mean(alea), pes))
    print(f"{d:2d}  {L(b, d):6d}  {perf:8d}  {np.mean(alea):23.1f}  {pes:6d}  {b ** d:6d}")

ds = np.array([f[0] for f in filas])
for j, nombre in ((1, "perfecto"), (2, "aleatorio"), (3, "pésimo")):
    y = np.log(np.array([f[j] for f in filas], dtype=float)) / np.log(b)
    pend = np.polyfit(ds, y, 1)[0]
    pend2 = np.polyfit(ds[-5:], y[-5:], 1)[0]
    print(f"{nombre:10s} pendiente de log_b(hojas) frente a d: {pend:.3f} (d = 2..10), {pend2:.3f} (d = 6..10)")

def R(b):
    lo, hi = 0.0, 1.0
    for _ in range(80):
        x = (lo + hi) / 2
        lo, hi = (x, hi) if x ** b + x - 1 < 0 else (lo, x)
    return x / (1 - x)
print("\n  b    R_b    log_b R_b   b^(3/4)   b/ln b")
for bb in (2, 3, 5, 8, 10, 20, 30, 40, 1000):
    print(f"{bb:4d}  {R(bb):6.3f}  {np.log(R(bb)) / np.log(bb):8.3f}  {bb ** 0.75:8.2f}  {bb / np.log(bb):7.2f}")

The results:

  • Perfect order. Leaves match L(3,d)L(3, d) exactly at all nine depths, and slope is almost exactly 1/21/2 (the formula oscillates between 2⋅3d/22 \cdot 3^{d/2} and 3(d+1)/2+3(d−1)/23^{(d+1)/2} + 3^{(d-1)/2} by parity).
  • Worst order. Slope is almost 1, but it does not evaluate all leaves (42 380 of 59 049 at d=10d = 10): putting the worst child first at each node does not guarantee no cutoff, because deep cutoffs compare with distant ancestor bounds. Worst case bdb^d exists, but needs deliberately chosen values.
  • Random order. The overall slope over d=2,…,10d = 2, \dots, 10 is clearly above Pearl’s asymptotic 0.6960.696 for b=3b = 3, and the last-level slope is lower than the overall one: measured exponent slowly approaches the limit, reached only as d→∞d \to \infty. At practical depths the b3d/4b^{3d/4} rule is a reasonable description.

The final table confirms what was said about RbR_b: for bb from 2 to 40, log⁡bRb\log_b R_b lies between 0.694 and 0.719, and RbR_b is somewhat below b3/4b^{3/4} (11.4 versus 12.8 for b=30b = 30); for b=1000b = 1000, RbR_b approaches b/ln⁡bb/\ln b and diverges from b3/4b^{3/4}.

Solved games

Solving a game means calculating its value under perfect play. Allis (1994) distinguished three levels: ultra-weak, if the value is known but not a strategy attaining it (Hex: a strategy-stealing argument proves the first player wins, but on large boards how is unknown); weak, if value and a strategy attaining it from the initial position are known; strong, if values of all reachable positions are known.

[ ]All of tic-tac-toeBrowser
from functools import lru_cache

LINEAS = [(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 ganador(t):
    for p, q, r in LINEAS:
        if t[p] != "." and t[p] == t[q] == t[r]:
            return t[p]
    return None

def hijos(t):
    jugador = "X" if t.count("X") == t.count("O") else "O"
    return [t[:i] + jugador + t[i + 1:] for i in range(9) if t[i] == "."]

@lru_cache(maxsize=None)
def analiza(t):
    """(valor para X, nodos del árbol, partidas que ganan X, O y tablas) desde la posición t."""
    g = ganador(t)
    if g or "." not in t:
        v = 1 if g == "X" else -1 if g == "O" else 0
        return v, 1, (v == 1, v == -1, v == 0)
    turno_x = t.count("X") == t.count("O")
    vals, nodos, cx, co, ct = [], 1, 0, 0, 0
    for h in hijos(t):
        v, k, (x, o, e) = analiza(h)
        vals.append(v); nodos += k; cx += x; co += o; ct += e
    return (max(vals) if turno_x else min(vals)), nodos, (cx, co, ct)

vacio = "." * 9
v, nodos, (cx, co, ct) = analiza(vacio)
print("valor del juego:", v, "  nodos del árbol:", nodos, "  posiciones distintas:", analiza.cache_info().currsize)
print("partidas:", cx + co + ct, "  gana X:", cx, "  gana O:", co, "  tablas:", ct)
print("valor de cada primera jugada:", [analiza(h)[0] for h in hijos(vacio)])

def alfabeta_ttt(t, alfa, beta, cuenta):
    """Negamax con alfa-beta (casillas en orden 0..8), valor para el jugador al turno."""
    cuenta[0] += 1
    g = ganador(t)
    if g:
        return -1                       # ha ganado el que acaba de jugar
    if "." not in t:
        return 0
    mejor = -2
    for h in hijos(t):
        v = -alfabeta_ttt(h, -beta, -alfa, cuenta)
        mejor = max(mejor, v)
        alfa = max(alfa, mejor)
        if alfa >= beta:
            break
    return mejor

cuenta = [0]
print("alfa-beta desde el tablero vacío:", alfabeta_ttt(vacio, -2, 2, cuenta), "con", cuenta[0], "nodos,",
      f"{nodos / cuenta[0]:.1f} veces menos que minimax")

The tree has 549 946 nodes and 255 168 possible games (X wins 131 184, O wins 77 904 and 46 080 draw), but only 5 478 distinct positions, and all nine first moves are worth 0. Alpha-beta with blind cell order 0 to 8 solves it visiting 18 297 nodes, 30 times fewer, the same count shown by the first figure’s oracle on the empty board.

Connect 4 was independently solved by James D. Allen (1 October 1988) and Victor Allis (16 October) with knowledge-guided search: the first player wins starting in the center column (by their piece on move 41 at latest); starting in a column adjacent to center draws, and starting in any of the other four lets the second player win. Brute-force solutions followed, starting with John Tromp’s 8-move database; legal board positions for 7×67 \times 6 number 4 531 985 219 092.

Checkers (Schaeffer and collaborators, Science, 2007) is the most ambitious game solved by search. It has about 5×10205 \times 10^{20} positions; from 1989 dozens of computers worked almost continuously on the proof, combining backward-computed endgame databases (all positions with 10 pieces or fewer: about 39 trillion, 3.9×10133.9 \times 10^{13}) with forward alpha-beta and proof-number search on 19 three-move openings. Result: with perfect play, draw, and the game is weakly solved. The architecture directly answers Knuth and Moore’s analysis: even with perfect order the tree cannot be traversed from initial position to end, so forward search stops upon reaching a position already valued in the database.

Common mistakes

Exercises

NumericMinimax leaves
A uniform game tree has branching factor b=30b = 30 and depth d=6d = 6. How many leaves does minimax evaluate?
NumericAlpha-beta leaves with perfect order
In the same tree (b=30b = 30, d=6d = 6), how many leaves does alpha-beta with perfect order evaluate according to Knuth and Moore’s formula?
NumericTwice the depth
With b=35b = 35 (typical of chess) and a budget of 10910^9 leaves, what is the maximum depth dd alpha-beta with perfect order can complete according to the exact formula L(b,d)L(b, d)?
NumericPearl’s factor for b = 2
According to Pearl, with continuous iid leaves and random order, the number of leaves alpha-beta evaluates grows as Rb dR_b^{\,d}, con Rb=ξb/(1−ξb)R_b = \xi_b/(1 - \xi_b) and ξb\xi_b the positive root of xb+x−1=0x^b + x - 1 = 0. Calculate R2R_2.
QuizWhat is pruned?
The root is MAX with two MIN children aa and bb. Each has two MAX children, a1,a2a_1, a_2 and b1,b2b_1, b_2, and each of these has two leaves: a1=(4,6)a_1 = (4, 6), a2=(7,9)a_2 = (7, 9), b1=(1,2)b_1 = (1, 2), b2=(0,8)b_2 = (0, 8). Alpha-beta explores children left to right with initial window (−∞,+∞)(-\infty, +\infty). Which leaves does it not evaluate?
QuizWhy (−β, −α)?
In negamax with alpha-beta, the child is called with window (−β,−α)(-\beta, -\alpha). Why?
QuizFixed-color evaluation
In fixed-depth Connect 4 negamax, evaluar always returns (red threats) − (yellow threats), regardless of whose turn it is. Wins are detected correctly. The program plays red, which starts, and always searches to the same fixed depth. What do you observe?
QuizReusing fail-hard or fail-soft
You search a position with window (10,20)(10, 20) and fail low. Fail-hard returns 10; fail-soft returns 4. You store the result and later revisit the same position at the same depth with window (5,15)(5, 15). What can you do without searching?
ProofAlpha-beta correctness (fail-soft)
Prove: Let F(s,α,β)F(s, \alpha, \beta) be the value returned by fail-soft negamax alpha-beta, with α<β\alpha < \beta, and N(s)N(s) the exact negamax value. Then, with v=F(s,α,β)v = F(s, \alpha, \beta): if v≤αv \le \alpha, N(s)≤vN(s) \le v; if v≥βv \ge \beta, N(s)≥vN(s) \ge v; and if α<v<β\alpha < v < \beta, v=N(s)v = N(s). In particular, F(s,−∞,+∞)=N(s)F(s, -\infty, +\infty) = N(s).
0
Use structural induction on the tree. At an internal node ss with children c1,…,ckc_1, \dots, c_k explored in order, let αi\alpha_i be the α\alpha current when calling child ii (α1=α\alpha_1 = \alpha, and αi+1=max⁡(αi,vi)\alpha_{i+1} = \max(\alpha_i, v_i)), vi=−F(ci,−β,−αi)v_i = -F(c_i, -\beta, -\alpha_i) and mm the maximum computed viv_i. Recall N(s)=max⁡i(−N(ci))N(s) = \max_i \big(-N(c_i)\big) over all children.

Step 1 of 5. What is the base case?

CodeFail-soft negamax with principal variation
Implement negamax_ab(nodo, alfa, beta, color) with fail-soft alpha-beta pruning. A node is a list of children; anything else is a leaf whose number is MAX’s utility. color is +1 if MAX moves at nodo and -1 if MIN moves. Return (valor, pv): value for the player to move and the principal variation, a list of child indices from nodo to a leaf attaining that value (empty at a leaf). Update the variation only on a strict value improvement. Tests compare exhaustive minimax on random trees with ties, check bound semantics under narrow windows and verify that you do not evaluate leaves alpha-beta must prune.
import math

def negamax_ab(nodo, alfa, beta, color):
  """Devuelve (valor para el jugador al turno, variante principal como lista de índices)."""
  if not isinstance(nodo, list):
      return color * nodo, []
  # tu código: recorre los hijos con la ventana negada e intercambiada, guarda el mejor y corta
  return 0, []
Shift+Enter to run

Summary

Key idea
In a perfect-information zero-sum game, each position’s value is defined by minimax; alpha-beta computes it exactly without looking at branches that cannot change it given bounds already achieved elsewhere, and with good move ordering evaluates on the order of the square root of the leaves, doubling reachable depth.
  • A finite two-player perfect-information zero-sum game has a value and optimal strategies (Zermelo); backward induction computes them. Negamax writes the recursion as one rule, N(s)=max⁡a−N(res(s,a))N(s) = \max_a -N(\text{res}(s, a)), with values relative to the player to move.
  • Alpha-beta carries window (α,β)(\alpha, \beta) and cuts off when α≥β\alpha \ge \beta. Fail-soft returns bounds outside the window: v≤αv \le \alpha is an upper bound and v≥βv \ge \beta a lower bound. With a full window the value is exact; narrow windows are cheaper.
  • With perfect order alpha-beta evaluates b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1 leaves, and no algorithm can evaluate fewer (one must see a MAX and a MIN strategy). With random order the exponent lies between 1/21/2 and 11: asymptotically Pearl’s log⁡bRb\log_b R_b, practically near 3/43/4.
  • Move ordering brings practice closer to the best case: domain knowledge first, and dynamic heuristics (killers, history, iterative deepening) recover much of the ordering when domain knowledge does not help. In Connect 4, center first reaches depth 8 with 856 times fewer nodes than minimax.
  • With these ideas and endgame databases, Connect 4 (first player wins starting in the center) and checkers (draw) have been solved. The next lesson adds what a complete engine needs: timed iterative deepening, transposition tables, quiescence search and null-window search.