Part 3 of 6 · 1 min read
Classes
Board holds cells, game holds rules.
The central choice is how to split Board and Game. The board knows cells and lines. The game knows whose turn it is and whether the game is over. If one class does both, the board cannot be reused (for example in a bot's lookahead), and the rules get mixed with storage.
| Class | Kind | Job in one sentence |
|---|---|---|
Mark |
enum | The two marks, X and O |
Status |
enum | In progress, won or draw |
Board |
entity | Holds the cells, places a mark, and reports whether the move completed a line |
Game |
entity | Holds the turn and the status, and checks each move against the rules |
InvalidMoveException |
checked exception | A refused move, with the reason |
MoveSource |
interface | Supplies the next move for a player (human or computer) |
Where rules live:
- "Is this cell on the board, and empty" needs only the board, so
Boardanswers it. - "Is the game over, and whose turn" needs the history of moves, so
Gameowns it. - "Who picks the move" will change (a person, a bot), so it sits behind
MoveSource. This is the strategy pattern (Level 4, module 1).
Status moves from in-progress to won or draw and never back. That is a small state machine, and an enum plus a check at the top of play is enough. A full state pattern (Level 4, module 3) would be too much for three states.
Game has-one Board
Game uses MoveSource (for each player, optional)
Board has-many cells (Mark or empty)
Check yourself:
1. Why are Board and Game separate classes?
2. Which rule needs the history of moves?
3. Why is a full state pattern not used for the status?