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
NumPlay: NumBlocks in the launcher, after Buckshot Roulette
Mason Chen8e908a083af0
diff --git a/games/games.json b/games/games.jsonindex c3b872cf..6e976ffd 100644--- a/games/games.json+++ b/games/games.json@@ -86,6 +86,29 @@],"repo": "https://github.com/Mason363/NumPlay/tree/main/games/buckshot"},+ {+ "id": "numblocks",+ "title": "NumBlocks",+ "tagline": "Mine, craft, survive",+ "credit": "Inspired by Minecraft, not affiliated with Mojang",+ "top": "0x5D9C3A",+ "bottom": "0x2E2116",+ "accent": "0x7FCC4A",+ "records": [+ "numblocks.cfg",+ "nb1.nbw",+ "nb1r*"+ ],+ "reset": [+ "nb1.nbw",+ "nb1r*"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "app": "NumBlocks.nwa",+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/numblocks"+ },{"id": "portal","title": "Portal Returns",diff --git a/games/numblocks/docs/shot.png b/games/numblocks/docs/shot.pngnew file mode 100644index 00000000..16f868e6Binary files /dev/null and b/games/numblocks/docs/shot.png differdiff --git a/games/numblocks/tests/gen/arm/bench.c b/games/numblocks/tests/gen/arm/bench.cindex 2bac8517..d26d3be8 100644--- a/games/numblocks/tests/gen/arm/bench.c+++ b/games/numblocks/tests/gen/arm/bench.c@@ -9,18 +9,23 @@ volatile uint32_t sums[64];volatile int32_t spawn[3];static uint8_t out[128 * 256];+#ifndef NSIDE+#define NSIDE 4+#endif+int main(void) {gen_init(12345);phase = 1;int k = 0;- for (int cz = -2; cz < 2; cz++)- for (int cx = -2; cx < 2; cx++) {+ for (int cz = -2; cz < -2 + NSIDE; cz++)+ for (int cx = -2; cx < -2 + NSIDE; cx++) {gen_slab(cx, cz, 0, 128, out);uint32_t s = 0;for (unsigned i = 0; i < sizeof out; i++) s = s * 31 + out[i];sums[k++] = s;phase = phase + 1;}+#ifndef NO_SPAWN/* a 32-high slab as the engine asks */gen_slab(5, 5, 32, 32, out);phase = phase + 1;@@ -28,6 +33,7 @@ int main(void) {gen_spawn(&x, &y, &z);spawn[0] = x, spawn[1] = y, spawn[2] = z;phase = phase + 1;+#endifreturn 0;}@@ -36,9 +42,6 @@ void Reset_Handler(void) {uint32_t *s = &_sidata, *d = &_sdata;while (d < &_edata) *d++ = *s++;for (d = &_sbss; d < &_ebss;) *d++ = 0;- /* enable the FPU (CPACR) */- *(volatile uint32_t *)0xE000ED88 |= 0xFu << 20;- __asm volatile("dsb\n isb");main();for (;;) __asm volatile("bkpt #0");}diff --git a/games/numblocks/tests/gen/arm/bench.py b/games/numblocks/tests/gen/arm/bench.pyindex 7707da88..6e99126d 100644--- a/games/numblocks/tests/gen/arm/bench.py+++ b/games/numblocks/tests/gen/arm/bench.py@@ -2,37 +2,46 @@"""Builds bench.c + gen.c for the Cortex-M7 (-Os, hard float) and runs it in Unicorn,counting instructions per gen_slab call (1 instruction ~ 1 cycle at 216 MHz, the sameconvention as tools/emu.py). Also reports the deepest stack use (painted stack).-Usage: bench.py [OUTDIR]"""+Usage: bench.py [OUTDIR] [--side N] [--no-spawn] [--profile]"""import osimport subprocessimport sysfrom elftools.elf.elffile import ELFFilefrom unicorn import UC_ARCH_ARM, UC_MODE_MCLASS, UC_MODE_THUMB, Uc-from unicorn.arm_const import UC_ARM_REG_PC, UC_ARM_REG_SP+from unicorn.arm_const import UC_ARM_REG_LR, UC_ARM_REG_PC, UC_ARM_REG_SPHERE = os.path.dirname(os.path.abspath(__file__))SRC = os.path.join(HERE, "..", "..", "..", "src")-OUT = sys.argv[1] if len(sys.argv) > 1 else "/tmp"+args = [a for a in sys.argv[1:] if not a.startswith("--")]+OUT = args[0] if args else "/tmp"+SIDE = int(sys.argv[sys.argv.index("--side") + 1]) if "--side" in sys.argv else 4+if "--side" in sys.argv:+ args = [a for a in args if a != str(SIDE)]+NO_SPAWN = "--no-spawn" in sys.argv+PROFILE = "--profile" in sys.argvELF = os.path.join(OUT, "gen_bench.elf")CFLAGS = ["-mcpu=cortex-m7", "-mfpu=fpv5-sp-d16", "-mfloat-abi=hard", "-mthumb", "-Os", "-std=c11",- "-Wall", "-Wextra", "-Wdouble-promotion", "-ffunction-sections", "-fdata-sections"]+ "-Wall", "-Wextra", "-Wdouble-promotion", "-ffunction-sections", "-fdata-sections", "-g"]subprocess.check_call(["arm-none-eabi-gcc", *CFLAGS, "-nostartfiles", "--specs=nano.specs", "--specs=nosys.specs","-T", os.path.join(HERE, "bench.ld"), "-Wl,--gc-sections",- os.path.join(HERE, "bench.c"), os.path.join(SRC, "gen.c"), "-lm", "-o", ELF])+ os.path.join(HERE, "bench.c"), os.path.join(SRC, "gen.c"), "-lm", "-o", ELF,+ f"-DNSIDE={SIDE}"] + (["-DNO_SPAWN"] if NO_SPAWN else []))subprocess.call(["arm-none-eabi-size", ELF])syms = {}+funcs = []with open(ELF, "rb") as f:elf = ELFFile(f)for s in elf.get_section_by_name(".symtab").iter_symbols():syms[s.name] = s["st_value"]+ if s["st_info"]["type"] == "STT_FUNC" and s["st_size"]:+ funcs.append((s["st_value"] & ~1, s["st_size"], s.name))segs = [(p["p_paddr"], p.data()) for p in elf.iter_segments() if p["p_type"] == "PT_LOAD"]uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)uc.mem_map(0x08000000, 1 << 20)uc.mem_map(0x20000000, 512 << 10)-uc.mem_map(0xE0000000, 1 << 20)for addr, data in segs:uc.mem_write(addr, data)STACK_TOP = 0x20000000 + (512 << 10)@@ -43,15 +52,30 @@ sp = int.from_bytes(vec[0:4], "little")pc = int.from_bytes(vec[4:8], "little")uc.reg_write(UC_ARM_REG_SP, sp)-CHUNK = 21600 # 0.1 ms+CHUNK = 21600 if not PROFILE else 997 # 0.1 ms (prime-ish when sampling)+samples = {}+lrs = {}insns = 0marks = []last_phase = 0phase_addr = syms["phase"]while True:- uc.emu_start(pc | 1, 0xFFFFFFFF, count=CHUNK)+ try:+ uc.emu_start(pc | 1, 0xFFFFFFFF, count=CHUNK)+ except Exception as e:+ p = uc.reg_read(UC_ARM_REG_PC)+ if uc.mem_read(p & ~1, 2) == b"\x00\xbe": # bkpt: done+ ph = int.from_bytes(uc.mem_read(phase_addr, 4), "little")+ if ph != last_phase:+ marks.append((ph, insns))+ break+ print(f"fault {e} at pc {p:#x} after ~{insns} insns", file=sys.stderr)+ raiseinsns += CHUNKpc = uc.reg_read(UC_ARM_REG_PC)+ if PROFILE:+ samples[pc & ~1] = samples.get(pc & ~1, 0) + 1+ lrs[pc & ~1] = uc.reg_read(UC_ARM_REG_LR) & ~1ph = int.from_bytes(uc.mem_read(phase_addr, 4), "little")if ph != last_phase:marks.append((ph, insns))@@ -63,7 +87,7 @@ while True:breakprev = 0-names = ["gen_init"] + [f"gen_slab 0..128 #{i}" for i in range(16)] + ["gen_slab 32..64", "gen_spawn"]+names = ["gen_init"] + [f"gen_slab 0..128 #{i}" for i in range(SIDE * SIDE)] + ["gen_slab 32..64", "gen_spawn"]slabs = []for i, (ph, n) in enumerate(marks):d = n - prev@@ -79,5 +103,33 @@ used = PAINT - next(i for i in range(PAINT) if st[i] != 0xA5)print(f"deepest stack: {used} bytes")sums = uc.mem_read(syms["sums"], 64)print("checksums:", " ".join(f"{int.from_bytes(sums[i:i + 4], 'little'):08x}" for i in range(0, 64, 4)))-sp3 = uc.mem_read(syms["spawn"], 12)-print("spawn:", [int.from_bytes(sp3[i:i + 4], "little", signed=True) for i in range(0, 12, 4)])+if not NO_SPAWN:+ sp3 = uc.mem_read(syms["spawn"], 12)+ print("spawn:", [int.from_bytes(sp3[i:i + 4], "little", signed=True) for i in range(0, 12, 4)])++if PROFILE:+ import bisect+ funcs.sort()+ starts = [f[0] for f in funcs]+ per = {}+ total = sum(samples.values())+ for a, n in samples.items():+ i = bisect.bisect_right(starts, a) - 1+ name = funcs[i][2] if i >= 0 and a < funcs[i][0] + funcs[i][1] else f"{a:#x}"+ per[name] = per.get(name, 0) + n+ for name, n in sorted(per.items(), key=lambda t: -t[1])[:40]:+ print(f"{100 * n / total:6.2f}% {name}")+ # helpers (libgcc): attribute to the caller's source line through lr+ helper = {}+ for a, n in samples.items():+ i = bisect.bisect_right(starts, a) - 1+ if i >= 0 and funcs[i][2].startswith("__"):+ helper[lrs[a]] = helper.get(lrs[a], 0) + n+ top = sorted(helper.items(), key=lambda t: -t[1])[:25]+ if top:+ out = subprocess.run(["arm-none-eabi-addr2line", "-f", "-i", "-e", ELF] + [hex(a - 2) for a, _ in top],+ capture_output=True, text=True).stdout.split("\n")+ print("libgcc helper time by call site:")+ for k, (a, n) in enumerate(top):+ print(f"{100 * n / total:6.2f}% {a:#x}")+ print("\n".join(out))diff --git a/launcher/src/np.h b/launcher/src/np.hindex 38cadfad..2657dc1e 100644--- a/launcher/src/np.h+++ b/launcher/src/np.h@@ -57,7 +57,7 @@ typedef struct {uint32_t bss_size;const np_shot_t *shots;uint8_t nshots;- const char *const *records; /* save files, deleted on uninstall */+ const char *const *records; /* save files, deleted on uninstall (name*: all starting so) */const char *const *progress; /* the ones Reset deletes (not levels made in an editor) */uint32_t est_size; /* code and data, for the simulator */} np_game_t;diff --git a/launcher/src/storage.c b/launcher/src/storage.cindex 0cc22258..4a88b327 100644--- a/launcher/src/storage.c+++ b/launcher/src/storage.c@@ -5,11 +5,49 @@#include "np.h"#include "../../games/common/epsilon_files.h"-bool np_storage_delete(const char *name) { return ef_remove(name); }+/* A name ending with '*' stands for every record that starts with the rest+ * (a game that keeps its world in many records, like NumBlocks). */+static int prefix_len(const char *name) {+ int n = (int)strlen(name);+ return n > 0 && name[n - 1] == '*' ? n - 1 : -1;+}++/* the name of the first record starting with `p` (n bytes) into out, false if none */+static bool first_with_prefix(const char *p, int n, char *out, uint32_t size) {+ ef_fs_t fs;+ if (!ef_open(&fs)) return false;+ int end = ef_end(&fs);+ for (uint32_t at = 0; end >= 0 && (int)at < end; at += ef_rd16(fs.buf + at)) {+ const char *r = (const char *)fs.buf + at + 2;+ if (strncmp(r, p, (size_t)n)) continue;+ uint32_t k = 0;+ while (r[k] && k < size - 1) out[k] = r[k], k++;+ out[k] = 0;+ return true;+ }+ return false;+}++bool np_storage_delete(const char *name) {+ int n = prefix_len(name);+ if (n < 0) return ef_remove(name);+ char rec[64];+ while (first_with_prefix(name, n, rec, sizeof rec))+ if (!ef_remove(rec)) return false;+ return true;+}uint32_t np_storage_record_size(const char *name) {uint32_t len = 0;- return ef_read(name, &len) ? len : 0;+ if (prefix_len(name) < 0) return ef_read(name, &len) ? len : 0;+ /* every record with the prefix */+ ef_fs_t fs;+ if (!ef_open(&fs)) return 0;+ int end = ef_end(&fs), n = prefix_len(name);+ uint32_t total = 0;+ for (uint32_t at = 0; end >= 0 && (int)at < end; at += ef_rd16(fs.buf + at))+ if (!strncmp((const char *)fs.buf + at + 2, name, (size_t)n)) total += ef_rd16(fs.buf + at);+ return total;}bool np_reset_game(int game) {diff --git a/tests/test_games.py b/tests/test_games.pyindex 226dca4a..7d53746e 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -101,6 +101,11 @@ GAMES = {"championisland": ("ChampionIsland.nwa", "champion.sav",presses((2000, "up", 1500)) + every(4000, 9000, 700, "ok"), 11000,presses((2000, "up", 400)), 4000),+ # Singleplayer, Create New World (Survival, a random seed), walk; then Play Selected World+ "numblocks": ("NumBlocks.nwa", "nb1.nbw",+ presses((3000, "ok"), (3600, "ok"), (4200, "down"), (4500, "down"), (4800, "ok"),+ (7500, "ln", 1500)), 11000,+ presses((3000, "ok"), (3600, "ok")), 8000),# 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,@@ -160,6 +165,9 @@ CHECKS = {"minesweeper": (lambda v: len(v) == 276 and v[:2] == b"M\1" and v[32:34] == bytes([9, 9]) and v[28] == 10and v[34] == 5 and struct.unpack_from("<H", v, 14)[0] == 1,lambda v: v[32] == 9 and struct.unpack_from("<H", v, 14)[0] == 2),+ # the world's record: its magic, then (offset 16) the time of day, which goes on from one session to the next+ "numblocks": (lambda v: v[:4] == b"NBW1" and struct.unpack_from("<I", v, 16)[0] > 0,+ lambda v: v[:4] == b"NBW1" and struct.unpack_from("<I", v, 16)[0] > 60),"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off}