Module contents
Lesson 6 of 23Advanced 115 min

Anatomy of a game engine: iterative deepening, transposition tables and evaluation

Bare alpha-beta does not win games; surrounding techniques do. Build a complete engine with timed iterative deepening, Zobrist hashing and transposition tables, quiescence, null windows (PVS), forward pruning and data-tuned evaluation, and extend search to chance games with expectiminimax.

After this lesson you can

  • Implement iterative deepening with time management and aspiration windows.
  • Design a transposition table with Zobrist hashing, value types, depth and replacement policy.
  • Mitigate the horizon effect with quiescence search and assess forward-pruning risks.
  • Tune evaluation weights from game results and validate improvements statistically.
  • Extend search to chance games with expectiminimax and reason about evaluation scale.

Before you start

Bare alpha-beta does not win games

The previous lesson ended with a correct Connect 4 player: negamax with alpha-beta pruning and good move ordering. As a player, however, it has four serious flaws:

  1. It cannot manage time. It searches to fixed depth dd. If dd is small, it plays worse than it could; if large, it may take minutes on a complicated position, and if interrupted halfway it has no move to offer.
  2. It repeats work. In Connect 4, chess and almost every game, the same position is reached through many orders of the same moves: the game tree is actually a graph. Alpha-beta searches each copy from scratch.
  3. It trusts meaningless evaluations. It cuts search at a fixed distance from the root even if a capture is half complete there. Static evaluation of such a position means nothing.
  4. Its evaluation is a guess. Weights “3 per threat and 1 per central piece” were eyeballed, and nobody has checked whether others play better.

A game engine is alpha-beta plus techniques solving these four problems. Deep Blue, IBM’s machine that defeated Kasparov in 1997, had them all. According to Campbell, Hoane and Hsu (2002), it combined “quiescence search, iterative deepening, transposition tables and NegaScout” (the PVS variant covered here), with 480 chess chips each searching 2 to 2.5 million positions per second and an average of 126 million per second in match searches exceeding one minute. Its evaluation summed about 8000 features. Twenty-five years later, Stockfish retains the same architecture with two major changes: aggressive forward pruning and, since 2020, neural-network evaluation.

This lesson builds these pieces one by one and measures them in a Connect 4 engine solving published test positions: timed iterative deepening and aspiration windows, Zobrist keys and transposition tables, quiescence, PVS, forward pruning, tuning evaluation from game results, chance games, and finally how to demonstrate an engine change is an improvement. The next lesson changes paradigm with Monte Carlo Tree Search, and AlphaZero replaces handcrafted evaluation and ordering with a network.

Iterative deepening: a move is always ready

The idea is the module’s first lesson’s iterative deepening depth-first search, applied to a game tree: search depth 1, then 2, then 3, and so on while time remains.

This looks wasteful: all shallow searches are repeated. It is not, for two reasons.

Earlier iterations cost a bounded fraction. If iteration kk visits on the order of c (b∗)kc\,(b^*)^k nodes, with b∗>1b^* > 1 the effective branching factor, the sum through dd is

∑k=1dc (b∗)k=c (b∗)d⋅1−(b∗)−d1−1/b∗<c (b∗)d⋅b∗b∗−1.\sum_{k=1}^{d} c\,(b^*)^k = c\,(b^*)^d \cdot \frac{1 - (b^*)^{-d}}{1 - 1/b^*} < c\,(b^*)^d \cdot \frac{b^*}{b^* - 1}.

With b∗=3b^* = 3 all iterations together cost at most 1.5 times the last; with b∗=6b^* = 6, 1.2 times. This is the same calculation as uninformed search, with b∗b^* instead of bb.

Earlier iterations make the last cheaper. The previous lesson proved alpha-beta with perfect order visits on the order of bd/2b^{d/2} leaves and with random order many more. Iteration d−1d - 1 leaves each explored position’s best move in the transposition table, and iteration dd tries it first: on the principal variation and much of the tree, the first move is already right. Thus iterative search through dd can cost fewer nodes than a direct search to depth dd; the lab measures it.

Time management

With iterative deepening, time control is a rule for when to begin the next iteration. The simplest:

  • Hard limit. Check the clock every few thousand nodes; if allocated time has expired, search throws an exception, discards the current iteration and plays the previous one’s best move.
  • Soft limit. Do not start an iteration unlikely to finish. Since each costs about b∗b^* times the previous one, if more than 1/b∗1/b^* of the budget is spent, the next probably will not finish; the lab cell uses fraction 1/31/3.

Real engines adjust budget according to search progress. Deep Blue had two time targets: normal, approximately remaining time to the next control divided by moves remaining, and “panic,” one third of remaining time. It kept thinking beyond normal if the best move had fallen 15 points or more from the previous iteration, or if a fail-high or fail-low was unresolved (Campbell, Hoane and Hsu, 2002). The general heuristic is to spend time when search is unstable.

Aspiration windows

Iteration d−1d - 1 also estimates value vd−1v_{d-1}, and iteration dd‘s value is usually close. An aspiration window searches the root with (α,β)=(vd−1−δ,vd−1+δ)(\alpha, \beta) = (v_{d-1} - \delta, v_{d-1} + \delta) instead of (−∞,+∞)(-\infty, +\infty). If the result lies inside, it is exact and search pruned more thanks to the narrow window (the previous lesson’s “Windows and bounds” figure showed how cheap a small window is). If outside, the fail-soft alpha-beta correctness theorem says it is only a bound, and search must be repeated with the window opened on that side. The tradeoff is δ\delta: too narrow causes re-searches; too wide prunes nothing extra.

Zobrist keys

Recognizing an already searched position requires a table indexed by position, and hence a fast hash function. In 1970 Albert Zobrist proposed the one used by almost all game programs since (University of Wisconsin technical report 88).

The power comes from XOR properties: it is associative and commutative, has identity 00, and each element is its own inverse, x⊕x=0x \oplus x = 0. Three consequences:

  • The key is independent of the order in which the position was reached. It is the XOR of a set, and XOR order does not matter. Different orders of the same moves yield the same key: exactly what a transposition table needs.
  • It updates in constant time. Adding a piece is h←h⊕Z[p,c]h \leftarrow h \oplus Z[p, c]; removing it uses the same XOR again. A Connect 4 move takes two XORs (the new piece and turn change); a chess move a few more (departing, arriving and captured pieces, turn, and if changed castling rights and en passant file, which also have strings). No board traversal is needed.
  • Undo is free. Applying the same move again undoes the key, fitting searches that make and unmake moves.
InteractiveZobrist live
1234567
The 64 key bits: dark gray is 1; white is 0. Magenta marks bits changed by XOR (dark if changed to 1, light if changed to 0).
5651b957cebf3117 ⊕ f46683e0b59042a9 = a2373ab77b2f73be
Probability of at least one collision among NN random kk-bit keys (horizontal axis: log⁡10N\log_{10} N)
  • 32 bits
  • 64 bits
32
100 k
Moves3 5 4 4
Key (incremental)a2373ab77b2f73be
Key calculated from scratchmatches
Expected colliding pairs, (N2)/2k\binom{N}{2}/2^k1.164
Probability of at least one collision68.78 %
Transposition: this position was already seen via “4 4 3 5”. Same position and player to move, same key: the table reuses its previous calculation.
Click a column to drop a piece: magenta bits are those changed by that move's XOR, with the hexadecimal calculation below. The initial position was reached by paths 4 4 3 5 and 3 5 4 4: the key is the same and the log detects a transposition. Try other move-order pairs and undo to see the key return exactly to its predecessor. Below is the probability that at least two among NN keys of kk bits match: with 32 bits it exceeds 50% around 77 000 positions; with 64 bits around 5×1095 \times 10^9.

Collisions: the birthday paradox

Two distinct positions can receive the same key. With what probability? For two particular positions s≠s′s \neq s', h(s)⊕h(s′)h(s) \oplus h(s') is the XOR of the ZZ strings for pieces present in one but not the other (plus ZturnoZ_{\text{turno}} if the turn changes). That set is nonempty because positions differ, and XOR of uniform independent strings is uniform. Thus

P(h(s)=h(s′))=P(h(s)⊕h(s′)=0)=2−k\Pr\big(h(s) = h(s')\big) = \Pr\big(h(s) \oplus h(s') = 0\big) = 2^{-k}

exactly: the Zobrist family is universal hashing.

Proof

C=∑i<j1[h(si)=h(sj)]C = \sum_{i < j} \ind[h(s_i) = h(s_j)]. By expectation linearity, E[C]=∑i<jP(h(si)=h(sj))=(N2)2−k\E[C] = \sum_{i<j} \Pr(h(s_i) = h(s_j)) = \binom{N}{2} 2^{-k}. The second inequality is the union bound over (N2)\binom{N}{2} events, or Markov’s inequality P(C≥1)≤E[C]\Pr(C \ge 1) \le \E[C]. The final approximation uses log⁡(1−x)≈−x\log(1 - x) \approx -x for small x=2−kx = 2^{-k}.

∎

The last formula’s independence assumption does not hold completely: Zobrist keys are pairwise independent but not four-wise independent (if s1△s2=s3△s4s_1 \triangle s_2 = s_3 \triangle s_4 as piece sets, h(s1)⊕h(s2)=h(s3)⊕h(s4)h(s_1) \oplus h(s_2) = h(s_3) \oplus h(s_4)). Hence we use it only as an approximation, and the cell compares it with real collisions. The practical consequence is the birthday paradox: collisions become likely when NN approaches 2k=2k/2\sqrt{2^k} = 2^{k/2}, not 2k2^k. With 32 bits, from about 216≈65 0002^{16} \approx 65\,000 positions; with 64 bits, about 4×1094 \times 10^9.

[ ]Connect 4 with Zobrist keysBrowser
import random

W, H = 7, 6
H1 = H + 1                                   # 6 casillas y un bit de guarda por columna
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)
TABLERO = FONDO * ((1 << H) - 1)

def alineado(p):
    for s in (1, H1, H, H + 2):
        m = p & (p >> s)
        if m & (m >> (2 * s)):
            return True
    return False

def amenazas(p, mascara):
    """Casillas vacías donde las fichas p completarían cuatro en línea."""
    r = (p << 1) & (p << 2) & (p << 3)
    for s in (H1, H, H + 2):
        q = (p << s) & (p << 2 * s)
        r |= q & (p << 3 * s)
        r |= q & (p >> s)
        q = (p >> s) & (p >> 2 * s)
        r |= q & (p << s)
        r |= q & (p >> 3 * s)
    return r & (TABLERO ^ mascara)

