SyntaxPilot
Courses/Low-Level Design/Lesson 85
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 85 of 90

Design a chess game 1: board, pieces and moves

chess requirementsBoardSquarePiece hierarchyKing Queen Rook Bishop Knight Pawnmove generation per pieceMovePlayerpolymorphic move rulesboard setup

These are the notes for Low-Level Design (LLD) episode 85: the first half of a classic machine-coding question, design a chess game. We cover the chess requirements, the Board and Square classes, a Piece hierarchy with King, Queen, Rook, Bishop, Knight and Pawn, move generation per piece with polymorphic move rules, and the Move, Player and board setup that turn pieces into a game. Episode 86 adds check, checkmate, castling, en passant, promotion and undo.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. The chess rules are the standard rules of chess; the players are made up.

1. The problem: Dadaji's chessboard in the park

Dadaji is teaching his grandson chess in the park.

  • The board has 64 squares: 8 columns named a to h and 8 rows numbered 1 to 8, so every square has a name, like e4.
  • He teaches each piece its own rule: "the horse jumps in an L, the rook goes straight, the bishop slants". He never recites one big rule for everything.
  • "Wait, it's my turn!": white moves, then black, then white.
  • In a club game, every move is written on a scoresheet.
Real life In the design
The board with 64 named squares Board, Square
"The horse jumps in an L" A Knight class with its own moves()
Each piece moving its own way The Piece hierarchy and polymorphic move rules
The person on each side Player (name + colour)
"It's my turn" The game's turn
A line on the scoresheet Move
The whole scoresheet The move history

2. Chess requirements, and the words we need

Chess requirements for this episode (what we promise to build):

  1. Board setup: put the 32 pieces in the starting position.
  2. Move generation: for any piece, list the squares it can move to.
  3. Two players take turns.
  4. Reject wrong moves with a clear error.
  5. Keep a history of moves.

Out of scope until episode 86: check, checkmate, stalemate, castling, en passant, promotion, undo. In an interview, saying what is in scope and what comes later is part of the round.

Chess words:

  • File: a column, a to h. Rank: a row, 1 to 8. e4 = file e, rank 4.
  • Capture: moving onto a square that holds an enemy piece; that piece is taken off the board.
  • Algebraic notation: the standard way to write moves: e4, Nf3 (N = knight), Nxe5 (x = capture).
  • In our printouts, capital letters are white pieces and small letters are black: K/k king, Q queen, R rook, B bishop, N knight, P pawn.

How each piece moves (standard chess rules):

Piece How it moves Family
King One square in any of the 8 directions Stepping
Queen Any distance straight or diagonally Sliding
Rook Any distance straight (along a file or rank) Sliding
Bishop Any distance diagonally Sliding
Knight An "L": two squares one way, one square to the side; jumps over pieces Stepping (jumping)
Pawn Forward one square (two from its starting rank); captures one square diagonally forward Its own rule

3. Attempt 1: a grid of letters and one big switch

The first idea most people have: a char[8][8] with letters, and one method with a switch on the letter.

public class Main {
    static char[][] board = new char[8][8];          // attempt: letters on a grid, 'R' white rook, 'r' black
    static int countMoves(int row, int col) {
        int moves = 0;
        switch (board[row][col]) {                           // one big switch for every kind of piece
            case 'R', 'r' -> {
                for (int c = col + 1; board[row][c] == '.'; c++) moves++;     // slide right until a piece
            }
            case 'N', 'n' -> moves = 8;                      // "a knight always has 8 moves"?
            default -> System.out.println("no rules for " + board[row][col] + " yet");
        }
        return moves;
    }
    public static void main(String[] args) {
        for (char[] r : board) java.util.Arrays.fill(r, '.');
        board[0][0] = 'N';                                   // a knight in the corner
        board[3][3] = 'Q';                                   // a queen
        board[5][0] = 'R';                                   // a rook with an empty row in front of it
        System.out.println("knight in the corner: " + countMoves(0, 0) + " moves");
        System.out.println("queen: " + countMoves(3, 3) + " moves");
        System.out.println("rook: " + countMoves(5, 0) + " moves");
    }
}

Real output:

knight in the corner: 8 moves
no rules for Q yet
queen: 0 moves
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8
    at Main.countMoves(Main.java:7)
    at Main.main(Main.java:21)

Why it failed

  • A letter is just data. 'N' can't tell you how a knight moves, so the rule lives far away in a switch, and someone wrote "always 8 moves". From a corner (a1) a knight really has 2 moves.
  • No bounds check. The rook loop c++ walked past column 7: ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8. Every loop has to remember the edge, and one forgot.
  • One switch for every piece. The queen had no rules for Q yet. Every new rule edits the same method; it breaks the Open-Closed Principle (episode 13: open for extension, closed for modification).

