Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Tools: the emulator window is tools/emulator.py, the builder tools/build.py, finished apps in build/compiled
Mason3637986a6f34245
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 325c6c24..4e6d596c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -25,7 +25,7 @@ git clone https://github.com/Mason363/NumPlay.gitpython3 NumPlay/tools/setup.py```-`tools/setup.py` gets the ARM compiler, nwlink and the Python packages into `~/.numplay` and tells you the one line that puts them on your PATH (`source ~/.numplay/env.sh` on macOS and Linux). On macOS, run `xcode-select --install` first if `make` is missing. Rust is needed only for Tetris: [rustup.rs](https://rustup.rs), then `rustup target add thumbv7em-none-eabihf`. On Windows, `python tools/build_windows.py` builds NumPlay natively (`--doctor` checks your setup), or use WSL.+`tools/setup.py` gets the ARM compiler, nwlink and the Python packages into `~/.numplay` and tells you the one line that puts them on your PATH (`source ~/.numplay/env.sh` on macOS and Linux). On macOS, run `xcode-select --install` first if `make` is missing. Rust is needed only for Tetris: [rustup.rs](https://rustup.rs), then `rustup target add thumbv7em-none-eabihf`. On Windows, `python tools/build.py` builds NumPlay natively (`--doctor` checks your setup), or use WSL.Then:@@ -38,7 +38,8 @@ Then:| `make -C games/<game> test` | That game's tests on your computer (most games have them) || `python3 tests/test_games.py build/apps` | Plays every app in the emulator and checks its saves || `python3 tools/emu.py app.nwa --ms 5000 --shots 2000 --out shots` | Runs any `.nwa` in the emulator and takes pictures |-| `python3 tools/emu_live.py app.nwa` | The emulator in a window, to play with the mouse and keyboard; `--live` rebuilds as you save |+| `python3 tools/emulator.py app.nwa` | The emulator in a window, to play with the mouse and keyboard; `--live` rebuilds as you save |+| `python3 tools/build.py` | Builds everything and puts the finished apps in `build/compiled/` (`--game ID` for one game, `--watch` to build again when you save) |## How the code is laid outdiff --git a/Makefile b/Makefileindex 8f889997..c4deeebb 100644--- a/Makefile+++ b/Makefile@@ -62,7 +62,7 @@ ARM_CFLAGS = -std=gnu11 $(EADK_CFLAGS) -DNP_VERSION='"$(VERSION)"' -Os -Wall -WeARM_LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable -Wl,--gc-sections -Wl,-e,main \-Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level-.PHONY: all nwa apps check sim emu clean lang FORCE+.PHONY: all nwa apps check sim emu clean lang FORCE tetris-appall: nwa appsnwa: $(foreach v,$(VARIANTS),$(B)/$(v).nwa) $(B)/NumPlay-Upsilon.nwa@@ -199,6 +199,11 @@ APP_buckshot = games/buckshot/output/buckshot.nwa:BuckshotRoulette.nwaAPP_portal = games/portal/output/portal.nwa:PortalReturns.nwaAPP_chess = games/chess/output/chess.nwa:NumChess.nwaAPP_tetris = games/tetris/tetris/target/thumbv7em-none-eabihf/release/tetris:Tetris.nwa+# Tetris on its own, without building every game (tools/build.py --game tetris)+tetris-app: | $(B)+ cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet+ cp $(word 1,$(subst :, ,$(APP_tetris))) $(B)/apps/Tetris.nwa+ arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwaAPP_numvisuals = games/numvisuals/output/numvisuals.nwa:NumVisuals.nwa# too big to share the calculator's app space with NumPlay: only on their ownAPP_celeste = games/celeste/output/celeste.nwa:Celeste.nwadiff --git a/README.md b/README.mdindex 446a90c5..58d5eeef 100644--- a/README.md+++ b/README.md@@ -251,7 +251,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks- **[Gabriele Cirulli](https://github.com/gabrielecirulli/2048)** made 2048.- **Block Blast!** by [Hungry Studio](https://www.hungrystudio.com) inspired NumPlay's Block Blast, written in C for NumPlay with no code or art from it. Its blocks, scoring and colours follow measurements of the app by the players behind [blockblast-Self-Improvement-loop](https://github.com/Kucze3205/blockblast-Self-Improvement-loop).- Snake, Solitaire and Block Breaker look and play like **Google's games** in Search. They are drawn from scratch; nothing is taken from Google.-- **Chrome's dinosaur game** by Google inspired Chrome Dino, which ports its rules, numbers and pictures from [Chromium's source](https://chromium.googlesource.com/chromium/src/+/main/components/neterror/resources/dino_game/) (BSD license). **[LilyTheCatgirl](https://github.com/LilyTheCuteCatgirl)** brought it to NumPlay, and also made the live emulator (`tools/emu_live.py`) and the Windows builder. Not affiliated with Google.+- **Chrome's dinosaur game** by Google inspired Chrome Dino, which ports its rules, numbers and pictures from [Chromium's source](https://chromium.googlesource.com/chromium/src/+/main/components/neterror/resources/dino_game/) (BSD license). **[LilyTheCatgirl](https://github.com/LilyTheCuteCatgirl)** brought it to NumPlay, and also made the live emulator (`tools/emulator.py`) and the builder (`tools/build.py`). Not affiliated with Google.- **[gd3ds](https://github.com/AleFunky/gd3ds)** by AleFunky and friends, whose research into Geometry Dash made NumDash possible. Clubstep, Deadlocked and Dash also rely on [gdsolver](https://github.com/gdsolver/gdsolver)'s measurements of Geometry Dash 2.2, level data from [gmdkit](https://github.com/UHDanke/gmdkit) by HDanke and checks against [GDRWeb](https://github.com/iliasHDZ/GDRWeb) by IliasHDZ.- **Balatro** by LocalThunk inspired NumPlay's Balatro, which uses art adapted from the game and the **m6x11** font by Daniel Linssen.- **Minecraft** by Mojang inspired NumBlocks, which follows Minecraft 1.8.8 exactly: it makes its worlds the way Minecraft 1.8.8 does and uses its blocks, items, recipes, textures, font and screens.diff --git a/docs/make-a-game.md b/docs/make-a-game.mdindex 465aaf35..c954fbe5 100644--- a/docs/make-a-game.md+++ b/docs/make-a-game.md@@ -27,7 +27,7 @@ python3 NumPlay/tools/setup.py| --- | --- || **macOS** (Apple silicon or Intel) | If `make` is missing, run `xcode-select --install` first. Then, in each new terminal: `source ~/.numplay/env.sh` || **Linux** | Same as macOS: `source ~/.numplay/env.sh` |-| **Windows** | `tools/setup.py` prints the PowerShell line to use. `python tools/build_windows.py` builds NumPlay natively (it gets GNU make for you), or use WSL |+| **Windows** | `tools/setup.py` prints the PowerShell line to use. `python tools/build.py` builds NumPlay natively (it gets GNU make for you), or use WSL |## 2. Start a game@@ -54,7 +54,7 @@ python3 tools/emu.py games/mygame/output/mygame.nwa --ms 6000 --keys "1500-1600:To play it with your mouse and keyboard instead, open it in the live emulator, a calculator in a window (made by LilyTheCuteCatgirl). With `--live` it builds your game again each time you save a file and reloads it:```bash-python3 tools/emu_live.py games/mygame/output/mygame.nwa+python3 tools/emulator.py games/mygame/output/mygame.nwa````tools/emu.py`'s `--keys` holds keys over time ranges in milliseconds (`ok`, `back`, `left`, `up`, `exe`, `home`, `1`...`9`, `shift`, `alpha`...). `--gif 0-5000` records a GIF, `--model n0110` emulates the slower N0110 and N0115 (if your game is smooth there, it's smooth everywhere), `--system upsilon` emulates Upsilon. It runs at about the speed of an N0110.@@ -88,7 +88,8 @@ And the tools, all in `tools/`:| `setup.py` | Gets the compiler, nwlink and the Python packages || `new_game.py` | Starts a game from the template || `emu.py` | Runs a `.nwa` in an emulator: pictures, GIFs, scripted keys, files kept between runs, profiling |-| `emu_live.py` | The emulator in a window: click the keys or use your keyboard; `--live` rebuilds when you save (`watch.py` on macOS and Linux, `build_windows.py` on Windows) |+| `emulator.py` | The emulator in a window: click the keys or use your keyboard; `--live` rebuilds when you save, with `build.py` |+| `build.py` | Builds NumPlay on macOS, Linux and Windows and puts the finished apps in `build/compiled/`; `--game ID` builds one game, `--watch` builds again when you save || `icon.py` | Makes the 55 x 56 app icon from any picture, with the rounded corners every NumPlay icon has || `record.py` | Makes GIFs from the emulator's frames || `sizes.py` | How much flash and RAM each game takes inside NumPlay |diff --git a/tools/build_windows.py b/tools/build.pysimilarity index 77%rename from tools/build_windows.pyrename to tools/build.pyindex ae5dec32..6fadd947 100644--- a/tools/build_windows.py+++ b/tools/build.py@@ -1,18 +1,18 @@#!/usr/bin/env python3-"""Build NumPlay .nwa files on native Windows (no WSL/Linux required).+"""Build NumPlay .nwa files on Windows, macOS and Linux.Requirements: Git for Windows (Git Bash), GNU Make 4.4.1 for Windows, Node.js/npm,Python, Rust/rustup and a native Windows arm-none-eabi-gcc toolchain.-Run from PowerShell in the repository root:- python tools/build_windows.py --doctor- python tools/build_windows.py --launcher-only --skip-languages -j2- python tools/build_windows.py --organize-only --tidy-legacy- python tools/build_windows.py --watch --launcher-only --skip-languages -j2+Run from PowerShell (Windows) or a terminal (macOS/Linux):+ python tools/build.py --doctor+ python tools/build.py --launcher-only --skip-languages -j2+ python tools/build.py --organize-only+ python tools/build.py --watch --launcher-only --skip-languages -j2It keeps Make's intermediate outputs untouched under build/ and atomically-exports finished calculator apps into top-level dist/, including the stable-live-emulator input dist/live/NumPlay.nwa. `--watch` monitors source edits and+exports finished calculator apps into top-level build/compiled/, including the stable+live-emulator input build/compiled/NumPlay.nwa. `--watch` monitors source edits andrebuilds incrementally, publishing only after successful builds. `--organize-only`exports an existing successful build with no toolchain necessary.@@ -25,6 +25,7 @@ from __future__ import annotationsimport argparseimport hashlib+import reimport timeimport osfrom pathlib import Path@@ -43,7 +44,7 @@ TOOL_URL = ("https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releasesf"download/v{TOOL_VERSION}/{TOOL_NAME}")TOOL_SHA256 = "bae6a3d1667697ce750c3b13d6d26d80973ecedc2cc87bf04869e83447fd93ea"ARM_BASE = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "NumPlay" / "toolchains"-OUTPUT = ROOT / "dist"+OUTPUT = ROOT / "build" / "compiled"RUST_TARGET = "thumbv7em-none-eabihf"# GnuWin32 Make 3.81 (often installed by winget) can crash with 0xc0000005@@ -293,10 +294,10 @@ def doctor() -> bool:if not b:print(" Git for Windows: https://git-scm.com/downloads/win (includes Git Bash; NOT Linux)")if not make_ok:- print(" GNU Make 4.4.1: python tools/build_windows.py --install-make")+ print(" GNU Make 4.4.1: python tools/build.py --install-make")print(" (Portable Windows binary; ~400 KB; no administrator privileges or PATH change)")if not arm:- print(" ARM compiler: python tools/build_windows.py --install-arm")+ print(" ARM compiler: python tools/build.py --install-arm")print(" (Downloads official xPack Windows compiler, about 320 MB, SHA-256 verified)")if not node or not npx:print(" Node.js: winget install --id OpenJS.NodeJS.LTS -e")@@ -445,7 +446,7 @@ def create_nwlink_bridge(shims: Path) -> Path:def run_bash(bash: Path, make: Path, make_name: str, arm: Path, jobs: int,- *, apps: bool, check: bool, langs: bool) -> None:+ *, apps: bool, check: bool, langs: bool, target_args: list[str] | None = None) -> None:# Ensure make's directories exist even when build/ was created by an# interrupted earlier run. Keep all existing compiled files for a retry.created = ensure_build_directories()@@ -485,19 +486,22 @@ command -v nwlink >/dev/null || { echo 'Tetris nwlink bridge is unavailable fromif completed.returncode:raise RuntimeError(f"GNU Make exited with code {completed.returncode} (build stopped)")- targets = ["nwa"]- if apps or check:- targets.append("apps")- if check:- targets.append("check")- invoke([f"-j{jobs}", *targets])- if langs:- invoke(["lang"])+ if target_args is not None:+ invoke([f"-j{jobs}", *target_args])+ else:+ targets = ["nwa"]+ if apps or check:+ targets.append("apps")+ if check:+ targets.append("check")+ invoke([f"-j{jobs}", *targets])+ if langs:+ invoke(["lang"])# Publish end-user .nwa files outside Make's internal build/ directory.# build/ is intentionally left alone: NumPlay's Makefile hard-codes B = build.-# The stable live path can later be supplied to emu_live.py for auto-reload.+# The stable live path can later be supplied to emulator.py for auto-reload.LIVE_DIR = "live"VARIANT_DIR = "variants"GAME_DIR = "games"@@ -509,9 +513,9 @@ def destination_for(name: str, output: Path) -> Path:if name == "NumPlay.nwa":return output / nameif name in LANGUAGE_VARIANTS:- return output / LANGUAGE_DIR / name+ return output / nameif name.startswith("NumPlay-") and name.endswith(".nwa"):- return output / VARIANT_DIR / name+ return output / namereturn output / GAME_DIR / name@@ -549,7 +553,7 @@ def atomic_copy(src: Path, dest: Path) -> None:def collect_sources(*, apps: bool, langs: bool) -> list[Path]:build = ROOT / "build"- # Never include existing dist/ files: only fresh Makefile output sources.+ # Never include existing build/compiled/ files: only fresh Makefile output sources.sources = list(sorted(build.glob("NumPlay*.nwa")))if not langs:sources = [p for p in sources if p.name not in LANGUAGE_VARIANTS]@@ -578,29 +582,27 @@ def publish_outputs(*, apps: bool, langs: bool, output: Path = OUTPUT,# Publish user-facing variants and standalone games first.# Publish the stable live file *last*, marking the completed build.main_src = None- for src in sources:+ ordered_sources = [p for p in sources if p.name != "NumPlay.nwa"]+ ordered_sources += [p for p in sources if p.name == "NumPlay.nwa"]+ for src in ordered_sources:if src.name == "NumPlay.nwa":main_src = srcdest = destination_for(src.name, output)atomic_copy(src, dest)published.append(dest)- if main_src is not None:- live = output / LIVE_DIR / "NumPlay.nwa"- atomic_copy(main_src, live)- published.append(live)if verbose:print(f"\nSUCCESS: organized {len(sources)} calculator app(s) in:", output)for path in published:print(" " + str(path.relative_to(output)))if main_src:- print("\nStable live-emulator input: " + str(output / LIVE_DIR / "NumPlay.nwa"))+ print("\nStable live-emulator input: " + str(output / "NumPlay.nwa"))return publisheddef safe_remove_legacy_duplicates(output: Path = OUTPUT) -> None:"""Opt-in cleanup of only byte-identical earlier exports in build/windows-nwa.- Do not delete anything that wasn't safely copied into dist/. No recursive+ Do not delete anything that wasn't safely copied into build/compiled/. No recursivedeletion; unknown or changed files are left exactly as they were."""legacy = ROOT / "build" / "windows-nwa"@@ -686,7 +688,7 @@ def differences(a: dict, b: dict) -> list[str]:def run_watch(build_once, *, interval: float = 1.0,- settle: float = 1.0, root: Path = ROOT) -> None:+ settle: float = 1.0, root: Path = ROOT, game: str | None = None) -> None:"""Debounce editor save bursts; rebuild and publish only on success.No extra watchdog package needed. Capture the baseline after a build so@@ -695,13 +697,22 @@ def run_watch(build_once, *, interval: float = 1.0,if interval <= 0 or settle <= 0:raise ValueError("watch interval and settle time must be positive")print("\nWatching NumPlay source files. Save an edit to rebuild; Ctrl+C to stop.")- print("Build failures keep the previous dist/live/NumPlay.nwa untouched.\n")- baseline = source_snapshot(root)+ print("Build failures keep the previous build/compiled/NumPlay.nwa untouched.\n")+ def snapshot():+ files = source_snapshot(root)+ if game is None:+ return files+ prefixes = (f"games/{game}/", "games/common/", "tools/")+ shared = {"Makefile", "VERSION", "games/games.json"}+ return {name: st for name, st in files.items()+ if name in shared or name.startswith(prefixes)}++ baseline = snapshot()pending: dict[str, tuple[int, int]] | None = Nonelast_change = 0.0while True:time.sleep(interval)- current = source_snapshot(root)+ current = snapshot()now = time.monotonic()if current == baseline:pending = None@@ -720,110 +731,176 @@ def run_watch(build_once, *, interval: float = 1.0,print(f" ... plus {len(changed) - 12} more")try:build_once()- except (OSError, RuntimeError) as exc:- print("\nBuild failed; keeping last good dist/live/NumPlay.nwa:", exc,+ except (OSError, RuntimeError, subprocess.CalledProcessError, ValueError) as exc:+ print("\nBuild failed; keeping last good build/compiled/ app:", exc,file=sys.stderr, flush=True)# Rescan after build. Generated files, if any, become the new baseline.# A human edit made during the build may need a further save to trigger.- baseline = source_snapshot(root)+ baseline = snapshot()pending = Noneprint("\nWatching for the next edit...", flush=True)+++# ---- Universal build entry point: native Windows, macOS and Linux ----++def _nwlink() -> str:+ found = shutil.which("nwlink")+ if found:+ return found+ local = Path.home() / ".numplay" / "node_modules" / ".bin" / "nwlink"+ if local.exists():+ return str(local)+ return "npx --yes -- [email protected]"+++def _run_make(args: list[str], *, jobs: int) -> None:+ print("Building:", " ".join(["make", f"-j{jobs}", *args]), flush=True)+ if os.name == "nt":+ make, make_name = find_make()+ bash, arm = git_bash(), find_arm()+ if not (make and make_name and bash and arm and make_supported(make)):+ raise RuntimeError("Windows toolchain missing; run python tools/build.py --doctor")+ run_bash(bash, make, make_name, arm, jobs, apps=False, check=False, langs=False,+ target_args=args)+ else:+ ensure_build_directories()+ cmd = ["make", f"-j{jobs}", *args, "NWLINK=" + _nwlink()]+ subprocess.run(cmd, check=True, cwd=ROOT)+++def _game_output(game: str) -> tuple[str, Path]:+ import json+ import re+ manifest = json.loads((ROOT / "games" / "games.json").read_text(encoding="utf-8"))+ labels = {g["id"]: g["app"] for g in manifest if g.get("app")}+ for match in re.finditer(r"(?m)^APP_(\w+)\s*=\s*([^:\n]+):(\S+\.nwa)\s*$",+ (ROOT / "Makefile").read_text(encoding="utf-8")):+ labels[match.group(1)] = match.group(3)+ if game not in labels:+ raise ValueError(f"Unknown standalone game '{game}'. Choices: " + ", ".join(sorted(labels)))+ game_dir = ROOT / "games" / game+ if not game_dir.is_dir():+ raise ValueError(f"Missing game directory: {game}")+ file = labels[game]+ # Each game's own output: output/, output/device/ (NumDrive) or build/ (NumDash); Tetris, Cargo's.+ candidate = [game_dir / "output" / f"{game}.nwa", game_dir / "output" / "device" / f"{game}.nwa",+ game_dir / "build" / f"{game}.nwa"]+ if game == "tetris":+ candidate = [ROOT / "build" / "apps" / "Tetris.nwa"]+ return file, next((p for p in candidate if p.is_file()), candidate[0])+++def _publish_game(game: str) -> Path:+ name, src = _game_output(game)+ if not src.is_file():+ raise RuntimeError(f"No successful game build found at {src}")+ dst = OUTPUT / "games" / name+ atomic_copy(src, dst)+ print("Stable live-emulator input:", dst.relative_to(ROOT), flush=True)+ return dst+++def _build_once(a) -> None:+ if a.game:+ if a.game == "tetris":+ # Dedicated Cargo target: do not compile all NumPlay games.+ # The Make recipe uses the existing Windows nwlink.exe bridge.+ _run_make(["tetris-app"], jobs=a.jobs)+ _publish_game("tetris")+ return+ _game_output(a.game) # Fail before launching a compiler on invalid IDs.+ _run_make(["-C", f"games/{a.game}", "build"], jobs=a.jobs)+ _publish_game(a.game)+ return+ if os.name == "nt":+ if not doctor():+ raise RuntimeError("Windows requirements are not yet ready")+ make, make_name = find_make()+ bash, arm = git_bash(), find_arm()+ assert make and make_name and bash and arm+ run_bash(bash, make, make_name, arm, a.jobs,+ apps=not a.launcher_only, check=not a.skip_check and not a.launcher_only,+ langs=not a.skip_languages)+ else:+ targets = ["nwa"]+ if not a.launcher_only:+ targets += ["apps"]+ if not a.skip_check and not a.launcher_only:+ targets += ["check"]+ _run_make(targets, jobs=a.jobs)+ if not a.skip_languages:+ _run_make(["lang"], jobs=a.jobs)+ sources = collect_sources(apps=not a.launcher_only, langs=not a.skip_languages)+ publish_outputs(apps=not a.launcher_only, langs=not a.skip_languages)+ if (ROOT / "build" / "compiled" / "NumPlay.nwa").is_file():+ print("Stable live-emulator input: build/compiled/NumPlay.nwa", flush=True)++def main() -> int:- ap = argparse.ArgumentParser(description="Build NumPlay .nwa apps on native Windows (no WSL).")- ap.add_argument("--doctor", action="store_true", help="check prerequisites, don't build")- ap.add_argument("--install-arm", action="store_true", help="download/verify official Windows ARM GCC")- ap.add_argument("--install-make", action="store_true", help="download/verify portable Windows GNU Make 4.4.1")- ap.add_argument("--make-zip", type=Path, metavar="ZIP", help="with --install-make, use a manually downloaded ZIP if SourceForge blocks Python")- ap.add_argument("--launcher-only", action="store_true", help="build only combined NumPlay variants")- ap.add_argument("--skip-check", action="store_true", help="skip linker/RAM checks")- ap.add_argument("--skip-languages", action="store_true", help="skip French/Chinese variants")- ap.add_argument("--organize-only", action="store_true", help="organize existing build outputs into dist/ without compiling")- ap.add_argument("--tidy-legacy", action="store_true", help="remove only verified duplicate .nwa files in build/windows-nwa/")- ap.add_argument("--watch", action="store_true", help="rebuild when source files change (Ctrl+C to stop)")- ap.add_argument("--watch-interval", type=float, default=1.0,- help="seconds between source scans in watch mode (default 1.0)")- ap.add_argument("-j", "--jobs", type=int, default=4, help="parallel make jobs (default 4)")+ ap = argparse.ArgumentParser(description="NumPlay unified build + live watch (Windows, macOS, Linux)")+ ap.add_argument("--doctor", action="store_true")+ ap.add_argument("--install-arm", action="store_true", help="Windows: install verified ARM compiler")+ ap.add_argument("--install-make", action="store_true", help="Windows: install portable GNU Make")+ ap.add_argument("--make-zip", type=Path)+ ap.add_argument("--game", metavar="ID", help="compile one standalone game")+ ap.add_argument("--launcher-only", action="store_true")+ ap.add_argument("--skip-check", action="store_true")+ ap.add_argument("--skip-languages", action="store_true")+ ap.add_argument("--organize-only", action="store_true", help="publish existing successful .nwa files")+ ap.add_argument("--watch", action="store_true", help="rebuild when source files change")+ ap.add_argument("--once", action="store_true", help="alias for a normal one-time build")+ ap.add_argument("--clean", action="store_true", help="make clean; removes generated build files")+ ap.add_argument("--watch-interval", type=float, default=1.0)+ ap.add_argument("-j", "--jobs", type=int, default=2)a = ap.parse_args()- rust_bin = ensure_rust_on_path()- if rust_bin:- print(f"Found installed Rust at {rust_bin}; using it for this command "- "(no permanent PATH changes).", flush=True)- if a.jobs < 1 or a.jobs > 32:- ap.error("--jobs must be between 1 and 32")- if a.make_zip and not a.install_make:- ap.error("--make-zip requires --install-make")- if a.watch_interval <= 0:- ap.error("--watch-interval must be positive")- if a.watch and (a.organize_only or a.doctor or a.install_arm or a.install_make):- ap.error("--watch requires a normal build, not --doctor / --organize-only / installation")- if a.install_make:- try:- install_make(a.make_zip)- except (OSError, RuntimeError, zipfile.BadZipFile, urllib.error.URLError) as exc:- print("GNU Make installation failed:", exc, file=sys.stderr)- return 1- if not a.doctor and not a.install_arm:- print("Next: python tools/build_windows.py --doctor")- return 0- if a.install_arm:- try:- install_arm()- except (OSError, RuntimeError, zipfile.BadZipFile) as exc:- print("Compiler installation failed:", exc, file=sys.stderr)- return 1- if not a.doctor:- print("Next: python tools/build_windows.py --doctor")- return 0+ if a.jobs < 1 or a.jobs > 32 or a.watch_interval <= 0:+ ap.error("jobs must be 1..32 and watch interval must be positive")+ if os.name == "nt":+ # Older PowerShell windows may not inherit ~/.cargo/bin in their PATH.+ ensure_rust_on_path()if a.doctor:- return 0 if doctor() else 1+ if os.name == "nt":+ return 0 if doctor() else 1+ return subprocess.call([sys.executable, str(ROOT / "tools" / "setup.py"), "--check"])+ if a.install_arm or a.install_make:+ if os.name != "nt":+ ap.error("Windows installers are Windows-only; use tools/setup.py")+ if a.install_arm:+ install_arm()+ if a.install_make:+ install_make(a.make_zip)+ return 0+ if a.clean:+ # Do not call `make clean`: several game recipes erase local build/+ # folders also used by host tests (including host-saves).+ for location in (OUTPUT,):+ if location.is_symlink():+ raise RuntimeError(f"Refusing to clean symlink: {location}")+ if location.is_dir():+ shutil.rmtree(location)+ print("Removed disposable build directory:", location.relative_to(ROOT))+ print("Kept game-local folders and ~/.numplay-emulator/ (saves and settings).")+ return 0if a.organize_only:- try:- publish_outputs(apps=True, langs=True)- if a.tidy_legacy:- safe_remove_legacy_duplicates()- return 0- except (OSError, RuntimeError) as exc:- print("Could not organize build outputs:", exc, file=sys.stderr)+ publish_outputs(apps=True, langs=True)+ return 0+ if a.game and a.launcher_only:+ ap.error("--game and --launcher-only are mutually exclusive")+ try:+ _build_once(a)+ except (OSError, RuntimeError, subprocess.CalledProcessError, ValueError) as exc:+ print("Build failed; the last good .nwa stays untouched:", exc, file=sys.stderr, flush=True)+ if not a.watch:return 1- if not doctor():- return 1- make, make_name = find_make()- assert make and make_name and make_supported(make)- bash, arm = git_bash(), find_arm()- assert bash and arm-- def build_once():- run_bash(bash, make, make_name, arm, a.jobs,- apps=not a.launcher_only,- check=not a.launcher_only and not a.skip_check,- langs=not a.skip_languages)- publish_outputs(apps=not a.launcher_only, langs=not a.skip_languages)- if a.tidy_legacy:- safe_remove_legacy_duplicates()-- if a.watch:+ if a.watch and not a.once:try:- # Initial build then repeat on changes; failed initial build doesn't- # stop observation, and existing exports remain intact.- try:- build_once()- except (OSError, RuntimeError) as exc:- print("\nInitial build failed; old exported files were kept:", exc,- file=sys.stderr, flush=True)- run_watch(build_once, interval=a.watch_interval)+ run_watch(lambda: _build_once(a), interval=a.watch_interval, game=a.game)except KeyboardInterrupt:- print("\nStopped watching. Compiled files remain in dist/.")- return 0- try:- build_once()- return 0- except (OSError, RuntimeError) as exc:- print("\nWindows build failed:", exc, file=sys.stderr)- print("The original source files and your emulator have not been modified.", file=sys.stderr)- return 1+ return 0+ return 0if __name__ == "__main__":- raise SystemExit(main())+ sys.exit(main())diff --git a/tools/emu_live.py b/tools/emulator.pysimilarity index 94%rename from tools/emu_live.pyrename to tools/emulator.pyindex 5f693d02..49432c20 100644--- a/tools/emu_live.py+++ b/tools/emulator.py@@ -1,33 +1,16 @@#!/usr/bin/env python3-"""Live NumWorks emulator for macOS, Linux and Windows: a calculator you can click, around tools/emu.py.--Put this file beside tools/emu.py. Requires Pillow, numpy, unicorn,-pyelftools and nwlink (tkinterdnd2 for dropping files, if you like). It shows a-picture of the NumWorks N0120 (emu_live_calculator.webp, beside this file), with the-screen and every key where they are on it.--Runs an ARM .nwa through the project's existing emu.Calculator, shows the-320x240 display, supports 46 clickable keys, keyboard, .nwa drops and reload.--To run:- python tools/emu_live.py path/to/NumPlay.nwa--The calculator skin does not depend on emu_live_skin.py; emu.py is still needed.--What it does:-- Single file / Live development: it builds again when you save, and reloads- (tools/watch.py on macOS and Linux, tools/build_windows.py on Windows);-- calculator skin / pixel-exact 320x240 screen, keyboard highlights;-- tear-reduced frame presentation, usable Epsilon firmware text;-- N0120 display-transfer timings calibrated using physical NumWorks results;-- fixed 550 MHz N0120 / 216 MHz older-model baseline (approximate timing);-- optional host-adaptive clock and opt-in speed diagnostics;-- manual confirmed USB upload with a live progress bar and USB activity log;-- installer percentages are shown only when nwlink actually reports them.--This is not a cycle-accurate Cortex-M7 emulator: demanding NumDrive scenes can-still be host-CPU-limited. This release excludes the experimental SRAM hooks and-LCD scanout simulation. Saves and crash logs remain outside build/ and dist/.+"""The NumWorks emulator in a window, for macOS, Linux and Windows: a calculator you can click, around tools/emu.py.++Requires Pillow, numpy, unicorn, pyelftools and nwlink (tkinterdnd2 for dropping files, if you like). It shows a+picture of the NumWorks N0120 (emu_live_calculator.webp, beside this file), with the screen and every key where+they are on it, and runs any .nwa through tools/emu.py's Calculator.++ python3 tools/emulator.py path/to/NumPlay.nwa # one app+ python3 tools/emulator.py --live # Live development: builds again when you save+ python3 tools/emulator.py --headless app.nwa ... # tools/emu.py's own options, without a window++Live development builds with tools/build.py, which puts the finished apps in build/compiled/ (NumPlay.nwa and+the other versions, games/ for each game on its own); pick any of them to build and run just that one."""from __future__ import annotations@@ -61,18 +44,15 @@ except ImportError:DND_FILES = NoneTkinterDnD = None-# emu.py is a sibling file when installed in the repository's tools folder.-try:- import emu-except ImportError as exc:- raise SystemExit("Put emu_live.py inside NumPlay/tools/, beside emu.py. "- f"Import failed: {exc}") from exc+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import emu # noqa: E402 (the ARM emulator: the CPU, the screen, the keys, the files)+REPO_ROOT = Path(__file__).resolve().parent.parentHOME_NWA = Path.home() / "Downloads" / "nwa"SAVE_DIR = Path.home() / ".numplay-emulator" / "saves"-LIVE_NWA = REPO_ROOT / "dist" / "live" / "NumPlay.nwa"-BUILD_SCRIPT = REPO_ROOT / "tools" / ("build_windows.py" if os.name == "nt" else "watch.py")+LIVE_NWA = REPO_ROOT / "build" / "compiled" / "NumPlay.nwa"+BUILD_SCRIPT = REPO_ROOT / "tools" / "build.py"LCD_WIDTH = 320LCD_HEIGHT = 240FRAME_VIRTUAL_MS = 32@@ -208,11 +188,11 @@ def validate_layout():def find_nwas() -> list[Path]:"""Quick bounded discovery: local builds and the user's normal download folder."""patterns = (- REPO_ROOT / "dist" / "live" / "*.nwa",- REPO_ROOT / "dist" / "*.nwa",- REPO_ROOT / "dist" / "games" / "*.nwa",- REPO_ROOT / "dist" / "variants" / "*.nwa",- REPO_ROOT / "dist" / "languages" / "*.nwa",+ REPO_ROOT / "build" / "compiled" / "live" / "*.nwa",+ REPO_ROOT / "build" / "compiled" / "*.nwa",+ REPO_ROOT / "build" / "compiled" / "games" / "*.nwa",+ REPO_ROOT / "build" / "compiled" / "variants" / "*.nwa",+ REPO_ROOT / "build" / "compiled" / "languages" / "*.nwa",REPO_ROOT / "build" / "*.nwa",REPO_ROOT / "build" / "apps" / "*.nwa",REPO_ROOT / "games" / "*" / "output" / "*.nwa",@@ -369,7 +349,7 @@ class FidelityFont:class TracedCalculator(emu.Calculator):"""Keep the headless emulator intact, but yield on time-changing syscalls.- In emu.py, Calculator.run() requests a full millisecond of ARM *instructions*+ In emulator.py, Calculator.run() requests a full millisecond of ARM *instructions*at once. A program can call eadk_timing_msleep(16) hundreds of times beforethat instruction budget expires. Each call immediately advances now_ms, soa single emu_start() can advance several *seconds* of virtual time. A 2ms@@ -644,14 +624,14 @@ class TracedCalculator(emu.Calculator):file=sys.stderr, flush=True)if svc == 23 and delta_ms >= 1:- # emu.py's 'no event' path adds 10ms, but does not mark the+ # emulator.py's 'no event' path adds 10ms, but does not mark the# interval as idle. Correct the worker's CPU-load measurement.self.slept_ms += delta_msif svc in self.TIME_ADVANCING_SVCS and delta_ms >= 0.5:self.last_svc_yield = (svc, pc - 2, delta_ms)self.svc_yield_count += 1- # emu.py unconditionally adds +1ms after emu_start() returns,+ # emulator.py unconditionally adds +1ms after emu_start() returns,# assuming its entire instruction budget ran. We deliberately# stopped before the budget was exhausted. Cancel that extra ms# now; the backend adds it back immediately after emu_stop().@@ -1221,7 +1201,7 @@ class LiveApp:def screenshot(self):if self._screen_rgb is None:return- directory = REPO_ROOT / "build" / "emu-live"+ directory = REPO_ROOT / "build" / "data" / "emulator"directory.mkdir(parents=True, exist_ok=True)path = directory / f"{self.current.stem if self.current else 'screen'}-{int(time.time())}.png"self._screen_rgb.save(path)@@ -1825,6 +1805,20 @@ class CalculatorSkinApp(LiveApp):menu = ttk.OptionMenu(grid, var, var.get(), *values, command=lambda _v, c=command: c())menu.grid(row=row, column=1, sticky="e", pady=3)+ # Quick compiled app picker (only files from build/compiled).+ self._section(inner, "Compiled Games")+ self._compiled_choice = tk.StringVar(master=self.root, value="NumPlay.nwa")+ self._compiled_picker = ttk.Combobox(inner, textvariable=self._compiled_choice,+ state="readonly", width=30)+ self._compiled_picker.pack(fill="x", pady=(2, 4))+ self._compiled_picker.bind("<Button-1>", lambda _e: self._refresh_compiled_games())+ self._compiled_picker.bind("<<ComboboxSelected>>", self._on_compiled_selection_changed)+ self._refresh_compiled_games()+ actions = tk.Frame(inner, bg=PANEL)+ actions.pack(fill="x", pady=(0, 3))+ ttk.Button(actions, text="Run", command=self._run_compiled_selection).pack(side="left")+ ttk.Button(actions, text="Build + Run", command=self._build_compiled_selection).pack(side="left", padx=(5, 0))+# Live Buildself._section(inner, "Live Build")ttk.Checkbutton(inner, text="Rebuild and reload when I save", variable=self.live_var,@@ -2093,9 +2087,23 @@ class CalculatorSkinApp(LiveApp):style = ttk.Style(self.root)style.theme_use("clam")style.configure(".", background=PANEL, foreground=FG)- style.configure("TButton", background=PANEL_2)+ style.configure("TButton", background=PANEL_2, foreground=FG)+ style.map("TButton",+ foreground=[("disabled", MUTED), ("pressed", FG), ("active", FG)],+ background=[("pressed", SELECT), ("active", HOVER)])style.configure("TCheckbutton", background=PANEL, foreground=FG)+ style.map("TCheckbutton",+ foreground=[("disabled", MUTED), ("active", FG)],+ background=[("active", PANEL)])style.configure("TMenubutton", background=PANEL_2, foreground=FG)+ style.map("TMenubutton",+ foreground=[("disabled", MUTED), ("pressed", FG), ("active", FG)],+ background=[("pressed", SELECT), ("active", HOVER)])+ style.configure("TCombobox", foreground=FG, fieldbackground=PANEL_2,+ background=PANEL_2, arrowcolor=FG)+ style.map("TCombobox", foreground=[("readonly", FG), ("disabled", MUTED)],+ fieldbackground=[("readonly", PANEL_2)],+ background=[("active", HOVER)])style.configure("Horizontal.TProgressbar", background=ACCENT, troughcolor=PANEL_2)except tk.TclError:pass@@ -2137,6 +2145,81 @@ class CalculatorSkinApp(LiveApp):self._set_build_state("Off", "Opens one .nwa. Turn this on to build NumPlay again each time you save ""a file, and reload it.")+ def _compiled_choices(self):+ """Offer every known app before it has been built, not just files on disk.++ A game is built on demand by `tools/build.py --game ID`. Discover its+ release filename from the manifest and the same APP_ assignments used+ by the root Makefile, including special-layout games.+ """+ root = REPO_ROOT / "build" / "compiled"+ filenames = [+ "NumPlay.nwa", "NumPlay-Invisible.nwa", "NumPlay-Matrices.nwa",+ "NumPlay-Upsilon.nwa", "NumPlay-French.nwa", "NumPlay-Chinese.nwa",+ ]+ manifest = json.loads((REPO_ROOT / "games" / "games.json").read_text(encoding="utf-8"))+ game_names = {record["app"] for record in manifest if record.get("app")}+ makefile = (REPO_ROOT / "Makefile").read_text(encoding="utf-8")+ game_names.update(re.findall(+ r"(?m)^APP_\w+\s*=\s*[^:\n]+:(\S+\.nwa)\s*$", makefile))+ filenames.extend("games/" + name for name in sorted(game_names, key=str.casefold))+ # Keep any existing nonstandard exported files reachable, too.+ filenames.extend(p.relative_to(root).as_posix() for p in root.glob("NumPlay-*.nwa") if p.is_file())+ filenames.extend(p.relative_to(root).as_posix() for p in (root / "games").glob("*.nwa") if p.is_file())+ return [root / name for name in dict.fromkeys(filenames)]++ def _refresh_compiled_games(self):+ paths = self._compiled_choices()+ self._compiled_paths = {str(p.relative_to(REPO_ROOT / "build" / "compiled")): p for p in paths}+ self._compiled_picker.configure(values=list(self._compiled_paths))+ if not self._compiled_choice.get() or self._compiled_choice.get() not in self._compiled_paths:+ if self._compiled_paths:+ self._compiled_choice.set(next(iter(self._compiled_paths)))++ def _on_compiled_selection_changed(self, _event=None):+ """Retarget an active live watcher; never let two builds run together."""+ if self.mode_var.get() != "live" or self._closing:+ return+ selected = self._compiled_choice.get()+ self._stop_builder()+ self._set_build_state("Switching live target", selected, busy=True)+ # _start_builder waits for the stopped process tree on Windows before+ # starting a new compiler. It reads the *current* selection then.+ self._start_builder()++ def _selected_compiled_path(self):+ return (REPO_ROOT / "build" / "compiled" / self._compiled_choice.get()).resolve()++ def _game_id_for_compiled(self, path):+ import json+ if path.parent.name != "games":+ return None+ manifest = json.loads((REPO_ROOT / "games" / "games.json").read_text(encoding="utf-8"))+ for record in manifest:+ if record.get("app") == path.name:+ return record["id"]+ for item in re.finditer(r"(?m)^APP_(\w+)\s*=\s*[^:\n]+:(\S+\.nwa)\s*$",+ (REPO_ROOT / "Makefile").read_text(encoding="utf-8")):+ if item.group(2) == path.name:+ return item.group(1)+ return None++ def _run_compiled_selection(self):+ path = self._selected_compiled_path()+ if not path.is_file():+ self._set_build_state("Not built yet", "Build the selected app first", error=True)+ return+ self.mode_var.set("file")+ self._switch_mode()+ self.load(path)++ def _build_compiled_selection(self):+ if self.mode_var.get() == "live":+ self._stop_builder()+ self.mode_var.set("live")+ self.live_var.set(True)+ self._switch_mode()+def _switch_mode(self):self._configure_mode_panel()self.watch_candidate = None@@ -2169,9 +2252,9 @@ class CalculatorSkinApp(LiveApp):if self._closing:returnif (self.mode_var.get() == "live" and self.watch_var.get() and- self._builder_ready and self.current == LIVE_NWA):+ self._builder_ready and self.current == self._selected_compiled_path()):try:- self._maybe_reload(LIVE_NWA)+ self._maybe_reload(self._selected_compiled_path())except OSError as exc:self.build_status.set("Live reload check failed")self.build_detail.set(str(exc)[:140])@@ -2233,8 +2316,19 @@ class CalculatorSkinApp(LiveApp):self._builder_log.clear()self.watch_candidate = Noneself.watch_var.set(True)- cmd = [sys.executable, "-u", str(BUILD_SCRIPT), "--watch",- "--launcher-only", "--skip-languages", "-j2"]+ selected = self._selected_compiled_path()+ game_id = self._game_id_for_compiled(selected) if selected else None+ if selected.parent.name == "games" and not game_id:+ self._set_build_state("Unknown standalone game", selected.name, error=True)+ return+ cmd = [sys.executable, "-u", str(BUILD_SCRIPT), "--watch", "-j2"]+ if game_id:+ # Only this game's sources compile; no full NumPlay launcher rebuild.+ cmd.extend(["--game", game_id])+ else:+ cmd.append("--launcher-only")+ if selected.name not in ("NumPlay-French.nwa", "NumPlay-Chinese.nwa"):+ cmd.append("--skip-languages")flags = subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0try:self.build_process = subprocess.Popen(cmd, cwd=str(REPO_ROOT),@@ -2342,11 +2436,11 @@ class CalculatorSkinApp(LiveApp):elif "Stable live-emulator input:" in line:self._builder_has_error = Falseself._builder_ready = True- self._set_build_state("Built", "Reloading dist/live/NumPlay.nwa", busy=False)- if self.mode_var.get() == "live" and LIVE_NWA.is_file():+ self._set_build_state("Built", f"Reloading {self._compiled_choice.get()}", busy=False)+ if self.mode_var.get() == "live" and self._selected_compiled_path().is_file():# Emulation runs in its own thread and will stop gracefully# before loading the atomically replaced file.- self.load(LIVE_NWA)+ self.load(self._selected_compiled_path())elif ("Build failed;" in line or "Initial build failed" in line or"Windows build failed:" in line):self._builder_has_error = True@@ -2408,7 +2502,7 @@ class CalculatorSkinApp(LiveApp):win.protocol("WM_DELETE_WINDOW", close)def _open_dist(self):- path = REPO_ROOT / "dist"+ path = REPO_ROOT / "build" / "compiled"path.mkdir(parents=True, exist_ok=True)if os.name == "nt":os.startfile(str(path))@@ -2422,7 +2516,7 @@ class CalculatorSkinApp(LiveApp):if self.mode_var.get() == "live":if self._builder_busy or not self._builder_ready:return None- return LIVE_NWA+ return self._selected_compiled_path()return self.currentdef _update_upload_controls(self):@@ -3052,7 +3146,7 @@ def main():print("Tip: pip install tkinterdnd2 for .nwa drag-and-drop.")start_live = args.live or args.follow_newestif start_live and args.nwa:- print("[NumPlay] --live uses dist/live/NumPlay.nwa; ignoring the supplied single-file path.")+ print("[NumPlay] --live uses build/compiled/NumPlay.nwa; ignoring the supplied single-file path.")CalculatorSkinApp(root, None if start_live else args.nwa, args.nwlink,args.model, args.system, False, art,max_sleep_ms=args.max_sleep_ms, profile_speed=args.profile_speed,@@ -3060,5 +3154,20 @@ def main():root.mainloop()+++# Previous headless CLI flags continue to work with this single file.+def _run_headless_cli():+ options = ("--ms", "--keys", "--shots", "--gif", "--fps", "--out",+ "--storage", "--flash-start", "--ram-length", "--records",+ "--frames", "--profile")+ return "--headless" in sys.argv or any(arg.split("=", 1)[0] in options for arg in sys.argv[1:])++if __name__ == "__main__":- main()+ if _run_headless_cli():+ if "--headless" in sys.argv:+ sys.argv.remove("--headless")+ emu.main()+ else:+ main()diff --git a/tools/setup.py b/tools/setup.pyindex a4b1aa94..a39ecb00 100644--- a/tools/setup.py+++ b/tools/setup.py@@ -12,7 +12,7 @@ What it gets:- nwlink 1.0.0 (NumWorks' tool that turns a program into a .nwa app), with npm, from Node.js;- the Python packages of the tools and the emulator (Pillow, NumPy, pyelftools, Unicorn, zopfli).It needs Python 3.9 or newer and Node.js (https://nodejs.org) already installed, and GNU make (on macOS,-`xcode-select --install`; on Windows, see tools/build_windows.py). Rust is only needed for Tetris.+`xcode-select --install`; on Windows, see tools/build.py). Rust is only needed for Tetris."""import argparseimport hashlib@@ -119,7 +119,7 @@ def main():[sys.executable, "-c", f"import {m}"], capture_output=True).returncode]say(not missing, "Python packages (Pillow, NumPy, pyelftools, Unicorn, zopfli)",f"{sys.executable} -m pip install {' '.join(missing)}")- say(bool(shutil.which("make")), "GNU make", "macOS: xcode-select --install; Windows: tools/build_windows.py")+ say(bool(shutil.which("make")), "GNU make", "macOS: xcode-select --install; Windows: tools/build.py")say(bool(shutil.which("cargo")), "Rust (only for Tetris)", "https://rustup.rs, then: rustup target add ""thumbv7em-none-eabihf")diff --git a/tools/watch.py b/tools/watch.pydeleted file mode 100644index 46c19a61..00000000--- a/tools/watch.py+++ /dev/null@@ -1,110 +0,0 @@-#!/usr/bin/env python3-"""Builds NumPlay (or one game) again each time a source file is saved, for the live emulator on macOS and Linux-(tools/emu_live.py --live; on Windows it uses tools/build_windows.py). Each good build is copied to-dist/live/NumPlay.nwa in one step, so the emulator never reads half a file; a failed build keeps the last good one.-- python3 tools/watch.py NumPlay (build/NumPlay.nwa)- python3 tools/watch.py --game sokoban one game on its own (games/sokoban's Makefile)- python3 tools/watch.py --once build once and stop--Needs what `make` needs (python3 tools/setup.py gets it). It prints the lines the live emulator follows:-"Detected edits (...)", "Building: ...", "Stable live-emulator input: ...", "Build failed; ...",-"Watching for the next edit".-"""-import argparse-import os-import shutil-import subprocess-import sys-import time--ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-LIVE = os.path.join(ROOT, "dist", "live", "NumPlay.nwa")-WATCHED = (".c", ".h", ".S", ".s", ".rs", ".py", ".json", ".txt", ".png", ".inc", "Makefile")-SKIP = {"build", "output", "dist", "node_modules", "target", ".git", "__pycache__"}---def stamp(folders):- """The newest change time among the sources, and how many there are."""- newest, n = 0.0, 0- for top in folders:- for d, dirs, files in os.walk(top):- dirs[:] = [x for x in dirs if x not in SKIP]- for f in files:- if f.endswith(WATCHED):- try:- newest = max(newest, os.stat(os.path.join(d, f)).st_mtime)- n += 1- except OSError:- pass- return newest, n---def nwlink():- for p in (shutil.which("nwlink"), os.path.join(os.path.expanduser("~"), ".numplay", "node_modules", ".bin", "nwlink"),- os.path.join(ROOT, "games", "numdash", "node_modules", ".bin", "nwlink")):- if p and os.path.exists(p):- return p- return "npx --yes -- [email protected]"---def build(game, jobs):- if game:- target = ["make", "-C", os.path.join(ROOT, "games", game), "-j%d" % jobs, "NWLINK=" + nwlink()]- out = None- else:- target = ["make", "-C", ROOT, "-j%d" % jobs, "build/NumPlay.nwa", "NWLINK=" + nwlink()]- out = os.path.join(ROOT, "build", "NumPlay.nwa")- print("Building:", " ".join(target), flush=True)- r = subprocess.run(target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)- for line in r.stdout.splitlines()[-25:]:- print(" " + line, flush=True)- if game: # (where each game's Makefile puts its app)- found = [os.path.join(ROOT, "games", game, n) for n in ("output/%s.nwa" % game, "build/%s.nwa" % game,- "output/device/%s.nwa" % game)]- found = [p for p in found if os.path.exists(p)]- out = max(found, key=os.path.getmtime) if found else None- if r.returncode or not out or not os.path.exists(out):- print("Build failed; the last good app stays in dist/live/NumPlay.nwa", flush=True)- return False- os.makedirs(os.path.dirname(LIVE), exist_ok=True)- tmp = LIVE + ".part"- shutil.copyfile(out, tmp)- os.replace(tmp, LIVE)- print("Stable live-emulator input:", os.path.relpath(LIVE, ROOT), flush=True)- return True---def main():- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- ap.add_argument("--game", help="a game's folder in games/, built on its own")- ap.add_argument("--once", action="store_true", help="build once, don't watch")- ap.add_argument("-j", type=int, default=max(1, (os.cpu_count() or 2) // 2), help="make's jobs")- # (what tools/build_windows.py takes, so tools/emu_live.py can start either: these change nothing here)- ap.add_argument("--watch", action="store_true")- ap.add_argument("--launcher-only", action="store_true")- ap.add_argument("--skip-languages", action="store_true")- a, _ = ap.parse_known_args()- folders = [os.path.join(ROOT, "games", a.game)] if a.game else [os.path.join(ROOT, d) for d in ("launcher", "games")]- folders.append(os.path.join(ROOT, "games", "common"))- build(a.game, a.j)- if a.once:- return- last, count = stamp(folders)- print("Watching NumPlay source files (%d). Save a file to build again; Ctrl+C stops." % count, flush=True)- try:- while True:- time.sleep(1)- now, n = stamp(folders)- if now != last or n != count:- time.sleep(0.3) # (editors write in several steps)- last, count = stamp(folders)- print("Detected edits (%d files watched)" % count, flush=True)- build(a.game, a.j)- print("Watching for the next edit", flush=True)- except KeyboardInterrupt:- pass---if __name__ == "__main__":- sys.exit(main())