azar = random.Random(2024)
Z = [[azar.getrandbits(64) for _ in range(W * H1)] for _ in range(2)]   # Z[jugador][bit de la casilla]
Z_TURNO = azar.getrandbits(64)

def jugar(actual, mascara, n, clave, c):
    """Ficha en la columna c. La clave se actualiza con dos XOR: la ficha nueva y el cambio de turno."""
    nueva = (mascara + ABAJO[c]) & COLUMNA[c]
    clave ^= Z[n & 1][nueva.bit_length() - 1] ^ Z_TURNO
    return actual ^ mascara, mascara | nueva, n + 1, clave

def clave_desde_cero(actual, mascara, n):
    k = Z_TURNO if n & 1 else 0
    al_turno, rival = actual, actual ^ mascara
    primero, segundo = (al_turno, rival) if n % 2 == 0 else (rival, al_turno)
    for jugador, fichas in ((0, primero), (1, segundo)):
        while fichas:
            b = fichas & -fichas
            k ^= Z[jugador][b.bit_length() - 1]
            fichas ^= b
    return k

def desde_cadena(jugadas):
    pos = (0, 0, 0, 0)
    for ch in jugadas:
        pos = jugar(*pos, int(ch) - 1)
    return pos

for a, b in (("1727", "2717"), ("4453", "5344")):
    pa, pb = desde_cadena(a), desde_cadena(b)
    print(f"{a} y {b}: misma posición {pa[:3] == pb[:3]}, misma clave {pa[3] == pb[3]}, clave {pa[3]:016x}")

# la actualización incremental coincide con el cálculo desde cero en 700 partidas al azar
distintas, errores = {}, 0
for g in range(700):
    pos = (0, 0, 0, 0)
    while pos[2] < W * H:
        libres = [c for c in range(W) if not pos[1] & ARRIBA[c]]
        c = azar.choice(libres)
        if alineado(pos[0] | ((pos[1] + ABAJO[c]) & COLUMNA[c])):
            break
        pos = jugar(*pos, c)
        errores += pos[3] != clave_desde_cero(*pos[:3])
        distintas[(pos[0], pos[1])] = pos[3]
print("discrepancias incremental frente a desde cero:", errores)
N = len(distintas)
claves = list(distintas.values())
print("posiciones distintas:", N, "  claves de 64 bits repetidas:", N - len(set(claves)))
print(" bits   pares que colisionan   predicción C(N,2)/2^k")
for k in (16, 20, 24, 32):
    cuenta = {}
    for x in claves:
        cuenta[x & ((1 << k) - 1)] = cuenta.get(x & ((1 << k) - 1), 0) + 1
    pares = sum(v * (v - 1) // 2 for v in cuenta.values())
    print(f"{k:5d}   {pares:20d}   {N * (N - 1) / 2 / 2**k:20.1f}")

Both move-order pairs reach the same position and key, and in 700 random games incremental update always matches recomputation. The 12 019 distinct positions share no 64-bit key, as expected. To see collisions retain only the lowest kk bits: with 16 bits, 1068 colliding pairs versus the 1102 predicted by (N2)/2k\binom{N}{2}/2^k; with 20, 79 versus 68.9; with 24, 6 versus 4.3. Deviations are the size of Poisson noise (standard deviation is the square root of the mean: about 33, 8 and 2).

Transposition tables

The type follows directly from the previous lesson’s fail-soft alpha-beta correctness theorem. If a depth d′d' search with window (α0,β)(\alpha_0, \beta) returns vv, then v≤α0v \le \alpha_0 implies the true value at that depth satisfies Vd′≤vV_{d'} \le v; v≥βv \ge \beta implies Vd′≥vV_{d'} \ge v; and α0<v<β\alpha_0 < v < \beta implies Vd′=vV_{d'} = v. On encountering the position again with remaining depth dd and window (α,β)(\alpha, \beta):

Proof

In case 1 the value is exact and satisfies the contract for any window: if vv falls inside it is exact, and outside an exact value is in particular a correctly directed bound. In case 2, the call requesting window (α,β)(\alpha, \beta) only needs to know the value is at least β\beta, and v≥βv \ge \beta is a true lower bound: the parent cuts off just as if it had searched. Case 3 is symmetric. In other cases, for example lower bound v<βv < \beta, all that is known is Vd′≥vV_{d'} \ge v: the value could lie in (α,β)(\alpha, \beta) and need to be known exactly, or be ≥β\ge \beta, and returning vv would violate the contract. Finally, if d′<dd' < d, the entry describes a shallower value than requested, generally different.

∎

Notice the qualification: with d′>dd' > d, search returns a bound on Vd′V_{d'}, not VdV_d. Search with a table no longer computes exactly depth-dd minimax value but something at least as informed. This is almost always advantageous, but has a known side effect: the same search may yield different values depending on table contents (search instability). And if the position is not truly identical (in chess, identical piece placement with different repetition or 50-move history), the table may mix history-dependent values: the graph-history interaction problem, accepted by engines as the lesser evil.

Depth, replacement and mate scores

Three design decisions and their common failures:

  • Depth. An entry shallower than requested cannot cut off (previous theorem), but its move remains the best candidate to try first. Treating shallow entries as valid is a frequent, hard-to-see error because the engine still plays, just worse.
  • Replacement. The table is fixed-size, like open addressing without probing: each key has one slot (or a small bucket) and a new entry can evict another. Classic policies are always (new evicts old: favors locality), depth-preferred (evict only if at least as deep: preserves expensive results), and two-tier (two-slot bucket, one depth-preferred and one always replaced). Depth-preferred needs aging: without it, deep entries from old searches occupy the table forever. The lab measures all three.
  • Mates. A chess engine scores mate in kk moves from the root as M−kM - k, preferring shorter mates. But the table must store distance from the node, not the root: if the node is pp plies from the root, store v+pv + p and subtract the querying node’s pp on lookup. Otherwise the same entry seen at another root distance gives artificially short or long mates and the engine may fail to finish a won game. Connect 4 avoids this: piece count is part of the position, and the Pons score used (winner’s pieces remaining) depends only on position, not root distance.

Lab: a Connect 4 engine

The engine starts from the previous lesson’s: same board in two integers, same function amenazas and evaluation. It adds the Zobrist key (previous cell) and here a transposition table, history heuristic and PVS (explained below; for now it can be switched off). Forward pruning is also in the code, disabled until its section.

The score is Pascal Pons’s: 0 for a draw under perfect play; positive if the player to move wins, equal to 22 minus the number of pieces they will have played upon winning (1 if winning with the last piece, 2 with the penultimate, and so on), so earlier wins score higher; negative by the same count for the opponent if losing. Inside the engine, winning with the next piece is worth VICTORIA plus that score to separate it from any heuristic evaluation, and pons removes the offset.

[ ]The engine: transposition table, history and PVSBrowser
import time, statistics

INF = 10**6
VICTORIA = 1000                    # ganar con la próxima ficha vale VICTORIA + puntuación de Pons
EXACTO, INFERIOR, SUPERIOR = 0, 1, 2
CENTRO_PRIMERO = (3, 2, 4, 1, 5, 0, 6)

def evaluar(actual, mascara, n=0):
    """La evaluación de la lección anterior, para el jugador al turno (n no se usa)."""
    rival = actual ^ mascara
    return (3 * (amenazas(actual, mascara).bit_count() - amenazas(rival, mascara).bit_count())
            + (actual & COLUMNA[3]).bit_count() - (rival & COLUMNA[3]).bit_count())

class SinTiempo(Exception):
    pass

class Motor:
    def __init__(self, tabla=True, historia=True, pvs=True, bits_tabla=16, reemplazo="siempre", nulo=False, lmr=False,
                 evaluacion=evaluar):
        self.evaluar = evaluacion                      # función (actual, mascara, n) -> valor para el que juega
        self.usa_tt, self.usa_hist, self.usa_pvs = tabla, historia, pvs
        self.nulo, self.lmr = nulo, lmr                # podas hacia delante (sección de podas): apagadas
        self.tam, self.reemplazo = 1 << bits_tabla, reemplazo
        self.tt = [None] * self.tam                    # direccionamiento directo por los bits bajos de la clave
        self.hist = [0] * (W * H1)                     # historia, indexada por la casilla de la ficha
        self.nodos = self.sondeos = self.aciertos = self.cortes_tt = self.rebusquedas = 0
        self.limite = None                             # instante en que se acaba el tiempo

    def negamax(self, actual, mascara, n, clave, d, alfa, beta, nulo_ok=True):
        self.nodos += 1
        if self.limite and not self.nodos & 1023 and time.perf_counter() > self.limite:
            raise SinTiempo
        if n == W * H:
            return 0
        if amenazas(actual, mascara) & (mascara + FONDO) & TABLERO:
            return VICTORIA + (W * H + 1 - n) // 2
        if d == 0:
            return self.evaluar(actual, mascara, n)
        alfa0, jugada_tt = alfa, -1
        if self.usa_tt:
            self.sondeos += 1
            i = clave & (self.tam - 1)
            if self.reemplazo == "dos":                # cubo de dos casillas: primero la de profundidad
                i &= ~1
                if self.tt[i] is None or self.tt[i][0] != clave:
                    i += 1
            e = self.tt[i]
            if e is not None and e[0] == clave:        # se comprueba la clave entera
                self.aciertos += 1
                _, de, tipo, v, jugada_tt = e
                if de >= d and (tipo == EXACTO or (tipo == INFERIOR and v >= beta)
                                or (tipo == SUPERIOR and v <= alfa)):
                    self.cortes_tt += 1
                    return v
        if self.nulo and nulo_ok and d >= 3 and beta < VICTORIA:
            # jugada nula (ilegal en Conecta 4): el rival mueve dos veces; si aun así v >= beta, se corta
            v = -self.negamax(actual ^ mascara, mascara, n + 1, clave ^ Z_TURNO, d - 3, -beta, -beta + 1, False)
            if v >= beta:
                return v
        cols = [c for c in CENTRO_PRIMERO if not mascara & ARRIBA[c]]
        if self.usa_hist:                               # sort es estable: a igual peso, el centro primero
            cols.sort(key=lambda c: -self.hist[((mascara + ABAJO[c]) & COLUMNA[c]).bit_length() - 1])
        if jugada_tt >= 0:                              # la jugada de la tabla, antes que nada
            cols.remove(jugada_tt)
            cols.insert(0, jugada_tt)
        mejor, mj = -INF, cols[0]
        for i, c in enumerate(cols):
            hijo = jugar(actual, mascara, n, clave, c)
            if self.usa_pvs and i > 0:
                if self.lmr and i >= 3 and d >= 3:                     # jugada tardía: primero, reducida
                    v = -self.negamax(*hijo, d - 2, -alfa - 1, -alfa)
                    if v > alfa:                                         # sorpresa: a la profundidad completa
                        v = -self.negamax(*hijo, d - 1, -alfa - 1, -alfa)
                else:
                    v = -self.negamax(*hijo, d - 1, -alfa - 1, -alfa)  # ventana nula: ¿supera a alfa?
                if alfa < v < beta:                                      # sí: hay que saber cuánto
                    self.rebusquedas += 1
                    v = -self.negamax(*hijo, d - 1, -beta, -alfa)
            else:
                v = -self.negamax(*hijo, d - 1, -beta, -alfa)
            if v > mejor:
                mejor, mj = v, c
                if v > alfa:
                    alfa = v
                    if alfa >= beta:
                        if self.usa_hist:
                            self.hist[((mascara + ABAJO[c]) & COLUMNA[c]).bit_length() - 1] += d * d
                        break
        if self.usa_tt:
            tipo = SUPERIOR if mejor <= alfa0 else INFERIOR if mejor >= beta else EXACTO
            i = clave & (self.tam - 1)
            nueva = (clave, d, tipo, mejor, mj)
            if self.reemplazo == "dos":                # par (i, i ^ 1): par = profundidad, impar = siempre
                p = i & ~1
                vieja = self.tt[p]
                if vieja is None or vieja[0] == clave or vieja[1] <= d:
                    self.tt[p] = nueva
                else:
                    self.tt[p + 1] = nueva
            else:
                vieja = self.tt[i]
                if self.reemplazo == "siempre" or vieja is None or vieja[1] <= d:
                    self.tt[i] = nueva
        self.ultima = mj
        return mejor

