Object-Oriented Animal Chess Engine

Hard · System Design · Software Engineer · Technical Screen

Prompt

Architect an object-oriented game engine for Animal Chess (also known as Jungle or Dou Shou Qi). Your design should model a 9 x 7 two-player grid featuring three special square types—river water, player traps, and player dens—alongside dedicated classes for all eight animals (Rat, Cat, Dog, Wolf, Leopard, Tiger, Lion, and Elephant).

Your design must cover:

  • Piece hierarchy and rules: Represent each animal's rank and movement capabilities (standard orthogonal steps, swimming in water, and leaping straight across river channels), as well as capture interactions across ranks, traps, and water boundaries.
  • Game controller and API: Provide clean methods to set up either the standard 16-piece opening or a custom configuration, place pieces on specific coordinates, execute both single moves and multi-move sequences, and output a human-readable text snapshot of the board and turn status.
  • Verification suite: Include automated test cases covering the standard opening layout, a Lion capturing an enemy piece across a river, and a multi-move turn sequence (including illegal-move handling).

Scope & Expectations

  • Explicit rule contract: State concrete assumptions for house-rule edge cases (for example, Rat-versus-Elephant captures across a riverbank, friendly versus enemy traps, blocked river leaps, and multi-move rollback behavior) before writing classes.
  • Clean object-oriented boundaries: Separate passive grid storage, per-animal movement/rank behavior, and turn/terrain/win enforcement so new rule variants require minimal changes.
  • Safe state transitions: Ensure rejected moves or failed steps inside a multi-move sequence never leave the board, turn indicator, or move log partially mutated.
  • Deterministic test coverage: Supply runnable tests that verify normal opening setup, river-jump captures, special terrain/rank exceptions, and multi-step sequences.