4. The fix, part 1: Square and Board

  • Square is a record: Java's short way to write a small class that only holds values (here file and rank). A record gets a constructor, getters (file(), rank()), equals, hashCode and toString for free.
  • A Square is a value object: two squares with the same file and rank are equal, so it works as a HashMap key.
  • It knows one question: onBoard(). And it can make a neighbour: plus(df, dr).
  • Board keeps a Map<Square, Piece> with only the occupied squares, guards its edges in put, and returns an Optional from at: a box that may hold a piece or be empty, so the caller must handle "no piece here".
  • enum Color has exactly two values, WHITE and BLACK. An enum is a type with a fixed list of values.
import java.util.*;  enum Color { WHITE, BLACK }
record Square(int file, int rank) {                         // file a-h = 0-7, rank 1-8 = 0-7
    static Square of(String s) { return new Square(s.charAt(0) - 'a', s.charAt(1) - '1'); }   // "e4"
    boolean onBoard() { return file >= 0 && file < 8 && rank >= 0 && rank < 8; }
    Square plus(int df, int dr) { return new Square(file + df, rank + dr); }
    public String toString() { return "" + (char) ('a' + file) + (rank + 1); } }
record Piece(Color color, char kind) {                      // for now: just a colour and a letter
    public String toString() { return "" + (color == Color.WHITE ? kind : Character.toLowerCase(kind)); } }
class Board {
    private final Map<Square, Piece> pieces = new HashMap<>();          // only squares that hold a piece
    Optional<Piece> at(Square s) { return Optional.ofNullable(pieces.get(s)); }
    void put(Square s, Piece p) {
        if (!s.onBoard()) throw new IllegalArgumentException("Off the board: " + s);
        pieces.put(s, p); }
    void setUp() {                                                      // the starting position
        for (int f = 0; f < 8; f++) for (Color c : Color.values()) {
            int home = c == Color.WHITE ? 0 : 7, pawns = c == Color.WHITE ? 1 : 6;
            put(new Square(f, home), new Piece(c, "RNBQKBNR".charAt(f)));
            put(new Square(f, pawns), new Piece(c, 'P')); } }
    void print() {
        for (int r = 7; r >= 0; r--) { String line = (r + 1) + "  ";
            for (int f = 0; f < 8; f++) line += at(new Square(f, r)).map(Piece::toString).orElse(".") + " ";
            System.out.println(line); }
        System.out.println("   a b c d e f g h   (" + pieces.size() + " pieces)"); } }
public class Main { public static void main(String[] args) {
    Board b = new Board();  b.setUp();  b.print();
    System.out.println("e1: " + b.at(Square.of("e1")).get() + ", e4 empty? " + b.at(Square.of("e4")).isEmpty());
    b.put(Square.of("e2").plus(0, 7), new Piece(Color.WHITE, 'Q'));   // e2 + 7 ranks = e9
} }

Real output:

8  r n b q k b n r 
7  p p p p p p p p 
6  . . . . . . . . 
5  . . . . . . . . 
4  . . . . . . . . 
3  . . . . . . . . 
2  P P P P P P P P 
1  R N B Q K B N R 
   a b c d e f g h   (32 pieces)
e1: K, e4 empty? true
Exception in thread "main" java.lang.IllegalArgumentException: Off the board: e9
    at Board.put(Main.java:13)
    at Main.main(Main.java:28)
  • The starting position (board setup): white's back rank R N B Q K B N R on rank 1, white pawns on rank 2, black pawns on rank 7, black pieces on rank 8. Queen on d1/d8 ("the queen on her own colour"), king on e1/e8.
  • e2 + 7 ranks = e9 is refused with a clear message instead of a random array crash.

5. The fix, part 2: the Piece hierarchy and polymorphic move rules

