Object-Oriented Checkers Engine and Move Validator

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement an object-oriented engine for two-player American checkers on an 8 x 8 grid using the classes and signatures declared in starter.py.

Board Geometry and Pieces

  • Coordinates use 0-based Square = (row, col) pairs where row = 0 is the top edge and col = 0 is the left edge (SIZE = 8).
  • Pieces occupy only the 32 dark squares where (row + col) % 2 == 1.
  • Player.BLACK ("b") begins on the dark squares of rows 5..7 (12 regular pieces), advances upward (forward == -1), promotes on king_row == 0, and takes the opening turn.
  • Player.WHITE ("w") begins on the dark squares of rows 0..2 (12 regular pieces), advances downward (forward == 1), and promotes on king_row == 7.
  • Piece(owner, king=False) is an immutable value whose symbol is 'b' or 'w' for regular men and 'B' or 'W' for promoted kings.
  • Board manages raw 8 x 8 cell storage without game rules:
    • get(square) and put(square, piece) access a single square, raising ValueError if square is not a 2-tuple of exact int values in 0..7 (booleans, floats, lists, and out-of-range integers must be rejected) or if piece is neither Piece nor None.
    • to_rows() serializes the grid into 8 eight-character strings using '.' for empty cells and 'b', 'w', 'B', 'W' for pieces. Board.from_rows(rows) parses that representation (raising ValueError on malformed dimensions or characters), and Board.initial() constructs the standard 24-piece starting board.

Game Rules, Validation, and State Transitions

  • Game(board=None, turn=Player.BLACK) initializes a match (defaulting to Board.initial() when board is None):
    • Raise ValueError if board is not a Board, turn is not a Player, any piece rests on a light square ((row + col) % 2 == 0), either player has more than MAX_PIECES = 12 pieces, an uncrowned piece already sits on its king_row, or turn.opponent has zero pieces.
    • Keep a private copy of board so external edits after construction cannot alter the match, and immediately end the game if turn begins with zero legal moves.
  • Steps and captures:
    • Regular pieces move diagonally forward by one cell ((r + forward, c ± 1)) into an empty square; kings move diagonally forward or backward ((r ± 1, c ± 1)).
    • A capture jumps diagonally along an allowed direction for that piece over an adjacent enemy piece at middle = (r + dr, c + dc) onto an empty landing square end = (r + 2*dr, c + 2*dc), removing the enemy piece and returning Move(start, end, captured=middle).
    • Compulsory capture: Whenever at least one capture exists for turn, ordinary non-capturing steps are illegal.
  • Multi-jumps and crowning:
    • Each move(start, end) call executes a single step or a single jump and appends the resulting Move to history.
    • When an uncrowned piece lands on its king_row, it is crowned (king=True), which immediately ends the turn even if a king capture would exist from that square.
    • After a capture that did not crown the piece, if at least one further capture is available from end, turn remains unchanged and jumping_from becomes end; only continuation captures from jumping_from are legal until no more jumps remain from the active piece's square.
  • Game-ending conditions:
    • If the side to move has zero legal moves at the start of a turn, is_over becomes True, winner becomes turn.opponent, turn stays on the stuck player, legal_moves() returns [], and end_reason becomes "no_pieces" (if that player has no pieces left) or "no_moves" (if remaining pieces are all blocked).
  • Illegal move error priority:
    • On any invalid move(start, end) call, leave all state unchanged and raise IllegalMoveError(code, message) using the first matching code below:
      1. "game_over" — the match has already ended.
      2. "bad_square" — start or end is not a 2-tuple of exact int values in 0..7.
      3. "no_piece" — start is empty.
      4. "not_your_turn" — start holds an opponent piece.
      5. "must_continue_jump" — jumping_from is set and start -> end is not a legal continuation capture from jumping_from.
      6. "must_capture" — at least one capture exists for turn, and start -> end is not a legal capture.
      7. "occupied" — end already holds a piece.
      8. "illegal_move" — any other invalid geometry or direction.

Examples

Example 1

Input:

board = Board.from_rows([
    "...w....",
    "........",
    "........",
    "..w.....",
    "........",
    "....w...",
    ".....b..",
    "b.......",
])
game = Game(board, Player.BLACK)

Operations & Output:

  • game.legal_moves() returns [Move(start=(6, 5), end=(4, 3), captured=(5, 4))].
  • game.move((7, 0), (6, 1)) raises IllegalMoveError with code == "must_capture".
  • game.move((6, 5), (4, 3)) returns Move((6, 5), (4, 3), captured=(5, 4)), leaving game.turn == Player.BLACK and game.jumping_from == (4, 3).
  • game.move((7, 0), (6, 1)) now raises IllegalMoveError with code == "must_continue_jump".
  • game.move((4, 3), (2, 1)) returns Move((4, 3), (2, 1), captured=(3, 2)), setting game.jumping_from == None and game.turn == Player.WHITE.

Explanation: Black must jump (5, 4) from (6, 5) rather than stepping (7, 0) -> (6, 1). Landing on (4, 3) exposes a second jump over (3, 2) to (2, 1), so Black retains the turn with jumping_from == (4, 3) until completing the second jump.

Example 2

Input:

board = Board.from_rows([
    "........",
    "........",
    "........",
    "........",
    "........",
    "..w.....",
    "...b.b..",
    "........",
])
game = Game(board, Player.WHITE)

Operations & Output:

  • game.move((5, 2), (7, 4)) captures (6, 3), crowns a White king ('W') at (7, 4), sets game.jumping_from == None, and switches game.turn to Player.BLACK.
  • game.move((6, 5), (5, 4)) steps Black's remaining piece upward and passes game.turn to Player.WHITE.
  • game.move((7, 4), (6, 3)) steps White's new king backward from row 7 to row 6.

