← MAIN
HEX // MONTE CARLO TREE SEARCH

HEX

Join your two edges with a chain of stones. The agents search by random games; Chance draws from fixed odds.
STATUS READY MOVES 0 AGENT SIMS — SPEED —

HOW TO PLAY

Join your two edges with an unbroken chain of stones. DOWN (pink) joins the top and bottom rows, and ACROSS (cyan) joins the left and right columns. Hex has no draws, so a full board always has one winner.

Click a hexagon to place a stone. DOWN moves first, and MATCH sets which side you play. With the swap rule on, the second player may take over the first stone: you press SWAP when you are ACROSS, and the agent decides when it is ACROSS.

Press HINT to see the search's suggestion without playing it. To watch two agents instead, set MODE to agent vs agent, choose both agents, and press START.

DOWN · X · TOP TO BOTTOM
ACROSS · O · LEFT TO RIGHT
Click a hexagon to place a stone. Your goal is the pink edges.
WHAT THE AGENT IS THINKING
Make a move, or press HINT, to see the search.
DOWN 50%ACROSS 50%
MOVEVISITSWINRAVE
No search yet.
Move log
MATCH
MODE
YOU PLAY
AGENT
SEARCH LEVEL
More settings
BOARD

HOW IT WORKS

The agents are variants of Monte Carlo tree search (MCTS), which plays many random games from the current position and keeps score of each candidate move. The default agent, RAVE, also credits a move with the results of random games in which that move was played later, so it learns faster from a small budget. The page also offers a plain UCT search, two baselines, and a chance player that does no search at all.

Hex and the board

Hex is a two-player game on a rhombus of hexagons. The board is n rows by n columns, with n = 7 by default and 5 to 11 on this page. Cell (r, c), the cell in row r and column c, is stored at index r · n + c1. DOWN wins by joining the top row to the bottom row with a chain of its stones. ACROSS wins by joining the left column to the right column. The two acute corners belong to both edges. On a full board exactly one player has such a chain, so Hex has no draws.

Each cell has up to six neighbours: the cells to its left and right, the cells above and below, and the two diagonals (r − 1, c + 1) and (r + 1, c − 1). The neighbours function keeps only the ones that lie on the board2.

A connection is a chain of one player's stones from its start edge to its goal edge. The connect function finds a shortest chain with a breadth-first search (BFS). BFS starts from every stone on the start edge and visits neighbours in rings of growing distance, recording each stone's parent so the chain can be read back from the goal edge3. winner_of checks DOWN first, then ACROSS4.

Monte Carlo tree search and UCT

Monte Carlo tree search estimates a move by playing random games from it, not with a hand-written evaluation. It builds a game tree whose root is the current position and whose children are the moves tried so far. Each node stores a visit count, the number of simulations that passed through it, and a win count, the number of those simulations that the player who moved into the node won5.

Each simulation has four steps. Selection descends from the root, choosing the child with the best score, while the node has no untried moves and has children6. Expansion adds one child for an untried move7. Simulation decides the game: if the new child connected its mover's stones, the game is already won, and otherwise a random playout finishes it8. Backpropagation adds one visit to every node on the path, and one win to each node whose mover won9.

UCT (upper confidence bounds applied to trees) chooses the child with the highest score: its win rate plus an exploration bonus, which is large when the child has few visits compared with its parent10.

a^{\star}=\arg\max_{i}\Bigl(\frac{w_i}{n_i}+c\sqrt{\frac{\ln N}{n_i}}\Bigr),\qquad c=0.6
1011

Here i ranges over the children of the node, w_i and n_i are the wins and visits of child i, and N is the node's own visit count, which the code reads as node.visits. The win count w_i belongs to the player who moved into child i, who is the player choosing among the children, so a higher score is always better for the chooser. The constant c = 0.6 is EXPLORE11, and ln is the natural logarithm. A child always has at least one visit by the time it can be selected, because it is backed up in the simulation that creates it.

