#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Rung 7: commercial games on the board, judged by their pictures at checkpoint frames. The lists (``tests/smoke_set.txt``, 39 ROMs; ``tests/games_set.txt``, 57) were carried over by the owner's decision of 2026-11-19 (docs/restart.md "Carried over"); their header says the columns. Each ROM is read in place from ``$NO_INTRO_DIR`` and run, never read or copied (restart.md; docs/validation.md class R). ``start`` is ``bios`` (Nintendo's BIOS boots the cartridge: ``--retail``, default the No-Intro dump beside the ROMs) or ``skip`` (the cartridge starts as the BIOS leaves it, ``GBA.skip_bios``, with ``--bios`` for the SWI calls). At each checkpoint the picture is written as ``OUT/-.png`` for reading by eye, and the run is classified automatically: - ``error``: the board raised a Python exception (a board bug, always); - ``exception``: the CPU took an undefined-instruction or abort vector (04, 0C, 10), which a working game never does on hardware (HYPOTHESIS for any one game; it is what this flags); - ``blank``: the checkpoint picture is one colour; - ``picture``: anything else. Whether the picture is right is read by eye (the PNGs), and against NanoBoyAdvance where a driver run exists (a detector). python scripts/board_games.py --out /tmp/smoke --jobs 8 python scripts/board_games.py --list tests/games_set.txt --quick --only Zelda ``--quick`` stops at the last checkpoint marked ``q``. ``--json FILE`` writes the results. """ from __future__ import annotations import argparse import json import os import sys import time import traceback from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, os.environ.get("GBA_PYTHON_SRC", str(ROOT / "src"))) from arm7tdmi_python import CODE, SEQ import gba_python.board as board_module from gba_python.board import GBA from gba_python.bus import Bus from gba_python.cartridge.rom import GamePakROM from gba_python.ppu.timing import FRAME_CYCLES from gba_python.ppu.view import png_bytes SET = "Nintendo - Game Boy Advance" RETAIL = "[BIOS] Nintendo Game Boy Advance Boot ROM (World).zip" EXCEPTION_VECTORS = (0x04, 0x0C, 0x10) # undefined, prefetch abort, data abort (DOC: ARM TRM) class WatchingBus(Bus): """The board's bus, noting the first non-sequential opcode fetch from one of those vectors (an exception's entry; the pipeline's own fetches of 04, 0C and 10 are sequential).""" seen = None def read(self, address: int, width: int, access: int) -> int: if ( address in EXCEPTION_VECTORS and access & CODE and not access & SEQ and self.seen is None ): self.seen = (self.board.frames, address, self.board.cpu.r[14]) return super().read(address, width, access) board_module.Bus = WatchingBus def parse_list(path: Path) -> list[dict]: entries = [] for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip() or line.startswith("#"): continue rom, checkpoints, keys, start, category = (field.strip() for field in line.split("|")) marks = [c.strip() for c in checkpoints.split(",")] entries.append( { "rom": rom.removeprefix("nointro:"), "checkpoints": [int(c.rstrip("q")) for c in marks], "quick": [int(c.rstrip("q")) for c in marks if c.endswith("q")], "keys": keys, "start": start, "category": category, } ) return entries def key_schedule(keys: str): """The KEYINPUT mask (1 = pressed) to hold during each frame: the list header's grammar.""" presses = [] # (first, last, every, mask): MASK for 4 frames every EVERY frames holds = [] # (frame, mask): MASK held from FRAME on for token in keys.split(): if token == "-": continue if "@" in token: mask, span = token.split("@") first_last, every = span.split("/") first, last = first_last.split("-") presses.append((int(first), int(last), int(every), int(mask, 0))) else: frame, mask = token.split(":") holds.append((int(frame), int(mask, 0))) holds.sort() def mask_at(frame: int) -> int: mask = 0 for at, held in holds: if at <= frame: mask = held for first, last, every, pressed in presses: if first <= frame <= last and (frame - first) % every < 4: mask |= pressed return mask return mask_at def run_one(job: tuple[dict, str, str | None, str, bool]) -> dict: entry, bios, retail, out, quick = job name = entry["rom"] result = {"rom": name, "start": entry["start"], "category": entry["category"]} # A name with a folder ("Nintendo - Game Boy Advance (Video)/...") is relative to the set root. base = Path(os.environ.get("NO_INTRO_DIR", "")) path = base / name if "/" in name else base / SET / name if not path.exists(): result["verdict"] = "missing" return result checkpoints = entry["quick"] if quick and entry["quick"] else entry["checkpoints"] stem = Path(name).stem try: if entry["start"] == "bios": board = GBA(GamePakROM.from_path(path), bios=retail) else: board = GBA(GamePakROM.from_path(path), bios=bios) board.skip_bios() mask_at = key_schedule(entry["keys"]) shots = {} started = time.process_time() last = max(checkpoints) for frame in range(last): board.set_keys(mask_at(frame)) board.run_until((frame + 1) * FRAME_CYCLES) if frame + 1 in checkpoints: picture = board.picture() colours = len({c for row in picture for c in row}) png = Path(out) / f"{stem}-{frame + 1}.png" png.write_bytes(png_bytes(picture)) shots[frame + 1] = colours result["ms_per_frame"] = round(1000 * (time.process_time() - started) / last, 1) result["colours"] = shots if board.bus.seen: frame, vector, lr = board.bus.seen result["verdict"] = "exception" result["detail"] = f"vector {vector:02X} at frame {frame}, LR {lr:08X}" elif shots[last] <= 1: result["verdict"] = "blank" else: result["verdict"] = "picture" result["pc"] = f"{board.cpu.r[15]:08X}" except Exception as error: # noqa: BLE001 - any exception is a board bug: report it result["verdict"] = "error" result["detail"] = f"{type(error).__name__}: {error}" result["trace"] = traceback.format_exc(limit=-3) return result def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--list", type=Path, default=ROOT / "tests" / "smoke_set.txt") parser.add_argument("--bios", default="free", help="BIOS for skip starts (free or a path)") parser.add_argument("--retail", help="Nintendo's BIOS for bios starts (default: No-Intro's)") parser.add_argument("--out", type=Path, default=Path("/tmp/gba-games")) parser.add_argument("--jobs", type=int, default=4) parser.add_argument("--quick", action="store_true", help="stop at the q checkpoints") parser.add_argument("--only", action="append", default=[], help="ROM names containing this") parser.add_argument("--json", type=Path) args = parser.parse_args() retail = args.retail or str(Path(os.environ.get("NO_INTRO_DIR", "")) / SET / RETAIL) args.out.mkdir(parents=True, exist_ok=True) entries = parse_list(args.list) if args.only: entries = [e for e in entries if any(o.lower() in e["rom"].lower() for o in args.only)] jobs = [(e, args.bios, retail, str(args.out), args.quick) for e in entries] results = [] with ProcessPoolExecutor(max_workers=max(1, args.jobs)) as pool: for result in pool.map(run_one, jobs): results.append(result) detail = result.get("detail", "") speed = result.get("ms_per_frame", "") print(f"{result['verdict']:10} {speed!s:>7} {result['rom']} {detail}", flush=True) counts = {} for result in results: counts[result["verdict"]] = counts.get(result["verdict"], 0) + 1 print(" ".join(f"{k} {v}" for k, v in sorted(counts.items())), f"of {len(results)}") if args.json: args.json.write_text(json.dumps(results, indent=1) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())