Real-life picture: on a cricket field the captain shouts one word, "Positions!", and every player goes to his own place. One call, and each answers in his own way; a new player joins and the call doesn't change. That's polymorphism: one method call, and each object runs its own version.

  • abstract class Piece: a class you can't create directly (new Piece(...) is a compile error), only extend. It has a color and a method moves(board, from) that returns the squares it can go to.
  • King, Queen, Rook, Bishop, Knight, Pawn each extend Piece: that's the Piece hierarchy (a parent class with child classes, "a Knight is a Piece").
  • Polymorphic move rules: the caller writes piece.moves(board, from) and never asks "which piece are you?". There is no switch and no instanceof.
  • Two families appear:
  • Sliding pieces (Rook, Bishop, Queen) go as far as they like in a direction until blocked.
  • Stepping pieces (King, Knight) take one step (the knight's "step" is its L-shaped jump; it can jump over pieces).
  • So five pieces share one helper, walk(directions, slides): for each direction, step square by square; an empty square is a move; an enemy is a capture and then stop; your own piece blocks; a stepping piece stops after one step.
  • Pseudo-legal moves: moves that follow each piece's own rule, but don't yet check whether your own king is left attacked. Episode 86 filters them into legal moves.
import java.util.*;  enum Color { WHITE, BLACK }
record Sq(int f, int r) { boolean on() { return f >= 0 && f < 8 && r >= 0 && r < 8; }
    Sq plus(int df, int dr) { return new Sq(f + df, r + dr); }
    static Sq of(String s) { return new Sq(s.charAt(0) - 'a', s.charAt(1) - '1'); }
    public String toString() { return "" + (char) ('a' + f) + (r + 1); } }
class Board { final Map<Sq, Piece> map = new HashMap<>();  Piece at(Sq s) { return map.get(s); }
    Board put(String s, Piece p) { map.put(Sq.of(s), p);  return this; } }
abstract class Piece { final Color color;  final int[][] dirs;  final boolean slides;
    Piece(Color c, int[][] d, boolean s) { color = c;  dirs = d;  slides = s; }
    List<Sq> moves(Board b, Sq from) {  List<Sq> out = new ArrayList<>();   // the usual rule: walk each direction
        for (int[] d : dirs) for (Sq s = from.plus(d[0], d[1]); s.on(); s = s.plus(d[0], d[1])) {
            Piece p = b.at(s);  if (p == null || p.color != color) out.add(s);   // empty, or capture
            if (p != null || !slides) break; }                                  // blocked, or one step only
        return out; } }
interface Dirs { int[][] LINE = {{1,0},{-1,0},{0,1},{0,-1}}, DIAG = {{1,1},{1,-1},{-1,1},{-1,-1}},
    BOTH = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}},
    L = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}; }               // the knight's L jumps
class Rook extends Piece { Rook(Color c) { super(c, Dirs.LINE, true); } }        // slides in straight lines
class Bishop extends Piece { Bishop(Color c) { super(c, Dirs.DIAG, true); } }    // slides on diagonals
class Queen extends Piece { Queen(Color c) { super(c, Dirs.BOTH, true); } }      // slides both ways
class King extends Piece { King(Color c) { super(c, Dirs.BOTH, false); } }       // one step any way
class Knight extends Piece { Knight(Color c) { super(c, Dirs.L, false); } }      // jumps, never blocked
public class Main { static void show(Piece p, String at, Board b) {
        List<Sq> m = p.moves(b, Sq.of(at));  String name = p.getClass().getSimpleName();
        System.out.println(name + " on " + at + ": " + m.size() + (m.size() < 9 ? " " + m : "")); }
    public static void main(String[] args) { Board empty = new Board();  Color W = Color.WHITE;
        show(new Knight(W), "a1", empty);  show(new Knight(W), "e4", empty);  show(new King(W), "a1", empty);
        show(new Rook(W), "d4", empty);  show(new Bishop(W), "d4", empty);  show(new Queen(W), "d4", empty);
        show(new Rook(W), "a1", new Board().put("a2", new King(W)).put("c1", new Knight(Color.BLACK))); } }

Real output:

Knight on a1: 2 [b3, c2]
Knight on e4: 8 [f6, g5, g3, f2, d2, c3, c5, d6]
King on a1: 3 [b1, a2, b2]
Rook on d4: 14
Bishop on d4: 13
Queen on d4: 27
Rook on a1: 2 [b1, c1]

Check the numbers by hand:

Piece and square (empty board) Moves Why
Knight on a1 2 b3 and c2; the other six L-jumps leave the board
Knight on e4 8 All eight L-jumps stay on the board
King on a1 3 b1, a2, b2
Rook on d4 14 7 squares along the file + 7 along the rank (from any square)
Bishop on d4 13 Diagonals: 3 + 3 + 4 + 3
Queen on d4 27 Rook + bishop = 14 + 13
Rook on a1, own king on a2, enemy knight on c1 2 b1, and c1 (capture, then stop)

Here the subclasses pass their directions to the parent's constructor (super(c, Dirs.LINE, true)), so each one is one line. Another common style (used in the mini project below) is to override moves() in every class and call the shared walk() from it. Both are polymorphic.

6. The pawn breaks the pattern: method overriding

The pawn is the odd one out:

  • It moves forward only, and "forward" depends on colour: up for white (+1 rank), down for black (−1).
  • One square forward, or two on its very first move (from rank 2 for white, rank 7 for black). Both squares must be empty.
  • It can't capture forward: any piece in front blocks it.
  • It captures diagonally, one square forward.

So Pawn writes its own moves(): method overriding (a subclass replaces a parent method with its own version, same name and parameters). The caller still just calls moves().

import java.util.*;  enum Color { WHITE, BLACK }
record Sq(int f, int r) { boolean on() { return f >= 0 && f < 8 && r >= 0 && r < 8; }
    Sq plus(int df, int dr) { return new Sq(f + df, r + dr); }
    static Sq of(String s) { return new Sq(s.charAt(0) - 'a', s.charAt(1) - '1'); }
    public String toString() { return "" + (char) ('a' + f) + (r + 1); } }
