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.

. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . O O . . .
. X X X X O . ← X wins
0 1 2 3 4 5 6

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:
state = encode(board)
if terminal_value(state) is not None:
raise ValueError("Game has ended")
return max(legal_actions(state),
key=lambda a: -search(world_model(state, a), 3))

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
│
├─ action 0 → world_model → search → score
├─ action 1 → world_model → search → score
└─ ...
best score → action

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
Bit value: 1 0 1 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)
0 1 2 3 4 5 6
sentinel 6 13 20 27 34 41 48
---------------------------
r = 5 5 12 19 26 33 40 47
r = 4 4 11 18 25 32 39 46
r = 3 3 10 17 24 31 38 45
r = 2 2 9 16 23 30 37 44
r = 1 1 8 15 22 29 36 43
r = 0 0 7 14 21 28 35 42

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

Their positions can be encoded as a single integer:

p = (1 << 0) | (1 << 1) | (1 << 7)
# 0b10000011 = 131

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
bool(p & (1 << 8)) # False

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

X O . 1 0 0 1 1 0
O X . 0 1 0 1 1 0

X: current player O: opponent .: empty

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)
_COLS = tuple(63 << (7*c) for c in range(7))
_FULL = sum(_COLS)
_BOTTOM = sum(1 << (7*c) for c in range(7))
_CENTER = _COLS[3]
_MATE = 100000


def encode(board):
p = mask = 0
for c in range(7):
for r in range(6):
value = board[5-r][c]
bit = 1 << (7*c+r)
if value:
mask |= bit
if value == 1:
p |= bit
return p, mask

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):
return (mask + _BOTTOM) & _FULL

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
+ 0000001 bottom bit
---------
0001000 next landing cell

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
↑ ↗
X → +7
↘
+6

Consider four discs at indices 0, 7, 14, 21. Shifting right aligns them at index 0:

Set-bit indices
p {0, 7, 14, 21}
p >> 7 {0, 7, 14}
p >> 14 {0, 7}
p >> 21 {0}
AND {0} ← a four-in-a-row starts here
def has_four(p):
for s in (1, 7, 6, 8):
if p & (p >> s) & (p >> (2*s)) & (p >> (3*s)):
return True
return False

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):
result = (p << 1) & (p << 2) & (p << 3)
for s in (7, 6, 8):
pair = (p << s) & (p << (2*s))
result |= pair & ((p << (3*s)) | (p >> s))
pair = (p >> s) & (p >> (2*s))
result |= pair & ((p << s) | (p >> (3*s)))
return result & (_FULL ^ 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):
_, mask = state
possible = possible_moves(mask)
return [c for c in _ORDER if possible & _COLS[c]]


def world_model(state, action):
p, mask = state
move = possible_moves(mask) & _COLS[action]
if not move:
raise ValueError("Column is full")
return mask ^ p, mask | move


def terminal_value(state):
p, mask = state
if has_four(mask ^ p):
return -_MATE
if has_four(p):
return _MATE
if mask == _FULL:
return 0
return None

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)
After: (old opponent's discs, all occupied cells + new disc)

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):
forced = possible & opponent_wins
if forced.bit_count() > 1:
return 0
return (forced or possible) & ~(opponent_wins >> 1)

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))
_EVEN_ROWS = _FULL ^ _ODD_ROWS


def generate_windows():
windows = []
for c in range(7):
for r in range(6):
for dc, dr in ((0, 1), (1, 0), (1, -1), (1, 1)):
cells = [(c+i*dc, r+i*dr) for i in range(4)]
if all(0 <= x < 7 and 0 <= y < 6 for x, y in cells):
windows.append(sum(1 << (7*x+y) for x, y in cells))
return windows


WINDOWS = generate_windows()


def window_features(player, opponent):
open_windows = [w for w in WINDOWS if not (w & opponent)]
return len(open_windows), sum((w & player).bit_count() >= 2
for w in open_windows)


def evaluate(state):
p, mask = state
q = mask ^ p
pw, qw = _winning(p, mask), _winning(q, mask)
if mask.bit_count() & 1:
my_parity, their_parity = _EVEN_ROWS, _ODD_ROWS
else:
my_parity, their_parity = _ODD_ROWS, _EVEN_ROWS
po, ps = window_features(p, q)
qo, qs = window_features(q, p)
possible = possible_moves(mask)
safe = safe_moves(possible, qw)
their_safe = possible & ~(pw >> 1)
features = (
pw.bit_count() - qw.bit_count(),
(pw & my_parity).bit_count() - (qw & their_parity).bit_count(),
(pw & (pw >> 1)).bit_count() - (qw & (qw >> 1)).bit_count(),
(p & _CENTER).bit_count() - (q & _CENTER).bit_count(),
po - qo, ps - qs,
safe.bit_count() - their_safe.bit_count(),
)
return sum(w*f for w, f in zip((48, 12, 40, 3, 2, 10, 4), features))

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):
value = terminal_value(state)
if value is not None:
return value
if depth == 0:
return evaluate(state)
return max(-search(world_model(state, a), depth-1)
for a in legal_actions(state))

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
bits = 0b10110
while bits:
move = bits & -bits
bits ^= move

x & -x isolates the least significant 1 (lowbit). Because -x = ~x + 1, in an illustrative eight-bit two's-complement representation:

 x     00010110   (22)
~x 11101001
-x 11101010 (-22)
AND 00000010 (2)

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
x - 1 00010011
AND 00010000

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:

  1. 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.
  2. 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.
  3. 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.