Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Watch lesson4:32
Many games
A server with a lock for each table
The point: games do not touch each other, so they do not share a lock. What they share is the list of games.
Split
Two kinds of lock
import secretsfrom dataclasses import dataclass, fieldfrom threading import Lockclass Refused(Exception): pass@dataclassclass Table: """One game on the server: the board, who sits where, and a lock of its own.""" board: list[str] = field(default_factory=lambda: ["."] * 9) seats: dict[str, str] = field(default_factory=dict) # token -> mark turn: str = "X" last: float = 0.0 lock: Lock = field(default_factory=Lock)class Hall: def __init__(self) -> None: self._tables: dict[str, Table] = {} self._lock = Lock() # guards the dictionary only def open(self, now: float) -> str: with self._lock: name = secrets.token_hex(4) self._tables[name] = Table(last=now) return name def _find(self, name: str) -> Table: with self._lock: if name not in self._tables: raise Refused("no such game") return self._tables[name] def sit(self, name: str) -> str: table = self._find(name) with table.lock: if len(table.seats) == 2: raise Refused("two players are here already") token = secrets.token_urlsafe(16) table.seats[token] = "X" if not table.seats else "O" return token def play(self, name: str, token: str, square: int, now: float) -> str: table = self._find(name) with table.lock: # games do not wait for each other mark = table.seats.get(token) if mark is None: raise Refused("you are watching") if mark != table.turn or not 0 <= square < 9 or table.board[square] != ".": raise Refused("not now, or not there") table.board[square], table.last = mark, now table.turn = "O" if mark == "X" else "X" return "".join(table.board) def sweep(self, now: float, idle: float = 3600) -> int: with self._lock: old = [n for n, t in self._tables.items() if now - t.last > idle] for name in old: del self._tables[name] return len(old)hall = Hall()game = hall.open(now=0)asha, noor = hall.sit(game), hall.sit(game)print(hall.play(game, asha, 4, now=1), hall.play(game, noor, 0, now=2))for token, square in [(noor, 1), ("a guess", 1), (asha, 4)]: try: hall.play(game, token, square, now=3) except Refused as no: print("refused:", no)print(hall.sweep(now=10_000))play calls Game.play.| Question | Answer |
|---|---|
| Why a token and not the mark? | Anybody can say X. The token is secret, random and given once |
| Why 128 bits? | It is a password that nobody types. Length is free |
| Can two locks block each other for ever? | No: nobody takes the hall's lock while holding a table's lock |
| What if the table was swept between find and lock? | The move goes into a game that nobody can reach any more. Harmless after an hour of silence; mark it closed under its lock if it matters |
| Who may watch? | Anybody with the name. No token, so no move |
Numbers
Memory and speed
- 1
Size of a table
Nine squares, two tokens, a lock and some objects: call it 2 KB in Python.
- 2
A hundred thousand games
200 MB. One machine.
- 3
Moves
One move in five seconds in each game: 20,000 a second. A move needs some microseconds, so the rules cost about a tenth of one core. The network is the work, not the game.
- 4
So where is the limit?
Open connections: 200,000. That is what decides how many machines there are.
Several machines
A game lives in one place
How do two servers not both own a game?
BreaksBoth keep it in memory and copy
- How
- Last writer wins.
- Limit
- Two players on two servers make two fourth moves.
- Choose when
- Never.
WorksRoute by name
- How
- A hash of the name chooses the server.
- Limit
- When a server is added, some games move. They must be replayed there.
- Choose when
- Most systems.
StrongRoute by name, and the store refuses a move number twice
- How
- Append move 5 only if it is the fifth. A unique key on game and number.
- Limit
- One write for each move before the answer.
- Choose when
- When a wrong result costs something. The check in the store is right even while routing is wrong.
Move numbers, lost answers, reconnecting and clocks belong to a match between two devices. They have their home on four in a row, a match over the network.