abstract class Piece { final Color color;  Piece(Color c) { color = c; }
    abstract List<Sq> moves(Map<Sq, Piece> b, Sq from); }                    // each piece: its own rule
class Knight extends Piece { Knight(Color c) { super(c); }
    List<Sq> moves(Map<Sq, Piece> b, Sq s) { List<Sq> out = new ArrayList<>();
        for (int[] d : new int[][] {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}) {
            Sq t = s.plus(d[0], d[1]);  Piece p = b.get(t);
            if (t.on() && (p == null || p.color != color)) out.add(t); }  return out; } }
class Pawn extends Piece { Pawn(Color c) { super(c); }                      // the odd one out
    List<Sq> moves(Map<Sq, Piece> b, Sq s) { List<Sq> out = new ArrayList<>();
        int up = color == Color.WHITE ? 1 : -1, start = color == Color.WHITE ? 1 : 6;   // black moves down
        Sq one = s.plus(0, up), two = s.plus(0, 2 * up);
        if (!b.containsKey(one)) { out.add(one);  if (s.r() == start && !b.containsKey(two)) out.add(two); }
        for (int df = -1; df <= 1; df += 2) { Piece p = b.get(s.plus(df, up));   // captures go diagonally
            if (p != null && p.color != color) out.add(s.plus(df, up)); }  return out; } }
public class Main { static Map<Sq, Piece> b = new HashMap<>();
    static List<Sq> movesAt(String s) { return b.get(Sq.of(s)).moves(b, Sq.of(s)); }
    public static void main(String[] args) { Color W = Color.WHITE, B = Color.BLACK;      // pawns and knights
        for (int f = 0; f < 8; f++) { b.put(new Sq(f, 1), new Pawn(W)); b.put(new Sq(f, 6), new Pawn(B)); }
        for (int f : List.of(1, 6)) { b.put(new Sq(f, 0), new Knight(W)); b.put(new Sq(f, 7), new Knight(B)); }
        System.out.println("e2 pawn: " + movesAt("e2") + ", g1 knight: " + movesAt("g1"));  int total = 0;
        for (var e : b.entrySet()) if (e.getValue().color == W) total += movesAt(e.getKey().toString()).size();
        System.out.println("white's first-move choices: " + total);
        b.put(Sq.of("d3"), new Pawn(B));  b.put(Sq.of("e3"), new Knight(B));
        System.out.println("black on d3 and e3, e2 pawn now: " + movesAt("e2")); } }

Real output:

e2 pawn: [e3, e4], g1 knight: [h3, f3]
white's first-move choices: 20
black on d3 and e3, e2 pawn now: [d3]
  • 20 first-move choices for white: 8 pawns × 2 (one or two squares) = 16, plus 2 knights × 2 = 4. The rook, bishops, queen and king are boxed in at the start, so this program only places pawns and knights; the mini project below sets up all 32 pieces and prints the same 20. Twenty is the well-known number of possible first moves in chess, a nice check that move generation is right.
  • With a black knight on e3 (in front) and a black pawn on d3 (diagonal), the e2 pawn can't move forward at all; its only move is the capture on d3.

7. Move, Player and a Game with turns

Next problem: anyone can move any piece at any time, and nothing remembers what happened.

  • Move (a record): from, to, and the piece it captured (or null). One line of the scoresheet.
  • Player (a record): name and color.
  • Game: owns the board, the two players, a turn counter and the history (a List<Move>).
  • play(from, to) validates first, then applies: (1) is there a piece? (2) is it yours? (3) is the target in its moves? Only then does it record the move, move the piece and pass the turn. A failed check leaves the board untouched.

To keep this program on one screen in the video, only knights are on the board:

import java.util.*;  enum Color { WHITE, BLACK }
record Sq(int f, int r) { boolean on() { return f >= 0 && f < 8 && r >= 0 && r < 8; }
    static Sq of(String s) { return new Sq(s.charAt(0) - 'a', s.charAt(1) - '1'); }
    public String toString() { return "" + (char) ('a' + f) + (r + 1); } }
class Knight { final Color color;  Knight(Color c) { color = c; }           // one piece type is enough here
    List<Sq> moves(Map<Sq, Knight> b, Sq s) { List<Sq> out = new ArrayList<>();
        for (int[] d : new int[][] {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}}) {
            Sq t = new Sq(s.f() + d[0], s.r() + d[1]);  Knight p = b.get(t);
            if (t.on() && (p == null || p.color != color)) out.add(t); }  return out; } }
record Move(Sq from, Sq to, Knight captured) {                               // one turn, remembered
    public String toString() { return from + (captured == null ? "-" : "x") + to; } }