Step-by-step walkthrough

  1. Clarify requirements and pin down the rules

    This is an object-oriented design (low-level system design) question rather than a distributed-servers question. Animal Chess—also known as Jungle or Dou Shou Qi—has a small 9x7 board, so performance is effortless; the real challenge is that eight animals, three special terrains (rivers, traps, and dens), and several rank exceptions all interact. Because real-world house rules vary slightly, start the interview by stating exact rule choices so every class has one clear job and every test checks an agreed rule.

    Functional requirements

    • Model a 9-row by 7-column board containing rivers (water), traps, and dens.
    • Define a dedicated class for each of the eight animals (Rat, Cat, Dog, Wolf, Leopard, Tiger, Lion, and Elephant) encapsulating its strength rank, movement capability, and capture rules.
    • Enforce turn order, movement, capture rules, and all three win conditions.
    • Expose a clean API to start a standard or empty game, place and remove pieces during setup, query legal moves, execute single or multi-move turns, undo moves, and render the board as text.
    • Provide automated tests covering initial board setup, a Lion river-jump capture, special terrain/rank rules, and a multi-move sequence.

    Non-functional requirements

    • Atomic state transitions (all-or-nothing updates): an illegal move—or a failed step midway through a multi-move sequence—must leave the board, turn, and history completely untouched.
    • Single source of truth per rule: each rule lives in one place so a house-rule tweak is a one-line change, and UI move highlighting never disagrees with move execution.
    • Pure game engine: no print() or input() calls inside the rule engine, making it trivial to test or embed behind a mobile app, web UI, or AI search.

    Agreed rule table (using chess-style coordinates: columns a–g left to right, rows 1–9 bottom to top)

    Topic Decision
    Sides RED starts on rows 1–3 and moves first; BLUE starts on rows 7–9 (180-degree rotation of RED).
    Terrain Water: two 2x3 river blocks at b4–c6 and e4–f6 (12 squares). Dens: d1 (RED), d9 (BLUE). Traps: c1, e1, d2 (RED's) and c9, e9, d8 (BLUE's).
    Ranks Elephant 8, Lion 7, Tiger 6, Leopard 5, Wolf 4, Dog 3, Cat 2, Rat 1.
    Normal step One square orthogonally (up, down, left, or right). Diagonal moves are never allowed.
    Rivers (water) Only the Rat may enter water. Lion and Tiger leap straight across a river (over 3 water squares vertically or 2 horizontally) onto the far bank, unless any Rat (friend or foe) is swimming in a crossed water square.
    Rank capture An attacker captures an enemy of equal or lower rank (attacker.rank >= defender.rank). Exception: Rat (1) can capture Elephant (8), while Elephant cannot capture Rat.
    Riverbank edge No capture may cross between water and land in either direction: a swimming Rat cannot capture an Elephant on the bank, and a land piece cannot capture a swimming Rat. Two Rats in water can capture each other.
    Traps An enemy piece standing in one of your three traps drops to effective rank 0, so any of your pieces (even a Cat vs. Elephant, or Elephant vs. Rat) can capture it. Your own pieces keep their full rank inside your own traps.
    Dens A piece may never enter its own den. Stepping into the opponent's den wins immediately.
    Other wins Capturing the opponent's last remaining piece, or leaving the opponent with zero legal moves on their turn.
    "Multi-move turn" Standard rules allow one move per turn (though a Lion/Tiger leap crosses up to 4 squares in a single turn). We clarify whether "multi-move turn" means submitting a batch sequence of moves atomically (play(moves) for replays, puzzles, or scripted turns) or a power-up double-move rule; we implement play(moves) with full rollback and isolate turn-switching in one line so a same-side double turn is trivial to toggle.
  2. Back-of-the-envelope numbers

    Doing a 30-second size check tells us which data structures are worth building and which optimizations would only add bugs:

    Board size        9 rows x 7 cols = 63 squares (12 water + 6 traps + 2 dens + 43 plain land)
    Pieces            16 total (8 per side, at most 1 of each animal per color)
    Branching factor  each piece tries 4 directions and gets at most 1 landing square per direction
                      (a river jump replaces stepping into water) -> at most 8 x 4 = 32 legal moves
                      in the standard opening, RED has exactly 24 legal moves
    Move validation   O(1): inspect 1 piece, walk at most 3 water squares, check 1 capture rule
    Legal move list   scan 63 cells + test <= 32 candidates -> ~100 simple operations (~0.1 ms in Python)
    Move history      200-ply game -> 200 tiny Move records (~20 KB as Python objects, ~400 B packed)
    

    What these numbers tell us:

    • Use a plain 9x7 2D list and recompute legal moves on demand. Bitboards (packing 63 squares into a 64-bit integer) or cached legal-move lists would add cache-invalidation bugs to save microseconds in a human-speed game.
    • Support in-place move() + undo() rather than cloning the whole game. Recording a tiny immutable Move object (including any captured piece) gives us undo/take-back, all-or-nothing rollback for multi-move sequences, and fast tree search (~1,000,000 nodes at depth 4) from one mechanism.
  3. Public API and rendered board

    Callers interact with one Game coordinator and the eight Piece subclasses. Human-friendly square strings like "c3" are accepted at the public boundary and immediately converted into an internal Pos(row, col) object so internal methods never re-parse strings.

    Game.standard() -> Game                     create standard 16-piece opening, RED to move
    Game.empty(first=Color.RED) -> Game         create blank board for custom scenarios and unit tests
    game.place(Lion(Color.RED), "c3") -> None   setup helper; raises ValueError on bad/illegal placement
    game.remove("c3") -> Optional[Piece]        setup helper; removes and returns piece if present
    game.is_legal("c3", "c7") -> bool           returns False on rule violation (for UI highlighting)
    game.legal_moves() -> list[(Pos, Pos)]      all legal moves for side to move ([] once game is won)
    game.move("c3", "c7") -> Move               executes 1 move or raises IllegalMove
    game.play([("g3", "g4"), ("a7", "a6")])     applies a sequence atomically; rolls back all on error
    game.undo() -> Move                         reverts last move and restores any captured piece
    game.render() -> str                        ASCII snapshot + "to move: RED" or "winner: BLUE"
    

    In render(), RED pieces use uppercase letters, BLUE pieces use lowercase letters, ~ marks water, # marks traps, @ marks dens, and . marks empty land (Leopard uses P so it does not collide with Lion's L):

      a b c d e f g
    9 l . # @ # . t
    8 . d . # . c .
    7 r . p . w . e
    6 . ~ ~ . ~ ~ .
    5 . ~ ~ . ~ ~ .
    4 . ~ ~ . ~ ~ .
    3 E . W . P . R
    2 . C . # . D .
    1 T . # @ # . L
    to move: RED
    

    Two deliberate API choices prevent common bugs:

    • Separate programmer/input errors (ValueError) from game-rule rejections (IllegalMove). Passing "z0" or trying to place a Wolf into water during setup raises ValueError; tapping a blocked jump "c3" -> "c7" during play raises IllegalMove so a UI can show a friendly shake animation instead of crashing.
    • Share one legality check across is_legal, legal_moves, and move. Every square the UI highlights green is guaranteed to be accepted by move().
  4. Data model: coordinates, terrain, board, and move records

    Before writing piece logic, we define small value types. A frozen dataclass (@dataclass(frozen=True)) is an immutable object whose fields cannot be modified after creation, giving us value equality and hashing (pos in WATER, TRAPS.get(pos)) automatically without risk of accidental mutation.

    Because rivers, traps, and dens never move during a game, we model terrain as three fixed lookup tables (WATER, TRAPS, DENS) rather than storing terrain flags inside every square object. Notice that TRAPS and DENS map a Pos directly to its owning Color—the exact fact needed by the capture and win rules.

    from dataclasses import dataclass
    from enum import Enum
    from typing import Optional
    
    ROWS = 9
    COLS = 7
    COLUMN_LETTERS = "abcdefg"
    DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    
    
    class IllegalMove(Exception):
        """Raised when squares are on the board, but the game rules forbid the move."""
    
    
    class Color(Enum):
        RED = "red"     # bottom side (rows 1-3), moves first
        BLUE = "blue"   # top side (rows 7-9)
    
        def opponent(self):
            if self is Color.RED:
                return Color.BLUE
            return Color.RED
    
    
    @dataclass(frozen=True)
    class Pos:
        row: int   # 0..8, where row 0 is rank "1" (RED's back row)
        col: int   # 0..6, where col 0 is file "a"
    
        @staticmethod
        def parse(name):
            """Convert algebraic square name like 'c3' into Pos(row=2, col=2)."""
            if not isinstance(name, str):
                raise ValueError(f"square name must be a string, got {name!r}")
            cleaned = name.strip().lower()
            is_valid = (
                len(cleaned) == 2
                and cleaned[0] in COLUMN_LETTERS
                and cleaned[1] in "123456789"
            )
            if not is_valid:
                raise ValueError(f"bad square name {name!r}")
            row_index = int(cleaned[1]) - 1
            col_index = COLUMN_LETTERS.index(cleaned[0])
            return Pos(row_index, col_index)
    
        def step(self, d_row, d_col):
            return Pos(self.row + d_row, self.col + d_col)
    
        def on_board(self):
            return 0 <= self.row < ROWS and 0 <= self.col < COLS
    
        def __str__(self):
            return COLUMN_LETTERS[self.col] + str(self.row + 1)
    
    
    def _build_water_squares():
        squares = set()
        for row in (3, 4, 5):          # board rows 4, 5, 6
            for col in (1, 2, 4, 5):  # columns b, c and e, f
                squares.add(Pos(row, col))
        return squares
    
    
    WATER = _build_water_squares()
    DENS = {Pos(0, 3): Color.RED, Pos(8, 3): Color.BLUE}
    TRAPS = {
        Pos(0, 2): Color.RED, Pos(0, 4): Color.RED, Pos(1, 3): Color.RED,
        Pos(8, 2): Color.BLUE, Pos(8, 4): Color.BLUE, Pos(7, 3): Color.BLUE,
    }
    
    
    class Board:
        """9x7 grid storing which piece sits on each square. Terrain lives in fixed tables."""
    
        def __init__(self):
            self.cells = []
            for _ in range(ROWS):
                self.cells.append([None] * COLS)
    
        def piece_at(self, pos):
            return self.cells[pos.row][pos.col]
    
        def put(self, piece, pos):
            self.cells[pos.row][pos.col] = piece
    
        def take(self, pos):
            piece = self.cells[pos.row][pos.col]
            self.cells[pos.row][pos.col] = None
            return piece
    
        def pieces_of(self, color):
            """Return [(pos, piece)] for every piece of this color in row-major order."""
            found = []
            for row in range(ROWS):
                for col in range(COLS):
                    piece = self.cells[row][col]
                    if piece is not None and piece.color is color:
                        found.append((Pos(row, col), piece))
            return found
    
    
    @dataclass(frozen=True)
    class Move:
        piece: "Piece"
        start: Pos
        end: Pos
        captured: Optional["Piece"] = None
    
  5. Class hierarchy and separation of responsibilities

    A common object-oriented pitfall is letting Piece know about turns and traps, or letting Board enforce rules. Instead, we split responsibilities by asking one simple question: whose fact is this?

    • "A Lion can jump straight over water unless a Rat is in the way" is a biological trait of Lions and Tigers, so it belongs in the Piece class hierarchy.
    • "Which piece currently sits on square c7?" is storage state, so it belongs on Board.
    • "An enemy piece inside your trap drops to rank 0, and stepping into the enemy den wins the game" combines two players with board landmarks, so it belongs in Game and its capture helper.
                     +--------------------------------------------+
                     | Game (referee & state coordinator)         |
                     |  turn, winner, history: list[Move]         |
                     |  standard()  empty()  place()  remove()    |
                     |  is_legal()  legal_moves()                 |
                     |  move()  play()  undo()  render()          |
                     +-------------+-----------------+------------+
                                   | owns 1          | appends 0..n
                                   v                 v
       +----------------------------------+   +-------------------------------+
       | Board (passive 9x7 storage)      |   | Move (immutable undo record)  |
       |  cells[9][7]: Piece | None       |   |  piece, start, end, captured  |
       |  piece_at()  put()  take()       |   +-------------------------------+
       |  pieces_of(color)                |
       +-----------------+----------------+   Fixed terrain tables:
                         | holds 0..16          WATER: set[Pos]
                         v                      TRAPS: dict[Pos, owner Color]
       +--------------------------------------+ DENS:  dict[Pos, owner Color]
       | Piece (base class)                   |
       |  color, rank, symbol, can_swim       |
       |  destinations(board, start)  --------+-- template method (4 directions)
       |  water_destination(...)      --------+-- hook overridden by swimmers/jumpers
       |  outranks(other)             --------+-- hook overridden by Rat & Elephant
       +---+--------------+-------------+-----+
           |              |             |
        Elephant     JumpingPiece      Rat         Leopard  Wolf  Dog  Cat
        outranks:    water_destination: can_swim    (plain land animals:
        not Rat      leap over water    outranks:    inherit base rules,
                      /          \      Elephant     differ only in rank/symbol)
                  Lion (7)    Tiger (6)
    
  6. Deep dive: piece classes and river-jump geometry

    All eight animals share the exact same four-direction loop, differing in only three small ways: whether they can swim, whether they leap over water, and whether they participate in the Rat-vs.-Elephant rank exception. We capture this cleanly with the template-method pattern—a design pattern where the base class implements the shared outer loop (destinations) once and calls small hook methods (water_destination and outranks) that subclasses override when their behavior differs:

    • For a land neighbor, destinations adds the square immediately.
    • For a water neighbor, destinations delegates to water_destination(board, start, d_row, d_col):
      • The base Piece returns that water square if self.can_swim is True (only Rat), and None otherwise (Elephant, Leopard, Wolf, Dog, Cat).
      • JumpingPiece steps square-by-square across WATER in (d_row, d_col) until it reaches land, returning None immediately if any piece occupies a water square along the path. Both Lion and Tiger inherit from JumpingPiece, so the river-jump loop is written in one place.

    Let's verify the river-jump geometry on our 9x7 grid before coding it:

    Vertical jump   Lion at c3 stepping up (+1, 0):
                    c4 (water, empty) -> c5 (water, empty) -> c6 (water, empty) -> lands on c7!
    Horizontal jump Tiger at a5 stepping right (0, +1):
                    b5 (water, empty) -> c5 (water, empty) -> lands on d5!
    Blocked jump    Rat (RED or BLUE) swimming at c5:
                    Lion at c3 checks c4 (empty) -> c5 (occupied!) -> returns None (jump blocked)
    

    Because both 2x3 river blocks (b4–c6 and e4–f6) are surrounded by land on all four sides (files a, d, g and rows 3 and 7), the while square in WATER: loop is guaranteed to terminate on a valid board square without ever stepping off the edge.

    class Piece:
        name = "Piece"
        rank = 0
        symbol = "?"
        can_swim = False
    
        def __init__(self, color):
            self.color = color
    
        def __repr__(self):
            return f"{self.color.name.title()} {self.name}"
    
        def outranks(self, other):
            """Pure animal-vs-animal rank rule; trap and riverbank rules live in can_capture."""
            return self.rank >= other.rank
    
        def destinations(self, board, start):
            """Squares geometrically reachable in 1 turn from start (ignoring who stands on end)."""
            reachable = []
            for d_row, d_col in DIRECTIONS:
                adjacent = start.step(d_row, d_col)
                if not adjacent.on_board():
                    continue
                if adjacent in WATER:
                    landing = self.water_destination(board, start, d_row, d_col)
                    if landing is not None:
                        reachable.append(landing)
                else:
                    reachable.append(adjacent)
            return reachable
    
        def water_destination(self, board, start, d_row, d_col):
            """Hook for stepping toward water: return landing square, or None if forbidden."""
            if self.can_swim:
                return start.step(d_row, d_col)
            return None
    
    
    class Elephant(Piece):
        name, rank, symbol = "Elephant", 8, "E"
    
        def outranks(self, other):
            if isinstance(other, Rat):
                return False   # Elephant (8) cannot capture Rat (1) on normal land
            return super().outranks(other)
    
    
    class JumpingPiece(Piece):
        """Shared river-jumping movement for Lion and Tiger."""
    
        def water_destination(self, board, start, d_row, d_col):
            square = start.step(d_row, d_col)
            while square in WATER:
                if board.piece_at(square) is not None:
                    return None   # any swimming Rat (friend or foe) blocks the leap
                square = square.step(d_row, d_col)
            return square
    
    
    class Lion(JumpingPiece):
        name, rank, symbol = "Lion", 7, "L"
    
    
    class Tiger(JumpingPiece):
        name, rank, symbol = "Tiger", 6, "T"
    
    
    class Leopard(Piece):
        name, rank, symbol = "Leopard", 5, "P"
    
    
    class Wolf(Piece):
        name, rank, symbol = "Wolf", 4, "W"
    
    
    class Dog(Piece):
        name, rank, symbol = "Dog", 3, "D"
    
    
    class Cat(Piece):
        name, rank, symbol = "Cat", 2, "C"
    
    
    class Rat(Piece):
        name, rank, symbol = "Rat", 1, "R"
        can_swim = True
    
        def outranks(self, other):
            if isinstance(other, Elephant):
                return True    # Rat (1) beats Elephant (8) when both are on land
            return super().outranks(other)
    
  7. Deep dive: capture rules and check ordering

    Capture bugs happen when special rules are scattered across classes or checked in the wrong order. Putting every capture rule into one pure function can_capture(attacker, start, defender, end) makes the exact priority order explicit:

    1. Same color -> False: You can never capture your own piece.
    2. Cross-riverbank -> False: If (start in WATER) != (end in WATER), one piece is swimming and the other is on dry land, so capture is forbidden in both directions. (Notice that a Lion jump starts on land c3 and lands on land c7, so (False != False) is False and jumps can capture normally!)
    3. Defender in attacker's trap -> True: If TRAPS.get(end) is attacker.color, the enemy defender's effective rank drops to 0. Checking this before attacker.outranks(defender) is critical: if rank ran first, a Cat could not capture a trapped Elephant, and an Elephant could not capture a trapped enemy Rat!
    4. Animal rank -> attacker.outranks(defender): On ordinary same-terrain squares, compare animal ranks including the Rat/Elephant exception.
    def can_capture(attacker, start, defender, end):
        """Return True if attacker moving start -> end is allowed to capture defender."""
        # 1. Never capture a friendly piece.
        if attacker.color is defender.color:
            return False
        # 2. Never capture across the water's edge (water -> land or land -> water).
        if (start in WATER) != (end in WATER):
            return False
        # 3. An enemy standing in ONE OF YOUR traps has rank 0 (overrides rank & Rat/Elephant).
        if TRAPS.get(end) is attacker.color:
            return True
        # 4. Standard rank comparison (with Rat/Elephant exception).
        return attacker.outranks(defender)
    

    Trace all eight tricky interactions against those four lines to confirm none slip through:

    Attacker (start)         Defender (end)              Result  Rule that decides it
    RED Lion at c3 (land)    BLUE Tiger at c7 (land)     True    step 4: jump is land->land, 7 >= 6
    RED Lion at c3 (land)    BLUE Elephant at c7 (land)  False   step 4: 7 < 8
    RED Rat at a4 (land)     BLUE Elephant at a5 (land)  True    step 4: Rat.outranks(Elephant)
    BLUE Elephant at a5      RED Rat at a4               False   step 4: Elephant.outranks(Rat) is False
    RED Rat at b4 (water)    BLUE Elephant at a4 (land)  False   step 2: water != land (riverbank block)
    RED Rat at b4 (water)    BLUE Rat at b5 (water)      True    step 4: water == water, 1 >= 1
    RED Cat at d3            BLUE Elephant at d2 (trap)  True    step 3: d2 is RED's trap -> rank 0
    BLUE Cat at d3           RED Elephant at d2 (trap)   False   step 4: d2 is RED's own trap -> keeps rank 8
    
  8. Deep dive: turns, legality, atomic multi-move sequences, and win detection

    Now we assemble Game. Four design choices keep state transitions bug-free:

    • 180-degree rotational setup: In Animal Chess, BLUE's starting layout is RED's layout rotated 180 degrees (a1 -> g9, g3 -> a7). Computing BLUE from RED_SETUP via rotate_180 makes it impossible for the two sides' starting tables to drift out of sync.
    • Guard board invariants during setup: place() enforces every board invariant (a rule that must always hold true)—no duplicate animal of the same color, no non-swimmer in water, no piece placed directly onto a den, and no calling place/remove after play has begun.
    • Validate completely before mutating: move() checks is_legal first and only touches self.board, self.history, self.winner, and self.turn once legality is proven. Notice how _moves_for computes piece.destinations() once per piece and shares _can_land_on with _legal_for so river jumps are never scanned twice per check.
    • All-or-nothing play(moves) via undo(): play executes a list of moves one by one, counting how many succeeded. If move k raises either IllegalMove or ValueError (such as a typo "z0"), the except block calls self.undo() applied times and re-raises the original error, leaving the game bit-for-bit identical to before play was called.
    RED_SETUP = [
        (Tiger, "a1"), (Lion, "g1"), (Cat, "b2"), (Dog, "f2"),
        (Elephant, "a3"), (Wolf, "c3"), (Leopard, "e3"), (Rat, "g3"),
    ]
    
    
    def rotate_180(pos):
        """Map RED's square to BLUE's 180-degree symmetric square (e.g. a1 -> g9)."""
        return Pos(ROWS - 1 - pos.row, COLS - 1 - pos.col)
    
    
    class Game:
        def __init__(self, first=Color.RED):
            self.board = Board()
            self.turn = first
            self.winner = None
            self.history = []
    
        @classmethod
        def standard(cls):
            game = cls(first=Color.RED)
            for piece_class, square_name in RED_SETUP:
                red_pos = Pos.parse(square_name)
                game.place(piece_class(Color.RED), red_pos)
                game.place(piece_class(Color.BLUE), rotate_180(red_pos))
            return game
    
        @classmethod
        def empty(cls, first=Color.RED):
            return cls(first=first)
    
        def place(self, piece, square):
            """Place a piece on an empty square during setup (before moves are played)."""
            if self.history:
                raise ValueError("cannot place pieces after moves have been played")
            pos = self._to_pos(square)
            if self.board.piece_at(pos) is not None:
                raise ValueError(f"{pos} is already occupied")
            if pos in WATER and not piece.can_swim:
                raise ValueError(f"a {piece.name} cannot stand in water at {pos}")
            if pos in DENS:
                raise ValueError(f"cannot place a piece directly on a den at {pos}")
            for _, existing in self.board.pieces_of(piece.color):
                if type(existing) is type(piece):
                    raise ValueError(f"{piece.color.name} already has a {piece.name}")
            self.board.put(piece, pos)
    
        def remove(self, square):
            """Remove a piece during setup (before moves are played)."""
            if self.history:
                raise ValueError("cannot remove pieces after moves have been played")
            return self.board.take(self._to_pos(square))
    
        def is_legal(self, start_square, end_square):
            """Return False for rule violations; raise ValueError only for bad square names."""
            start = self._to_pos(start_square)
            end = self._to_pos(end_square)
            if self.winner is not None:
                return False
            return self._legal_for(self.turn, start, end)
    
        def legal_moves(self):
            """Return [(start, end)] for every legal move of the side to move."""
            if self.winner is not None:
                return []
            return self._moves_for(self.turn)
    
        def _can_land_on(self, color, piece, start, end):
            if DENS.get(end) is color:
                return False   # a piece may never enter its own den
            defender = self.board.piece_at(end)
            if defender is None:
                return True
            return can_capture(piece, start, defender, end)
    
        def _legal_for(self, color, start, end):
            piece = self.board.piece_at(start)
            if piece is None or piece.color is not color:
                return False
            if end not in piece.destinations(self.board, start):
                return False
            return self._can_land_on(color, piece, start, end)
    
        def _moves_for(self, color):
            moves = []
            for start, piece in self.board.pieces_of(color):
                for end in piece.destinations(self.board, start):
                    if self._can_land_on(color, piece, start, end):
                        moves.append((start, end))
            return moves
    
        def move(self, start_square, end_square):
            start = self._to_pos(start_square)
            end = self._to_pos(end_square)
            if not self.is_legal(start, end):
                raise IllegalMove(f"{self.turn.name}: {start} -> {end} is not legal")
            piece = self.board.take(start)
            captured = self.board.take(end)
            self.board.put(piece, end)
            record = Move(piece, start, end, captured)
            self.history.append(record)
            self._update_winner(piece.color, end)
            self.turn = self.turn.opponent()
            return record
    
        def play(self, moves):
            """Apply [(start, end), ...] in turn order, rolling back everything if any step fails."""
            applied = 0
            try:
                for start, end in moves:
                    self.move(start, end)
                    applied += 1
            except (IllegalMove, ValueError):
                for _ in range(applied):
                    self.undo()
                raise
            return self.history[len(self.history) - applied:]
    
        def undo(self):
            if not self.history:
                raise IllegalMove("nothing to undo")
            record = self.history.pop()
            self.board.take(record.end)
            self.board.put(record.piece, record.start)
            if record.captured is not None:
                self.board.put(record.captured, record.end)
            self.turn = record.piece.color
            self.winner = None
            return record
    
        def _update_winner(self, mover, end):
            opponent = mover.opponent()
            if DENS.get(end) is opponent:
                self.winner = mover
            elif not self.board.pieces_of(opponent):
                self.winner = mover
            elif not self._moves_for(opponent):
                self.winner = mover   # opponent has pieces left, but zero legal moves
    
        def render(self):
            lines = ["  a b c d e f g"]
            for row in range(ROWS - 1, -1, -1):
                row_chars = [self._cell_char(Pos(row, col)) for col in range(COLS)]
                lines.append(f"{row + 1} " + " ".join(row_chars))
            if self.winner is not None:
                lines.append(f"winner: {self.winner.name}")
            else:
                lines.append(f"to move: {self.turn.name}")
            return "\n".join(lines)
    
        def _cell_char(self, pos):
            piece = self.board.piece_at(pos)
            if piece is not None:
                return piece.symbol if piece.color is Color.RED else piece.symbol.lower()
            if pos in WATER:
                return "~"
            if pos in DENS:
                return "@"
            if pos in TRAPS:
                return "#"
            return "."
    
        @staticmethod
        def _to_pos(square):
            pos = square if isinstance(square, Pos) else Pos.parse(square)
            if not pos.on_board():
                raise ValueError(f"{pos!r} is off the board")
            return pos
    
  9. Test suite: board setup, lion capture, river blocks, traps, and multi-move turns

    Every scenario requested in the prompt—plus each edge case from our capture truth table—gets an explicit, deterministic unittest method. Notice how hand-counted assertions verify our design rather than trusting run output blindly: in test_standard_setup, RED's 24 opening moves come from Tiger (2) + Lion (2) + Cat (4) + Dog (4) + Elephant (3) + Wolf (3, since c4 is water) + Leopard (3, since e4 is water) + Rat (3, g4 is land and f3 is land, right edge off-board) = 24.

    import unittest
    
    
    class JungleTests(unittest.TestCase):
        def test_standard_setup(self):
            """16 pieces on the standard squares, RED to move, and 24 legal opening moves."""
            game = Game.standard()
            self.assertEqual(len(game.board.pieces_of(Color.RED)), 8)
            self.assertEqual(len(game.board.pieces_of(Color.BLUE)), 8)
            self.assertIsInstance(game.board.piece_at(Pos.parse("g1")), Lion)
            self.assertIs(game.board.piece_at(Pos.parse("a9")).color, Color.BLUE)
            self.assertIs(game.turn, Color.RED)
            self.assertEqual(game.render(), "\n".join([
                "  a b c d e f g",
                "9 l . # @ # . t",
                "8 . d . # . c .",
                "7 r . p . w . e",
                "6 . ~ ~ . ~ ~ .",
                "5 . ~ ~ . ~ ~ .",
                "4 . ~ ~ . ~ ~ .",
                "3 E . W . P . R",
                "2 . C . # . D .",
                "1 T . # @ # . L",
                "to move: RED",
            ]))
            self.assertEqual(len(game.legal_moves()), 24)
    
        def test_lion_jumps_river_and_captures_tiger(self):
            """A Lion jumps c3 -> c7 across three water squares and captures a lower-ranked Tiger."""
            game = Game.empty()
            game.place(Lion(Color.RED), "c3")
            game.place(Tiger(Color.BLUE), "c7")
            game.place(Rat(Color.BLUE), "a9")   # keep a second BLUE piece so the game continues
            record = game.move("c3", "c7")
            self.assertIsInstance(record.captured, Tiger)
            self.assertIsInstance(game.board.piece_at(Pos.parse("c7")), Lion)
            self.assertIsNone(game.board.piece_at(Pos.parse("c3")))
            self.assertIs(game.turn, Color.BLUE)
    
        def test_rat_in_water_blocks_jump(self):
            """Any Rat (friend or foe) swimming along the jump path blocks the Lion."""
            game = Game.empty()
            game.place(Lion(Color.RED), "c3")
            game.place(Tiger(Color.BLUE), "c7")
            game.place(Rat(Color.RED), "c5")
            with self.assertRaises(IllegalMove):
                game.move("c3", "c7")
    
        def test_lion_cannot_capture_elephant_and_tiger_jumps_sideways(self):
            """Higher rank blocks capture; Tigers also jump horizontally across 2 water squares."""
            game = Game.empty()
            game.place(Lion(Color.RED), "c3")
            game.place(Elephant(Color.BLUE), "c7")
            game.place(Tiger(Color.RED), "a5")
            self.assertFalse(game.is_legal("c3", "c7"))
            self.assertIn((Pos.parse("a5"), Pos.parse("d5")), game.legal_moves())
    
        def test_rat_elephant_and_water_edge(self):
            """Rat beats Elephant on land, never from water; Elephant cannot take Rat outside a trap."""
            game = Game.empty()
            game.place(Rat(Color.RED), "a4")
            game.place(Elephant(Color.BLUE), "a5")
            self.assertTrue(game.is_legal("a4", "a5"))
    
            blue_first = Game.empty(first=Color.BLUE)
            blue_first.place(Rat(Color.RED), "a4")
            blue_first.place(Elephant(Color.BLUE), "a5")
            self.assertFalse(blue_first.is_legal("a5", "a4"))
    
            riverbank = Game.empty()
            riverbank.place(Rat(Color.RED), "b4")       # swimming in water
            riverbank.place(Elephant(Color.BLUE), "a4") # standing on bank
            self.assertFalse(riverbank.is_legal("b4", "a4"))
    
        def test_trap_makes_any_enemy_capturable(self):
            """An enemy in RED's trap (d2) drops to rank 0: Cat takes Elephant, Elephant takes Rat."""
            game = Game.empty()
            game.place(Cat(Color.RED), "d3")
            game.place(Elephant(Color.BLUE), "d2")
            self.assertIsInstance(game.move("d3", "d2").captured, Elephant)
    
            trap_override = Game.empty()
            trap_override.place(Elephant(Color.RED), "d3")
            trap_override.place(Rat(Color.BLUE), "d2")
            self.assertIsInstance(trap_override.move("d3", "d2").captured, Rat)
    
        def test_den_entry_wins_and_own_den_is_forbidden(self):
            """Entering the enemy den wins immediately; entering your own den is illegal."""
            game = Game.empty()
            game.place(Dog(Color.RED), "d8")
            game.place(Wolf(Color.RED), "d2")
            game.place(Cat(Color.BLUE), "a9")
            self.assertFalse(game.is_legal("d2", "d1"))
            game.move("d8", "d9")
            self.assertIs(game.winner, Color.RED)
            self.assertEqual(game.legal_moves(), [])
    
        def test_multi_move_sequence_and_atomic_rollback(self):
            """Four valid moves advance play; any illegal move or bad square rolls back the whole batch."""
            game = Game.standard()
            game.play([("g3", "g4"), ("a7", "a6"), ("g4", "f4"), ("g7", "g6")])
            self.assertIsInstance(game.board.piece_at(Pos.parse("f4")), Rat)   # swimming Rat
            self.assertIsNone(game.board.piece_at(Pos.parse("g3")))
            self.assertIs(game.turn, Color.RED)
    
            before = game.render()
            with self.assertRaises(IllegalMove):
                game.play([("e3", "d3"), ("g6", "g5"), ("c3", "c4")])   # Wolf cannot swim into c4
            self.assertEqual(game.render(), before)
    
            with self.assertRaises(ValueError):
                game.play([("e3", "d3"), ("z0", "a1")])                 # bad square rolls back too
            self.assertEqual(game.render(), before)
            self.assertEqual(len(game.history), 4)
    
        def test_undo_restores_capture_and_turn(self):
            """Undo puts back the captured piece, restores the mover, and resets turn order."""
            game = Game.empty()
            game.place(Lion(Color.RED), "c3")
            game.place(Tiger(Color.BLUE), "c7")
            game.place(Rat(Color.BLUE), "a9")
            before = game.render()
            game.move("c3", "c7")
            game.undo()
            self.assertEqual(game.render(), before)
    
    
    if __name__ == "__main__":
        unittest.main()
    
  10. Scaling, rule variants, failure handling, and trade-offs

    Even though a 9x7 board never grows in size, real software grows along three axes—rule variants, AI opponents, and multiplayer traffic—and our class boundaries make each extension local:

    • Supporting house-rule variants:
      • Leopard jumps horizontally: override Leopard.water_destination to leap when d_row == 0 and return None when d_row != 0.
      • Swimming Rat can capture Elephant on the bank: edit the single riverbank check in can_capture.
      • Multiple rule sets coexisting at runtime: pass a Rules strategy object into Game(rules=...) when a second live mode is needed (avoiding extra abstraction until required).
    • Adding an AI opponent: With <= 32 moves per turn, searching 4 plies deep visits up to 32^4 ≈ 1,050,000 positions (~100 seconds in unpruned Python at 0.1 ms/node). Our move() + undo() pair lets minimax with alpha-beta pruning (a game-tree search that discards branches provably worse than a move already found) explore one Game in place without copying boards, and ordering captures first shrinks the searched tree dramatically.
    • Running as an online multiplayer service: For 100,000 concurrent games making 1 move every 10 seconds (~10,000 moves/s), rule validation takes ~1 CPU core total (10,000 x 0.1 ms = 1.0 CPU-second/s). The server stays authoritative: clients send (game_id, expected_move_number, "c3", "c7"). Checking expected_move_number provides optimistic concurrency (rejecting duplicate taps or stale retries if the move counter already advanced). Storing the append-only move log (2 bytes per move, ~400 bytes per game) rather than raw board dumps means replaying through move() validates every historical state and pinpoints any corrupted entry immediately.
    • Key trade-offs summarized:
      • Subclasses per animal vs. a config table: Subclasses match the prompt and colocate each animal's hooks (can_swim, water_destination, outranks) with its class; keeping subclasses thin avoids deep inheritance tangles.
      • Terrain as fixed lookup tables vs. Square objects: Fixed dicts/sets (WATER, TRAPS, DENS) keep Board minimal and make trap/den ownership a direct O(1) lookup.
      • Validate-then-mutate + undo vs. immutable board copies: Requires storing captured on Move, but powers undo buttons, atomic play() batches, and AI search from a single mechanism.