def pons(v):
    """Valor del motor a la puntuación de Pons: positiva si gana el jugador al turno."""
    return v - VICTORIA if v >= VICTORIA else v + VICTORIA if v <= -VICTORIA else v

def resolver(motor, pos):
    actual, mascara, n, clave = pos
    return pons(motor.negamax(actual, mascara, n, clave, W * H - n, -INF, INF))

for jugadas, esperado in (("7532455277545526", -10), ("5554224333234511764415115", 4)):
    M = Motor()
    print(f"{jugadas}: puntuación {resolver(M, desde_cadena(jugadas))} (Pons: {esperado}),  nodos {M.nodos},"
          f"  aciertos de la tabla {M.aciertos} de {M.sondeos} sondeos, cortes por la tabla {M.cortes_tt}")

The two positions are among the first in Pons’s benchmark and the engine solves them with expected scores. The table is directly addressed by the key’s low 16 bits and compares the entire key, so it admits no false hits.

Test positions

The next 30 positions are the first in Pascal Pons’s blog’s “Middle-Easy” set (Test_L2_R1): 15 to 28 pieces on the board and fewer than 14 moves to the end under perfect play, each with its exact score. Solving requires searching to the end, so evaluation does not intervene: a clean search benchmark. The cell compares alpha-beta with center order, without and with a table.

[ ]Test positions: without and with tableBrowser
PRUEBAS = [("5554224333234511764415115", 4), ("52753311433677442422121", 8), ("1233722555341451114725221333", -1),
    ("271713432331713132", -11), ("6672375354252731116762237724", -2), ("763452543756455357732314", -8),
    ("662222576343651642712157", 8), ("3455565261655364217", -10), ("4661237137541742643224", 8),
    ("21253774536432517717274325", 2), ("715371563635542612576371", 3), ("4435612735531457155143", -5),
    ("3457741246677474572223453551", 5), ("754732466173162124726115261", 7), ("64115442265757253615", 10),
    ("34651743747475571565", -9), ("36127316172165452675422251", 7), ("4235245615377275211512", -7),
    ("122435527534575161761", 10), ("473175162213611457122724", -7), ("5533212164224336233241461", 3),
    ("1231426213112346726266353", -7), ("45277231624411643516213", 8), ("1667675535724753771415352132", 1),
    ("41416453222527221644", 10), ("1715764132212113656454", -9), ("651142666562345525716135112", 2),
    ("7532455277545526", -10), ("2737772244262123677516643354", 0), ("5746741223753516274755", 8)]

def banco(nombre, **kw):
    t = time.perf_counter()
    nodos, aciertos, sondeos, ok, rebus = [], 0, 0, 0, 0
    for jugadas, esperado in PRUEBAS:
        M = Motor(**kw)
        ok += resolver(M, desde_cadena(jugadas)) == esperado
        nodos.append(M.nodos); aciertos += M.aciertos; sondeos += M.sondeos; rebus += M.rebusquedas
    dt = time.perf_counter() - t
    tasa = f"{aciertos / sondeos:6.1%}" if sondeos else "     -"
    print(f"{nombre:26s} {ok:2d}/{len(PRUEBAS)}  {statistics.geometric_mean(nodos):7.0f}  {sum(nodos):8d}  {max(nodos):7d}"
          f"   {tasa}   {rebus:6d}   {sum(nodos) / dt:8.0f}")
    return nodos

print("configuración              bien   media g.     total   máximo   aciertos  re-búsq.  nodos/s")
sin_tt = banco("alfa-beta, centro primero", tabla=False, historia=False, pvs=False)
con_tt = banco("+ tabla de transposición", tabla=True, historia=False, pvs=False)
print("posiciones en las que la tabla ahorra nodos:", sum(a > b for a, b in zip(sin_tt, con_tt)), "de", len(PRUEBAS))

Both configurations get all 30 scores right. The table divides total nodes by 4.9 (306 841 to 62 564), geometric mean by 2.1 (1060 to 501), and worst case by 8.6 (164 940 to 19 072). Savings grow with search size because deeper trees contain more transpositions: small positions have little to reuse, and on 5 of 30 the table saves no nodes. Only 23% of probes find the position, but each hit may save an entire subtree. Nodes per second depends on your machine and changes little with the table: in Python extra per-node work (indexing, comparing, storing) is small compared with the rest of search, so total time falls nearly in proportion to nodes.

Now history heuristic and PVS on top of the table:

[ ]History and PVS on top of the tableBrowser
print("configuración              bien   media g.     total   máximo   aciertos  re-búsq.  nodos/s")
banco("tabla + historia", tabla=True, historia=True, pvs=False)
banco("tabla + PVS", tabla=True, historia=False, pvs=True)
banco("tabla + historia + PVS", tabla=True, historia=True, pvs=True)

The result differs from the books, and deserves careful reading. PVS with the table reduces total from 62 564 to 52 668 nodes (16% less). History slightly improves geometric mean (501 to 470) but doubles total (127 244) and worst case: on large positions history’s learned order contradicts center order, already very good in Connect 4, and often gets it wrong. This mirrors the previous lesson’s center plus killers and history: a dynamic heuristic need not improve good domain knowledge and can worsen it. A real engine measures each heuristic separately and together, retaining it only if it wins.

Table size and replacement policy

With 2162^{16}-slot tables these searches have almost no conflicts. To make replacement policy matter, the cell uses 29=5122^{9} = 512 slots, far fewer than distinct positions visited in large searches.

[ ]Replacement policy with a small tableBrowser
print("política       nodos   aciertos   bien   (tabla de 2^9 casillas, sin historia)")
for politica in ("siempre", "profundidad", "dos"):
    total = aciertos = sondeos = ok = 0
    for jugadas, esperado in PRUEBAS:
        M = Motor(bits_tabla=9, reemplazo=politica, historia=False)
        ok += resolver(M, desde_cadena(jugadas)) == esperado
        total += M.nodos; aciertos += M.aciertos; sondeos += M.sondeos
    print(f"{politica:12s} {total:8d}   {aciertos / sondeos:6.1%}   {ok}/{len(PRUEBAS)}")

All three policies solve all 30 positions correctly (replacement never changes correctness, only what is remembered), but costs vary. “Depth-preferred” is worst: 97 673 nodes and only 8.5% of probes find their position, because deep entries from early moves occupy slots never queried again and nothing evicts them. “Always” favors recency and falls to 90 328 nodes. The two-tier bucket, holding both the deepest and newest entry in the same memory, is best: 72 136 nodes, 20% below “always.” Chess Programming Wiki describes this two-tier scheme, often augmented with search age so deep entries no longer useful can be evicted between moves.

Timed iterative deepening and aspiration windows

Benchmark positions need no iterative deepening: search goes to the end. In middlegame, the engine must cut at a depth and evaluate. The next cell defines pensar, iterative deepening with hard and soft limits, and compares it with direct fixed-depth search on six middlegame positions (the first six with 15 to 17 pieces from Pons’s Test_L2_R2 set), counting nodes of all iterative passes.

[ ]Iterative deepening and aspiration windowsBrowser
def b_efectivo(N, d):
    """b* con N = 1 + b* + ... + b*^d (como en la lección anterior)."""
    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

def pensar(pos, segundos=None, dmax=40, aspiracion=None, motor=None, informe=True):
    """Profundización iterativa. Devuelve (jugada, valor, profundidad completada)."""
    M = motor or Motor()
    actual, mascara, n, clave = pos
    M.limite = time.perf_counter() + segundos if segundos else None
    jugada = valor = None
    completada, t0 = 0, time.perf_counter()
    for d in range(1, min(dmax, W * H - n) + 1):
        antes = M.nodos
        try:
            if aspiracion and valor is not None and abs(valor) < VICTORIA:
                a, b = valor - aspiracion, valor + aspiracion
                v = M.negamax(actual, mascara, n, clave, d, a, b)
                if v <= a or v >= b:                        # fuera de la ventana: v es solo una cota
                    M.fallos_aspiracion += 1
                    v = M.negamax(actual, mascara, n, clave, d, -INF if v <= a else a, INF if v >= b else b)
                    if v <= a or v >= b:                    # (con la tabla, puede volver a caer fuera)
                        v = M.negamax(actual, mascara, n, clave, d, -INF, INF)
            else:
                v = M.negamax(actual, mascara, n, clave, d, -INF, INF)
        except SinTiempo:
            break                                          # límite duro: la iteración a medias se descarta
        e = M.tt[clave & (M.tam - 1)]                     # la mejor jugada de la raíz está en la tabla
        jugada, valor, completada = (e[4] if e and e[0] == clave else M.ultima), v, d
        if informe:
            print(f"  d = {d:2d}   valor {v:6d}   jugada {jugada + 1}   nodos de la iteración {M.nodos - antes:7d}"
                  f"   {time.perf_counter() - t0:5.2f} s")
        if abs(v) >= VICTORIA:
            break                                          # resultado demostrado: no hace falta seguir
        if segundos and time.perf_counter() - t0 > segundos / 3:
            break                                          # límite blando: la siguiente no llegaría a terminar
    M.limite = None
    return jugada, valor, completada

