What is a Bitboard?
Instead of using a 2D array likeboard[6][7], Marlin uses a single 64-bit integer (called a “bitboard”) where each bit represents one cell on the board.
Computers are extremely fast at bitwise operations (AND, OR, XOR, shifts). This lets us check for wins, make moves, and evaluate positions in just a few CPU instructions instead of loops.
The Bit Layout
The 6x7 Connect 4 board is mapped to bits 0-48 of a 64-bit integer:The buffer bit prevents false diagonal wins from wrapping around between columns.
Bit Index Formula
The formula to convert board coordinates to bit index is:- Cell (row=0, col=0) → bit 0
- Cell (row=5, col=0) → bit 5
- Cell (row=0, col=1) → bit 7
- Cell (row=2, col=3) → bit 23
The Two Core Bitboards
Marlin uses two bitboards to represent the game state:1. The Mask Bitboard
A bitboard where every occupied cell (by either player) has a 1.2. The Position Bitboard
A bitboard showing only the current player’s stones.Helper Mask Functions
Marlin provides several helper functions to work with bitboards:Bottom Mask
Returns a bitboard with a single 1 at the bottom of a given column:Column Mask
Returns a bitboard with 1s in all playable cells of a column:Top Mask
Returns a bitboard with a single 1 at the top playable cell (row 5):The Gravity Trick
One of the most elegant parts of bitboard representation is how moves are made. Instead of looping to find the first empty row, Marlin uses binary addition.How It Works
Fromposition.hpp:138-161:
The Magic of Binary Addition
Adding 1 to a sequence of 1s causes a “carry” that propagates up until it hits a 0:Win Detection with Bitshifts
To check for 4-in-a-row, Marlin shifts the bitboard against itself and ANDs the results. If we get a non-zero result, there’s a 4-in-a-row! Fromposition.hpp:192-217:
Horizontal Wins
Shift by 7 (one column apart):Vertical Wins
Shift by 1 (one row apart):Diagonal Wins (/)
Shift by 8 (one row + one column):Diagonal Wins ()
Shift by 6 (one row - one column):Position Key Generation
Thekey() function generates a unique identifier for each position, used by the transposition table:
This formula cleverly encodes both the stone positions and whose turn it is in a single 64-bit integer.
Why Bitboards Are Fast
- Single CPU instructions: Bitwise operations (AND, OR, XOR, shifts) are single-cycle operations on modern CPUs
- Cache-friendly: Two 64-bit integers fit in a single cache line
- No loops needed: Win detection happens in constant time with bit shifts
- The gravity trick: Making a move is just one addition operation
- Parallel operations: A single bitwise operation can check multiple cells simultaneously
Related Concepts
- Transposition Tables - How position keys are used for caching
- Negamax Algorithm - The search algorithm that uses these bitboards