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

UML design

Two diagrams, and five minutes at the board

The point: all arrows go out of Game. Nobody points back, so board and counts can be tested alone.

The design to reach: the board stores, the counts see wins, the game enforces

Game- moves: List<Move>- turn: Mark- status: Status+ play(mark, row, col): Status+ undo(): Move+ legal(): List<Square>+ rows(): List<String>«enum»StatusPLAYING, DRAWX_WON, O_WON

1/5The referee

Game knows whose turn it is and whether the game goes on. It is the only way to change anything, so a rule checked here is a rule.

owns (dies together)uses

Draw

In this order

  1. 1

    Game with play

    Write the full signature. play(mark, row, col): Status already answers three questions of the interviewer.

  2. 2

    Board below it

    put and clear, a pair. Say that the pair is for undo.

  3. 3

    Move beside it

    The word "in order" on the arrow is the history.

  4. 4

    LineCounts

    add and remove, the same pair again.

  5. 5

    Two enums

    Four statuses. Point at the order of checks.

Compare

The version with everything in it

The design to avoid: the game is inside the screen, and the winner is inside the board

TicTacToe- board: char[3][3]- player1, player2: Player- moveCount: int+ run()- readInput(): int[2]- printBoard()- checkWinner(): char- switchPlayer()

1/4One class from keyboard to verdict

Reading, printing, turns and winning in one class. There is no way to ask who has won without somebody typing.

owns (dies together)extends (is a)

WishBad design changesGood design changes
Size 4Three loops and the printingOne argument
UndoBoard, counter, player, loopNothing: it is there
A computermakeMove with the real boardA new caller
A web pagerun, and a copy of the rulesA new caller
No diagonalscheckWinner_lines