← The Engines

How Four in a Row’s computer never loses

A companion to the game: the board as two numbers, a search that proves the result, the tricks that make it fast, and the levels below it

Download PDFPlay Four in a Row

The Hard computer in Four in a Row plays perfectly whenever it can prove a move wins. This companion explains each idea that lets it do that in a browser. The board fits in two 49-bit numbers, so dropping a coin is one addition and spotting four in a row is a few shifts. A search called negamax plays the game out to the end. Alpha-beta pruning, a filter for safe moves, a good move order and a table of positions already solved let it skip almost all of the tree. Null-window searches then find the exact score by bisection. The first moves come from an opening book proven offline. Finally, the weaker levels and the coach show how to play well without proving anything. This companion builds on the Tic-tac-toe companion’s game trees and minimax.

1 The board as two numbers

How can a computer look at millions of positions a second?

A computer is fastest when it treats a position as numbers. One instruction combines 32 or 64 bits at once. So the solver does not store a grid of cells. It gives every cell one bit of a number and works on whole numbers.

The cells are numbered column by column from the bottom left: column a holds bits 0 to 6, column b bits 7 to 13, and so on to bit 48. Each column has seven bits for its six cells. The seventh bit, the spare bit, sits on top and never holds a coin. It keeps columns apart, as the next two sections show.

A position needs two such numbers. One, 𝑝, has a 1 for each coin of the player to move, called the mover below. The other, 𝑚 (for mask), has a 1 for every coin on the board. The other player’s coins are the bits in 𝑚 but not in 𝑝.

In wordsIn symbols
the coins of the player to move𝑝
every coin on the board𝑚
the other player’s coins𝑝⊕𝑚
the bit of the cell in column 𝑐, row 𝑟, both counted from 027𝑐+𝑟
the bottom cell of column 𝑐𝑏𝑐=27𝑐
The running example has 10 coins, the first player’s red coins and the second player’s yellow coins, numbered in the order they were played. The first player is to move, so 𝑝 holds the red coins and 𝑚 all ten. Every later section starts from this position.

2 Dropping a coin

How does adding one number drop a coin into a column?

In a column, the coins fill the cells from the bottom up with no gaps. In bits, a column of height ℎ is ℎ ones followed by zeros. Adding the column’s bottom bit to that pattern is binary addition with a carry. Each 1+1 makes 0 and carries 1 up through the ones, until the carry reaches the first 0, which is the lowest empty cell.

Figure 1: Dropping a coin into column d of the example, which holds four coins. Each column is drawn with its bottom bit at the bottom. Adding the bottom bit carries up to the first empty cell, and an or keeps the coins below it.
Theorem 1 (the carry finds the lowest empty cell). If column 𝑐 holds ℎ<6 coins, then within column 𝑐, 𝑚+𝑏𝑐 has exactly one bit set. That bit is bit ℎ, the lowest empty cell. The other columns of 𝑚 are unchanged.
Proof. Within column 𝑐, 𝑚 reads 2ℎ−1, with bits 0,…,ℎ−1 set. Adding 𝑏𝑐 adds 1 there, and 2ℎ−1+1=2ℎ. Since ℎ≤5, the result stays below the spare bit, so no carry leaves the column and the other columns are untouched. ∎

So 𝑚∨(𝑚+𝑏𝑐) is 𝑚 with the new coin added. The turn passes at the same time. The player who just moved becomes the other player, and the other player becomes the mover. The new mover’s coins are 𝑝⊕𝑚, computed from the board before the drop.

Algorithm 1: Playing a move, as Position.play in src/games/four-in-a-row/rules.ts.
Require: a position (𝑝,𝑚); a column 𝑐 with room
Ensure: the position after the player to move drops a coin in 𝑐
1𝑝←𝑝⊕𝑚the other player’s coins: they move next
2𝑚←𝑚∨(𝑚+𝑏𝑐)the carry stops at the lowest empty cell

3 Spotting four in a row

