Get four discs in a row, across, down or diagonally, before the opponent.
Click a column to drop a disc. Red moves first.
Choose AI vs AI to watch two algorithms play each other.
Connect Four is played on a grid of seven columns and six rows. Players take turns dropping a disc into a column, and the disc falls to the lowest empty cell of that column. The first player to make four discs in a row wins. A full board with no four in a row is a draw. This page offers four ways to choose a column: an AlphaZero-style agent, which combines a tree search with a neural network trained by self-play; alpha-beta minimax, which searches ahead with a hand-written evaluation; Monte Carlo tree search, which judges moves by random games; and a chance agent, which draws a column from fixed odds.
A position is stored as two integers, each with seven bits per column. Bits 0 to 5 of a column are its six cells, from the bottom up, and bit 6 is a spare bit that stops line checks from carrying into the next column. The integer mask marks every stone on the board. The integer current marks the stones of the player to move. The other player's stones are current ^ mask, so the pair describes the position from either side1.
Dropping a disc in column c is mask | (mask + bottom(c))2. The addition carries up through the stones already in the column and sets the lowest empty cell, clearing the stones it passed; the OR restores them. A column is full when its top cell is set3. A four in a row is detected with two shift-and-AND steps per direction: a pair of adjacent stones ANDed with the same pair two steps further on leaves a run of four4. The integer current + mask is the position's key, which the transposition table below uses to recognise a repeated position5.
Tree search builds a game tree. The root is the current position, each legal move is a branch, and each reply is a further branch. The tree grows one simulation at a time. A simulation starts at the root, follows branches down to a leaf (a position whose moves have not been expanded yet, or a terminal position: a four in a row, or a full board), evaluates the leaf, and passes the result back up the path.
The selection rule is PUCT, a variant of UCT (upper confidence bounds applied to trees) in which the exploration bonus is scaled by a prior. The prior is the probability that the network's policy gives each move before the move has been searched. The policy is a distribution over the seven columns. For each position s and column a, the search keeps the visit count N(s,a), the number of simulations that passed through a; the total value W(s,a), the sum of the values backed up through a; and the prior P(s,a). The mean value Q(s,a) is zero for an unvisited move.
Here a* is the chosen column, Legal(s) is the set of columns that are not full, and c_puct = 2.0 is the default both in the Tree constructor9 and in search10, which the agent calls without overriding it11. The prior P(s,a) is the network's probability for column a, zero for a full column. The term N(s) sums the visits of all columns of s, and the +1 inside the square root keeps U non-zero before the first visit. The first term favours moves that have done well so far. The second favours moves that have a high prior and few visits. As visits accumulate, U shrinks relative to Q, so the search concentrates on the lines it has found good.
Expansion. When a simulation reaches a leaf that is not terminal, the network is called once. It returns the priors over the legal columns and a value v in [−1, 1], the network's estimate of the result for the player to move, where 1 is a win and −1 a loss. The priors are stored at the leaf and v is backed up. A terminal leaf needs no network call. Its value is −1 if the player to move has lost, which is the case when the previous move made four in a row, and 0 for a full board.
Backup. The value changes sign at each step up the path, because a position that is good for the player to move is bad for the player who moved into it. Each move on the path gains one visit, and its total value gains the value as seen by the player who chose that move.
Each step applies these three updates to the move (s,a) that was chosen at each node on the path, from the leaf back to the root. The sign flip happens before the update, so W(s,a) is always the value seen by the player who chose a at s.
Choosing the move. After the simulations, the agent plays the column with the most visits13. The win probability shown on the page is the mean of all root backups, mapped from [−1, 1] to a percentage14 15:
Here s_0 is the root position. The sum runs over the seven columns, so the numerator and denominator together are the total value and total visits over all simulations from the root. The result is a search estimate, not the value of a single network call.
function PUCT-SEARCH(position, simulations):
EXPAND(root, NETWORK-PRIORS(position))
repeat simulations times:
leaf, path ← SELECT(root) # follow the largest Q + U
if leaf is terminal:
value ← TERMINAL-VALUE(leaf) # −1 lost, 0 draw
else:
priors, value ← NETWORK(leaf)
EXPAND(leaf, priors)
BACKUP(path, value) # the sign flips at each level
return the column with the most visits
function PUCT-SEARCH(position, simulations, c_puct = 2.0):
root ← NODE(position)
priors, value ← NETWORK(position) # the root's value is not used
if self-play:
priors ← MIX-NOISE(priors) # (1 − ε) prior + ε η, root only
root.prior ← priors
repeat simulations times:
node ← root
path ← empty list
while node is expanded and node is not terminal:
N ← sum of visits of node over all columns
for each legal column a:
if N(node, a) > 0:
Q ← W(node, a) / N(node, a)
else:
Q ← 0
U ← c_puct · prior(node, a) · sqrt(N + 1) / (1 + N(node, a))
score(a) ← Q + U
a ← argmax over legal columns of score(a)
append (node, a) to path
node ← child of node after a, created if missing
if node is terminal:
value ← TERMINAL-VALUE(node) # −1 if the player to move lost, 0 if full
else:
priors, value ← NETWORK(node.position)
node.prior ← priors
for (node, a) in reversed(path):
value ← −value # the parent's player is the leaf's opponent
N(node, a) ← N(node, a) + 1
W(node, a) ← W(node, a) + value
return the column a with the largest N(root, a)
Selection, in the full version. The loop descends while the node already has priors and is not terminal. Q and U are computed for each legal column and the largest sum is taken. A column that has never been visited has Q = 0, so its U term alone decides whether it is tried. The child node is created the first time a path reaches it.
Terminal values. A terminal leaf is scored without the network. The value is −1 when the player to move has lost, because the previous move made four in a row, and 0 for a full board17. Because the value is taken from the player to move at the leaf, the backup flip gives the correct sign at every level above it.
Batching. Self-play runs many games at once. In each round every game selects its leaf, and all the leaves are sent to the network in one call18. The result is the same search as the one-game version above, but the network is called once per round instead of once per leaf.
Tree reuse. After a move is played, the child node for that move becomes the new root and keeps its subtree of visits. During self-play the new root receives fresh Dirichlet noise19. Playing against a person uses no noise.
The Dirichlet distribution Dir(α) gives a random probability vector over the legal columns. The parameter α = 1.0 and the mixing weight ε = 0.25 are both set in the self-play trees21. P' replaces the root prior, so each self-play game explores moves the network would not choose on its own. The noise is only applied at the root, not at deeper nodes22.
A neural network is a function whose weights are learned from data. The network here is a policy-value network with two outputs: the policy, one score per column, and the value, a number in [−1, 1] for the player to move. Its input is two 6×7 planes. Plane 0 marks the stones of the player to move, and plane 1 the other player's23.
The trunk is a 3×3 convolution stem (a learned filter applied at every cell), followed by four residual blocks. A residual block is two 3×3 convolutions whose output is added back to the block's input, so each block learns a change to its input. Each convolution is followed by batch normalisation during training, a learned rescaling of its channels. For serving, that rescaling is folded into the convolution weights24, so the website runs the network in plain NumPy with no torch.
Here x is the encoded position, z the logits, and ReLU(x) = max(x, 0). Conv1×1 is a 1×1 convolution, a linear map across channels at each cell. W and b are learned weights and biases, and tanh squashes the value into [−1, 1]. The shipped weights have the sizes of the defaults: 4 blocks of 32 channels, a policy head with 2 channels feeding a 84-to-7 layer, and a value head with 1 channel feeding a 42-to-64 layer and then a 64-to-1 layer (checked in the shipped weights file29). The masked softmax sets illegal columns to zero before normalising, so the priors are a distribution over legal columns only30.
Self-play means the network plays games against itself, and its own search chooses every move. Each iteration plays a batch of games: 128 per iteration on the laptop runs (the script default31), and 512 on the Kaggle run32. Two details keep the games varied. The root of each search gets Dirichlet noise, as described above. And during the first 8 moves of each game, the move is sampled from the visit counts rather than taken as the most visited column33.
The policy target π is the distribution of root visits, computed with temperature = 1.035. For a position s, N(s,a) is the number of simulations of that search that chose column a at the root. The move is sampled from π while the board has fewer than 8 stones, and is the column with the largest π after that.
Each game gives training rows. A row holds the board, the policy target π, and the outcome z for the player to move there. The outcome is +1 for a win, 0 for a draw and −1 for a loss, seen from that player's side36. Every row is also stored with its mirror image, the board reflected left to right and π reversed in the same way, since a Connect Four position and its reflection have the same game-theoretic value37.
Training samples minibatches from a replay buffer, a rolling store of the newest rows. The laptop runs kept the script's default of 200,000 rows and used its default minibatch of 25638. The Kaggle run used --buffer 400000 --batch 51232. For each sample the loss has two parts. The mean squared error compares the value with the outcome. The cross-entropy compares the policy with the visit distribution π.
Here B is the minibatch size, v_i and z_i are the value and outcome of row i, π_i is its visit target, and p_i = softmax(logits) is the network's policy for row i, so log p is taken with log-softmax. The loss is minimised with AdamW, an Adam optimiser with decoupled weight decay: the weights are shrunk by a factor each step, which discourages large weights. The learning rate is 0.00140 and the weight decay is 0.000141. The weight decay is applied by the optimiser, not added to the loss.
function TRAIN(iterations):
network ← NEW-NETWORK()
buffer ← empty, keeps the newest rows
repeat iterations times:
rows ← SELF-PLAY(network) # games played by the search
add rows to buffer
repeat steps times:
batch ← rows drawn at random from buffer
loss ← (value − outcome)² + cross-entropy(policy, visit targets)
update the network weights to reduce loss
save the checkpoint and the NumPy weights
function TRAIN(iterations, games, simulations, steps, batch, buffer_size):
network ← NEW-NETWORK() # 4 residual blocks, 32 channels
optimiser ← ADAMW(learning rate 0.001, weight decay 0.0001)
buffer ← empty, with maximum length buffer_size
repeat iterations times:
rows, results ← SELF-PLAY(network, games, simulations)
append rows to buffer # the oldest rows drop out first
repeat steps times:
minibatch ← min(batch, length of buffer) rows drawn at random from buffer
value_loss ← mean over minibatch of (v − z)²
policy_loss ← mean over minibatch of −sum over a of π(a) · log p(a)
loss ← value_loss + policy_loss
take one AdamW step on loss
save the checkpoint # so a run can resume
export the weights as NumPy arrays with batch norm folded in
function SELF-PLAY(network, games, simulations):
trees ← one search tree per game, each with root noise (ε = 0.25, α = 1.0)
histories ← one empty list per game
active ← every game
while active is not empty:
RUN-SIMULATIONS(trees of the active games, simulations) # one batched network call per round
for each game g in active:
board ← root board of tree g
π ← root visit counts of tree g, divided by their sum
if board has fewer than 8 stones:
move ← a column sampled from π
else:
move ← the column with the largest π
append (board, π) to histories[g]
next ← RESULT(board, move)
if next has four in a row: # the player who moved wins
result[g] ← +1 if the mover is the first player, else −1
remove g from active
else if next is full:
result[g] ← 0
remove g from active
else:
ADVANCE(tree g, move) # keep the subtree of the chosen move
rows ← empty list
for each game g:
for each (board, π) in histories[g]:
z ← result[g] if the mover of board is the first player, else −result[g]
append (board, π, z) to rows
append (MIRROR(board), π reversed, z) to rows
return rows, results
The network is trained only on its own games, with no human games, no opening book and no positions labelled by another engine. The first 37 iterations ran on a laptop CPU (Intel Core i7-1265U, no GPU) and produced 4,736 self-play games. A Kaggle notebook then continued from that checkpoint for 8 hours on 4 CPU threads, with no GPU attached. It ran 59 iterations, to iteration 96 and 34,944 games, and the weights served on this page are the export from iteration 9632. Each iteration of the Kaggle run used 512 games and 100 simulations per move, with 400 training steps.
The table compares the served network with the iteration-19 network it replaced. Every match is against fixed-depth alpha-beta minimax with no time limit, 100 games per depth, 200 simulations per move, colours alternating, and two random opening moves per game43. The score counts a draw as half a win.
| Match | Wins | Draws | Losses | Score |
|---|---|---|---|---|
| Iteration 96 vs minimax depth 2 | 67 | 8 | 25 | 71% |
| Iteration 96 vs minimax depth 4 | 79 | 4 | 17 | 81% |
| Iteration 96 vs minimax depth 6 | 77 | 8 | 15 | 81% |
| Iteration 19 vs minimax depth 2 | 61 | 5 | 34 | 63.5% |
| Iteration 19 vs minimax depth 4 | 53 | 10 | 37 | 58% |
| Iteration 19 vs minimax depth 6 | 29 | 20 | 51 | 39% |
| Plain MCTS, 1,000 rollouts, vs minimax depth 4 (50 games) | 32 | 2 | 16 | 66% |
| AlphaZero, level 1 (50 simulations), vs chance (20 games) | 20 | 0 | 0 | 100% |
The iteration-96 numbers are in the results file44. The iteration-19 rows use the same protocol and openings and are kept in the same file under previous_network. The MCTS row is from the earlier 50-game evaluation, which does not depend on the network. The chance row is in the results file45, which plays with colours alternating and seed 046. Over 100 games the iteration-19 network scores lower than in its earlier 50-game run (77% against depth 4), which shows how far 50 games can move from noise. The goal of winning nearly every game against depth 6 was not reached: the served network still loses 15 of 100 games there.
Minimax is a decision rule for two-player, zero-sum games, where one player's gain is exactly the other's loss. It assumes each player chooses the move that is best for them. The algorithm searches the game tree to a fixed depth, the number of plies (single moves) searched, and at the bottom scores each position with a heuristic evaluation, a fast estimate of how good the position is for the player to move.
The code uses negamax, a form of minimax that is written once for both players. A position's score is seen from the side to move, and the score of a move is the negation of the score of the position it leads to. The best move is the one with the largest negated score.
Here V(s) is the score of position s for the side to move, s·a is the position after column a, and the leaf value at depth 0 is the evaluation E(s) below. A draw has score 0.
Alpha-beta pruning carries two bounds down the tree. Alpha is the lowest score the side to move can already guarantee. Beta is the highest score the opponent would allow, because the opponent would avoid any line that gives more. When a move's score reaches beta, the opponent will not let play reach this position, so the rest of its moves are not searched. The root's value is the same as plain negamax gives, with fewer positions visited. How soon the best move is tried decides how many branches are cut.
Iterative deepening searches to depth 1, then depth 2, and so on, until the time budget runs out. A depth that does not finish is thrown away, and the move from the last finished depth is played. The result of each depth also orders the next one: the previous best move is tried first48.
A transposition table remembers positions that different move orders reach. For each key it stores the depth searched, a flag, the value and the best move. EXACT means the value is exact. LOWER means the true value is at least the stored value, because the search failed high (a score reached beta). UPPER means the true value is at most the stored value, because the search failed low (no score exceeded the starting alpha). An entry is used only when it was searched to at least the current depth.
Columns are tried in the order 3, 2, 4, 1, 5, 0, 6, centre first49, after the table's suggested move. The centre column lies on more four-cell lines than any other, so a centre move is more likely to be good, and trying it early cuts more branches.
At depth 0, a position is scored by counting windows. A window is one of the 69 lines of four cells on the board. A window that holds stones of only one player scores for that player: 1 point for one stone, 8 for two, 64 for three. Stones in the centre column add to the score (3 points each for the side to move, −3 for the opponent)50.
Here W is the set of 69 windows, a_w and b_w are the numbers of stones of the side to move and of the opponent in window w, and P_k is the points for k stones (P_0 = 0, and P_4 = 0 because a four in a row is caught as a win before evaluation). The bracket 1[·] is 1 when its condition holds and 0 otherwise. c_me and c_opp count the stones of each side in the centre column (column 3). A window with stones of both players scores nothing, which is why the bracketed terms vanish when both a_w and b_w are non-zero.
A win is scored as WIN minus the number of moves from the search's root to the winning move, with WIN = 1,000,000. A faster win therefore scores higher, and the agent prefers it52.
Here p is the number of moves already made from the search's root when the side to move finds its winning column, so p + 1 counts that winning move too. Scores within 64 of WIN are treated as forced results. When the root's best score is forced, the search stops deepening, since a deeper search cannot change a forced result54.
How the evaluation was chosen: hand-set. The window points, the centre weight of 3 and WIN are constants in the minimax file55. No tuning run is recorded in results/.
function ALPHA-BETA(position, depth, α, β):
if a column wins at once for the side to move:
return WIN − ply − 1 # a faster win scores higher
if no column is legal:
return 0 # a full board is a draw
if depth = 0:
return EVALUATE(position) # score for the side to move
best ← −infinity
for each legal column m, centre first:
score ← −ALPHA-BETA(RESULT(position, m), depth − 1, −β, −α)
best ← max(best, score)
α ← max(α, score)
if α ≥ β:
break # prune: the opponent avoids this line
return best
function SEARCH(position, max_depth, max_seconds):
deadline ← now + max_seconds
nodes ← 0
for each legal column m:
if m wins at once:
return m # a win in one move needs no search
best ← (first legal column in centre order, score 0, depth 0)
depth ← 0
repeat max_depth times:
depth ← depth + 1
try:
scores ← empty map
α ← −2 · WIN
order ← legal columns in centre order
if best.depth > 0:
move best.move to the front of order
for each column m in order:
scores[m] ← −ALPHA-BETA(RESULT(position, m), depth − 1, −2 · WIN, −α, 1)
α ← max(α, scores[m])
on time-limit reached:
stop # an unfinished depth is thrown away
move ← the column with the highest score, ties to the more central column
best ← (move, scores[move], depth, nodes, root scores)
if |scores[move]| ≥ WIN − 64:
stop # a forced result; deeper search cannot change it
return best
function ALPHA-BETA(position, depth, α, β, ply):
nodes ← nodes + 1
if nodes mod 1024 = 0 and now > deadline:
raise time-limit reached
if a node limit is set and nodes > node limit:
raise time-limit reached # the page does not set a node limit
if a column wins at once for the side to move:
return WIN − ply − 1
if no column is legal:
return 0
if depth = 0:
return EVALUATE(position)
α0 ← α
key ← KEY(position)
move_tt ← none
if key is in TABLE:
(d, flag, value, move_tt) ← TABLE[key]
if d ≥ depth:
if flag = EXACT:
return value
if flag = LOWER and value ≥ β:
return value
if flag = UPPER and value ≤ α:
return value
order ← legal columns in centre order
if move_tt is in order:
move move_tt to the front of order
best ← −2 · WIN
best_move ← order[0]
for each column m in order:
score ← −ALPHA-BETA(RESULT(position, m), depth − 1, −β, −α, ply + 1)
if score > best:
best, best_move ← score, m
α ← max(α, best)
if α ≥ β:
break # beta cutoff
if best ≤ α0:
flag ← UPPER
else if best ≥ β:
flag ← LOWER
else:
flag ← EXACT
TABLE[key] ← (depth, flag, best, best_move)
return best
The root. The outer procedure is iterative deepening. Each finished depth replaces the previous answer, and the root search in each depth uses the previous best move first. The timeout is checked once every 1,024 nodes, so the search stops close to the budget without a clock call at every node.
The root window. At the root, each child is searched with the window from −2·WIN to −α. Each later column is searched only far enough to show whether it can beat the best score found so far. Only the chosen column's score is exact; the scores of the other columns are bounds, which is why the page marks them as upper bounds.
The transposition table. The key is current + mask, a single integer for the position5. An entry searched to at least the current depth can be reused, which saves work. A win score stores its distance from the node where it was found, so a reused entry can misjudge which of two wins is faster, but never whether a position is won57.
Ordering. The table's best move is tried first, then the other columns in centre order. A good first move raises alpha early, and that makes the cutoffs on later moves more frequent.
Monte Carlo tree search (MCTS) estimates the value of a move by simulated games, not by a hand-written evaluation or a learned network. A rollout plays random legal moves from a position until one side makes four in a row or the board fills, then returns the result. The search uses UCT to choose which branch to follow: at each node, the child with the largest upper confidence bound is chosen. The bound used here is UCB1, which adds to the child's mean result an exploration bonus that is large when the child has few visits compared with its parent.
Here i ranges over the children of the node, w_i is the total result of child i for the player who moved into it, n_i is its visit count, N is the node's own visit count, and ln is the natural logarithm. The constant c = 1.4 is the default in the MCTS constructor59, and the agent does not change it.
Each simulation has four steps. Selection descends by the formula above until it reaches a node with an untried move. Expansion adds one child for a randomly chosen untried move. Rollout plays the rest of the game at random, and its result is taken for the player who moved into the new child. Backup adds the result to every node on the path, flipping its sign at each level. The move played is the child with the most visits. A move that wins at once is played without any search60.
function MCTS-SEARCH(position, simulations):
repeat simulations times:
node ← SELECT(root) # follow UCB1 down the tree
if node has untried moves:
node ← EXPAND(node) # add one random untried move
result ← ROLLOUT(node.position) # random play to the end
BACKUP(node, result) # flip the sign at each level
return the child of the root with the most visits
function MCTS-SEARCH(position, simulations, max_seconds, c = 1.4):
start ← now
root ← NODE(position)
for each legal column m:
if m wins at once:
return m # an immediate win needs no search
sims ← 0
repeat simulations times:
try:
if max_seconds is set and sims mod 64 = 0 and now − start > max_seconds:
raise time-limit reached
node ← root
while node has no untried moves and node has children: # selection
node ← the child of node with the largest w/n + c · sqrt(ln N_node / n)
if node has untried moves: # expansion
m ← a random untried move, removed from the list
child ← NODE(RESULT(node.position, m), parent node, move m)
add child to the children of node
node ← child
if node.position has four in a row: # simulation
result ← +1
else:
result ← −ROLLOUT(node.position)
while node is not empty: # backup
node.visits ← node.visits + 1
node.value ← node.value + result
result ← −result # the parent's player is the opponent
node ← node.parent
sims ← sims + 1
on time-limit reached:
stop
m* ← the child of root with the most visits
return m*, sims, visit counts, elapsed time
function ROLLOUT(position):
if position has four in a row for the player who moved last:
return −1
sign ← +1
loop:
moves ← legal columns of position
if moves is empty:
return 0 # full board: draw
m ← a random column from moves
if m wins at once for the player to move:
return sign # the player to move wins
position ← RESULT(position, m)
sign ← −sign
Why the rollout sign alternates. The rollout starts from the position after the expansion, where the player to move is the opponent of the player who moved into the new node. Its result is therefore negated before backup62. Within the rollout, each random move passes the turn, so the sign flips after every move63.
Why there is no learned knowledge. The rollouts are uniform random play, so the search does not know that centre columns are better. Its estimates come only from the random games it has played, and the page labels it as plain MCTS for that reason.
The chance agent is a baseline with no search, evaluation or lookahead. It draws a column from fixed weights, one per column, that favour the centre: w = (1, 2, 3, 4, 3, 2, 1) from the left64. A full column has weight zero, and the remaining weights are renormalised so that they sum to one.
Here c is a column, and 1[c open] is 1 when the column has room and 0 when it is full. On an empty board the weights sum to 16, so the odds are 6.25%, 12.5%, 18.75%, 25%, 18.75%, 12.5% and 6.25%. The page shows them rounded to whole percent: 6%, 12%, 19%, 25%, 19%, 12% and 6%65. The strength setting has no effect on this agent.
function CHANCE-MOVE(position):
for each column c:
weight[c] ← 0 if column c is full, else CHANCE-WEIGHTS[c]
return one column drawn with probability weight[c] / sum of weights
function CHANCE-MOVE(position, rng):
weights ← empty list
for each column c:
if column c is full:
weights[c] ← 0
else:
weights[c] ← CHANCE-WEIGHTS[c] # (1, 2, 3, 4, 3, 2, 1)
total ← sum of weights
odds ← weights[c] / total for each column c # sums to 1, full columns get 0
column ← one draw from 0 to 6 with probabilities odds, using rng
return column, odds rounded to four places
The draw uses an unseeded random generator in the page's API67, which passes no rng66, so the same position can give different columns on different requests. The agent returns its odds with its move, and the page draws them as the bars of the analysis panel.