Learn / System Design
Module 10 · System Design · Six more low-level rounds
Continue where you left off ×
Design chess (pieces that know their own moves)
Design Chess · Open board
Pieces that answer one question, legal moves as pseudo-legal minus check, the move as a command, and two players pressing at once.
Before you start. You need three lessons. Has-a beats is-a (composition over inheritance) showed a class holding another class as a part (composition) and many classes answering one call in their own way. Tell everyone who cares (Observer and State) showed a state machine: a thing that is always in exactly one named state and moves between them on events. Design a parking lot (the first whole round) showed the shape of a whole interview round, questions first, then entities, then one tricky interaction. You do not need to play chess.
The idea in 30 seconds
A chess round is classes for pieces, a board, a move and a game, and each holds one kind of rule.
Polymorphism: every piece answers moves(board, square) in its own way, so no code asks what kind of piece it holds.
Sliding pieces share one Slider part. They have it, they are not descended from each other.
The board holds where everyone stands, and passes the square to the piece.
Move validation: pseudo-legal moves minus those that leave your own king attacked. The pinned bishop has 9 candidates and 0 legal moves.
A move is a command object with execute and undo, so validation and the undo button share one tool. The game state is worked out from the legal moves.
Read the story
Lesson 49 of 73 in System Design
The rest of this lesson is part of a plan.
A plan opens every lesson, board, video, lab and paper on chalk. Yearly is $39/year , or $19.50 for your first year with LAUNCH50 , ends 1 Nov, 18:30 UTC .
See plans Already a member? Sign in
Or start free : a free account opens lessons 2 and 3 of every track.
In this lesson May 1997: a machine that had to know every legal move The obvious way: one function with a long if-chain Each piece answers moves: polymorphism The board knows where everyone stands Move validation: the move that exposes your own king A move is an object: the command pattern Game state: whose turn it is, and what is happening Terms it explains: polymorphism, board, file, rank, pinned, move validation, command pattern, game state, chess clock, expected move number.
Review System Design
Mark as read Saved in this browser, and to your account when you sign in.