← MAIN
02 // ADVERSARIAL SEARCH

CONNECT FOUR

Play a self-taught network, a search or a fixed-odds baseline, or watch two of them play.
YOU — MOVE 1 STATUS YOUR TURN

HOW TO PLAY

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.

HOW THE AI DECIDED
Make a move to see the agent's reasoning.
Game log
MATCH
MODE
OPPONENT
STRENGTH (SEARCH BUDGET)
More settings
WHO MOVES FIRST

HOW IT WORKS

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.

The board

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.

AlphaZero: PUCT search guided by a network

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.

a^{\star}=\arg\max_{a\in\mathrm{Legal}(s)}\bigl(Q(s,a)+U(s,a)\bigr)
6
Q(s,a)=\begin{cases}W(s,a)\,/\,N(s,a) & N(s,a)>0\\ 0 & \text{otherwise}\end{cases}
7
U(s,a)=c_{\mathrm{puct}}\;P(s,a)\;\frac{\sqrt{N(s)+1}}{1+N(s,a)},\qquad N(s)=\sum_{b}N(s,b)
8

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.

v\leftarrow -v,\qquad N(s,a)\leftarrow N(s,a)+1,\qquad W(s,a)\leftarrow W(s,a)+v
12

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:

p_{\mathrm{win}}=\frac{1}{2}\Bigl(1+\frac{\sum_{a}W(s_0,a)}{\sum_{a}N(s_0,a)}\Bigr)
14 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.

16
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

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.

P'(s_0,a)=(1-\varepsilon)\,P(s_0,a)+\varepsilon\,\eta_a,\qquad \eta\sim\mathrm{Dir}(\alpha,\dots,\alpha)\ \text{over the legal columns}
20 21

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.

The network

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.

h_0=\mathrm{ReLU}\bigl(\mathrm{Conv}_{\mathrm{stem}}(x)\bigr),\qquad h_i=\mathrm{ReLU}\Bigl(h_{i-1}+\mathrm{Conv}_{i,2}\bigl(\mathrm{ReLU}(\mathrm{Conv}_{i,1}(h_{i-1}))\bigr)\Bigr)\quad i=1,\dots,4
25 26
\mathrm{logits}=W_{\mathrm{pol}}\,\mathrm{ReLU}\bigl(\mathrm{Conv}^{\mathrm{pol}}_{1\times1}(h_4)\bigr)+b_{\mathrm{pol}},\qquad v=\tanh\Bigl(W_2\,\mathrm{ReLU}\bigl(W_1\,\mathrm{ReLU}(\mathrm{Conv}^{\mathrm{val}}_{1\times1}(h_4))+b_1\bigr)+b_2\Bigr)
27
P(s,a)=\frac{\exp(z_a)}{\sum_{b\in\mathrm{Legal}(s)}\exp(z_b)}\ \text{for } a\in\mathrm{Legal}(s),\qquad P(s,a)=0 \text{ otherwise}
28

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.

Training by self-play

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.

\pi(a)=\frac{N(s,a)}{\sum_{b}N(s,b)}
34

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 π.

\mathcal{L}=\frac{1}{B}\sum_{i=1}^{B}\bigl(v_i-z_i\bigr)^2\;-\;\frac{1}{B}\sum_{i=1}^{B}\sum_{a}\pi_{i,a}\,\log p_{i,a}
39

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.

42
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

Results of the served network

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.

MatchWinsDrawsLossesScore
Iteration 96 vs minimax depth 26782571%
Iteration 96 vs minimax depth 47941781%
Iteration 96 vs minimax depth 67781581%
Iteration 19 vs minimax depth 26153463.5%
Iteration 19 vs minimax depth 453103758%
Iteration 19 vs minimax depth 629205139%
Plain MCTS, 1,000 rollouts, vs minimax depth 4 (50 games)3221666%
AlphaZero, level 1 (50 simulations), vs chance (20 games)2000100%

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 with alpha-beta pruning

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.

V(s)=\max_{a\in\mathrm{Legal}(s)}\bigl(-V(s\cdot a)\bigr)
47

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.

E(s)=\sum_{w\in\mathcal{W}}\Bigl(P_{a_w}\,\mathbf{1}[b_w=0]-P_{b_w}\,\mathbf{1}[a_w=0]\Bigr)+3\,\bigl(c_{\mathrm{me}}-c_{\mathrm{opp}}\bigr),\qquad P=(0,\,1,\,8,\,64,\,0)
51

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.

V_{\mathrm{win}}=\mathrm{WIN}-p-1,\qquad \mathrm{WIN}=10^{6}
53

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/.

56
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

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

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.

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

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.

61
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

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.

Chance

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.

p(c)=\frac{w_c\,\mathbf{1}[c\text{ open}]}{\sum_{c'}w_{c'}\,\mathbf{1}[c'\text{ open}]},\qquad w=(1,2,3,4,3,2,1)
64

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.

66
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

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.