Motor.fallos_aspiracion = 0
MEDIO = ["274552224131661", "5455174361263362", "2531276566711153", "6614446666373154", "4642332434166445", "1113222154334225"]
d = 9
print(f"profundidad {d}, seis posiciones      nodos     b*   fallos de aspiración   valores")
for nombre, asp in (("directa a profundidad fija", None), ("iterativa", 0), ("iterativa + aspiración ±2", 2), ("iterativa + aspiración ±5", 5)):
    total, valores, fallos = 0, [], 0
    for p in MEDIO:
        M = Motor()
        if asp is None:
            v = M.negamax(*desde_cadena(p), d, -INF, INF)
        else:
            _, v, _ = pensar(desde_cadena(p), dmax=d, aspiracion=asp or None, motor=M, informe=False)
        total += M.nodos; valores.append(v); fallos += M.fallos_aspiracion
    print(f"{nombre:32s} {total:8d}   {b_efectivo(total / len(MEDIO), d):4.2f}   {fallos:10d}           {valores}")

All four configurations give the same values on all six positions, as expected: iterative deepening and aspiration windows change cost, not result. Counting nine iterations, iterative search visits 33 151 nodes, fewer than direct depth-9 search’s 34 419: the ordering left in the table repays the eight earlier iterations. A ±2 aspiration window worsens the result (35 666 nodes and 33 failures requiring re-search); ±5 barely improves it (32 889 nodes, 4 failures). The next cell shows why: Connect 4 values oscillate greatly between even and odd iterations because at the horizon the last mover had one extra move to create threats. With evaluation jumping like this, a narrow window around the previous value often fails. Chess engines, with more stable evaluations between iterations, also use aspiration windows and widen gradually after failure.

[ ]Thinking on a clockBrowser
pos = desde_cadena(MEDIO[0])
print("medio segundo de reloj desde", MEDIO[0])
j, v, d = pensar(pos, segundos=0.5)
print(f"juega la columna {j + 1} con valor {v} tras completar la profundidad {d}")

Completed iteration count depends on your machine’s speed (in the browser Pyodide is several times slower than native Python), so the move may vary by machine: this is timed search’s nature. What does not change is that a move is always ready, from the last completed iteration.

Fixed-depth search evaluates every position dd moves from the root, whatever its nature. If a capture just occurred and recapture is one move away, static evaluation counts gained material but not the immediate loss. Hans Berliner called this the horizon effect (1973) and distinguished two forms:

  • Positive: the engine thinks it wins something because refutation lies just beyond the horizon (a queen taking a defended pawn on the last examined move).
  • Negative: the engine sees an unavoidable loss and pushes it beyond the horizon with delaying moves that prevent nothing and also cost material.

The stand-pat assumption is the null-move observation: in almost every position, having to move does not hurt, so the player to move is worth at least the position’s value without moving. It fails in two situations shown in the figure and pruning section: when a threatened piece cannot be saved by any capture, and in zugzwang.

InteractiveThe horizon effect
+5+5−4+5+1+4+100D×TP×DquietC×PD×CA×DP×Aquietquietquiet
Game: D×T → P×D
starting position
  • MAX (▲) and MIN (▼) in the main search
  • nodes added by quiescence
  • dotted circle: evaluated at the horizon or with stand-pat
  • game played so far (dashed: remaining moves); outline: search root
  • move with check
Position
1
Chosen move at the marked nodeD×T
Engine estimate · true value+5 · +1
Nodes: main search · quiescence4 · 0
Game result · best possible−4 · +1
The horizon falls immediately after D×T: the evaluation counts the rook captured (+5) and misses P×D. The game ends at −4.
Two schematic positions with material as evaluation (positive favors MAX). ‘Poisoned capture’, depth 1: the engine thinks Q×R wins a rook (+5) because P×Q is beyond the horizon; play it and the game ends at −4. Enable quiescence: magenta nodes are added captures, evaluation changes to +1 and the move to N×P. Raise depth to 2 without quiescence: now the horizon cuts N×P mid-exchange. ‘Trapped rook’: MAX loses a rook whatever happens, and without extensions prefers sacrificing three pawns with check to delay loss. Check that quiescence alone does not fix this but check extensions do.

The figure teaches three things worth stating precisely:

  1. Quiescence fixes the positive horizon effect. Any capture sequence beginning at the horizon continues to a quiet position, eliminating mid-exchange evaluation. In the poisoned capture at depth 1 it adds 7 nodes and changes Q×R (losing −4-4) to N×P (gaining +1+1).
  2. It does not generally fix the negative effect. In the trapped rook, the horizon falls on a MAX node after a check and response. MAX stands pat on current material because it “could do nothing,” but its rook hangs: no capture saves it and quiescence does not examine opponent threats. With quiescence and no extensions the game ends at −7-7 or −6-6 by depth, instead of −4-4 for surrendering the rook for a pawn.
  3. Extensions fix delaying moves: do not spend depth on forced moves (a check and its response). Deep Blue devoted much of its design to this: its paper describes a “credit” system extending singular moves (much better than all alternatives), only legal responses and responses to threats detected by a null-move search, and quiescence including checks. Even this does not eliminate the horizon effect; it only pushes it farther away.

Quiescence costs arise because the capture tree can be huge in positions with many captures. Engines control it through ordering (most valuable victim, least valuable attacker, MVV-LVA, so e(s)≥βe(s) \ge \beta cutoff arrives early) and their own pruning: discard captures losing material according to static exchange evaluation (SEE), or those that even winning the captured piece could not reach α\alpha (delta pruning). The final coding exercise asks you to implement stand-pat quiescence and check it against exhaustive capture-sequence search.

Null windows: PVS and MTD(f)

The previous lesson showed a null-window search (α,α+1)(\alpha, \alpha + 1), answering only “does value exceed α\alpha?”, costs a fraction of computing the value. With integer evaluations that question has an exact answer: fail-soft result vv satisfies v≤αv \le \alpha (value is at most vv) or v≥α+1v \ge \alpha + 1 (at least vv).

PVS bets on good ordering: if the first child is best, all others fail low, and the null window proves this more cheaply than the full window. If wrong, it pays for two searches of the same child. Marsland and Campbell described it in 1982, and Reinefeld proposed an almost identical variant, NegaScout, in 1983, the one cited by Deep Blue. It computes exactly alpha-beta’s value: every null-window answer is a valid bound by the fail-soft correctness theorem, and when insufficient the search is repeated.

InteractiveNull windows and re-searches
1313≤11≤1213≥16≥15≥14≥15≤11≥18≤12441316614101561411411535511181181211141114
step 65 / 65
  • MAX (▲)
  • MIN (▼)
  • searched with a null window
  • re-searched with a full window
  • pruned branch
PVS leaves divided by alpha-beta leaves (average across hundreds of random trees): below the dashed line, PVS saves work
  • b = 3, d = 6
  • b = 5, d = 6
  • b = 8, d = 5
  • equal cost
Algorithm
0.5
Leaves in this tree: alpha-beta · PVS20 · 17
PVS re-searches1
Root value (both agree)13 · 13
Leaves evaluated so far17 of 17
Mean PVS / alpha-beta ratio with q = 0.5, for b = 3 · 5 · 81.17 · 1.03 · 0.89
The root returns 13.
Above, a tree with b=3b = 3 and d=3d = 3 traversed step by step. With PVS, nodes with dashed magenta outlines are searched with null windows, and orange-edged nodes re-searched with the full window because the null window returned inside (α,β)(\alpha, \beta). Initially, with q=0.5q = 0.5, PVS evaluates 17 leaves versus alpha-beta's 20, with one re-search; rewind and find the orange step. Change algorithm, raise and lower qq, and try other trees. Below, mean leaf ratio in larger trees: with poor ordering re-searches make PVS lose up to 53%; with good ordering it saves up to 12% with b=8b = 8; with perfect order both visit exactly the minimal tree.

The graph summarizes the tradeoff with model data: at each node, with probability qq the best child goes first and the rest in random order. With q=1q = 1 both algorithms agree, because perfect-order alpha-beta already visits Knuth and Moore’s minimal tree and nothing can be saved. With low qq PVS loses: many null windows fail high and each causes a re-search. In the middle and high region, where real engines with transposition tables live, PVS wins, increasingly as bb grows because more siblings can be refuted with the cheap window: with b=8b = 8 and d=5d = 5, the ratio falls to 0.875 with q=0.7q = 0.7; with b=3b = 3 and d=6d = 6, PVS never wins in this model. The Connect 4 lab (b≤7b \le 7, center order and table) was in the good region: 16% fewer nodes.

MTD(f): null windows only

Plaat, Schaeffer, Pijls and de Bruin (1996) took the idea to its extreme with MTD(f): search the root only with null windows, like binary search for the value. With guess ff (for example the previous iteration’s value), search with window (γ−1,γ)(\gamma - 1, \gamma), γ=f\gamma = f; if result gg fails low, gg is an upper bound; if high, a lower bound; repeat with γ\gamma at the new bound until both meet. Each pass reuses everything the previous left in the table; without a table this would be impractical. In their experiments with tournament-level chess, checkers and Othello programs, MTD(f) visited fewer nodes than NegaScout. Its weakness is table dependence: each pass needs the previous one still present.

[ ]MTD(f) on test positionsBrowser
def mtdf(M, pos, f, d):
    """MTD(f): búsquedas con ventana nula que acotan el valor por los dos lados hasta que las cotas se encuentran."""
    g, inferior, superior, pasadas = f, -INF, INF, 0
    while inferior < superior:
        gamma = g + 1 if g == inferior else g              # pregunta: ¿el valor es >= gamma?
        g = M.negamax(*pos, d, gamma - 1, gamma)
        pasadas += 1
        if g < gamma:
            superior = g                                   # falla por abajo: cota superior
        else:
            inferior = g                                   # falla por arriba: cota inferior
    return g, pasadas