Random playouts fill the board instead of playing it move by move. fill_playout shuffles the empty cells and hands them out alternately, starting with the player to move. It then checks once whether DOWN is connected. A full board has exactly one winner, so that single check decides the game. The shuffle gives the same distribution of finished games as playing uniformly random legal moves12.

The agent plays the child with the most visits, not the child with the highest win rate13. The search's value is the win chance it reports for the mover, which is the win rate of that same child14.

\hat p=\frac{w_b}{n_b},\qquad b=\arg\max_{i}\,n_i
1314

Here b is the most-visited child of the root, and w_b and n_b are its wins and visits. The gauge on the page shows this value for DOWN and for ACROSS.

1516
function MCTS-SEARCH(position, simulations):
    repeat simulations times:
        path ← DESCEND(root)                # best blended score at each level
        node ← the last node of path
        if node has untried moves:
            node ← EXPAND(node)             # RAVE tries the best AMAF rate first
        winner ← PLAYOUT(node)              # a connected child is decided; else random fill
        BACKUP(path, winner)                # visits, wins and AMAF counts
    return the move of the root child with the most visits

Selection and expansion in the full version. The selection loop descends until it reaches a node with an untried move, or a node without children, which is a finished game. PICK-UNTRIED is where UCT and RAVE differ: UCT chooses at random, while RAVE chooses the move with the best AMAF rate. The rate uses a Laplace-smoothed estimate, so an unseen move starts at one half.

The board is shared, not copied. The stones of the current path are placed on one list, and they are taken off again after the backup, so each simulation starts from the root position. The random playout still works on a copy, because it fills every empty cell and does not undo the fill.

Terminal children. When expansion creates a child whose stone connects its mover, the game is decided at once. The child is marked terminal and gets no random playout, and its result is known exactly.

The time budget. The clock is read only every 32 simulations, which keeps the timing check cheap. A budget of simulations and a time limit can both be set, and the search stops at whichever comes first.

RAVE: all-moves-as-first statistics

RAVE (rapid action value estimation) adds all-moves-as-first (AMAF) statistics to UCT. In a playout, a cell that a player takes after a node has been reached is credited to that node's player as if it had been played first. Each node keeps, for every cell m, rave_n[m], how often its player took m after the node in a simulation through it, and rave_w[m], how often that player then won5. These estimates are biased, because a cell played later is often a different move in the position where the node sits. They come in much larger numbers early in the search, which is why they help when the budget is small.

Each child's score then blends the UCT win rate q with the RAVE rate q_RAVE, for the child's cell m, read at the parent17:

Q=(1-\beta)\,q+\beta\,q_{\mathrm{RAVE}},\qquad \beta=\sqrt{\frac{k}{3n+k}}
1718

Here q = w / n is the child's own win rate, and n is its visit count. The RAVE rate q_RAVE = rave_w[m] / rave_n[m] is used only when rave_n[m] is above zero. Otherwise the score is the plain UCT value. The constant k = 300 is RAVE_K19, and β, the weight on the RAVE rate, falls as the child gains visits. A child with few visits trusts the shared estimate, and a child with many visits trusts its own win rate.

Example. At n = 300 visits, β = √(300 / (900 + 300)) = 0.5, so the two estimates count equally. A child with 3 visits has β = √(300 / 309) ≈ 0.99, so almost all of its score is the RAVE rate.

RAVE also changes which untried move is expanded first. Each untried cell m gets the Laplace-smoothed rate below, which is one half for a cell that has never been played in a simulation through the node20. Ties are broken at random.

\frac{\mathrm{rave\_w}[m]+1}{\mathrm{rave\_n}[m]+2}
21

The expansion picks the untried cell with the largest value of this rate. The numerator and denominator are the RAVE win and visit counts of the cell at this node. One is added to the win count and two to the visit count, so a cell with no samples scores one half.

In backpropagation, the sequence of cells played after the root is the tree moves followed by the playout order22. The player who moves at each depth d also plays the cells at positions d, d + 2 and so on, so each node receives one AMAF sample for every such cell. The full MCTS pseudocode above shows this loop.

The swap rule