Explanation: Landing an uncrowned White man on king_row == 7 promotes it to 'W' and halts its turn immediately—even though (6, 5) sits adjacent with (5, 6) open. On White's next turn, the promoted king can step backward toward row 0.

Example 3

Input:

# Position A: capturing the last opponent piece
game_a = Game(Board.from_rows([
    "........",
    "........",
    "........",
    "..w.....",
    ".b......",
    "........",
    "........",
    "........",
]), Player.BLACK)

# Position B: blocking the opponent's sole piece
game_b = Game(Board.from_rows([
    "........",
    "........",
    "........",
    "........",
    "........",
    "........",
    ".....B.w",
    "........",
]), Player.BLACK)

Operations & Output:

  • game_a.move((4, 1), (2, 3)) sets game_a.is_over == True, game_a.winner == Player.BLACK, game_a.end_reason == "no_pieces", and game_a.legal_moves() == []; any further game_a.move(...) raises IllegalMoveError with code == "game_over".
  • game_b.move((6, 5), (7, 6)) sets game_b.is_over == True, game_b.winner == Player.BLACK, and game_b.end_reason == "no_moves".

Explanation: In game_a, White loses its final piece on (3, 2). In game_b, Black's king steps onto (7, 6), leaving White's man at (6, 7) wedged against the right and bottom edges with zero legal moves.

Constraints

  • Board dimensions are fixed at 8 x 8 (0 <= row, col < 8), with at most 12 pieces per side (MAX_PIECES = 12).
  • Coordinate validation must reject bool (True/False), float, negative integers, and non-tuple containers.
  • Game.history and Game.rows() must return copies so external mutation cannot corrupt internal state.
  • Standard library only; every operation (legal_moves, move, piece_at, rows) should run in O(1) time on the 64-square board.

