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

Computer player

Looking at all futures, and why that is possible here

The point: the value of a position is the best of what the other leaves you. With 5,478 positions a program can know them all.

Count

How large is the game?

Python
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]def won(b: str) -> bool:    return any(b[x] != "." and b[x] == b[y] == b[z] for x, y, z in LINES)def same(b: str) -> str:    """The smallest of the eight turned and mirrored copies."""    copies = []    for _ in range(4):        b = "".join(b[i] for i in (6, 3, 0, 7, 4, 1, 8, 5, 2))         # a quarter turn        copies += [b, "".join(b[i] for i in (2, 1, 0, 5, 4, 3, 8, 7, 6))]    return min(copies)games, seen, ends = 0, set(), {"X": 0, "O": 0, "-": 0}def walk(b: str, turn: str) -> None:    global games    seen.add(b)    if won(b) or "." not in b:        games += 1        ends[("O" if turn == "X" else "X") if won(b) else "-"] += 1        return    for i in range(9):        if b[i] == ".":            walk(b[:i] + turn + b[i + 1:], "O" if turn == "X" else "X")walk("." * 9, "X")print(games, "games", ends)print(len(seen), "positions,", len({same(b) for b in seen}), "after turning and mirroring")
Prints 255168 games: 131184 won by X, 77904 by O, 46080 drawn. 5478 positions can be reached, and 765 if turned and mirrored ones count as one.
Edit and run it in your browser

Nine factorial, 362,880, is the number of ways to fill the board, and it is often quoted as the number of games. It is too large: games end early. Being able to tell the two apart is worth a sentence.

Think

Best play

Python
from functools import lru_cacheLINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]calls = 0def winner(b: str) -> str | None:    return next((b[x] for x, y, z in LINES if b[x] != "." and b[x] == b[y] == b[z]), None)@lru_cache(maxsize=None)def value(b: str, turn: str) -> int:    """Best result for whoever moves next: positive is a win, sooner is larger."""    global calls    calls += 1    if winner(b):        return -(b.count(".") + 1)               # the last mover won: bad for `turn`    if "." not in b:        return 0    other = "O" if turn == "X" else "X"    return max(-value(b[:i] + turn + b[i + 1:], other) for i in range(9) if b[i] == ".")def best(b: str, turn: str) -> int:    other = "O" if turn == "X" else "X"    free = [i for i in range(9) if b[i] == "."]    return max(free, key=lambda i: -value(b[:i] + turn + b[i + 1:], other))print("start:", value("." * 9, "X"), "positions looked at:", calls)print(best("XX.OO....", "X"), best("XX.O.....", "O"))     # take the win, block the threat
Minimax in its short form: one function, and a minus sign because what is good for one is bad for the other. Prints start 0, 5478 positions, then 2 and 2: take the win, block the threat.
Edit and run it in your browser
LineWhyWithout it
lru_cacheMany orders of moves lead to one positionThe walk visits 549,946 nodes instead of 5,478
-(empty + 1)A faster win is worth moreAll wins are equal, and the program plays with its food
-value(...)The value is always seen from whoever moves nextTwo functions, max and min, that must agree
Text as positionCan be a key in a cacheA board object would need a hash and a copy

Place

Where does it plug in?

Players around the game

two seatsMatch- seats: Map<Mark, Player>+ run(): StatusGame+ play(mark, row, col)«interface»Player+ choose(view, mark): Square

1/2A wish, not an act

choose gets a copy of the board and answers with a square. The match passes the wish to the game, and the game may refuse it.

usesimplements

Python
import randomfrom typing import ProtocolLINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]class Player(Protocol):    def choose(self, board: str, mark: str) -> int: ...      # a copy goes in, a wish comes outclass RandomPlayer:    def __init__(self, seed: int) -> None:        self._rng = random.Random(seed)    def choose(self, board: str, mark: str) -> int:        return self._rng.choice([i for i in range(9) if board[i] == "."])class RulePlayer:    """Win if you can, block if you must, else centre, corner, edge."""    def choose(self, board: str, mark: str) -> int:        for who in (mark, "O" if mark == "X" else "X"):            for line in LINES:                cells = [board[i] for i in line]                if cells.count(who) == 2 and "." in cells:                    return line[cells.index(".")]        return next(i for i in (4, 0, 2, 6, 8, 1, 3, 5, 7) if board[i] == ".")class Cheat:    def choose(self, board: str, mark: str) -> int:        return 4                                             # whatever is theredef match(x: Player, o: Player) -> str:    board, mark = "." * 9, "X"    while "." in board:        try:            i = (x if mark == "X" else o).choose(board, mark)        except Exception:            i = -1        if not 0 <= i < 9 or board[i] != ".":            return f"{mark} loses by a bad move"             # the referee decides, not the player        board = board[:i] + mark + board[i + 1:]        if any(all(board[k] == mark for k in line) for line in LINES):            return f"{mark} won"        mark = "O" if mark == "X" else "X"    return "draw"results = [match(RulePlayer(), RandomPlayer(seed)) for seed in range(1000)]print({r: results.count(r) for r in sorted(set(results))})print(match(RulePlayer(), RulePlayer()), "|", match(RulePlayer(), Cheat()))
The referee does not trust the players. Out of 1,000 games the rule player wins 962 against random play and draws 38. Against itself it draws.
Edit and run it in your browser

How strong should the computer be?

WorksRules: win, block, centre, corner, edge
How
Four lines of priorities.
Limit
It misses some double threats. Easy to explain.
Choose when
A beginner's opponent.
StrongAll futures with a cache
How
Never loses. Half of a second once, then a table.
Limit
Does not carry over: four in a row has 4.5 trillion positions. Then depth limits and estimates are needed.
Choose when
This game.
BreaksTrain a network
How
Thousands of games.
Limit
Slower, weaker and unexplainable where 5,478 exact values fit into a small file.
Choose when
Never for this game. Say why.