Module contents
Lesson 7 of 23Core 110 min

Monte Carlo Tree Search and UCT

When no good evaluation function exists and branching is enormous, as in Go, alpha-beta fails. MCTS builds an asymmetric tree guided by simulations and treats each node as a multi-armed bandit. This lesson studies its four phases, the UCT rule and its convergence guarantee, and implements a generic MCTS that will underpin AlphaZero in the reinforcement learning module.

After this lesson you can

  • Explain why alpha-beta fails in games with no good evaluation and a large branching factor.
  • Implement the four MCTS phases with UCT and negamax-perspective backpropagation.
  • Calculate UCT scores and choose the exploration constant for the reward range.
  • State the Kocsis and Szepesvári consistency result and recognize trap trees with slow convergence.
  • Compare MCTS with alpha-beta in Connect 4 and Hex using confidence intervals.

Before you start

When alpha-beta has nothing to hold onto

Alpha-beta pruning in the previous two lessons rests on two supports. First, a manageable tree: with perfect order it evaluates b⌈d/2⌉+b⌊d/2⌋−1b^{\lceil d/2 \rceil} + b^{\lfloor d/2 \rfloor} - 1 leaves, manageable only if branching factor bb is moderate. Second, more delicately, an evaluation function saying who is ahead at limited-search leaves. Chess satisfies both: b≈35b \approx 35, and counting material (pawn 1, rook 5) is already a reasonable evaluation refined by engines over decades.

Go satisfies neither. The AlphaGo paper (Silver et al., 2016) summarizes game sizes by approximate legal moves per position and game length: b≈35b \approx 35 and d≈80d \approx 80 in chess, b≈250b \approx 250 and d≈150d \approx 150 in Go. Even with perfect order, an 8-ply search (4 per side) needs 2⋅2504−1≈7.8×1092 \cdot 250^4 - 1 \approx 7.8 \times 10^9 leaves in Go versus 2⋅354−1≈3.0×1062 \cdot 35^4 - 1 \approx 3.0 \times 10^6 in chess. Even if affordable, there is no evaluation: Go has no material to count, a stone group’s value depends on whether it eventually lives or is captured, decided many moves later elsewhere on the board, and territory is undefined until the end. Müller’s (2002) survey of computer Go lists position evaluation among the game’s main difficulties alongside tree size.

A way out arrived in 2006 by applying an old idea differently. Brügmann had proposed in 1993 evaluating Go moves by playing random games to the end. Rémi Coulom (2006) combined those games with a search tree growing toward promising moves and coined Monte Carlo Tree Search; his program Crazy Stone won that year’s Computer Olympiad 9×9 Go tournament. That year Kocsis and Szepesvári published UCT, choosing which branch to explore with the UCB1 bandit algorithm and a convergence guarantee. Ten years later AlphaGo defeated Lee Sedol with neural-network-guided MCTS, and AlphaGo Zero and AlphaZero dispensed with human knowledge except the rules. This lesson builds the central piece:

  1. Evaluation by simulation. A random game’s result is a noisy, biased estimator of a position’s value.
  2. MCTS’s four phases (selection, expansion, simulation and backpropagation), joined by visit and reward bookkeeping.
  3. UCT: a multi-armed bandit at each node, its exploration constant and why that depends on reward range.
  4. Convergence: Kocsis and Szepesvári’s theorem, its requirements and what it does not promise, with a trap tree where convergence is desperately slow.
  5. Two labs: generic MCTS from scratch, against the alpha-beta engine in Connect 4 and Hex 7×7, with confidence intervals.

Evaluating by random play

Suppose you receive a position and no idea who is winning, but know the rules. You can always play a game from there with uniformly random moves to the end and record the outcome. Let X∈{0,12,1}X \in \{0, \tfrac12, 1\} be the player-to-move’s reward (loss, draw, win). Repeating nn independent games, mean Xˉn\bar X_n is a Monte Carlo estimator of

vazar(s)=E[X],v_{\text{azar}}(s) = \E[X],

the position’s value under random play. Since XX lies in [0,1][0, 1], Hoeffding’s inequality gives a guarantee without further assumptions:

P(∣Xˉn−vazar(s)∣≥ε)≤2e−2nε2,\Pr\big(\abs{\bar X_n - v_{\text{azar}}(s)} \ge \eps\big) \le 2 e^{-2 n \eps^2},

so with n≥ln⁡(2/δ)/(2ε2)n \ge \ln(2/\delta) / (2\eps^2) games the error is below ε\eps with probability at least 1−δ1 - \delta: for ε=0.05\eps = 0.05 and δ=0.05\delta = 0.05, 738 suffice. Monte Carlo error decreases as 1/n1/\sqrt{n} independently of game size, which is attractive.

The catch is the definition: vazarv_{\text{azar}} is not minimax value. It is the value of a different game where both players are monkeys, and more simulations only estimate that more accurately. The cell shows a tic-tac-toe position. Number squares 0 to 8 by row: O has square 3 (middle left), X squares 5 (middle right) and 7 (bottom center), and O moves. For each O move, the cell calculates exact minimax value, exact value under random play (recursively averaging instead of maximizing), and an estimate from 200 random games.

[ ]The value of a random gameBrowser
import math, random
from functools import lru_cache

LINEAS = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]

def ganador(t):
    for a, b, c in LINEAS:
        if t[a] and t[a] == t[b] == t[c]:
            return t[a]
    return 0

def libres(t):
    return [i for i in range(9) if not t[i]]

def poner(t, i, p):
    return t[:i] + (p,) + t[i + 1:]

@lru_cache(maxsize=None)
def minimax(t, p):
    """Valor exacto en [0, 1] para el jugador al turno p (1 = X, 2 = O): 1 gana, 0.5 tablas, 0 pierde."""
    if ganador(t):
        return 0.0                      # ha ganado el que acaba de mover
    if all(t):
        return 0.5
    return max(1 - minimax(poner(t, i, p), 3 - p) for i in libres(t))

@lru_cache(maxsize=None)
def al_azar(t, p):
    """Valor esperado para p si, desde aquí, los dos juegan uniformemente al azar."""
    if ganador(t):
        return 0.0
    if all(t):
        return 0.5
    L = libres(t)
    return sum(1 - al_azar(poner(t, i, p), 3 - p) for i in L) / len(L)

def simulacion(t, p, rng):
    """Una partida al azar desde t (juega p). Devuelve la recompensa de p."""
    yo = p
    while True:
        if ganador(t):
            return 1.0 if ganador(t) == yo else 0.0
        L = libres(t)
        if not L:
            return 0.5
        t = poner(t, rng.choice(L), p)
        p = 3 - p

INICIO = (0, 0, 0,
          2, 0, 1,
          0, 1, 0)                      # O tiene la casilla 3; X, la 5 y la 7. Juega O.
n, delta = 200, 0.05
h = math.sqrt(math.log(2 / delta) / (2 * n))   # semianchura de Hoeffding para recompensas en [0, 1]
rng = random.Random(0)
print("casilla   minimax   valor al azar exacto   estimación con", n, "partidas")
estim = {}
for i in libres(INICIO):
    t = poner(INICIO, i, 2)
    estim[i] = sum(1 - simulacion(t, 1, rng) for _ in range(n)) / n
    print(f"{i:5d}   {1 - minimax(t, 1):7.1f}   {1 - al_azar(t, 1):18.3f}   {estim[i]:12.3f} ± {h:.3f}")
plana = max(estim, key=estim.get)
print("Monte Carlo plano elige la casilla", plana, "cuyo valor minimax es", 1 - minimax(poner(INICIO, plana, 2), 1))

The two moves scoring highest at random, corners 0 and 6 (values 0.500 and 0.483), lose. After 0, X blocks O’s column at 6, simultaneously threatening 8 (6-7-8); O must block and X plays center with two threats, 1-4-7 and 2-4-6, which O cannot block both at once. After 6 the mechanism is similar: X blocks at 0 and, whatever O plays, obtains a double threat. The moves drawing under perfect play, squares 2 and 8, block X’s right-column lines in time but under random play are worth only 0.333 and 0.367, because they leave many continuations where careless O loses. Flat Monte Carlo, playing the highest mean, chooses square 0. Notice the ±0.096\pm 0.096 Hoeffding interval is correct: estimate 0.480 is close to 0.500. The estimator works; the question it answers fails. Against a nonrandom opponent their best reply matters, and averaging uniform replies dilutes it.

