Skip to content

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.

Sonic: tests, fetch script and release entries

Mason363b382a48c79a8
diff --git a/Makefile b/Makefile
index 739287df..155e6ee4 100644
--- a/Makefile
+++ b/Makefile
@@ -24,7 +24,7 @@ RAM_LIMIT = 148928
# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
-BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies
+BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog
# the calculator's space for installed apps (0x90200000 to 0x903F0000 in its flash)
APP_SPACE = 2031616
# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has
@@ -214,6 +214,7 @@ APP_numpowder = games/numpowder/output/numpowder.nwa:NumPowder.nwa
APP_doom = games/doom/output/doom.nwa:Doom.nwa
APP_isaac = games/isaac/output/isaac.nwa:BindingOfIsaac.nwa
APP_pvz = games/pvz/output/pvz.nwa:PlantsVsZombies.nwa
+APP_sonic = games/sonic/output/sonic.nwa:SonicTheHedgehog.nwa
apps: | $(B)
$(MAKE) -C games/numdash build NWLINK="node node_modules/nwlink/bin/nwlink"
@@ -236,6 +237,7 @@ apps: | $(B)
$(MAKE) -C games/doom build NWLINK="$(NWLINK)"
$(MAKE) -C games/isaac build NWLINK="$(NWLINK)"
$(MAKE) -C games/pvz build NWLINK="$(NWLINK)"
+ $(MAKE) -C games/sonic build NWLINK="$(NWLINK)"
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))
@@ -258,6 +260,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_doom))) $(B)/apps/$(word 2,$(subst :, ,$(APP_doom)))
cp $(word 1,$(subst :, ,$(APP_isaac))) $(B)/apps/$(word 2,$(subst :, ,$(APP_isaac)))
cp $(word 1,$(subst :, ,$(APP_pvz))) $(B)/apps/$(word 2,$(subst :, ,$(APP_pvz)))
+ cp $(word 1,$(subst :, ,$(APP_sonic))) $(B)/apps/$(word 2,$(subst :, ,$(APP_sonic)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
@@ -321,5 +324,6 @@ clean:
-$(MAKE) -C games/doom clean
-$(MAKE) -C games/isaac clean
-$(MAKE) -C games/pvz clean
+ -$(MAKE) -C games/sonic clean
-cd games/tetris/tetris && $(CARGO) clean
-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/games/sonic/tests/check.py b/games/sonic/tests/check.py
new file mode 100644
index 00000000..9698b251
--- /dev/null
+++ b/games/sonic/tests/check.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+"""Checks of Sonic the Hedgehog on a computer (make test): the host build, with
+AddressSanitizer and UBSan, through the keys screen, the title, a new game, the
+saves and Continue, the attract demos (played back as the original plays them:
+no deaths), every act, every special stage, the continue screen and the ending.
+
+ python3 tests/check.py build/play [--quick]
+
+--quick skips the acts, special stages and ending (the longest part)."""
+import os
+import re
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+
+PLAY = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "build/play"
+QUICK = "--quick" in sys.argv
+ENV = dict(os.environ, ASAN_OPTIONS="detect_leaks=0", UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1")
+failures = []
+
+
+def run(frames, keys="", saves=None, args=(), what=""):
+ """Plays; returns the trace (a line a frame) and the last line."""
+ own = saves is None
+ if own:
+ saves = tempfile.mkdtemp(prefix="sonic_check_")
+ shots = tempfile.mkdtemp(prefix="sonic_shots_")
+ p = subprocess.run([PLAY, "--saves", saves, "--out", shots, "--frames", str(frames), "--trace"]
+ + (["--keys", keys] if keys else []) + list(args),
+ capture_output=True, text=True, env=ENV, timeout=1200)
+ shutil.rmtree(shots, ignore_errors=True)
+ if own:
+ shutil.rmtree(saves, ignore_errors=True)
+ if p.returncode or "runtime error" in p.stderr or "AddressSanitizer" in p.stderr:
+ failures.append(f"{what}: crashed or a sanitizer error\n{p.stderr[-2000:]}")
+ lines = p.stdout.splitlines()
+ return lines, lines[-1] if lines else ""
+
+
+def frames_of(lines):
+ """(frame, mode, zone, act, routine) of each traced frame."""
+ out = []
+ for l in lines:
+ m = re.match(r"f(\d+) mode ([0-9a-f]+) zone (\d+)\.(\d+) sonic -?\d+,-?\d+ r(\d+)", l)
+ if m:
+ out.append((int(m[1]), int(m[2], 16), int(m[3]), int(m[4]), int(m[5])))
+ return out
+
+
+def save(d):
+ p = os.path.join(d, "sonic.sav")
+ if not os.path.exists(p):
+ return None
+ v = open(p, "rb").read()
+ return {"ok": v[:4] == b"S1SV", "has_game": v[6], "zone": v[7], "act": v[8], "lives": v[9],
+ "frames": struct.unpack_from("<I", v, 28)[0]}
+
+
+def check(cond, msg):
+ if not cond:
+ failures.append(msg)
+
+
+# a new game: the keys screen (the first time only), the title, Green Hill Zone; Home saves and quits
+d = tempfile.mkdtemp(prefix="sonic_check_")
+lines, last = run(800, "30-31:a,400-401:a,560-700:right", saves=d, what="a new game")
+f = frames_of(lines)
+check(any(m == 0x0C and z == 0 for _, m, z, a, _ in f), f"the new game did not start Green Hill Zone: {last}")
+s = save(d)
+check(s and s["ok"] and s["has_game"] == 1 and s["zone"] == 0 and s["frames"] > 0, f"Home did not save the game: {s}")
+check(os.path.exists(os.path.join(d, "sonic_saves.py")), "no copy of the save in sonic_saves.py")
+t0 = s["frames"] if s else 0
+
+# next time: no keys screen, the title offers Continue, which goes back to the act
+lines, last = run(700, "380-381:a,440-441:a", saves=d, what="Continue")
+f = frames_of(lines)
+check(f and f[0][1] != 0x0C, "the keys screen came back")
+check(any(m == 0x0C and z == 0 for _, m, z, a, _ in f), f"Continue did not go back to Green Hill Zone: {last}")
+s = save(d)
+check(s and s["frames"] > t0, f"the time played did not go on: {s} (before {t0})")
+
+# the copy in the Python script brings the save back when the file is gone
+os.remove(os.path.join(d, "sonic.sav"))
+run(10, saves=d, what="the save from its copy")
+s = save(d)
+check(s and s["has_game"] == 1, f"the save did not come back from sonic_saves.py: {s}")
+shutil.rmtree(d, ignore_errors=True)
+
+# the attract demos (Green Hill, Marble, Spring Yard, the Special Stage): the recorded buttons replayed,
+# Sonic does not die (a wrong object or physics step soon sends him into a badnik or a pit)
+d = tempfile.mkdtemp(prefix="sonic_check_")
+open(os.path.join(d, "sonic.sav"), "wb").write(b"S1SV\1\1" + bytes(26)) # (the keys screen seen)
+lines, last = run(10500, saves=d, what="the demos")
+f = frames_of(lines)
+demos = {z for _, m, z, a, _ in f if m == 0x08}
+check({0, 2, 4} <= demos, f"not every level demo played: zones {sorted(demos)}")
+check(any(m == 0x10 for _, m, z, a, _ in f), "the Special Stage demo did not play")
+deaths = [x for x in f if x[1] == 0x08 and x[4] == 6]
+check(not deaths, f"Sonic died in a demo: {deaths[:1]}")
+shutil.rmtree(d, ignore_errors=True)
+
+if not QUICK:
+ # every act, running right (invincible), every special stage, the continue screen and the ending
+ for z, acts in ((0, 3), (1, 4), (2, 3), (3, 3), (4, 3), (5, 3)):
+ for a in range(acts):
+ lines, last = run(900, "100-900:right,200-900:a", args=["--level", f"{z}.{a}", "--god"],
+ what=f"zone {z} act {a}")
+ f = frames_of(lines)
+ check(any(m == 0x0C and fz == z and fa == a for _, m, fz, fa, _ in f), f"zone {z} act {a} did not play")
+ for n in range(6):
+ lines, last = run(1500, "100-500:right,500-900:left,150-1500:a", args=["--level", f"7.{n}"],
+ what=f"special stage {n + 1}")
+ check(any(x[1] == 0x10 for x in frames_of(lines)), f"special stage {n + 1} did not play")
+ lines, last = run(900, "400-401:start", args=["--level", "9.2"], what="the continue screen")
+ check(frames_of(lines)[-1][1] == 0x0C, f"the continue screen did not go back to the game: {last}")
+ lines, last = run(3000, args=["--level", "8.6"], what="the good ending")
+ check(any(x[1] == 0x1C for x in frames_of(lines)), f"the ending did not go on to the credits: {last}")
+ lines, last = run(1500, args=["--level", "8.1"], what="the ending without the emeralds")
+
+for x in failures:
+ print("FAIL:", x)
+print("sonic: all checks passed" if not failures else f"sonic: {len(failures)} failed")
+sys.exit(1 if failures else 0)
diff --git a/games/sonic/tools/fetch.py b/games/sonic/tools/fetch.py
new file mode 100644
index 00000000..5e399b56
--- /dev/null
+++ b/games/sonic/tools/fetch.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+"""Gathers what the pack is made from, into REF (not committed): the Sonic Retro disassembly of
+Sonic the Hedgehog (github.com/sonicretro/s1disasm), at the commit the game was made from.
+
+ python3 -I tools/fetch.py REF
+ make data REF=REF/s1disasm
+
+It holds the game's art, mappings, animations, levels, object placement, palettes and demos as the
+disassembly keeps them; tools/pack.py reads them and the assembly source's tables."""
+import io
+import os
+import shutil
+import sys
+import urllib.request
+import zipfile
+
+REPO = "sonicretro/s1disasm"
+COMMIT = "15dfa3a6ee4c53aeb482233e493755c84b4f3479"
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit(__doc__)
+ ref = sys.argv[1]
+ dest = os.path.join(ref, "s1disasm")
+ if os.path.exists(os.path.join(dest, "sonic.asm")):
+ print(f"{dest}: already there")
+ return
+ url = f"https://codeload.github.com/{REPO}/zip/{COMMIT}"
+ print(f"fetching {url}")
+ data = urllib.request.urlopen(url, timeout=300).read()
+ tmp = dest + ".part"
+ shutil.rmtree(tmp, ignore_errors=True)
+ with zipfile.ZipFile(io.BytesIO(data)) as z:
+ z.extractall(tmp)
+ top = os.path.join(tmp, os.listdir(tmp)[0])
+ os.makedirs(ref, exist_ok=True)
+ shutil.move(top, dest)
+ shutil.rmtree(tmp, ignore_errors=True)
+ print(f"{dest}: ready")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_games.py b/tests/test_games.py
index 4530b755..0fec92a3 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -176,6 +176,11 @@ GAMES = {
"pvz": ("PlantsVsZombies.nwa", "pvzlevel.sav", presses((1500, "ok"), (2500, "ok"), (3500, "ok"), (12500, "1"),
(13000, "ok")), 16000,
presses((1500, "ok"), (2500, "ok"), (3500, "ok")), 9000),
+ # past the keys, the SEGA screen and the title: Green Hill Zone, running; Home keeps the act, and next time
+ # Continue goes back to it
+ "sonic": ("SonicTheHedgehog.nwa", "sonic.sav",
+ presses((1500, "ok"), (5500, "ok"), (7000, "ok"), (9000, "right", 6000)), 16000,
+ presses((5500, "ok"), (7000, "ok"), (9500, "right", 2000)), 13000),
# a level, its message, then play; then back to the level select
"portal": ("PortalReturns.nwa", "portal.sav",
presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,
@@ -206,7 +211,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"hollowknight": "hollowknight_saves.py", "finalearth2": "finalearth2_saves.py",
"numpowder": "numpowder_saves.py", "undertale": "undertale_saves.py", "subway": "subway_saves.py",
"fnaf": "fnaf_saves.py", "doom": "doom_saves.py", "isaac": "isaac_saves.py",
- "hillclimb": "hillclimb_saves.py", "pvz": "pvz_saves.py"}
+ "hillclimb": "hillclimb_saves.py", "pvz": "pvz_saves.py", "sonic": "sonic_saves.py"}
CHECKS = {
# the island remembers where Lucky was; after the reinstall, from the copy
"championisland": (lambda v: v[:3] == b"CI1" and b"PLAYER_LOC" in v,) * 2,
@@ -235,6 +240,10 @@ CHECKS = {
# goes on
"pvz": (lambda v: v[:4] == b"PVZL" and v[8] == 1 and struct.unpack_from("<I", v, 16)[0] > 0,
lambda v: v[:4] == b"PVZL" and v[8] == 1 and struct.unpack_from("<I", v, 16)[0] > 500),
+ # a game kept ("S1SV": has_game at 6, Green Hill at 7, the frames played at 28); after the reinstall, from the
+ # copy, it goes on
+ "sonic": (lambda v: v[:4] == b"S1SV" and v[6] == 1 and v[7] == 0 and struct.unpack_from("<I", v, 28)[0] > 0,
+ lambda v: v[:4] == b"S1SV" and v[6] == 1 and struct.unpack_from("<I", v, 28)[0] > 600),
# a simulation saved ("NPWD"); after the reinstall, from the copy, it goes on and is saved again
"numpowder": (lambda v: v[:4] == b"NPWD",) * 2,
# a run banked ("HCR1", runs at 212) with a best on the Countryside (at 48); after the reinstall, from the copy,
diff --git a/tools/release.py b/tools/release.py
index 158d0a48..844ce982 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -52,6 +52,9 @@ ALONE = {
"pvz": ("Plants vs. Zombies", "the whole Adventure, from the front lawn to the roof and Dr. Zomboss: 50 levels, 40 "
"plants, 24 zombies, Crazy Dave, his shop and the Almanac. Too big to share the calculator with NumPlay: "
"install it on its own"),
+ "sonic": ("Sonic the Hedgehog", "the whole 1991 game: Green Hill to Scrap Brain, the Final Zone, the Special "
+ "Stages and the six Chaos Emeralds, and the ending. Too big to share the calculator with NumPlay: install "
+ "it on its own"),
}
VARIANTS = [
("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),