Module contents
Stage 1 of 9Advanced 110 min

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.

InteractiveOne position, seven decisions

Choose a column to play with blue pieces.

Each button shows column, exact outcome (+1 win, 0 draw, −1 loss), and search calls. Each column is calculated separately with an empty table; calls include table hits. Search ends when a forced win is found, the maximum possible. Endgames start from 30 legal moves.

Mode
StatusTurn blue
Best outcome this turndraws
Play on the board and compare columns. The analysis solves continuations of the displayed position to the end; node count is search work, not a probability. Observe how the answer changes after placing a piece and how gravity limits actions.

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 +1+1, draw 00, loss −1-1. 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 cc and row rr, both zero-based with row zero at the bottom, the index is 7c+r7c+r. 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: 11 vertical, 77 horizontal, and 66 and 88 for diagonals. For distance dd, first compute m=b&(b≫d)m=b\mathbin{\&}(b\gg d). Bit ii of mm indicates two pieces of bb separated by dd; then m&(m≫2d)m\mathbin{\&}(m\gg 2d) is nonzero exactly when two pairs appear 2d2d 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 V(s)V(s) for the player to move in nonterminal position ss. If a move wins immediately, its value is +1+1; if it fills the board without a win, it is 00; for any other successor sas_a, its value is −V(sa)-V(s_a). Therefore

V(s)=max⁡a∈A(s)Q(s,a),Q(s,a)={1si a gana,0si a empata,−V(sa)en otro caso.V(s)=\max_{a\in A(s)} Q(s,a),\qquad Q(s,a)=\begin{cases}1 & \text{si }a\text{ gana},\\ 0 & \text{si }a\text{ empata},\\ -V(s_a) & \text{en otro caso}.\end{cases}

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 +1+1 means there is a winning strategy against every response; 00 guarantees at least a draw, and −1-1 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-+1+1 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 −1-1, not +1+1. 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 −1,0,1-1,0,1 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 (α,β)(\alpha,\beta), α\alpha represents the best value the ancestor can already guarantee and β\beta the limit beyond which the opponent will not allow this node to be reached. When an action reaches at least β\beta, searching more siblings cannot change the ancestor’s choice: a cutoff occurs. On descent, signs and endpoints swap, so the child window is (−β,−α)(-\beta,-\alpha).

The guarantee is conditional: a narrow-window search may return a bound, not the exact value. If the result is at or below α\alpha, it is an upper bound; if it reaches or exceeds β\beta, it is a lower bound. Only a result strictly inside the window is exact. For example, finding an action of value at least 00 suffices to refute that the node is a loss, but does not distinguish draw from win. Saving that 00 as an exact value and reusing it with another window can erase a win.

A null window over integer values is (t,t+1)(t,t+1): it contains no integer. Search answers whether value is at most tt or at least t+1t+1. 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 β\beta. 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 α\alpha; an upper bound can lower β\beta. 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 hh, mask is 2h−12^h-1 and current is a subset of those hh bits, so local sum lies between 2h−12^h-1 and 2h+1−22^{h+1}-2. 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.

[ ]Engine and negamax with boundsLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Check against an independent arrayLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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 [−1,1][-1,1] are valid by the scale’s definition. This version uses a full window in the value interface. For a null window, call search with (t,t+1)(t,t+1) 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.

[ ]Compare with public endgamesLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Close the window with thresholdsLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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 −1-1 to 11 into one integer: (inferior + 1) * 3 + superior + 1. An immediate win allows storing exact 11 directly because no higher value exists on this scale.

[ ]Compiled search and validationLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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.

[ ]Generate labeled positionsLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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

NumericCount lines, not cells
How many distinct horizontal, vertical, or diagonal segments of four consecutive cells fit on the board of 7 columns and 6 rows? Count each segment once, without requiring its cells to be simultaneously reachable in a game.
QuizWhy does order matter?
Two exact alpha-beta searches start from the same position, use the same rules and an empty table, but visit actions in a different order. What follows?
QuizA table that lies
A search with window (0, 1) finds an action worth at least 1 and cuts off. Later the same position is queried with a wider window. What can safely be stored?
ProofWhy a cutoff preserves minimax
Prove: In a finite deterministic zero-sum tree with exact terminal utilities, alpha-beta returns the same root value as minimax when started with a window containing every possible value.
0
At each maximizing node, alpha is the best result already found there or an inherited bound; beta represents an alternative the opponent can already secure at an ancestor.

Step 1 of 3. One node action reaches beta. What is known about that node's maximum?

CodeFour shifts
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
An exact oracle combines verified rules, search to the outcome, and an explicit value contract. Alpha-beta and the transposition table save work only if they preserve the bounds justifying each cutoff.

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.