MCTS aims to fix this without abandoning simulations: build a tree that near the root carefully chooses each player’s responses (in the limit, like minimax) and uses random games only to evaluate what lies below it.

The four phases of MCTS

Two design decisions define the algorithm: the tree policy choosing which child to descend to during selection (UCT in the next section), and the simulation policy playing from the new node to the end (uniform random for now). The rest is bookkeeping, and its trap is perspective. In a two-player game the same simulated game is a win for one and a loss for the other. Storing at each node the reward of the player who chose the move to it makes every parent choose among children by maximizing QQ, just as negamax maximizes −N(hijo)-N(\text{hijo}): in [0,1][0, 1], negamax’s “minus” is r↦1−rr \mapsto 1 - r, and a draw 12\tfrac12 has equal value for both.

The widget runs this algorithm with UCT and c=2c = \sqrt2 on the previous cell’s tic-tac-toe position. Each iteration is shown in four phases.

InteractiveThe four phases of MCTS
Board at reached node
  • O move (levels 1, 3)
  • X move (level 2)
  • path for this iteration
  • expanded node
Seed
Statuscalculating…
MCTS tree on the previous cell's tic-tac-toe position (O to move). Advance phase by phase: selection path is highlighted, the expanded node has a magenta ring, the small board shows the simulated game (numbers indicate random move order), and backpropagation shows each node's addition to W. Click a node for the UCT breakdown of its parent's decision: dark bar segment is exploitation Q; pale segment is exploration. Skip +100 and +1000 iterations: the most visited move starts as a losing corner and ends as a drawing move.

Three things visible in the widget are worth fixing:

  • The tree is asymmetric. Each iteration adds one node, which accumulate under moves selection visits most. Alpha-beta explores a uniform-depth tree; MCTS explores to the depth statistics dictate.
  • A new node is evaluated by one game. Its QQ starts at 0, 12\tfrac12 or 1, a terrible estimate improving only if selection returns.
  • Backpropagation alternates. The same result adds 1 to WW at one player’s nodes and 0 at the other’s. Always adding rr would make each player choose moves good for the opponent.

The next cell is the MCTS used throughout the lesson. It is generic: it asks the game for only five operations (jugadas, jugar, terminal, resultado for the previous mover’s reward in a terminal position, and simular for the reward of the player moving to a nonterminal position), so it works for tic-tac-toe, Connect 4 and Hex. It tests the earlier position with increasing budgets.

[ ]Generic MCTS with UCTBrowser
class Nodo:
    """Un nodo del árbol. N y W son las estadísticas de la arista que llega a él."""
    __slots__ = ("padre", "jugada", "hijos", "sin_probar", "N", "W")

    def __init__(self, padre, jugada, sin_probar):
        self.padre, self.jugada = padre, jugada
        self.hijos = []                  # hijos ya expandidos
        self.sin_probar = sin_probar     # jugadas legales que aún no tienen nodo
        self.N = 0                       # visitas
        self.W = 0.0                     # suma de recompensas, vistas por quien hizo 'jugada'

def seleccionar_uct(nodo, c):
    """Hijo de mayor UCT: media W/N más el bono c * sqrt(ln N_padre / N_hijo)."""
    lnN = math.log(nodo.N)
    return max(nodo.hijos, key=lambda h: h.W / h.N + c * math.sqrt(lnN / h.N))

def iteracion(juego, raiz, estado, c, rng):
    """Una iteración de MCTS desde la raíz (cuyo estado es 'estado')."""
    nodo, s = raiz, estado
    # 1. selección: bajar por UCT mientras el nodo esté completamente expandido
    while not nodo.sin_probar and nodo.hijos:
        nodo = seleccionar_uct(nodo, c)
        s = juego.jugar(s, nodo.jugada)
    # 2. expansión: una jugada no probada, al azar
    if nodo.sin_probar:
        a = nodo.sin_probar.pop(rng.randrange(len(nodo.sin_probar)))
        s = juego.jugar(s, a)
        hijo = Nodo(nodo, a, [] if juego.terminal(s) else juego.jugadas(s))
        nodo.hijos.append(hijo)
        nodo = hijo
    # 3. simulación: recompensa en [0, 1] para quien hizo la última jugada del camino
    r = juego.resultado(s) if juego.terminal(s) else juego.simular(s, rng)
    # 4. retropropagación en perspectiva negamax: r para quien movió, 1 - r para su rival
    while nodo is not None:
        nodo.N += 1
        nodo.W += r
        r = 1.0 - r
        nodo = nodo.padre

def mcts(juego, estado, iteraciones, c=math.sqrt(2), rng=None):
    """MCTS con UCT. El juego da jugadas, jugar, terminal, resultado y simular."""
    rng = rng or random.Random(0)
    raiz = Nodo(None, None, juego.jugadas(estado))
    for _ in range(iteraciones):
        iteracion(juego, raiz, estado, c, rng)
    return raiz

class TresEnRaya:
    """Estado: (tablero, jugador al turno)."""
    def jugadas(self, s):
        return libres(s[0])
    def jugar(self, s, i):
        return poner(s[0], i, s[1]), 3 - s[1]
    def terminal(self, s):
        return bool(ganador(s[0])) or all(s[0])
    def resultado(self, s):              # recompensa de quien acaba de mover
        return 1.0 if ganador(s[0]) else 0.5
    def simular(self, s, rng):           # recompensa de quien movió hasta s
        return 1 - simulacion(s[0], s[1], rng)

ttt = TresEnRaya()
for it in (30, 300, 3000, 30000):
    raiz = mcts(ttt, (INICIO, 2), it, rng=random.Random(1))
    hijos = sorted(raiz.hijos, key=lambda h: h.jugada)
    mas = max(hijos, key=lambda h: h.N)
    print(f"{it:6d} iteraciones   N por casilla:", {h.jugada: h.N for h in hijos},
          f"  más visitada: {mas.jugada} (Q = {mas.W / mas.N:.3f}, minimax {1 - minimax(poner(INICIO, mas.jugada, 2), 1)})")

With 30 and 300 iterations the most visited move is a losing corner, 0 then 6: the tree is still shallow and means nearly match flat Monte Carlo. With 3000, square 8 has 1369 of 3000 visits; with 30 000 the two drawing moves, 2 and 8, receive 12 951 and 15 855, while others remain between 215 and 358. Square 8’s mean is 0.483, near its minimax value 12\tfrac12 and far from random play’s 0.367. Under square 0, the tree found X’s reply at 8 and concentrated X’s visits there, lowering square 0’s mean until it ceased to interest. Other seeds lead to the same conclusion:

[ ]Ten seedsBrowser
print("iteraciones   semillas (de 10) cuya jugada más visitada empata")
for it in (300, 1000, 3000):
    buenas = 0
    for semilla in range(10):
        raiz = mcts(ttt, (INICIO, 2), it, rng=random.Random(100 + semilla))
        buenas += minimax(poner(INICIO, max(raiz.hijos, key=lambda h: h.N).jugada, 2), 1) == 0.5
    print(f"{it:11d}   {buenas}")

None of 10 searches with 300 iterations chooses correctly, one of 10 with 1000 and all 10 with 3000.

UCT: a multi-armed bandit at each node

At each node selection faces the multi-armed bandit dilemma: each child is an arm with unknown mean reward; descending to the best mean exploits what is known, while choosing a rarely visited child explores whether it is underestimated. UCT’s criterion comes from UCB1 (Auer, Cesa-Bianchi and Fischer, 2002): with KK arms with rewards in [0,1][0, 1], after nn total pulls and njn_j of arm jj, pull the arm maximizing

Xˉj+2ln⁡nnj.\bar X_j + \sqrt{\frac{2 \ln n}{n_j}}.

The bonus is the half-width of a Hoeffding interval with confidence increasingly stringent in nn: each arm is judged by what it could optimistically be worth. Their theorem 1 bounds expected pulls of a suboptimal arm with gap Δj\Delta_j from the best:

E[Tj(n)]≤8ln⁡nΔj2+1+π23,\E[T_j(n)] \le \frac{8 \ln n}{\Delta_j^2} + 1 + \frac{\pi^2}{3},

so regret grows only logarithmically.

