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

Implementation

Python line by line, with Java, C++ and TypeScript

The point: ask all questions first, change second, and let the object that knows the answer ask the question.

First half

Parts

Marks, squares and lines

Two small enums, one record, one way to say no.

from dataclasses import dataclassfrom enum import Enumclass Mark(Enum):    X = "X"    O = "O"    @property    def other(self) -> "Mark":        return Mark.O if self is Mark.X else Mark.Xclass Status(Enum):    PLAYING = "playing"    X_WON = "X won"    O_WON = "O won"    DRAW = "draw"@dataclass(frozen=True)class Move:    row: int    col: int    mark: Markclass IllegalMove(Exception):    """Outside, taken, not your turn, or the game is over."""

Lines 5 to 11

Two marks, closed set. other is here because it is knowledge about marks. Without it, "O if X else X" is copied into four places.

1 of 4

Why it is built this way

  • I do not write a Player class yet. Two names with a mark would be data that nobody asks for.

Second half

The referee

The referee

Four questions, one change, three outcomes.

class Game:    def __init__(self, size: int = 3, first: Mark = Mark.X) -> None:        self._board = Board(size)        self._lines = LineCounts(size)        self._moves: list[Move] = []        self._turn = first        self._status = Status.PLAYING    @property    def turn(self) -> Mark:        return self._turn    @property    def status(self) -> Status:        return self._status    def play(self, mark: Mark, row: int, col: int) -> Status:        if self._status is not Status.PLAYING:            raise IllegalMove("the game is over")        if mark is not self._turn:            raise IllegalMove("not your turn")        if not self._board.holds(row, col):            raise IllegalMove("outside")        move = Move(row, col, mark)        self._board.put(move)                      # raises if the square is taken        self._moves.append(move)        if self._lines.add(move):            self._status = Status.X_WON if mark is Mark.X else Status.O_WON        elif self._board.full:            self._status = Status.DRAW        else:            self._turn = mark.other        return self._status

Lines 2 to 7

Everything is made here and nothing is global. Two games in one program are two objects.

1 of 9

Why it is built this way

  • play returns the status, so a caller needs no second question. In a program with several threads a second question might be answered about another move.

Languages

What differs, and why

PointPythonJavaC++TypeScript
Empty squareNonenull, only inside Boardoptional<Mark>null
GridList of listsMark[n][n]One vector, row after rowArray of arrays
LinesKeys in a dictionaryNumbers: rows 0 to n-1, columns n to 2n-1, then two diagonalsThe same numbersStrings in a Map
Read onlyPropertiesMethods without settersconst methodsGetters over private fields
Bad index-1 is the lastExceptionUndefined behaviourundefined, and 0.5 is possible: isInteger
The numbered lines are the faster form: one array access for each line and no text. The dictionary reads better in an interview.