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.
| MOVE | VISITS | WIN | RAVE | |
|---|---|---|---|---|
| No search yet. | ||||
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 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 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.
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.
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.
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
function MCTS-SEARCH(position, simulations, seconds, rave = true, c = 0.6, k = 300):
board ← copy of the cells of position # stones on the tree path are placed here, then taken back
root ← NODE(to move = the player to move, untried = the empty cells)
start ← now
sims ← 0
repeat while sims < simulations:
if seconds is set and sims mod 32 = 0 and now − start > seconds:
stop # the time budget is spent
node ← root
path ← [root] # the nodes from the root to this simulation's leaf
moves ← empty list # the cells played along the tree part
# 1. selection: descend while the node has no untried moves and has children
while node has no untried moves and node has children:
node ← SELECT(node, c, k, rave)
board[node.cell] ← node.mover
append node to path
append node.cell to moves
# 2. expansion: add one child for an untried move
if node has untried moves:
cell ← PICK-UNTRIED(node, rave), removed from node.untried
mover ← node.to_move
board[cell] ← mover
connected ← CONNECTED(board, mover)
child ← NODE(cell, mover, to move = other(mover), untried = [] if connected else the empty cells, terminal = connected)
add child to node.children
node ← child
append node to path
append cell to moves
# 3. simulation: a finished game has a known winner
if node is terminal:
winner ← node.mover
order ← empty list
else:
winner, order ← FILL-PLAYOUT(copy of board, node.to_move)
# 4. backpropagation: visit and win counts, then the AMAF counts
for each nd in path:
nd.visits ← nd.visits + 1
if nd.mover = winner:
nd.wins ← nd.wins + 1
if rave:
seq ← moves followed by order
for each depth d, nd in path: # nd.to_move plays seq[d], seq[d+2], ...
for j ← d, d + 2, ... while j < length of seq:
m ← seq[j]
nd.rave_n[m] ← nd.rave_n[m] + 1
if winner = nd.to_move:
nd.rave_w[m] ← nd.rave_w[m] + 1
for each cell m in moves:
board[m] ← EMPTY # the board is back to the root position
sims ← sims + 1
best ← the root child with the most visits
return best.cell, sims, the visit and win counts, value = best.wins / best.visits
function SELECT(node, c, k, rave):
log_n ← ln(node.visits)
for each child ch of node:
q ← ch.wins / ch.visits
if rave and node.rave_n[ch.cell] > 0:
q_rave ← node.rave_w[ch.cell] / node.rave_n[ch.cell]
β ← sqrt(k / (3 · ch.visits + k))
q ← (1 − β) · q + β · q_rave
score ← q + c · sqrt(log_n / ch.visits)
return the child with the largest score
function PICK-UNTRIED(node, rave):
if not rave:
return a random index into node.untried
for each index i, cell m in node.untried:
key ← ((node.rave_w[m] + 1) / (node.rave_n[m] + 2), a random number)
return the index with the largest key
function FILL-PLAYOUT(cells, to_move):
order ← the empty cells of cells, shuffled
player ← to_move
for each cell i in order:
cells[i] ← player
player ← other(player)
if CONNECTED(cells, DOWN):
winner ← DOWN
else:
winner ← ACROSS
return winner, order
function CONNECTED(cells, player):
queue ← the stones of player on its start edge, each with no parent
while queue is not empty:
u ← the first cell in queue, removed
if u is on the goal edge:
return the chain of parents back from u
for each neighbour v of u with cells[v] = player and v not yet reached:
record u as the parent of v
add v to the back of queue
return none
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 (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:
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.
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 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.
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.
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)
function CHOOSE-MOVE(board, agent, sims, seconds, seed):
rng ← random generator seeded with seed
if board.swap_rule and length of board.moves = 1 and board.to_move = ACROSS:
stay ← MCTS-SEARCH(board.cells, ACROSS, sims, seconds, seed = a new random seed)
swapped ← copy of board.cells
swapped[first move] ← other(swapped[first move]) # the second player takes the stone
after ← MCTS-SEARCH(swapped, DOWN, sims, seconds, seed = another new random seed)
win_stay ← stay.value # ACROSS's win chance
win_swap ← 1 − after.value # ACROSS's win chance after the swap
if win_swap > win_stay:
return SWAP, analysis with both searches' counts and both win chances
return stay.move, analysis of stay, with both win chances
move, analysis ← MCTS-SEARCH(board.cells, board.to_move, sims, seconds, a new random seed)
return move, analysis
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.
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.
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.
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
function SHORTEST-PATH-MOVE(cells, to_move, rng):
opp ← other(to_move)
best ← empty list
best_score ← none
for each cell m from 0 to n × n − 1:
if cells[m] is occupied:
skip m
cells[m] ← to_move
score ← DISTANCE(cells, opp) − DISTANCE(cells, to_move)
cells[m] ← EMPTY
if best_score is none or score > best_score:
best ← [m]
best_score ← score
else if score = best_score:
append m to best
return a random element of best
function DISTANCE(cells, player):
dist[i] ← infinity for every cell i # the code uses 10^6 as infinity
queue ← empty double-ended queue
for each start-edge cell s with cells[s] ≠ opp:
w ← 0 if cells[s] = player, else 1
dist[s] ← w
push s to the front if w = 0, else to the back
while queue is not empty:
u ← pop from the front
for each neighbour v of u with cells[v] ≠ opp:
w ← 0 if cells[v] = player, else 1
if dist[u] + w < dist[v]:
dist[v] ← dist[u] + w
push v to the front if w = 0, else to the back
return the minimum of dist over the goal-edge cells
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.
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.
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:
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:
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.
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
function CHANCE-MOVE(cells, rng):
weights ← empty list
for each cell i:
if cells[i] is occupied:
weights[i] ← 0
else:
weights[i] ← CHANCE-RING-WEIGHTS[min(HEX-RING(i), 3)] # (4, 3, 2, 1)
total ← sum of weights
odds[i] ← weights[i] / total for each cell i # sums to 1, occupied cells get 0
return one cell drawn from 0 to n × n − 1 with probabilities odds, using rng
function HEX-RING(cell):
r, c ← the row and column of cell
m ← floor((n − 1) / 2) # the centre row and column
dr ← r − m
dc ← c − m
if dr × dc ≤ 0:
return max(|dr|, |dc|)
return |dr| + |dc|
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.
| Heuristic | What it measures | Value / weight |
|---|---|---|
| Exploration c | Bonus for children with few visits, in UCT and RAVE | 0.6 |
| Equivalence k | Visits before a child's own win rate outweighs its RAVE rate | 300 |
| beta | Weight on the RAVE rate for a child with n visits | sqrt(k / (3n + k)); 0.5 at n = 300 |
| Level 1 budget | Simulations or seconds per move, whichever ends first | 300 or 0.4 s |
| Level 2 budget (default) | Same rule, the page's standard setting | 1,000 or 0.9 s |
| Level 3 budget | Same rule, the deep setting | 3,000 or 1.8 s |
| Chance ring weights | Fixed weight per hex ring from the centre cell, before renormalising over empty cells | 4 / 3 / 2 / 1 for rings 0 / 1 / 2 / 3+ |
| Board size | Side of the rhombus of hexagons | 5 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.
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:
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.