for nombre, kw in (("con historia", {}), ("sin historia", dict(historia=False))):
    nodos_pvs = nodos_mtd = pasadas = ok = 0
    for jugadas, esperado in PRUEBAS:
        pos = desde_cadena(jugadas)
        M = Motor(**kw); resolver(M, pos); nodos_pvs += M.nodos
        M = Motor(**kw); v, k = mtdf(M, pos, 0, W * H - pos[2]); nodos_mtd += M.nodos; pasadas += k
        ok += pons(v) == esperado
    print(f"{nombre}: PVS {nodos_pvs} nodos, MTD(f) desde f = 0 {nodos_mtd} nodos en {pasadas} pasadas "
          f"({pasadas / len(PRUEBAS):.1f} por posición), bien {ok}/{len(PRUEBAS)}")

MTD(f) gets all 30 scores right with about three null-window passes per position from guess f=0f = 0. Compared with PVS in the same configuration, results depend on ordering: with history it visits 93 466 nodes versus 118 489 (21% less), and without it 54 157 versus 52 668 (3% more). This is general: MTD(f) performance depends strongly on the table and initial guess. Most current chess engines, including Stockfish, use PVS.

Forward pruning

Everything above preserves minimax value: the table, quiescence (which changes only what is evaluated at the horizon) and PVS discard nothing that could matter. Forward pruning does: it discards or reduces branches without searching them, betting they do not matter. This is Shannon’s “type B strategy,” abandoned by chess programming for decades and recovered by modern engines with safeguards. The two most important:

Null-move pruning. At a node with remaining depth dd and window (α,β)(\alpha, \beta), the player to move “passes”: search with the opponent to move, reduced depth d−1−Rd - 1 - R (with R=2R = 2 or 3) and a null window around β\beta. If even after giving away a move the result is ≥β\ge \beta, assume some real move will be too and cut off without searching any. The justification is the null-move observation, as in stand-pat: moving almost never worsens. Reduced search is so cheap the pruning more than pays.

Late move reductions (LMR). With good ordering, moves late in the list are almost never best. Search them at reduced depth (here d−2d - 2 instead of d−1d - 1) and a null window; only if they surprise by exceeding α\alpha are they re-searched at full depth.

Their risks differ:

  • Null move fails in zugzwang, positions where the player to move would prefer to pass because every legal move worsens the position. There “passing” overestimates value, null-move search exceeds β\beta, and a branch is incorrectly pruned. In chess zugzwang arises mainly in pawn endgames. Common safeguards: do not use it in check (passing is illegal), when the player has only king and pawns, or twice consecutively; some engines verify cutoff with ordinary reduced search (verified null-move pruning, Tabibi and Netanyahu, 2002).
  • LMR fails when ordering fails: a good move placed late and reduced may not surprise at reduced depth and is then lost. Larger reductions risk more.

Connect 4 is the worst possible terrain for null move: passing is illegal and the game is dominated by zugzwang. Victor Allis’s 1988 solution rests precisely on controlling zugzwang: who must play below an opponent threat square. The next two cells enable each pruning technique in the full engine and solve the 30 positions again, whose exact scores are known.

[ ]Null move in a zugzwang gameBrowser
def podas(nombre, **kw):
    total, mal = 0, []
    for jugadas, esperado in PRUEBAS:
        M = Motor(**kw)
        v = resolver(M, desde_cadena(jugadas))
        total += M.nodos
        if v != esperado:
            mal.append((jugadas, esperado, v))
    print(f"{nombre:26s} {total:7d} nodos   puntuaciones erróneas: {len(mal)}")
    for jugadas, esperado, v in mal:
        cambia = (esperado > 0) - (esperado < 0) != (v > 0) - (v < 0)
        print(f"    {jugadas}: Pons {esperado:3d}, motor {v:3d}" + ("   <- cambia el resultado" if cambia else ""))

podas("sin podas hacia delante")
podas("jugada nula, R = 2", nulo=True)
[ ]Late move reductionsBrowser
podas("LMR desde la 4.ª jugada", lmr=True)

The data are clear. With null move, the engine gets 4 of 30 exact scores wrong, in one case changing the result: a won position (score 2) appears drawn. It does not even save work: 156 433 nodes versus 118 489, because in a zugzwang game search after “passing” rarely reaches β\beta and is nearly always added cost. LMR makes no errors on this benchmark because re-searches recover surprising moves, but visits 39% more nodes (164 499): with b≤7b \le 7, center order and searches reaching game end, few late moves are worth reducing, and re-searches cost more than they save. Forward pruning suits wide, deep trees with good ordering, such as chess (b≈35b \approx 35), where Stockfish combines it with many additional conditions, each validated by games on its test platform. Transplanting it blindly to another game can hurt.

The evaluation function

What should it estimate? If outcomes win, draw and loss score 1, 1/2 and 0, a useful evaluation is an increasing function of the player-to-move’s expected score P(gana)+12P(tablas)\Pr(\text{gana}) + \frac{1}{2}\Pr(\text{tablas}) under reasonable subsequent play by both sides. Minimax cares only about evaluation order, not scale (you will prove this); tuning weights, however, benefits from a meaningful scale: expected score.

Tuning weights from game results

The method Peter Österlund popularized in 2014 with his Texel engine (Miguel Ballicora described a similar one in 2009 for Gaviota) is regression: take many positions from played games, each labeled with the game’s eventual outcome Ri∈{0,12,1}R_i \in \{0, \frac{1}{2}, 1\} for the player to move, and minimize squared error between outcome and a sigmoid of evaluation:

E(w)=1N∑i=1N(Ri−σ(w⊤xi))2,σ(z)=11+e−z.E(\vb{w}) = \frac{1}{N}\sum_{i=1}^{N}\Big(R_i - \sigma\big(\vb{w}\T\vb{x}_i\big)\Big)^2, \qquad \sigma(z) = \frac{1}{1 + e^{-z}}.

Österlund writes the sigmoid as 1/(1+10−Kqi/400)1/(1 + 10^{-K q_i / 400}), with qiq_i the evaluation in centipawns after quiescence and constant KK fitted once; this is the same function with weights on another scale. The gradient is direct:

∇E(w)=−2N∑i=1N(Ri−σi) σi (1−σi) xi,σi=σ(w⊤xi),\grad E(\vb{w}) = -\frac{2}{N}\sum_{i=1}^{N}\big(R_i - \sigma_i\big)\,\sigma_i\,(1 - \sigma_i)\,\vb{x}_i, \qquad \sigma_i = \sigma(\vb{w}\T\vb{x}_i),

and minimized with gradient descent. Using log-likelihood instead of squared error would be exactly logistic regression with fractional labels. Texel’s figures suggest scale: about 8.8 million positions from 64 000 rapid games, about 400 parameters and, across several tuning rounds, about 100 Elo points improvement measured with 32 000 games (Chess Programming Wiki, “Texel’s Tuning Method”).

Two details matter. Labels are noisy: a winning position may end in defeat after a later mistake, and only averages over many positions make sense. Positions must also be quiet (Texel evaluates with quiescence), because evaluation mid-exchange is meaningless.

Lab: tuning Connect 4 evaluation

Four features, all differences between the player to move and the opponent: threats (empty squares completing four in a row), threats in the “good” row by parity (for the first player odd rows from the bottom; for the other, even: Allis’s rule), center-column pieces, and four-square windows with two own pieces and two empty. The previous lesson’s evaluation is 3⋅amenazas+centro3 \cdot \text{amenazas} + \text{centro}.

Data come from self-play: 600 games by a player searching depth 1 with the previous lesson’s evaluation and playing randomly for the first four moves and 20% of the rest for variety. Save all positions from the sixth piece onward where the player to move cannot win in one, labeled with the final result from their perspective. Reserve the last 150 games for validation.

[ ]Self-play dataBrowser
import random, math
import numpy as np

VENTANAS = []                                      # las 69 líneas de cuatro casillas, como máscaras de bits
for c in range(W):
    for f in range(H):
        for dc, df in ((1, 0), (0, 1), (1, 1), (1, -1)):
            cs = [(c + k * dc, f + k * df) for k in range(4)]
            if all(0 <= x < W and 0 <= y < H for x, y in cs):
                VENTANAS.append(sum(1 << (x * H1 + y) for x, y in cs))
IMPARES = sum(1 << (c * H1 + f) for c in range(W) for f in (0, 2, 4))   # filas 1, 3 y 5 desde abajo
PARES = TABLERO ^ IMPARES
NOMBRES = ("amenazas", "amenazas de paridad", "centro", "dobles abiertas")

def rasgos(actual, mascara, n):
    """Cuatro características, como diferencia entre el jugador al turno y su rival."""
    rival = actual ^ mascara
    am, ar = amenazas(actual, mascara), amenazas(rival, mascara)
    mi_par, su_par = (IMPARES, PARES) if n % 2 == 0 else (PARES, IMPARES)   # n par: juega quien empezó
    dobles = 0
    for v in VENTANAS:
        a, r = (actual & v).bit_count(), (rival & v).bit_count()
        if a == 2 and r == 0:
            dobles += 1
        elif r == 2 and a == 0:
            dobles -= 1
    return (am.bit_count() - ar.bit_count(), (am & mi_par).bit_count() - (ar & su_par).bit_count(),
            (actual & COLUMNA[3]).bit_count() - (rival & COLUMNA[3]).bit_count(), dobles)

def partida(rnd, ev_primero, ev_segundo, d=2, eps=0.0, apertura=4, guardar=None):
    """Una partida. Devuelve la puntuación del primer jugador (1, 0.5 o 0)."""
    pos = (0, 0, 0, 0)
    motores = (Motor(evaluacion=ev_primero, historia=False), Motor(evaluacion=ev_segundo, historia=False))
    while True:
        actual, mascara, n, clave = pos
        if n == W * H:
            return 0.5
        if amenazas(actual, mascara) & (mascara + FONDO) & TABLERO:      # el jugador al turno gana ya
            return 1.0 if n % 2 == 0 else 0.0
        if guardar is not None and n >= 6:
            guardar.append((actual, mascara, n))
        if n < apertura or rnd.random() < eps:
            c = rnd.choice([c for c in range(W) if not mascara & ARRIBA[c]])
        else:
            M = motores[n % 2]
            M.negamax(actual, mascara, n, clave, d, -INF, INF)
            c = M.ultima
        pos = jugar(*pos, c)