Intuition & how it works

Think of designing a board-game engine like separating animal biology from arena referee rules. Each animal card (Piece subclass) only knows its own physical traits: its strength rank (1 to 8), whether it can swim (Rat), whether it can leap straight across water (Lion and Tiger), and its natural rivalry (Rat beats Elephant). Meanwhile, Board is just a passive 9x7 tray holding pieces, and Game is the referee who enforces turn order, special landmarks (traps, dens, and riverbanks), win conditions, and an undoable move log.

Why do the obvious approaches fall apart? Cramming all eight animals' movements and capture exceptions into one giant if/elif block inside Board.move() turns overlapping rules—like a weak Cat capturing an Elephant inside a trap, or a swimming Rat blocking a Lion's river leap—into brittle spaghetti code. On the flip side, letting Piece.move() mutate the board directly forces every piece class to know about turns, dens, traps, and history, and risks leaving the board half-updated whenever a move turns out to be illegal.

Let's trace a tiny four-step sequence on our 9x7 grid with a RED Lion at c3, a BLUE Tiger at c7 across the river (c4, c5, c6 are water), and a RED Rat swimming at c5:

1. RED tries move("c3", "c7"):
   Lion (JumpingPiece) scans c4 (empty) -> c5 (occupied by Rat!) -> returns None.
   Game raises IllegalMove; board and turn stay untouched.

