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:
- It cannot manage time. It searches to fixed depth . If 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.
- 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.
- 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.
- 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 visits on the order of nodes, with the effective branching factor, the sum through is
With all iterations together cost at most 1.5 times the last; with , 1.2 times. This is the same calculation as uninformed search, with instead of .
Earlier iterations make the last cheaper. The previous lesson proved alpha-beta with perfect order visits on the order of leaves and with random order many more. Iteration leaves each explored position’s best move in the transposition table, and iteration tries it first: on the principal variation and much of the tree, the first move is already right. Thus iterative search through can cost fewer nodes than a direct search to depth ; 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 times the previous one, if more than of the budget is spent, the next probably will not finish; the lab cell uses fraction .
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 also estimates value , and iteration ‘s value is usually close. An aspiration window searches the root with instead of . 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 : 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 , and each element is its own inverse, . 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 ; 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.
Collisions: the birthday paradox
Two distinct positions can receive the same key. With what probability? For two particular positions , is the XOR of the strings for pieces present in one but not the other (plus if the turn changes). That set is nonempty because positions differ, and XOR of uniform independent strings is uniform. Thus
exactly: the Zobrist family is universal hashing.
Proof
. By expectation linearity, . The second inequality is the union bound over events, or Markov’s inequality . The final approximation uses for small .
∎The last formula’s independence assumption does not hold completely: Zobrist keys are pairwise independent but not four-wise independent (if as piece sets, ). 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 approaches , not . With 32 bits, from about positions; with 64 bits, about .
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 bits: with 16 bits, 1068 colliding pairs versus the 1102 predicted by ; 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 search with window returns , then implies the true value at that depth satisfies ; implies ; and implies . On encountering the position again with remaining depth and window :
Proof
In case 1 the value is exact and satisfies the contract for any window: if falls inside it is exact, and outside an exact value is in particular a correctly directed bound. In case 2, the call requesting window only needs to know the value is at least , and 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 , all that is known is : the value could lie in and need to be known exactly, or be , and returning would violate the contract. Finally, if , the entry describes a shallower value than requested, generally different.
∎Notice the qualification: with , search returns a bound on , not . Search with a table no longer computes exactly depth- 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 moves from the root as , preferring shorter mates. But the table must store distance from the node, not the root: if the node is plies from the root, store and subtract the querying node’s 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.
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.
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:
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 -slot tables these searches have almost no conflicts. To make replacement policy matter, the cell uses slots, far fewer than distinct positions visited in large searches.
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.
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.
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.
The horizon effect and quiescence search
Fixed-depth search evaluates every position 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.
The figure teaches three things worth stating precisely:
- 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 ) to N×P (gaining ).
- 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 or by depth, instead of for surrendering the rook for a pawn.
- 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 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 (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 , answering only “does value exceed ?”, costs a fraction of computing the value. With integer evaluations that question has an exact answer: fail-soft result satisfies (value is at most ) or (at least ).
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.
The graph summarizes the tradeoff with model data: at each node, with probability the best child goes first and the rest in random order. With both algorithms agree, because perfect-order alpha-beta already visits Knuth and Moore’s minimal tree and nothing can be saved. With low 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 grows because more siblings can be refuted with the cheap window: with and , the ratio falls to 0.875 with ; with and , PVS never wins in this model. The Connect 4 lab (, 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 (for example the previous iteration’s value), search with window , ; if result fails low, is an upper bound; if high, a lower bound; repeat with 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.
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 . 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 and window , the player to move “passes”: search with the opponent to move, reduced depth (with or 3) and a null window around . If even after giving away a move the result is , 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 instead of ) and a null window; only if they surprise by exceeding 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 , 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.
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)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 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 , 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 (), 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 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 for the player to move, and minimize squared error between outcome and a sigmoid of evaluation:
Österlund writes the sigmoid as , with the evaluation in centipawns after quiescence and constant fitted once; this is the same function with weights on another scale. The gradient is direct:
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 .
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.
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)}")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 ) 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.
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)))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 on square , with my king on square ”) 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 alternatives and chance outcomes, the tree through moves has on the order of nodes. In backgammon (distinct two-dice rolls) and 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, . With bounds, Ballard’s (1983) *-minimax algorithms bound the mean before seeing all children: if seen children plus unseen ones valued at cannot reach , the chance node can be cut off.
A deeper difference from minimax is shown in the figure.
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.
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 , 8.9% with , and 29.0% with , the furthest from a straight line on . 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 Elo points above the old one, its expected score per game is
Near , : 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 and expected score , its variance is , and variance of the mean over games is . By the delta method, the 95% Elo interval has half-width
With and 20 games, about points; with 200, ; with 20 000, . Declaring improvement from a few dozen games is reading noise.
Sequential tests. Fixing 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 and , updating log likelihood ratio after every game and stopping as soon as it leaves band ; with , . With a normal approximation to mean score , variance , log ratio is
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.
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.
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.")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
Step 1 of 4. At a MAX node whose children satisfy , why ?
(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 eSummary
- Iterative deepening costs at most a factor 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 , and among positions collisions become likely near .
- A sufficiently deep table entry cuts off if exact, a lower bound , or an upper bound ; 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.