rnd = random.Random(1)
X, y, partida_de = [], [], []
resultados = []
for g in range(600):
    vistas = []
    r = partida(rnd, evaluar, evaluar, d=1, eps=0.2, guardar=vistas)
    resultados.append(r)
    for actual, mascara, n in vistas:
        X.append(rasgos(actual, mascara, n))
        y.append(r if n % 2 == 0 else 1 - r)        # resultado para el jugador al turno
        partida_de.append(g)
X, y, partida_de = np.array(X, dtype=float), np.array(y), np.array(partida_de)
print(f"{len(X)} posiciones de 600 partidas; gana quien empieza {resultados.count(1.0)}, "
      f"tablas {resultados.count(0.5)}, gana el segundo {resultados.count(0.0)}")
[ ]Weight tuning by gradient descentBrowser
entreno, valida = partida_de < 450, partida_de >= 450
sig = lambda z: 1 / (1 + np.exp(-z))
def error(w, mask):
    return np.mean((y[mask] - sig(X[mask] @ w)) ** 2)

def ajustar(w, mask, pasos=2000, eta=0.5):
    Xm, ym = X[mask], y[mask]
    for _ in range(pasos):
        s = sig(Xm @ w)
        w = w + eta * 2 * ((ym - s) * s * (1 - s)) @ Xm / len(ym)    # w - eta * gradiente
    return w

a_mano = np.array([3.0, 0.0, 1.0, 0.0])                # la evaluación de la lección anterior
Ks = np.linspace(0.01, 1, 100)
K = Ks[np.argmin([error(k * a_mano, entreno) for k in Ks])]   # su mejor escala, como la K de Texel
w = ajustar(K * a_mano, entreno)
print(f"error cuadrático en validación:  constante {np.mean((y[valida] - y[entreno].mean()) ** 2):.4f}   "
      f"a mano (con K = {K:.2f}) {error(K * a_mano, valida):.4f}   ajustada {error(w, valida):.4f}")
print("en entrenamiento:                a mano", f"{error(K * a_mano, entreno):.4f}   ajustada {error(w, entreno):.4f}")
print("pesos ajustados:", ", ".join(f"{nm} {wi:.3f}" for nm, wi in zip(NOMBRES, w)))
print("pesos a mano reescalados:", ", ".join(f"{nm} {wi:.3f}" for nm, wi in zip(NOMBRES, K * a_mano)))

The 600 games yield 6283 positions. Read squared errors at their scale: always predicting the training mean score gives 0.2434 on validation; the previous lesson’s evaluation (rescaled with its best KK) drops to 0.2276, and the tuned one to 0.2156. Improvement looks small because outcomes between such imprecise players depend heavily on what happens later: no weights can predict future mistakes. What matters is that tuning also wins on 150 unseen games and weights make sense: threats still weigh most (0.305), favorable-parity threats add more (0.133), and open two-piece lines, ignored by handcrafted evaluation, receive a clearly positive weight (0.122).

The test that matters is playing. Each match has 50 random four-piece openings, each played twice with colors swapped so neither version benefits from a favorable opening. Both search depth 2. The Elo interval uses a normal approximation to mean score, explained in the last section.

[ ]Tournament: tuned and handcrafted versus center onlyBrowser
def ev_ajustada(actual, mascara, n):
    return round(100 * float(np.dot(w, rasgos(actual, mascara, n))))
def ev_a_mano(actual, mascara, n):
    return evaluar(actual, mascara)
def ev_centro(actual, mascara, n):
    return (actual & COLUMNA[3]).bit_count() - ((actual ^ mascara) & COLUMNA[3]).bit_count()

def elo(s):
    return -400 * math.log10(1 / s - 1)

def match(ev_a, ev_b, aperturas=50, semilla=5):
    """ev_a contra ev_b: cada apertura aleatoria de 4 fichas se juega dos veces, con los colores cambiados.
    Devuelve los puntos de ev_a, partida a partida."""
    rnd = random.Random(semilla)
    puntos = []
    for _ in range(aperturas):
        s = rnd.getrandbits(32)
        puntos.append(partida(random.Random(s), ev_a, ev_b))
        puntos.append(1 - partida(random.Random(s), ev_b, ev_a))
    return np.array(puntos)

def informe(x):
    """Puntuación media, Elo y su intervalo del 95 % (aproximación normal de la media de puntos)."""
    n, m = len(x), x.mean()
    ee = x.std() / math.sqrt(n)
    g, e, p = (x == 1).sum(), (x == 0.5).sum(), (x == 0).sum()
    return (f"{n} partidas  +{g} ={e} -{p}  puntuación {m:.3f}  Elo {elo(m):+.0f}"
            f"  IC 95 % [{elo(m - 1.96 * ee):+.0f}, {elo(m + 1.96 * ee):+.0f}]")

print("ajustada contra solo centro: ", informe(match(ev_ajustada, ev_centro)))
print("a mano contra solo centro:   ", informe(match(ev_a_mano, ev_centro)))
[ ]Tournament: tuned versus the previous lessonBrowser
x5 = match(ev_ajustada, ev_a_mano, semilla=5)
x6 = match(ev_ajustada, ev_a_mano, semilla=6)
print("ajustada contra a mano, aperturas A: ", informe(x5))
print("ajustada contra a mano, aperturas B: ", informe(x6))
print("las dos juntas:                      ", informe(np.concatenate([x5, x6])))

Against an evaluation counting only central pieces, both win clearly: tuned by +131 Elo, 95% interval [+68, +204], and the previous lesson’s by +108, [+49, +173]. Intervals overlap almost entirely: these 100 games do not establish which is better against that opponent.

The direct match shows what validation really costs. With the first 50 openings, tuned wins by +85 [+22, +155], excluding zero. With another 50 openings the same match yields +21 [−43, +86], no longer excluding zero. Pooling 200 games gives +53 with interval [+8, +99]: tuned is probably better, but uncertainty is enormous, on the order of the improvement itself. Declaring the result after the first match would estimate improvement 60% higher than the 200-game result (+85 versus +53). Full tuning (more self-play, features and deeper tournament searches) uses the same lab; what changes is thousands of games are needed to measure smaller improvements, as the last section explains.

From features to networks: NNUE

Tuning weights by hand or Texel does not solve the fundamental problem: choosing features. Deep Blue had about 8000, most with hand-tuned weights; its authors said “automatic and manual” tuning was far from complete. The alternative is to learn features too. Yu Nasu proposed in 2018 for shogi a small network whose first-layer input consists of very sparse binary features (such as “piece pp on square cc, with my king on square rr”) and can be updated incrementally: since a move changes very few inputs, the expensive first-layer output is updated by adding and subtracting a few weight columns, like updating a Zobrist key with a few XORs. Hence NNUE (efficiently updatable neural network), and why it fits inside alpha-beta, which evaluates millions of positions per second. Stockfish adopted it in August 2020; published tests then gave NNUE evaluation 92.77 ± 2.1 Elo over classical in 60 000 games at 10 seconds plus 0.1 per move, and 89.47 ± 2.0 in 40 000 slower games with 8 threads. AlphaZero goes further, replacing evaluation and alpha-beta search with a network and Monte Carlo Tree Search.

Games with chance: expectiminimax

In backgammon legal moves depend on dice. The tree has three node types: MAX, MIN, and chance nodes whose children are roll outcomes with their probabilities.

If each move has bb alternatives and nn chance outcomes, the tree through mm moves has on the order of bmnmb^m n^m nodes. In backgammon n=21n = 21 (distinct two-dice rolls) and bb is usually around 20 (Russell and Norvig, Artificial Intelligence: A Modern Approach): deep search is infeasible, and strong backgammon programs since TD-Gammon search very little and rely on learned evaluation. Pruning is harder too: at a chance node a child cannot be discarded without knowing the others unless evaluation is bounded, L≤e≤UL \le e \le U. With bounds, Ballard’s (1983) *-minimax algorithms bound the mean before seeing all children: if seen children plus unseen ones valued at UU cannot reach α\alpha, the chance node can be cut off.

A deeper difference from minimax is shown in the figure.

InteractiveChance and evaluation scale
A314243544546mean 16.33B1122031495106mean 31.17transformed leaves, f(x) = x²
  • mean transformed leaf, colored by move (expectiminimax value)
  • worst leaf (minimax value)
  • move chosen by expectiminimax
Evaluation transformation
10
Expectiminimax: mean of A · mean of B16.33 · 31.17
Choice (expectiminimax)B
Minimax with die as adversary: worst of A · worst of B9.00 · 0.00
Choice (minimax)A
Without transformationexpectiminimax A, minimax A
With f(x)=x2f(x) = x^2 expectiminimax changes from A to B: the transformation preserves leaf order but not mean order. Minimax still chooses A.
MAX chooses A or B and a die is rolled. Expectiminimax values each move by its six-leaf mean (colored dashed line); minimax, treating the die as an opponent, by its worst leaf (gray dotted line). With original evaluation expectiminimax chooses A (mean 4 versus 3.83). With f(x)=x2f(x) = x^2, preserving leaf order, it chooses B (mean 31.17 versus 16.33): B's large leaves weigh more. Try x\sqrt{x} and 2x2^x, and the affine 2x+32x + 3, which never changes the choice. Minimax chooses A under any transformation. Click a leaf to change its value and seek other changes.

In minimax only evaluation order matters: any strictly increasing transformation of all leaves preserves the move. In expectiminimax evaluation is averaged, and averaging does not preserve order under nonlinear transformations. A chance-game evaluation must be proportional to something meaningful, such as expected score or win probability, not merely order positions correctly. This is expected utility in decision theory: utility is defined up to positive affine transformations, not arbitrary monotone transformations. You will prove this in the guided exercise; the cell quantifies it on random trees.

[ ]Monotone transformations and expectiminimaxBrowser
import numpy as np
rng = np.random.default_rng(0)
T = 20000
hojas = rng.uniform(0, 10, size=(T, 3, 6))    # 3 jugadas de MAX, un dado de 6 caras, hojas en [0, 10]
base_media = hojas.mean(axis=2).argmax(axis=1)
base_peor = hojas.min(axis=2).argmax(axis=1)
print(f"{T} árboles: MAX elige entre 3 jugadas y después se tira un dado")
print("transformación     cambia la elección de expectiminimax   cambia la de minimax")
for nombre, f in (("2x + 3", lambda x: 2 * x + 3), ("x^2", np.square), ("raíz de x", np.sqrt), ("2^x", np.exp2)):
    fh = f(hojas)
    cambia_e = (fh.mean(axis=2).argmax(axis=1) != base_media).mean()
    cambia_m = (fh.min(axis=2).argmax(axis=1) != base_peor).mean()
    print(f"{nombre:16s}   {cambia_e:10.1%}                            {cambia_m:6.1%}")