2. RED plays move("c5", "b5"):
   Rat has can_swim = True, so stepping into adjacent water b5 is legal -> turn becomes BLUE.

3. BLUE plays a waiting move elsewhere on row 9 -> turn becomes RED.

4. RED plays move("c3", "c7"):
   c4, c5, c6 are now empty water -> Lion lands on c7 (land).
   can_capture checks: not friendly -> both on land -> not a trap -> Lion (7) >= Tiger (6) -> True!
   Game removes BLUE Tiger, places RED Lion on c7, appends Move(Lion, c3, c7, captured=Tiger),
   checks win conditions, and switches turn to BLUE.

Key trade-offs

  • One subclass per animal (with hooks) vs. a data-driven capability table. Defining eight subclasses fulfills the object-oriented prompt and uses the template-method pattern (a design where the base class writes the shared 4-direction loop once and subclasses override small hook methods like water_destination and outranks). A plain configuration dictionary ({"Lion": {"rank": 7, "jumps": True}}) would be slightly shorter, so we keep the subclasses thin (2–6 lines each) to get clear polymorphism without deep inheritance chains.
  • Putting movement on Piece vs. putting terrain-and-side rules on Game. Whether an animal can swim or leap water depends only on the animal and water squares, so it belongs on Piece. Traps, dens, and riverbank capture blocks depend on which player owns the square and both squares' terrain, so putting them in can_capture and Game spares Piece from knowing about players' home sides.
  • Fixed capture-check priority order. can_capture checks friendly-fire -> riverbank boundary -> defender in attacker's trap -> animal rank. Checking the trap before animal rank is essential; reversing those two lines would falsely stop a Cat from capturing a trapped Elephant or an Elephant from capturing a trapped enemy Rat.
  • Validate-then-apply plus undo() vs. cloning the board before every move. Recording an immutable Move object (one whose fields never change after creation, storing piece, start, end, and captured) requires careful restoration in undo(), but that single mechanism unlocks take-backs, atomic multi-move batches (all-or-nothing execution via rollback), and fast AI tree search without allocating millions of 63-cell copies.
  • Plain 9x7 2D list vs. bitboards. A bitboard (packing all 63 squares into bits of a 64-bit integer) speeds up deep chess engines, but with at most 32 legal moves per turn (~0.1 ms in plain Python), a 2D list is far easier to read and debug while keeping the option to swap Board internals later behind the same API.
  • Distinguishing ValueError from IllegalMove plus a boolean is_legal. Bad coordinates ("z0") or broken setup invariants raise ValueError to catch caller bugs, rule rejections in move() raise IllegalMove so callers cannot ignore failed moves, and is_legal() / legal_moves() call the exact same _legal_for helper so UI move highlights never disagree with the engine.

