CSE Roadmap

Common tier · about 5 hours · 6 parts

Part 3 of 6 · 2 min read

Classes

Pieces know movement, the game knows the rules.

The key split is between what a piece can do and what the game allows.

  • A piece knows its own geometry: a rook moves along a row or a column, a knight jumps in an L. It also needs to know whether something is in the way.
  • The game knows whose turn it is, that a player may not capture their own piece, and that the king must be safe. Those rules do not depend on the kind of piece.
Class Kind Job in one sentence
Color enum White or black, and its opposite
Pos value (record) A square, checked to be on the board, readable as "e2"
Piece abstract class Has a colour, and says whether it can reach a square
Rook, Bishop, Queen, Knight, King, Pawn subclasses The movement rule of each piece
Board entity Holds the 64 squares and answers "what is here" and "is the path clear"
Game entity Holds the turn and status, checks each move, and finds check and mate
IllegalMoveException checked exception A refused move, with the reason

This is polymorphism (Level 1, module 5). Game calls piece.canReach(board, from, to) and never asks which piece it is. A new piece, such as a variant piece, is a new subclass. There is no type switch on the piece in the game's rules.

Why subclasses here and an enum in the parking lot? The parking lot's vehicles differed only in which spots they fit and what they paid, which a lookup could express. Chess pieces differ in how they move, which is code, and code is what polymorphism is for.

Two other choices:

  • Board is plain data plus two helper questions. It has no idea about turns or check.
  • A move is tested by trying it. To find out whether a move leaves the king in check, play it on the board, test for check, and put everything back. That is simpler than reasoning about pins and discovered checks.
Game   has-one   Board
Game   has-one   Color (turn)
Board  has-many  Piece (64 squares)
Piece  <- Rook, Bishop, Queen, Knight, King, Pawn

Check yourself: 1. Which class knows that a player may not capture their own piece? 2. Why are pieces subclasses, when vehicles were an enum? 3. How does the game test whether a move leaves the king in check?