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
Tower Blocks: stack the moving blocks, inside NumPlay
Mason363d2cd1b097014
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex c2042c09..c0127f6b 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -76,6 +76,7 @@ jobs:make -C games/uttt host testmake -C games/sokoban host testmake -C games/flappydunk host test+ make -C games/towerblock host testdiff --git a/LICENSES/MIT-TowerBlocks.txt b/LICENSES/MIT-TowerBlocks.txtnew file mode 100644index 00000000..9a7ba804--- /dev/null+++ b/LICENSES/MIT-TowerBlocks.txt@@ -0,0 +1,18 @@+Tower Blocks by Steve Gardner (https://codepen.io/ste-vg/pen/ppLQNW), whose rules, numbers, colours and camera+Tower Blocks (games/towerblock) ports. Public pens on CodePen are under the MIT License.++Copyright (c) 2017 Steve Gardner (https://codepen.io/ste-vg/pen/ppLQNW)++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the Software without restriction, including without limitation+the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of+the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO+THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/Makefile b/Makefileindex 04c8c246..d40f9e7b 100644--- a/Makefile+++ b/Makefile@@ -30,7 +30,7 @@ APP_SPACE = 2031616# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)UPSILON_RAM = 107674-UPSILON_GAMES = crossyroad blockblast portal tetris dinorun chess flappybird flappydunk pacman snake connectfour solitaire g2048 minesweeper \+UPSILON_GAMES = crossyroad blockblast portal tetris dinorun chess flappybird flappydunk towerblock pacman snake connectfour solitaire g2048 minesweeper \breakout twoplayer invaders sudoku uttt sokoban# NumPlay and its discreet versions: the same app, with another name and icondiff --git a/README.md b/README.mdindex 48664b7f..36dc8bbd 100644--- a/README.md+++ b/README.md@@ -111,10 +111,6 @@ 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 installYou need your calculator, its USB cable, and a computer with **Google Chrome** or **Microsoft Edge**. It takes about 2 minutes.@@ -253,7 +249,6 @@ 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, and also made the live emulator (`tools/emu_live.py`) and the Windows builder. Not affiliated with Google.diff --git a/games/games.json b/games/games.jsonindex c71eff15..33ec68ed 100644--- a/games/games.json+++ b/games/games.json@@ -260,6 +260,24 @@"app": "FlappyDunk.nwa","repo": "https://github.com/Mason363/NumPlay/tree/main/games/flappydunk"},+ {+ "id": "towerblock",+ "title": "Tower Blocks",+ "tagline": "Stack the blocks as high as you can",+ "credit": "Based on Tower Blocks by Steve Gardner",+ "top": "0xD8C7E8",+ "bottom": "0x6E7BA8",+ "accent": "0xF2D27A",+ "colors": 16,+ "records": [+ "towerblocks.sav"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "app": "TowerBlocks.nwa",+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/towerblock"+ },{"id": "pacman","title": "Pac-Man",diff --git a/games/towerblock/.gitignore b/games/towerblock/.gitignoreindex 16be8f21..79fafc9f 100644--- a/games/towerblock/.gitignore+++ b/games/towerblock/.gitignore@@ -1 +1,2 @@/output/+/build/diff --git a/games/towerblock/Makefile b/games/towerblock/Makefileindex 188dc189..150ecc83 100644--- a/games/towerblock/Makefile+++ b/games/towerblock/Makefile@@ -1,51 +1,83 @@-# Tower Block: English-only app and NumPlay module.+# Tower Blocks: drop each moving block on the tower; what hangs over the edge falls off.+# make build output/towerblock.nwa+# make check link the app like the calculator does (output/towerblock.bin)+#+# In NumPlay the game draws with the launcher's strips, shapes and fonts and saves through its+# file functions (module.o leaves them to the launcher); on its own it brings them along.+Q ?= @CC = arm-none-eabi-gccNWLINK ?= 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+BUILD_DIR = output+SRC = src/main.c+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h ../../launcher/src/gfx.h \+ ../../launcher/src/np.h ../../launcher/src/font.h++CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean+build: $(BUILD_DIR)/towerblock.nwa++check: $(BUILD_DIR)/towerblock.nwa+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/towerblock.bin+ @echo "BIN $(BUILD_DIR)/towerblock.bin: $$(wc -c < $(BUILD_DIR)/towerblock.bin) bytes"++# compiled, then linked (the link options would upset the compiler)+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ @echo "CC $<"+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@+$(BUILD_DIR)/gfx.o: ../../launcher/src/gfx.c $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@+$(BUILD_DIR)/font_data.o: ../../launcher/src/font_data.c ../../launcher/src/font.h | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@+$(BUILD_DIR)/xfont.o: ../../launcher/src/xfont.c ../../launcher/src/np_xfont.h $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@++$(BUILD_DIR)/towerblock.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \+ $(BUILD_DIR)/icon.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@+ $(Q) arm-none-eabi-strip --strip-unneeded $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@+clean:- rm -rf output+ $(Q) rm -rf $(BUILD_DIR)++# NumPlay launcher: the app 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-main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -DNP_MODULE=1 -c $(SRC) -o $@+$(BUILD_DIR)/module.o: $(BUILD_DIR)/module-main.o+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@++sim-module: $(BUILD_DIR)/sim-module.o+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ $(Q) mkdir -p $(BUILD_DIR)/sim+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -DNP_MODULE=1 -Dmain=np_towerblock_main \+ -c $(SRC) -o $(BUILD_DIR)/sim/main.o+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_towerblock_main -o $@++# on a computer, with the sanitizers: a bot builds 300 towers (tests/play.c)+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -DPLATFORM_DEVICE=1 -DHOST \+ $(shell $(NWLINK) eadk-cflags-simulator) -fsanitize=address,undefined -fno-sanitize-recover=undefined+.PHONY: host test+host: build/play+build/play: $(SRC) tests/play.c $(HEADERS)+ $(Q) mkdir -p build+ $(Q) cc $(HOST_FLAGS) tests/play.c ../../launcher/src/gfx.c ../../launcher/src/font_data.c \+ ../../launcher/src/xfont.c -lm -o $@+ @echo "HOST $@"+test: build/play+ build/play testdiff --git a/games/towerblock/README.md b/games/towerblock/README.mdindex fbc6a10f..6b06c3ed 100644--- a/games/towerblock/README.md+++ b/games/towerblock/README.md@@ -1,102 +1,28 @@-# Tower Block+# Tower Blocks-Game made by **Bobydeluxe**.+Drop each moving block on the tower; what hangs over the edge falls off. Steve Gardner's Tower Blocks for the NumWorks calculator, ported from its source.-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.+<img src="docs/shot.png" width="320" alt="A tower of fifteen pastel blocks, the next one sliding in from the right">--+- **One button.** Each block slides in from one side, along one edge of the tower and then the other. Press OK to drop it.+- **Cut to size.** The part over the block below stays and the rest falls away, so the blocks get smaller. Land within a hair of it and the block stays whole.+- **Faster and faster.** Every block comes a little quicker than the one before, as in the original.+- **The original's look.** Its pastel colours shifting up the tower, its light and its camera, with the cut pieces tumbling away. When the game ends the tower shrinks away from the top and the score counts down.+- Your tower and best score are saved, so you can stop and carry on later.-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.+## Controls| 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.+| OK or EXE | Drop the block |+| Back | Menu: Resume, New game, How to play, Quit |-```sh-make test-python tests/arm.py --nwlink /path/to/nwlink-python tests/test_compact_nwa.py-```+## Credits-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.+Tower Blocks is **[Steve Gardner](https://codepen.io/ste-vg)**'s game ([on CodePen](https://codepen.io/ste-vg/pen/ppLQNW), MIT License), the one Y8 shows as Tower Block. **[Bobydeluxe](https://github.com/Bobydeluxe)** brought it to NumPlay. This version is written in C from its source: its sizes, speeds, colours, light and camera are the original's (see [LICENSES/MIT-TowerBlocks.txt](../../LICENSES/MIT-TowerBlocks.txt)).-## Resources+Inside NumPlay it draws with the launcher's own shapes and fonts and saves through its file functions, so the game itself is about 5 KB.-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.+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `TowerBlocks.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).-Licensed under GPL-3.0-only, like NumPlay.+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink). Tests: `make test`.diff --git a/games/towerblock/VALIDATION.md b/games/towerblock/VALIDATION.mddeleted file mode 100644index 1c5bdc77..00000000--- a/games/towerblock/VALIDATION.md+++ /dev/null@@ -1,51 +0,0 @@-# 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.pngdeleted file mode 100644index a727b655..00000000Binary files a/games/towerblock/docs/gameplay.png and /dev/null differdiff --git a/games/towerblock/docs/guide.png b/games/towerblock/docs/guide.pngdeleted file mode 100644index afa6160b..00000000Binary files a/games/towerblock/docs/guide.png and /dev/null differdiff --git a/games/towerblock/docs/shot.png b/games/towerblock/docs/shot.pngnew file mode 100644index 00000000..58f8919dBinary files /dev/null and b/games/towerblock/docs/shot.png differdiff --git a/games/towerblock/docs/title.png b/games/towerblock/docs/title.pngdeleted file mode 100644index 95ec235b..00000000Binary files a/games/towerblock/docs/title.png and /dev/null differdiff --git a/games/towerblock/lang/fr.txt b/games/towerblock/lang/fr.txtnew file mode 100644index 00000000..496485cf--- /dev/null+++ b/games/towerblock/lang/fr.txt@@ -0,0 +1,16 @@+# Tower Blocks in French: the English text as in the source, a tab, the translation (see tools/lang.py).+Resume Reprendre+New game Nouvelle partie+How to play Comment jouer+Quit Quitter+Back menu Retour menu+Start Jouer+Press OK to go on Appuie sur OK pour continuer+Press OK to place the block Appuie sur OK pour poser le bloc+Game Over Partie terminée+You did great, you're the best. Bravo, tu es le meilleur.+Press OK to start again Appuie sur OK pour recommencer+Best Record+Paused Pause+Press OK to drop the moving block on the tower. What hangs over the edge falls off, so the blocks get smaller. Land it just right to keep it whole. Miss the tower and it's over. Appuie sur OK pour lâcher le bloc sur la tour. Ce qui dépasse tombe, et les blocs rétrécissent. Pose-le pile dessus pour le garder entier. Rate la tour et c'est fini.+Play Jouerdiff --git a/games/towerblock/lang/zh.txt b/games/towerblock/lang/zh.txtnew file mode 100644index 00000000..9e900d64--- /dev/null+++ b/games/towerblock/lang/zh.txt@@ -0,0 +1,16 @@+# Tower Blocks in Chinese: the English text as in the source, a tab, the translation (see tools/lang.py).+Resume 继续+New game 新游戏+How to play 玩法+Quit 退出+Back menu 返回 菜单+Start 开始+Press OK to go on 按 OK 继续+Press OK to place the block 按 OK 放下方块+Game Over 游戏结束+You did great, you're the best. 干得好,你是最棒的。+Press OK to start again 按 OK 重新开始+Best 最高+Paused 暂停+Press OK to drop the moving block on the tower. What hangs over the edge falls off, so the blocks get smaller. Land it just right to keep it whole. Miss the tower and it's over. 按 OK 把移动的方块放到塔上。超出边缘的部分会掉落,方块就会变小。对得刚好就能保持完整。没放到塔上就结束了。+Play 开始diff --git a/games/towerblock/src/icon.png b/games/towerblock/src/icon.pngindex 11a8086e..b5a9117e 100644Binary files a/games/towerblock/src/icon.png and b/games/towerblock/src/icon.png differdiff --git a/games/towerblock/src/main.c b/games/towerblock/src/main.cindex a6898347..cf5e8a7b 100644--- a/games/towerblock/src/main.c+++ b/games/towerblock/src/main.c@@ -1,131 +1,407 @@-/* SPDX-License-Identifier: GPL-3.0-only */+/* Tower Blocks: drop each moving block on the tower; what hangs over the edge falls off.+ *+ * Steve Gardner's Tower Blocks (the game Y8 shows as Tower Block), ported from its source: blocks slide in+ * from either side, along one axis then the other, faster and faster; the part that misses the block below+ * is cut off and falls, landing within 0.3 of it keeps the whole block, and missing it completely ends the+ * game. Its sizes, speeds, colours, light and camera are the original's, seen from the same corner, drawn+ * in pixel lines two across for one down.+ *+ * Inside NumPlay it draws with the launcher's strips, shapes and fonts (launcher/src/gfx.c) and saves+ * through its file functions; on its own (TowerBlocks.nwa) it brings them along.+ *+ * Made by Bobydeluxe and Mason Chen as part of NumPlay. */#include <eadk.h>-#include "tower.h"-#include "render.h"+#include "../../../launcher/src/gfx.h"+#include "../../common/np_text.h"++#if NP_MODULE /* (np_file_read and np_file_write: NumPlay's, launcher/src/np.h) */+#define np_app_begin()+#define np_app_end() 0+#else#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";+#define np_file_read ef_read+#define np_file_write ef_write+#ifndef HOST /* (a computer build of the tests has no app header) */+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Tower Blocks";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;+void np_push(int x, int y, int w, int h, const color_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);}-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;+#endif++#define KEY(k) (1ull << (k))+#define INK HEX(0x333344)++/* ------------------------------------------------------------ the original's numbers (world units, 60 ticks a second) */+#define SIZE 10.0f /* the first block, 10 x 2 x 10 */+#define LAYER 2.0f+#define TRAVEL 12.0f /* blocks slide between -12 and 12 */+#define SNAP 0.3f /* closer than this keeps the whole block */+static float speed_of(uint32_t index) { /* -0.1 - index * 0.005 a tick, at most 4 */+ float s = 0.1f + (float)index * 0.005f;+ return s > 4 ? 4 : s;+}++/* on screen: 3.2 pixels a unit, two across for one down; the camera's point (2, cam, 2) in the middle */+#define K 3.2f+#define KY (K * 1.2247f)++#define KEEP 40 /* blocks kept (all a screen shows, with room to spare) */+typedef struct {+ float x, z, w, d;+} slab_t;++/* towerblocks.sav: the best, and the tower in progress */+static struct {+ uint8_t magic, version, flags, pad; /* flags: 1 a tower to go on with, 2 the guide was read */+ uint32_t sum; /* of the words after it: a damaged file starts afresh */+ uint32_t best, score, offset; /* offset: the colours' start, the original's colorOffset */+ float pos, dir; /* the moving block, on its axis */+ slab_t slab[KEEP]; /* block i (the base is 1) at slab[i % KEEP] */+} sv;+#define SAVE_NAME "towerblocks.sav"+#define TOP (sv.score + 1) /* the top block's index */+#define MOVING (sv.score + 2) /* the moving one's: on x when odd, on z when even */+#define AT(i) sv.slab[(i) % KEEP]++static color_t strip[SCREEN_W * STRIP_H];+static uint32_t now, seed, over_t, reset_t, reset_n, cam_t, shown;+static float cam, cam_from, cam_to;+static int ov, sel;+enum { S_READY, S_PLAY, S_OVER, S_RESET };+static int state;+static bool frozen; /* a tower back from the menu or a save: the next OK sets it going */+enum { OV_NONE, OV_MENU, OV_HELP };++/* the pieces cut off, falling */+typedef struct {+ float x, y, z, w, d, rx, ry, rz, out;+ uint32_t t, index;+ uint8_t axis; /* 0 x, 1 z */+} chip_t;+static chip_t chips[4];++static uint32_t rnd(void) {+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;+ return seed;+}+static float frand(void) { return (float)(rnd() & 0xFFFF) / 65536.0f; }+static float fabs_(float v) { return v < 0 ? -v : v; }++/* sine and cosine, for the colours and the turning pieces */+static float sin_(float x) {+ const float tp = 6.2831853f;+ x -= tp * (float)(int)(x / tp);+ if (x < 0) x += tp;+ if (x > 3.1415927f) return -sin_(x - 3.1415927f);+ if (x > 1.5707964f) x = 3.1415927f - x;+ float x2 = x * x;+ return x * (1 - x2 / 6 * (1 - x2 / 20 * (1 - x2 / 42 * (1 - x2 / 72))));+}+static float cos_(float x) { return sin_(x + 1.5707964f); }++static char *num(char *o, uint32_t v) {+ char t[10];+ int n = 0;+ do t[n++] = (char)('0' + v % 10); while (v /= 10);+ while (n) *o++ = t[--n];+ *o = 0;+ return o;+}++/* ------------------------------------------------------------ the rules */+static uint32_t checksum(void) {+ uint32_t h = 0x811C9DC5u;+ for (const uint32_t *w = &sv.sum + 1; w < (const uint32_t *)(&sv + 1); w++) h = (h ^ *w) * 0x01000193u;+ return h;+}+static void save(void) {+ sv.magic = 'T', sv.version = 1, sv.sum = checksum();+ np_file_write(SAVE_NAME, &sv, sizeof sv);+}++static void camera_to(float y) { cam_from = cam, cam_to = y, cam_t = now; }++/* the next block, from the side its axis starts on, at the speed for its height */+static void next_block(void) {+ sv.pos = rnd() & 1 ? -TRAVEL : TRAVEL;+ sv.dir = -speed_of(MOVING);+ camera_to(LAYER * (float)(MOVING) + 2);+}++static void new_game(void) {+ for (int i = 0; i < KEEP; i++) sv.slab[i] = (slab_t){0, 0, SIZE, SIZE};+ sv.score = 0, sv.offset = rnd() % 101, sv.flags |= 1;+ for (int i = 0; i < 4; i++) chips[i].t = 0;+ state = S_PLAY, frozen = false, shown = 0;+ next_block();+}++static void tick(void) { /* the moving block, a sixtieth of a second */+ if (sv.pos > TRAVEL || sv.pos < -TRAVEL) sv.dir = sv.dir > 0 ? -speed_of(MOVING) : speed_of(MOVING);+ sv.pos += sv.dir;+}++/* the block placed: what overlaps the one below stays, the rest falls off */+static void place(void) {+ uint32_t i = MOVING;+ slab_t below = AT(i - 1), b = below;+ int axis = i % 2 ? 0 : 1;+ float *p = axis ? &b.z : &b.x, *dim = axis ? &b.d : &b.w, bp = axis ? below.z : below.x;+ *p = sv.pos;+ float overlap = *dim - fabs_(sv.pos - bp);+ if (*dim - overlap < SNAP) { /* close enough: the whole block, right on the one below */+ AT(i) = below;+ } else if (overlap > 0) {+ chip_t *c = &chips[0];+ for (int k = 1; k < 4; k++)+ if (chips[k].t < c->t) c = &chips[k];+ *c = (chip_t){b.x, LAYER * (float)i, b.z, b.w, b.d, 0, frand() * 0.1f, 0, 40 * fabs_(sv.dir), now, i, (uint8_t)axis};+ float spin = frand() * 10 - 5;+ if (axis) c->rx = spin, c->rz = 0.1f, c->d = *dim - overlap;+ else c->rz = spin, c->rx = 0.1f, c->w = *dim - overlap;+ if (sv.pos < bp) { /* sticking out before it: the kept part starts where the block below does */+ *p = bp;+ if (sv.dir > 0) c->out = -c->out;+ } else {+ (axis ? &c->z : &c->x)[0] += overlap;}- 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;- }+ if ((sv.pos < bp) == (sv.dir > 0)) c->out = sv.pos < bp ? -fabs_(c->out) : fabs_(c->out);+ *dim = overlap;+ AT(i) = b;+ } else { /* missed: it falls whole, and the game is over */+ state = S_OVER, over_t = now, sv.flags &= (uint8_t)~1;+ save();+ return;+ }+ sv.score++;+ if (sv.score > sv.best) sv.best = sv.score;+ next_block();+}++/* ------------------------------------------------------------ drawing */+static float ease_in(float t) { return t <= 0 ? 0 : t >= 1 ? 1 : t * t; }+static float ease_out(float t) { return t <= 0 ? 0 : t >= 1 ? 1 : 1 - (1 - t) * (1 - t); }+static float ease_io(float t) { return t <= 0 ? 0 : t >= 1 ? 1 : t < 0.5f ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t); }++/* block i's colour, as the original works it out: three waves a third of a turn apart */+static uint32_t colour(uint32_t i) {+ if (i <= 1) return 0x333344;+ float o = 0.3f * (float)(i + sv.offset);+ uint32_t r = (uint32_t)(sin_(o) * 55 + 200), g = (uint32_t)(sin_(o + 2) * 55 + 200), b = (uint32_t)(sin_(o + 4) * 55 + 200);+ return r << 16 | g << 8 | b;+}+static color_t lit(uint32_t rgb, int k256) { /* the colour under the light: 0.9 on top, 0.75 on the sides */+ return gfx_rgb(gfx_lerp888(rgb, 0, 256 - k256));+}++/* a convex four-sided face, filled row by row within the strip */+static void quad(const float *px, const float *py, color_t c) {+ float y0 = py[0], y1 = py[0];+ for (int k = 1; k < 4; k++) y0 = py[k] < y0 ? py[k] : y0, y1 = py[k] > y1 ? py[k] : y1;+ int a = (int)y0, b = (int)y1 + 1;+ if (a < gfx_y0) a = gfx_y0;+ if (b > gfx_y1) b = gfx_y1;+ for (int y = a; y < b; y++) {+ float yc = (float)y + 0.5f, l = 1e9f, r = -1e9f;+ for (int k = 0; k < 4; k++) {+ int n = (k + 1) & 3;+ float ya = py[k], yb = py[n];+ if ((yc < ya) == (yc < yb)) continue;+ float x = px[k] + (px[n] - px[k]) * (yc - ya) / (yb - ya);+ l = x < l ? x : l, r = x > r ? x : r;+ }+ int xl = (int)(l + 0.5f), xr = (int)(r + 0.5f);+ if (xr > xl) gfx_fill(xl, y, xr - xl, 1, c);+ }+}++/* a block: its corner at (x, y, z), turned (Euler x, y, z about that corner, as three.js does) and scaled;+ the faces turned towards the camera, lit as the original lights them */+static void box(float x, float y, float z, float w, float d, float rx, float ry, float rz, float s, uint32_t rgb) {+ float cx = cos_(rx), sx = sin_(rx), cy = cos_(ry), sy = sin_(ry), cz = cos_(rz), sz = sin_(rz);+ /* R = Rx Ry Rz */+ float m[9] = {cy * cz, -cy * sz, sy, cx * sz + sx * sy * cz, cx * cz - sx * sy * sz, -sx * cy,+ sx * sz - cx * sy * cz, sx * cz + cx * sy * sz, cx * cy};+ float sxp[8], syp[8];+ for (int k = 0; k < 8; k++) {+ float lx = (k & 1 ? w : 0) * s, ly = (k & 2 ? LAYER : 0) * s, lz = (k & 4 ? d : 0) * s;+ float wx = x + m[0] * lx + m[1] * ly + m[2] * lz, wy = y + m[3] * lx + m[4] * ly + m[5] * lz,+ wz = z + m[6] * lx + m[7] * ly + m[8] * lz;+ sxp[k] = 160 + K * (wx - wz), syp[k] = 120 - KY * (wy - cam) + K * 0.5f * (wx + wz - 4);+ }+ float top = syp[0], bot = syp[0];+ for (int k = 1; k < 8; k++) top = syp[k] < top ? syp[k] : top, bot = syp[k] > bot ? syp[k] : bot;+ if (bot < gfx_y0 || top >= gfx_y1) return;+ /* the faces: their corners (bits x, y, z) in order around, then the axis of their normal, + or - */+ static const int8_t face[6][6] = {{2, 3, 7, 6, 1, 1}, {1, 3, 7, 5, 0, 1}, {4, 5, 7, 6, 2, 1},+ {0, 1, 5, 4, 1, -1}, {0, 2, 6, 4, 0, -1}, {0, 1, 3, 2, 2, -1}};+ for (int f = 0; f < 6; f++) {+ int ax = face[f][4];+ float nx = m[ax] * face[f][5], ny = m[3 + ax] * face[f][5], nz = m[6 + ax] * face[f][5];+ if (nx + ny + nz <= 0.0001f) continue; /* turned away from the camera, at (1, 1, 1) */+ float qx[4], qy[4];+ for (int k = 0; k < 4; k++) qx[k] = sxp[face[f][k]], qy[k] = syp[face[f][k]];+ quad(qx, qy, lit(rgb, ny * 0.5f + 0.5f < 0.7f ? 192 : 230));+ }+}++static void button(int y, const char *s, bool on) {+ gfx_rrect(100, y, 120, 24, 4, on ? INK : HEX(0xE6E2DF), 256);+ gfx_rrect_outline(100, y, 120, 24, 4, 2, INK, 256);+ gfx_text_center(&np_font_body, 160, y + 17, s, on ? HEX(0xD0CBC7) : INK, 256);+}+static const char *const menu_items[] = {T("Resume"), T("New game"), T("How to play"), T("Quit")};++/* the pieces falling away behind the tower (back) or in front of it */+static void chips_drawn(bool back) {+ for (int k = 0; k < 4; k++) {+ chip_t *c = &chips[k];+ float t = (float)(now - c->t) / 1000.0f;+ if (!c->t || t >= 1 || (c->out < 0) != back) continue;+ float e = ease_in(t), r = ease_out(t - 0.05f);+ box(c->x + (c->axis ? 0 : c->out * e), c->y - 30 * e, c->z + (c->axis ? c->out * e : 0), c->w, c->d, c->rx * r,+ c->ry * r, c->rz * r, 1, colour(c->index));+ }+}++static void scene(void *ctx) {+ char s[16];+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, HEX(0xD0CBC7));+ chips_drawn(true);+ /* the tower, from the bottom block on screen up; while it resets, each block shrinks away in turn */+ uint32_t top = state == S_PLAY && !frozen ? MOVING : TOP; /* (a missed block is gone, as in the original) */+ uint32_t lo = top > KEEP - 2 ? top - (KEEP - 2) : 1;+ for (uint32_t i = lo; i <= top; i++) {+ slab_t b = AT(i);+ float sc = 1, ry = 0;+ if (state == S_RESET && i > 1) { /* from the top, 0.02 s apart, 0.2 s each */+ float t = ((float)(now - reset_t) / 1000.0f - (float)(reset_n + 1 - i) * 0.02f) / 0.2f;+ sc = 1 - ease_in(t), ry = 0.5f * ease_in(t);+ if (sc <= 0) continue;+ }+ if (i == MOVING && state != S_RESET) { /* the moving block, at its place on its axis */+ b = AT(i - 1);+ if (i % 2) b.x = sv.pos;+ else b.z = sv.pos;+ }+ box(b.x, LAYER * (float)i, b.z, b.w, b.d, 0, ry, 0, sc, colour(i));+ }+ chips_drawn(false);+ gfx_text_right(&np_font_small, 314, 14, T("Back menu"), INK, 160);+ if (state == S_READY) {+ gfx_rrect_outline(122, 44, 76, 34, 0, 3, INK, 256);+ gfx_text_center(&np_font_title, 160, 68, T("Start"), INK, 256);+ } else {+ num(s, state == S_RESET ? shown : sv.score);+ gfx_text_center(&np_font_title, 160, state == S_OVER ? 46 : 32, s, INK, 256);+ }+ if (state == S_PLAY && (frozen || sv.score < 3))+ gfx_text_center(&np_font_body, 160, 52, frozen ? T("Press OK to go on") : T("Press OK to place the block"), INK, 256);+ if (state == S_OVER && now - over_t > 300) {+ gfx_text_center(&np_font_title, 160, 72, T("Game Over"), INK, 256);+ gfx_text_center(&np_font_body, 160, 90, T("You did great, you're the best."), INK, 256);+ gfx_text_center(&np_font_body, 160, 106, T("Press OK to start again"), INK, 256);+ char *e = s;+ for (const char *p = T("Best "); *p;) *e++ = *p++;+ num(e, sv.best);+ gfx_text_center(&np_font_small, 160, 119, s, INK, 190);+ }+ if (ov) {+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, HEX(0xD0CBC7));+ if (ov == OV_MENU) {+ gfx_text_center(&np_font_title, 160, 60, T("Paused"), INK, 256);+ for (int i = 0; i < 4; i++) button(76 + 32 * i, menu_items[i], sel == i);} 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;+ gfx_text_center(&np_font_title, 160, 60, T("How to play"), INK, 256);+ gfx_paragraph(&np_font_body, 160, 84, 220, 16,+ T("Press OK to drop the moving block on the tower. What hangs over the edge falls off, so the blocks get smaller. Land it just right to keep it whole. Miss the tower and it's over."),+ INK, 256);+ button(176, T("Play"), true);+ }+ }+}++/* ------------------------------------------------------------ the game */+static void load(void) {+ uint32_t len = 0;+ const uint8_t *d = np_file_read(SAVE_NAME, &len);+ uint8_t *v = (uint8_t *)&sv;+ bool ok = d && len == sizeof sv && d[0] == 'T' && d[1] == 1;+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = ok ? d[i] : 0;+ if (sv.sum != checksum())+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = 0;+}++int main(void) {+ np_app_begin();+ color_t *their_strip = gfx_buf;+ gfx_buf = strip;+ now = (uint32_t)eadk_timing_millis();+ seed = eadk_random() ^ now;+ if (!seed) seed = 1;+ load();+ if (sv.flags & 1) state = S_PLAY, frozen = true, camera_to(LAYER * (float)MOVING + 2);+ else {+ state = S_READY, sv.score = 0;+ for (int i = 0; i < KEEP; i++) sv.slab[i] = (slab_t){0, 0, SIZE, SIZE};+ camera_to(LAYER * 2 + 2);+ }+ cam = cam_to;+ if (!(sv.flags & 2)) ov = OV_HELP, sv.flags |= 2;+ uint64_t held = eadk_keyboard_scan(), stale = held; /* keys still down from the launcher wait to be let go */+ uint32_t ticks = now;+ for (;;) {+ now = (uint32_t)eadk_timing_millis();+ uint64_t raw = eadk_keyboard_scan(), k = raw & ~(stale &= raw), hit = k & ~held;+ held = k;+ if (raw & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe));+ int dy = !!(hit & KEY(eadk_key_down)) - !!(hit & KEY(eadk_key_up));+ if (ov) {+ int n = ov == OV_MENU ? 4 : 1;+ sel = (sel + dy + n) % n;+ if (hit & KEY(eadk_key_back)) ov = OV_NONE;+ if (ok) {+ int choice = ov == OV_MENU ? sel : 0;+ ov = OV_NONE;+ if (choice == 1) new_game();+ else if (choice == 2) ov = OV_HELP;+ else if (choice == 3) break;}+ } else if (hit & KEY(eadk_key_back)) {+ ov = OV_MENU, sel = 0;+ if (state == S_PLAY) frozen = true;+ save();+ } else if (ok) {+ if (state == S_READY) new_game();+ else if (state == S_OVER && now - over_t > 300) { /* the tower goes, the score counts down, a new game */+ state = S_RESET, reset_t = now, reset_n = TOP, shown = sv.score;+ camera_to(LAYER * 2 + 2);+ cam_t = now;+ } else if (state == S_PLAY && frozen) frozen = false;+ else if (state == S_PLAY) place();}- 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;+ /* sixty ticks a second, as the original's frames, catching up after a slow frame */+ if (state != S_PLAY || frozen || ov) ticks = now;+ if (now - ticks > 100) ticks = now - 100;+ for (; now - ticks >= 17; ticks += 17) tick();+ if (state == S_RESET) {+ float dur = 0.4f + (float)reset_n * 0.02f, t = (float)(now - reset_t) / 1000.0f / dur;+ shown = (uint32_t)((float)sv.score * (1 - (t > 1 ? 1 : t)) + 0.5f);+ cam = cam_from + (cam_to - cam_from) * ease_io(t);+ if (t >= 1) new_game();+ } else {+ cam = cam_from + (cam_to - cam_from) * ease_io((float)(now - cam_t) / 300.0f);}- eadk_timing_msleep(4);+ eadk_display_wait_for_vblank();+ gfx_render(scene, 0, 0, SCREEN_H);+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;+ if (spent < 16) eadk_timing_msleep(16 - spent);}+ save();+ gfx_buf = their_strip;return np_app_end();}diff --git a/games/towerblock/src/physics.c b/games/towerblock/src/physics.cdeleted file mode 100644index 5099acaa..00000000--- a/games/towerblock/src/physics.c+++ /dev/null@@ -1,134 +0,0 @@-/* 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.cdeleted file mode 100644index 7f572cc0..00000000--- a/games/towerblock/src/render.c+++ /dev/null@@ -1,339 +0,0 @@-/* 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.hdeleted file mode 100644index 462db4ba..00000000--- a/games/towerblock/src/render.h+++ /dev/null@@ -1,10 +0,0 @@-/* 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);-#endifdiff --git a/games/towerblock/src/save.c b/games/towerblock/src/save.cdeleted file mode 100644index ac2403b6..00000000--- a/games/towerblock/src/save.c+++ /dev/null@@ -1,58 +0,0 @@-/* 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.hdeleted file mode 100644index 7693c50a..00000000--- a/games/towerblock/src/tower.h+++ /dev/null@@ -1,54 +0,0 @@-/* 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);-#endifdiff --git a/games/towerblock/tests/arm.py b/games/towerblock/tests/arm.pydeleted file mode 100644index f1d59612..00000000--- a/games/towerblock/tests/arm.py+++ /dev/null@@ -1,184 +0,0 @@-#!/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.bindeleted file mode 100644index c275ef1c..00000000Binary files a/games/towerblock/tests/legacy-classic-save.bin and /dev/null differdiff --git a/games/towerblock/tests/legacy-practice-save.bin b/games/towerblock/tests/legacy-practice-save.bindeleted file mode 100644index 1f6ecdfc..00000000Binary files a/games/towerblock/tests/legacy-practice-save.bin and /dev/null differdiff --git a/games/towerblock/tests/play.c b/games/towerblock/tests/play.cnew file mode 100644index 00000000..c5af5226--- /dev/null+++ b/games/towerblock/tests/play.c@@ -0,0 +1,152 @@+/* Tower Blocks on a computer, for tests and pictures (make host, make test).+ *+ * play test a bot builds 300 towers, aiming a little off: every block kept is the part over the+ * one below, landing within 0.3 keeps it whole, and missing ends the game; pressing OK+ * at random never breaks those rules; a save comes back, and a damaged one starts afresh+ * play film DIR N N frames of the bot's tower, a picture every 2 (DIR/f_NNNN.ppm) */+#define NP_MODULE 1 /* (its drawing pushed to fb, its saves kept in disk, below) */+#define main tb_main+#include "../src/main.c"+#undef main+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static uint16_t fb[SCREEN_H][SCREEN_W];+static uint8_t disk[sizeof sv];+static uint32_t disk_len;+void np_push(int x, int y, int w, int h, const color_t *p) {+ for (int j = 0; j < h; j++)+ for (int i = 0; i < w; i++) fb[y + j][x + i] = p[j * w + i];+}+bool eadk_display_wait_for_vblank(void) { return true; }+uint64_t eadk_keyboard_scan(void) { return 0; }+uint64_t eadk_timing_millis(void) { return 0; }+void eadk_timing_msleep(uint32_t ms) { (void)ms; }+void *np_alloc(uint32_t size) { return malloc(size); }+uint32_t eadk_random(void) { return 0x2545F491u; }+const uint8_t *np_file_read(const char *name, uint32_t *len) { *len = disk_len; return disk_len ? disk : 0; }+bool np_file_write(const char *name, const void *d, uint32_t len) { memcpy(disk, d, disk_len = len); return true; }++static int fails;+#define CHECK(c, ...) do { if (!(c)) { printf(__VA_ARGS__); printf("\n"); fails++; } } while (0)+static float r01(void) { static uint32_t s = 7; s = s * 1664525u + 1013904223u; return (float)(s >> 8) / 16777216.0f; }++/* one block: ticks until it is within `off` of the one below (or never, for a miss), then placed;+ the result checked against the original's rules */+static bool drop(float off, bool random_press) {+ uint32_t i = MOVING;+ slab_t below = AT(i - 1);+ int axis = i % 2 ? 0 : 1;+ float bp = axis ? below.z : below.x, dim = axis ? below.d : below.w;+ for (int t = 0; t < 4000; t++) {+ tick();+ if (random_press ? r01() < 0.02f : fabs_(sv.pos - (bp + off)) <= fabs_(sv.dir) / 2) break;+ }+ float pos = sv.pos, overlap = dim - fabs_(pos - bp);+ uint32_t score = sv.score;+ place();+ if (dim - overlap < SNAP) {+ slab_t b = AT(i);+ CHECK(sv.score == score + 1 && b.x == below.x && b.z == below.z && b.w == below.w && b.d == below.d, "a near miss should keep the whole block");+ } else if (overlap > 0) {+ slab_t b = AT(i);+ float p = axis ? b.z : b.x, w = axis ? b.d : b.w, q = axis ? b.x : b.z, v = axis ? b.w : b.d;+ float qb = axis ? below.x : below.z, vb = axis ? below.w : below.d;+ CHECK(sv.score == score + 1, "score");+ CHECK(fabs_(w - overlap) < 1e-4f && p >= bp - 1e-4f && p + w <= bp + dim + 1e-4f, "kept part %f..%f over %f..%f", p, p + w, bp, bp + dim);+ CHECK(q == qb && v == vb, "the other axis must not change");+ } else {+ CHECK(state == S_OVER && sv.score == score && !(sv.flags & 1), "a miss should end the game");+ return false;+ }+ return true;+}++static void picture(const char *path) {+ FILE *f = fopen(path, "wb");+ if (!f) exit(2);+ fprintf(f, "P6 320 240 255\n");+ for (int y = 0; y < SCREEN_H; y++)+ for (int x = 0; x < SCREEN_W; x++) {+ uint16_t c = fb[y][x];+ fputc((c >> 11) * 255 / 31, f), fputc((c >> 5 & 63) * 255 / 63, f), fputc((c & 31) * 255 / 31, f);+ }+ fclose(f);+}+static void render(void) {+ gfx_buf = strip;+ gfx_render(scene, 0, 0, SCREEN_H);+}++int main(int argc, char **argv) {+ seed = 99;+ if (argc >= 4 && !strcmp(argv[1], "film")) {+ int frames = atoi(argv[3]), k = 0;+ seed = argc > 4 ? (uint32_t)atoi(argv[4]) : 99;+ now = 1000;+ sv.flags = 2;+ new_game();+ cam = cam_to;+ float target = 0;+ bool aimed = false;+ char path[256];+ for (int f = 0; f < frames; f++) {+ now += 17;+ if (state == S_PLAY) {+ tick();+ uint32_t i = MOVING;+ slab_t below = AT(i - 1);+ float bp = i % 2 ? below.x : below.z;+ if (!aimed) target = bp + (r01() < 0.55f ? 0 : (r01() - 0.5f) * 3.0f), aimed = true;+ if (argc > 5 && sv.score >= (uint32_t)atoi(argv[5])) target = bp > 0 ? bp - 10.5f : bp + 10.5f; /* a miss, to film the end */+ if (fabs_(sv.pos - target) <= fabs_(sv.dir) / 2 && now - cam_t > 350) place(), aimed = false;+ }+ if (state == S_OVER && now - over_t > 900) /* OK: the tower goes */+ state = S_RESET, reset_t = now, reset_n = TOP, shown = sv.score, camera_to(LAYER * 2 + 2);+ if (state == S_RESET) {+ float dur = 0.4f + (float)reset_n * 0.02f, t = (float)(now - reset_t) / 1000.0f / dur;+ shown = (uint32_t)((float)sv.score * (1 - (t > 1 ? 1 : t)) + 0.5f);+ cam = cam_from + (cam_to - cam_from) * ease_io(t);+ if (t >= 1) break;+ } else+ cam = cam_from + (cam_to - cam_from) * ease_io((float)(now - cam_t) / 300.0f);+ if (f % 2) continue;+ render();+ snprintf(path, sizeof path, "%s/f_%04d.ppm", argv[2], k++);+ picture(path);+ }+ printf("score %u\n", sv.score);+ return 0;+ }+ /* the bot, a little off each time */+ uint32_t best = 0;+ long total = 0;+ for (int g = 0; g < 300; g++) {+ new_game();+ while (drop((r01() - 0.5f) * (0.2f + 1.6f * r01()), false) && sv.score < 2000) {}+ total += sv.score, best = sv.score > best ? sv.score : best;+ }+ printf("bot: 300 towers, %ld blocks on average, best %u\n", total / 300, best);+ CHECK(best > 100, "the bot should build past 100 at least once");+ /* random presses */+ for (int g = 0; g < 300; g++) {+ new_game();+ while (drop(0, true) && sv.score < 500) {}+ }+ /* the save: back as it was; damaged, a fresh start */+ new_game();+ for (int n = 0; n < 5; n++) drop(0.5f, false);+ sv.best = 77;+ save();+ uint32_t score = sv.score;+ memset(&sv, 0, sizeof sv);+ load();+ CHECK(sv.best == 77 && sv.score == score && (sv.flags & 1), "save not read back");+ disk[30] ^= 4;+ load();+ CHECK(sv.best == 0 && !(sv.flags & 1), "a damaged file should start afresh");+ render();+ printf(fails ? "FAILED (%d)\n" : "ok\n", fails);+ return fails != 0;+}diff --git a/games/towerblock/tests/test.c b/games/towerblock/tests/test.cdeleted file mode 100644index ab472f6e..00000000--- a/games/towerblock/tests/test.c+++ /dev/null@@ -1,167 +0,0 @@-/* 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.pydeleted file mode 100644index 4874fac7..00000000--- a/games/towerblock/tests/test_compact_nwa.py+++ /dev/null@@ -1,90 +0,0 @@-#!/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.pydeleted file mode 100644index 8b66b5fb..00000000--- a/games/towerblock/tools/build.py+++ /dev/null@@ -1,90 +0,0 @@-#!/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.pydeleted file mode 100644index f320bb54..00000000--- a/games/towerblock/tools/compact_nwa.py+++ /dev/null@@ -1,228 +0,0 @@-#!/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.pydeleted file mode 100644index 2da8972c..00000000--- a/games/towerblock/tools/icon.py+++ /dev/null@@ -1,18 +0,0 @@-#!/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.lddeleted file mode 100644index 28679582..00000000--- a/games/towerblock/tools/standalone.ld+++ /dev/null@@ -1,15 +0,0 @@-/* 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) }-}diff --git a/tests/test_games.py b/tests/test_games.pyindex 9a7a22bf..443bc03a 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -69,6 +69,8 @@ GAMES = {# past how to play, two flaps; next time the run goes on after a flap"flappydunk": ("FlappyDunk.nwa", "flappydunk.sav", presses((1500, "ok"), (2200, "ok"), (2550, "ok")), 3500,presses((1500, "ok")), 2500),+ # past how to play, a game started and a block placed; next time the tower is still there, waiting+ "towerblock": ("TowerBlocks.nwa", "towerblocks.sav", presses((1500, "ok"), (2200, "ok"), (3000, "ok")), 3600, [], 2500),"flappybird": ("FlappyBird.nwa", "flappy.sav",presses((1500, "down"), (1800, "ok"), (2100, "right"), (2400, "back"), (2700, "up"),(2900, "right"), (3100, "ok"), (3900, "ok")) + every(4300, 7500, 450, "ok"), 9000,@@ -283,6 +285,9 @@ CHECKS = {# a run kept (guide read), the ball on its way; then further along the same run"flappydunk": (lambda v: len(v) == 200 and v[:2] == b"F\1" and v[2] & 3 == 3 and struct.unpack_from("<f", v, 24)[0] > 1,lambda v: v[2] & 1 and struct.unpack_from("<f", v, 24)[0] > 6),+ # a tower kept (guide read) with one block placed; then kept as it was+ "towerblock": (lambda v: len(v) == 668 and v[:2] == b"T\1" and v[2] & 3 == 3 and struct.unpack_from("<I", v, 12)[0] == 1,+ lambda v: v[2] & 1 and struct.unpack_from("<I", v, 12)[0] == 1),"flappybird": (lambda v: len(v) == 26 and v[:3] == b"F\1\1" and v[8] == 3, # Custom, Speed Fastlambda v: v[2] == 1 and v[8] == 4), # read back, Speed Insane# the game went on (more points, fewer dots), then Fast was chosen and the game kept