Step-by-step walkthrough

  1. Clarify the rules and board geometry

    Before writing code, make sure every geometric and state-transition convention matches the required interface:

    • Coordinates and playable squares: Squares are 0-based (row, col) pairs with row = 0 at the top edge. Only the 32 dark squares where (row + col) % 2 == 1 are used.
    • Sides and directions: Black starts with 12 regular pieces ("men") on rows 5..7, moves upward (d_row = -1 toward row 0), and moves first. White starts with 12 men on rows 0..2 and moves downward (d_row = +1 toward row 7).
    • Compulsory captures and multi-jumps: Under standard American checkers rules, if any capture is available anywhere on the board, the active player must capture rather than take a plain step. After landing a capture, that same piece must keep jumping while another capture exists from its new square (each jump is one move(start, end) call).
    • Promotion (crowning) ends the turn: When a regular man lands on its opponent's back row (row 0 for Black, row 7 for White), it promotes to a king (B or W) and its turn ends immediately — even if a backward capture would be open to the new king.
    • Kings and game over: Kings step or jump one diagonal square forward or backward (not long-range "flying" kings). A player who begins a turn with zero legal moves (either zero pieces left or every piece blocked) loses immediately.
           col: 0   1   2   3   4   5   6   7
    row 0:      .   w   .   w   .   w   .   w    <- White starts on rows 0..2, moves DOWN (+1)
    row 1:      w   .   w   .   w   .   w   .       Black promotes to King ('B') on row 0
    row 2:      .   w   .   w   .   w   .   w
    row 3:      .   .   .   .   .   .   .   .
    row 4:      .   .   .   .   .   .   .   .
    row 5:      b   .   b   .   b   .   b   .    <- Black starts on rows 5..7, moves UP (-1)
    row 6:      .   b   .   b   .   b   .   b       White promotes to King ('W') on row 7
    row 7:      b   .   b   .   b   .   b   .       Black moves first
    
  2. Split responsibilities into focused classes

    A clean object-oriented design keeps grid storage separate from game rules so neither class becomes a tangled monolith:

    Class               Responsibility
    ------------------  -------------------------------------------------------------------
    Player (Enum)       BLACK / WHITE; knows opponent, forward row delta, and king_row
    Piece (frozen)      Immutable value (owner + king flag); returns allowed diagonal steps
    Move (frozen)       Immutable record (start, end, optional captured square)
    IllegalMoveError    Exception carrying a stable machine-readable `code` + human message
    Board               8 x 8 grid storage, bounds checks, text serialization; ZERO rules
    Game                Owns private Board, turn, multi-jump state, winner, history, rules
    

    Why this separation works so well:

    • Board handles geometry; Game owns rules. You can construct or print a Board in unit tests with 8 short strings (".w.w.w.w"), and changing a game rule (such as optional captures) touches only Game.
    • Immutable value objects (@dataclass(frozen=True)) let Piece and Move be returned to callers or stored in history without any risk of someone mutating them afterward.
    • Structured errors (error.code) let UIs, network servers, and unit tests branch on stable codes like "must_capture" instead of matching fragile English phrasing.
  3. Define the public API and error-code priority

    Another engineer can drive an entire match using just Game(), legal_moves(), move(start, end), and read-only state properties:

    # Public usage sketch (implemented in the steps below):
    # game = Game()                                    # standard start, Black to move
    # options = game.legal_moves()                     # list of Move(start, end, captured)
    # applied = game.move((5, 4), (4, 5))              # returns Move or raises IllegalMoveError
    # state = (game.turn, game.winner, game.is_over)   # read-only properties
    

    When game.move(start, end) rejects an input, it checks failure reasons in a deterministic priority order from outermost to innermost and leaves the game state completely untouched:

    Priority  Error code           Condition
    --------  -------------------  ----------------------------------------------------------
    1         game_over            The game has already ended
    2         bad_square           start or end is not a 2-tuple of exact ints in 0..7
    3         no_piece             start square is empty
    4         not_your_turn        Piece on start belongs to the other player
    5         must_continue_jump   A multi-jump is active and this move is not its next jump
    6         must_capture         A capture exists on the board, and this move is a plain step
    7         occupied             end square is already occupied
    8         illegal_move         Not diagonal, wrong distance, or backward move by a man
    
  4. Build the value types and the 8 x 8 board

    Putting forward and king_row on Player eliminates repetitive if player == BLACK branches everywhere else. Similarly, Piece.directions() is the single place that knows regular men get 2 forward diagonals while kings get all 4 diagonals.

    Pay special attention to two subtle Python traps in Board:

    1. bool is a subclass of int in Python (isinstance(True, int) is True), and (5.0, 2.0) == (5, 2). Checking type(coord) is not int rejects both True and 5.0.
    2. Negative list indices wrap around in Python (cells[-1] reads row 7!). Both Board.get and Board.put validate Board.is_valid_square(square) before indexing self._cells.
    from typing import List, Optional, Tuple
    from dataclasses import dataclass
    from enum import Enum
    
    # Board coordinates are 0-based (row, col) pairs; row 0 is the top edge (White's home side).
    Square = Tuple[int, int]
    SIZE = 8
    MAX_PIECES = 12
    
    
    class Player(Enum):
        # Black starts on rows 5..7, moves upward toward row 0, and always moves first.
        BLACK = "b"
        # White starts on rows 0..2 and moves downward toward row 7.
        WHITE = "w"
    
        @property
        def opponent(self) -> "Player":
            if self is Player.BLACK:
                return Player.WHITE
            return Player.BLACK
    
        @property
        def forward(self) -> int:
            """Row delta (+1 or -1) for one forward step by this player."""
            if self is Player.BLACK:
                return -1
            return 1
    
        @property
        def king_row(self) -> int:
            """Far edge row where this player's regular pieces promote to kings."""
            if self is Player.BLACK:
                return 0
            return SIZE - 1
    
    
    @dataclass(frozen=True)
    class Piece:
        owner: Player
        king: bool = False
    
        def directions(self) -> List[Tuple[int, int]]:
            """Allowed diagonal (d_row, d_col) step vectors: 2 for a man, 4 for a king."""
            row_steps = [self.owner.forward]
            if self.king:
                row_steps.append(-self.owner.forward)
            deltas = []
            for dr in row_steps:
                for dc in (-1, 1):
                    deltas.append((dr, dc))
            return deltas
    
        @property
        def symbol(self) -> str:
            if self.king:
                return self.owner.value.upper()
            return self.owner.value
    
    
    @dataclass(frozen=True)
    class Move:
        start: Square
        end: Square
        captured: Optional[Square] = None
    
    
    class IllegalMoveError(Exception):
        """A rejected move. `code` is stable for programs; the message is for people."""
    
        def __init__(self, code: str, message: str):
            super().__init__(f"{code}: {message}")
            self.code = code
    
    
    class Board:
        """The 8 x 8 grid. Each square is empty (None) or holds a Piece. Knows no rules."""
    
        def __init__(self):
            self._cells: List[List[Optional[Piece]]] = []
            for _ in range(SIZE):
                self._cells.append([None] * SIZE)
    
        @staticmethod
        def in_bounds(square: Square) -> bool:
            return 0 <= square[0] < SIZE and 0 <= square[1] < SIZE
    
        @staticmethod
        def is_valid_square(square) -> bool:
            """True only for a 2-tuple of exact ints in 0..7 (rejects bools and floats)."""
            if not isinstance(square, tuple) or len(square) != 2:
                return False
            for coord in square:
                if type(coord) is not int:
                    return False
            return Board.in_bounds(square)
    
        @staticmethod
        def is_dark(square: Square) -> bool:
            return (square[0] + square[1]) % 2 == 1
    
        def get(self, square: Square) -> Optional[Piece]:
            if not Board.is_valid_square(square):
                raise ValueError(f"{square!r} is not a valid (row, col) square in 0..{SIZE - 1}")
            return self._cells[square[0]][square[1]]
    
        def put(self, square: Square, piece: Optional[Piece]) -> None:
            if not Board.is_valid_square(square):
                raise ValueError(f"{square!r} is not a valid (row, col) square in 0..{SIZE - 1}")
            if piece is not None and not isinstance(piece, Piece):
                raise ValueError(f"piece must be a Piece or None, got {piece!r}")
            self._cells[square[0]][square[1]] = piece
    
        def squares_of(self, player: Player) -> List[Square]:
            occupied = []
            for row in range(SIZE):
                for col in range(SIZE):
                    piece = self._cells[row][col]
                    if piece is not None and piece.owner is player:
                        occupied.append((row, col))
            return occupied
    
        def to_rows(self) -> List[str]:
            rows = []
            for row in range(SIZE):
                chars = []
                for piece in self._cells[row]:
                    chars.append("." if piece is None else piece.symbol)
                rows.append("".join(chars))
            return rows
    
        @classmethod
        def from_rows(cls, rows: List[str]) -> "Board":
            if len(rows) != SIZE:
                raise ValueError(f"need {SIZE} rows, got {len(rows)}")
            board = cls()
            for row, text in enumerate(rows):
                if len(text) != SIZE:
                    raise ValueError(f"row {row} must have {SIZE} characters: {text!r}")
                for col, char in enumerate(text):
                    if char == ".":
                        continue
                    lower_char = char.lower()
                    if lower_char not in ("b", "w"):
                        raise ValueError(f"unknown piece {char!r} at {(row, col)}")
                    piece = Piece(owner=Player(lower_char), king=char.isupper())
                    board.put((row, col), piece)
            return board
    
        @classmethod
        def initial(cls) -> "Board":
            return cls.from_rows([
                ".w.w.w.w",
                "w.w.w.w.",
                ".w.w.w.w",
                "........",
                "........",
                "b.b.b.b.",
                ".b.b.b.b",
                "b.b.b.b.",
            ])
    
  5. Guard initial positions and encapsulate game state

    When a caller initializes Game(board, turn) with a custom puzzle board, we protect state consistency in three ways:

    1. Validate invariants on entry (check_consistent): Reject impossible boards with ValueError — any piece on a light square, more than 12 pieces for one side, an uncrowned man sitting on its promotion row, or zero pieces for turn.opponent (meaning the game would already have ended before turn got to move).
    2. Make a defensive copy of board: If Game kept a reference to the caller's Board, the caller could call board.put(...) mid-game and teleport pieces past our rules. Copying via Board.from_rows(board.to_rows()) isolates Game completely.
    3. Check immediately if turn is stuck (_end_if_stuck): If a custom starting board leaves the player to move completely blocked, is_over is True right away.
    def check_consistent(board: Board, turn: Player) -> None:
        """Reject custom boards that violate basic checkers invariants."""
        for player in Player:
            squares = board.squares_of(player)
            if len(squares) > MAX_PIECES:
                raise ValueError(f"{player.name} has {len(squares)} pieces; the maximum is {MAX_PIECES}")
            for square in squares:
                if not Board.is_dark(square):
                    raise ValueError(f"piece on light square {square}")
                piece = board.get(square)
                if not piece.king and square[0] == player.king_row:
                    raise ValueError(f"{player.name} man on {square} should have been crowned")
        if not board.squares_of(turn.opponent):
            raise ValueError(f"{turn.opponent.name} has no pieces, so the game ended before {turn.name}'s turn")
    
  6. Generate legal steps, compulsory captures, and multi-jumps

    Instead of duplicating rule checks inside move(), we compute all legal moves in one place (_moves_for_turn). That makes legal_moves(), move(), and game-over detection guaranteed to agree:

    Plain step along (dr, dc):            Capture jump along (dr, dc):
      start = (r, c)                        start  = (r, c)          [our piece]
      end   = (r + dr, c + dc) [empty]      middle = (r + dr, c + dc) [opponent piece]
                                            target = (r + 2*dr, c + 2*dc) [empty & on board]
    
    • Mid multi-jump (_jumping_from is not None): Only the piece at _jumping_from may move, and only via _captures_from.
    • Start of a turn (_jumping_from is None): Gather all captures and all steps across the current player's pieces. If captures is non-empty, return captures only (compulsory capture); otherwise return steps.
    def _moves_for_turn(self) -> List[Move]:
        if self._jumping_from is not None:
            return self._captures_from(self._jumping_from)
    
        captures = []
        steps = []
        for square in self._board.squares_of(self._turn):
            captures.extend(self._captures_from(square))
            steps.extend(self._steps_from(square))
        if captures:
            return captures
        return steps
    
    
    def _steps_from(self, square: Square) -> List[Move]:
        piece = self._board.get(square)
        result = []
        for dr, dc in piece.directions():
            target = (square[0] + dr, square[1] + dc)
            if Board.in_bounds(target) and self._board.get(target) is None:
                result.append(Move(square, target))
        return result
    
    
    def _captures_from(self, square: Square) -> List[Move]:
        piece = self._board.get(square)
        result = []
        for dr, dc in piece.directions():
            middle = (square[0] + dr, square[1] + dc)
            target = (square[0] + 2 * dr, square[1] + 2 * dc)
            if not Board.in_bounds(target) or self._board.get(target) is not None:
                continue
            jumped = self._board.get(middle)
            if jumped is not None and jumped.owner is not piece.owner:
                result.append(Move(square, target, captured=middle))
        return result
    
  7. Validate moves and apply state transitions

    move(start, end) runs in three clean phases: 1. Reject game_over or malformed coordinates (bad_square) before touching the board. 2. Search _moves_for_turn() for a matching (start, end) pair. If found, call _apply(candidate) and return it. 3. If not found, call _explain(start, end, legal) to return the exact IllegalMoveError without having modified a single cell.

    Inside _apply(move): - Move the piece from move.start to move.end, clearing move.captured if present. - Promote the piece if not piece.king and move.end[0] == piece.owner.king_row. - Keep the turn (self._jumping_from = move.end) only when all three hold: move.captured is not None, not crowned, and self._captures_from(move.end) is non-empty. Otherwise clear _jumping_from, flip _turn, and run _end_if_stuck().

    def _apply(self, move: Move) -> None:
        piece = self._board.get(move.start)
        self._board.put(move.start, None)
        if move.captured is not None:
            self._board.put(move.captured, None)
    
        crowned = not piece.king and move.end[0] == piece.owner.king_row
        if crowned:
            piece = Piece(piece.owner, king=True)
        self._board.put(move.end, piece)
        self._history.append(move)
    
        if move.captured is not None and not crowned and self._captures_from(move.end):
            self._jumping_from = move.end
            return
    
        self._jumping_from = None
        self._turn = self._turn.opponent
        self._end_if_stuck()
    
  8. Trace Example 1's compulsory double-jump step by step

    Consider Example 1 from the problem statement with Black (b) moving upward:

           col: 0 1 2 3 4 5 6 7
    row 0:      . . . w . . . .
    row 1:      . . . . . . . .
    row 2:      . . . . . . . .     <- 2nd jump lands at (2, 1)
    row 3:      . . w . . . . .     <- 2nd jumped White man at (3, 2)
    row 4:      . . . . . . . .     <- 1st jump lands at (4, 3)
    row 5:      . . . . w . . .     <- 1st jumped White man at (5, 4)
    row 6:      . . . . . b . .     <- Black man starts at (6, 5)
    row 7:      b . . . . . . .     <- Other Black man at (7, 0)
    
    1. Before move 1: legal_moves() finds [Move((6, 5), (4, 3), captured=(5, 4))]. If Black tries stepping (7, 0) -> (6, 1), move raises must_capture and changes nothing.
    2. First jump move((6, 5), (4, 3)): (5, 4) is removed and b lands on (4, 3). Since (4, 3) is not row 0 (not crowned) and _captures_from((4, 3)) sees (4, 3) -> (2, 1) over (3, 2), jumping_from becomes (4, 3) and turn stays Player.BLACK.
    3. Mid multi-jump: Trying (7, 0) -> (6, 1) or a non-jump step (4, 3) -> (3, 4) raises must_continue_jump; White trying (0, 3) -> (1, 2) raises not_your_turn.
    4. Second jump move((4, 3), (2, 1)): (3, 2) is removed, _captures_from((2, 1)) is empty, jumping_from resets to None, and turn switches to Player.WHITE (who still has (0, 3) -> (1, 2) and (0, 3) -> (1, 4), so the game continues).
  9. Complete solution

    from typing import List, Optional, Tuple
    from dataclasses import dataclass
    from enum import Enum
    
    # Board coordinates are 0-based (row, col) pairs; row 0 is the top edge (White's home side).
    Square = Tuple[int, int]
    SIZE = 8
    MAX_PIECES = 12
    
    
    class Player(Enum):
        # Black starts on rows 5..7, moves upward toward row 0, and always moves first.
        BLACK = "b"
        # White starts on rows 0..2 and moves downward toward row 7.
        WHITE = "w"
    
        @property
        def opponent(self) -> "Player":
            if self is Player.BLACK:
                return Player.WHITE
            return Player.BLACK
    
        @property
        def forward(self) -> int:
            """Row delta (+1 or -1) for one forward step by this player."""
            if self is Player.BLACK:
                return -1
            return 1
    
        @property
        def king_row(self) -> int:
            """Far edge row where this player's regular pieces promote to kings."""
            if self is Player.BLACK:
                return 0
            return SIZE - 1
    
    
    # Frozen dataclasses make Piece and Move immutable values safe to share and log.
    @dataclass(frozen=True)
    class Piece:
        owner: Player
        king: bool = False
    
        def directions(self) -> List[Tuple[int, int]]:
            """Allowed diagonal (d_row, d_col) step vectors: 2 for a man, 4 for a king."""
            row_steps = [self.owner.forward]
            if self.king:
                row_steps.append(-self.owner.forward)
            deltas = []
            for dr in row_steps:
                for dc in (-1, 1):
                    deltas.append((dr, dc))
            return deltas
    
        @property
        def symbol(self) -> str:
            if self.king:
                return self.owner.value.upper()
            return self.owner.value
    
    
    @dataclass(frozen=True)
    class Move:
        start: Square
        end: Square
        captured: Optional[Square] = None  # middle square jumped over during a capture, else None
    
    
    class IllegalMoveError(Exception):
        """A rejected move. `code` is stable for programs; the message is for people."""
    
        def __init__(self, code: str, message: str):
            super().__init__(f"{code}: {message}")
            self.code = code
    
    
    class Board:
        """The 8 x 8 grid. Each square is empty (None) or holds a Piece. Knows no rules."""
    
        def __init__(self):
            # _cells[row][col] stores Optional[Piece] for each of the 8 x 8 board squares.
            self._cells: List[List[Optional[Piece]]] = []
            for _ in range(SIZE):
                self._cells.append([None] * SIZE)
    
        @staticmethod
        def in_bounds(square: Square) -> bool:
            return 0 <= square[0] < SIZE and 0 <= square[1] < SIZE
    
        @staticmethod
        def is_valid_square(square) -> bool:
            """True only for a 2-tuple of exact ints in 0..7 (rejects bools and floats)."""
            if not isinstance(square, tuple) or len(square) != 2:
                return False
            for coord in square:
                # Use `type(coord) is not int` because `isinstance(True, int)` is True in Python!
                if type(coord) is not int:
                    return False
            return Board.in_bounds(square)
    
        @staticmethod
        def is_dark(square: Square) -> bool:
            # Playable checkers squares have odd (row + col), e.g., (7, 0) and (0, 1).
            return (square[0] + square[1]) % 2 == 1
    
        def get(self, square: Square) -> Optional[Piece]:
            # Validate bounds so negative indices like -1 never wrap around to the back row.
            if not Board.is_valid_square(square):
                raise ValueError(f"{square!r} is not a valid (row, col) square in 0..{SIZE - 1}")
            return self._cells[square[0]][square[1]]
    
        def put(self, square: Square, piece: Optional[Piece]) -> None:
            if not Board.is_valid_square(square):
                raise ValueError(f"{square!r} is not a valid (row, col) square in 0..{SIZE - 1}")
            if piece is not None and not isinstance(piece, Piece):
                raise ValueError(f"piece must be a Piece or None, got {piece!r}")
            self._cells[square[0]][square[1]] = piece
    
        def squares_of(self, player: Player) -> List[Square]:
            """All (row, col) squares currently occupied by `player`, in row-major order."""
            occupied = []
            for row in range(SIZE):
                for col in range(SIZE):
                    piece = self._cells[row][col]
                    if piece is not None and piece.owner is player:
                        occupied.append((row, col))
            return occupied
    
        def to_rows(self) -> List[str]:
            """8 strings: '.' empty, 'b' / 'w' a man, 'B' / 'W' a king."""
            rows = []
            for row in range(SIZE):
                chars = []
                for piece in self._cells[row]:
                    chars.append("." if piece is None else piece.symbol)
                rows.append("".join(chars))
            return rows
    
        @classmethod
        def from_rows(cls, rows: List[str]) -> "Board":
            """The inverse of to_rows. Raises ValueError for a malformed picture."""
            if len(rows) != SIZE:
                raise ValueError(f"need {SIZE} rows, got {len(rows)}")
            board = cls()
            for row, text in enumerate(rows):
                if len(text) != SIZE:
                    raise ValueError(f"row {row} must have {SIZE} characters: {text!r}")
                for col, char in enumerate(text):
                    if char == ".":
                        continue
                    lower_char = char.lower()
                    if lower_char not in ("b", "w"):
                        raise ValueError(f"unknown piece {char!r} at {(row, col)}")
                    piece = Piece(owner=Player(lower_char), king=char.isupper())
                    board.put((row, col), piece)
            return board
    
        @classmethod
        def initial(cls) -> "Board":
            """Standard starting setup: 12 White men on rows 0..2, 12 Black men on rows 5..7."""
            return cls.from_rows([
                ".w.w.w.w",
                "w.w.w.w.",
                ".w.w.w.w",
                "........",
                "........",
                "b.b.b.b.",
                ".b.b.b.b",
                "b.b.b.b.",
            ])
    
    
    def check_consistent(board: Board, turn: Player) -> None:
        """Reject custom boards that violate basic checkers invariants."""
        for player in Player:
            squares = board.squares_of(player)
            if len(squares) > MAX_PIECES:
                raise ValueError(f"{player.name} has {len(squares)} pieces; the maximum is {MAX_PIECES}")
            for square in squares:
                if not Board.is_dark(square):
                    raise ValueError(f"piece on light square {square}")
                piece = board.get(square)
                # Any regular man reaching its king_row would already have been promoted.
                if not piece.king and square[0] == player.king_row:
                    raise ValueError(f"{player.name} man on {square} should have been crowned")
        # If the player NOT to move has zero pieces, the game already ended before this turn!
        if not board.squares_of(turn.opponent):
            raise ValueError(f"{turn.opponent.name} has no pieces, so the game ended before {turn.name}'s turn")
    
    
    class Game:
        """One game of checkers: owns the board, the turn and the rules.
    
        Black moves first. Men step one square diagonally forward; kings also backward.
        A capture jumps an adjacent opponent piece into the empty square beyond it and is
        compulsory. After a capture the same piece must keep jumping while it can, unless that
        capture crowned it, which ends the turn. A player with no legal move (for example, no
        pieces) loses.
        """
    
        def __init__(self, board: Optional[Board] = None, turn: Player = Player.BLACK):
            if board is None:
                board = Board.initial()
            if not isinstance(board, Board):
                raise ValueError(f"board must be a Board, got {board!r}")
            if not isinstance(turn, Player):
                raise ValueError(f"turn must be a Player, got {turn!r}")
            check_consistent(board, turn)
    
            # Store a private defensive copy so caller edits to `board` cannot bypass rules.
            self._board = Board.from_rows(board.to_rows())
            self._turn = turn
            # _jumping_from holds the square of the active piece during a multi-jump, else None.
            self._jumping_from: Optional[Square] = None
            self._winner: Optional[Player] = None
            self._end_reason: Optional[str] = None
            # _history records every applied single step or single jump in chronological order.
            self._history: List[Move] = []
            # Detect immediately if the starting position already leaves `turn` with no moves.
            self._end_if_stuck()
    
        # ----- read-only state -----
    
        @property
        def turn(self) -> Player:
            """The player to move (after the game ends: the player who lost)."""
            return self._turn
    
        @property
        def winner(self) -> Optional[Player]:
            return self._winner
    
        @property
        def end_reason(self) -> Optional[str]:
            """None while playing, then "no_pieces" or "no_moves"."""
            return self._end_reason
    
        @property
        def is_over(self) -> bool:
            return self._winner is not None
    
        @property
        def jumping_from(self) -> Optional[Square]:
            """The square of a piece in the middle of a multi-jump, else None."""
            return self._jumping_from
    
        @property
        def history(self) -> List[Move]:
            return list(self._history)
    
        def piece_at(self, square: Square) -> Optional[Piece]:
            if not Board.is_valid_square(square):
                raise ValueError(f"{square!r} is not a (row, col) pair of ints in 0..{SIZE - 1}")
            return self._board.get(square)
    
        def rows(self) -> List[str]:
            return self._board.to_rows()
    
        # ----- move generation, validation, and state transition -----
    
        def legal_moves(self) -> List[Move]:
            """Every move the player to move may make now; empty once the game is over."""
            if self.is_over:
                return []
            return self._moves_for_turn()
    
        def move(self, start: Square, end: Square) -> Move:
            """Make one step or one jump. On an illegal move, raise IllegalMoveError and change nothing."""
            # Phase 1: check game status and coordinate types before touching the board.
            if self.is_over:
                raise IllegalMoveError("game_over", f"the game is over; {self._winner.name} won")
            for square in (start, end):
                if not Board.is_valid_square(square):
                    raise IllegalMoveError("bad_square", f"{square!r} is not a (row, col) pair of ints in 0..{SIZE - 1}")
    
            # Phase 2: validate against the single authoritative list of legal moves.
            legal = self._moves_for_turn()
            for candidate in legal:
                if candidate.start == start and candidate.end == end:
                    self._apply(candidate)
                    return candidate
    
            # Phase 3: no state changed; diagnose the most specific reason for rejection.
            raise self._explain(start, end, legal)
    
        def _moves_for_turn(self) -> List[Move]:
            # Mid multi-jump: only the piece on _jumping_from may move, and only by capturing.
            if self._jumping_from is not None:
                return self._captures_from(self._jumping_from)
    
            captures = []
            steps = []
            for square in self._board.squares_of(self._turn):
                captures.extend(self._captures_from(square))
                steps.extend(self._steps_from(square))
            # Compulsory capture rule: if any capture exists anywhere, ordinary steps are illegal.
            if captures:
                return captures
            return steps
    
        def _steps_from(self, square: Square) -> List[Move]:
            piece = self._board.get(square)
            result = []
            for dr, dc in piece.directions():
                target = (square[0] + dr, square[1] + dc)
                if Board.in_bounds(target) and self._board.get(target) is None:
                    result.append(Move(square, target))
            return result
    
        def _captures_from(self, square: Square) -> List[Move]:
            piece = self._board.get(square)
            result = []
            for dr, dc in piece.directions():
                middle = (square[0] + dr, square[1] + dc)
                target = (square[0] + 2 * dr, square[1] + 2 * dc)
                # Landing square must be on the board and empty; middle square must hold an enemy.
                if not Board.in_bounds(target) or self._board.get(target) is not None:
                    continue
                jumped = self._board.get(middle)
                if jumped is not None and jumped.owner is not piece.owner:
                    result.append(Move(square, target, captured=middle))
            return result
    
        def _explain(self, start: Square, end: Square, legal: List[Move]) -> IllegalMoveError:
            """Return the highest-priority IllegalMoveError explaining why start -> end failed."""
            piece = self._board.get(start)
            if piece is None:
                return IllegalMoveError("no_piece", f"there is no piece on {start}")
            if piece.owner is not self._turn:
                return IllegalMoveError("not_your_turn", f"it is {self._turn.name}'s turn")
            if self._jumping_from is not None:
                return IllegalMoveError("must_continue_jump",
                                        f"the piece on {self._jumping_from} must keep jumping")
            # Since captures and steps are never mixed in `legal`, checking legal[0] suffices.
            if legal and legal[0].captured is not None:
                options = [f"{m.start}->{m.end}" for m in legal]
                return IllegalMoveError("must_capture", "a capture is compulsory: " + ", ".join(options))
            if self._board.get(end) is not None:
                return IllegalMoveError("occupied", f"{end} is not empty")
            return IllegalMoveError("illegal_move",
                                    "move one square diagonally (men only forward) or jump an opponent piece")
    
        def _apply(self, move: Move) -> None:
            piece = self._board.get(move.start)
            self._board.put(move.start, None)
            if move.captured is not None:
                self._board.put(move.captured, None)
    
            # Promote a regular man that reaches its opponent's back row.
            crowned = not piece.king and move.end[0] == piece.owner.king_row
            if crowned:
                piece = Piece(piece.owner, king=True)
            self._board.put(move.end, piece)
            self._history.append(move)
    
            # Keep the turn ONLY if this move captured, did NOT crown, and can jump again.
            if move.captured is not None and not crowned and self._captures_from(move.end):
                self._jumping_from = move.end
                return
    
            self._jumping_from = None
            self._turn = self._turn.opponent
            self._end_if_stuck()
    
        def _end_if_stuck(self) -> None:
            """End the game if the current player to move has zero legal moves."""
            if self._moves_for_turn():
                return
            self._winner = self._turn.opponent
            if self._board.squares_of(self._turn):
                self._end_reason = "no_moves"
            else:
                self._end_reason = "no_pieces"
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a referee officiating a match on a wooden checkerboard. The physical board (Board) only knows which piece sits on each of the 64 squares and has no idea whose turn it is or what makes a move legal. The referee (Game) holds a private copy of that board plus a clipboard tracking the active player, whether a piece is mid-way through a multi-jump, and one master list of legal moves for the current moment.

