# SPDX-License-Identifier: MIT """Milestone 7: does a game follow the CX53 trak-ball model? (the board only, no detector) python scripts/trak_titles.py CART --press 300:start:10 --play 600 --out DIR [--slow 3] [--fast 8] [--phase 60] [--rest 30] [--port 1] [--stick] The trak-ball is plugged into port 1 (or PORT) from power-on, so the program's calibration (CONSOL bit 2 low: the [FSM] section 7 "clear" line) sees it. ``--press`` takes the same FRAME:KEY:FRAMES[:PORT] items as ``scripted_run.py`` to get into play; from ``--play`` the ball is rolled in eight phases: right slow, left slow, right fast, left fast, up slow, down slow, up fast, down fast (``--phase`` frames each, ``--rest`` frames still between), then the lower button is pressed five times, then the upper button five times. ``--tap`` also taps the lower button as each phase starts (the sports titles need it to put a ball in play). The judge is the game's own RAM: every address's signed change over each phase is recorded, and an address is reported as an X (Y) candidate when it moves one way in both right (up) phases, the other way in both left (down) phases, and by less in every phase of the other axis. Pictures are saved at the end of each phase (DIR/STEM-NN-PHASE.png) and three frames after each button press, to be read by eye. ``--stick`` runs the same schedule with a stick deflected in proportion instead (a control for the same game). """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a5200_python.controllers import TrakBall # noqa: E402 from a5200_python.media import write_png # noqa: E402 from a5200_python.system import Console # noqa: E402 PHASES = [ ("right-slow", 1, 0, "slow"), ("left-slow", -1, 0, "slow"), ("right-fast", 1, 0, "fast"), ("left-fast", -1, 0, "fast"), ("up-slow", 0, -1, "slow"), ("down-slow", 0, 1, "slow"), ("up-fast", 0, -1, "fast"), ("down-fast", 0, 1, "fast"), ] # fmt: skip # Y runs up first: most players start at the bottom. def candidates( deltas: dict[str, list[int]], axis: int, strict: bool = True ) -> list[tuple[int, list[int]]]: """Addresses that move with the given axis (0 = X phases 0-3, 1 = Y phases 4-7).""" own = [name for name, dx, dy, _ in PHASES if (dx, dy)[axis]] other = [name for name, dx, dy, _ in PHASES if not (dx, dy)[axis]] found = [] for address in range(len(deltas[own[0]])): d = [deltas[name][address] for name in own] # +slow, -slow, +fast, -fast if 0 in d: continue if not (d[0] > 0) == (d[2] > 0) != (d[1] > 0) == (d[3] > 0): continue least = min(abs(v) for v in d) if not strict or all(abs(deltas[name][address]) < least for name in other): found.append((address, d)) found.sort(key=lambda item: -min(abs(v) for v in item[1])) return found def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("cart") parser.add_argument("--press", action="append", default=[]) parser.add_argument("--play", type=int, required=True, help="frame the motion script starts") parser.add_argument("--slow", type=float, default=3.0, help="encoder counts per frame") parser.add_argument("--fast", type=float, default=8.0, help="encoder counts per frame") parser.add_argument("--phase", type=int, default=60) parser.add_argument("--rest", type=int, default=30) parser.add_argument("--port", type=int, default=1) parser.add_argument("--stick", action="store_true", help="control: a stick instead") parser.add_argument( "--tap", action="store_true", help="tap the lower button for 5 frames as each phase starts" ) parser.add_argument("--watch", action="append", default=[], help="RAM address (hex) to print") parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() presses = [] for item in args.press: frame, key, length, *port = item.split(":") presses.append((int(frame), key, int(length), int(port[0]) if port else args.port)) console = Console(args.cart) board = console.board pad = console.controllers.pads[args.port - 1] pad.plugged = True pad.trakball = not args.stick speeds = {"slow": args.slow, "fast": args.fast} # The schedule: (first frame, last frame, phase) and the button presses. schedule = [] frame = args.play for phase in PHASES: schedule.append((frame, frame + args.phase, phase)) frame += args.phase + args.rest buttons = [] for kind in ("trigger", "top"): for _ in range(5): buttons.append((frame, kind)) frame += 24 last = frame + 30 # What the program reads: the BIOS's POT shadows ($11-$18, [BUCH]), POKEY's # POT registers directly, and CONSOL writes with bit 2 low (pot power off: # the trak-ball's calibration line, [FSM] section 7). reads = {"shadow": 0, "pot": 0, "consol_low": 0, "consol_writes": 0} def watch(kind: str, address: int, value: int, cycle: int) -> None: if kind == "R" and 0x11 <= address <= 0x18: reads["shadow"] += 1 elif kind == "R" and 0xE800 <= address < 0xF000 and address & 0x0F < 8: reads["pot"] += 1 elif kind == "W" and 0xC000 <= address < 0xD000 and address & 0x1F == 0x1F: reads["consol_writes"] += 1 if not value & 4: reads["consol_low"] += 1 board.bus_observers.append(watch) args.out.mkdir(parents=True, exist_ok=True) stem = Path(args.cart).stem.replace(" ", "_") tag = "stick" if args.stick else "trak" deltas: dict[str, list[int]] = {} shadows: dict[str, tuple[float, float]] = {} start_ram = b"" seen: list[tuple[int, int]] = [] for f in range(1, last + 1): for number, other in enumerate(console.controllers.pads, 1): if number != args.port: down = {k for g, k, n, p in presses if p == number and g <= f < g + n} other.keys = down - {"trigger", "top"} other.trigger = "trigger" in down other.top = "top" in down held = {k for g, k, n, p in presses if p == args.port and g <= f < g + n} held |= {k for g, k in buttons if g <= f < g + 5} if args.tap and any(first <= f < first + 5 for first, _, _ in schedule): held.add("trigger") pad.keys = held - {"trigger", "top"} pad.trigger = "trigger" in held pad.top = "top" in held vx = vy = 0.0 current = None for first, end, phase in schedule: if first <= f < end: current = phase vx, vy = phase[1] * speeds[phase[3]], phase[2] * speeds[phase[3]] if f == first: start_ram = bytes(board.ram) seen = [] if args.stick: scale = TrakBall.span / TrakBall.full_speed pad.x = TrakBall.centre + max(-TrakBall.span, min(TrakBall.span, vx * scale)) pad.y = TrakBall.centre + max(-TrakBall.span, min(TrakBall.span, vy * scale)) else: pad.vx, pad.vy = vx, vy console.run_frames(1) if args.watch and f in (args.play, last): shown = " ".join(f"${a}={board.ram[int(a, 16)]:02X}" for a in args.watch) print(f" frame {f}: {shown}") n = args.port - 1 if current is not None: seen.append((board.ram[0x11 + 2 * n], board.ram[0x12 + 2 * n])) for first, end, phase in schedule: if f == end - 1: ram = bytes(board.ram) # plain difference: a position crossing the screen moves more than 127 deltas[phase[0]] = [b - a for a, b in zip(start_ram, ram)] shadows[phase[0]] = ( sum(s[0] for s in seen) / len(seen), sum(s[1] for s in seen) / len(seen), ) index = PHASES.index(phase) write_png(args.out / f"{stem}-{tag}-{index}-{phase[0]}.png", board.frame) for g, kind in buttons: if f == g + 3: write_png(args.out / f"{stem}-{tag}-{kind}-{f}.png", board.frame) print(f"{Path(args.cart).name} ({tag}): play from {args.play}, slow {args.slow}, " f"fast {args.fast} counts/frame, port {args.port}") # fmt: skip print(f" reads of POT shadows {reads['shadow']}, of POKEY POT registers {reads['pot']}; " f"CONSOL writes {reads['consol_writes']}, with bit 2 low {reads['consol_low']}") # fmt: skip for name, *_ in PHASES: sx, sy = shadows[name] print(f" {name:10s} POT shadows mean {sx:6.1f} {sy:6.1f}") for axis, label in ((0, "X"), (1, "Y")): found = candidates(deltas, axis) loose = [a for a, _ in candidates(deltas, axis, strict=False) if a not in dict(found)] print(f" {label} candidates ({len(found)}; sign pattern only, other axis moving too:" f" {' '.join(f'${a:04X}' for a in loose[:8]) or 'none'}):") # fmt: skip for address, d in found[:8]: print(f" ${address:04X}: +slow {d[0]:4d} -slow {d[1]:4d} +fast {d[2]:4d} -fast {d[3]:4d}") # fmt: skip return 0 if __name__ == "__main__": raise SystemExit(main())