record Player(String name, Color color) {}
class Game { final Map<Sq, Knight> board = new HashMap<>();  final List<Move> history = new ArrayList<>();
    final Player[] players;  int turn = 0;  Game(Player w, Player b) { players = new Player[] {w, b}; }
    Player toMove() { return players[turn % 2]; }                            // white, black, white, ...
    void need(boolean ok, String why) { if (!ok) throw new IllegalArgumentException(why); }
    void play(String from, String to) { Sq f = Sq.of(from), t = Sq.of(to);  Knight p = board.get(f);
        need(p != null, "No piece on " + from);                              // validate, then apply
        need(p.color == toMove().color(), "Not your turn: " + toMove().name() + " to move");
        need(p.moves(board, f).contains(t), "Illegal move: " + from + " to " + to);
        history.add(new Move(f, t, board.get(t)));  board.remove(f);  board.put(t, p);  turn++; } }
public class Main { public static void main(String[] args) {
    Game g = new Game(new Player("Asha", Color.WHITE), new Player("Ravi", Color.BLACK));
    for (String s : List.of("b1", "g1")) g.board.put(Sq.of(s), new Knight(Color.WHITE));
    for (String s : List.of("b8", "g8")) g.board.put(Sq.of(s), new Knight(Color.BLACK));
    g.play("g1", "f3");  g.play("b8", "c6");  g.play("f3", "e5");  g.play("c6", "e5");   // Ravi captures on e5
    System.out.println("history: " + g.history + ", " + g.toMove().name() + " to move");
    for (String[] m : new String[][] {{"e4", "e5"}, {"e5", "c4"}, {"b1", "b3"}})
        try { g.play(m[0], m[1]); } catch (RuntimeException e) { System.out.println(e.getMessage()); } } }

Real output:

history: [g1-f3, b8-c6, f3-e5, c6xe5], Asha to move
No piece on e4
Not your turn: Asha to move
Illegal move: b1 to b3
  • c6xe5: the x marks a capture, as in chess notation. Ravi's knight took Asha's knight on e5.
  • After four moves it's Asha's turn again. e5 holds Ravi's knight, so moving it is Not your turn.

8. The class diagram

Square (record: file a-h, rank 1-8) · of("e4") · plus(df, dr) · onBoard()
Board: Map<Square, Piece> · at(square) · put(square, piece) · setUp() · print()
Piece (abstract: color, moves(board, from))   ◁── King · Queen · Rook · Bishop · Knight · Pawn
  walk(directions, slides): Rook, Bishop, Queen slide · King, Knight step · Pawn overrides moves()
Move (record: from, to, captured) · Player (record: name, color)
Game: board, players, turn, history · play(from, to): validate, then apply
Errors: "Off the board" · "No piece on" · "Not your turn" · "Illegal move"

◁── means "is extended by" (inheritance), as in a UML class diagram (episode 18).

9. Interview follow-ups

Follow-up A good answer
Is my king in check? Next episode: filter pseudo-legal moves by trying each one and asking "is my king attacked?"
Pawn promotion? A pawn reaching the last rank is replaced by a queen (or rook, bishop, knight): the Move carries the new piece.
Undo? Move keeps the captured piece, so undo can put it back (Command pattern, episode 86).
Load a position from text? A string per rank, like rnbqkbnr/pppppppp/8/...; the Simple Factory create(letter, color) builds pieces.
A new made-up piece (rook + knight)? One new class whose moves() returns walk(LINE, slide) + walk(L, step). Nothing else is edited: Open-Closed.
Why not instanceof everywhere? Every new piece would edit every if; polymorphism keeps each rule inside its own class.
Why Map<Square, Piece> and not Piece[8][8]? Both work. A map with a value-object key is safe from index errors and easy to copy; an array is faster. Say the trade-off.

10. Common mistakes

Mistake What you see (real) Fix
char[][] and one big switch knight in the corner: 8 moves; no rules for Q yet A class per piece with its own moves()
Loop with no edge check ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8 Square.onBoard()
Putting a piece anywhere a piece on "e9" Board.put refuses: Off the board: e9
Building the pawn with walk() the pawn captures forward and can't capture diagonally Pawn overrides moves()
A slider that doesn't stop at the first piece rooks jump over blockers break on any piece
Applying a move before validating it a half-changed board when a check fails validate first, then apply
No turn check one player moves twice Not your turn: Asha to move

Mini project: the whole board with every piece

One program with all six pieces, the full starting position, Move with notation, Player, Game with turns and history, and a printed board after a short opening (e4 e5 Nf3 Nc6 Bc4 Nf6 Nxe5 Nxe5).

import java.util.*;

enum Color { WHITE, BLACK }

record Square(int file, int rank) {                          // file a-h = 0-7, rank 1-8 = 0-7
    static Square of(String s) {
        Square sq = new Square(s.charAt(0) - 'a', s.charAt(1) - '1');
        if (s.length() != 2 || !sq.onBoard()) throw new IllegalArgumentException("Not a square: " + s);
        return sq;
    }
    boolean onBoard() { return file >= 0 && file < 8 && rank >= 0 && rank < 8; }
    Square plus(int df, int dr) { return new Square(file + df, rank + dr); }
    public String toString() { return "" + (char) ('a' + file) + (rank + 1); }
}

