board
This module defines the Board class for managing the state of a Connect Four game.
Classes:
| Name | Description |
|---|---|
Board |
Represents the state of a Connect Four board. Mostly a thin wrapper around BoardCore. |
Board
Represents the state of a Connect Four board. Mostly a thin wrapper around BoardCore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sequence[Sequence[int]] | Sequence[int] | str | None
|
Optional initial board state. Accepts: - 2D array (list, tuple, numpy-array) with shape 7x6 or 6x7 - 1D sequence of ints: a move sequence of columns (e.g., [0, 0, 2, 2, 3, 3]) - String: A move sequence of columns as string (e.g., "002233") - None for an empty board |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provided initial board state is invalid. |
Example
You can initialize an empty board in multiple ways:
import bitbully as bb
# Create an empty board using the default constructor.
board = bb.Board() # Starts with no tokens placed.
# Alternatively, initialize the board explicitly from a 2D list.
# Each inner list represents a column (7 columns total, 6 rows each).
# A value of 0 indicates an empty cell; 1 and 2 would represent player tokens.
board = bb.Board([[0] * 6 for _ in range(7)]) # Equivalent to an empty board.
# You can also set up a specific board position manually using a 6 x 7 layout,
# where each inner list represents a row instead of a column.
# (Both layouts are accepted by BitBully for convenience.)
# For more complex examples using 2D arrays, see the examples below.
board = bb.Board([[0] * 7 for _ in range(6)]) # Also equivalent to an empty board.
# Display the board in text form.
# The __repr__ method shows the current state (useful for debugging or interactive use).
board
The recommended way to initialize an empty board is simply Board().
Example
You can also initialize a board with a sequence of moves:
import bitbully as bb
# Initialize a board with a sequence of moves played in the center column.
# The list [3, 3, 3] represents three moves in column index 3 (zero-based).
# Moves alternate automatically between Player 1 (yellow, X) and Player 2 (red, O).
# After these three moves, the center column will contain:
# - Row 0: Player 1 token (bottom)
# - Row 1: Player 2 token
# - Row 2: Player 1 token
board = bb.Board([3, 3, 3])
# Display the resulting board.
# The textual output shows the tokens placed in the center column.
board
Expected output:
Example
You can also initialize a board using a string containing a move sequence:
import bitbully as bb
# Initialize a board using a compact move string.
# The string "33333111" represents a sequence of eight moves:
# 3 3 3 3 3 → five moves in the center column (index 3)
# 1 1 1 → three moves in the second column (index 1)
#
# Moves are applied in order, alternating automatically between Player 1 (yellow, X)
# and Player 2 (red, O), just as if you had called `board.play()` repeatedly.
#
# This shorthand is convenient for reproducing board states or test positions
# without having to provide long move lists.
board = bb.Board("33333111")
# Display the resulting board.
# The printed layout shows how the tokens stack in each column.
board
Example
You can also initialize a board using a 2D array (list of lists):
import bitbully as bb
# Use a 6 x 7 list (rows x columns) to set up a specific board position manually.
# Each inner list represents a row of the Connect-4 grid.
# Convention:
# - 0 → empty cell
# - 1 → Player 1 token (yellow, X)
# - 2 → Player 2 token (red, O)
#
# The top list corresponds to the *top row* (row index 5),
# and the bottom list corresponds to the *bottom row* (row index 0).
# This layout matches the typical visual display of the board.
board_array = [
[0, 0, 0, 0, 0, 0, 0], # Row 5 (top)
[0, 0, 0, 1, 0, 0, 0], # Row 4: Player 1 token in column 3
[0, 0, 0, 2, 0, 0, 0], # Row 3: Player 2 token in column 3
[0, 2, 0, 1, 0, 0, 0], # Row 2: tokens in columns 1 and 3
[0, 1, 0, 2, 0, 0, 0], # Row 1: tokens in columns 1 and 3
[0, 2, 0, 1, 0, 0, 0], # Row 0 (bottom): tokens stacked lowest
]
# Create a Board instance directly from the 2D list.
# This allows reconstructing arbitrary positions (e.g., from test data or saved states)
# without replaying the move sequence.
board = bb.Board(board_array)
# Display the resulting board state in text form.
board
Example
You can also initialize a board using a 2D (7 x 6) array with columns as inner lists:
import bitbully as bb
# Use a 7 x 6 list (columns x rows) to set up a specific board position manually.
# Each inner list represents a **column** of the Connect-4 board, from left (index 0)
# to right (index 6). Each column contains six entries — one for each row, from
# bottom (index 0) to top (index 5).
#
# Convention:
# - 0 → empty cell
# - 1 → Player 1 token (yellow, X)
# - 2 → Player 2 token (red, O)
#
# This column-major layout matches the internal representation used by BitBully,
# where tokens are dropped into columns rather than filled row by row.
board_array = [
[0, 0, 0, 0, 0, 0], # Column 0 (leftmost)
[2, 1, 2, 0, 0, 0], # Column 1
[0, 0, 0, 0, 0, 0], # Column 2
[1, 2, 1, 2, 1, 0], # Column 3 (center)
[0, 0, 0, 0, 0, 0], # Column 4
[0, 0, 0, 0, 0, 0], # Column 5
[0, 0, 0, 0, 0, 0], # Column 6 (rightmost)
]
# Create a Board instance directly from the 2D list.
# This allows reconstructing any arbitrary position (e.g., test cases, saved games)
# without replaying all moves individually.
board = bb.Board(board_array)
# Display the resulting board.
# The text output shows tokens as they would appear in a real Connect-4 grid.
board
- BitBully API Reference
Methods:
| Name | Description |
|---|---|
__eq__ |
Checks equality between two Board instances. |
__hash__ |
Returns a hash of the Board instance for use in hash-based collections. |
__ne__ |
Checks inequality between two Board instances. |
__repr__ |
Returns a string representation of the Board instance. |
__str__ |
Return a human-readable ASCII representation (same as to_string()). |
all_positions |
Find all positions reachable from the current position up to a given ply. |
can_win_next |
Checks if the current player can win in the next move. |
copy |
Creates a copy of the current Board instance. |
count_tokens |
Counts the total number of tokens currently placed on the board. |
current_player |
Returns the player whose turn it is to move. |
from_array |
Creates a board directly from a 2D array representation. |
from_moves |
Creates a board by replaying a sequence of moves from the empty position. |
has_win |
Checks if the current player has a winning position. |
is_full |
Checks whether the board has any empty cells left. |
is_game_over |
Checks whether the game has ended (win or draw). |
is_legal_move |
Checks if a move (column) is legal in the current position. |
legal_moves |
Returns a list of all legal moves (non-full columns) for the current board state. |
mirror |
Returns a new Board instance that is the mirror image of the current board. |
moves_left |
Returns the number of moves left until the board is full. |
play |
Plays one or more moves for the current player. |
play_on_copy |
Return a new board with the given move applied, leaving the current board unchanged. |
random_board |
Generates a random board state by playing a specified number of random moves. |
reset_board |
Resets the board or sets (overrides) the board to a specific state. |
to_array |
Returns the board state as a 2D array (list of lists). |
to_huffman |
Encode the current board position into a Huffman-compressed byte sequence. |
to_string |
Returns a human-readable ASCII representation of the board. |
uid |
Returns a unique identifier for the current board state. |
winner |
Returns the winning player, if the game has been won. |
Attributes:
| Name | Type | Description |
|---|---|---|
N_COLUMNS |
int
|
|
N_ROWS |
int
|
|
Player |
|
Source code in src/bitbully/board.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
__eq__
Checks equality between two Board instances.
Notes
- Equality checks in BitBully compare the exact board state (bit patterns), not just the move history.
- Two different move sequences can still yield the same position if they result in identical token configurations.
- This is useful for comparing solver states, verifying test positions, or detecting transpositions in search algorithms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
object
|
The other Board instance to compare against. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if both boards are equal, False otherwise. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the other value is not a Board instance. |
Example
import bitbully as bb
# Create two boards that should represent *identical* game states.
board1 = bb.Board()
assert board1.play("33333111")
board2 = bb.Board()
# Play the same position step by step using a different but equivalent sequence.
# Internally, the final bitboard state will match `board1`.
assert board2.play("31133331")
# Boards with identical token placements are considered equal.
# Equality (`==`) and inequality (`!=`) operators are overloaded for convenience.
assert board1 == board2
assert not (board1 != board2)
# ------------------------------------------------------------------------------
# Create two boards that differ by one move.
board1 = bb.Board("33333111")
board2 = bb.Board("33333112") # One extra move in the last column (index 2)
# Since the token layout differs, equality no longer holds.
assert board1 != board2
assert not (board1 == board2)
Source code in src/bitbully/board.py
__hash__
__hash__() -> int
Returns a hash of the Board instance for use in hash-based collections.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The hash value of the Board instance. |
Example
import bitbully as bb
# Create two boards that represent the same final position.
# The first board is initialized directly from a move string.
board1 = bb.Board("33333111")
# The second board is built incrementally by playing an equivalent sequence of moves.
# Even though the order of intermediate plays differs, the final layout of tokens
# (and thus the internal bitboard state) will be identical to `board1`.
board2 = bb.Board()
board2.play("31133331")
# Boards with identical configurations produce the same hash value.
# This allows them to be used efficiently as keys in dictionaries or members of sets.
assert hash(board1) == hash(board2)
# Display the board's hash value.
hash(board1)
Source code in src/bitbully/board.py
__ne__
Checks inequality between two Board instances.
See the documentation for Board.eq for details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
object
|
The other Board instance to compare against. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if both boards are not equal, False otherwise. |
Source code in src/bitbully/board.py
__repr__
__repr__() -> str
__str__
__str__() -> str
Return a human-readable ASCII representation (same as to_string()).
See the documentation for Board.to_string for details.
all_positions
Find all positions reachable from the current position up to a given ply.
This is a high-level wrapper around
bitbully_core.BoardCore.allPositions.
Starting from the current board, it generates all positions that can be reached by playing additional moves such that the resulting position has:
- At most
up_to_n_plytokens on the board, ifexactly_nisFalse. - Exactly
up_to_n_plytokens on the board, ifexactly_nisTrue.
Note
The number of tokens already present in the current position is taken
into account. If up_to_n_ply is smaller than
self.count_tokens(), the result is typically empty.
This function can grow combinatorially with up_to_n_ply and the
current position, so use it with care for large depths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The maximum total number of tokens (ply) for generated positions. Must be between 0 and 42 (inclusive). |
required |
|
bool
|
If |
required |
Returns:
| Type | Description |
|---|---|
list[Board]
|
list[Board]: A list of :class: |
list[Board]
|
reachable positions that satisfy the ply constraint. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Compute all positions at exactly 3 ply from the empty board:
import bitbully as bb
# Start from an empty board.
board = bb.Board()
# Generate all positions that contain exactly 3 tokens.
positions = board.all_positions(3, exactly_n=True)
# According to OEIS A212693, there are exactly 238 distinct
# reachable positions with 3 played moves in standard Connect-4.
assert len(positions) == 238
Reference: - Number of distinct positions at ply n: https://oeis.org/A212693
Source code in src/bitbully/board.py
can_win_next
Checks if the current player can win in the next move.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | None
|
Optional column to check for an immediate win. If None, checks all columns. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the current player can win next, False otherwise. |
See also: Board.has_win.
Example
import bitbully as bb
# Create a board from a move string.
# The string "332311" represents a short sequence of alternating moves
# that results in a nearly winning position for Player 1 (yellow, X).
board = bb.Board("332311")
# Display the current board state (see below)
print(board)
# Player 1 (yellow, X) — who is next to move — can win immediately
# by placing a token in either column 0 or column 4.
assert board.can_win_next(0)
assert board.can_win_next(4)
# However, playing in other columns does not result in an instant win.
assert not board.can_win_next(2)
assert not board.can_win_next(3)
# You can also call `can_win_next()` without arguments to perform a general check.
# It returns True if the current player has *any* winning move available.
assert board.can_win_next()
Source code in src/bitbully/board.py
copy
copy() -> Board
Creates a copy of the current Board instance.
The copy() method returns a new Board object that represents the
same position as the original at the time of copying. Subsequent
changes to one board do not affect the other — they are completely
independent.
Returns:
| Name | Type | Description |
|---|---|---|
Board |
Board
|
A new Board instance that is a copy of the current one. |
Example
Create a board, copy it, and verify that both represent the same position:
import bitbully as bb
# Create a board from a compact move string.
board = bb.Board("33333111")
# Create an independent copy of the current position.
board_copy = board.copy()
# Both boards represent the same position and are considered equal.
assert board == board_copy
assert hash(board) == hash(board_copy)
assert board.to_string() == board_copy.to_string()
# Display the board state.
print(board)
Example
Modifying the copy does not affect the original:
import bitbully as bb
board = bb.Board("33333111")
# Create a copy of the current position.
board_copy = board.copy()
# Play an additional move on the copied board only.
assert board_copy.play(0) # Drop a token into the leftmost column.
# Now the boards represent different positions.
assert board != board_copy
# The original board remains unchanged.
print("Original:")
print(board)
print("Modified copy:")
print(board_copy)
Source code in src/bitbully/board.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 | |
count_tokens
count_tokens() -> int
Counts the total number of tokens currently placed on the board.
This method simply returns how many moves have been played so far in the current position — that is, the number of occupied cells on the 7x6 grid.
It does not distinguish between players; it only reports the total number of tokens, regardless of whether they belong to Player 1 or Player 2.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The total number of tokens on the board (between 0 and 42). |
Example
Count tokens on an empty board:
Expected output:Example
Count tokens after a few moves:
Expected output:Example
Relation to the length of a move sequence:
Source code in src/bitbully/board.py
current_player
current_player() -> int
Returns the player whose turn it is to move.
The current player is derived from the parity of the number of tokens on the board:
- Player 1 (yellow,
X) moves first on an empty board. - After an even number of moves → it is Player 1's turn.
- After an odd number of moves → it is Player 2's turn.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The player to move:
|
Example
import bitbully as bb
# Empty board → Player 1 starts.
board = bb.Board()
assert board.current_player() == 1
assert board.count_tokens() == 0
# After one move, it's Player 2's turn.
assert board.play(3)
assert board.count_tokens() == 1
assert board.current_player() == 2
# After a second move, it's again Player 1's turn.
assert board.play(4)
assert board.count_tokens() == 2
assert board.current_player() == 1
Source code in src/bitbully/board.py
from_array
classmethod
Creates a board directly from a 2D array representation.
This is a convenience wrapper around the main constructor board.Board and accepts the same array formats:
- Row-major: 6 x 7 (
[row][column]), top row first. - Column-major: 7 x 6 (
[column][row]), left column first.
Values must follow the usual convention:
0→ empty cell1→ Player 1 token (yellow,X)2→ Player 2 token (red,O)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sequence[Sequence[int]]
|
A 2D array describing the board state, either in row-major or column-major layout. See the examples in Board for details. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Board |
Board
|
A new |
Example
Using a 6 x 7 row-major layout:
Example
Using a 7 x 6 column-major layout:
import bitbully as bb
board_array = [
[0, 0, 0, 0, 0, 0], # Column 0
[2, 1, 2, 1, 0, 0], # Column 1
[0, 0, 0, 0, 0, 0], # Column 2
[1, 2, 1, 2, 1, 0], # Column 3
[0, 0, 0, 0, 0, 0], # Column 4
[2, 1, 2, 0, 0, 0], # Column 5
[0, 0, 0, 0, 0, 0], # Column 6
]
board = bb.Board.from_array(board_array)
# Round-trip via to_array:
assert board.to_array() == board_array
Source code in src/bitbully/board.py
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 | |
from_moves
classmethod
Creates a board by replaying a sequence of moves from the empty position.
This is a convenience constructor around Board.play. It starts from an empty board and applies the given move sequence, assuming it is legal (no out-of-range columns, no moves in full columns, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sequence[int] | str
|
The move sequence to replay from the starting position. Accepts:
Each value represents a column index (0-6). Players alternate automatically between moves. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Board |
Board
|
A new |
Example
Source code in src/bitbully/board.py
has_win
has_win() -> bool
Checks if the current player has a winning position.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the current player has a winning position (4-in-a-row), False otherwise. |
Unlike can_win_next(), which checks whether the current player could win
on their next move, the has_win() method determines whether a winning
condition already exists on the board.
This method is typically used right after a move to verify whether the game
has been won.
See also: Board.can_win_next.
Example
import bitbully as bb
# Initialize a board from a move sequence.
# The string "332311" represents a position where Player 1 (yellow, X)
# is one move away from winning.
board = bb.Board("332311")
# At this stage, Player 1 has not yet won, but can win immediately
# by placing a token in either column 0 or column 4.
assert not board.has_win()
assert board.can_win_next(0) # Check column 0
assert board.can_win_next(4) # Check column 4
assert board.can_win_next() # General check (any winning move)
# Simulate Player 1 playing in column 4 — this completes
# a horizontal line of four tokens and wins the game.
assert board.play(4)
# Display the updated board to visualize the winning position.
print(board)
# The board now contains a winning configuration:
# Player 1 (yellow, X) has achieved a Connect-4.
assert board.has_win()
Source code in src/bitbully/board.py
is_full
is_full() -> bool
Checks whether the board has any empty cells left.
A Connect Four board has 42 cells in total (7 columns x 6 rows).
This method returns True if all cells are occupied, i.e.
when Board.moves_left returns 0.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Example
import bitbully as bb
board = bb.Board()
assert not board.is_full()
assert board.moves_left() == 42
assert board.count_tokens() == 0
# Fill the board column by column.
for _ in range(6):
assert board.play("0123456") # one token per column, per row
# Now every cell is occupied.
assert board.is_full()
assert board.moves_left() == 0
assert board.count_tokens() == 42
-
BitBully API Reference
boardBoardis_game_over
Source code in src/bitbully/board.py
is_game_over
is_game_over() -> bool
Checks whether the game has ended (win or draw).
A game of Connect Four is considered over if:
- One of the players has a winning position (see Board.has_win), or
- The board is completely full and no further moves can be played (see Board.is_full).
This method does not indicate who won; for that, use Board.winner.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
Example
Game over by a win:
Example
Game over by a draw (full board, no winner):
Source code in src/bitbully/board.py
is_legal_move
Checks if a move (column) is legal in the current position.
A move is considered legal if:
- The column index is within the valid range (0-6), and
- The column is not full (i.e. it still has at least one empty cell).
This method does not check for tactical consequences such as leaving an immediate win to the opponent, nor does it stop being usable once a player has already won. It purely validates whether a token can be dropped into the given column according to the basic rules of Connect Four. You have to check for wins separately using Board.has_win.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The column index (0-6) to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the move is legal, False otherwise. |
Example
All moves are legal on an empty board:
Example
Detecting an illegal move in a full column:
import bitbully as bb
# Fill the center column (index 3) with six tokens.
board = bb.Board()
assert board.play([3, 3, 3, 3, 3, 3])
# The center column is now full, so another move in column 3 is illegal.
assert not board.is_legal_move(3)
# Other columns are still available (as long as they are not full).
assert board.is_legal_move(0)
assert board.is_legal_move(6)
print(board)
Example
This function only checks legality, not for situations where a player has won:
Expected output:Source code in src/bitbully/board.py
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 | |
legal_moves
legal_moves(non_losing: bool = False, order_moves: bool = False) -> list[int]
Returns a list of all legal moves (non-full columns) for the current board state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
bool
|
If |
False
|
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
list[int]
|
list[int]: A list of column indices (0-6) where a token can be legally dropped. |
Example
import bitbully as bb
board = bb.Board()
legal_moves = board.legal_moves()
assert set(legal_moves) == set(range(7)) # All columns are initially legal
assert set(legal_moves) == set(board.legal_moves(order_moves=True))
board.legal_moves(order_moves=True) == [3, 2, 4, 1, 5, 0, 6] # Center column prioritized
Example
Expected output:
Source code in src/bitbully/board.py
mirror
mirror() -> Board
Returns a new Board instance that is the mirror image of the current board.
This method reflects the board horizontally around its vertical center column: - Column 0 <-> Column 6 - Column 1 <-> Column 5 - Column 2 <-> Column 4 - Column 3 stays in the center
The player to move is not changed - only the spatial
arrangement of the tokens is mirrored. The original board remains unchanged;
mirror() always returns a new Board instance.
Returns:
| Name | Type | Description |
|---|---|---|
Board |
Board
|
A new Board instance that is the mirror image of the current one. |
Example
Mirroring a simple asymmetric position:
import bitbully as bb
# Play four moves along the bottom row.
board = bb.Board()
assert board.play("0123") # Columns: 0, 1, 2, 3
# Create a mirrored copy of the board.
mirrored = board.mirror()
print("Original:")
print(board)
print("Mirrored:")
print(mirrored)
Expected output:
Example
Mirroring a position that is already symmetric:
Expected output:Source code in src/bitbully/board.py
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 | |
moves_left
moves_left() -> int
Returns the number of moves left until the board is full.
This is simply the number of empty cells remaining on the 7x6 grid. On an empty board there are 42 free cells, so:
- At the start of the game:
moves_left() == 42 - After
nvalid moves:moves_left() == 42 - n - On a completely full board:
moves_left() == 0
This method is equivalent to:
but implemented efficiently in the underlying C++ core.Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of moves left (0-42). |
Example
Moves left on an empty board:
Example
Relation to the number of moves played:
import bitbully as bb
# Play five moves in various columns.
moves = [3, 3, 1, 4, 6]
board = bb.Board()
assert board.play(moves)
# Five tokens have been placed, so 42 - 5 = 37 moves remain.
assert board.count_tokens() == 5
assert board.moves_left() == 37
assert board.moves_left() + board.count_tokens() == 42
Source code in src/bitbully/board.py
play
Plays one or more moves for the current player.
The method updates the internal board state by dropping tokens
into the specified columns. Input can be:
- a single integer (column index 0 to 6),
- an iterable sequence of integers (e.g., [3, 1, 3] or range(7)),
- or a string of digits (e.g., "33333111") representing the move order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int | Sequence[int] | str
|
The column index or sequence of column indices where tokens should be placed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the move was played successfully, False if the move was illegal. |
Example
Play a sequence of moves into the center column (column index 3):
import bitbully as bb
board = bb.Board()
assert board.play([3, 3, 3]) # returns True on successful move
board
Expected output:
Example
Play a sequence of moves across all columns:
Expected output:Example
Play a sequence using a string:
Expected output:-
BitBully API Reference
boardBoardfrom_moves
Source code in src/bitbully/board.py
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | |
play_on_copy
Return a new board with the given move applied, leaving the current board unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
The column index (0-6) in which to play the move. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Board |
Board
|
A new Board instance representing the position after the move. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the move is illegal (e.g. column is full or out of range). |
Example
Source code in src/bitbully/board.py
random_board
staticmethod
Generates a random board state by playing a specified number of random moves.
If forbid_direct_win is True, the generated position is guaranteed
not to contain an immediate winning move for the player to move.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
int
|
Number of random moves to simulate (0-42). |
required |
|
bool
|
If |
required |
Returns:
| Type | Description |
|---|---|
tuple[Board, list[int]]
|
tuple[Board, list[int]]:
A pair |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Basic usage:
Example
Using random boards in tests or simulations:
import bitbully as bb
# Generate 50 random 10-ply positions.
for _ in range(50):
board, moves = bb.Board.random_board(10, forbid_direct_win=True)
assert len(moves) == 10
assert not board.has_win() # Game should not be over
assert board.count_tokens() == 10 # All generated boards contain exactly 10 tokens
assert not board.can_win_next() # Since `forbid_direct_win=True`, no immediate threat
Example
Reconstructing the board manually from the move list:
Example
Ensure randomness by generating many distinct sequences:
Source code in src/bitbully/board.py
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 | |
reset_board
Resets the board or sets (overrides) the board to a specific state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Sequence[int] | Sequence[Sequence[int]] | str | None
|
The new board state. Accepts: - 2D array (list, tuple, numpy-array) with shape 7x6 or 6x7 - 1D sequence of ints: a move sequence of columns (e.g., [0, 0, 2, 2, 3, 3]) - String: A move sequence of columns as string (e.g., "002233...") - None: to reset to an empty board |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the board was set successfully, False otherwise. |
Example
Reset the board to an empty state:
import bitbully as bb
# Create a temporary board position from a move string.
# The string "0123456" plays one token in each column (0-6) in sequence.
board = bb.Board("0123456")
# Reset the board to an empty state.
# Calling `reset_board()` clears all tokens and restores the starting position.
# No moves → an empty board.
assert board.reset_board()
board
Example
(Re-)Set the board using a move sequence string:
import bitbully as bb
# This is just a temporary setup; it will be replaced below.
board = bb.Board("0123456")
# Set the board state directly from a move sequence.
# The list [3, 3, 3] represents three consecutive moves in the center column (index 3).
# Moves alternate automatically between Player 1 (yellow) and Player 2 (red).
#
# The `reset_board()` method clears the current position and replays the given moves
# from an empty board — effectively overriding any existing board state.
assert board.reset_board([3, 3, 3])
# Display the updated board to verify the new position.
board
Example
You can also set the board using other formats, such as a 2D array or a string. See the examples in the Board docstring for details.
# Briefly demonstrate the different input formats accepted by `reset_board()`.
import bitbully as bb
# Create an empty board instance
board = bb.Board()
# Variant 1: From a list of moves (integers)
# Each number represents a column index (0-6); moves alternate between players.
assert board.reset_board([3, 3, 3])
# Variant 2: From a compact move string
# Equivalent to the list above — useful for quick testing or serialization.
assert board.reset_board("33333111")
# Variant 3: From a 2D list in row-major format (6 x 7)
# Each inner list represents a row (top to bottom).
# 0 = empty, 1 = Player 1, 2 = Player 2.
board_array = [
[0, 0, 0, 0, 0, 0, 0], # Row 5 (top)
[0, 0, 0, 1, 0, 0, 0], # Row 4
[0, 0, 0, 2, 0, 0, 0], # Row 3
[0, 2, 0, 1, 0, 0, 0], # Row 2
[0, 1, 0, 2, 0, 0, 0], # Row 1
[0, 2, 0, 1, 0, 0, 0], # Row 0 (bottom)
]
assert board.reset_board(board_array)
# Variant 4: From a 2D list in column-major format (7 x 6)
# Each inner list represents a column (left to right); this matches BitBully's internal layout.
board_array = [
[0, 0, 0, 0, 0, 0], # Column 0 (leftmost)
[2, 1, 2, 1, 0, 0], # Column 1
[0, 0, 0, 0, 0, 0], # Column 2
[1, 2, 1, 2, 1, 0], # Column 3 (center)
[0, 0, 0, 0, 0, 0], # Column 4
[2, 1, 2, 0, 0, 0], # Column 5
[0, 0, 0, 0, 0, 0], # Column 6 (rightmost)
]
assert board.reset_board(board_array)
# Display the final board state in text form
board
Expected output:
Source code in src/bitbully/board.py
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 | |
to_array
to_array(column_major_layout: bool = True) -> list[list[int]]
Returns the board state as a 2D array (list of lists).
This layout is convenient for printing, serialization, or converting to a NumPy array for further analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
bool
|
Use column-major format if set to |
True
|
Returns:
| Type | Description |
|---|---|
list[list[int]]
|
list[list[int]]: A 7x6 2D list representing the board state. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
Example
The returned array is in column-major format with shape 7 x 6
([column][row]):
- There are 7 inner lists, one for each column of the board.
- Each inner list has 6 integers, one for each row.
- Row index
0corresponds to the bottom row, row index5to the top row. - Convention:
0-> empty cell1-> Player 1 token (yellow, X)2-> Player 2 token (red, O)
import bitbully as bb
from pprint import pprint
# Create a position from a move sequence.
board = bb.Board("33333111")
# Extract the board as a 2D list (rows x columns).
arr = board.to_array()
# Reconstruct the same position from the 2D array.
board2 = bb.Board(arr)
# Both boards represent the same position.
assert board == board2
assert board.to_array() == board2.to_array()
# print ther result of `board.to_array()`:
pprint(board.to_array())
Source code in src/bitbully/board.py
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 | |
to_huffman
to_huffman() -> int
Encode the current board position into a Huffman-compressed byte sequence.
This is a high-level wrapper around
bitbully_core.BoardCore.toHuffman. The returned int encodes the
exact token layout and the side to move using the same format as
the BitBully opening databases.
The encoding is:
- Deterministic: the same position always yields the same byte sequence.
- Compact: suitable for storage (of positions with little number of tokens), or lookups in the BitBully database format.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
A Huffman-compressed representation of the current board |
int
|
state. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the position does not contain exactly 8 or 12 tokens, as the Huffman encoding is only defined for these cases. |
Example
Encode a position and verify that equivalent positions have the same Huffman code:
Expected output:
Source code in src/bitbully/board.py
to_string
to_string() -> str
Returns a human-readable ASCII representation of the board.
The returned string shows the current board position as a 6x7 grid,
laid out exactly as it would appear when you print a Board instance:
- 6 lines of text, one per row (top row first, bottom row last)
- 7 entries per row, separated by two spaces
_represents an empty cellXrepresents a token from Player 1 (yellow)Orepresents a token from Player 2 (red)
This is useful when you want to explicitly capture the board as a string
(e.g., for logging, debugging, or embedding into error messages) instead
of relying on print(board) or repr(board).
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A multi-line ASCII string representing the board state. |
Example
Using to_string() on an empty board:
Expected output:
Source code in src/bitbully/board.py
uid
uid() -> int
Returns a unique identifier for the current board state.
The UID is a deterministic integer computed from the internal bitboard representation of the position. It is stable, position-based, and uniquely tied to the exact token layout and the side to move.
Key properties:
- Boards with the same configuration (tokens + player to move) always produce the same UID.
- Any change to the board (e.g., after a legal move) will almost always result in a different UID.
- Copies of a board created via the copy constructor or
Board.copy()naturally share the same UID as long as their states remain identical.
Unlike __hash__(), the UID is not optimized for hash-table dispersion.
For use in transposition tables, caching, or dictionary/set keys,
prefer __hash__() since it provides a higher-quality hash distribution.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
A unique integer identifier for the board state. |
Example
UID is an integer and not None:
Example
UID changes when the position changes:
Example
Copies share the same UID while they are identical:
import bitbully as bb
board = bb.Board("0123")
# Create an independent copy of the same position.
board_copy = board.copy()
assert board is not board_copy # Different objects
assert board == board_copy # Same position
assert board.uid() == board_copy.uid() # Same UID
# After modifying the copy, they diverge.
assert board_copy.play(4)
assert board != board_copy
assert board.uid() != board_copy.uid()
Example
Different move sequences leading to the same position share the same UID:
import bitbully as bb
board_1 = bb.Board("01234444")
board_2 = bb.Board("44440123")
assert board_1 is not board_2 # Different objects
assert board_1 == board_2 # Same position
assert board_1.uid() == board_2.uid() # Same UID
# After modifying the copy, they diverge.
assert board_1.play(4)
assert board_1 != board_2
assert board_1.uid() != board_2.uid()
Source code in src/bitbully/board.py
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 | |
winner
winner() -> int | None
Returns the winning player, if the game has been won.
This helper interprets the current board under the assumption that Board.has_win indicates the last move created a winning configuration. In that case, the winner is the previous player:
- If it is currently Player 1's turn, then Player 2 must have just won.
- If it is currently Player 2's turn, then Player 1 must have just won.
If there is no winner (i.e. Board.has_win is False),
this method returns None.
Returns:
| Type | Description |
|---|---|
int | None
|
int | None:
The winning player, or
|
Example
Detecting a winner:
import bitbully as bb
# Player 1 wins with a horizontal line at the bottom.
board = bb.Board()
assert board.play("1122334")
assert board.has_win()
assert board.is_game_over()
# It is now Player 2's turn to move next...
assert board.current_player() == 2
# ...which implies Player 1 must be the winner.
assert board.winner() == 1
Example
No winner yet:
-
BitBully API Reference
boardBoardis_game_over