Connect-4 position represented as a pair of 64-bit bitboards. More...
#include <Board.h>
Classes | |
| struct | RawState |
| Plain-data snapshot of the board's internal state. More... | |
Public Types | |
| enum | Player { P_EMPTY = 0 , P_YELLOW = 1 , P_RED = 2 } |
| Player identifiers used by the board's array view. More... | |
| using | TBitBoard = uint64_t |
| 64-bit type used for any bitboard value. | |
| using | TMovesCounter = int |
| Type used to count remaining moves on a position. | |
| using | TBoardArray = std::array<std::array<int32_t, N_ROWS>, N_COLUMNS> |
| Column-major 2D representation of the board (Board representation[col][row]). | |
| using | TBoardArrayT = std::array<std::array<int32_t, N_COLUMNS>, N_ROWS> |
| Row-major 2D representation of the board (Board representation[row][col]). | |
Public Member Functions | |
| Board () | |
| Construct an empty board with player Yellow to move. | |
| Board | playBitMaskOnCopy (const TBitBoard mv) const |
| Apply a move (already encoded as a single-bit mask) on a copy of this board. | |
| Board | playMoveOnCopy (const int mv) const |
| Apply a move given by column index on a copy of this board. | |
| Board | copy () const |
| Return a deep copy of this board. | |
| TBitBoard | legalMovesMask () const |
| Bitboard whose set bits mark the next reachable cell of every non-full column. | |
| std::vector< int > | legalMoves (bool nonLosing, bool orderMoves) const |
| Enumerate legal moves as column indices. | |
| auto | popCountBoard () const |
| Number of stones currently on the board. | |
| bool | isLegalMove (int column) const |
Check whether dropping a stone in column is legal. | |
| uint64_t | uid () const |
| Unique 64-bit identifier of the position. | |
| uint64_t | hash () const |
| 64-bit hash of the position derived from uid(). | |
| bool | operator== (const Board &b) const |
| Compare two positions for equality (same stones, same side to move). | |
| bool | operator!= (const Board &b) const |
Inequality counterpart of operator==. | |
| TBitBoard | findOddThreats (TBitBoard moves) |
| Identify candidate moves that introduce a new "odd" threat. | |
| bool | setBoard (const TBoardArray &board) |
Replace the current position with the one described by board. | |
| bool | setBoard (const TBoardArrayT &board) |
Row-major variant of setBoard(const TBoardArray&). | |
| bool | setBoard (const std::vector< int > &moveSequence) |
| Replay a move sequence onto a fresh board and copy the result. | |
| bool | play (int column) |
Drop a stone of the player to move into column. | |
| bool | play (const std::vector< int > &moveSequence) |
| Apply a sequence of column-index moves. | |
| bool | play (const std::string &moveSequence) |
| Apply a sequence of moves encoded as digit characters. | |
| bool | setBoard (const std::string &moveSequence) |
| String-based variant of setBoard(const std::vector<int>&). | |
| TBoardArray | toArray () const |
| Convert the bitboard representation into a column-major array. | |
| bool | canWin () const |
| Does the player to move have an immediately winning move? | |
| bool | canWin (int column) const |
| Variant of canWin() restricted to a particular column. | |
| bool | hasWin () const |
| Did the player who just moved form a four-in-a-row? | |
| std::string | toString () const |
| Pretty-printed ASCII representation of the board. | |
| TMovesCounter | movesLeft () const |
| Number of plies remaining until the board is full. | |
| TMovesCounter | countTokens () const |
| Number of stones currently placed on the board. | |
| Board | mirror () const |
| Mirror the board around its central column. | |
| MoveList | sortMoves (TBitBoard moves) const |
| Sort candidate moves into a MoveList using a threat-based heuristic. | |
| TBitBoard | findThreats (TBitBoard moves) |
| Identify candidate moves that yield a tactical advantage. | |
| int | getColumnHeight (const int column) const |
Number of stones currently stacked in column. | |
| TBitBoard | generateNonLosingMoves () const |
| Compute moves that do not lose immediately. | |
| TBitBoard | doubleThreat (const TBitBoard moves) const |
| Identify moves that create a "double threat" (forced win). | |
| int | toHuffman () const |
| Encode the position as a compact Huffman-like integer. | |
| std::vector< Board > | allPositions (const int upToNPly, bool exactlyN) const |
| Enumerate every reachable position from this board within a depth. | |
| RawState | rawState () const noexcept |
| Snapshot the internal state. | |
| void | setRawState (const RawState &s) noexcept |
| Restore an internal state previously captured with rawState(). | |
Static Public Member Functions | |
| static constexpr int | popCountBoard (uint64_t x) |
| Software popcount fallback used when no intrinsic is available. | |
| static uint64_t | hash (uint64_t x) |
| Splittable-mix-style hash for a 64-bit integer. | |
| static TBitBoard | nextMove (TBitBoard allMoves) |
| Pick the best-ranked move from a candidate set using a fixed priority order. | |
| static bool | isValid (const TBoardArray &board) |
| Validate a board layout. | |
| static TBitBoard | lsb (const TBitBoard x) |
| Isolate the least significant set bit of a bitboard. | |
| static std::pair< Board, std::vector< int > > | randomBoard (const int nPly, const bool forbidDirectWin=true) |
| Generate a random reachable position with a fixed number of plies. | |
Static Public Attributes | |
| static constexpr int | N_COLUMNS = 7 |
| Number of columns in a Connect-4 grid. | |
| static constexpr int | N_ROWS = 6 |
| Number of rows in a Connect-4 grid. | |
| static constexpr int | COLUMN_BIT_OFFSET = 9 |
| Bit-offset between two columns inside the 64-bit board representation. | |
| static constexpr size_t | N_VALID_BOARD_VALUES = 3 |
| Number of distinct cell values: empty, yellow, red. | |
Friends | |
| class | BoardTest |
Connect-4 position represented as a pair of 64-bit bitboards.
The board uses two 64-bit integers to encode an entire 7×6 position:
m_bAllTokens has a bit set for every occupied cell.m_bActivePTokens has a bit set for every cell occupied by the player whose turn it is. The opponent mask is therefore obtained as m_bActivePTokens ^ m_bAllTokens.Encoding the position this way removes any branching when switching the side to move — m_bActivePTokens is simply XOR'ed with m_bAllTokens after each ply. The internal bit layout is:
Bit indices for a column c and row r are c * 9 + r.
| using BitBully::Board::TBitBoard = uint64_t |
| using BitBully::Board::TBoardArray = std::array<std::array<int32_t, N_ROWS>, N_COLUMNS> |
Column-major 2D representation of the board (Board representation[col][row]).
| using BitBully::Board::TBoardArrayT = std::array<std::array<int32_t, N_COLUMNS>, N_ROWS> |
Row-major 2D representation of the board (Board representation[row][col]).
| using BitBully::Board::TMovesCounter = int |
| BitBully::Board::Board | ( | ) |
|
inlinenodiscard |
Enumerate every reachable position from this board within a depth.
Performs a recursive expansion via addAfterStates() and deduplicates positions by their uid().
| upToNPly | Maximum number of plies to play from the current board. |
| exactlyN | If true, return only positions with exactly upToNPly stones placed; if false, include all intermediate positions as well. |
Definition at line 719 of file Board.h.
|
nodiscard |
|
nodiscard |
|
inlinenodiscard |
|
inlinenodiscard |
Identify moves that create a "double threat" (forced win).
A double threat is a stone that produces two immediate vertical threats stacked on top of each other — the opponent can only block one of them.
| moves | Candidate move bitboard. |
moves whose execution yields a double threat. Definition at line 619 of file Board.h.
|
nodiscard |
Identify candidate moves that introduce a new "odd" threat.
A threat sitting in an odd-numbered row (rows 3 and 5 from below) is particularly valuable for the first player due to Connect-4's even/odd-row strategy theory.
| moves | Set of candidate moves (bitboard). |
moves that increase the number of odd threats. Definition at line 344 of file Board.cpp.
| Board::TBitBoard BitBully::Board::findThreats | ( | TBitBoard | moves | ) |
Identify candidate moves that yield a tactical advantage.
Returns either:
| moves | Candidate move bitboard. |
moves. Definition at line 313 of file Board.cpp.
|
inlinenodiscard |
Compute moves that do not lose immediately.
Inspired by Pascal Pons' Connect-4 solver (http://blog.gamesolver.org/). The function returns a bitboard of legal moves whose execution does not let the opponent finish the game on the next ply.
winningPositions() explicitly.Definition at line 591 of file Board.h.
|
nodiscard |
|
inlinenodiscard |
|
inlinestaticnodiscard |
Splittable-mix-style hash for a 64-bit integer.
Implementation of David Stafford's "Mix13" finaliser. Used internally to derive transposition-table indices from board UIDs.
| x | 64-bit input. |
x. Definition at line 334 of file Board.h.
|
nodiscard |
|
nodiscard |
Check whether dropping a stone in column is legal.
| column | Column index. |
true if column is in range and not yet full. Definition at line 170 of file Board.cpp.
|
staticnodiscard |
Validate a board layout.
Checks that all cells contain a known value, that gravity is respected, and that the stone count satisfies 0 <= yellow - red <= 1.
| Board representation | Column-major array to validate. |
true if board could appear in a real game. Definition at line 97 of file Board.cpp.
|
nodiscard |
Enumerate legal moves as column indices.
| nonLosing | If true, restrict the result to moves that do not immediately allow the opponent to win. Direct winning moves of the active player are always included. |
| orderMoves | If true, sort the moves by the heuristic implemented in sortMoves() (best first). |
N_COLUMNS-1). Definition at line 448 of file Board.cpp.
|
nodiscard |
|
nodiscard |
Mirror the board around its central column.
Useful for transposition lookups: a position and its mirror image have identical theoretical value, so storing only one of them roughly halves the effective table size.
Definition at line 501 of file Board.cpp.
|
inlinenodiscard |
Pick the best-ranked move from a candidate set using a fixed priority order.
The static priority lists BB_MOVES_PRIO1 … BB_MOVES_PRIO6 encode a center-first ordering. The first priority class that has a non-empty intersection with allMoves wins; among the remaining candidates the one with the smallest bit index (i.e. lower row, leftmost column) is returned.
| allMoves | Bitboard of candidate moves (one bit per cell). |
0 if allMoves is empty. Definition at line 376 of file Board.h.
|
inlinenodiscard |
|
inlinenodiscard |
|
nodiscard |
Apply a sequence of moves encoded as digit characters.
Each character must be in '0'..'0'+N_COLUMNS-1.
| moveSequence | String of column-index digits. |
true on success, false on the first illegal move; on failure the board is left unchanged. Definition at line 156 of file Board.cpp.
|
nodiscard |
| bool BitBully::Board::play | ( | int | column | ) |
Drop a stone of the player to move into column.
| column | Column index. |
true if the move was legal and applied, false otherwise. Definition at line 137 of file Board.cpp.
Apply a move (already encoded as a single-bit mask) on a copy of this board.
| mv | Bitboard with exactly one bit set, representing the cell to occupy. Must be a legal move; behaviour is undefined otherwise. |
Definition at line 245 of file Board.h.
|
inlinenodiscard |
Apply a move given by column index on a copy of this board.
| mv | Column index (0…N_COLUMNS-1). |
Board with the move applied. If mv is illegal a freshly-constructed empty board is returned instead. Definition at line 258 of file Board.h.
|
inlinenodiscard |
Number of stones currently on the board.
Equivalent to countTokens() but exposes the raw popcount of the internal bitboard.
|
inlinestaticnodiscardconstexpr |
|
inlinestatic |
Generate a random reachable position with a fixed number of plies.
Plays random legal moves until nPly stones are on the board. If forbidDirectWin is true the function reroutes around positions where the side to move can win immediately (useful when generating benchmark positions).
| nPly | Number of plies to play (0…N_ROWS*N_COLUMNS). |
| forbidDirectWin | Reject positions where the active player has an immediate win. |
nPly is out of range. Definition at line 689 of file Board.h.
|
inlinenodiscardnoexcept |
|
nodiscard |
String-based variant of setBoard(const std::vector<int>&).
Definition at line 41 of file Board.cpp.
|
nodiscard |
Replay a move sequence onto a fresh board and copy the result.
| moveSequence | Sequence of column indices to play in order. |
true on success, false if the sequence contains an illegal move; the object is unchanged on failure. Definition at line 30 of file Board.cpp.
|
nodiscard |
Replace the current position with the one described by board.
| Board representation | Column-major array using P_EMPTY / P_YELLOW / P_RED values. Stones must respect gravity (no floating cells). |
true on success, false if board is malformed; the object is unchanged on failure. Definition at line 67 of file Board.cpp.
|
nodiscard |
Row-major variant of setBoard(const TBoardArray&).
Definition at line 62 of file Board.cpp.
|
inlinenoexcept |
Restore an internal state previously captured with rawState().
Definition at line 760 of file Board.h.
Sort candidate moves into a MoveList using a threat-based heuristic.
Each move is scored by the number of new threats (winning lines) it introduces, with a penalty for moves placed directly under one of the active player's existing threats.
| moves | Bitboard of candidate moves. |
Definition at line 285 of file Board.cpp.
|
nodiscard |
|
inlinenodiscard |
Encode the position as a compact Huffman-like integer.
Used as a key for the opening-book tables. The encoding is only defined for positions with an even number of tokens and at most 12 placed stones (i.e. m_movesLeft is even and at least 30).
Each column is encoded by walking from the bottom up: every stone contributes two bits (10 for the active player, 11 for the opponent), and the stack is terminated by a single 0 bit.
0 if the position does not qualify for encoding. Definition at line 650 of file Board.h.
|
nodiscard |
Pretty-printed ASCII representation of the board.
Yellow stones are rendered as X, Red stones as O, and empty cells as _. Rows are printed from top to bottom.
Definition at line 481 of file Board.cpp.
|
inlinenodiscard |
Unique 64-bit identifier of the position.
Combines the "all tokens" bitboard with the "active player" bitboard in a way that ensures every legal Connect-4 position maps to a distinct value. Suitable as a key for transposition tables.
Definition at line 350 of file Board.h.
|
staticconstexpr |
|
staticconstexpr |
Number of columns in a Connect-4 grid.
|
staticconstexpr |
|
staticconstexpr |