abstract class Piece {
    static final int[][] LINE = {{1,0},{-1,0},{0,1},{0,-1}};
    static final int[][] DIAG = {{1,1},{1,-1},{-1,1},{-1,-1}};
    static final int[][] BOTH = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
    static final int[][] L = {{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};

    final Color color;
    Piece(Color color) { this.color = color; }

    abstract char letter();                                  // K Q R B N P
    abstract List<Square> moves(Board board, Square from);   // pseudo-legal moves

    /** Shared rule for Rook, Bishop, Queen (slide) and King, Knight (one step). */
    protected List<Square> walk(Board board, Square from, int[][] dirs, boolean slides) {
        List<Square> out = new ArrayList<>();
        for (int[] d : dirs) {
            for (Square s = from.plus(d[0], d[1]); s.onBoard(); s = s.plus(d[0], d[1])) {
                Piece p = board.at(s);
                if (p == null || p.color != color) out.add(s);  // empty, or capture an enemy
                if (p != null || !slides) break;                 // blocked, or a stepping piece
            }
        }
        return out;
    }
    public String toString() { return "" + (color == Color.WHITE ? letter() : Character.toLowerCase(letter())); }
}

class King extends Piece {
    King(Color c) { super(c); }
    char letter() { return 'K'; }
    List<Square> moves(Board b, Square s) { return walk(b, s, BOTH, false); }
}
class Queen extends Piece {
    Queen(Color c) { super(c); }
    char letter() { return 'Q'; }
    List<Square> moves(Board b, Square s) { return walk(b, s, BOTH, true); }
}
class Rook extends Piece {
    Rook(Color c) { super(c); }
    char letter() { return 'R'; }
    List<Square> moves(Board b, Square s) { return walk(b, s, LINE, true); }
}
class Bishop extends Piece {
    Bishop(Color c) { super(c); }
    char letter() { return 'B'; }
    List<Square> moves(Board b, Square s) { return walk(b, s, DIAG, true); }
}
class Knight extends Piece {
    Knight(Color c) { super(c); }
    char letter() { return 'N'; }
    List<Square> moves(Board b, Square s) { return walk(b, s, L, false); }
}
class Pawn extends Piece {
    Pawn(Color c) { super(c); }
    char letter() { return 'P'; }
    List<Square> moves(Board b, Square s) {                  // its own rule: overrides, no walk()
        List<Square> out = new ArrayList<>();
        int up = color == Color.WHITE ? 1 : -1, start = color == Color.WHITE ? 1 : 6;
        Square one = s.plus(0, up), two = s.plus(0, 2 * up);
        if (one.onBoard() && b.at(one) == null) {
            out.add(one);
            if (s.rank() == start && b.at(two) == null) out.add(two);
        }
        for (int df : new int[] {-1, 1}) {
            Square c = s.plus(df, up);
            if (c.onBoard() && b.at(c) != null && b.at(c).color != color) out.add(c);
        }
        return out;
    }
}

class Board {
    private final Map<Square, Piece> pieces = new HashMap<>();
    Piece at(Square s) { return pieces.get(s); }
    void put(Square s, Piece p) {
        if (!s.onBoard()) throw new IllegalArgumentException("Off the board: " + s);
        pieces.put(s, p);
    }
    Piece remove(Square s) { return pieces.remove(s); }
    Map<Square, Piece> all() { return Collections.unmodifiableMap(pieces); }

    static Piece create(char letter, Color c) {              // a Simple Factory, used only by setUp()
        return switch (letter) {
            case 'K' -> new King(c);   case 'Q' -> new Queen(c);  case 'R' -> new Rook(c);
            case 'B' -> new Bishop(c); case 'N' -> new Knight(c); case 'P' -> new Pawn(c);
            default -> throw new IllegalArgumentException("Unknown piece: " + letter);
        };
    }
    void setUp() {
        String back = "RNBQKBNR";
        for (int f = 0; f < 8; f++) {
            put(new Square(f, 0), create(back.charAt(f), Color.WHITE));
            put(new Square(f, 1), create('P', Color.WHITE));
            put(new Square(f, 6), create('P', Color.BLACK));
            put(new Square(f, 7), create(back.charAt(f), Color.BLACK));
        }
    }
    void print() {
        for (int r = 7; r >= 0; r--) {
            StringBuilder line = new StringBuilder().append(r + 1).append("  ");
            for (int f = 0; f < 8; f++) {
                Piece p = at(new Square(f, r));
                line.append(p == null ? "." : p.toString()).append(' ');
            }
            System.out.println(line);
        }
        System.out.println("   a b c d e f g h");
    }
}

record Move(Piece piece, Square from, Square to, Piece captured) {
    public String toString() {
        String who = piece instanceof Pawn ? "" : String.valueOf(piece.letter());
        return who + from + (captured == null ? "-" : "x") + to;
    }
}
record Player(String name, Color color) {}

class Game {
    final Board board = new Board();
    private final Player[] players;
    private int turn = 0;
    private final List<Move> history = new ArrayList<>();