How can a few shifts find four in a row anywhere on the board?

Shifting a number right by 𝑑 bits moves every coin 𝑑 cells back along the numbering. Because every column takes seven bits, each value of 𝑑 is one step in one direction on the board: 𝑑=1 is one row down, 𝑑=7 one column left, 𝑑=6 one column left and one row up, and 𝑑=8 one column left and one row down.

In wordsIn symbols
a line up a column, each coin moved one row down𝑑=1
a line along a row, each coin moved one column left𝑑=7
a diagonal rising to the left, each coin moved one column left and one row up𝑑=6
a diagonal falling to the left, each coin moved one column left and one row down𝑑=8
pairs, the cells whose neighbour 𝑑 along is also yours𝑥=𝑠∧(𝑠≫𝑑)
fours, the pairs whose pair 2𝑑 along is also yours𝑥∧(𝑥≫2𝑑)
Figure 2: Finding four along the bottom row. The shift 𝑠≫7 moves every coin one column left, and the and keeps the coins with a neighbour to their right, the pairs. The same steps two columns over leave one bit, at the four’s first cell.
Theorem 2 (shifts find exactly the fours). For 𝑑∈{1,6,7,8}, bit 𝑖 of 𝑥∧(𝑥≫2𝑑), with 𝑥=𝑠∧(𝑠≫𝑑), is set exactly when bits 𝑖, 𝑖+𝑑, 𝑖+2𝑑 and 𝑖+3𝑑 of 𝑠 are all set, and those four bits are four cells in a line on the board.
Proof. Bit 𝑖 of 𝑥 is set when bits 𝑖 and 𝑖+𝑑 of 𝑠 are. Bit 𝑖 of 𝑥≫2𝑑 is set when bits 𝑖+2𝑑 and 𝑖+3𝑑 are. Their and needs all four. Four bits 𝑑 apart are four cells in a line unless the line runs off the top or the bottom of the board, and every such step lands on a spare bit. One row up from row 6 is the column’s spare bit. One row down from row 1, a step of 𝑑=6 to the next column, is the previous column’s spare bit. Spare bits are never set in 𝑠, and neither are bits past 48, beyond column g. ∎

The four directions together take eight shifts and eight ands on two numbers, whatever the position. Checking cell by cell would look at 69 lines of four.

Figure 3: Drop coins and watch the operations: the addition that drops each coin, the turn passing, and the shifts that look for four.

4 Searching to the end

Can the computer know, not guess, that a move wins?

The Tic-tac-toe companion’s minimax plays every game to its end. Four in a Row has about 4.5 trillion positions, so no computer searches them all at every move. But the solver only has to prove the result of the current position, and the next sections show that most of the tree does not affect that result. This section defines the score the solver proves.

Definition 1 (score). A position’s score is from the side of the player to move, with best play by both: 22−𝑛 if that player wins with their 𝑛th coin of the game, 𝑛−22 if they lose to the opponent’s 𝑛th coin, and 0 for a draw. Each player has 21 coins, so a win scores from 1 to 18.

Like Tic-tac-toe’s 10−𝑑, the score ranks quick wins above slow ones and slow losses above quick ones. Because the score is always from the mover’s side, one function works for both players. The opponent’s best reply is the mover’s worst, so a position’s score is the largest of −score over its moves. This form of minimax is called negamax.

In wordsIn symbols
a position’s score𝑣(𝑃)=maxmove𝑐−𝑣(𝑃+𝑐)
a win with the mover’s 𝑛th coin22−𝑛
a loss to the opponent’s 𝑛th coin𝑛−22
a full board without a four0

In the example, the first player is to move with five coins down, so the earliest possible win comes with the sixth coin. The scores of the seven columns are −2, 1, 2, 1, 4, −2, −3, so the best move, column e, wins with coin 18.

5 Alpha-beta pruning

How can a search skip most moves and still be exact?

Suppose you have two moves, A and B, and the opponent replies to each. You have searched A. Its two replies leave you 3 and 5, and the opponent will pick the one worse for you, so A is worth 3. Next you search B, and its first reply leaves you 2.

