Chess Board Model
Low-Level Design: lesson 15 of 15
The piece owns its shape; the board owns who is standing where.
Lesson 15 of 15 · 7 min
Chess Board Model
Step 1 of 9
Two objects, two halves of one question. The piece owns shape; the board owns who is standing where.
The Idea
Cut the question in two. A piece answers only about geometry — is this offset shaped like my move? The board answers about occupancy — is the path clear, is the target one of mine, is it my turn?
Neither object needs the other's data, so a new piece is a new class and nothing else.
Real-World Example
A choreographer and a stage manager. The choreographer says a dancer may travel diagonally; the stage manager says that wing is blocked tonight. A step happens only when both agree.
The Code
class Rook:
def shape_ok(self, a, b): return a[0] == b[0] or a[1] == b[1]
class Knight:
def shape_ok(self, a, b):
return sorted((abs(a[0] - b[0]), abs(a[1] - b[1]))) == [1, 2]
class Board:
def __init__(self, pieces): self.pieces = pieces # square -> piece
def legal(self, a, b): # geometry, then state
piece = self.pieces.get(a)
return bool(piece) and piece.shape_ok(a, b) and b not in self.pieces
b = Board({(0, 0): Rook(), (1, 0): Knight()})
print(b.legal((0, 0), (0, 5)), b.legal((1, 0), (2, 2)), b.legal((0, 0), (1, 0)))
# True True FalseThe Tradeoff
Per-piece geometry keeps the board tiny, but every sliding piece repeats the walk-the-squares-between loop, and castling, en passant and check span pieces — so they land on the board anyway. A move-rule table is more uniform and much harder to read.
Your turn
Put the steps in the right order.
- The board also confirms the target square is empty or holds an opponent
- A move request names a from-square and a to-square
- The board looks up which piece is standing on the from-square
- That piece answers whether the offset matches its own movement shape
Mini quiz
1 / 3