Build a Jungle Board Game Engine with Class Hierarchies
Data Structure DesignModel answerLast updated
Design the classes for a two-player Jungle (Dou Shou Qi) engine: eight animals, a 9x7 board with water, traps and dens, capture and jump rules, a small API, and tests.
You are building the rules engine for a local, two-player version of the traditional board game Jungle (also called Animal Chess or Dou Shou Qi). There is no AI opponent and no GUI.
Your design should cover:
- Eight animals: Elephant, Lion, Tiger, Leopard, Wolf, Dog, Cat and Rat. Each has its own movement and capture behaviour.
- A 9-row by 7-column board with two lakes, trap squares, and one den for each player.
- Move and capture logic, including swimming, river jumping and trap effects.
- A compact public API that can set up a game, place pieces, list legal moves for a piece, play a move, and print the board as text.
- Test cases for at least three scenarios: the starting position, a Lion capturing across a river, and several turns played in a row.
Before writing any classes, state the rules you are assuming. Then explain which class owns which responsibility and why that split makes the design easy to extend.
Hints
Hint 1
Separate 'may this animal take that one?' from 'what is the situation on the board?'. If the animal answers the first and the board supplies facts such as terrain and trap ownership, the board never needs to know about specific species.
Hint 2
Most animals follow the default rules and differ in one respect only (swims, jumps, or a special capture rule). Model that as small overridable attributes and methods instead of a long if/else chain on the animal type.
Hint 3
A trap is a property of the square the defender stands on, relative to the attacker's side. Do not mutate the defender's rank; just pass 'defender is in a trap of the attacker's side' into the capture check.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Rules I would pin down first
- Board: 9 rows by 7 columns, addressed as 0-indexed
(row, col). - Lakes: rows 3-5 in columns 1-2 and in columns 4-5 (12 water squares).
- Dens and traps: each den sits in the middle of its owner's back row with three traps around it. Top den
(0,3), traps(0,2) (0,4) (1,3). Bottom den(8,3), traps(8,2) (8,4) (7,3). - Ranks: Elephant 8, Lion 7, Tiger 6, Leopard 5, Wolf 4, Dog 3, Cat 2, Rat 1.
- Movement: one orthogonal step. Only the Rat may enter water. Lion and Tiger may jump in a straight line over a lake to the first land square beyond it. The jump is illegal if a Rat sits on any water square along the path.
- Capture:
- Equal or lower rank can be captured.
- A Rat can capture an Elephant, and an Elephant can never capture a Rat.
- A piece in water and a piece on land cannot capture each other.
- An enemy standing in a trap of the attacker's side counts as rank 0, so anything can capture it.
- Ending: stepping into the enemy den wins. Entering your own den is forbidden. A player with no legal move loses.
2. Responsibilities
| Class | Owns |
|---|---|
Side (enum) | TOP / BOTTOM and a foe helper |
Piece and subclasses | rank, side, swims, jumps, can_capture(...) |
Board | geometry, terrain constants, placement, legal-move generation, rendering |
Game | whose turn it is, applying moves, detecting a winner |
The central decision is that a piece judges whether it may capture, while the board supplies context (attacker in water? defender in water? defender in an attacker-side trap?). A new animal is then just a new subclass, and Board stays unchanged (Open/Closed). The subclass overrides are tiny: Rat sets swims and beats Elephants, Elephant refuses Rats, Lion and Tiger set jumps.
Terrain is kept as constant sets because the board is fixed. If variant boards mattered, I would promote it to a Square class holding terrain, owner and occupant.
3. Implementation
from enum import Enum
ROWS, COLS = 9, 7
WATER = {(r, c) for r in (3, 4, 5) for c in (1, 2, 4, 5)}
DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
class Side(Enum):
TOP = 0
BOTTOM = 1
@property
def foe(self): return Side(1 - self.value)
DEN = {Side.TOP: (0, 3), Side.BOTTOM: (8, 3)}
TRAPS = {Side.TOP: {(0, 2), (0, 4), (1, 3)},
Side.BOTTOM: {(8, 2), (8, 4), (7, 3)}}
class Piece:
rank, symbol = 0, "?"
swims = jumps = False
def __init__(self, side): self.side = side
def outranks(self, t): return self.rank >= t.rank
def can_capture(self, t, me_wet, t_wet, t_trapped):
if me_wet != t_wet: return False # water and land never interact
return t_trapped or self.outranks(t) # trapped target has rank 0
class Rat(Piece):
rank, symbol, swims = 1, "r", True
def outranks(self, t): return isinstance(t, (Elephant, Rat))
class Cat(Piece): rank, symbol = 2, "c"
class Dog(Piece): rank, symbol = 3, "d"
class Wolf(Piece): rank, symbol = 4, "w"
class Leopard(Piece): rank, symbol = 5, "p"
class Tiger(Piece): rank, symbol, jumps = 6, "t", True
class Lion(Piece): rank, symbol, jumps = 7, "l", True
class Elephant(Piece):
rank, symbol = 8, "e"
def outranks(self, t): return not isinstance(t, Rat)
class Board:
def __init__(self): self.grid = {}
def place(self, piece, pos):
r, c = pos
if not (0 <= r < ROWS and 0 <= c < COLS) or pos in self.grid:
raise ValueError("bad square")
if pos in WATER and not piece.swims:
raise ValueError("land animal in water")
if pos == DEN[piece.side]:
raise ValueError("own den")
self.grid[pos] = piece
def _landing(self, pos, d):
r, c = pos[0] + d[0], pos[1] + d[1]
while (r, c) in WATER:
if (r, c) in self.grid: return None # a swimming rat blocks
r, c = r + d[0], c + d[1]
return (r, c) if 0 <= r < ROWS and 0 <= c < COLS else None
def _enterable(self, p, src, dst):
if dst == DEN[p.side]: return False
t = self.grid.get(dst)
if t is None: return True
if t.side == p.side: return False
return p.can_capture(t, src in WATER, dst in WATER, dst in TRAPS[p.side])
def legal_moves(self, pos):
p = self.grid.get(pos)
if p is None: return []
out = []
for d in DIRS:
dst = (pos[0] + d[0], pos[1] + d[1])
if not (0 <= dst[0] < ROWS and 0 <= dst[1] < COLS): continue
if dst in WATER and not p.swims:
dst = self._landing(pos, d) if p.jumps else None
if dst is None: continue
if self._enterable(p, pos, dst): out.append(dst)
return out
def render(self):
dens = set(DEN.values())
traps = TRAPS[Side.TOP] | TRAPS[Side.BOTTOM]
lines = []
for r in range(ROWS):
row = ""
for c in range(COLS):
p = self.grid.get((r, c))
if p: row += p.symbol.upper() if p.side == Side.BOTTOM else p.symbol
elif (r, c) in WATER: row += "~"
elif (r, c) in dens: row += "*"
elif (r, c) in traps: row += "#"
else: row += "."
lines.append(row)
return "\n".join(lines)
class Game:
def __init__(self, board=None, turn=Side.BOTTOM):
self.board, self.turn, self.winner = board or Board(), turn, None
@classmethod
def standard(cls):
g = cls()
layout = {(0,0): Lion, (0,6): Tiger, (1,1): Dog, (1,5): Cat,
(2,0): Rat, (2,2): Leopard, (2,4): Wolf, (2,6): Elephant}
for (r, c), kind in layout.items():
g.board.place(kind(Side.TOP), (r, c))
g.board.place(kind(Side.BOTTOM), (8 - r, 6 - c)) # rotated copy
return g
def move(self, src, dst):
if self.winner: raise ValueError("game over")
p = self.board.grid.get(src)
if p is None or p.side != self.turn: raise ValueError("wrong piece or turn")
if dst not in self.board.legal_moves(src): raise ValueError("illegal move")
grid = self.board.grid
captured = grid.pop(dst, None)
grid[dst] = grid.pop(src)
foe = p.side.foe
stuck = not any(self.board.legal_moves(q) for q, x in list(grid.items()) if x.side == foe)
if dst == DEN[foe] or stuck: self.winner = p.side
else: self.turn = foe
return captured
Move generation costs O(4) per piece (a jump scans at most 3 squares), so checking "does the opponent have any move" is O(16 x 4) per turn, which is trivial.
4. Tests
- Setup:
Game.standard()holds 16 pieces.render()showslat(0,0),Lat(8,6),~in both lakes, and Bottom moves first. - Lion jump capture: on an empty board, put a bottom Lion at
(6,1), a top Dog at(2,1), and a spare top Cat at(0,0)so the game does not end by stalemate.legal_moves((6,1))contains(2,1)andmovereturns the Dog. Add a top Rat at(4,1)and that destination disappears. - Several turns: Elephant
(6,0)->(5,0), Rat(2,0)->(3,0), Elephant(5,0)->(4,0), Rat(3,0)->(4,0)captures the Elephant. Also assert that the same side moving twice raisesValueError.
Further edge cases: a water Rat cannot take a land Elephant, an Elephant cannot take a Rat, a piece cannot enter its own den, an enemy Elephant in my trap is taken by my Cat, and a side with no moves loses.
5. Trade-offs and common mistakes
- Type checks in the board:
if isinstance(p, Rat)scattered through move generation defeats extensibility. Keep species knowledge in the piece classes. - Mutating rank for traps: changing a piece's rank when it enters a trap leaks state and breaks when it leaves. Derive the effect from the square instead.
- Forgetting the water/land barrier: a Rat in a lake and a land piece next to it must not interact in either direction.
- Jump blocking: check every water square on the path, not just the first one.
- Mixing rules with I/O: keep
render()free of game logic so it can be swapped for a GUI later. - Alternative: a data-driven table of rank and abilities is shorter, but subclasses make special rules (Rat vs Elephant) explicit and individually testable.