Bitboard in Connect Four
Definition
A bitboard is a board representation that packs the entire Connect Four position into one or two 64-bit integers, enabling extremely fast move generation and threat detection.
Explanation
A bitboard is a clever encoding of the Connect Four board state into a small number of integer bits. The board has 7 columns and 6 rows, giving 42 squares. By assigning each square a bit position in a 64-bit integer, the entire board state can be stored in just two 64-bit integers (one for player 1's pieces, one for player 2's pieces). This compact representation enables the engine to perform operations like move generation, threat detection, and position evaluation using bitwise operations that execute in a single CPU cycle.
The bit layout typically uses 7 bits per column with one extra bit between columns as padding. The padding bit ensures that operations spanning columns do not accidentally affect adjacent columns. With this layout, common operations become trivially fast. To find all winning positions for a player, the engine performs a few shift and AND operations on the player's bitboard. To check if four-in-a-row exists, similar shift operations test horizontal, vertical, and both diagonal directions in just a few CPU instructions.
Bitboards are the standard representation in modern Connect Four engines because they are dramatically faster than alternatives. A naive 2D array representation requires looping through cells one at a time. A bitboard processes the entire board in parallel using single CPU instructions. The speedup is often 10x to 100x, which directly translates into deeper search and stronger play within the same time budget.
While bitboards are an implementation detail, they have strategic implications. Engines using bitboards can search deeper than engines using slower representations, which means they play stronger. When you face a strong Connect Four engine, the speed difference between bitboards and naive representations may be the deciding factor in who wins. The play4row engine uses a bitboard representation internally, which is why it responds instantly with perfect or near-perfect moves.
Example
The bitboard for player 1 might be the integer 0x040810004000. Decoded, this means bits at specific positions are set, corresponding to player 1 pieces at specific board squares. The engine can check for four-in-a-row in microseconds.
Related Articles
Put It Into Practice
Understanding bitboard is one thing. Applying it is another.