"""Pure-python tic-tac-toe: board, cell names, winner, minimax. No sim, no strands imports. Board = list of 9 chars in {"X", "O", " "}, row-major, index 0 = top-left as seen in the OVERHEAD camera (image top = far side of the table from the robot = +x, image left = +y). """ from __future__ import annotations import functools import re ROWS = ("top", "middle", "bottom") COLS = ("left", "center", "right") CELL_NAMES = [("center" if (r, c) == ("middle", "center") else f"{r}-{c}") for r in ROWS for c in COLS] 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)] # geometry (metres, env frame = robot base). Board centre and pitch shared with the server. BOARD_CENTER = (0.50, 0.00) PITCH = 0.10 def cell_xy(i: int) -> tuple[float, float]: r, c = divmod(i, 3) return (BOARD_CENTER[0] + (1 - r) * PITCH, BOARD_CENTER[1] + (1 - c) * PITCH) def xy_to_cell(x: float, y: float, tol: float = 0.045) -> int | None: """Nearest cell index if within tol (m) of its centre along both axes, else None.""" best = min(range(9), key=lambda i: (cell_xy(i)[0] - x) ** 2 + (cell_xy(i)[1] - y) ** 2) cx, cy = cell_xy(best) return best if abs(cx - x) <= tol and abs(cy - y) <= tol else None _ALIASES = { "centre": "center", "mid": "middle", "upper": "top", "lower": "bottom", "central": "center", } def parse_cell(s: str | int) -> int: """'top-left' | 'top left' | 'center' | 'middle' | '1'..'9' | 1..9 | 'a1'..'c3' (col letter, row digit) → 0..8.""" if isinstance(s, int): if 1 <= s <= 9: return s - 1 raise ValueError(f"cell number must be 1..9, got {s}") t = str(s).strip().lower() if re.fullmatch(r"[1-9]", t): return int(t) - 1 m = re.fullmatch(r"([abc])([123])", t) if m: return (int(m.group(2)) - 1) * 3 + "abc".index(m.group(1)) for k, v in _ALIASES.items(): t = re.sub(rf"\b{k}\b", v, t) t = re.sub(r"[\s_]+", "-", t).strip("-") if t in ("center", "middle", "middle-middle", "center-center"): return 4 words = t.split("-") r = next((ROWS.index(w) for w in words if w in ROWS), None) c = next((COLS.index(w) for w in words if w in ("left", "right")), None) mid = any(w in ("middle", "center") for w in words) if r is None and c is not None and mid: r = 1 if c is None and r is not None and (r != 1 and mid or words.count("middle") + words.count("center") > 1): c = 1 if r is None or c is None: raise ValueError(f"cannot parse cell {s!r}; use one of {CELL_NAMES} or 1-9") return r * 3 + c def winner(b: list[str]) -> str | None: for a, c, d in LINES: if b[a] != " " and b[a] == b[c] == b[d]: return b[a] return None def is_full(b: list[str]) -> bool: return all(v != " " for v in b) def status(b: list[str]) -> str: w = winner(b) return f"{w} wins" if w else ("draw" if is_full(b) else "in progress") def to_move(b: list[str]) -> str: nx, no = b.count("X"), b.count("O") return "X" if nx == no else "O" def ascii_board(b: list[str]) -> str: rows = [" | ".join(v if v != " " else str(r * 3 + k + 1) for k, v in enumerate(b[r * 3:r * 3 + 3])) for r in range(3)] return "\n---------\n".join(" " + r for r in rows) @functools.lru_cache(maxsize=None) def _minimax(bs: str, player: str) -> tuple[int, int]: """(score from X's view: +1 X wins, -1 O wins, 0 draw; best move) for `player` to move.""" b = list(bs) w = winner(b) if w: return (1 if w == "X" else -1), -1 if is_full(b): return 0, -1 best = None for i in range(9): if b[i] != " ": continue b[i] = player s, _ = _minimax("".join(b), "O" if player == "X" else "X") b[i] = " " # prefer quicker wins/slower losses: tie-break by centre, corners, edges order if best is None or (s > best[0] if player == "X" else s < best[0]): best = (s, i) return best # type: ignore[return-value] _PREF = [4, 0, 2, 6, 8, 1, 3, 5, 7] def minimax_move(b: list[str], player: str | None = None) -> int: player = player or to_move(b) target, _ = _minimax("".join(b), player) for i in range(9): # take an immediate win first if b[i] == " " and winner(b[:i] + [player] + b[i + 1:]) == player: return i # among optimal moves pick by preference order (deterministic, natural-looking) for i in _PREF: if b[i] != " ": continue nb = list(b) nb[i] = player w = winner(nb) s = (1 if w == "X" else -1) if w else (0 if is_full(nb) else _minimax("".join(nb), "O" if player == "X" else "X")[0]) if s == target: return i raise ValueError("no legal move")