Design chess
hard 90 minModel chess with classes that each know one thing: pieces know their steps, rules know about the king, the game knows whose turn it is.
Video lesson · Chapter 1 of 6
Make a prediction
Theory
Read or listen first. About 2 min.
What it is
Chess in a low-level design round is the object model of a board game with strict rules: six kinds of pieces, turns, special moves, and an end that depends on a piece that does not move.
It is a problem of ownership. Where a piece stands, whose turn it is, which rights are left: each fact needs exactly one owner, or undo and check become guesswork.
The answer has five moving parts: pieces, board, position, rules and game, and two records, the move and what it destroyed.
Why it exists
It is one of the few popular exercises where a class hierarchy is really right, so it shows whether you can tell when inheritance is earned.
It hides a trap: legality depends on check, and check seems to depend on legality. Seeing that attack and legal move differ is the turning point.
It grows naturally. Undo, clocks, computer players, ratings and online rooms each test another skill without changing the core.
A short history
1970
Albert Zobrist describes a hashing method for game playing that updates a position's hash with a few XORs.
1993
Steven J. Edwards devises PGN, a text format for whole games.
1996
Bobby Fischer introduces Chess960, with a random back rank.
1997
The computer Deep Blue wins its second match against the world champion Garry Kasparov in New York, in May.
2000
The Universal Chess Interface is released in November. Screens and engines become separate programs.
2023
The present FIDE Laws of Chess take effect on 1 January.
Words to know
- Attack
- To hit a square, whether or not the piece may legally go there.
- Legal move
- A move after which the own king is not hit.
- Pseudo-legal move
- A move that follows the piece's steps, king not considered. In this text: candidate.
- Pin
- A piece that may not leave a line because its king is behind it.
- Half move, ply
- One move of one side.
- Check, mate, stalemate
- King hit. King hit and no legal move. King not hit and no legal move.
- En passant
- Taking a pawn that has just jumped two squares, as if it had stepped one.
- FEN and PGN
- Text for one position, text for one game.
- Perft
- The number of move sequences of a given length. A test of the rules.
- Quiet move
- No capture and no pawn move. 100 of them in half moves allow a draw claim.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Ask. The game checks the turn and looks the move up in the legal list
Understand it
Story
Living chess in the castle yard
Once a year the people of a small town play chess with themselves as the pieces. Who knows what in this yard is exactly the question of this interview.
The herald has not learned any steps. The tower has never thought about the king. The yard has no opinion. That is the design.
What an interviewer looks for here
Who owns a fact
Where a piece stands must be written in one place.
Inheritance that earns it
Six kinds, six behaviours, two shared loops.
Attack is not move
The sentence that separates a working design from a stack overflow.
Undo without loss
Castling rights, en passant and counters come back.
Scope
Castling, en passant and promotion are named early and added in order.
Proof
Known move counts: 20, 400, 8902.
How to spend the round
Domain
The rules that become code
| Piece | Hits | Moves | Class |
|---|---|---|---|
| Rook | Straight lines until something is in the way | The same, not onto a friend | Slider |
| Bishop | Diagonals | The same | Slider |
| Queen | Rook and bishop together | The same | Slider |
| Knight | Two and one, over others | The same | Stepper |
| King | One step in eight directions | The same, and castling | Stepper, plus Rules |
| Pawn | One step diagonally forward | One or two straight onto empty squares, captures diagonally | Its own |
Four special moves, and what each one forces
| Move | Rule | Forces |
|---|---|---|
| Castling | King two steps to a rook. Neither has moved, nothing between, king not hit at the start, on the way or at the end | Rights in the position, a move of two pieces |
| En passant | A pawn that jumped two may be taken as if it had stepped one, only on the next move | A square in the position, captured_at in Undo |
| Promotion | A pawn on the last row becomes queen, rook, bishop or knight | A letter in the move, a factory |
| Double step | Only from the first row, both squares empty | A row test, no flag |
Is the game over?
Avoid
The design most people draw first
Nouns become classes and verbs become helper classes. It looks tidy, and the same fact lives in three places.
The design to avoid: three helpers judge, three classes know where a piece stands
1/4Three owners of one fact
The cell holds the piece, the piece knows its cell, the board also knows the king's cell. Every move has to change all three, and every undo has to change all three back.
usesowns (dies together)has (lives on)extends (is a)
class Side: def __init__(self, name): self.name, self.enemy = name, None def can_move(self, target): # "legal" includes: my king must be safe return not self.in_check() def in_check(self): # some enemy piece can move to my king return self.enemy.can_move("my king")white, black = Side("white"), Side("black")white.enemy, black.enemy = black, whitetry: white.can_move("e4")except RecursionError: print("white asks black asks white asks black ...")in_check asks can_move, and can_move asks in_check. Run it.Target
The design to reach
The design to reach: pieces know steps, rules know kings, the game knows turns
1/5Pieces
Six kinds with six different behaviours: here a class tree earns its place. A piece answers one question, which squares it hits. It does not know where it stands.
usesowns (dies together)depends onhas (lives on)extends (is a)
State
What each class owns
| Class | State | Answers | Does not know |
|---|---|---|---|
Piece | Colour | Which squares do I hit from here? | Its square, the king, the turn |
Board | Square to piece | Who is there? Who hits this square? | Turns, history |
Position | Board, turn, castling, en passant, quiet | What is the state after this move, and before it? | Whether the move is legal |
Rules | Nothing | Which moves are legal? | Who the players are |
Game | History, counts, status | May this player do this now? Is it over? | How a knight walks |
The life of a game
Decision
How should check be found?
A piece wants to move. How do you find out whether its king would be hit?
BreaksAsk every enemy piece can_move(king)
- How
- Reuse the legal-move method.
- Limit
can_moveasks about the other king. Endless recursion, and pinned pieces would not give check.- Choose when
- Never.
WorksCopy the board and look
- How
- Deep copy, move on the copy, ask which squares are attacked.
- Limit
- One copy of up to 32 pieces for each candidate, about 30 times a move.
- Choose when
- Fine for two people. Simple to explain.
StrongApply, look, revert
- How
- One board. Apply returns an
Undo, askhit_by, revert. - Limit
- Revert must be exact. Prove it with move counts. Not safe for two threads on one board.
- Choose when
- The default: undo is needed anyway.
StrongPin and check masks
- How
- Compute checkers and pinned pieces once per position, then most moves need no trial.
- Limit
- More code, and the en passant row case needs its own test.
- Choose when
- Engines. Say it, do not write it.
Where does has the king moved? live?
Breakshas_moved on the piece
- How
- Set it in
move_to. - Limit
- Undo forgets it. A position loaded from text has no history. A captured and promoted rook confuses it.
- Choose when
- Only without undo, load and repetition.
WorksSearch the history
- How
- Has any move started on e1?
- Limit
- A position set up in the middle has no history. O(n).
- Choose when
- A toy game from the start.
StrongRights in the position
- How
- A set of corners, reduced by each move, restored by
Undo. - Limit
- One more field.
- Choose when
- Always. It is also what a FEN text stores.
Numbers
What a move costs
Work to list legal moves at the start
Known counts of move sequences from the start
| Half moves | Sequences | Why useful |
|---|---|---|
| 1 | 20 | 16 pawn moves, 4 knight moves |
| 2 | 400 | 20 x 20 |
| 3 | 8,902 | First captures and checks: our code gives this number |
| 4 | 197,281 | First mates appear |
| 5 | 4,865,609 | First en passant captures. A wrong rule shows here |
Earned here
- Subclasses of
Piece: behaviour differs - Template Method in
moves - Undo record as a Command
- Listeners for screen, clock and log
- A dictionary as a factory
Not earned
- A
Cellclass around a square - A
CheckDetectorand aSpecialMoveHandler - State classes for white's turn and black's turn
- A Singleton game
- Human and computer subclasses inside
Game
Summary
The whole topic in one minute.
Pieces say which squares they hit and know nothing else. The board alone knows who stands where. The position adds turn, castling rights, the en passant square and a counter, and can apply a move and take it back exactly.
Rules make candidates and keep those after which the king is not hit. The game checks the turn, plays, judges the end and tells its listeners. Check is a question, not a state.
- Pieces know steps, rules know kings, the game knows turns.
attacksandmovesare two methods. The pawn and the pin both need it.- Legal means: candidate, applied, king not hit, reverted.
Undoholds what cannot be worked out again: captured piece and place, castling, en passant, quiet counter.- Check is a fact about a position. Mate and stalemate are no legal move, with and without it.
- Prove it with 20, 400 and 8,902.
Sources
- FIDE Laws of Chess, from 1 January 2023
- Chess Programming Wiki: perft results
- Chess Programming Wiki: make move
- Stockfish source
- python-chess: core
- scalachess
- chess.js
- shakmaty
- Wikipedia: Universal Chess Interface
- Wikipedia: Portable Game Notation
- Wikipedia: Zobrist hashing
- Wikipedia: Glicko rating system
- Wikipedia: Chess960
- Wikipedia: Deep Blue versus Garry Kasparov