    Game(Player white, Player black) { players = new Player[] {white, black}; board.setUp(); }
    Player toMove() { return players[turn % 2]; }
    List<Move> history() { return List.copyOf(history); }

    int countMoves(Color c) {
        int n = 0;
        for (var e : board.all().entrySet())
            if (e.getValue().color == c) n += e.getValue().moves(board, e.getKey()).size();
        return n;
    }
    Move play(String from, String to) {                      // validate first, then apply
        Square f = Square.of(from), t = Square.of(to);
        Piece p = board.at(f);
        if (p == null) throw new IllegalArgumentException("No piece on " + from);
        if (p.color != toMove().color()) throw new IllegalStateException("Not your turn: " + toMove().name() + " to move");
        if (!p.moves(board, f).contains(t)) throw new IllegalArgumentException("Illegal move: " + p + " " + from + " to " + to);
        Move m = new Move(p, f, t, board.at(t));
        board.remove(f);
        board.put(t, p);
        history.add(m);
        turn++;
        return m;
    }
}

public class Main {
    public static void main(String[] args) {
        Game g = new Game(new Player("Asha", Color.WHITE), new Player("Ravi", Color.BLACK));
        System.out.println("white's first-move choices: " + g.countMoves(Color.WHITE)
            + ", black's: " + g.countMoves(Color.BLACK));
        String[][] moves = {{"e2", "e4"}, {"e7", "e5"}, {"g1", "f3"}, {"b8", "c6"}, {"f1", "c4"}, {"g8", "f6"}, {"f3", "e5"}, {"c6", "e5"}};
        for (String[] m : moves) g.play(m[0], m[1]);
        g.board.print();
        System.out.println("history: " + g.history());
        System.out.println(g.toMove().name() + " to move, with " + g.countMoves(Color.WHITE) + " pseudo-legal moves");
        for (String[] bad : new String[][] {{"e5", "e6"}, {"a7", "a6"}, {"c4", "c8"}, {"d1", "d5"}}) {
            try { g.play(bad[0], bad[1]); }
            catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); }
        }
    }
}

Real output:

white's first-move choices: 20, black's: 20
8  r . b q k b . r 
7  p p p p . p p p 
6  . . . . . n . . 
5  . . . . n . . . 
4  . . B . P . . . 
3  . . . . . . . . 
2  P P P P . P P P 
1  R N B Q K . . R 
   a b c d e f g h
history: [e2-e4, e7-e5, Ng1-f3, Nb8-c6, Bf1-c4, Ng8-f6, Nf3xe5, Nc6xe5]
Asha to move, with 32 pseudo-legal moves
IllegalStateException: Not your turn: Asha to move
IllegalStateException: Not your turn: Asha to move
IllegalArgumentException: Illegal move: B c4 to c8
IllegalArgumentException: Illegal move: Q d1 to d5
  • With all 32 pieces, both sides have 20 first moves: the boxed-in pieces add zero.
  • board.create(letter, color) is a Simple Factory (episode 23): the only switch in the program, used once at setup to turn a letter into an object. Move rules never use it.
  • Bf1-c4: pieces other than pawns are written with their letter, as on a scoresheet.

Practice

1. How many moves does a knight have on b1 on an empty board? On d4?

Answer

b1: 3 (a3, c3, d2). d4: 8 (all L-jumps stay on the board).

2. Write class Amazon extends Piece (moves like a queen and a knight).

Answer
class Amazon extends Piece {
    Amazon(Color c) { super(c); }
    char letter() { return 'A'; }
    List<Square> moves(Board b, Square s) {
        List<Square> out = walk(b, s, BOTH, true);
        out.addAll(walk(b, s, L, false));
        return out;
    }
}

Nothing else changes: Game.play just calls moves().

3. Why is Square a record, and why does that matter for Map<Square, Piece>?

Answer

A record gets equals and hashCode from its fields, so new Square(4, 3) and Square.of("e4") are equal and find the same map entry. A plain class without equals/hashCode would compare by identity, and board.at(Square.of("e4")) would never find the piece.

4. In the mini project, how many moves does black's e7 pawn have at the start? And a pawn on e5 with a black pawn on e6?

Answer

At the start: 2 (e6, e5). Blocked by a piece directly in front: 0 forward moves (it can still capture diagonally if an enemy is there).

5. Add a check to Game.play that refuses moving onto your own piece. Is it needed?

Answer

Not needed: walk() never adds a square with your own piece, and the pawn's moves only add empty squares or enemies, so moves().contains(to) already refuses it with Illegal move.

6. Print the board after every move in the mini project. Where would you put the call?

