AlgoViz

Design chess

hard 90 min

Model 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

0:00 / 4:35

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

  1. 1970

    Albert Zobrist describes a hashing method for game playing that updates a position's hash with a few XORs.

  2. 1993

    Steven J. Edwards devises PGN, a text format for whole games.

  3. 1996

    Bobby Fischer introduces Chess960, with a random back rank.

  4. 1997

    The computer Deep Blue wins its second match against the world champion Garry Kasparov in New York, in May.

  5. 2000

    The Universal Chess Interface is released in November. Screens and engines become separate programs.

  6. 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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 4

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.

Tower, king and herald
ABCDEF321

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

Special moves come after ordinary moves work, and before the clock.

Domain

The rules that become code

PieceHitsMovesClass
RookStraight lines until something is in the wayThe same, not onto a friendSlider
BishopDiagonalsThe sameSlider
QueenRook and bishop togetherThe sameSlider
KnightTwo and one, over othersThe sameStepper
KingOne step in eight directionsThe same, and castlingStepper, plus Rules
PawnOne step diagonally forwardOne or two straight onto empty squares, captures diagonallyIts own

Four special moves, and what each one forces

MoveRuleForces
CastlingKing two steps to a rook. Neither has moved, nothing between, king not hit at the start, on the way or at the endRights in the position, a move of two pieces
En passantA pawn that jumped two may be taken as if it had stepped one, only on the next moveA square in the position, captured_at in Undo
PromotionA pawn on the last row becomes queen, rook, bishop or knightA letter in the move, a factory
Double stepOnly from the first row, both squares emptyA row test, no flag

Is the game over?

Articles 5 and 9 of the FIDE Laws of Chess in effect from January 2023. Three and fifty must be claimed. Five and seventy-five end the game.

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

64holdsknowsBoard- cells: Cell[8][8]- whiteKing: Cell+ movePiece(from, to)Cell- row, col- piece: Piece«abstract»Piece- cell: Cell- hasMoved: bool+ canMove(board, to)# isValidMove(to)# wouldExposeKing(to)Six subclasses

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)

Python
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 ...")
The bug in eight lines. in_check asks can_move, and can_move asks in_check. Run it.
Edit and run it in your browser

Target

The design to reach

The design to reach: pieces know steps, rules know kings, the game knows turns

«abstract»Piece+ color: Color+ attacks(board, at)+ moves(board, at)«abstract»Sliderdirections«abstract»StepperstepsPawnRook, Bishop, QueenKnight, King

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

ClassStateAnswersDoes not know
PieceColourWhich squares do I hit from here?Its square, the king, the turn
BoardSquare to pieceWho is there? Who hits this square?Turns, history
PositionBoard, turn, castling, en passant, quietWhat is the state after this move, and before it?Whether the move is legal
RulesNothingWhich moves are legal?Who the players are
GameHistory, counts, statusMay this player do this now? Is it over?How a knight walks

The life of a game

Check is not in it. White and black to move are a field, not states: all rules are the same for both.

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_move asks 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, ask hit_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

20 candidates×16 enemy pieces=320 attack questions20\ \text{candidates} \times 16\ \text{enemy pieces} = 320\ \text{attack questions}
For people at a board this is nothing. For a search that visits a million positions it is 320 million, which is why engines use masks and tables.

Known counts of move sequences from the start

Half movesSequencesWhy useful
12016 pawn moves, 4 knight moves
240020 x 20
38,902First captures and checks: our code gives this number
4197,281First mates appear
54,865,609First en passant captures. A wrong rule shows here
These counts are called perft. Published values let you test a generator without trusting your own idea of the rules.

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 Cell class around a square
  • A CheckDetector and a SpecialMoveHandler
  • 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.
  • attacks and moves are two methods. The pawn and the pin both need it.
  • Legal means: candidate, applied, king not hit, reverted.
  • Undo holds 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