A common beginner trap is writing one set of if checks inside move() to validate an attempted move while writing separate logic for legal_moves() and game-over detection, or mutating the grid halfway through checking a move. Those duplicate rule checks quickly drift out of sync (often missing forced captures or multi-jump continuations), and partial edits leave a corrupted board whenever an exception is raised. Making _moves_for_turn() the single source of truth — one authoritative function that every check consults — guarantees that validation, UI move hints, and game-over detection always agree, while mutating state only after validation passes.

Trace 4 short actions from Example 1 when Black has men at (6, 5) and (7, 0), and White has men at (5, 4), (3, 2), and (0, 3): 1. Compulsory capture check: _moves_for_turn() scans Black's pieces, finds jump (6, 5) -> (4, 3) over (5, 4), and discards (7, 0)'s plain step. 2. Rejected step: Calling game.move((7, 0), (6, 1)) sees the move is not in legal, diagnoses must_capture, and leaves the board untouched. 3. First jump: Calling game.move((6, 5), (4, 3)) removes (5, 4), sees (4, 3) can jump (3, 2) -> (2, 1) without having been crowned, sets jumping_from = (4, 3), and keeps turn = BLACK. 4. Second jump: Calling game.move((4, 3), (2, 1)) removes (3, 2), sees no more jumps from (2, 1), clears jumping_from, switches turn to WHITE, and confirms White still has legal moves from (0, 3) before continuing.