No transformation ever changes minimax’s choice, and the affine one does not change expectiminimax’s either. Nonlinear ones change it in an appreciable fraction of trees: 11.3% with x2x^2, 8.9% with x\sqrt{x}, and 29.0% with 2x2^x, the furthest from a straight line on [0,10][0, 10]. If your backgammon evaluation measures “how good the position is” on an arbitrary scale, expectiminimax is not optimizing anything well-defined.

Validating a change: from Deep Blue to Stockfish

You changed something in the engine. Is it better? The only reliable answer is to play many games against the old version, and statistics are less forgiving than they seem.

The Elo model. If the new version is Δ\Delta Elo points above the old one, its expected score per game is

s(Δ)=11+10−Δ/400,Δ(s)=400log⁡10s1−s.s(\Delta) = \frac{1}{1 + 10^{-\Delta/400}}, \qquad \Delta(s) = 400 \log_{10}\frac{s}{1 - s}.

Near Δ=0\Delta = 0, s′(0)=ln⁡10/1600≈0.00144s'(0) = \ln 10 / 1600 \approx 0.00144: one Elo point is 0.144% of score. Ten Elo points, an improvement any engine developer would celebrate, mean a score of 0.514 versus 0.5.

Noise. A game’s score is a variable taking 1, 1/2 or 0. If draw rate is DD and expected score 1/21/2, its variance is (1−D)/4(1 - D)/4, and variance of the mean over nn games is (1−D)/(4n)(1 - D)/(4n). By the delta method, the 95% Elo interval has half-width

± 1.96⋅1600ln⁡101−D4n≈± 6811−Dn puntos de Elo.\pm\, 1.96 \cdot \frac{1600}{\ln 10} \sqrt{\frac{1 - D}{4n}} \approx \pm\, 681 \sqrt{\frac{1 - D}{n}} \text{ puntos de Elo}.

With D=0.6D = 0.6 and 20 games, about ±96\pm 96 points; with 200, ±30\pm 30; with 20 000, ±3\pm 3. Declaring improvement from a few dozen games is reading noise.

Sequential tests. Fixing nn in advance wastes games: a bad change is apparent early and so is a very good one. Wald’s sequential probability ratio test (SPRT) compares two hypotheses H0:Δ=Δ0H_0: \Delta = \Delta_0 and H1:Δ=Δ1H_1: \Delta = \Delta_1, updating log likelihood ratio after every game and stopping as soon as it leaves band (log⁡β1−α,log⁡1−βα)\big(\log\frac{\beta}{1-\alpha}, \log\frac{1-\beta}{\alpha}\big); with α=β=0.05\alpha = \beta = 0.05, (−2.94,2.94)(-2.94, 2.94). With a normal approximation to mean score xˉ\bar{x}, variance σ2\sigma^2, log ratio is

log⁡Λn=∑i=1n(xi−s0)2−(xi−s1)22σ2=n (s1−s0) (2xˉ−s0−s1)2σ2,sj=s(Δj).\log\Lambda_n = \sum_{i=1}^{n}\frac{(x_i - s_0)^2 - (x_i - s_1)^2}{2\sigma^2} = \frac{n\,(s_1 - s_0)\,(2\bar{x} - s_0 - s_1)}{2\sigma^2}, \qquad s_j = s(\Delta_j).

Fishtest, the distributed platform testing every Stockfish change, works this way: a patch plays the main version until SPRT accepts or rejects it, often after tens of thousands of games. The NNUE figures above (92.77 ± 2.1 with 60 000 games) show the order of magnitude needed to assert a difference to two-point precision.

InteractiveHow many games are needed?
Elo estimate versus number of games (logarithmic scale)
  • Estimated Elo (band: 95% interval)
  • True Elo
SPRT: the test stops the first time the log likelihood ratio leaves the band
  • log likelihood ratio
  • upper bound: accept H1
  • lower bound: accept H0
