Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Add standalone Flappy Dunk by Bobydeluxe

Bobydeluxe2c398f58f0e3
diff --git a/README.md b/README.md
index 67eeae81..6c6abfe7 100644
--- a/README.md
+++ b/README.md
@@ -87,6 +87,10 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
</tr>
</table>
+**[Flappy Dunk](games/flappydunk/README.md)** is also offered as a separate,
+English-only app by **Bobydeluxe**. Its README includes build and installation
+instructions.
+
## How to install
You need your calculator, its USB cable, and a computer with **Google Chrome** or **Microsoft Edge**. It takes about 2 minutes.
@@ -198,6 +202,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **[Tatone26](https://github.com/Tatone26/Numworks-games)**'s **All the Apps** inspired NumPlay's list of classics. Flappy Bird, Pac-Man, Snake, Connect Four, Solitaire and 2048 are written in C for NumPlay and keep its options, with no code copied from it. Tetris is Tatone26's own, which they released into the public domain, adapted for NumPlay.
- **[Gabriele Cirulli](https://github.com/gabrielecirulli/2048)** made 2048.
+- **[Bobydeluxe](https://github.com/Bobydeluxe)** made **[Flappy Dunk](games/flappydunk/README.md)**, including its English interface, procedural artwork and basketball engine. Inspired by Flappy Dunk; no original game assets are bundled.
- **Block Blast!** by [Hungry Studio](https://www.hungrystudio.com) inspired NumPlay's Block Blast, written in C for NumPlay with no code or art from it. Its blocks, scoring and colours follow measurements of the app by the players behind [blockblast-Self-Improvement-loop](https://github.com/Kucze3205/blockblast-Self-Improvement-loop).
- Snake, Solitaire and Block Breaker look and play like **Google's games** in Search. They are drawn from scratch; nothing is taken from Google.
- **Chrome's dinosaur game** by Google inspired Chrome Dino, which ports its rules, numbers and pictures from [Chromium's source](https://chromium.googlesource.com/chromium/src/+/main/components/neterror/resources/dino_game/) (BSD license). **[LilyTheCatgirl](https://github.com/LilyTheCuteCatgirl)** brought it to NumPlay. Not affiliated with Google.
diff --git a/games/flappydunk/.gitignore b/games/flappydunk/.gitignore
new file mode 100644
index 00000000..16be8f21
--- /dev/null
+++ b/games/flappydunk/.gitignore
@@ -0,0 +1 @@
+/output/
diff --git a/games/flappydunk/Makefile b/games/flappydunk/Makefile
new file mode 100644
index 00000000..4f83fb2b
--- /dev/null
+++ b/games/flappydunk/Makefile
@@ -0,0 +1,54 @@
+# Flappy Dunk: English-only app and NumPlay module.
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+PYTHON ?= python3
+ARM_LD ?= arm-none-eabi-ld
+OBJCOPY = arm-none-eabi-objcopy
+PACKER = tools/compact_nwa.py tools/standalone.ld
+SRC = src/main.c src/physics.c src/save.c src/render.c
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+OBJECTS = $(patsubst src/%.c,output/%.o,$(SRC))
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device) -Os -Wall -Wextra -Werror
+CFLAGS += -fno-math-errno -fsingle-precision-constant -ffunction-sections -fdata-sections -fstack-usage
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fvisibility=internal
+LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable,--gc-sections,-e,main -flinker-output=nolto-rel
+
+.PHONY: build check module sim-module test playability clean
+build: output/flappydunk.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/flappydunk-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/flappydunk.nwa: output/flappydunk-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/flappydunk.nwa output/flappydunk.bin --ram-length 107674
+ $(NWLINK) nwa-bin output/flappydunk-debug.nwa output/flappydunk-debug.bin --ram-length 107674
+ $(PYTHON) -c "from pathlib import Path; assert Path('output/flappydunk.bin').read_bytes() == Path('output/flappydunk-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
+playability: | output
+ $(HOST_CC) -std=c11 -O2 -Wall -Wextra -Werror -Isrc tests/playability.c src/physics.c -lm -o output/playability
+ cd output && ./playability
+HOST_CC ?= cc
+sim-module: | output
+ mkdir -p output/sim
+ cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_flappydunk_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_flappydunk_main -o output/sim-module.o
+clean:
+ rm -rf output
diff --git a/games/flappydunk/README.md b/games/flappydunk/README.md
new file mode 100644
index 00000000..c359f742
--- /dev/null
+++ b/games/flappydunk/README.md
@@ -0,0 +1,87 @@
+# Flappy Dunk
+
+Game made by **Bobydeluxe**.
+
+An English-only NumWorks game inspired by one-button basketball. Fly a winged
+ball and descend through every hoop. Menus, physics and procedural artwork
+are original; no mobile-game assets are bundled.
+
+![Title screen](docs/title.png)
+![A clean swish](docs/gameplay.png)
+
+## Play
+
+Install `FlappyDunk.nwa` with a compatible NumWorks external-app installer.
+This PR provides a separate application; open Flappy Dunk from the calculator's Home menu after installation.
+
+| Key | Action |
+| --- | --- |
+| OK, EXE or Up | Flap once; release before the next flap |
+| Back | Pause during flight; go back in menus |
+| Home or On/Off | Save and exit |
+| Arrows | Choose a menu item or ball |
+
+The title has three choices: **Play / Continue**, **Locker**, **How to Play**.
+The two decorative slogans, Flight School, challenges and medal system have
+been removed. Only endless flight remains, with gradually increasing speed.
+
+Pass through hoops from above, with the entire ball clearing the rim. A normal
+basket earns one point. A centred shot without rim contact is a swish;
+consecutive swishes award 2, 3, 4, then 5 points each. Missing a hoop or hitting
+the floor or ceiling ends the flight. The green marker identifies the next hoop.
+
+The Locker's balls are cosmetic and do not change difficulty. New unlocks
+use the best score from a single endless run:
+
+| Ball | Required best score |
+| --- | ---: |
+| Classic | Available from the start |
+| Midnight | 15 |
+| Mint | 35 |
+| Candy | 70 |
+| Golden | 120 |
+| Cosmic | 200 |
+
+![Locker](docs/locker.png)
+
+Previously earned balls remain unlocked when importing an old save, including
+those obtained through the former medal system. No new medals can be earned
+or used. The selected ball, best and lifetime statistics survive the update.
+A normal flight resumes; an old challenge opens a fresh endless flight instead.
+
+Continuing opens a ready screen and waits for a fresh flap. Pause freezes
+simulation. Replacing a flight asks for confirmation. A full-storage exit
+offers Retry, Return, or an explicit exit without saving.
+
+## Build and verify
+
+Requires ARM GCC, Python 3 and nwlink 1.0.0:
+
+```sh
+make build check
+make test playability
+python tests/arm.py --nwlink /path/to/nwlink
+
+# Optional portable standalone build
+python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+```
+
+The Python build needs pyelftools and creates `output/FlappyDunk.nwa`, a debug
+build, an optional module object, four linked profiles and `output/sizes.json`. Pillow
+is needed to regenerate the launcher icon with `tools/icon.py`. The game-local
+lossless packer verifies that release/debug apps install identical bytes.
+
+The host suite tests scoring, rim contact, missed hoops, score-unlock
+boundaries, old save import, corruption rejection, 120,000 physics ticks and
+pixel-exact dirty redraws. The offline controller reaches 50 baskets through
+normal flap input; it is not shipped in the game. Run both host programs before
+the ARM suite because they generate its save and keyboard fixtures.
+
+The title screen credits **Bobydeluxe**.
+
+No heap or full-screen framebuffer: a 5,120-byte strip buffer, three reusable
+hoops and sixteen bounded particles. The fixed `FDK2` save payload remains
+160 bytes and imports `FDK1`. Older apps cannot read the new format. See
+[VALIDATION.md](VALIDATION.md) for measurements and limitations.
+
+Licensed under GPL-3.0-only, like NumPlay.
diff --git a/games/flappydunk/VALIDATION.md b/games/flappydunk/VALIDATION.md
new file mode 100644
index 00000000..5dc724a9
--- /dev/null
+++ b/games/flappydunk/VALIDATION.md
@@ -0,0 +1,55 @@
+# Local validation — 20 October 2026
+
+Simplified-menu/endless-only update. ARM GCC 15.2.1, nwlink 1.0.0, C11,
+`-Os`, LTO and warnings treated as errors.
+
+| Resource | Previous version | Updated version |
+| --- | ---: | ---: |
+| Standalone NWA | 26,472 bytes | 23,580 bytes |
+| Installed flash | 19,652 bytes | 17,532 bytes |
+| Static RAM | 5,965 bytes | 5,941 bytes |
+| Observed standalone ARM stack | 696 bytes | 648 bytes |
+| Save payload | 160 bytes | 160 bytes |
+
+The downloadable app is 10.9% smaller; installed flash is 10.8% smaller.
+Challenge data, mode-specific physics, the selection screen and medal UI are
+removed. The existing lossless icon/ELF packing remains. Release/debug apps
+produce identical installed bytes on N0110, N0115/custom, N0120 and Upsilon.
+
+- Host suite: scoring direction and complete passage, rim collision, missed
+ hoops, floor/ceiling, saturating totals, 120,000 endless simulation ticks,
+ save round trips every 19 ticks and every single-byte corruption rejected.
+- Score-only unlocks: each locked/exact boundary at 15, 35, 70, 120 and 200,
+ permanent ownership and an actual 13-to-15-point scoring transition pass.
+- Both legacy fixtures were generated and validated with the old engine.
+ Normal-flight import preserves flight state, totals and previously unlocked
+ balls; a discontinued course becomes a fresh endless flight. New `FDK2`
+ saves have zeroed old mode/medal fields and retain cosmetic ownership.
+ Malformed-but-checksummed data leaves live state unchanged.
+- Partial redraws match full redraws pixel-for-pixel over 140 moving frames;
+ unchanged frames produce no display push. No push exceeds 320 x 8 pixels.
+- Offline reachability controller: 50 baskets, 16 swishes, 70 points and 174
+ flaps through the normal input API, over 89.4 simulated seconds. It is a
+ test-only controller and is not part of the app.
+- Actual ARM app on all four profiles: held launcher input ignored, one flap
+ per fresh press, pause freeze, ready-on-resume, save/reload, preservation of
+ unrelated files and safe Home/On-Off exits. Maximum observed draw time:
+ 15 ms; no draws exceeded the 32 ms presentation interval.
+- ARM input replay scores at least three baskets and one swish, with live
+ particles and multipliers; maximum observed draw time 14 ms.
+- ARM menu navigation exercises the three title choices, Locker's locked
+ Cosmic ball at 200 points, guide, wraparound navigation and confirmed fresh
+ flight. Locked selection does not equip the ball. Both old save fixtures
+ migrate on the actual ARM app, retaining the selected Cosmic ball.
+- Full-storage exit remains interactive and existing data survives. Explicit
+ unsaved exit works. App RAM is cleared and firmware RAM remains intact.
+- Repository standalone smoke test passes two sessions, including a record
+ inserted after the first save. The published app does not register a game
+ in the combined launcher or alter its build, workflow or release scripts.
+- The lossless packing tests and four-profile ARM scenarios are repeated from
+ the isolated publication snapshot using the upstream repository helpers.
+
+
+Captures in `docs/title.png`, `docs/gameplay.png`, `docs/locker.png` come from the actual ARM app. Timings use the repository
+emulator model; they are not physical-calculator FPS measurements. The full
+all-game/translated build and physical NumWorks testing were not repeated.
diff --git a/games/flappydunk/docs/gameplay.png b/games/flappydunk/docs/gameplay.png
new file mode 100644
index 00000000..8dd75805
Binary files /dev/null and b/games/flappydunk/docs/gameplay.png differ
diff --git a/games/flappydunk/docs/locker.png b/games/flappydunk/docs/locker.png
new file mode 100644
index 00000000..a620e9d6
Binary files /dev/null and b/games/flappydunk/docs/locker.png differ
diff --git a/games/flappydunk/docs/title.png b/games/flappydunk/docs/title.png
new file mode 100644
index 00000000..adc6d081
Binary files /dev/null and b/games/flappydunk/docs/title.png differ
diff --git a/games/flappydunk/src/dunk.h b/games/flappydunk/src/dunk.h
new file mode 100644
index 00000000..17f4b72d
--- /dev/null
+++ b/games/flappydunk/src/dunk.h
@@ -0,0 +1,52 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Flappy Dunk: an original NumWorks implementation by Bobydeluxe.
+ */
+#ifndef FLAPPY_DUNK_H
+#define FLAPPY_DUNK_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define FD_TICK_MS 16
+#define FD_SAVE_BYTES 160
+#define FD_HOOPS 3
+#define FD_PARTICLES 16
+#define FD_SKINS 6
+#define FD_BALL_R 9
+#define FD_TOP 38
+#define FD_FLOOR 212
+
+enum { FD_WAITING, FD_RUNNING, FD_OVER };
+enum { FD_NO_REASON, FD_FLOOR_HIT, FD_CEILING_HIT, FD_MISSED };
+extern const char *const fd_skin_names[FD_SKINS];
+extern const uint16_t fd_skin_targets[FD_SKINS];
+
+typedef struct {
+ float x, y;
+ uint8_t state, touched, clean, wobble;
+} fd_hoop;
+typedef struct { float x,y,vx,vy; uint8_t life,kind; } fd_particle;
+typedef struct {
+ uint32_t best, baskets, swishes, runs, flaps, best_streak;
+ uint8_t skin, unlocked;
+} fd_stats;
+typedef struct {
+ float x,y,vx,vy,scroll;
+ fd_hoop hoop[FD_HOOPS];
+ fd_particle particle[FD_PARTICLES];
+ uint32_t rng,tick,score,baskets,swishes,flaps;
+ uint16_t streak,peak;
+ uint8_t phase,reason,present,started;
+ uint8_t flap_anim,message,message_timer,award,unlocks;
+} fd_game;
+
+void fd_new(fd_game *g,uint32_t seed);
+bool fd_flap(fd_game *g,fd_stats *s);
+void fd_step(fd_game *g,fd_stats *s);
+float fd_half_width(const fd_game *g);
+float fd_speed(const fd_game *g);
+uint8_t fd_unlocked(const fd_stats *s);
+bool fd_valid(const fd_game *g,const fd_stats *s);
+void fd_encode(const fd_game *g,const fd_stats *s,uint8_t out[FD_SAVE_BYTES]);
+bool fd_decode(fd_game *g,fd_stats *s,const uint8_t *data,size_t length);
+#endif
diff --git a/games/flappydunk/src/icon.png b/games/flappydunk/src/icon.png
new file mode 100644
index 00000000..fcbc2ef2
Binary files /dev/null and b/games/flappydunk/src/icon.png differ
diff --git a/games/flappydunk/src/main.c b/games/flappydunk/src/main.c
new file mode 100644
index 00000000..dea1cff5
--- /dev/null
+++ b/games/flappydunk/src/main.c
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <eadk.h>
+#include "dunk.h"
+#include "render.h"
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Flappy Dunk";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+#define KEY(k) (UINT64_C(1) << (k))
+#define SAVE_NAME "flappydunk.sav"
+static fd_game game;
+static fd_stats stats;
+static uint8_t save_data[FD_SAVE_BYTES];
+static uint32_t last_checksum;
+static bool 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) {
+ fd_encode(&game,&stats,save_data);
+ unsigned n=FD_SAVE_BYTES-4;
+ uint32_t checksum=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(checksum==last_checksum&&!save_failed)return true;
+ save_failed=!ef_write(SAVE_NAME,save_data,FD_SAVE_BYTES);
+ if(!save_failed)last_checksum=checksum;
+ return !save_failed;
+}
+static unsigned grid(unsigned n,uint64_t hit,unsigned count) {
+ if(hit&KEY(eadk_key_left))n=n%3?n-1:n+2;
+ if(hit&KEY(eadk_key_right))n=n%3<2?n+1:n-2;
+ if(hit&KEY(eadk_key_up))n=(n+count-3)%count;
+ if(hit&KEY(eadk_key_down))n=(n+3)%count;
+ return n;
+}
+int main(void) {
+ np_app_begin();
+ uint32_t len=0;
+ const uint8_t *p=ef_read(SAVE_NAME,&len);
+ fd_decode(&game,&stats,p,len);
+ unsigned view=FD_TITLE,selected=0,help_return=FD_TITLE;
+ unsigned confirm_return=FD_PAUSE,confirm_selection=0;
+ unsigned error_return=FD_TITLE;
+ 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;
+ fd_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 flap=ok||(hit&KEY(eadk_key_up));
+ if(view!=FD_SAVE_ERROR&&(keys&(KEY(eadk_key_home)|KEY(eadk_key_on_off)))) {
+ if(save())break;
+ error_return=view==FD_FLIGHT?FD_READY:view;
+ view=FD_SAVE_ERROR;selected=0;stale=keys;hit=0;ok=back=flap=false;
+ }
+ if(view==FD_FLIGHT) {
+ if(back) {view=FD_PAUSE;selected=0;save();}
+ else {
+ if(flap)fd_flap(&game,&stats);
+ if(now-tick_at>4*FD_TICK_MS)tick_at=now-4*FD_TICK_MS;
+ while(now-tick_at>=FD_TICK_MS&&game.phase==FD_RUNNING) {
+ fd_step(&game,&stats);tick_at+=FD_TICK_MS;
+ }
+ if(game.phase>=FD_OVER) {view=FD_RESULT;selected=0;save();}
+ if(now-save_at>=5000) {save();save_at=now;}
+ }
+ } else {
+ tick_at=now;
+ if(view==FD_TITLE) {
+ if(hit&KEY(eadk_key_down))selected=(selected+1)%3;
+ if(hit&KEY(eadk_key_up))selected=(selected+2)%3;
+ if(back) {
+ if(save())break;
+ view=FD_SAVE_ERROR;error_return=FD_TITLE;selected=0;
+ } else if(ok) {
+ if(selected==0) {
+ if(!game.present||game.phase>=FD_OVER)fd_new(&game,eadk_random()^now);
+ view=FD_READY;
+ } else if(selected==1)view=FD_LOCKER;
+ else {view=FD_GUIDE;help_return=FD_TITLE;}
+ selected=view==FD_LOCKER?stats.skin:0;
+ }
+ } else if(view==FD_READY) {
+ if(back)view=FD_TITLE,selected=0;
+ else if(flap) {fd_flap(&game,&stats);view=FD_FLIGHT;tick_at=now;}
+ } else if(view==FD_PAUSE) {
+ if(hit&KEY(eadk_key_down))selected=(selected+1)%4;
+ if(hit&KEY(eadk_key_up))selected=(selected+3)%4;
+ if(back||(ok&&selected==0))view=FD_READY;
+ else if(ok&&selected==1) {
+ confirm_return=FD_PAUSE;confirm_selection=1;
+ view=FD_CONFIRM;selected=0;
+ } else if(ok&&selected==2)help_return=FD_PAUSE,view=FD_GUIDE;
+ else if(ok&&selected==3)view=FD_TITLE,selected=0;
+ } else if(view==FD_LOCKER) {
+ selected=grid(selected,hit,FD_SKINS);
+ if(back)view=FD_TITLE,selected=1;
+ else if(ok&&(fd_unlocked(&stats)&(1u<<selected))) {stats.skin=(uint8_t)selected;save();}
+ } else if(view==FD_GUIDE) {
+ if(back||ok)view=help_return,selected=0;
+ } else if(view==FD_CONFIRM) {
+ if(hit&(KEY(eadk_key_up)|KEY(eadk_key_down)))selected=!selected;
+ if(back||(ok&&selected==0))view=confirm_return,selected=confirm_selection;
+ else if(ok) {fd_new(&game,eadk_random()^now);view=FD_READY;selected=0;}
+ } else if(view==FD_RESULT) {
+ if(hit&(KEY(eadk_key_up)|KEY(eadk_key_down)))selected=!selected;
+ if(back||(ok&&selected==1))view=FD_TITLE,selected=0;
+ else if(ok) {fd_new(&game,eadk_random()^now);view=FD_READY;selected=0;}
+ } else if(view==FD_SAVE_ERROR) {
+ if(back)break;
+ if(ok&&save())break;
+ if(hit&KEY(eadk_key_one))view=error_return,selected=0;
+ }
+ }
+ if(now-draw_at>=32||hit||perf_frames==0) {
+ uint32_t begin=(uint32_t)eadk_timing_millis();
+ fd_render(&game,&stats,view,selected,now,save_failed,push);
+ uint32_t spent=(uint32_t)eadk_timing_millis()-begin;
+ if(spent>perf_max)perf_max=spent;
+ if(spent>32)++perf_slow;
+ ++perf_frames;draw_at=now;
+ }
+ eadk_timing_msleep(4);
+ }
+ return np_app_end();
+}
diff --git a/games/flappydunk/src/physics.c b/games/flappydunk/src/physics.c
new file mode 100644
index 00000000..34446695
--- /dev/null
+++ b/games/flappydunk/src/physics.c
@@ -0,0 +1,175 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "dunk.h"
+#include <math.h>
+#include <string.h>
+
+const char *const fd_skin_names[] = {"CLASSIC","MIDNIGHT","MINT","CANDY","GOLDEN","COSMIC"};
+const uint16_t fd_skin_targets[] = {0,15,35,70,120,200};
+static const int8_t wave[32] = {0,6,12,18,23,27,30,31,32,31,30,27,23,18,12,6,
+ 0,-6,-12,-18,-23,-27,-30,-31,-32,-31,-30,-27,-23,-18,-12,-6};
+static float clamp(float v,float lo,float hi) { return v<lo?lo:v>hi?hi:v; }
+static void add(uint32_t *value,uint32_t n) { *value=UINT32_MAX-*value<n?UINT32_MAX:*value+n; }
+static uint32_t random32(fd_game *g) {
+ uint32_t x=g->rng; x^=x<<13;x^=x>>17;x^=x<<5;return g->rng=x;
+}
+uint8_t fd_unlocked(const fd_stats *s) {
+ uint8_t mask=(uint8_t)(s->unlocked|1);
+ for(unsigned i=1;i<FD_SKINS;++i)if(s->best>=fd_skin_targets[i])mask|=(uint8_t)(1u<<i);
+ return mask;
+}
+float fd_half_width(const fd_game *g) {
+ return g->baskets<5?29.0f:g->baskets<20?27.0f:25.0f;
+}
+float fd_speed(const fd_game *g) {
+ float n=g->baskets<80?(float)g->baskets:80.0f;
+ return 1.10f+n*0.0035f;
+}
+static void generate(fd_game *g,fd_hoop *h,float x,float previous_y) {
+ int delta=(int)(random32(g)%65)-32;
+ float next_y=previous_y+delta;
+ *h=(fd_hoop){x,clamp(next_y,103.0f,172.0f),0,0,0,0};
+}
+void fd_new(fd_game *g,uint32_t seed) {
+ memset(g,0,sizeof *g);
+ g->rng=seed?seed:0x6C8E9CF5u;
+ g->phase=FD_WAITING;g->present=1;
+ g->x=80;g->y=111;
+ g->hoop[0]=(fd_hoop){191,148,0,0,0,0};
+ for(unsigned i=1;i<FD_HOOPS;++i) {
+ float next_x=g->hoop[i-1].x+129;
+ generate(g,&g->hoop[i],next_x,g->hoop[i-1].y);
+ }
+}
+static void finish(fd_game *g,unsigned reason) { g->phase=FD_OVER;g->reason=(uint8_t)reason; }
+bool fd_flap(fd_game *g,fd_stats *s) {
+ if(!g->present||g->phase>=FD_OVER)return false;
+ if(!g->started) { g->started=1;add(&s->runs,1); }
+ g->phase=FD_RUNNING;g->vy=-2.85f;g->flap_anim=12;
+ add(&g->flaps,1);add(&s->flaps,1);return true;
+}
+static void burst(fd_game *g,float x,float y,bool clean) {
+ /* Cosmetic particles never consume the course generator's random stream. */
+ for(unsigned i=0;i<FD_PARTICLES;++i) {
+ unsigned a=(i*7)&31;
+ g->particle[i]=(fd_particle){x,y,wave[a]*0.045f,wave[(a+8)&31]*0.045f-0.7f,
+ (uint8_t)(22+i%9),(uint8_t)(clean?i%3:0)};
+ }
+}
+static void score(fd_game *g,fd_stats *s,fd_hoop *h) {
+ uint8_t before=fd_unlocked(s);
+ bool clean=h->clean&&!h->touched;
+ h->state=2;h->wobble=20;
+ add(&g->baskets,1);add(&s->baskets,1);
+ if(clean) {
+ if(g->streak<999)++g->streak;
+ if(g->streak>g->peak)g->peak=g->streak;
+ if(g->streak>s->best_streak)s->best_streak=g->streak;
+ add(&g->swishes,1);add(&s->swishes,1);
+ } else g->streak=0;
+ unsigned award=clean?(g->streak<4?g->streak+1:5):1;
+ add(&g->score,award);
+ if(g->score>s->best)s->best=g->score;
+ s->unlocked=fd_unlocked(s);
+ g->award=(uint8_t)award;g->message=clean?2:1;g->message_timer=65;
+ burst(g,h->x,h->y,clean);
+ g->unlocks|=(uint8_t)(fd_unlocked(s)&~before);
+}
+static void rim_contact(fd_game *g,fd_hoop *h,float rim_x,float speed) {
+ float dx=g->x-rim_x,dy=g->y-h->y,rr=FD_BALL_R+2.2f;
+ if(fabsf(dx)>=rr||fabsf(dy)>=rr)return;
+ float d2=dx*dx+dy*dy;
+ if(d2>=rr*rr)return;
+ float distance=sqrtf(d2),nx,ny;
+ if(distance<0.0001f)nx=0,ny=-1;
+ else nx=dx/distance,ny=dy/distance;
+ g->x+=nx*(rr-distance+0.01f);g->y+=ny*(rr-distance+0.01f);
+ float relative=(g->vx+speed)*nx+g->vy*ny;
+ if(relative<0) { g->vx-=relative*1.28f*nx;g->vy-=relative*1.28f*ny; }
+ g->vx=clamp(g->vx,-3.0f,3.0f);g->vy=clamp(g->vy,-5.0f,5.0f);
+ if(h->state!=2)h->touched=1;
+ h->wobble=8;
+}
+void fd_step(fd_game *g,fd_stats *s) {
+ if(g->phase!=FD_RUNNING)return;
+ ++g->tick;
+ if(g->flap_anim)--g->flap_anim;
+ if(g->message_timer)--g->message_timer;
+ float speed=fd_speed(g),half=fd_half_width(g);
+ g->scroll+=speed/4;
+ if(g->scroll>=64)g->scroll-=64;
+ g->vx=(g->vx+(80-g->x)*0.006f)*0.955f;
+ g->vy+=0.155f;
+ g->vx=clamp(g->vx,-3.0f,3.0f);
+ g->vy=clamp(g->vy,-5.0f,5.0f);
+ for(unsigned i=0;i<FD_HOOPS;++i)if(g->hoop[i].wobble)--g->hoop[i].wobble;
+ /* Swept plane crossing and four short substeps prevent a fast ball from
+ * skipping the rim. A hoop scores only after a complete downward pass. */
+ for(unsigned sub=0;sub<4&&g->phase==FD_RUNNING;++sub) {
+ float old_x=g->x,old_y=g->y;
+ g->x+=g->vx*0.25f;g->y+=g->vy*0.25f;
+ for(unsigned i=0;i<FD_HOOPS&&g->phase==FD_RUNNING;++i) {
+ fd_hoop *h=&g->hoop[i];
+ float old_hx=h->x,old_hy=h->y;
+ h->x-=speed*0.25f;
+ float left=h->x-half,right=h->x+half;
+ rim_contact(g,h,left,speed);
+ rim_contact(g,h,right,speed);
+ if(h->state==0&&old_y<old_hy&&g->y>=h->y&&g->vy>0) {
+ float denominator=(g->y-h->y)-(old_y-old_hy);
+ float t=denominator>0?(old_hy-old_y)/denominator:0;
+ t=clamp(t,0.0f,1.0f);
+ float x=old_x-old_hx+((g->x-h->x)-(old_x-old_hx))*t;
+ if(fabsf(x)<=half-FD_BALL_R-1) {
+ h->state=1;h->clean=(uint8_t)(fabsf(x)<=half-FD_BALL_R-5);
+ }
+ }
+ if(h->state==1) {
+ if(g->y-FD_BALL_R>h->y+2&&g->vy>0)score(g,s,h);
+ else if(g->y+FD_BALL_R<h->y)h->state=0,h->clean=0;
+ }
+ if(h->state!=2&&h->x+half<g->x-FD_BALL_R-2&&g->phase==FD_RUNNING)finish(g,FD_MISSED);
+ }
+ if(g->phase==FD_RUNNING) {
+ if(g->y+FD_BALL_R>=FD_FLOOR)
+ finish(g,FD_FLOOR_HIT);
+ else if(g->y-FD_BALL_R<=FD_TOP)finish(g,FD_CEILING_HIT);
+ }
+ /* Prevent a rare double-rim impulse from escaping the view/snapshot range. */
+ g->x=clamp(g->x,20.0f,148.0f);g->y=clamp(g->y,(float)(FD_TOP+FD_BALL_R),(float)(FD_FLOOR-FD_BALL_R));
+ }
+ for(unsigned i=0;i<FD_HOOPS;++i) {
+ fd_hoop *h=&g->hoop[i];
+ if(h->x+half>=-4)continue;
+ unsigned last=0;
+ for(unsigned j=1;j<FD_HOOPS;++j)if(g->hoop[j].x>g->hoop[last].x)last=j;
+ float next_x=g->hoop[last].x+126+(random32(g)%16);
+ generate(g,h,next_x,g->hoop[last].y);
+ }
+ for(unsigned i=0;i<FD_PARTICLES;++i) {
+ fd_particle *p=&g->particle[i];if(!p->life)continue;
+ --p->life;p->x+=p->vx-speed;p->y+=p->vy;p->vy+=0.045f;
+ }
+}
+bool fd_valid(const fd_game *g,const fd_stats *s) {
+ if(s->skin>=FD_SKINS||s->unlocked>=1u<<FD_SKINS||s->best_streak>999||
+ s->swishes>s->baskets||s->best_streak>s->swishes||
+ !(fd_unlocked(s)&(1u<<s->skin)))return false;
+ if(g->phase>FD_OVER||g->reason>FD_MISSED||
+ g->present>1||g->started>1||g->streak>999||g->peak>999||g->peak<g->streak||
+ g->unlocks>=1u<<FD_SKINS)return false;
+ if(!g->present)return g->phase==FD_WAITING&&!g->started;
+ if((g->phase==FD_WAITING)==(g->started!=0)||g->baskets>s->baskets||
+ g->swishes>s->swishes||g->flaps>s->flaps||g->peak>g->swishes||
+ (g->phase==FD_OVER)!=(g->reason!=FD_NO_REASON))return false;
+ if(!g->rng||!isfinite(g->x)||!isfinite(g->y)||!isfinite(g->vx)||!isfinite(g->vy)||
+ !isfinite(g->scroll)||g->x<20||g->x>148||g->y<FD_TOP+FD_BALL_R-0.1f||
+ g->y>FD_FLOOR-FD_BALL_R+0.1f||fabsf(g->vx)>3.01f||fabsf(g->vy)>5.01f||
+ g->scroll<0||g->scroll>=64||g->swishes>g->baskets)return false;
+ for(unsigned i=0;i<FD_HOOPS;++i) {
+ const fd_hoop *h=&g->hoop[i];
+ if(!isfinite(h->x)||!isfinite(h->y)||h->x<-80||h->x>620||
+ h->y<90||h->y>183||h->state>2||
+ h->touched>1||h->clean>1||h->wobble>20)return false;
+ }
+ return true;
+}
diff --git a/games/flappydunk/src/render.c b/games/flappydunk/src/render.c
new file mode 100644
index 00000000..bfbc0a76
--- /dev/null
+++ b/games/flappydunk/src/render.c
@@ -0,0 +1,368 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Original procedural artwork. No sprites, framebuffer, or heap allocations.
+ */
+#include "render.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#define C(v) ((uint16_t)((((v) >> 8) & 0xF800) | (((v) >> 5) & 0x07E0) | (((v) >> 3) & 0x1F)))
+#define PAPER C(0xF5EEE3)
+#define INK C(0x354650)
+#define MUTED C(0x9A958C)
+#define GREEN C(0x3F8B87)
+#define RED C(0xD76150)
+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 fd_game *world;
+static const fd_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 fd_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 roundbox(int x, int y, int w, int h, int radius, uint16_t c) {
+ if (y >= y1 || y + h <= y0 || x >= x1 || x + w <= x0) return;
+ for (int j = y > y0 ? y : y0; j < y + h && j < y1; ++j) {
+ int dy = j < y + radius ? y + radius - j : j >= y + h - radius ? j - (y + h - radius - 1) : 0;
+ int inset = dy ? radius - (int)sqrtf((float)(radius * radius - dy * dy)) : 0;
+ rect(x + inset, j, w - 2 * inset, 1, c);
+ }
+}
+static void line(int a, int b, int c, int d, uint16_t ink) {
+ 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 circle(int x, int y, int r, uint16_t c, bool outline) {
+ if (y + r < y0 || y - r >= y1 || x + r < x0 || x - r >= x1) return;
+ for (int j = y - r > y0 ? y - r : y0; j <= y + r && j < y1; ++j) {
+ int half = (int)sqrtf((float)(r * r - (j - y) * (j - y)));
+ if (outline) {
+ pixel(x - half, j, c); pixel(x + half, j, c);
+ if (abs(j - y) >= r - 1) rect(x - half, j, 2 * half + 1, 1, c);
+ } else rect(x - half, j, 2 * half + 1, 1, c);
+ }
+}
+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 mix(uint16_t a,uint16_t b,unsigned amount) {
+ uint32_t x=((a|(uint32_t)a<<16)&0x07E0F81F),z=((b|(uint32_t)b<<16)&0x07E0F81F);
+ x=((x*(32-amount)+z*amount)>>5)&0x07E0F81F;
+ return (uint16_t)(x|x>>16);
+}
+static void ellipse(int x,int y,int rx,int ry,uint16_t color,bool outline) {
+ if(ry<=0||rx<=0||y+ry<y0||y-ry>=y1||x+rx<x0||x-rx>=x1)return;
+ for(int j=y-ry>y0?y-ry:y0;j<=y+ry&&j<y1;++j) {
+ float t=(float)(j-y)/ry;int half=(int)(rx*sqrtf(1-t*t));
+ if(!outline||abs(j-y)>=ry-1)rect(x-half,j,2*half+1,1,color);
+ else {rect(x-half,j,2,1,color);rect(x+half-1,j,2,1,color);}
+ }
+}
+static void stroke(int x,int y,int xx,int yy,int thick,uint16_t color) {
+ for(int i=0;i<thick;++i)line(x,y+i,xx,yy+i,color);
+}
+static void star(int x,int y,int r,uint16_t color) {
+ line(x-r,y,x+r,y,color);line(x,y-r,x,y+r,color);
+ if(r>2) {line(x-r+1,y-r+1,x+r-1,y+r-1,color);line(x+r-1,y-r+1,x-r+1,y+r-1,color);}
+}
+static const uint16_t ball_colors[]={C(0xF6A24E),C(0x54748B),C(0x83C9B6),C(0xEAA5B5),C(0xE8C265),C(0xA595CA)};
+static const uint16_t ball_rims[]={C(0xA96334),C(0x304B63),C(0x458C7F),C(0xAA667E),C(0xA08035),C(0x695991)};
+static void ball(int x,int y,int r,unsigned skin,unsigned lift,bool happy) {
+ if(y+r+3<y0||y-r-12>=y1||x+2*r+8<x0||x-2*r-8>=x1)return;
+ int feather=r/3+1,spread=r/2+2,up=(int)lift*r/30;
+ for(int side=-1;side<=1;side+=2) {
+ for(int i=2;i>=0;--i) {
+ int wx=x+side*(r+spread-i*spread/3),wy=y-2-up+i*feather/2;
+ ellipse(wx,wy,feather+3,feather,C(0xB7B1A6),false);
+ ellipse(wx,wy-1,feather+2,feather-1,C(0xFFFDF6),false);
+ }
+ }
+ circle(x+1,y+2,r,C(0xD9CCB8),false);
+ circle(x,y,r,ball_rims[skin],false);circle(x,y-1,r-1,ball_colors[skin],false);
+ ellipse(x-r/3,y-r/3,r/4+1,r/5+1,mix(ball_colors[skin],C(0xFFF2CE),21),false);
+ int top=y-r+1,bottom=y+r-1;
+ stroke(x-r+2,y-1,x+r-2,y-1,r>20?2:1,ball_rims[skin]);
+ /* Curved basketball seams, kept inside the ball. */
+ for(int row=top;row<=bottom;++row) {
+ float yy=(float)(row-y)/r;
+ int offset=(int)(r*0.42f*(1-yy*yy));
+ pixel(x-offset,row,ball_rims[skin]);pixel(x+offset,row,ball_rims[skin]);
+ }
+ if(skin==5) {star(x-r/3,y-r/2,r/8+1,C(0xFFF9E8));star(x+r/2,y+r/3,r/9+1,C(0xFFF9E8));}
+ int ex=r>18?r/4:3,ey=y+r/5;
+ if(happy) {
+ line(x-ex-1,ey,x-ex,ey-1,INK);line(x-ex,ey-1,x-ex+1,ey,INK);
+ line(x+ex-1,ey,x+ex,ey-1,INK);line(x+ex,ey-1,x+ex+1,ey,INK);
+ } else {rect(x-ex,ey,r>25?2:1,r>20?3:2,INK);rect(x+ex,ey,r>25?2:1,r>20?3:2,INK);}
+ line(x-2,ey+4,x,ey+5,INK);line(x,ey+5,x+2,ey+4,INK);
+}
+static void button(int x,int y,int w,const char *label,bool active) {
+ roundbox(x,y+2,w,23,6,C(0xD9CEBD));roundbox(x,y,w,23,6,active?GREEN:C(0xEEE5D7));
+ centered(x+w/2,y+8,label,1,active?C(0xFFFDF6):INK);
+}
+static void card(int x,int y,int w,int h) {
+ roundbox(x,y+3,w,h,8,C(0xDCCFBB));roundbox(x,y,w,h,8,C(0xFFF9ED));
+}
+static void wall(int shift,bool court) {
+ int top=court?FD_TOP:0,bottom=court?FD_FLOOR:240;
+ for(int y=top>y0?top:y0;y<bottom&&y<y1;++y) {
+ unsigned amount=(unsigned)((y-top)*9/(bottom-top));
+ rect(0,y,320,1,mix(PAPER,C(0xE5DCCB),amount));
+ }
+ uint16_t mortar=C(0xEAE1D3);
+ for(int y=top+9;y<bottom;y+=24) {
+ rect(0,y,320,1,mortar);
+ int offset=((y-top)/24&1)?32:0;
+ for(int x=-64+offset-shift;x<320;x+=64)rect(x,y,1,24,mortar);
+ }
+ if(court) {
+ rect(0,FD_TOP-2,320,2,C(0xD7C6AF));
+ rect(0,FD_FLOOR,320,13,C(0xE2BE92));rect(0,FD_FLOOR,320,2,C(0xC59A6C));
+ for(int x=-64-shift*2;x<320;x+=48)rect(x,FD_FLOOR+2,1,11,C(0xCFA77A));
+ }
+}
+static void hoop_back(const fd_hoop *h,float half) {
+ int x=(int)h->x,y=(int)h->y,w=(int)half;
+ if(y+28<y0||y-11>=y1||x+w+4<x0||x-w-4>=x1)return;
+ int sway=h->wobble?(h->wobble&4?2:-2):0;
+ uint16_t rope=h->state==2?C(0xC0B7A4):C(0xBEB3A0);
+ for(int i=0;i<5;++i) {
+ int px=x-w+4+i*(2*w-8)/4,bx=x-w/2+i*w/4+sway;
+ line(px,y+2,bx,y+21,rope);
+ if(i<4) {int nx=x-w+4+(i+1)*(2*w-8)/4;line(px,y+2,(bx+nx)/2,y+12,rope);line(nx,y+2,(bx+nx)/2,y+12,rope);}
+ }
+ stroke(x-w/2+sway,y+21,x+w/2+sway,y+21,1,rope);
+ ellipse(x,y,w+2,6,C(0xA4483D),false);
+ ellipse(x,y,w,4,PAPER,false);
+ for(int row=y-4;row<y;++row) {
+ float a=(float)(row-y)/4;int ex=(int)(w*sqrtf(1-a*a));
+ rect(x-ex,row,3,1,C(0xEF8C6D));rect(x+ex-2,row,3,1,C(0xEF8C6D));
+ }
+}
+static void hoop_front(const fd_hoop *h,float half) {
+ int x=(int)h->x,y=(int)h->y,w=(int)half;
+ if(y+7<y0||y>=y1)return;
+ for(int row=y;row<=y+6;++row) {
+ float a=(float)(row-y)/6;int edge=(int)((w+2)*sqrtf(1-a*a));
+ if(row<y+4) {
+ float t=(float)(row-y)/4;int inner=(int)(w*sqrtf(1-t*t));
+ rect(x-edge,row,edge-inner+1,1,RED);rect(x+inner,row,edge-inner+1,1,RED);
+ } else rect(x-edge,row,2*edge+1,1,RED);
+ }
+ if(h->wobble>12)star(x-w-6,y-4,3,C(0xE6B853));
+}
+static void flight(void) {
+ const fd_game *g=world;
+ wall((int)g->scroll,true);
+ text(12,9,"FLAPPY DUNK",1,INK);text(12,23,"ENDLESS",1,MUTED);
+ number(147,10,g->score,g->score<10000?2:1,INK);
+ text(252,9,"BEST",1,MUTED);number(252,22,stats->best,1,INK);
+ float half=fd_half_width(g);
+ unsigned next=FD_HOOPS;float nx=1000;
+ for(unsigned i=0;i<FD_HOOPS;++i) {
+ const fd_hoop *h=&g->hoop[i];hoop_back(h,half);
+ if(h->state!=2&&h->x<nx)nx=h->x,next=i;
+ }
+ if(next<FD_HOOPS&&g->phase<FD_OVER) {
+ const fd_hoop *h=&g->hoop[next];int x=(int)h->x,y=(int)h->y;
+ line(x-3,y-13,x,y-10,GREEN);line(x,y-10,x+3,y-13,GREEN);
+ }
+ int shadow=12+(int)(g->y-FD_TOP)/12;
+ ellipse((int)g->x,FD_FLOOR+5,shadow,2,C(0xCDA779),false);
+ if(g->streak>=3) {
+ for(int i=3;i>0;--i)circle((int)g->x-9-i*4,(int)g->y+i/2,4-i,C(0xEDB55C),false);
+ }
+ ball((int)g->x,(int)g->y,FD_BALL_R,stats->skin,g->flap_anim,g->message_timer&&g->message==2);
+ for(unsigned i=0;i<FD_HOOPS;++i)hoop_front(&g->hoop[i],half);
+ for(unsigned i=0;i<FD_PARTICLES;++i) {
+ const fd_particle *p=&g->particle[i];if(!p->life)continue;
+ if(p->kind==2)star((int)p->x,(int)p->y,p->life>14?2:1,C(0xD8B85F));
+ else circle((int)p->x,(int)p->y,p->life>14?2:1,p->kind?GREEN:RED,false);
+ }
+ if(g->message_timer) {
+ card(200,49,108,28);
+ text(209,59,g->message==2?"SWISH!":"DUNK!",1,g->message==2?GREEN:RED);
+ text(262,59,g->message==2?"X":"+",1,INK);number(274,59,g->award,1,INK);
+ }
+ text(12,231,"OK FLAP | BACK PAUSE",1,INK);
+ if(g->streak>1) {text(213,231,"STREAK",1,GREEN);number(260,231,g->streak,1,GREEN);}
+ else text(238,231,"HOME EXIT",1,MUTED);
+
+}
+static void title(void) {
+ wall(0,false);
+ text(17,35,"FLAPPY",3,INK);text(17,62,"DUNK",3,RED);
+ ellipse(85,206,55,5,C(0xD9CCB7),false);
+ fd_hoop h={86,187,0,0,0,0};hoop_back(&h,42);
+ unsigned lift=6+((clock_ms/130)%4)*3;
+ ball(84,147,32,stats->skin,lift,false);hoop_front(&h,42);
+ card(190,32,114,48);text(202,41,"PERSONAL BEST",1,MUTED);
+ number(202,56,stats->best,stats->best<100000?2:1,INK);
+ bool resume=world->present&&world->started&&world->phase<FD_OVER;
+ button(185,96,121,resume?"CONTINUE":"PLAY",selection==0);
+ button(185,132,121,"LOCKER",selection==1);
+ button(185,168,121,"HOW TO PLAY",selection==2);
+ text(15,230,"BY BOBYDELUXE",1,MUTED);text(194,230,"OK SELECT",1,MUTED);
+}
+static void locker(void) {
+ wall(0,false);text(12,12,"YOUR LOCKER",2,INK);text(12,35,"UNLOCK WITH YOUR BEST SCORE",1,MUTED);
+ uint8_t unlocked=fd_unlocked(stats);
+ for(unsigned i=0;i<FD_SKINS;++i) {
+ int x=12+(int)(i%3)*102,y=57+(int)(i/3)*73;bool active=i==selection,open=unlocked&(1u<<i);
+ roundbox(x-1,y-1,96,67,7,active?GREEN:C(0xDDD4C5));roundbox(x,y,94,65,6,open?C(0xFFF9ED):C(0xE7E0D6));
+ ball(x+46,y+25,15,i,active?12:0,stats->skin==i);
+ centered(x+47,y+49,fd_skin_names[i],1,open?INK:MUTED);
+ if(stats->skin==i)star(x+82,y+10,3,GREEN);
+ if(!open) {roundbox(x+68,y+7,14,11,2,C(0x9D998D));circle(x+75,y+6,4,C(0x9D998D),true);}
+ }
+ if(!(unlocked&(1u<<selection))) {
+ text(12,213,"BEST",1,MUTED);number(43,213,fd_skin_targets[selection],1,INK);
+ text(76,213,"POINTS TO UNLOCK",1,MUTED);
+ } else text(12,213,selection==stats->skin?"EQUIPPED":"OK TO EQUIP",1,GREEN);
+ text(12,231,"ARROWS CHOOSE",1,MUTED);text(264,231,"BACK",1,MUTED);
+}
+static void modal(void) {
+ for(int y=y0;y<y1;++y)for(int x=x0;x<x1;++x)if((x+y)&1)pixel(x,y,C(0xD5CBBB));
+ card(38,31,244,177);
+ if(page==FD_READY) {
+ centered(160,50,world->started?"BACK IN THE AIR":"READY TO DUNK?",2,INK);
+ centered(160,81,"FLAP TO STAY UP.",1,MUTED);
+ centered(160,97,"DROP THROUGH EVERY HOOP.",1,MUTED);
+ fd_hoop h={160,139,0,0,0,0};hoop_back(&h,24);ball(160,119,12,stats->skin,12,false);hoop_front(&h,24);
+ button(68,173,184,"OK / EXE / UP TO FLAP",true);
+ } else if(page==FD_GUIDE) {
+ centered(160,45,"HOW TO FLY",2,INK);
+ text(52,70,"OK / EXE / UP FLAP ONCE",1,INK);
+ text(52,85,"BACK PAUSE",1,INK);
+ text(52,100,"HOME SAVE AND EXIT",1,INK);
+ text(52,124,"GO DOWN THROUGH EVERY HOOP.",1,MUTED);
+ text(52,139,"CENTRE SHOTS BUILD A STREAK.",1,MUTED);
+ text(52,154,"AVOID THE CEILING AND FLOOR.",1,MUTED);
+ button(92,179,136,"OK GOT IT",true);
+ } else if(page==FD_CONFIRM) {
+ centered(160,50,"START AGAIN?",2,INK);
+ centered(160,85,"YOUR CURRENT FLIGHT WILL END.",1,MUTED);
+ centered(160,103,"RECORDS AND UNLOCKS WILL STAY.",1,MUTED);
+ button(66,133,188,"KEEP PLAYING",selection==0);button(66,168,188,"NEW FLIGHT",selection==1);
+ } else if(page==FD_SAVE_ERROR) {
+ centered(160,48,"SAVE FAILED",2,RED);
+ centered(160,83,"CALCULATOR STORAGE IS FULL",1,INK);
+ centered(160,101,"OR THE SAVE CANNOT BE WRITTEN.",1,MUTED);
+ centered(160,123,"1 RETURN TO YOUR FLIGHT",1,GREEN);
+ button(66,151,188,"OK RETRY SAVE",true);
+ centered(160,190,"BACK EXIT WITHOUT SAVING",1,RED);
+ } else if(page==FD_RESULT) {
+ centered(160,45,"KEEP FLYING!",2,INK);
+ static const char *const why[]={"","THE FLOOR GOT YOU.","A LITTLE TOO HIGH.","YOU MISSED A HOOP."};
+ centered(160,69,why[world->reason],1,MUTED);
+ text(63,89,"SCORE",1,MUTED);number(119,85,world->score,world->score<100000?2:1,INK);
+ text(205,89,"SWISH",1,MUTED);number(246,89,world->swishes,1,GREEN);
+ text(63,111,world->unlocks?"NEW BALL IN YOUR LOCKER!":"YOUR NEXT SWISH IS WAITING.",1,world->unlocks?GREEN:MUTED);
+ button(65,129,190,"PLAY AGAIN",selection==0);
+ button(65,158,190,"TITLE SCREEN",selection==1);
+ } else {
+ centered(160,44,"TAKE A BREATHER",2,INK);
+ centered(160,69,failed?"STORAGE FULL - SAVE FAILED":"YOUR FLIGHT IS SAVED.",1,failed?RED:MUTED);
+ button(65,86,190,"RESUME",selection==0);button(65,115,190,"NEW FLIGHT",selection==1);
+ button(65,144,190,"HOW TO PLAY",selection==2);button(65,173,190,"TITLE SCREEN",selection==3);
+ }
+}
+static unsigned old_page=99,old_selection,old_skin;
+static uint32_t old_tick,old_score,old_best,old_clock;
+static bool old_failed;
+void fd_render(const fd_game *g,const fd_stats *s,unsigned view,unsigned selected,uint32_t ms,bool save_failed,fd_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_skin!=s->skin||old_failed!=failed;
+ if(full)mark(0,0,320,240);
+ else if(view==FD_FLIGHT&&old_tick!=g->tick)mark(0,FD_TOP,320,240-FD_TOP);
+ else if(view==FD_TITLE&&old_clock!=ms/130)mark(12,106,153,110);
+ if(s->best!=old_best||g->score!=old_score)mark(0,0,320,FD_TOP);
+ old_page=view;old_selection=selected;old_skin=s->skin;old_tick=g->tick;old_score=g->score;
+ old_best=s->best;old_clock=ms/130;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==FD_TITLE)title();
+ else if(view==FD_LOCKER)locker();
+ else {flight();if(view!=FD_FLIGHT)modal();}
+ push(x0,y0,x1-x0,8,band);dirty_lo[row]=320;dirty_hi[row]=0;
+ }
+ initialized=true;
+}
diff --git a/games/flappydunk/src/render.h b/games/flappydunk/src/render.h
new file mode 100644
index 00000000..ba18d525
--- /dev/null
+++ b/games/flappydunk/src/render.h
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef FD_RENDER_H
+#define FD_RENDER_H
+#include "dunk.h"
+enum { FD_TITLE,FD_FLIGHT,FD_READY,FD_PAUSE,FD_GUIDE,FD_LOCKER,FD_RESULT,FD_CONFIRM,FD_SAVE_ERROR };
+typedef void (*fd_push)(int x,int y,int w,int h,const uint16_t *pixels);
+void fd_invalidate(void);
+void fd_render(const fd_game *g,const fd_stats *s,unsigned view,unsigned selected,
+ uint32_t clock_ms,bool save_failed,fd_push push);
+#endif
diff --git a/games/flappydunk/src/save.c b/games/flappydunk/src/save.c
new file mode 100644
index 00000000..5ddd78ca
--- /dev/null
+++ b/games/flappydunk/src/save.c
@@ -0,0 +1,68 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "dunk.h"
+#include <string.h>
+static void wr16(uint8_t *p,uint32_t v) { p[0]=(uint8_t)v;p[1]=(uint8_t)(v>>8); }
+static unsigned rd16(const uint8_t *p) { return p[0]|(unsigned)p[1]<<8; }
+static void wr32(uint8_t *p,uint32_t v) { wr16(p,v);wr16(p+2,v>>16); }
+static uint32_t rd32(const uint8_t *p) { return rd16(p)|(uint32_t)rd16(p+2)<<16; }
+static float fixed(const uint8_t *p,float unit) { return (int16_t)rd16(p)/unit; }
+static uint32_t hash(const uint8_t *p) {
+ uint32_t h=2166136261u;for(unsigned i=0;i<FD_SAVE_BYTES-4;++i)h=(h^p[i])*16777619u;return h;
+}
+void fd_encode(const fd_game *g,const fd_stats *s,uint8_t out[FD_SAVE_BYTES]) {
+ memset(out,0,FD_SAVE_BYTES);memcpy(out,"FDK2",4);
+ wr32(out+4,s->best);wr32(out+8,s->baskets);wr32(out+12,s->swishes);
+ wr32(out+16,s->runs);wr32(out+20,s->flaps);wr32(out+24,s->best_streak);
+ out[30]=s->skin;out[31]=fd_unlocked(s);
+ wr32(out+32,g->score);wr32(out+36,g->baskets);wr32(out+40,g->swishes);
+ wr32(out+44,g->flaps);wr32(out+48,g->rng);wr32(out+52,g->tick);
+ wr16(out+56,(int)(g->x*128));wr16(out+58,(int)(g->y*128));
+ wr16(out+60,(int)(g->vx*256));wr16(out+62,(int)(g->vy*256));wr16(out+64,(int)(g->scroll*256));
+ wr16(out+66,g->streak);wr16(out+68,g->peak);
+ out[71]=g->phase;out[72]=g->reason;out[73]=g->present;
+ out[74]=g->started;out[76]=g->unlocks;
+ for(unsigned i=0;i<FD_HOOPS;++i) {
+ const fd_hoop *h=&g->hoop[i];uint8_t *p=out+80+i*16;
+ wr16(p,(int)(h->x*32));wr16(p+2,(int)(h->y*128));
+ p[7]=h->state;p[8]=h->touched;p[9]=h->clean;p[10]=h->wobble;
+ }
+ wr32(out+FD_SAVE_BYTES-4,hash(out));
+}
+bool fd_decode(fd_game *g,fd_stats *s,const uint8_t *p,size_t length) {
+ if(!p||length!=FD_SAVE_BYTES||(memcmp(p,"FDK1",4)&&memcmp(p,"FDK2",4))||rd32(p+length-4)!=hash(p))return false;
+ bool legacy=p[3]=='1';
+ fd_game a;fd_stats b;memset(&a,0,sizeof a);memset(&b,0,sizeof b);
+ b.best=rd32(p+4);b.baskets=rd32(p+8);b.swishes=rd32(p+12);
+ b.runs=rd32(p+16);b.flaps=rd32(p+20);b.best_streak=rd32(p+24);
+ b.skin=p[30];b.unlocked=p[31];
+ a.score=rd32(p+32);a.baskets=rd32(p+36);a.swishes=rd32(p+40);
+ a.flaps=rd32(p+44);a.rng=rd32(p+48);a.tick=rd32(p+52);
+ a.x=fixed(p+56,128);a.y=fixed(p+58,128);a.vx=fixed(p+60,256);a.vy=fixed(p+62,256);a.scroll=fixed(p+64,256);
+ a.streak=(uint16_t)rd16(p+66);a.peak=(uint16_t)rd16(p+68);
+ a.phase=p[71];a.reason=p[72];a.present=p[73];a.started=p[74];a.unlocks=p[76];
+ if(legacy) {
+ /* Import earned cosmetics, then discard the removed mode/progress data. */
+ unsigned old_medals=rd16(p+28),earned=0;
+ if(old_medals>=4096||p[70]>12||a.phase>3||a.reason>4)return false;
+ for(unsigned i=0;i<12;++i)earned+=(old_medals>>i)&1;
+ static const uint8_t old_targets[]={0,5,15,30,60,100};
+ b.unlocked=1;
+ for(unsigned i=1;i<FD_SKINS;++i)
+ if(b.best>=old_targets[i]||earned>=i*2)b.unlocked|=(uint8_t)(1u<<i);
+ if(a.phase==3) {
+ if(!p[70]||!(old_medals&(1u<<(p[70]-1))))return false;
+ a.phase=FD_OVER;a.reason=FD_MISSED;
+ } else if(a.reason==4)a.reason=FD_FLOOR_HIT;
+ } else if(p[28]||p[29]||p[70]||!(b.unlocked&1))return false;
+ for(unsigned i=0;i<FD_HOOPS;++i) {
+ const uint8_t *v=p+80+i*16;fd_hoop *h=&a.hoop[i];
+ h->x=fixed(v,32);h->y=fixed(v+2,128);
+ if(legacy&&(fixed(v+4,128)<103||fixed(v+4,128)>172||v[6]>31)&&a.present)return false;
+ h->state=v[7];h->touched=v[8];h->clean=v[9];h->wobble=v[10];
+ }
+ if(!fd_valid(&a,&b))return false;
+ /* A discontinued course becomes a fresh endless flight, preserving totals,
+ * the personal best and every already-earned ball. Normal runs resume. */
+ if(legacy&&p[70])fd_new(&a,a.rng);
+ *g=a;*s=b;return true;
+}
diff --git a/games/flappydunk/tests/arm.py b/games/flappydunk/tests/arm.py
new file mode 100644
index 00000000..a8b8faa6
--- /dev/null
+++ b/games/flappydunk/tests/arm.py
@@ -0,0 +1,178 @@
+#!/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, host test and
+playability test first (they create the reference input and save fixture).
+"""
+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('flappydunk_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 after a completed sleep at each requested checkpoint.
+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 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/'flappydunk-debug.nwa')
+ report = []
+ 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)
+ storage = OUT/(name+'-storage.bin')
+ sentinel = record('untouched.py',b'print(42)\n')
+ storage.write_bytes(sentinel+b'\0\0')
+ c = emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink)
+ c.enable_checks()
+ # Held launcher OK is ignored. A new Up press makes exactly one flap.
+ c.keys = presses((0,'ok',300),(600,'ok',70),(1000,'up',400),(1450,'back',80),
+ (2600,'ok',70),(2850,'exe',70),(3200,'home',120))
+ c.run(550);c.save_png(str(OUT/(name+'-title.png')))
+ c.run(1900)
+ saved = records(c.storage_bytes())['flappydunk.sav']
+ assert len(saved)==160 and saved[:4]==b'FDK2'
+ assert struct.unpack_from('<I',saved,44)[0]==1
+ assert saved[71]==1 and saved[74]==1
+ frame = bytes(c.screen)
+ c.run(2400)
+ assert bytes(c.screen)==frame
+ assert records(c.storage_bytes())['flappydunk.sav']==saved
+ c.run(3120)
+ performance = {k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ c.run(3500);safe(c)
+ saved = records(c.storage_bytes())['flappydunk.sav']
+ assert struct.unpack_from('<I',saved,44)[0]==2
+ assert records(c.storage_bytes())['untouched.py']==b'print(42)\n'
+ stack = c.stack_used()
+ # A record after our save survives replacement and a second launch.
+ after = record('after.py',b'x=123\n')
+ raw = c.storage_bytes()
+ end = len(sentinel)+2+len('flappydunk.sav')+1+160
+ 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),(1000,'ok',80),(1250,'back',80),(1550,'onoff',120))
+ d.run(1800);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['flappydunk.sav'],44)[0]==3
+ report.append(dict(profile=name,stack_bytes=max(stack,d.stack_used()),**performance))
+ print(json.dumps(report[-1]),flush=True)
+ # Replay ordinary input on the slow model: three actual baskets, swish
+ # particles and multipliers. The reference planner is an offline test only.
+ emu.configure('n0110','epsilon',148928)
+ storage = OUT/'flight-arm.bin'
+ storage.write_bytes(record('flappydunk.sav',(OUT/'flight-start.bin').read_bytes())+b'\0\0')
+ c = emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink)
+ c.enable_checks()
+ taps = [int(t) for t in (OUT/'flight-taps.txt').read_text().splitlines() if int(t)<420]
+ c.keys = presses((600,'ok',80),
+ *((1000+t*16+(12 if t else 0),'up',24) for t in taps),
+ (7200,'home',120))
+ c.run(3000);c.save_png(str(OUT/'arm-swish.png'))
+ c.run(7000)
+ flight_perf = {k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ assert flight_perf['perf_slow']==0, flight_perf
+ c.run(7500);safe(c)
+ flight = records(c.storage_bytes())['flappydunk.sav']
+ assert struct.unpack_from('<I',flight,36)[0]>=3
+ assert struct.unpack_from('<I',flight,40)[0]>=1
+ print('ARM gameplay: three baskets and swish effects; '+json.dumps(flight_perf),flush=True)
+ # Migrate both old endless and discontinued-mode saves, preserving all
+ # previously earned balls without retaining medal counters or mode data.
+ for filename,phase in [('legacy-save.bin',1),('legacy-challenge-save.bin',0)]:
+ old=(ROOT/'tests'/filename).read_bytes();storage=OUT/('arm-'+filename)
+ storage.write_bytes(record('flappydunk.sav',old)+b'\0\0')
+ c=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((500,'home',100));c.run(1000);safe(c)
+ saved=records(c.storage_bytes())['flappydunk.sav']
+ assert saved[:4]==b'FDK2' and saved[4:28]==old[4:28]
+ assert saved[28:30]==b'\0\0' and saved[30:32]==b'\x05\x3f' and saved[70]==0 and saved[71]==phase
+ # Three-item title navigation, locked Cosmic ball at the new 200-point
+ # requirement, guide access and wrapping back to the Play entry.
+ emu.configure('n0110','epsilon',148928)
+ storage=OUT/'menus-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((500,'down',70),(800,'ok',70),(1300,'up',70),(1600,'right',70),(1900,'right',70),
+ (2500,'ok',70),(2800,'back',70),(3100,'down',70),(3400,'ok',70),
+ (4000,'back',70),(4300,'up',70),(4600,'down',70),(4900,'ok',70),
+ (5200,'up',70),(5450,'back',70),(5750,'down',70),(6050,'ok',70),
+ (6350,'down',70),(6650,'ok',70),(6950,'back',70),(7250,'home',100))
+ c.run(2200);c.save_png(str(OUT/'arm-locker.png'))
+ c.run(3700);c.save_png(str(OUT/'arm-guide.png'))
+ c.run(6800);c.save_png(str(OUT/'arm-new-flight.png'))
+ c.run(7700);safe(c)
+ saved=records(c.storage_bytes())['flappydunk.sav']
+ assert saved[30]==0 and saved[31]==1 and saved[71]==0 and saved[74]==0
+ # Full storage: failed exit remains interactive, and Back explicitly exits.
+ emu.configure('n0120','epsilon',153676)
+ 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))
+ c.run(1200);safe(c,False);c.save_png(str(OUT/'arm-storage-full.png'))
+ assert c.storage_bytes()[:len(full)]==full
+ c.keys+=presses((1300,'ok',80),(1600,'back',80))
+ c.run(1900);safe(c)
+ (OUT/'arm-validation.json').write_text(json.dumps(dict(profiles=report,flight=flight_perf),indent=2)+'\n')
+ print('All ARM profiles: pause, fresh input, persistence, safe exits and full storage passed. Menu navigation, score-only locker and legacy migration passed.')
+
+if __name__ == '__main__':
+ main()
diff --git a/games/flappydunk/tests/legacy-challenge-save.bin b/games/flappydunk/tests/legacy-challenge-save.bin
new file mode 100644
index 00000000..5a3020a5
Binary files /dev/null and b/games/flappydunk/tests/legacy-challenge-save.bin differ
diff --git a/games/flappydunk/tests/legacy-save.bin b/games/flappydunk/tests/legacy-save.bin
new file mode 100644
index 00000000..ece99165
Binary files /dev/null and b/games/flappydunk/tests/legacy-save.bin differ
diff --git a/games/flappydunk/tests/playability.c b/games/flappydunk/tests/playability.c
new file mode 100644
index 00000000..2544ab1e
--- /dev/null
+++ b/games/flappydunk/tests/playability.c
@@ -0,0 +1,76 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Offline reachability search. This test controller is never shipped in the app.
+ * It uses only the real flap/step API, favouring clear approaches to the rim.
+ */
+#include "dunk.h"
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#define BEAM 4096
+#define HORIZON 180
+typedef struct { fd_game g;fd_stats s;uint8_t taps[HORIZON]; } node;
+static node layer[2][BEAM];
+static int seen[320*44*2];
+static uint8_t taps[HORIZON];
+static unsigned chosen_ticks;
+static bool next(fd_game *g,fd_stats *s) {
+ layer[0][0].g=*g;layer[0][0].s=*s;
+ memset(layer[0][0].taps,0,HORIZON);
+ unsigned count=1;
+ for(unsigned tick=0;tick<HORIZON&&count;++tick) {
+ unsigned n=0;int best=-1;
+ memset(seen,255,sizeof seen);
+ for(unsigned i=0;i<count;++i)for(unsigned tap=0;tap<2;++tap) {
+ node a=layer[tick&1][i];
+ if(tap&&(a.g.flap_anim>4||!fd_flap(&a.g,&a.s)))continue;
+ a.taps[tick]=(uint8_t)tap;fd_step(&a.g,&a.s);
+ if(a.g.phase==FD_OVER)continue;
+ bool touch=false;unsigned nearest=0;float x=1000;
+ for(unsigned j=0;j<FD_HOOPS;++j) {
+ if(a.g.hoop[j].state!=2&&a.g.hoop[j].touched)touch=true;
+ if(a.g.hoop[j].state!=2&&a.g.hoop[j].x<x)x=a.g.hoop[j].x,nearest=j;
+ }
+ if(touch)continue;
+ if(a.g.baskets>g->baskets) {
+ if(best<0||a.g.flaps<layer[(tick+1)&1][best].g.flaps) {
+ if(best<0) {if(n==BEAM)continue;best=(int)n++;}
+ layer[(tick+1)&1][best]=a;
+ }
+ continue;
+ }
+ int yy=(int)((a.g.y-47)*2),vy=(int)((a.g.vy+5)*4);
+ if(yy<0||yy>=320||vy<0||vy>=44)continue;
+ unsigned cell=(unsigned)((yy*44+vy)*2+(a.g.hoop[nearest].state==1));
+ int old=seen[cell];
+ if(old>=0&&layer[(tick+1)&1][old].g.flaps<=a.g.flaps)continue;
+ if(old<0) {if(n==BEAM)continue;old=(int)n++;seen[cell]=old;}
+ layer[(tick+1)&1][old]=a;
+ }
+ if(best>=0) {
+ node *a=&layer[(tick+1)&1][best];
+ *g=a->g;*s=a->s;chosen_ticks=tick+1;memcpy(taps,a->taps,chosen_ticks);
+ return true;
+ }
+ count=n;
+ }
+ return false;
+}
+int main(void) {
+ fd_game g;fd_stats s={0};fd_new(&g,73);fd_flap(&g,&s);
+ FILE *f=fopen("flight-taps.txt","w");assert(f);fprintf(f,"0\n");
+ unsigned elapsed=0;
+ while(g.phase==FD_RUNNING&&g.baskets<50) {
+ unsigned basket=g.baskets;
+ bool reachable=next(&g,&s);
+ if(!reachable)printf("FAILED basket %u y %.1f flaps %u\n",basket,g.y,(unsigned)g.flaps);
+ assert(reachable&&fd_valid(&g,&s));
+ for(unsigned i=0;i<chosen_ticks;++i)if(taps[i])fprintf(f,"%u\n",elapsed+i);
+ elapsed+=chosen_ticks;
+ }
+ fclose(f);
+ assert(g.baskets==50&&g.phase==FD_RUNNING);
+ printf("Endless: %u baskets, %u swishes, score %u, %u flaps, %.1f seconds. Normal flap input only.\n",
+ (unsigned)g.baskets,(unsigned)g.swishes,(unsigned)g.score,(unsigned)g.flaps,elapsed*.016);
+ return 0;
+}
diff --git a/games/flappydunk/tests/test.c b/games/flappydunk/tests/test.c
new file mode 100644
index 00000000..fc84a512
--- /dev/null
+++ b/games/flappydunk/tests/test.c
@@ -0,0 +1,144 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "dunk.h"
+#include "render.h"
+#include <assert.h>
+#include <math.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 rehash(uint8_t *data) {
+ uint32_t h=2166136261u;
+ for(unsigned i=0;i<FD_SAVE_BYTES-4;++i)h=(h^data[i])*16777619u;
+ for(unsigned i=0;i<4;++i)data[FD_SAVE_BYTES-4+i]=(uint8_t)(h>>(8*i));
+}
+static void saves(void) {
+ fd_game g,h;fd_stats s={0},t;uint8_t data[FD_SAVE_BYTES],copy[FD_SAVE_BYTES];
+ fd_new(&g,73);fd_encode(&g,&s,data);
+ FILE *fixture=fopen("flight-start.bin","wb");assert(fixture);
+ assert(fwrite(data,1,sizeof data,fixture)==sizeof data);fclose(fixture);
+ fd_flap(&g,&s);
+ for(unsigned i=0;i<21;++i)fd_step(&g,&s);
+ fd_encode(&g,&s,data);assert(fd_decode(&h,&t,data,sizeof data));
+ assert(h.phase==FD_RUNNING&&t.runs==1&&h.rng==g.rng);
+ fd_encode(&h,&t,copy);assert(!memcmp(data,copy,sizeof data));
+ fd_game before=h;fd_stats prior=t;
+ for(unsigned i=0;i<FD_SAVE_BYTES;++i) {
+ data[i]^=128;assert(!fd_decode(&h,&t,data,sizeof data));data[i]^=128;
+ assert(!memcmp(&before,&h,sizeof h)&&!memcmp(&prior,&t,sizeof t));
+ }
+ assert(!fd_decode(&h,&t,NULL,0));assert(!fd_decode(&h,&t,data,sizeof data-1));
+ data[70]=255;rehash(data);assert(!fd_decode(&h,&t,data,sizeof data));
+ fd_encode(&g,&s,data);data[30]=5;rehash(data);assert(!fd_decode(&h,&t,data,sizeof data));
+ fd_encode(&g,&s,data);data[87]=3;rehash(data);assert(!fd_decode(&h,&t,data,sizeof data));
+ g=(fd_game){0};s=(fd_stats){0};fd_encode(&g,&s,data);
+ assert(fd_decode(&h,&t,data,sizeof data)&&!h.present);
+}
+static void setup(fd_game *g,fd_stats *s) {
+ *s=(fd_stats){0};fd_new(g,42);fd_flap(g,s);
+ g->hoop[0]=(fd_hoop){83,140,0,0,0,0};
+ g->y=138;g->vy=2;
+}
+static void scoring(void) {
+ fd_game g;fd_stats s;setup(&g,&s);
+ fd_step(&g,&s);assert(g.hoop[0].state==1&&g.baskets==0);
+ for(unsigned i=0;i<7;++i)fd_step(&g,&s);
+ assert(g.baskets==1&&s.baskets==1&&g.swishes==1&&g.score==2&&s.best==2);
+ for(unsigned i=0;i<3;++i)fd_step(&g,&s);
+ assert(g.baskets==1); /* Never score one hoop twice. */
+ setup(&g,&s);g.y=145;g.vy=-3;
+ for(unsigned i=0;i<5;++i)fd_step(&g,&s);
+ assert(g.baskets==0&&g.hoop[0].state==0); /* Upward passes do not count. */
+ setup(&g,&s);g.hoop[0].touched=1;g.streak=g.peak=4;
+ for(unsigned i=0;i<8;++i)fd_step(&g,&s);
+ assert(g.baskets==1&&g.streak==0&&g.score==1);
+ setup(&g,&s);g.y=126;g.vy=5;g.hoop[0].x=109;
+ for(unsigned i=0;i<5;++i)fd_step(&g,&s);
+ assert(g.hoop[0].touched&&g.baskets==0); /* Fast rim contact, no tunnelling. */
+ setup(&g,&s);g.hoop[0].x=30;fd_step(&g,&s);
+ assert(g.phase==FD_OVER&&g.reason==FD_MISSED);
+ fd_game frozen=g;fd_step(&g,&s);assert(!memcmp(&g,&frozen,sizeof g));assert(!fd_flap(&g,&s));
+ setup(&g,&s);g.y=202;g.vy=5;fd_step(&g,&s);assert(g.reason==FD_FLOOR_HIT);
+ setup(&g,&s);g.y=48;g.vy=-3;fd_step(&g,&s);assert(g.reason==FD_CEILING_HIT);
+ /* New cosmetics require the higher score, with no alternative currency. */
+ for(unsigned i=1;i<FD_SKINS;++i) {
+ s=(fd_stats){0};s.best=fd_skin_targets[i]-1;
+ assert(!(fd_unlocked(&s)&(1u<<i)));
+ s.best++;assert(fd_unlocked(&s)&(1u<<i));
+ s.unlocked=fd_unlocked(&s);s.best=0;assert(fd_unlocked(&s)&(1u<<i));
+ }
+ setup(&g,&s);g.score=s.best=13;
+ for(unsigned i=0;i<8;++i)fd_step(&g,&s);
+ assert(g.score==15&&s.best==15&&(g.unlocks&2)&&(s.unlocked&2));
+ setup(&g,&s);s.baskets=UINT32_MAX;s.swishes=UINT32_MAX;s.best=UINT32_MAX;
+ for(unsigned i=0;i<8;++i)fd_step(&g,&s);
+ assert(s.baskets==UINT32_MAX&&s.swishes==UINT32_MAX&&s.best==UINT32_MAX);
+}
+static void stress(void) {
+ uint8_t data[FD_SAVE_BYTES];unsigned ticks=0;
+ for(unsigned seed=1;seed<=40;++seed) {
+ fd_game g,h;fd_stats s={0},t;fd_new(&g,seed);fd_flap(&g,&s);
+ for(unsigned i=0;i<3000;++i) {
+ if(i%(8+seed%41)==0)fd_flap(&g,&s);
+ fd_step(&g,&s);assert(fd_valid(&g,&s));++ticks;
+ if(i%19==0) {fd_encode(&g,&s,data);assert(fd_decode(&h,&t,data,sizeof data));}
+ if(g.phase>=FD_OVER) {fd_new(&g,seed*713+i);fd_flap(&g,&s);}
+ }
+ }
+ printf("Stress: %u endless ticks, save validation every 19 ticks.\n",ticks);
+}
+static void screenshots(void) {
+ fd_game g;fd_stats s={0};fd_new(&g,42);
+ fd_invalidate();fd_render(&g,&s,FD_TITLE,0,390,false,push);shot("title.ppm");
+ fd_render(&g,&s,FD_LOCKER,5,390,false,push);shot("locker.ppm");
+ fd_render(&g,&s,FD_READY,0,390,false,push);shot("ready.ppm");
+ fd_render(&g,&s,FD_GUIDE,0,390,false,push);shot("guide.ppm");
+ fd_render(&g,&s,FD_PAUSE,0,390,false,push);shot("pause.ppm");
+ setup(&g,&s);
+ for(unsigned i=0;i<8;++i)fd_step(&g,&s);
+ fd_render(&g,&s,FD_FLIGHT,0,390,false,push);shot("game.ppm");
+ for(unsigned i=0;i<140;++i) {
+ if(g.phase>=FD_OVER) {fd_new(&g,42);fd_flap(&g,&s);}
+ if(i%30==0)fd_flap(&g,&s);
+ fd_step(&g,&s);fd_render(&g,&s,FD_FLIGHT,0,i*32,false,push);
+ memcpy(reference,screen,sizeof screen);
+ fd_invalidate();fd_render(&g,&s,FD_FLIGHT,0,i*32,false,push);
+ assert(!memcmp(reference,screen,sizeof screen)); /* Dirty redraw equals full. */
+ }
+ pushes=0;fd_render(&g,&s,FD_FLIGHT,0,139*32,false,push);assert(pushes==0);
+ g.phase=FD_OVER;g.reason=FD_MISSED;
+ fd_render(&g,&s,FD_RESULT,0,390,false,push);shot("result.ppm");
+ fd_render(&g,&s,FD_SAVE_ERROR,0,390,true,push);shot("storage.ppm");
+}
+static void migration(void) {
+ fd_game g,h;fd_stats s,t;uint8_t data[FD_SAVE_BYTES],copy[FD_SAVE_BYTES];
+ const char *names[]={"../tests/legacy-save.bin","../tests/legacy-challenge-save.bin"};
+ for(unsigned i=0;i<2;++i) {
+ FILE *f=fopen(names[i],"rb");assert(f);assert(fread(data,1,sizeof data,f)==sizeof data);fclose(f);
+ assert(!memcmp(data,"FDK1",4)&&fd_decode(&g,&s,data,sizeof data));
+ assert(fd_valid(&g,&s)&&s.best==30&&s.skin==5&&fd_unlocked(&s)==63);
+ assert(i?(g.phase==FD_WAITING&&!g.started&&g.score==0):g.phase==FD_RUNNING);
+ fd_encode(&g,&s,copy);assert(!memcmp(copy,"FDK2",4));
+ assert(copy[28]==0&&copy[29]==0&&copy[70]==0&&copy[31]==63);
+ assert(fd_decode(&h,&t,copy,sizeof copy)&&t.skin==5&&fd_unlocked(&t)==63);
+ fd_encode(&h,&t,data);assert(!memcmp(data,copy,sizeof data));
+ }
+}
+int main(void) {
+ saves();scoring();stress();migration();screenshots();
+ puts("Save migration, endless physics, score unlocks and pixel-exact redraw tests passed.");return 0;
+}
diff --git a/games/flappydunk/tests/test_compact_nwa.py b/games/flappydunk/tests/test_compact_nwa.py
new file mode 100644
index 00000000..4874fac7
--- /dev/null
+++ b/games/flappydunk/tests/test_compact_nwa.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Build-time LZ4 correctness and block-format boundary checks (stdlib only)."""
+import importlib.util
+from pathlib import Path
+import random
+import unittest
+
+SOURCE = Path(__file__).resolve().parents[1]/'tools/compact_nwa.py'
+SPEC = importlib.util.spec_from_file_location('compact_nwa', SOURCE)
+packing = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(packing)
+
+
+class CompressionTests(unittest.TestCase):
+ def check_block(self, raw):
+ block = packing.compress_lz4(raw)
+ self.assertEqual(packing.decode_lz4(block, len(raw)), raw)
+ # Walk token boundaries independently to check the LZ4 end constraints.
+ pos, decoded, last_match, final_literals = 0, 0, None, None
+ while pos < len(block):
+ token = block[pos]
+ pos += 1
+ literal = token >> 4
+ if literal == 15:
+ while block[pos] == 255:
+ literal += 255
+ pos += 1
+ literal += block[pos]
+ pos += 1
+ pos += literal
+ decoded += literal
+ if pos == len(block):
+ final_literals = literal
+ break
+ distance = int.from_bytes(block[pos:pos+2], 'little')
+ self.assertGreater(distance, 0)
+ self.assertLessEqual(distance, decoded)
+ pos += 2
+ match = (token & 15) + 4
+ if (token & 15) == 15:
+ while block[pos] == 255:
+ match += 255
+ pos += 1
+ match += block[pos]
+ pos += 1
+ last_match = decoded
+ decoded += match
+ self.assertEqual(decoded, len(raw))
+ self.assertIsNotNone(final_literals)
+ if last_match is not None:
+ self.assertGreaterEqual(final_literals, 5)
+ self.assertLessEqual(last_match, len(raw)-12)
+ return block
+
+ def test_lengths_and_random_literals(self):
+ rng = random.Random(6140)
+ for size in (0, 1, 4, 5, 11, 12, 15, 19, 20, 254, 255, 270, 1024):
+ with self.subTest(size=size):
+ self.check_block(bytes(rng.randrange(256) for _ in range(size)))
+
+ def test_long_overlapping_matches_and_extension_bytes(self):
+ for pattern in (b'A', b'\x00\xff', bytes(range(32))):
+ raw = (pattern*packing.ICON_BYTES)[:packing.ICON_BYTES]
+ with self.subTest(pattern=pattern):
+ self.assertLess(len(self.check_block(raw)), 150)
+
+ def test_repeated_pixel_rows(self):
+ row = b'\x08\xc5'*20 + b'\xff\xff'*15 + b'\x08\xc5'*20
+ self.check_block(row*56)
+
+ def test_known_raw_block(self):
+ self.assertEqual(packing.decode_lz4(b'\x13A\x01\x00\x50hello', 13), b'A'*8+b'hello')
+
+ def test_truncated_invalid_and_oversized_output(self):
+ for block, expected in ((b'',1),(b'\xf0',1),(b'\x10',1),
+ (b'\x00\x00\x00',4),(b'\x10A\x02\x00',5),
+ (b'\x10A',2),(b'\x13A\x01\x00\x50hello',12)):
+ with self.subTest(block=block):
+ with self.assertRaises(ValueError):
+ packing.decode_lz4(block,expected)
+
+ def test_repeatable_and_bounded_input(self):
+ raw = b'abcd'*100+b'last five'
+ self.assertEqual(self.check_block(raw),self.check_block(raw))
+ with self.assertRaises(ValueError):
+ packing.compress_lz4(b'x'*65536)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/games/flappydunk/tools/build.py b/games/flappydunk/tools/build.py
new file mode 100644
index 00000000..b0cfecc2
--- /dev/null
+++ b/games/flappydunk/tools/build.py
@@ -0,0 +1,90 @@
+#!/usr/bin/env python3
+"""Optional portable standalone build; the normal NumPlay build uses Make.
+
+python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+Requires nwlink 1.0.0, ARM GCC, Pillow (icon generation), pyelftools (size report).
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import subprocess
+import sys
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('--toolchain', type=Path)
+ ap.add_argument('--nwlink', default='nwlink')
+ ap.add_argument('--node', default='node')
+ a = ap.parse_args()
+ out = ROOT / 'output'
+ out.mkdir(exist_ok=True)
+
+ def run(*args, capture=False):
+ return subprocess.run([str(v) for v in args], cwd=ROOT, check=True,
+ capture_output=capture, text=capture)
+
+ def tool(name):
+ binary = 'arm-none-eabi-' + name + ('.exe' if os.name == 'nt' else '')
+ return a.toolchain / binary if a.toolchain else binary
+
+ nw = [a.node, a.nwlink] if Path(a.nwlink).is_file() and not a.nwlink.endswith(('.exe', '.cmd')) else [a.nwlink]
+ flags = ['-std=c11', '-Os', '-Wall', '-Wextra', '-Werror', '-fno-math-errno',
+ '-fsingle-precision-constant', '-ffunction-sections', '-fdata-sections',
+ '-fstack-usage', '-fno-tree-loop-distribute-patterns', '-flto', '-fvisibility=internal']
+ flags += shlex.split(run(*nw, 'eadk-cflags-device', capture=True).stdout, posix=True)
+ # shlex on Windows may treat the include path's backslashes as escapes;
+ # nwlink prints forward slashes on Windows, so this remains portable.
+ objects = []
+ for source in ('main', 'physics', 'save', 'render'):
+ obj = out / (source + '.o')
+ run(tool('gcc'), *flags, '-c', ROOT / 'src' / (source + '.c'), '-o', obj)
+ objects.append(obj)
+ run(*nw, 'png-icon-o', ROOT / 'src/icon.png', out / 'icon.o')
+ packer = ROOT / 'tools/compact_nwa.py'
+ icon_report = json.loads(run(sys.executable, packer, 'icon', out / 'icon.o',
+ out / 'icon-compact.o', '--objcopy', tool('objcopy'), capture=True).stdout)
+ common = [tool('gcc'), *flags, '-nostartfiles', '--specs=nano.specs',
+ '-Wl,--relocatable,--gc-sections,-e,main', '-flinker-output=nolto-rel', *objects]
+ run(*common, '-lm', '-o', out / 'module.o')
+ run(*common, '-Wl,-u,eadk_app_name,-u,eadk_app_icon,-u,eadk_api_level', out / 'icon-compact.o',
+ '-lm', '-o', out / 'standalone.o')
+ run(sys.executable, packer, 'app', out / 'standalone.o', out / 'flappydunk-debug.nwa',
+ '--ld', tool('ld'))
+ run(sys.executable, packer, 'release', out / 'flappydunk-debug.nwa',
+ out / 'FlappyDunk.nwa', '--objcopy', tool('objcopy'))
+ if os.name != 'nt':
+ shutil.copyfile(out / 'FlappyDunk.nwa', out / 'flappydunk.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 / 'FlappyDunk.nwa', elf, *options)
+ run(*nw, 'nwa-bin', out / 'FlappyDunk.nwa', binary, *options)
+ debug_binary = out / (name + '-debug.bin')
+ run(*nw, 'nwa-bin', out / 'flappydunk-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 / 'FlappyDunk.nwa').stat().st_size, save_bytes=160,
+ **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/flappydunk/tools/compact_nwa.py b/games/flappydunk/tools/compact_nwa.py
new file mode 100644
index 00000000..f320bb54
--- /dev/null
+++ b/games/flappydunk/tools/compact_nwa.py
@@ -0,0 +1,228 @@
+#!/usr/bin/env python3
+"""Lossless standalone NWA packing. Python standard library + ARM binutils.
+
+Keep the standard ELF/NWI formats: no runtime decoder, extra RAM, or archive.
+"""
+import argparse
+from bisect import bisect_left, insort
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+
+ICON_BYTES = 55 * 56 * 2
+
+
+def decode_lz4(data, expected_size):
+ """Decode a raw LZ4 block, with an exact output bound for launcher icons."""
+ out = bytearray()
+ pos = 0
+
+ def length(value):
+ nonlocal pos
+ if value == 15:
+ while True:
+ if pos >= len(data):
+ raise ValueError('Truncated LZ4 length')
+ extra = data[pos]
+ pos += 1
+ value += extra
+ if extra != 255:
+ break
+ return value
+
+ while pos < len(data):
+ token = data[pos]
+ pos += 1
+ size = length(token >> 4)
+ if pos + size > len(data) or len(out) + size > expected_size:
+ raise ValueError('Invalid LZ4 literal run')
+ out += data[pos:pos + size]
+ pos += size
+ if pos == len(data):
+ break
+ if pos + 2 > len(data):
+ raise ValueError('Truncated LZ4 offset')
+ distance = data[pos] | data[pos + 1] << 8
+ pos += 2
+ size = length(token & 15) + 4
+ if not distance or distance > len(out) or len(out) + size > expected_size:
+ raise ValueError('Invalid LZ4 match')
+ for _ in range(size):
+ out.append(out[-distance])
+ if len(out) != expected_size:
+ raise ValueError('Unexpected decoded icon size')
+ return bytes(out)
+
+
+def _extension_cost(value, threshold):
+ return 0 if value < threshold else 1 + (value - threshold) // 255
+
+
+def compress_lz4(data):
+ """Find a minimum-size raw LZ4 parse for a small (<= 65535 byte) image.
+
+ A suffix array finds the longest legal previous match. Dynamic programming
+ chooses literal/match lengths, including extension-byte costs. The final
+ five bytes are literals; the last match starts at least twelve bytes from
+ the end, as required by standard LZ4 block decoders.
+ """
+ n = len(data)
+ if n > 65535:
+ raise ValueError('Only small build-time assets are supported')
+ if not n:
+ return b'\0'
+ suffixes = sorted(range(n), key=lambda i: data[i:])
+ rank = [0] * n
+ for r, pos in enumerate(suffixes):
+ rank[pos] = r
+ seen = []
+ matches = [(0, 0)] * n
+ for i in range(n - 11):
+ r = rank[i]
+ at = bisect_left(seen, r)
+ best, distance = 0, 0
+ # Among earlier suffixes, a lexicographic neighbour has the longest
+ # common prefix. Overlapping matches are legal in LZ4.
+ for q in seen[max(0, at - 1):at + 1]:
+ j = suffixes[q]
+ lo, hi = 0, n - i - 5
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if data[i:i + mid] == data[j:j + mid]:
+ lo = mid
+ else:
+ hi = mid - 1
+ if lo > best:
+ best, distance = lo, i - j
+ matches[i] = best, distance
+ insort(seen, r)
+
+ dp = [0] * (n + 1)
+ plan = [None] * n
+ match_cost = [0] * n
+ match_length = [0] * n
+ starts = []
+ for i in range(n - 1, -1, -1):
+ best = n - i + 1 + _extension_cost(n - i, 15)
+ longest, _ = matches[i]
+ if longest >= 4:
+ cost, size = min((2 + _extension_cost(size, 19) + dp[i + size], size)
+ for size in range(4, longest + 1))
+ match_cost[i], match_length[i] = cost, size
+ starts.append(i)
+ for j in reversed(starts):
+ literal = j - i
+ if literal + 3 >= best:
+ break
+ cost = 1 + literal + _extension_cost(literal, 15) + match_cost[j]
+ if cost < best:
+ best = cost
+ plan[i] = j, match_length[j], matches[j][1]
+ dp[i] = best
+
+ out = bytearray()
+
+ def emit_length(value):
+ while value >= 255:
+ out.append(255)
+ value -= 255
+ out.append(value)
+
+ anchor = 0
+ while anchor < n:
+ entry = plan[anchor]
+ if entry is None:
+ literal = n - anchor
+ out.append(min(literal, 15) << 4)
+ if literal >= 15:
+ emit_length(literal - 15)
+ out += data[anchor:]
+ break
+ j, size, distance = entry
+ literal = j - anchor
+ out.append(min(literal, 15) << 4 | min(size - 4, 15))
+ if literal >= 15:
+ emit_length(literal - 15)
+ out += data[anchor:j]
+ out += bytes((distance & 255, distance >> 8))
+ if size >= 19:
+ emit_length(size - 19)
+ anchor = j + size
+ if len(out) != dp[0] or decode_lz4(out, n) != data:
+ raise ValueError('Lossless compression verification failed')
+ return bytes(out)
+
+
+def compact_icon(source, output, objcopy):
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ folder = Path(folder)
+ original, packed, obj = folder/'original.nwi', folder/'packed.nwi', folder/'icon.o'
+ section = '.rodata.eadk_app_icon'
+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(original),
+ str(source), str(obj)], check=True)
+ before = original.read_bytes()
+ pixels = decode_lz4(before, ICON_BYTES)
+ after = compress_lz4(pixels)
+ if len(after) > len(before):
+ after = before
+ packed.write_bytes(after)
+ subprocess.run([objcopy, '--update-section=' + section + '=' + str(packed),
+ str(obj), str(output)], check=True)
+ # Verify the bytes actually stored in the resulting ELF, too.
+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(packed),
+ str(output), str(folder/'verify.o')], check=True)
+ if decode_lz4(packed.read_bytes(), ICON_BYTES) != pixels:
+ raise ValueError('Packed icon pixels changed')
+ return dict(source_icon_bytes=len(before), icon_bytes=len(after), decoded_icon_bytes=ICON_BYTES)
+
+
+def compact_app(source, output, linker):
+ output.parent.mkdir(parents=True, exist_ok=True)
+ script = Path(__file__).with_name('standalone.ld')
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ packed = Path(folder)/'packed.nwa'
+ subprocess.run([linker, '--relocatable', '--script', str(script), str(source),
+ '-o', str(packed)], check=True)
+ output.write_bytes(packed.read_bytes())
+
+
+def compact_release(source, output, objcopy):
+ """Remove unused ARM mapping symbols from the transport ELF only.
+
+ GNU objcopy preserves $t/$d symbols specially even when unused. Rename
+ them in a temporary release copy, then let objcopy decide which symbols
+ relocations still need. Keep the debug ELF intact for ARM disassembly.
+ Python builders compare release/debug bytes on all supported profiles;
+ Make's check target compares them on the smallest RAM profile.
+ """
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:
+ folder = Path(folder)
+ stripped, renamed = folder/'stripped.nwa', folder/'renamed.nwa'
+ subprocess.run([objcopy, '--strip-unneeded', str(source), str(stripped)], check=True)
+ subprocess.run([objcopy, '--redefine-sym=$t=unused_thumb_marker',
+ '--redefine-sym=$d=unused_data_marker', str(stripped),
+ str(renamed)], check=True)
+ subprocess.run([objcopy, '--strip-unneeded', str(renamed), str(output)], check=True)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('kind', choices=('icon', 'app', 'release'))
+ ap.add_argument('source', type=Path)
+ ap.add_argument('output', type=Path)
+ ap.add_argument('--objcopy', default='arm-none-eabi-objcopy')
+ ap.add_argument('--ld', default='arm-none-eabi-ld')
+ args = ap.parse_args()
+ if args.kind == 'icon':
+ print(json.dumps(compact_icon(args.source, args.output, args.objcopy)))
+ elif args.kind == 'release':
+ compact_release(args.source, args.output, args.objcopy)
+ else:
+ compact_app(args.source, args.output, args.ld)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/flappydunk/tools/icon.py b/games/flappydunk/tools/icon.py
new file mode 100644
index 00000000..26b6db7f
--- /dev/null
+++ b/games/flappydunk/tools/icon.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python3
+"""Generate the original Flappy Dunk launcher icon (Pillow)."""
+from pathlib import Path
+from PIL import Image, ImageDraw
+
+S = 4
+im = Image.new('RGB', (55*S, 56*S), '#f5eee3')
+d = ImageDraw.Draw(im)
+def oval(box, color, outline=None):
+ d.ellipse(tuple(int(v*S) for v in box), fill=color, outline=outline, width=S)
+def line(points, color, width=1):
+ d.line([(int(x*S), int(y*S)) for x,y in points], fill=color, width=width*S)
+
+for y in (8, 24, 40):
+ line([(0,y),(55,y)], '#eae1d3')
+for side in (-1,1):
+ for i in range(3):
+ cx=27+side*(21-i*3)
+ oval((cx-6,14+i*3,cx+6,20+i*3),'#fffdf6','#b7b1a6')
+oval((12,9,43,40),'#a96334')
+oval((13,9,42,38),'#f6a24e')
+oval((18,13,25,17),'#ffe0a0')
+line([(13,23),(42,23)],'#a96334')
+for side in (-1,1):
+ line([(27,10),(27+side*7,18),(27+side*7,29),(27,38)],'#a96334')
+oval((21,25,23,28),'#354650')
+oval((32,25,34,28),'#354650')
+line([(25,30),(27,32),(29,30)],'#354650')
+for x in (9,18,27,36,45):
+ line([(x,43),(18+(x-9)*.5,54)],'#b4a895')
+oval((6,38,49,47),'#ad493d')
+oval((9,40,46,44),'#f5eee3')
+d.arc((6*S,38*S,49*S,47*S),0,180,fill='#d76150',width=2*S)
+im.resize((55,56),Image.Resampling.LANCZOS).save(Path(__file__).resolve().parents[1]/'src/icon.png')
diff --git a/games/flappydunk/tools/standalone.ld b/games/flappydunk/tools/standalone.ld
new file mode 100644
index 00000000..28679582
--- /dev/null
+++ b/games/flappydunk/tools/standalone.ld
@@ -0,0 +1,15 @@
+/* Compact a standalone NWA after the first link has removed unused code.
+ * Keep EADK metadata separate, and preserve mergeable strings for nwlink.
+ * NumPlay modules retain their original sections for launcher garbage collection.
+ */
+SECTIONS {
+ .rodata.eadk_app_name : { *(.rodata.eadk_app_name) }
+ .rodata.eadk_app_icon : { *(.rodata.eadk_app_icon) }
+ .rodata.eadk_api_level : { *(.rodata.eadk_api_level) }
+ .text : { *(.text.startup.main) *(.text .text.*) }
+ .rodata.str1.1 : { *(.rodata*.str1.1) }
+ .rodata : { *(.rodata .rodata.*) }
+ .data : { *(.data .data.*) }
+ .bss : { *(.bss .bss.*) *(COMMON) }
+ /DISCARD/ : { *(.comment) *(.note.GNU-stack) }
+}