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 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:
- Minimax, the algorithm computing a game’s value by traversing its tree, and its compact version, negamax.
- 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.
Three things the oracle shows and the lesson explains:
- 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.
- Computing it without pruning costs the whole tree. From the empty board minimax visits 549 946 nodes, one per legal game prefix.
- 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 determines a complete game and thus a utility .
Proof
Define for each tree node by structural induction from the leaves:
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 be MAX’s strategy choosing a maximizing move at each MAX node, and MIN’s strategy choosing a minimizing move. Prove by induction on node height that, from , guarantees at least against any . At a leaf this is the definition. If MAX moves, goes to a child with and, by induction, from gets at least . If MIN moves, any child chosen by satisfies , and from it gets at least . The symmetric claim for is identical with maxima replaced by minima. With both inequalities follow. For the last sentence, take utilities , and : if MAX wins, if MIN wins, and if 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, still guarantees , 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 children and all leaves are at depth , minimax evaluates leaves and visits nodes. Its memory is depth-first search’s: the current branch and, if moves are generated one by one, positions; if every level’s moves are generated at once.
Writing two cases, one for MAX and one for MIN, doubles code and errors. Identity 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 , so . If MIN moves, and . Both agree with . Negamax requires alternating turns (or, if they do not alternate, changing sign only when the player changes) and zero-sum utility.
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 and replace leaf utility with an evaluation function estimating (or in negamax, : value for the player to move). Recursion is unchanged with one extra base case: if remaining depth is 0, return .
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 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 :
- is the best MAX has already guaranteed somewhere on the path from the root;
- is the best (lowest) MIN has guaranteed on the path.
While exploring a node, only values strictly between and matter: if the node is worth , MAX will avoid it higher up; if , MIN will avoid it. As soon as a MIN node finds a child worth (or a MAX node one worth ), remaining children are irrelevant: a cutoff.
In negamax the window changes sign and order when descending a level. The parent seeks values with ; since , the child seeks with . The entire algorithm is then:
Two details are visible step by step. First, or 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 , 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 , unexplored children can only raise the maximum, so the node is worth at least , all its parent needs to discard it.
Fail-hard and fail-soft
The theorem concerns the version returning , 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 , you know , more informative than . 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).
The lower curve anticipates an idea engines exploit: a null window never returns an exact value (with integers, or ), 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 in exploration order and name each node by its path from the root, with .
Counting critical leaves is direct. Those with in every odd position vary only in the even positions: . Those with in every even position vary in the odd positions: . Only leaf 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 . Other children are strictly worse and therefore fail: type 2. The root is type 1.
- Type 2 (CUT). Its value exceeds (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 . To prove it, all children must be seen to be bad: it explores every child without cutoff, each type 2.
If is the number of leaves alpha-beta evaluates under a node of type with remaining depth , with , the three types give a system of linear recurrences:
This is a nonhomogeneous recurrence solved by expansion, matching the critical-leaf count: the PV node at depth 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 leaves because there are MIN levels above leaves. A MIN strategy conversely has . By minimax recursion,
the value is the best MAX can guarantee with some strategy.
Proof
Suppose a deterministic algorithm returns after evaluating leaf set . If no MAX strategy has all its leaves in , change every leaf outside to a number less than . The algorithm never looked at them, so behaves identically and returns again. But now every MAX strategy contains a leaf worth less than , and by the preceding formula the new value is below : the algorithm is wrong. Thus contains every leaf of some MAX strategy , and by the symmetric argument (raising unseen leaves above ), all leaves of some MIN strategy . 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 , at each MIN node by ). Therefore .
∎With perfect order, alpha-beta evaluates exactly the union of one MAX strategy (nodes with 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 ), an algorithm finding can stop immediately; alpha-beta does so when given the utility range as initial window instead of , and can then fall below . The argument holds for each particular tree, including ties: any algorithm correct for arbitrary real leaves, alpha-beta included, evaluates at least leaves in any uniform tree. Distinct values ensure that perfect order evaluates exactly critical leaves; with ties the 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 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 , with
and proved no directional algorithm (examining leaves left to right) can improve that rate. For , and is the golden ratio . For usual , resembles , Russell and Norvig’s rule for “moderate ”; as , grows as , so the comparison with no longer holds for enormous .
The practical consequence is the statement opening the lesson. With a budget of leaves, minimax reaches ; alpha-beta with perfect order ; with random order . 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 or , whenever that move causes a cutoff with remaining depth . It generalizes killers across the tree.
- Iterative deepening as oracle. Search to depth , 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 , together they cost at most a factor 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 and row (from the bottom) is bit . Position is stored in two integers: actual, the player-to-move pieces, and mascara, all pieces. Opponent pieces are actual ^ mascara.
- Play in column :
mascara + abajo(c)adds 1 at the column’s lowest bit and carry rises to the first free cell, somascara | (mascara + abajo(c))adds the new piece. Before that,actual ^= mascarachanges 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 also belongs to the player, andm & (m >> 2*s)is nonzero if four are consecutive. Directions are (vertical), 7 (horizontal), 6 and 8 (both diagonals). The guard bit prevents a line crossing from one column into the next.
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.
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.
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 , 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 . 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.
@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 , where 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.
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:
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 .
- 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 . 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 ; with random order the growth exponent lies between and , near Pearl’s. First, agreement on trees with ties (integer leaves between and ), where implementation errors appear.
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 and , generate trees with leaves uniform on (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.
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 exactly at all nine depths, and slope is almost exactly (the formula oscillates between and by parity).
- Worst order. Slope is almost 1, but it does not evaluate all leaves (42 380 of 59 049 at ): putting the worst child first at each node does not guarantee no cutoff, because deep cutoffs compare with distant ancestor bounds. Worst case exists, but needs deliberately chosen values.
- Random order. The overall slope over is clearly above Pearl’s asymptotic for , and the last-level slope is lower than the overall one: measured exponent slowly approaches the limit, reached only as . At practical depths the rule is a reasonable description.
The final table confirms what was said about : for from 2 to 40, lies between 0.694 and 0.719, and is somewhat below (11.4 versus 12.8 for ); for , approaches and diverges from .
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.
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 number 4 531 985 219 092.
Checkers (Schaeffer and collaborators, Science, 2007) is the most ambitious game solved by search. It has about 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, ) 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
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?Step 1 of 5. What is the base case?
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, []Summary
- 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, , with values relative to the player to move.
- Alpha-beta carries window and cuts off when . Fail-soft returns bounds outside the window: is an upper bound and a lower bound. With a full window the value is exact; narrow windows are cheaper.
- With perfect order alpha-beta evaluates leaves, and no algorithm can evaluate fewer (one must see a MAX and a MIN strategy). With random order the exponent lies between and : asymptotically Pearl’s , practically near .
- 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.