Design Chess
♟️ What is a chess game system? It is the code behind a chess app. Two players take turns moving pieces on an 8×8 board. The system checks that every move follows the rules, refuses the ones that don't, tells the players when a king is in check, and ends the game on checkmate or stalemate. It also remembers every move, so a player can take one back.
Chess is a favorite hard problem in low-level design interviews. The board is easy; the rules are not. Six piece types move in different ways, a move that looks fine can be illegal because it exposes your own king, and "is the game over?" needs a search over every move the other side could make. The interviewer wants to see whether you can keep all of that in clean, separate places.
Requests for "move validation", "check and checkmate", "multiplayer chess" and "chess with move history" are all this same design. Move validation and check detection are the core of the Implementation section, move history becomes an undo feature built on a Move record, and multiplayer (players, online games, clocks) is a follow-up in Extensibility.
Requirements
"Design a chess game for two players. It should reject illegal moves and know when the game is over."
Chess has a lot of rules, and you do not have time to code all of them in 45 minutes. The questions below decide which rules are in, how a move is described, and what the game reports back.
Clarifying Questions
You: How much of the rule book do you want? Castling, en passant and pawn promotion are all special cases.
Interviewer: Normal movement for all six pieces, captures, check, checkmate and stalemate. Promote a pawn to a queen automatically. Leave castling and en passant out for now; we may come back to them.
You: How does a player describe a move?
Interviewer: By two squares, in the usual names: move("e2", "e4").
You: What should the game say after a move?
Interviewer: Whether it was rejected. If it was accepted, whether it gives check, checkmate or stalemate.
You: Which draws count? There is repetition, the fifty-move rule, not enough material...
Interviewer: Only stalemate for now.
You: Do we need a move history?
Interviewer: Yes. List the moves made so far, and let a player take back the last move.
You: Are the two players on one device, or online?
Interviewer: One device for the core design. Talk about online play at the end.
You: Clocks or time controls?
Interviewer: Not now.
The first answer is the most important one. It gives us a clear boundary: we build the general mechanism (generate moves, reject the ones that leave the king in check), and the special moves become a follow-up that should plug into that mechanism without rewriting it.
💡 Interview tip: In chess, say early that you will leave castling and en passant for later, and ask whether that is fine. Interviewers almost always agree, and it saves you from spending twenty minutes on edge cases before the core works.
Final Requirements
- The game starts from the standard position. White moves first, then the players alternate.
- A move names a source square and a target square. It is rejected if the source is empty, holds the other side's piece, or the move breaks a rule.
- Each piece moves by its own rule. Rooks, bishops and queens slide and cannot jump over pieces; knights jump; kings step one square; pawns move forward and capture diagonally, with a two-square first move.
- A move may capture an enemy piece but never land on a friendly one.
- A move is legal only if the mover's own king is not attacked afterwards.
- After each move the game reports one of: check, checkmate, stalemate, or a normal move. Checkmate and stalemate end the game; after that every move is rejected.
- A pawn that reaches the last rank becomes a queen.
- The game keeps the list of moves made, and the last move can be taken back, restoring any captured piece.
Out of scope
- Castling and en passant (Extensibility).
- Choosing the promotion piece, other draw rules, and resigning.
- Clocks, ratings, and online play (Extensibility).
- A user interface, and computer opponents.
Entities and Relationships
Underline the nouns in the requirements and keep the ones that hold state or enforce a rule.
- ChessGame: the entry point. It owns the board, knows whose turn it is and whether the game is over, keeps the move history, and is the only class the players talk to.
- Board: the 8×8 grid of squares, each empty or holding a piece. It can answer "what is on this square?" and "is this square attacked by that color?".
- Piece: a piece of one color and one kind. Its job is to know how it moves. There are six kinds: king, queen, rook, bishop, knight and pawn.
- Move: the record of one move: where it went from and to, which piece moved, what it captured, and what it promoted to. The history is a list of these, and undo reads them backwards.
Some nouns look like classes but are not worth one:
- Player is just a color in this design. Both players sit at one device, so there is nothing to store about them. When online play comes in, a real
Playerappears (Extensibility 4). - Square is a pair of numbers
(row, col). A class would add nothing but ceremony. - Color (white, black) and GameStatus (active, checkmate, stalemate) are enums.
Who owns whom:
| Owner | Owns | How many |
|---|---|---|
| ChessGame | Board | exactly one |
| Board | Piece | up to 32, one per occupied square |
| ChessGame | Move | one per move made, in order |
| Move | Piece (references) | the mover, plus the captured piece and the promoted queen if any |
Class Design
We go top down from the class the players call. The rule for a good orchestrator: it decides the order of steps, and each step is someone else's job. ChessGame should not know how a knight moves; it should ask the knight.
ChessGame
The orchestrator. It answers the five requests a chess app needs: make a move, list a piece's legal moves (to highlight squares on screen), read a square, undo, and show the history.
class ChessGame:
board: Board
turn: Color # requirement 1
status: GameStatus # requirement 6: ACTIVE until checkmate or stalemate
moves: List[Move] # requirement 8: the history, oldest first
def move(self, frm: str, to: str) -> str: ... # "INVALID", "OK", "CHECK", "CHECKMATE", "STALEMATE"
def legal_moves(self, square: str) -> List[str]: ...
def piece_at(self, square: str) -> str: ... # "wK", "bP", or "" for empty
def undo(self) -> bool: ...
def history(self) -> List[str]: ... # ["e2e4", "e7e5", ...]
move returns a string instead of raising an exception because a rejected move is a normal event in a game, not an error in the program. legal_moves is not strictly required, but almost every chess app highlights the squares a piece can reach, and it falls out of the validation code for free.
Board
The grid and the questions you can ask about it. It knows nothing about turns or history.
class Board:
grid: List[List[Optional[Piece]]] # grid[row][col], row 0 is rank 1, col 0 is file a
def get(self, sq: Square) -> Optional[Piece]: ...
def set(self, sq: Square, piece: Optional[Piece]) -> None: ...
def pieces(self, color: Color) -> List[Tuple[Square, Piece]]: ...
def find_king(self, color: Color) -> Square: ...
def is_attacked(self, sq: Square, by: Color) -> bool: ... # requirement 5
def apply(self, move: Move) -> None: ...
def revert(self, move: Move) -> None: ...
is_attacked lives on the board because it needs to look at every piece, and the board is the class that has them all. apply and revert are the only methods that change the grid for a move, so captures and promotions are handled in exactly one place.
Piece
class Piece:
color: Color
symbol: str # "K", "Q", "R", "B", "N", "P"
def candidate_moves(self, board: Board, frm: Square) -> List[Square]: ...
A piece answers one question: "from this square, on this board, where could I go by my own movement rule?" These are candidate moves: they follow the piece's pattern (requirements 3 and 4) but ignore check. Whether a candidate is actually legal is the game's question, because it depends on the whole position. Keeping those two questions apart is the most important design decision in this problem.
Each of the six kinds is a subclass. Unlike the vehicles in /low-level-design/parking-lot, which differed only in a lookup value, chess pieces really do behave differently, so here inheritance earns its place. How much code each subclass needs is the first choice in the Implementation section.
Move
@dataclass
class Move:
frm: Square
to: Square
piece: Piece # who moved
captured: Optional[Piece] # what stood on `to`, so undo can put it back
promoted_to: Optional[Piece] # the new queen if a pawn reached the last rank
def notation(self) -> str: ... # "e2e4"
A move stores everything needed to reverse it. That one decision powers three features: trying a move during validation, undo, and the history list.
The enums:
class Color(Enum):
WHITE = "w"
BLACK = "b"
def opponent(self) -> "Color":
return Color.BLACK if self is Color.WHITE else Color.WHITE
class GameStatus(Enum):
ACTIVE = "ACTIVE"
CHECKMATE = "CHECKMATE"
STALEMATE = "STALEMATE"
Implementation
We build from the bottom up this time, because each layer depends on the one below: first how pieces move, then which of those moves are legal, then what a move does to the game.
Squares come in as names like "e2". Two tiny helpers turn them into (row, col) pairs and back:
def to_square(name: str) -> Square:
return (int(name[1]) - 1, ord(name[0]) - ord("a")) # "e2" -> (1, 4)
def to_name(sq: Square) -> str:
return chr(ord("a") + sq[1]) + str(sq[0] + 1) # (1, 4) -> "e2"
Generating a piece's moves
Every piece needs candidate_moves. The question is where that logic lives and how much of it repeats.
Bad Solution: one function with a branch per piece
Approach
Write a single function that checks the piece type and runs the matching loop.
def candidate_moves(board: Board, frm: Square) -> List[Square]:
piece = board.get(frm)
if piece.kind == "ROOK":
... # four loops, one per direction
elif piece.kind == "BISHOP":
... # four more loops
elif piece.kind == "QUEEN":
... # all eight
elif piece.kind == "KNIGHT":
...
# and so on for king and pawn
Challenges
It works, and it is how many first drafts look. But the function grows to well over a hundred lines, the queen's code is a copy of the rook's plus the bishop's, and every change (a new fairy-chess piece, a bug fix in sliding) means editing the same giant function. It is also impossible to test the knight on its own. This is the type switch smell from /low-level-design/anti-patterns.
Good Solution: a subclass per piece
Approach
Give each kind its own class with its own candidate_moves. The rook walks four directions, the bishop walks four diagonals, and so on.
class Rook(Piece):
def candidate_moves(self, board: Board, frm: Square) -> List[Square]:
moves = []
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
r, c = frm[0] + dr, frm[1] + dc
while board.in_bounds((r, c)):
... # add empty squares, stop at the first piece
r, c = r + dr, c + dc
return moves
Challenges
Each piece is now small and testable, and the game just calls piece.candidate_moves(...) without caring which kind it is. That is polymorphism doing real work. The weakness is repetition: the rook, bishop and queen all contain the same "slide until blocked" loop with different directions, and the knight and king share the same "jump to fixed offsets" loop. Three copies of one loop means three places for the same bug.
Great Solution: share the two movement styles
Approach
Look at what actually differs. Rooks, bishops and queens all slide along a set of directions until something is in the way; they differ only in the directions. Knights and kings both step to a fixed set of offsets; they differ only in the offsets. So we write each loop once and let the subclasses supply data.
ROOK_DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
BISHOP_DIRS = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
class SlidingPiece(Piece):
directions: List[Tuple[int, int]] = []
def candidate_moves(self, board: Board, frm: Square) -> List[Square]:
moves = []
for dr, dc in self.directions:
r, c = frm[0] + dr, frm[1] + dc
while board.in_bounds((r, c)):
target = board.get((r, c))
if target is None:
moves.append((r, c))
else:
if target.color != self.color:
moves.append((r, c)) # capture, then stop
break
r, c = r + dr, c + dc
return moves
class Rook(SlidingPiece):
symbol = "R"
directions = ROOK_DIRS
class Queen(SlidingPiece):
symbol = "Q"
directions = ROOK_DIRS + BISHOP_DIRS # a queen is a rook plus a bishop
The stepping pieces work the same way:
class SteppingPiece(Piece):
offsets: List[Tuple[int, int]] = []
def candidate_moves(self, board: Board, frm: Square) -> List[Square]:
moves = []
for dr, dc in self.offsets:
to = (frm[0] + dr, frm[1] + dc)
if board.in_bounds(to):
target = board.get(to)
if target is None or target.color != self.color:
moves.append(to)
return moves
class Knight(SteppingPiece):
symbol = "N"
offsets = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]
class King(SteppingPiece):
symbol = "K"
offsets = ROOK_DIRS + BISHOP_DIRS # one step in any direction
Challenges
The pawn does not fit either style, and that is fine: it gets its own class with its own rules, shown next. This is the Template Method idea in a light form: the base class owns the loop, the subclass fills in the part that varies. Five of the six pieces are now one-line data declarations, and the queen's definition reads exactly like the rule book.
⚠️ Common mistake: Making
Queeninherit from bothRookandBishop. It looks clever, but multiple inheritance of behavior gets confusing fast, and many languages forbid it. Sharing a direction list says the same thing with no tricks.
The pawn is the odd one out. It moves forward but captures diagonally, its direction depends on its color, and it may move two squares from its starting row.
class Pawn(Piece):
symbol = "P"
def candidate_moves(self, board: Board, frm: Square) -> List[Square]:
step = 1 if self.color is Color.WHITE else -1
start_row = 1 if self.color is Color.WHITE else 6
r, c = frm
moves = []
one = (r + step, c)
if board.in_bounds(one) and board.get(one) is None:
moves.append(one)
two = (r + 2 * step, c)
if r == start_row and board.get(two) is None:
moves.append(two)
for dc in (-1, 1):
diag = (r + step, c + dc)
if board.in_bounds(diag):
target = board.get(diag)
if target is not None and target.color != self.color:
moves.append(diag) # pawns capture diagonally only
return moves
Notice that the two-square move is nested inside the one-square check: if the square right in front is blocked, the pawn cannot jump over it. A pawn on its last row would step off the board, but that never happens, because it is promoted the moment it arrives.
Validating a move: does it leave your king in check?
Candidate moves follow each piece's pattern, but requirement 5 adds a rule that no single piece can check on its own: after your move, your king must not be attacked. This rule is what makes chess hard. It covers three cases that look different but are the same thing:
- a king may not step onto an attacked square;
- a pinned piece (one standing between its king and an enemy slider) may not step out of the line;
- a player in check must answer it, by moving the king, capturing the attacker or blocking.
Bad Solution: movement rules only
Approach
Accept any candidate move, and treat check as something to report afterwards.
def move(self, frm: str, to: str) -> str:
src, dst = to_square(frm), to_square(to)
piece = self.board.get(src)
if piece is None or piece.color != self.turn:
return "INVALID"
if dst not in piece.candidate_moves(self.board, src):
return "INVALID"
... # make the move
Challenges
This is not chess. A player can leave their king in check, walk it into an attack, or move a pinned piece. The game can even end with a king being captured, which never happens in real chess. You could try to patch it with special cases ("if the king is in check, only allow king moves"), but that is wrong too: blocking and capturing the attacker are also valid answers. Special cases will never cover pins correctly.
Good Solution: try the move on a copy of the board
Approach
The rule is about the position after the move, so build that position and look at it. For every candidate, copy the board, make the move on the copy, and ask whether the mover's king is attacked there.
import copy
def _legal_targets(self, src: Square) -> List[Square]:
piece = self.board.get(src)
legal = []
for dst in piece.candidate_moves(self.board, src):
trial = copy.deepcopy(self.board)
trial.set(dst, piece)
trial.set(src, None)
if not trial.is_attacked(trial.find_king(piece.color), piece.color.opponent()):
legal.append(dst)
return legal
Challenges
This is correct, and it handles all three cases (king moves, pins, answering check) with no special code at all. That is the big win, and in an interview it is a perfectly good answer. The cost is copying: every candidate copies 64 squares and the pieces on them, and checkmate detection (below) tries every move of every piece. It also duplicates "what does a move do to the board" in a second place, which will hurt when promotion and, later, castling arrive.
Great Solution: make the move, test it, take it back
Approach
Make the trial move on the real board with the same Move record that history uses, test the king, then revert it. apply and revert are each two lines, and they are the only code in the program that knows how a move changes the board.
def apply(self, move: Move) -> None: # on Board
self.set(move.to, move.promoted_to or move.piece)
self.set(move.frm, None)
def revert(self, move: Move) -> None:
self.set(move.frm, move.piece)
self.set(move.to, move.captured)
def _legal_targets(self, src: Square) -> List[Square]: # on ChessGame
"""Candidate moves that do not leave the mover's own king attacked."""
piece = self.board.get(src)
legal = []
for dst in piece.candidate_moves(self.board, src):
move = self._build_move(src, dst)
self.board.apply(move) # try it ...
if not self.board.is_attacked(self.board.find_king(piece.color), piece.color.opponent()):
legal.append(dst)
self.board.revert(move) # ... and take it back
return legal
_build_move creates the Move record, including the captured piece and the promotion:
def _build_move(self, src: Square, dst: Square) -> Move:
piece = self.board.get(src)
promoted = None
if isinstance(piece, Pawn) and dst[0] in (0, 7):
promoted = Queen(piece.color) # requirement 7: always a queen
return Move(src, dst, piece, self.board.get(dst), promoted)
Challenges
No copies, and one definition of "what a move does" shared by validation, real moves and undo. This is the make/unmake technique that real chess engines use. The risk is that revert must restore the board exactly; if it ever leaves something behind, later checks go wrong in confusing ways. That is why Move stores the captured piece and the promotion explicitly instead of trying to recompute them, and why the tests run long random games with undo mixed in.
Now the question both solutions rely on: is a square attacked? The simplest correct version reuses the pieces' own rules.
def is_attacked(self, sq: Square, by: Color) -> bool: # on Board
return any(sq in piece.candidate_moves(self, frm) for frm, piece in self.pieces(by))
There is one subtle point. A pawn's candidate moves include forward steps, and a forward step is not an attack. Here that is harmless, because we only ever ask about the square a king stands on, and a pawn can never step forward onto an occupied square. If you later need to ask about an empty square (castling does), you will need a separate "attacks" method for pawns. Say this out loud; it shows the interviewer you know where the shortcut stops working.
💡 Interview tip: If the interviewer asks about speed, mention the faster check: start from the king and look outward along the eight lines and the eight knight jumps for an enemy piece that could hit it. That is about 30 squares instead of every enemy move. For a two-player app it does not matter, so build the simple version first.
Making the move and ending the game
With validation in place, move reads like the requirements:
def move(self, frm: str, to: str) -> str:
if self.status is not GameStatus.ACTIVE: # requirement 6
return "INVALID"
src, dst = to_square(frm), to_square(to)
piece = self.board.get(src)
if piece is None or piece.color != self.turn: # requirement 2
return "INVALID"
if dst not in self._legal_targets(src): # requirements 3-5
return "INVALID"
move = self._build_move(src, dst)
self.board.apply(move)
self.moves.append(move) # requirement 8
self.turn = self.turn.opponent()
return self._update_status()
After the move, it is the other player's turn, and two facts decide everything: is that player's king attacked, and does that player have any legal move at all?
| King attacked? | Any legal move? | Result |
|---|---|---|
| no | yes | OK |
| yes | yes | CHECK |
| yes | no | CHECKMATE, game over |
| no | no | STALEMATE, game over (a draw) |
def _has_legal_move(self, color: Color) -> bool:
return any(self._legal_targets(sq) for sq, _ in self.board.pieces(color))
def _update_status(self) -> str:
in_check = self.board.is_attacked(self.board.find_king(self.turn), self.turn.opponent())
if not self._has_legal_move(self.turn):
self.status = GameStatus.CHECKMATE if in_check else GameStatus.STALEMATE
return self.status.value
return "CHECK" if in_check else "OK"
Checkmate and stalemate are the same search with a different answer. Many candidates get this wrong in one of two ways: they call it checkmate when the king has no moves (but another piece could block), or they forget stalemate entirely and the game hangs with a player who cannot move. The table above avoids both, and any(...) stops at the first legal move it finds, so in a normal position the search ends almost at once.
The game has only three states and one transition rule each, so a plain enum is enough. A full State pattern with one class per state would be over-engineering here; it starts to pay off when states add behavior, such as "waiting for opponent" or "paused" in an online game. See /low-level-design/state-pattern for when it does.
The two read-only methods are short. legal_moves reuses the validation code and sorts the result so the screen (and the tests) get a stable order:
def legal_moves(self, square: str) -> List[str]:
src = to_square(square)
piece = self.board.get(src)
if self.status is not GameStatus.ACTIVE or piece is None or piece.color != self.turn:
return []
return sorted(to_name(dst) for dst in self._legal_targets(src))
def piece_at(self, square: str) -> str:
piece = self.board.get(to_square(square))
return piece.code() if piece else "" # code() is color + symbol, e.g. "wK"
Move history and undo
Requirement 8 asks for a list of moves and a way to take the last one back.
Bad Solution: save a copy of the board after every move
Approach
Keep a list of board snapshots. Undo pops the last one and restores the previous.
def move(self, frm: str, to: str) -> str:
...
self.snapshots.append(copy.deepcopy(self.board))
def undo(self) -> bool:
if len(self.snapshots) < 2:
return False
self.snapshots.pop()
self.board = copy.deepcopy(self.snapshots[-1])
...
Challenges
It is simple and hard to get wrong, and for chess (64 squares) the memory is not a real problem. But a snapshot does not say what happened: to show "e2e4" in the history, you would have to diff two boards. And it does not scale to the follow-ups: castling and en passant need to know what the last move was, not just what the board looks like.
Good Solution: a list of Move records
Approach
We already have a Move that knows how to apply and revert itself, so the history is just the list of moves made, and undo reverts the last one.
def undo(self) -> bool:
if not self.moves:
return False
self.board.revert(self.moves.pop())
self.turn = self.turn.opponent()
self.status = GameStatus.ACTIVE # the position before any move had a legal move
return True
def history(self) -> List[str]:
return [m.notation() for m in self.moves]
Challenges
Each record is a few fields, the history reads naturally, and undo is three lines. This is the Command pattern: each move is an object that can be executed and reversed, and the list of them is an undo stack. See /low-level-design/command-pattern. Undo can always set the status back to ACTIVE, because the position before the last move was one where a player could move: that is how the last move got made. Redo, if asked for, is a second stack that undo pushes onto and any new move clears.
💡 Interview tip: Say "the same Move object powers validation, history and undo". It shows the interviewer that you designed one mechanism and reused it, instead of building three features three ways.
Edge cases
- Wrong turn or empty square: rejected before any search, and nothing changes.
- Same square for from and to: no piece lists its own square as a candidate, so it is rejected.
- Pinned piece: its candidate moves leave the king attacked, so
_legal_targetsdrops them, with no pin-specific code. - King walks into check: same mechanism; the trial position shows the king attacked.
- Capturing the checking piece or blocking it: both are candidates that leave the king safe, so both are legal.
- Promotion: the
Movecarries the new queen;revertputs the pawn back and the captured piece (if any) too. - Move after the game ended:
statusis notACTIVE, so it is rejected andlegal_movesis empty. - Undo with no moves: returns
false. - Undo after checkmate: the game goes on, and the same mating move can be played again.
Verification
Let's trace the shortest possible checkmate (the first practice test), starting from the usual position.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | move("f2", "f3") |
White pawn one step; Black is not in check and has moves | "OK" |
| 2 | move("e7", "e5") |
Black pawn two steps from its starting row | "OK" |
| 3 | move("g2", "g4") |
White pawn two steps; the diagonal h4-g3-f2-e1 is now open |
"OK" |
| 4 | legal_moves("g1") |
It is Black's turn, so the white knight reports nothing | [] |
| 5 | move("d8", "h4") |
The queen slides d8-e7-f6-g5-h4 (e7 emptied in step 2) and attacks e1 along h4-g3-f2-e1. Every white candidate is tried and leaves the king attacked |
"CHECKMATE" |
| 6 | move("a2", "a3") |
Status is CHECKMATE |
"INVALID" |
| 7 | legal_moves("e1") |
Game over | [] |
| 8 | history() |
The four moves made | ["f2f3","e7e5","g2g4","d8h4"] |
| 9 | undo() |
Queen back to d8, turn back to Black, status ACTIVE |
true |
| 10 | move("d8", "h4") |
The same mate again | "CHECKMATE" |
| 11 | piece_at("h4") |
The black queen | "bQ" |
Step 5 is worth a closer look, because it shows why "the king has no moves" is not the whole question. White would need to block on g3 or f2, or capture the queen, and no white piece can reach any of those squares; the king's only free square, f2, is on the same diagonal. Our code does not reason about any of this. It tries each white candidate, sees the king still attacked after every one, and concludes checkmate. Had a knight been able to jump to g3, the same loop would have found that block and returned "CHECK" instead. That is the strength of the "try it and look" design.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Tuple
Square = Tuple[int, int] # (row, col): row 0 is rank 1, col 0 is file a
class Color(Enum):
WHITE = "w"
BLACK = "b"
def opponent(self) -> "Color":
return Color.BLACK if self is Color.WHITE else Color.WHITE
class GameStatus(Enum):
ACTIVE = "ACTIVE"
CHECKMATE = "CHECKMATE"
STALEMATE = "STALEMATE"
ROOK_DIRS = [(1, 0), (-1, 0), (0, 1), (0, -1)]
BISHOP_DIRS = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
KNIGHT_JUMPS = [(2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)]
class Piece:
symbol = "?"
def __init__(self, color: Color):
self.color = color
def code(self) -> str:
return self.color.value + self.symbol # e.g. "wK"
def candidate_moves(self, board: "Board", frm: Square) -> List[Square]:
"""Squares this piece could move to by its own movement rule, ignoring check."""
raise NotImplementedError
class SlidingPiece(Piece):
"""Rook, bishop and queen: slide along each direction until something is in the way."""
directions: List[Tuple[int, int]] = []
def candidate_moves(self, board: "Board", frm: Square) -> List[Square]:
moves = []
for dr, dc in self.directions:
r, c = frm[0] + dr, frm[1] + dc
while board.in_bounds((r, c)):
target = board.get((r, c))
if target is None:
moves.append((r, c))
else:
if target.color != self.color:
moves.append((r, c)) # capture, then stop
break
r, c = r + dr, c + dc
return moves
class SteppingPiece(Piece):
"""Knight and king: jump to a fixed set of offsets."""
offsets: List[Tuple[int, int]] = []
def candidate_moves(self, board: "Board", frm: Square) -> List[Square]:
moves = []
for dr, dc in self.offsets:
to = (frm[0] + dr, frm[1] + dc)
if board.in_bounds(to):
target = board.get(to)
if target is None or target.color != self.color:
moves.append(to)
return moves
class Rook(SlidingPiece):
symbol = "R"
directions = ROOK_DIRS
class Bishop(SlidingPiece):
symbol = "B"
directions = BISHOP_DIRS
class Queen(SlidingPiece):
symbol = "Q"
directions = ROOK_DIRS + BISHOP_DIRS
class Knight(SteppingPiece):
symbol = "N"
offsets = KNIGHT_JUMPS
class King(SteppingPiece):
symbol = "K"
offsets = ROOK_DIRS + BISHOP_DIRS
class Pawn(Piece):
symbol = "P"
def candidate_moves(self, board: "Board", frm: Square) -> List[Square]:
step = 1 if self.color is Color.WHITE else -1
start_row = 1 if self.color is Color.WHITE else 6
r, c = frm
moves = []
one = (r + step, c)
if board.in_bounds(one) and board.get(one) is None:
moves.append(one)
two = (r + 2 * step, c)
if r == start_row and board.get(two) is None:
moves.append(two)
for dc in (-1, 1):
diag = (r + step, c + dc)
if board.in_bounds(diag):
target = board.get(diag)
if target is not None and target.color != self.color:
moves.append(diag) # pawns capture diagonally only
return moves
@dataclass
class Move:
frm: Square
to: Square
piece: Piece
captured: Optional[Piece]
promoted_to: Optional[Piece] # the new queen when a pawn reaches the last row
def notation(self) -> str:
return to_name(self.frm) + to_name(self.to)
def to_square(name: str) -> Square:
return (int(name[1]) - 1, ord(name[0]) - ord("a"))
def to_name(sq: Square) -> str:
return chr(ord("a") + sq[1]) + str(sq[0] + 1)
class Board:
def __init__(self):
self.grid: List[List[Optional[Piece]]] = [[None] * 8 for _ in range(8)]
@staticmethod
def standard() -> "Board":
board = Board()
back_rank = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
for col, piece_class in enumerate(back_rank):
board.set((0, col), piece_class(Color.WHITE))
board.set((1, col), Pawn(Color.WHITE))
board.set((6, col), Pawn(Color.BLACK))
board.set((7, col), piece_class(Color.BLACK))
return board
def in_bounds(self, sq: Square) -> bool:
return 0 <= sq[0] < 8 and 0 <= sq[1] < 8
def get(self, sq: Square) -> Optional[Piece]:
return self.grid[sq[0]][sq[1]]
def set(self, sq: Square, piece: Optional[Piece]) -> None:
self.grid[sq[0]][sq[1]] = piece
def pieces(self, color: Color) -> List[Tuple[Square, Piece]]:
return [((r, c), p) for r in range(8) for c in range(8)
for p in [self.grid[r][c]] if p is not None and p.color == color]
def find_king(self, color: Color) -> Square:
for sq, piece in self.pieces(color):
if isinstance(piece, King):
return sq
raise ValueError("no king")
def is_attacked(self, sq: Square, by: Color) -> bool:
# Only ever asked about an occupied square (a king), so a pawn's forward
# moves can never land on it and candidate_moves gives exactly the attacks.
return any(sq in piece.candidate_moves(self, frm) for frm, piece in self.pieces(by))
def apply(self, move: Move) -> None:
self.set(move.to, move.promoted_to or move.piece)
self.set(move.frm, None)
def revert(self, move: Move) -> None:
self.set(move.frm, move.piece)
self.set(move.to, move.captured)
class ChessGame:
def __init__(self):
self.board = Board.standard()
self.turn = Color.WHITE
self.status = GameStatus.ACTIVE
self.moves: List[Move] = [] # the history, oldest first
def move(self, frm: str, to: str) -> str:
if self.status is not GameStatus.ACTIVE:
return "INVALID"
src, dst = to_square(frm), to_square(to)
piece = self.board.get(src)
if piece is None or piece.color != self.turn:
return "INVALID"
if dst not in self._legal_targets(src):
return "INVALID"
move = self._build_move(src, dst)
self.board.apply(move)
self.moves.append(move)
self.turn = self.turn.opponent()
return self._update_status()
def legal_moves(self, square: str) -> List[str]:
src = to_square(square)
piece = self.board.get(src)
if self.status is not GameStatus.ACTIVE or piece is None or piece.color != self.turn:
return []
return sorted(to_name(dst) for dst in self._legal_targets(src))
def piece_at(self, square: str) -> str:
piece = self.board.get(to_square(square))
return piece.code() if piece else ""
def undo(self) -> bool:
if not self.moves:
return False
self.board.revert(self.moves.pop())
self.turn = self.turn.opponent()
self.status = GameStatus.ACTIVE # the position before any move had a legal move
return True
def history(self) -> List[str]:
return [m.notation() for m in self.moves]
# --- helpers ---
def _build_move(self, src: Square, dst: Square) -> Move:
piece = self.board.get(src)
promoted = None
if isinstance(piece, Pawn) and dst[0] in (0, 7):
promoted = Queen(piece.color) # always promote to a queen
return Move(src, dst, piece, self.board.get(dst), promoted)
def _legal_targets(self, src: Square) -> List[Square]:
"""Candidate moves that do not leave the mover's own king attacked."""
piece = self.board.get(src)
legal = []
for dst in piece.candidate_moves(self.board, src):
move = self._build_move(src, dst)
self.board.apply(move) # try it ...
if not self.board.is_attacked(self.board.find_king(piece.color), piece.color.opponent()):
legal.append(dst)
self.board.revert(move) # ... and take it back
return legal
def _has_legal_move(self, color: Color) -> bool:
return any(self._legal_targets(sq) for sq, _ in self.board.pieces(color))
def _update_status(self) -> str:
in_check = self.board.is_attacked(self.board.find_king(self.turn), self.turn.opponent())
if not self._has_legal_move(self.turn):
self.status = GameStatus.CHECKMATE if in_check else GameStatus.STALEMATE
return self.status.value
return "CHECK" if in_check else "OK"
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
These are the follow-ups interviewers ask once the core works. For each one, notice which classes change and which do not.
1) How would you add castling and en passant?
Both are special moves that move a second piece or capture a piece that is not on the target square, and both depend on history: castling is allowed only if the king and that rook have never moved, and en passant only right after the enemy pawn's two-square move.
The design absorbs this in three places. Move grows two optional fields that apply and revert handle, the king and pawn add the new candidates, and the game's move list already answers the history questions.
@dataclass
class Move:
...
rook_move: Optional[Tuple[Square, Square]] = None # castling: the rook's from/to
en_passant_square: Optional[Square] = None # where the captured pawn actually stood
def apply(self, move: Move) -> None:
self.set(move.to, move.promoted_to or move.piece)
self.set(move.frm, None)
if move.rook_move:
rook_from, rook_to = move.rook_move
self.set(rook_to, self.get(rook_from))
self.set(rook_from, None)
if move.en_passant_square:
self.set(move.en_passant_square, None) # revert puts move.captured back here
"Has this piece moved?" can be a scan of the history (any(m.piece is king for m in moves)) or a counter on the piece that apply increments and revert decrements. Castling adds one rule our is_attacked shortcut does not cover: the king may not pass through an attacked square, and those squares are empty. So pawns need a separate attacks() method that returns only their diagonals. The legality check (try the move, look at the king) works unchanged for both special moves, which is the payoff of keeping it general.
2) How would you let the player choose the promotion piece and export standard notation?
Promotion choice is a third argument, move("e7", "e8", promotion="N"), passed through to _build_move, which creates that piece instead of a queen. legal_moves then lists a promotion square once, and the UI asks which piece to use.
Standard notation (Nf3, exd5, Qxf7#) is a different view of the same history. It needs the piece letter, a capture mark, a check suffix, and sometimes the starting file when two identical pieces can reach the same square. Keep it out of Move and out of the game: a small NotationFormatter that reads the move list and replays it on a scratch board is enough. That same formatter can write a PGN file for saving and loading games, which turns persistence into "store the list of moves and replay it".
3) How would you detect draws by repetition or the fifty-move rule?
Both are rules about history, so they sit next to the move list.
from collections import Counter
class ChessGame:
def __init__(self):
...
self.position_counts: Counter = Counter()
self.quiet_moves = 0 # moves since the last capture or pawn move
def _position_key(self) -> str:
cells = "".join(p.code() if p else ".." for row in self.board.grid for p in row)
return cells + self.turn.value
After each move, add the position key to the counter; if any position reaches three, the game is a draw by repetition. quiet_moves resets on a capture or a pawn move, and at 100 (fifty moves each) the game is drawn. Undo must reverse both, so either store the old values in the Move, or recompute them from the history. GameStatus gains a DRAW value, and _update_status checks these rules after checkmate and stalemate.
4) How would you support online multiplayer games?
Now players become real: they have ids, they join a game, and only the player who owns a color may move it. A GameManager holds many games at once, and each move names the player.
@dataclass
class Player:
player_id: str
name: str
class OnlineGame:
def __init__(self, game_id: str, white: Player, black: Player):
self.game = ChessGame()
self.players = {Color.WHITE: white, Color.BLACK: black}
self.lock = threading.Lock()
self.listeners: List[Callable[[str], None]] = [] # spectators, the two clients
def move(self, player_id: str, frm: str, to: str) -> str:
with self.lock:
if self.players[self.game.turn].player_id != player_id:
return "INVALID" # not your turn, or not your game
result = self.game.move(frm, to)
if result != "INVALID":
for notify in self.listeners:
notify(frm + to)
return result
The chess rules do not change at all; ChessGame is wrapped, not edited. The lock matters because two requests for the same game can arrive at once (a move and a resignation, or a client retrying); one lock per game is plenty, and different games never share state, so they never wait on each other (see /low-level-design/race-conditions-and-locks). Clients and spectators get moves through Observer-style listeners (/low-level-design/observer-pattern). Clocks come in as timestamps on each move: the game subtracts the time since the last move from the mover's clock and ends the game when it runs out. Undo turns into a request the opponent must accept. Matching players by rating is its own problem: /low-level-design/matchmaking.
💡 Interview tip: For "make it multiplayer", resist editing the rules engine. Wrap it: identity and turn ownership, a lock per game, notifications out. An interviewer is checking that you can add a layer without breaking the one underneath.
What is Expected at Each Level?
Junior
A junior candidate should model the board, the pieces and the game, and get basic moves working: each piece moves in its own pattern, captures work, and turns alternate. It is fine if the move rules start as one long function and if check detection needs a hint from the interviewer. The candidate should be able to trace a few moves by hand and explain why a move was rejected.
Mid-level
A mid-level candidate separates "how a piece moves" from "is this move legal", uses polymorphism for piece movement, and validates moves by checking the king after a trial move, which handles pins and answering check without special cases. They detect checkmate and stalemate correctly with the "attacked / any legal move" table, and they build undo on a move record that stores the captured piece. They scope the problem early by leaving castling and en passant for later.
Senior
A senior candidate gets the core done quickly and spends the time on trade-offs and growth. They share the sliding and stepping loops so pieces are data, use make/unmake with one Move record for validation, history and undo, and explain where the is_attacked shortcut stops being correct. On follow-ups they place each feature precisely: special moves in Move and the piece classes, draws next to the history, notation as a separate formatter, and online play as a wrapper with a lock per game and observers, leaving the rules engine untouched.