"Design a chess game" has a weak answer that looks complete. It draws an abstract Piece with six subclasses, each with a canMove(from, to), an 8 × 8 array, and a loop that asks two Player objects for moves. Then castling, en passant and check arrive, and each one becomes an if in a different subclass. A pinned bishop still moves, because the bishop's canMove does not know where its king is.
The interviewer is checking where the rules live. Each piece moves in its own way, but one rule covers all of them: no move may leave your own king in check. Two special moves depend on what happened earlier in the game, and the game must tell a checkmate from a stalemate. A good design gives each of these one place in the code. Tic-tac-toe covered moves that arrive as calls and refusals that come back as answers, so this page reuses those ideas and spends its words on the rules.
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose, and each answer below changes the code. The right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| The full rules, with castling, en passant and promotion? | Yes, all of them | The position must remember more than where the pieces stand |
| How does a move arrive? | As a call with a from square and a to square, from a screen or a server | Game.move(from, to), and no Player class |
| What does a pawn become on the last rank? | The player's choice: queen, rook, bishop or knight | A move can carry a promotion piece, and a missing one is refused |
| What happens to an illegal move? | It is refused with a reason, and nothing changes | An Outcome enum with one value per reason |
| Does the game spot check, checkmate and stalemate? | Yes, after every move | The game works out every legal move after each move |
| Draws by repetition or the 50-move rule, resignation? | Not in this version | No move counters and no draw offers |
| Is there undo? | Yes, any number of moves, back to the start | The game keeps its history |
| Can a game start from a given position, such as a puzzle? | Yes, written in FEN, the usual one-line notation for a position | A Fen reader, and a position that is checked before it is accepted |
| Clocks, or a computer player? | No | No clock and no move chooser |
| Can two moves for one game arrive at once? | No: a server hands each game its moves one at a time | Game has no lock |
The first row matters most. Castling and en passant depend on the past: whether a king or a rook has ever moved, and what the last move was. A board alone cannot answer that, so the design needs one object for everything the rules need to know at a given moment. That object is the Position.
Requirements
Functional:
- A game starts from the usual position, or from a position written in FEN, the usual one-line notation for a chess position. White moves first, and the players take turns.
- Each piece moves by its own rule, and a move its rule does not allow is refused.
- A move that leaves the mover's own king attacked is refused. This covers a pinned piece, a king stepping into check, and a move that ignores a check.
- A king may castle on either side if neither the king nor that rook has moved, the squares between them are empty, and the king does not start on, cross or land on an attacked square.
- A pawn may take en passant only on the move straight after the other pawn's two-square step.
- A pawn that reaches the last rank becomes the queen, rook, bishop or knight its player chooses.
- After every move the game reports check, checkmate or stalemate. A finished game refuses further moves.
- The last move can be taken back, repeatedly, back to the start, and everything it changed comes back.
- Every refused move gets a reason and leaves the game exactly as it was.
Out of scope: draws by threefold repetition, by the 50-move rule or by too little material, resignation and draw offers, clocks, a computer player, and writing moves in chess notation. We come back to these at the end as follow-ups.
Everything lives in memory, as is normal for a low-level design interview.
What the code itself must handle:
- Rules full of exceptions. Castling, en passant and promotion each break the plain "one piece moves from one square to another" model. They must fit without an
iffor them in every class. - One rule over every piece. King safety applies to every move of every piece, so it should be written once.
- Testable. A test must be able to set up any position directly, instead of reaching it by playing forty moves.
- One thread per game. We assume a server queues each game's moves. If it does not, a private lock around each public method of
Game, as in tic-tac-toe, is enough.
Finding the classes
One kept noun is not in the question at all. The position is the board plus whose move it is, which castling rights are left, and whether a pawn may be taken en passant. Another noun is a rule rather than data: how a piece moves differs for each type, so it gets an interface, MoveRule.
Does a piece know its square?
A cell object that holds its piece, and a piece that holds its cell
This is the shape of many class diagrams: a Cell with a piece field and a Piece with a position field. Every move must update both ends, and a missed update leaves a piece that thinks it is on e2 while the board has it on e4. A piece with a field that changes also cannot be shared between two positions.
A square is a coordinate, and only the board knows what stands whereOur pick
Square is a file and a rank. Board keeps a Piece[8][8] and is the one place that says what stands where. A Piece is only a colour and a type, so it never changes and two positions can share it.
Data or behaviour?
Most classes here only carry data. Square, Step, Piece, Move and MoveResult are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us. Fixed sets of values are enums: Color, PieceType, MoveKind, CastlingRight, Outcome and Status.
A piece has no hasMoved flag. Castling needs to know whether a king or rook has moved, but that answer belongs to the position, as we will see.
The class diagram
The classes fall into three groups:
- Data:
Square,Step,Piece,MoveandMoveResult, and the enumsColor,PieceType,MoveKind,CastlingRight,OutcomeandStatus. - The core:
Game,PositionandBoard. APositionnever changes once built, andGamekeeps the list of them. - Rules:
MoveRuleand its four implementations, one for each way of moving.Fenreads positions for puzzles and tests.
Building it
Squares and the board
A Square is a file and a rank, both from 0 to 7, so a1 is (0, 0) and e4 is (4, 3). It refuses anything off the board, and Square.of("e4") reads a name. plus(step) returns the square one Step away, or empty at the edge. Every piece rule moves with it, so no rule does its own edge check.
/** * Which piece stands on which square. Anyone may read a board; only Position * changes one, and only a fresh copy that nobody else has seen yet. */public final class Board { private final Piece[][] squares = new Piece[Square.SIZE][Square.SIZE]; private Board() { } public static Board of(Map<Square, Piece> pieces) { Board board = new Board(); pieces.forEach((square, piece) -> board.put(Objects.requireNonNull(square), Objects.requireNonNull(piece))); return board; } public Optional<Piece> pieceAt(Square square) { return Optional.ofNullable(squares[square.rank()][square.file()]); }The grid is private, and so is the constructor. Anyone can read a board through pieceAt, and the methods that change one are package-private. Outside Board, only Position.apply calls put and remove, and only on a board that copy has just made, so a board that anyone else holds never changes.
Each piece type brings its own rule
Six piece types need only four rule classes. A rook, a bishop and a queen all slide until something stops them, and only their directions differ. A knight takes one jump from a fixed list. The king steps one square and can castle, and the pawn is unlike everything else. So each PieceType carries a rule object:
public enum PieceType { KING('k', new KingRule()), QUEEN('q', new SlidingRule(Step.ALL_AROUND)), ROOK('r', new SlidingRule(Step.STRAIGHT)), BISHOP('b', new SlidingRule(Step.DIAGONAL)), KNIGHT('n', new StepRule(Step.KNIGHT_JUMPS)), PAWN('p', new PawnRule());A queen is a SlidingRule with all eight directions, and a rook is one with the four straight ones. The king gets its own rule because of castling, and that rule uses a StepRule inside for its plain steps.
/** How one type of piece moves. Each PieceType holds one. */public interface MoveRule { /** The squares a piece on from attacks: where it could capture, whatever stands there now. */ List<Square> attacks(Board board, Square from, Color color); /** * The moves a piece on from could make, before anyone checks that its own king * is safe. By default these are the attacked squares not taken by its own side. */ default List<Move> candidates(Position position, Square from, Color color) { List<Move> moves = new ArrayList<>(); for (Square to : attacks(position.board(), from, color)) { if (!position.board().isOccupiedBy(to, color)) { moves.add(Move.normal(from, to)); } } return moves; }}A rule answers two different questions. attacks lists the squares the piece could capture on. candidates lists the moves it could make. For most pieces the second is the first minus the squares its own side holds, and that is the default method. A pawn breaks this, because it moves straight ahead but captures diagonally, so PawnRule overrides both.
@Override public List<Square> attacks(Board board, Square from, Color color) { List<Square> squares = new ArrayList<>(); for (Step direction : directions) { Optional<Square> next = from.plus(direction); while (next.isPresent()) { Square square = next.get(); squares.add(square); if (board.pieceAt(square).isPresent()) { break; } next = square.plus(direction); } } return squares; }The slide adds each square, then stops at the first piece it meets. The square with the piece is included, because that piece may be an enemy to capture. candidates drops it if the piece is our own.
A class per piece, or a rule per piece type?
An abstract Piece with a subclass per type, each with canMove(from, to)
Each subclass judges one pair of squares at a time. Finding every legal move then means asking every piece about all 64 squares. The queen repeats the rook's and the bishop's code, and a hasMoved field on the king and rooks must be put back by undo.
One method with a switch on the piece type
All the movement code is in one place, but that place grows with every special case, and a new piece type means editing it.
A Piece record, and a MoveRule held by each PieceTypeOur pick
A rule lists its moves directly, so a knight produces its eight targets instead of being asked about 64 squares. Three types share SlidingRule with different directions. A new piece, such as one that moves like a bishop or a knight, is one new enum constant with a rule that joins two lists.
A position, and a new one for every move
Position holds the board and the three facts the board cannot show: whose move it is, which castling rights are left, and the square where a pawn may be taken en passant.
public final class Position { private static final List<PieceType> BACK_RANK = List.of(PieceType.ROOK, PieceType.KNIGHT, PieceType.BISHOP, PieceType.QUEEN, PieceType.KING, PieceType.BISHOP, PieceType.KNIGHT, PieceType.ROOK); private final Board board; private final Color sideToMove; private final Set<CastlingRight> castlingRights; private final Square enPassantSquare; private Position(Board board, Color sideToMove, Set<CastlingRight> castlingRights, Square enPassantSquare) { this.board = board; this.sideToMove = sideToMove; this.castlingRights = Collections.unmodifiableSet(castlingRights); this.enPassantSquare = enPassantSquare; }Every field is final, and nothing changes a position after it is built. A move does not edit the board. apply copies the board, changes the copy, and returns a new position:
/** The position after a move. The move must be one of this position's candidates. */ Position apply(Move move) { Board next = board.copy(); Piece piece = next.remove(move.from()); if (move.kind() == MoveKind.PROMOTION) { piece = new Piece(piece.color(), move.promotion()); } next.put(move.to(), piece); if (move.kind() == MoveKind.EN_PASSANT) { next.remove(new Square(move.to().file(), move.from().rank())); } if (move.kind() == MoveKind.CASTLE) { CastlingRight right = CastlingRight.forCastle(move); next.put(right.rookTo(), next.remove(right.rookFrom())); } Set<CastlingRight> rights = EnumSet.noneOf(CastlingRight.class); for (CastlingRight right : castlingRights) { if (!right.isLostBy(move)) { rights.add(right); } } Square passed = null; if (move.kind() == MoveKind.DOUBLE_STEP) { passed = new Square(move.from().file(), (move.from().rank() + move.to().rank()) / 2); } return new Position(next, sideToMove.opponent(), rights, passed); }The move's MoveKind says what happens besides one piece moving. Promotion swaps the pawn for the new piece. En passant removes a pawn from a square the move does not land on. Castling moves the rook too. The castling rights and the en passant square are worked out fresh for the new position, and we come back to both.
Change one board in place, or make a new position for each move?
One board, changed in place, with an unmake for every move
Changing one board is fast, and chess engines that search millions of positions work this way. But every kind of move needs its own exact reverse. The safety test below would have to make and unmake moves on the live game, and one missed restore corrupts it.
A new Position for every moveOur pick
apply copies 64 squares and never touches the old position. The safety test can try any move and throw the result away, and undo only has to go back to an earlier position. The cost is one board copy for every move tried, a few dozen per turn, which is small next to a person's thinking time. A computer player that searches deeply would want the first option.
Playing a move
Game keeps the positions and the legal moves for the current one, worked out after every change. move checks a request in a fixed order and answers with a MoveResult. As in tic-tac-toe, a refusal is an answer with a reason. Programmer errors throw, such as a null square or the name "z9". setUp also throws for a position that cannot happen. It rejects a side without exactly one king, a pawn on the first or last rank, and a castling right whose king or rook is not at home. It also rejects an en passant square no pawn has just crossed, and a side in check when it is not their move. A puzzle FEN typed by a person is user input, so the screen catches that exception and shows its message.
private MoveResult play(Square from, Square to, PieceType promotion) { Objects.requireNonNull(from, "from"); Objects.requireNonNull(to, "to"); Position position = position(); if (status.isOver()) { return refuse(Outcome.GAME_OVER); } Optional<Piece> piece = position.board().pieceAt(from); if (piece.isEmpty()) { return refuse(Outcome.NO_PIECE); } if (piece.get().color() != position.sideToMove()) { return refuse(Outcome.NOT_YOUR_TURN); } List<Move> legal = matching(legalMoves, from, to); if (legal.isEmpty()) { boolean ruleAllows = !matching(position.candidatesFrom(from), from, to).isEmpty(); return refuse(ruleAllows ? Outcome.KING_UNSAFE : Outcome.CANNOT_MOVE_THERE); } Optional<Move> chosen = choose(legal, promotion); if (chosen.isEmpty()) { return refuse(promotion == null ? Outcome.CHOOSE_PROMOTION : Outcome.BAD_PROMOTION); } positions.add(position.apply(chosen.get())); moves.add(chosen.get()); judge(); return new MoveResult(Outcome.MOVED, status); }The checks run in this order: the game is still on, there is a piece on from, it belongs to the side to move, and the move is in the legal list. When the move is not legal, move asks the piece's rule alone. If the rule allows the move, only the king's safety stands in the way, and the answer is KING_UNSAFE. Otherwise it is CANNOT_MOVE_THERE, so a player who drags a pinned bishop learns why it will not go. Nothing is written until every check has passed, so a refused move leaves the game exactly as it was.
Keeping the king safe
This rule is where a design with a canMove per piece breaks. A bishop on e2, with its king on e1 and an enemy rook on e8, may not move at all, though nothing in the bishop's own rule says so. The same rule stops a king stepping into check and any move that ignores a check.
/** Every move the side to move may make: each piece's candidates that keep the king safe. */ public List<Move> legalMoves() { List<Move> legal = new ArrayList<>(); for (Square from : board.squaresOf(sideToMove)) { for (Move move : candidatesFrom(from)) { if (keepsKingSafe(move)) { legal.add(move); } } } return legal; } /** The moves the piece's own rule allows, before anyone checks the king. */ List<Move> candidatesFrom(Square from) { Piece piece = board.pieceAt(from).orElseThrow(); return piece.type().rule().candidates(this, from, piece.color()); } private boolean keepsKingSafe(Move move) { if (move.kind() == MoveKind.CASTLE) { for (Square square : CastlingRight.forCastle(move).kingPath()) { if (isAttacked(square, sideToMove.opponent())) { return false; } } } return !apply(move).inCheck(sideToMove); }legalMoves asks each piece for its candidates, and keepsKingSafe applies each one to a copy and asks whether the mover's king is attacked there. isAttacked asks every enemy piece's rule for its attacks and looks for the king's square in them. No rule knows about pins or checks. Both come out of one question, asked after the move.
Two more cases come out right without any code of their own. A king that steps back along a checking rook's line is still attacked, because the test looks at the board after the move. An en passant capture that takes two pawns off one rank can open that rank to a rook, and the test sees the open rank. Castling is the exception: the king crosses a square that the board after the move does not show. So castling adds its own check first, at lines 158 to 164, which the next part explains.
How do we refuse a move that leaves the king in check?
Each piece's rule checks pins and checks itself
The bishop would need to know where its king is and which enemy lines cross it, and so would every other piece. A check uncovered by another piece's move, or by en passant along a rank, would need code of its own in more than one place.
Every rule lists candidates; one filter tries each and drops any that leave the king attackedOur pick
The rules stay simple, and one method holds the safety rule. The cost is one board copy and one attack scan for each candidate, and a position has a few dozen candidates.
Castling
Castling has five conditions. The king and that rook have never moved, and the squares between them are empty. The king is not in check, does not cross an attacked square, and does not land on one. Each of the four ways to castle is a constant of CastlingRight, which holds its squares as data:
public enum CastlingRight { WHITE_KINGSIDE('K', Color.WHITE, "e1", "g1", "h1", "f1", List.of("f1", "g1"), List.of("e1", "f1", "g1")), WHITE_QUEENSIDE('Q', Color.WHITE, "e1", "c1", "a1", "d1", List.of("b1", "c1", "d1"), List.of("e1", "d1", "c1")), BLACK_KINGSIDE('k', Color.BLACK, "e8", "g8", "h8", "f8", List.of("f8", "g8"), List.of("e8", "f8", "g8")), BLACK_QUEENSIDE('q', Color.BLACK, "e8", "c8", "a8", "d8", List.of("b8", "c8", "d8"), List.of("e8", "d8", "c8"));Read one row from left to right: its FEN letter, its colour, the king's start and end squares, and the rook's start and end squares. Then come the squares that must be empty, and the squares the king starts on, crosses and lands on. On the queenside, b1 must be empty but is not on the king's path, so an attack on b1 does not stop castling. KingRule offers a castling move for each right still kept whose squares are empty:
@Override public List<Move> candidates(Position position, Square from, Color color) { List<Move> moves = steps.candidates(position, from, color); for (CastlingRight right : position.castlingRights()) { if (right.color() == color && right.squaresBetweenAreEmpty(position.board())) { moves.add(Move.castle(right)); } } return moves; }The three attack conditions live in keepsKingSafe, shown above. Before it applies a castle, it checks every square on kingPath, and refuses the castle if any of them is attacked. So every rule about the king's safety sits in one method.
That leaves "has never moved". Instead of a flag on each piece, the position keeps the set of rights still alive, and apply drops any right that a move touches:
A right ends when any move starts or ends on its king's or its rook's home square. That one line covers the king moving, the rook moving, and the rook being taken at home. The last case is easy to miss with flags: the taken rook never moved, so a flag check must also look for the rook on its square. A king that moves and comes back has still lost its rights, because they are gone from the set.
Where does the right to castle live?
A hasMoved flag on each king and rook
This is easy to picture. But pieces stop being plain values, undo must put each flag back, and a puzzle set up from a position has no way to say which pieces have moved.
A set of castling rights on the position, lost when a move touches a home squareOur pick
The rights are data in the position, so undo restores them by going back to an earlier position, and a FEN states them in its third field. setUp checks that each claimed right has its king and rook at home, so a right never outlives its rook.
En passant
En passant is the one rule that depends on the last move. A pawn that has just stepped two squares may be taken by an enemy pawn beside it, as if it had stepped one, but only on the very next move. The position remembers the square the pawn passed over:
Every move builds a new position, and only a two-square step sets the square. So the chance lasts exactly one move, with no code to clear it later. PawnRule offers the capture when a diagonal target is that square:
When apply plays it, the taken pawn is not on the target square. It stands beside the capturing pawn, on the target's file and the mover's rank, which is the square that line 177 of Position clears.
How does the game know en passant is allowed?
Look at the last move in the history
This works in a game played from the start. But a position set up from a puzzle has no history, and the rules would have to read the game's history instead of the position in front of them.
The position stores the square, set by a two-square step and empty after any other moveOur pick
The position alone answers every rule question, and a FEN gives the square in its fourth field. The chance cannot outlive its move, because each new position sets the square again.
Promotion
A pawn move onto the last rank is not one move but four, one for each piece the pawn may become:
/** A move onto the last rank is four moves, one for each piece the pawn may become. */ private static void addAdvance(List<Move> moves, Square from, Square to, Color color) { if (to.rank() != color.promotionRank()) { moves.add(Move.normal(from, to)); return; } for (PieceType type : PieceType.PROMOTIONS) { moves.add(Move.promotion(from, to, type)); } }The legal list holds all four, so the request must say which one it means. If it names no piece, move refuses with CHOOSE_PROMOTION, and the screen asks the player. If it names a king or a pawn, or names a piece for a move that is not a promotion, the answer is BAD_PROMOTION. The Move record's constructor keeps the two in step: a move names a promotion piece if and only if its kind is PROMOTION. We chose not to make a queen without asking. A knight is sometimes the better piece, and a default would hide a real choice. In the demo, a knight on a8 gives check where a queen would not.
Check, checkmate or stalemate
After every move, and after every undo, judge works out the legal moves for the side now to move. The status follows from two facts:
/** Works out the moves and the status of the position the game is now in. */ private void judge() { Position position = position(); legalMoves = List.copyOf(position.legalMoves()); boolean inCheck = position.inCheck(position.sideToMove()); if (legalMoves.isEmpty()) { status = inCheck ? Status.CHECKMATE : Status.STALEMATE; } else { status = inCheck ? Status.CHECK : Status.NORMAL; } }A side with no legal moves has lost if its king is attacked, and the game is drawn if it is not. A side with moves is either in check or not. The list judge builds is also the list the next move looks in, so the work is not wasted.
How do we tell checkmate from stalemate?
Checkmate when the king is in check and has no safe square
This misses a check that another piece can block, or a checking piece that can be taken, and calls those checkmate. It also says nothing about stalemate.
No legal moves at all; checkmate if the king is attacked, stalemate if notOur pick
Blocks and captures are legal moves, so they count, and stalemate needs no code of its own. The cost is finding every legal move after each move, which the next move needs anyway.
Undo
The game keeps every position it has been through, so undo drops the last one:
The earlier position already holds the right board, the right castling rights and the right en passant square, so undo restores all of them with no special cases. Undoing a castle puts the rook back, undoing en passant brings back the taken pawn, and undoing a promotion gives back the pawn. Undoing a checkmate reopens the game, because judge runs again on the earlier position.
Undo: reverse each move, or keep the positions?
Replay every move from the start
This needs only the start and the move list. But each undo then takes longer as the game gets longer.
Reverse the last move
It stores little. But each kind of move needs its own reverse: castling moves the rook back, en passant puts a pawn on a square the move never touched, and promotion turns a queen back into a pawn. A move must also remember what it captured, and the castling rights and en passant square before it.
Keep every position, and go back to the one beforeOur pick
A position is one 64-square board and three small fields, so a game of 200 moves keeps 200 small boards. Undo drops the last position, and that is right for every kind of move at once. Tic-tac-toe chose to reverse moves instead, because its board can hold 10,000 cells and a move changes one of them.
The final design
Game is the core. It owns the list of positions, the list of moves and the legal moves for the current position. Each Position owns its board and its castling rights, and reaches the way each piece moves only through the MoveRule its PieceType holds.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Does a piece know its square? | A square is a coordinate, and only the board knows what stands where | One place says what stands where |
| 2 | A class per piece, or a rule per piece type? | A Piece record, and a MoveRule held by each PieceType | Rules list their moves directly, and three types share one rule |
| 3 | Change one board in place, or make a new position for each move? | A new Position for every move | Trying a move and undoing one never touch the live game |
| 4 | How do we refuse a move that leaves the king in check? | Every rule lists candidates; one filter tries each and drops any that leave the king attacked | Pins and checks come out of one test |
| 5 | Where does the right to castle live? | A set of castling rights on the position, lost when a move touches a home square | Undo restores the rights, and a FEN can state them |
| 6 | How does the game know en passant is allowed? | The position stores the square, set by a two-square step and empty after any other move | The position alone answers every rule question |
| 7 | How do we tell checkmate from stalemate? | No legal moves at all; checkmate if the king is attacked, stalemate if not | Blocks and captures count, and stalemate needs no code of its own |
| 8 | Undo: reverse each move, or keep the positions? | Keep every position, and go back to the one before | Dropping the last position is right for every kind of move |
Here is white's en passant capture from the demo, end to end:
- The screen calls
move(e5, d6)on its own thread. There is no lock, because the server hands this game one move at a time, and there is no outside call. movefinds the game still on, a white pawn on e5 and white to move. It finds e5-d6 inlegalMoves, wherejudgeput it after black's d7-d5.PawnRule.candidateshad offered it because d6 was theenPassantSquare, andkeepsKingSafehad found the king safe.Position.applycopies the board, moves the pawn to d6 and clears d5. The new position has black to move and no en passant square.moveadds the new position and the move to its lists, andjudgeworks out black's legal moves and the status.- The caller gets
MoveResult(MOVED, NORMAL). A laterundoremoves that position, and the d5 pawn and the en passant chance come back.
A refused move takes the first steps of this path and stops before apply, so nothing in the game changes. Undo runs the path backwards: it removes the last position and the last move, then judge runs on the position before, so the status and the legal moves match the board again.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package game; import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Optional; import board.Color;import board.Square;import piece.Piece;import piece.PieceType; /** * One game of chess. Players are not objects here: a move arrives as a call to * move(), from a screen or a server. The game keeps every position it has been * through, so undo goes back to the one before. * Not thread-safe: a server hands each game its moves one at a time. */public final class Game { private final List<Position> positions = new ArrayList<>(); private final List<Move> moves = new ArrayList<>(); private List<Move> legalMoves; private Status status; public Game() { this(Position.start()); } public Game(Position start) { positions.add(Objects.requireNonNull(start, "start")); judge(); } public MoveResult move(Square from, Square to) { return play(from, to, null); } public MoveResult move(Square from, Square to, PieceType promotion) { return play(from, to, Objects.requireNonNull(promotion, "promotion")); } private MoveResult play(Square from, Square to, PieceType promotion) { Objects.requireNonNull(from, "from"); Objects.requireNonNull(to, "to"); Position position = position(); if (status.isOver()) { return refuse(Outcome.GAME_OVER); } Optional<Piece> piece = position.board().pieceAt(from); if (piece.isEmpty()) { return refuse(Outcome.NO_PIECE); } if (piece.get().color() != position.sideToMove()) { return refuse(Outcome.NOT_YOUR_TURN); } List<Move> legal = matching(legalMoves, from, to); if (legal.isEmpty()) { boolean ruleAllows = !matching(position.candidatesFrom(from), from, to).isEmpty(); return refuse(ruleAllows ? Outcome.KING_UNSAFE : Outcome.CANNOT_MOVE_THERE); } Optional<Move> chosen = choose(legal, promotion); if (chosen.isEmpty()) { return refuse(promotion == null ? Outcome.CHOOSE_PROMOTION : Outcome.BAD_PROMOTION); } positions.add(position.apply(chosen.get())); moves.add(chosen.get()); judge(); return new MoveResult(Outcome.MOVED, status); } /** Takes back the last move, whoever made it. Empty if there is none. */ public Optional<Move> undo() { if (moves.isEmpty()) { return Optional.empty(); } positions.remove(positions.size() - 1); Move last = moves.remove(moves.size() - 1); judge(); return Optional.of(last); } /** Every move the side to move may make, for a screen that shows them. */ public List<Move> legalMoves() { return legalMoves; } public Position position() { return positions.get(positions.size() - 1); } public Status status() { return status; } /** The winner, once the game has ended in checkmate. */ public Optional<Color> winner() { return status == Status.CHECKMATE ? Optional.of(position().sideToMove().opponent()) : Optional.empty(); } public List<Move> moves() { return List.copyOf(moves); } /** Works out the moves and the status of the position the game is now in. */ private void judge() { Position position = position(); legalMoves = List.copyOf(position.legalMoves()); boolean inCheck = position.inCheck(position.sideToMove()); if (legalMoves.isEmpty()) { status = inCheck ? Status.CHECKMATE : Status.STALEMATE; } else { status = inCheck ? Status.CHECK : Status.NORMAL; } } private static List<Move> matching(List<Move> candidates, Square from, Square to) { return candidates.stream().filter(move -> move.from().equals(from) && move.to().equals(to)).toList(); } /** All moves here share from and to; they differ only in the piece a pawn becomes. */ private static Optional<Move> choose(List<Move> legal, PieceType promotion) { for (Move move : legal) { if (move.promotion() == promotion) { return Optional.of(move); } } return Optional.empty(); } private MoveResult refuse(Outcome outcome) { return new MoveResult(outcome, status); }}demo/Main.java plays six short scenes: a quick checkmate and its undo, a pinned bishop, castling, en passant, promotion, and a checkmate set beside a stalemate.
1. A quick checkmate, and undo e2-e4 MOVED NORMAL e7-e5 MOVED NORMAL c1-e3 CANNOT_MOVE_THERE NORMAL f1-c4 MOVED NORMAL d7-d6 MOVED NORMAL b8-c6 NOT_YOUR_TURN NORMAL d1-h5 MOVED NORMAL g8-f6 MOVED NORMAL h5-f7 MOVED CHECKMATE e8-f7 GAME_OVER CHECKMATE undo h5-f7 NORMAL f7 holds black pawn 2. A pinned bishop e2-d3 KING_UNSAFE NORMAL e2-e4 CANNOT_MOVE_THERE NORMAL 3. Castling e1-g1 KING_UNSAFE NORMAL e1-c1 MOVED NORMAL e8-g8 MOVED NORMAL 8 r....rk. 7 ........ 6 b....... 5 ........ 4 ........ 3 n....... 2 ........ 1 ..KR...R abcdefgh 4. En passant, now or never e2-e4 MOVED NORMAL a7-a6 MOVED NORMAL e4-e5 MOVED NORMAL d7-d5 MOVED NORMAL h2-h3 MOVED NORMAL h7-h6 MOVED NORMAL e5-d6 CANNOT_MOVE_THERE NORMAL undo h7-h6 NORMAL undo h2-h3 NORMAL e5-d6 MOVED NORMAL d5 holds nothing 5. Promotion a7-a8 CHOOSE_PROMOTION NORMAL a7-a8=K BAD_PROMOTION NORMAL a7-a8=N MOVED CHECK 6. Checkmate or stalemate g1-g6 MOVED STALEMATE undo g1-g6 NORMAL g1-g7 MOVED CHECKMATE winner: WHITE
Notice four things in the output:
- Two refusals of one bishop give two reasons. In scene 2, e2-d3 is
KING_UNSAFE, because the bishop's rule allows it and only the pin stops it. Then e2-e4 isCANNOT_MOVE_THERE, because a bishop never moves straight. - An attack on b1 does not stop castling. In scene 3, white cannot castle kingside, because the bishop on a6 attacks f1. White can castle queenside, though the knight on a3 attacks b1. The board printed after it shows both sides castled.
- Undo brings back the en passant chance. In scene 4, e5-d6 is refused after h2-h3 and h7-h6. Two undos open the chance again, and the same move then succeeds and clears d5.
- One queen gives stalemate on g6 and checkmate on g7. Both leave black with no legal move, and only the check on g7 tells them apart.
Follow-up questions
| The interviewer asks | What changes | What does not |
|---|---|---|
| Draw by threefold repetition? | Game counts how often the current Position appears in its list, using the equals it already has. equals compares the en passant square even when no pawn can use it, so a strict count clears such a square first. Status gains a value for the draw | The pieces, the rules |
| The 50-move rule? | Position gains a count of moves since the last capture or pawn move, which apply resets or adds to. Fen reads it from the fifth field, and Position.equals leaves it out, or a repeated position would never match. judge checks it, and Status gains a value for the draw | The piece rules |
| Resignation and draw offers? | Game gains resign(color) and an agreed draw, and Status gains values for them | Position, the rules |
| Chess clocks? | Game takes a java.time.Clock and each side's time left. Running out of time loses the game, so Status gains a loss on time, and Game needs a time check that runs without a move, such as a checkTime() the server calls on a timer | Position, the rules |
| A computer player? | A MoveChooser outside Game, as in tic-tac-toe, that searches legalMoves(). A deep search would want one board changed in place instead of a new Position per move | Game's methods and its callers |
| Chess960, with a shuffled back rank? | CastlingRight becomes a class built from the start position, because the king's and rooks' home squares change from game to game. Position.start builds a shuffled rank, and Fen reads the castling letters that name a rook's file. Position.apply must lift the king and rook before placing either, because the king can land on the rook's start square. Game.move names a castle as the king moving onto its own rook, because a one-square castle looks like a king step | SlidingRule, StepRule, PawnRule |
| A new piece that moves like a bishop or a knight? | A new PieceType constant with a rule that joins the two lists, and a FEN letter | Position, Game |
| Write moves in chess notation, such as Nf3? | A writer that turns a Move and its Position into text. It uses the legal list to tell apart two knights that can reach one square. The + and # marks need the position after the move, so the writer goes through Game, or apply becomes public | The rules |
| Two players on two phones, moves on two threads? | A private lock around each public method of Game, as in tic-tac-toe | Position and the rules, which hold nothing that changes |
Most rows add a class or a field and leave the piece rules alone. The 50-move rule and Chess960 reach into Position, CastlingRight and Fen, because they change what a position has to remember. Chess960 also changes how Game.move reads a castle. Saying that in the interview, with the class named, is the point of the follow-up.
What the interviewer looks for
Mid-level
A mid-level candidate builds a board, pieces that move by their rules, turns, and refusals for illegal moves. They know that a move must not leave the king in check, even if their test for it is narrow, such as one that checks only king moves.
Senior
A senior candidate puts each piece's movement behind one interface and shares the sliding code between the rook, the bishop and the queen. They enforce king safety with one test after the move, keep castling rights and the en passant square on the position instead of flags on pieces, and tell checkmate from stalemate by counting legal moves.
Staff+
A staff candidate explains why positions never change and what that buys: a safety test that cannot corrupt the game, and undo with no special cases. They name the cost, a board copy for every move tried, and say when it stops being acceptable. They also point out the cases a narrow design gets wrong, such as en passant that opens a rank to the king.
Common mistakes
- A
canMove(from, to)per piece and no list of moves. Checkmate and stalemate need to know whether any legal move exists at all, and asking each piece about 64 squares repeats work. - King safety inside each piece's rule. Pins, uncovered checks and en passant along a rank then need code in several places, and one gets missed.
- A
hasMovedflag for castling. Undo must restore it, and a puzzle cannot state it. A rook taken at home never moved, so its flag alone still says it can castle. - Checking only where the castling king lands. The king may not castle out of check or through an attacked square either, but an attack on b1 does not matter.
- Keeping the en passant chance for more than one move. It belongs to the next move only.
- Calling every position with no moves checkmate. A side with no moves and no check is stalemated, and that is a draw.
- Making a queen without asking. The player chooses the piece, and a knight is sometimes the better one.
Summary
- A
Positionholds the board and the three facts the board cannot show: whose move it is, the castling rights left, and the en passant square. - Each
PieceTypeholds aMoveRule, and the rook, bishop and queen shareSlidingRulewith different directions. - Rules list candidates, and one filter applies each and drops any that leave the king attacked. Pins and checks need no code of their own.
- Castling keeps its squares as data in
CastlingRight, and a right is lost when any move touches its king's or rook's home square. - A two-square pawn step sets the en passant square, and the next position built leaves it empty.
- No legal moves means checkmate if the king is attacked, and stalemate if not.
- Positions never change, so undo goes back to the previous one and restores everything at once.