The optional swap rule, also called the pie rule, lets the second player take over the first stone instead of replying. The stone changes colour, and the turn passes back to the first player. The move is written SWAP, as −1, and it is legal only as the reply to the first move, with the rule on23.

The agent decides this only on ACROSS's first turn, as the second player. It runs two searches, each with the full budget of its level, so that turn can take about twice as long: one for staying, from the position as it is, and one for swapping, from the position with the first stone recoloured and DOWN to move. The agent swaps when its win chance is higher after the swap24.

\text{swap}\iff 1-v_{\mathrm{after}}>v_{\mathrm{stay}}
25

Here v_stay is ACROSS's win chance from the search that stays, and v_after is DOWN's win chance from the search after the swap. The term 1 − v_after is therefore ACROSS's win chance after the swap. If the swap is not chosen, the agent plays the most-visited move of the search that stays.

26
function CHOOSE-MOVE(board):
    if the swap rule is on and ACROSS is to move with one stone on the board:
        stay ← ACROSS's win chance from MCTS-SEARCH(board)
        swapped ← board with the first stone recoloured
        swap ← 1 − DOWN's win chance from MCTS-SEARCH(swapped)
        if swap > stay:
            return SWAP
    return the move of MCTS-SEARCH(board)

Why the swap is compared with the stay. Both values are estimates of the same thing, ACROSS's chance of winning, so the larger one is the better choice. The search after a swap has DOWN to move, so its value is read as 1 − value to get ACROSS's chance. Each search draws its own seed from the agent's generator, so a seeded game repeats exactly.

Shortest-path race (baseline)

The shortest-path agent does not search. It measures each side's distance to connection, the fewest empty cells that side still has to fill to complete a chain. Its own stones cost 0, empty cells cost 1, and opposing stones are walls27. The distance is found with a 0-1 breadth-first search, a shortest-path search in which each step costs 0 or 1 and a double-ended queue keeps the frontier in order28.

d_p=\min_{g\in G_p}\operatorname{dist}_p(g),\qquad \operatorname{score}(m)=d_{\mathrm{opp}}-d_{p}
2930

Here d_p is the distance of player p, G_p is the set of its goal-edge cells, and dist_p(g) is the cheapest cost to reach g from the start edge. Both distances are measured with the candidate move m placed. The agent plays the empty cell with the largest score, which lengthens the opponent's route the most while shortening its own. Ties are broken at random31. It looks one move ahead, so it does not see that a block can be answered. It is a fair but weak benchmark opponent.

3128
function SHORTEST-PATH-MOVE(position):
    for each empty cell m:
        score(m) ← DISTANCE(opponent) − DISTANCE(player to move), with m placed
    return a cell with the largest score, ties broken at random

The deque. A 0-1 search needs a queue sorted by distance. Zero-cost steps go to the front and one-cost steps to the back, so the first cell popped always has the smallest distance so far. This is cheaper than a general shortest-path search.

Random (baseline)

The random agent plays a uniformly random empty cell with no thought32. It sets the floor for the others. It ignores the strength setting, as the shortest-path agent does.

Chance (fixed odds)

The chance agent is a fixed-odds baseline with no search, evaluation or lookahead. Each empty cell gets a weight from its hex ring, which is its hex distance from the centre cell. The centre is ring 0, its six neighbours are ring 1, and so on. The weights for rings 0, 1, 2 and 3 and beyond are 4, 3, 2 and 133.

The hex distance is measured on the same six-neighbour grid as the board. With m = ⌊(n − 1) / 2⌋ the centre row and column, and dr and dc the row and column offsets from the centre34:

\operatorname{ring}=\begin{cases}\max(|dr|,|dc|) & dr\cdot dc\le 0\\ |dr|+|dc| & \text{otherwise}\end{cases}
34

The six neighbour steps are (0, ±1), (±1, 0), (−1, +1) and (+1, −1). A diagonal step therefore changes the row and column in opposite directions, and two offsets with the same sign need the sum of their sizes.

Each empty cell i gets the weight of its ring, with rings 3 and beyond sharing the last weight, and the weights are renormalised over the empty cells35:

p(i)=\frac{w_{\min(\mathrm{ring}(i),\,3)}\;\mathbf{1}[i\ \text{empty}]}{\sum_{j}w_{\min(\mathrm{ring}(j),\,3)}\;\mathbf{1}[j\ \text{empty}]},\qquad (w_0,w_1,w_2,w_3)=(4,3,2,1)
3533

Here 1[i empty] is 1 for an empty cell and 0 for an occupied one, so an occupied cell has probability zero. The denominator sums the weights of the empty cells, so the probabilities add to one while any cell is empty. The agent draws one cell with these probabilities36.

Example. On an empty 7 × 7 board, the centre is ring 0, six cells are ring 1, twelve are ring 2, and the other 30 are ring 3 or beyond. The weights total 4 + 18 + 24 + 30 = 76, so the centre has probability 4/76 ≈ 5.3%, a ring 1 cell 3/76 ≈ 3.9%, a ring 2 cell 2/76 ≈ 2.6%, and an outer cell 1/76 ≈ 1.3%. The page's table lists the most likely cells with their odds. The strength setting has no effect on this agent.

363534
function CHANCE-MOVE(position):
    for each cell i:
        weight[i] ← 0 if i is occupied, else CHANCE-RING-WEIGHTS[min(HEX-RING(i), 3)]
    return one empty cell drawn with probability weight[i] / total weight

The chance agent never swaps, and its analysis carries the odds rather than a search table. The page's requests pass no seed to the agents, so the same position can get different moves on different requests. The CLI and the benchmark pass seeds, which makes their games repeatable.

Parameters and their values

HeuristicWhat it measuresValue / weight
Exploration cBonus for children with few visits, in UCT and RAVE0.6
Equivalence kVisits before a child's own win rate outweighs its RAVE rate300
betaWeight on the RAVE rate for a child with n visitssqrt(k / (3n + k)); 0.5 at n = 300
Level 1 budgetSimulations or seconds per move, whichever ends first300 or 0.4 s
Level 2 budget (default)Same rule, the page's standard setting1,000 or 0.9 s
Level 3 budgetSame rule, the deep setting3,000 or 1.8 s
Chance ring weightsFixed weight per hex ring from the centre cell, before renormalising over empty cells4 / 3 / 2 / 1 for rings 0 / 1 / 2 / 3+
Board sizeSide of the rhombus of hexagons5 to 11; the page starts at 7

How these were chosen. c = 0.6 and k = 300 are constants in hexgame/mcts.py37, set by hand and not tuned: the repository has no sweep over either. The beta formula is the RAVE blend that the module attributes to Gelly and Silver38. Each level's budget caps the work per move at a simulation count or a time, whichever comes first, so one request stays bounded39.

Results

The benchmark plays seeded games on a 7 × 7 board with 400 simulations per move and 40 games per matchup, alternating colours40. RAVE beats UCT in 40 of 40 games, and it beats the shortest-path race in 39 of 40. UCT wins 13 of 40 against the race, and both search agents beat the random agent in all 40 games. Each win rate carries a 95% Wilson score interval, the interval in which the true rate lies with 95% confidence, computed from the win count k in n games41:

\text{centre}=\frac{p+\frac{z^{2}}{2n}}{1+\frac{z^{2}}{n}},\qquad \text{half}=\frac{z\sqrt{\frac{p(1-p)}{n}+\frac{z^{2}}{4n^{2}}}}{1+\frac{z^{2}}{n}},\qquad p=\frac{k}{n},\; z=1.96
41

The interval is centre ± half. Here k is the number of wins, n the number of games, p the observed win rate and z the 95% normal quantile. For 20 wins in 20 games the interval is 91.2% to 100%.

Speed on an empty 7 × 7 board, on one core in pure Python, is 5,811 simulations per second for RAVE, 5,783 for UCT, and 10,739 random fill playouts per second40. A check at 1,000 simulations per move, which is in the README but not in results/, has RAVE winning 18 of 20 games against UCT42. The gap narrows as the budget grows. That check is not a measured reversal.

Against the chance player at level 1, 300 simulations per move, RAVE won all 20 games with colours alternating43.