Complexity

  • legal_moves() and move() time — O(S), where S = 64 squares (or O(N²) on an N × N board): squares_of scans all 64 grid cells once to find the current player's pieces (at most 12), and for each piece we inspect at most 4 diagonal neighbors in O(1) time. move() computes the current player's legal moves and, when the turn passes, computes the opponent's legal moves once to check whether the opponent is stuck, which is still two passes over 64 cells.
  • Space — O(S + M), where S = 64 cells and M is the number of moves played: Board stores a fixed 8 × 8 grid of 64 references, and Game._history appends one immutable value object (an object whose fields cannot be changed after creation) per executed step or jump.

Edge cases

  • Tricky coordinate types in Python: isinstance(True, int) is True and (5.0, 2.0) == (5, 2), so is_valid_square requires type(coord) is int to reject booleans and floats. Negative indices like -1 are rejected before indexing so Python never wraps cells[-1] around to row 7.
  • Compulsory capture across the board: if piece A can capture, piece B's ordinary diagonal step is rejected with must_capture.
  • Mid multi-jump restrictions: while jumping_from is set, moving any other piece or attempting a plain step with the jumping piece is rejected with must_continue_jump.
  • Crowning halts a jump chain: when a regular man lands on king_row via a capture, it promotes to a king and its turn ends immediately, even if a backward capture is sitting right next to it.
  • Blocked player vs. eliminated player: a side with zero legal moves loses immediately; _end_if_stuck sets end_reason = "no_pieces" when zero pieces remain and "no_moves" when remaining pieces are wedged in.
  • Already-over custom boards and post-game calls: if a custom starting position already leaves turn with no legal moves, Game.__init__ marks is_over = True immediately; any later move() call raises game_over.
  • Impossible custom boards (invariant checks): an invariant is a property that must remain true in every valid state. check_consistent raises ValueError for pieces on light squares, more than 12 pieces on one side, uncrowned men sitting on their promotion row, or zero pieces for turn.opponent.
  • Caller mutating its Board after creating Game: Game.__init__ makes a defensive copy (a private duplicate of the input object) and encapsulates (hides behind read-only methods) its internal grid and history.

