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.

NumBlocks: NumPlay module targets, Peaceful, starving by difficulty

Mason Chen87993aa2ac42
diff --git a/games/numblocks/Makefile b/games/numblocks/Makefile
index c1c0d2e3..5740eb0d 100644
--- a/games/numblocks/Makefile
+++ b/games/numblocks/Makefile
@@ -1,4 +1,4 @@
-# NumBlocks: Minecraft 1.8.8 on the NumWorks calculator.
+# NumBlocks: a game like Minecraft 1.8.8 for the NumWorks calculator (part of NumPlay).
# make output/numblocks.nwa
# make check link it like the calculator does (output/numblocks.bin)
# make host build/play: the game on a computer, for tests and screenshots
@@ -64,3 +64,19 @@ data:
clean:
$(Q) rm -rf $(BUILD_DIR) build
+
+# NumPlay launcher: the game as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(GAME) src/plat_eadk.c $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel \
+ $(GAME) src/plat_eadk.c -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(GAME) src/plat_eadk.c $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) for f in $(basename $(notdir $(GAME) src/plat_eadk.c)); do cc -std=gnu11 -O2 -fPIC \
+ $(shell $(NWLINK) eadk-cflags-simulator) -fno-math-errno -Dmain=np_numblocks_main -c src/$$f.c \
+ -o $(BUILD_DIR)/sim/$$f.o || exit 1; done
+ $(Q) ld -r $(BUILD_DIR)/sim/*.o -exported_symbol _np_numblocks_main -o $@
diff --git a/games/numblocks/src/main.c b/games/numblocks/src/main.c
index 4a007626..58c59c5d 100644
--- a/games/numblocks/src/main.c
+++ b/games/numblocks/src/main.c
@@ -37,6 +37,13 @@ static void loading(void) {
gui = GUI_LOADING;
render_frame(NULL, game_time);
world_follow(pl.x, pl.y, pl.z);
+ /* standing inside blocks (the world changed under a saved player): up to the first free space */
+ for (int k = 0; k < WORLD_H; k++) {
+ int x = (int)floorf(pl.x), y = (int)floorf(pl.y), z = (int)floorf(pl.z);
+ if (!(blk_flags[world_get(x, y, z)] & BF_SOLID) && !(blk_flags[world_get(x, y + 1, z)] & BF_SOLID)) break;
+ pl.y = (float)(y + 1);
+ world_follow(pl.x, pl.y, pl.z);
+ }
camera_reset();
gui = GUI_NONE;
in_world = true;
diff --git a/games/numblocks/src/player.c b/games/numblocks/src/player.c
index 7dc4f154..31cd86c3 100644
--- a/games/numblocks/src/player.c
+++ b/games/numblocks/src/player.c
@@ -161,8 +161,14 @@ void player_hurt(float amount, int kind) {
}
}
-/* FoodStats.onUpdate */
+/* FoodStats.onUpdate (and on Peaceful, EntityPlayer.onLivingUpdate's healing and feeding) */
+extern uint32_t game_time;
static void food_tick(void) {
+ if (opt.difficulty == 0) {
+ if (pl.health < 20 && game_time % 20 == 0) pl.health = pl.health + 1 > 20 ? 20 : pl.health + 1;
+ if (pl.food < 20 && game_time % 10 == 0) pl.food++;
+ return;
+ }
if (pl.exhaustion > 4) {
pl.exhaustion -= 4;
if (pl.sat > 0) pl.sat = pl.sat > 1 ? pl.sat - 1 : 0;
@@ -177,7 +183,8 @@ static void food_tick(void) {
}
} else if (pl.food <= 0) {
if (++pl.food_timer >= 80) {
- if (pl.health > 1) player_hurt(1, DMG_STARVE); /* Normal: down to half a heart */
+ /* starving: Easy stops at 5 hearts, Normal at half a heart, Hard kills */
+ if (pl.health > 10 || opt.difficulty == 3 || (pl.health > 1 && opt.difficulty == 2)) player_hurt(1, DMG_STARVE);
pl.food_timer = 0;
}
} else pl.food_timer = 0;
@@ -424,7 +431,6 @@ static void eat_done(void) {
}
/* EntityPlayer.trySleep: at night, with no monster within 8 blocks; the bed is the new spawn point */
-extern uint32_t game_time;
static void sleep_in(int x, int y, int z) {
int t = (int)(game_time % 24000);
if (t < 12541 || t > 23458) {
diff --git a/games/numblocks/tests/gen/arm/bench.c b/games/numblocks/tests/gen/arm/bench.c
new file mode 100644
index 00000000..2bac8517
--- /dev/null
+++ b/games/numblocks/tests/gen/arm/bench.c
@@ -0,0 +1,46 @@
+/* Bare-metal Cortex-M7 benchmark of the generator, run by bench.py in Unicorn.
+ * phase is bumped after each step so the runner can count instructions per step. */
+#include <stdint.h>
+#include <string.h>
+#include "../../../src/gen.h"
+
+volatile uint32_t phase;
+volatile uint32_t sums[64];
+volatile int32_t spawn[3];
+static uint8_t out[128 * 256];
+
+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++) {
+ 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;
+ }
+ /* a 32-high slab as the engine asks */
+ gen_slab(5, 5, 32, 32, out);
+ phase = phase + 1;
+ int x, y, z;
+ gen_spawn(&x, &y, &z);
+ spawn[0] = x, spawn[1] = y, spawn[2] = z;
+ phase = phase + 1;
+ return 0;
+}
+
+extern uint32_t _sidata, _sdata, _edata, _sbss, _ebss, _estack;
+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");
+}
+
+__attribute__((section(".isr_vector"), used)) const void *const vectors[2] = {&_estack, (void *)Reset_Handler};
diff --git a/games/numblocks/tests/gen/arm/bench.ld b/games/numblocks/tests/gen/arm/bench.ld
new file mode 100644
index 00000000..fe59d031
--- /dev/null
+++ b/games/numblocks/tests/gen/arm/bench.ld
@@ -0,0 +1,13 @@
+MEMORY {
+ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1M
+ RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 512K
+}
+_estack = ORIGIN(RAM) + LENGTH(RAM);
+ENTRY(Reset_Handler)
+SECTIONS {
+ .text : { KEEP(*(.isr_vector)) *(.text*) *(.rodata*) . = ALIGN(4); } > FLASH
+ .ARM.exidx : { *(.ARM.exidx*) } > FLASH
+ _sidata = LOADADDR(.data);
+ .data : { _sdata = .; *(.data*) . = ALIGN(4); _edata = .; } > RAM AT > FLASH
+ .bss : { _sbss = .; *(.bss*) *(COMMON) . = ALIGN(4); _ebss = .; } > RAM
+}
diff --git a/games/numblocks/tests/gen/arm/bench.py b/games/numblocks/tests/gen/arm/bench.py
new file mode 100644
index 00000000..7707da88
--- /dev/null
+++ b/games/numblocks/tests/gen/arm/bench.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+"""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 same
+convention as tools/emu.py). Also reports the deepest stack use (painted stack).
+Usage: bench.py [OUTDIR]"""
+import os
+import subprocess
+import sys
+
+from elftools.elf.elffile import ELFFile
+from 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
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SRC = os.path.join(HERE, "..", "..", "..", "src")
+OUT = sys.argv[1] if len(sys.argv) > 1 else "/tmp"
+ELF = 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"]
+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])
+subprocess.call(["arm-none-eabi-size", ELF])
+
+syms = {}
+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"]
+ 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)
+PAINT = 64 << 10
+uc.mem_write(STACK_TOP - PAINT, b"\xa5" * PAINT)
+vec = uc.mem_read(0x08000000, 8)
+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
+insns = 0
+marks = []
+last_phase = 0
+phase_addr = syms["phase"]
+while True:
+ uc.emu_start(pc | 1, 0xFFFFFFFF, count=CHUNK)
+ insns += CHUNK
+ pc = uc.reg_read(UC_ARM_REG_PC)
+ ph = int.from_bytes(uc.mem_read(phase_addr, 4), "little")
+ if ph != last_phase:
+ marks.append((ph, insns))
+ last_phase = ph
+ op = uc.mem_read(pc & ~1, 2)
+ if op == b"\x00\xbe": # bkpt
+ break
+ if insns > 20_000_000_000:
+ break
+
+prev = 0
+names = ["gen_init"] + [f"gen_slab 0..128 #{i}" for i in range(16)] + ["gen_slab 32..64", "gen_spawn"]
+slabs = []
+for i, (ph, n) in enumerate(marks):
+ d = n - prev
+ prev = n
+ name = names[i] if i < len(names) else f"phase {ph}"
+ if name.startswith("gen_slab 0"):
+ slabs.append(d)
+ print(f"{name:22s} {d / 1e6:8.2f} M insns ~{d / 216e3:7.1f} ms at 216 MHz")
+if slabs:
+ print(f"gen_slab 0..128: avg {sum(slabs) / len(slabs) / 216e3:.1f} ms, max {max(slabs) / 216e3:.1f} ms")
+st = uc.mem_read(STACK_TOP - PAINT, PAINT)
+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)])