Algorithm 2: Negamax with alpha-beta pruning, as Solver.negamax in src/games/four-in-a-row/rules.ts.
Require: a position where the player to move cannot win at once; a window (𝛼,𝛽)
Ensure: the exact score if it lies inside the window, else a bound on the side it lies
1if every move hands the opponent a win: return a losssafe moves, below
2narrow (𝛼,𝛽) to the scores still possible with the coins left
3narrow 𝛽 to the bound stored for this positionthe transposition table
4for each safe move, the most threatening firstmove ordering
5𝑠←−negamax(the position after it, (−𝛽,−𝛼))
6if 𝑠≥𝛽: return 𝑠cut-off: the opponent avoids this position
7𝛼←max(𝛼,𝑠)the best score so far
8store 𝛼 as this position’s bound; return 𝛼
1Search the first moveAlgorithm 2
⋮
4for each safe move, the most threatening first
5𝑠←−negamax(the position after it, (−𝛽,−𝛼))
6if 𝑠≥𝛽: return 𝑠
7𝛼←max(𝛼,𝑠)
8store 𝛼 as this position’s bound; return 𝛼
Move A’s replies leave you 3 and 5, and the opponent takes 3. You are now sure of at least 3. That value is 𝛼, the score the mover is already sure of.
2The second move’s first replyAlgorithm 2
⋮
4for each safe move, the most threatening first
5𝑠←−negamax(the position after it, (−𝛽,−𝛼))
6if 𝑠≥𝛽: return 𝑠
⋮
B’s first reply leaves you 2. Whatever B’s other replies are, the opponent can hold B to 2 or less, and you already have 3.
3Cut offAlgorithm 2
⋮
5𝑠←−negamax(the position after it, (−𝛽,−𝛼))
6if 𝑠≥𝛽: return 𝑠
7𝛼←max(𝛼,𝑠)
⋮
So the search skips B’s other replies. In negamax terms, B’s first reply, scored from the opponent’s side, already reaches 𝛽=−𝛼, the most you would allow. Stopping there is a cut-off. The answer, 3, is exact.

The search passes the two numbers down as a window (𝛼,𝛽). The lower end, 𝛼, is the score the mover is already sure of elsewhere. The upper end, 𝛽, is the score above which the opponent will not let the game reach this position. A move scoring 𝛽 or more ends the search of its position, because the opponent will avoid that position anyway.

Lemma 1 (what alpha-beta returns). Let 𝑣 be a position’s score. Negamax with window (𝛼,𝛽) returns 𝑣 when 𝛼<𝑣<𝛽; a value 𝑟 with 𝑣≤𝑟≤𝛼 when 𝑣≤𝛼; and a value 𝑟 with 𝛽≤𝑟≤𝑣 when 𝑣≥𝛽.
Proof. By induction on the depth of the tree below the position. A move is cut off only after one of its siblings reached 𝛽, so the position’s score is at least 𝛽 whatever the skipped moves are worth, and the value returned is a true lower bound. When no move reaches 𝛽, every move was searched with the window narrowed only by scores already achieved, so the largest value seen is exact if it beats 𝛼, and an upper bound otherwise. ∎

How much alpha-beta saves depends on the order of the moves. A cut-off comes as soon as the search tries a good enough move, so trying the best move first saves the most. With the best move always first, a search of depth 𝑑 with 𝑏 moves per position visits about 𝑏𝑑/2 positions instead of 𝑏𝑑. In the same time, the search goes twice as deep.

6 Fewer moves to try

Which moves can the solver rule out before searching them at all?

The solver never searches a move that loses at once. Before it searches anything, it also narrows the window by counting coins.

  • Win at once. If the player to move can complete four, the score is known. The solver calls the search only on positions where that is not possible.
  • Forced blocks. If the opponent has a cell where they would win next, the only move worth searching is the one that fills it. If they have two such cells, the position is lost, because one block cannot stop both.
  • Never under a threat. A coin directly below the opponent’s winning cell lets them play there next, so the solver drops those moves too.