3.0
60 %
5.0
Win · draw · loss per game0.204 · 0.600 · 0.196
Estimated Elo after 20 games−35 [−121, +48]
After 200−12 [−43, +18]
After 2000+4 [−6, +13]
After 20000+5 [+2, +8]
SPRT accepts H1 (Δ=5\Delta = 5) after 6700 games. With true Elo 3.0, this is the correct decision (closer to H1 than H0).
A simulated match between engine versions with true Elo difference Δ\Delta and fixed draw rate (this section's Elo model). Above, estimated Elo with 95% interval on a logarithmic game-count scale: at 20 games the interval spans over 150 points. Below, SPRT log likelihood ratio between H0:Δ=0H_0: \Delta = 0 and H1:Δ=Δ1H_1: \Delta = \Delta_1, stopping when it leaves the band; the vertical line marks the decision. With Δ=3\Delta = 3 and Δ1=5\Delta_1 = 5, truth lies between hypotheses and the test takes thousands of games. Try Δ=10\Delta = 10, Δ=0\Delta = 0 and other matches with the same Δ\Delta: game count varies greatly by seed.

Lab: a minimal chess engine

The chess library (python-chess) provides legal move generation, mate and draw detection, and Polyglot-format Zobrist keys (chess.polyglot.zobrist_hash). On top, the engine uses this lesson’s techniques: negamax with alpha-beta, timed iterative deepening, a transposition table with mate scores adjusted to node distance, and stand-pat quiescence with captures ordered by MVV-LVA and all evasions in check. Evaluation is material plus a small bonus for occupying the center. Pure-Python move generation is slow, so this cell runs on your machine (runtime=local); positions are built by playing moves from the start, avoiding hand-written FEN that could be wrong. If Stockfish is installed on PATH, the last part plays two games against its lowest level.

[ ]A minimal chess engine with python-chessLocal GPU
import time, shutil
import chess, chess.polyglot

VALOR = {chess.PAWN: 100, chess.KNIGHT: 320, chess.BISHOP: 330, chess.ROOK: 500, chess.QUEEN: 900, chess.KING: 0}
MATE, CASI_MATE = 100_000, 99_000
EXACTO, INFERIOR, SUPERIOR = 0, 1, 2
CENTRO = chess.SquareSet([chess.D4, chess.E4, chess.D5, chess.E5])

def evaluar(b):
    """Material y un pequeño premio por ocupar el centro, para el bando al turno."""
    s = 0
    for tipo, v in VALOR.items():
        s += v * (len(b.pieces(tipo, chess.WHITE)) - len(b.pieces(tipo, chess.BLACK)))
    s += 10 * (sum(1 for c in CENTRO if b.color_at(c) == chess.WHITE) - sum(1 for c in CENTRO if b.color_at(c) == chess.BLACK))
    return s if b.turn == chess.WHITE else -s

def victima(b, m):
    return VALOR[chess.PAWN] if b.is_en_passant(m) else VALOR[b.piece_type_at(m.to_square)]

def mvv_lva(b, m):
    """Víctima más valiosa primero; a igual víctima, atacante menos valioso."""
    return 10 * victima(b, m) - VALOR[b.piece_type_at(m.from_square)] // 10

class Ajedrez:
    def __init__(self, quiescencia=True, tabla=True, ajustar_mates=True):
        self.qs, self.usa_tt, self.ajustar = quiescencia, tabla, ajustar_mates
        self.tt = {}
        self.nodos = self.nodos_q = 0
        self.limite = None

    # valores de mate en la tabla: «mate en k desde ESTE nodo», no desde la raíz
    def a_tabla(self, v, ply):
        if not self.ajustar:
            return v
        return v + ply if v > CASI_MATE else v - ply if v < -CASI_MATE else v

    def de_tabla(self, v, ply):
        if not self.ajustar:
            return v
        return v - ply if v > CASI_MATE else v + ply if v < -CASI_MATE else v

    def quiescencia(self, b, alfa, beta, ply):
        self.nodos_q += 1
        en_jaque = b.is_check()
        if en_jaque:                                   # en jaque no se puede plantar: todas las evasiones
            mejor = -MATE + ply
            jugadas = list(b.legal_moves)
        else:
            mejor = evaluar(b)                         # stand-pat
            if mejor >= beta:
                return mejor
            alfa = max(alfa, mejor)
            jugadas = sorted((m for m in b.legal_moves if b.is_capture(m)), key=lambda m: -mvv_lva(b, m))
        for m in jugadas:
            b.push(m)
            v = -self.quiescencia(b, -beta, -alfa, ply + 1)
            b.pop()
            if v > mejor:
                mejor = v
                if v > alfa:
                    alfa = v
                    if alfa >= beta:
                        break
        return mejor

    def negamax(self, b, d, alfa, beta, ply):
        if self.limite and not self.nodos & 255 and time.perf_counter() > self.limite:
            raise TimeoutError
        if ply > 0 and (b.is_repetition(2) or b.halfmove_clock >= 100 or b.is_insufficient_material()):
            return 0
        if d <= 0:
            if self.qs:
                return self.quiescencia(b, alfa, beta, ply)
            self.nodos += 1
            return evaluar(b)
        self.nodos += 1
        clave = chess.polyglot.zobrist_hash(b)
        alfa0, jugada_tt = alfa, None
        e = self.tt.get(clave) if self.usa_tt else None
        if e is not None:
            de, tipo, vt, jugada_tt = e
            v = self.de_tabla(vt, ply)
            if de >= d and ply > 0 and (tipo == EXACTO or (tipo == INFERIOR and v >= beta) or (tipo == SUPERIOR and v <= alfa)):
                return v
        jugadas = list(b.legal_moves)
        if not jugadas:
            return -MATE + ply if b.is_check() else 0
        jugadas.sort(key=lambda m: -(10**6 if m == jugada_tt else mvv_lva(b, m) if b.is_capture(m) else 0))
        mejor, mj = -MATE - 1, jugadas[0]
        for m in jugadas:
            b.push(m)
            v = -self.negamax(b, d - 1, -beta, -alfa, ply + 1)
            b.pop()
            if v > mejor:
                mejor, mj = v, m
                if v > alfa:
                    alfa = v
                    if alfa >= beta:
                        break
        tipo = SUPERIOR if mejor <= alfa0 else INFERIOR if mejor >= beta else EXACTO
        if self.usa_tt:
            self.tt[clave] = (d, tipo, self.a_tabla(mejor, ply), mj)
        return mejor

    def pensar(self, b, segundos=5.0, dmax=8, informe=False):
        """Profundización iterativa con reloj. Devuelve (jugada, valor, profundidad completada)."""
        self.limite = time.perf_counter() + segundos
        jugada = valor = None
        completada = 0
        for d in range(1, dmax + 1):
            try:
                v = self.negamax(b, d, -MATE - 1, MATE + 1, 0)
            except TimeoutError:
                break
            jugada, valor, completada = self.tt[chess.polyglot.zobrist_hash(b)][3], v, d
            if informe:
                print(f"  d = {d}: {b.san(jugada)}  valor {valor}  nodos {self.nodos} + {self.nodos_q} de quiescencia")
            if abs(v) > CASI_MATE:
                break
        self.limite = None
        return jugada, valor, completada

def tras(san):
    b = chess.Board()
    for s in san.split():
        b.push_san(s)
    return b

def texto_valor(v):
    if v > CASI_MATE:
        return f"mate en {(MATE - v + 1) // 2}"
    if v < -CASI_MATE:
        return f"recibe mate en {(MATE + v) // 2}"
    return f"{v} centipeones"

problemas = [
    ("mate en 1 (blancas)", "e4 e5 Bc4 Nc6 Qh5 Nf6", "Qxf7#"),
    ("mate en 1 (negras)", "f3 e5 g4", "Qh4#"),
    ("mate de Légal, en 2", "e4 e5 Nf3 d6 Bc4 Bg4 Nc3 g6 Nxe5 Bxd1", "Bxf7+"),
]
for nombre, san, esperada in problemas:
    b = tras(san)
    A = Ajedrez()
    t = time.perf_counter()
    j, v, d = A.pensar(b, segundos=20, dmax=5)
    linea, bb = [], b.copy()
    for _ in range(5):                                  # variante principal desde la tabla
        e = A.tt.get(chess.polyglot.zobrist_hash(bb))
        if not e or bb.is_game_over():
            break
        linea.append(bb.san(e[3])); bb.push(e[3])
    print(f"{nombre}: {b.san(j)} ({texto_valor(v)}), profundidad {d}, {A.nodos} + {A.nodos_q} nodos, "
          f"variante {' '.join(linea)}, ¿termina en mate? {bb.is_checkmate()}, esperada {esperada}: {b.san(j) == esperada}")

# quiescencia: tras 1.e4 e5 2.Qh5 Nc6, las capturas de la dama en e5 o f7 pierden la dama
b = tras("e4 e5 Qh5 Nc6")
for d in (1, 2):
    for qs in (False, True):
        A = Ajedrez(quiescencia=qs)
        j, v, _ = A.pensar(b, segundos=20, dmax=d)
        print(f"profundidad {d}, quiescencia {'sí' if qs else 'no'}: {b.san(j):6s} valor {v:5d}  ({A.nodos} + {A.nodos_q} nodos)")

if shutil.which("stockfish"):
    import chess.engine
    with chess.engine.SimpleEngine.popen_uci(shutil.which("stockfish")) as sf:
        sf.configure({"Skill Level": 0})
        puntos = 0.0
        for color in (chess.WHITE, chess.BLACK):
            b = chess.Board()
            while not b.is_game_over() and b.fullmove_number < 80:
                if b.turn == color:
                    j, _, _ = Ajedrez().pensar(b, segundos=2, dmax=6)
                else:
                    j = sf.play(b, chess.engine.Limit(time=0.05)).move
                b.push(j)
            r = b.result(claim_draw=True)
            puntos += 1.0 if r == ("1-0" if color == chess.WHITE else "0-1") else 0.5 if r in ("1/2-1/2", "*") else 0.0
            print("con", "blancas" if color == chess.WHITE else "negras", ":", r)
        print("puntos contra Stockfish con nivel 0:", puntos, "de 2")
else:
    print("Stockfish no está instalado: descárgalo de stockfishchess.org y ponlo en el PATH para jugar contra él.")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The engine finds both mates in one and Légal’s mate in two (6.Bxf7+ Ke7 7.Nd5#; the cell prints moves in the library’s English notation, B for bishop and N for knight), with the full variation, and checks it ends in mate. The second part shows the horizon effect in real chess: after 1.e4 e5 2.Qh5 Nc6, at depth 1 without quiescence the engine plays 3.Qxe5+ believing it wins a pawn (120 centipawns: pawn plus center bonus), missing the c6 knight recapturing the queen. With quiescence it sees the recapture. At depth 2 without quiescence it no longer falls for that one, but the horizon moved one move rather than disappearing.

Common mistakes

Exercises

NumericOne billion keys
An engine stores 64-bit Zobrist keys for N=109N = 10^9 distinct positions. Using this lesson’s approximation, what is the probability that at least two share a key? Answer as a fraction, not a percentage.
QuizDoes the table cut off?
On entering a node with remaining depth 6, the transposition table returns an entry for the same position at depth 8, type LOWER and value 50. What can search do with window (30,40)(30, 40) and window (60,80)(60, 80)?
QuizA null window fails high
At a MAX node with window (10,50)(10, 50), PVS searched the first child with value 10 and searches the second with null window (10,11)(10, 11). Fail-soft search returns 37. What should it do?
NumericCost of previous iterations
An engine has effective branching factor b∗=4b^* = 4: each iterative-deepening iteration costs 4 times the previous one. At most, what additional fraction of the final iteration’s cost do all previous iterations sum to?
NumericStoring a mate
A chess engine values a position where the player to move is mated at jj plies from the root as −M+j-M + j, with M=100 000M = 100\,000. At position PP, 3 plies from the root, it finds mate against the player to move at ply 7 from the root, so V(P)=−99 993V(P) = -99\,993. What value should it store in the transposition table to remain correct in any other search reaching PP?
QuizWhen passing would be best
A chess engine with null-move pruning (R=2R = 2) plays a king-and-pawns versus king-and-pawns endgame badly. In the critical position the player to move is in zugzwang. What is the correct explanation and what safeguards do engines use?
NumericHow many games for ten points
Two engine versions are equally strong and draw 60% of games. Using this lesson’s normal approximation and delta method, how many games are needed for a 95% Elo interval with half-width 10 points?
ProofWhich transformations each algorithm preserves
Prove: Let ff be strictly increasing. (a) Applying ff to every minimax-tree leaf changes each node’s value from VV to f(V)f(V) and preserves the chosen root move. (b) For expectiminimax this holds for every f(x)=ax+bf(x) = ax + b with a>0a > 0. (c) Other increasing ff may fail.
0
Let VV be a node’s value with original leaves and VfV_f its value with transformed leaves. Reason by induction from the leaves.

Step 1 of 4. At a MAX node whose children satisfy Vf(hi)=f(V(hi))V_f(h_i) = f(V(h_i)), why Vf=f(V)V_f = f(V)?

CodeQuiescence with stand-pat
A simplified capture game: each node is a tuple (e, hijos), where e is static evaluation for the player to move and hijos are positions after each possible capture from the opponent’s perspective. At each node the player to move may stand pat with e or capture. Implement quiescencia(nodo, alfa, beta) in fail-soft negamax form: stand-pat, immediate cutoff if sufficient, alpha-beta pruning of captures and reasonable ordering. Increment NODOS[0] at each visited node. Tests compare it with exhaustivo, which tries all capture sequences, under random windows and measure pruning.
import random

INF = float("inf")
NODOS = [0]

def arbol(rnd, material=0, prof=5):
  """Nodo = (evaluación estática para el jugador al turno, lista de capturas posibles).
  Una captura gana g en {1, 3, 5, 9}: para el rival, que juega después, el material pasa a -(material + g)."""
  hijos = []
  if prof > 0:
      for _ in range(rnd.randint(0, 3)):
          g = rnd.choice((1, 3, 5, 9))
          hijos.append(arbol(rnd, -(material + g), prof - 1))
  return (material, hijos)

def exhaustivo(nodo):
  """Cada bando puede plantarse o capturar; se prueban todas las secuencias de capturas."""
  e, hijos = nodo
  return max([e] + [-exhaustivo(h) for h in hijos])

def tamano(nodo):
  return 1 + sum(tamano(h) for h in nodo[1])

def quiescencia(nodo, alfa, beta):
  """Quiescencia fail-soft con stand-pat y poda alfa-beta. Cuenta cada nodo visitado en NODOS[0]."""
  NODOS[0] += 1
  e, hijos = nodo
  # tu código: plantarse, cortar si basta, y probar las capturas con la ventana negada
  return e
Shift+Enter to run

Summary

Key idea
A game engine is alpha-beta surrounded by techniques deciding where to spend search: iterative deepening always supplies a move and ordering, the transposition table remembers prior searches, quiescence and extensions avoid evaluating where evaluation is meaningless, PVS and forward pruning bet on ordering, and evaluation is fitted to data and statistically validated.
  • Iterative deepening costs at most a factor b∗/(b∗−1)b^*/(b^* - 1) over the last iteration and, thanks to table ordering, often less than a direct search. It enables time management and aspiration windows.
  • Zobrist keys update with a few XORs per move and do not depend on move order. Collision probability between two positions is exactly 2−k2^{-k}, and among NN positions collisions become likely near N≈2k/2N \approx 2^{k/2}.
  • A sufficiently deep table entry cuts off if exact, a lower bound ≥β\ge \beta, or an upper bound ≤α\le \alpha; otherwise its move is tried first. Mates are stored relative to the node.
  • Stand-pat quiescence fixes exchanges cut by the horizon; delaying moves also require extensions.
  • PVS and MTD(f) exploit cheap null windows. PVS wins with good ordering and loses with poor ordering; with perfect order it matches alpha-beta.
  • Null move and LMR prune without searching. Null move fails in zugzwang and returns wrong scores in Connect 4, a zugzwang game.
  • Evaluation weights are tuned by regression on game results (Texel); NNUE takes this idea to an incrementally updatable network.
  • In chance games expectiminimax averages, and evaluation needs a meaningful scale: only positive affine transformations preserve it.
  • Detecting an improvement of a few Elo points requires thousands of games; engines are validated with SPRT.