Common mistakes

  • Allowing diagonal steps or multi-square land moves: Every animal moves one orthogonal square at a time; only Lion and Tiger jump multiple squares, and only straight across water.
  • Checking only the landing square of a river jump: A Lion or Tiger must walk every water square between start and end (c4, c5, c6) so a swimming Rat of either color blocks the leap.
  • Letting a swimming Rat capture an Elephant on the riverbank (or vice versa): Under standard rules, captures cannot cross between water and land in either direction; only two swimming Rats can capture each other in water.
  • Weakening pieces inside their own traps: Traps only drop enemy defenders to rank 0 (TRAPS.get(end) is attacker.color). A defender standing in its own protective trap keeps its full rank.
  • Evaluating Rat-vs.-Elephant before trap weakness: Inside RED's trap, BLUE's Rat has rank 0, so RED's Elephant can capture it—which breaks if Piece.outranks runs before the trap check.
  • Mutating the board before finishing validation: Moving the attacker off start before checking whether end is its own den or an uncapturable enemy leaves phantom or missing pieces after an exception, and failing partway through play(moves) without rolling back corrupts the game state.
  • Duplicating the 8-piece setup table for RED and BLUE: Animal Chess uses 180-degree rotational symmetry (a1 maps to g9), not mirror symmetry (a1 to a9); computing BLUE via rotate_180(pos) prevents hand-typed setup mismatches.

