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 Suika Game by Bobydeluxe

Bobydeluxef9f8cf91f181
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 89966b26..c5e1d09d 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -55,6 +55,8 @@ jobs:
make -C games/numblocks host test
make -C games/championisland host test
make -C games/undertale host test
+ make -C games/suika test
+ python3 tests/test_suika.py build/apps/SuikaGame.nwa
- uses: actions/upload-artifact@v4
with:
diff --git a/Makefile b/Makefile
index dc8e38ce..db4400b5 100644
--- a/Makefile
+++ b/Makefile
@@ -31,7 +31,7 @@ APP_SPACE = 2031616
# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)
UPSILON_RAM = 107674
UPSILON_GAMES = crossyroad blockblast portal tetris dinorun chess flappybird pacman snake connectfour solitaire g2048 minesweeper \
- breakout numvisuals
+ breakout suika numvisuals
# NumPlay and its discreet versions: the same app, with another name and icon
# on the calculator's home screen. Each one is a release file.
diff --git a/README.md b/README.md
index 67eeae81..d4242de0 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
<h1 align="center">NumPlay</h1>
<p align="center">
- <b>19 free games for your NumWorks calculator, in one app.</b><br>
+ <b>20 free games for your NumWorks calculator, in one app.</b><br>
Plus five big games that install on their own. For the N0110, N0115 and N0120, in English, French and Chinese.
</p>
@@ -61,12 +61,17 @@ All of these come in one app, **NumPlay.nwa**.
<td align="center"><a href="games/g2048/README.md"><img src="docs/media/thumb_g2048.png" width="120" alt="2048"><br><b>2048</b></a></td>
<td align="center"><a href="games/minesweeper/README.md"><img src="docs/media/thumb_minesweeper.png" width="120" alt="Minesweeper"><br><b>Minesweeper</b></a></td>
<td align="center"><a href="games/breakout/README.md"><img src="docs/media/thumb_breakout.png" width="120" alt="Block Breaker"><br><b>Block Breaker</b></a></td>
+ <td align="center"><a href="games/suika/README.md"><img src="docs/media/thumb_suika.png" width="120" alt="Suika Game"><br><b>Suika Game</b></a></td>
+ </tr>
+ <tr>
<td align="center"><a href="games/numvisuals/README.md"><img src="docs/media/thumb_numvisuals.png" width="120" alt="NumVisuals"><br><b>NumVisuals</b></a></td>
</tr>
</table>
Want just one game? Each one also comes as its own file on the [downloads page](https://github.com/Mason363/NumPlay/releases/latest).
+Suika Game stays in English in every build.
+
## Big games, installed on their own
These are too big to fit next to NumPlay, so each one is its own app. Install it without NumPlay.
@@ -108,7 +113,7 @@ You need your calculator, its USB cable, and a computer with **Google Chrome** o
| --- | --- | --- |
| N0120 | Epsilon 23.2 or newer (the calculator's own software) | Everything |
| N0110, N0115 | Epsilon 23.2 or newer | Everything. These models are about 2.5 times slower, so the big games show fewer frames per second, but they keep their speed. |
-| N0110, N0115 | Upsilon | NumPlay-Upsilon.nwa: 15 games (see Other versions) |
+| N0110, N0115 | Upsilon | NumPlay-Upsilon.nwa: 16 games (see Other versions) |
| Any | Custom software built from Epsilon 25.2's source | Everything. These builds can give apps less memory (133 KB): on one that gives even less, a game that needs more says how much on its card. |
To see your calculator's model and software, open **Settings**, then **About**. To update the software, go to [my.numworks.com](https://my.numworks.com) with the calculator plugged in.
@@ -124,7 +129,7 @@ To see your calculator's model and software, open **Settings**, then **About**.
| [NumPlay-Matrices.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay-Matrices.nwa) | The same app, in disguise: it looks like a math app called **Matrices**. |
| [NumPlay-French.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay-French.nwa) | NumPlay en français : tous les jeux, en français. |
| [NumPlay-Chinese.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay-Chinese.nwa) | NumPlay 中文版:所有游戏,简体中文。 |
-| [NumPlay-Upsilon.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay-Upsilon.nwa) | For calculators running **Upsilon**: the 15 games that fit in the memory it gives apps. |
+| [NumPlay-Upsilon.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay-Upsilon.nwa) | For calculators running **Upsilon**: the 16 games that fit in the memory it gives apps. |
<img src="docs/media/home_invisible.png" width="240" alt="The home screen with NumPlay-Invisible: the spot after Settings looks empty"> <img src="docs/media/home_matrices.png" width="240" alt="The home screen with NumPlay-Matrices among the calculator's own apps">
@@ -198,6 +203,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 **[Suika Game](games/suika/README.md)** for NumPlay, including its English interface, procedural fruit artwork and fruit-merging engine. Inspired by Suika Game; not affiliated with Aladdin X.
- **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/docs/media/thumb_suika.png b/docs/media/thumb_suika.png
new file mode 100644
index 00000000..53c06287
Binary files /dev/null and b/docs/media/thumb_suika.png differ
diff --git a/docs/play.md b/docs/play.md
index fe008a94..c84b5acf 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -20,6 +20,24 @@ Your progress is also copied into a Python script, `numplay_saves.py`, so updati
In every game, **Back** pauses, and the pause menu has a small **Quit game** button. It always asks first, since Back sits right next to OK.
+## Suika Game
+
+![Suika Game](../games/suika/docs/shot.png)
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** | Move the cloud |
+| **OK / EXE** | Drop one fruit |
+| **Back** | Pause / resume |
+| **Home / On-Off** | Save and leave |
+
+Merge matching fruit to reach the watermelon. Only the next fruit is shown;
+each new fruit is an independent draw from the five smallest kinds. There is
+no reserve, placement hint or combo bonus. The red rim warns when the pile
+needs to settle. Pause freezes physics; **New game** asks before replacing a
+run. **Title screen**, then **Back**, returns to NumPlay with the run saved.
+English-only. [More details](../games/suika/README.md).
+
## NumDash
<img src="media/numdash.gif" width="320" align="right" alt="NumDash gameplay: Stereo Madness">
diff --git a/games/games.json b/games/games.json
index 46baffab..d69c14b7 100644
--- a/games/games.json
+++ b/games/games.json
@@ -361,6 +361,19 @@
"app": "BlockBreaker.nwa",
"repo": "https://github.com/Mason363/NumPlay/tree/main/games/breakout"
},
+ {
+ "id": "suika",
+ "title": "Suika Game",
+ "tagline": "A little fruit. A big merge.",
+ "credit": "Game made by Bobydeluxe",
+ "top": "0xD8D9A6",
+ "bottom": "0x36563C",
+ "accent": "0xF5AD69",
+ "records": ["suika.sav"],
+ "shots": ["docs/shot.png"],
+ "app": "SuikaGame.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/suika"
+ },
{
"id": "numvisuals",
"title": "NumVisuals",
diff --git a/games/suika/.gitignore b/games/suika/.gitignore
new file mode 100644
index 00000000..16be8f21
--- /dev/null
+++ b/games/suika/.gitignore
@@ -0,0 +1 @@
+/output/
diff --git a/games/suika/Makefile b/games/suika/Makefile
new file mode 100644
index 00000000..a1678f67
--- /dev/null
+++ b/games/suika/Makefile
@@ -0,0 +1,51 @@
+# Suika: 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/suika.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/suika-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/suika.nwa: output/suika-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/suika.nwa output/suika.bin --ram-length 107674
+ $(NWLINK) nwa-bin output/suika-debug.nwa output/suika-debug.bin --ram-length 107674
+ $(PYTHON) -c "from pathlib import Path; assert Path('output/suika.bin').read_bytes() == Path('output/suika-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_suika_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_suika_main -o output/sim-module.o
+clean:
+ rm -rf output
diff --git a/games/suika/README.md b/games/suika/README.md
new file mode 100644
index 00000000..224353ba
--- /dev/null
+++ b/games/suika/README.md
@@ -0,0 +1,89 @@
+# Suika Game
+
+An English-only fruit-merging game for NumWorks, rebuilt for NumPlay.
+Match two identical fruits to grow the next one, from cherry to watermelon.
+Each merge awards its base value: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 or 66
+points. Two watermelons clear each other. There are no combo bonuses.
+
+**Game made by [Bobydeluxe](https://github.com/Bobydeluxe).**
+
+![The fruit basket](docs/shot.png)
+![Title screen](docs/title.png)
+
+| Key | Action |
+| --- | --- |
+| Left / Right | Move the cloud |
+| OK / EXE | Drop one fruit (holding does not repeat) |
+| Back | Pause / resume |
+| Home / On-Off | Save and leave |
+
+Only the next fruit is shown. The cloud holds the fruit ready to drop. Each
+new fruit is an independent, equally weighted draw from cherry, strawberry,
+grape, dekopon and persimmon. Repeats and streaks are possible. There is no
+reserve, three-fruit queue, bag, position suggestion or landing guide.
+
+The warm checked background, glass box, cloud, score/Next bubbles, evolution
+circle, fruit proportions, colours and expressions are adapted at 320 x 240
+from the classic skin shown in the [official screenshots](https://www.nintendo.com/us/store/products/suika-game-switch/).
+Fruit radii are 5, 7, 9, 11, 14, 17, 20, 25, 28, 31 and 40 calculator pixels;
+this is a small-screen procedural interpretation, not the original sprites.
+
+Newly dropped fruit has time to fall before counting toward overflow. A mature
+fruit protruding above the box triggers a red rim warning. It has 180 simulation
+ticks (2.88 seconds) to settle or merge; clearing the rim resets the timer.
+The 48-body pool blocks overlapping or excess drops while the pile settles.
+
+Pause freezes simulation. **New game** asks before discarding a run and keeps
+the record. **Title screen** leaves the run available under **Continue**.
+Back on the title returns to NumPlay.
+
+## Memory and saves
+
+No heap or full-screen framebuffer. Fruit, faces and scenery are drawn with
+code. Only dirty regions are composed, at most eight rows at a time (5120
+bytes). Physics uses two substeps and six contact passes per 16 ms tick;
+drawing runs at up to 31.25 Hz with bounded simulation catch-up.
+
+The fixed 608-byte `suika.sav` payload now uses version `SKA2`. It preserves
+the run, best score, random generator, current fruit, single next fruit and
+danger timer. Existing NumPlay `SKA1` saves are imported: scores and fruit
+ranks remain, positions are scaled/clamped to the new box, and removed
+reserve/queue/combo state is discarded. The pile settles under the updated
+geometry on resuming. Historical scores are kept as earned. A save written
+by this update cannot be loaded by the previous app. NumGames `.nwa` saves
+are not imported.
+
+Length, checksum and field validation finish before loading live state.
+Writes occur on pause, game over, exit and every five seconds while playing,
+skipping identical payloads. Save failures offer retry, return to play or
+explicit exit without saving. The existing NumPlay backup/reset/uninstall
+mechanisms cover the same registered save record.
+
+## Build and check
+
+With ARM GCC, nwlink 1.0.0 and Python/pyelftools available:
+
+```sh
+make -C games/suika build check NWLINK=nwlink
+make -C games/suika test
+python tests/test_suika.py games/suika/output/suika-debug.nwa --nwlink nwlink
+```
+
+The host suite must run before the ARM scenarios to generate the scene fixture.
+The release output is `games/suika/output/suika.nwa`. The root build copies it
+to `build/apps/SuikaGame.nwa` and includes the separate module in NumPlay.
+The portable standalone build also works on Windows:
+
+```sh
+python games/suika/tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink
+```
+
+It writes `output/SuikaGame.nwa` and four-profile size/link reports. Standalone
+packing uses the game-local lossless NWA/icon packer, with no extra runtime memory.
+The debug and release files must produce identical installed bytes on all
+profiles. The build enforces 12 KiB static RAM and 64 KiB installed flash limits.
+Pillow is needed to regenerate the icon with `tools/icon.py`.
+
+See [validation](VALIDATION.md) for measured results. Code and procedural
+artwork are under the repository's GPL-3.0 licence. Inspired by Suika Game;
+not affiliated with Aladdin X. No original game's artwork or binary is included.
diff --git a/games/suika/VALIDATION.md b/games/suika/VALIDATION.md
new file mode 100644
index 00000000..43b40924
--- /dev/null
+++ b/games/suika/VALIDATION.md
@@ -0,0 +1,54 @@
+# Validation
+
+Local classic-style update, 2026-10-20. ARM GCC 15.2.1, nwlink 1.0.0.
+
+| Metric | Previous app | Updated app |
+| --- | ---: | ---: |
+| Standalone `.nwa` | 31,324 bytes | 20,880 bytes |
+| Installed flash | 17,520 bytes | 15,600 bytes |
+| Static RAM (`.data` + `.bss`) | 7,245 bytes | 7,225 bytes |
+| ARM stack high-water mark in tested scenarios | 372 bytes | 376 bytes |
+| Save payload | 608 bytes | 608 bytes |
+
+File size decreases by 33.3%; installed flash decreases by 11.0%. The update
+removes reserve/queue/hint/combo logic and uses a game-local lossless packer.
+Packing alone adds no runtime memory or decoding work. The updated visuals,
+geometry and random rules are intentional gameplay changes. Save-record
+headers/name overhead is additional to the payload above.
+
+- Host C suite: 28,800 physics ticks across 12 seeds, save round trips every
+ 17 ticks, every single-byte save corruption, invalid-but-checksummed payload,
+ coincident contacts, watermelon clearing, overflow/recovery, blocked spawn
+ and base-only consecutive merge scoring. A 100,000-drop deterministic
+ generator test checks all five ranks, approximate frequency balance and
+ repeated streaks. Old `SKA1` fixture import and stable `SKA2` round trips pass.
+- Dirty and full rendering match pixel-for-pixel over 120 changing frames,
+ with additional edge/cloud/cooldown, five next-fruit and maximum-score cases.
+ No display call exceeds the 320 x 8-pixel staging buffer.
+- Actual ARM application: pause freezes simulation; resuming does not catch
+ up paused time. Save/reload, Home/On-Off exit, cleared app RAM, unrelated
+ file preservation and balanced Home locking pass on N0110/Epsilon,
+ N0115 custom (133,652 bytes), N0120/Epsilon and Upsilon (107,674 bytes).
+- Dense 48-fruit ARM basket: 76 presentation cycles over 2.5 simulated seconds,
+ maximum instrumented draw time 9 ms and no draws over 32 ms. This uses the
+ repository emulator's timing model; it is not a physical-device FPS test.
+- Full storage: failed exit remains visible, allows returning to play and
+ explicit unsaved exit, and leaves the existing file intact.
+- ARM legacy import preserves score, best, RNG, ranks, current and next;
+ removed reserve/queue/combo bytes are zeroed when writing `SKA2`.
+ Gameplay keys 1/2 leave the dropper and preview unchanged.
+- Release/debug NWA files install identical bytes on all four profiles.
+- Repository `test_games.py --game suika` passes both release-app sessions,
+ including a file inserted after the first save.
+- Real launcher/module integration, filtered to Suika: module relocation,
+ generated game table and screenshots compile and link at 107,674 / 133,652 /
+ 148,928 bytes of RAM. Two ARM launcher sessions pass launch/save/reload,
+ preserve unrelated files, write `numplay_saves.py`, clear app RAM and exit
+ safely. Launcher stack high-water mark: 984 bytes. A fresh catalogue capture
+ confirms the Suika card and Bobydeluxe credit.
+- Captures in `docs/shot.png`, `docs/title.png` and `docs/menu.png` come from
+ the actual ARM app/launcher.
+
+
+The complete all-game/translated NumPlay builds and physical NumWorks
+testing have not been repeated for this revision.
diff --git a/games/suika/docs/menu.png b/games/suika/docs/menu.png
new file mode 100644
index 00000000..53c7090d
Binary files /dev/null and b/games/suika/docs/menu.png differ
diff --git a/games/suika/docs/shot.png b/games/suika/docs/shot.png
new file mode 100644
index 00000000..2081ade9
Binary files /dev/null and b/games/suika/docs/shot.png differ
diff --git a/games/suika/docs/title.png b/games/suika/docs/title.png
new file mode 100644
index 00000000..9b153e49
Binary files /dev/null and b/games/suika/docs/title.png differ
diff --git a/games/suika/src/icon.png b/games/suika/src/icon.png
new file mode 100644
index 00000000..d1def873
Binary files /dev/null and b/games/suika/src/icon.png differ
diff --git a/games/suika/src/main.c b/games/suika/src/main.c
new file mode 100644
index 00000000..baf65a27
--- /dev/null
+++ b/games/suika/src/main.c
@@ -0,0 +1,124 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <eadk.h>
+#include "suika.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"))) = "Suika Game";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+#define KEY(k) (UINT64_C(1) << (k))
+#define SAVE_NAME "suika.sav"
+static sk_game game;
+static uint8_t save_data[SK_SAVE_BYTES];
+static uint32_t last_checksum;
+static bool save_failed;
+/* Instrumentation for the existing NumPlay ARM emulator. */
+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 uint32_t save_checksum(void) {
+ unsigned n=SK_SAVE_BYTES-4;
+ return save_data[n] | (uint32_t)save_data[n+1]<<8 | (uint32_t)save_data[n+2]<<16 | (uint32_t)save_data[n+3]<<24;
+}
+static bool save(void) {
+ sk_encode(&game,save_data);
+ uint32_t checksum=save_checksum();
+ if(checksum==last_checksum&&!save_failed)return true;
+ save_failed=!ef_write(SAVE_NAME,save_data,SK_SAVE_BYTES);
+ if(!save_failed)last_checksum=checksum;
+ return !save_failed;
+}
+static void load(void) {
+ uint32_t len=0;
+ const uint8_t *p=ef_read(SAVE_NAME,&len);
+ if(!sk_decode(&game,p,len))sk_new(&game,eadk_random(),0);
+}
+int main(void) {
+ np_app_begin();
+ load();
+ unsigned view=SK_TITLE,selected=0,help_return=SK_TITLE;
+ uint64_t previous=eadk_keyboard_scan(),stale=previous;
+ uint32_t now=(uint32_t)eadk_timing_millis(),tick_at=now,draw_at=now,save_at=now;
+ sk_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;
+ if(view!=SK_SAVE_ERROR && keys&(KEY(eadk_key_home)|KEY(eadk_key_on_off))) {
+ if(save())break;
+ view=SK_SAVE_ERROR;selected=0;
+ /* A failed exit remains visible until a fresh OK or Back press. */
+ stale=keys;hit=0;ok=back=false;
+ }
+ if(view==SK_PLAY) {
+ if(back) { view=SK_PAUSE;selected=0;save(); }
+ else {
+ if(ok)sk_drop(&game);
+ /* Bound catch-up after a slow frame; resuming never simulates the
+ * time spent paused. Input is consumed once, not per catch-up tick. */
+ if(now-tick_at>4*SK_TICK_MS)tick_at=now-4*SK_TICK_MS;
+ while(now-tick_at>=SK_TICK_MS) {
+ int dir=((active&KEY(eadk_key_right))!=0)-((active&KEY(eadk_key_left))!=0);
+ if(dir)sk_aim(&game,game.aim+dir*2.0f);
+ sk_step(&game);
+ tick_at+=SK_TICK_MS;
+ }
+ if(game.over) { view=SK_RESULT;selected=0;save(); }
+ if(now-save_at>=5000) { save();save_at=now; }
+ }
+ } else {
+ tick_at=now;
+ bool nav=(hit&(KEY(eadk_key_up)|KEY(eadk_key_down)))!=0;
+ if(view==SK_TITLE) {
+ if(nav)selected=!selected;
+ if(back) { if(save())break;view=SK_SAVE_ERROR; }
+ else if(ok&&selected) { help_return=SK_TITLE;view=SK_HELP; }
+ else if(ok) {
+ if(game.over)sk_new(&game,eadk_random()^now,game.best);
+ view=SK_PLAY;selected=0;tick_at=now;
+ }
+ } else if(view==SK_HELP) {
+ if(ok||back) { view=help_return;selected=0; }
+ } else if(view==SK_PAUSE) {
+ if(hit&KEY(eadk_key_down))selected=(selected+1)%4;
+ if(hit&KEY(eadk_key_up))selected=(selected+3)%4;
+ if(back||(ok&&selected==0))view=SK_PLAY;
+ else if(ok&&selected==1)view=SK_CONFIRM,selected=0;
+ else if(ok&&selected==2)help_return=SK_PAUSE,view=SK_HELP;
+ else if(ok&&selected==3)view=SK_TITLE,selected=0;
+ } else if(view==SK_CONFIRM) {
+ if(nav)selected=!selected;
+ if(back||(ok&&selected==0))view=SK_PAUSE,selected=0;
+ else if(ok) { sk_new(&game,eadk_random()^now,game.best);view=SK_PLAY; }
+ } else if(view==SK_RESULT) {
+ if(nav)selected=!selected;
+ if(back||(ok&&selected==1))view=SK_TITLE,selected=0;
+ else if(ok) { sk_new(&game,eadk_random()^now,game.best);view=SK_PLAY; }
+ } else if(view==SK_SAVE_ERROR) {
+ if(back)break;
+ if(ok&&save())break;
+ if(hit&KEY(eadk_key_one))view=game.over?SK_RESULT:game.started?SK_PLAY:SK_TITLE,selected=0;
+ }
+ }
+ /* Simulation at 62.5 Hz, screen at up to 31.25 Hz. Menus sleep too. */
+ if(now-draw_at>=32||hit||perf_frames==0) {
+ uint32_t begin=(uint32_t)eadk_timing_millis();
+ sk_render(&game,view,selected,save_failed,push);
+ uint32_t spent=(uint32_t)eadk_timing_millis()-begin;
+ if(spent>perf_max)perf_max=spent;
+ if(spent>32)++perf_slow;
+ ++perf_frames;draw_at=now;
+ }
+ eadk_timing_msleep(4);
+ }
+ return np_app_end();
+}
diff --git a/games/suika/src/physics.c b/games/suika/src/physics.c
new file mode 100644
index 00000000..eb85f44a
--- /dev/null
+++ b/games/suika/src/physics.c
@@ -0,0 +1,188 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Suika for NumPlay: bounded storage, fixed-step circle physics, no heap.
+ */
+#include "suika.h"
+#include <math.h>
+#include <string.h>
+
+const uint8_t sk_radius[] = {0, 5, 7, 9, 11, 14, 17, 20, 25, 28, 31, 40};
+const char *const sk_names[] = {"", "CHERRY", "STRAWBERRY", "GRAPE", "DEKOPON", "PERSIMMON",
+ "APPLE", "PEAR", "PEACH", "PINEAPPLE", "MELON", "WATERMELON"};
+static float clamp(float x, float lo, float hi) { return x < lo ? lo : x > hi ? hi : x; }
+static void add_score(sk_game *g, uint32_t n) {
+ g->score = UINT32_MAX - g->score < n ? UINT32_MAX : g->score + n;
+ if (g->score > g->best) g->best = g->score;
+}
+static uint32_t random32(sk_game *g) {
+ uint32_t x = g->rng;
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ return g->rng = x;
+}
+/* Independent uniform draws; repeats are intentional, with no bag or pity. */
+static uint8_t take(sk_game *g) {return (uint8_t)(1+random32(g)%5);}
+static void advance(sk_game *g) {
+ g->current=g->next;g->next=take(g);sk_aim(g,g->aim);
+}
+void sk_new(sk_game *g, uint32_t seed, uint32_t best) {
+ memset(g, 0, sizeof *g);
+ g->rng = seed ? seed : 0xA341316Cu;
+ g->best = best;
+ g->current = take(g);
+ g->next = take(g);
+ g->aim = SK_WIDTH * 0.5f;
+ g->highest = 1;
+}
+void sk_aim(sk_game *g, float x) {
+ float r = sk_radius[g->current];
+ g->aim = clamp(x, r + 0.5f, SK_WIDTH - r - 0.5f);
+}
+bool sk_drop(sk_game *g) {
+ if (g->over || g->cooldown) return false;
+ float r = sk_radius[g->current];
+ /* No interpenetrating spawn when a stack reaches the dropper. Allow the
+ * pile to settle/merge and let the danger timer decide whether it is over. */
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ const sk_fruit *b = &g->fruit[i];
+ if (!b->kind) continue;
+ float dx = b->x - g->aim, dy = b->y - SK_DROP_Y, sum = sk_radius[b->kind] + r;
+ if (dx * dx + dy * dy < sum * sum) { g->notice = 60; return false; }
+ }
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ sk_fruit *b = &g->fruit[i];
+ if (b->kind) continue;
+ *b = (sk_fruit){g->aim, SK_DROP_Y, 0, 0, 0, g->current, 0};
+ if (b->kind > g->highest) g->highest = b->kind;
+ ++g->count;
+ g->started = 1;
+ g->cooldown = 24;
+ g->notice = 0;
+ advance(g);
+ return true;
+ }
+ g->notice = 60;
+ return false;
+}
+static void walls(sk_fruit *b) {
+ float r = sk_radius[b->kind];
+ if (b->x < r) {
+ b->x = r;
+ if (b->vx < 0) b->vx *= -0.18f;
+ }
+ if (b->x > SK_WIDTH - r) {
+ b->x = SK_WIDTH - r;
+ if (b->vx > 0) b->vx *= -0.18f;
+ }
+ if (b->y > SK_HEIGHT - r) {
+ b->y = SK_HEIGHT - r;
+ if (b->vy > 0) b->vy = b->vy < 0.45f ? 0 : -b->vy * 0.12f;
+ b->vx *= 0.85f;
+ }
+ /* A finite ceiling bound protects fixed-size saves even in dense stacks. */
+ if (b->y < -48) b->y = -48, b->vy = 0;
+ b->vx = clamp(b->vx, -8, 8);
+ b->vy = clamp(b->vy, -8, 8);
+}
+static void merge(sk_game *g, sk_fruit *a, sk_fruit *b) {
+ unsigned kind = a->kind;
+ float x = (a->x + b->x) * 0.5f, y = (a->y + b->y) * 0.5f;
+ float vx = (a->vx + b->vx) * 0.5f, vy = (a->vy + b->vy) * 0.5f;
+ /* Preserve mature stack age. Give growth a short grace period only. */
+ unsigned age = a->age > b->age ? a->age : b->age;
+ if (age > 90) age = 90;
+ memset(b, 0, sizeof *b);
+ --g->count;
+ add_score(g, kind * (kind + 1) / 2);
+ if (g->merges < UINT32_MAX) ++g->merges;
+ if (kind == SK_RANKS) {
+ memset(a, 0, sizeof *a);
+ --g->count;
+ } else {
+ *a = (sk_fruit){x, y, vx, vy, (uint16_t)age, (uint8_t)(kind + 1), 16};
+ if (a->kind > g->highest) g->highest = a->kind;
+ walls(a);
+ }
+}
+void sk_step(sk_game *g) {
+ if (g->over) return;
+ if (g->cooldown) --g->cooldown;
+ if (g->notice) --g->notice;
+ uint64_t merged = 0;
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ sk_fruit *b = &g->fruit[i];
+ if (!b->kind) continue;
+ if (b->age < 65535) ++b->age;
+ if (b->pop) --b->pop;
+ b->vx *= 0.994f;
+ b->vy = clamp(b->vy + 0.115f, -8, 8);
+ }
+ /* Two substeps prevent small fruit passing through a fast contact. Six
+ * total solver passes, mass proportional to area, damped contact friction. */
+ for (unsigned sub = 0; sub < 2; ++sub) {
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ sk_fruit *b = &g->fruit[i];
+ if (!b->kind) continue;
+ b->x += b->vx * 0.5f;
+ b->y += b->vy * 0.5f;
+ walls(b);
+ }
+ for (unsigned pass = 0; pass < 3; ++pass) {
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ sk_fruit *a = &g->fruit[i];
+ if (!a->kind) continue;
+ for (unsigned j = i + 1; j < SK_CAPACITY; ++j) {
+ sk_fruit *b = &g->fruit[j];
+ if (!b->kind) continue;
+ float dx = b->x - a->x, dy = b->y - a->y;
+ float ra = sk_radius[a->kind], rb = sk_radius[b->kind], sum = ra + rb;
+ if (fabsf(dx) >= sum || fabsf(dy) >= sum) continue;
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= sum * sum) continue;
+ uint64_t mask = (UINT64_C(1) << i) | (UINT64_C(1) << j);
+ if (a->kind == b->kind && !(merged & mask)) {
+ merged |= mask;
+ merge(g, a, b);
+ if (!a->kind) break;
+ continue;
+ }
+ /* Coincident centres need a real separation axis, not dx=1 with
+ * an unrelated zero distance. The tie-break is deterministic. */
+ float dist;
+ if (d2 < 0.0001f) dx = 1, dy = 0, dist = 1;
+ else dist = sqrtf(d2);
+ float nx = dx / dist, ny = dy / dist;
+ float wa = rb * rb / (ra * ra + rb * rb), wb = 1 - wa;
+ float overlap = sum - dist + 0.002f;
+ a->x -= nx * overlap * wa;
+ a->y -= ny * overlap * wa;
+ b->x += nx * overlap * wb;
+ b->y += ny * overlap * wb;
+ float relative = (b->vx - a->vx) * nx + (b->vy - a->vy) * ny;
+ if (relative < 0) {
+ float impulse = -relative * (relative < -0.8f ? 1.12f : 1.0f);
+ a->vx -= impulse * nx * wa;
+ a->vy -= impulse * ny * wa;
+ b->vx += impulse * nx * wb;
+ b->vy += impulse * ny * wb;
+ float slip = ((b->vx - a->vx) * -ny + (b->vy - a->vy) * nx) * 0.035f;
+ a->vx -= slip * ny * wa;
+ a->vy += slip * nx * wa;
+ b->vx += slip * ny * wb;
+ b->vy -= slip * nx * wb;
+ }
+ walls(a);
+ walls(b);
+ }
+ }
+ }
+ }
+ bool danger = false;
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ const sk_fruit *b = &g->fruit[i];
+ if (b->kind && b->age > 120 && b->y - sk_radius[b->kind] < SK_DANGER) danger = true;
+ }
+ if (danger) { if (g->danger < 180) ++g->danger; }
+ else g->danger = 0;
+ if (g->danger >= 180) g->over = 1;
+}
diff --git a/games/suika/src/render.c b/games/suika/src/render.c
new file mode 100644
index 00000000..216087d9
--- /dev/null
+++ b/games/suika/src/render.c
@@ -0,0 +1,379 @@
+/* SPDX-License-Identifier: GPL-3.0-only
+ * Original procedural artwork. No sprites, framebuffer, or heap allocations.
+ */
+#include "render.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#define C(v) ((uint16_t)((((v) >> 8) & 0xF800) | (((v) >> 5) & 0x07E0) | (((v) >> 3) & 0x1F)))
+#define PAPER C(0xFCF4DF)
+#define INK C(0x354C34)
+#define MUTED C(0x8D8867)
+#define GREEN C(0x477842)
+#define RED C(0xC64F49)
+#define BX 88
+#define BY 52
+static uint16_t band[320 * 8];
+static int x0, y0, x1, y1;
+static int16_t dirty_lo[30], dirty_hi[30];
+static bool initialized;
+static const sk_game *world;
+static unsigned page, selection;
+static bool failed;
+static bool basket_clip;
+
+/* Five columns, seven rows. One tiny alphabet for every page of the game. */
+static const uint8_t alphabet[][5] = {
+ {0x7e,0x11,0x11,0x11,0x7e},{0x7f,0x49,0x49,0x49,0x36},{0x3e,0x41,0x41,0x41,0x22},
+ {0x7f,0x41,0x41,0x22,0x1c},{0x7f,0x49,0x49,0x49,0x41},{0x7f,0x09,0x09,0x09,0x01},
+ {0x3e,0x41,0x49,0x49,0x7a},{0x7f,0x08,0x08,0x08,0x7f},{0x00,0x41,0x7f,0x41,0x00},
+ {0x20,0x40,0x41,0x3f,0x01},{0x7f,0x08,0x14,0x22,0x41},{0x7f,0x40,0x40,0x40,0x40},
+ {0x7f,0x02,0x0c,0x02,0x7f},{0x7f,0x04,0x08,0x10,0x7f},{0x3e,0x41,0x41,0x41,0x3e},
+ {0x7f,0x09,0x09,0x09,0x06},{0x3e,0x41,0x51,0x21,0x5e},{0x7f,0x09,0x19,0x29,0x46},
+ {0x46,0x49,0x49,0x49,0x31},{0x01,0x01,0x7f,0x01,0x01},{0x3f,0x40,0x40,0x40,0x3f},
+ {0x1f,0x20,0x40,0x20,0x1f},{0x3f,0x40,0x38,0x40,0x3f},{0x63,0x14,0x08,0x14,0x63},
+ {0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},
+ {0x3e,0x51,0x49,0x45,0x3e},{0x00,0x42,0x7f,0x40,0x00},{0x62,0x51,0x49,0x49,0x46},
+ {0x22,0x41,0x49,0x49,0x36},{0x18,0x14,0x12,0x7f,0x10},{0x27,0x45,0x45,0x45,0x39},
+ {0x3c,0x4a,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},{0x36,0x49,0x49,0x49,0x36},
+ {0x06,0x49,0x49,0x29,0x1e},
+ {0,0x08,0x3e,0x08,0},{0,0x08,0x08,0x08,0},{0,0x60,0x60,0,0},
+ {0,0x36,0x36,0,0},{0x20,0x10,0x08,0x04,0x02},{0,0,0x5f,0,0},
+ {0x08,0x14,0x22,0x41,0},{0x41,0x22,0x14,0x08,0},{0,0,0x7f,0,0}
+};
+static void mark(int x, int y, int w, int h) {
+ if (x < 0) w += x, x = 0;
+ if (y < 0) h += y, y = 0;
+ if (x + w > 320) w = 320 - x;
+ if (y + h > 240) h = 240 - y;
+ if (w <= 0 || h <= 0) return;
+ for (int row = y / 8; row <= (y + h - 1) / 8; ++row) {
+ if (x < dirty_lo[row]) dirty_lo[row] = (int16_t)x;
+ if (x + w > dirty_hi[row]) dirty_hi[row] = (int16_t)(x + w);
+ }
+}
+void sk_invalidate(void) { mark(0, 0, 320, 240); initialized = false; }
+static void pixel(int x, int y, uint16_t c) {
+ if (basket_clip && (x < BX || x >= BX + SK_WIDTH || y < BY-32 || y >= BY + SK_HEIGHT)) return;
+ if (x >= x0 && x < x1 && y >= y0 && y < y1) band[(y - y0) * (x1 - x0) + x - x0] = c;
+}
+static void rect(int x, int y, int w, int h, uint16_t c) {
+ int l = x < x0 ? x0 : x, t = y < y0 ? y0 : y;
+ int r = x + w > x1 ? x1 : x + w, b = y + h > y1 ? y1 : y + h;
+ if (basket_clip) {
+ if (l < BX) l = BX;
+ if (r > BX + SK_WIDTH) r = BX + SK_WIDTH;
+ if (t < BY-32) t = BY-32;
+ if (b > BY + SK_HEIGHT) b = BY + SK_HEIGHT;
+ }
+ if (l >= r || t >= b) return;
+ /* Clip once per span instead of branching on every individual pixel. */
+ for (int j = t; j < b; ++j) {
+ uint16_t *p = band + (j-y0)*(x1-x0) + l-x0;
+ for (int i = l; i < r; ++i) *p++ = c;
+ }
+}
+static void roundbox(int x, int y, int w, int h, int radius, uint16_t c) {
+ if (y >= y1 || y + h <= y0 || x >= x1 || x + w <= x0) return;
+ for (int j = y > y0 ? y : y0; j < y + h && j < y1; ++j) {
+ int dy = j < y + radius ? y + radius - j : j >= y + h - radius ? j - (y + h - radius - 1) : 0;
+ int inset = dy ? radius - (int)sqrtf((float)(radius * radius - dy * dy)) : 0;
+ rect(x + inset, j, w - 2 * inset, 1, c);
+ }
+}
+static void line(int a, int b, int c, int d, uint16_t ink) {
+ int dx = abs(c - a), sx = a < c ? 1 : -1, dy = -abs(d - b), sy = b < d ? 1 : -1, err = dx + dy;
+ for (;;) {
+ pixel(a, b, ink);
+ if (a == c && b == d) break;
+ int e = 2 * err;
+ if (e >= dy) err += dy, a += sx;
+ if (e <= dx) err += dx, b += sy;
+ }
+}
+static void circle(int x, int y, int r, uint16_t c, bool outline) {
+ if (y + r < y0 || y - r >= y1 || x + r < x0 || x - r >= x1) return;
+ for (int j = y - r > y0 ? y - r : y0; j <= y + r && j < y1; ++j) {
+ int half = (int)sqrtf((float)(r * r - (j - y) * (j - y)));
+ if (outline) {
+ pixel(x - half, j, c); pixel(x + half, j, c);
+ if (abs(j - y) >= r - 1) rect(x - half, j, 2 * half + 1, 1, c);
+ } else rect(x - half, j, 2 * half + 1, 1, c);
+ }
+}
+static void text(int x, int y, const char *s, int scale, uint16_t ink) {
+ if (y >= y1 || y + 7 * scale <= y0) return;
+ for (; *s; ++s, x += 6 * scale) {
+ unsigned ch = (unsigned char)*s, i;
+ if (ch >= 'a' && ch <= 'z') ch -= 32;
+ if (ch >= 'A' && ch <= 'Z') i = ch - 'A';
+ else if (ch >= '0' && ch <= '9') i = ch - '0' + 26;
+ else {
+ static const char punctuation[] = "+-.:/!<>|";
+ const char *p = strchr(punctuation, (int)ch);
+ if (!p || ch == ' ') continue;
+ i = 36 + (unsigned)(p - punctuation);
+ }
+ for (int col = 0; col < 5; ++col) for (int row = 0; row < 7; ++row)
+ if (alphabet[i][col] & (1 << row)) rect(x + col * scale, y + row * scale, scale, scale, ink);
+ }
+}
+static int width(const char *s, int scale) { return (int)strlen(s) * 6 * scale - scale; }
+static void centered(int cx, int y, const char *s, int scale, uint16_t ink) {
+ text(cx - width(s, scale) / 2, y, s, scale, ink);
+}
+static void number(int x, int y, uint32_t value, int scale, uint16_t ink) {
+ char s[11]; int n = 0;
+ do { s[n++] = (char)('0' + value % 10); value /= 10; } while (value);
+ for (int i = 0; i < n / 2; ++i) { char c = s[i]; s[i] = s[n - i - 1]; s[n - i - 1] = c; }
+ s[n] = 0;
+ text(x, y, s, scale, ink);
+}
+/* Relative scale and expressions adapted from the publisher's classic skin. */
+static const uint16_t colors[]={0,C(0xF21F28),C(0xFF655F),C(0xA34CF5),C(0xFFB517),C(0xFF8E24),
+ C(0xF21D2D),C(0xFFF28B),C(0xFFB6BF),C(0xFFE84F),C(0xD7ED76),C(0x43B60C)};
+static const uint16_t rims[]={0,C(0xB91B24),C(0xD94047),C(0x792FD4),C(0xE59A08),C(0xE16D0D),
+ C(0xB61020),C(0xD5AD2E),C(0xDD6B85),C(0xCFAB20),C(0x96B538),C(0x146509)};
+static void leaf(int x,int y,int size) {
+ line(x-size,y,x+size,y,GREEN);line(x,y-size,x,y+size,GREEN);
+ line(x-size,y-size/2,x+size,y+size/2,GREEN);
+}
+static void fruit(int k,int x,int y,int r,bool happy) {
+ if(y+r+9<y0||y-r-9>=y1||x+r+3<x0||x-r-3>=x1)return;
+ if(k==3) {
+ int a=r/2;if(a<2)a=2;
+ static const int8_t xx[]={-1,0,1,-1,1,0},yy[]={0,-1,0,1,1,2};
+ for(unsigned i=0;i<6;++i)circle(x+xx[i]*a,y+(yy[i]-1)*a*2/3,a+1,rims[k],false);
+ for(unsigned i=0;i<6;++i)circle(x+xx[i]*a,y+(yy[i]-1)*a*2/3,a,colors[k],false);
+ leaf(x-r+2,y-r+3,2);
+ } else if(k==2) {
+ /* A round shoulder tapers to the strawberry's tip. */
+ int top=y-r>y0?y-r:y0,bottom=y+r<y1?y+r:y1-1;
+ for(int j=top;j<=bottom;++j) {
+ int dy=j-y,half=(int)sqrtf((float)(r*r-dy*dy));
+ if(dy>0)half=half*(2*r-dy)/(2*r);
+ rect(x-half,j,2*half+1,1,rims[k]);
+ if(half>0)rect(x-half+1,j,2*half-1,1,colors[k]);
+ }
+ } else {
+ circle(x,y,r,rims[k],false);circle(x,y,r-1,colors[k],false);
+ }
+ if(k==4) {circle(x,y-r+1,r/3+1,rims[k],false);circle(x,y-r+1,r/3,colors[k],false);}
+ if(k==2||k==5)leaf(x,y-r+2,r/3+1);
+ if(k==1||k==6||k==7) {
+ line(x-1,y-r+2,x+1,y-r-3,C(0x8A5C24));
+ if(k==1)leaf(x+3,y-r-3,2);
+ }
+ if(k==9) {
+ for(int i=-2;i<=2;++i)line(x,y-r+2,x+i*3,y-r-5-((i&1)?0:3),GREEN);
+ }
+ if(k==8&&r>7)line(x-r/5,y-r+3,x-r/3,y-r/2,rims[k]);
+ int top=y-r+2>y0?y-r+2:y0,bottom=y+r-2<y1?y+r-2:y1-1;
+ if(k>=9)for(int j=top;j<=bottom;++j) {
+ int dy=j-y,half=(int)sqrtf((float)((r-1)*(r-1)-dy*dy));
+ for(int i=-half+1;i<half;++i) {
+ if(k==11) {
+ if((i+dy/3+r*3)%18<6)pixel(x+i,j,C(0x217A08));
+ } else if((i+dy+r*4)%9==0||(i-dy+r*4)%9==0)
+ pixel(x+i,j,k==10?C(0xECF5AC):C(0xE1BC29));
+ }
+ }
+ if(k==2)for(int j=-r/2;j<r/2;j+=4)for(int i=-r/2;i<=r/2;i+=4)
+ pixel(x+i+(j&1),y+j,C(0xFFE7A8));
+ if(r>7) {
+ circle(x-r/3,y-r/2,r/7+1,k==11?C(0xFFFFFF):C(0xFFF7D6),false);
+ if(k>=6)circle(x-r/2,y-r/6,1,C(0xFFF7D6),false);
+ }
+ if(r<4)return;
+ int ex=r>14?r/4:2,ey=y+r/10,eye=r>=17?2:1;
+ uint16_t face=k==11?C(0x124902):k==6?C(0x8D1019):k==8?C(0xAA243E):C(0x8E6727);
+ if(k==11||happy) {
+ line(x-ex-eye,ey-eye,x-ex+eye,ey,face);line(x-ex+eye,ey,x-ex-eye,ey+eye,face);
+ circle(x+ex,ey,eye,face,false);
+ } else {
+ circle(x-ex,ey,eye,face,false);circle(x+ex,ey,eye,face,false);
+ if(k==3||k==4) {pixel(x-ex,ey,C(0xFFFFFF));pixel(x+ex,ey,C(0xFFFFFF));}
+ }
+ int mouth=ey+(r>12?5:3);
+ if(k==6) {line(x-1,mouth-1,x+2,mouth-1,face);line(x+2,mouth-1,x,mouth+2,face);}
+ else if(k==8) {
+ line(x-3,mouth-1,x-2,mouth+2,face);line(x-2,mouth+2,x,mouth,face);
+ line(x,mouth,x+2,mouth+2,face);line(x+2,mouth+2,x+3,mouth-1,face);
+ } else if(k==3)circle(x,mouth,1,face,true);
+ else {line(x-2,mouth,x,mouth+1,face);line(x,mouth+1,x+2,mouth-1,face);}
+ if(r>=10&&k!=11) {pixel(x-ex-3,ey+3,C(0xEE8275));pixel(x+ex+3,ey+3,C(0xEE8275));}
+}
+static void button(int x, int y, int w, const char *label, bool active) {
+ roundbox(x,y+2,w,23,6,C(0xDDD2AB));
+ roundbox(x,y,w,23,6,active?GREEN:C(0xF4E9CE));
+ centered(x+w/2,y+8,label,1,active?C(0xFFF9E9):INK);
+}
+static void card(int x, int y, int w, int h) {
+ roundbox(x,y+3,w,h,7,C(0xE5D7B5)); roundbox(x,y,w,h,7,C(0xFFFBEF));
+}
+static void backdrop(void) {
+ rect(0,0,320,110,C(0xCF9859));rect(0,110,320,23,C(0xB9812D));
+ rect(0,133,320,7,C(0xE6CA81));rect(0,140,320,100,C(0xF4DF92));
+ for(int y=140;y<240;y+=25)for(int x=0;x<320;x+=40)
+ if(((x/40+y/25)&1)==0)rect(x,y,40,25,C(0xFFF0BB));
+}
+static void bubble(int x,int y,int r) {
+ circle(x,y,r,C(0xF5D999),false);circle(x,y,r-2,C(0xE9BD7F),false);
+ circle(x,y,r-5,C(0xDDA86D),false);
+ circle(x-r/2,y-r/2,r/8+1,C(0xFFF4CE),false);
+ circle(x-r/2-3,y-r/2+8,1,C(0xFFF9DC),false);
+ line(x+r/3,y+r-6,x+r/2,y+r-9,C(0xFBE8B1));
+}
+static void cloud(int x,int y) {
+ const uint16_t rim=C(0xEAC751),fill=C(0xFFF19B),face=C(0x8C6950);
+ circle(x-10,y+3,9,rim,false);circle(x,y-3,12,rim,false);circle(x+11,y+3,9,rim,false);
+ rect(x-10,y+3,23,10,rim);
+ circle(x-10,y+3,7,fill,false);circle(x,y-3,10,fill,false);circle(x+11,y+3,7,fill,false);
+ rect(x-10,y+2,23,9,fill);
+ circle(x-5,y+1,1,face,false);circle(x+5,y+1,1,face,false);
+ line(x-1,y+4,x,y+5,face);line(x,y+5,x+2,y+4,face);
+ rect(x-11,y+5,3,2,C(0xF0B5A0));rect(x+9,y+5,3,2,C(0xF0B5A0));
+}
+static void board(void) {
+ const sk_game *g=world;
+ rect(BX,BY,SK_WIDTH,SK_HEIGHT,C(0xFFF0C0));
+ rect(BX+2,BY,8,SK_HEIGHT,C(0xFFF5D3));rect(BX+SK_WIDTH-10,BY,8,SK_HEIGHT,C(0xEDDCAC));
+ rect(BX+8,BY-9,SK_WIDTH-16,9,C(0xE9D79A));
+ line(BX-2,BY,BX+7,BY-10,C(0xFFE7A1));line(BX+7,BY-10,BX+SK_WIDTH-7,BY-10,C(0xFFE7A1));
+ line(BX+SK_WIDTH-7,BY-10,BX+SK_WIDTH+2,BY,C(0xFFE7A1));
+ basket_clip=true;
+ for(unsigned i=0;i<SK_CAPACITY;++i) {
+ const sk_fruit *b=&g->fruit[i];if(!b->kind)continue;
+ fruit(b->kind,BX+(int)b->x,BY+(int)b->y,sk_radius[b->kind],b->pop>0);
+ }
+ basket_clip=false;
+ rect(BX-3,BY,3,SK_HEIGHT+3,C(0xFFE39A));rect(BX+SK_WIDTH,BY,3,SK_HEIGHT+3,C(0xEBCD7B));
+ rect(BX-3,BY+SK_HEIGHT,SK_WIDTH+6,4,C(0xFFE39A));rect(BX-3,BY,SK_WIDTH+6,2,C(0xFFE39A));
+ if(g->danger)for(int x=BX+2;x<BX+SK_WIDTH;x+=7)rect(x,BY+SK_DANGER,4,1,RED);
+ if(!g->over) {
+ int ax=BX+(int)g->aim;cloud(ax,18);
+ if(!g->cooldown)fruit(g->current,ax,BY+SK_DROP_Y,sk_radius[g->current],false);
+ }
+}
+static void center_number(int x,int y,uint32_t value,int scale,uint16_t ink) {
+ unsigned digits=1;for(uint32_t n=value;n>=10;n/=10)++digits;
+ number(x-((int)digits*6-1)*scale/2,y,value,scale,ink);
+}
+static void evolution(void) {
+ static const int8_t xx[]={12,26,32,27,14,-4,-20,-30,-30,-21,-4};
+ static const int8_t yy[]={-30,-18,0,17,29,32,25,10,-9,-25,-32};
+ circle(278,170,37,C(0xF6ECA6),false);circle(278,170,26,C(0xEBDCA0),false);
+ centered(278,109,"CIRCLE OF",1,INK);centered(278,120,"EVOLUTION",1,INK);
+ for(unsigned i=0;i<SK_RANKS;++i)fruit((int)i+1,278+xx[i],170+yy[i],2+(int)i/2,false);
+ line(290,133,294,135,GREEN);line(294,135,290,137,GREEN);
+}
+static void gameplay(void) {
+ const sk_game *g=world;backdrop();
+ bubble(38,59,35);centered(38,24,"SCORE",1,INK);
+ center_number(38,43,g->score,g->score<10000?2:1,C(0xFFF7CC));
+ centered(38,66,"BEST",1,INK);center_number(38,78,g->best,1,C(0xFFF7CC));
+ bubble(279,58,30);centered(279,26,"NEXT",1,INK);
+ fruit(g->next,279,63,sk_radius[g->next],false);
+ evolution();board();
+}
+static void title(void) {
+ text(22,18,"NUMPLAY / SUIKA",1,MUTED);
+ text(21,42,"SUIKA",4,INK);
+ text(23,82,"A LITTLE FRUIT. A BIG MERGE.",1,GREEN);
+ fruit(11,272,52,28,true);
+ roundbox(16,112,143,105,10,C(0xEAD5AD));
+ roundbox(20,113,135,98,8,C(0xFFFBEF));
+ fruit(11,67,169,34,false); fruit(8,119,187,20,false);
+ fruit(5,111,151,14,false); fruit(3,124,125,10,false); fruit(1,88,128,6,false);
+ text(177,111,"BEST SCORE",1,MUTED); number(177,124,world->best,2,INK);
+ button(176,151,128,world->started&&!world->over?"CONTINUE":"PLAY",selection==0);
+ button(176,181,128,"HOW TO PLAY",selection==1);
+ text(178,218,"OK SELECT",1,MUTED);
+ text(22,230,"BY BOBYDELUXE",1,GREEN);
+}
+static void modal(void) {
+ /* Deterministic stipple dims without a second framebuffer. */
+ for(int y=y0;y<y1;++y)for(int x=x0;x<x1;++x)if((x+y)&1)pixel(x,y,C(0xD5C9A6));
+ card(40,35,240,174);
+ if(page==SK_HELP) {
+ centered(160,48,"HOW TO PLAY",2,INK);
+ text(54,72,"MATCH TWO FRUITS TO GROW.",1,INK);
+ text(54,86,"KEEP FRUIT INSIDE THE BOX.",1,INK);
+ text(54,107,"< > MOVE THE DROPPER",1,MUTED);
+ text(54,121,"OK DROP ONE FRUIT",1,MUTED);
+ text(54,135,"ONLY THE NEXT FRUIT IS SHOWN.",1,MUTED);
+ text(54,149,"FIVE SMALL FRUITS CAN DROP.",1,MUTED);
+ text(54,163,"BACK PAUSE / RESUME",1,MUTED);
+ button(91,181,138,"OK GOT IT",true);
+ } else if(page==SK_CONFIRM) {
+ centered(160,50,"START AGAIN?",2,INK);
+ centered(160,86,"YOUR CURRENT RUN WILL BE LOST.",1,MUTED);
+ centered(160,102,"YOUR BEST SCORE WILL STAY.",1,MUTED);
+ button(66,133,188,"KEEP PLAYING",selection==0);
+ button(66,166,188,"NEW GAME",selection==1);
+ } else if(page==SK_RESULT) {
+ centered(160,49,"BASKET FULL",2,INK);
+ centered(160,78,world->score && world->score==world->best?"A NEW PERSONAL BEST!":"A FRESH BASKET AWAITS.",1,GREEN);
+ text(67,103,"SCORE",1,MUTED); number(149,99,world->score,2,INK);
+ text(67,122,"MERGES",1,MUTED); number(149,122,world->merges,1,INK);
+ button(66,145,188,"PLAY AGAIN",selection==0);
+ button(66,175,188,"TITLE SCREEN",selection==1);
+ } else if(page==SK_SAVE_ERROR) {
+ centered(160,52,"SAVE FAILED",2,RED);
+ centered(160,85,"CALCULATOR STORAGE IS FULL",1,INK);
+ centered(160,102,"OR THE SAVE CANNOT BE WRITTEN.",1,MUTED);
+ centered(160,124,"YOUR RUN IS STILL IN MEMORY.",1,MUTED);
+ centered(160,138,"1 RETURN TO THE GAME",1,GREEN);
+ button(66,158,188,"OK RETRY SAVE",true);
+ centered(160,193,"BACK EXIT WITHOUT SAVING",1,RED);
+ } else {
+ centered(160,49,"TAKE A BREATHER",2,INK);
+ centered(160,77,failed?"STORAGE FULL - SAVE FAILED":"YOUR BASKET IS SAVED.",1,failed?RED:MUTED);
+ button(66,90,188,"RESUME",selection==0);
+ button(66,119,188,"NEW GAME",selection==1);
+ button(66,148,188,"HOW TO PLAY",selection==2);
+ button(66,177,188,"TITLE SCREEN",selection==3);
+ }
+}
+typedef struct {int16_t x,y;uint8_t kind,pop;} projection;
+static projection previous[SK_CAPACITY];
+static int old_aim,old_current,old_danger;
+static uint32_t old_score,old_best;
+static unsigned old_page=99,old_selection;
+static uint8_t old_next,old_ready,old_over;
+static bool old_failed;
+void sk_render(const sk_game *g,unsigned view,unsigned selected,bool save_failed,sk_push push) {
+ world=g;page=view;selection=selected;failed=save_failed;
+ bool full=!initialized||page!=old_page||selection!=old_selection||failed!=old_failed;
+ if(full) mark(0,0,320,240);
+ int aim=(int)g->aim;
+ for(unsigned i=0;i<SK_CAPACITY;++i) {
+ const sk_fruit *b=&g->fruit[i]; projection p={(int16_t)b->x,(int16_t)b->y,b->kind,b->pop};
+ if(memcmp(&p,&previous[i],sizeof p)) {
+ projection q=previous[i];
+ if(q.kind)mark(BX+q.x-sk_radius[q.kind]-9,BY+q.y-sk_radius[q.kind]-12,2*sk_radius[q.kind]+22,2*sk_radius[q.kind]+24);
+ if(p.kind)mark(BX+p.x-sk_radius[p.kind]-9,BY+p.y-sk_radius[p.kind]-12,2*sk_radius[p.kind]+22,2*sk_radius[p.kind]+24);
+ previous[i]=p;
+ }
+ }
+ if(aim!=old_aim||g->current!=old_current||(g->cooldown==0)!=old_ready||g->over!=old_over) {
+ mark(BX+old_aim-25,0,51,BY+26);mark(BX+aim-25,0,51,BY+26);
+ }
+ if((g->danger>0)!=(old_danger>0))mark(BX-3,BY,SK_WIDTH+6,8);
+ if(g->score!=old_score||g->best!=old_best)mark(0,18,78,80);
+ if(g->next!=old_next)mark(246,24,72,68);
+ old_aim=aim;old_current=g->current;old_danger=g->danger;
+ old_score=g->score;old_best=g->best;old_next=g->next;
+ old_page=page;old_selection=selection;old_failed=failed;
+ old_ready=g->cooldown==0;old_over=g->over;
+ for(int row=0;row<30;++row) {
+ if(dirty_hi[row]<=dirty_lo[row])continue;
+ x0=dirty_lo[row];x1=dirty_hi[row];y0=row*8;y1=y0+8;
+ rect(x0,y0,x1-x0,8,PAPER);
+ if(page==SK_TITLE)title();
+ else { gameplay();if(page!=SK_PLAY)modal(); }
+ push(x0,y0,x1-x0,8,band);
+ dirty_lo[row]=320;dirty_hi[row]=0;
+ }
+ initialized=true;
+}
diff --git a/games/suika/src/render.h b/games/suika/src/render.h
new file mode 100644
index 00000000..5a5ebc3d
--- /dev/null
+++ b/games/suika/src/render.h
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef SK_RENDER_H
+#define SK_RENDER_H
+#include "suika.h"
+enum { SK_TITLE, SK_PLAY, SK_PAUSE, SK_HELP, SK_CONFIRM, SK_RESULT, SK_SAVE_ERROR };
+typedef void (*sk_push)(int x, int y, int w, int h, const uint16_t *pixels);
+/* Rendering composes at most eight rows at a time (5120 bytes). */
+void sk_render(const sk_game *g, unsigned view, unsigned selected, bool save_failed, sk_push push);
+void sk_invalidate(void);
+#endif
diff --git a/games/suika/src/save.c b/games/suika/src/save.c
new file mode 100644
index 00000000..48c75f33
--- /dev/null
+++ b/games/suika/src/save.c
@@ -0,0 +1,105 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "suika.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void put16(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
+static unsigned get16(const uint8_t *p) { return p[0] | (unsigned)p[1] << 8; }
+static void put32(uint8_t *p, uint32_t v) { put16(p, v); put16(p + 2, v >> 16); }
+static uint32_t get32(const uint8_t *p) { return get16(p) | (uint32_t)get16(p + 2) << 16; }
+static uint32_t checksum(const uint8_t *p, size_t n) {
+ uint32_t h = 2166136261u;
+ while (n--) h = (h ^ *p++) * 16777619u;
+ return h;
+}
+void sk_encode(const sk_game *g, uint8_t out[SK_SAVE_BYTES]) {
+ memset(out, 0, SK_SAVE_BYTES);
+ memcpy(out, "SKA2", 4);
+ put32(out + 4, g->score);
+ put32(out + 8, g->best);
+ put32(out + 12, g->rng);
+ put32(out + 16, g->merges);
+ put16(out + 20, (int)(g->aim * 64));
+ put16(out + 22, g->danger);
+ out[24] = g->cooldown;
+ out[25] = g->current;
+ out[26] = g->next;
+ out[31] = g->highest;
+ out[32] = g->over;
+ out[33] = g->started;
+ unsigned n = 0;
+ for (unsigned i = 0; i < SK_CAPACITY; ++i) {
+ const sk_fruit *b = &g->fruit[i];
+ if (!b->kind) continue;
+ uint8_t *p = out + 48 + n++ * 11;
+ p[0] = b->kind;
+ put16(p + 1, (int)(b->x * 64));
+ put16(p + 3, (int)(b->y * 64));
+ put16(p + 5, (int)(b->vx * 256));
+ put16(p + 7, (int)(b->vy * 256));
+ put16(p + 9, b->age);
+ }
+ out[45] = (uint8_t)n;
+ put32(out + SK_SAVE_BYTES - 4, checksum(out, SK_SAVE_BYTES - 4));
+}
+bool sk_decode(sk_game *g, const uint8_t *p, size_t n) {
+ if (!p || n != SK_SAVE_BYTES || (memcmp(p, "SKA1", 4) && memcmp(p, "SKA2", 4)) ||
+ get32(p + n - 4) != checksum(p, n - 4)) return false;
+ bool legacy=p[3]=='1';
+ static const uint8_t old_radius[]={0,6,8,10,12,14,17,20,24,28,33,38};
+ unsigned width=legacy?194:SK_WIDTH,height=legacy?178:SK_HEIGHT;
+ if (!get32(p+12)||get32(p+4)>get32(p+8)||get16(p+20)>width*64||
+ get16(p+22)>180||p[24]>24||p[25]<1||p[25]>(legacy?4:5)||
+ p[26]<1||p[26]>(legacy?4:5)||p[31]<1||p[31]>SK_RANKS||
+ p[32]>1||p[33]>1||p[45]>SK_CAPACITY)return false;
+ if(legacy) {
+ if(p[29]>4||p[30]>1||p[34]>8||p[43]>99||p[44]>75)return false;
+ for(unsigned i=27;i<29;++i)if(p[i]<1||p[i]>4)return false;
+ unsigned counts[5]={0};
+ for(unsigned i=35;i<43;++i) {
+ if(p[i]<1||p[i]>4)return false;
+ ++counts[p[i]];
+ }
+ if(counts[1]!=3||counts[2]!=2||counts[3]!=2||counts[4]!=1)return false;
+ }
+ /* Validate the complete payload before touching the caller's live state. */
+ for (unsigned i = 0; i < p[45]; ++i) {
+ const uint8_t *b = p + 48 + i * 11;
+ if (!b[0] || b[0] > SK_RANKS) return false;
+ float x = (int16_t)get16(b + 1) / 64.0f, y = (int16_t)get16(b + 3) / 64.0f;
+ unsigned r=legacy?old_radius[b[0]]:sk_radius[b[0]];
+ if (x < r - 0.05f || x > width - r + 0.05f ||
+ y < -48 || y > height - r + 0.05f ||
+ abs((int16_t)get16(b + 5)) > 2048 || abs((int16_t)get16(b + 7)) > 2048) return false;
+ }
+ memset(g, 0, sizeof *g);
+ g->score = get32(p + 4);
+ g->best = get32(p + 8);
+ g->rng = get32(p + 12);
+ g->merges = get32(p + 16);
+ g->danger = get16(p + 22);
+ g->cooldown = p[24];
+ g->current = p[25];
+ g->next = p[26];
+ g->highest = p[31];
+ g->over = p[32];
+ g->started = p[33];
+ g->count = p[45];
+ sk_aim(g, get16(p + 20) / 64.0f * (legacy?SK_WIDTH/194.0f:1));
+ for (unsigned i = 0; i < g->count; ++i) {
+ const uint8_t *b = p + 48 + i * 11;
+ g->fruit[i] = (sk_fruit){(int16_t)get16(b + 1) / 64.0f, (int16_t)get16(b + 3) / 64.0f,
+ (int16_t)get16(b + 5) / 256.0f, (int16_t)get16(b + 7) / 256.0f,
+ (uint16_t)get16(b + 9), b[0], 0};
+ if(legacy) {
+ sk_fruit *f=&g->fruit[i];float r=sk_radius[f->kind];
+ f->x*=SK_WIDTH/194.0f;f->y*=SK_HEIGHT/178.0f;
+ f->vx*=SK_WIDTH/194.0f;f->vy*=SK_HEIGHT/178.0f;
+ if(f->x<r)f->x=r;
+ if(f->x>SK_WIDTH-r)f->x=SK_WIDTH-r;
+ if(f->y>SK_HEIGHT-r)f->y=SK_HEIGHT-r;
+ }
+ }
+ return true;
+}
diff --git a/games/suika/src/suika.h b/games/suika/src/suika.h
new file mode 100644
index 00000000..6fea3616
--- /dev/null
+++ b/games/suika/src/suika.h
@@ -0,0 +1,40 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef SUIKA_H
+#define SUIKA_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SK_CAPACITY 48
+#define SK_RANKS 11
+#define SK_WIDTH 144
+#define SK_HEIGHT 162
+#define SK_DANGER 0
+#define SK_DROP_Y (-8)
+#define SK_SAVE_BYTES 608
+#define SK_TICK_MS 16 /* fixed simulation step; independent of render speed */
+
+typedef struct {
+ float x, y, vx, vy;
+ uint16_t age;
+ uint8_t kind, pop;
+} sk_fruit;
+
+typedef struct {
+ sk_fruit fruit[SK_CAPACITY];
+ uint32_t rng, score, best, merges;
+ float aim;
+ uint16_t danger, cooldown;
+ uint8_t current, next, count, highest, over, started, notice;
+} sk_game;
+
+extern const uint8_t sk_radius[SK_RANKS + 1];
+extern const char *const sk_names[SK_RANKS + 1];
+void sk_new(sk_game *g, uint32_t seed, uint32_t best);
+void sk_aim(sk_game *g, float x);
+bool sk_drop(sk_game *g);
+void sk_step(sk_game *g);
+void sk_encode(const sk_game *g, uint8_t out[SK_SAVE_BYTES]);
+/* Rejects truncated/corrupt saves without modifying g. */
+bool sk_decode(sk_game *g, const uint8_t *data, size_t len);
+#endif
diff --git a/games/suika/tests/legacy-save.bin b/games/suika/tests/legacy-save.bin
new file mode 100644
index 00000000..e964ac52
Binary files /dev/null and b/games/suika/tests/legacy-save.bin differ
diff --git a/games/suika/tests/test.c b/games/suika/tests/test.c
new file mode 100644
index 00000000..b943a8ac
--- /dev/null
+++ b/games/suika/tests/test.c
@@ -0,0 +1,171 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include "suika.h"
+#include "render.h"
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static uint16_t screen[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 body(sk_game *g,int slot,int kind,float x,float y) {
+ g->fruit[slot]=(sk_fruit){x,y,0,0,200,(uint8_t)kind,0};++g->count;
+}
+static void valid(const sk_game *g) {
+ unsigned count=0;
+ for(unsigned i=0;i<SK_CAPACITY;++i) {
+ const sk_fruit *b=&g->fruit[i];if(!b->kind)continue;++count;
+ assert(b->kind<=SK_RANKS);
+ assert(isfinite(b->x)&&isfinite(b->y)&&isfinite(b->vx)&&isfinite(b->vy));
+ assert(b->x>=sk_radius[b->kind]-0.001f&&b->x<=SK_WIDTH-sk_radius[b->kind]+0.001f);
+ assert(b->y>=-48&&b->y<=SK_HEIGHT-sk_radius[b->kind]+0.001f);
+ assert(fabsf(b->vx)<=8.001f&&fabsf(b->vy)<=8.001f);
+ }
+ assert(count==g->count&&count<=SK_CAPACITY);
+}
+static void saves(void) {
+ sk_game g,h;uint8_t data[SK_SAVE_BYTES],copy[SK_SAVE_BYTES];
+ sk_new(&g,1234,99);body(&g,7,2,80,150);g.started=1;
+ sk_encode(&g,data);assert(sk_decode(&h,data,sizeof data));
+ assert(h.count==1&&h.fruit[0].kind==2&&h.best==99&&h.started);
+ sk_encode(&h,copy);assert(!memcmp(data,copy,sizeof data));
+ sk_game before=h;
+ assert(!sk_decode(&h,data,sizeof data-1));assert(!memcmp(&before,&h,sizeof h));
+ for(unsigned i=0;i<sizeof data;++i) {
+ data[i]^=0x80;assert(!sk_decode(&h,data,sizeof data));data[i]^=0x80;
+ assert(!memcmp(&before,&h,sizeof h));
+ }
+ assert(!sk_decode(&h,NULL,0));
+ /* Deliberately valid checksum with a semantically invalid fruit kind. */
+ data[48]=255;uint32_t hash=2166136261u;
+ for(unsigned i=0;i<SK_SAVE_BYTES-4;++i)hash=(hash^data[i])*16777619u;
+ for(int i=0;i<4;++i)data[SK_SAVE_BYTES-4+i]=(uint8_t)(hash>>(i*8));
+ assert(!sk_decode(&h,data,sizeof data));assert(!memcmp(&before,&h,sizeof h));
+}
+static void physics(void) {
+ sk_game g;sk_new(&g,1,0);
+ sk_aim(&g,-500);assert(g.aim>=sk_radius[g.current]);
+ assert(sk_drop(&g)&&!sk_drop(&g)&&g.count==1);
+ for(int t=0;t<200;++t)sk_step(&g);
+ assert(!g.over);valid(&g);
+ sk_new(&g,1,0);body(&g,0,3,80,140);body(&g,1,3,80,140);
+ sk_step(&g);assert(g.count==1&&g.fruit[0].kind==4&&g.score==6&&g.merges==1);valid(&g);
+ sk_new(&g,1,0);body(&g,0,11,40,100);body(&g,1,11,104,100);
+ sk_step(&g);assert(g.count==0&&g.score==66&&g.merges==1);
+ sk_new(&g,1,0);body(&g,0,2,80,140);body(&g,1,3,80,140);
+ sk_step(&g);assert(fabsf(g.fruit[0].x-g.fruit[1].x)>15);valid(&g);
+ /* Do not lose just because a newly dropped fruit crosses the line. */
+ sk_new(&g,1,0);assert(sk_drop(&g));sk_step(&g);assert(!g.danger);
+ /* Continuous danger, not a wrapping byte or a stale capacity flag. */
+ sk_new(&g,1,0);body(&g,0,1,30,0);
+ for(int t=0;t<179;++t) {g.fruit[0].y=0;g.fruit[0].vy=0;sk_step(&g);assert(!g.over);}
+ g.fruit[0].y=0;g.fruit[0].vy=0;sk_step(&g);assert(g.over&&g.danger==180);
+ sk_new(&g,1,0);body(&g,0,1,30,0);sk_step(&g);assert(g.danger==1);
+ g.fruit[0].y=150;sk_step(&g);assert(g.danger==0);
+ /* Consecutive merges award only their base points, without a combo. */
+ sk_new(&g,1,0);body(&g,0,1,25,140);body(&g,1,1,25,140);
+ sk_step(&g);assert(g.score==1);
+ body(&g,2,1,110,140);body(&g,3,1,110,140);
+ sk_step(&g);assert(g.score==2&&g.merges==2);valid(&g);
+ /* A blocked spawn never adds an overlapping body. */
+ sk_new(&g,1,0);body(&g,0,2,g.aim,SK_DROP_Y);assert(!sk_drop(&g)&&g.count==1&&g.notice);
+ /* Independent draws allow repeats; each of the five ranks is available. */
+ sk_game h;sk_new(&g,4242,0);sk_new(&h,4242,0);
+ unsigned frequency[6]={0},repeats=0,streak=1,longest=1;
+ for(int n=0;n<100000;++n) {
+ assert(g.current==h.current&&g.next==h.next);
+ assert(g.current>=1&&g.current<=5&&g.next>=1&&g.next<=5);
+ ++frequency[g.current];uint8_t old=g.current;
+ memset(g.fruit,0,sizeof g.fruit);g.count=0;g.cooldown=0;
+ memset(h.fruit,0,sizeof h.fruit);h.count=0;h.cooldown=0;
+ assert(sk_drop(&g)&&sk_drop(&h));
+ if(old==g.current) {++repeats;++streak;if(streak>longest)longest=streak;}
+ else streak=1;
+ }
+ for(int k=1;k<=5;++k)assert(frequency[k]>19000&&frequency[k]<21000);
+ assert(repeats>19000&&repeats<21000&&longest>=4);
+
+}
+static void stress(void) {
+ uint8_t data[SK_SAVE_BYTES];sk_game g,h;unsigned ticks=0;
+ for(unsigned seed=1;seed<=12;++seed) {
+ sk_new(&g,seed,0);
+ for(unsigned t=0;t<2400;++t) {
+ if(t%27==0) { sk_aim(&g,(float)((t*37+seed*13)%SK_WIDTH));sk_drop(&g); }
+ sk_step(&g);valid(&g);++ticks;
+ if(t%17==0) { sk_encode(&g,data);assert(sk_decode(&h,data,sizeof data));valid(&h); }
+ if(g.over)sk_new(&g,seed*131+t,g.best);
+ }
+ }
+ printf("Physics stress: %u ticks, save round trips every 17 ticks.\n",ticks);
+}
+static void screenshots(void) {
+ sk_game g;sk_new(&g,73,1284);
+ sk_invalidate();sk_render(&g,SK_TITLE,0,false,push);shot("title.ppm");
+ body(&g,0,11,44,122);body(&g,1,8,113,137);body(&g,2,7,112,91);
+ body(&g,3,6,46,65);body(&g,4,5,80,87);body(&g,5,3,30,86);
+ body(&g,6,2,104,61);body(&g,7,1,131,104);g.score=386;g.merges=24;g.highest=11;
+ g.current=2;g.next=5;g.aim=77;g.started=1;
+ uint8_t data[SK_SAVE_BYTES];sk_encode(&g,data);
+ FILE *f=fopen("scene-save.bin","wb");assert(f);fwrite(data,1,sizeof data,f);fclose(f);
+ sk_invalidate();sk_render(&g,SK_PLAY,0,false,push);shot("game.ppm");
+ uint16_t previous[320*240];memcpy(previous,screen,sizeof screen);
+ pushes=0;sk_render(&g,SK_PLAY,0,false,push);assert(pushes==0);
+ for(int t=0;t<20;++t)sk_step(&g);
+ sk_render(&g,SK_PLAY,0,false,push);memcpy(previous,screen,sizeof screen);
+ sk_invalidate();sk_render(&g,SK_PLAY,0,false,push);
+ assert(!memcmp(previous,screen,sizeof screen)); /* partial == full render */
+ for(unsigned t=0;t<120;++t) {
+ if(t%23==0)sk_aim(&g,(float)((t*47)%SK_WIDTH));
+ if(t%29==0)sk_drop(&g);
+ if(t%3)sk_step(&g);
+ sk_render(&g,SK_PLAY,0,false,push);memcpy(previous,screen,sizeof screen);
+ sk_invalidate();sk_render(&g,SK_PLAY,0,false,push);
+ assert(!memcmp(previous,screen,sizeof screen));
+ }
+ for(int k=1;k<=5;++k) {
+ g.next=(uint8_t)k;g.current=(uint8_t)k;g.cooldown=0;
+ g.score=g.best=UINT32_MAX;sk_aim(&g,k&1?0:SK_WIDTH);
+ sk_render(&g,SK_PLAY,0,false,push);memcpy(previous,screen,sizeof screen);
+ sk_invalidate();sk_render(&g,SK_PLAY,0,false,push);
+ assert(!memcmp(previous,screen,sizeof screen));
+ }
+ g.score=386;g.best=1284;
+ sk_render(&g,SK_PAUSE,0,false,push);shot("pause.ppm");
+ sk_render(&g,SK_HELP,0,false,push);shot("help.ppm");
+ g.over=1;sk_render(&g,SK_RESULT,0,false,push);shot("result.ppm");
+ sk_render(&g,SK_SAVE_ERROR,0,true,push);shot("save-error.ppm");
+}
+static void migration(void) {
+ sk_game g,h;uint8_t data[SK_SAVE_BYTES],copy[SK_SAVE_BYTES];
+ FILE *f=fopen("../tests/legacy-save.bin","rb");assert(f);
+ assert(fread(data,1,sizeof data,f)==sizeof data);fclose(f);
+ assert(!memcmp(data,"SKA1",4)&&sk_decode(&g,data,sizeof data));valid(&g);
+ assert(g.count==data[45]&&g.current==data[25]&&g.next==data[26]);
+ assert(g.score==(uint32_t)(data[4]|data[5]<<8|data[6]<<16|data[7]<<24));
+ sk_encode(&g,copy);assert(!memcmp(copy,"SKA2",4));
+ assert(sk_decode(&h,copy,sizeof copy));valid(&h);
+ assert(g.score==h.score&&g.best==h.best&&g.rng==h.rng&&g.count==h.count);
+ sk_encode(&h,data);assert(!memcmp(copy,data,sizeof data));
+ sk_new(&g,73,1284);sk_encode(&g,data);
+ f=fopen("start-save.bin","wb");assert(f);fwrite(data,1,sizeof data,f);fclose(f);
+}
+int main(void) {
+ physics();saves();stress();migration();screenshots();
+ printf("Suika: physics, save migration, five-rank generation and dirty rendering passed.\n");
+ return 0;
+}
diff --git a/games/suika/tests/test_compact_nwa.py b/games/suika/tests/test_compact_nwa.py
new file mode 100644
index 00000000..4874fac7
--- /dev/null
+++ b/games/suika/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/suika/tools/build.py b/games/suika/tools/build.py
new file mode 100644
index 00000000..78d9e424
--- /dev/null
+++ b/games/suika/tools/build.py
@@ -0,0 +1,89 @@
+#!/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 / 'suika-debug.nwa',
+ '--ld', tool('ld'))
+ run(sys.executable, packer, 'release', out / 'suika-debug.nwa',
+ out / 'SuikaGame.nwa', '--objcopy', tool('objcopy'))
+ shutil.copyfile(out / 'SuikaGame.nwa', out / 'suika.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 / 'SuikaGame.nwa', elf, *options)
+ run(*nw, 'nwa-bin', out / 'SuikaGame.nwa', binary, *options)
+ debug_binary = out / (name + '-debug.bin')
+ run(*nw, 'nwa-bin', out / 'suika-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 / 'SuikaGame.nwa').stat().st_size, save_bytes=608,
+ **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/suika/tools/compact_nwa.py b/games/suika/tools/compact_nwa.py
new file mode 100644
index 00000000..f320bb54
--- /dev/null
+++ b/games/suika/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/suika/tools/icon.py b/games/suika/tools/icon.py
new file mode 100644
index 00000000..4ed56325
--- /dev/null
+++ b/games/suika/tools/icon.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+"""Original procedural Suika icon. Run from any directory; requires Pillow."""
+from pathlib import Path
+from PIL import Image, ImageDraw
+
+S = 4
+im = Image.new('RGB', (55*S, 56*S), '#fcf4df')
+d = ImageDraw.Draw(im)
+
+
+def ellipse(box, fill, outline=None, width=1):
+ d.ellipse(tuple(int(v*S) for v in box), fill=fill, outline=outline, width=width*S)
+
+
+def line(points, fill, width=1):
+ d.line([(int(x*S), int(y*S)) for x, y in points], fill=fill, width=width*S)
+
+
+ellipse((6, 11, 50, 55), '#e6d4aa')
+ellipse((5, 8, 49, 52), '#64a66c', '#3c784b')
+for inset in (8, 15):
+ d.arc((int((5+inset)*S), 8*S, int((49-inset)*S), 52*S), 90, 270, fill='#3c784b', width=S)
+ d.arc((int((5+inset)*S), 8*S, int((49-inset)*S), 52*S), -90, 90, fill='#3c784b', width=S)
+ellipse((13, 16, 23, 24), '#c3dc9d')
+line([(27, 11), (28, 3)], '#796043', 2)
+ellipse((28, 2, 40, 8), '#477842')
+ellipse((18, 29, 21, 34), '#354c34')
+ellipse((33, 29, 36, 34), '#354c34')
+line([(25, 35), (27, 37), (29, 35)], '#354c34')
+ellipse((12, 35, 18, 38), '#e88d83')
+ellipse((37, 35, 43, 38), '#e88d83')
+im.resize((55, 56), Image.Resampling.LANCZOS).save(Path(__file__).resolve().parents[1] / 'src/icon.png')
diff --git a/games/suika/tools/standalone.ld b/games/suika/tools/standalone.ld
new file mode 100644
index 00000000..28679582
--- /dev/null
+++ b/games/suika/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) }
+}
diff --git a/tests/test_games.py b/tests/test_games.py
index 3a18a000..961c137a 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -42,6 +42,10 @@ def every(t0, t1, step, key, d=80):
# name: (nwa, save record, first run keys, home time, second run keys, home time)
GAMES = {
+ "suika": ("SuikaGame.nwa", "suika.sav",
+ presses((500, "ok"), (1000, "ok"), (1800, "1"), (2300, "right", 180),
+ (2800, "ok"), (3600, "2"), (4000, "ok")), 5500,
+ presses((500, "ok"), (1000, "left", 200), (1700, "ok")), 3500),
"crossyroad": ("CrossyRoad.nwa", "crossyroad.sav",
every(1500, 9000, 350, "up"), 12000, every(1500, 4000, 400, "up"), 6000),
"chess": ("NumChess.nwa", "numchess.sav", presses((1500, "ok"), (2500, "ok")), 4000, [], 2500),
@@ -169,6 +173,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"hollowknight": "hollowknight_saves.py", "finalearth2": "finalearth2_saves.py",
"numpowder": "numpowder_saves.py", "undertale": "undertale_saves.py"}
CHECKS = {
+ "suika": (lambda v: len(v) == 608 and v[:4] == b"SKA2" and v[33] == 1 and v[45] >= 1,) * 2,
# the island remembers where Lucky was; after the reinstall, from the copy
"championisland": (lambda v: v[:3] == b"CI1" and b"PLAYER_LOC" in v,) * 2,
"numdrive": (lambda v: v[27] == 1, lambda v: v[27] == 0), # last played level
diff --git a/tests/test_suika.py b/tests/test_suika.py
new file mode 100644
index 00000000..66666034
--- /dev/null
+++ b/tests/test_suika.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""Suika's actual ARM app: pause/reload, low-RAM profiles and full-storage exits.
+
+python tests/test_suika.py games/suika/output/suika-debug.nwa --nwlink nwlink
+Run the Suika host suite first to generate the scene fixture.
+Unstripped builds also report emulator render timings (not hardware benchmarks).
+"""
+import argparse
+import json
+import io
+import tempfile
+import types
+import os
+from pathlib import Path
+import struct
+import sys
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tools'))
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_games import records, presses # noqa: E402
+# Load ELF bytes before nwlink replaces its temporary file (Windows locking).
+# Stop on a completed sleep so static menus cannot skip a test checkpoint.
+emu_path=Path(__file__).resolve().parents[1]/'tools/emu.py'
+emu=types.ModuleType('suika_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()))')
+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')
+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 storage(path, items):
+ data = bytearray(emu.STORAGE_SIZE)
+ offset = 0
+ for name, value in items:
+ record = name.encode('ascii') + b'\0' + value
+ size = 2 + len(record)
+ struct.pack_into('<H', data, offset, size)
+ data[offset + 2:offset + size] = record
+ offset += size
+ assert offset + 2 <= len(data)
+ path.write_bytes(data)
+
+
+def live_records(c):
+ return dict(records(bytes(c.uc.mem_read(emu.STORAGE + 4, emu.STORAGE_SIZE))))
+
+
+def check_exit(c, upsilon=False):
+ assert c.exited, 'App did not exit'
+ assert not c.violations, sorted(set(c.violations))
+ assert not c.firmware_ram_changes(), 'Firmware RAM changed'
+ assert c.app_ram_clean(), 'Application RAM was not cleared'
+ assert c.locks == 0 and c.max_locks == (0 if upsilon else 1), 'Home lock imbalance'
+ assert c.stack_used() < 8192, c.stack_used()
+ if upsilon:
+ assert not any(c.svc_counts.get(n) for n in (10, 13, 15, 16, 30, 32))
+
+
+def seed_basket():
+ p = bytearray(608)
+ p[:4] = b'SKA1'
+ struct.pack_into('<4I', p, 4, 123, 777, 73, 12)
+ struct.pack_into('<HH', p, 20, 97 * 64, 0)
+ p[25:29] = bytes([3, 1, 2, 4])
+ p[29] = 2
+ p[31] = 6
+ p[33:35] = bytes([1, 4])
+ p[35:43] = bytes([1, 1, 1, 2, 2, 3, 3, 4])
+ p[45] = 48
+ for i in range(48):
+ struct.pack_into('<BhhhhH', p, 48 + 11 * i, 1, (14 + i % 8 * 22) * 64,
+ (76 + i // 8 * 16) * 64, 0, 0, 240)
+ h = 2166136261
+ for b in p[:-4]:
+ h = ((h ^ b) * 16777619) & 0xffffffff
+ struct.pack_into('<I', p, 604, h)
+ return p
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('nwa')
+ ap.add_argument('--nwlink', default='nwlink')
+ ap.add_argument('--out', type=Path, default=Path('build/test_suika'))
+ a = ap.parse_args()
+ a.out.mkdir(parents=True, exist_ok=True)
+ tempfile.tempdir=str(a.out.resolve())
+ report = []
+ sentinel = b'\x01print(42)\n\0'
+ 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)
+ st = a.out / (name + '.bin')
+ storage(st, [('keep.py', sentinel)])
+ c = emu.Calculator(a.nwa, storage_file=str(st), nwlink=a.nwlink)
+ c.enable_checks()
+ c.keys = presses((500, 'ok', 60), (1000, 'ok', 60), (1150, 'back', 60),
+ (3400, 'back', 60), (3550, 'back', 60), (4700, 'home', 200))
+ c.run(2200)
+ first = live_records(c)['suika.sav']
+ age0 = struct.unpack_from('<H', first, 57)[0]
+ c.run(3300)
+ assert live_records(c)['suika.sav'] == first, 'Pause changed the saved basket'
+ c.run(4100)
+ second = live_records(c)['suika.sav']
+ age1 = struct.unpack_from('<H', second, 57)[0]
+ assert 5 <= age1 - age0 <= 15, ('Paused time caught up', age0, age1)
+ c.save_png(str(a.out / (name + '-pause.png')))
+ c.run(5500)
+ check_exit(c, system == 'upsilon')
+ recs = dict(records(st.read_bytes()))
+ assert recs['keep.py'] == sentinel
+ kept = recs['suika.sav']
+ # Continue from disk and immediately pause: no drop was fabricated.
+ d = emu.Calculator(a.nwa, storage_file=str(st), nwlink=a.nwlink)
+ d.enable_checks()
+ d.keys = presses((500, 'ok', 60), (650, 'back', 60), (1100, 'onoff', 200))
+ d.run(2000)
+ check_exit(d, system == 'upsilon')
+ resumed = dict(records(st.read_bytes()))['suika.sav']
+ assert resumed[45] == kept[45] and resumed[4:20] == kept[4:20]
+ report.append(dict(profile=name, pause_reload_exit='pass', stack_bytes=max(c.stack_used(), d.stack_used())))
+
+ emu.configure('n0110', 'epsilon', 148928)
+ st = a.out / 'full.bin'
+ filler = bytes([0x5a]) * (emu.STORAGE_SIZE - 32)
+ storage(st, [('full.dat', filler)])
+ c = emu.Calculator(a.nwa, storage_file=str(st), nwlink=a.nwlink)
+ c.enable_checks()
+ c.keys = presses((500, 'ok', 60), (800, 'ok', 60), (1200, 'home', 200),
+ (1900, '1', 60), (2400, 'home', 200), (3000, 'back', 100))
+ c.run(1800)
+ assert not c.exited, 'Save failure was silently discarded'
+ assert 'suika.sav' not in live_records(c)
+ c.save_png(str(a.out / 'save-failed.png'))
+ error_screen = bytes(c.screen)
+ c.run(2200)
+ assert not c.exited and bytes(c.screen) != error_screen, 'Could not cancel a failed exit'
+ c.run(4000)
+ check_exit(c)
+ assert dict(records(st.read_bytes()))['full.dat'] == filler
+
+ # Dense 48-body basket, to exercise bounded physics and rendering in ARM.
+ st = a.out / 'dense.bin'
+ storage(st, [('keep.py', sentinel), ('suika.sav', seed_basket())])
+ c = emu.Calculator(a.nwa, storage_file=str(st), nwlink=a.nwlink)
+ c.enable_checks()
+ c.keys = presses((500, 'ok', 60), (3000, 'home', 200))
+ c.run(2500)
+ timing = {}
+ for key in ('perf_frames', 'perf_max', 'perf_slow'):
+ if key in c.symbols:
+ timing[key] = struct.unpack('<I', bytes(c.uc.mem_read(c.symbols[key], 4)))[0]
+ if timing:
+ assert timing['perf_max'] <= 32 and timing['perf_slow'] == 0, timing
+ c.save_png(str(a.out / 'dense.png'))
+ c.run(4000)
+ check_exit(c)
+ assert dict(records(st.read_bytes()))['keep.py'] == sentinel
+ report.append(dict(dense_basket='pass', full_storage='pass', emulator_timing=timing, stack_bytes=c.stack_used()))
+ # Import a real SKA1 basket, then write SKA2 without losing progress.
+ fixtures=Path(__file__).resolve().parents[1]/'games/suika'
+ old=(fixtures/'tests/legacy-save.bin').read_bytes()
+ st=a.out/'legacy.bin';storage(st,[('keep.py',sentinel),('suika.sav',old)])
+ c=emu.Calculator(a.nwa,storage_file=str(st),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((500,'home',100));c.run(1000);check_exit(c)
+ migrated=dict(records(st.read_bytes()))['suika.sav']
+ assert migrated[:4]==b'SKA2' and migrated[4:20]==old[4:20]
+ assert migrated[25:27]==old[25:27] and migrated[45]==old[45]
+ assert not any(migrated[27:31]+migrated[34:45])
+ assert dict(records(st.read_bytes()))['keep.py']==sentinel
+ # Render the new scene on the actual ARM app. Removed 1/2 actions must not
+ # consume randomness, exchange the held fruit, or move the dropper.
+ st=a.out/'scene.bin';scene=(fixtures/'output/scene-save.bin').read_bytes()
+ storage(st,[('keep.py',sentinel),('suika.sav',scene)])
+ c=emu.Calculator(a.nwa,storage_file=str(st),nwlink=a.nwlink);c.enable_checks()
+ c.keys=presses((500,'ok',60),(700,'1',60),(850,'2',60),(1100,'back',60),
+ (1400,'home',100))
+ c.run(300);c.save_png(str(a.out/'title.png'))
+ c.run(650);c.save_png(str(a.out/'game.png'))
+ c.run(1250)
+ saved=live_records(c)['suika.sav']
+ assert saved[12:16]==scene[12:16] and saved[20:22]==scene[20:22]
+ assert saved[25:27]==scene[25:27] and not any(saved[27:31]+saved[34:45])
+ c.run(1800);check_exit(c)
+ report.append(dict(legacy_migration='pass',removed_keys='pass',scene_stack_bytes=c.stack_used()))
+ (a.out / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
+ print(json.dumps(report, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/release.py b/tools/release.py
index 07a8754a..99e92363 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -46,7 +46,7 @@ LANGUAGES = [
("NumPlay-French.nwa", "NumPlay en français : tous les jeux, en français"),
("NumPlay-Chinese.nwa", "NumPlay 中文版:所有游戏,简体中文"),
]
-UPSILON = ("NumPlay-Upsilon.nwa", "For calculators running Upsilon (N0110, N0115): the 15 games that fit in the memory "
+UPSILON = ("NumPlay-Upsilon.nwa", "For calculators running Upsilon (N0110, N0115): the 16 games that fit in the memory "
"Upsilon gives apps. Install it with nwlink, see the README")