Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Suika Game: drop the fruit, join two of a kind, inside NumPlay
Mason3635130d866129b
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex c0127f6b..8da657ef 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -77,6 +77,7 @@ jobs:make -C games/sokoban host testmake -C games/flappydunk host testmake -C games/towerblock host test+ make -C games/suika host testdiff --git a/Makefile b/Makefileindex d40f9e7b..1b5c4271 100644--- a/Makefile+++ b/Makefile@@ -30,7 +30,7 @@ APP_SPACE = 2031616# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)UPSILON_RAM = 107674-UPSILON_GAMES = crossyroad blockblast portal tetris dinorun chess flappybird flappydunk towerblock pacman snake connectfour solitaire g2048 minesweeper \+UPSILON_GAMES = crossyroad blockblast suika portal tetris dinorun chess flappybird flappydunk towerblock pacman snake connectfour solitaire g2048 minesweeper \breakout twoplayer invaders sudoku uttt sokoban# NumPlay and its discreet versions: the same app, with another name and icondiff --git a/docs/media/thumb_suika.png b/docs/media/thumb_suika.pngdeleted file mode 100644index 53c06287..00000000Binary files a/docs/media/thumb_suika.png and /dev/null differdiff --git a/games/games.json b/games/games.jsonindex 33ec68ed..b57fcdf5 100644--- a/games/games.json+++ b/games/games.json@@ -159,6 +159,24 @@"app": "BlockBlast.nwa","repo": "https://github.com/Mason363/NumPlay/tree/main/games/blockblast"},+ {+ "id": "suika",+ "title": "Suika Game",+ "tagline": "Merge the fruit into a watermelon",+ "credit": "Based on Suika Game by Aladdin X",+ "top": "0xF2C46A",+ "bottom": "0x9A5A22",+ "accent": "0x6CC530",+ "colors": 16,+ "records": [+ "suika.sav"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "app": "SuikaGame.nwa",+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/suika"+ },{"id": "portal","title": "Portal Returns",diff --git a/games/suika/.gitignore b/games/suika/.gitignoreindex 16be8f21..79fafc9f 100644--- a/games/suika/.gitignore+++ b/games/suika/.gitignore@@ -1 +1,2 @@/output/+/build/diff --git a/games/suika/Makefile b/games/suika/Makefileindex a1678f67..1d760f92 100644--- a/games/suika/Makefile+++ b/games/suika/Makefile@@ -1,51 +1,84 @@-# Suika: English-only app and NumPlay module.+# Suika Game: drop the fruit, join two of a kind, up to the watermelon.+# make build output/suika.nwa+# make check link the app like the calculator does (output/suika.bin)+#+# In NumPlay the game draws with the launcher's strips, shapes and fonts and saves through its+# file functions (module.o leaves them to the launcher); on its own it brings them along.+Q ?= @CC = arm-none-eabi-gccNWLINK ?= npx --yes -- [email protected]-PYTHON ?= python3-ARM_LD ?= arm-none-eabi-ld-OBJCOPY = arm-none-eabi-objcopy-PACKER = tools/compact_nwa.py tools/standalone.ld-SRC = src/main.c src/physics.c src/save.c src/render.c-HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h-OBJECTS = $(patsubst src/%.c,output/%.o,$(SRC))-CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device) -Os -Wall -Wextra -Werror-CFLAGS += -fno-math-errno -fsingle-precision-constant -ffunction-sections -fdata-sections -fstack-usage-CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fvisibility=internal-LINK = -nostartfiles --specs=nano.specs -Wl,--relocatable,--gc-sections,-e,main -flinker-output=nolto-rel--.PHONY: build check module sim-module test clean-build: output/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+BUILD_DIR = output+SRC = src/main.c+L = ../../launcher/src+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h $(L)/gfx.h $(L)/np.h $(L)/font.h++CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean+build: $(BUILD_DIR)/suika.nwa++check: $(BUILD_DIR)/suika.nwa+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/suika.bin+ @echo "BIN $(BUILD_DIR)/suika.bin: $$(wc -c < $(BUILD_DIR)/suika.bin) bytes"++# compiled, then linked (the link options would upset the compiler)+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ @echo "CC $<"+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@+$(BUILD_DIR)/gfx.o: $(L)/gfx.c $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@+$(BUILD_DIR)/icons.o: $(L)/icons.c $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@+$(BUILD_DIR)/font_data.o: $(L)/font_data.c $(L)/font.h | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@+$(BUILD_DIR)/xfont.o: $(L)/xfont.c $(L)/np_xfont.h $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@++$(BUILD_DIR)/suika.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/icons.o $(BUILD_DIR)/font_data.o \+ $(BUILD_DIR)/xfont.o $(BUILD_DIR)/icon.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@+ $(Q) arm-none-eabi-strip --strip-unneeded $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@+clean:- rm -rf output+ $(Q) rm -rf $(BUILD_DIR) build++# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the+# calculator, and as a relocatable object for the simulator build.+.PHONY: module sim-module+module: $(BUILD_DIR)/module.o+$(BUILD_DIR)/module-main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(CFLAGS) -DNP_MODULE=1 -c $(SRC) -o $@+$(BUILD_DIR)/module.o: $(BUILD_DIR)/module-main.o+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@++sim-module: $(BUILD_DIR)/sim-module.o+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ $(Q) mkdir -p $(BUILD_DIR)/sim+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -DNP_MODULE=1 -Dmain=np_suika_main \+ -c $(SRC) -o $(BUILD_DIR)/sim/main.o+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_suika_main -o $@++# on a computer, with the sanitizers: a bot plays 300 games (tests/play.c)+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -DPLATFORM_DEVICE=1 -DHOST \+ $(shell $(NWLINK) eadk-cflags-simulator) -fsanitize=address,undefined -fno-sanitize-recover=undefined+.PHONY: host test+host: build/play+build/play: $(SRC) tests/play.c $(HEADERS)+ $(Q) mkdir -p build+ $(Q) cc $(HOST_FLAGS) tests/play.c $(L)/gfx.c $(L)/icons.c $(L)/font_data.c $(L)/xfont.c -lm -o $@+ @echo "HOST $@"+test: build/play+ build/play testdiff --git a/games/suika/README.md b/games/suika/README.mdindex 224353ba..83b040a2 100644--- a/games/suika/README.md+++ b/games/suika/README.md@@ -1,89 +1,30 @@# 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.+Drop fruit in the box and join two of a kind into the next one, all the way to the watermelon. Aladdin X's Suika Game for the NumWorks calculator, playing and looking like the Switch game.-**Game made by [Bobydeluxe](https://github.com/Bobydeluxe).**+<img src="docs/shot.png" width="320" alt="A game of Suika Game: a melon, a pineapple and apples in the box, the cloud holding a grape">--+- **The 11 fruit**, cherry to watermelon, at the original's sizes and colours, with their faces. Drops come from the first five, each as likely as the others.+- **Two of a kind join** where they touch, into the next fruit of the circle. Two watermelons vanish. Each merge scores as in the original: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, and 66 for two watermelons.+- **The original's physics.** Fruit fall, roll and stack as on the Switch, measured frame by frame: the same gravity, no bounce, and the next fruit comes the moment the last one touches down.+- **Over the top and it's over.** A fruit that stays above the box for about a second ends the game.+- The cloud, the Next bubble and the circle of evolution, as in the original.+- Your game and best score are saved, so you can stop and carry on later.++## Controls| 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:+| Left and Right, or 4 and 6 | Move the cloud |+| OK or EXE | Drop the fruit |+| Back | Menu: Resume, Restart, How to play, Quit |-```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-```+## Credits-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:+Suika Game is **Aladdin X**'s game (2021). **[Bobydeluxe](https://github.com/Bobydeluxe)** brought it to NumPlay. This version is written in C for NumPlay with no code or art from the original. Its fruit sizes, colours, speeds and timings were measured on the Switch version, with the sizes checked against [kairess/suika-game](https://github.com/kairess/suika-game) and players' measurements.-```sh-python games/suika/tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink-```+Inside NumPlay it draws with the launcher's own shapes and fonts and saves through its file functions, so the game itself is about 9 KB.-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`.+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `SuikaGame.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).-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.+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink). Tests: `make test`.diff --git a/games/suika/VALIDATION.md b/games/suika/VALIDATION.mddeleted file mode 100644index 43b40924..00000000--- a/games/suika/VALIDATION.md+++ /dev/null@@ -1,54 +0,0 @@-# 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.pngdeleted file mode 100644index 53c7090d..00000000Binary files a/games/suika/docs/menu.png and /dev/null differdiff --git a/games/suika/docs/shot.png b/games/suika/docs/shot.pngindex 2081ade9..1b298570 100644Binary files a/games/suika/docs/shot.png and b/games/suika/docs/shot.png differdiff --git a/games/suika/docs/title.png b/games/suika/docs/title.pngdeleted file mode 100644index 9b153e49..00000000Binary files a/games/suika/docs/title.png and /dev/null differdiff --git a/games/suika/lang/fr.txt b/games/suika/lang/fr.txtnew file mode 100644index 00000000..39a1bc5c--- /dev/null+++ b/games/suika/lang/fr.txt@@ -0,0 +1,23 @@+# Suika Game in French: the English text as in the source, a tab, the translation (see tools/lang.py).+Score Score+Best score Record+Next Suivant+Circle of Cercle+Evolution d'évolution+Move Bouger+Drop Lâcher+Back Retour+Menu Menu+Resume Reprendre+Restart Recommencer+How to play Comment jouer+Quit Quitter+No Non+Yes Oui+Play Jouer+Paused Pause+Start again? Recommencer ?+New best! Nouveau record !+Game over Partie terminée+Move the cloud with the arrows and drop the fruit with OK. Two of the same fruit that touch join into the next one, up to the watermelon. If fruit stays above the box, it's over. Déplace le nuage avec les flèches et lâche le fruit avec OK. Deux fruits pareils qui se touchent deviennent le suivant, jusqu'à la pastèque. Si un fruit reste au-dessus de la boîte, c'est fini.+Best Recorddiff --git a/games/suika/lang/zh.txt b/games/suika/lang/zh.txtnew file mode 100644index 00000000..2c67d7fb--- /dev/null+++ b/games/suika/lang/zh.txt@@ -0,0 +1,23 @@+# Suika Game in Chinese: the English text as in the source, a tab, the translation (see tools/lang.py).+Score 分数+Best score 最高分+Next 下一个+Circle of 进化+Evolution 之轮+Move 移动+Drop 放下+Back 返回+Menu 菜单+Resume 继续+Restart 重新开始+How to play 玩法+Quit 退出+No 否+Yes 是+Play 开始+Paused 暂停+Start again? 重新开始?+New best! 新纪录!+Game over 游戏结束+Move the cloud with the arrows and drop the fruit with OK. Two of the same fruit that touch join into the next one, up to the watermelon. If fruit stays above the box, it's over. 用方向键移动云朵,按 OK 放下水果。两个相同的水果碰到一起会合成下一种,一直到西瓜。水果停在箱子上方,游戏就结束了。+Best 最高diff --git a/games/suika/src/icon.png b/games/suika/src/icon.pngindex d1def873..03c9feff 100644Binary files a/games/suika/src/icon.png and b/games/suika/src/icon.png differdiff --git a/games/suika/src/main.c b/games/suika/src/main.cindex baf65a27..ac393eb2 100644--- a/games/suika/src/main.c+++ b/games/suika/src/main.c@@ -1,124 +1,627 @@-/* SPDX-License-Identifier: GPL-3.0-only */+/* Suika Game: drop fruit in the box; two of a kind that touch join into the next one, up to the watermelon.+ *+ * Aladdin X's Suika Game as it plays on the Nintendo Switch. The cloud carries a fruit along the top of the+ * box and OK drops it; the next one comes the moment it touches something. Fruit fall, roll and stack as+ * the original's physics makes them (Unity's Box2D at 50 steps a second: no bounce, friction 0.4, mass by+ * area, still fruit asleep), two of a kind that touch become the next fruit where they met, two+ * watermelons vanish, and a fruit that stays above the box for about a second ends the game. The sizes,+ * colours, speeds and timings were measured on the Switch version (gamesrc/suika/spec): the physics runs+ * in its 720p pixels, drawn at a third of that.+ *+ * Inside NumPlay it draws with the launcher's strips, shapes and fonts (launcher/src/gfx.c) and saves+ * through its file functions; on its own (SuikaGame.nwa) it brings them along.+ *+ * Made by Bobydeluxe and Mason Chen as part of NumPlay. */#include <eadk.h>-#include "suika.h"-#include "render.h"+#include "../../../launcher/src/gfx.h"+#include "../../common/np_text.h"++#if NP_MODULE /* (np_file_read and np_file_write: NumPlay's, launcher/src/np.h) */+#define np_app_begin()+#define np_app_end() 0+#else#include "../../common/epsilon_app.h"#include "../../common/epsilon_files.h"--#ifdef __ELF__+#define np_file_read ef_read+#define np_file_write ef_write+#ifndef HOST /* (a computer build of the tests has no app header) */const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Suika Game";const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;#endif-#define KEY(k) (UINT64_C(1) << (k))+void np_push(int x, int y, int w, int h, const color_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);+}+#endif++#define KEY(k) (1ull << (k))+#define INK HEX(0x7A4A1E)++/* ------------------------------------------------------------ the original's numbers (its 720p pixels, seconds) */+#define W 448.0f /* the box inside, wall to wall */+#define FLOOR 564.0f /* its floor, below the line at its top (y = 0) */+#define HANG -16.5f /* where the cloud holds a fruit's centre */+#define GRAV 1450.0f /* gravity, px/s^2 */+#define DT 0.02f /* Unity's physics step */+#define MU 0.4f /* friction (Unity's default material, bounciness 0) */+#define CLOUD 5.8f /* the cloud's move in a step: 290 px/s */+#define OVER_STEPS 47 /* above the line this long (0.94 s) and the game is over */+#define SLOP 0.75f /* Box2D's linear slop, the overlap resting fruit keep */+#define BETA 0.4f /* position correction per iteration */+#define STILL 3.0f /* slower than this (px/s) for half a second: asleep */+/* the fruit: cherry, strawberry, grape, dekopon, persimmon, apple, pear, peach, pineapple, melon, watermelon;+ and 0, the cloud's colours */+static const uint16_t diam[12] = {0, 33, 44, 61, 70, 89, 113, 130, 158, 178, 219, 259};+#define RAD(k) (diam[k] * 0.5f)+static const color_t fill_c[12] = {HEX(0xFFF0A0), HEX(0xEE0A0A), HEX(0xFB5E4A), HEX(0xA86AFC), HEX(0xFFB000), HEX(0xFC8414),+ HEX(0xF01818), HEX(0xFFF07A), HEX(0xFFC0BA), HEX(0xF6E21C), HEX(0x98D418), HEX(0x22A412)};+static const color_t line_c[12] = {HEX(0xF0C45A), HEX(0xA80406), HEX(0xE01E1A), HEX(0x6A1CE6), HEX(0xE07C06), HEX(0xEE5E0C),+ HEX(0xC00808), HEX(0xEAB824), HEX(0xF0786A), HEX(0xE2A60E), HEX(0x4E9C12), HEX(0x0A4A04)};+static const color_t face_c[12] = {HEX(0x5A3A2A), HEX(0x6A0000), HEX(0x8A1410), HEX(0x3C0A90), HEX(0xFFF3C4), HEX(0xA0300C),+ HEX(0x7A0606), HEX(0x8E6418), HEX(0xC21C1C), HEX(0x8E5210), HEX(0x2E6A0E), HEX(0x042A00)};++/* on screen: a third of the original, the box's inside from x = 85.3 to 234.7, its top line at y = 36.7 */+#define SX(x) (85.333f + (x) * (1 / 3.0f))+#define SY(y) (36.667f + (y) * (1 / 3.0f))++#define MAXF 64+#define MAXC 256+#define WALL MAXF /* f[WALL], f[WALL + 1], f[WALL + 2]: the walls and the floor, as huge circles that never move */+#define BIG 65536.0f+typedef struct {+ float x, y, vx, vy, c, s, w; /* where, how fast, turned how far (cos, sin) and how fast */+ uint8_t k, land, over, still, zz; /* kind, has touched something, steps above the line, still, asleep */+} fruit_t;+typedef struct {+ uint8_t a, b;+ float nx, ny, pn, pt; /* from a to b; the impulses so far (kept for the next step) */+} contact_t;+static fruit_t f[WALL + 3];+static float rad[WALL + 3], inv[WALL + 3]; /* radius and 1 / mass (by area), for this step */+static contact_t con[2][MAXC];+static int ncon[2], cb;++/* suika.sav: the best, and the game in progress */+enum { GAME = 1, SEEN = 2, HELD = 4 };+typedef struct {+ int16_t v[7]; /* x, y, vx, vy, c, s, w, times scale[] */+ uint8_t k, land;+} packed_t;+static struct {+ uint8_t magic, version, flags, cur; /* cur: the fruit in (or coming to) the cloud */+ uint8_t next, drop, pad[2]; /* drop: the falling fruit + 1 */+ uint32_t sum; /* of the words after it: a damaged file starts afresh */+ uint32_t best, score, rng;+ float aim;+ packed_t p[MAXF];+} sv;#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 const float scale[7] = {8, 8, 4, 4, 16384, 16384, 64};++static color_t strip[SCREEN_W * STRIP_H];+static uint32_t now, over_t, best0;+static bool over;+static int ov, sel;+enum { OV_NONE, OV_MENU, OV_SURE, OV_HELP, OV_OVER };++static float sqrt_(float v) { return __builtin_sqrtf(v); }+#define fminf_ __builtin_fminf+#define fmaxf_ __builtin_fmaxf+static float clampf(float v, float a, float b) { return fminf_(fmaxf_(v, a), b); }+static float frac(float v) { return v - (float)(int)v; }+static uint32_t rnd(void) {+ uint32_t x = sv.rng;+ x ^= x << 13, x ^= x >> 17, x ^= x << 5;+ return sv.rng = x;}+static uint8_t drop_kind(void) { return (uint8_t)(rnd() % 5 + 1); }+static char *num(char *o, uint32_t v) {+ char t[10];+ int n = 0;+ do t[n++] = (char)('0' + v % 10); while (v /= 10);+ while (n) *o++ = t[--n];+ *o = 0;+ return o;+}++/* ------------------------------------------------------------ the rules */+static uint32_t checksum(void) {+ uint32_t h = 0x811C9DC5u;+ for (const uint32_t *w = &sv.sum + 1; w < (const uint32_t *)(&sv + 1); w++) h = (h ^ *w) * 0x01000193u;+ return h;+}+static void unpack(void) {+ for (int i = 0; i < MAXF; i++) {+ float *a = &f[i].x;+ for (int j = 0; j < 7; j++) a[j] = sv.p[i].v[j] / scale[j];+ f[i].k = sv.p[i].k > 11 ? 0 : sv.p[i].k, f[i].land = sv.p[i].land;+ }+}+static void save(void) {+ for (int i = 0; i < MAXF; i++) {+ float *a = &f[i].x;+ for (int j = 0; j < 7; j++) sv.p[i].v[j] = (int16_t)clampf(a[j] * scale[j], -32767, 32767);+ sv.p[i].k = f[i].k, sv.p[i].land = f[i].land;+ }+ unpack(); /* (what goes on is what was saved) */+ sv.magic = 'S', sv.version = 1, sv.sum = checksum();+ np_file_write(SAVE_NAME, &sv, sizeof sv);+}++static void aim_at(float x) { sv.aim = clampf(x, RAD(sv.cur), W - RAD(sv.cur)); }++static void new_game(void) {+ for (int i = 0; i < MAXF; i++) f[i].k = 0;+ if (!sv.rng) sv.rng = 0x2545F491u;+ sv.score = 0, sv.drop = 0, sv.flags |= GAME | HELD;+ sv.cur = drop_kind(), sv.next = drop_kind();+ aim_at(W / 2);+ over = false, best0 = sv.best;+}++/* the dropped fruit touched something: the next one comes to the cloud */+static void landed(void) {+ f[sv.drop - 1].land = 1;+ sv.drop = 0, sv.flags |= HELD;+ sv.cur = sv.next, sv.next = drop_kind();+ aim_at(sv.aim);+}++static void drop_fruit(void) {+ if (!(sv.flags & HELD) || over) return;+ for (int i = 0; i < MAXF; i++)+ if (!f[i].k) {+ f[i] = (fruit_t){sv.aim, HANG, 0, 0, 1, 0, 0, sv.cur, 0, 0, 0, 0};+ sv.drop = (uint8_t)(i + 1), sv.flags &= (uint8_t)~HELD;+ return;+ }+}++/* b, for a contact with a: a wall or the floor is moved to face a */+static fruit_t *body(int a, int b) {+ fruit_t *p = &f[b];+ int w = b - WALL;+ if (w >= 0) p->k = 12, p->zz = 1, p->x = w == 2 ? f[a].x : w ? W + BIG : -BIG, p->y = w == 2 ? FLOOR + BIG : f[a].y;+ return p;+}++static void radius(int i) { rad[i] = i < WALL ? RAD(f[i].k) : BIG, inv[i] = i < WALL && f[i].k ? 1 / (rad[i] * rad[i]) : 0; }++/* two of a kind touched: the next fruit where they met, at rest; two watermelons both go */+static void merge(int i, int j) {+ int k = f[i].k;+ sv.score += (uint32_t)(k * (k + 1) / 2); /* 1, 3, 6 ... 55, and 66 for two watermelons */+ if (sv.score > sv.best) sv.best = sv.score;+ if (sv.drop - 1 == i || sv.drop - 1 == j) landed();+ f[j].k = 0;+ f[i] = (fruit_t){(f[i].x + f[j].x) / 2, (f[i].y + f[j].y) / 2, 0, 0, 1, 0, 0, (uint8_t)(k < 11 ? k + 1 : 0), 1, 0, 0, 0};+ radius(i), radius(j);+}++/* the contacts: every fruit against those after it, then the walls and the floor (so they come out in+ order, to find last step's impulses); two of a kind merge instead */+static void collide(void) {+ contact_t *c = con[cb ^ 1], *o = con[cb];+ int n = 0, on = ncon[cb], oi = 0, d = sv.drop - 1;+ bool touched = false;+ uint64_t merged = 0;+ for (int i = 0; i < MAXF; i++)+ for (int j = i + 1; j < WALL + 3 && f[i].k; j++) {+ fruit_t *a = &f[i], *b = body(i, j);+ if (!b->k) continue;+ float rs = rad[i] + rad[j], dx = b->x - a->x, dy = b->y - a->y;+ if (dx > rs || dx < -rs || dy > rs || dy < -rs) continue;+ float d2 = dx * dx + dy * dy, l = sqrt_(d2);+ if (d2 >= rs * rs) continue;+ if (a->k == b->k && !((merged >> i | merged >> j) & 1)) {+ merged |= 1ull << i | 1ull << j;+ merge(i, j);+ continue;+ }+ touched |= i == d || j == d;+ int key = i << 7 | j;+ while (oi < on && (o[oi].a << 7 | o[oi].b) < key) oi++;+ bool kept = oi < on && (o[oi].a << 7 | o[oi].b) == key;+ if (n < MAXC) c[n++] = (contact_t){(uint8_t)i, (uint8_t)j, l > 1e-3f ? dx / l : 0, l > 1e-3f ? dy / l : 1, kept ? o[oi].pn : 0, kept ? o[oi].pt : 0};+ }+ if (touched && sv.drop) landed();+ cb ^= 1, ncon[cb] = n;+}++/* an impulse along the normal (pn) and the tangent (pt), on b and back on a; the tangent one turns them */+static void impulse(contact_t *c, float pn, float pt) {+ fruit_t *a = &f[c->a], *b = &f[c->b];+ float px = pn * c->nx - pt * c->ny, py = pn * c->ny + pt * c->nx, ia = inv[c->a], ib = inv[c->b];+ a->vx -= px * ia, a->vy -= py * ia, a->w -= pt * 2 * ia / rad[c->a];+ b->vx += px * ib, b->vy += py * ib, b->w -= pt * 2 * ib / rad[c->b];+}++static bool live(const contact_t *c) { return f[c->a].k && f[c->b].k && !(f[c->a].zz && f[c->b].zz); }++static uint8_t root(uint8_t *up, int i) {+ while (up[i] != i) i = up[i] = up[up[i]];+ return (uint8_t)i;+}++/* a fiftieth of a second, as Box2D steps: forces, contacts, 8 velocity and 3 position iterations, then+ islands of still fruit go to sleep */+static void step(void) {+ if (over) return;+ for (int i = 0; i < WALL + 3; i++) radius(i);+ collide();+ contact_t *cs = con[cb];+ int n = ncon[cb];+ uint8_t up[MAXF], least[MAXF], awake[MAXF];+ /* islands: fruit touching each other; one awake wakes them all */+ for (int i = 0; i < MAXF; i++) up[i] = (uint8_t)i, least[i] = 255, awake[i] = 0;+ for (int i = 0; i < n; i++)+ if (cs[i].b < WALL && f[cs[i].a].k && f[cs[i].b].k) up[root(up, cs[i].a)] = root(up, cs[i].b);+ for (int i = 0; i < MAXF; i++) awake[root(up, i)] |= f[i].k && !f[i].zz;+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ if (!a->k || !awake[root(up, i)]) continue;+ if (a->zz) a->zz = a->still = 0;+ a->vy += GRAV * DT, a->w *= 0.999f; /* Unity's angular drag, 0.05 */+ }+ for (int it = -1; it < 8; it++)+ for (int i = 0; i < n; i++) {+ contact_t *c = &cs[i];+ if (!live(c)) continue;+ fruit_t *a = &f[c->a], *b = &f[c->b];+ float m = inv[c->a] + inv[c->b], vn;+ if (it < 0) { /* last step's impulses again */+ impulse(c, c->pn, c->pt);+ continue;+ }+ /* friction first, up to MU times the push */+ float vt = (b->vy - a->vy) * c->nx - (b->vx - a->vx) * c->ny - a->w * rad[c->a] - b->w * rad[c->b];+ float lim = MU * c->pn, pt = clampf(c->pt - vt / (3 * m), -lim, lim);+ impulse(c, 0, pt - c->pt), c->pt = pt;+ vn = (b->vx - a->vx) * c->nx + (b->vy - a->vy) * c->ny;+ float pn = c->pn - vn / m;+ if (pn < 0) pn = 0;+ impulse(c, pn - c->pn, 0), c->pn = pn;+ }+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ if (!a->k || a->zz) continue;+ a->x += a->vx * DT, a->y += a->vy * DT;+ float t = a->w * DT, c = a->c - a->s * t, s = a->s + a->c * t, m = 1 / sqrt_(c * c + s * s);+ a->c = c * m, a->s = s * m;+ }+ for (int it = 0; it < 3; it++)+ for (int i = 0; i < n; i++) {+ contact_t *c = &cs[i];+ if (!live(c)) continue;+ fruit_t *a = &f[c->a], *b = body(c->a, c->b);+ float dx = b->x - a->x, dy = b->y - a->y, d = sqrt_(dx * dx + dy * dy), nx = c->nx, ny = c->ny;+ float ia = inv[c->a], ib = inv[c->b], corr = BETA * (d - rad[c->a] - rad[c->b] + SLOP);+ if (d > 1e-3f) nx = dx / d, ny = dy / d;+ if (corr >= 0) continue;+ float p = -clampf(corr, -20, 0) / (ia + ib);+ a->x -= nx * p * ia, a->y -= ny * p * ia, b->x += nx * p * ib, b->y += ny * p * ib;+ }+ /* still for half a second, with all it touches: asleep */+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ float r = rad[i];+ a->x = clampf(a->x, r - SLOP, W - r + SLOP), a->y = clampf(a->y, -2000, FLOOR - r + SLOP);+ bool slow = a->vx * a->vx + a->vy * a->vy < STILL * STILL && a->w * a->w * r * r < STILL * STILL;+ a->still = a->zz ? 255 : slow ? (uint8_t)(a->still < 254 ? a->still + 1 : 254) : 0;+ if (a->k && a->still < least[root(up, i)]) least[root(up, i)] = a->still;+ }+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ if (!a->k) continue;+ if (!a->zz && least[root(up, i)] >= 25) a->zz = 1, a->vx = a->vy = a->w = 0;+ if (a->land && a->y < rad[i]) { /* landed and above the line too long: the end */+ if (++a->over >= OVER_STEPS) over = true, over_t = now, sv.flags &= (uint8_t)~GAME;+ } else+ a->over = 0;+ }+ if (over) save();+}++static void sim(int dir) { /* a step of the game: the cloud, then the fruit */+ aim_at(sv.aim + (float)dir * CLOUD);+ step();+}++/* ------------------------------------------------------------ drawing */+static void put(color_t *p, color_t c, int t) { *p = t >= 32 ? c : gfx_mix(*p, c, t); }+/* a line with round ends, ro thick on either side (a disc when it has no length), hollow within ri; t of 32 */+static void seg(float x0, float y0, float x1, float y1, float ro, float ri, color_t c, int t) {+ int ya = (int)fmaxf_(fminf_(y0, y1) - ro, gfx_y0), yb = (int)fminf_(fmaxf_(y0, y1) + ro + 1, gfx_y1);+ int xa = (int)fmaxf_(fminf_(x0, x1) - ro, 0), xb = (int)fminf_(fmaxf_(x0, x1) + ro + 1, SCREEN_W);+ float dx = x1 - x0, dy = y1 - y0, l2 = dx * dx + dy * dy;+ for (int y = ya; y < yb; y++)+ for (int x = xa; x < xb; x++) {+ float qx = x + 0.5f - x0, qy = y + 0.5f - y0, u = l2 > 0 ? clampf((qx * dx + qy * dy) / l2, 0, 1) : 0;+ qx -= u * dx, qy -= u * dy;+ float d = sqrt_(qx * qx + qy * qy), cov = clampf(ro + 0.5f - d, 0, 1), hole = clampf(d - ri + 0.5f, 0, 1);+ if (ri > 0 && hole < cov) cov = hole;+ if (cov > 0) put(gfx_buf + (y - gfx_y0) * SCREEN_W + x, c, (int)(cov * t));+ }+}+#define DISC(x, y, r, c, t) seg(x, y, x, y, r, 0, c, t)++/* the faces and the bits that stick out, drawn on the fruit in its own frame (a 32nd of its radius, y down):+ each a dot, or with CONT a line on from the one before; thickness in 64ths of the radius; colours:+ 0 shine, 1 the face, 2 leaf, 3 dark leaf, 4 stem, 5 seed, 6 the fruit's outline, 7 blush. */+typedef struct {+ int8_t x, y;+ uint8_t tc;+} stroke_t;+#define S(x, y, t, c) {x, y, (uint8_t)((t) | (c) << 4)}+#define C(x, y, t, c) {x, y, (uint8_t)((t) | (c) << 4 | 0x80)}+static const stroke_t strokes[] = {+ /* the cloud */+ S(-8, 2, 7, 1), S(10, 2, 7, 1), S(-2, 6, 4, 1), C(0, 8, 4, 1), C(3, 6, 4, 1), S(-15, 6, 14, 7), S(17, 6, 14, 7), S(19, 0, 15, 0),+ /* cherry */+ S(2, -26, 7, 4), C(8, -52, 7, 4), S(14, -50, 14, 2), C(22, -46, 12, 2), S(-12, -12, 15, 0), S(-10, 4, 10, 1), S(10, 4, 10, 1),+ /* strawberry */+ S(-16, -30, 12, 2), C(0, -24, 12, 2), C(16, -30, 12, 2), S(0, -34, 10, 2), C(0, -24, 10, 2), S(-17, -6, 7, 5), S(15, -9, 7, 5),+ S(-5, 15, 7, 5), S(17, 13, 7, 5), S(-19, 17, 7, 5), S(3, -12, 6, 5), S(-10, 1, 9, 1), S(10, 1, 9, 1), S(-4, 8, 5, 1), C(0, 11, 5, 1),+ C(4, 8, 5, 1),+ /* grape (its bunch drawn with the berries below) */+ S(-24, -28, 15, 2), C(-13, -22, 12, 2), S(-8, -2, 8, 1), S(8, -2, 8, 1), S(0, 7, 8, 1),+ /* dekopon */+ S(-10, -2, 9, 1), S(10, -2, 9, 1), S(0, 8, 9, 1), S(-15, -16, 8, 0),+ /* persimmon */+ S(-14, -34, 10, 2), C(0, -28, 12, 2), C(14, -34, 10, 2), S(-8, -22, 9, 2), C(0, -28, 9, 2), C(8, -22, 9, 2), S(16, -14, 10, 0),+ S(-11, 0, 7, 1), S(11, 0, 7, 1), S(-3, 6, 4, 1), C(0, 9, 4, 1), C(3, 6, 4, 1),+ /* apple */+ S(1, -29, 6, 4), C(5, -40, 6, 4), S(-16, -16, 11, 0), S(-21, -5, 5, 0), S(-10, -2, 7, 1), S(10, -2, 7, 1), S(0, 6, 8, 1), S(0, 5, 3, 0),+ /* pear */+ S(0, -31, 5, 4), C(4, -40, 5, 4), S(-14, 12, 3, 6), S(18, -12, 3, 6), S(11, 19, 3, 6), S(-21, -9, 3, 6), S(20, 16, 9, 0),+ S(-14, -2, 7, 1), S(14, -2, 7, 1), S(-6, 4, 3, 1), C(-3, 7, 3, 1), C(0, 4, 3, 1), C(3, 7, 3, 1), C(6, 4, 3, 1),+ /* peach */+ S(-3, -31, 3, 6), C(-9, -19, 3, 6), S(-13, -1, 7, 1), S(13, -1, 7, 1), S(-5, 3, 5, 1), C(0, 8, 5, 1), C(5, 3, 5, 1), S(0, 5, 3, 0),+ /* pineapple */+ S(-14, -40, 9, 2), C(0, -29, 9, 2), C(-5, -44, 9, 2), C(0, -29, 9, 2), C(5, -44, 9, 2), C(0, -29, 9, 2), C(14, -40, 9, 2),+ S(-16, -18, 8, 0), S(-14, 0, 4, 1), C(-10, -4, 4, 1), C(-6, 0, 4, 1), S(6, 0, 4, 1), C(10, -4, 4, 1), C(14, 0, 4, 1), S(-4, 6, 5, 1),+ C(0, 10, 5, 1), C(4, 6, 5, 1), S(0, 7, 3, 0),+ /* melon */+ S(12, -30, 5, 3), C(18, -38, 5, 3), C(24, -36, 5, 3), S(20, 22, 6, 0), S(-10, -2, 6, 1), S(10, -2, 6, 1), S(-4, 6, 3, 1),+ C(-2, 8, 3, 1), C(0, 6, 3, 1), C(2, 8, 3, 1), C(4, 6, 3, 1),+ /* watermelon */+ S(-14, -6, 4, 1), C(-8, -2, 4, 1), C(-14, 2, 4, 1), S(10, -2, 8, 1), S(-4, 4, 4, 1), C(0, 9, 4, 1), C(4, 4, 4, 1), S(16, -22, 9, 0),+ S(22, -14, 4, 0),+};+#undef S+#undef C+static const uint8_t first[13] = {0, 8, 15, 31, 36, 40, 52, 60, 74, 82, 100, 111, 120};++/* the strokes of kind k (0: the cloud) at (cx, cy), r its radius, turned (c, s) */+static void decor(int k, float cx, float cy, float r, float c, float s) {+ static const color_t pal[8] = {0xFFFF, 0, HEX(0x6CC530), HEX(0x2C7A1A), HEX(0x8E5B2A), HEX(0xFFE9A6), 0, HEX(0xF7A8A0)};+ float q = r / 32, x0 = 0, y0 = 0;+ for (int i = first[k]; i < first[k + 1]; i++) {+ const stroke_t *t = &strokes[i];+ int n = t->tc >> 4 & 7;+ float x = cx + (t->x * c - t->y * s) * q, y = cy + (t->x * s + t->y * c) * q, rd = (float)(t->tc & 15) * r / 128;+ color_t col = n == 1 ? face_c[k] : n == 6 ? line_c[k] : pal[n];+ if (rd < 0.5f) rd = 0.5f;+ if (t->tc & 0x80)+ seg(x0, y0, x, y, rd, 0, col, 32);+ else+ DISC(x, y, rd, col, n ? n == 7 ? 18 : 32 : 24);+ x0 = x, y0 = y;+ }+}++/* the grape's bunch: its berries, back to front */+static const int8_t berry[7][3] = {{-14, -14, 13}, {6, -18, 13}, {20, -4, 12}, {-20, 4, 12}, {16, 14, 12}, {-8, 18, 12}, {0, 0, 14}};++/* a fruit at (cx, cy), radius r on screen, turned (c, s): its outline, its body lit from the top left (the+ pineapple's lattice, the melon's net and the watermelon's stripes turning with it), then its face */+static void fruit(int k, float cx, float cy, float r, float c, float s) {+ if (cy + 1.6f * r + 2 < gfx_y0 || cy - 1.6f * r - 2 >= gfx_y1) return;+ color_t fc = fill_c[k], lc = line_c[k], shade = gfx_mix(fc, lc, 10);+ float q = r / 32, ow = r * 0.08f + 0.5f;+ if (k == 3) { /* the bunch */+ for (int i = 0; i < 7; i++) {+ float x = cx + (berry[i][0] * c - berry[i][1] * s) * q, y = cy + (berry[i][0] * s + berry[i][1] * c) * q, br = berry[i][2] * q;+ DISC(x, y, br + ow * 0.6f, lc, 32), DISC(x, y, br - ow * 0.4f, fc, 32);+ }+ } else {+ float bx = cx + 27 * s * q, by = cy - 27 * c * q; /* the dekopon's bump */+ if (k == 4) DISC(bx, by, 10 * q + ow * 0.5f, lc, 32);+ int ya = (int)fmaxf_(cy - r, gfx_y0), yb = (int)fminf_(cy + r + 1, gfx_y1), xa = (int)fmaxf_(cx - r, 0), xb = (int)fminf_(cx + r + 1, SCREEN_W);+ for (int y = ya; y < yb; y++)+ for (int x = xa; x < xb; x++) {+ float dx = x + 0.5f - cx, dy = y + 0.5f - cy, d = sqrt_(dx * dx + dy * dy), lx = dx + 0.12f * r, ly = dy + 0.14f * r;+ if (d >= r + 0.5f) continue;+ color_t col = d > r - ow ? lc : lx * lx + ly * ly < 0.88f * r * r ? fc : shade;+ if (k >= 9 && d <= r - ow) { /* lines across it (in tenths): a u + b v + c u^2, and maybe a second set; how wide (100ths), from how far out, how strong */+ static const int8_t pat[3][8] = {{23, 23, 0, 23, -23, 9, 0, 14}, {33, 8, 0, -8, 33, 16, 6, 24}, {0, 18, 4, 0, 0, 34, 0, 24}};+ static const color_t pc[3] = {HEX(0xD9A80C), HEX(0xDCF290), HEX(0x0C6A08)};+ const int8_t *t = pat[k - 9];+ float u = (dx * c + dy * s) / r, v = (dy * c - dx * s) / r, w = t[5] * 0.01f;+ bool on = frac((t[0] * u + t[1] * v + t[2] * u * u) * 0.1f + 9.25f) < w || (t[3] && frac((t[3] * u + t[4] * v) * 0.1f + 9) < w);+ if (on && d > t[6] * 0.1f * r) col = gfx_mix(col, pc[k - 9], t[7]);+ }+ put(gfx_buf + (y - gfx_y0) * SCREEN_W + x, col, (int)(clampf(r + 0.5f - d, 0, 1) * 32));+ }+ if (k == 4) DISC(bx, by, 10 * q - ow * 0.5f, fc, 32);+ }+ decor(k, cx, cy, r, c, s);+}+static void fruit_at(int k, float x, float y) { fruit(k, x, y, RAD(k) / 3, 1, 0); }++/* the cloud, holding the fruit at its lower left */+static void cloud(float x, float y) {+ static const int8_t lobe[7][3] = {{-13, 2, 8}, {-6, -5, 9}, {4, -6, 10}, {13, -1, 8}, {11, 6, 7}, {0, 5, 10}, {-11, 8, 6}};+ for (int pass = 0; pass < 2; pass++) {+ float e = pass ? 0 : 1.4f;+ color_t col = pass ? fill_c[0] : line_c[0];+ for (int i = 0; i < 7; i++) DISC(x + lobe[i][0], y + lobe[i][1], lobe[i][2] + e, col, 32);+ }+ decor(0, x, y, 20, 1, 0);+}++/* a soap bubble */+static void bubble(float x, float y, float r) {+ seg(x, y, x, y, r, r - 1.3f, 0xFFFF, 13);+ seg(x - r * 0.62f, y - r * 0.2f, x - r * 0.3f, y - r * 0.62f, 1.6f, 0, 0xFFFF, 22);+}+static const np_font_t *const fonts[3] = {&np_font_title, &np_font_body, &np_font_small};+/* cream with a shadow (style 0), brown (1) or orange (2) */+static void text(int fs, int x, int y, const char *s) {+ if (!(fs >> 4)) gfx_text_center(fonts[fs & 3], x + 1, y + 1, s, HEX(0x8A5420), 256);+ gfx_text_center(fonts[fs & 3], x, y, s, (fs >> 4) == 1 ? INK : (fs >> 4) ? HEX(0xD9480F) : HEX(0xFFF4D6), 256);+}+static const struct {+ uint8_t fs, y; /* font, style, and 0x40 for the right side */+ const char *s;+} labels[] = {+ {0x00, 24, T("Score")}, {0x02, 75, T("Best score")}, {0x40, 30, T("Next")}, {0x42, 117, T("Circle of")},+ {0x42, 128, T("Evolution")}, {0x12, 140, T("Move")}, {0x21, 163, "OK"}, {0x12, 176, T("Drop")},+ {0x21, 199, T("Back")}, {0x12, 212, T("Menu")},+};+static const char *const items[] = {T("Resume"), T("Restart"), T("How to play"), T("Quit"), T("No"), T("Yes"), T("Play"), T("Restart"), T("Quit")};+static const uint8_t ov_first[5] = {0, 0, 4, 6, 7}, ov_count[5] = {0, 4, 2, 1, 2}, ov_h[5] = {0, 186, 120, 208, 176};+static const char *const ov_title[4] = {0, T("Paused"), T("Start again?"), T("How to play")};++static void scene(void *ctx) {+ char s[24];+ /* the room: the wall, its shadow, the floor */+ for (int y = gfx_y0; y < gfx_y1; y++)+ gfx_fill(0, y, SCREEN_W, 1, y < 87 ? HEX(0xC68E52) : y < 108 ? HEX(0xB0751F) : y < 137 ? HEX(0xCDA458) : HEX(0xEEDFA4));+ /* the box, behind the fruit: its glass, its top seen from above */+ gfx_fill_alpha(85, 41, 150, 184, HEX(0xFFF6E0), 80);+ gfx_fill(95, 37, 130, 4, HEX(0xF4D680));+ seg(95, 39, 83, 55, 1.4f, 0, HEX(0xF4D680), 32), seg(225, 39, 237, 55, 1.4f, 0, HEX(0xF4D680), 32);+ bool held = sv.flags & HELD && !over, danger = false;+ if (held) gfx_fill_alpha((int)SX(sv.aim), 31, 1, 194, 0xFFFF, 190); /* the guide line */+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ if (a->k) fruit(a->k, SX(a->x), SY(a->y), RAD(a->k) / 3, a->c, a->s), danger |= a->over > 0;+ }+ /* its front, over them */+ gfx_fill_alpha(81, 53, 158, 5, HEX(0xF4D27E), 210);+ gfx_vgrad(81, 58, 4, 167, 0xF4D27E, 0xE8B04A), gfx_vgrad(235, 58, 4, 167, 0xF4D27E, 0xE8B04A);+ gfx_fill(81, 225, 158, 4, HEX(0xE8B04A));+ if (danger)+ for (int x = 86; x < 234; x += 7) gfx_fill(x, 36, 4, 2, HEX(0xE8341C));+ /* the score, the next fruit, the circle of evolution, and the keys where the original lists the day's best */+ bubble(40, 58, 33), bubble(280, 62, 28);+ gfx_rrect(6, 104, 68, 116, 10, HEX(0xFFF7E2), 190);+ gfx_icon(&np_icon_left, 27, 112, INK, 256), gfx_icon(&np_icon_right, 45, 112, INK, 256);+ for (unsigned i = 0; i < sizeof labels / sizeof labels[0]; i++) text(labels[i].fs & 0x33, labels[i].fs & 0x40 ? 280 : 40, labels[i].y, labels[i].s);+ num(s, sv.score), text(0, 40, 62, s);+ num(s, sv.best), text(1, 40, 88, s);+ fruit_at(sv.next, 280, 64);+ seg(280, 182, 280, 182, 40, 23, HEX(0xC8EC6A), 17);+ static const int8_t evo[11][2] = {{16, -28}, {28, -16}, {32, 0}, {28, 16}, {16, 28}, {0, 32}, {-16, 28}, {-28, 16}, {-32, 0}, {-28, -16}, {-16, -28}};+ for (int k = 1; k <= 11; k++) fruit(k, 280 + evo[k - 1][0], 182 + evo[k - 1][1], 5.2f, 1, 0);+ /* the cloud and its fruit */+ cloud(SX(sv.aim) + 18, SY(HANG) - 13);+ if (held) fruit_at(sv.cur, SX(sv.aim), SY(HANG));+ if (ov) {+ int h = ov_h[ov], top = 120 - h / 2, n = ov_count[ov];+ gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 110);+ gfx_rrect(40, top, 240, h, 14, HEX(0xFFF7DE), 256);+ gfx_rrect_outline(40, top, 240, h, 14, 3, HEX(0xE8B04A), 256);+ gfx_text_center(&np_font_title, 160, top + 30, ov < OV_OVER ? ov_title[ov] : sv.score > best0 ? T("New best!") : T("Game over"), INK,+ 256);+ if (ov == OV_HELP) {+ gfx_paragraph(&np_font_body, 160, top + 52, 216, 15,+ T("Move the cloud with the arrows and drop the fruit with OK. Two of the same fruit that touch join into the next one, up to the watermelon. If fruit stays above the box, it's over."),+ INK, 256);+ float x = 70;+ for (int k = 1; k <= 11; k++) { /* the fruit, smallest to biggest */+ float r = 2.6f + k * 0.75f;+ fruit(k, x + r, top + 154, r, 1, 0), x += 2 * r + 1.6f;+ }+ }+ if (ov == OV_OVER) {+ num(s, sv.score);+ gfx_text_center(&np_font_title, 160, top + 66, s, HEX(0xF08A00), 256);+ char *e = s;+ for (const char *p = T("Best "); *p;) *e++ = *p++;+ num(e, sv.best);+ gfx_text_center(&np_font_body, 160, top + 86, s, INK, 256);+ }+ for (int i = 0; i < n; i++) {+ int y = top + h - 38 - 34 * (n - 1 - i);+ gfx_rrect(95, y, 130, 24, 12, sel == i ? HEX(0xFFB624) : HEX(0xE6DFD0), 256);+ gfx_text_center(&np_font_body, 160, y + 17, items[ov_first[ov] + i], sel == i ? 0xFFFF : INK, 256);+ }+ }+}++/* ------------------------------------------------------------ the game */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);+ uint32_t len = 0;+ const uint8_t *d = np_file_read(SAVE_NAME, &len);+ uint8_t *v = (uint8_t *)&sv;+ bool ok = d && len == sizeof sv && d[0] == 'S' && d[1] == 1;+ for (int i = 0; i < MAXF; i++) f[i] = (fruit_t){0};+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = ok ? d[i] : 0;+ if (sv.sum != checksum() || sv.cur - 1u > 4 || sv.next - 1u > 4 || sv.drop > MAXF)+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = 0;+ unpack();+ aim_at(sv.aim);+ over = false;}+int main(void) {np_app_begin();+ color_t *their_strip = gfx_buf;+ gfx_buf = strip;+ now = (uint32_t)eadk_timing_millis();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;+ sv.rng ^= eadk_random() ^ now;+ if (!(sv.flags & GAME)) new_game();+ best0 = sv.best;+ if (!(sv.flags & SEEN)) ov = OV_HELP, sv.flags |= SEEN;+ uint64_t held = eadk_keyboard_scan(), stale = held; /* keys still down from the launcher wait to be let go */+ uint32_t tick = now, saved = now;+ for (;;) {+ now = (uint32_t)eadk_timing_millis();+ uint64_t raw = eadk_keyboard_scan(), k = raw & ~(stale &= raw), hit = k & ~held;+ held = k;+ if (raw & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe));+ int dy = !!(hit & KEY(eadk_key_down)) - !!(hit & KEY(eadk_key_up));+ int dir = !!(k & (KEY(eadk_key_right) | KEY(eadk_key_six))) - !!(k & (KEY(eadk_key_left) | KEY(eadk_key_four)));+ if (over && !ov && now - over_t > 530) ov = OV_OVER, sel = 0;+ if (ov) {+ sel = (sel + dy + ov_count[ov]) % ov_count[ov];+ if (hit & KEY(eadk_key_back) && ov != OV_OVER) {+ ov = ov == OV_SURE ? OV_MENU : OV_NONE, sel = 1;+ } else if (ok) {+ int was = ov, choice = sel;+ ov = OV_NONE, sel = 0;+ if (was == OV_MENU) { /* Resume, Restart (asks first), How to play, Quit */+ if (choice == 1) ov = OV_SURE;+ else if (choice == 2) ov = OV_HELP;+ else if (choice == 3) break;+ } else if (was == OV_SURE) { /* No, Yes */+ if (choice) new_game();+ else ov = OV_MENU, sel = 1;+ } else if (was == OV_OVER) { /* Restart, Quit */+ if (choice) break;+ new_game();}- 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;+ } else if (hit & KEY(eadk_key_back)) {+ ov = OV_MENU, sel = 0;+ save();+ } else if (ok) {+ drop_fruit();}- eadk_timing_msleep(4);+ /* fifty steps a second, as the original's physics, catching up after a slow frame */+ if (ov || over) tick = now;+ if (now - tick > 100) tick = now - 100;+ for (; now - tick >= 20; tick += 20) sim(dir);+ if (now - saved > 10000) saved = now, save();+ eadk_display_wait_for_vblank();+ gfx_render(scene, 0, 0, SCREEN_H);+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;+ if (spent < 20) eadk_timing_msleep(20 - spent);}+ save();+ gfx_buf = their_strip;return np_app_end();}diff --git a/games/suika/src/physics.c b/games/suika/src/physics.cdeleted file mode 100644index eb85f44a..00000000--- a/games/suika/src/physics.c+++ /dev/null@@ -1,188 +0,0 @@-/* 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.cdeleted file mode 100644index 216087d9..00000000--- a/games/suika/src/render.c+++ /dev/null@@ -1,379 +0,0 @@-/* 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.hdeleted file mode 100644index 5a5ebc3d..00000000--- a/games/suika/src/render.h+++ /dev/null@@ -1,10 +0,0 @@-/* 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);-#endifdiff --git a/games/suika/src/save.c b/games/suika/src/save.cdeleted file mode 100644index 48c75f33..00000000--- a/games/suika/src/save.c+++ /dev/null@@ -1,105 +0,0 @@-/* 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.hdeleted file mode 100644index 6fea3616..00000000--- a/games/suika/src/suika.h+++ /dev/null@@ -1,40 +0,0 @@-/* 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);-#endifdiff --git a/games/suika/tests/legacy-save.bin b/games/suika/tests/legacy-save.bindeleted file mode 100644index e964ac52..00000000Binary files a/games/suika/tests/legacy-save.bin and /dev/null differdiff --git a/games/suika/tests/play.c b/games/suika/tests/play.cnew file mode 100644index 00000000..a8940bff--- /dev/null+++ b/games/suika/tests/play.c@@ -0,0 +1,409 @@+/* Suika Game on a computer, for tests and pictures (make host, make test).+ *+ * play test the original's numbers (a grape's fall, the cloud's speed, no bounce, the next+ * fruit on touching, the points of every merge, two watermelons vanishing, the+ * game ending after 47 steps above the line); a bot plays 300 games with every+ * step checked against the rules (merges scored right, fruit in the box, drops+ * from the first five); a settled pile must sleep without a pixel of jitter; the+ * whole game run 120 times with random keys; a save comes back, a damaged one+ * starts afresh+ * play film DIR N [SEED [SKIP]] N frames of the bot's game after SKIP steps (DIR/f_NNNN.ppm)+ * play screens DIR the menus over a filled box (DIR/ov_N.ppm), and that game's save (DIR/suika.sav)+ * play icon FILE the app's icon (the top left 55 x 56 of FILE) */+#define NP_MODULE 1 /* (its drawing pushed to fb, its saves kept in disk, below) */+#define main sk_main+#define gfx_render test_render+#include "../src/main.c"+#undef gfx_render+#undef main+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++void gfx_render(gfx_scene_t scene, void *ctx, int y0, int y1);+static uint16_t fb[SCREEN_H][SCREEN_W];+static uint8_t disk[sizeof sv + 64];+static uint32_t disk_len;+void np_push(int x, int y, int w, int h, const color_t *p) {+ for (int j = 0; j < h; j++)+ for (int i = 0; i < w; i++) fb[y + j][x + i] = p[j * w + i];+}+static int render_every = 1, render_n;+void test_render(gfx_scene_t scene, void *ctx, int y0, int y1) {+ if (++render_n % render_every == 0) gfx_render(scene, ctx, y0, y1);+}++/* the calculator, for the game run whole: a clock, random keys, Home after a while */+static uint32_t clock_ms, frames_left, key_hold;+static uint64_t keys_now;+static int fails, checking;+#define CHECK(c, ...) do { if (!(c)) { printf(__VA_ARGS__); printf("\n"); fails++; } } while (0)+static uint32_t lcg = 7;+static uint32_t rand32(void) { return lcg = lcg * 1664525u + 1013904223u; }+static void invariants(const char *where);+uint64_t eadk_keyboard_scan(void) {+ if (!frames_left) return 0;+ if (--frames_left == 0) return KEY(eadk_key_home);+ if (!key_hold) { /* a new key (or none), held for a while */+ static const int pick[] = {-1, -1, -1, eadk_key_left, eadk_key_right, eadk_key_four, eadk_key_six, eadk_key_ok, eadk_key_exe,+ eadk_key_back, eadk_key_up, eadk_key_down, eadk_key_ok, eadk_key_left, eadk_key_right};+ int k = pick[(rand32() >> 8) % (sizeof pick / sizeof pick[0])];+ keys_now = k < 0 ? 0 : KEY(k), key_hold = 1 + (rand32() >> 8) % 12;+ }+ key_hold--;+ return keys_now;+}+uint64_t eadk_timing_millis(void) { return clock_ms; }+void eadk_timing_msleep(uint32_t ms) { clock_ms += ms; }+bool eadk_display_wait_for_vblank(void) {+ if (checking) invariants("in play");+ return true;+}+void *np_alloc(uint32_t size) { return malloc(size); }+uint32_t eadk_random(void) { return rand32(); }+const uint8_t *np_file_read(const char *name, uint32_t *len) { *len = disk_len; return disk_len ? disk : 0; }+bool np_file_write(const char *name, const void *d, uint32_t len) {+ if (len > sizeof disk) return false;+ memcpy(disk, d, disk_len = len);+ return true;+}++/* ------------------------------------------------------------ the rules, checked */+static void invariants(const char *where) {+ CHECK(sv.cur >= 1 && sv.cur <= 5 && sv.next >= 1 && sv.next <= 5, "%s: drops come from the first five (%d %d)", where, sv.cur, sv.next);+ CHECK(ncon[cb] <= MAXC && ov >= 0 && ov <= OV_OVER, "%s: state", where);+ for (int i = 0; i < MAXF; i++) {+ fruit_t *a = &f[i];+ if (!a->k) continue;+ float r = RAD(a->k);+ CHECK(a->k <= 11, "%s: kind %d", where, a->k);+ CHECK(isfinite(a->x) && isfinite(a->y) && isfinite(a->vx) && isfinite(a->vy) && isfinite(a->w), "%s: not a number", where);+ CHECK(a->x >= r - 1 && a->x <= W - r + 1 && a->y <= FLOOR - r + 1, "%s: fruit %d (kind %d) out of the box at %.1f %.1f", where, i,+ a->k, a->x, a->y);+ CHECK(a->over < OVER_STEPS || over, "%s: above the line too long without the end", where);+ }+}+static void count(int n[13]) {+ memset(n, 0, 13 * sizeof n[0]);+ for (int i = 0; i < MAXF; i++) n[f[i].k]++;+}+static int touching(int d) {+ for (int i = 0; i < ncon[cb]; i++)+ if (con[cb][i].a == d || con[cb][i].b == d) return 1;+ return 0;+}+static long steps_checked, merges_seen[13];+static int most; /* fruit in the box at once */+/* a step, and what it did against the rules: merges from the changes in each kind's count, each worth+ T(k); the next fruit only once the dropped one touched something */+static void checked_sim(int dir) {+ int n0[13], n1[13], d = sv.drop - 1;+ uint32_t s0 = sv.score;+ bool was_held = sv.flags & HELD, was_over = over;+ count(n0);+ sim(dir);+ count(n1);+ long m = 0, pts = 0, carry = 0;+ for (int k = 1; k <= 11; k++) {+ long diff = n1[k] - n0[k]; /* = merges of the kind below - 2 x merges of this kind */+ long mk = carry - diff;+ CHECK(mk >= 0 && mk % 2 == 0, "merge counts don't add up (kind %d)", k);+ mk /= 2, m += mk, pts += mk * k * (k + 1) / 2, merges_seen[k] += mk, carry = mk;+ }+ CHECK(sv.score - s0 == pts, "score %u -> %u, the merges were worth %ld", s0, sv.score, pts);+ if (!was_held && d >= 0) {+ if (sv.flags & HELD) CHECK(!f[d].k || f[d].land, "the next fruit came before the dropped one touched anything");+ else CHECK(!touching(d), "the dropped fruit touched something, and no next fruit");+ }+ CHECK(was_held || !(sv.flags & HELD) || !sv.drop, "drop state");+ if (over && !was_over) {+ bool why = false;+ for (int i = 0; i < MAXF; i++) why |= f[i].k && f[i].land && f[i].y < RAD(f[i].k) && f[i].over >= OVER_STEPS;+ CHECK(why, "the game ended with no fruit above the line");+ }+ invariants("bot");+ steps_checked++;+ int many = 0;+ for (int i = 0; i < MAXF; i++) many += f[i].k > 0;+ most = many > most ? many : most;+}++/* ------------------------------------------------------------ the bot */+/* where a fruit dropped at x would stop first, and on what */+static float landing(float x, int k, int *on) {+ float r = RAD(k), best = FLOOR - r;+ *on = 0;+ for (int i = 0; i < MAXF; i++) {+ if (!f[i].k) continue;+ float rs = r + RAD(f[i].k), dx = f[i].x - x;+ if (dx * dx >= rs * rs) continue;+ float y = f[i].y - sqrtf(rs * rs - dx * dx);+ if (y < best) best = y, *on = f[i].k;+ }+ return best;+}+static float target;+static void choose(void) {+ float r = RAD(sv.cur), bestv = -1e9f;+ for (int n = 0; n <= 32; n++) {+ float x = r + (W - 2 * r) * (float)n / 32;+ int on;+ float v = landing(x, sv.cur, &on) + (on == sv.cur ? 160 : 0) - (on && on < sv.cur ? 60 : 0) + (float)(rand32() % 40);+ if (v > bestv) bestv = v, target = x;+ }+}+/* one bot move: to its spot, then drop; false when the game is over */+static bool bot_move(bool random_play) {+ if (over) return false;+ int dir = 0;+ if (sv.flags & HELD) {+ if (random_play) {+ if (rand32() % 20 == 0) drop_fruit();+ dir = (int)(rand32() % 3) - 1;+ } else if (fabsf(target - sv.aim) <= CLOUD / 2 + 0.01f) {+ drop_fruit();+ } else+ dir = target > sv.aim ? 1 : -1;+ }+ bool was_held = sv.flags & HELD;+ checked_sim(dir);+ if (!was_held && sv.flags & HELD && !random_play) choose();+ return !over;+}+static void bot_game(uint32_t seed, int max_steps, bool random_play) {+ sv.rng = seed ? seed : 1;+ new_game();+ choose();+ for (int s = 0; s < max_steps && bot_move(random_play); s++) now += 20;+}++/* ------------------------------------------------------------ pictures */+static void picture(const char *path) {+ FILE *fp = fopen(path, "wb");+ if (!fp) exit(2);+ fprintf(fp, "P6 320 240 255\n");+ for (int y = 0; y < SCREEN_H; y++)+ for (int x = 0; x < SCREEN_W; x++) {+ uint16_t c = fb[y][x];+ fputc((c >> 11) * 255 / 31, fp), fputc((c >> 5 & 63) * 255 / 63, fp), fputc((c & 31) * 255 / 31, fp);+ }+ fclose(fp);+}+static void render(void) {+ gfx_buf = strip;+ gfx_render(scene, 0, 0, SCREEN_H);+}++/* a fruit put somewhere by hand */+static int place(int k, float x, float y, bool land) {+ for (int i = 0; i < MAXF; i++)+ if (!f[i].k) {+ f[i] = (fruit_t){x, y, 0, 0, 1, 0, 0, (uint8_t)k, land, 0, 0, 0};+ return i;+ }+ return -1;+}+static void empty_box(void) {+ new_game();+ over = false;+}++/* the app's icon: a watermelon and a cherry on the box's honey */+static void icon_scene(void *ctx) {+ gfx_vgrad(0, 0, 55, 56, 0xF6DC8C, 0xF9EFC8);+ fruit(11, 26, 32, 20.5f, 0.97f, -0.24f);+ fruit(1, 45, 15, 6.5f, 1, 0);+}++int main(int argc, char **argv) {+ if (argc >= 3 && !strcmp(argv[1], "icon")) {+ gfx_buf = strip;+ gfx_render(icon_scene, 0, 0, 64);+ picture(argv[2]);+ return 0;+ }+ if (argc >= 3 && !strcmp(argv[1], "screens")) { /* the overlays, over a game going on; and its save */+ sv.flags = SEEN, sv.rng = 26;+ new_game();+ choose();+ for (int s = 0; s < 20000 && bot_move(false); s++) { /* until the box is well filled */+ int many = 0;+ for (int i = 0; i < MAXF; i++) many += f[i].k > 0;+ if (many >= 30 && sv.flags & HELD) break;+ now += 20;+ }+ char path[512];+ for (int o = OV_MENU; o <= OV_OVER; o++) {+ ov = o, sel = 0;+ render();+ snprintf(path, sizeof path, "%s/ov_%d.ppm", argv[2], o);+ picture(path);+ }+ ov = 0, save();+ snprintf(path, sizeof path, "%s/suika.sav", argv[2]);+ FILE *fp = fopen(path, "wb");+ fwrite(disk, 1, disk_len, fp), fclose(fp);+ return 0;+ }+ if (argc >= 4 && !strcmp(argv[1], "film")) {+ int frames = atoi(argv[3]), skip = argc > 5 ? atoi(argv[5]) : 0, shot = 0;+ sv.flags = SEEN;+ sv.rng = argc > 4 ? (uint32_t)atoi(argv[4]) : 5;+ new_game();+ choose();+ now = 1000, sv.best = 2471; /* (someone's best from before) */+ char path[512];+ for (int s = 0; s < skip + frames && !over; s++) {+ bot_move(false);+ now += 20;+ if (s < skip || (s - skip) % 2) continue;+ render();+ snprintf(path, sizeof path, "%s/f_%04d.ppm", argv[2], shot++);+ picture(path);+ }+ printf("score %u, %s\n", sv.score, over ? "over" : "going");+ return 0;+ }++ /* ---- the original's numbers */+ sv.rng = 99;+ empty_box();+ sv.cur = 3, aim_at(341); /* a grape where the video's first one fell */+ drop_fruit();+ int d = sv.drop - 1, steps = 0;+ while (!(sv.flags & HELD) && steps < 200) checked_sim(0), steps++;+ printf("a grape falls to the floor in %d steps (%.2f s; the Switch: 0.87 s)\n", steps, steps * DT);+ CHECK(steps >= 42 && steps <= 46, "fall time");+ float rest = FLOOR - RAD(3), highest = 1e9f;+ for (int s = 0; s < 60; s++) {+ checked_sim(0);+ if (f[d].y < highest) highest = f[d].y;+ }+ printf(" no bounce: after landing it stays at least %.2f px into the floor, and rests %.2f px into it\n", highest - rest,+ f[d].y - rest);+ CHECK(fabsf(f[d].y - rest) < SLOP + 0.1f && highest > rest - 1, "it should land without bouncing");+ CHECK(f[d].zz, "a fruit at rest should sleep");+ float a0 = sv.aim;+ for (int s = 0; s < 25; s++) checked_sim(-1);+ CHECK(fabsf(a0 - sv.aim - 25 * CLOUD) < 0.01f, "the cloud moves 290 px/s");+ /* every merge's points, and the fruit it makes, at the middle of the two */+ for (int k = 1; k <= 11; k++) {+ empty_box();+ float r = RAD(k);+ int i = place(k, W / 2 - r + 1, FLOOR - r, true);+ place(k, W / 2 + r - 1, FLOOR - r, true);+ uint32_t s0 = sv.score;+ checked_sim(0);+ CHECK(sv.score - s0 == (uint32_t)(k * (k + 1) / 2), "two of kind %d: %u points", k, sv.score - s0);+ if (k < 11) CHECK(f[i].k == k + 1 && fabsf(f[i].x - W / 2) < 2, "two of kind %d should make kind %d in the middle", k, k + 1);+ else CHECK(!f[i].k && !f[i + 1].k, "two watermelons should both vanish");+ }+ /* the end: a fruit that has landed, above the line for 47 steps */+ empty_box();+ int top = place(5, 200, -60, true), loose = place(4, 60, -60, false);+ for (int s = 1; s <= OVER_STEPS && !over; s++) {+ f[top].y = f[loose].y = -60, f[top].vy = f[loose].vy = 0;+ sim(0);+ CHECK(over == (s == OVER_STEPS), "the game should end after exactly %d steps above the line (step %d)", OVER_STEPS, s);+ }+ CHECK(!(sv.flags & GAME), "a game over is not one to go on with");+ empty_box();+ loose = place(4, 60, -60, false);+ for (int s = 0; s < 100; s++) f[loose].y = -60, f[loose].vy = 0, sim(0);+ CHECK(!over, "a fruit still falling never ends the game");++ /* ---- the bot: 300 games, every step checked */+ long total = 0, drops = 0;+ uint32_t best = 0;+ int biggest = 0, ended = 0;+ for (int g = 0; g < 300; g++) {+ bot_game(1234 + g * 7919, 12000, false);+ total += sv.score, best = sv.score > best ? sv.score : best, ended += over;+ for (int i = 0; i < MAXF; i++) biggest = f[i].k > biggest ? f[i].k : biggest;+ }+ for (int k = 1; k <= 11; k++) biggest = merges_seen[k] ? (k + 1 > biggest ? k + 1 : biggest) : biggest;+ printf("bot: 300 games, %ld points on average, best %u, %d ended, biggest fruit %d, %d fruit at most, %ld steps checked\n",+ total / 300, best, ended, biggest > 11 ? 11 : biggest, most, steps_checked);+ printf(" merges by kind:");+ for (int k = 1; k <= 11; k++) printf(" %ld", merges_seen[k]);+ printf("\n");+ CHECK(best > 1500 && merges_seen[10] > 0, "the bot should make a watermelon at least once");+ (void)drops;+ /* random play */+ for (int g = 0; g < 100; g++) bot_game(77 + g, 6000, true);++ /* ---- a settled pile sleeps and never moves */+ sv.rng = 4242;+ new_game();+ choose();+ for (int s = 0; s < 20000 && bot_move(false); s++) {+ int many = 0;+ for (int i = 0; i < MAXF; i++) many += f[i].k > 0;+ if (many >= 24 && sv.flags & HELD) break;+ }+ over = false;+ sv.flags &= (uint8_t)~HELD; /* no more drops */+ sv.drop = 0;+ for (int s = 0; s < 400; s++) checked_sim(0);+ float snap[MAXF][2], moved = 0, overlap = 0;+ int awake = 0, n = 0;+ for (int i = 0; i < MAXF; i++) snap[i][0] = f[i].x, snap[i][1] = f[i].y;+ for (int s = 0; s < 200; s++) checked_sim(0);+ for (int i = 0; i < MAXF; i++) {+ if (!f[i].k) continue;+ n++, awake += !f[i].zz;+ float m = fabsf(f[i].x - snap[i][0]) + fabsf(f[i].y - snap[i][1]);+ moved = m > moved ? m : moved;+ for (int j = i + 1; j < MAXF; j++)+ if (f[j].k) {+ float dx = f[j].x - f[i].x, dy = f[j].y - f[i].y, o = RAD(f[i].k) + RAD(f[j].k) - sqrtf(dx * dx + dy * dy);+ overlap = o > overlap ? o : overlap;+ }+ }+ printf("a settled pile of %d: %d awake, moved %.4f px in 4 s, deepest overlap %.2f px (%.2f on screen)\n", n, awake, moved,+ overlap, overlap / 3);+ CHECK(n > 10 && awake == 0 && moved < 0.01f, "a settled pile should sleep, not jitter");+ CHECK(overlap < 6, "fruit sink into each other");++ /* ---- the whole game with random keys: menus, drops, quitting; the save after each */+ render_every = 25, checking = 1;+ for (int run = 0; run < 120; run++) {+ if (run % 30 == 0) disk_len = 0;+ clock_ms = 1000 + run * 7, frames_left = 300 + rand32() % 3000, key_hold = 0;+ memset(f, 0, sizeof f), ov = 0, over = false;+ sk_main();+ uint8_t copy[sizeof sv];+ memcpy(copy, &sv, sizeof sv);+ load();+ CHECK(!memcmp(copy, &sv, sizeof sv), "run %d: the save didn't come back as it was", run);+ }+ checking = 0;++ /* ---- the save: back as it was (the falling fruit too); damaged, a fresh start */+ bot_game(31337, 900, false);+ if (sv.flags & HELD) drop_fruit();+ for (int s = 0; s < 5; s++) sim(0);+ sv.best = 777;+ save();+ fruit_t keep[MAXF];+ memcpy(keep, f, sizeof keep);+ uint32_t score = sv.score;+ uint8_t drop = sv.drop, cur = sv.cur, next = sv.next;+ memset(&sv, 0, sizeof sv), memset(f, 0, sizeof f);+ load();+ bool same = sv.best == 777 && sv.score == score && sv.drop == drop && sv.cur == cur && sv.next == next && (sv.flags & GAME);+ for (int i = 0; i < MAXF; i++)+ same &= f[i].k == keep[i].k && (!f[i].k || (f[i].x == keep[i].x && f[i].y == keep[i].y && f[i].vy == keep[i].vy &&+ f[i].c == keep[i].c && f[i].land == keep[i].land));+ CHECK(same, "save not read back");+ disk[40] ^= 4;+ load();+ CHECK(sv.best == 0 && !(sv.flags & GAME), "a damaged file should start afresh");+ disk[40] ^= 4, disk_len -= 4;+ load();+ CHECK(sv.best == 0, "a short file should start afresh");+ render();+ printf(fails ? "FAILED (%d)\n" : "ok\n", fails);+ return fails != 0;+}diff --git a/games/suika/tests/test.c b/games/suika/tests/test.cdeleted file mode 100644index b943a8ac..00000000--- a/games/suika/tests/test.c+++ /dev/null@@ -1,171 +0,0 @@-/* 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.pydeleted file mode 100644index 4874fac7..00000000--- a/games/suika/tests/test_compact_nwa.py+++ /dev/null@@ -1,90 +0,0 @@-#!/usr/bin/env python3-"""Build-time LZ4 correctness and block-format boundary checks (stdlib only)."""-import importlib.util-from pathlib import Path-import random-import unittest--SOURCE = Path(__file__).resolve().parents[1]/'tools/compact_nwa.py'-SPEC = importlib.util.spec_from_file_location('compact_nwa', SOURCE)-packing = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(packing)---class CompressionTests(unittest.TestCase):- def check_block(self, raw):- block = packing.compress_lz4(raw)- self.assertEqual(packing.decode_lz4(block, len(raw)), raw)- # Walk token boundaries independently to check the LZ4 end constraints.- pos, decoded, last_match, final_literals = 0, 0, None, None- while pos < len(block):- token = block[pos]- pos += 1- literal = token >> 4- if literal == 15:- while block[pos] == 255:- literal += 255- pos += 1- literal += block[pos]- pos += 1- pos += literal- decoded += literal- if pos == len(block):- final_literals = literal- break- distance = int.from_bytes(block[pos:pos+2], 'little')- self.assertGreater(distance, 0)- self.assertLessEqual(distance, decoded)- pos += 2- match = (token & 15) + 4- if (token & 15) == 15:- while block[pos] == 255:- match += 255- pos += 1- match += block[pos]- pos += 1- last_match = decoded- decoded += match- self.assertEqual(decoded, len(raw))- self.assertIsNotNone(final_literals)- if last_match is not None:- self.assertGreaterEqual(final_literals, 5)- self.assertLessEqual(last_match, len(raw)-12)- return block-- def test_lengths_and_random_literals(self):- rng = random.Random(6140)- for size in (0, 1, 4, 5, 11, 12, 15, 19, 20, 254, 255, 270, 1024):- with self.subTest(size=size):- self.check_block(bytes(rng.randrange(256) for _ in range(size)))-- def test_long_overlapping_matches_and_extension_bytes(self):- for pattern in (b'A', b'\x00\xff', bytes(range(32))):- raw = (pattern*packing.ICON_BYTES)[:packing.ICON_BYTES]- with self.subTest(pattern=pattern):- self.assertLess(len(self.check_block(raw)), 150)-- def test_repeated_pixel_rows(self):- row = b'\x08\xc5'*20 + b'\xff\xff'*15 + b'\x08\xc5'*20- self.check_block(row*56)-- def test_known_raw_block(self):- self.assertEqual(packing.decode_lz4(b'\x13A\x01\x00\x50hello', 13), b'A'*8+b'hello')-- def test_truncated_invalid_and_oversized_output(self):- for block, expected in ((b'',1),(b'\xf0',1),(b'\x10',1),- (b'\x00\x00\x00',4),(b'\x10A\x02\x00',5),- (b'\x10A',2),(b'\x13A\x01\x00\x50hello',12)):- with self.subTest(block=block):- with self.assertRaises(ValueError):- packing.decode_lz4(block,expected)-- def test_repeatable_and_bounded_input(self):- raw = b'abcd'*100+b'last five'- self.assertEqual(self.check_block(raw),self.check_block(raw))- with self.assertRaises(ValueError):- packing.compress_lz4(b'x'*65536)---if __name__ == '__main__':- unittest.main()diff --git a/games/suika/tools/build.py b/games/suika/tools/build.pydeleted file mode 100644index 78d9e424..00000000--- a/games/suika/tools/build.py+++ /dev/null@@ -1,89 +0,0 @@-#!/usr/bin/env python3-"""Optional portable standalone build; the normal NumPlay build uses Make.--python tools/build.py --toolchain /path/to/arm/bin --nwlink /path/to/nwlink/bin/nwlink-Requires nwlink 1.0.0, ARM GCC, Pillow (icon generation), pyelftools (size report).-"""-import argparse-import json-import os-from pathlib import Path-import shlex-import shutil-import subprocess-import sys--ROOT = Path(__file__).resolve().parents[1]---def main():- ap = argparse.ArgumentParser(description=__doc__)- ap.add_argument('--toolchain', type=Path)- ap.add_argument('--nwlink', default='nwlink')- ap.add_argument('--node', default='node')- a = ap.parse_args()- out = ROOT / 'output'- out.mkdir(exist_ok=True)-- def run(*args, capture=False):- return subprocess.run([str(v) for v in args], cwd=ROOT, check=True,- capture_output=capture, text=capture)-- def tool(name):- binary = 'arm-none-eabi-' + name + ('.exe' if os.name == 'nt' else '')- return a.toolchain / binary if a.toolchain else binary-- nw = [a.node, a.nwlink] if Path(a.nwlink).is_file() and not a.nwlink.endswith(('.exe', '.cmd')) else [a.nwlink]- flags = ['-std=c11', '-Os', '-Wall', '-Wextra', '-Werror', '-fno-math-errno',- '-fsingle-precision-constant', '-ffunction-sections', '-fdata-sections',- '-fstack-usage', '-fno-tree-loop-distribute-patterns', '-flto', '-fvisibility=internal']- flags += shlex.split(run(*nw, 'eadk-cflags-device', capture=True).stdout, posix=True)- # shlex on Windows may treat the include path's backslashes as escapes;- # nwlink prints forward slashes on Windows, so this remains portable.- objects = []- for source in ('main', 'physics', 'save', 'render'):- obj = out / (source + '.o')- run(tool('gcc'), *flags, '-c', ROOT / 'src' / (source + '.c'), '-o', obj)- objects.append(obj)- run(*nw, 'png-icon-o', ROOT / 'src/icon.png', out / 'icon.o')- packer = ROOT / 'tools/compact_nwa.py'- icon_report = json.loads(run(sys.executable, packer, 'icon', out / 'icon.o',- out / 'icon-compact.o', '--objcopy', tool('objcopy'), capture=True).stdout)- common = [tool('gcc'), *flags, '-nostartfiles', '--specs=nano.specs',- '-Wl,--relocatable,--gc-sections,-e,main', '-flinker-output=nolto-rel', *objects]- run(*common, '-lm', '-o', out / 'module.o')- run(*common, '-Wl,-u,eadk_app_name,-u,eadk_app_icon,-u,eadk_api_level', out / 'icon-compact.o',- '-lm', '-o', out / 'standalone.o')- run(sys.executable, packer, 'app', out / 'standalone.o', out / '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.pydeleted file mode 100644index f320bb54..00000000--- a/games/suika/tools/compact_nwa.py+++ /dev/null@@ -1,228 +0,0 @@-#!/usr/bin/env python3-"""Lossless standalone NWA packing. Python standard library + ARM binutils.--Keep the standard ELF/NWI formats: no runtime decoder, extra RAM, or archive.-"""-import argparse-from bisect import bisect_left, insort-import json-from pathlib import Path-import subprocess-import tempfile--ICON_BYTES = 55 * 56 * 2---def decode_lz4(data, expected_size):- """Decode a raw LZ4 block, with an exact output bound for launcher icons."""- out = bytearray()- pos = 0-- def length(value):- nonlocal pos- if value == 15:- while True:- if pos >= len(data):- raise ValueError('Truncated LZ4 length')- extra = data[pos]- pos += 1- value += extra- if extra != 255:- break- return value-- while pos < len(data):- token = data[pos]- pos += 1- size = length(token >> 4)- if pos + size > len(data) or len(out) + size > expected_size:- raise ValueError('Invalid LZ4 literal run')- out += data[pos:pos + size]- pos += size- if pos == len(data):- break- if pos + 2 > len(data):- raise ValueError('Truncated LZ4 offset')- distance = data[pos] | data[pos + 1] << 8- pos += 2- size = length(token & 15) + 4- if not distance or distance > len(out) or len(out) + size > expected_size:- raise ValueError('Invalid LZ4 match')- for _ in range(size):- out.append(out[-distance])- if len(out) != expected_size:- raise ValueError('Unexpected decoded icon size')- return bytes(out)---def _extension_cost(value, threshold):- return 0 if value < threshold else 1 + (value - threshold) // 255---def compress_lz4(data):- """Find a minimum-size raw LZ4 parse for a small (<= 65535 byte) image.-- A suffix array finds the longest legal previous match. Dynamic programming- chooses literal/match lengths, including extension-byte costs. The final- five bytes are literals; the last match starts at least twelve bytes from- the end, as required by standard LZ4 block decoders.- """- n = len(data)- if n > 65535:- raise ValueError('Only small build-time assets are supported')- if not n:- return b'\0'- suffixes = sorted(range(n), key=lambda i: data[i:])- rank = [0] * n- for r, pos in enumerate(suffixes):- rank[pos] = r- seen = []- matches = [(0, 0)] * n- for i in range(n - 11):- r = rank[i]- at = bisect_left(seen, r)- best, distance = 0, 0- # Among earlier suffixes, a lexicographic neighbour has the longest- # common prefix. Overlapping matches are legal in LZ4.- for q in seen[max(0, at - 1):at + 1]:- j = suffixes[q]- lo, hi = 0, n - i - 5- while lo < hi:- mid = (lo + hi + 1) // 2- if data[i:i + mid] == data[j:j + mid]:- lo = mid- else:- hi = mid - 1- if lo > best:- best, distance = lo, i - j- matches[i] = best, distance- insort(seen, r)-- dp = [0] * (n + 1)- plan = [None] * n- match_cost = [0] * n- match_length = [0] * n- starts = []- for i in range(n - 1, -1, -1):- best = n - i + 1 + _extension_cost(n - i, 15)- longest, _ = matches[i]- if longest >= 4:- cost, size = min((2 + _extension_cost(size, 19) + dp[i + size], size)- for size in range(4, longest + 1))- match_cost[i], match_length[i] = cost, size- starts.append(i)- for j in reversed(starts):- literal = j - i- if literal + 3 >= best:- break- cost = 1 + literal + _extension_cost(literal, 15) + match_cost[j]- if cost < best:- best = cost- plan[i] = j, match_length[j], matches[j][1]- dp[i] = best-- out = bytearray()-- def emit_length(value):- while value >= 255:- out.append(255)- value -= 255- out.append(value)-- anchor = 0- while anchor < n:- entry = plan[anchor]- if entry is None:- literal = n - anchor- out.append(min(literal, 15) << 4)- if literal >= 15:- emit_length(literal - 15)- out += data[anchor:]- break- j, size, distance = entry- literal = j - anchor- out.append(min(literal, 15) << 4 | min(size - 4, 15))- if literal >= 15:- emit_length(literal - 15)- out += data[anchor:j]- out += bytes((distance & 255, distance >> 8))- if size >= 19:- emit_length(size - 19)- anchor = j + size- if len(out) != dp[0] or decode_lz4(out, n) != data:- raise ValueError('Lossless compression verification failed')- return bytes(out)---def compact_icon(source, output, objcopy):- output.parent.mkdir(parents=True, exist_ok=True)- with tempfile.TemporaryDirectory(dir=output.parent) as folder:- folder = Path(folder)- original, packed, obj = folder/'original.nwi', folder/'packed.nwi', folder/'icon.o'- section = '.rodata.eadk_app_icon'- subprocess.run([objcopy, '--dump-section=' + section + '=' + str(original),- str(source), str(obj)], check=True)- before = original.read_bytes()- pixels = decode_lz4(before, ICON_BYTES)- after = compress_lz4(pixels)- if len(after) > len(before):- after = before- packed.write_bytes(after)- subprocess.run([objcopy, '--update-section=' + section + '=' + str(packed),- str(obj), str(output)], check=True)- # Verify the bytes actually stored in the resulting ELF, too.- subprocess.run([objcopy, '--dump-section=' + section + '=' + str(packed),- str(output), str(folder/'verify.o')], check=True)- if decode_lz4(packed.read_bytes(), ICON_BYTES) != pixels:- raise ValueError('Packed icon pixels changed')- return dict(source_icon_bytes=len(before), icon_bytes=len(after), decoded_icon_bytes=ICON_BYTES)---def compact_app(source, output, linker):- output.parent.mkdir(parents=True, exist_ok=True)- script = Path(__file__).with_name('standalone.ld')- with tempfile.TemporaryDirectory(dir=output.parent) as folder:- packed = Path(folder)/'packed.nwa'- subprocess.run([linker, '--relocatable', '--script', str(script), str(source),- '-o', str(packed)], check=True)- output.write_bytes(packed.read_bytes())---def compact_release(source, output, objcopy):- """Remove unused ARM mapping symbols from the transport ELF only.-- GNU objcopy preserves $t/$d symbols specially even when unused. Rename- them in a temporary release copy, then let objcopy decide which symbols- relocations still need. Keep the debug ELF intact for ARM disassembly.- Python builders compare release/debug bytes on all supported profiles;- Make's check target compares them on the smallest RAM profile.- """- output.parent.mkdir(parents=True, exist_ok=True)- with tempfile.TemporaryDirectory(dir=output.parent) as folder:- folder = Path(folder)- stripped, renamed = folder/'stripped.nwa', folder/'renamed.nwa'- subprocess.run([objcopy, '--strip-unneeded', str(source), str(stripped)], check=True)- subprocess.run([objcopy, '--redefine-sym=$t=unused_thumb_marker',- '--redefine-sym=$d=unused_data_marker', str(stripped),- str(renamed)], check=True)- subprocess.run([objcopy, '--strip-unneeded', str(renamed), str(output)], check=True)---def main():- ap = argparse.ArgumentParser(description=__doc__)- ap.add_argument('kind', choices=('icon', 'app', 'release'))- ap.add_argument('source', type=Path)- ap.add_argument('output', type=Path)- ap.add_argument('--objcopy', default='arm-none-eabi-objcopy')- ap.add_argument('--ld', default='arm-none-eabi-ld')- args = ap.parse_args()- if args.kind == 'icon':- print(json.dumps(compact_icon(args.source, args.output, args.objcopy)))- elif args.kind == 'release':- compact_release(args.source, args.output, args.objcopy)- else:- compact_app(args.source, args.output, args.ld)---if __name__ == '__main__':- main()diff --git a/games/suika/tools/icon.py b/games/suika/tools/icon.pydeleted file mode 100644index 4ed56325..00000000--- a/games/suika/tools/icon.py+++ /dev/null@@ -1,32 +0,0 @@-#!/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.lddeleted file mode 100644index 28679582..00000000--- a/games/suika/tools/standalone.ld+++ /dev/null@@ -1,15 +0,0 @@-/* Compact a standalone NWA after the first link has removed unused code.- * Keep EADK metadata separate, and preserve mergeable strings for nwlink.- * NumPlay modules retain their original sections for launcher garbage collection.- */-SECTIONS {- .rodata.eadk_app_name : { *(.rodata.eadk_app_name) }- .rodata.eadk_app_icon : { *(.rodata.eadk_app_icon) }- .rodata.eadk_api_level : { *(.rodata.eadk_api_level) }- .text : { *(.text.startup.main) *(.text .text.*) }- .rodata.str1.1 : { *(.rodata*.str1.1) }- .rodata : { *(.rodata .rodata.*) }- .data : { *(.data .data.*) }- .bss : { *(.bss .bss.*) *(COMMON) }- /DISCARD/ : { *(.comment) *(.note.GNU-stack) }-}diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txtindex 5ab1b842..92f8651c 100644--- a/launcher/lang/fr.txt+++ b/launcher/lang/fr.txt@@ -74,6 +74,8 @@ Buckshot Roulette Buckshot RouletteYou, the Dealer, one shotgun Toi, le croupier, un fusilBlock Blast Block BlastFit the blocks, blast the lines Place les blocs, fais sauter les lignes+Suika Game Suika Game+Merge the fruit into a watermelon Fusionne les fruits jusqu'à la pastèquePortal Returns Portal ReturnsThink with portals Pense avec les portailsTetris Tetris@@ -118,6 +120,7 @@ By Tatone26, from All the Apps Par Tatone26, tiré d'All the AppsInspired by Tatone26's All the Apps Inspiré d'All the Apps de Tatone26Based on 2048 by Gabriele Cirulli D'après 2048 de Gabriele CirulliBased on Block Blast! by Hungry Studio D'après Block Blast! de Hungry Studio+Based on Suika Game by Aladdin X D'après Suika Game d'Aladdin XBased on Space Invaders by Taito D'après Space Invaders de TaitoBased on Chrome's dinosaur game by Google D'après le jeu du dinosaure de Chrome, de Google# a game the RAM of the calculator's software is too small fordiff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txtindex 0540b24e..a80a2316 100644--- a/launcher/lang/zh.txt+++ b/launcher/lang/zh.txt@@ -73,6 +73,8 @@ Buckshot Roulette 恶魔轮盘You, the Dealer, one shotgun 你、庄家、一把霰弹枪Block Blast 方块爆破Fit the blocks, blast the lines 摆放方块,消除整行+Suika Game 西瓜游戏+Merge the fruit into a watermelon 合成水果,直到大西瓜Portal Returns 传送门归来Think with portals 用传送门思考Tetris 俄罗斯方块@@ -117,6 +119,7 @@ By Tatone26, from All the Apps 作者 Tatone26,出自 All the AppsInspired by Tatone26's All the Apps 灵感来自 Tatone26 的 All the AppsBased on 2048 by Gabriele Cirulli 改编自 Gabriele Cirulli 的 2048Based on Block Blast! by Hungry Studio 改编自 Hungry Studio 的 Block Blast!+Based on Suika Game by Aladdin X 改编自 Aladdin X 的西瓜游戏Based on Space Invaders by Taito 改编自 Taito 的 Space InvadersBased on Chrome's dinosaur game by Google 改编自 Google Chrome 的小恐龙游戏# a game the RAM of the calculator's software is too small fordiff --git a/tests/test_games.py b/tests/test_games.pyindex 443bc03a..19671a8a 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -69,6 +69,10 @@ GAMES = {# past how to play, two flaps; next time the run goes on after a flap"flappydunk": ("FlappyDunk.nwa", "flappydunk.sav", presses((1500, "ok"), (2200, "ok"), (2550, "ok")), 3500,presses((1500, "ok")), 2500),+ # past how to play, a fruit dropped, the cloud moved, another dropped; next time the box is still there, and one+ # more falls in+ "suika": ("SuikaGame.nwa", "suika.sav", presses((1500, "ok"), (2200, "ok"), (2600, "right", 400), (3600, "ok")), 4800,+ presses((1500, "ok")), 3000),# past how to play, a game started and a block placed; next time the tower is still there, waiting"towerblock": ("TowerBlocks.nwa", "towerblocks.sav", presses((1500, "ok"), (2200, "ok"), (3000, "ok")), 3600, [], 2500),"flappybird": ("FlappyBird.nwa", "flappy.sav",@@ -285,6 +289,9 @@ CHECKS = {# a run kept (guide read), the ball on its way; then further along the same run"flappydunk": (lambda v: len(v) == 200 and v[:2] == b"F\1" and v[2] & 3 == 3 and struct.unpack_from("<f", v, 24)[0] > 1,lambda v: v[2] & 1 and struct.unpack_from("<f", v, 24)[0] > 6),+ # a game kept (guide read) with fruit in the box; then one more+ "suika": (lambda v: len(v) == 1052 and v[:2] == b"S\1" and v[2] & 3 == 3 and sum(v[42 + 16 * i] > 0 for i in range(64)) >= 1,+ lambda v: v[2] & 1 and sum(v[42 + 16 * i] > 0 for i in range(64)) >= 2),# a tower kept (guide read) with one block placed; then kept as it was"towerblock": (lambda v: len(v) == 668 and v[:2] == b"T\1" and v[2] & 3 == 3 and struct.unpack_from("<I", v, 12)[0] == 1,lambda v: v[2] & 1 and struct.unpack_from("<I", v, 12)[0] == 1),diff --git a/tests/test_suika.py b/tests/test_suika.pydeleted file mode 100644index 66666034..00000000--- a/tests/test_suika.py+++ /dev/null@@ -1,198 +0,0 @@-#!/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/tests/test_upsilon.py b/tests/test_upsilon.pyindex 1f50e330..ad2703d2 100644--- a/tests/test_upsilon.py+++ b/tests/test_upsilon.py@@ -31,10 +31,11 @@ def main():st = os.path.join(a.out, "storage.bin")save = bytes(range(30))write_storage(st, [("pi.py", b"\x01print(3.14159)\n\x00"), ("snake.sav", save)])- # the home screen: Crossy Road, Block Blast, Portal Returns, Tetris, Chrome Dino, Chess...: Right five times, OK+ # the home screen: Crossy Road, Block Blast, Suika Game, Portal Returns, Tetris, Chrome Dino, Chess...: Right six times, OKc = emu.Calculator(a.nwa, storage_file=st)c.enable_checks(reads=True)- c.keys = presses((1200, "right"), (1600, "right"), (2000, "right"), (2400, "right"), (2800, "right"), (3200, "ok")) + \+ c.keys = presses((1200, "right"), (1600, "right"), (2000, "right"), (2400, "right"), (2800, "right"), (3200, "right"),+ (3600, "ok")) + \[(7400, 7800, emu.KEYS["home"])]menu = os.path.join(a.out, "chess.png")c.pending_shots = [(6900, menu)]