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.

Add standalone Tower Block by Bobydeluxe

Bobydeluxe80873df9695d
diff --git a/README.md b/README.md
index 67eeae81..008a177e 100644
--- a/README.md
+++ b/README.md
@@ -87,6 +87,10 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
</tr>
</table>
+**[Tower Block](games/towerblock/README.md)** is also offered as a separate,
+English-only app by **Bobydeluxe**. Its README includes build and installation
+instructions.
+
## How to install
You need your calculator, its USB cable, and a computer with **Google Chrome** or **Microsoft Edge**. It takes about 2 minutes.
@@ -198,6 +202,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **[Tatone26](https://github.com/Tatone26/Numworks-games)**'s **All the Apps** inspired NumPlay's list of classics. Flappy Bird, Pac-Man, Snake, Connect Four, Solitaire and 2048 are written in C for NumPlay and keep its options, with no code copied from it. Tetris is Tatone26's own, which they released into the public domain, adapted for NumPlay.
- **[Gabriele Cirulli](https://github.com/gabrielecirulli/2048)** made 2048.
+- **[Bobydeluxe](https://github.com/Bobydeluxe)** made **[Tower Block](games/towerblock/README.md)**, including its English interface, procedural isometric artwork and stacking engine. Inspired by Tower Block; no original game assets are bundled.
- **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. Not affiliated with Google.
diff --git a/games/towerblock/.gitignore b/games/towerblock/.gitignore
new file mode 100644
index 00000000..16be8f21
--- /dev/null
+++ b/games/towerblock/.gitignore
@@ -0,0 +1 @@
+/output/
diff --git a/games/towerblock/Makefile b/games/towerblock/Makefile
new file mode 100644
index 00000000..188dc189
--- /dev/null
+++ b/games/towerblock/Makefile
@@ -0,0 +1,51 @@
+# Tower Block: English-only app and NumPlay module.
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+PYTHON ?= python3
+ARM_LD ?= arm-none-eabi-ld
+OBJCOPY = arm-none-eabi-objcopy
+PACKER = tools/compact_nwa.py tools/standalone.ld
+SRC = src/main.c src/physics.c src/save.c src/render.c
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+OBJECTS = $(patsubst src/%.c,output/%.o,$(SRC))
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device) -Os -Wall -Wextra -Werror
+CFLAGS += -fno-math-errno -fsingle-precision-constant -ffunction-sections -fdata-sections -fstack-usage
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fvisibility=internal
+LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable,--gc-sections,-e,main -flinker-output=nolto-rel
+
+.PHONY: build check module sim-module test clean
+build: output/towerblock.nwa
+output/%.o: src/%.c $(HEADERS) | output
+ $(CC) $(CFLAGS) -c $< -o $@
+output/icon.o: src/icon.png | output
+ $(NWLINK) png-icon-o $< $@
+output/icon-compact.o: output/icon.o $(PACKER)
+ $(PYTHON) tools/compact_nwa.py icon $< $@ --objcopy $(OBJCOPY)
+output/towerblock-debug.nwa: $(OBJECTS) output/icon-compact.o $(PACKER)
+ $(CC) $(CFLAGS) $(LINK) -Wl,-u,eadk_app_name,-u,eadk_app_icon,-u,eadk_api_level $(OBJECTS) output/icon-compact.o -lm -o output/standalone.o
+ $(PYTHON) tools/compact_nwa.py app output/standalone.o $@ --ld $(ARM_LD)
+output/towerblock.nwa: output/towerblock-debug.nwa $(PACKER)
+ $(PYTHON) tools/compact_nwa.py release $< $@ --objcopy $(OBJCOPY)
+module: output/module.o
+output/module.o: $(OBJECTS)
+ $(CC) $(CFLAGS) $(LINK) $^ -lm -o $@
+check: build
+ $(NWLINK) nwa-bin output/towerblock.nwa output/towerblock.bin --ram-length 107674
+ $(NWLINK) nwa-bin output/towerblock-debug.nwa output/towerblock-debug.bin --ram-length 107674
+ $(PYTHON) -c "from pathlib import Path; assert Path('output/towerblock.bin').read_bytes() == Path('output/towerblock-debug.bin').read_bytes(), 'Release compaction changed installed bytes'"
+output:
+ mkdir -p $@
+test: | output
+ $(PYTHON) tests/test_compact_nwa.py
+ $(HOST_CC) -std=c11 -O2 -Wall -Wextra -Werror -Isrc tests/test.c src/physics.c src/save.c src/render.c -lm -o output/test
+ cd output && ./test
+HOST_CC ?= cc
+sim-module: | output
+ mkdir -p output/sim
+ cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_towerblock_main -c src/main.c -o output/sim/main.o
+ cc -std=c11 -O2 -fPIC -c src/physics.c -o output/sim/physics.o
+ cc -std=c11 -O2 -fPIC -c src/save.c -o output/sim/save.o
+ cc -std=c11 -O2 -fPIC -c src/render.c -o output/sim/render.o
+ ld -r output/sim/*.o -exported_symbol _np_towerblock_main -o output/sim-module.o
+clean:
+ rm -rf output
diff --git a/games/towerblock/README.md b/games/towerblock/README.md
new file mode 100644
index 00000000..fbc6a10f
--- /dev/null
+++ b/games/towerblock/README.md
@@ -0,0 +1,102 @@
+# Tower Block
+
+Game made by **Bobydeluxe**.
+
+An original NumWorks implementation inspired by
+[Tower Block on Y8, by Sumalya](https://fr.y8.com/games/tower_block).
+The reference uses moving 3D slabs: place each one on the tower and the
+overhanging portion falls away. This version recreates that mechanic with
+original code and procedural isometric artwork. No original game assets or
+source code are included.
+
+![Title](docs/title.png)
+![A tower in play](docs/gameplay.png)
+
+The English interface uses a restrained night theme: a clear sky, geometric
+typography, an isometric tower, a horizontal title menu and compact side panels.
+During play, height, the personal record, brief placement feedback and key hints
+leave room for the tower. Studio and the guide keep the remaining options easy
+to find.
+
+## Play
+
+Install `TowerBlock.nwa` with a compatible NumWorks external-app installer.
+Open Tower Block from the calculator's Home menu after installation.
+
+| Key | Action |
+| --- | --- |
+| Left / Right | Choose a title-menu item |
+| OK / EXE | Select; start or resume motion; place the moving slab |
+| Back | Pause or return |
+| Home / On-Off | Save and exit |
+| Up / Down | Choose a pause or Studio item |
+
+Release the key between placements. The ready screen starts motion with one
+press; the next fresh press places the slab. Inputs during the short landing
+animation are ignored so a held key cannot drop the following slab.
+
+- **Build:** alternate between the two isometric axes and stack as high as
+ possible. Excess material is cut away. A completely missed slab ends the run.
+ Height is the number of slabs placed above the foundation.
+- **Perfects:** align within 1.5 world units to keep the whole slab. Every third
+ consecutive perfect restores up to two units on the current axis, capped at
+ the initial size. At least a quarter-unit of overlap must remain after a cut.
+- **Studio:** four palettes (Prism, Aurora, Ember, Mono), an optional alignment
+ guide and reduced-animation mode. Palettes are cosmetic and freely available.
+
+The current tower, placement phase, direction, personal best and preferences
+are saved. Returning from pause or reopening a save waits for a fresh start
+press. The title has three entries: **Build / Resume**, **Studio** and **Guide**.
+**Resume** continues the active tower. **New Build** from pause asks before
+replacing it. A full-storage exit offers Retry, Return, or an explicit unsaved
+exit.
+
+Practice has been removed. The new `TBK2` save imports old `TBK1` saves:
+normal towers resume with their original personal best, while former Practice
+towers become fresh normal games. The old Practice record is discarded and
+is never promoted to the normal personal best. Preferences and lifetime
+counters are retained. Older app versions cannot read `TBK2` saves.
+
+## Build
+
+Requires ARM GCC, Python 3, Node.js and nwlink 1.0.0:
+
+```sh
+make build
+make check
+
+# Optional build without Make, including Windows
+python tools/icon.py
+python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+```
+
+The Python builder also needs Pillow and pyelftools. It produces the standalone
+`output/TowerBlock.nwa`, an unstripped debug binary, an optional module object and four
+linked profiles with their sizes in `output/sizes.json`.
+The game-local standard-library Python packer groups standalone ELF sections and
+compresses the launcher icon losslessly. Installed flash is 14,248 bytes; the
+downloadable NWA is 20,160 bytes. Artwork and normal-run save compatibility
+are retained. Unused ARM mapping symbols are removed from the
+release transport file; the debug build keeps them for disassembly. The Python
+builder checks release/debug installed bytes on all four profiles.
+
+```sh
+make test
+python tests/arm.py --nwlink /path/to/nwlink
+python tests/test_compact_nwa.py
+```
+
+The host test creates the input trace and tall-tower fixture used by the ARM
+test. ARM tests require Unicorn, pyelftools and Pillow and reuse the repository's
+CPU emulator. See [VALIDATION.md](VALIDATION.md) for measured results and limits.
+
+## Resources
+
+The engine uses integer fixed-point coordinates, no heap and no full-screen
+framebuffer. Only the last 24 floors are kept for drawing, regardless of tower
+height. Three reusable falling fragments bound visual effects. RGB565 rendering
+uses a 5,120-byte strip buffer and clips polygon scanlines to dirty regions.
+Save payload: 384 bytes. Cosmetic falling fragments are intentionally omitted
+from saves; the tower and next placement remain intact.
+
+Licensed under GPL-3.0-only, like NumPlay.
diff --git a/games/towerblock/VALIDATION.md b/games/towerblock/VALIDATION.md
new file mode 100644
index 00000000..1c5bdc77
--- /dev/null
+++ b/games/towerblock/VALIDATION.md
@@ -0,0 +1,51 @@
+# Local validation — 20 October 2026
+
+Practice removal: one normal mode and a three-entry title menu (Build/Resume,
+Studio, Guide).
+
+| Resource | Bytes |
+| --- | ---: |
+| Standalone NWA | 20,160 |
+| Installed flash | 14,248 |
+| Static RAM | 6,141 |
+| Deepest observed standalone ARM stack | 612 |
+| Save payload | 384 |
+
+Built with ARM GCC 15.2.1, nwlink 1.0.0, C11, `-Os`, LTO and warnings treated as
+errors. Release/debug builds install identical bytes on N0110, N0115/custom
+RAM, N0120 and Upsilon. Static RAM and installed size match on all profiles.
+
+- Old-save fixtures were generated and validated with the previous engine.
+ `TBK1` normal runs resume under `TBK2`; old Practice runs reset to a fresh
+ tower. An old Practice height/record of 20 leaves the normal best of 5
+ untouched. A separate zero-best case confirms it cannot create a personal
+ record either. Totals, attempts and preferences remain intact; deprecated
+ mode/Practice-record fields are zero in new saves.
+- Host tests: geometry, minimum overlap, perfect restoration, complete misses,
+ frozen game-over state, every single-byte corruption, malformed-but-valid
+ checksums, save round trips and migration without changing live state on
+ failure. Normal input reaches 3,000 floors in 146,760 ticks with a bounded
+ 24-floor history. Random input adds 120,000 ticks across 40 runs.
+- Dirty/full rendering matches pixel-for-pixel over 1,360 moving frames across
+ four palettes. Unchanged frames push no pixels; every staging buffer stays
+ within 320 x 8 RGB565 pixels.
+- Actual ARM app on all four profiles: old normal/Practice save import,
+ personal-best protection, three-entry title navigation, Studio/Guide access,
+ normal resume, restart cancellation, fresh/held input, pause freeze,
+ persistence, unrelated-file preservation and safe Home/On-Off exits.
+ Observed maximum draw time in input/save checks: 6 ms.
+- Scripted ARM keyboard play builds 12 floors; maximum observed draw time
+ 10 ms. A loaded 3,000-floor tower exercises maximum history, camera and
+ fragments; maximum observed draw time 13 ms. No draw exceeds 32 ms.
+- Studio settings persist. Full-storage failures remain interactive and allow
+ an explicit unsaved exit while preserving existing files. App RAM is cleared,
+ firmware RAM is intact and Home locking is balanced on exit.
+
+The isolated publication build is byte-identical to the locally validated
+app; its packing and four-profile ARM suites are repeated using the upstream
+repository helpers. Packaging tools are local to this game.
+
+Captures in `docs/title.png` and `docs/guide.png` come from the actual ARM app.
+Timings use the repository emulator model, not physical-device FPS. The full
+all-game/translated NumPlay build and a physical NumWorks playtest have not
+been repeated for this revision.
diff --git a/games/towerblock/docs/gameplay.png b/games/towerblock/docs/gameplay.png
new file mode 100644
index 00000000..a727b655
Binary files /dev/null and b/games/towerblock/docs/gameplay.png differ
diff --git a/games/towerblock/docs/guide.png b/games/towerblock/docs/guide.png
new file mode 100644
index 00000000..afa6160b
Binary files /dev/null and b/games/towerblock/docs/guide.png differ
diff --git a/games/towerblock/docs/title.png b/games/towerblock/docs/title.png
new file mode 100644
index 00000000..95ec235b
Binary files /dev/null and b/games/towerblock/docs/title.png differ
diff --git a/games/towerblock/src/icon.png b/games/towerblock/src/icon.png
new file mode 100644
index 00000000..11a8086e
Binary files /dev/null and b/games/towerblock/src/icon.png differ
diff --git a/games/towerblock/src/main.c b/games/towerblock/src/main.c
new file mode 100644
index 00000000..a6898347
--- /dev/null
+++ b/games/towerblock/src/main.c
@@ -0,0 +1,131 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <eadk.h>
+#include "tower.h"
+#include "render.h"
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Tower Block";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+#define KEY(k) (UINT64_C(1) << (k))
+#define SAVE_NAME "towerblock.sav"
+static tb_game game;
+static tb_stats stats;
+static uint8_t save_data[TB_SAVE_BYTES];
+static uint32_t last_checksum;
+static bool have_save,save_failed;
+uint32_t perf_frames,perf_max,perf_slow;
+
+static void push(int x,int y,int w,int h,const uint16_t *p) {
+ eadk_display_push_rect((eadk_rect_t){x,y,w,h},p);
+}
+static bool save(void) {
+ tb_encode(&game,&stats,save_data);
+ unsigned n=TB_SAVE_BYTES-4;
+ uint32_t hash=save_data[n]|(uint32_t)save_data[n+1]<<8|
+ (uint32_t)save_data[n+2]<<16|(uint32_t)save_data[n+3]<<24;
+ if(have_save&&hash==last_checksum&&!save_failed)return true;
+ save_failed=!ef_write(SAVE_NAME,save_data,TB_SAVE_BYTES);
+ if(!save_failed)last_checksum=hash,have_save=true;
+ return !save_failed;
+}
+int main(void) {
+ np_app_begin();
+ uint32_t len=0;const uint8_t *p=ef_read(SAVE_NAME,&len);
+ if(!tb_decode(&game,&stats,p,len))stats.guide=stats.motion=1;
+ unsigned view=TB_TITLE,selected=0,help_return=TB_TITLE,help_selection=2;
+ unsigned error_return=TB_TITLE,error_selection=0;
+ uint64_t previous=eadk_keyboard_scan(),stale=previous;
+ uint32_t now=(uint32_t)eadk_timing_millis(),tick_at=now,draw_at=now,save_at=now;
+ tb_invalidate();
+ for(;;) {
+ now=(uint32_t)eadk_timing_millis();
+ uint64_t keys=eadk_keyboard_scan();stale&=keys;
+ uint64_t active=keys&~stale,hit=active&~previous;previous=active;
+ bool ok=(hit&(KEY(eadk_key_ok)|KEY(eadk_key_exe)))!=0;
+ bool back=(hit&KEY(eadk_key_back))!=0;
+ bool next=(hit&(KEY(eadk_key_right)|KEY(eadk_key_down)))!=0;
+ bool prev=(hit&(KEY(eadk_key_left)|KEY(eadk_key_up)))!=0;
+ if(view!=TB_SAVE_ERROR&&(keys&(KEY(eadk_key_home)|KEY(eadk_key_on_off)))) {
+ if(save())break;
+ error_return=view==TB_PLAY?TB_READY:view;error_selection=selected;
+ view=TB_SAVE_ERROR;stale=keys;hit=0;ok=back=next=prev=false;
+ }
+ if(view==TB_PLAY) {
+ if(back)view=TB_PAUSE,selected=0,save();
+ else {
+ if(ok)tb_place(&game,&stats);
+ if(now-tick_at>4*TB_TICK_MS)tick_at=now-4*TB_TICK_MS;
+ while(now-tick_at>=TB_TICK_MS&&game.phase!=TB_OVER) {
+ tb_step(&game,&stats);tick_at+=TB_TICK_MS;
+ }
+ if(game.phase==TB_OVER)view=TB_RESULT,selected=0,save();
+ if(now-save_at>=5000)save(),save_at=now;
+ }
+ } else {
+ tick_at=now;
+ if(view==TB_TITLE) {
+ if(next)selected=(selected+1)%3;
+ if(prev)selected=(selected+2)%3;
+ if(back) {
+ if(save())break;
+ error_return=TB_TITLE;error_selection=selected;view=TB_SAVE_ERROR;
+ } else if(ok) {
+ if(selected==0) {
+ if(!game.present||game.phase==TB_OVER)tb_new(&game);
+ view=TB_READY;
+ } else if(selected==1)view=TB_STUDIO,selected=0;
+ else help_return=TB_TITLE,help_selection=2,view=TB_GUIDE;
+
+ }
+ } else if(view==TB_READY) {
+ if(back)view=TB_TITLE,selected=0;
+ else if(ok)tb_start(&game,&stats),view=TB_PLAY,tick_at=now;
+ } else if(view==TB_PAUSE) {
+ if(next)selected=(selected+1)%4;
+ if(prev)selected=(selected+3)%4;
+ if(back||(ok&&selected==0))view=TB_READY;
+ else if(ok&&selected==1) {
+ view=TB_CONFIRM;selected=0;
+ } else if(ok&&selected==2)help_return=TB_PAUSE,help_selection=2,view=TB_GUIDE;
+ else if(ok&&selected==3)view=TB_TITLE,selected=0;
+ } else if(view==TB_CONFIRM) {
+ if(next||prev)selected=!selected;
+ if(back||(ok&&selected==0))view=TB_PAUSE,selected=1;
+ else if(ok)tb_new(&game),view=TB_READY,selected=0;
+ } else if(view==TB_RESULT) {
+ if(next||prev)selected=!selected;
+ if(back||(ok&&selected))view=TB_TITLE,selected=0;
+ else if(ok)tb_new(&game),view=TB_READY,selected=0;
+ } else if(view==TB_STUDIO) {
+ if(hit&KEY(eadk_key_down))selected=(selected+1)%3;
+ if(hit&KEY(eadk_key_up))selected=(selected+2)%3;
+ if(back)view=TB_TITLE,selected=1;
+ else if(ok||(hit&(KEY(eadk_key_left)|KEY(eadk_key_right)))) {
+ if(selected==0)stats.palette=(uint8_t)((stats.palette+((hit&KEY(eadk_key_left))?3:1))%TB_PALETTES);
+ else if(selected==1)stats.guide=!stats.guide;
+ else stats.motion=!stats.motion;
+ save();
+ }
+ } else if(view==TB_GUIDE) {
+ if(ok||back)view=help_return,selected=help_selection;
+ } else if(view==TB_SAVE_ERROR) {
+ if(back)break;
+ if(ok&&save())break;
+ if(hit&KEY(eadk_key_one))view=error_return,selected=error_selection;
+ }
+ }
+ if(now-draw_at>=32||hit||perf_frames==0) {
+ uint32_t begin=(uint32_t)eadk_timing_millis();
+ tb_render(&game,&stats,view,selected,now,save_failed,push);
+ uint32_t spent=(uint32_t)eadk_timing_millis()-begin;
+ if(spent>perf_max)perf_max=spent;
+ if(spent>32)++perf_slow;
+ ++perf_frames;draw_at=now;
+ }
+ eadk_timing_msleep(4);
+ }
+ return np_app_end();
+}
diff --git a/games/towerblock/src/physics.c b/games/towerblock/src/physics.c
new file mode 100644
index 00000000..5099acaa
--- /dev/null
+++ b/games/towerblock/src/physics.c
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "tower.h"
+#include <string.h>
+
+static int absolute(int x) { return x<0?-x:x; }
+static void add(uint32_t *v) { if(*v<UINT32_MAX)++*v; }
+static void spawn(tb_game *g) {
+ g->axis=(uint8_t)(g->height&1u);
+ g->direction=(g->height&2u)?-1:1;
+ g->offset=-g->direction*TB_TRAVEL;g->phase=TB_MOVING;g->timer=0;
+}
+void tb_new(tb_game *g) {
+ memset(g,0,sizeof *g);g->present=1;g->count=1;
+ g->layer[0]=(tb_layer){-TB_SIZE/2,-TB_SIZE/2,TB_SIZE,TB_SIZE,0};
+ spawn(g);
+}
+void tb_start(tb_game *g,tb_stats *s) {
+ if(!g->present||g->phase==TB_OVER)return;
+ if(!g->started) { g->started=1;add(&s->attempts); }
+}
+unsigned tb_speed(const tb_game *g) {
+ return g->height<140?220+(unsigned)g->height*3:640;
+}
+static void shard(tb_game *g,const tb_layer *b,int direction) {
+ unsigned slot=0;
+ for(unsigned i=0;i<TB_SHARDS;++i) {
+ if(!g->shard[i].life) {slot=i;break;}
+ if(g->shard[i].life<g->shard[slot].life)slot=i;
+ }
+ g->shard[slot]=(tb_shard){b->x,b->z,-4*TB_Q,g->height==UINT32_MAX?g->height:g->height+1,
+ b->w,b->d,(int16_t)(g->axis?0:direction*100),(int16_t)(g->axis?direction*100:0),
+ -90,52,b->tone};
+}
+static int16_t bounded_origin(int v,int size) {
+ if(v<-TB_SIZE/2)v=-TB_SIZE/2;
+ if(v>TB_SIZE/2-size)v=TB_SIZE/2-size;
+ return (int16_t)v;
+}
+bool tb_place(tb_game *g,tb_stats *s) {
+ if(!g->present||!g->started||g->phase!=TB_MOVING)return false;
+ tb_layer b=g->layer[g->count-1],piece=b;
+ int offset=g->offset,loss=absolute(offset);
+ int size=g->axis?b.d:b.w;
+ b.tone=piece.tone=(uint8_t)((g->height%96+1)%96);
+ if(loss<=TB_SNAP) {
+ if(g->streak<999)++g->streak;
+ if(g->streak>g->peak)g->peak=g->streak;
+ add(&g->perfect);add(&s->perfect);g->result=TB_PERFECT;
+ if(g->streak%3==0&&size<TB_SIZE) {
+ int grow=TB_SIZE-size<2*TB_Q?TB_SIZE-size:2*TB_Q;
+ if(g->axis) { b.d=(int16_t)(b.d+grow);b.z=bounded_origin(b.z-grow/2,b.d); }
+ else { b.w=(int16_t)(b.w+grow);b.x=bounded_origin(b.x-grow/2,b.w); }
+ g->result=TB_GROW;
+ }
+ } else if(size-loss>=TB_MIN) {
+ g->streak=0;g->result=TB_CUT;
+ if(g->axis) {
+ b.d=(int16_t)(size-loss);piece.d=(int16_t)loss;
+ if(offset>0) {b.z=(int16_t)(b.z+offset);piece.z=(int16_t)(piece.z+size);}
+ else piece.z=(int16_t)(piece.z+offset);
+ } else {
+ b.w=(int16_t)(size-loss);piece.w=(int16_t)loss;
+ if(offset>0) {b.x=(int16_t)(b.x+offset);piece.x=(int16_t)(piece.x+size);}
+ else piece.x=(int16_t)(piece.x+offset);
+ }
+ shard(g,&piece,offset>0?1:-1);
+ } else {
+ /* A completely missed slab ends the run. */
+ if(g->axis)piece.z=(int16_t)(piece.z+offset);
+ else piece.x=(int16_t)(piece.x+offset);
+ shard(g,&piece,offset>0?1:-1);
+ g->streak=0;add(&g->misses);g->result=TB_MISS;g->message=60;
+ g->phase=TB_ENDING;g->timer=48;
+ return true;
+ }
+ if(g->count==TB_LAYERS)memmove(g->layer,g->layer+1,(TB_LAYERS-1)*sizeof(tb_layer));
+ else ++g->count;
+ g->layer[g->count-1]=b;
+ add(&g->height);add(&s->total);
+ if(g->height>s->best)s->best=g->height;
+ g->camera=g->height>8?-8*TB_Q:0;g->drop=-4*TB_Q;
+ g->phase=TB_SETTLING;g->timer=16;g->message=62;
+ return true;
+}
+static int approach(int value,int target) {
+ int d=target-value;
+ return absolute(d)<6?target:value+d/6;
+}
+void tb_step(tb_game *g,const tb_stats *s) {
+ if(!g->present||!g->started||g->phase==TB_OVER)return;
+ ++g->tick;
+ if(g->message)--g->message;
+ const tb_layer *top=&g->layer[g->count-1];
+ int target_x=top->x+top->w/2,target_z=top->z+top->d/2;
+ g->cam_x=s->motion?approach(g->cam_x,target_x):target_x;
+ g->cam_z=s->motion?approach(g->cam_z,target_z):target_z;
+ g->camera=s->motion?(int16_t)approach(g->camera,0):0;
+ g->drop=s->motion?(int16_t)approach(g->drop,0):0;
+ for(unsigned i=0;i<TB_SHARDS;++i) {
+ tb_shard *p=&g->shard[i];if(!p->life)continue;
+ --p->life;p->x+=p->vx;p->z+=p->vz;p->fall+=p->vy;p->vy+=48;
+ }
+ if(g->phase==TB_MOVING) {
+ g->offset+=g->direction*(int)tb_speed(g);
+ if(g->offset>TB_TRAVEL)g->offset=2*TB_TRAVEL-g->offset,g->direction=-1;
+ else if(g->offset<-TB_TRAVEL)g->offset=-2*TB_TRAVEL-g->offset,g->direction=1;
+ } else if(g->timer&&!--g->timer) {
+ if(g->phase==TB_ENDING)g->phase=TB_OVER;
+ else spawn(g);
+ }
+}
+bool tb_valid(const tb_game *g,const tb_stats *s) {
+ if(s->palette>=TB_PALETTES||s->guide>1||s->motion>1||s->perfect>s->total)return false;
+ if(g->present>1||g->started>1||g->phase>TB_OVER||g->axis>1||
+ g->result>TB_MISS||g->message>62||g->streak>999||g->peak>999||
+ g->streak>g->peak||g->peak>g->perfect||g->perfect>g->height||g->height>s->total)return false;
+ if(!g->present)return !g->started&&g->height==0;
+ if(g->count!=(g->height<TB_LAYERS-1?g->height+1:TB_LAYERS)||
+ (g->direction!=1&&g->direction!=-1)||g->offset<-TB_TRAVEL||g->offset>TB_TRAVEL||
+ g->cam_x<-TB_SIZE/2||g->cam_x>TB_SIZE/2||g->cam_z<-TB_SIZE/2||g->cam_z>TB_SIZE/2||
+ g->camera<-8*TB_Q||g->camera>0||g->drop<-4*TB_Q||g->drop>0||
+ g->height>s->best||
+ (g->height&&!g->started)||g->timer>48)return false;
+ if(g->phase==TB_MOVING&&g->timer)return false;
+ if((g->phase==TB_SETTLING||g->phase==TB_ENDING)&&(!g->started||!g->timer))return false;
+ if((g->phase==TB_OVER||g->phase==TB_ENDING)&&g->result!=TB_MISS)return false;
+ if(g->phase==TB_OVER&&g->timer)return false;
+ for(unsigned i=0;i<g->count;++i) {
+ const tb_layer *p=&g->layer[i];
+ if(p->w<TB_MIN||p->w>TB_SIZE||p->d<TB_MIN||p->d>TB_SIZE||p->tone>=96||
+ p->x<-TB_SIZE/2||p->z<-TB_SIZE/2||p->x+p->w>TB_SIZE/2||p->z+p->d>TB_SIZE/2)return false;
+ }
+ return true;
+}
diff --git a/games/towerblock/src/render.c b/games/towerblock/src/render.c
new file mode 100644
index 00000000..7f572cc0
--- /dev/null
+++ b/games/towerblock/src/render.c
@@ -0,0 +1,339 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Original procedural artwork. No sprites, framebuffer, or heap allocations.
+ */
+#include "render.h"
+#include <stdlib.h>
+#include <string.h>
+#define C(v) ((uint16_t)((((v) >> 8) & 0xF800) | (((v) >> 5) & 0x07E0) | (((v) >> 3) & 0x1F)))
+#define PAPER C(0x081927)
+#define INK C(0xEDF4EF)
+#define MUTED C(0x839FAE)
+#define GREEN C(0x74E8C3)
+#define RED C(0xFFA58F)
+static uint16_t band[320 * 8];
+static int x0, y0, x1, y1;
+static int16_t dirty_lo[30], dirty_hi[30];
+static bool initialized;
+static const tb_game *world;
+static const tb_stats *stats;
+static uint32_t clock_ms;
+static unsigned page, selection;
+static bool failed;
+
+/* Five columns, seven rows. One tiny alphabet for every page of the game. */
+static const uint8_t alphabet[][5] = {
+ {0x7e,0x11,0x11,0x11,0x7e},{0x7f,0x49,0x49,0x49,0x36},{0x3e,0x41,0x41,0x41,0x22},
+ {0x7f,0x41,0x41,0x22,0x1c},{0x7f,0x49,0x49,0x49,0x41},{0x7f,0x09,0x09,0x09,0x01},
+ {0x3e,0x41,0x49,0x49,0x7a},{0x7f,0x08,0x08,0x08,0x7f},{0x00,0x41,0x7f,0x41,0x00},
+ {0x20,0x40,0x41,0x3f,0x01},{0x7f,0x08,0x14,0x22,0x41},{0x7f,0x40,0x40,0x40,0x40},
+ {0x7f,0x02,0x0c,0x02,0x7f},{0x7f,0x04,0x08,0x10,0x7f},{0x3e,0x41,0x41,0x41,0x3e},
+ {0x7f,0x09,0x09,0x09,0x06},{0x3e,0x41,0x51,0x21,0x5e},{0x7f,0x09,0x19,0x29,0x46},
+ {0x46,0x49,0x49,0x49,0x31},{0x01,0x01,0x7f,0x01,0x01},{0x3f,0x40,0x40,0x40,0x3f},
+ {0x1f,0x20,0x40,0x20,0x1f},{0x3f,0x40,0x38,0x40,0x3f},{0x63,0x14,0x08,0x14,0x63},
+ {0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},
+ {0x3e,0x51,0x49,0x45,0x3e},{0x00,0x42,0x7f,0x40,0x00},{0x62,0x51,0x49,0x49,0x46},
+ {0x22,0x41,0x49,0x49,0x36},{0x18,0x14,0x12,0x7f,0x10},{0x27,0x45,0x45,0x45,0x39},
+ {0x3c,0x4a,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},{0x36,0x49,0x49,0x49,0x36},
+ {0x06,0x49,0x49,0x29,0x1e},
+ {0,0x08,0x3e,0x08,0},{0,0x08,0x08,0x08,0},{0,0x60,0x60,0,0},
+ {0,0x36,0x36,0,0},{0x20,0x10,0x08,0x04,0x02},{0,0,0x5f,0,0},
+ {0x08,0x14,0x22,0x41,0},{0x41,0x22,0x14,0x08,0},{0,0,0x7f,0,0}
+};
+static void mark(int x, int y, int w, int h) {
+ if (x < 0) w += x, x = 0;
+ if (y < 0) h += y, y = 0;
+ if (x + w > 320) w = 320 - x;
+ if (y + h > 240) h = 240 - y;
+ if (w <= 0 || h <= 0) return;
+ for (int row = y / 8; row <= (y + h - 1) / 8; ++row) {
+ if (x < dirty_lo[row]) dirty_lo[row] = (int16_t)x;
+ if (x + w > dirty_hi[row]) dirty_hi[row] = (int16_t)(x + w);
+ }
+}
+void tb_invalidate(void) { mark(0, 0, 320, 240); initialized = false; }
+static void pixel(int x, int y, uint16_t c) {
+ if (x >= x0 && x < x1 && y >= y0 && y < y1) band[(y - y0) * (x1 - x0) + x - x0] = c;
+}
+static void rect(int x, int y, int w, int h, uint16_t c) {
+ int l = x < x0 ? x0 : x, t = y < y0 ? y0 : y;
+ int r = x + w > x1 ? x1 : x + w, b = y + h > y1 ? y1 : y + h;
+ if (l >= r || t >= b) return;
+ /* Clip once per span instead of branching on every individual pixel. */
+ for (int j = t; j < b; ++j) {
+ uint16_t *p = band + (j-y0)*(x1-x0) + l-x0;
+ for (int i = l; i < r; ++i) *p++ = c;
+ }
+}
+static void line(int a, int b, int c, int d, uint16_t ink) {
+ if((a<x0&&c<x0)||(a>=x1&&c>=x1)||(b<y0&&d<y0)||(b>=y1&&d>=y1))return;
+ int dx = abs(c - a), sx = a < c ? 1 : -1, dy = -abs(d - b), sy = b < d ? 1 : -1, err = dx + dy;
+ for (;;) {
+ pixel(a, b, ink);
+ if (a == c && b == d) break;
+ int e = 2 * err;
+ if (e >= dy) err += dy, a += sx;
+ if (e <= dx) err += dx, b += sy;
+ }
+}
+static void text(int x, int y, const char *s, int scale, uint16_t ink) {
+ if (y >= y1 || y + 7 * scale <= y0) return;
+ for (; *s; ++s, x += 6 * scale) {
+ unsigned ch = (unsigned char)*s, i;
+ if (ch >= 'a' && ch <= 'z') ch -= 32;
+ if (ch >= 'A' && ch <= 'Z') i = ch - 'A';
+ else if (ch >= '0' && ch <= '9') i = ch - '0' + 26;
+ else {
+ static const char punctuation[] = "+-.:/!<>|";
+ const char *p = strchr(punctuation, (int)ch);
+ if (!p || ch == ' ') continue;
+ i = 36 + (unsigned)(p - punctuation);
+ }
+ for (int col = 0; col < 5; ++col) for (int row = 0; row < 7; ++row)
+ if (alphabet[i][col] & (1 << row)) rect(x + col * scale, y + row * scale, scale, scale, ink);
+ }
+}
+static int width(const char *s, int scale) { return (int)strlen(s) * 6 * scale - scale; }
+static void centered(int cx, int y, const char *s, int scale, uint16_t ink) {
+ text(cx - width(s, scale) / 2, y, s, scale, ink);
+}
+static void number(int x, int y, uint32_t value, int scale, uint16_t ink) {
+ char s[11]; int n = 0;
+ do { s[n++] = (char)('0' + value % 10); value /= 10; } while (value);
+ for (int i = 0; i < n / 2; ++i) { char c = s[i]; s[i] = s[n - i - 1]; s[n - i - 1] = c; }
+ s[n] = 0;
+ text(x, y, s, scale, ink);
+}
+
+static uint16_t blend(uint16_t a,uint16_t b,unsigned t) {
+ uint32_t x=(a|(uint32_t)a<<16)&0x07E0F81F,z=(b|(uint32_t)b<<16)&0x07E0F81F;
+ x=((x*(32-t)+z*t)>>5)&0x07E0F81F;return (uint16_t)(x|x>>16);
+}
+static uint16_t accent(void) {
+ static const uint16_t colors[]={GREEN,C(0x68DED6),C(0xFFC487),C(0xC5DDE5)};
+ return colors[stats->palette];
+}
+static uint16_t material(unsigned tone) {
+ static const uint16_t colors[TB_PALETTES][4]={
+ {C(0x69DEBF),C(0x7BA6ED),C(0xC29CEB),C(0xF0ACAD)},
+ {C(0x42CFCE),C(0x81DF9B),C(0x608DE9),C(0xB1ACF2)},
+ {C(0xF2CB83),C(0xED9B79),C(0xCA799C),C(0xDEAA86)},
+ {C(0xBBD5DE),C(0x83AAB7),C(0xD4E5DF),C(0x7096A9)}
+ };
+ tone%=96;return blend(colors[stats->palette][tone/24],colors[stats->palette][(tone/24+1)%4],tone%24*32/24);
+}
+static void background(void) {
+ for(int y=y0;y<y1;++y)rect(0,y,320,1,blend(C(0x071524),C(0x204757),(unsigned)(y*21/240)));
+}
+typedef struct {int x,y;} point;
+static void polygon(const point p[4],uint16_t color) {
+ int top=p[0].y,bottom=top,left=p[0].x,right=left;
+ for(unsigned i=1;i<4;++i) {
+ if(p[i].y<top)top=p[i].y;
+ if(p[i].y>bottom)bottom=p[i].y;
+ if(p[i].x<left)left=p[i].x;
+ if(p[i].x>right)right=p[i].x;
+ }
+ if(top>=y1||bottom<y0||left>=x1||right<x0)return;
+ if(top<y0)top=y0;
+ if(bottom>=y1)bottom=y1-1;
+ for(int y=top;y<=bottom;++y) {
+ int lo=10000,hi=-10000;
+ for(unsigned i=0;i<4;++i) {
+ point a=p[i],b=p[(i+1)&3];
+ if(a.y>b.y) {point t=a;a=b;b=t;}
+ if(y<a.y||y>b.y)continue;
+ if(a.y==b.y) {
+ if(a.x<lo)lo=a.x;
+ if(b.x<lo)lo=b.x;
+ if(a.x>hi)hi=a.x;
+ if(b.x>hi)hi=b.x;
+ } else {
+ int x=a.x+(b.x-a.x)*(y-a.y)/(b.y-a.y);
+ if(x<lo)lo=x;
+ if(x>hi)hi=x;
+ }
+ }
+ if(hi>=lo)rect(lo,y,hi-lo+1,1,color);
+ }
+}
+static int scene_x,scene_y,zoom;
+static int32_t camera_x,camera_z;
+static point project(int32_t x,int32_t z,int offset) {
+ return (point){scene_x+(int)((x-z-camera_x+camera_z)*zoom/(TB_Q*256)),
+ scene_y+(int)((x+z-camera_x-camera_z)*zoom/(TB_Q*512))+offset};
+}
+static void slab(int32_t x,int32_t z,int w,int d,int offset,unsigned tone,unsigned fade,bool wire) {
+ point p[4]={project(x,z,offset),project(x+w,z,offset),project(x+w,z+d,offset),project(x,z+d,offset)};
+ int min_y=p[0].y,max_y=p[0].y,min_x=p[0].x,max_x=p[0].x;
+ for(unsigned i=1;i<4;++i) {
+ if(p[i].y<min_y)min_y=p[i].y;
+ if(p[i].y>max_y)max_y=p[i].y;
+ if(p[i].x<min_x)min_x=p[i].x;
+ if(p[i].x>max_x)max_x=p[i].x;
+ }
+ if(min_y>=y1||max_y+8*zoom/256<y0||min_x>=x1||max_x<x0)return;
+ uint16_t top=blend(material(tone),C(0x183441),fade);
+ if(!wire) {
+ int h=8*zoom/256;if(h<2)h=2;
+ point left[4]={p[3],p[2],{p[2].x,p[2].y+h},{p[3].x,p[3].y+h}};
+ point right[4]={p[1],p[2],{p[2].x,p[2].y+h},{p[1].x,p[1].y+h}};
+ polygon(left,blend(top,C(0x021322),12));polygon(right,blend(top,C(0x021322),22));polygon(p,top);
+ uint16_t seam=blend(top,PAPER,25);
+ line(p[3].x,p[3].y+h,p[2].x,p[2].y+h,seam);
+ line(p[1].x,p[1].y+h,p[2].x,p[2].y+h,seam);
+ line(p[0].x,p[0].y,p[1].x,p[1].y,blend(top,INK,9));
+ line(p[0].x,p[0].y,p[3].x,p[3].y,blend(top,INK,6));
+ } else for(unsigned i=0;i<4;++i)line(p[i].x,p[i].y,p[(i+1)&3].x,p[(i+1)&3].y,blend(accent(),PAPER,15));
+}
+static void scene(void) {
+ const tb_game *g=world;
+ bool side=page==TB_PAUSE||page==TB_RESULT||page==TB_CONFIRM||page==TB_SAVE_ERROR;
+ scene_x=side?232:160;scene_y=188-(int)(g->height<8?g->height:8)*8;zoom=side?160:256;
+ camera_x=g->cam_x;camera_z=g->cam_z;
+ for(unsigned i=0;i<g->count;++i) {
+ const tb_layer *p=&g->layer[i];unsigned depth=g->count-1-i;
+ int offset=(int)depth*8+g->camera/TB_Q;
+ if(i+1u==(unsigned)g->count&&g->phase==TB_SETTLING&&g->result!=TB_MISS)offset+=g->drop/TB_Q;
+ slab(p->x,p->z,p->w,p->d,offset,p->tone,depth>6?(depth-6>12?12:depth-6):0,false);
+ }
+ if(g->present&&g->phase==TB_MOVING) {
+ const tb_layer *p=&g->layer[g->count-1];
+ int32_t x=p->x+(g->axis?0:g->offset),z=p->z+(g->axis?g->offset:0);
+ if(stats->guide) {
+ slab(p->x,p->z,p->w,p->d,-8,p->tone,0,true);
+ point target=project(p->x+p->w/2,p->z+p->d/2,-8);
+ point moving=project(x+p->w/2,z+p->d/2,-12);
+ for(int i=0;i<12;++i)if(i&1)pixel(target.x+(moving.x-target.x)*i/12,target.y+(moving.y-target.y)*i/12,accent());
+ }
+ slab(x,z,p->w,p->d,-12,(g->height%96+1)%96,0,false);
+ }
+ if(stats->motion)for(unsigned i=0;i<TB_SHARDS;++i) {
+ const tb_shard *p=&g->shard[i];if(!p->life)continue;
+ int relative=g->height>=p->level?(int)(g->height-p->level):-1;
+ slab(p->x,p->z,p->w,p->d,relative*8+p->fall/TB_Q+g->camera/TB_Q,p->tone,52-p->life>32?12:0,false);
+ }
+}
+static void demo(bool title_view) {
+ scene_x=title_view?244:250;scene_y=185;zoom=title_view?152:120;camera_x=camera_z=0;
+ for(int i=0;i<11;++i) {
+ int n=i*TB_Q;
+ slab(-TB_SIZE/2+n/3,-TB_SIZE/2+n/5,TB_SIZE-n,TB_SIZE-n/2,-i*6,(unsigned)i*5,0,false);
+ }
+ int n=stats->motion?(int)((clock_ms/32)%96):24;if(n>48)n=96-n;
+ slab(-TB_SIZE/2+(n-24)*TB_Q,-TB_SIZE/2,TB_SIZE-10*TB_Q,TB_SIZE-5*TB_Q,-72,57,0,false);
+}
+static unsigned digit_scale(uint32_t n) {return n<10000?3:n<1000000?2:1;}
+static void title(void) {
+ background();demo(true);
+ text(17,29,"TOWER",4,INK);text(17,63,"BLOCK",4,accent());
+ text(18,112,"BEST",1,MUTED);number(18,128,stats->best,stats->best<1000000?2:1,INK);
+ text(18,188,"BY BOBYDELUXE",1,MUTED);
+ rect(0,209,320,31,PAPER);
+ static const char *const names[]={"BUILD","STUDIO","GUIDE"};
+ for(unsigned i=0;i<3;++i) {
+ int x=20+(int)i*105;
+ const char *name=i==0&&world->present&&world->phase<TB_OVER&&world->started?"RESUME":names[i];
+ centered(x+35,220,name,1,i==selection?INK:MUTED);
+ if(i==selection)rect(x+5,234,60,2,accent());
+ }
+}
+static void play(void) {
+ const tb_game *g=world;background();scene();
+ rect(0,0,320,52,PAPER);
+ text(13,9,"HEIGHT",1,MUTED);number(13,23,g->height,digit_scale(g->height),INK);
+ text(259,10,"BEST",1,MUTED);number(259,26,stats->best,1,accent());
+ if(g->phase==TB_SETTLING&&g->message&&g->result>=TB_PERFECT&&g->result!=TB_MISS) {
+ if(g->result==TB_GROW)centered(160,64,"WIDTH RESTORED",1,accent());
+ else if(g->streak>1) {
+ text(128,64,"PERFECT",1,accent());text(178,64,"X",1,MUTED);number(190,64,g->streak,1,accent());
+ } else centered(160,64,"PERFECT",1,accent());
+ }
+ rect(0,219,320,21,PAPER);
+ text(13,230,"OK DROP",1,MUTED);text(247,230,"BACK PAUSE",1,MUTED);
+}
+static const char *const palettes[]={"PRISM","AURORA","EMBER","MONO"};
+static void studio(void) {
+ background();demo(false);
+ text(14,14,"STUDIO",3,INK);
+ static const char *const labels[]={"PALETTE","ALIGNMENT GUIDE","ANIMATIONS"};
+ for(unsigned i=0;i<3;++i) {
+ int y=74+(int)i*39;
+ text(15,y,labels[i],1,i==selection?accent():MUTED);
+ if(i==selection)rect(9,y,2,25,accent());
+ const char *value=i==0?palettes[stats->palette]:i==1?(stats->guide?"ON":"OFF"):(stats->motion?"FULL":"REDUCED");
+ text(15,y+14,"<",1,MUTED);text(31,y+14,value,1,INK);text(119,y+14,">",1,MUTED);
+ }
+ text(15,230,"ARROWS CHANGE",1,MUTED);text(253,230,"BACK",1,MUTED);
+}
+static void guide(void) {
+ background();text(15,15,"HOW TO PLAY",2,INK);
+ static const char *const steps[]={"DROP","STACK","PERFECT","GAME OVER"};
+ static const char *const body[]={"OK / EXE PLACES THE BLOCK.","OVERHANGS ARE CUT AWAY.","THREE IN A ROW RESTORE WIDTH.","A MISSED BLOCK ENDS THE RUN."};
+ for(unsigned i=0;i<4;++i) {
+ int y=51+(int)i*35;text(15,y,steps[i],1,accent());text(15,y+12,body[i],1,MUTED);
+ }
+ text(15,205,"BACK PAUSE | HOME SAVE AND EXIT",1,MUTED);
+ text(15,230,"OK / BACK RETURN",1,INK);
+}
+static void choice(int x,int y,const char *name,unsigned index) {
+ if(selection==index) {rect(x-7,y-5,123,23,accent());text(x,y+3,name,1,PAPER);}
+ else text(x,y+3,name,1,MUTED);
+}
+static void overlay(void) {
+ if(page==TB_READY) {
+ rect(0,191,320,49,PAPER);
+ text(14,200,world->started?"RESUME":"READY",2,INK);
+ text(15,226,world->started?"OK RESUME":"OK START",1,accent());text(264,226,"BACK",1,MUTED);
+ return;
+ }
+ if(page==TB_GUIDE) {guide();return;}
+ rect(0,0,147,240,PAPER);rect(146,12,1,216,accent());
+ if(page==TB_PAUSE) {
+ text(14,22,"PAUSED",2,INK);text(15,48,failed?"SAVE FAILED":"TOWER BLOCK",1,failed?RED:MUTED);
+ choice(18,82,"RESUME",0);choice(18,111,"NEW BUILD",1);choice(18,140,"GUIDE",2);choice(18,169,"TITLE",3);
+ text(15,228,"OK SELECT",1,MUTED);
+ } else if(page==TB_RESULT) {
+ text(14,21,"GAME OVER",2,RED);
+ text(15,71,"FINAL HEIGHT",1,MUTED);number(15,87,world->height,digit_scale(world->height),INK);
+ text(15,120,"PERFECT",1,MUTED);number(82,120,world->perfect,1,accent());
+ if(world->height&&world->height==stats->best)text(15,137,"PERSONAL BEST",1,accent());
+ choice(18,169,"BUILD AGAIN",0);choice(18,199,"TITLE",1);
+ text(15,229,"OK SELECT",1,MUTED);
+ } else if(page==TB_CONFIRM) {
+ text(14,21,"NEW",3,INK);text(14,49,"BUILD?",3,accent());
+ text(15,92,"THIS TOWER WILL",1,MUTED);text(15,106,"BE LEFT BEHIND.",1,MUTED);
+ text(15,129,"RECORDS STAY.",1,MUTED);
+ choice(18,166,"KEEP TOWER",0);choice(18,197,"START NEW",1);
+ text(15,229,"OK SELECT",1,MUTED);
+ } else if(page==TB_SAVE_ERROR) {
+ text(14,23,"SAVE",3,RED);text(14,52,"FAILED",3,RED);
+ text(15,92,"STORAGE IS FULL",1,MUTED);text(15,106,"OR UNAVAILABLE.",1,MUTED);
+ text(15,138,"OK RETRY SAVE",1,accent());text(15,163,"1 KEEP BUILDING",1,INK);
+ text(15,196,"BACK EXIT",1,RED);text(15,210,"WITHOUT SAVING",1,RED);
+ }
+}
+static unsigned old_page=99,old_selection,old_palette,old_guide,old_motion;
+static uint32_t old_tick,old_clock,old_height;
+static bool old_failed;
+void tb_render(const tb_game *g,const tb_stats *s,unsigned view,unsigned selected,uint32_t ms,bool save_failed,tb_push push) {
+ world=g;stats=s;page=view;selection=selected;clock_ms=ms;failed=save_failed;
+ bool full=!initialized||old_page!=view||old_selection!=selected||old_palette!=s->palette||old_guide!=s->guide||
+ old_motion!=s->motion||old_failed!=failed;
+ if(full)mark(0,0,320,240);
+ else if(view==TB_PLAY&&old_tick!=g->tick)mark(0,52,320,167);
+ else if(s->motion&&(view==TB_TITLE||view==TB_STUDIO)&&old_clock!=ms/64)mark(165,70,155,133);
+ if(g->height!=old_height)mark(0,0,320,52);
+ old_page=view;old_selection=selected;old_palette=s->palette;old_guide=s->guide;old_motion=s->motion;
+ old_tick=g->tick;old_clock=ms/64;old_height=g->height;old_failed=failed;
+ for(int row=0;row<30;++row) {
+ if(dirty_hi[row]<=dirty_lo[row])continue;
+ x0=dirty_lo[row];x1=dirty_hi[row];y0=row*8;y1=y0+8;rect(x0,y0,x1-x0,8,PAPER);
+ if(view==TB_TITLE)title();
+ else if(view==TB_STUDIO)studio();
+ else if(view==TB_GUIDE)guide();
+ else if(view==TB_PLAY||view==TB_READY) {play();if(view==TB_READY)overlay();}
+ else {background();scene();overlay();}
+ push(x0,y0,x1-x0,8,band);dirty_lo[row]=320;dirty_hi[row]=0;
+ }
+ initialized=true;
+}
diff --git a/games/towerblock/src/render.h b/games/towerblock/src/render.h
new file mode 100644
index 00000000..462db4ba
--- /dev/null
+++ b/games/towerblock/src/render.h
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef TOWER_RENDER_H
+#define TOWER_RENDER_H
+#include "tower.h"
+enum { TB_TITLE,TB_PLAY,TB_READY,TB_PAUSE,TB_STUDIO,TB_GUIDE,TB_RESULT,TB_CONFIRM,TB_SAVE_ERROR };
+typedef void (*tb_push)(int x,int y,int w,int h,const uint16_t *pixels);
+void tb_invalidate(void);
+void tb_render(const tb_game *g,const tb_stats *s,unsigned view,unsigned selected,
+ uint32_t ms,bool save_failed,tb_push push);
+#endif
diff --git a/games/towerblock/src/save.c b/games/towerblock/src/save.c
new file mode 100644
index 00000000..ac2403b6
--- /dev/null
+++ b/games/towerblock/src/save.c
@@ -0,0 +1,58 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "tower.h"
+#include <string.h>
+static void w16(uint8_t *p,uint32_t v) {p[0]=(uint8_t)v;p[1]=(uint8_t)(v>>8);}
+static unsigned r16(const uint8_t *p) {return p[0]|(unsigned)p[1]<<8;}
+static void w32(uint8_t *p,uint32_t v) {w16(p,v);w16(p+2,v>>16);}
+static uint32_t r32(const uint8_t *p) {return r16(p)|(uint32_t)r16(p+2)<<16;}
+static uint32_t checksum(const uint8_t *p) {
+ uint32_t h=2166136261u;for(unsigned i=0;i<TB_SAVE_BYTES-4;++i)h=(h^p[i])*16777619u;return h;
+}
+void tb_encode(const tb_game *g,const tb_stats *s,uint8_t out[TB_SAVE_BYTES]) {
+ memset(out,0,TB_SAVE_BYTES);memcpy(out,"TBK2",4);
+ w32(out+4,s->best);w32(out+12,s->total);
+ w32(out+16,s->perfect);w32(out+20,s->attempts);
+ out[24]=s->palette;out[25]=s->guide;out[26]=s->motion;
+ w32(out+28,g->height);w32(out+32,g->perfect);w32(out+36,g->misses);w32(out+40,g->tick);
+ w32(out+44,g->cam_x);w32(out+48,g->cam_z);w32(out+52,g->offset);
+ w16(out+56,g->camera);w16(out+58,g->drop);
+ out[60]=g->count;out[62]=g->phase;out[63]=(uint8_t)g->direction;
+ out[64]=g->started;out[65]=g->axis;w16(out+66,g->streak);w16(out+68,g->peak);
+ out[70]=g->timer;out[71]=g->result;out[72]=g->message;out[73]=g->present;
+ for(unsigned i=0;i<g->count&&i<TB_LAYERS;++i) {
+ const tb_layer *b=&g->layer[i];uint8_t *p=out+80+i*10;
+ w16(p,b->x);w16(p+2,b->z);w16(p+4,b->w);w16(p+6,b->d);p[8]=b->tone;
+ }
+ w32(out+TB_SAVE_BYTES-4,checksum(out));
+}
+bool tb_decode(tb_game *g,tb_stats *s,const uint8_t *p,size_t length) {
+ if(!p||length!=TB_SAVE_BYTES||(memcmp(p,"TBK1",4)&&memcmp(p,"TBK2",4))||r32(p+TB_SAVE_BYTES-4)!=checksum(p))return false;
+ bool legacy=p[3]=='1';
+ if(p[61]>(legacy?1:0)||(!legacy&&r32(p+8)))return false;
+ bool old_practice=legacy&&p[61]==1;
+ tb_game a;tb_stats b;memset(&a,0,sizeof a);memset(&b,0,sizeof b);
+ b.best=r32(p+4);b.total=r32(p+12);
+ b.perfect=r32(p+16);b.attempts=r32(p+20);
+ b.palette=p[24];b.guide=p[25];b.motion=p[26];
+ a.height=r32(p+28);a.perfect=r32(p+32);a.misses=r32(p+36);a.tick=r32(p+40);
+ a.cam_x=(int32_t)r32(p+44);a.cam_z=(int32_t)r32(p+48);a.offset=(int32_t)r32(p+52);
+ a.camera=(int16_t)r16(p+56);a.drop=(int16_t)r16(p+58);
+ a.count=p[60];a.phase=p[62];a.direction=(int8_t)p[63];
+ a.started=p[64];a.axis=p[65];a.streak=(uint16_t)r16(p+66);a.peak=(uint16_t)r16(p+68);
+ a.timer=p[70];a.result=p[71];a.message=p[72];a.present=p[73];
+ if(a.count>TB_LAYERS)return false;
+ for(unsigned i=0;i<a.count;++i) {
+ const uint8_t *v=p+80+i*10;
+ a.layer[i]=(tb_layer){(int16_t)r16(v),(int16_t)r16(v+2),(int16_t)r16(v+4),(int16_t)r16(v+6),v[8]};
+ }
+ /* Validate the old tower against its own record before discarding it.
+ * Never promote a Practice score into the normal personal best. */
+ tb_stats checked=b;
+ if(old_practice) {
+ if(a.phase>=TB_ENDING)return false;
+ checked.best=r32(p+8);
+ }
+ if(!tb_valid(&a,&checked))return false;
+ if(old_practice)tb_new(&a);
+ *g=a;*s=b;return true;
+}
diff --git a/games/towerblock/src/tower.h b/games/towerblock/src/tower.h
new file mode 100644
index 00000000..7693c50a
--- /dev/null
+++ b/games/towerblock/src/tower.h
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Original NumWorks implementation by Bobydeluxe.
+ */
+#ifndef TOWER_BLOCK_H
+#define TOWER_BLOCK_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define TB_Q 256
+#define TB_SIZE (72*TB_Q)
+#define TB_TRAVEL (80*TB_Q)
+#define TB_SNAP 384
+#define TB_MIN 64
+#define TB_LAYERS 24
+#define TB_SHARDS 3
+#define TB_SAVE_BYTES 384
+#define TB_TICK_MS 16
+#define TB_PALETTES 4
+
+enum { TB_MOVING,TB_SETTLING,TB_ENDING,TB_OVER };
+enum { TB_NONE,TB_CUT,TB_PERFECT,TB_GROW,TB_MISS };
+
+typedef struct { int16_t x,z,w,d;uint8_t tone; } tb_layer;
+typedef struct {
+ int32_t x,z,fall;
+ uint32_t level;
+ int16_t w,d,vx,vz,vy;
+ uint8_t life,tone;
+} tb_shard;
+typedef struct {
+ uint32_t best,total,perfect,attempts;
+ uint8_t palette,guide,motion;
+} tb_stats;
+typedef struct {
+ tb_layer layer[TB_LAYERS];
+ tb_shard shard[TB_SHARDS];
+ uint32_t height,perfect,misses,tick;
+ int32_t offset,cam_x,cam_z;
+ int16_t camera,drop;
+ uint16_t streak,peak;
+ int8_t direction;
+ uint8_t count,phase,present,started,axis,timer,result,message;
+} tb_game;
+
+void tb_new(tb_game *g);
+void tb_start(tb_game *g,tb_stats *s);
+bool tb_place(tb_game *g,tb_stats *s);
+void tb_step(tb_game *g,const tb_stats *s);
+unsigned tb_speed(const tb_game *g);
+bool tb_valid(const tb_game *g,const tb_stats *s);
+void tb_encode(const tb_game *g,const tb_stats *s,uint8_t out[TB_SAVE_BYTES]);
+bool tb_decode(tb_game *g,tb_stats *s,const uint8_t *data,size_t length);
+#endif
diff --git a/games/towerblock/tests/arm.py b/games/towerblock/tests/arm.py
new file mode 100644
index 00000000..f1d59612
--- /dev/null
+++ b/games/towerblock/tests/arm.py
@@ -0,0 +1,184 @@
+#!/usr/bin/env python3
+"""Run the actual Cortex-M7 application on NumPlay's four emulator profiles.
+
+python tests/arm.py --nwlink /path/to/nwlink
+Requires pyelftools, Unicorn and Pillow. Run the build and host test first.
+"""
+import argparse
+import io
+import json
+from pathlib import Path
+import struct
+import tempfile
+import types
+
+ROOT = Path(__file__).resolve().parents[1]
+OUT = ROOT / 'output'
+# The shared emulator leaves its ELF stream open; use an in-memory stream so
+# Windows can remove its temporary directory. Do not change the shared tool.
+emu_path = ROOT.parents[1] / 'tools/emu.py'
+emu = types.ModuleType('towerblock_emu')
+emu.__file__ = str(emu_path)
+emu.io = io
+source = emu_path.read_text().replace('ELFFile(open(elf, "rb"))',
+ 'ELFFile(io.BytesIO(open(elf, "rb").read()))')
+# Short CPU slices keep checkpoints within a few milliseconds even on a static
+# menu where thousands of sleep calls can otherwise fit in a single slice.
+source = source.replace('chunk = CPU_HZ // 1000', 'chunk = CPU_HZ // 10000')
+source = source.replace('self.now_ms += 1\n', 'self.now_ms += 0.1\n')
+# Stop on a completed sleep so static screens cannot skip checkpoints.
+source=source.replace(' next_frame = self.now_ms if frame_ms else None',
+ ' self.checkpoint = until_ms\n next_frame = self.now_ms if frame_ms else None')
+source=source.replace(' self.slept_ms += r0\n',
+ ' self.slept_ms += r0\n if self.now_ms >= self.checkpoint: uc.emu_stop()\n')
+exec(compile(source, str(emu_path), 'exec'), emu.__dict__)
+
+def record(name, value):
+ data = name.encode() + b'\0' + value
+ return struct.pack('<H', len(data)+2) + data
+
+def records(data):
+ result = {}
+ pos = 0
+ while True:
+ n, = struct.unpack_from('<H', data, pos)
+ if not n:
+ return result
+ assert n >= 4 and pos+n <= len(data)
+ end = data.index(0, pos+2, pos+n)
+ result[data[pos+2:end].decode()] = data[end+1:pos+n]
+ pos += n
+
+def presses(*items):
+ return [(t,t+d,emu.KEYS[k]) for t,k,d in items]
+
+def u32(c, name):
+ return struct.unpack('<I', c.uc.mem_read(c.symbols[name], 4))[0]
+
+def safe(c, exited=True):
+ assert c.exited == exited
+ assert not c.violations, c.violations
+ assert not c.firmware_ram_changes(), c.firmware_ram_changes()
+ if exited:
+ assert c.app_ram_clean() and c.locks == 0
+
+def menu_and_migration(nwa,nwlink,name):
+ """Three title entries; old Practice cannot inflate the personal best."""
+ storage=OUT/(name+'-migration-storage.bin')
+ for filename,height,started in [('legacy-practice-save.bin',0,0),('legacy-classic-save.bin',3,1)]:
+ old=(ROOT/'tests'/filename).read_bytes()
+ storage.write_bytes(record('towerblock.sav',old)+b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=nwlink);c.enable_checks()
+ c.keys=presses((500,'home',120));c.run(900);safe(c)
+ saved=records(c.storage_bytes())['towerblock.sav']
+ assert saved[:4]==b'TBK2' and saved[8:12]==b'\0'*4 and saved[61]==0
+ assert struct.unpack_from('<I',saved,4)[0]==5
+ assert struct.unpack_from('<I',saved,28)[0]==height and saved[64]==started
+ assert saved[12:27]==old[12:27]
+ # Resume an existing normal tower without resetting it.
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=nwlink);c.enable_checks()
+ c.keys=presses((400,'ok',80),(750,'home',120));c.run(1100);safe(c)
+ assert records(c.storage_bytes())['towerblock.sav']==saved
+ # A single Right selects Studio; Guide is the third and last title entry.
+ storage.write_bytes(b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=nwlink);c.enable_checks()
+ c.keys=presses((400,'right',80),(650,'ok',80),(950,'right',80),(1200,'back',80),
+ (1450,'right',80),(1700,'ok',80),(2200,'back',80),(2450,'right',80),
+ (2700,'ok',80),(3000,'ok',80),(3350,'back',80),(3650,'down',80),
+ (3900,'ok',80),(4200,'ok',80),(4500,'back',80),(4800,'home',120))
+ c.run(1950);c.save_png(str(OUT/(name+'-guide.png')))
+ c.run(4400);c.save_png(str(OUT/(name+'-pause.png')))
+ c.run(5200);safe(c);saved=records(c.storage_bytes())['towerblock.sav']
+ assert saved[24]==1 and saved[61]==0 and saved[64]==1
+ assert struct.unpack_from('<I',saved,4)[0]==0
+ assert struct.unpack_from('<I',saved,20)[0]==1
+ print(name+': three-item menu, resume, restart cancellation and old-record protection passed.',flush=True)
+
+
+def main():
+ ap=argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('--nwlink',default='nwlink')
+ a=ap.parse_args()
+ (OUT/'tmp').mkdir(exist_ok=True);tempfile.tempdir=str(OUT/'tmp')
+ nwa=str(OUT/'towerblock-debug.nwa');report=[]
+ sentinel=record('untouched.py',b'print(42)\n')
+ for name,model,system,ram in [('n0110','n0110','epsilon',148928),
+ ('n0115-custom','n0110','epsilon',133652),('n0120','n0120','epsilon',153676),
+ ('upsilon','n0110','upsilon',107674)]:
+ emu.configure(model,system,ram)
+ menu_and_migration(nwa,a.nwlink,name)
+ storage=OUT/(name+'-storage.bin');storage.write_bytes(sentinel+b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((0,'ok',300),(600,'ok',80),(1000,'ok',400),(1450,'back',90),
+ (2600,'ok',80),(2850,'exe',80),(3150,'ok',300),(3500,'home',120))
+ c.run(500);c.save_png(str(OUT/(name+'-title.png')))
+ c.run(1900);saved=records(c.storage_bytes())['towerblock.sav']
+ assert len(saved)==384 and saved[:4]==b'TBK2' and saved[64]==1
+ assert struct.unpack_from('<I',saved,28)[0]==0 # Held OK never auto-places.
+ frame=bytes(c.screen);c.run(2400)
+ assert bytes(c.screen)==frame and records(c.storage_bytes())['towerblock.sav']==saved
+ c.run(3450);performance={k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ c.run(3800);safe(c)
+ saved=records(c.storage_bytes())['towerblock.sav']
+ assert struct.unpack_from('<I',saved,28)[0]==1
+ assert struct.unpack_from('<I',saved,20)[0]==1
+ assert records(c.storage_bytes())['untouched.py']==b'print(42)\n'
+ stack=c.stack_used()
+ after=record('after.py',b'x=123\n');raw=c.storage_bytes()
+ end=len(sentinel)+2+len('towerblock.sav')+1+384
+ storage.write_bytes(raw[:end]+after+b'\0\0')
+ d=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);d.enable_checks()
+ d.keys=presses((500,'ok',80),(900,'ok',80),(1250,'onoff',120))
+ d.run(1500);safe(d);loaded=records(d.storage_bytes())
+ assert loaded['after.py']==b'x=123\n' and loaded['untouched.py']==b'print(42)\n'
+ assert struct.unpack_from('<I',loaded['towerblock.sav'],28)[0]==1
+ assert struct.unpack_from('<I',loaded['towerblock.sav'],20)[0]==1
+ report.append(dict(profile=name,stack_bytes=max(stack,d.stack_used()),**performance))
+ assert performance['perf_slow']==0,performance
+ print(json.dumps(report[-1]),flush=True)
+ # Real input through an entire reference flight; no test-only functions in
+ # the binary. 24 ms holds allow sampling around the display transfers.
+ emu.configure('n0110','epsilon',148928)
+ c=emu.Calculator(nwa,nwlink=a.nwlink);c.enable_checks()
+ taps=[int(t) for t in (OUT/'build-taps.txt').read_text().splitlines()[:12]]
+ c.keys=presses((600,'ok',80),(1000,'ok',80),
+ *((1000+t*16+8,'exe',24) for t in taps))
+ end=1000+taps[-1]*16+500
+ c.run(end);c.save_png(str(OUT/'arm-gameplay.png'))
+ gameplay_perf={k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ c.keys+=presses((int(c.now_ms)+100,'home',120));c.run(c.now_ms+500);safe(c)
+ flight=records(c.storage_bytes())['towerblock.sav']
+ floors=struct.unpack_from('<I',flight,28)[0]
+ assert floors>=8,(floors,flight[62])
+ assert gameplay_perf['perf_slow']==0,gameplay_perf
+ print('Keyboard gameplay: '+str(floors)+' floors; '+json.dumps(gameplay_perf),flush=True)
+ # Maximum history, falling cut pieces and camera movement on a slow model.
+ storage=OUT/'tall-storage.bin'
+ storage.write_bytes(record('towerblock.sav',(OUT/'tall-start.bin').read_bytes())+b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((500,'ok',80),(900,'ok',80),(1800,'exe',80),(3500,'home',120))
+ c.run(3200);tall_perf={k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ c.save_png(str(OUT/'arm-tall.png'));c.run(3800);safe(c)
+ assert tall_perf['perf_slow']==0,tall_perf
+ print('Tall tower: '+json.dumps(tall_perf),flush=True)
+ # Studio choices persist independently of a tower.
+ storage=OUT/'studio-storage.bin';storage.write_bytes(b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((400,'right',80),(900,'ok',80),(1200,'right',80),
+ (1500,'down',80),(1700,'right',80),(1950,'down',80),(2150,'right',80),(2500,'home',120))
+ c.run(2800);safe(c)
+ assert records(c.storage_bytes())['towerblock.sav'][24:27]==bytes([1,0,0])
+ # Refuse a failed exit cleanly and keep unrelated storage intact.
+ storage=OUT/'full-storage.bin';full=record('large.py',b'#'*(emu.STORAGE_SIZE-16))
+ storage.write_bytes(full+b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((500,'home',300),(1300,'ok',80),(1700,'back',80))
+ c.run(1200);safe(c,False);c.save_png(str(OUT/'arm-storage-full.png'))
+ assert c.storage_bytes()[:len(full)]==full
+ c.run(2000);safe(c)
+ (OUT/'arm-validation.json').write_text(json.dumps(dict(practice_removed=True,legacy_records=True,profiles=report,gameplay=gameplay_perf,
+ gameplay_floors=floors,tall=tall_perf),indent=2)+'\n')
+ print('ARM input, persistence, rendering, safe exits and full storage passed.')
+
+if __name__=='__main__':
+ main()
diff --git a/games/towerblock/tests/legacy-classic-save.bin b/games/towerblock/tests/legacy-classic-save.bin
new file mode 100644
index 00000000..c275ef1c
Binary files /dev/null and b/games/towerblock/tests/legacy-classic-save.bin differ
diff --git a/games/towerblock/tests/legacy-practice-save.bin b/games/towerblock/tests/legacy-practice-save.bin
new file mode 100644
index 00000000..1f6ecdfc
Binary files /dev/null and b/games/towerblock/tests/legacy-practice-save.bin differ
diff --git a/games/towerblock/tests/test.c b/games/towerblock/tests/test.c
new file mode 100644
index 00000000..ab472f6e
--- /dev/null
+++ b/games/towerblock/tests/test.c
@@ -0,0 +1,167 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "tower.h"
+#include "render.h"
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+static uint16_t screen[320*240],reference[320*240];
+static unsigned pushes;
+static void push(int x,int y,int w,int h,const uint16_t *p) {
+ assert(x>=0&&y>=0&&w>0&&h>0&&x+w<=320&&y+h<=240&&w*h<=320*8);
+ for(int j=0;j<h;++j)memcpy(screen+(y+j)*320+x,p+j*w,(size_t)w*2);
+ ++pushes;
+}
+static void shot(const char *name) {
+ FILE *f=fopen(name,"wb");assert(f);fprintf(f,"P6\n320 240\n255\n");
+ for(unsigned i=0;i<320*240;++i) {
+ unsigned c=screen[i];fputc(((c>>11)&31)*255/31,f);
+ fputc(((c>>5)&63)*255/63,f);fputc((c&31)*255/31,f);
+ }
+ fclose(f);
+}
+static void setup(tb_game *g,tb_stats *s) {
+ *s=(tb_stats){0};s->guide=s->motion=1;tb_new(g);tb_start(g,s);
+}
+static void settle(tb_game *g,const tb_stats *s) {
+ for(unsigned i=0;g->phase==TB_SETTLING&&i<50;++i)tb_step(g,s);
+ assert(g->phase==TB_MOVING);
+}
+static void geometry(void) {
+ tb_game g;tb_stats s;setup(&g,&s);
+ g.offset=10*TB_Q;assert(tb_place(&g,&s)&&g.height==1&&g.count==2);
+ tb_layer p=g.layer[1];assert(p.x==-26*TB_Q&&p.w==62*TB_Q&&p.d==TB_SIZE);
+ assert(g.shard[0].w==10*TB_Q&&g.shard[0].x==36*TB_Q&&g.axis==0);
+ assert(!tb_place(&g,&s));settle(&g,&s);assert(g.axis==1);
+ g.offset=-12*TB_Q;tb_place(&g,&s);p=g.layer[2];
+ assert(p.z==-36*TB_Q&&p.d==60*TB_Q&&p.w==62*TB_Q);
+ assert(g.shard[1].z==-48*TB_Q&&g.shard[1].d==12*TB_Q);assert(tb_valid(&g,&s));
+ /* Snap keeps the complete slab; every third perfect restores two units. */
+ for(unsigned i=0;i<3;++i) {
+ settle(&g,&s);g.offset=i==1?-TB_SNAP:TB_SNAP;assert(tb_place(&g,&s));
+ }
+ assert(g.streak==3&&g.perfect==3&&g.result==TB_GROW&&s.perfect==3);
+ assert(g.layer[g.count-1].w==64*TB_Q&&s.best==5);assert(tb_valid(&g,&s));
+ settle(&g,&s);g.offset=TB_TRAVEL;tb_place(&g,&s);
+ assert(g.phase==TB_ENDING&&g.height==5&&g.misses==1);
+ for(unsigned i=0;i<48;++i)tb_step(&g,&s);
+ assert(g.phase==TB_OVER&&!g.timer);tb_game frozen=g;
+ tb_step(&g,&s);assert(!memcmp(&frozen,&g,sizeof g)&&!tb_place(&g,&s));
+ /* Quarter-unit overlap remains playable; just below the minimum falls away. */
+ setup(&g,&s);g.offset=TB_SIZE-TB_MIN;tb_place(&g,&s);
+ assert(g.height==1&&g.layer[1].w==TB_MIN);assert(tb_valid(&g,&s));
+ setup(&g,&s);g.offset=TB_SIZE-TB_MIN+1;tb_place(&g,&s);assert(!g.height&&g.phase==TB_ENDING);
+}
+static void rehash(uint8_t *p) {
+ uint32_t h=2166136261u;
+ for(unsigned i=0;i<TB_SAVE_BYTES-4;++i)h=(h^p[i])*16777619u;
+ for(unsigned i=0;i<4;++i)p[TB_SAVE_BYTES-4+i]=(uint8_t)(h>>(8*i));
+}
+static void saves(void) {
+ tb_game g,h;tb_stats s,t;uint8_t data[TB_SAVE_BYTES],copy[TB_SAVE_BYTES];
+ setup(&g,&s);g.offset=7*TB_Q;tb_place(&g,&s);
+ tb_encode(&g,&s,data);assert(tb_decode(&h,&t,data,sizeof data));
+ assert(h.height==1&&h.phase==TB_SETTLING&&!h.shard[0].life);
+ tb_encode(&h,&t,copy);assert(!memcmp(data,copy,sizeof data));
+ tb_game before=h;tb_stats prior=t;
+ for(unsigned i=0;i<TB_SAVE_BYTES;++i) {
+ data[i]^=128;assert(!tb_decode(&h,&t,data,sizeof data));data[i]^=128;
+ assert(!memcmp(&before,&h,sizeof h)&&!memcmp(&prior,&t,sizeof t));
+ }
+ assert(!tb_decode(&h,&t,NULL,0)&&!tb_decode(&h,&t,data,sizeof data-1));
+ unsigned bad[]={24,60,61,62,65,88};
+ for(unsigned i=0;i<sizeof bad/sizeof bad[0];++i) {
+ memcpy(data,copy,sizeof data);data[bad[i]]=255;rehash(data);assert(!tb_decode(&h,&t,data,sizeof data));
+ }
+ memcpy(data,copy,sizeof data);data[63]=0;rehash(data);assert(!tb_decode(&h,&t,data,sizeof data));
+ memcpy(data,copy,sizeof data);memset(data+44,0,4);data[47]=128;rehash(data);assert(!tb_decode(&h,&t,data,sizeof data));
+ g=(tb_game){0};s=(tb_stats){0};s.guide=s.motion=1;
+ tb_encode(&g,&s,data);assert(tb_decode(&h,&t,data,sizeof data)&&!h.present);
+}
+static void reachability(void) {
+ tb_game g;tb_stats s,t;tb_game loaded;uint8_t data[TB_SAVE_BYTES];
+ setup(&g,&s);unsigned ticks=0;
+ FILE *f=fopen("build-taps.txt","w");assert(f);
+ while(g.height<3000) {
+ if(g.phase==TB_MOVING&&g.offset>=-TB_SNAP&&g.offset<=TB_SNAP) {
+ if(g.height<25)fprintf(f,"%u\n",ticks);
+ assert(tb_place(&g,&s));
+ }
+ tb_step(&g,&s);++ticks;
+ assert(tb_valid(&g,&s));
+ if(ticks%97==0) {tb_encode(&g,&s,data);assert(tb_decode(&loaded,&t,data,sizeof data));}
+ assert(g.phase!=TB_ENDING&&g.phase!=TB_OVER);
+ }
+ fclose(f);assert(g.count==TB_LAYERS&&g.streak==999&&s.best==3000);
+ tb_encode(&g,&s,data);f=fopen("tall-start.bin","wb");assert(f);
+ assert(fwrite(data,1,sizeof data,f)==sizeof data);fclose(f);
+ printf("Reached 3000 floors with normal input in %u ticks; fixed %u-layer history.\n",ticks,TB_LAYERS);
+ /* Unpredictable timing remains bounded across both axes and directions. */
+ for(unsigned run=0;run<40;++run) {
+ setup(&g,&s);
+ for(unsigned tick=0;tick<3000;++tick) {
+ if(tick%(13+run)==0)tb_place(&g,&s);
+ tb_step(&g,&s);assert(tb_valid(&g,&s));
+ if(g.phase==TB_OVER)tb_new(&g),tb_start(&g,&s);
+ }
+ }
+}
+static void pictures(void) {
+ tb_game g;tb_stats s;setup(&g,&s);
+ tb_invalidate();tb_render(&g,&s,TB_TITLE,0,400,false,push);shot("title.ppm");
+ for(unsigned n=0;n<15;++n) {
+ g.offset=n%4==0?4*TB_Q:0;tb_place(&g,&s);settle(&g,&s);
+ }
+ g.offset=12*TB_Q;
+ tb_render(&g,&s,TB_PLAY,0,400,false,push);shot("game.ppm");
+ tb_render(&g,&s,TB_PAUSE,0,400,false,push);shot("pause.ppm");
+ tb_render(&g,&s,TB_STUDIO,0,400,false,push);shot("studio.ppm");
+ tb_render(&g,&s,TB_GUIDE,0,400,false,push);shot("guide.ppm");
+ tb_render(&g,&s,TB_READY,0,400,false,push);shot("ready.ppm");
+ g.offset=TB_TRAVEL;tb_place(&g,&s);
+ for(unsigned i=0;i<48;++i)tb_step(&g,&s);
+ tb_render(&g,&s,TB_RESULT,0,400,false,push);shot("result.ppm");
+ tb_render(&g,&s,TB_CONFIRM,0,400,false,push);shot("confirm.ppm");
+ tb_render(&g,&s,TB_SAVE_ERROR,0,400,true,push);shot("storage.ppm");
+ for(unsigned palette=0;palette<TB_PALETTES;++palette) {
+ setup(&g,&s);s.palette=(uint8_t)palette;tb_invalidate();
+ for(unsigned i=0;i<340;++i) {
+ if(g.phase==TB_OVER)tb_new(&g),tb_start(&g,&s);
+ if(i%73==0)tb_place(&g,&s);
+ tb_step(&g,&s);tb_render(&g,&s,TB_PLAY,0,i*32,false,push);
+ memcpy(reference,screen,sizeof screen);tb_invalidate();tb_render(&g,&s,TB_PLAY,0,i*32,false,push);
+ assert(!memcmp(reference,screen,sizeof screen));
+ }
+ }
+ pushes=0;tb_render(&g,&s,TB_PLAY,0,339*32,false,push);assert(pushes==0);
+ s.motion=0;
+ for(unsigned view=0;view<2;++view) {
+ unsigned page=view?TB_STUDIO:TB_TITLE;
+ tb_render(&g,&s,page,0,400,false,push);pushes=0;
+ tb_render(&g,&s,page,0,1400,false,push);assert(pushes==0);
+ }
+}
+static void migration(void) {
+ tb_game g,h;tb_stats s,t;uint8_t old[TB_SAVE_BYTES],data[TB_SAVE_BYTES],copy[TB_SAVE_BYTES];
+ const char *names[]={"../tests/legacy-practice-save.bin","../tests/legacy-classic-save.bin"};
+ for(unsigned i=0;i<2;++i) {
+ FILE *f=fopen(names[i],"rb");assert(f);assert(fread(old,1,sizeof old,f)==sizeof old);fclose(f);
+ assert(!memcmp(old,"TBK1",4)&&tb_decode(&g,&s,old,sizeof old));
+ assert(tb_valid(&g,&s)&&s.best==5&&s.palette==2&&s.guide&&s.motion);
+ if(i==0)assert(g.height==0&&g.count==1&&!g.started&&g.present);
+ else assert(g.height==3&&g.started);
+ tb_encode(&g,&s,data);assert(!memcmp(data,"TBK2",4));
+ assert(data[8]==0&&data[9]==0&&data[10]==0&&data[11]==0&&data[61]==0);
+ assert(!memcmp(data+12,old+12,15)); /* totals, attempts, preferences */
+ assert(tb_decode(&h,&t,data,sizeof data)&&t.best==5);
+ tb_encode(&h,&t,copy);assert(!memcmp(data,copy,sizeof data));
+ if(i==0) {
+ memset(old+4,0,4);rehash(old);assert(tb_decode(&g,&s,old,sizeof old));
+ assert(s.best==0&&g.height==0); /* Practice must never become a personal best. */
+ }
+ }
+}
+int main(void) {
+ geometry();saves();migration();reachability();pictures();
+ puts("Geometry, saves, legacy record protection, playability and exact redraw tests passed.");return 0;
+}
diff --git a/games/towerblock/tests/test_compact_nwa.py b/games/towerblock/tests/test_compact_nwa.py
new file mode 100644
index 00000000..4874fac7
--- /dev/null
+++ b/games/towerblock/tests/test_compact_nwa.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Build-time LZ4 correctness and block-format boundary checks (stdlib only)."""
+import importlib.util
+from pathlib import Path
+import random
+import unittest
+
+SOURCE = Path(__file__).resolve().parents[1]/'tools/compact_nwa.py'
+SPEC = importlib.util.spec_from_file_location('compact_nwa', SOURCE)
+packing = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(packing)
+
+
+class CompressionTests(unittest.TestCase):
+ def check_block(self, raw):
+ block = packing.compress_lz4(raw)
+ self.assertEqual(packing.decode_lz4(block, len(raw)), raw)
+ # Walk token boundaries independently to check the LZ4 end constraints.
+ pos, decoded, last_match, final_literals = 0, 0, None, None
+ while pos < len(block):
+ token = block[pos]
+ pos += 1
+ literal = token >> 4
+ if literal == 15:
+ while block[pos] == 255:
+ literal += 255
+ pos += 1
+ literal += block[pos]
+ pos += 1
+ pos += literal
+ decoded += literal
+ if pos == len(block):
+ final_literals = literal
+ break
+ distance = int.from_bytes(block[pos:pos+2], 'little')
+ self.assertGreater(distance, 0)
+ self.assertLessEqual(distance, decoded)
+ pos += 2
+ match = (token & 15) + 4
+ if (token & 15) == 15:
+ while block[pos] == 255:
+ match += 255
+ pos += 1
+ match += block[pos]
+ pos += 1
+ last_match = decoded
+ decoded += match
+ self.assertEqual(decoded, len(raw))
+ self.assertIsNotNone(final_literals)
+ if last_match is not None:
+ self.assertGreaterEqual(final_literals, 5)
+ self.assertLessEqual(last_match, len(raw)-12)
+ return block
+
+ def test_lengths_and_random_literals(self):
+ rng = random.Random(6140)
+ for size in (0, 1, 4, 5, 11, 12, 15, 19, 20, 254, 255, 270, 1024):
+ with self.subTest(size=size):
+ self.check_block(bytes(rng.randrange(256) for _ in range(size)))
+
+ def test_long_overlapping_matches_and_extension_bytes(self):
+ for pattern in (b'A', b'\x00\xff', bytes(range(32))):
+ raw = (pattern*packing.ICON_BYTES)[:packing.ICON_BYTES]
+ with self.subTest(pattern=pattern):
+ self.assertLess(len(self.check_block(raw)), 150)
+
+ def test_repeated_pixel_rows(self):
+ row = b'\x08\xc5'*20 + b'\xff\xff'*15 + b'\x08\xc5'*20
+ self.check_block(row*56)
+
+ def test_known_raw_block(self):
+ self.assertEqual(packing.decode_lz4(b'\x13A\x01\x00\x50hello', 13), b'A'*8+b'hello')
+
+ def test_truncated_invalid_and_oversized_output(self):
+ for block, expected in ((b'',1),(b'\xf0',1),(b'\x10',1),
+ (b'\x00\x00\x00',4),(b'\x10A\x02\x00',5),
+ (b'\x10A',2),(b'\x13A\x01\x00\x50hello',12)):
+ with self.subTest(block=block):
+ with self.assertRaises(ValueError):
+ packing.decode_lz4(block,expected)
+
+ def test_repeatable_and_bounded_input(self):
+ raw = b'abcd'*100+b'last five'
+ self.assertEqual(self.check_block(raw),self.check_block(raw))
+ with self.assertRaises(ValueError):
+ packing.compress_lz4(b'x'*65536)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/games/towerblock/tools/build.py b/games/towerblock/tools/build.py
new file mode 100644
index 00000000..8b66b5fb
--- /dev/null
+++ b/games/towerblock/tools/build.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Optional portable standalone build; the normal NumPlay build uses Make.
+
+python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+Requires nwlink 1.0.0, ARM GCC, Pillow (icon generation), pyelftools (size report).
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import subprocess
+import sys
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('--toolchain', type=Path)
+ ap.add_argument('--nwlink', default='nwlink')
+ ap.add_argument('--node', default='node')
+ a = ap.parse_args()
+ out = ROOT / 'output'
+ out.mkdir(exist_ok=True)
+
+ def run(*args, capture=False):
+ return subprocess.run([str(v) for v in args], cwd=ROOT, check=True,
+ capture_output=capture, text=capture)
+
+ def tool(name):
+ binary = 'arm-none-eabi-' + name + ('.exe' if os.name == 'nt' else '')
+ return a.toolchain / binary if a.toolchain else binary
+
+ nw = [a.node, a.nwlink] if Path(a.nwlink).is_file() and not a.nwlink.endswith(('.exe', '.cmd')) else [a.nwlink]
+ flags = ['-std=c11', '-Os', '-Wall', '-Wextra', '-Werror', '-fno-math-errno',
+ '-fsingle-precision-constant', '-ffunction-sections', '-fdata-sections',
+ '-fstack-usage', '-fno-tree-loop-distribute-patterns', '-flto', '-fvisibility=internal']
+ flags += shlex.split(run(*nw, 'eadk-cflags-device', capture=True).stdout, posix=True)
+ # shlex on Windows may treat the include path's backslashes as escapes;
+ # nwlink prints forward slashes on Windows, so this remains portable.
+ objects = []
+ for source in ('main', 'physics', 'save', 'render'):
+ obj = out / (source + '.o')
+ run(tool('gcc'), *flags, '-c', ROOT / 'src' / (source + '.c'), '-o', obj)
+ objects.append(obj)
+ run(*nw, 'png-icon-o', ROOT / 'src/icon.png', out / 'icon.o')
+ packer = ROOT / 'tools/compact_nwa.py'
+ icon_report = json.loads(run(sys.executable, packer, 'icon', out / 'icon.o',
+ out / 'icon-compact.o', '--objcopy', tool('objcopy'), capture=True).stdout)
+ common = [tool('gcc'), *flags, '-nostartfiles', '--specs=nano.specs',
+ '-Wl,--relocatable,--gc-sections,-e,main', '-flinker-output=nolto-rel', *objects]
+ run(*common, '-lm', '-o', out / 'module.o')
+ run(*common, '-Wl,-u,eadk_app_name,-u,eadk_app_icon,-u,eadk_api_level', out / 'icon-compact.o',
+ '-lm', '-o', out / 'standalone.o')
+ run(sys.executable, packer, 'app', out / 'standalone.o', out / 'towerblock-debug.nwa',
+ '--ld', tool('ld'))
+ run(sys.executable, packer, 'release', out / 'towerblock-debug.nwa',
+ out / 'TowerBlock.nwa', '--objcopy', tool('objcopy'))
+ if os.name != 'nt':
+ shutil.copyfile(out / 'TowerBlock.nwa', out / 'towerblock.nwa')
+ profiles = []
+ from elftools.elf.elffile import ELFFile
+ for name, base, ram in [('n0110', 0x20000000, 148928), ('n0115-custom', 0x20000000, 133652),
+ ('n0120', 0x24000000, 153676), ('upsilon', 0x20000000, 107674)]:
+ options = ['--ram-start', hex(base + 0x37000 - ram), '--ram-length', str(ram)]
+ elf, binary = out / (name + '.elf'), out / (name + '.bin')
+ run(*nw, 'nwa-elf', out / 'TowerBlock.nwa', elf, *options)
+ run(*nw, 'nwa-bin', out / 'TowerBlock.nwa', binary, *options)
+ debug_binary = out / (name + '-debug.bin')
+ run(*nw, 'nwa-bin', out / 'towerblock-debug.nwa', debug_binary, *options)
+ if binary.read_bytes() != debug_binary.read_bytes():
+ raise RuntimeError(f'Release compaction changed installed bytes on {name}')
+ with elf.open('rb') as f:
+ e = ELFFile(f)
+ static_ram = sum(s['sh_size'] for s in e.iter_sections() if s.name in ('.data', '.bss'))
+ if static_ram > 12288:
+ raise RuntimeError(f'Static RAM budget exceeded: {static_ram}')
+ if binary.stat().st_size > 65536:
+ raise RuntimeError('Installed flash budget exceeded')
+ profiles.append(dict(profile=name, installed_flash=binary.stat().st_size, static_ram=static_ram, ram_limit=ram))
+ report = dict(nwa_bytes=(out / 'TowerBlock.nwa').stat().st_size, save_bytes=384,
+ **icon_report, profiles=profiles)
+ (out / 'sizes.json').write_text(json.dumps(report, indent=2) + '\n')
+ print(json.dumps(report, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/towerblock/tools/compact_nwa.py b/games/towerblock/tools/compact_nwa.py
new file mode 100644
index 00000000..f320bb54
--- /dev/null
+++ b/games/towerblock/tools/compact_nwa.py
@@ -0,0 +1,228 @@
+#!/usr/bin/env python3
+"""Lossless standalone NWA packing. Python standard library + ARM binutils.
+
+Keep the standard ELF/NWI formats: no runtime decoder, extra RAM, or archive.
+"""
+import argparse
+from bisect import bisect_left, insort
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+
+ICON_BYTES = 55 * 56 * 2
+
+
+def decode_lz4(data, expected_size):
+ """Decode a raw LZ4 block, with an exact output bound for launcher icons."""
+ out = bytearray()
+ pos = 0
+
+ def length(value):
+ nonlocal pos
+ if value == 15:
+ while True:
+ if pos >= len(data):
+ raise ValueError('Truncated LZ4 length')
+ extra = data[pos]
+ pos += 1
+ value += extra
+ if extra != 255:
+ break
+ return value
+
+ while pos < len(data):
+ token = data[pos]
+ pos += 1
+ size = length(token >> 4)
+ if pos + size > len(data) or len(out) + size > expected_size:
+ raise ValueError('Invalid LZ4 literal run')
+ out += data[pos:pos + size]
+ pos += size
+ if pos == len(data):
+ break
+ if pos + 2 > len(data):
+ raise ValueError('Truncated LZ4 offset')
+ distance = data[pos] | data[pos + 1] << 8
+ pos += 2
+ size = length(token & 15) + 4
+ if not distance or distance > len(out) or len(out) + size > expected_size:
+ raise ValueError('Invalid LZ4 match')
+ for _ in range(size):
+ out.append(out[-distance])
+ if len(out) != expected_size:
+ raise ValueError('Unexpected decoded icon size')
+ return bytes(out)
+
+
+def _extension_cost(value, threshold):
+ return 0 if value < threshold else 1 + (value - threshold) // 255
+
+
+def compress_lz4(data):
+ """Find a minimum-size raw LZ4 parse for a small (<= 65535 byte) image.
+
+ A suffix array finds the longest legal previous match. Dynamic programming
+ chooses literal/match lengths, including extension-byte costs. The final
+ five bytes are literals; the last match starts at least twelve bytes from
+ the end, as required by standard LZ4 block decoders.
+ """
+ n = len(data)
+ if n > 65535:
+ raise ValueError('Only small build-time assets are supported')
+ if not n:
+ return b'\0'
+ suffixes = sorted(range(n), key=lambda i: data[i:])
+ rank = [0] * n
+ for r, pos in enumerate(suffixes):
+ rank[pos] = r
+ seen = []
+ matches = [(0, 0)] * n
+ for i in range(n - 11):
+ r = rank[i]
+ at = bisect_left(seen, r)
+ best, distance = 0, 0
+ # Among earlier suffixes, a lexicographic neighbour has the longest
+ # common prefix. Overlapping matches are legal in LZ4.
+ for q in seen[max(0, at - 1):at + 1]:
+ j = suffixes[q]
+ lo, hi = 0, n - i - 5
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if data[i:i + mid] == data[j:j + mid]:
+ lo = mid
+ else:
+ hi = mid - 1
+ if lo > best:
+ best, distance = lo, i - j
+ matches[i] = best, distance
+ insort(seen, r)
+
+ dp = [0] * (n + 1)
+ plan = [None] * n
+ match_cost = [0] * n
+ match_length = [0] * n
+ starts = []
+ for i in range(n - 1, -1, -1):
+ best = n - i + 1 + _extension_cost(n - i, 15)
+ longest, _ = matches[i]
+ if longest >= 4:
+ cost, size = min((2 + _extension_cost(size, 19) + dp[i + size], size)
+ for size in range(4, longest + 1))
+ match_cost[i], match_length[i] = cost, size
+ starts.append(i)
+ for j in reversed(starts):
+ literal = j - i
+ if literal + 3 >= best:
+ break
+ cost = 1 + literal + _extension_cost(literal, 15) + match_cost[j]
+ if cost < best:
+ best = cost
+ plan[i] = j, match_length[j], matches[j][1]
+ dp[i] = best
+
+ out = bytearray()
+
+ def emit_length(value):
+ while value >= 255:
+ out.append(255)
+ value -= 255
+ out.append(value)
+
+ anchor = 0
+ while anchor < n:
+ entry = plan[anchor]
+ if entry is None:
+ literal = n - anchor
+ out.append(min(literal, 15) << 4)
+ if literal >= 15:
+ emit_length(literal - 15)
+ out += data[anchor:]
+ break
+ j, size, distance = entry
+ literal = j - anchor
+ out.append(min(literal, 15) << 4 | min(size - 4, 15))
+ if literal >= 15:
+ emit_length(literal - 15)
+ out += data[anchor:j]
+ out += bytes((distance & 255, distance >> 8))
+ if size >= 19:
+ emit_length(size - 19)
+ anchor = j + size
+ if len(out) != dp[0] or decode_lz4(out, n) != data:
+ raise ValueError('Lossless compression verification failed')
+ return bytes(out)
+
+
+def compact_icon(source, output, objcopy):
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ folder = Path(folder)
+ original, packed, obj = folder/'original.nwi', folder/'packed.nwi', folder/'icon.o'
+ section = '.rodata.eadk_app_icon'
+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(original),
+ str(source), str(obj)], check=True)
+ before = original.read_bytes()
+ pixels = decode_lz4(before, ICON_BYTES)
+ after = compress_lz4(pixels)
+ if len(after) > len(before):
+ after = before
+ packed.write_bytes(after)
+ subprocess.run([objcopy, '--update-section=' + section + '=' + str(packed),
+ str(obj), str(output)], check=True)
+ # Verify the bytes actually stored in the resulting ELF, too.
+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(packed),
+ str(output), str(folder/'verify.o')], check=True)
+ if decode_lz4(packed.read_bytes(), ICON_BYTES) != pixels:
+ raise ValueError('Packed icon pixels changed')
+ return dict(source_icon_bytes=len(before), icon_bytes=len(after), decoded_icon_bytes=ICON_BYTES)
+
+
+def compact_app(source, output, linker):
+ output.parent.mkdir(parents=True, exist_ok=True)
+ script = Path(__file__).with_name('standalone.ld')
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ packed = Path(folder)/'packed.nwa'
+ subprocess.run([linker, '--relocatable', '--script', str(script), str(source),
+ '-o', str(packed)], check=True)
+ output.write_bytes(packed.read_bytes())
+
+
+def compact_release(source, output, objcopy):
+ """Remove unused ARM mapping symbols from the transport ELF only.
+
+ GNU objcopy preserves $t/$d symbols specially even when unused. Rename
+ them in a temporary release copy, then let objcopy decide which symbols
+ relocations still need. Keep the debug ELF intact for ARM disassembly.
+ Python builders compare release/debug bytes on all supported profiles;
+ Make's check target compares them on the smallest RAM profile.
+ """
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ folder = Path(folder)
+ stripped, renamed = folder/'stripped.nwa', folder/'renamed.nwa'
+ subprocess.run([objcopy, '--strip-unneeded', str(source), str(stripped)], check=True)
+ subprocess.run([objcopy, '--redefine-sym=$t=unused_thumb_marker',
+ '--redefine-sym=$d=unused_data_marker', str(stripped),
+ str(renamed)], check=True)
+ subprocess.run([objcopy, '--strip-unneeded', str(renamed), str(output)], check=True)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('kind', choices=('icon', 'app', 'release'))
+ ap.add_argument('source', type=Path)
+ ap.add_argument('output', type=Path)
+ ap.add_argument('--objcopy', default='arm-none-eabi-objcopy')
+ ap.add_argument('--ld', default='arm-none-eabi-ld')
+ args = ap.parse_args()
+ if args.kind == 'icon':
+ print(json.dumps(compact_icon(args.source, args.output, args.objcopy)))
+ elif args.kind == 'release':
+ compact_release(args.source, args.output, args.objcopy)
+ else:
+ compact_app(args.source, args.output, args.ld)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/towerblock/tools/icon.py b/games/towerblock/tools/icon.py
new file mode 100644
index 00000000..2da8972c
--- /dev/null
+++ b/games/towerblock/tools/icon.py
@@ -0,0 +1,18 @@
+#!/usr/bin/env python3
+"""Original isometric tower icon; generate with Pillow."""
+from pathlib import Path
+from PIL import Image,ImageDraw
+S=4
+im=Image.new('RGB',(55*S,56*S),'#091b2b');d=ImageDraw.Draw(im)
+def poly(points,color):
+ d.polygon([(int(x*S),int(y*S)) for x,y in points],fill=color)
+def slab(cx,cy,w,h,color,left,right):
+ a,b,c,e=(cx,cy-h),(cx+w,cy),(cx,cy+h),(cx-w,cy)
+ poly([e,c,(c[0],c[1]+4),(e[0],e[1]+4)],left)
+ poly([b,c,(c[0],c[1]+4),(b[0],b[1]+4)],right)
+ poly([a,b,c,e],color)
+ d.line([(int(e[0]*S),int(e[1]*S)),(int(a[0]*S),int(a[1]*S)),(int(b[0]*S),int(b[1]*S))],fill='#c7eee7',width=S)
+for i,color in enumerate(['#f0acad','#c29ceb','#7ba6ed','#69debf']):
+ slab(27,39-i*6,19,9,color,'#36627c','#25475b')
+slab(34,11,15,7,'#95f0d2','#438d8b','#29636f')
+im.resize((55,56),Image.Resampling.LANCZOS).save(Path(__file__).resolve().parents[1]/'src/icon.png')
diff --git a/games/towerblock/tools/standalone.ld b/games/towerblock/tools/standalone.ld
new file mode 100644
index 00000000..28679582
--- /dev/null
+++ b/games/towerblock/tools/standalone.ld
@@ -0,0 +1,15 @@
+/* Compact a standalone NWA after the first link has removed unused code.
+ * Keep EADK metadata separate, and preserve mergeable strings for nwlink.
+ * NumPlay modules retain their original sections for launcher garbage collection.
+ */
+SECTIONS {
+ .rodata.eadk_app_name : { *(.rodata.eadk_app_name) }
+ .rodata.eadk_app_icon : { *(.rodata.eadk_app_icon) }
+ .rodata.eadk_api_level : { *(.rodata.eadk_api_level) }
+ .text : { *(.text.startup.main) *(.text .text.*) }
+ .rodata.str1.1 : { *(.rodata*.str1.1) }
+ .rodata : { *(.rodata .rodata.*) }
+ .data : { *(.data .data.*) }
+ .bss : { *(.bss .bss.*) *(COMMON) }
+ /DISCARD/ : { *(.comment) *(.note.GNU-stack) }
+}