Answer

In main, after each g.play(...), call g.board.print(). Keep printing out of Game.play, so the game logic doesn't depend on the console (Single Responsibility, episode 12).

Quick quiz

An empty board and a white rook on a1. How many squares can it move to? (a) 7 (b) 8 (c) 14 (d) 16

Answer

(c) 14. 7 up the a-file (a2-a8) + 7 along rank 1 (b1-h1). A rook has 14 moves from any square of an empty board.

Interview questions

  1. What classes would you start with for chess? Square, Board, Piece (abstract) and its six subclasses, Move, Player, Game.
  2. How do you avoid a giant switch for move rules? Polymorphism: each piece class implements moves(); the caller just calls it.
  3. Which pieces can share code? Rook, Bishop and Queen slide; King and Knight step. One walk(directions, slides) helper covers all five.
  4. Why is the pawn different? Direction depends on colour, a two-square first move, and captures (diagonal) differ from moves (straight). It overrides moves().
  5. What is a pseudo-legal move? A move allowed by the piece's own rule, before checking whether your king is left in check.
  6. How do you represent the board? Map<Square, Piece> (or Piece[8][8]); squares as a value object with onBoard().
  7. How many first moves does white have, and how do you test move generation? 20; counting moves from known positions is the standard test for move generators.
  8. Where do turns and history live? In Game: a turn counter, two players and a List<Move>.
  9. Why validate before applying? So a refused move never leaves the board half-changed.
  10. How would you add a new piece? One new subclass; nothing else edited (Open-Closed).

Glossary

Term Meaning, with an example
Chess requirements What the program must do: set up the board, generate moves, turns, reject wrong moves, history
Board The 8×8 playing area; here a Map<Square, Piece>
Square One of the 64 places on the board, named by file and rank: e4
File A column of the board, a to h
Rank A row of the board, 1 to 8
Algebraic notation Writing moves as squares and piece letters: e4, Nf3, Nxe5
Capture Moving onto an enemy piece's square and removing it: c6xe5
Piece Anything that stands on a square: King, Queen, Rook, Bishop, Knight, Pawn
Piece hierarchy Piece as the parent class, with six subclasses
King Moves one square in any direction
Queen Slides any distance straight or diagonally
Rook Slides any distance straight
Bishop Slides any distance diagonally
Knight Jumps in an L (2 + 1); can jump over pieces
Pawn Moves forward 1 (2 from its start), captures diagonally forward
Sliding piece Moves any distance until blocked: rook, bishop, queen
Stepping piece Moves one step: king, knight
Move generation Listing every square a piece (or a side) can move to
Pseudo-legal move Allowed by the piece's rule, ignoring check
Legal move A pseudo-legal move that doesn't leave your own king in check (episode 86)
Polymorphism One call, each object runs its own version: piece.moves(...)
Polymorphic move rules Each piece class carries its own moves()
Abstract class A class you can't create directly, only extend: abstract class Piece
Abstract method A method with no body that subclasses must write
Method overriding A subclass replaces a parent's method: Pawn.moves()
extends / super Make a subclass / call the parent's constructor or method
record A short class that only holds values, with equals/hashCode/toString built in
Value object An object defined by its values; equal values = equal objects: Square
enum A type with a fixed set of values: enum Color { WHITE, BLACK }
Optional A box that holds a value or is empty: board.at(e4)
HashMap A key → value table with fast lookup
Move A record of one turn: from, to, captured piece
Player A person on one side: name + colour
Turn Whose move it is: white, then black, then white
History The list of moves played so far: the scoresheet
Board setup Placing the 32 pieces in the starting position
Starting position RNBQKBNR on ranks 1 and 8, pawns on ranks 2 and 7
Simple Factory One method that creates the right object from a key: create('N', WHITE)
Open-Closed Principle Add behaviour by adding code (a new class), not by editing old code
ArrayIndexOutOfBoundsException Java's error for an array index outside 0..length−1
IllegalArgumentException Java's exception for a bad argument: Off the board: e9
IllegalStateException Java's exception for "not allowed right now": Not your turn

Summary

  • Chess requirements: board setup, move generation, turns, clear errors, history; check and the rest come in episode 86.
  • A grid of letters with one switch gave a corner knight 8 moves, had no rule for the queen, and crashed with Index 8 out of bounds for length 8.
  • Square (a record that knows onBoard()) and Board (a map that guards its edges) replaced raw indexes.
  • The Piece hierarchy gives King, Queen, Rook, Bishop, Knight and Pawn their own polymorphic move rules; sliders and steppers share one walk(), and the Pawn overrides moves().
  • Move generation per piece is checked with real counts: knight 2/8, rook 14, bishop 13, queen 27, and 20 first moves for white.
  • Move, Player and a Game with turns and history validate every move before applying it.
  • Next episode: chess part 2: move validation, check, checkmate, stalemate, castling, en passant, promotion and undo.