The example has one such cell, ringed. Column c, row 4 would complete four for the first player. It cannot be played yet, because the cell under it is empty. The second player must not fill that empty cell, and the first player should not either, because the second player could then block.

The narrower window comes from counting coins. A player who cannot win with their next coin wins at best with the one after. A game cannot last past the 42nd coin. So before searching, the solver shrinks (𝛼,𝛽) to the scores still possible, in line 2 of Algorithm 2.

The solver finds the safe moves with the same shifts as the four check. The shifts find the cells that would complete four for a player, in every direction at once. A move is safe when it neither leaves such a cell of the opponent’s playable nor sits right under one.

7 Trying the best move first

In what order should the solver try the moves?

Alpha-beta cuts off as soon as it finds a good enough move, so the solver tries the likeliest good moves first. For each safe move, it counts the empty cells that would complete four for the mover once that coin is down. These cells are the move’s threats. Moves that make more threats go first, and ties go to the more central column. A central coin is on more lines of four than an edge coin.

Each cell shows the number of lines of four through it on the empty board, from 3 in a corner to 13 in the middle of the centre column. That is why the search, the opening book and the coach all prefer the middle. It is also why the solver breaks ties in the column order d, c, e, b, f, a, g.

8 Remembering positions

Why would the solver search the same position twice?
Different orders of the same moves reach the same position. Here the first player plays d and e and the second player plays c, in two orders. The search below the two boards would be identical, so the solver records what it learned about each position it finishes.

The solver keeps these records in a transposition table of about four million slots. Each slot holds a position’s key and an upper bound on its score. The bound is the value of 𝛼 when the position’s search ended, in line 8 of Algorithm 2. When the position comes up again, the bound narrows 𝛽 before the search tries any move. Often the narrowed window is enough to return at once.

The key must tell positions apart, and one addition builds such a key.

Theorem 3 (one number identifies a position). The key 𝑝+𝑚 determines the position. The height of every column and the owner of every coin can be read back from it.
Proof. Take one column with ℎ coins. In that column, 𝑚 is 2ℎ−1, and 𝑝 is some number 𝑞 with 0≤𝑞≤2ℎ−1, because the mover’s coins are a subset of the column’s coins. So the column of 𝑝+𝑚 is 2ℎ−1+𝑞, a number from 2ℎ−1 to 2ℎ+1−2. These ranges do not overlap for different ℎ, so the column’s value gives ℎ, and then 𝑞. The largest value, 27−2, still fits in seven bits, so no carry crosses into the next column. ∎

Each slot stores less than the 49-bit key. A position’s slot number is the key modulo the table’s size, a prime above 217, and the slot stores only the key’s low 32 bits. By the Chinese remainder theorem, the slot number and the low 32 bits together identify a 49-bit key exactly, so no two positions can be confused.

9 The exact score

Alpha-beta proves bounds. How does the solver find the exact score?

By Lemma 1, a search with the narrowest window, (𝑠,𝑠+1), called a null window, answers whether the score is above 𝑠. Null windows also cause the most cut-offs. So the solver finds the exact score by bisection. It keeps the range the score can be in and halves that range with one null-window search at a time.

Algorithm 3: The exact score by null-window bisection, as Solver.solve in src/games/four-in-a-row/rules.ts.
Require: a position where the player to move cannot win at once
Ensure: its exact score
1(lo,hi)← the lowest and highest scores possible with the coins left
2while lo<hi
3𝑠← a score between lo and hi, nearer 0draws and quick results are likeliest
4𝑟← negamax(position, (𝑠,𝑠+1))is the score above 𝑠?
5if 𝑟≤𝑠: hi←𝑟 else lo←𝑟
6return lo
Figure 4: The example’s exact score, found in 4 searches. Each search asks whether the score is above the red mark, and the green range is what remains possible.

