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 Doodle Jump by Bobydeluxe

Bobydeluxea1ff2213dc05
diff --git a/README.md b/README.md
index 67eeae81..5f10ac39 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>
+**[Doodle Jump](games/doodlejump/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 **[Doodle Jump](games/doodlejump/README.md)**, including its English interface, procedural artwork and platform-climbing engine. Inspired by Doodle Jump; 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/doodlejump/.gitignore b/games/doodlejump/.gitignore
new file mode 100644
index 00000000..16be8f21
--- /dev/null
+++ b/games/doodlejump/.gitignore
@@ -0,0 +1 @@
+/output/
diff --git a/games/doodlejump/Makefile b/games/doodlejump/Makefile
new file mode 100644
index 00000000..553cdc0c
--- /dev/null
+++ b/games/doodlejump/Makefile
@@ -0,0 +1,51 @@
+# Doodle Jump: English-only app and NumPlay module.
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+PYTHON ?= python3
+ARM_LD ?= arm-none-eabi-ld
+OBJCOPY = arm-none-eabi-objcopy
+PACKER = tools/compact_nwa.py tools/standalone.ld
+SRC = src/main.c src/physics.c src/save.c src/render.c
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+OBJECTS = $(patsubst src/%.c,output/%.o,$(SRC))
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device) -Os -Wall -Wextra -Werror
+CFLAGS += -fno-math-errno -fsingle-precision-constant -ffunction-sections -fdata-sections -fstack-usage
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fvisibility=internal
+LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable,--gc-sections,-e,main -flinker-output=nolto-rel
+
+.PHONY: build check module sim-module test clean
+build: output/doodlejump.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/doodlejump-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/doodlejump.nwa: output/doodlejump-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/doodlejump.nwa output/doodlejump.bin --ram-length 107674
+ $(NWLINK) nwa-bin output/doodlejump-debug.nwa output/doodlejump-debug.bin --ram-length 107674
+ $(PYTHON) -c "from pathlib import Path; assert Path('output/doodlejump.bin').read_bytes() == Path('output/doodlejump-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_doodlejump_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_doodlejump_main -o output/sim-module.o
+clean:
+ rm -rf output
diff --git a/games/doodlejump/README.md b/games/doodlejump/README.md
new file mode 100644
index 00000000..f8130278
--- /dev/null
+++ b/games/doodlejump/README.md
@@ -0,0 +1,104 @@
+# Doodle Jump
+
+Game made by **Bobydeluxe**.
+
+A new NumWorks implementation of automatic jumping, bounded left/right steering and
+an endless climb. The English interface keeps an ink-and-paper look with
+lightly ruled menu pages and a clear playfield. Decorative binding, dense grid,
+side rulers, extra annotations and note shadows have been removed.
+The character, platforms, monsters and interface are drawn procedurally.
+
+![Title page](docs/title.png)
+![Climbing](docs/gameplay.png)
+
+## Play
+
+Install the standalone `DoodleJump.nwa` with a compatible NumWorks external-app
+installer. Open Doodle Jump from the calculator's Home menu after installation.
+
+| Key | Action |
+| --- | --- |
+| Left / Right, or 4 / 6 | Steer; stop at the left and right walls |
+| OK / EXE / Up | Shoot upward once; release before shooting again |
+| Back | Pause, or return in menus |
+| Home / On-Off | Save and exit |
+| Arrows, then OK / EXE | Select a menu entry |
+
+Jumping is automatic. Land on platforms while descending; rising through one
+does not cause a collision. The camera climbs with you, and falling below the
+page ends the expedition. Height determines the high score.
+
+- **Green:** normal platform.
+- **Blue:** moving platform.
+- **Brown:** brittle; breaks without giving a bounce. These are optional ledges.
+- **White:** one bounce, then disappears.
+- **Spring:** land near its centre for a higher jump.
+- **Rocket:** land near its centre for a temporary, protected flight.
+- **Monsters:** shoot upward or land on top. Touching the side or underside
+ ends the climb. Their patrols stay within the page.
+
+The route uses seeded random short, medium and long offsets, including nearly
+vertical jumps. Direction can change anywhere on the page; there is no fixed
+left/right sweep. Proposals reflect near the edges instead of accumulating
+there. After four route ledges in the same screen half, an inward bias prevents
+staying there for more than six consecutive ledges. Consecutive base centres
+stay within 68 pixels, while rises stay between 36 and 54 pixels. Moving
+platforms remain inside the playfield. Higher climbs retain narrower, moving
+and one-use platforms, springs, rockets and optional brittle ledges.
+
+The character stays fully on the page. Holding a direction against a wall
+stops horizontal speed; pressing the opposite direction moves away immediately.
+There are no opposite-edge character copies or collisions across the page.
+Old DJN1 and DJN2 saves import records and climbing progress into DJN3. DJN1 edge
+positions and queued wrapping routes are adapted to the walls. DJN2 climbs
+keep their visible platforms and exact progress; only generator history resets. New saves retain exact
+state on subsequent reloads and remain 384 bytes.
+
+**Field Notes** records the best height, expeditions, bounces, springs, rockets
+and monsters cleared. Its animation option reduces cosmetic movement without
+changing the physics. Pausing freezes the world; resuming waits on the ready
+note. Starting a new expedition asks before replacing a live climb. From the
+pause menu, **Title Page**, then **Back**, leaves the app with progress saved.
+
+The 384-byte save includes the exact integer simulation state, generated
+platforms, monsters, shots, statistics and animation preference. Invalid saves
+are rejected before replacing live state. If saving fails, an interactive note
+offers retry, return to the climb or an explicit exit without saving.
+
+## Build
+
+Requires ARM GCC with newlib, Python 3 and nwlink 1.0.0. The optional Python
+builder additionally uses pyelftools; regenerating the icon uses Pillow.
+
+```sh
+make build check
+make test
+python tests/arm.py --nwlink nwlink
+
+# Optional portable build, also usable on Windows without Make:
+python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+python tools/icon.py
+```
+
+The builders use a game-local lossless icon/ELF packer. The Python builder checks
+release/debug installed bytes on N0110, N0115/custom RAM, N0120 and Upsilon.
+The unstripped debug NWA is used by the ARM regression suite. A module build is
+provided for a later NumPlay integration.
+
+| Resource | Bytes |
+| --- | ---: |
+| Downloadable NWA | 19,764 |
+| Installed code and assets | 13,664 |
+| Static RAM | 6,065 |
+| Deepest observed ARM stack in exit/input tests | 548 |
+| Save payload | 384 |
+
+The renderer uses one 5,120-byte strip buffer. Physics uses fixed-point integers,
+16 platform slots, three monsters and three shots. There are no heap allocations,
+full-screen framebuffer or runtime image decompressor. The launcher icon is
+409 compressed bytes with identical decoded pixels.
+
+Simulation runs at 62.5 Hz and drawing at up to 31.25 Hz. The worst observed
+render in the ARM emulator was 5 ms, including a crowded rocket scene. These
+are emulator measurements; physical calculator display timing remains to be
+checked. See [validation details](VALIDATION.md).
diff --git a/games/doodlejump/VALIDATION.md b/games/doodlejump/VALIDATION.md
new file mode 100644
index 00000000..0195d0b8
--- /dev/null
+++ b/games/doodlejump/VALIDATION.md
@@ -0,0 +1,100 @@
+# Local validation — 20 October 2026
+
+Standalone Doodle Jump with bounded movement, a controlled-random route and
+an English-only interface. Publication changes are limited to this game and
+its link/credit in the root README.
+
+## Boundaries and reachable routes
+
+The player centre is clamped to 18..270 within the 288-pixel playfield, keeping
+the character on screen. An outward horizontal velocity becomes zero at the
+wall; an opposite input accelerates inward immediately. Landing interpolation
+uses the actual clamped displacement. Collision distances are direct, with no
+opposite-edge contact. The renderer no longer draws wrapped copies. Moving
+platforms and monster patrols also remain within the page.
+
+The route now samples nearly vertical, short and larger offsets rather than
+following bands in order. A random direction can reverse away from the walls;
+long direction runs are limited, and four consecutive ledges in one half
+trigger an inward bias. Reflected proposals avoid edge clamping/pileups.
+One existing history byte tracks the same-half count, direction and run length.
+
+A generation-only probe checked 28,800 ledges over 120 seeds. Direct base-centre
+gaps were at most 68 pixels; no same-half streak exceeded six. Each seed had
+both short and long hops, repeated movement in the same direction and over ten
+reversals away from the edges. Across the sample there were 12,045 such interior
+reversals. Counts in six left-to-right zones were 849 / 4,311 / 9,213 / 9,275 /
+4,286 / 866. This is a controlled, centre-biased distribution with no fixed
+visitation schedule, not an equal-count cyclic route. Every seed reached both
+halves and all four inner zones; the aggregate reached the whole route range.
+Moving platforms and the player stayed within the playfield.
+
+The normal steering/shooting controller completed 6,000 height on 75 of 80
+seeds. Four runs ended from monster contact and one from a fall. Highest climb:
+6,007. All platform types appeared. Seed 1 reached 6,001 with 51 bounces,
+13 springs, two rockets and two monsters cleared. The test requires broad
+successful play (at least 70/80); these observed losses do not assert that a
+human cannot fall or hit a monster. Another 120,000 irregular-input ticks
+passed state validation. The controller is test code, absent from the app.
+
+## Saves and regression tests
+
+DJN3 remains 384 bytes and uses the existing memory layout. The decoder still
+accepts checked DJN1 and DJN2 records, preserving lifetime records, height, camera,
+peak, items and random state. It clamps an imported edge position, places the
+nearest supporting route ledge under the character and limits gaps in the
+route above it before continuing with the wall-aware generator. This one-time
+layout adjustment prevents an old queued wrapping jump from blocking progress.
+The original legacy fixture and an actual wrapping climb were tested. An
+actual DJN2 bounded climb imported byte-identical world/record data, with only
+its old generator phase reset. New DJN3 saves retain random-generator history,
+so subsequent reloads preserve exact state and future route choices.
+
+Tests cover sustained wall contact, immediate reversal, maximum displacement
+per tick, no landing across the old seam, clamped moving ledges, descending
+landings, pass-through while rising, platform types, centred/off-centre boosts,
+shots, stomps, fatal monster contact, rocket protection and death-state freeze.
+Save corruption, invalid values and repeated reloads remain covered. Partial
+and complete redraws matched pixel for pixel; unchanged screens pushed no data.
+The native suite ran with TinyCC, and ARM GCC checked the test source with
+warnings treated as errors.
+
+## Actual ARM program
+
+N0110/Epsilon, N0115/custom RAM, N0120/Epsilon and N0110/Upsilon passed the
+compiled-app suite, including held fire, pause/cancel/resume, saves, Home and
+On-Off exit, RAM cleanup, Home locking, unchanged firmware RAM and preservation
+of unrelated calculator records. Each profile also ran separate held-left and
+held-right flights: sampled positions stayed bounded, moved continuously,
+reached the expected wall and had zero outward speed there.
+
+A keyboard-controlled run reached 1,202 height, with 12 bounces in 650 ticks.
+Crowded rocket rendering, a generated saved climb, reduced animations and
+full-storage handling also passed. Maximum measured render time was 5 ms,
+with no frame over the 32 ms drawing interval. These are emulator results;
+physical calculator timing remains to be checked.
+
+## Build and resources
+
+ARM GCC 15.2.1, C11, `-Os`, LTO, nwlink 1.0.0 and a game-local lossless packer.
+Both standalone and module builds completed. Release/debug installed bytes
+match on all four profiles.
+
+| Resource | Bytes |
+| --- | ---: |
+| Standalone NWA | 19,764 |
+| Installed code/assets | 13,664 |
+| Static RAM | 6,065 |
+| Observed ARM stack | 548 |
+| Save payload | 384 |
+| Compressed icon | 409 |
+
+The preceding wall build used 19,524 download bytes and 13,436 installed bytes.
+The controlled-random update adds 240 download bytes and 228 installed bytes;
+static RAM, stack observation and the save payload are unchanged. There is no
+heap allocation or full framebuffer. Actual ARM screenshots are in docs;
+build/validation reports are in the ignored output folder.
+
+The isolated publication build matches the locally validated app byte for byte.
+Host, packing and four-profile ARM suites are repeated from this snapshot using
+the upstream repository helpers.
diff --git a/games/doodlejump/docs/gameplay.png b/games/doodlejump/docs/gameplay.png
new file mode 100644
index 00000000..6c90272f
Binary files /dev/null and b/games/doodlejump/docs/gameplay.png differ
diff --git a/games/doodlejump/docs/guide.png b/games/doodlejump/docs/guide.png
new file mode 100644
index 00000000..8bca2da3
Binary files /dev/null and b/games/doodlejump/docs/guide.png differ
diff --git a/games/doodlejump/docs/journal.png b/games/doodlejump/docs/journal.png
new file mode 100644
index 00000000..3355ec3e
Binary files /dev/null and b/games/doodlejump/docs/journal.png differ
diff --git a/games/doodlejump/docs/left-wall.png b/games/doodlejump/docs/left-wall.png
new file mode 100644
index 00000000..156f00ff
Binary files /dev/null and b/games/doodlejump/docs/left-wall.png differ
diff --git a/games/doodlejump/docs/right-wall.png b/games/doodlejump/docs/right-wall.png
new file mode 100644
index 00000000..be7d4da4
Binary files /dev/null and b/games/doodlejump/docs/right-wall.png differ
diff --git a/games/doodlejump/docs/title.png b/games/doodlejump/docs/title.png
new file mode 100644
index 00000000..c55b40ed
Binary files /dev/null and b/games/doodlejump/docs/title.png differ
diff --git a/games/doodlejump/src/doodle.h b/games/doodlejump/src/doodle.h
new file mode 100644
index 00000000..34a10cf2
--- /dev/null
+++ b/games/doodlejump/src/doodle.h
@@ -0,0 +1,55 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Doodle Jump: original NumWorks implementation by Bobydeluxe.
+ */
+#ifndef DOODLE_H
+#define DOODLE_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#define DJ_Q 256
+#define DJ_WIDTH 288
+#define DJ_LEFT 18
+#define DJ_RIGHT (DJ_WIDTH-18)
+#define DJ_TICK_MS 16
+#define DJ_PLATFORMS 16
+#define DJ_ENEMIES 3
+#define DJ_SHOTS 3
+#define DJ_SAVE_BYTES 384
+#define DJ_LIMIT 1000000
+enum { DJ_WAIT, DJ_RUNNING, DJ_OVER };
+enum { DJ_SOLID, DJ_MOVING, DJ_BRITTLE, DJ_FADING };
+enum { DJ_SPRING=1, DJ_ROCKET=2 };
+enum { DJ_FELL=1, DJ_HIT=2 };
+typedef struct {
+ int32_t y;
+ uint16_t x;
+ uint8_t width,type,item,phase,active;
+} dj_platform;
+typedef struct { int32_t y; uint16_t x; uint8_t phase,active; } dj_enemy;
+typedef struct { int32_t x,y; uint8_t active; } dj_shot;
+typedef struct {
+ uint32_t best,runs,jumps,springs,rockets,monsters;
+ uint8_t motion;
+} dj_stats;
+typedef struct {
+ int32_t x,y,vx,vy,camera,peak,next_y;
+ uint32_t rng,tick,rows,jumps;
+ uint16_t route_x;
+ uint8_t phase,present,started,reason,boost,cooldown,face,bounce;
+ uint8_t route_phase; /* Half/run/direction history; zero starts a new history. */
+ dj_platform platform[DJ_PLATFORMS];
+ dj_enemy enemy[DJ_ENEMIES];
+ dj_shot shot[DJ_SHOTS];
+} dj_game;
+void dj_new(dj_game *g,uint32_t seed);
+void dj_start(dj_game *g,dj_stats *s);
+void dj_migrate(dj_game *g);
+void dj_step(dj_game *g,dj_stats *s,int steering);
+bool dj_fire(dj_game *g);
+uint32_t dj_height(const dj_game *g);
+int32_t dj_platform_x(const dj_platform *p,uint32_t tick);
+int32_t dj_enemy_x(const dj_enemy *e,uint32_t tick);
+bool dj_valid(const dj_game *g,const dj_stats *s);
+void dj_encode(const dj_game *g,const dj_stats *s,uint8_t out[DJ_SAVE_BYTES]);
+bool dj_decode(dj_game *g,dj_stats *s,const uint8_t *p,size_t n);
+#endif
diff --git a/games/doodlejump/src/icon.png b/games/doodlejump/src/icon.png
new file mode 100644
index 00000000..4f8bb9c1
Binary files /dev/null and b/games/doodlejump/src/icon.png differ
diff --git a/games/doodlejump/src/main.c b/games/doodlejump/src/main.c
new file mode 100644
index 00000000..ee63abc0
--- /dev/null
+++ b/games/doodlejump/src/main.c
@@ -0,0 +1,120 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <eadk.h>
+#include "doodle.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")))="Doodle Jump";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level")))=0;
+#endif
+#define KEY(k) (UINT64_C(1)<<(k))
+static dj_game game;
+static dj_stats stats;
+static uint8_t save_data[DJ_SAVE_BYTES];
+static bool have_save,save_failed;
+static uint32_t last_checksum;
+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) {
+ dj_encode(&game,&stats,save_data);
+ unsigned n=DJ_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("doodlejump.sav",save_data,DJ_SAVE_BYTES);
+ if(!save_failed)have_save=true,last_checksum=hash;
+ return !save_failed;
+}
+static void fresh(uint32_t seed) {dj_new(&game,seed);}
+int main(void) {
+ np_app_begin();stats.motion=1;
+ uint32_t length=0;const uint8_t *data=ef_read("doodlejump.sav",&length);
+ dj_decode(&game,&stats,data,length);
+ unsigned view=DJ_TITLE,selected=0,help_return=DJ_TITLE,help_selection=2;
+ unsigned error_return=DJ_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;
+ dj_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!=DJ_SAVE_ERROR&&(keys&(KEY(eadk_key_home)|KEY(eadk_key_on_off)))) {
+ if(save())break;
+ error_return=view==DJ_PLAY?DJ_READY:view;error_selection=selected;
+ view=DJ_SAVE_ERROR;hit=0;ok=back=next=prev=false;stale=keys;
+ }
+ if(view==DJ_PLAY) {
+ if(back)view=DJ_PAUSE,selected=0,save();
+ else {
+ if(hit&(KEY(eadk_key_ok)|KEY(eadk_key_exe)|KEY(eadk_key_up)))dj_fire(&game);
+ int steer=(active&(KEY(eadk_key_right)|KEY(eadk_key_six))?1:0)-
+ (active&(KEY(eadk_key_left)|KEY(eadk_key_four))?1:0);
+ if(now-tick_at>4*DJ_TICK_MS)tick_at=now-4*DJ_TICK_MS;
+ while(now-tick_at>=DJ_TICK_MS&&game.phase==DJ_RUNNING) {
+ dj_step(&game,&stats,steer);tick_at+=DJ_TICK_MS;
+ }
+ if(game.phase==DJ_OVER)view=DJ_RESULT,selected=0,save();
+ if(now-save_at>=5000)save(),save_at=now;
+ }
+ } else {
+ tick_at=now;
+ if(view==DJ_TITLE) {
+ if(next)selected=(selected+1)%3;
+ if(prev)selected=(selected+2)%3;
+ if(back) {
+ if(save())break;
+ error_return=DJ_TITLE;error_selection=selected;view=DJ_SAVE_ERROR;
+ } else if(ok) {
+ if(selected==0) {
+ if(!game.present||game.phase==DJ_OVER)fresh(now^(stats.runs*0x9E3779B9u));
+ view=DJ_READY;selected=0;
+ } else if(selected==1)view=DJ_JOURNAL,selected=0;
+ else help_return=DJ_TITLE,help_selection=2,view=DJ_GUIDE;
+ }
+ } else if(view==DJ_READY) {
+ if(back)view=DJ_TITLE,selected=0;
+ else if(ok)dj_start(&game,&stats),view=DJ_PLAY,tick_at=now;
+ } else if(view==DJ_PAUSE) {
+ if(next)selected=(selected+1)%4;
+ if(prev)selected=(selected+3)%4;
+ if(back||(ok&&selected==0))view=DJ_READY;
+ else if(ok&&selected==1)view=DJ_CONFIRM,selected=0;
+ else if(ok&&selected==2)help_return=DJ_PAUSE,help_selection=2,view=DJ_GUIDE;
+ else if(ok&&selected==3)view=DJ_TITLE,selected=0;
+ } else if(view==DJ_CONFIRM) {
+ if(next||prev)selected=!selected;
+ if(back||(ok&&selected==0))view=DJ_PAUSE,selected=1;
+ else if(ok)fresh(now^(stats.runs*0x9E3779B9u)),view=DJ_READY,selected=0;
+ } else if(view==DJ_RESULT) {
+ if(next||prev)selected=!selected;
+ if(back||(ok&&selected))view=DJ_TITLE,selected=0;
+ else if(ok)fresh(now^(stats.runs*0x9E3779B9u)),view=DJ_READY,selected=0;
+ } else if(view==DJ_JOURNAL) {
+ if(back)view=DJ_TITLE,selected=1;
+ else if(ok||next||prev)stats.motion=!stats.motion,save();
+ } else if(view==DJ_GUIDE) {
+ if(back||ok)view=help_return,selected=help_selection;
+ } else if(view==DJ_SAVE_ERROR) {
+ if(back)break;
+ if(ok&&save())break;
+ if(hit&KEY(eadk_key_one))view=error_return,selected=error_selection;
+ }
+ }
+ if(now-draw_at>=32||hit||!perf_frames) {
+ uint32_t start=(uint32_t)eadk_timing_millis();
+ dj_render(&game,&stats,view,selected,now,save_failed,push);
+ uint32_t spent=(uint32_t)eadk_timing_millis()-start;
+ 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/doodlejump/src/physics.c b/games/doodlejump/src/physics.c
new file mode 100644
index 00000000..602207e2
--- /dev/null
+++ b/games/doodlejump/src/physics.c
@@ -0,0 +1,245 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "doodle.h"
+#include <string.h>
+static int32_t clamp(int32_t x,int32_t low,int32_t high) {
+ return x<low?low:x>high?high:x;
+}
+static int32_t distance(int32_t a,int32_t b) {
+ int32_t d=a-b;
+ return d<0?-d:d;
+}
+static void add(uint32_t *v) {if(*v<UINT32_MAX)++*v;}
+static uint32_t random32(dj_game *g) {
+ uint32_t x=g->rng;x^=x<<13;x^=x>>17;x^=x<<5;return g->rng=x;
+}
+static int wave(uint32_t tick,unsigned phase) {
+ unsigned t=(tick+phase)&127;
+ return t<64?(int)t-32:95-(int)t;
+}
+int32_t dj_platform_x(const dj_platform *p,uint32_t tick) {
+ int half=(p->width+1)/2;
+ return clamp((int32_t)p->x*DJ_Q+(p->type==DJ_MOVING?wave(tick,p->phase)*128:0),half*DJ_Q,(DJ_WIDTH-half)*DJ_Q);
+}
+int32_t dj_enemy_x(const dj_enemy *e,uint32_t tick) {
+ return clamp((int32_t)e->x*DJ_Q+wave(tick,e->phase)*96,DJ_LEFT*DJ_Q,DJ_RIGHT*DJ_Q);
+}
+uint32_t dj_height(const dj_game *g) {
+ return g->peak>20*DJ_Q?(uint32_t)(g->peak/DJ_Q-20):0;
+}
+static dj_platform *slot(dj_game *g) {
+ for(unsigned i=0;i<DJ_PLATFORMS;++i)
+ if(!g->platform[i].active||g->platform[i].y<g->camera-32*DJ_Q)return &g->platform[i];
+ return NULL;
+}
+static void generate(dj_game *g) {
+ /* Random short/medium/long hops, not a fixed sweep. Reflect proposals at
+ * the walls instead of piling them onto an edge. A brief inward bias after
+ * four ledges in one half prevents prolonged one-sided climbs. */
+ dj_platform *p=slot(g);
+ if(!p)return;
+ uint32_t r=random32(g);unsigned level=dj_height(g)/600;
+ if(level>5)level=5;
+ unsigned half_run=g->route_phase&7,run=(g->route_phase>>3)&7;
+ bool before_right=(g->route_phase&64)!=0,right=((r>>16)&1)!=0;
+ unsigned roll=r%10;
+ int step=roll==0?(int)((r>>8)%9):roll<4?12+(int)((r>>8)%21):32+(int)((r>>8)%37);
+ if(run>=3)right=!before_right;
+ if(half_run>=4)right=g->route_x<144,step=48+(int)((r>>8)%21);
+ int next=g->route_x+(right?step:-step);
+ if(next<24)next=48-next;
+ if(next>264)next=528-next;
+ /* Imported routes can begin outside the new centre range. Keep the first
+ * generated hop bounded too, without rearranging already visible ledges. */
+ next=(int)clamp(next,(int)g->route_x-68,(int)g->route_x+68);
+ if(next!=g->route_x)right=next>g->route_x;
+ run=next==g->route_x?0:right==before_right?run+1:1;
+ if(run>7)run=7;
+ half_run=(next<144)==(g->route_x<144)?half_run+1:1;
+ if(half_run>6)half_run=6;
+ g->route_phase=(uint8_t)(half_run|(run<<3)|(right?64:0));
+ g->route_x=(uint16_t)next;++g->rows;
+ unsigned type=DJ_SOLID;
+ if(g->rows>8&&(r>>8)%5==0)type=DJ_MOVING;
+ else if(g->rows>16&&(r>>8)%7==0)type=DJ_FADING;
+ unsigned item=g->rows%23==0?DJ_ROCKET:g->rows%7==0?DJ_SPRING:0;
+ *p=(dj_platform){g->next_y,(uint16_t)next,(uint8_t)(58-level*3),
+ (uint8_t)type,(uint8_t)item,(uint8_t)(r>>16),1};
+ if(g->rows>8&&g->rows%3==0) {
+ dj_platform *bonus=slot(g);
+ if(bonus) {
+ int bx=next<144?next+100:next-100;
+ *bonus=(dj_platform){g->next_y-13*DJ_Q,(uint16_t)bx,39,DJ_BRITTLE,0,0,1};
+ }
+ }
+ if(g->rows>12&&g->rows%11==0) {
+ for(unsigned i=0;i<DJ_ENEMIES;++i)if(!g->enemy[i].active||g->enemy[i].y<g->camera-32*DJ_Q) {
+ unsigned ex=(unsigned)(next+110)%DJ_WIDTH;
+ g->enemy[i]=(dj_enemy){g->next_y+20*DJ_Q,(uint16_t)ex,(uint8_t)r,1};break;
+ }
+ }
+ g->next_y+=(int32_t)(36+(r>>24)%19)*DJ_Q;
+}
+void dj_new(dj_game *g,uint32_t seed) {
+ memset(g,0,sizeof *g);g->rng=seed?seed:0x6D2B79F5u;
+ g->x=144*DJ_Q;g->y=g->peak=20*DJ_Q;g->vy=1440;
+ g->phase=DJ_WAIT;g->present=1;g->face=1;g->route_x=144;
+ g->platform[0]=(dj_platform){20*DJ_Q,144,68,DJ_SOLID,0,0,1};
+ g->next_y=62*DJ_Q;
+ while(g->next_y<230*DJ_Q)generate(g);
+}
+void dj_start(dj_game *g,dj_stats *s) {
+ if(!g->present||g->phase==DJ_OVER)return;
+ if(!g->started)add(&s->runs),g->started=1;
+ g->phase=DJ_RUNNING;
+}
+void dj_migrate(dj_game *g) {
+ if(!g->present)return;
+ int32_t bounded=clamp(g->x,DJ_LEFT*DJ_Q,DJ_RIGHT*DJ_Q);
+ if(bounded!=g->x)g->x=bounded,g->vx=0;
+ /* Keep an imported flight's height, items and records. Put its nearest
+ * supporting route ledge under the player, then repair only the route
+ * above it: an old edge-to-edge jump must not require wrapping anymore. */
+ int anchor=-1;int32_t floor=INT32_MIN;
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ dj_platform *p=&g->platform[i];
+ if(p->active&&p->type!=DJ_BRITTLE&&p->y<=g->y&&p->y>floor)anchor=(int)i,floor=p->y;
+ }
+ int x=g->x/DJ_Q;
+ if(anchor>=0)g->platform[anchor].x=(uint16_t)x;
+ else floor=g->y;
+ for(unsigned n=0;n<DJ_PLATFORMS;++n) {
+ int best=-1;int32_t lowest=INT32_MAX;
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ dj_platform *p=&g->platform[i];
+ if(p->active&&p->type!=DJ_BRITTLE&&p->y>floor&&p->y<lowest)best=(int)i,lowest=p->y;
+ }
+ if(best<0)break;
+ dj_platform *p=&g->platform[best];x=(int)clamp(p->x,x-68,x+68);
+ p->x=(uint16_t)x;floor=p->y;
+ }
+ g->route_x=(uint16_t)x;g->route_phase=0;
+}
+bool dj_fire(dj_game *g) {
+ if(g->phase!=DJ_RUNNING||g->cooldown)return false;
+ for(unsigned i=0;i<DJ_SHOTS;++i)if(!g->shot[i].active) {
+ g->shot[i]=(dj_shot){g->x,g->y+18*DJ_Q,1};g->cooldown=12;return true;
+ }
+ return false;
+}
+static void bounce(dj_game *g,dj_stats *s,int32_t velocity) {
+ g->vy=velocity;g->bounce=9;add(&g->jumps);add(&s->jumps);
+}
+void dj_step(dj_game *g,dj_stats *s,int steering) {
+ if(g->phase!=DJ_RUNNING)return;
+ ++g->tick;
+ if(g->cooldown)--g->cooldown;
+ if(g->bounce)--g->bounce;
+ if(steering) {
+ g->vx+=steering>0?96:-96;g->face=(uint8_t)(steering>0);
+ if(g->vx>672)g->vx=672;
+ if(g->vx<-672)g->vx=-672;
+ } else {
+ g->vx=g->vx*3/4;
+ if(g->vx<12&&g->vx>-12)g->vx=0;
+ }
+ int32_t old_x=g->x,old_y=g->y;
+ g->x=clamp(g->x+g->vx,DJ_LEFT*DJ_Q,DJ_RIGHT*DJ_Q);
+ if((g->x==DJ_LEFT*DJ_Q&&g->vx<0)||(g->x==DJ_RIGHT*DJ_Q&&g->vx>0))g->vx=0;
+ bool powered=g->boost!=0;
+ if(g->boost) {--g->boost;g->vy=1536;}
+ else {
+ g->vy-=47;
+ if(g->vy<-2304)g->vy=-2304;
+ }
+ g->y+=g->vy;
+ /* Descending feet cross the highest intersected platform first. Fractional
+ * time-of-impact steering follows the actual movement, including wall stops.
+ */
+ int found=-1;int32_t highest=INT32_MIN;
+ if(g->vy<=0)for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ dj_platform *p=&g->platform[i];
+ if(!p->active||old_y<p->y||g->y>p->y||p->y<highest)continue;
+ int32_t fraction=old_y==g->y?0:(old_y-p->y)*DJ_Q/(old_y-g->y);
+ int32_t hit_x=old_x+(g->x-old_x)*fraction/DJ_Q;
+ int32_t before=dj_platform_x(p,g->tick-1),after=dj_platform_x(p,g->tick);
+ int32_t px=before+(after-before)*fraction/DJ_Q;
+ if(distance(hit_x,px)<((int32_t)p->width/2+7)*DJ_Q)found=(int)i,highest=p->y;
+ }
+ if(found>=0) {
+ dj_platform *p=&g->platform[found];
+ if(p->type==DJ_BRITTLE)p->active=0;
+ else {
+ g->y=p->y;bounce(g,s,1440);
+ bool centre=distance(g->x,dj_platform_x(p,g->tick))<17*DJ_Q;
+ if(centre&&p->item==DJ_SPRING)g->vy=2432,add(&s->springs);
+ if(centre&&p->item==DJ_ROCKET)g->boost=80,g->vy=1536,add(&s->rockets),p->item=0;
+ if(p->type==DJ_FADING)p->active=0;
+ }
+ }
+ for(unsigned i=0;i<DJ_SHOTS;++i) {
+ dj_shot *b=&g->shot[i];
+ if(!b->active)continue;
+ int32_t from=b->y;b->y+=9*DJ_Q;
+ if(b->y>g->camera+245*DJ_Q)b->active=0;
+ for(unsigned j=0;j<DJ_ENEMIES&&b->active;++j) {
+ dj_enemy *e=&g->enemy[j];
+ if(e->active&&distance(b->x,dj_enemy_x(e,g->tick))<14*DJ_Q&&from<e->y+12*DJ_Q&&b->y>e->y-10*DJ_Q)
+ e->active=b->active=0,add(&s->monsters);
+ }
+ }
+ for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ dj_enemy *e=&g->enemy[i];
+ if(!e->active)continue;
+ if(distance(g->x,dj_enemy_x(e,g->tick))<19*DJ_Q&&g->y<e->y+12*DJ_Q&&g->y+18*DJ_Q>e->y-9*DJ_Q) {
+ if(powered||g->boost||(g->vy<=0&&old_y>=e->y+7*DJ_Q)) {
+ e->active=0;add(&s->monsters);
+ if(!powered&&!g->boost)g->y=e->y+12*DJ_Q,bounce(g,s,1690);
+ } else g->phase=DJ_OVER,g->reason=DJ_HIT;
+ }
+ if(e->y<g->camera-32*DJ_Q)e->active=0;
+ }
+ if(g->y>DJ_LIMIT*DJ_Q)g->y=DJ_LIMIT*DJ_Q,g->vy=-47,g->boost=0;
+ if(g->y>g->peak)g->peak=g->y;
+ if(g->y-g->camera>124*DJ_Q)g->camera=g->y-124*DJ_Q;
+ uint32_t height=dj_height(g);
+ if(height>s->best)s->best=height;
+ if(g->y<g->camera-24*DJ_Q)g->phase=DJ_OVER,g->reason=DJ_FELL;
+ while(g->next_y<g->camera+232*DJ_Q) {
+ int32_t before=g->next_y;generate(g);
+ if(before==g->next_y)break;
+ }
+}
+bool dj_valid(const dj_game *g,const dj_stats *s) {
+ if(s->motion>1||s->best>DJ_LIMIT||g->present>1)return false;
+ if(!g->present)return true;
+ if(!g->rng||g->phase>DJ_OVER||g->started>1||g->reason>DJ_HIT||g->face>1||
+ g->boost>80||g->cooldown>12||g->bounce>9||g->route_x>=DJ_WIDTH||g->route_phase>127||
+ (g->route_phase&&(!(g->route_phase&7)||(g->route_phase&7)>6))||
+ g->x<0||g->x>=DJ_WIDTH*DJ_Q||g->vx<-672||g->vx>672||g->vy<-2304||g->vy>2432||
+ g->camera<0||g->camera>DJ_LIMIT*DJ_Q||g->peak<20*DJ_Q||g->peak>DJ_LIMIT*DJ_Q||
+ g->y<g->camera-40*DJ_Q||g->y>g->camera+250*DJ_Q||g->peak<g->y||
+ g->next_y<g->camera||g->next_y>g->camera+300*DJ_Q||
+ g->rows>DJ_LIMIT/36+20||(!g->started&&g->phase!=DJ_WAIT)||
+ (g->phase==DJ_OVER&&!g->reason)||(g->phase!=DJ_OVER&&g->reason))return false;
+ unsigned live=0;
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ const dj_platform *p=&g->platform[i];
+ if(p->active>1)return false;
+ if(!p->active)continue;
+ ++live;
+ if(p->x>=DJ_WIDTH||p->width<26||p->width>68||p->type>DJ_FADING||p->item>DJ_ROCKET||
+ p->y<0||p->y>g->camera+300*DJ_Q)return false;
+ }
+ if(!live)return false;
+ for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ const dj_enemy *e=&g->enemy[i];
+ if(e->active>1)return false;
+ if(e->active&&(e->x>=DJ_WIDTH||e->y<0||e->y>g->camera+330*DJ_Q))return false;
+ }
+ for(unsigned i=0;i<DJ_SHOTS;++i) {
+ const dj_shot *b=&g->shot[i];
+ if(b->active>1)return false;
+ if(b->active&&(b->x<0||b->x>=DJ_WIDTH*DJ_Q||b->y<g->camera-40*DJ_Q||b->y>g->camera+260*DJ_Q))return false;
+ }
+ return true;
+}
diff --git a/games/doodlejump/src/render.c b/games/doodlejump/src/render.c
new file mode 100644
index 00000000..84b05c12
--- /dev/null
+++ b/games/doodlejump/src/render.c
@@ -0,0 +1,315 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * An ink-and-graph-paper field notebook. All artwork is procedural.
+ * One 5,120-byte strip buffer; no framebuffer, sprites, heap or floating point.
+ */
+#include "render.h"
+#include <stdlib.h>
+#include <string.h>
+#define C(v) ((uint16_t)((((v)>>8)&0xF800)|(((v)>>5)&0x07E0)|(((v)>>3)&31)))
+#define PAPER C(0xFAF4DD)
+#define INK C(0x294853)
+#define GRID C(0xDBE5D8)
+#define GREEN C(0x8DBD69)
+#define BLUE C(0x71A6B5)
+#define RED C(0xC76A55)
+#define LIGHT C(0xFFFBEF)
+#define PENCIL C(0x7B8D87)
+static uint16_t band[320*8];
+static int x0,y0,x1,y1;
+static int16_t lo[30],hi[30];
+static bool initialized;
+static const dj_game *world;
+static const dj_stats *stats;
+static unsigned page,selection;
+static uint32_t clock_ms;
+static bool failed;
+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<lo[row])lo[row]=(int16_t)x;
+ if(x+w>hi[row])hi[row]=(int16_t)(x+w);
+ }
+}
+void dj_invalidate(void) {initialized=false;mark(0,0,320,240);}
+static void pixel(int x,int y,uint16_t color) {
+ if(x>=x0&&x<x1&&y>=y0&&y<y1)band[(y-y0)*(x1-x0)+x-x0]=color;
+}
+static void rect(int x,int y,int w,int h,uint16_t color) {
+ int l=x<x0?x0:x,t=y<y0?y0:y,r=x+w>x1?x1:x+w,b=y+h>y1?y1:y+h;
+ if(l>=r||t>=b)return;
+ 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++=color;
+ }
+}
+static void line(int a,int b,int c,int d,uint16_t color) {
+ 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,e=dx+dy;
+ for(;;) {
+ pixel(a,b,color);
+ if(a==c&&b==d)break;
+ int twice=e*2;
+ if(twice>=dy)e+=dy,a+=sx;
+ if(twice<=dx)e+=dx,b+=sy;
+ }
+}
+static void circle(int x,int y,int r,uint16_t color) {
+ if(y+r<y0||y-r>=y1||x+r<x0||x-r>=x1)return;
+ int start=y-r>y0?y-r:y0,end=y+r<y1?y+r:y1-1;
+ for(int j=start;j<=end;++j) {
+ int dy=j-y,half=0;
+ while((half+1)*(half+1)+dy*dy<=r*r)++half;
+ rect(x-half,j,half*2+1,1,color);
+ }
+}
+static void text(int x,int y,const char *s,int scale,uint16_t color) {
+ 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,color);
+ }
+}
+static void center(int x,int y,const char *s,int scale,uint16_t color) {
+ text(x-((int)strlen(s)*6*scale-scale)/2,y,s,scale,color);
+}
+static void number(int x,int y,uint32_t value,int scale,uint16_t color) {
+ char s[11];unsigned n=0;
+ do{s[n++]=(char)('0'+value%10);value/=10;}while(value);
+ for(unsigned 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,color);
+}
+static void arrow(int x,int y,int direction,uint16_t color) {
+ line(x,y,x+direction*12,y,color);line(x+direction*12,y,x+direction*7,y-4,color);
+ line(x+direction*12,y,x+direction*7,y+4,color);
+}
+static void paper(bool ruled) {
+ rect(x0,y0,x1-x0,y1-y0,PAPER);
+ if(ruled)for(int y=y0;y<y1;++y)if(y%24==0)rect(0,y,320,1,GRID);
+}
+static void hero(int x,int foot,int size,bool face,unsigned bounce,unsigned boost) {
+ if(foot<y0||foot-35*size>=y1||x+20*size<x0||x-20*size>=x1)return;
+ int top=foot-18*size+(bounce?size:0),nose=face?1:-1;
+ if(boost) {
+ int tail=(boost&2)?11:8;
+ line(x-9*size,foot,x-11*size,foot+tail*size,RED);
+ line(x-8*size,foot,x-7*size,foot+(tail-3)*size,C(0xD8AB45));
+ }
+ circle(x,top,10*size,INK);rect(x-10*size,top,20*size,12*size,INK);
+ circle(x,top,9*size,GREEN);rect(x-9*size,top,18*size,11*size,GREEN);
+ rect(x-9*size,top+11*size,18*size,size,INK);
+ for(int k=-5;k<=5;k+=5)line(x+k*size,top+3*size,x+(k-1)*size,top+9*size,C(0x6B9955));
+ rect(x-14*size,top+3*size,5*size,11*size,INK);
+ rect(x-13*size,top+4*size,3*size,8*size,boost?RED:BLUE);
+ rect(x+nose*8*size-(nose<0?7*size:0),top-size,9*size,6*size,INK);
+ rect(x+nose*8*size-(nose<0?6*size:0),top,8*size,4*size,GREEN);
+ for(int i=0;i<2;++i) {
+ int ex=x+(face?2+i*4:-5-i*4)*size;
+ rect(ex,top-5*size,3*size,5*size,LIGHT);rect(ex+size,top-3*size,size,2*size,INK);
+ }
+ line(x-6*size,top+12*size,x-7*size,foot,INK);line(x+5*size,top+12*size,x+7*size,foot,INK);
+ line(x-9*size,foot,x-4*size,foot,INK);line(x+4*size,foot,x+10*size,foot,INK);
+}
+static void spring(int x,int y) {
+ for(int k=0;k<4;++k)line(x+(k&1?4:-4),y-2-k*2,x+(k&1?-4:4),y-4-k*2,INK);
+ line(x-5,y-10,x+5,y-10,RED);
+}
+static void rocket(int x,int y) {
+ line(x-4,y,x-4,y-12,INK);line(x+4,y,x+4,y-12,INK);
+ line(x-4,y-12,x,y-17,INK);line(x,y-17,x+4,y-12,INK);
+ rect(x-3,y-11,7,10,RED);circle(x,y-9,2,LIGHT);
+ line(x-4,y-2,x-7,y+2,INK);line(x+4,y-2,x+7,y+2,INK);
+}
+static void ledge(int x,int y,int w,unsigned type,unsigned item) {
+ if(y+6<y0||y-18>=y1)return;
+ uint16_t color=type==DJ_MOVING?BLUE:type==DJ_BRITTLE?C(0xB8936E):type==DJ_FADING?LIGHT:GREEN;
+ int left=x-w/2;rect(left,y,w,6,INK);rect(left+1,y+1,w-2,4,color);
+ line(left+3,y+2,left+w-5,y+2,LIGHT);
+ if(type==DJ_BRITTLE){line(x-4,y,x+1,y+3,INK);line(x+1,y+3,x-2,y+6,INK);}
+ if(type==DJ_MOVING){line(x-4,y+3,x+4,y+3,INK);pixel(x-4,y+2,INK);pixel(x+4,y+4,INK);}
+ if(type==DJ_FADING)for(int k=left+6;k<left+w-3;k+=6)pixel(k,y+4,PENCIL);
+ if(item==DJ_SPRING)spring(x,y);else if(item==DJ_ROCKET)rocket(x,y);
+}
+static void monster(int x,int y,unsigned tick) {
+ if(y+12<y0||y-12>=y1)return;
+ circle(x,y,11,INK);circle(x,y,10,C(0xD99890));
+ for(int k=-8;k<=8;k+=8){line(x+k,y-7,x+k-3,y-14,INK);circle(x+k-3,y-14,1,INK);}
+ circle(x-4,y-3,3,LIGHT);circle(x+4,y-3,3,LIGHT);
+ circle(x-3,y-3,1,INK);circle(x+5,y-3,1,INK);
+ line(x-4,y+4,x+4,y+4,INK);
+ for(int k=-7;k<=7;k+=7)line(x+k,y+8,x+k+(tick&8?3:-3),y+13,INK);
+}
+static void flight(void) {
+ const dj_game *g=world;
+ paper(false);
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ const dj_platform *p=&g->platform[i];
+ if(!p->active)continue;
+ int y=227-(int)((p->y-g->camera)/DJ_Q);
+ if(y>=31&&y<=234) {
+ int px=16+(int)(dj_platform_x(p,g->tick)/DJ_Q);
+ ledge(px,y,p->width,p->type,p->item);
+ }
+ }
+ for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ const dj_enemy *e=&g->enemy[i];
+ if(!e->active)continue;
+ int y=227-(int)((e->y-g->camera)/DJ_Q);
+ if(y>=38&&y<=236) {
+ int px=16+(int)(dj_enemy_x(e,g->tick)/DJ_Q);unsigned tick=stats->motion?g->tick:0;
+ monster(px,y,tick);
+ }
+ }
+ for(unsigned i=0;i<DJ_SHOTS;++i) {
+ const dj_shot *b=&g->shot[i];
+ if(!b->active)continue;
+ int y=227-(int)((b->y-g->camera)/DJ_Q);
+ if(y>=29&&y<228)circle(16+b->x/DJ_Q,y,2,INK);
+ }
+ int x=16+g->x/DJ_Q,y=227-(int)((g->y-g->camera)/DJ_Q);
+ unsigned boost=g->boost?(stats->motion?g->boost:1):0;
+ hero(x,y,1,g->face,stats->motion?g->bounce:0,boost);
+ rect(0,0,320,26,PAPER);line(21,25,316,25,GRID);
+ text(26,5,"HEIGHT",1,PENCIL);number(72,5,dj_height(g),2,INK);
+ text(210,5,"BEST",1,PENCIL);number(241,5,stats->best,1,INK);
+ if(g->boost){rect(211,17,g->boost,3,RED);text(146,16,"ROCKET",1,RED);}
+ rect(0,228,320,12,PAPER);line(21,228,316,228,GRID);
+ text(25,232,"< > MOVE",1,INK);text(101,232,"OK SHOOT",1,INK);text(229,232,"BACK PAUSE",1,PENCIL);
+}
+static void entry(int y,const char *label,bool active) {
+ text(32,y,label,1,active?INK:PENCIL);
+ if(active){arrow(207,y+4,1,RED);line(32,y+11,168,y+11,RED);}
+}
+static void title(void) {
+ paper(true);
+ text(31,33,"DOODLE",3,INK);text(32,61,"JUMP",3,INK);
+ line(31,87,158,89,RED);
+ text(32,125,"BEST",1,PENCIL);number(81,123,stats->best,2,INK);
+ unsigned t=stats->motion?(clock_ms/100)%16:4;
+ int lift=t<8?(int)t:15-(int)t;
+ ledge(259,144,53,DJ_SOLID,DJ_SPRING);
+ hero(256,126-lift*2,2,true,0,0);
+ bool resume=world->present&&world->phase!=DJ_OVER;
+ entry(163,resume?"CONTINUE CLIMB":"START CLIMBING",selection==0);
+ entry(184,"FIELD NOTES",selection==1);entry(205,"HOW TO PLAY",selection==2);
+ text(30,231,"BY BOBYDELUXE",1,PENCIL);text(215,231,"OK OPEN",1,PENCIL);
+}
+static void heading(const char *name) {
+ paper(true);text(30,17,name,2,INK);line(30,38,300,39,RED);
+}
+static void journal(void) {
+ heading("FIELD NOTES");
+ const char *labels[]={"HIGHEST CLIMB","EXPEDITIONS","BOUNCES","SPRINGS USED","ROCKET RIDES","MONSTERS CLEARED"};
+ uint32_t values[]={stats->best,stats->runs,stats->jumps,stats->springs,stats->rockets,stats->monsters};
+ for(unsigned i=0;i<6;++i) {
+ int y=71+(int)i*20;text(31,y,labels[i],1,INK);number(226,y,values[i],1,INK);line(31,y+12,296,y+12,GRID);
+ }
+ text(31,201,"ANIMATIONS",1,INK);text(226,201,stats->motion?"ON":"REDUCED",1,RED);
+ text(31,217,"OK / LEFT / RIGHT TO CHANGE",1,PENCIL);text(263,231,"BACK",1,PENCIL);
+}
+static void guide(void) {
+ heading("HOW TO CLIMB");
+ text(31,69,"LEFT / RIGHT STEER",1,INK);
+ text(31,85,"OK / EXE / UP SHOOT UPWARD",1,INK);
+ text(31,101,"BACK PAUSE HOME SAVE / EXIT",1,INK);
+ ledge(57,128,43,DJ_SOLID,0);text(91,128,"SAFE LANDING",1,INK);
+ ledge(57,147,43,DJ_MOVING,0);text(91,147,"MOVES SIDE TO SIDE",1,INK);
+ ledge(57,166,43,DJ_BRITTLE,0);text(91,166,"BREAKS. NO BOUNCE!",1,RED);
+ ledge(57,185,43,DJ_FADING,0);text(91,185,"ONE BOUNCE ONLY",1,INK);
+ spring(47,214);rocket(74,217);text(96,207,"LAND ON CENTRE TO BOOST",1,INK);
+ text(31,231,"STOMP OR SHOOT MONSTERS",1,PENCIL);text(263,231,"BACK",1,PENCIL);
+}
+static void sheet(void) {
+ rect(31,40,254,155,LIGHT);
+ line(31,40,285,40,INK);line(31,40,31,194,INK);line(285,40,285,194,INK);line(31,194,285,194,INK);
+}
+static void choice(int y,const char *label,unsigned id) {
+ text(56,y,label,1,selection==id?INK:PENCIL);
+ if(selection==id){arrow(40,y+3,1,RED);line(56,y+11,264,y+11,RED);}
+}
+static void modal(void) {
+ sheet();
+ if(page==DJ_READY) {
+ center(158,57,"A LITTLE HIGHER?",2,INK);
+ center(158,85,"BOUNCING IS AUTOMATIC.",1,PENCIL);
+ center(158,101,"LEFT / RIGHT TO FIND A LEDGE.",1,INK);
+ hero(157,151,1,true,0,0);ledge(157,153,59,DJ_SOLID,0);
+ center(158,173,"OK TO BEGIN",1,RED);
+ } else if(page==DJ_PAUSE) {
+ center(158,55,"PENCIL DOWN.",2,INK);
+ center(158,78,failed?"SAVE FAILED - STORAGE FULL":"YOUR CLIMB IS SAVED.",1,failed?RED:PENCIL);
+ choice(99,"KEEP CLIMBING",0);choice(120,"NEW EXPEDITION",1);choice(141,"HOW TO PLAY",2);choice(162,"TITLE PAGE",3);
+ } else if(page==DJ_CONFIRM) {
+ center(158,57,"A FRESH PAGE?",2,INK);
+ center(158,88,"YOUR CURRENT CLIMB WILL END.",1,PENCIL);
+ center(158,104,"YOUR RECORDS WILL STAY.",1,PENCIL);
+ choice(133,"KEEP THIS CLIMB",0);choice(162,"START NEW",1);
+ } else if(page==DJ_SAVE_ERROR) {
+ center(158,55,"SAVE FAILED",2,RED);
+ center(158,84,"NOT ENOUGH FREE STORAGE",1,INK);
+ center(158,101,"OR THE SAVE CANNOT BE WRITTEN.",1,PENCIL);
+ center(158,125,"OK RETRY SAVE",1,INK);center(158,146,"1 RETURN TO YOUR CLIMB",1,INK);
+ center(158,175,"BACK EXIT WITHOUT SAVING",1,RED);
+ } else {
+ center(158,55,"END OF THIS PAGE",2,INK);
+ center(158,80,world->reason==DJ_HIT?"A MONSTER CAUGHT YOU.":"THE NEXT LEDGE IS WAITING.",1,PENCIL);
+ text(59,104,"HEIGHT",1,PENCIL);number(112,99,dj_height(world),2,INK);
+ text(212,104,"BEST",1,PENCIL);number(212,119,stats->best,1,INK);
+ choice(142,"TRY AGAIN",0);choice(168,"TITLE PAGE",1);
+ }
+}
+static unsigned old_page=99,old_selection,old_motion,old_boost;
+static uint32_t old_tick,old_height,old_best,old_clock;
+static bool old_failed;
+void dj_render(const dj_game *g,const dj_stats *s,unsigned view,unsigned selected,uint32_t ms,bool save_failed,dj_push push) {
+ world=g;stats=s;page=view;selection=selected;clock_ms=ms;failed=save_failed;
+ bool full=!initialized||view!=old_page||selected!=old_selection||s->motion!=old_motion||failed!=old_failed;
+ if(full)mark(0,0,320,240);
+ else if(view==DJ_PLAY&&old_tick!=g->tick)mark(0,26,320,202);
+ else if(view==DJ_TITLE&&s->motion&&old_clock!=ms/100)mark(221,54,79,100);
+ if(view==DJ_PLAY&&(old_height!=dj_height(g)||old_best!=s->best||old_boost!=g->boost))mark(0,0,320,26);
+ old_page=view;old_selection=selected;old_motion=s->motion;old_failed=failed;
+ old_tick=g->tick;old_height=dj_height(g);old_best=s->best;old_boost=g->boost;old_clock=ms/100;
+ for(int row=0;row<30;++row) {
+ if(hi[row]<=lo[row])continue;
+ x0=lo[row];x1=hi[row];y0=row*8;y1=y0+8;
+ if(view==DJ_TITLE)title();else if(view==DJ_JOURNAL)journal();else if(view==DJ_GUIDE)guide();
+ else {
+ if(g->present)flight();else title();
+ if(view!=DJ_PLAY)modal();
+ }
+ push(x0,y0,x1-x0,8,band);lo[row]=320;hi[row]=0;
+ }
+ initialized=true;
+}
diff --git a/games/doodlejump/src/render.h b/games/doodlejump/src/render.h
new file mode 100644
index 00000000..703d9b24
--- /dev/null
+++ b/games/doodlejump/src/render.h
@@ -0,0 +1,9 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef DOODLE_RENDER_H
+#define DOODLE_RENDER_H
+#include "doodle.h"
+enum { DJ_TITLE,DJ_PLAY,DJ_READY,DJ_PAUSE,DJ_JOURNAL,DJ_GUIDE,DJ_CONFIRM,DJ_RESULT,DJ_SAVE_ERROR };
+typedef void (*dj_push)(int x,int y,int w,int h,const uint16_t *pixels);
+void dj_invalidate(void);
+void dj_render(const dj_game *g,const dj_stats *s,unsigned page,unsigned selected,uint32_t ms,bool failed,dj_push push);
+#endif
diff --git a/games/doodlejump/src/save.c b/games/doodlejump/src/save.c
new file mode 100644
index 00000000..993afee6
--- /dev/null
+++ b/games/doodlejump/src/save.c
@@ -0,0 +1,66 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "doodle.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<DJ_SAVE_BYTES-4;++i)h=(h^p[i])*16777619u;return h;
+}
+void dj_encode(const dj_game *g,const dj_stats *s,uint8_t out[DJ_SAVE_BYTES]) {
+ memset(out,0,DJ_SAVE_BYTES);memcpy(out,"DJN3",4);
+ w32(out+4,s->best);w32(out+8,s->runs);w32(out+12,s->jumps);
+ w32(out+16,s->springs);w32(out+20,s->rockets);w32(out+24,s->monsters);out[28]=s->motion;
+ w32(out+32,g->x);w32(out+36,g->y);w32(out+40,g->vx);w32(out+44,g->vy);
+ w32(out+48,g->camera);w32(out+52,g->peak);w32(out+56,g->next_y);
+ w32(out+60,g->rng);w32(out+64,g->tick);w32(out+68,g->rows);w32(out+72,g->jumps);
+ w16(out+76,g->route_x);out[78]=g->phase;out[79]=g->present;out[80]=g->started;
+ out[81]=g->reason;out[82]=g->boost;out[83]=g->cooldown;out[84]=g->face;out[85]=g->bounce;
+ out[86]=g->route_phase;
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ const dj_platform *p=&g->platform[i];uint8_t *d=out+96+i*12;
+ w32(d,p->y);w16(d+4,p->x);d[6]=p->width;d[7]=p->type;d[8]=p->item;d[9]=p->phase;d[10]=p->active;
+ }
+ for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ const dj_enemy *e=&g->enemy[i];uint8_t *d=out+288+i*8;
+ w32(d,e->y);w16(d+4,e->x);d[6]=e->phase;d[7]=e->active;
+ }
+ for(unsigned i=0;i<DJ_SHOTS;++i) {
+ const dj_shot *b=&g->shot[i];uint8_t *d=out+312+i*10;
+ w32(d,b->x);w32(d+4,b->y);d[8]=b->active;
+ }
+ w32(out+DJ_SAVE_BYTES-4,checksum(out));
+}
+bool dj_decode(dj_game *g,dj_stats *s,const uint8_t *p,size_t n) {
+ if(!p||n!=DJ_SAVE_BYTES||(memcmp(p,"DJN1",4)&&memcmp(p,"DJN2",4)&&memcmp(p,"DJN3",4))||r32(p+DJ_SAVE_BYTES-4)!=checksum(p))return false;
+ dj_game a;dj_stats b;memset(&a,0,sizeof a);memset(&b,0,sizeof b);
+ b.best=r32(p+4);b.runs=r32(p+8);b.jumps=r32(p+12);
+ b.springs=r32(p+16);b.rockets=r32(p+20);b.monsters=r32(p+24);b.motion=p[28];
+ a.x=(int32_t)r32(p+32);a.y=(int32_t)r32(p+36);a.vx=(int32_t)r32(p+40);a.vy=(int32_t)r32(p+44);
+ a.camera=(int32_t)r32(p+48);a.peak=(int32_t)r32(p+52);a.next_y=(int32_t)r32(p+56);
+ a.rng=r32(p+60);a.tick=r32(p+64);a.rows=r32(p+68);a.jumps=r32(p+72);
+ a.route_x=(uint16_t)r16(p+76);a.phase=p[78];a.present=p[79];a.started=p[80];
+ a.reason=p[81];a.boost=p[82];a.cooldown=p[83];a.face=p[84];a.bounce=p[85];
+ a.route_phase=p[86];
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ const uint8_t *d=p+96+i*12;
+ a.platform[i]=(dj_platform){(int32_t)r32(d),(uint16_t)r16(d+4),d[6],d[7],d[8],d[9],d[10]};
+ }
+ for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ const uint8_t *d=p+288+i*8;
+ a.enemy[i]=(dj_enemy){(int32_t)r32(d),(uint16_t)r16(d+4),d[6],d[7]};
+ }
+ for(unsigned i=0;i<DJ_SHOTS;++i) {
+ const uint8_t *d=p+312+i*10;a.shot[i]=(dj_shot){(int32_t)r32(d),(int32_t)r32(d+4),d[8]};
+ }
+ uint8_t previous_phase=a.route_phase;
+ if(p[3]!='3') {
+ if(previous_phase>12)return false;
+ a.route_phase=0;
+ }
+ if(!dj_valid(&a,&b))return false;
+ if(p[3]=='1')dj_migrate(&a);
+ else if(a.present&&(a.x<DJ_LEFT*DJ_Q||a.x>DJ_RIGHT*DJ_Q))return false;
+ *g=a;*s=b;return true;
+}
diff --git a/games/doodlejump/tests/arm.py b/games/doodlejump/tests/arm.py
new file mode 100644
index 00000000..9ecbe3ee
--- /dev/null
+++ b/games/doodlejump/tests/arm.py
@@ -0,0 +1,197 @@
+#!/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
+(the host test creates the reference input and save fixtures).
+"""
+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('doodlejump_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')
+# Keep static-menu checkpoints bounded at completed sleeps.
+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 state(c):
+ # Layout checked by offsetof assertions in the host/ARM C tests.
+ return bytes(c.uc.mem_read(c.symbols['game'],308))
+
+def performance(c):
+ result={k:u32(c,k) for k in ('perf_frames','perf_max','perf_slow')}
+ assert result['perf_max']<=32 and result['perf_slow']==0,result
+ return result
+
+def steering(g):
+ x,y,vx,vy,camera=struct.unpack_from('<5i',g)
+ tick=struct.unpack_from('<I',g,32)[0];boost=g[50];best=None
+ def delta(a,b):
+ return a-b
+ def position(base,kind,phase,time,width):
+ t=(time+phase)&127;wave=t-32 if t<64 else 95-t
+ return max(((width+1)//2)*256,min((288-(width+1)//2)*256,base*256+(wave*128 if kind==1 else 0)))
+ # Avoid rising into a monster's underside; descending onto it is safe.
+ for i in range(3):
+ ey,ex,phase,active=struct.unpack_from('<iH2B',g,248+i*8)
+ t=(tick+phase)&127;wave=t-32 if t<64 else 95-t
+ dx=delta(max(18*256,min(270*256,ex*256+wave*96)),x)
+ if active and vy>0 and not boost and -15*256<ey-y<80*256 and abs(dx)<30*256:
+ avoid=-1 if dx>=0 else 1
+ return 0 if (avoid<0 and x<46*256) or (avoid>0 and x>242*256) else avoid
+ for i in range(16):
+ py,px,width,kind,item,phase,active=struct.unpack_from('<iH5B',g,56+i*12)
+ if not active or kind==2 or py<camera-12*256:continue
+ yy,vv,bb=y,vy,boost
+ for t in range(1,200):
+ old=yy
+ if bb:bb-=1;vv=1536
+ else:vv=max(-2304,vv-47)
+ yy+=vv
+ if vv<0 and old>=py and yy<=py:
+ aim=position(px,kind,phase,tick+t,width)
+ if abs(delta(aim,x))<max(0,t-7)*672+(width//2+5)*256 and (best is None or py>best[0]):best=(py,aim)
+ break
+ if yy<camera-24*256:break
+ if best is None:return 0
+ dx=delta(best[1],x+vx*3)
+ return 0 if abs(dx)<3*256 else 1 if dx>0 else -1
+
+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/'doodlejump-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()
+ c.keys=presses((0,'ok',300),(600,'ok',70),(1000,'ok',70),(1150,'up',500),(1750,'back',70),(1950,'down',70),(2100,'ok',70),(2250,'back',70),(2400,'up',70),(2550,'ok',70),(2700,'ok',70),(3000,'home',120))
+ c.run(550);c.save_png(str(OUT/(name+'-title.png')))
+ c.run(1280);g=state(c);assert g[46]==1 and sum(g[280+i*12] for i in range(3))==1
+ c.run(1690);g=state(c);assert g[51]==0 and sum(g[280+i*12] for i in range(3))==0,'Held shoot key repeated'
+ c.save_png(str(OUT/(name+'-gameplay.png')))
+ c.run(1900);saved=records(c.storage_bytes())['doodlejump.sav']
+ assert len(saved)==384 and saved[:4]==b'DJN3' and saved[80]==1
+ frozen_tick=struct.unpack_from('<I',saved,64)[0];c.save_png(str(OUT/(name+'-pause.png')))
+ c.run(2380);assert records(c.storage_bytes())['doodlejump.sav']==saved
+ assert struct.unpack_from('<I',state(c),32)[0]==frozen_tick,'Pause/confirmation advanced the world'
+ c.run(2900);perf=performance(c);c.run(3300);safe(c)
+ saved=records(c.storage_bytes())['doodlejump.sav']
+ assert struct.unpack_from('<I',saved,8)[0]==1,'Resume counted as a new expedition'
+ assert records(c.storage_bytes())['untouched.py']==b'print(42)\n'
+ stack=c.stack_used();recs=records(c.storage_bytes());recs['later.py']=b'x=123\n'
+ storage.write_bytes(b''.join(record(k,v) for k,v in recs.items())+b'\0\0')
+ c2=emu.Calculator(nwa,storage_file=str(storage),nwlink=a.nwlink);c2.enable_checks()
+ c2.keys=presses((500,'ok',70),(900,'ok',70),(1150,'left',160),(1450,'onoff',120));c2.run(1800);safe(c2)
+ recs=records(c2.storage_bytes());assert recs['later.py']==b'x=123\n' and recs['untouched.py']==b'print(42)\n'
+ assert struct.unpack_from('<I',recs['doodlejump.sav'],8)[0]==1
+ for direction,wall in [('left',18),('right',270)]:
+ edge_storage=OUT/(name+'-'+direction+'-storage.bin')
+ edge_storage.write_bytes(record('doodlejump.sav',(OUT/'edge-save.bin').read_bytes())+b'\0\0')
+ edge=emu.Calculator(nwa,storage_file=str(edge_storage),nwlink=a.nwlink);edge.enable_checks()
+ edge.keys=presses((500,'ok',70),(900,'ok',70),(1000,direction,1200),(2300,'home',100))
+ edge.run(980);last=struct.unpack_from('<i',state(edge))[0]
+ for t in range(1050,2151,50):
+ edge.run(t);xx=struct.unpack_from('<i',state(edge))[0]
+ assert 18*256<=xx<=270*256 and abs(xx-last)<24*256,'Player crossed a wall'
+ last=xx
+ assert last==wall*256 and struct.unpack_from('<i',state(edge),8)[0]==0
+ edge.save_png(str(OUT/(name+'-'+direction+'-wall.png')))
+ edge.run(2600);safe(edge);stack=max(stack,edge.stack_used())
+ report.append(dict(profile=name,stack=max(stack,c2.stack_used()),**perf))
+ print(name+': '+json.dumps(report[-1]),flush=True)
+ # A packed 16-platform/3-monster/3-shot rocket scene tests full redraws.
+ emu.configure('n0110','epsilon',148928);storage=OUT/'stress-storage.bin'
+ storage.write_bytes(record('keep.py',b'hello\n')+record('doodlejump.sav',(OUT/'stress-save.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',70),(900,'ok',70),(1250,'right',250),(1750,'up',70),(2300,'back',70),(2800,'home',100))
+ c.run(1400);c.save_png(str(OUT/'arm-rocket.png'));c.run(2200);stress=performance(c);c.run(3100);safe(c)
+ assert records(c.storage_bytes())['keep.py']==b'hello\n'
+ storage=OUT/'climb-storage.bin'
+ storage.write_bytes(record('doodlejump.sav',(OUT/'climb-save.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',70),(900,'ok',70),(1600,'back',70),(2100,'home',100))
+ c.run(1350);c.save_png(str(OUT/'arm-climb.png'));c.run(2400);safe(c)
+ # A read-only controller plays through ordinary held/released key events.
+ storage=OUT/'keyboard-climb-storage.bin'
+ storage.write_bytes(record('doodlejump.sav',(OUT/'start-save.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',70),(900,'ok',70));c.run(915)
+ last_fire=-16
+ for _ in range(5000):
+ g=state(c);tick=struct.unpack_from('<I',g,32)[0];peak=struct.unpack_from('<i',g,20)[0]//256-20
+ if peak>=1200 or g[46]==2:break
+ steer=steering(g)
+ if tick-last_fire>=16:last_fire=tick
+ fire=tick-last_fire<4
+ key=(emu.KEYS['left'] if steer<0 else emu.KEYS['right'] if steer>0 else 0)|(emu.KEYS['up'] if fire else 0)
+ c.keys=[(c.now_ms,c.now_ms+20,key)];c.run(c.now_ms+8)
+ c.save_png(str(OUT/'arm-keyboard-last.png'))
+ assert peak>=1200,(peak,tick,g[46],g[49])
+ c.save_png(str(OUT/'arm-keyboard-climb.png'));keyboard=performance(c)
+ keyboard.update(height=peak,ticks=tick,jumps=struct.unpack_from('<I',g,40)[0])
+ c.keys=[(c.now_ms,c.now_ms+150,emu.KEYS['home'])];c.run(c.now_ms+500);safe(c)
+ # Options persist even without starting a game.
+ emu.configure('n0120','epsilon',153676);storage=OUT/'journal-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),(1100,'ok',70),(1500,'back',70),(1750,'down',70),(2000,'ok',70),(2550,'back',70),(2900,'home',100))
+ c.run(1400);c.save_png(str(OUT/'arm-journal.png'));c.run(2400);c.save_png(str(OUT/'arm-guide.png'));c.run(3300);safe(c)
+ assert records(c.storage_bytes())['doodlejump.sav'][28]==0
+ 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((1400,'ok',70),(1800,'back',70));c.run(2200);safe(c);assert c.storage_bytes()[:len(full)]==full
+ (OUT/'arm-validation.json').write_text(json.dumps(dict(profiles=report,stress=stress,keyboard=keyboard),indent=2)+'\n')
+ print('PASS: four ARM profiles, held input, pause/cancel/resume, saves, full storage, rocket stress; '+json.dumps(stress),flush=True)
+
+if __name__=='__main__':
+ main()
diff --git a/games/doodlejump/tests/bounded-save.bin b/games/doodlejump/tests/bounded-save.bin
new file mode 100644
index 00000000..19a9fdc7
Binary files /dev/null and b/games/doodlejump/tests/bounded-save.bin differ
diff --git a/games/doodlejump/tests/legacy-save.bin b/games/doodlejump/tests/legacy-save.bin
new file mode 100644
index 00000000..5c218823
Binary files /dev/null and b/games/doodlejump/tests/legacy-save.bin differ
diff --git a/games/doodlejump/tests/test.c b/games/doodlejump/tests/test.c
new file mode 100644
index 00000000..056d48e3
--- /dev/null
+++ b/games/doodlejump/tests/test.c
@@ -0,0 +1,270 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "doodle.h"
+#include "render.h"
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+typedef char checked_layout[(offsetof(dj_game,shot)==272 && sizeof(dj_game)==308)?1:-1];
+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(dj_game *g,dj_stats *s) {
+ *s=(dj_stats){0};s->motion=1;dj_new(g,42);dj_start(g,s);assert(dj_valid(g,s));
+}
+static void landing(dj_game *g,dj_stats *s,unsigned type,unsigned item) {
+ setup(g,s);memset(g->platform,0,sizeof g->platform);
+ g->platform[0]=(dj_platform){20*DJ_Q,144,58,(uint8_t)type,(uint8_t)item,0,1};
+ g->y=g->peak=24*DJ_Q;g->vy=-1400;
+}
+static void collisions(void) {
+ dj_game g;dj_stats s;
+ landing(&g,&s,DJ_SOLID,0);dj_step(&g,&s,0);assert(g.y==20*DJ_Q&&g.vy==1440&&g.jumps==1&&s.jumps==1);
+ landing(&g,&s,DJ_SOLID,0);g.y=18*DJ_Q;g.vy=1000;dj_step(&g,&s,0);assert(g.jumps==0&&g.vy>0);
+ landing(&g,&s,DJ_BRITTLE,0);dj_step(&g,&s,0);assert(!g.platform[0].active&&g.vy<0&&g.jumps==0);
+ landing(&g,&s,DJ_FADING,0);dj_step(&g,&s,0);assert(!g.platform[0].active&&g.vy==1440);
+ landing(&g,&s,DJ_MOVING,0);g.platform[0].phase=32;dj_step(&g,&s,0);assert(g.vy==1440);
+ landing(&g,&s,DJ_SOLID,DJ_SPRING);dj_step(&g,&s,0);assert(g.vy==2432&&s.springs==1);
+ landing(&g,&s,DJ_SOLID,DJ_SPRING);g.x+=25*DJ_Q;dj_step(&g,&s,0);assert(g.vy==1440&&!s.springs);
+ landing(&g,&s,DJ_SOLID,DJ_ROCKET);dj_step(&g,&s,0);assert(g.boost==80&&s.rockets==1&&!g.platform[0].item);
+ landing(&g,&s,DJ_SOLID,DJ_ROCKET);g.enemy[0]=(dj_enemy){25*DJ_Q,144,32,1};
+ dj_step(&g,&s,0);assert(g.boost==80&&g.phase==DJ_RUNNING&&!g.enemy[0].active);
+ setup(&g,&s);g.x=DJ_LEFT*DJ_Q+16;g.vx=-672;dj_step(&g,&s,-1);assert(g.x==DJ_LEFT*DJ_Q&&!g.vx);
+ dj_step(&g,&s,1);assert(g.x>DJ_LEFT*DJ_Q&&g.vx>0);
+ g.x=DJ_RIGHT*DJ_Q-16;g.vx=672;dj_step(&g,&s,1);assert(g.x==DJ_RIGHT*DJ_Q&&!g.vx);
+ dj_step(&g,&s,-1);assert(g.x<DJ_RIGHT*DJ_Q&&g.vx<0);
+ /* A platform across the old seam cannot catch the player anymore. */
+ landing(&g,&s,DJ_SOLID,0);g.x=DJ_LEFT*DJ_Q;g.platform[0].x=DJ_WIDTH-1;
+ dj_step(&g,&s,0);assert(!g.jumps&&g.vy<0);
+ setup(&g,&s);g.enemy[0]=(dj_enemy){50*DJ_Q,144,32,1};assert(dj_fire(&g));assert(!dj_fire(&g));
+ dj_step(&g,&s,0);assert(!g.enemy[0].active&&s.monsters==1);
+ setup(&g,&s);g.y=g.peak=35*DJ_Q;g.vy=-2304;g.enemy[0]=(dj_enemy){20*DJ_Q,144,32,1};
+ dj_step(&g,&s,0);assert(!g.enemy[0].active&&g.vy==1690&&g.phase==DJ_RUNNING);
+ setup(&g,&s);g.enemy[0]=(dj_enemy){25*DJ_Q,144,32,1};dj_step(&g,&s,0);assert(g.phase==DJ_OVER&&g.reason==DJ_HIT);
+ setup(&g,&s);g.boost=1;g.enemy[0]=(dj_enemy){25*DJ_Q,144,32,1};dj_step(&g,&s,0);
+ assert(g.phase==DJ_RUNNING&&!g.enemy[0].active&&!g.boost);
+ setup(&g,&s);g.y=-23*DJ_Q;g.vy=-2304;dj_step(&g,&s,0);assert(g.phase==DJ_OVER&&g.reason==DJ_FELL);
+ dj_game frozen=g;dj_stats record=s;dj_step(&g,&s,1);assert(!memcmp(&g,&frozen,sizeof g)&&!memcmp(&s,&record,sizeof s));
+}
+static int delta(int target,int x) {
+ return target-x;
+}
+static int controller(const dj_game *g) {
+ int best=-1,best_y=-1,ticks=0;
+ if(g->vy>0&&!g->boost)for(unsigned i=0;i<DJ_ENEMIES;++i) {
+ const dj_enemy *e=&g->enemy[i];int dy=e->y-g->y;
+ int dx=delta(dj_enemy_x(e,g->tick),g->x);
+ if(e->active&&dy>-15*DJ_Q&&dy<80*DJ_Q&&abs(dx)<30*DJ_Q) {
+ int avoid=dx>=0?-1:1;
+ if((avoid<0&&g->x<(DJ_LEFT+28)*DJ_Q)||(avoid>0&&g->x>(DJ_RIGHT-28)*DJ_Q))return 0;
+ return avoid;
+ }
+ }
+ for(unsigned i=0;i<DJ_PLATFORMS;++i) {
+ const dj_platform *p=&g->platform[i];if(!p->active||p->type==DJ_BRITTLE||p->y<g->camera-12*DJ_Q)continue;
+ int y=g->y,v=g->vy,boost=g->boost;
+ for(int t=1;t<200;++t) {
+ int old=y;if(boost)--boost,v=1536;else v-=47;
+ if(v<-2304)v=-2304;
+ y+=v;
+ if(v<0&&old>=p->y&&y<=p->y) {
+ int dx=delta(dj_platform_x(p,g->tick+(unsigned)t),g->x);
+ if(abs(dx)<(t>7?(t-7)*672:0)+((int)p->width/2+5)*DJ_Q&&p->y>best_y)
+ best=(int)i,best_y=p->y,ticks=t;
+ break;
+ }
+ if(y<g->camera-24*DJ_Q)break;
+ }
+ }
+ if(best<0)return 0;
+ int aim=dj_platform_x(&g->platform[best],g->tick+(unsigned)ticks);
+ int dx=delta(aim,g->x+g->vx*3);
+ return abs(dx)<3*DJ_Q?0:dx>0?1:-1;
+}
+static void saves(void) {
+ dj_game g,a;dj_stats s,b;setup(&g,&s);
+ uint8_t raw[DJ_SAVE_BYTES],again[DJ_SAVE_BYTES];
+ dj_encode(&g,&s,raw);assert(dj_decode(&a,&b,raw,sizeof raw));dj_encode(&a,&b,again);assert(!memcmp(raw,again,sizeof raw));
+ for(unsigned i=0;i<sizeof raw;++i) {
+ raw[i]^=1;dj_game before=a;dj_stats previous=b;
+ assert(!dj_decode(&a,&b,raw,sizeof raw));assert(!memcmp(&a,&before,sizeof a)&&!memcmp(&b,&previous,sizeof b));raw[i]^=1;
+ }
+ assert(!dj_decode(&a,&b,NULL,0)&&!dj_decode(&a,&b,raw,sizeof raw-1));
+ g.vx=INT32_MAX;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.camera=INT32_MAX;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.platform[0].width=255;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.enemy[0].active=2;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.route_phase=128;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.route_phase=7;dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ setup(&g,&s);g.shot[0]=(dj_shot){INT32_MIN,1,1};dj_encode(&g,&s,raw);assert(!dj_decode(&a,&b,raw,sizeof raw));
+ landing(&g,&s,DJ_SOLID,0);s.jumps=UINT32_MAX;dj_step(&g,&s,0);assert(s.jumps==UINT32_MAX);
+ FILE *legacy=fopen("../tests/legacy-save.bin","rb");assert(legacy);
+ assert(fread(raw,1,sizeof raw,legacy)==sizeof raw);fclose(legacy);
+ assert(dj_decode(&g,&s,raw,sizeof raw)&&!g.route_phase);
+ dj_encode(&g,&s,again);assert(!memcmp(again,"DJN3",4));
+ assert(dj_decode(&a,&b,again,sizeof again)&&!memcmp(&g,&a,sizeof g)&&!memcmp(&s,&b,sizeof s));
+ uint32_t runs=s.runs,best=s.best;
+ for(unsigned i=0;i<120;++i){g.boost=80;dj_step(&g,&s,0);assert(dj_valid(&g,&s));}
+ assert(g.route_phase>0&&g.route_phase<=127&&s.runs==runs&&s.best>=best);
+ legacy=fopen("../tests/wrapping-save.bin","rb");assert(legacy);
+ assert(fread(raw,1,sizeof raw,legacy)==sizeof raw);fclose(legacy);
+ assert(!memcmp(raw,"DJN1",4)&&dj_decode(&g,&s,raw,sizeof raw));
+ assert(g.x>=DJ_LEFT*DJ_Q&&g.x<=DJ_RIGHT*DJ_Q);
+ dj_encode(&g,&s,again);assert(!memcmp(raw+4,again+4,25)); /* Lifetime records. */
+ assert(!memcmp(raw+36,again+36,4)&&!memcmp(raw+48,again+48,8)); /* Height/camera/peak. */
+ legacy=fopen("../tests/bounded-save.bin","rb");assert(legacy);
+ assert(fread(raw,1,sizeof raw,legacy)==sizeof raw);fclose(legacy);
+ assert(!memcmp(raw,"DJN2",4)&&dj_decode(&g,&s,raw,sizeof raw)&&!g.route_phase);
+ dj_encode(&g,&s,again);
+ assert(!memcmp(raw+4,again+4,82)&&!memcmp(raw+87,again+87,DJ_SAVE_BYTES-91));
+ setup(&g,&s);dj_new(&g,1);dj_start(&g,&s);a=g;b=s;
+ for(unsigned i=0;i<1200;++i) {
+ int steer=controller(&g);
+ if(i%16==0){dj_fire(&g);dj_fire(&a);}
+ dj_step(&g,&s,steer);dj_step(&a,&b,steer);
+ if(i%37==0) {
+ dj_encode(&g,&s,raw);dj_encode(&a,&b,again);assert(!memcmp(raw,again,sizeof raw));
+ assert(dj_decode(&a,&b,raw,sizeof raw));
+ }
+ }
+}
+static void distribution(void) {
+ unsigned samples=0,all_counts[6]={0},all_turns=0;
+ for(unsigned seed=1;seed<=120;++seed) {
+ dj_game g;dj_stats s;setup(&g,&s);dj_new(&g,seed);dj_start(&g,&s);
+ unsigned counts[6]={0},n=0,streak=0,side=2,short_hops=0,long_hops=0,turns=0,runs=0;
+ int previous=g.route_x,last_direction=0;
+ for(unsigned tick=0;n<240&&tick<4000;++tick) {
+ uint32_t rows=g.rows;g.boost=80;dj_step(&g,&s,0);assert(dj_valid(&g,&s));
+ if(g.rows==rows)continue;
+ assert(g.rows==rows+1);
+ int hop=g.route_x-previous;assert(abs(hop)<=68);
+ assert(g.route_x>=24&&g.route_x<=264);
+ if(abs(hop)<16)++short_hops;
+ if(abs(hop)>=48)++long_hops;
+ int direction=hop>0?1:hop<0?-1:0;
+ if(direction&&last_direction) {
+ if(direction!=last_direction&&previous>68&&previous<220)++turns;
+ if(direction==last_direction)++runs;
+ }
+ if(direction)last_direction=direction;
+ previous=g.route_x;
+ unsigned band=g.route_x/48;assert(band<6);++counts[band];
+ unsigned now=band/3;streak=now==side?streak+1:1;side=now;assert(streak<=6);
+ assert(g.x>=DJ_LEFT*DJ_Q&&g.x<=DJ_RIGHT*DJ_Q);
+ for(unsigned i=0;i<DJ_PLATFORMS;++i)if(g.platform[i].active) {
+ const dj_platform *p=&g.platform[i];int x=dj_platform_x(p,g.tick),half=(p->width+1)/2;
+ assert(x>=half*DJ_Q&&x<=(DJ_WIDTH-half)*DJ_Q);
+ }
+ ++n;
+ }
+ assert(n==240&&short_hops>0&&long_hops>0&&turns>10&&runs>10);
+ unsigned left=counts[0]+counts[1]+counts[2];assert(left>70&&left<170);
+ for(unsigned i=0;i<6;++i){if(i>0&&i<5)assert(counts[i]>0);all_counts[i]+=counts[i];}
+ samples+=n;all_turns+=turns;
+ }
+ for(unsigned i=0;i<6;++i)assert(all_counts[i]>100);
+ printf("Random generation: %u ledges, direct hops <=68 px, half streak <=6; %u interior turns\n",samples,all_turns);
+ printf("Zone counts: %u / %u / %u / %u / %u / %u\n",all_counts[0],all_counts[1],all_counts[2],all_counts[3],all_counts[4],all_counts[5]);
+}
+static void long_runs(void) {
+ uint32_t successes=0,highest=0;unsigned observed=0,falls=0,hits=0;
+ FILE *trace=fopen("climb-input.bin","wb");assert(trace);
+ for(unsigned seed=1;seed<=80;++seed) {
+ dj_game g;dj_stats s;setup(&g,&s);dj_new(&g,seed);
+ if(seed==1) {
+ uint8_t initial[DJ_SAVE_BYTES];dj_encode(&g,&s,initial);
+ FILE *f=fopen("start-save.bin","wb");assert(f);fwrite(initial,1,sizeof initial,f);fclose(f);
+ }
+ dj_start(&g,&s);
+ for(unsigned n=0;n<30000&&g.phase==DJ_RUNNING&&dj_height(&g)<6000;++n) {
+ int steer=controller(&g);bool fire=n%16==0;
+ if(seed==1){fputc(steer+1,trace);fputc(fire,trace);}
+ if(fire)dj_fire(&g);
+ dj_step(&g,&s,steer);assert(dj_valid(&g,&s));
+ if(n%97==0) {
+ uint8_t raw[DJ_SAVE_BYTES];dj_game a;dj_stats b;dj_encode(&g,&s,raw);assert(dj_decode(&a,&b,raw,sizeof raw));
+ }
+ for(unsigned i=0;i<DJ_PLATFORMS;++i)if(g.platform[i].active)observed|=1u<<g.platform[i].type;
+ if(seed==1&&dj_height(&g)>1100&&dj_height(&g)<1200) {
+ uint8_t raw[DJ_SAVE_BYTES];dj_encode(&g,&s,raw);FILE *f=fopen("climb-save.bin","wb");assert(f);fwrite(raw,1,sizeof raw,f);fclose(f);
+ }
+ }
+ if(dj_height(&g)>=6000)++successes;
+ else if(g.reason==DJ_HIT)++hits;
+ else ++falls;
+ if(dj_height(&g)>highest)highest=dj_height(&g);
+ if(seed==1)printf("Reference: %u height, %u bounces, %u springs, %u rockets, %u monsters\n",(unsigned)dj_height(&g),(unsigned)s.jumps,(unsigned)s.springs,(unsigned)s.rockets,(unsigned)s.monsters);
+ }
+ fclose(trace);
+ dj_game fixture;dj_stats book;setup(&fixture,&book);
+ fixture.camera=900*DJ_Q;fixture.y=fixture.peak=1024*DJ_Q;fixture.next_y=1160*DJ_Q;fixture.boost=70;
+ for(unsigned i=0;i<DJ_PLATFORMS;++i)fixture.platform[i]=(dj_platform){(int32_t)(914+i*12)*DJ_Q,(uint16_t)(30+i*15),43,(uint8_t)(i%4),(uint8_t)(i%3),0,1};
+ for(unsigned i=0;i<DJ_ENEMIES;++i)fixture.enemy[i]=(dj_enemy){(int32_t)(950+i*50)*DJ_Q,(uint16_t)(40+i*90),32,1};
+ for(unsigned i=0;i<DJ_SHOTS;++i)fixture.shot[i]=(dj_shot){(int32_t)(45+i*70)*DJ_Q,(int32_t)(940+i*60)*DJ_Q,1};
+ assert(dj_valid(&fixture,&book));uint8_t data[DJ_SAVE_BYTES];dj_encode(&fixture,&book,data);
+ FILE *stress=fopen("stress-save.bin","wb");assert(stress);fwrite(data,1,sizeof data,stress);fclose(stress);
+ printf("Controller: %u/80 reached 6000; highest %u; platform kinds %u\n",(unsigned)successes,(unsigned)highest,observed);
+ printf("Other runs: %u monster contacts, %u falls\n",hits,falls);
+ /* The controller can lose a run; require broad successful play through
+ * the new random layouts, alongside the separate route invariants. */
+ assert(successes>=70&&highest>=6000&&observed==15);
+ dj_game g;dj_stats s;setup(&g,&s);uint32_t r=0x124578u;
+ for(unsigned i=0;i<120000;++i) {
+ if(g.phase==DJ_OVER)dj_new(&g,r),dj_start(&g,&s);
+ r^=r<<13;r^=r>>17;r^=r<<5;
+ if(r%31==0)dj_fire(&g);
+ dj_step(&g,&s,(int)(r%3)-1);assert(dj_valid(&g,&s));
+ }
+}
+static void walls(void) {
+ dj_game g;dj_stats s;setup(&g,&s);g.boost=80;
+ uint8_t raw[DJ_SAVE_BYTES];dj_encode(&g,&s,raw);
+ FILE *f=fopen("edge-save.bin","wb");assert(f);fwrite(raw,1,sizeof raw,f);fclose(f);
+ for(int side=-1;side<=1;side+=2) {
+ setup(&g,&s);g.boost=80;
+ for(unsigned i=0;i<72;++i) {
+ int32_t before=g.x;dj_step(&g,&s,side);
+ assert(g.x>=DJ_LEFT*DJ_Q&&g.x<=DJ_RIGHT*DJ_Q&&abs(g.x-before)<=672);
+ }
+ assert(g.x==(side<0?DJ_LEFT:DJ_RIGHT)*DJ_Q&&!g.vx);
+ dj_step(&g,&s,-side);assert(side<0?g.vx>0:g.vx<0);
+ }
+ puts("PASS: bounded movement, sustained wall contact and immediate reversal");
+}
+static void rendering(void) {
+ dj_game g;dj_stats s;setup(&g,&s);
+ g.x=DJ_LEFT*DJ_Q;g.vx=-600;
+ g.platform[1]=(dj_platform){62*DJ_Q,30,58,DJ_MOVING,DJ_SPRING,0,1};
+ g.enemy[0]=(dj_enemy){140*DJ_Q,1,32,1};g.boost=12;
+ for(unsigned view=0;view<=DJ_SAVE_ERROR;++view) {
+ dj_invalidate();dj_render(&g,&s,view,0,0,false,push);
+ if(view==DJ_TITLE)shot("title.ppm");
+ if(view==DJ_GUIDE)shot("guide.ppm");
+ if(view==DJ_JOURNAL)shot("journal.ppm");
+ for(unsigned frame=1;frame<=36;++frame) {
+ if(view==DJ_PLAY){int steer=controller(&g);dj_step(&g,&s,steer);}
+ dj_render(&g,&s,view,0,frame*64,false,push);memcpy(reference,screen,sizeof screen);
+ dj_invalidate();dj_render(&g,&s,view,0,frame*64,false,push);assert(!memcmp(screen,reference,sizeof screen));
+ }
+ unsigned before=pushes;dj_render(&g,&s,view,0,36*64,false,push);assert(pushes==before);
+ }
+ uint8_t data[DJ_SAVE_BYTES];FILE *f=fopen("climb-save.bin","rb");assert(f);assert(fread(data,1,sizeof data,f)==sizeof data);fclose(f);
+ assert(dj_decode(&g,&s,data,sizeof data));
+ dj_invalidate();dj_render(&g,&s,DJ_PLAY,0,0,false,push);shot("gameplay.ppm");
+}
+int main(void) {
+ collisions();walls();saves();distribution();long_runs();rendering();puts("PASS: collisions, saves, distribution, generated courses, stress, partial/full rendering");return 0;
+}
diff --git a/games/doodlejump/tests/test_compact_nwa.py b/games/doodlejump/tests/test_compact_nwa.py
new file mode 100644
index 00000000..4874fac7
--- /dev/null
+++ b/games/doodlejump/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/doodlejump/tests/wrapping-save.bin b/games/doodlejump/tests/wrapping-save.bin
new file mode 100644
index 00000000..27c76795
Binary files /dev/null and b/games/doodlejump/tests/wrapping-save.bin differ
diff --git a/games/doodlejump/tools/build.py b/games/doodlejump/tools/build.py
new file mode 100644
index 00000000..8a937ddd
--- /dev/null
+++ b/games/doodlejump/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 / 'doodlejump-debug.nwa',
+ '--ld', tool('ld'))
+ run(sys.executable, packer, 'release', out / 'doodlejump-debug.nwa',
+ out / 'DoodleJump.nwa', '--objcopy', tool('objcopy'))
+ if os.name != 'nt':
+ shutil.copyfile(out / 'DoodleJump.nwa', out / 'doodlejump.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 / 'DoodleJump.nwa', elf, *options)
+ run(*nw, 'nwa-bin', out / 'DoodleJump.nwa', binary, *options)
+ debug_binary = out / (name + '-debug.bin')
+ run(*nw, 'nwa-bin', out / 'doodlejump-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 / 'DoodleJump.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/doodlejump/tools/compact_nwa.py b/games/doodlejump/tools/compact_nwa.py
new file mode 100644
index 00000000..f320bb54
--- /dev/null
+++ b/games/doodlejump/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/doodlejump/tools/icon.py b/games/doodlejump/tools/icon.py
new file mode 100644
index 00000000..a1ee1a78
--- /dev/null
+++ b/games/doodlejump/tools/icon.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+"""Original flat-colour notebook icon: small both as PNG and as an NWI."""
+from pathlib import Path
+from PIL import Image, ImageDraw
+im=Image.new('RGB',(55,56),'#faf4dd');d=ImageDraw.Draw(im)
+for y in range(5,56,7):d.line((0,y,54,y),fill='#dbe5d8')
+for x in range(9,55,7):d.line((x,0,x,55),fill='#dbe5d8')
+d.rectangle((0,0,6,55),fill='#e6e1c9');d.line((10,0,10,55),fill='#c76a55')
+ink='#294853';green='#8dbd69'
+for y in (10,26,42):d.ellipse((3,y-2,7,y+2),fill=ink);d.line((0,y-2,6,y-2),fill=ink)
+d.rectangle((16,45,48,49),fill=ink);d.rectangle((17,46,47,48),fill=green)
+d.ellipse((20,12,42,34),fill=ink);d.ellipse((21,13,41,33),fill=green)
+d.rectangle((20,22,42,35),fill=ink);d.rectangle((21,21,41,34),fill=green)
+d.rectangle((16,23,21,35),fill=ink);d.rectangle((17,24,19,33),fill='#71a6b5')
+d.rectangle((39,22,49,28),fill=ink);d.rectangle((40,23,48,27),fill=green)
+for x in (29,35):d.rectangle((x,17,x+3,22),fill='#fffbef');d.rectangle((x+2,20,x+2,22),fill=ink)
+d.line((25,35,24,42),fill=ink);d.line((36,35,39,42),fill=ink)
+d.line((21,42,27,42),fill=ink);d.line((36,42,43,42),fill=ink)
+im.save(Path(__file__).resolve().parents[1]/'src/icon.png',optimize=True)
diff --git a/games/doodlejump/tools/standalone.ld b/games/doodlejump/tools/standalone.ld
new file mode 100644
index 00000000..28679582
--- /dev/null
+++ b/games/doodlejump/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) }
+}