Common mistakes

  • Switching turns after every jump instead of keeping turn on the same player until the active piece has no further captures.
  • Allowing a newly crowned piece to keep jumping as a king on the same turn it reached king_row.
  • Duplicating rule checks inside move() separately from legal_moves(), causing legal_moves() to advertise moves that move() rejects (or vice versa).
  • Mutating self._board before confirming the entire move is valid, leaving missing or duplicated pieces after raising IllegalMoveError.
  • Checking only len(pieces) == 0 for game over and missing positions where a player still has pieces on the board that are completely blocked.
  • Storing the caller's Board reference directly or returning self._history without copying, letting external code corrupt game state without going through move().

Follow-up questions

  • How would you extend the engine to detect draws by threefold repetition and non-progressing move limits? Track a frequency dictionary keyed by (tuple(game.rows()), game.turn, game.jumping_from) and declare a draw (end_reason = "repetition", winner = None) when the exact same state appears 3 times. Also keep a counter of consecutive half-moves without a capture or a regular man advancing, resetting it on either event and ending with end_reason = "move_limit" at a configured threshold (such as 80 plies). Update is_over to check self._end_reason is not None instead of self._winner is not None since draws have no winner.

  • What state would you record to support an O(1) undo() method for a UI or minimax game-tree search? For a human UI, replaying history[:-1] from a saved copy of the initial board takes O(M) time and needs zero new state. For an AI minimax search exploring millions of nodes per second, store an undo record per move containing (move, captured_piece, was_crowned, prev_jumping_from, prev_turn, prev_winner, prev_end_reason) — note that captured_piece must remember whether the jumped enemy was a king! Reversing the last record restores all fields in O(1) time.

  • How would you refactor the class hierarchy to support 10 x 10 international draughts alongside 8 x 8 American rules? Pass board size size and a RuleSet strategy object into Game rather than hardcoding SIZE = 8 and American rules. In international draughts, regular men can capture backward, kings "fly" any number of empty squares along a diagonal, captured pieces remain on the board as blockers until the full multi-jump sequence finishes, and players must choose a sequence that captures the maximum number of pieces — which RuleSet can compute via a small depth-first search while Board, Player, IllegalMoveError, and the public Game interface stay unchanged.

Alternative approaches

  • Bitboards: A bitboard packs the 32 playable dark squares into a single 32-bit integer per piece type (black_men, white_men, kings), finding all steps or jumps in parallel with bitwise shifts and masks. It is orders of magnitude faster for deep AI search, at the cost of tricky bit-index math that is much harder to read and maintain than an 8 × 8 grid.
  • Purely functional state (next_state = apply(state, move)): Making GameState itself immutable gives free undo, thread safety, and trivial tree search, and copying 64 references per move is tiny in Python.
  • Whole-turn move API (move([(6, 5), (4, 3), (2, 1)])): Accepting the full path of a multi-jump in a single call avoids keeping jumping_from across network requests, whereas one jump per call is often nicer for interactive board UIs that highlight intermediate squares.

Follow-up questions

Similar questions

More Zipline interview questions

All 4 Zipline questions →