Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 17
Module 7 · Design problems IV: ATMs, chess and hotels · Chapter 17 of 28
Chess: Board, Pieces, Legal Moves and Game End
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps and Design Patterns in TypeScript: Creational, Structural and Behavioural. Next up: Hotel Management: Rooms, Bookings, Stays and Billing.
Part 1 · Requirements
What the game must do
Chess has one rule that touches every other: a move may never leave your own king attacked. This chapter builds a chess game as small classes you can run, with each piece deciding its own moves and the game deciding which of them are legal.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. The rules below follow the FIDE Laws of Chess, the international federation's rulebook, and we quote its article numbers where they decide a design question. Here is our list.
- Two players, white and black, take turns. White moves first.
- Every piece moves by its own rule. A rook slides along ranks and files, a bishop along diagonals, a queen along both, a knight jumps in an L, a king steps one square, and a pawn moves forward and captures diagonally.
- A piece captures by moving onto a square that holds an opponent's piece. A move onto your own piece is not allowed.
- A move may not expose your king to attack or leave it attacked (article 3.9.2). A king is in check when an opposing piece attacks it.
- A player who is to move, is in check and has no legal move has been checkmated and loses (articles 1.4.1 and 5.1.1).
- A player who is to move, is not in check and has no legal move is stalemated, and the game is drawn (article 5.2.1).
- Players can agree a draw, once both have moved (article 5.2.3), and a player can resign (article 5.1.2). In our model a resignation always gives the win to the other side; the Laws make it a draw when the opponent could never checkmate, and we leave that case out.
- The game keeps the list of moves played.
Castling, en passant and promotion are real rules and we model them, but in the last lessons. The first version leaves them out on purpose, so the core stays small enough to read in one sitting.
A short prompt such as "design chess" leaves rules open, so we ask questions. Ask the ones whose answers change a class or a method.
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Three matter here. The same position must always give the same legal moves, so tests can rely on them. A refused move must change nothing: not the board, not the turn and not the history. And the rules must be easy to find: when a rule changes, one class should change.
Numbers help us size the work. Each side has up to sixteen pieces, and a typical position has a few dozen legal moves. Testing each move on a copy of the board is therefore cheap, and we will not optimise it.
We rejected two designs. The first puts every rule in one long switch on the piece kind inside a single isLegal function. It works, and every new rule then edits the same function, so every change risks every piece. The second remembers "the king is in check" as a flag that each move updates. A stale flag is a classic bug, because one forgotten update lets a player ignore a check. We compute check from the board every time instead.
| Must | Should | Out of scope |
|---|---|---|
| Piece moves, legality, check, mate, stalemate, draw, resign | Castling, en passant, promotion, undo | Clocks, repetition draws, an opponent that plays by itself |
Check yourself
A player's only legal moves are all moves that leave the king attacked, and the king is not currently attacked. What is the result?
- Stalemate, a draw: the player to move has no legal move and is not in check.
Why compute check from the board instead of keeping a flag?
- A flag has to be updated after every move, and one missed update lets a check be ignored.
- The board is the single source of truth, so the answer cannot go stale.
Which of the "should" items changes the shape of a position, not only its moves?
- Castling rights and the en passant square are memory that a position must carry, because the board alone does not say whether a king has moved before.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. Chess has one kind of actor, the player, and two of them take turns. The system itself decides every question of legality, so there is no referee actor.
A use case diagram shows actors, their use cases and how those relate. Include means a use case always runs another as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Moving a piece always includes checking that the move is legal. A move that leaves the king attacked is refused, and a move that ends the game by mate or stalemate adds the end of the game, so both extend the move.
The blue box is the actor and the pills are use cases, with the exceptional one in red. An arrow from the actor means the player starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
Read the diagram as a checklist of goals. Each pill becomes a method or two and a few tests. The legality check is not something the player asks for, which is why it hangs below the move and not beside the actor.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Start a game | Two named players, the standard set-up, white to move | A set-up position given for a test |
| Move a piece | Name a start and an end square; the game checks, applies and passes the turn | Wrong turn, no piece, not a move for that piece, king left attacked: refuse |
| Offer or accept a draw | One side offers, the other accepts, the game is drawn | Before both have moved, or no offer to accept: refuse |
| Resign | The player resigns and the other side wins | The game is already over: refuse |
| End by mate or stalemate | After a move, no legal reply exists: mate if in check, else stalemate | None |
Every alternative is a named refusal, and each one must change nothing. We will assert that.
Notice that "not a move for that piece" and "king left attacked" are different refusals. In both cases the player asked for something not in the legal list. The first means the piece cannot reach that square at all. The second means it can, but the move would expose the king, and the message should say so. A player who sees "illegal move" for a pinned piece will think the program is wrong.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('two players start a game with white to move'); test.todo('a player moves a piece and the turn passes'); test.todo('a move that leaves the king attacked is refused'); test.todo('checkmate ends the game and names the winner'); test.todo('stalemate ends the game as a draw'); test.todo('a player offers a draw and the other accepts'); test.todo('a player resigns');
✔ two players start a game with white to move (0.8449ms) # TODO ✔ a player moves a piece and the turn passes (0.106ms) # TODO ✔ a move that leaves the king attacked is refused (0.0991ms) # TODO ✔ checkmate ends the game and names the winner (0.0976ms) # TODO ✔ stalemate ends the game as a draw (0.1215ms) # TODO ✔ a player offers a draw and the other accepts (0.1013ms) # TODO ✔ a player resigns (0.1072ms) # TODO ℹ tests 7 ℹ todo 7
Output (durations vary)
All seven names are reported as todo, and none counts as passed. If a name never gets a test, the requirement behind it was probably missed.
What is the difference between include and extend?
- Include: the base case always runs the included case, as a move always checks legality.
- Extend: an exceptional case adds steps under a condition, as the end of the game does after a mating move.
Why are "not a move for that piece" and "king left attacked" separate refusals?
- They tell the player different things: the piece cannot go there at all, or it can but would expose the king.
A player tries to resign after the game ended in checkmate. Which alternative applies, and what is left afterwards?
- Resign is refused because the game is already over, and the result stays checkmate.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: player, piece, square, board, move, king, check, game, turn, history, draw. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Game | Class Game | Owns turns, history, draws and the result |
| Position | Class Position | A board plus whose turn it is, and the rules over them |
| Board | Class Board | Sixty-four cells, with attack queries |
| Piece | Abstract class Piece, six subclasses | Each kind moves by its own rule |
| Square | A number from 0 to 63 | Only arithmetic is needed, so no class |
| Move | A value: from and to | No behaviour of its own |
| Player | A name and a colour | Two fields on Game |
| Check, mate | Methods on Position | They are questions about a position |
Two choices deserve a reason. A piece is a class with a method that says where it can go, so adding a rule for one kind touches one class. That is polymorphism: the same call, moves, runs different code for each kind of piece. And Position is separate from Game because the question "is this king attacked, if we play this move?" needs a position and nothing else. A Game is a position plus a history and a result.
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 0..32 means none to thirty-two. An arrow with a closed head means "is a kind of".
white, black: stringphase: Phasewinner: Color?move(by, from, to)resign(by), offerDraw(by)acceptDraw(by)board: Boardturn: Colorplay(move): PositionlegalMoves(): Move[]inCheck(), status()get(sq), set(sq, piece)clone()kingOf(color)isAttacked(sq, by)kind, colorattacks(board, from)moves(position, from)dirs: directionsattacks(): walks raysdirsattacks(): one step eachattacks(): two diagonalsmoves(): pushes, capturesfrom: Sqto: Sq- Game 1 → 1 Position
- Position 1 → 1 Board
- Board 1 → 0..32 Piece (abstract)
- Slider (abstract) → Piece (abstract)
- Rook, Bishop, Queen → Slider (abstract)
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with the small types. A square is a number, with helpers to turn it into a file and a rank. The colours and kinds are string unions, because enum is not erasable syntax and Node's type stripping rejects it.
export type Color = 'white' | 'black'; export type Kind = | 'king' | 'queen' | 'rook' | 'bishop' | 'knight' | 'pawn'; // A square is a number: 0 is a1, 7 is h1, 56 is a8, 63 is h8. export type Sq = number; export interface Move { from: Sq; to: Sq; } export const sq = (f: number, r: number): Sq => r * 8 + f; export const file = (s: Sq): number => s % 8; export const rank = (s: Sq): number => Math.floor(s / 8); export const inside = (f: number, r: number): boolean => f >= 0 && f < 8 && r >= 0 && r < 8; export const other = (c: Color): Color => c === 'white' ? 'black' : 'white'; export const nameOf = (s: Sq): string => 'abcdefgh'[file(s)]! + String(rank(s) + 1);
The next file holds the errors. Every refusal is a ChessError with a code, so callers and tests branch on the code and never on the message.
export type ChessCode = | 'BAD_SQUARE' | 'GAME_OVER' | 'NOT_YOUR_TURN' | 'NO_PIECE' | 'ILLEGAL_MOVE' | 'KING_ATTACKED' | 'DRAW_NOT_ALLOWED' | 'NO_DRAW_OFFER'; export class ChessError extends Error { readonly code: ChessCode; constructor(code: ChessCode, message: string) { super(message); this.name = 'ChessError'; this.code = code; } }
The abstract class is the heart of the design. It fixes what every piece must answer, and gives a default for the common case.
export abstract class Piece { abstract readonly kind: Kind; abstract readonly letter: string; readonly color: Color; constructor(color: Color) { this.color = color; } // Squares this piece attacks, even if its own piece stands there. abstract attacks(b: Board, from: Sq): Sq[]; // Pseudo-legal moves: they ignore whether the king is left attacked. moves(pos: Position, from: Sq): Move[] { return this.attacks(pos.board, from) .filter((to) => pos.board.get(to)?.color !== this.color) .map((to) => ({ from, to })); } }
attacks is abstract, so every subclass must say which squares it attacks. moves has a default: the attacked squares that do not hold a piece of your own colour. Only the pawn will need to replace it. Type-check the project:
Part 4 · Game states and move checks
The six phases
A state machine lists the states, the events that cause moves and the events a state refuses. Our game has six phases. Two are turns, whiteToMove and blackToMove. Four end the game: checkmate, stalemate, drawn and resigned. The scene plays a short game and shows a refused move in the middle of it.
Watch for black being refused a move that ignores the check
Read it as steps
White gives check, black cannot ignore it, and the game ends by agreement.
White's queen gives check on h5. Black then tries a7a6, which does nothing about the check, so the game answers KING_ATTACKED and the phase does not change. Only a move that removes the check is accepted, here g7g6. After that, both sides have moved, so a draw can be agreed, and the game ends.
The full picture is easier to read as a table: for each phase, what every action does.
Checking one move
The tricky action is move. A move is legal when the piece can reach the square and the mover's king is not attacked afterwards. The second half has a neat answer: try the move on a copy and look.
Watch for the king step being tried on a copy and not on the real board
Read it as steps
The position plays the move on a copy of the board and asks whether the king is attacked.
The position asks the board for a copy, moves the king there and asks whether d1 is attacked by black. It is, because a black rook stands on the open d file, so the move is dropped from the legal list. The real board never changed, which is why trying moves is safe. Everything rests on play returning a new position and leaving the old one alone.
| Step | Can fail with | Changes anything? |
|---|---|---|
| Game is not over | GAME_OVER | No |
| It is the mover's turn | NOT_YOUR_TURN | No |
| The squares exist |
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. This one plays the shortest possible game, known as fool's mate, and makes two mistakes on the way.
const game = new Game('Asha', 'Bilal'); const play = (by: 'white' | 'black', from: string, to: string) => { try { game.move(by, from, to); console.log(`${by} ${from}${to} -> ${game.phase}`); } catch (e) { const code = (e as ChessError).code; console.log(`${by} ${from}${to} refused: ${code}`); } }; play('black', 'e7', 'e5'); play('white', 'f2', 'f3'); play('black', 'e7', 'e5'); play('white', 'g2', 'g4'); play('black', 'd8', 'h4'); play('white', 'a2', 'a3'); console.log(text(game.position.board)); console.log(`winner: ${game.winner}`);
black e7e5 refused: NOT_YOUR_TURN white f2f3 -> blackToMove black e7e5 -> whiteToMove white g2g4 -> blackToMove black d8h4 -> checkmate white a2a3 refused: GAME_OVER 8 rnb.kbnr 7 pppp.ppp 6 ........ 5 ....p... 4 ......Pq 3 .....P.. 2 PPPPP..P 1 RNBQKBNR abcdefgh winner: black
Output
The first move was refused with NOT_YOUR_TURN, because white goes first. Then the two sides alternated, and after g2g4 and d8h4 the black queen checkmated the white king and the phase became checkmate. The last move was refused with GAME_OVER. The board shows white's king on e1 with no legal move, and the queen on h4 attacking it along the diagonal.
Why does the game answer NOT_YOUR_TURN before it looks at the squares?
- Turn order is the cheapest check and applies to every move, so it comes first.
- A wrong-turn move should not reveal anything about the board.
In the scene, why does a7a6 get KING_ATTACKED and not ILLEGAL_MOVE?
- A pawn can legally go from a7 to a6, so the move is a pseudo-legal one. It is refused only because black's king stays attacked.
Part 5 · Code: pieces and moves
Walking along a ray
Every piece attacks squares by walking in directions. A rook walks four, a bishop four others, a queen eight. A king and a knight take one step in each of their directions and stop. One small function, the ray walker, serves all of them. It steps from a square along a direction, collects squares, and stops at the first piece it meets. The piece it stops on is included, because it is attacked, and the caller decides whether it is a capture or a blocker.
type Dir = readonly [number, number]; // The ray walker: step along one direction, stop at the first piece. export const walk = ( b: Board, from: Sq, [df, dr]: Dir, far: boolean, ): Sq[] => { const out: Sq[] = []; let f = file(from) + df; let r = rank(from) + dr; while (inside(f, r)) { out.push(sq(f, r)); if (!far || b.get(sq(f, r))) break; f += df; r += dr; } return out; };
The far flag is what separates the families, and it is the reason one function can serve six kinds of piece. A slider keeps walking until it is stopped, and a stepper takes one step. The list of directions is data, so the pieces differ only in what they hand the walker.
const ORTHO: Dir[] = [[1, 0], [-1, 0], [0, 1], [0, -1]]; const DIAG: Dir[] = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; abstract class Slider extends Piece { abstract readonly dirs: readonly Dir[]; attacks(b: Board, from: Sq): Sq[] { return this.dirs.flatMap((d) => walk(b, from, d, true)); } } export class Rook extends Slider { readonly kind = 'rook'; readonly letter = 'r'; readonly dirs = ORTHO; } export class Bishop extends Slider { readonly kind = 'bishop'; readonly letter = 'b'; readonly dirs = DIAG; } export class Queen extends Slider { readonly kind = 'queen'; readonly letter = 'q'; readonly dirs = [...ORTHO, ...DIAG]; }
Slider is abstract and holds the one thing the three share. Each subclass is three lines: its kind, its letter and its list of directions. A queen's directions are simply the rook's and the bishop's together, which is exactly how a queen is defined.
A small factory turns a kind and a colour into the right object, which the test set-up code and, in a later lesson, the promotion rule both need. It is the only place that names all six classes, so adding a piece means one new class and one new line there. The letter field exists only for printing, so the demo can draw a board as text.
Steppers and the pawn
The knight and the king take one step in each direction, with far set to false.
const JUMPS: Dir[] = [ [1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2], ]; export class Knight extends Piece { readonly kind = 'knight'; readonly letter = 'n'; attacks(b: Board, from: Sq): Sq[] { return JUMPS.flatMap((d) => walk(b, from, d, false)); } } export class King extends Piece { readonly kind = 'king'; readonly letter = 'k'; attacks(b: Board, from: Sq): Sq[] { return [...ORTHO, ...DIAG].flatMap((d) => walk(b, from, d, false)); } }
A knight jumps over pieces, and the walker already gives that for free: with one step in each of eight directions, nothing stands in the way. The pawn is different, because its attack squares and its move squares differ. It attacks diagonally, even onto an empty square, but it can only move there to capture. It pushes straight ahead only onto an empty square, and from its starting rank it may push two.
export class Pawn extends Piece { readonly kind = 'pawn'; readonly letter = 'p'; get #step(): number { return this.color === 'white' ? 1 : -1; } // A pawn attacks the two squares ahead on its diagonals. attacks(_b: Board, from: Sq): Sq[] { const r = rank(from) + this.#step; return [file(from) - 1, file(from) + 1] .filter((f) => inside(f, r)) .map((f) => sq(f, r)); }
That separation is why attacks and moves are two methods. When we ask "is this square attacked?", we need the pawn's diagonals whether or not anything stands there. When we ask "where can it move?", we need its pushes and its captures.
moves(pos: Position, from: Sq): Move[] { const out: Move[] = []; const r = rank(from); const one = sq(file(from), r + this.#step); const two = sq(file(from), r + 2 * this.#step); const home = this.color === 'white' ? 1 : 6; if (inside(file(from), r + this.#step) && !pos.board.get(one)) { out.push({ from, to: one }); if (r === home && !pos.board.get(two)) { out.push({ from, to: two }); } } for (const to of this.attacks(pos.board, from)) { const t = pos.board.get(to); if (t && t.color !== this.color) out.push({ from, to }); } return out; } }
The push checks that the next square is on the board and empty, then the starting rank and the square beyond. The loop adds captures: a diagonal square counts only when an enemy piece stands on it. In this first version, a pawn on the last rank has nowhere to go. A later lesson fixes that.
Tests, piece by piece
The helpers set up a position from a short text called FEN, for Forsyth–Edwards Notation, which lists the pieces on each rank from the eighth down to the first. A capital letter is white, a lower-case one black, a number means that many empty squares, and w or b says whose turn it is. pseudo returns the squares a piece could move to if we ignore check.
test('a knight in the corner has two moves', () => { assert.deepEqual(pseudo('8/8/8/8/8/8/8/N7 w', 'a1'), ['b3', 'c2']); }); test('a rook stops at its own piece and takes an enemy one', () => { const own = pseudo('8/8/3P4/8/3R4/8/8/8 w', 'd4'); assert.equal(own.length, 11); assert.ok(own.includes('d5') && !own.includes('d6')); const enemy = pseudo('8/8/3p4/8/3R4/8/8/8 w', 'd4'); assert.ok(enemy.includes('d6') && !enemy.includes('d7')); }); test('sliders and the king count their squares', () => { assert.equal(pseudo('8/8/8/8/3Q4/8/8/8 w', 'd4').length, 27); assert.equal(pseudo('8/8/8/8/3B4/8/8/8 w', 'd4').length, 13); assert.equal(pseudo('8/8/8/8/4K3/8/8/8 w', 'e4').length, 8); });
The other tests count squares for a queen, a bishop and a king on an empty board, check the pawn's pushes and captures, and count white's moves from the start position.
✔ a knight in the corner has two moves (2.3174ms) ✔ a rook stops at its own piece and takes an enemy one (0.582ms) ✔ sliders and the king count their squares (0.3596ms) ✔ a pawn pushes one or two, and captures only diagonally (0.4002ms) ✔ the start position gives white twenty legal moves (1.1586ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
The counts are checkable by hand, which is the point. A queen on d4 of an empty board attacks 27 squares, a bishop 13 and a king 8, and the start position gives white 20 moves: sixteen from the pawns and four from the two knights.
Why does the ray walker include the square of the piece it stops on?
- That square is attacked, and the caller decides whether it is a capture or blocked by a piece of the same colour.
Why does a pawn have separate attacks and moves?
- It attacks diagonally even where nothing stands, but moves there only to capture.
Part 6 · Code: legality and game end
Attacks, positions and check
A square is attacked when some piece of the other colour attacks it. The board can answer that by asking each enemy piece for its attacked squares. Because attacks ignores whose piece stands where, one question serves every kind.
kingOf(color: Color): Sq {
const found = this.pieces(color).find(([, p]) => p.kind === 'king');
if (!found) throw new Error(`no ${color} king on the board`);
return found[0];
}
isAttacked(s: Sq, by: Color): boolean {
return this.pieces(by).some(([from, p]) =>
p.attacks(this, from).includes(s));
}
}kingOf finds the king, and isAttacked asks every piece of the other colour. It is not fast, but it is a few dozen small calls, and it is correct for every piece without a special case. The position builds check on top of that.
// Applies a move to a copy. This position is left unchanged. play(m: Move): Position { const board = this.board.clone(); board.set(m.to, board.get(m.from)); board.set(m.from, undefined); return new Position(board, other(this.turn)); } isKingAttacked(color: Color): boolean { const king = this.board.kingOf(color); return this.board.isAttacked(king, other(color)); } inCheck(): boolean { return this.isKingAttacked(this.turn); } pseudoMoves(): Move[] { return this.board .pieces(this.turn) .flatMap(([from, p]) => p.moves(this, from)); } legalMoves(): Move[] { return this.pseudoMoves().filter( (m) => !this.play(m).isKingAttacked(this.turn), ); } status(): 'ongoing' | 'checkmate' | 'stalemate' { if (this.legalMoves().length > 0) return 'ongoing'; return this.inCheck() ? 'checkmate' : 'stalemate'; } }
play copies the board, moves the piece and returns a new position with the turn flipped. Nothing the old position holds is touched. legalMoves then tries every pseudo-legal move on its own copy and keeps those after which the mover's king is not attacked. Everything that follows, pins and escapes from check included, comes out of that one filter.
Pins, check and checkmate in tests
A pin is a piece that cannot move without exposing its king. We never wrote a rule for pins. The filter above handles them, and the tests show it.
test('a pinned rook can only move along the pin', () => { const fen = '4r3/8/8/8/8/8/4R3/4K3 w'; assert.ok(pseudo(fen, 'e2').includes('a2')); assert.deepEqual(legal(fen, 'e2'), [ 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', ]); }); test('a king cannot step onto an attacked square', () => { assert.deepEqual(legal('3r4/8/8/8/8/8/8/4K3 w', 'e1'), [ 'e2', 'f1', 'f2', ]); }); test('a pawn attacks diagonally, so the king avoids e2', () => { assert.deepEqual(legal('8/8/8/8/8/3p4/8/4K3 w', 'e1'), [ 'd1', 'd2', 'f1', 'f2', ]); }); test('in check, only moves that answer the check are legal', () => { const fen = '4r3/8/8/8/8/8/8/4K1N1 w'; assert.deepEqual(legal(fen, 'g1'), ['e2']); assert.deepEqual(legal(fen, 'e1'), ['d1', 'd2', 'f1', 'f2']); });
The first test sets up a white rook on e2 between its king and a black rook. The pseudo-legal list holds squares like a2, but the legal list holds only squares on the e file, where the rook still shields the king. The third test shows why attacks and moves differ: the king avoids e2 because the pawn on d3 attacks it, even though that pawn could never move there.
✔ a pinned rook can only move along the pin (2.3958ms) ✔ a king cannot step onto an attacked square (0.2142ms) ✔ a pawn attacks diagonally, so the king avoids e2 (0.3357ms) ✔ in check, only moves that answer the check are legal (0.4995ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
All four pass. The fourth is the escape from check: of the knight's moves, only the one that blocks is legal, and the king has four safe squares.
The filter does real work, and a short run shows how much. At the start position every pseudo-legal move is also legal. With a pinned rook in front of its king, seven of the seventeen pseudo-legal moves are dropped.
const show = (l: string, n: number) => console.log(`${l}: ${n}`); const start = parseFen(START); show('start, pseudo-legal', start.pseudoMoves().length); show('start, legal', start.legalMoves().length); const pinned = parseFen('4r3/8/8/8/8/8/4R3/4K3 w'); show('pinned rook, pseudo-legal', pinned.pseudoMoves().length); show('pinned rook, legal', pinned.legalMoves().length);
start, pseudo-legal: 20 start, legal: 20 pinned rook, pseudo-legal: 17 pinned rook, legal: 10
Output
Mate, stalemate and the game
The game ties these together. After every move it asks the position for its status. No legal move plus check is checkmate, and no legal move without check is stalemate.
#settle(): void { const status = this.#position.status(); const turn = this.#position.turn; if (status === 'checkmate') { this.#phase = 'checkmate'; this.#winner = other(turn); } else if (status === 'stalemate') { this.#phase = 'stalemate'; } else { this.#phase = turn === 'white' ? 'whiteToMove' : 'blackToMove'; } } #assertActive(): void { const p = this.#phase; if (p !== 'whiteToMove' && p !== 'blackToMove') { throw new ChessError('GAME_OVER', `the game is ${p}`); } }
Checkmate also names the winner, the side that did not have to move. The same method runs when a game is created, so a set-up position that is already over starts in the right phase. The move method is the table from the previous lesson, written as code.
move(by: Color, from: string, to: string): void { this.#assertActive(); const turn = this.#position.turn; if (by !== turn) { throw new ChessError('NOT_YOUR_TURN', `it is ${turn} to move`); } const move: Move = { from: parseSquare(from), to: parseSquare(to) }; if (this.#position.board.get(move.from)?.color !== by) { throw new ChessError('NO_PIECE', `no ${by} piece on ${from}`); } const same = (m: Move) => m.from === move.from && m.to === move.to; if (!this.#position.legalMoves().some(same)) { const reaches = this.#position.pseudoMoves().some(same); throw reaches ? new ChessError('KING_ATTACKED', 'your king would be attacked') : new ChessError('ILLEGAL_MOVE', `${from} cannot go to ${to}`); } this.#position = this.#position.play(move); this.#history.push(`${from}${to}`); this.#drawOffer = undefined; this.#settle(); }
Each check above the last two lines throws before any state changes. The refusal for a king left attacked is told apart from a plain illegal move by one extra question: is the move in the pseudo-legal list?
Tests for the end of the game
The tests use known positions. Fool's mate is a game of four moves. A back-rank mate is a set-up in which a rook gives check along the eighth rank and black's own pawns block the king's escape. The stalemate position is the standard one: black's king on h8 has no square to go to, and nothing attacks it.
test('fool\'s mate: black mates in two moves', () => { const g = new Game('Asha', 'Bilal'); play(g, 'f2f3 e7e5 g2g4 d8h4'); assert.equal(g.phase, 'checkmate'); assert.equal(g.winner, 'black'); assert.throws(() => play(g, 'a2a3'), { code: 'GAME_OVER' }); }); test('a back-rank mate from a set-up position', () => { const start = parseFen('6k1/5ppp/8/8/8/8/8/R3K3 w'); const g = new Game('Asha', 'Bilal', start); assert.equal(g.phase, 'whiteToMove'); play(g, 'a1a8'); assert.equal(g.phase, 'checkmate'); assert.equal(g.winner, 'white'); });
✔ fool's mate: black mates in two moves (7.1803ms) ✔ a back-rank mate from a set-up position (0.4449ms) ✔ check is not mate while the king has a way out (0.4339ms) ✔ a known stalemate: no legal move and no check (0.2003ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The game tests cover refusals and the end actions. The refusal test shows that a refused move changes nothing: the position is the very same object, the history is empty and the phase is the same.
test('a refused move changes nothing', () => { const start = parseFen('3r4/8/8/8/8/8/8/4K3 w'); const g = new Game('Asha', 'Bilal', start); assert.throws(() => g.move('white', 'e1', 'd1'), { code: 'KING_ATTACKED', }); assert.equal(g.position, start); assert.deepEqual(g.history, []); assert.equal(g.phase, 'whiteToMove'); });
✔ each refusal has its own code (4.1449ms) ✔ a refused move changes nothing (0.7153ms) ✔ resigning ends the game for the other side (0.8897ms) ✔ a draw needs an offer from the other side (2.6329ms) ✔ a move withdraws an offer that is still open (2.3702ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output (durations vary)
Why does legalMoves try moves on a copy and not undo them on the real board?
playleaves the original untouched, so there is nothing to undo and no way to forget.
How does the code tell checkmate from stalemate?
- Both mean no legal move for the side to move. Checkmate is when that side's king is attacked, and stalemate when it is not.
Part 7 · Extensions and trade-offs
Every use case, tested
The use case lesson left seven test.todo names. With the game in place, each becomes a real test that drives it the way a player would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('two players start a game with white to move', () => { const g = new Game('Asha', 'Bilal'); assert.equal(g.phase, 'whiteToMove'); assert.deepEqual([g.white, g.black], ['Asha', 'Bilal']); }); test('a player moves a piece and the turn passes', () => { const g = new Game('Asha', 'Bilal'); g.move('white', 'e2', 'e4'); assert.equal(g.phase, 'blackToMove'); assert.deepEqual(g.history, ['e2e4']); }); test('a move that leaves the king attacked is refused', () => { const start = parseFen('3r4/8/8/8/8/8/8/4K3 w'); const g = new Game('Asha', 'Bilal', start); assert.throws(() => g.move('white', 'e1', 'd2'), { code: 'KING_ATTACKED', }); }); test('checkmate ends the game and names the winner', () => { const g = new Game('Asha', 'Bilal'); play(g, 'f2f3 e7e5 g2g4 d8h4'); assert.equal(g.phase, 'checkmate'); assert.equal(g.winner, 'black'); });
The other three cover stalemate, the draw and resignation.
✔ two players start a game with white to move (3.045ms) ✔ a player moves a piece and the turn passes (2.1504ms) ✔ a move that leaves the king attacked is refused (0.7521ms) ✔ checkmate ends the game and names the winner (3.2211ms) ✔ stalemate ends the game as a draw (0.1799ms) ✔ a player offers a draw and the other accepts (1.4057ms) ✔ a player resigns (0.3555ms) ℹ tests 7 ℹ pass 7 ℹ fail 0 ℹ todo 0
Output (durations vary)
Seven pass and no todo is left. The whole suite, including the earlier tests, also passes.
ℹ tests 25 ℹ pass 25 ℹ fail 0 ℹ todo 0
Output: whole suite
Castling
Castling needs memory that the board does not hold: whether the king or the rook has ever moved. The position gains a set of castling rights, one letter per right, and a right is lost the first time a move touches the king's square or that rook's square. The rest of this lesson lives in a copy of the project with the new code laid over the old.
// A castling right is lost when a move touches its king or rook square. const TOUCH: Record<string, Sq[]> = { K: [4, 7], Q: [4, 0], k: [60, 63], q: [60, 56], };
One table does the bookkeeping. A move that starts from or lands on a listed square removes the right. That covers a rook that moves, a king that moves and a rook that is captured on its own square. Article 3.8.2.1 of the Laws says the right to castle is lost once the king or that rook has moved. Article 3.8.2.2 says castling is prevented for the moment while a piece stands between them or while the king's square, the square it crosses or its destination is attacked.
castles(): Move[] {
const white = this.turn === 'white';
const home = white ? 4 : 60;
const foe = other(this.turn);
if (this.board.isAttacked(home, foe)) return [];
const sides: [string, number, number[]][] = [
[white ? 'K' : 'k', 1, [1, 2]],
[white ? 'Q' : 'q', -1, [1, 2, 3]],
];
const out: Move[] = [];
for (const [right, dir, between] of sides) {
if (!this.castling.has(right)) continue;
if (between.some((n) => this.board.get(home + dir * n))) continue;
const cross = [home + dir, home + 2 * dir];
if (cross.some((s) => this.board.isAttacked(s, foe))) continue;
out.push({ from: home, to: home + 2 * dir });
}
return out;
}The first line refuses castling out of check. Then each side is tried: the right must still be held, the squares between must be empty, and the two squares the king crosses and lands on must be safe. Moves from castles join the legal list. When one is played, play also moves the rook beside the king.
const BOTH = 'r3k2r/8/8/8/8/8/8/R3K2R w KQkq'; test('both castles are legal on an open back rank', () => { const moves = legal(BOTH, 'e1'); assert.ok(moves.includes('g1') && moves.includes('c1')); }); test('castling moves the king two and the rook beside it', () => { const g = new Game('Asha', 'Bilal', parseFen(BOTH)); g.move('white', 'e1', 'g1'); const b = g.position.board; assert.equal(b.get(sq(6, 0))?.kind, 'king'); assert.equal(b.get(sq(5, 0))?.kind, 'rook'); assert.equal(b.get(sq(7, 0)), undefined); }); test('no castling out of, or through, an attacked square', () => { const inCheck = legal('4r3/8/8/8/8/8/8/R3K2R w KQ', 'e1'); assert.ok(!inCheck.includes('g1') && !inCheck.includes('c1')); const through = legal('4kr2/8/8/8/8/8/8/R3K2R w KQ', 'e1'); assert.ok(!through.includes('g1') && through.includes('c1')); });
En passant and promotion
Two pawn rules complete the set. En passant lets a pawn capture an enemy pawn that has just advanced two squares, as if it had advanced only one, and only on the move right after (articles 3.7.3.1 and 3.7.3.2). The position records the square the jumping pawn passed over, and play clears it on the following move. Promotion makes a pawn that reaches the last rank become a queen, rook, bishop or knight of its colour, chosen by the player (article 3.7).
// Reaching the last rank becomes four moves, one per new piece. #land(from: Sq, to: Sq): Move[] { const last = this.color === 'white' ? 7 : 0; if (rank(to) !== last) return [{ from, to }]; return PROMOTIONS.map((promotion) => ({ from, to, promotion })); }
A move onto the last rank becomes four moves, one for each new piece, and the Move type gains an optional promotion. The game then needs the player's choice. If the move has four legal versions and none was named, it answers PROMOTION_NEEDED.
test('en passant takes the pawn that just jumped', () => { const g = new Game('Asha', 'Bilal'); play(g, 'e2e4 a7a6 e4e5 d7d5 e5d6'); const b = g.position.board; assert.equal(b.get(sq(3, 5))?.kind, 'pawn'); assert.equal(b.get(sq(3, 4)), undefined); }); test('the en passant chance lasts one move only', () => { const g = new Game('Asha', 'Bilal'); play(g, 'e2e4 a7a6 e4e5 d7d5 a2a3 a6a5'); assert.throws(() => g.move('white', 'e5', 'd6'), { code: 'ILLEGAL_MOVE', }); });
The last two tests check the four promotion moves and the player's choice.
test('a pawn on the seventh rank has four ways forward', () => { const fen = '8/4P2k/8/8/8/8/8/K7 w'; assert.deepEqual(legal(fen, 'e7'), ['e8', 'e8', 'e8', 'e8']); }); test('promotion needs a choice and honours it', () => { const start = parseFen('8/4P2k/8/8/8/8/8/K7 w'); const g = new Game('Asha', 'Bilal', start); assert.throws(() => g.move('white', 'e7', 'e8'), { code: 'PROMOTION_NEEDED', }); g.move('white', 'e7', 'e8', 'knight'); assert.equal(g.position.board.get(sq(4, 7))?.kind, 'knight'); assert.deepEqual(g.history, ['e7e8n']); });
✔ en passant takes the pawn that just jumped (10.3284ms) ✔ the en passant chance lasts one move only (6.7092ms) ✔ a pawn on the seventh rank has four ways forward (0.7801ms) ✔ promotion needs a choice and honours it (0.4125ms) ℹ tests 4 ℹ pass 4 ℹ fail 0
Output (durations vary)
The en passant test plays a real sequence and checks that the captured pawn disappears from the square beside the capturer, not from the landing square. The second test lets the chance pass for one move and the capture is refused.
Undo, and where this design is weak
Undo is cheap because positions are immutable. The game keeps the position before each move, and undoing restores the last one. This is a memento, a saved snapshot of an earlier state. The other common way is a command object that knows how to reverse its move, as in the editor example of the patterns chapter. That is the better tool when a change happens in place and the old state is gone, so a reverse step must be written for each kind of change. Here play never changes the old position, so saving it is enough. Taking back a checkmate works too, because the phase is recomputed from the restored position.
undo(): void { if (this.#phase === 'drawn' || this.#phase === 'resigned') { throw new ChessError('GAME_OVER', `the game is ${this.#phase}`); } const before = this.#before.pop(); if (!before) { throw new ChessError('NOTHING_TO_UNDO', 'no move to take back'); } this.#history.pop(); this.#position = before; this.#winner = undefined; this.#drawOffer = undefined; this.#settle(); }
test('undo restores the position before the last move', () => { const g = new Game('Asha', 'Bilal'); g.move('white', 'e2', 'e4'); const afterOne = g.position; g.move('black', 'e7', 'e5'); g.undo(); assert.equal(g.position, afterOne); assert.deepEqual(g.history, ['e2e4']); assert.equal(g.phase, 'blackToMove'); }); test('a checkmate can be taken back', () => { const g = new Game('Asha', 'Bilal'); play(g, 'f2f3 e7e5 g2g4 d8h4'); assert.equal(g.phase, 'checkmate'); g.undo(); assert.equal(g.phase, 'blackToMove'); assert.equal(g.winner, undefined); });
✔ undo restores the position before the last move (7.8786ms) ✔ a checkmate can be taken back (3.4735ms) ✔ there is nothing to undo at the start (0.6256ms) ℹ tests 3 ℹ pass 3 ℹ fail 0
Output (durations vary)
ℹ tests 36 ℹ pass 36 ℹ fail 0 ℹ todo 0
Output: whole extended suite
Every design has costs. Copying a board for every pseudo-legal move is simple and plenty fast for human play, though an engine that searches millions of positions would use a faster scheme. We never detect draws by repetition or by a count of moves, which the Laws also define. A game cannot be saved to a file and loaded again, because we left out a notation for that. And the undo is unlimited, which a real game would not allow.
| Term | Meaning |
|---|
All chapters · Previous: ATM: Sessions, PIN Checks, Cash Dispensing and Reversals