Connect Four engine and exact solver
Implement Connect 4 with bitboards and a negamax solver using alpha-beta pruning, center-first move ordering, null windows, and a transposition table. The solver, validated with public test positions of known value, will be the oracle measuring the agent throughout the project.
After this lesson you can
- Implement bitboard state, move generation, and four-in-a-row detection with shifts.
- Implement negamax with alpha-beta pruning, move ordering, and a transposition table.
- Validate the solver with public test sets of known value.
- Generate a set of positions labeled with exact value and optimal moves.
Before you start
An external truth for a learning agent
An agent can beat its previous version and still make elementary mistakes. If both share a blind spot, their head-to-head score will not reveal it. In this project we need a second measure: given a specific position, which moves preserve the best possible result against a perfect opponent? This lesson’s engine answers that question without a neural network, samples, or estimating a probability.
Connect 4 provides a useful testbed. The rules are small, but gravity means an apparently empty cell may not yet be playable and one threat can prepare another several turns later. The standard board has seven columns and six rows. Players alternate pieces; a piece falls to the lowest empty cell in its column. The first player to form four consecutive pieces horizontally, vertically, or diagonally wins. If the board fills without a line, it is a draw. The game ends at the first win: no pieces may be added afterward.
The initial position’s result is known. In his 1988 thesis, Louis Victor Allis proves that the first player can force a win on the standard board. His method combines proven rules with search. This does not mean any first move wins: the same work proves that opening outside the center column allows the second player at least a draw. That theoretical result does not replace testing our program: an error in an intermediate position can contaminate thousands of labels.
The figure uses an explicit finite tree of legal positions, not a table of hand-picked results. Value is expressed from the perspective of the player to move: win , draw , loss . Each column shows the value of choosing it and then letting both play optimally. All columns with maximum value are optimal. Later we will distinguish this label from a score that also prefers earlier wins.
State fits in two integers
An array of 42 cells is easy to read and serves as a reference implementation. To explore many positions, a bitboard engine stores each player’s occupancy as bits of an integer. We reserve seven consecutive bits per column: six for cells and one sentinel. With column and row , both zero-based with row zero at the bottom, the index is . Text columns are numbered 1 through 7; code uses indices 0 through 6.
The sentinel bit is not a cell. Its purpose is to prevent shifts from accidentally connecting the end of one column to the start of another. A compact representation is not correct merely because its numbers fit in 64 bits: operations must respect board, gravity, turn, and termination. For a reachable position without an earlier win, the two bitboards do not overlap and occupied bits in each column form a prefix from the bottom. Turn follows from piece-count parity.
A win can be checked with four distances between bits: vertical, horizontal, and and for diagonals. For distance , first compute . Bit of indicates two pieces of separated by ; then is nonzero exactly when two pairs appear apart, meaning four consecutive pieces. The sentinel and restriction to valid cells prevent false crossings between columns. Check the mask of the player who just moved, not the next player.
The two-bitboard representation is intentionally simple: the transposition table can use the complete pair and turn as a key. A hash function can collide; the table must compare the complete key before accepting a result. A Zobrist key is convenient for updating states, but if used alone as identity, a collision can turn another position’s bound into a false answer. Below we use lossless keys so the correctness argument does not depend on an absence of collisions.
Negamax: value changes sign when the turn passes
In a deterministic, perfect-information, zero-sum game with no chance, the next player’s utility is the opposite of the current player’s. This symmetry turns minimax into negamax. Define for the player to move in nonterminal position . If a move wins immediately, its value is ; if it fills the board without a win, it is ; for any other successor , its value is . Therefore
A leaf is not evaluated heuristically: recursion reaches an outcome. Depth is bounded by the number of empty cells, so induction on that number proves the definition. In the base case a move ends the game with its exact result; in the inductive step, the opponent chooses their best continuation and changing sign gives the current player’s result, who in turn chooses the maximum. Value means there is a winning strategy against every response; guarantees at least a draw, and means the opponent can force defeat.
There are two different quantifiers in that statement. To prove a forced win it suffices to exhibit an action for which all opponent responses leave a winning continuation. To prove a loss, all your own actions must be ruled out: for each there is a response preserving the opponent’s win. A search finding a plausible threat without examining the relevant defense offers only a hypothesis. By contrast, finding a value- action on our scale does allow the node to finish: no sibling can exceed that value. For a loss, justify that no action reaches a draw unless an established bound permits a cutoff.
Perspective must travel with the data. If blue moves and leaves an orange-winning position, blue’s action is worth , not . In the cell, current always refers to the active player: current ^ mask switches perspective and the sign before the call converts the child’s answer to the parent’s perspective. If victory is evaluated after swapping players, it is easy to check the wrong bitboard and miss the move just placed.
Define what “optimal” means. With these three labels, two wins are equally good even if one is faster. Pons datasets may use an integer score distinguishing distance to the outcome. Comparing those integers directly with would be incorrect; comparing their sign checks outcome but not whether speed preferences match. To evaluate an agent by outcome, all columns with the best sign are optimal; speed evaluation requires retaining full score and declaring that convention.
Prune without changing the answer
Alpha-beta pruning avoids exploring branches that can no longer change a decision. In a call with window , represents the best value the ancestor can already guarantee and the limit beyond which the opponent will not allow this node to be reached. When an action reaches at least , searching more siblings cannot change the ancestor’s choice: a cutoff occurs. On descent, signs and endpoints swap, so the child window is .
The guarantee is conditional: a narrow-window search may return a bound, not the exact value. If the result is at or below , it is an upper bound; if it reaches or exceeds , it is a lower bound. Only a result strictly inside the window is exact. For example, finding an action of value at least suffices to refute that the node is a loss, but does not distinguish draw from win. Saving that as an exact value and reusing it with another window can erase a win.
A null window over integer values is : it contains no integer. Search answers whether value is at most or at least . Repeating these questions over an integer interval containing the value, updating the corresponding bound, ends with one possible value. It is not an approximation if the bounds invariant is maintained and search reaches terminal states. A narrow window is not equivalent to cutting search off at fixed depth: the latter needs an evaluation function and stops being an exact oracle.
Action order does not change value, but does change when an action causing a cutoff is found. Exploring the center first is a natural heuristic: many potential lines pass through central columns. It does not guarantee the first action is best in every position. Node count depends on position, window, table, and order; it should not be interpreted as an intrinsic board property or measure of move quality.
To see why order matters, imagine a node choosing among several actions and the first reaches limit . The others are irrelevant to that ancestor and omitted. If the same action is visited last, earlier actions have already been explored. Both searches prove the same decision, but one discovers the sufficient inequality sooner. Order can also be counterproductive in a specific position: an immediate side threat should be checked before a general center preference if that knowledge is available. Measurement requires counting nodes under the same window and same initial table state.
Transpositions: also save the result type
Different move orders can reach the same state. A transposition table reuses work: the key identifies position and turn, and the entry retains value and type: exact, lower bound, or upper bound. A lower bound can raise ; an upper bound can lower . If the window closes, search can cut off. Otherwise it continues. When storing, classify the result against the call’s original window, before narrowing it using internal results.
The empty board equals its reflection, but generally two reflected positions have different keys unless normalized. Canonicalizing by reflection can save work, provided output columns are reflected too. The seven columns do not admit arbitrary rotation: gravity fixes the vertical direction. Horizontal symmetry also serves as a metamorphic test: reflecting a legal position must preserve value and reflect the optimal-move set.
In particular, a lower-bound entry must not be interpreted as the best move already calculated. Suppose a search has only proven the value is at least a draw. That information rejects a window asking whether it is a loss, but does not label the position a draw: an unexplored win might exist. Conversely, a draw upper bound does not rule out actual loss. If both bounds meet, the exact value is known. The later implementation retains this interval so different windows can contribute information without turning an inequality into equality.
Lab: build and validate the oracle
The following implementation separates the rules engine from search. First test rules against an independent representation, then search against a published set. Tests generated by the solver itself detect internal inconsistencies but are not an independent reference for outcome. A reference solver oracle earns that name only when its domain, value convention, and validation are clear.
In this lab current contains the player-to-move’s pieces and mask those occupied by either player. After adding piece b, the opponent’s old pieces are current ^ mask and become the next player’s. Addition mask + BOTTOM propagates a carry to the first empty cell of each column; BOARD removes sentinels and outside cells. In a full column the carry reaches the sentinel and creates no legal move.
Key current + mask is injective for gravity-respecting states. In a column of height , mask is and current is a subset of those bits, so local sum lies between and . These intervals do not overlap across heights. Given height, current is recovered by subtracting the mask. The local sum does not overflow into the next column thanks to the sentinel. Turn is implicit in which pieces belong to the current player; to interpret absolute identities outside search, retain parity or sequence too.
W, H, S = 7, 6, 7
ORDER = (3, 2, 4, 1, 5, 0, 6)
BOTTOM = sum(1 << (c * S) for c in range(W))
BOARD = BOTTOM * ((1 << H) - 1)
def win(p):
for d in (1, 6, 7, 8):
pairs = p & (p >> d)
if pairs & (pairs >> (2 * d)):
return True
return False
def move_bit(mask, c):
legal = (mask + BOTTOM) & BOARD
return legal & (((1 << H) - 1) << (c * S))
def position(sequence):
# sequence contiene columnas desde cero y termina antes de ganar.
current = mask = 0
for c in sequence:
if not 0 <= c < W:
raise ValueError('Columna fuera del tablero')
b = move_bit(mask, c)
if not b or win(current | b):
raise ValueError('Columna llena o partida ya terminada')
current, mask = current ^ mask, mask | b
return current, mask
class Solver:
def __init__(self):
self.table = {}
self.nodes = 0
def search(self, current, mask, alpha, beta):
self.nodes += 1
if mask == BOARD:
return 0
key = current + mask
entry = self.table.get(key)
if entry is not None:
lower, upper = entry
if lower == upper:
return lower
alpha, beta = max(alpha, lower), min(beta, upper)
if alpha >= beta:
return lower if lower >= beta else upper
a0, b0 = alpha, beta
best = -2
for c in ORDER:
b = move_bit(mask, c)
if not b:
continue
if win(current | b):
value = 1
else:
value = -self.search(current ^ mask, mask | b, -beta, -alpha)
best = max(best, value)
alpha = max(alpha, best)
if alpha >= beta:
break
lower, upper = self.table.get(key, (-1, 1))
if best <= a0:
upper = min(upper, best)
elif best >= b0:
lower = max(lower, best)
else:
lower = upper = best
self.table[key] = (lower, upper)
return best
def value(self, current, mask):
return self.search(current, mask, -2, 2)
def analyze(self, current, mask):
values = []
for c in range(W):
b = move_bit(mask, c)
if not b:
values.append(None)
elif win(current | b):
values.append(1)
else:
values.append(-self.value(current ^ mask, mask | b))
return values
lines = []
for c in range(W):
for r in range(H):
for dc, dr in ((1, 0), (0, 1), (1, 1), (1, -1)):
if 0 <= c + 3*dc < W and 0 <= r + 3*dr < H:
lines.append(sum(1 << (S*(c+i*dc) + r+i*dr) for i in range(4)))
assert len(lines) == 69
assert all(win(line) for line in lines)
assert all(not win(line ^ (line & -line)) for line in lines)
print('Líneas verificadas:', len(lines))npm run lab and open the connection link.The following detector uses no bit shifts: it walks cells and looks for segments within the board. It compares both detectors after every move in random games and stops immediately when someone wins. It also compares the cell obtained by mask addition with separately maintained height. This is a fixed-seed property test, not an exhaustive proof of every reachable state.
import random
def matrix_win(grid, player):
for c in range(7):
for r in range(6):
for dc, dr in ((1, 0), (0, 1), (1, 1), (1, -1)):
if 0 <= c + 3*dc < 7 and 0 <= r + 3*dr < 6:
if all(grid[c+i*dc][r+i*dr] == player for i in range(4)):
return True
return False
randomizer = random.Random(12)
checked = 0
for _ in range(1000):
grid = [[0]*6 for _ in range(7)]
heights = [0]*7
masks = [0, 0]
mask = 0
for turn in range(42):
legal = [c for c in range(7) if heights[c] < 6]
c = randomizer.choice(legal)
b = move_bit(mask, c)
assert b == 1 << (7*c + heights[c])
player = turn % 2
masks[player] |= b
mask |= b
grid[c][heights[c]] = player + 1
heights[c] += 1
for j in range(2):
assert win(masks[j]) == matrix_win(grid, j+1)
checked += 1
if matrix_win(grid, player+1):
break
print('Transiciones contrastadas:', checked)npm run lab and open the connection link.The table stores an interval of integer bounds. The first element is a lower bound and the second an upper bound; when they meet, value is exact. Initial bounds are valid by the scale’s definition. This version uses a full window in the value interface. For a null window, call search with and retain the returned bound; repeating with thresholds that close the interval recovers exact value. The Python table favors clarity and checks the algorithm, but no claim is made that it solves the initial position in practical time.
The external check downloads a revision-pinned mirror of Pons’s test_easy_end dataset. The mirror repository explains its reorganization of the datasets; per-column analyses come from the mirror. Only sign is compared, and None identifies a full column. This cell needs a connection. If download fails, do not turn that failure into successful validation.
import json
from urllib.request import urlopen
url = ('https://raw.githubusercontent.com/Pietot/Gonnect-4/'
'c82e1f1548c4a64d7ee04911a77cac2438a1f0a2/data/test_easy_end.json')
with urlopen(url, timeout=30) as response:
rows = json.load(response)
solver = Solver()
columns = 0
for row in rows:
current, mask = position([int(c)-1 for c in row['sequence']])
expected = (row['score'] > 0) - (row['score'] < 0)
assert solver.value(current, mask) == expected
for got, score in zip(solver.analyze(current, mask), row['analysis']):
reference = None if score is None else (score > 0) - (score < 0)
assert got == reference
columns += 1
print('Posiciones correctas:', len(rows), 'de', len(rows))
print('Columnas contrastadas:', columns)npm run lab and open the connection link.This threshold search is the executable form of the null window. The initial interval contains all possible results; each call eliminates at least one integer from the interval. It is compared against the same external values, without confusing an individual call with an exact answer.
def value_null(solver, current, mask):
low, high = -1, 1
while low < high:
threshold = (low + high) // 2
bound = solver.search(current, mask, threshold, threshold + 1)
if bound <= threshold:
high = bound
else:
low = bound
return low
null_solver = Solver()
for row in rows:
current, mask = position([int(c)-1 for c in row['sequence']])
expected = (row['score'] > 0) - (row['score'] < 0)
assert value_null(null_solver, current, mask) == expected
print('Ventanas nulas correctas:', len(rows), 'de', len(rows))npm run lab and open the connection link.In this lesson’s run, all 1 000 values and 7 000 columns match, including illegal ones. This is concrete evidence for that file and the three-result scale. It does not show our Python implementation is fast on openings or reproduces Pons’s strong score. The external reference and our program are not completely independent as ideas: both apply the same rules. Representation tests and a second detector remain useful for finding errors a single dataset does not cover.
Compile the search with Numba
Search cost is concentrated in visiting nodes, generating bits, and looking up the table. Compiling only one small operation and calling it from Python at every node could shift cost to the boundary between environments. This variant compiles full recursion and uses a typed integer dictionary. State occupies fewer than 64 bits, so keys fit in int64 here. The table packs two bounds from to into one integer: (inferior + 1) * 3 + superior + 1. An immediate win allows storing exact directly because no higher value exists on this scale.
import numpy as np
from numba import njit, types
from numba.typed import Dict
@njit
def n_win(p):
for d in (1, 6, 7, 8):
pairs = p & (p >> d)
if pairs & (pairs >> (2*d)):
return True
return False
@njit
def n_bit(mask, c):
return ((mask + BOTTOM) & BOARD) & (63 << (c*7))
@njit
def n_search(p, mask, alpha, beta, table, counter):
counter[0] += 1
if mask == BOARD:
return 0
key = p + mask
if key in table:
entry = table[key]
lower, upper = entry // 3 - 1, entry % 3 - 1
if lower == upper:
return lower
alpha, beta = max(alpha, lower), min(beta, upper)
if alpha >= beta:
return lower if lower >= beta else upper
a0, b0 = alpha, beta
best = -2
for c in (3, 2, 4, 1, 5, 0, 6):
b = n_bit(mask, c)
if not b:
continue
if n_win(p | b):
table[key] = 8
return 1
value = -n_search(p ^ mask, mask | b, -beta, -alpha, table, counter)
best = max(best, value)
alpha = max(alpha, best)
if alpha >= beta:
break
lower, upper = -1, 1
if key in table:
entry = table[key]
lower, upper = entry // 3 - 1, entry % 3 - 1
if best <= a0:
upper = min(upper, best)
elif best >= b0:
lower = max(lower, best)
else:
lower = upper = best
table[key] = (lower + 1)*3 + upper + 1
return best
@njit
def n_analyze(p, mask, table, counter):
result = np.full(7, -2, dtype=np.int64)
for c in range(7):
b = n_bit(mask, c)
if b:
if n_win(p | b):
result[c] = 1
else:
result[c] = -n_search(p ^ mask, mask | b, -2, 2, table, counter)
return result
@njit
def n_value(p, mask, table, counter):
if n_search(p, mask, -1, 0, table, counter) < 0:
return -1
if n_search(p, mask, 0, 1, table, counter) >= 1:
return 1
return 0
table = Dict.empty(key_type=types.int64, value_type=types.int64)
counter = np.zeros(1, dtype=np.int64)
for row in rows:
p, mask = position([int(c)-1 for c in row['sequence']])
assert n_value(p, mask, table, counter) == (row['score'] > 0) - (row['score'] < 0)
values = n_analyze(p, mask, table, counter)
for got, score in zip(values, row['analysis']):
expected = -2 if score is None else (score > 0) - (score < 0)
assert got == expected
print('Numba: valores y columnas contrastados:', len(rows), len(rows)*7)npm run lab and open the connection link.Here -2 is an illegal-column sentinel, never a game value. The first call includes compilation; to measure performance, separate that phase, fix the same positions and table policies, and compare node and time ratios across several repetitions. The preceding correctness result does not depend on Numba being faster on a particular machine. A production engine also needs to bound table memory and document what happens when entries are replaced.
The Pons protocol represents a position by a sequence of columns numbered from 1 and publishes six sets of 1 000 positions. Its strong score includes speed of victory or delay of defeat; its sign matches this lesson’s weak label. A sequence is not valid merely because it contains digits 1 through 7: it may fill a column or continue after a win. The reader must retain input file, version, and comparison criterion alongside the result, and report how many positions were actually tested. A 100% score on easy endings does not prove all difficult openings were validated.
Creating a training or evaluation set needs more than position value. In each nonterminal state, analyze every legal move from the current player’s perspective, take the maximum, and save every column attaining it. Also save the sequence, state or verifiable key, value convention, and solver version. Deduplicate by position and turn, not just sequence: different orders can transpose. Split training and test by position before training, and consider grouping reflections in the same split to avoid a test position being the reflection of one already seen. A collection of random endings does not automatically represent opening positions or those an agent will visit; record how it was sampled and use it only within that scope.
The next cell generates 20 000 distinct positions with 36 moves without allowing an intermediate winning move. They are not a uniform sample of legal positions or natural games: conditioning each step to avoid a win strongly changes the distribution. It saves zero-based column sequence, value, and all optimal moves under the weak scale. The preceding external set validates the solver and is not mixed into this generation.
import random
from pathlib import Path
rng = random.Random(1201)
seen = set()
solver = Solver()
root = next(p for p in (Path.cwd(), *Path.cwd().parents)
if (p / 'package.json').exists())
output = root / 'labs' / 'runs' / 'p12-l01' / 'positions_20000.jsonl'
output.parent.mkdir(parents=True, exist_ok=True)
attempts = 0
with output.open('w', encoding='utf-8') as f:
while len(seen) < 20000:
current = mask = 0
sequence = []
for _ in range(36):
legal = [(c, move_bit(mask, c)) for c in range(W)]
legal = [(c, b) for c, b in legal if b and not win(current | b)]
if not legal:
break
c, b = rng.choice(legal)
sequence.append(c)
current, mask = current ^ mask, mask | b
attempts += 1
if len(sequence) != 36 or current + mask in seen:
continue
seen.add(current + mask)
values = solver.analyze(current, mask)
best = max(v for v in values if v is not None)
row = {'sequence': sequence, 'value': best, 'values': values,
'optimal': [c for c, v in enumerate(values) if v == best]}
f.write(json.dumps(row, separators=(',', ':')) + '\n')
if len(seen) % 1000 == 0:
solver.table.clear()
print('Posiciones distintas:', len(seen), '; intentos:', attempts)
print('Archivo:', output.name)npm run lab and open the connection link.With the preceding seed and procedure, the run produced 20 000 positions in 24 643 attempts. This file is a reproducible starting point, not a representative test sample for the future agent. To evaluate the pipeline, separate position groups before learning and also save positions from a different sampling procedure. Do not infer playing strength from the proportion of labeled wins in this conditioned sample.
A regression test should include at least one full column, both diagonal directions, a win by the last player, and a draw on a full board. It should also check that simulation rejects a move after a win. To test line detection, isolate every board line and remove one piece: this checks both true positives and the neighboring non-winning case. This does not replace comparison against a detector that walks cells: a mask-construction error could affect both sides of a test based on the same masks.
Exercises
Step 1 of 3. One node action reaches beta. What is known about that node's maximum?
is_win(p) for a nonnegative integer whose valid bits correspond to a board of seven columns of six cells with a sentinel bit between columns. The bit for cell (column c, row r) is 7*c+r, with zero-based indices. Return whether the player has any line of four.def is_win(p):
passSummary
The bitboard engine makes gravity, alternation, and game termination explicit. Negamax swaps perspectives with a sign; center-first ordering accelerates some searches without changing the answer. A table stores bounds with their type and key, and the public dataset checks results against an external source. Evaluation in the next lessons will distinguish outcome accuracy from a preference for fast wins, and retain all tied moves under the chosen convention.