Follow-up questions

  • How would you build an AI opponent on top of these classes? Run minimax with alpha-beta pruning (a lookahead search that alternates maximizing your score and minimizing your opponent's while skipping branches that cannot beat a move already found) over game.legal_moves(), stepping forward with game.move() and backward with game.undo() so zero board copies are allocated. Score leaf positions using material (sum of remaining piece ranks), Manhattan distance of your closest pieces to the enemy den, and enemy proximity to your own den, and sort capture moves first so alpha-beta prunes most of the 32^d tree.
  • How would you support multiple house-rule variants simultaneously at runtime, such as Leopards jumping horizontally or Rats attacking from water? Extract can_capture, win checks, and movement toggles into a Rules configuration or strategy object passed into Game(rules=...) rather than hard-coding one variant globally. Each variant becomes a tiny, independently testable Rules preset (for example, StandardRules vs. HorizontalLeopardRules), and saved games record the rule preset's name alongside the move log so replays remain deterministic.
  • How would you persist, replay, and serve this game for 100,000 concurrent online matches? Store the rule preset and an append-only list of moves (each start -> end pair fits in 2 bytes since 0..62 needs 6 bits, making a 200-move game ~400 bytes) rather than serializing the 2D grid, and reconstruct or audit games by replaying moves through move(). To prevent double-taps or network retries from applying a move twice, require each client request to include expected_move_number (optimistic concurrency, rejecting any request whose move counter no longer matches len(game.history)).

Follow-up questions

Similar questions

More Duolingo interview questions

All 2 Duolingo questions →