With rewards in [0,1][0, 1] and c=2c = \sqrt 2, the score is exactly UCB1’s. Kocsis and Szepesvári write the bonus as 2Cpln⁡t/s2 C_p \sqrt{\ln t / s}; with Cp=1/2C_p = 1/\sqrt 2 it is the same. The UCT rule has three properties visible in the formula:

  • If a node is visited infinitely often, so is every child. If a child stopped being visited, its bonus would grow without bound as ln⁡N(v)\sqrt{\ln N(v)} and eventually exceed those still visited.
  • Bad children receive only logarithmically many visits. A child with large N(v′)N(v') has a small bonus and its score is nearly its mean; with stationary arms, a child with gap Δ\Delta from the best cannot exceed roughly c2ln⁡N(v)/Δ2c^2 \ln N(v) / \Delta^2 visits except through mean-estimation error.
  • The bonus has reward units. Mean and bonus are added, so cc makes sense only relative to the reward range.

The third causes most errors. Hoeffding for rewards in [a,b][a, b] gives half-widths proportional to b−ab - a. If rewards are ±1\pm 1, range is 2 and the constant equivalent to 2\sqrt 2 is 222\sqrt 2; for Go point differences with a range of hundreds, c=2c = \sqrt 2 makes the bonus negligible relative to mean differences and UCT becomes greedy. The clean approach is normalizing rewards to [0,1][0, 1] and choosing cc there. Value 2\sqrt 2 makes the proof work, not necessarily practice: tune experimentally, and in many games a smaller value works better.

InteractiveThe exploration constant
Tree by depth: width = visit share; color = first move column
01234567891011121314
MCTS with c versus MCTS with c = √2, 1000 iterations per move
  • points per game (win 1, draw ½) and 95% Wilson interval
  • 50%: as strong as the opponent
  • current c
0.00
Iterations per move
Statuscalculating…
Above, the tree UCT builds from an empty Connect 4 board with selected constant c and budget, drawn by depth: each rectangle is a node, width is visit proportion and color is first-move column. Below, points by that MCTS against the same MCTS with c = √2, 40 games per c with 95% Wilson intervals. Start at c = 0 and move the slider slowly: the tree shifts from one very deep branch to almost breadth-first search.

With c=0c = 0 selection is purely greedy: once a child has mean 0 (its only game lost), it is never revisited and search commits to the first lucky branch. With 1000 iterations, 89% of root visits go to one column and the tree reaches 23 moves deep, but its player loses all 40 games against c=2c = \sqrt 2: it looked far down one line and barely at the others. With c=3c = 3 the bonus dominates, the most visited column gets only 20% and the tree stays at depth 4 with the first three levels (7, 49 and 343 nodes) complete: breadth-first search spending many iterations on moves already known bad. Between c=0.5c = 0.5 and c=3c = 3, results against the fixed opponent fall within overlapping intervals: 40 games per point do not distinguish them. The constant matters greatly far from the reward scale and much less within it, so it is tuned with long tournaments, not by eye.

Convergence: what UCT guarantees and does not

UCB1 assumes each arm yields independent rewards with fixed mean. In a tree this is false. What child v′v' receives depends on choices below it, which change over time: initially the subtree plays almost randomly, later increasingly well. Internal-node rewards form a nonstationary bandit whose means drift toward the child’s minimax value. Kocsis and Szepesvári addressed precisely this.

Their analysis has two pieces. First is UCB1 with drift: assume each arm’s expected mean E[Xˉj,n]\E[\bar X_{j, n}] converges to limit μj\mu_j, and mean deviations satisfy Hoeffding-type tail inequalities with the same bonus ct,sc_{t,s}; then prove global mean bias and probability of not selecting the best arm tend to zero. Second is induction on depth: at last-level nodes arms are stationary; if drift conditions hold for a node’s children, the preceding result says they hold for the node, and so on to the root.

The paper states this for Markov decision processes, maximizing at every level. In a game tree negamax perspective turns each node into a maximization for the player to move, so the induction applies similarly; the authors themselves test UCT on random game trees (P-games). We call this MCTS consistency: with infinite budget, root mean converges to minimax value and the recommended move to an optimal move. The guided proof exercise establishes it on a depth-2 tree, exposing the whole mechanism.

Now what the theorem does not say:

  • Nothing about speed. O(log⁡n/n)\bigO(\log n / n) hides tree-dependent constants. Coquelin and Munos (2007) constructed depth-DD trees where UCT regret (loss from iterations spent on suboptimal moves) has a lower bound on the order of a tower of D−1D - 1 nested exponentials, exp⁡(exp⁡(⋯exp⁡(1)⋯ ))\exp(\exp(\cdots \exp(1) \cdots)). This is worst case, but shows the guarantee is purely asymptotic.
  • Assumptions exceed practice. The DD bonus factor required for the proof is rarely used; real implementations use one manually tuned cc.
  • Nothing about a specific node’s mid-search mean. Q(v)Q(v) mixes exploratory and good visits and midway may be far from vv‘s minimax value.

The next figure shows convergence on a Connect 4 position with 16 empty cells whose exact value the cell computes with a complete negamax solver. First, the game in the MCTS interface, using minimax lesson bitboards: two integers, one for the player-to-move pieces and one for all pieces, and random simulation inside the bit loop for speed. The cell also includes that lesson’s amenazas function, marking empty squares where a player would complete four in a row; informed simulation and the alpha-beta engine use it.

[ ]Connect 4 in the MCTS interfaceBrowser
W, H, H1 = 7, 6, 7                     # columnas, filas y bits por columna (uno de guarda)
ABAJO = [1 << (c * H1) for c in range(W)]
ARRIBA = [1 << (H - 1 + c * H1) for c in range(W)]
COLUMNA = [((1 << H) - 1) << (c * H1) for c in range(W)]
FONDO = sum(ABAJO)
TABLERO = FONDO * ((1 << H) - 1)

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

def amenazas(p, m):
    """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 ^ m)

class Conecta4:
    """Estado: (actual, mascara, n). 'actual' son las fichas del jugador al turno."""
    orden = (3, 2, 4, 1, 5, 0, 6)
    inicial = (0, 0, 0)
    def jugadas(self, s):
        return [c for c in self.orden if not s[1] & ARRIBA[c]]
    def jugar(self, s, c):
        a, m, n = s
        return a ^ m, m | (m + ABAJO[c]), n + 1
    def terminal(self, s):
        return s[2] == W * H or alineado(s[0] ^ s[1])
    def resultado(self, s):            # para quien acaba de mover
        return 1.0 if alineado(s[0] ^ s[1]) else 0.5
    def simular(self, s, rng):         # para quien movió hasta s
        a, m, n = s
        turno_rival = True             # mueve ahora el rival de quien movió hasta s
        while n < W * H:
            cols = [c for c in range(W) if not m & ARRIBA[c]]
            c = cols[rng.randrange(len(cols))]
            m2 = m | (m + ABAJO[c])
            mias = a | (m2 ^ m)        # fichas de quien acaba de jugar
            if alineado(mias):
                return 0.0 if turno_rival else 1.0
            a, m, n = m2 ^ mias, m2, n + 1
            turno_rival = not turno_rival
        return 0.5

def desde_cadena(jugadas):
    s = Conecta4.inicial
    for ch in jugadas:
        s = Conecta4().jugar(s, int(ch) - 1)
    return s

def dibujar(s):
    a, m, n = s
    x, o = (a, a ^ m) if n % 2 == 0 else (a ^ m, a)
    filas = [" ".join("X" if x >> (c * H1 + f) & 1 else "O" if o >> (c * H1 + f) & 1 else "." for c in range(W))
             for f in range(H - 1, -1, -1)]
    return "\n".join(filas) + "\n1 2 3 4 5 6 7"
[ ]The figure’s position, solvedBrowser
from functools import lru_cache

def gana_ya(a, m):
    """¿Puede el jugador al turno (fichas a) ganar en esta jugada?"""
    return any(not m & ARRIBA[c] and alineado(a | ((m + ABAJO[c]) & COLUMNA[c])) for c in range(W))

@lru_cache(maxsize=None)
def exacto(a, m, n):
    """Valor exacto en {0, 0.5, 1} para el jugador al turno, con poda al encontrar una victoria."""
    if n == W * H:
        return 0.5
    if gana_ya(a, m):
        return 1.0
    mejor = 0.0
    for c in Conecta4.orden:
        if not m & ARRIBA[c]:
            mejor = max(mejor, 1 - exacto(a ^ m, m | (m + ABAJO[c]), n + 1))
            if mejor == 1.0:
                break
    return mejor

c4 = Conecta4()
POS = "47134413416646662452275672"
s = desde_cadena(POS)
print(dibujar(s), "\nJuega X;", W * H - s[2], "casillas libres")
valor = {}
for c in c4.jugadas(s):
    s2 = c4.jugar(s, c)
    valor[c] = 1.0 if alineado(s2[0] ^ s2[1]) else 1 - exacto(*s2)
print("valor exacto de cada columna (1 gana, 0.5 tablas, 0 pierde):", {c + 1: valor[c] for c in sorted(valor)})
print("posiciones distintas resueltas:", exacto.cache_info().currsize)

rng = random.Random(1)
raiz = Nodo(None, None, c4.jugadas(s))
for it in range(1, 20001):
    iteracion(c4, raiz, s, math.sqrt(2), rng)
    if it in (100, 1000, 5000, 20000):
        hijos = sorted(raiz.hijos, key=lambda h: h.jugada)
        print(f"{it:6d} it.  visitas %:", {h.jugada + 1: round(100 * h.N / it) for h in hijos},
              "  Q:", {h.jugada + 1: round(h.W / h.N, 2) for h in hijos})

With perfect play, X wins using column 7, draws with 3 and loses with 1, 2 or 5 (4 and 6 are full). The solver establishes this visiting only 1147 distinct positions. MCTS takes much longer: with 100 iterations it prefers column 3, with 5000 already gives 75% of visits to 7, and with 20 000, 93%. Column 7’s mean rises slowly from 0.59 at 100 iterations to 0.83 at 20 000 because it retains early visits where O’s responses were still poor. Losing-move means do not converge to 0 within this budget: they remain between 0.23 and 0.40 because once UCT sees they are worse it rarely visits them and means freeze. Recommended moves converge much earlier than values.

InteractiveVisit convergence
X to play. Exact value of each column
+1½000
X: filled pieces. O: hollow pieces. Under each playable column are its chart color and exact value (+1 win, ½ draw, 0 loss).
Visit share for each root child
  • col 7 (win)
  • col 3 (draw)
  • col 1 (loss)
  • col 2 (loss)
  • col 5 (loss)
Mean Q = W/N for each child and exact minimax value (dashed)
  • col 7 (win)
  • col 3 (draw)
  • col 1 (loss)
  • col 2 (loss)
  • col 5 (loss)
  • minimax: win
  • minimax: draw
  • minimax: loss
Seed
Exploration constant
Statuscalculating…
The previous cell's position (X to move; columns 4 and 6 full). Above, each root child's visit proportion versus iteration count on a logarithmic scale; below, mean Q with each move's exact minimax value dashed. Move the iteration slider to see each moment, and change seed and constant c. Notice the winning column gets nearly all visits while losing means freeze far from 0.

Trap trees

A trap is a move appearing good under almost all continuations but refuted by a particular deep opponent line. It is the worst case for an averaging estimator: the refutation is one branch among many and random games almost never find it. Ramanujan, Sabharwal and Selman (2010) studied shallow traps: frequent in chess positions, even grandmaster games, and very rare in Go; they proposed this difference as an explanation for UCT’s strength in Go and alpha-beta’s continuing dominance in chess.

To see this clearly, consider a synthetic tree with adjustable trap depth. MAX’s root has two moves: a safe draw (worth 12\tfrac12) and the trap. After the trap are kk MIN levels; at each, MIN has bb moves, one continuing the refutation and the other b−1b - 1 losing immediately; between levels MAX has bb moves all following the line. At level kk the refutation wins for MIN. The trap’s minimax value is 0. Random play follows the refutation with probability 1/b1/b at each MIN level, so its expected value for MAX is 1−b−k1 - b^{-k}: with b=3b = 3 and k=4k = 4, 0.9880.988. To simulation the trap is nearly a certain win.

[ ]The deep trapBrowser
class Trampa:
    """Raíz MAX: jugada 0 = segura (tablas), 1 = trampa. Tras la trampa, k niveles de MIN con b jugadas:
    la 0 sigue la refutación y las demás pierden en el acto; entre nivel y nivel, MAX tiene b jugadas
    que siguen todas por la línea. En el nivel k, la refutación gana para MIN.
    Estado: (tipo, nivel, juega_max). Las simulaciones son uniformes salvo que MIN, con probabilidad rho,
    conoce la refutación."""
    def __init__(self, k, b=3, rho=0.0):
        self.k, self.b, self.rho = k, b, rho
    inicial = ("raiz", 0, True)
    def jugadas(self, s):
        tipo = s[0]
        return [0, 1] if tipo == "raiz" else list(range(self.b)) if tipo in ("min", "max") else []
    def jugar(self, s, a):
        tipo, j, juega_max = s
        if tipo == "raiz":
            return ("segura", 0, False) if a == 0 else ("min", 1, False)
        if tipo == "min":
            return ("gana_max", j, True) if a else ("gana_min" if j == self.k else "max", j, True)
        return ("min", j + 1, False)                       # tipo == "max"
    def terminal(self, s):
        return s[0] in ("segura", "gana_max", "gana_min")
    def resultado(self, s):                                # para quien acaba de mover
        v = {"segura": 0.5, "gana_max": 1.0, "gana_min": 0.0}[s[0]]
        return v if not s[2] else 1 - v                    # si ahora juega MIN, movió MAX
    def simular(self, s, rng):
        movio_max = not s[2]
        while not self.terminal(s):
            if s[0] == "min" and rng.random() < self.rho:
                a = 0
            else:
                a = rng.randrange(len(self.jugadas(s)))
            s = self.jugar(s, a)
        v = {"segura": 0.5, "gana_max": 1.0, "gana_min": 0.0}[s[0]]
        return v if movio_max else 1 - v

def hasta_descartar(juego, tope, semilla):
    """Iteraciones hasta que la jugada segura pasa a ser la más visitada para siempre (dentro del tope)."""
    rng = random.Random(semilla)
    raiz = Nodo(None, None, juego.jugadas(juego.inicial))
    ultima = 0
    for i in range(1, tope + 1):
        iteracion(juego, raiz, juego.inicial, math.sqrt(2), rng)
        if len(raiz.hijos) == 2:
            mas = max(raiz.hijos, key=lambda h: h.N)
            if mas.jugada == 1:
                ultima = i
    trampa = next(h for h in raiz.hijos if h.jugada == 1)
    return ultima + 1, trampa.W / trampa.N

print(" k   valor de una simulación   iteraciones hasta preferir las tablas (3 semillas)   Q(trampa) al final")
for k in (1, 2, 3, 4):
    J = Trampa(k)
    q = 1 / J.b                                         # MIN sigue la refutación al azar con prob. 1/b
    res = [hasta_descartar(J, 8000, s) for s in range(3)]
    print(f"{k:2d}   {1 - q ** k:23.3f}   {str([r[0] if r[0] <= 8000 else '>8000' for r in res]):>40s}   {res[0][1]:.3f}")

def nodos_minimax(J, s):
    """Nodos que recorre minimax sin poda en el subárbol de s."""
    return 1 + sum(nodos_minimax(J, J.jugar(s, a)) for a in J.jugadas(s))
J = Trampa(4)
print("minimax sin poda recorre", nodos_minimax(J, J.jugar(J.inicial, 1)), "nodos bajo la trampa con k = 4")
J = Trampa(4, rho=1.0)
print("k = 4 con simulaciones perfectas (rho = 1): valor de una simulación 0, iteraciones hasta preferir las tablas:",
      [hasta_descartar(J, 8000, s)[0] for s in range(3)])

The cost of discarding the trap multiplies by 4 to 8 per level: from 8–23 iterations with k=1k = 1 to 2920–4668 with k=4k = 4, whereas unpruned minimax refutes it traversing the subtree’s 160 nodes. There are two causes, separated by the cell’s last line. One is simulation bias: random games report 0.988 where truth is 0. The other is exploration: even with perfect simulations (ρ=1\rho = 1, MIN always knows the refutation and every simulation from the trap is worth 0), MCTS needs about 2100 iterations with k=4k = 4. The trap mean is not the minimum of MIN’s means, but an average of everything played below, and at each of the subtree’s 40 MIN nodes UCT occasionally visits MIN’s losing moves, each a MAX win. The trap mean is still 0.459 after 8000 iterations with k=4k = 4. In the figure raise kk to 6 (with seed 1, MCTS then needs 148 564 iterations to discard a trap whose complete subtree has 1456 nodes), remove MAX’s intermediate choices (greatly reducing MIN-node count) and improve simulation with ρ\rho.

InteractiveThe deep trap
The tree (▲ MAX, ▼ MIN; leaves: MAX reward)
safe: ½trap111111⋮through level 40: MIN wins
Dashed: the refutation. A random game follows it to the end with probability 0.012.
4
Moves per node bb
0.00
Seed
Expected rollout value from the trap0.988
Trap minimax value0
MCTS prefers the draw from iteration…
Nodes in full tree under the trap160
Synthetic tree with a refutation at depth k (▲ MAX and ▼ MIN in the diagram). The graph shows trap mean Q seen by MCTS and its visit proportion versus iterations up to 200 000; the vertical line marks when MCTS permanently switches to preferring the safe move. Raise k: the discard point jumps right. Then raise ρ to 1 and see that even perfect simulations do not discard the trap immediately.

MCTS as an anytime algorithm, and its relationship to minimax

MCTS is an anytime algorithm in the strongest sense: stop after any iteration and the recommendation is the best accumulated statistics allow. Alpha-beta iterative deepening is also anytime, but in jumps: a partial iteration is usually discarded. MCTS spends budget selectively: it deepens important lines and leaves others with a few visits, which alpha-beta achieves only with handcrafted extensions and reductions.

Its minimax relationship is the theorem’s: with infinite budget, UCT’s tree policy concentrates on each player’s optimal moves and root mean converges to minimax value. With finite budgets these are distinct algorithms with opposite weaknesses. Alpha-beta sees everything to its horizon exactly (short traps do not affect it) and relies entirely on horizon evaluation. MCTS has no horizon or need for evaluation, but averages, and averages can hide a specific refutation. The winner depends on the game: two labs measure Connect 4, where threat evaluation is good, and Hex, where simple evaluation is poor. Variants combining both ideas (MCTS certainly solving terminal nodes, or short minimax searches within selection or simulation) are in the next lesson. The same machinery also works outside games: any sequential decision problem with a simulator and final reward admits the four-phase loop, and tree search over reasoning steps in language models reuses UCT selection with one model proposing steps and another scoring outcomes.

Choosing the final move

When the budget expires one must play, and the selection rule no longer applies: its exploration bonus gathers information, not actions. Browne et al. (2012) survey four final-move selection criteria:

  • Max child: greatest QQ.
  • Robust child: greatest NN.
  • Max-robust child: greatest QQ and greatest NN; if they disagree, keep searching until they agree.
  • Secure child: maximizes a lower confidence bound such as Q−A/NQ - A/\sqrt{N}.

Most visited is most common. Under UCT visits summarize mean and confidence: a child accumulates visits only if its mean stays high while examined, because other bonuses grow. Few visits with high mean is the dangerous case: with 3 visits and 3 wins, the 95% Hoeffding half-width is ln⁡40/6≈0.78\sqrt{\ln 40 / 6} \approx 0.78, and mean 1 is compatible with true value 0.22. Max child errs as soon as a lightly explored child is lucky; robust child rarely does, because exceeding others’ visits requires sustaining a mean for much of the search. AlphaZero’s training policy, playing proportional to visits, is different: an exploration mechanism for generating games, covered in the reinforcement-learning module.

Simulation policies

The simulation policy (rollout or default policy) plays from the expanded node to the end. Uniform random needs no knowledge, but you have seen what it measures: random-play value, possibly almost independent of true value. A little knowledge (win if possible, block the opponent’s immediate win) produces more realistic games and less biased estimates. The cell compares them on the convergence figure’s position.

[ ]Random and informed simulationBrowser
import time
class Conecta4Informada(Conecta4):
    """Simulación con conocimiento: si puedes ganar, gana; si el rival gana en una casilla jugable, tápala;
    si no, al azar. El resto del juego es idéntico."""
    def simular(self, s, rng):
        a, m, n = s
        turno_rival = True
        while n < W * H:
            jugables = (m + FONDO) & TABLERO
            ganar = amenazas(a, m) & jugables
            if ganar:                                   # el jugador al turno gana ya
                return 0.0 if turno_rival else 1.0
            tapar = amenazas(a ^ m, m) & jugables
            if tapar:
                ficha = tapar & -tapar                  # una casilla de amenaza (la de bit más bajo)
            else:
                cols = [c for c in range(W) if not m & ARRIBA[c]]
                c = cols[rng.randrange(len(cols))]
                ficha = (m + ABAJO[c]) & COLUMNA[c]
            m2 = m | ficha
            a, m, n = (a | ficha) ^ m2, m2, n + 1       # fichas del siguiente al turno
            turno_rival = not turno_rival
        return 0.5

informada = Conecta4Informada()
rng = random.Random(2)
print("columna   exacto   media de 400 simulaciones al azar   media de 400 informadas")
pos = desde_cadena(POS)
for c in c4.jugadas(pos):
    s2 = c4.jugar(pos, c)
    if c4.terminal(s2):
        continue
    azar = sum(c4.simular(s2, rng) for _ in range(400)) / 400
    inf = sum(informada.simular(s2, rng) for _ in range(400)) / 400
    print(f"{c + 1:7d}   {valor[c]:6.1f}   {azar:33.3f}   {inf:23.3f}")
t0 = time.perf_counter(); [c4.simular(c4.inicial, rng) for _ in range(300)]; t1 = time.perf_counter()
[informada.simular(c4.inicial, rng) for _ in range(300)]; t2 = time.perf_counter()
print(f"una simulación informada desde el tablero vacío cuesta {(t2 - t1) / (t1 - t0):.1f} veces una al azar")

Under random play the five moves are worth 0.465 to 0.610 in an order unlike the truth (the best by simulation is drawing column 3; winning column 7 is only 0.497). With informed play, losing column 5 is exactly 0 and winning column 7 rises to 0.710, clearly best. Not everything improves: drawing column 3 drops to 0.346, below losing column 2. A little knowledge reduces bias without eliminating it. Each informed simulation costs roughly three to four times a random one, calculating threats every move.

A stronger playing policy is not guaranteed to be better inside MCTS. Gelly and Silver (2007) found this in 9×9 Go: a simulation policy based on a learned value function improved UCT over random simulation but, surprisingly, gave weaker UCT than a handcrafted policy that played worse. What matters is that mean simulation outcomes order positions correctly, not that each simulation plays well; a strong biased policy (for example, never playing a certain move type) introduces systematic bias no number of iterations fixes. Silver and Tesauro (2009) turned this into simulation balancing, tuning the policy to minimize mean error rather than maximize strength. The final step in this line is AlphaGo Zero and AlphaZero: replace simulation with a network directly estimating value.

Lab: MCTS versus alpha-beta in Connect 4

You have the first two pieces: generic MCTS from the four-phases section and Connect 4 in the MCTS interface. The opponent remains. It is from the minimax lesson: negamax with alpha-beta, center columns first and threat evaluation (three times the difference in empty squares where each player could complete four, plus center-column piece difference), relative to the player to move. Immediate wins are detected before the horizon and worth 1000−n1000 - n to prefer early wins. The cell reproduces it in a few lines, with wrappers converting each algorithm into a player and a game-playing function.

[ ]The opponent: alpha-beta with threat evaluationBrowser
import time
GANA = 1000
CENTRO = COLUMNA[3]

def evaluar(a, m):
    """La evaluación de la lección de minimax, para el jugador al turno."""
    o = a ^ m
    return (3 * (amenazas(a, m).bit_count() - amenazas(o, m).bit_count())
            + (a & CENTRO).bit_count() - (o & CENTRO).bit_count())

def negamax(a, m, n, d, alfa, beta, cuenta):
    cuenta[0] += 1
    if n == W * H:
        return 0
    if amenazas(a, m) & (m + FONDO) & TABLERO:
        return GANA - n                          # el jugador al turno gana en esta jugada
    if d == 0:
        return evaluar(a, m)
    mejor = -10**9
    for c in Conecta4.orden:
        if not m & ARRIBA[c]:
            v = -negamax(a ^ m, m | (m + ABAJO[c]), n + 1, d - 1, -beta, -alfa, cuenta)
            if v > mejor:
                mejor = v
                if v > alfa:
                    alfa = v
                    if alfa >= beta:
                        break
    return mejor

def jugador_alfabeta(d):
    """Jugador de profundidad fija d con la evaluación por amenazas."""
    def elegir(s, rng=None, cuenta=None):
        a, m, n = s
        cuenta = cuenta if cuenta is not None else [0]
        mejor, mj, alfa = -10**9, None, -10**9
        for c in Conecta4.orden:
            if not m & ARRIBA[c]:
                v = -negamax(a ^ m, m | (m + ABAJO[c]), n + 1, d - 1, -10**9, -alfa, cuenta)
                if v > mejor:
                    mejor, mj = v, c
                alfa = max(alfa, v)
        return mj
    return elegir

def jugador_mcts(iteraciones, c=math.sqrt(2), juego=None):
    """Jugador MCTS: tantas iteraciones por jugada y el hijo más visitado."""
    juego = juego or Conecta4()
    def elegir(s, rng):
        raiz = mcts(juego, s, iteraciones, c, rng)
        return max(raiz.hijos, key=lambda h: h.N).jugada
    return elegir

def partida(juego, j1, j2, rng):
    """Juega j1 (empieza) contra j2. Devuelve los puntos de j1 y la lista de jugadas."""
    s, turno, jugadas = juego.inicial, 0, []
    while not juego.terminal(s):
        a = (j1, j2)[turno](s, rng)
        jugadas.append(a)
        s, turno = juego.jugar(s, a), 1 - turno
    if juego.resultado(s) == 0.5:
        return 0.5, jugadas
    return (1.0 if turno == 1 else 0.0), jugadas    # turno == 1: la última jugada fue de j1

def jugador_mcts_reloj(segundos, c=math.sqrt(2), juego=None):
    """Variante con presupuesto de tiempo: itera hasta agotar los segundos."""
    juego = juego or Conecta4()
    def elegir(s, rng):
        raiz, fin = Nodo(None, None, juego.jugadas(s)), time.perf_counter() + segundos
        while time.perf_counter() < fin:
            iteracion(juego, raiz, s, c, rng)
        return max(raiz.hijos, key=lambda h: h.N).jugada
    return elegir

def jugador_alfabeta_reloj(segundos):
    """Profundización iterativa: empieza otra profundidad solo si cabe con un factor 7 de margen."""
    def elegir(s, rng=None):
        t0, d, jugada = time.perf_counter(), 1, None
        while d <= W * H - s[2]:
            t = time.perf_counter()
            jugada = jugador_alfabeta(d)(s)
            gastado = time.perf_counter() - t
            if time.perf_counter() - t0 + 7 * gastado > segundos:
                break
            d += 1
        return jugada
    return elegir

The cell’s players use fixed budgets, iterations for MCTS and depth for alpha-beta, not time, although both timed versions are available. This ensures reproducibility: fixed budgets and seeds give the exact same tournament result on any machine, while a clock depends on speed and other work. Each configuration’s cost is measured separately in milliseconds per move and compared by ratios. One browser game:

[ ]One game: MCTS versus alpha-betaBrowser
rng = random.Random(4)
pts, jug = partida(c4, jugador_mcts(300), jugador_alfabeta(4), rng)
print("MCTS (300 iteraciones, X) contra alfa-beta (profundidad 4, O):", {1.0: "gana MCTS", 0.0: "gana alfa-beta", 0.5: "tablas"}[pts])
print("jugadas:", "".join(str(c + 1) for c in jug), f"({len(jug)} fichas)")
print(dibujar(desde_cadena("".join(str(c + 1) for c in jug))))

One game says nothing; many are needed. Each tournament cell is 60 games, 30 per color because moving first is advantageous in Connect 4. The 540 Connect 4 games and Hex games would take too long in the browser, so tournaments run in the local Python process: a hidden cell repeats previous definitions there and the next plays. Scores are 1 per win and 12\tfrac12 per draw, and the interval is mean ± 1.96 standard errors, the normal approximation for a mean of 60 independent games.

[ ]Connect 4 tournamentLocal GPU
def cronometrado(jugador, reloj):
    """Envuelve un jugador para acumular su tiempo y su número de jugadas."""
    def elegir(s, rng):
        t = time.perf_counter()
        a = jugador(s, rng)
        reloj[0] += time.perf_counter() - t
        reloj[1] += 1
        return a
    return elegir

def torneo(juego, A, B, partidas, semilla):
    """A contra B alternando quién empieza. Devuelve la media de puntos de A, su intervalo al 95 %,
    (victorias, tablas, derrotas) de A y el tiempo medio por jugada de A y de B."""
    ra, rb, pts = [0.0, 0], [0.0, 0], []
    a, b = cronometrado(A, ra), cronometrado(B, rb)
    for k in range(partidas):
        rng = random.Random(f"{semilla}-{k}")
        p = partida(juego, a, b, rng)[0] if k % 2 == 0 else 1 - partida(juego, b, a, rng)[0]
        pts.append(p)
    n = len(pts)
    media = sum(pts) / n
    sd = math.sqrt(sum((x - media) ** 2 for x in pts) / (n - 1))
    vtd = (pts.count(1.0), pts.count(0.5), pts.count(0.0))
    return media, 1.96 * sd / math.sqrt(n), vtd, ra[0] / ra[1], rb[0] / rb[1]

c4 = Conecta4()
print("Conecta 4: puntos de MCTS contra alfa-beta (60 partidas por casilla, 30 con cada color)")
print("iteraciones  profundidad    puntos de MCTS      V-T-D    ms/jugada MCTS   ms/jugada alfa-beta")
for it in (250, 1000, 4000):
    for d in (2, 5, 8):
        m, ic, vtd, ta, tb = torneo(c4, jugador_mcts(it), jugador_alfabeta(d), 60, f"c4-{it}-{d}")
        print(f"{it:11d}  {d:11d}   {m:6.2f} ± {ic:.2f}   {vtd[0]:2d}-{vtd[1]}-{vtd[2]:2d}   {1000 * ta:14.1f}   {1000 * tb:19.1f}", flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

MCTS exceeds 50% of points in none of nine configurations. Depth-2 alpha-beta, costing about a tenth of a millisecond per move, takes 70% and 63% of points from MCTS at 250 and 1000 iterations; only at 4000 iterations, hundreds of times more expensive per move, does MCTS approach it (0.47 ± 0.12, compatible with a draw). At depth 8, alpha-beta spends less than half as much per move as MCTS at 4000 iterations and still wins: MCTS scores 0.28, 0.23 and 0.37 at 250, 1000 and 4000. More iterations help (against depth 2, 0.30 to 0.47), but slowly.

The explanation is what each measures. Threat evaluation captures Connect 4’s essential feature, squares where someone could complete a line, and alpha-beta consults it at every leaf. Random simulations barely distinguish positions: in the convergence figure, five moves scored 0.465 to 0.610 at random although one wins and three lose. If simulation is the defect, adding knowledge should matter, and it does:

[ ]Simulation policy in the tournamentLocal GPU
inf = Conecta4Informada()
print("Simulación informada contra simulación al azar, mismo número de iteraciones (60 partidas)")
for it in (250, 1000):
    m, ic, vtd, ta, tb = torneo(c4, jugador_mcts(it, juego=inf), jugador_mcts(it), 60, f"pol-{it}")
    print(f"  {it:5d} iteraciones: puntos de la informada {m:.2f} ± {ic:.2f}  (V-T-D {vtd[0]}-{vtd[1]}-{vtd[2]}),"
          f" tiempo por jugada {ta / tb:.1f} veces el de la aleatoria", flush=True)
m, ic, vtd, ta, tb = torneo(c4, jugador_mcts(1000, juego=inf), jugador_alfabeta(5), 60, "pol-ab")
print(f"  informada con 1000 iteraciones contra alfa-beta a profundidad 5: {m:.2f} ± {ic:.2f}  (V-T-D {vtd[0]}-{vtd[1]}-{vtd[2]}),"
      f" tiempo por jugada {ta / tb:.0f} veces el de alfa-beta")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

At the same iteration counts, informed-simulation MCTS takes 80% of points from random-simulation MCTS, at both 250 and 1000 iterations, although each move costs a little over twice as much time. And at 1000 informed iterations it already beats depth-5 alpha-beta (0.57 ± 0.12), although spending more than ten times as much per move. The knowledge MCTS lacked to compete in Connect 4 is exactly what threat evaluation gives alpha-beta.

Lab: MCTS in Hex, where alpha-beta without evaluation fails

Hex is played on a rhombus of n×nn \times n hexagonal cells, each with up to six neighbors. Black starts and aims to connect top and bottom edges with a chain of its pieces; white connects left and right. Two facts make Hex ideal for MCTS:

  • There are no draws. With a full board exactly one player has connected their edges. This is the Hex theorem, which Gale (1979) proved equivalent to Brouwer’s fixed-point theorem.
  • Simulation reduces to filling. A piece never obstructs the player placing it, so a player connected at any point remains connected on a full board. Random play to the end equals filling empty cells in random order, alternating colors, and checking once who connects. That is a connected-components problem, solved by union-find in one pass over pieces with two virtual edge nodes.

By Nash’s strategy-stealing argument, the first player wins under perfect play at any size, although the argument does not say how; Hayward and colleagues (2003) solved 7×7 for all openings. For a knowledge-free program, however, even 7×7 is hard: 49 moves in the initial position and a simple evaluation misleads.

[ ]Hex 7×7 with union-findBrowser
from collections import deque

LADO = 7
CASILLAS = LADO * LADO
VECINOS = [[] for _ in range(CASILLAS)]
for f in range(LADO):
    for q in range(LADO):
        for df, dq in ((-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0)):   # las seis vecinas del rombo
            if 0 <= f + df < LADO and 0 <= q + dq < LADO:
                VECINOS[f * LADO + q].append((f + df) * LADO + q + dq)
ARRIBA_HEX, ABAJO_HEX = CASILLAS, CASILLAS + 1     # nodos virtuales: los dos bordes del negro

def raiz_uf(padre, x):
    """Representante de x, con compresión de caminos a la mitad."""
    while padre[x] != x:
        padre[x] = padre[padre[x]]
        x = padre[x]
    return x

def conecta_negro(tab):
    """¿Une el negro (1) el borde de arriba con el de abajo? Unión-búsqueda sobre sus fichas."""
    padre = list(range(CASILLAS + 2))
    for i in range(CASILLAS):
        if tab[i] != 1:
            continue
        f = i // LADO
        if f == 0:
            padre[raiz_uf(padre, i)] = raiz_uf(padre, ARRIBA_HEX)
        if f == LADO - 1:
            padre[raiz_uf(padre, i)] = raiz_uf(padre, ABAJO_HEX)
        for j in VECINOS[i]:
            if j < i and tab[j] == 1:
                padre[raiz_uf(padre, i)] = raiz_uf(padre, j)
    return raiz_uf(padre, ARRIBA_HEX) == raiz_uf(padre, ABAJO_HEX)

def une_bordes(tab, jug, i):
    """¿La ficha de jug recién puesta en i une sus dos bordes? Recorrido de su grupo."""
    vistos, pila, b0, b1 = {i}, [i], False, False
    while pila:
        x = pila.pop()
        k = x // LADO if jug == 1 else x % LADO       # el negro une filas; el blanco, columnas
        b0, b1 = b0 or k == 0, b1 or k == LADO - 1
        for y in VECINOS[x]:
            if y not in vistos and tab[y] == jug:
                vistos.add(y)
                pila.append(y)
    return b0 and b1

class Hex:
    """Estado: (tablero de bytes, jugador al turno, ganador o 0). Negro (1) empieza y une arriba con abajo."""
    inicial = (bytes(CASILLAS), 1, 0)
    def jugadas(self, s):
        return [i for i in range(CASILLAS) if not s[0][i]]
    def jugar(self, s, i):
        tab, p, _ = s
        t = bytearray(tab)
        t[i] = p
        t = bytes(t)
        return t, 3 - p, (p if une_bordes(t, p, i) else 0)
    def terminal(self, s):
        return s[2] != 0
    def resultado(self, s):              # en Hex no hay tablas: quien acaba de mover ha ganado
        return 1.0
    def simular(self, s, rng):
        """Rellena el tablero al azar alternando colores y mira una sola vez quién gana."""
        tab, p, _ = s
        t = bytearray(tab)
        vacias = [i for i in range(CASILLAS) if not t[i]]
        rng.shuffle(vacias)
        for k, i in enumerate(vacias):
            t[i] = p if k % 2 == 0 else 3 - p
        ganador = 1 if conecta_negro(t) else 2
        return 1.0 if ganador != p else 0.0            # para quien movió hasta s, que es 3 - p

# En un tablero lleno gana exactamente uno: lo comprobamos con el blanco transpuesto (filas por columnas)
def conecta_blanco(tab):
    return conecta_negro(bytes(1 if tab[(i % LADO) * LADO + i // LADO] == 2 else 0 for i in range(CASILLAS)))

rng = random.Random(0)
uno_solo = 0
for _ in range(2000):
    t = [1] * 25 + [2] * 24
    rng.shuffle(t)
    uno_solo += conecta_negro(t) != conecta_blanco(t)
print("tableros llenos al azar con exactamente un ganador:", uno_solo, "de 2000")

All 2000 checks, using two independent verifications (black with union-find and white with the same function on the transposed board), confirm exactly one winner on a full board.

The opponent is alpha-beta with the most natural evaluation: each player’s distance to connection, the minimum empty cells needed to join their edges, a shortest path costing 0 on own pieces, 1 on empty cells and prohibited through opponent pieces. Evaluation is opponent distance minus own distance. It is naive because it ignores what makes a Hex position strong: two pieces sharing two empty adjacent cells (a bridge) are effectively connected, because if the opponent occupies one, answer with the other, but distance counts a missing cell. Pre-MCTS successful evaluations, such as Anshelevich’s (2002) virtual connections, build precisely on that idea.

[ ]Alpha-beta with distance evaluationBrowser
INF = 10**6

def distancia(tab, jug):
    """Fichas que le faltan a jug para unir sus bordes: camino más corto con coste 0 en sus
    fichas, 1 en las vacías y sin pasar por las del rival (BFS 0-1)."""
    d = [INF] * CASILLAS
    cola = deque()
    lado = (lambda i: i // LADO) if jug == 1 else (lambda i: i % LADO)
    for i in range(CASILLAS):
        if lado(i) == 0 and tab[i] != 3 - jug:
            d[i] = 0 if tab[i] == jug else 1
            cola.appendleft(i) if d[i] == 0 else cola.append(i)
    while cola:
        x = cola.popleft()
        for y in VECINOS[x]:
            if tab[y] == 3 - jug:
                continue
            w = 0 if tab[y] == jug else 1
            if d[x] + w < d[y]:
                d[y] = d[x] + w
                cola.appendleft(y) if w == 0 else cola.append(y)
    return min(d[i] for i in range(CASILLAS) if lado(i) == LADO - 1)

def evaluar_hex(s):
    """Evaluación ingenua para el jugador al turno: lo que le falta al rival menos lo que le falta a él."""
    tab, p, _ = s
    return distancia(tab, 3 - p) - distancia(tab, p)

def negamax_hex(juego, s, d, alfa, beta):
    if s[2]:
        return -INF                          # quien acaba de mover ha ganado
    if d == 0:
        return evaluar_hex(s)
    mejor = -INF - 1
    for a in juego.jugadas(s):
        v = -negamax_hex(juego, juego.jugar(s, a), d - 1, -beta, -alfa)
        if v > mejor:
            mejor = v
            if v > alfa:
                alfa = v
                if alfa >= beta:
                    break
    return mejor

def jugador_alfabeta_hex(d, juego=None):
    """Alfa-beta de profundidad d; entre jugadas empatadas, una al azar (si no, siempre jugaría igual)."""
    juego = juego or Hex()
    def elegir(s, rng):
        valores = {a: -negamax_hex(juego, juego.jugar(s, a), d - 1, -INF - 1, INF + 1) for a in juego.jugadas(s)}
        mejor = max(valores.values())
        return rng.choice([a for a, v in valores.items() if v == mejor])
    return elegir
[ ]A Hex gameBrowser
hx = Hex()
def dibujar_hex(tab):
    return "\n".join(" " * f + " ".join(".XO"[tab[f * LADO + q]] for q in range(LADO)) for f in range(LADO))

pts, jug = partida(hx, jugador_mcts(500, juego=hx), jugador_alfabeta_hex(2), random.Random(3))
s = hx.inicial
for a in jug:
    s = hx.jugar(s, a)
print("MCTS (500 iteraciones, negro X, une arriba y abajo) contra alfa-beta (profundidad 2, blanco O):",
      "gana MCTS" if pts == 1.0 else "gana alfa-beta", f"en {len(jug)} jugadas")
print(dibujar_hex(s[0]))

At 500 iterations MCTS still loses, and early. The local-process tournament measures how its strength scales with iterations against depth-2 alpha-beta. Depth 3 is already unreasonable: with about 49 moves per level, each extra level multiplies leaves by dozens even with pruning, and each leaf costs a shortest-path search.

[ ]Hex 7×7 tournamentLocal GPU
hx = Hex()
print("Hex 7x7: puntos de MCTS contra alfa-beta de profundidad 2 con la distancia como evaluación (60 partidas)")
print("iteraciones    puntos de MCTS    V-D      ms/jugada MCTS   ms/jugada alfa-beta")
for it in (100, 300, 1000, 3000):
    m, ic, vtd, ta, tb = torneo(hx, jugador_mcts(it, juego=hx), jugador_alfabeta_hex(2), 60, f"hex-{it}")
    print(f"{it:11d}   {m:6.2f} ± {ic:.2f}   {vtd[0]:2d}-{vtd[2]:2d}   {1000 * ta:14.1f}   {1000 * tb:19.1f}", flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

MCTS strength rises steadily with budget: 0 of 60 at 100 iterations, 8 at 300, 20 at 1000 and 43 at 3000, or 0.72 ± 0.11 of points. At 3000 iterations its per-move cost is comparable to depth-2 alpha-beta, so at equal time MCTS wins in Hex what it lost in Connect 4. The difference is not the search algorithm but information source: in Connect 4 threat evaluation was good and alpha-beta exploited it; in Hex simple evaluation is poor, alpha-beta sees only two moves ahead, and random simulations, cheap and draw-free in Hex, measure something much closer to true value. This is computer Hex’s story: MoHex, an MCTS to which Arneson, Hayward and Henderson (2010) added connection knowledge for tree pruning and simulation-board simplification, won the 2009 Computer Olympiad Hex tournament.

To continue, three natural experiments are available in these cells: raise MCTS budget to 10 000 iterations and see whether the curve keeps rising, use timed players to compare at equal time on your machine, and add automatic bridge responses to Hex simulation (if the opponent occupies one of a bridge’s two cells, occupy the other), measuring whether the resulting MCTS beats pure simulation at equal iterations.

Common mistakes

Exercises

NumericThree UCT scores
A node with N=52N = 52 visits has three expanded children with (W,N)=(6,10)(W, N) = (6, 10), (20,40)(20, 40) and (1,2)(1, 2), rewards in [0,1][0, 1] and c=2c = \sqrt 2. Calculate each UCT score. What is the score of the chosen child?
NumericHow many simulations
You want to estimate a position’s random-play value, with rewards in [0,1][0, 1], to error below 0.020.02 with probability at least 0.990.99. By Hoeffding’s inequality, what is the smallest number of independent simulations guaranteeing it?
NumericThe same search on another scale
You implement UCT with rewards in [−1,1][-1, 1] (win 1, draw 0, loss −1-1), opponent reward −r-r and c=2c = \sqrt2. What constant c′c' makes UCT take exactly the same decisions with transformed rewards r′=(r+1)/2∈[0,1]r' = (r + 1)/2 \in [0, 1]?
QuizMore random games
In the lesson’s tic-tac-toe position, flat Monte Carlo with 200 games per move chooses losing corner 0. What happens with 10610^6 games per move?
QuizThree out of three
After 1000 iterations, root child A has N=3N = 3 and Q=1Q = 1 (three wins from three), and B has N=890N = 890 and Q=0.62Q = 0.62; other children have smaller means. You cannot continue searching. What do you play?
QuizPoint rewards
Your game rewards final point difference in [−50,50][-50, 50], and you use UCT with c=2c = \sqrt 2 unchanged. What happens and how do you fix it?
QuizPerfect simulations and still slow
In the trap tree with b=3b = 3 and k=4k = 4, even with perfect simulations (ρ=1\rho = 1: MAX loses every simulation from the trap), MCTS takes about 2100 iterations to prefer a draw. What is the main cause?
ProofUCT converges to minimax value at depth 2
Prove: A depth-2 tree: the root is MAX and has KK children, all MIN; child jj has Lj≥1L_j \ge 1 terminal leaves with deterministic rewards vj1,…,vjLj∈[0,1]v_{j1}, \dots, v_{jL_j} \in [0, 1] for MAX. MCTS uses UCT with constant c>0c > 0 at both levels. Let mj=min⁡lvjlm_j = \min_l v_{jl} y V=max⁡jmjV = \max_j m_j, the minimax value. Then each root child is visited infinitely often and root mean Q0=∑jWj/NQ_0 = \sum_j W_j / N, converges to VV.
0
Write NN for root visits, satisfying N=∑jNjN = \sum_j N_j, NjN_j y Qj=Wj/NjQ_j = W_j / N_j for child jj (with MAX reward) and NjlN_{jl} for its leaves. The first visit to child jj expands it and simulates a game; every later visit descends to one of its leaves, chosen by MIN using UCT on rewards 1−vjl1 - v_{jl}.

Step 1 of 4. Why is every root child visited infinitely often?

CodeBackpropagation with alternating perspective
Implement retropropagar(camino, r). camino lists nodes from root to the iteration’s last node (each has N and W attributes), and r is the [0,1][0, 1] reward of the player whose move reached the last node: 1 for a win, 0.5 for a draw, 0 for a loss. Each node must gain one visit and add to W the reward from the perspective of the player who moved to it. Tests check individual paths then use your function in complete MCTS on small trees with draws and known minimax values.
def retropropagar(camino, r):
  """camino: nodos desde la raíz hasta el último del camino; r: recompensa en [0, 1] de quien hizo
  la jugada que lleva al último nodo. Actualiza N y W de cada nodo del camino."""
  for nodo in camino:
      nodo.N += 1
      nodo.W += r        # ¿de quién es r en cada nivel?
Shift+Enter to run

Summary

Key idea
MCTS replaces evaluation with simulated games and the uniform tree with an asymmetric one growing toward statistically promising moves; UCT decides at each node using UCB1, guaranteeing infinite-budget root mean converges to minimax value, although convergence can be extremely slow when a specific refutation is hidden deep.
  • A random game is an unbiased estimator of random-play value, not minimax value. Flat Monte Carlo measures the wrong question accurately; the MCTS tree makes each player respond well near the root.
  • Each iteration has four phases: tree-policy selection, node expansion, simulation to the end, and backpropagation of NN and WW. With two players, reward is stored from the perspective of the mover to the node and transformed r↦1−rr \mapsto 1 - r at each level.
  • UCT chooses the child maximizing Q+cln⁡Npadre/NhijoQ + c\sqrt{\ln N_{\text{padre}} / N_{\text{hijo}}}. With rewards in [0,1][0, 1] and c=2c = \sqrt 2 it is UCB1; cc refers to reward range and is experimentally tuned.
  • Kocsis and Szepesvári proved UCT consistent, with root bias O(log⁡n/n)\bigO(\log n / n) under their assumptions. Coquelin and Munos showed worst-case time to find the optimal move is hyperexponential in depth, illustrated by deep traps.
  • Choose the final move by visits, not the mean of a rarely visited child. Simulation policy introduces bias that iteration count does not correct; a little knowledge helps greatly, but what matters is that mean values order positions correctly.
  • In the labs alpha-beta with good evaluation beats random-simulation MCTS in Connect 4 in all nine tested configurations, and MCTS catches up when simulation is informed; in Hex 7×7, where simple evaluation is poor, MCTS rises from zero wins at 100 iterations to 0.72 of points at 3000.