AlgoViz

Design tic-tac-toe

easy 70 min

Model a game everybody knows: marks on a grid, turns, a full line wins.

Watch lesson4:32

Entities

Four classes, and why a cell is not one of them

The point: a class needs state of its own and a decision of its own. Most nouns of this game have neither.

Keep

What earns its place

TypeStateDecision
GameTurn, status, movesMay this move be made now?
BoardSquares, number of empty onesIs this square free?
LineCountsCountersDid this move complete a line?
MoveRow, column, markNone: a record
Mark, StatusValuesother

Reject

What does not

NounWhy notSay
CellIts row and column are its place in the list. Its mark is the value there"A value, not an object."
PlayerA name and a mark. Nobody asks it anything yet"It becomes an interface when it can choose."
Row, Column, DiagonalA number each, in one map"Keys, not classes."
GameManager, ControllerThere is one game"When there are many, it is a hall with tables."
WinnerStrategy with five subclassesOne rule is known"LineCounts can be handed in when there is a second."
Screen, PrinterOutput"They use rows()."

Where does the win check live?

BreaksIn the screen or in main
How
After each move, main looks at the board.
Limit
Two screens have two win checks. A test of the rules needs a screen.
Choose when
Never.
WorksIn Board, as winner()
How
The board reads its own lines.
Limit
The board now has two reasons to change: storage and rules. It cannot be used for a game with other rules.
Choose when
Small boards and no undo. Many good answers do this.
StrongIn an object that sees each move
How
LineCounts.add(move) answers for this move only.
Limit
It must see all moves and all undos. The game guarantees that, because it is the only caller.
Choose when
Any size, undo, or more than one rule.

Design it twice

The smallest design that could work

One class Game with a list of nine letters and a method play, about forty lines. For 3 by 3 without undo it is the better design, and it is fair to say so. Each split on this page is paid for by a sentence from the requirements: any size pays for LineCounts, undo pays for Move, and both together pay for Board.