Back to Old-School Programming: Dissecting a Connect4 Policy
This article dissects an LLM-generated policy for Connect4, a classic board game. The policy itself is not the point; the goal is to sharpen our ability to read highly optimized, hard-to-read code in the era of AI-assisted programming.
Back to Old-School Programming: Dissecting a Connect4 Policy
Why Learn Programming When AI Can Code for Us?
Production code still requires human review, at least for now. Yet LLMs may favor computational efficiency over human readability. This article offers an exercise in reading such code, with a particular focus on bitwise operations.
Background: Connect4
Connect4 is a two-player, deterministic, zero-sum game on a 6-row × 7-column board. Players take turns dropping a disc into a non-full column. The disc falls to the lowest empty cell. Four discs of the same color in a horizontal, vertical, or diagonal line win the game; a full board without a winner is a draw.
. . . . . . . |
Our task is to implement policy(board) -> int, which maps a board state to a column index (0–6).
The Agent at a Glance
We study GPT-6 Astra High #005, a top-performing Connect4 automaton from Strautomata. Stripped of its optimizations, the agent consists of an exact world model, a handcrafted value function, and a search-based planner.
def policy(board: list[list[int]]) -> int: |
The intuition is simple: simulate each legal action with the world model, estimate the resulting state's value by looking several moves ahead, and choose the best action. The negative sign converts the opponent's value into ours, since every action switches the current player.
board → encode → state |
The interesting part is how Astra represents states and implements these operations. Many of its techniques have human-written precedents; see Pascal Pons's bitboard tutorial.
The Python implementation blocks below, together with policy() above, form a runnable teaching version (Python 3.10+). We keep Astra's bitboard and evaluation features but simplify its planner. This is not the original tournament agent or a perfect Connect4 solver.
1. State Representation: Bitboards
There's a visualization website for this post.
From arrays to bitboards. A natural way to represent a Connect4 board is a 6 × 7 array, where each cell stores 0 (empty), 1 (our disc), or -1 (the opponent's disc). However, we can also represent the board using two integers. This representation is called a bitboard.
Bitwise basics. An integer is represented internally in binary. For example:
Bit index: 4 3 2 1 0 |
In Python, this integer is written as 0b10110, whose decimal value is \(2^4+2^2+2^1=22\).
Instead of interpreting it as a number, we can interpret it as a set of indices: bit i is 1 if element i belongs to the set. Thus, 0b10110 represents the set {1, 2, 4}.
Bitwise operations allow us to manipulate such sets directly:
| Operation | Example | Meaning |
|---|---|---|
1 << i |
1 << 3 = 0b1000 |
Create a set containing only index i. |
x << k |
0b0011 << 2 = 0b1100 |
Shift all bits left by k positions. |
x >> k |
0b1100 >> 2 = 0b0011 |
Shift all bits right by k positions. |
x & y |
0b1100 & 0b1010 = 0b1000 |
AND: intersection. |
x \| y |
0b1100 \| 0b1010 = 0b1110 |
OR: union. |
x ^ y |
0b1100 ^ 0b1010 = 0b0110 |
XOR: elements belonging to exactly one set. |
~x |
~0b0011 = -4 |
NOT: flip every bit. |
x.bit_count() |
(0b10110).bit_count() = 3 |
Count the set bits. |
x |= bit adds an element to a set, x ^= bit toggles its membership, and if x & y: checks whether two sets overlap.
Python integers have arbitrary precision: ~x == -x - 1. Therefore, to flip only the bits within a finite region, we use mask & ~x, where mask specifies the region.
Board encoding. The idea of a bitboard is to assign each cell a unique bit index. We can then represent any subset of cells using a single integer.
Astra allocates seven bit positions per column: six for the playable cells and one extra position called the sentinel, whose bit value is always zero in a valid board. We will see why this extra bit is useful shortly.
The bit indices are assigned from bottom to top and from left to right:
Column (c) |
Note that the numbers above are bit indices, not cell values. The cell at column c and row r corresponds to bit index 7*c + r. Its corresponding single-bit mask is:
bit = 1 << (7*c + r) |
For example, suppose we have three discs at bit indices 0, 1, and 7:
0 1 2 3 4 5 6 |
Their positions can be encoded as a single integer:
p = (1 << 0) | (1 << 1) | (1 << 7) |
The integer 131 now represents all three disc positions. To check whether a particular cell contains one of these discs, we simply test its corresponding bit:
bool(p & (1 << 7)) # True |
Astra uses two such integers to represent the complete game state:
p: the positions occupied by the current player.mask: the positions occupied by either player.
For example:
Board p mask |
Since p is a subset of mask, the opponent's bitboard is simply:
q = mask ^ p |
Similarly, all empty cells can be obtained by:
empty = _FULL ^ mask |
where _FULL is a bitmask containing all 42 playable cells.
The entire game state is thus represented by just two 49-bit-wide integers. More importantly, operations on multiple cells can now be performed simultaneously using integer arithmetic and bitwise operations, rather than iterating over a two-dimensional array.
_ORDER = (3, 2, 4, 1, 5, 0, 6) |
The input uses 1 for the current player, -1 for the opponent, and 0 for empty cells. Array rows start at the top, whereas bitboard rows start at the bottom (board[5-r][c]). Since 63 = 0b0111111, _COLS[c] selects all six playable cells in column c. _FULL selects the entire playable board, and _BOTTOM selects its bottom row. Disjoint masks can be combined using addition as well as OR.
Operation 1: Find all landing cells. This is perhaps the most elegant line in Astra's code:
def possible_moves(mask): |
In a column containing three discs, the occupied bits are 0000111. Adding 1 propagates the carry through the consecutive 1s until it reaches the first empty cell:
0000111 occupied cells |
For a full column, 0111111 + 1 = 1000000: the carry lands on the sentinel, which & _FULL removes. The sentinel prevents the carry from entering the next column. Adding _BOTTOM thus computes the landing cells of all seven columns at once.
Operation 2: Detect four in a row. In the 49-bit layout, adjacent cells are separated by a constant bit stride: vertical 1, horizontal 7, and diagonal 6 or 8.
+1 +8 |
Consider four discs at indices 0, 7, 14, 21. Shifting right aligns them at index 0:
Set-bit indices |
def has_four(p): |
The intersection detects all four-cell alignments in a direction simultaneously. The zero sentinel bits prevent alignments from wrapping around column boundaries. Our simplified agent uses this explicit terminal test; Astra mainly checks winning cells instead.
Operation 3: Find winning cells. Rather than testing whether four discs already exist, Astra's _winning(p, mask) identifies empty cells that would complete a four. They need not be playable yet. In a nonvertical direction there are four patterns:
. X X X X . X X X X . X X X X . |
For example, (p << s) & (p << (2*s)) & (p << (3*s)) marks the missing cell in X X X . (in increasing bit-index order). The other patterns are handled by combining left and right shifts:
def _winning(p, mask): |
Vertical patterns only need the cell above three discs because gravity rules out empty cells below occupied cells. The final AND removes occupied cells and sentinels. This loop is equivalent to Astra's unrolled implementation on valid, gravity-respecting boards.
To obtain immediate winning moves, simply intersect _winning(p, mask) with possible_moves(mask).
2. World Model
With the bitboard operations in place, the world model is straightforward:
def legal_actions(state): |
move is a one-hot mask for the landing cell. mask | move adds the disc to the occupancy mask. Why is the next p equal to mask ^ p rather than p | move? Because it is now the opponent's turn.
Before: (current player's discs, all occupied cells) |
The reward is also relative to the current player. If the previous player just made four, the new player has lost. Python integers are immutable, so search branches need no mutable board copies. We assume valid inputs and legal column indices.
3. Value Function
Astra uses a weighted sum of handcrafted features rather than a learned value function:
\[ \hat V(s)=\sum_{i=1}^{7}w_i\phi_i(s). \]
| Feature (current player minus opponent, except as noted) | Weight |
|---|---|
| Potential winning cells | 48 |
| Winning cells at preferred heights (first player: odd; second: even) | 12 |
| Vertically adjacent winning cells | 40 |
| Discs in the center column | 3 |
| Unblocked four-cell windows | 2 |
| Unblocked windows with at least two friendly discs | 10 |
| Tactical mobility (asymmetric safety heuristic) | 4 |
These are empirical heuristics, not guarantees of optimal play. The only additional bitwise idea worth explaining here is tactical safety. If the opponent can win at two distinct landing cells, a single disc cannot block both. A move directly below any opponent winning cell is also unsafe, because it makes that cell playable.
def safe_moves(possible, opponent_wins): |
This assumes we have no immediate winning move of our own. opponent_wins >> 1 marks cells below the threats; & ~ excludes them. Python's or returns the first truthy operand, so forced or possible selects the forced block if one exists, and all legal moves otherwise.
For the remaining features, the following implementation uses explicit loops over the board's 69 four-cell windows instead of Astra's more opaque parallel window statistics. The seven weights are unchanged.
_ODD_ROWS = sum(1 << (7*c+r) for c in range(7) for r in (0, 2, 4)) |
Here, mask.bit_count() & 1 tests whether the move count is odd, and pw & (pw >> 1) detects vertically adjacent threats. Heights are one-based (height 1 is row 0). The final feature intentionally retains Astra's asymmetric definition of mobility. The simplified search may call this heuristic on positions Astra would resolve tactically before evaluation.
4. Planning: Negamax
If the exact optimal value function \(V^*\) were available, one-step planning would suffice:
\[ \pi^*(s)\in\arg\max_{a\in\mathcal A(s)}[-V^*(F(s,a))]. \]
Since we only have an approximate value function, we search multiple moves ahead. Negamax exploits the zero-sum property: the opponent's gain is our loss.
def search(state, depth): |
The policy() from the beginning chooses the best action using this search, looking four plies ahead (one root move plus three recursive plies). Terminal states use their actual outcome, not the heuristic. Astra uses the same basic idea, but performs tactical pruning, alpha-beta pruning, and progressively deeper searches within a 0.90-second internal time budget. We omit these optimizations here.
5. A Few More Bitwise Idioms
Iterating over set bits. Astra loops over the available landing cells without scanning all 49 positions:
# Standalone example |
x & -x isolates the least significant 1 (lowbit). Because -x = ~x + 1, in an illustrative eight-bit two's-complement representation:
x 00010110 (22) |
Negation preserves the rightmost 1 and the lower zeros while complementing the higher bits. AND keeps only that 1. This identity also holds for Python's arbitrary-precision integers. XOR then removes the selected bit, so the loop extracts 2, 4, and 16 in order.
Testing for a single set bit. x & (x - 1) clears the rightmost 1:
x 00010100 |
Thus x != 0 and (x & (x - 1)) == 0 is equivalent to x.bit_count() == 1 for nonnegative integers. Astra uses the shorter not (allowed & (allowed - 1)) because it has already checked that allowed is nonzero. Similarly, column & (column + 1) == 0 tests whether a column consists of contiguous low bits (000000, 000001, 000011, ...), detecting invalid floating discs.
Compressing the state key. Astra uses key = p + mask instead of the tuple (p, mask). In a column of height \(h\), the occupancy equals \(2^h-1\) and the player's bitboard is a subset of it. Their sum lies in \([2^h-1, 2^{h+1}-2]\). These intervals do not overlap for different heights, so the sum uniquely identifies the occupancy and the player's bits. The largest possible sum is 126, which fits within the seven-bit column slot. This is a collision-free state encoding under gravity, not a general property of addition.
6. What We Retained and What We Omitted
| Astra feature | Coverage |
|---|---|
| 49-bit encoding and board masks | Retained and explained |
| Carry-based landing cells and state transition | Retained and explained |
| Winning-cell detection | Retained; repeated directions replaced by a loop |
| Terminal detection and rewards | Made explicit; mate-distance scoring omitted |
| Seven evaluation features and weights | Retained; simplified window counting |
Parallel window statistics (_LINE_STARTS) |
Replaced by explicit windows; derivation omitted |
| Lowbit, single-bit and floating-disc tests | Explained; not required by the simplified planner |
| Immediate wins, forced blocks, unsafe-move filtering | Explained; not used as search pruning |
| Negamax and center-first order | Retained; fixed depth |
| Alpha-beta pruning and principal variation search | Omitted |
| Transposition table | State key explained; caching and bound flags omitted |
| Symmetry, history and killer heuristics | Omitted |
| Forced extensions and endgame shortcuts | Omitted |
| Iterative deepening, aspiration windows and timeout handling | Omitted |
| Opening shortcut, tactical fallback and defensive input handling | Omitted |
The goal is comprehension, not reproducing Astra's Elo. Separating representation, world model, evaluation and planning makes the underlying algorithm easier to read without discarding its most interesting bitwise techniques. The performance cost of this rewrite would require benchmarking.
Appendix: A Brief History of Solving Connect4
Following the three levels of game solving:
- Ultra-weakly solved: the game-theoretic outcome (win, draw, or loss) from the initial state under optimal play is known; an optimal strategy need not be known.
- Weakly solved: a strategy achieving the game-theoretic value from the initial state under reasonable computational resources is known. Optimal actions outside its coverage need not be known.
- Strongly solved: an optimal action can be determined for every legal reachable non-terminal state under reasonable computational resources.
What counts as reasonable depends on the computational context.
In 1988, James D. Allen and, 15 days later, Victor Allis independently weakly solved standard Connect4, establishing a first-player winning strategy. This does not necessarily tell the second player how to exploit every mistake made by the first player.
In the 1990s, John Tromp strongly solved the game by precomputing the values of all 8-ply positions, spending approximately 40,000 computational hours. Earlier positions can be evaluated by searching forward to the database; later positions can be evaluated by exact game-tree search. The combination made it feasible to solve arbitrary legal positions.
In 2025, Markus Böck computed the optimal win/draw/loss value function over the reachable state space and stored it in a compressed 89.6 GB lookup table. With this database, WDL-optimal actions can be selected by one-step planning rather than deep online search.