The example’s score is 4, so the first player wins with coin 18. Solving every column’s score visited 3,503,195 positions and took 1215 milliseconds on the machine that built this page.

Figure 5: The solver’s verdict on every column, computed in your browser. Play a coin and the solver runs again.

10 The first moves

What about the empty board, where a proof takes minutes?

Early in a game, few coins are down and the game has the most moves left, so a proof can take longer than a player would wait. The first player wins with perfect play by opening in the centre, but a browser cannot prove that during a game. So when the Hard computer moves first, it takes its early moves from an opening book.

The opening book holds a proven winning reply for every position the Hard computer can face as first player with up to 8 coins down, 702 positions in all. The tool src/games/four-in-a-row/tools/book.ts builds it offline. Starting from the empty board, the solver finds a move that keeps the win. The tool then branches on every reply the opponent can make, and repeats until the positions hold 8 coins. It splits the work across worker threads, each with its own solver.

A position and its mirror image have mirrored answers. If a column wins in one, its mirror column wins in the other. So the opening book stores only one position of each pair, the one whose list of moves comes first in dictionary order. When a position is missing, the computer looks up its mirror.

11 Playing without a proof

What does the computer do when it cannot prove anything in time?

The Hard computer tries to prove its move within its thinking time, 2.5 seconds by default. The page runs the search in a background thread, so the board keeps responding to input. When a proof runs out of time, the computer abandons it and falls back to a heuristic search. That search is alpha-beta negamax only a few moves deep. It scores the positions where it stops with a fixed scoring rule instead of playing them out.

In wordsIn symbols
three of the mover’s coins in a window of four, the fourth cell empty+12
two of the mover’s coins in such a window+3
three of the opponent’s−14
two of the opponent’s−3
each of the mover’s coins in the centre column+3

The scoring rule looks at every window of four cells that holds coins of only one side, and counts threes and twos. The opponent’s threes weigh a little more, 14 against 12, so the computer prefers blocking a line to extending its own. A forced win or loss found within the search outranks any score from the scoring rule.

Hard
Plays from the opening book when it can. Otherwise it looks for a proof of a winning move within the thinking time, and keeps a move proven to draw if it finds no win. Failing both, it runs an 8-move heuristic search. When every move loses, it plays the one that loses latest.
Medium
Always wins at once when it can. Otherwise it runs a 6-move heuristic search over its safe moves and picks at random among the moves within 4 points of the best.
Easy
Takes an immediate win 90% of the time. Searches only 2 moves deep, considers every legal move instead of only the safe ones 40% of the time, and picks at random among moves within 25 points of the best.

12 Reading the board like a person

How can a person play well without a solver?

The game’s coach explains positions the way a strong player reads them, with no search at all.

Definition 2 (threat, good row, trapdoor). A threat is an empty cell that would complete four for one player. Late in a game the first player tends to get the odd rows, 1, 3 and 5, and the second player the even rows. A threat is on its owner’s good row when its row is one of its owner’s rows. A trapdoor is a threat on a good row that cannot be filled yet, because the cell under it is still empty.

A trapdoor is strong because of who has to play into the cell under it. As the other columns fill up, one player is forced to play there. When the threat is on its owner’s good row, that player tends to be the opponent. In the example, the first player’s threat at column c, row 4 is on an even row, a good row of the second player’s, so it is not a trapdoor.

The example as the coach reads it. Each row number has the colour of the player whose good row it is, red for the first player’s odd rows and yellow for the second player’s even rows. The dashed green ring marks the first player’s threat on row 4, a row in the second player’s colour. The solid yellow ring marks the rule of thumb’s pick.

The coach’s rule of thumb picks a move in this order: win if you can; block if you must; never fill the cell under the other side’s threat; otherwise take the cell on the most open lines of four. A line is open while only one side has coins in it. Each trapdoor your coin makes counts as six more lines, and each trapdoor the opponent still has after your move counts as six fewer. In the example the rule of thumb picks column e, on 9 open lines.