Skip to content

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

Update 2 Players with fifteen mini-games and fairer bots

Bobydeluxeafc8f3834bb6
diff --git a/.github/workflows/twoplayer.yml b/.github/workflows/twoplayer.yml
new file mode 100644
index 00000000..ad6df47d
--- /dev/null
+++ b/.github/workflows/twoplayer.yml
@@ -0,0 +1,52 @@
+name: 2 Players
+
+on:
+ pull_request:
+ paths:
+ - 'games/twoplayer/**'
+ - 'games/common/**'
+ - 'launcher/src/**'
+ - 'tools/emu.py'
+ - 'tools/gen_games.py'
+ - 'tools/npmodule.py'
+ - 'games/games.json'
+ - '.github/workflows/twoplayer.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ game:
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ - name: ARM toolchain
+ run: |
+ v=15.2.1-1.1
+ curl -fsSL "https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v$v/xpack-arm-none-eabi-gcc-$v-linux-x64.tar.gz" | tar -xz -C "$RUNNER_TEMP"
+ echo "$RUNNER_TEMP/xpack-arm-none-eabi-gcc-$v/bin" >> "$GITHUB_PATH"
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Tools
+ run: |
+ npm install -g [email protected]
+ pip install pillow==11.3.0 numpy pyelftools unicorn==2.1.4
+ - name: Existing game build and engine checks
+ run: |
+ make build/data/apps/TwoPlayers.nwa build/data/modules/twoplayer.o NWLINK=nwlink
+ make -C games/twoplayer build module check test HOST_CC=gcc NWLINK=nwlink
+ - name: ARM controls, saves and firmware guards
+ run: python3 games/twoplayer/tests/test_arm.py --nwlink nwlink
+ - name: Existing NumPlay launcher integration
+ run: python3 games/twoplayer/tests/test_integration.py --nwlink nwlink
+ - name: French and Chinese layouts
+ run: python3 games/twoplayer/tests/test_languages.py
+ - uses: actions/upload-artifact@v4
+ with:
+ name: TwoPlayers
+ path: build/data/apps/TwoPlayers.nwa
diff --git a/README.md b/README.md
index ece2d770..4b0fdee5 100644
--- a/README.md
+++ b/README.md
@@ -253,7 +253,7 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
- [x] Plants vs. Zombies: the whole Adventure, from the front lawn to the roof and Dr. Zomboss
- [x] Doom: Knee-Deep in the Dead, the shareware episode
- [x] Five Nights at Freddy's: all five nights, the 6th and the Custom Night
-- [x] Pong and more two-player games: 2 Players, with Pong, Air Hockey, Tanks and Light Cycles
+- [x] [2 Players](games/twoplayer/README.md): fifteen mini-games, with local two-player controls or three computer difficulties
- [x] Cookie Clicker
- [x] Level Devil
- [x] Sonic the Hedgehog: the whole 1991 game, Green Hill to the Final Zone, with the Special Stages
@@ -306,6 +306,8 @@ Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, an
## Credits
+- **[Bobydeluxe](https://github.com/Bobydeluxe)** added eleven mini-games to **[2 Players](games/twoplayer/README.md)** and updated its controls, readability and computer opponents while retaining the original four games and red/blue style.
+
NumPlay is a fan project, made out of love for these games and for the NumWorks calculator. If you enjoy a game here, go play the original and support the people who made it. NumWorks also has a great community of people making games by hand: try [Numcraft](https://github.com/yannis300307/NumcraftRust), [Celeste Classic](https://github.com/BenchatonDev/Celeste-Numworks), [Tatone26's All the Apps](https://github.com/Tatone26/Numworks-games), the apps on [Nwagyu](https://nwagyu.org/guide/) and [yannis300307's list](https://gist.github.com/yannis300307/9123136f90877107ec0d49ba96b303e5).
- **[Tatone26](https://github.com/Tatone26/Numworks-games)**'s **All the Apps** inspired NumPlay's list of classics. Flappy Bird, Pac-Man, Snake, Connect Four, Solitaire and 2048 are written in C for NumPlay and keep its options, with no code copied from it. Tetris is Tatone26's own, which they released into the public domain, adapted for NumPlay.
diff --git a/docs/media/thumb_twoplayer.png b/docs/media/thumb_twoplayer.png
index 7e805e2a..7d952a9a 100644
Binary files a/docs/media/thumb_twoplayer.png and b/docs/media/thumb_twoplayer.png differ
diff --git a/games/games.json b/games/games.json
index a8a86cfb..1797c5da 100644
--- a/games/games.json
+++ b/games/games.json
@@ -479,8 +479,8 @@
"id": "twoplayer",
"rank": 14,
"title": "2 Players",
- "tagline": "Pong and more, side by side",
- "credit": null,
+ "tagline": "Fifteen mini-games, side by side",
+ "credit": "Additional mini-games by Bobydeluxe",
"top": "0xD33B3B",
"bottom": "0x172A72",
"accent": "0x2E7CF6",
diff --git a/games/twoplayer/.gitignore b/games/twoplayer/.gitignore
index ea1472ec..179b4868 100644
--- a/games/twoplayer/.gitignore
+++ b/games/twoplayer/.gitignore
@@ -1 +1,3 @@
output/
+__pycache__/
+*.pyc
diff --git a/games/twoplayer/Makefile b/games/twoplayer/Makefile
index 2c6a58d2..f95d1be3 100644
--- a/games/twoplayer/Makefile
+++ b/games/twoplayer/Makefile
@@ -1,4 +1,4 @@
-# 2 Players — Pong, Air Hockey, Tanks, Light Cycles and Quick Draw, for two on one calculator.
+# 2 Players — fifteen mini-games inside the existing NumPlay app/module.
# make build output/twoplayer.nwa
# make check link the app like the calculator does (output/twoplayer.bin)
#
@@ -10,22 +10,27 @@ NWLINK ?= npx --yes -- [email protected]
BUILD_DIR = output
SRC = src/main.c
HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h ../../launcher/src/gfx.h \
- ../../launcher/src/np.h ../../launcher/src/font.h
+ ../../launcher/src/np.h ../../launcher/src/font.h src/party.h
+HOST_CC ?= cc
+PYTHON ?= python3
CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
# (smaller still: NumPlay has little room left)
CFLAGS += -fno-schedule-insns2 -fno-reorder-blocks -fno-tree-loop-optimize
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections -fstack-usage
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
+.PHONY: build check clean host test test-arm test-integration
build: $(BUILD_DIR)/twoplayer.nwa
check: $(BUILD_DIR)/twoplayer.nwa
- $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/twoplayer.bin
+ $(Q) $(NWLINK) nwa-bin --ram-length 107674 $< $(BUILD_DIR)/twoplayer.bin
+ $(Q) $(NWLINK) nwa-bin --ram-length 107674 $(BUILD_DIR)/twoplayer-debug.nwa $(BUILD_DIR)/twoplayer-debug.bin
+ $(Q) cmp $(BUILD_DIR)/twoplayer.bin $(BUILD_DIR)/twoplayer-debug.bin
@echo "BIN $(BUILD_DIR)/twoplayer.bin: $$(wc -c < $(BUILD_DIR)/twoplayer.bin) bytes"
# compiled, then linked (the link options would upset the compiler)
@@ -39,12 +44,23 @@ $(BUILD_DIR)/font_data.o: ../../launcher/src/font_data.c ../../launcher/src/font
$(BUILD_DIR)/xfont.o: ../../launcher/src/xfont.c ../../launcher/src/np_xfont.h $(HEADERS) | $(BUILD_DIR)
$(Q) $(CC) $(CFLAGS) -c $< -o $@
-$(BUILD_DIR)/twoplayer.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \
+$(BUILD_DIR)/twoplayer-debug.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \
$(BUILD_DIR)/icon.o
@echo "LD $@"
$(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+$(BUILD_DIR)/twoplayer.nwa: $(BUILD_DIR)/twoplayer-debug.nwa
+ $(Q) cp $< $@
$(Q) arm-none-eabi-strip --strip-unneeded $@
+host: test
+test: | $(BUILD_DIR)
+ $(HOST_CC) -std=c11 -O2 -Wall -Wextra -Wno-unused-parameter -Wno-misleading-indentation -ffunction-sections -fdata-sections -Itests tests/test.c ../../launcher/src/gfx.c ../../launcher/src/font_data.c ../../launcher/src/xfont.c -Wl,--gc-sections -lm -o $(BUILD_DIR)/test
+ cd $(BUILD_DIR) && ./test
+test-arm: build test
+ $(PYTHON) tests/test_arm.py --nwlink "$(NWLINK)"
+test-integration: module
+ $(PYTHON) tests/test_integration.py --nwlink "$(NWLINK)"
+
$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
@echo "ICON $<"
$(Q) $(NWLINK) png-icon-o $< $@
diff --git a/games/twoplayer/README.md b/games/twoplayer/README.md
index 8e81d23e..9bb9685d 100644
--- a/games/twoplayer/README.md
+++ b/games/twoplayer/README.md
@@ -1,39 +1,87 @@
# 2 Players
-Pong and three more games for two people on one calculator, side by side: player 1 on the arrows, player 2 on the keys around +, both at once. No one to play with? Player 2 can be the computer, easy, normal or hard.
+Fifteen mini-games inside the existing **2 Players** app in NumPlay, side by side: player 1 on the arrows, player 2 on the keys around +, both at once. No one to play with? Player 2 can be the computer, easy, normal or hard.
-<img src="docs/games.png" width="480" alt="Pong, Air Hockey, Tanks and Light Cycles">
+<img src="docs/games.png" width="640" alt="The fifteen 2 Players mini-games">
- **Pong**, the 1972 arcade game: black and white, the dashed net and the blocky scores. The paddle has eight segments: the two in the middle send the ball back straight, the others at steeper and steeper angles. The ball speeds up as a rally goes on, and the first to 11 wins.
- **Air Hockey**: a mallet each, in your own half, and a puck that slides and bounces off the rails and the goal posts. Hit it while you move to send it flying. First to 7.
- **Tanks**: a new maze every round, shells that bounce off the walls (five each at a time) and can hit the tank that fired them. First to 5 rounds.
- **Light Cycles**: never stop, never turn back, and make the other cycle crash into a wall or a trail. Two turns can wait in line, and the cycles speed up as the round goes on. First to 5 rounds.
- **Before each game**, a map of the calculator's keyboard lights up each player's keys in their colour, with the rules.
-- **The computer** plays every game: in Pong it works out where the ball will come and aims at the corners, in Air Hockey it gets behind the puck to shoot or guards its goal, its tank finds its way through the maze and plans shots off the walls, and its light cycle keeps the most room for itself and, on hard, cuts you off.
+- **The computer** has three approachable difficulty levels, with reaction delays, imperfect aiming and slower attack cadence. It does not borrow Player 2’s physical inputs in solo mode.
- **The matches won** by each side are kept for every game, against a friend and against the computer.
+## Eleven additional games
+
+The original four games keep their IDs, rules and artwork. The additions use the same red/blue teams, night-blue cards, rounded shapes, fonts, score bar and keyboard tutorial. There are no separate apps for these mini-games.
+
+| Game | How to play | First to |
+| --- | --- | ---: |
+| Quick Draw | Wait for DRAW, then press Action; a false start loses | 5 |
+| Tug of War | Tap and release Action to pull the flag across your line | 5 |
+| Football | Move, push the ball and kick with Action | 5 |
+| Volley Ball | Move sideways, jump with Up or Action; keep the ball off your floor | 7 |
+| Archery | Aim with Up/Down; follow the dotted trajectory, charge with OK / EXE and release to shoot | 5 |
+| Dodge Ball | Move in your half, throw with Action; three hits knock out | 5 |
+| Meteor Run | Move sideways; survive the same falling rocks as your rival | 5 |
+| Rocket Race | Tap Up or Action to fly through identical obstacle courses | 5 |
+| Sumo | Move and dash with Action; push your rival out of the shrinking ring | 5 |
+| Fishing | Move the rod, hold Action to lower the hook, release to reel in a fish | 5 |
+| Memory Duel | Watch a shared arrow sequence, then repeat it without a mistake | 5 |
+
+All fifteen games support two people and the existing easy/normal/hard computer choices. Simultaneous outcomes draw when possible. New survival/duel rounds have time limits; a tied round awards neither side a point. Each game's wins against a friend and against the computer are kept separately.
+
+<img src="docs/pages.png" width="640" alt="Four pages of mini-games in the existing red and blue menu">
+
## Controls
| | Player 1 | Player 2 |
| --- | --- | --- |
| Move (in Pong, up and down) | Arrows | × up, Ans down, 3 left, − right |
-| Fire (Tanks) | shift | EXE |
+| Action (shoot, jump, pull, dash, fish) | OK | EXE |
| Key | Action |
| --- | --- |
| Up, Down, OK | Pick a game, then OK to play |
+| 7, 9 | Previous / next page of four games |
| Left, Right | Player 2, or the computer: easy, normal, hard |
| Back | Pause: Resume, Restart, Other games, Quit game |
-| Home | Quit |
+| Home, Power | Save and quit |
+
+OK is Player 1’s Action key in both modes. Against the computer, EXE is also a solo alias; in two-player mode, EXE belongs only to Player 2. Shift is no longer used. Hold actions are supported for archery and fishing. Each tutorial highlights only the keys used by that game. Confirm keys held while opening a screen must be released before acting again.
+
+## Saves and footprint
+
+The same `twoplayer.sav` record is used. Original 36-byte version 1 saves and the previous sixteen-game version 2 saves migrate automatically. Version 3 uses 128 bytes with explicit little-endian encoding and CRC-32. Memory Duel's wins are kept when its ID moves; only the removed game's counters are discarded. If it was the last selection, the menu opens at Pong instead. A malformed save is rejected before changing progress. Full storage shows a retry / explicit unsaved-exit choice when quitting.
-Against the computer, OK and EXE fire too.
+The added games share **352 bytes** of working state, fixed projectile pools and procedural artwork; there are no imported images or sound files in the game. The installed standalone package is **53,912 bytes** (about 52.6 KiB). In NumPlay the module uses **33,597 bytes** of code/read-only data and **22,052 bytes** of shared arena RAM. It reuses the launcher's fonts and drawing functions. A fixed 8 ms physics step keeps gameplay independent of the LCD frame rate; rendering targets roughly 30 frames per second.
+
+## Readability and difficulty
+
+Archery now has clearly drawn bows and directional arrows, coloured trajectory dots, angle readouts, power gauges, hit feedback and three visible hearts. Hold OK / EXE to increase power and release to shoot. The preview follows the same gravity and launch power as the real arrow. The two-player keyboard tutorial highlights OK beside Player 1's arrows and keeps EXE on Player 2's side.
+
+The other games retain their established layouts. Targeted additions show Football's round clock, Dodge Ball's hearts, Rocket Race's boost flame and Fishing's hold/release prompts. Tanks' tutorial explicitly distinguishes driving from turning.
+
+Computer difficulty is reduced across all fifteen games: sampled movement decisions instead of instant tracking, lower movement speeds where needed, aiming errors, longer reloads, slower tugging and memory playback, and longer Quick Draw reactions. Light Cycles no longer predicts and blocks the player's next possible cells. Hard remains faster and more accurate than Easy, without the old perfect responses.
+
+<img src="docs/archery.png" width="480" alt="Archery with trajectory previews, power bars, visible arrows and hearts">
## Credits
**Pong** is Atari's arcade game (1972, by Allan Alcorn), whose paddles and ball this one follows. Air hockey, tanks duelling in a maze in the spirit of Tank Trouble, and the light cycles of the film Tron (1982) are classics of two-player games. Everything here is written in C for NumPlay and drawn from shapes as it goes, with no code or art from any of them.
-Inside NumPlay it draws with the launcher's own shapes and fonts and saves through its file functions, so the four games take about 13 KB.
+**Additional mini-games by [Bobydeluxe](https://github.com/Bobydeluxe)**. Inspired by the short local duels of [GoBattle 2](https://poki.com/fr/g/gobattle2) by YouDevice! and [12 MiniBattles](https://poki.com/fr/g/12-minibattles) by Shared Dreams Studio, together with familiar sports, reaction, memory and survival games. These are native calculator implementations using NumPlay's existing visual style, with no code, images or sounds imported from those games. The original four games remain credited to their existing authors and inspirations above.
It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `TwoPlayers.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
-Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink). `tools/bot.py` plays it against the computer in the emulator for these pictures.
+## Build and verification
+
+Build from this directory with `make build module check` (ARM GCC, Make and nwlink required). The normal NumPlay root build discovers the same `twoplayer` module and `TwoPlayers.nwa` release name through `games/games.json`; Upsilon includes it too.
+
+- `make test HOST_CC=gcc`: native mechanics, saves, complete CPU matches, random inputs and rendering.
+- `make test-arm PYTHON=python3`: actual ARM package, real keypad menus and firmware guards on four memory profiles (Python Unicorn, pyelftools and Pillow required).
+- `make test-integration PYTHON=python3`: compile the actual launcher with a deliberately single-module **test catalogue**, then verify module entry, return, re-entry and shared save backup. This test build is not a full NumPlay release.
+- `python3 tests/test_languages.py`: French/Chinese string coverage, font generation and the same host/layout checks. Nunito is downloaded from its upstream font source on the first run.
+
+See [VALIDATION.md](VALIDATION.md) for measured results and limits. No physical calculator was connected for these checks. `output/` holds generated reports and screenshots.
diff --git a/games/twoplayer/VALIDATION.md b/games/twoplayer/VALIDATION.md
new file mode 100644
index 00000000..dcf33487
--- /dev/null
+++ b/games/twoplayer/VALIDATION.md
@@ -0,0 +1,53 @@
+# Validation — 23 October 2026
+
+This updates the existing `twoplayer` module and `TwoPlayers.nwa`. There are now **15 games**: the original four plus eleven additions. Turtle Hop is removed. Player 1 uses **OK** for Action; Player 2 still uses **EXE**. No physical calculator was connected for these checks.
+
+## Build and footprint
+
+| Measurement | Result |
+| --- | ---: |
+| Release `.nwa` file | 93,728 bytes |
+| Installed flash | 53,912 bytes |
+| Standalone static RAM, including installer alignment | 22,065 bytes |
+| Highest measured standalone ARM stack in these runs | 580 bytes |
+| Module code and read-only data | 33,597 bytes |
+| Module shared arena RAM | 22,052 bytes |
+| Working state shared by the eleven additions | 352 bytes |
+| Save payload | 128 bytes |
+| Smallest tested installer RAM allocation | 107,674 bytes |
+
+Release SHA-256: `c4dba2cd62da31fe9ff72cdf13045b976019fedecc8dc741e32f2ebc659bd036`.
+
+ARM GCC passes with `-Wall -Wextra`. The release and debug packages convert with real nwlink at the smallest RAM allocation and produce identical installed bytes. The root Makefile's actual module and `build/data/apps/TwoPlayers.nwa` targets pass; the release copy matches the tested package.
+
+There are no imported textures, sounds or heap allocations for the mini-games. Artwork uses the existing shared shapes/fonts, fixed projectile pools and LCD strips. Physics stays on the fixed eight-millisecond step with bounded catch-up. The new bot intention cache is shared, rather than allocating one AI engine per game.
+
+## Gameplay and difficulty
+
+All fifteen bots were reviewed. Pong/Hockey use slower, sampled targeting with aiming error. Tanks reacts and reloads more slowly, moves more slowly, and has less accurate bank shots. Light Cycles has delayed decisions and limited lookahead, with no prediction of the player's future cells. The additions receive longer reaction times, reduced movement/attack rates, imperfect archery and throwing accuracy, and slower/error-prone memory responses. Two-human movement and physics do not get these bot handicaps.
+
+- **33 complete matches** cover the eleven additions at all three difficulties against an idle human. CPU decisions are real; no score injection or forced completion is used. This checks progress, not human difficulty balance.
+- **150 seeded random-input runs** cover all fifteen games and opponent modes, checking score bounds and finite state.
+- **120 additional scripted-player matches** exercise Quick Draw and Archery, twenty per difficulty per game. The 420 ms reaction policy wins Quick Draw in [20, 20, 16] matches at Easy/Normal/Hard. The 650 ms charge / 1.8 s shot-cycle policy wins Archery in [20, 20, 20] matches. These reproducible policies show the bots are beatable; they are not human play-test results.
+- Tug of War is won against each bot with five presses per second. Pong and Football explicitly wait before reacting. A solo EXE action cannot also trigger the bot.
+- Targeted regression checks cover false starts/ties, tap debouncing, goals/rebounds, volley net-top collisions, charged arrows/hits, dodge-ball knockouts, mirrored obstacles, rocket bounds, sumo, fishing hold/reel/contested catches and memory watch/input/error/tie rules.
+
+## Readability and controls
+
+Archery is rebuilt with visible bows, directional arrows, player-coloured trajectory dots, angle values, power bars, hit flashes and three hearts. The trajectory uses the same launch/gravity formula as the real arrow, with the small integration difference of an eight-millisecond tick. The tutorial explicitly explains charging/releasing and the new OK/EXE layout.
+
+The review keeps the established layouts where they already communicate the rules. Selected improvements add Football's clock, Dodge Ball's hearts, Rocket Race's boost flame and Fishing's hold/release prompts. Tanks' rules distinguish driving and turning. Menu pagination handles a last page containing three games, including page wrapping from its final row.
+
+All fifteen rules/game screens, four menu pages, pause/results/failure cards are rendered. English, French and Chinese run the same native engine and text-height checks with the real Nunito/Fusion Pixel fonts. Representative screenshots and actual ARM Archery charging/flight frames were visually inspected.
+
+## Saves and actual ARM checks
+
+The original 36-byte v1 save migrates with all sixteen original win counters preserved. The 136-byte v2 format migrates to 128-byte v3: the removed game's counters are dropped, Memory Duel's counters move intact to its new ID, and selecting the removed game falls back to Pong. Old Memory selection restores Memory correctly. Both v2 cases also run through the installed ARM package. V3 round trips, truncation and every individual flipped save bit are tested without mutating progress on rejection.
+
+The compiled app passes N0120, N0110, the smaller N0115 allocation and Upsilon profiles. Each opens all fifteen games through real keys and checks pause/resume/restart, selection and page wrapping. Real OK and EXE presses score independently in Quick Draw. In Archery, both keys charge and release independently; Shift does nothing, and real arrows remain in flight after release. Home/Power saves, relaunch, held launch keys and full-storage retry/explicit unsaved exit are checked. Unrelated records stay intact.
+
+Memory guards check unaligned storage accesses, flash writes, firmware RAM preservation, cleaned app RAM on exit and balanced Home locks. Upsilon makes no unsupported Epsilon-only system calls.
+
+`tests/test_integration.py` compiles the actual launcher and module pipeline with a deliberately one-module **test catalogue**. N0120 and Upsilon open 2 Players, start a game, return to the carousel, re-enter and exit safely. The real record and NumPlay's Python backup are verified. Maximum measured launcher/integration stack is 1,056 bytes. This is not a full release build of every unrelated NumPlay game.
+
+Reports/screenshots are generated under ignored `output/`: `build-report.json`, `host-report.json`, `balance-report.json`, `arm/report.json`, `integration/report.json` and `languages/`. Commands are in [README.md](README.md). Physical LCD/key-matrix behaviour and subjective difficulty still need play testing on a calculator.
diff --git a/games/twoplayer/docs/archery.png b/games/twoplayer/docs/archery.png
new file mode 100644
index 00000000..943d3f8d
Binary files /dev/null and b/games/twoplayer/docs/archery.png differ
diff --git a/games/twoplayer/docs/games.png b/games/twoplayer/docs/games.png
index 0c8c9b65..b2b77613 100644
Binary files a/games/twoplayer/docs/games.png and b/games/twoplayer/docs/games.png differ
diff --git a/games/twoplayer/docs/pages.png b/games/twoplayer/docs/pages.png
new file mode 100644
index 00000000..d36f1e7c
Binary files /dev/null and b/games/twoplayer/docs/pages.png differ
diff --git a/games/twoplayer/docs/shot.png b/games/twoplayer/docs/shot.png
index 7e91494f..98ab65ca 100644
Binary files a/games/twoplayer/docs/shot.png and b/games/twoplayer/docs/shot.png differ
diff --git a/games/twoplayer/lang/fr.txt b/games/twoplayer/lang/fr.txt
index 6bf2f85b..95a4a34f 100644
--- a/games/twoplayer/lang/fr.txt
+++ b/games/twoplayer/lang/fr.txt
@@ -5,7 +5,6 @@ Tanks Tanks
Light Cycles Motos de lumière
Return the ball with your paddle: its middle sends the ball back straight, its ends at a steep angle. The longer a rally lasts, the faster the ball. Renvoie la balle avec ta raquette : son milieu la renvoie tout droit, ses bouts en biais. Plus l'échange dure, plus la balle va vite.
Knock the puck into the other goal. Your mallet stays in your half; hit the puck on the move to send it flying. Envoie le palet dans l'autre but. Ton maillet reste dans ta moitié ; frappe le palet en bougeant pour qu'il file.
-Drive through the maze and hit the other tank. Shells bounce off the walls: watch out for your own! Roule dans le labyrinthe et touche l'autre tank. Les obus rebondissent sur les murs : gare aux tiens !
Steer your light cycle and make the other one crash into a wall or a trail. It never stops and never turns back. Pilote ta moto de lumière et fais percuter l'autre contre un mur ou une traînée. Elle ne s'arrête et ne recule jamais.
Computer IA
Player 2 Joueur 2
@@ -31,3 +30,45 @@ Rematch Revanche
No Non
Yes Oui
Quit game? Quitter ?
+
+# Additional mini-games
+Quick Draw Duel éclair
+Tug of War Tir à la corde
+Football Football
+Volley Ball Volley
+Archery Tir à l'arc
+Dodge Ball Balle au prisonnier
+Meteor Run Météores
+Rocket Race Fusées
+Sumo Sumo
+Fishing Pêche
+Memory Duel Duel de mémoire
+Wait for DRAW, then press your action key. A false start loses the round. Simultaneous shots draw. Attends le signal, puis appuie sur Action. Un faux départ perd la manche. Tirs simultanés : égalité.
+Tap your action key to pull the rope. Release between pulls: holding does not repeat. Drag the flag past your line. Appuie puis relâche Action pour tirer. Maintenir ne répète pas. Fais passer le drapeau derrière ta ligne.
+Move around the pitch and kick with your action key. Push the ball into the other goal; rebounds stay in play. Déplace-toi et tire avec Action. Envoie le ballon dans le but adverse. Les rebonds restent en jeu.
+Move left and right; Up or your action key jumps. Keep the ball off your floor and send it over the net. Va à gauche ou à droite ; Haut ou Action fait sauter. Renvoie la balle au-dessus du filet sans la laisser tomber.
+Move in your half and throw with your action key. Dodge incoming balls. Three hits knock a player out. Déplace-toi dans ta moitié et lance avec Action. Évite les balles. Trois impacts éliminent un joueur.
+Move left and right to dodge the falling rocks. Both lanes get the same obstacles. Stay alive longer than your rival. Va à gauche ou à droite pour éviter les rochers. Les deux pistes sont identiques. Survis plus longtemps que ton rival.
+Tap Up or your action key to boost your rocket. Fly through the gaps; avoid the walls. Both pilots face the same course. Haut ou Action propulse ta fusée. Vole dans les ouvertures sans toucher les murs. Le parcours est le même pour les deux.
+Move inside the ring. Your action key dashes and pushes your rival. Stay inside: the ring gradually shrinks. Bouge dans le cercle. Action fait charger pour pousser ton rival. Reste à l'intérieur : le cercle rétrécit.
+Move your rod left and right. Hold your action key to lower the hook; release to reel in a fish. Catch five first. Déplace ta canne. Maintiens Action pour descendre le crochet ; relâche pour remonter un poisson. Premier à cinq.
+Watch the arrow sequence, then repeat it with your direction keys. The first correct sequence wins; a wrong arrow loses. Observe les flèches, puis répète la suite avec les directions. Le premier sans faute gagne ; une erreur fait perdre.
+DRAW! GO !
+Wait... Attends...
+Too soon loses the round Trop tôt : manche perdue
+Tap, release, pull! Appuie, relâche, tire !
+Repeat the arrows! Répète les flèches !
+Watch the arrows Observe les flèches
+7 / 9: page 7 / 9 : page
+Use direction keys Touches de direction
+Retry saving Réessayer
+Exit without saving Quitter sans sauver
+Save failed Échec de sauvegarde
+Aim with Up and Down. Hold OK (player 1) or EXE (player 2) to charge; release to shoot. The dotted arc shows your shot. Three hits win the round. Haut/Bas pour viser. Maintiens OK (J1) ou EXE (J2), puis relâche pour tirer. Les pointillés montrent le tir. Trois impacts gagnent.
+Power Puissance
+Hold OK / EXE, release to shoot Maintiens OK / EXE, relâche pour tirer
+Action: OK / EXE Action : OK / EXE
+Up/Down drive; Left/Right turn. OK (player 1) or EXE (player 2) fires. Shells bounce off walls and can hit your own tank! Haut/Bas pour avancer ou reculer, Gauche/Droite pour tourner. OK (J1) ou EXE (J2) tire. Les obus rebondissent : gare aux tiens !
+Release! Relâche !
+Hold OK Maintiens OK
+Hold EXE Maintiens EXE
diff --git a/games/twoplayer/lang/zh.txt b/games/twoplayer/lang/zh.txt
index 7f16e822..66fc60ef 100644
--- a/games/twoplayer/lang/zh.txt
+++ b/games/twoplayer/lang/zh.txt
@@ -5,7 +5,6 @@ Tanks 坦克大战
Light Cycles 光速摩托
Return the ball with your paddle: its middle sends the ball back straight, its ends at a steep angle. The longer a rally lasts, the faster the ball. 用球拍把球打回去:拍子中间把球直直打回,两端打出斜角。来回越久,球越快。
Knock the puck into the other goal. Your mallet stays in your half; hit the puck on the move to send it flying. 把冰球打进对方球门。你的球槌只能在自己半场;边移动边击球,球就会飞出去。
-Drive through the maze and hit the other tank. Shells bounce off the walls: watch out for your own! 在迷宫里开坦克,击中对方。炮弹会在墙上反弹:小心别打到自己!
Steer your light cycle and make the other one crash into a wall or a trail. It never stops and never turns back. 驾驶你的光速摩托,让对方撞上墙壁或光轨。摩托从不停下,也不能掉头。
Computer 电脑
Player 2 玩家 2
@@ -31,3 +30,45 @@ Rematch 再来一局
No 否
Yes 是
Quit game? 退出游戏?
+
+# Additional mini-games
+Quick Draw 极速对决
+Tug of War 拔河
+Football 足球
+Volley Ball 排球
+Archery 射箭
+Dodge Ball 躲避球
+Meteor Run 陨石闪避
+Rocket Race 火箭竞速
+Sumo 相扑
+Fishing 钓鱼
+Memory Duel 记忆对决
+Wait for DRAW, then press your action key. A false start loses the round. Simultaneous shots draw. 等待开枪信号,再按行动键。抢先开枪会输;同时开枪则平局。
+Tap your action key to pull the rope. Release between pulls: holding does not repeat. Drag the flag past your line. 反复按下并松开行动键来拉绳。长按不会重复。把旗子拉过你的线。
+Move around the pitch and kick with your action key. Push the ball into the other goal; rebounds stay in play. 在球场移动,用行动键踢球。把球踢进对方球门;球会在边线反弹。
+Move left and right; Up or your action key jumps. Keep the ball off your floor and send it over the net. 左右移动,用上键或行动键跳跃。把球打过球网,别让它落在己方地上。
+Move in your half and throw with your action key. Dodge incoming balls. Three hits knock a player out. 在己方半场移动,用行动键投球。躲避来球,被击中三次就出局。
+Move left and right to dodge the falling rocks. Both lanes get the same obstacles. Stay alive longer than your rival. 左右移动躲避陨石。两条赛道的障碍完全相同,比对手坚持更久。
+Tap Up or your action key to boost your rocket. Fly through the gaps; avoid the walls. Both pilots face the same course. 按上键或行动键推进火箭。穿过空隙,避开墙壁。两位飞行员面对同一赛道。
+Move inside the ring. Your action key dashes and pushes your rival. Stay inside: the ring gradually shrinks. 在圆环里移动。行动键冲刺并推开对手。别出界,圆环会逐渐缩小。
+Move your rod left and right. Hold your action key to lower the hook; release to reel in a fish. Catch five first. 左右移动鱼竿。按住行动键放下鱼钩,松开收竿。先钓到五条鱼获胜。
+Watch the arrow sequence, then repeat it with your direction keys. The first correct sequence wins; a wrong arrow loses. 先记住箭头顺序,再用方向键重复。先正确完成者获胜,按错就输。
+DRAW! 开枪!
+Wait... 等等……
+Too soon loses the round 抢先行动会输
+Tap, release, pull! 按下、松开、拉!
+Repeat the arrows! 重复箭头!
+Watch the arrows 记住箭头
+7 / 9: page 7 / 9:翻页
+Use direction keys 使用方向键
+Retry saving 重试保存
+Exit without saving 不保存退出
+Save failed 保存失败
+Aim with Up and Down. Hold OK (player 1) or EXE (player 2) to charge; release to shoot. The dotted arc shows your shot. Three hits win the round. 用上下键瞄准。玩家1按住OK,玩家2按住EXE蓄力,松开射箭。虚线显示轨迹,命中三次获胜。
+Power 力度
+Hold OK / EXE, release to shoot 按住OK / EXE,松开射箭
+Action: OK / EXE 行动:OK / EXE
+Up/Down drive; Left/Right turn. OK (player 1) or EXE (player 2) fires. Shells bounce off walls and can hit your own tank! 上下键前后移动,左右键转向。玩家1按OK,玩家2按EXE开火。炮弹会反弹,小心自己的炮弹!
+Release! 松开!
+Hold OK 按住OK
+Hold EXE 按住EXE
diff --git a/games/twoplayer/src/main.c b/games/twoplayer/src/main.c
index 66cd8ec5..eba40770 100644
--- a/games/twoplayer/src/main.c
+++ b/games/twoplayer/src/main.c
@@ -1,6 +1,6 @@
-/* 2 Players: Pong and three more games for two people on one calculator.
+/* 2 Players: fifteen mini-games for two people on one calculator.
*
- * Player 1 holds the left of the keyboard (the arrows, and shift to fire), player 2 the right
+ * Player 1 holds the left of the keyboard (the arrows, and OK for action), player 2 the right
* (the keys around +, and EXE to fire), both at once; or player 2 is the computer, easy, normal
* or hard. Pong plays as the 1972 arcade game does; then Air Hockey, Tanks in a maze with
* shells that bounce off the walls, and Light Cycles. A match is first to a few points, and the
@@ -11,6 +11,7 @@
* along. Positions are in 256ths of a pixel and time in milliseconds, but for the round things
* of Air Hockey. */
#include <eadk.h>
+#include <string.h>
#include "../../../launcher/src/gfx.h"
#include "../../common/np_text.h"
@@ -33,14 +34,32 @@ void np_push(int x, int y, int w, int h, const color_t *px) {
#define INK HEX(0x161A33) /* the menus' night blue */
#define GOLD HEX(0xFFC93C)
-enum { PONG, HOCKEY, TANKS, CYCLES, NG };
-static const char *const NAME[NG] = {T("Pong"), T("Air Hockey"), T("Tanks"), T("Light Cycles")};
-static const uint8_t TARGET[NG] = {11, 7, 5, 5}; /* first to */
+/* IDs 0..3 are the original games and remain stable in existing saves. */
+enum { PONG, HOCKEY, TANKS, CYCLES, QUICK, TUG, FOOTBALL, VOLLEY,
+ ARCHERY, DODGE, METEORS, ROCKETS, SUMO, FISHING, MEMORY, NG };
+static const char *const NAME[NG] = {T("Pong"), T("Air Hockey"), T("Tanks"), T("Light Cycles"),
+ T("Quick Draw"), T("Tug of War"), T("Football"), T("Volley Ball"),
+ T("Archery"), T("Dodge Ball"), T("Meteor Run"), T("Rocket Race"),
+ T("Sumo"), T("Fishing"), T("Memory Duel")};
+static const uint8_t TARGET[NG] = {11, 7, 5, 5, 5, 5, 5, 7, 5, 5, 5, 5, 5, 5, 5};
+/* left=1, up=2, down=4, right=8, action=16; used by the keyboard tutorial. */
+static const uint8_t CONTROL[NG] = {6,15,31,15,16,16,31,27,22,31,9,18,31,25,15};
static const char *const RULES[NG] = {
T("Return the ball with your paddle: its middle sends the ball back straight, its ends at a steep angle. The longer a rally lasts, the faster the ball."),
T("Knock the puck into the other goal. Your mallet stays in your half; hit the puck on the move to send it flying."),
- T("Drive through the maze and hit the other tank. Shells bounce off the walls: watch out for your own!"),
+ T("Up/Down drive; Left/Right turn. OK (player 1) or EXE (player 2) fires. Shells bounce off walls and can hit your own tank!"),
T("Steer your light cycle and make the other one crash into a wall or a trail. It never stops and never turns back."),
+ T("Wait for DRAW, then press your action key. A false start loses the round. Simultaneous shots draw."),
+ T("Tap your action key to pull the rope. Release between pulls: holding does not repeat. Drag the flag past your line."),
+ T("Move around the pitch and kick with your action key. Push the ball into the other goal; rebounds stay in play."),
+ T("Move left and right; Up or your action key jumps. Keep the ball off your floor and send it over the net."),
+ T("Aim with Up and Down. Hold OK (player 1) or EXE (player 2) to charge; release to shoot. The dotted arc shows your shot. Three hits win the round."),
+ T("Move in your half and throw with your action key. Dodge incoming balls. Three hits knock a player out."),
+ T("Move left and right to dodge the falling rocks. Both lanes get the same obstacles. Stay alive longer than your rival."),
+ T("Tap Up or your action key to boost your rocket. Fly through the gaps; avoid the walls. Both pilots face the same course."),
+ T("Move inside the ring. Your action key dashes and pushes your rival. Stay inside: the ring gradually shrinks."),
+ T("Move your rod left and right. Hold your action key to lower the hook; release to reel in a fish. Catch five first."),
+ T("Watch the arrow sequence, then repeat it with your direction keys. The first correct sequence wins; a wrong arrow loses."),
};
/* twoplayer.sav: the game last chosen, who player 2 is, and the matches won */
@@ -59,7 +78,7 @@ static int pad[2], tap[2]; /* each player's keys held, and just
enum { B_LEFT = 1, B_UP = 2, B_DOWN = 4, B_RIGHT = 8, B_FIRE = 16 };
/* the keys: left, up, down, right, fire */
static const uint8_t KEYS[2][5] = {
- {eadk_key_left, eadk_key_up, eadk_key_down, eadk_key_right, eadk_key_shift},
+ {eadk_key_left, eadk_key_up, eadk_key_down, eadk_key_right, eadk_key_ok},
{eadk_key_three, eadk_key_multiplication, eadk_key_ans, eadk_key_minus, eadk_key_exe}};
static uint32_t rnd(void) {
@@ -76,6 +95,16 @@ static bool down(uint64_t keys, int k) { return (uint32_t)(keys >> (k & 32)) >>
static bool is_cpu(int p) { return p && cpu; }
static int dirx(int p) { return !!(pad[p] & B_RIGHT) - !!(pad[p] & B_LEFT); }
static int diry(int p) { return !!(pad[p] & B_DOWN) - !!(pad[p] & B_UP); }
+/* CPU intentions are sampled, never recomputed with perfect reflexes every tick.
+ * Each round starts with a short observation delay, and harder still leaves
+ * a human reaction window. The two-human input path never uses this state. */
+static struct { uint32_t next; float x,y; int pad; } bot;
+static bool bot_due(void) {
+ if((int32_t)(now-bot.next)<0)return false;
+ bot.next=now+(cpu==1?340:cpu==2?240:160)+rn(cpu==1?140:cpu==2?100:70);
+ return true;
+}
+static void bot_input(void) { pad[1]=bot.pad;tap[1]=0; }
/* sine of a 64th of a turn, times 127 */
static const int8_t SINQ[17] = {0, 12, 25, 37, 49, 60, 71, 81, 90, 98, 106, 112, 117, 122, 125, 126, 127};
static int sin64(int a) {
@@ -128,21 +157,26 @@ static uint32_t serve_at; /* the ball waits in the middle until then (0: in play
static int pong_speed(void) { return hits >= 12 ? clampi(46 + hits, 58, 84) : hits >= 4 ? 48 : 38; }
static void pong_start(void) { /* the ball is served towards the one who lost the point */
int to = winner < 2 ? 1 - winner : rn(2);
- hits = aim = 0;
+ hits = aim = 0;bot.y=120<<8;
bx = (160 - BS / 2) << 8, by = (70 + rn(100)) << 8, bvx = to ? 1 : -1, bvy = rn(9) - 4;
serve_at = now + 900;
if (!score[0] && !score[1]) py[0] = py[1] = (120 - PH / 2) << 8;
}
/* the computer's paddle (player 2): to where the ball will come, off centre by its aim */
static int pong_cpu(void) {
- static const uint8_t SPEED[4] = {0, 32, 46, 64};
- int to = 120 << 8, v = SPEED[cpu];
- if (bvx > 0 && !serve_at && bx > (cpu == 1 ? 170 << 8 : cpu == 2 ? 100 << 8 : 0)) {
- int span = (PBOT - BS - PTOP) << 8, y = by - (PTOP << 8) + bvy * (((PX[1] - BS) << 8) - bx) / bvx;
- for (int i = 0; i < 8 && (y < 0 || y > span); i++) y = y < 0 ? -y : 2 * span - y;
- to = y + ((PTOP + BS / 2) << 8) - aim;
+ static const uint8_t SPEED[4]={0,20,30,40};
+ if(bot_due()){
+ int to=120<<8;
+ if(bvx>0&&!serve_at&&bx>(cpu==1?190<<8:cpu==2?145<<8:90<<8)){
+ int span=(PBOT-BS-PTOP)<<8,y=by-(PTOP<<8)+bvy*(((PX[1]-BS)<<8)-bx)/bvx;
+ for(int i=0;i<8&&(y<0||y>span);i++)y=y<0?-y:2*span-y;
+ to=y+((PTOP+BS/2)<<8)-aim;
+ }
+ int error=cpu==1?20:cpu==2?12:7;
+ bot.y=clampi(to+(rn(error*2+1)-error)*256,PTOP<<8,PBOT<<8);
}
- return clampi((to - py[1] - (PH << 7)) / 32, -v, v);
+ int delta=(int)bot.y-py[1]-(PH<<7);
+ return clampi(delta/40,-SPEED[cpu],SPEED[cpu]);
}
static void pong_step(void) {
for (int p = 0; p < 2; p++)
@@ -200,6 +234,7 @@ static float mx[2], my[2], mvx[2], mvy[2], qx, qy, qvx, qvy, qaim;
static void hockey_start(void) { /* the puck to the one who was scored on */
int to = winner < 2 ? 1 - winner : rn(2);
for (int p = 0; p < 2; p++) mx[p] = p ? RX1 - 40 : RX0 + 40, my[p] = RYM, mvx[p] = mvy[p] = 0;
+ bot.x=RX1-40;bot.y=RYM;
qx = to ? 220 : 100, qy = RYM, qvx = qvy = 0, qaim = (float)(rn(44) - 22); /* where the computer aims */
}
/* the puck off something round at (x, y) moving at (vx, vy) */
@@ -212,10 +247,11 @@ static void knock(float x, float y, float vx, float vy, float r) {
if (vn < 0) qvx -= 1.85f * vn * dx, qvy -= 1.85f * vn * dy;
}
static void hockey_step(void) {
- static const float V[4] = {0, 120, 175, 235};
+ static const float V[4] = {0, 90, 130, 175};
for (int p = 0; p < 2; p++) {
float tx, ty, k = clampf(ms * 0.014f, 0, 1);
if (is_cpu(p)) { /* behind the puck to shoot it at the other goal, or guarding its own */
+ if(bot_due()) {
tx = RX1 - 36, ty = RYM + (qy - RYM) / 2;
if (qx > 160 - QR && !phase) {
float ax = RX0 - qx, ay = RYM + qaim - qy, l = len(ax, ay);
@@ -224,7 +260,9 @@ static void hockey_step(void) {
if (mx[1] < qx + 2) tx = qx + MR + QR + 10, ty = qy + (qy > RYM ? -28 : 28); /* in front of it: go round */
else if (len(tx - mx[1], ty - my[1]) < 7) tx = qx + ax * 24, ty = qy + ay * 24; /* strike */
}
- tx -= mx[1], ty -= my[1];
+ bot.x=tx;bot.y=ty+(rn(cpu==1?37:cpu==2?23:13)-(cpu==1?18:cpu==2?11:6));
+ }
+ tx=bot.x-mx[1];ty=bot.y-my[1];
float l = len(tx, ty) + 0.01f, v = V[cpu] * (l < 16 ? l / 16 : 1) / l;
tx *= v, ty *= v;
} else {
@@ -393,14 +431,14 @@ static bool shot_finds(int a, int b) {
/* the computer's tank: a shot when there is one to take, else the way to the player, cell by
cell through the maze (found breadth first from the player) */
static void tanks_cpu(int *v, int *turn) {
- static const int16_t RELOAD[4] = {0, 1500, 950, 550};
- static const int8_t BOUNCES[4] = {0, 0, 1, 3};
+ static const int16_t RELOAD[4] = {0, 2300, 1700, 1200};
+ static const int8_t BOUNCES[4] = {0, 0, 0, 1};
int dir = ta[1] >> 8, want = dir;
- if (ago(ai_t) > 300) {
+ if (ago(ai_t) > (uint32_t)(cpu==1?700:cpu==2?500:350)) {
ai_t = now, ai_aim = -1;
for (int i = 0; i < 64 && ai_aim < 0; i++) { /* the nearest to where it faces first */
int a = (dir + (i & 1 ? 1 : -1) * ((i + 1) / 2)) & 63;
- if (shot_finds(a, BOUNCES[cpu])) ai_aim = (a + (cpu == 1 ? rn(5) - 2 : 0)) & 63;
+ if (shot_finds(a, BOUNCES[cpu])) ai_aim = (a + rn(cpu==1?11:cpu==2?7:3) - (cpu==1?5:cpu==2?3:1)) & 63;
}
}
if (ai_aim >= 0) {
@@ -422,10 +460,10 @@ static void tanks_cpu(int *v, int *turn) {
int d = (gx >> 8) * cos64(a) + (gy >> 8) * sin64(a);
if (d > best) best = d, want = a;
}
- *v = clampi(6 - (((want - dir + 32) & 63) - 32) * (((want - dir + 32) & 63) - 32), 0, 1) * 70;
+ *v = clampi(6 - (((want - dir + 32) & 63) - 32) * (((want - dir + 32) & 63) - 32), 0, 1) * (cpu==1?45:cpu==2?55:64);
}
int d = ((want - dir + 32) & 63) - 32;
- *turn = d > 0 ? 8 : d < 0 ? -8 : 0;
+ *turn = d > 0 ? 4+cpu : d < 0 ? -4-cpu : 0;
}
static void tanks_step(void) {
for (int p = 0; p < 2; p++) {
@@ -535,25 +573,21 @@ static int room(int x, int y, int cap) {
}
return n;
}
-/* the computer's way: the turn that leaves it the most room; hard, it counts the cells the
- player could take next as taken, and with room to spare it goes to cut the player off */
+/* Choose space at human reaction intervals, without predicting the player's
+ future cells. Look a little ahead so slower decisions can still avoid a wall. */
static int cycles_cpu(void) {
- static const int16_t CAP[4] = {0, 30, 300, 900};
+ if(!bot_due())return hd[1];
+ static const int16_t CAP[4] = {0, 12, 70, 220};
int best = hd[1], bv = -(1 << 30);
- uint8_t *taken[3] = {0};
- for (int d = 0; d < 3 && cpu == 3; d++) {
- int x = hx[0] + DX[(hd[0] + d + 3) & 3], y = hy[0] + DY[(hd[0] + d + 3) & 3];
- if (free_at(x, y)) taken[d] = &cell[y][x], cell[y][x] = 3;
- }
for (int t = 0; t < 3; t++) {
int d = (hd[1] + t + (t == 2)) & 3, x = hx[1] + DX[d], y = hy[1] + DY[d], r = room(x, y, CAP[cpu]);
- int v = r * 8 + (t ? 0 : 6) + rn(cpu == 1 ? 120 : 6), ex = x - hx[0] - 6 * DX[hd[0]], ey = y - hy[0] - 6 * DY[hd[0]];
- if (cpu == 3 && r >= CAP[3]) v -= (ex < 0 ? -ex : ex) + (ey < 0 ? -ey : ey);
+ int v = r * 8 + (t ? 0 : 6) + rn(cpu == 1 ? 120 : 6);
+ int ahead=0;
+ while(ahead<7&&free_at(x+ahead*DX[d],y+ahead*DY[d]))ahead++;
+ v+=ahead*48;
if (!r) v = -(1 << 29);
if (v > bv) bv = v, best = d;
}
- for (int d = 0; d < 3; d++)
- if (taken[d]) *taken[d] = 0;
return best;
}
static void cycles_step(void) {
@@ -601,21 +635,77 @@ static void cycles_paint(void) {
}
}
-static void (*const START[NG])(void) = {pong_start, hockey_start, tanks_start, cycles_start};
-static void (*const STEP_[NG])(void) = {pong_step, hockey_step, tanks_step, cycles_step};
-static void (*const PAINT[NG])(void) = {pong_paint, hockey_paint, tanks_paint, cycles_paint};
+#include "party.h"
+static void (*const START[NG])(void) = {pong_start,hockey_start,tanks_start,cycles_start,
+ quick_start,tug_start,football_start,volley_start,archery_start,dodge_start,
+ meteors_start,rockets_start,sumo_start,fishing_start,memory_start};
+static void (*const STEP_[NG])(void) = {pong_step,hockey_step,tanks_step,cycles_step,
+ quick_step,tug_step,football_step,volley_step,archery_step,dodge_step,
+ meteors_step,rockets_step,sumo_step,fishing_step,memory_step};
+static void (*const PAINT[NG])(void) = {pong_paint,hockey_paint,tanks_paint,cycles_paint,
+ quick_paint,tug_paint,football_paint,volley_paint,archery_paint,dodge_paint,
+ meteors_paint,rockets_paint,sumo_paint,fishing_paint,memory_paint};
/* ------------------------------------------------------------ screens */
-enum { S_MENU, S_RULES, S_PLAY, S_PAUSE, S_ASK, S_OVER };
+enum { S_MENU, S_RULES, S_PLAY, S_PAUSE, S_ASK, S_OVER, S_SAVE_ERROR };
static int screen, sel, back_to;
-static void save(void) {
- sv.magic = 'P', sv.version = 1, sv.game = (uint8_t)game, sv.cpu = (uint8_t)cpu;
- np_file_write(SAVE_NAME, &sv, sizeof sv);
+#define SAVE_BYTES (8+NG*8)
+static uint32_t save_crc(const uint8_t*d,unsigned n) {
+ uint32_t c=~0u;while(n--){c^=*d++;for(int k=0;k<8;k++)c=c>>1^((c&1)?0xEDB88320u:0);}return ~c;
+}
+static void save_encode(uint8_t*out) {
+ out[0]='P';out[1]=3;out[2]=(uint8_t)game;out[3]=(uint8_t)cpu;
+ for(unsigned g=0;g<NG;g++)for(unsigned m=0;m<2;m++)for(unsigned p=0;p<2;p++){
+ unsigned i=g*4+m*2+p;uint16_t count=sv.wins[g][m][p];
+ out[4+i*2]=(uint8_t)count;out[5+i*2]=(uint8_t)(count>>8);
+ }
+ uint32_t crc=save_crc(out,SAVE_BYTES-4);for(int i=0;i<4;i++)out[SAVE_BYTES-4+i]=(uint8_t)(crc>>(8*i));
+}
+static bool save_decode(const uint8_t*d,unsigned n) {
+ if(!d||n<4||d[0]!='P'||d[3]>3)return false;
+ unsigned count;
+ if(d[1]==1&&n==36&&d[2]<4)count=4;
+ else if((d[1]==2&&n==136&&d[2]<16)||(d[1]==3&&n==SAVE_BYTES&&d[2]<NG)){
+ uint32_t crc=0;for(int i=0;i<4;i++)crc|=(uint32_t)d[n-4+i]<<(8*i);
+ if(crc!=save_crc(d,n-4))return false;
+ count=d[1]==2?16:NG;
+ }else return false;
+ memset(&sv,0,sizeof sv);sv.magic='P';sv.version=3;sv.game=d[1]==2?(d[2]==14?PONG:d[2]==15?MEMORY:d[2]):d[2];sv.cpu=d[3];
+ for(unsigned g=0;g<count;g++)for(unsigned m=0;m<2;m++)for(unsigned p=0;p<2;p++){
+ if(d[1]==2&&g==14)continue;
+ unsigned dest=d[1]==2&&g==15?MEMORY:g;
+ unsigned i=g*4+m*2+p;sv.wins[dest][m][p]=(uint16_t)(d[4+i*2]|d[5+i*2]<<8);
+ }
+ return true;
+}
+static bool save(void) {
+ uint8_t packed[SAVE_BYTES];save_encode(packed);
+ return np_file_write(SAVE_NAME,packed,sizeof packed);
+}
+static void start_round(void) {
+ memset(&bot,0,sizeof bot);bot.next=now+(cpu==1?750:cpu==2?600:450);START[game]();
+}
+static int page_game(int direction) {
+ int page=(game/4+direction+(NG+3)/4)%((NG+3)/4);
+ return clampi(page*4+game%4,0,NG-1);
}
static void new_match(void) {
score[0] = score[1] = 0, phase = 0, winner = 2, screen = S_PLAY;
- START[game]();
+ start_round();
+}
+static void match_step(void) {
+ if(cpu)pad[1]=tap[1]=0; /* EXE is a solo action alias, never an input to the bot. */
+ STEP_[game]();
+ if(phase==1&&ago(phase_t)>1500){
+ phase=0;
+ if(score[0]<TARGET[game]&&score[1]<TARGET[game])start_round();
+ else{
+ phase=2;screen=S_OVER;sel=0;
+ uint16_t*w=&sv.wins[game][cpu>0][score[1]>score[0]];if(*w<65535)(*w)++;
+ save();
+ }
+ }
}
static const char *opponent(void) {
static const char *const O[4] = {T("Player 2"), T("Computer: easy"), T("Computer: normal"), T("Computer: hard")};
@@ -644,7 +734,7 @@ static void keyboard(int x0, int y0) {
else x += (k - 30) % 6 * 24, y += 74 + (k - 30) / 6 * 14, w = 20, h = 10;
for (int q = 0; q < 2; q++)
for (int i = 0; i < 5; i++)
- if (KEYS[q][i] == k && (i == 4 ? game == TANKS : game != PONG || i == 1 || i == 2) && !is_cpu(q))
+ if (KEYS[q][i] == k && (CONTROL[game] & (1<<i)) && !is_cpu(q))
p = q, b = i;
box(x, y, w, h, 3, p < 0 ? HEX(0x3A4268) : team[p]);
if (p >= 0 && b == 4) disc(x + w / 2, y + h / 2, 2, WHITE);
@@ -660,14 +750,14 @@ static void button(int x, int y, int w, const char *s, bool on) {
look: Pong's black court and white walls with its square ball, the air hockey rink with a mallet, the tanks' grey maze, the light cycles' blue grid; over the menu, in the menu's */
static void card(int y, int h, const char *title, const char *const *items, int n, int by) {
gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 130);
- if (screen <= S_RULES || (screen == S_ASK && back_to == S_MENU)) {
+ if (screen <= S_RULES || (screen == S_ASK && back_to == S_MENU) || game>=QUICK || screen==S_SAVE_ERROR) {
box(60, y, 200, h, 14, HEX(0x262D52));
gfx_rrect_outline(60, y, 200, h, 14, 2, HEX(0x56619A), 256);
say(&np_font_title, 160, y + 30, title, WHITE);
for (int i = 0; i < n; i++) button(84, by + 32 * i, 152, items[i], sel == i);
return;
}
- static const uint32_t LOOK[NG][3] = {{0x000000, 0xFFFFFF, 0xFFFFFF}, {0xF4F6FA, 0x9AA3B8, 0x161A33},
+ static const uint32_t LOOK[4][3] = {{0x000000, 0xFFFFFF, 0xFFFFFF}, {0xF4F6FA, 0x9AA3B8, 0x161A33},
{0xE6E6EA, 0x3A3D4F, 0x3A3D4F}, {0x0B1230, 0x3E8BFF, 0xFFFFFF}};
color_t bg = gfx_rgb(LOOK[game][0]), edge = gfx_rgb(LOOK[game][1]), ink = gfx_rgb(LOOK[game][2]);
gfx_fill(57, y - 3, 206, h + 6, edge);
@@ -692,46 +782,64 @@ static const int8_t ICON[][6] = {
{0, 0, 0, 0, 0, 0}, /* (a tank) */
{4, 7, 12, 3, 0, 0}, {13, 7, 3, 12, 0, 0}, {10, 19, 12, 3, 0, 1}, {10, 12, 3, 9, 0, 1}, /* Light Cycles */
};
-static const uint8_t ICON_AT[NG + 1] = {0, 3, 6, 7, 11};
+static const uint8_t ICON_AT[5] = {0, 3, 6, 7, 11};
static void icon(int g, int x, int y) {
const color_t C[3] = {team[0], team[1], WHITE};
box(x, y, 26, 26, 6, INK);
- if (g == TANKS) tank(x + 13, y + 14, 54, 0);
+ if(g>=QUICK){
+ int cx=x+13,cy=y+13;
+ switch(g){
+ case QUICK:disc(cx-5,cy,5,team[0]);disc(cx+5,cy,5,team[1]);box(cx-2,cy-8,4,16,2,GOLD);break;
+ case TUG:gfx_fill(x+3,cy,20,3,WHITE);box(cx-2,cy-5,5,11,2,GOLD);break;
+ case FOOTBALL:case VOLLEY:disc(cx,cy,8,g==FOOTBALL?WHITE:GOLD);disc(cx-2,cy-2,3,g==FOOTBALL?INK:WHITE);break;
+ case ARCHERY:gfx_fill(cx-8,cy,17,2,WHITE);gfx_fill(cx+5,cy-3,2,8,team[0]);break;
+ case DODGE:disc(cx-5,cy+3,5,team[0]);disc(cx+6,cy-5,5,team[1]);break;
+ case METEORS:disc(cx+3,cy-4,6,HEX(0xA5AFCB));box(cx-7,cy+6,11,4,2,team[0]);break;
+ case ROCKETS:box(cx-8,cy-4,16,9,4,team[1]);gfx_fill(cx-11,cy-2,5,5,GOLD);break;
+ case SUMO:disc(cx,cy,10,GOLD);disc(cx-4,cy,4,team[0]);disc(cx+4,cy,4,team[1]);break;
+ case FISHING:gfx_fill(cx,cy-9,1,14,WHITE);box(cx-6,cy+3,13,7,3,GOLD);break;
+ default:tri(cx,cy-3,3,team[0]);gfx_fill(cx-1,cy-2,3,11,team[1]);break;
+ }
+ }else if (g == TANKS) tank(x + 13, y + 14, 54, 0);
else
for (int i = ICON_AT[g]; i < ICON_AT[g + 1]; i++)
box(x + ICON[i][0], y + ICON[i][1], ICON[i][2], ICON[i][3], ICON[i][4], C[ICON[i][5]]);
}
static void scene(void *ctx) {
- char s[16];
+ char s[48];
if (screen <= S_RULES || (screen == S_ASK && back_to == S_MENU)) {
gfx_vgrad(0, 0, 160, SCREEN_H, 0xB8323A, 0x3A0F24); /* the two players' colours */
gfx_vgrad(160, 0, 160, SCREEN_H, 0x2A5FD0, 0x0F1A44);
say(&np_font_title, 160, 28, T("2 Players"), WHITE);
- for (int g = 0; g < NG; g++) {
- int y = 46 + 39 * g, on = g == game;
+ char*page_end=num(s,(uint32_t)(game/4+1));*page_end++='/';num(page_end,(NG+3)/4);
+ gfx_text_right(&np_font_small,301,28,s,WHITE,256);
+ for (int g = game/4*4; g < NG && g < game/4*4+4; g++) {
+ int y = 46 + 39 * (g%4), on = g == game;
gfx_rrect(24, y, 272, 32, 10, on ? WHITE : INK, on ? 256 : 170);
icon(g, 27, y + 3);
gfx_text(&np_font_body, 62, y + 21, NAME[g], on ? INK : WHITE, 256);
for (int p = 0; p < 2; p++) { /* the matches each side has won */
- num(s, sv.wins[g][cpu > 0][p]);
- gfx_text_center(&np_font_body, 248 + 30 * p, y + 21, s, team[p], 256);
+ unsigned wins=sv.wins[g][cpu > 0][p];char*e=num(s,wins>999?999:wins);if(wins>999)*e++='+',*e=0;
+ gfx_text_center(&np_font_body, 246 + 36 * p, y + 21, s, team[p], 256);
}
gfx_text_center(&np_font_body, 263, y + 21, "-", on ? INK : WHITE, 256);
}
gfx_rrect(40, 212, 240, 24, 12, INK, 200);
tri(52, 224, 2, WHITE), tri(268, 224, 0, WHITE);
gfx_text_center(&np_font_body, 160, 229, opponent(), WHITE, 256);
+ gfx_text_center(&np_font_small,160,207,T("7 / 9: page"),WHITE,256);
if (screen == S_RULES) {
gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 140);
box(8, 8, 304, 224, 14, HEX(0x262D52));
say(&np_font_title, 160, 34, NAME[game], WHITE);
- gfx_paragraph(&np_font_small, 160, 54, 284, 12, RULES[game], HEX(0xD6DCF5), 256);
+ gfx_paragraph(&np_font_small, 160, 52, 284, 11, RULES[game], HEX(0xD6DCF5), 256);
char *e = s;
for (const char *q = T("First to "); *q; q++) *e++ = *q;
num(e, TARGET[game]);
gfx_text_center(&np_font_body, 231, 184, s, GOLD, 256);
keyboard(26, 100);
+ gfx_text_center(&np_font_small,231,101,CONTROL[game]&16?T("Action: OK / EXE"):T("Use direction keys"),GOLD,256);
for (int p = 0; p < 2; p++) {
box(166, 110 + 30 * p, 14, 14, 4, team[p]);
gfx_text(&np_font_body, 188, 122 + 30 * p, p ? opponent() : who(0), WHITE, 256);
@@ -772,79 +880,85 @@ static void scene(void *ctx) {
if (screen == S_ASK) {
static const char *const ITEM[2] = {T("No"), T("Yes")};
card(60, 120, T("Quit game?"), ITEM, 2, 104);
+ }else if(screen==S_SAVE_ERROR){
+ static const char*const ITEM[2]={T("Retry saving"),T("Exit without saving")};
+ card(45,158,T("Save failed"),ITEM,2,113);
}
}
int main(void) {
np_app_begin();
- color_t *their_strip = gfx_buf;
- gfx_buf = strip;
- static const uint32_t TEAM[2] = {0xEF4136, 0x2E7CF6};
- for (int p = 0; p < 2; p++)
- team[p] = gfx_rgb(TEAM[p]), light[p] = gfx_rgb(gfx_lerp888(TEAM[p], 0xFFFFFF, 120)), dark[p] = gfx_rgb(gfx_lerp888(TEAM[p], 0, 110));
- uint32_t last = (uint32_t)eadk_timing_millis(), n = 0;
- seed = eadk_random() ^ last;
- if (!seed) seed = 1;
- const uint8_t *d = np_file_read(SAVE_NAME, &n);
- if (d && n == sizeof sv && d[0] == 'P' && d[1] == 1)
- for (uint32_t i = 0; i < n; i++) ((uint8_t *)&sv)[i] = d[i];
- game = sv.game % NG, cpu = sv.cpu & 3;
- uint64_t held = eadk_keyboard_scan(), stale = held; /* keys still down from the launcher wait to be let go */
- for (bool quit = false; !quit;) {
- uint32_t t = (uint32_t)eadk_timing_millis();
- ms = t - last < 40 ? (int)(t - last) : 40, last = t;
- if (screen == S_PLAY) now += (uint32_t)ms;
- uint64_t k = eadk_keyboard_scan();
- stale &= k, k &= ~stale;
- uint64_t hit = k & ~held;
- held = k;
- if (down(k, eadk_key_home) || down(k, eadk_key_on_off)) break;
- bool ok = down(hit, eadk_key_ok) || down(hit, eadk_key_exe), back = down(hit, eadk_key_back);
- pad[0] = pad[1] = tap[0] = tap[1] = 0;
- for (int i = 0; i < 10; i++)
- pad[i / 5] |= down(k, KEYS[i / 5][i % 5]) << i % 5, tap[i / 5] |= down(hit, KEYS[i / 5][i % 5]) << i % 5;
- if (cpu && ok) tap[0] |= B_FIRE; /* alone: OK and EXE fire too */
- int dx = down(hit, eadk_key_right) - down(hit, eadk_key_left), dy = down(hit, eadk_key_down) - down(hit, eadk_key_up);
- switch (screen) {
+ color_t *their_strip=gfx_buf;gfx_buf=strip;
+ static const uint32_t TEAM[2]={0xEF4136,0x2E7CF6};
+ for(int p=0;p<2;p++)team[p]=gfx_rgb(TEAM[p]),light[p]=gfx_rgb(gfx_lerp888(TEAM[p],0xFFFFFF,120)),dark[p]=gfx_rgb(gfx_lerp888(TEAM[p],0,110));
+ uint32_t last=(uint32_t)eadk_timing_millis(),n=0,accum=0,draw_at=last;
+ seed=eadk_random()^last;if(!seed)seed=1;
+ const uint8_t*d=np_file_read(SAVE_NAME,&n);save_decode(d,n);
+ game=sv.game%NG;cpu=sv.cpu&3;screen=S_MENU;sel=0;now=0;
+ uint64_t held=eadk_keyboard_scan(),stale=held;int previous_pad[2]={0},queued[2]={0};
+ bool dirty=true;
+ for(bool quit=false;!quit;){
+ uint32_t t=(uint32_t)eadk_timing_millis(),elapsed=t-last;last=t;
+ uint64_t k=eadk_keyboard_scan();stale&=k;k&=~stale;uint64_t hit=k&~held;held=k;
+ bool ok=down(hit,eadk_key_ok)||down(hit,eadk_key_exe),back=down(hit,eadk_key_back);
+ int dx=down(hit,eadk_key_right)-down(hit,eadk_key_left),dy=down(hit,eadk_key_down)-down(hit,eadk_key_up),before=screen;
+ if(hit)dirty=true;
+ if(screen!=S_SAVE_ERROR&&(down(k,eadk_key_home)||down(k,eadk_key_on_off))){
+ if(save())break;
+ screen=S_SAVE_ERROR;sel=0;stale|=k;ok=back=false;dx=dy=0;dirty=true;
+ }
+ pad[0]=pad[1]=0;
+ for(int i=0;i<10;i++)pad[i/5]|=down(k,KEYS[i/5][i%5])<<(i%5);
+ if(cpu&&(down(k,eadk_key_ok)||down(k,eadk_key_exe)))pad[0]|=B_FIRE;
+ for(int p=0;p<2;p++){tap[p]=pad[p]&~previous_pad[p];previous_pad[p]=pad[p];queued[p]|=tap[p];}
+ switch(screen){
case S_MENU:
case S_RULES:
- if (dx) cpu = (cpu + dx) & 3, save();
- if (screen == S_RULES) {
- if (ok) new_match();
- else if (back) screen = S_MENU;
- } else if (dy) game = (game + dy + NG) % NG;
- else if (ok) screen = S_RULES, save();
- else if (back) back_to = S_MENU, screen = S_ASK, sel = 0;
+ if(dx){cpu=(cpu+dx+4)%4;save();}
+ if(screen==S_RULES){if(ok)new_match();else if(back)screen=S_MENU;}
+ else if(dy)game=(game+dy+NG)%NG;
+ else if(down(hit,eadk_key_seven))game=page_game(-1);
+ else if(down(hit,eadk_key_nine))game=page_game(1);
+ else if(ok){screen=S_RULES;save();}
+ else if(back){back_to=S_MENU;screen=S_ASK;sel=0;}
break;
case S_PLAY:
- if (back) {
- screen = S_PAUSE, sel = 0;
- break;
- }
- STEP_[game]();
- if (phase == 1 && ago(phase_t) > 1500) {
- phase = 0;
- if (score[0] < TARGET[game] && score[1] < TARGET[game]) START[game]();
- else phase = 2, screen = S_OVER, sel = 0, sv.wins[game][cpu > 0][score[1] > score[0]]++, save();
+ if(back){screen=S_PAUSE;sel=0;break;}
+ /* A fixed eight-millisecond simulation, independent of LCD frame rate.
+ * A tap is queued until a tick consumes it; held keys keep moving. */
+ accum+=elapsed>160?160:elapsed;
+ for(int steps=0;accum>=8&&steps<20&&screen==S_PLAY;steps++){
+ ms=8;now+=8;tap[0]=queued[0];tap[1]=queued[1];queued[0]=queued[1]=0;
+ match_step();accum-=8;
}
break;
- default: /* the cards: Paused, the match over, Quit game? */
- sel = (sel + dy) & (screen == S_PAUSE ? 3 : 1);
- if (screen == S_ASK) {
- if (back || (ok && !sel)) screen = back_to;
- else quit = ok;
- } else if (back && screen == S_PAUSE) {
- screen = S_PLAY;
- } else if (ok) { /* Resume, Restart, Other games, Quit game; Rematch, Other games */
- int a = screen == S_PAUSE ? sel : sel ? 2 : 1;
- if (a == 1) new_match();
- else screen = a ? a == 2 ? S_MENU : S_ASK : S_PLAY, back_to = S_PAUSE, sel = 0;
+ case S_SAVE_ERROR:
+ if(dy)sel^=1;
+ if(back||(ok&&sel))quit=true;else if(ok&&save())quit=true;
+ break;
+ default:
+ sel=(sel+dy)&(screen==S_PAUSE?3:1);
+ if(screen==S_ASK){
+ if(back||(ok&&!sel))screen=back_to;
+ else if(ok){if(save())quit=true;else screen=S_SAVE_ERROR,sel=0;}
+ }else if(back&&screen==S_PAUSE)screen=S_PLAY;
+ else if(ok){
+ int a=screen==S_PAUSE?sel:sel?2:1;
+ if(a==1)new_match();
+ else{screen=a?(a==2?S_MENU:S_ASK):S_PLAY;back_to=S_PAUSE;sel=0;}
}
+ break;
+ }
+ if(screen!=S_PLAY)accum=0,queued[0]=queued[1]=0;
+ if(before!=screen){
+ dirty=true;accum=0;queued[0]=queued[1]=0;previous_pad[0]=previous_pad[1]=0;stale|=k;
+ last=(uint32_t)eadk_timing_millis();
+ }
+ if(dirty||(screen==S_PLAY&&t-draw_at>=30)){
+ eadk_display_wait_for_vblank();gfx_render(scene,0,0,SCREEN_H);draw_at=t;dirty=false;
}
- eadk_display_wait_for_vblank();
- gfx_render(scene, 0, 0, SCREEN_H);
+ eadk_timing_msleep(2);
}
- save();
- gfx_buf = their_strip;
+ gfx_buf=their_strip;
return np_app_end();
}
diff --git a/games/twoplayer/src/party.h b/games/twoplayer/src/party.h
new file mode 100644
index 00000000..c917cb4e
--- /dev/null
+++ b/games/twoplayer/src/party.h
@@ -0,0 +1,492 @@
+/* Additional games share one small working state and the original game's
+ * colours, shapes, input, points and CPU levels. Included once by main.c. */
+#ifndef TWOPLAYER_PARTY_H
+#define TWOPLAYER_PARTY_H
+typedef struct { float x,y,vx,vy; uint32_t ready,last; int aux; } PartyPlayer;
+typedef struct { float x,y,vx,vy; int16_t life; int8_t own,kind; } PartyShot;
+static struct {
+ PartyPlayer p[2]; PartyShot shot[12];
+ float x,y,vx,vy,value;
+ uint32_t started,at,next,signal;
+ uint16_t mark[2]; uint8_t flags[2],seq[8],index[2],n;
+} party;
+static float sq(float a) { return a*a; }
+static float distance2(float x,float y,float a,float b) { return sq(x-a)+sq(y-b); }
+static bool reached(uint32_t t) { return (int32_t)(now-t)>=0; }
+static float seconds(void) { return ms*.001f; }
+static void party_start(void) {
+ memset(&party,0,sizeof party);party.started=party.at=now;party.p[0].x=52;party.p[1].x=268;
+ for(int p=0;p<2;p++) party.p[p].y=190,party.mark[p]=3;
+}
+static void bot_to(float x,float y,float margin) {
+ pad[1]=(party.p[1].x<x-margin?B_RIGHT:party.p[1].x>x+margin?B_LEFT:0)|
+ (party.p[1].y<y-margin?B_DOWN:party.p[1].y>y+margin?B_UP:0);
+ tap[1]=0;
+}
+static void actor2(int x,int feet,int p) {
+ disc(x+2,feet+1,10,HEX(0x232944));box(x-7,feet-19,14,19,5,team[p]);
+ disc(x,feet-25,7,light[p]);disc(x+(p?-2:2),feet-26,1,INK);
+ box(x-8,feet-3,6,5,2,dark[p]);box(x+2,feet-3,6,5,2,dark[p]);
+}
+static void arena(color_t bg) {
+ gfx_fill(0,22,320,218,INK);box(6,28,308,206,12,bg);
+}
+static void centre_text(int y,const char*s,color_t c) { say(&np_font_body,160,y,s,c); }
+static void time_text(int y,uint32_t elapsed,uint32_t duration) {
+ char s[16];char*e=num(s,elapsed<duration?(duration-elapsed+999)/1000:0);*e++='s';*e=0;centre_text(y,s,GOLD);
+}
+static int shot_slot(void) { for(int i=0;i<12;i++)if(party.shot[i].life<=0)return i;return -1; }
+static void tie_dead(void) { if(!party.mark[0]||!party.mark[1])point(!party.mark[0]&&!party.mark[1]?2:party.mark[0]?0:1); }
+
+/* ------------------------------------------------------------ Quick Draw */
+static void quick_start(void) {
+ party_start();party.signal=now+1800+rn(2800);
+ party.next=party.signal+(cpu==1?700:cpu==2?500:350)+rn(cpu==1?400:cpu==2?300:200);
+}
+static void quick_step(void) {
+ if(phase)return;
+ if(cpu&&reached(party.next))tap[1]|=B_FIRE;
+ int a=!!(tap[0]&B_FIRE),b=!!(tap[1]&B_FIRE);
+ if(a||b)point(a&&b?2:reached(party.signal)?(a?0:1):(a?1:0));
+}
+static void quick_paint(void) {
+ arena(HEX(0x262D52));bool go=reached(party.signal);
+ for(int p=0;p<2;p++){actor2(74+p*172,197,p);box(32+p*172,81,84,48,12,go?team[p]:dark[p]);}
+ centre_text(55,T("Quick Draw"),WHITE);centre_text(151,go?T("DRAW!"):T("Wait..."),go?GOLD:WHITE);
+ if(!go)centre_text(222,T("Too soon loses the round"),HEX(0xB5BEDF));
+}
+
+/* ------------------------------------------------------------ Tug of War */
+static void tug_start(void) { party_start();party.next=now+500; }
+static void tug_step(void) {
+ if(phase)return;
+ if(cpu&&reached(party.next)){tap[1]|=B_FIRE;party.next=now+(cpu==1?500:cpu==2?350:250)+rn(cpu==1?150:cpu==2?120:90);}
+ int pull[2]={0};
+ for(int p=0;p<2;p++)if((tap[p]&B_FIRE)&&ago(party.p[p].last)>=100){pull[p]=1;party.p[p].last=now;}
+ party.value+=(pull[1]-pull[0])*7.5f;
+ if(party.value>0)party.value=clampf(party.value-seconds()*3,0,100);
+ else party.value=clampf(party.value+seconds()*3,-100,0);
+ if(party.value<-67)point(0);else if(party.value>67)point(1);
+ else if(ago(party.started)>30000)point(party.value<-1?0:party.value>1?1:2);
+}
+static void tug_paint(void) {
+ arena(HEX(0x262D52));centre_text(56,T("Tug of War"),WHITE);time_text(79,ago(party.started),30000);
+ gfx_fill(91,101,2,100,team[0]);gfx_fill(227,101,2,100,team[1]);
+ int x=160+(int)party.value;
+ for(int p=0;p<2;p++){actor2(x+(p?85:-85),182,p);gfx_fill(x+(p?12:-80),141,68,4,HEX(0xC5CBE4));}
+ box(x-6,131,12,19,3,GOLD);centre_text(219,T("Tap, release, pull!"),WHITE);
+}
+
+/* ------------------------------------------------------------ Football */
+static void football_start(void) {
+ party_start();party.p[0].x=66;party.p[1].x=254;party.p[0].y=party.p[1].y=131;
+ party.x=160;party.y=131;
+}
+static void football_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){
+ float target=party.x+15,ty=party.y;
+ if(party.vx>130&&party.x>190)target=282,ty=clampf(party.y+party.vy*.15f,60,202);
+ bot_to(clampf(target,20,300),ty,3);
+ if(distance2(party.x,party.y,party.p[1].x,party.p[1].y)<sq(cpu==1?19:27)&&reached(party.p[1].ready))tap[1]|=B_FIRE;
+ bot.pad=pad[1];}}
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];float speed=is_cpu(p)?(cpu==1?70:cpu==2?85:100):116;
+ float dx=dirx(p),dy=diry(p);if(dx&&dy)dx*=.7071f,dy*=.7071f;
+ a->vx=dx*speed;a->vy=dy*speed;a->x=clampf(a->x+a->vx*dt,20,300);a->y=clampf(a->y+a->vy*dt,43,220);
+ float x=party.x-a->x,y=party.y-a->y,d=len(x,y);
+ if(d<17){
+ if(d<.1f){x=p?-1:1;y=0;d=1;}
+ x/=d;y/=d;
+ party.x=a->x+x*17;party.y=a->y+y*17;
+ float v=(party.vx-a->vx)*x+(party.vy-a->vy)*y;
+ if(v<0)party.vx-=1.5f*v*x,party.vy-=1.5f*v*y;
+ party.vx+=a->vx*.13f;party.vy+=a->vy*.13f;
+ }
+ if((tap[p]&B_FIRE)&&reached(a->ready)){a->ready=now+(is_cpu(p)?1100-cpu*180:350);
+ if(d<30){float gx=p?5:315,gy=131;
+ if(is_cpu(p))gy=131+(cpu==1?rn(70)-35:(party.p[0].y>=131?-19:19)+rn(cpu==2?18:6)-(cpu==2?9:3));
+ float vx=gx-party.x,vy=gy-party.y,n=len(vx,vy);
+ party.vx=vx/n*260;party.vy=vy/n*260;}}
+ }
+ party.x+=party.vx*dt;party.y+=party.vy*dt;party.vx*=1-dt*.55f;party.vy*=1-dt*.55f;
+ float v=len(party.vx,party.vy);if(v>310)party.vx*=310/v,party.vy*=310/v;
+ if(party.y<39)party.y=39,party.vy=__builtin_fabsf(party.vy)*.85f;
+ if(party.y>223)party.y=223,party.vy=-__builtin_fabsf(party.vy)*.85f;
+ if(party.y>106&&party.y<156){if(party.x<10)point(1);if(party.x>310)point(0);}
+ else{if(party.x<18)party.x=18,party.vx=__builtin_fabsf(party.vx)*.85f;if(party.x>302)party.x=302,party.vx=-__builtin_fabsf(party.vx)*.85f;}
+ if(ago(party.started)>45000)point(2);
+}
+static void football_paint(void) {
+ arena(HEX(0x254E46));gfx_rrect_outline(14,35,292,194,8,2,HEX(0x9CC4AE),256);
+ gfx_fill(159,35,2,194,HEX(0x9CC4AE));gfx_rrect_outline(127,99,66,66,33,2,HEX(0x9CC4AE),256);
+ gfx_fill(4,103,12,56,dark[0]);gfx_fill(304,103,12,56,dark[1]);
+ for(int p=0;p<2;p++){int x=party.p[p].x,y=party.p[p].y;disc(x+1,y+2,11,HEX(0x18352F));disc(x,y,11,team[p]);disc(x-2,y-3,4,light[p]);}
+ disc(party.x+1,party.y+2,7,HEX(0x18352F));disc(party.x,party.y,7,WHITE);disc(party.x,party.y,3,INK);
+ time_text(51,ago(party.started),45000);
+}
+
+/* ------------------------------------------------------------ Volley Ball */
+static void volley_start(void) {
+ party_start();for(int p=0;p<2;p++)party.p[p].x=75+p*170,party.p[p].y=208;
+ int serve=winner<2?1-winner:rn(2);party.x=serve?242:78;party.y=75;party.vx=serve?-60:60;
+}
+static void volley_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){
+ /* Get behind the ball to return it over the net, with time to react. */
+ float target=party.x>152?party.x+14+party.vx*(cpu==1?0:cpu==2?.06f:.12f):240;
+ bot_to(clampf(target,180,292),208,5);pad[1]&=B_LEFT|B_RIGHT;
+ if(party.x>161&&party.y>120&&party.y<183&&__builtin_fabsf(party.x-party.p[1].x)<30)tap[1]|=B_FIRE;
+ bot.pad=pad[1];
+ }}
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];a->x=clampf(a->x+dirx(p)*(is_cpu(p)?60+cpu*15:125)*dt,p?178:20,p?300:142);
+ if((tap[p]&(B_UP|B_FIRE))&&a->y>=207)a->vy=-232;
+ a->vy+=570*dt;a->y+=a->vy*dt;if(a->y>208)a->y=208,a->vy=0;
+ float dx=party.x-a->x,dy=party.y-(a->y-12),d=len(dx,dy);
+ if(d<24&&d>.01f){party.x=a->x+dx/d*24;party.y=a->y-12+dy/d*24;float v=party.vx*dx/d+(party.vy-a->vy)*dy/d;
+ if(v<0){party.vx-=1.75f*v*dx/d;party.vy-=1.75f*v*dy/d;party.vy-=30;}}
+ }
+ float oldx=party.x,oldy=party.y;party.vy+=360*dt;party.x+=party.vx*dt;party.y+=party.vy*dt;
+ party.vx=clampf(party.vx,-255,255);party.vy=clampf(party.vy,-285,360);
+ if(party.x<18)party.x=18,party.vx=__builtin_fabsf(party.vx);
+ if(party.x>302)party.x=302,party.vx=-__builtin_fabsf(party.vx);
+ if(party.y<39)party.y=39,party.vy=__builtin_fabsf(party.vy);
+ if(party.x>149&&party.x<171){
+ if(oldy<=136&&party.y>=136){party.y=136;party.vy=-__builtin_fabsf(party.vy)*.85f;}
+ else if(party.y>136){party.x=oldx<160?149:171;party.vx=oldx<160?-__builtin_fabsf(party.vx):__builtin_fabsf(party.vx);}
+ }
+ if(party.y>=211)point(party.x<160?1:0);
+}
+static void volley_paint(void) {
+ arena(HEX(0x27385D));gfx_fill(12,221,296,9,HEX(0xB6BFE0));gfx_fill(157,145,6,76,WHITE);disc(160,145,4,WHITE);
+ for(int p=0;p<2;p++){int x=party.p[p].x,y=party.p[p].y;disc(x+1,y+3,15,dark[p]);disc(x,y-3,15,team[p]);gfx_fill(x-15,y+1,30,18,team[p]);disc(x+(p?-4:4),y-7,2,WHITE);}
+ disc(party.x+1,party.y+2,9,INK);disc(party.x,party.y,9,GOLD);disc(party.x-3,party.y-3,3,WHITE);
+}
+
+/* ------------------------------------------------------------ Archery */
+#define ARROW_GRAVITY 240
+#define BOW_Y 190
+static float archery_power(unsigned held) { return 140+clampi(held,0,1000)*.14f; }
+static void archery_plan(void) {
+ PartyPlayer*a=&party.p[1];int angle=6+rn(5),spread=cpu==1?260:cpu==2?180:110;
+ float power=__builtin_sqrtf(ARROW_GRAVITY*223.0f*127*127/(2*cos64(angle)*sin64(angle)));
+ a->vx=angle;a->aux=clampi((int)((power-140)/.14f)+rn(spread*2+1)-spread,180,1000);
+}
+static void archery_start(void) {
+ party_start();party.p[0].x=40;party.p[1].x=280;
+ for(int p=0;p<2;p++){party.p[p].vx=8;party.p[p].y=0;}
+ if(cpu){archery_plan();party.p[1].ready=now+(cpu==1?1600:cpu==2?1300:1000);}
+}
+static void archery_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){
+ PartyPlayer*a=&party.p[1];pad[1]=tap[1]=0;
+ if(reached(a->ready)&&(!party.flags[1]||ago(a->last)<(uint32_t)a->aux))pad[1]=B_FIRE;
+ }
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];a->vx=clampf(a->vx-diry(p)*dt*6,2,14);
+ a->y=clampf(a->y-dt,0,1); /* short hit flash, independent of the reload timer */
+ if((pad[p]&B_FIRE)&&reached(a->ready)&&!party.flags[p])party.flags[p]=1,a->last=now;
+ if(party.flags[p]&&!(pad[p]&B_FIRE)){
+ int slot=shot_slot(),angle=(int)a->vx;float power=archery_power(ago(a->last));
+ if(slot>=0)party.shot[slot]=(PartyShot){a->x+(p?-17:17),BOW_Y,
+ (p?-1:1)*cos64(angle)*power/127,-sin64(angle)*power/127,4000,(int8_t)p,0};
+ a->ready=now+(is_cpu(p)?(cpu==1?2000:cpu==2?1650:1350)+rn(400):600);
+ party.flags[p]=0;
+ if(is_cpu(p))archery_plan();
+ }
+ }
+ for(int i=0;i<12;i++){
+ PartyShot*s=&party.shot[i];if(s->life<=0)continue;
+ s->life-=ms;s->vy+=ARROW_GRAVITY*dt;s->x+=s->vx*dt;s->y+=s->vy*dt;
+ if(s->x<-12||s->x>332||s->y>208)s->life=0;
+ int p=1-s->own;
+ if(s->life>0&&__builtin_fabsf(s->x-party.p[p].x)<13&&s->y>165&&s->y<208){
+ s->life=0;if(party.mark[p])party.mark[p]--;party.p[p].y=.25f;
+ }
+ }
+ tie_dead();if(ago(party.started)>30000)point(party.mark[0]==party.mark[1]?2:party.mark[0]>party.mark[1]?0:1);
+}
+/* Small integer line segments keep bows, fletching and arrowheads readable
+ * without a texture atlas. Only pixels in the current LCD strip are drawn. */
+static void archery_line(int x,int y,int xx,int yy,color_t c) {
+ int dx=xx-x,dy=yy-y,sx=dx<0?-1:1,sy=dy<0?-1:1;
+ if(dx<0)dx=-dx;
+ if(dy<0)dy=-dy;
+ int error=dx-dy;
+ for(;;){
+ if(y>=gfx_y0&&y<gfx_y1)gfx_fill(x,y,1,1,c);
+ if(x==xx&&y==yy)break;
+ int e=error*2;if(e>-dy)error-=dy,x+=sx;if(e<dx)error+=dx,y+=sy;
+ }
+}
+static void archery_arrow(int x,int y,float vx,float vy,color_t c) {
+ float norm=len(vx,vy);if(norm<1)norm=1;
+ int dx=(int)(vx/norm*10),dy=(int)(vy/norm*10);
+ archery_line(x-dx,y-dy,x+dx,y+dy,WHITE);
+ archery_line(x+dx,y+dy,x+dx-dx/2+dy/3,y+dy-dy/2-dx/3,c);
+ archery_line(x+dx,y+dy,x+dx-dx/2-dy/3,y+dy-dy/2+dx/3,c);
+ archery_line(x-dx,y-dy,x-dx+dy/3,y-dy-dx/3,c);
+}
+static void hearts(int x,int y,int p,int remaining) {
+ for(int j=0;j<3;j++){
+ int hx=x+j*14;color_t h=j<remaining?team[p]:HEX(0x404867);
+ disc(hx-2,y,3,h);disc(hx+2,y,3,h);
+ for(int k=0;k<5;k++)gfx_fill(hx-4+k,y+2+k,9-k*2,1,h);
+ }
+}
+static void archery_paint(void) {
+ arena(HEX(0x262D52));gfx_fill(12,209,296,4,HEX(0x7A86A8));
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];int x=a->x,d=p?-1:1,angle=(int)a->vx,ax=x+d*17;
+ float power=archery_power(party.flags[p]?ago(a->last):650);
+ float vx=d*cos64(angle)*power/127,vy=-sin64(angle)*power/127;
+ for(int j=1;j<36;j++){
+ float t=j*.06f,xx=ax+vx*t,yy=BOW_Y+vy*t+ARROW_GRAVITY*t*t*.5f;
+ if(xx<17||xx>303||yy>208)break;
+ if(yy>98)disc(xx,yy,1,gfx_mix(INK,light[p],24));
+ }
+ actor2(x,206,p);if(a->y>0)disc(x,181,8,WHITE);
+ archery_line(x+d*4,190,ax,BOW_Y,light[p]);disc(ax,BOW_Y,2,light[p]);
+ /* Draw the curved bow and its taut string in the actual aiming direction. */
+ int cx=cos64(angle),sn=sin64(angle),ux=d*cx,uy=-sn,px=d*sn,py=cx;
+ int lastx=ax-px*15/127,lasty=BOW_Y-py*15/127;
+ for(int j=-2;j<=2;j++){
+ int side=j*7,bulge=(4-j*j)*2;
+ int xx=ax+(px*side+ux*bulge)/127,yy=BOW_Y+(py*side+uy*bulge)/127;
+ archery_line(lastx,lasty,xx,yy,GOLD);lastx=xx;lasty=yy;
+ }
+ archery_line(ax-px*14/127,BOW_Y-py*14/127,ax+px*14/127,BOW_Y+py*14/127,light[p]);
+ if(!party.flags[p]||now%180<130)archery_arrow(ax,BOW_Y,vx,vy,team[p]);
+ hearts(26+p*240,48,p,party.mark[p]);
+ int bx=p?226:18;box(bx,73,76,8,4,INK);
+ int charge=party.flags[p]?clampi(ago(a->last),0,1000)*72/1000:0;
+ if(charge)box(bx+2,75,charge,4,2,GOLD);
+ gfx_text_center(&np_font_small,bx+38,68,T("Power"),light[p],256);
+ char text[16];char*e=num(text,(unsigned)(angle*360/64));
+ *e++=' ';*e++='d';*e++='e';*e++='g';*e=0;
+ gfx_text_center(&np_font_small,bx+38,96,text,WHITE,256);
+ }
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0)archery_arrow(s->x,s->y,s->vx,s->vy,light[s->own]);}
+ /* HUD is painted last, so a high arrow cannot obscure its text. */
+ time_text(51,ago(party.started),30000);
+ centre_text(226,T("Hold OK / EXE, release to shoot"),WHITE);
+}
+
+/* ------------------------------------------------------------ Dodge Ball */
+static void dodge_start(void) {party_start();party.p[0].x=64;party.p[1].x=256;party.p[0].y=party.p[1].y=130;}
+static void dodge_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){
+ float ty=party.p[0].y,tx=254;
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0&&!s->own&&s->vx>0&&s->x>135&&__builtin_fabsf(s->y-party.p[1].y)<(cpu==1?15:28))ty=s->y<party.p[1].y?216:43;}
+ bot_to(tx,ty,4);if(reached(party.p[1].ready))tap[1]=B_FIRE;
+ bot.pad=pad[1];}}
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];float speed=is_cpu(p)?47+cpu*18:125;float dx=dirx(p),dy=diry(p);if(dx&&dy)dx*=.7071f,dy*=.7071f;
+ a->x=clampf(a->x+dx*speed*dt,p?178:19,p?301:142);a->y=clampf(a->y+dy*speed*dt,44,218);
+ if((tap[p]&B_FIRE)&&reached(a->ready)){
+ int slot=shot_slot();float x=party.p[1-p].x-a->x,y=party.p[1-p].y-a->y;if(is_cpu(p))y+=rn(cpu==1?101:cpu==2?61:33)-(cpu==1?50:cpu==2?30:16);float d=len(x,y);
+ if(slot>=0&&d>1)party.shot[slot]=(PartyShot){a->x,a->y,x/d*218,y/d*218,3500,(int8_t)p,0};
+ a->ready=now+(is_cpu(p)?1950-cpu*300:520);
+ }
+ }
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life<=0)continue;s->life-=ms;s->x+=s->vx*dt;s->y+=s->vy*dt;
+ if(s->y<37)s->y=37,s->vy=__builtin_fabsf(s->vy);
+ if(s->y>225)s->y=225,s->vy=-__builtin_fabsf(s->vy);
+ if(s->x<8||s->x>312)s->life=0;
+ int p=1-s->own;if(s->life>0&&distance2(s->x,s->y,party.p[p].x,party.p[p].y)<sq(16)&&reached(party.p[p].last)){
+ if(party.mark[p])party.mark[p]--;
+ party.p[p].last=now+450;s->life=0;
+ }
+ }
+ tie_dead();if(ago(party.started)>30000)point(party.mark[0]==party.mark[1]?2:party.mark[0]>party.mark[1]?0:1);
+}
+static void dodge_paint(void) {
+ arena(HEX(0x293658));for(int y=33;y<230;y+=14)gfx_fill(159,y,2,8,HEX(0x7482AF));
+ for(int p=0;p<2;p++){int x=party.p[p].x,y=party.p[p].y;
+ if(reached(party.p[p].last)||now%160<100){disc(x+1,y+2,12,dark[p]);disc(x,y,11,team[p]);disc(x-3,y-3,4,light[p]);}
+ hearts(26+p*240,40,p,party.mark[p]);
+ }
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0){disc(s->x,s->y,5,team[s->own]);disc(s->x-1,s->y-1,2,WHITE);}}
+ time_text(45,ago(party.started),30000);
+}
+
+/* ------------------------------------------------------------ Meteor Run */
+static void meteors_start(void) {party_start();party.p[0].x=party.p[1].x=80;party.next=now+650;}
+static void meteors_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){float best=80;int danger[3]={0};
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0&&s->y>85&&s->y<226){for(int k=0;k<3;k++)if(__builtin_fabsf(s->x-(30+50*k))<29)danger[k]+=s->y>150?3:1;}}
+ int choice=0;for(int k=1;k<3;k++)if(danger[k]<danger[choice]||(danger[k]==danger[choice]&&__builtin_fabsf(party.p[1].x-(30+50*k))<__builtin_fabsf(party.p[1].x-(30+50*choice))))choice=k;
+ best=30+50*choice;if(cpu==1&&ago(party.started)%1600<550)best=80;
+ bot_to(best,190,4);pad[1]&=B_LEFT|B_RIGHT;
+ bot.pad=pad[1];}}
+ for(int p=0;p<2;p++)if(party.mark[p])party.p[p].x=clampf(party.p[p].x+dirx(p)*(is_cpu(p)?55+cpu*20:145)*dt,23,137);
+ if(reached(party.next)){
+ int slot=shot_slot();if(slot>=0)party.shot[slot]=(PartyShot){25+rn(111),22,0,90+clampi(ago(party.started)/180,0,130),1,0,(int8_t)(8+rn(5))};
+ party.next=now+(ago(party.started)>15000?450:650);
+ }
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life<=0)continue;s->y+=s->vy*dt;if(s->y>250)s->life=0;
+ for(int p=0;p<2;p++)if(party.mark[p]&&distance2(party.p[p].x,208,s->x,s->y)<sq(s->kind+9))party.mark[p]=0;
+ }
+ tie_dead();if(ago(party.started)>30000)point(2);
+}
+static void meteors_paint(void) {
+ arena(HEX(0x1C2847));gfx_fill(158,30,4,200,HEX(0x56618C));
+ for(int p=0;p<2;p++){
+ for(int j=0;j<9;j++)disc(14+p*160+(j*37)%140,45+(j*29)%145,1,HEX(0x8592B7));
+ if(party.mark[p]){int x=p*160+(int)party.p[p].x;box(x-9,200,18,14,5,team[p]);disc(x,199,6,light[p]);}
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0){int x=p*160+(int)s->x,y=s->y;box(x-3,y-18,6,18,3,HEX(0xBA714A));disc(x,y,s->kind,HEX(0x757F9D));disc(x-3,y-3,3,HEX(0xA3ACC5));}}
+ }
+ time_text(52,ago(party.started),30000);
+}
+
+/* ------------------------------------------------------------ Rocket Race */
+static void rockets_start(void) {party_start();for(int p=0;p<2;p++)party.p[p].y=125;party.next=now+900;}
+static void rockets_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){float target=125,closest=1000;
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0&&s->x>4&&s->x<closest)closest=s->x,target=s->y;}
+ if(party.p[1].y>target+(cpu==1?15:cpu==2?7:1)&&party.p[1].vy>-45&&ago(party.p[1].last)>150)tap[1]|=B_FIRE;
+ bot.pad=pad[1];}}
+ for(int p=0;p<2;p++)if(party.mark[p]){
+ PartyPlayer*a=&party.p[p];if((tap[p]&(B_UP|B_FIRE))&&ago(a->last)>=100)a->vy=-123,a->last=now;
+ a->vy=clampf(a->vy+225*dt,-160,190);a->y+=a->vy*dt;if(a->y<40||a->y>221)party.mark[p]=0;
+ }
+ if(reached(party.next)){int slot=shot_slot();if(slot>=0)party.shot[slot]=(PartyShot){172,88+rn(88),65+clampi(ago(party.started)/1000,0,24),0,1,0,0};party.next=now+1700;}
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life<=0)continue;s->x-=s->vx*dt;if(s->x<-22)s->life=0;
+ if(s->x<66&&s->x+18>46)for(int p=0;p<2;p++)if(party.p[p].y<s->y-34||party.p[p].y>s->y+34)party.mark[p]=0;
+ }
+ tie_dead();if(ago(party.started)>30000)point(2);
+}
+static void rockets_paint(void) {
+ arena(HEX(0x1B2441));gfx_fill(158,30,4,200,HEX(0x56618C));
+ for(int p=0;p<2;p++){
+ for(int i=0;i<12;i++){PartyShot*s=&party.shot[i];if(s->life>0){
+ int left=clampi((int)s->x,12,148),right=clampi((int)s->x+18,12,148),g=s->y;
+ if(right>left){int x=p*160+left;box(x,30,right-left,g-73,4,HEX(0x56618C));box(x,g+43,right-left,230-g-43,4,HEX(0x56618C));}
+ }}
+ if(party.mark[p]){
+ int x=56+p*160,y=party.p[p].y;box(x-9,y-7,18,14,6,team[p]);disc(x+4,y-2,3,WHITE);
+ int thrust=ago(party.p[p].last)<180?12:5;
+ gfx_fill(x-8-thrust,y-3,thrust,6,GOLD);
+ }
+ }
+ time_text(52,ago(party.started),30000);
+}
+
+/* ------------------------------------------------------------ Sumo */
+static void sumo_start(void) {party_start();for(int p=0;p<2;p++)party.p[p].x=115+p*90,party.p[p].y=133;}
+static float ring_radius(void) {return 96-clampf(((float)ago(party.started)-6000)*.003f,0,57);}
+static void sumo_step(void) {
+ if(phase)return;
+ float dt=seconds(),radius=ring_radius();
+ if(cpu){bot_input();if(bot_due()){float x=party.p[0].x,y=party.p[0].y;
+ if(distance2(party.p[1].x,party.p[1].y,160,133)>sq(radius-18))x=160,y=133;
+ bot_to(x,y,2);if(distance2(x,y,party.p[1].x,party.p[1].y)<sq(cpu==1?24:48)&&reached(party.p[1].ready))tap[1]|=B_FIRE;
+ bot.pad=pad[1];}}
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];float dx=dirx(p),dy=diry(p),n=len(dx,dy);if(n>0)dx/=n,dy/=n;
+ if((tap[p]&B_FIRE)&&reached(a->ready)){
+ if(n==0){dx=party.p[1-p].x-a->x;dy=party.p[1-p].y-a->y;n=len(dx,dy);if(n>0)dx/=n,dy/=n;}
+ a->vx+=dx*225;a->vy+=dy*225;a->ready=now+(is_cpu(p)?2200-cpu*300:1100);
+ }
+ a->vx+=dx*500*dt;a->vy+=dy*500*dt;float friction=1-dt*4.2f;a->vx*=friction;a->vy*=friction;
+ a->x+=a->vx*dt;a->y+=a->vy*dt;
+ }
+ PartyPlayer*a=&party.p[0],*b=&party.p[1];float dx=b->x-a->x,dy=b->y-a->y,n=len(dx,dy);
+ if(n<27){if(n<.01f)dx=1,dy=0,n=1;dx/=n;dy/=n;float shift=(27-n)*.5f;a->x-=dx*shift;a->y-=dy*shift;b->x+=dx*shift;b->y+=dy*shift;
+ float v=(b->vx-a->vx)*dx+(b->vy-a->vy)*dy;if(v<0){float impulse=-v*.9f+12;a->vx-=dx*impulse;a->vy-=dy*impulse;b->vx+=dx*impulse;b->vy+=dy*impulse;}}
+ for(int p=0;p<2;p++)if(distance2(party.p[p].x,party.p[p].y,160,133)>sq(radius+2))party.mark[p]=0;
+ tie_dead();if(ago(party.started)>30000)point(2);
+}
+static void sumo_paint(void) {
+ arena(HEX(0x202745));int r=ring_radius();disc(160,135,r+4,HEX(0x10162D));disc(160,133,r+3,GOLD);disc(160,133,r,HEX(0xD0D3DE));disc(160,133,4,HEX(0x8791AD));
+ for(int p=0;p<2;p++){int x=party.p[p].x,y=party.p[p].y;disc(x+1,y+3,14,HEX(0x8992AA));disc(x,y,13,team[p]);disc(x-3,y-4,5,light[p]);if(reached(party.p[p].ready))disc(x+4,y+3,3,WHITE);}
+}
+
+/* ------------------------------------------------------------ Fishing */
+static void fishing_start(void) {
+ party_start();party.p[0].x=64;party.p[1].x=256;
+ for(int p=0;p<2;p++)party.p[p].y=83,party.p[p].aux=-1;
+ for(int i=0;i<7;i++)party.shot[i]=(PartyShot){25+rn(270),115+rn(90),(i&1?1:-1)*(28+rn(25)),0,1,-1,0};
+}
+static void fishing_step(void) {
+ if(phase)return;
+ float dt=seconds();
+ if(cpu){bot_input();if(bot_due()){
+ PartyPlayer*a=&party.p[1];float best=1e6f,target=250;int choice=0;
+ for(int i=0;i<7;i++){PartyShot*s=&party.shot[i];if(s->own>=0)continue;float d=__builtin_fabsf(s->x-a->x)+(s->y-80)*.2f;if(d<best)best=d,target=clampf(s->x+s->vx*(s->y-a->y)/100,18,302),choice=i;}
+ bot_to(target,190,5);pad[1]&=B_LEFT|B_RIGHT;
+ if(a->aux<0&&a->y<party.shot[choice].y+9&&__builtin_fabsf(a->x-party.shot[choice].x)<(cpu==1?14:cpu==2?23:31))pad[1]|=B_FIRE;
+ bot.pad=pad[1];
+ }}
+ for(int i=0;i<7;i++){PartyShot*s=&party.shot[i];if(s->own<0){s->x+=s->vx*dt;if(s->x<21)s->x=21,s->vx=__builtin_fabsf(s->vx);if(s->x>299)s->x=299,s->vx=-__builtin_fabsf(s->vx);}}
+ bool caught[2]={false,false};
+ for(int p=0;p<2;p++){
+ PartyPlayer*a=&party.p[p];a->x=clampf(a->x+dirx(p)*(is_cpu(p)?60+cpu*15:115)*dt,18,302);bool lower=(pad[p]&B_FIRE)!=0;
+ a->y=clampf(a->y+(lower?105:-145)*dt,83,219);
+ if(a->aux>=0){PartyShot*s=&party.shot[a->aux];s->x=a->x;s->y=a->y+6;if(a->y<=83)caught[p]=true;}
+ }
+ for(int i=0;i<7;i++)if(party.shot[i].own<0){
+ PartyShot*s=&party.shot[i];float d[2];for(int p=0;p<2;p++)d[p]=party.p[p].aux<0?distance2(party.p[p].x,party.p[p].y,s->x,s->y):1e6f;
+ if(d[0]<144&&d[1]<144&&__builtin_fabsf(d[0]-d[1])<1){point(2);return;}
+ int p=d[0]<d[1]?0:1;if(d[p]<144)party.p[p].aux=i,s->own=p;
+ }
+ if(caught[0]||caught[1])point(caught[0]&&caught[1]?2:caught[0]?0:1);
+ if(ago(party.started)>30000)point(2);
+}
+static void fishing_paint(void) {
+ arena(HEX(0x283D67));gfx_fill(12,82,296,147,HEX(0x244F75));gfx_fill(12,79,296,3,HEX(0x7FA6C3));
+ for(int p=0;p<2;p++){int x=party.p[p].x,y=party.p[p].y;actor2(x,77,p);gfx_fill(x,82,1,y-82,light[p]);gfx_fill(x,y,7,2,team[p]);gfx_fill(x+6,y-5,2,7,team[p]);}
+ for(int i=0;i<7;i++){PartyShot*s=&party.shot[i];int x=s->x,y=s->y;box(x-8,y-4,16,9,4,i&1?GOLD:HEX(0xA4D3DE));gfx_fill(x+(s->vx>0?-11:8),y-5,4,11,HEX(0x7B9DAF));disc(x+(s->vx>0?4:-4),y-1,1,INK);}
+ for(int p=0;p<2;p++)if(!is_cpu(p))
+ gfx_text_center(&np_font_small,80+p*160,47,party.p[p].aux>=0?T("Release!"):p?T("Hold EXE"):T("Hold OK"),GOLD,256);
+ time_text(48,ago(party.started),30000);
+}
+
+/* ------------------------------------------------------------ Memory Duel */
+static const uint8_t MEMORY_BIT[4]={B_LEFT,B_UP,B_DOWN,B_RIGHT};
+static void memory_start(void) {
+ party_start();party.n=(uint8_t)(3+clampi(score[0]+score[1],0,4));for(int i=0;i<party.n;i++)party.seq[i]=rn(4);
+ party.signal=now+700+party.n*650;party.next=party.signal+(cpu==1?1100:cpu==2?850:600);
+ party.p[1].aux=rn(100)<(cpu==1?60:cpu==2?35:15)?rn(party.n):-1;
+}
+static void memory_step(void) {
+ if(phase||!reached(party.signal))return;
+ if(cpu&&reached(party.next)&&party.index[1]<party.n&&!party.flags[1]){
+ int i=party.index[1],d=party.seq[i];if(i==party.p[1].aux)d=(d+1)%4;tap[1]=MEMORY_BIT[d];party.next=now+(cpu==1?1100:cpu==2?850:600);
+ }
+ for(int p=0;p<2;p++)if(!party.flags[p]&&party.index[p]<party.n){
+ unsigned bits=tap[p]&15;if(!bits)continue;int d=0;while(!(bits&MEMORY_BIT[d]))d++;
+ if((bits&(bits-1))||d!=party.seq[party.index[p]])party.flags[p]=1;
+ else party.index[p]++;
+ }
+ if(party.flags[0]||party.flags[1])point(party.flags[0]&&party.flags[1]?2:party.flags[0]?1:0);
+ else if(party.index[0]==party.n||party.index[1]==party.n)point(party.index[0]==party.n&&party.index[1]==party.n?2:party.index[0]==party.n?0:1);
+ if(ago(party.signal)>15000&&reached(party.signal))point(2);
+}
+static void memory_arrow(int x,int y,int d,color_t c) {
+ static const int8_t dx[4]={-1,0,0,1},dy[4]={0,-1,1,0};int xx=x+dx[d]*20,yy=y+dy[d]*20;
+ if(dx[d]){gfx_fill(xx-7,yy-2,14,5,c);for(int i=0;i<7;i++)gfx_fill(xx+(dx[d]>0?7-i:-7+i),yy-i,1,2*i+1,c);}
+ else{gfx_fill(xx-2,yy-7,5,14,c);for(int i=0;i<7;i++)gfx_fill(xx-i,yy+(dy[d]>0?7-i:-7+i),2*i+1,1,c);}
+}
+static void memory_paint(void) {
+ arena(HEX(0x262D52));bool replay=reached(party.signal);centre_text(54,replay?T("Repeat the arrows!"):T("Watch the arrows"),WHITE);
+ int elapsed=ago(party.started),shown=elapsed<700?-1:(elapsed-700)/650;
+ for(int p=0;p<2;p++){
+ int x=80+p*160;box(x-61,76,122,123,14,INK);
+ for(int d=0;d<4;d++)memory_arrow(x,137,d,!replay&&shown<party.n&&shown>=0&&(elapsed-700)%650<470&&party.seq[shown]==d?GOLD:team[p]);
+ for(int i=0;i<party.n;i++)disc(x-((party.n-1)*6)+i*12,217,4,replay?(i<party.index[p]?light[p]:dark[p]):(i==shown?GOLD:HEX(0x56618C)));
+ }
+}
+#endif
diff --git a/games/twoplayer/tests/eadk.h b/games/twoplayer/tests/eadk.h
new file mode 100644
index 00000000..c36bc437
--- /dev/null
+++ b/games/twoplayer/tests/eadk.h
@@ -0,0 +1,14 @@
+/* Host-only declarations. ARM builds/tests use NumWorks' actual SDK. */
+#ifndef TWOPLAYER_HOST_EADK_H
+#define TWOPLAYER_HOST_EADK_H
+#include <stdint.h>
+enum { eadk_key_left=0,eadk_key_up=1,eadk_key_down=2,eadk_key_right=3,
+ eadk_key_ok=4,eadk_key_back=5,eadk_key_home=6,eadk_key_on_off=8,
+ eadk_key_shift=12,eadk_key_seven=30,eadk_key_nine=32,eadk_key_multiplication=39,
+ eadk_key_three=44,eadk_key_minus=46,eadk_key_ans=51,eadk_key_exe=52 };
+uint64_t eadk_timing_millis(void);
+uint32_t eadk_random(void);
+uint64_t eadk_keyboard_scan(void);
+void eadk_display_wait_for_vblank(void);
+void eadk_timing_msleep(uint32_t);
+#endif
diff --git a/games/twoplayer/tests/test.c b/games/twoplayer/tests/test.c
new file mode 100644
index 00000000..0bafeefb
--- /dev/null
+++ b/games/twoplayer/tests/test.c
@@ -0,0 +1,136 @@
+#include <assert.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#define NP_MODULE 1
+#define main twoplayer_appmain
+#include "../src/main.c"
+#undef main
+
+static uint16_t pixels[320*240];
+static uint8_t saved[SAVE_BYTES];
+static unsigned saves;
+uint64_t eadk_timing_millis(void){return now;}
+uint32_t eadk_random(void){return 1;}
+uint64_t eadk_keyboard_scan(void){return 0;}
+void eadk_display_wait_for_vblank(void){}
+void eadk_timing_msleep(uint32_t n){(void)n;}
+void*np_alloc(uint32_t n){return malloc(n);}
+bool np_file_write(const char*name,const void*d,uint32_t n){assert(!strcmp(name,SAVE_NAME)&&n==SAVE_BYTES);memcpy(saved,d,n);saves++;return true;}
+const uint8_t*np_file_read(const char*name,uint32_t*n){*n=0;return NULL;}
+void np_push(int x,int y,int w,int h,const color_t*d){assert(x>=0&&y>=0&&x+w<=320&&y+h<=240);for(int i=0;i<h;i++)memcpy(pixels+(y+i)*320+x,d+i*w,w*2);}
+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=pixels[i];unsigned char p[3]={(c>>11)*255/31,((c>>5)&63)*255/63,(c&31)*255/31};fwrite(p,1,3,f);}fclose(f);}
+static void init(int g,int level,unsigned random){
+ game=g;cpu=level;seed=random?random:1;now=1000;ms=8;pad[0]=pad[1]=tap[0]=tap[1]=0;
+ new_match();
+}
+static void tick(unsigned a,unsigned b){pad[0]=tap[0]=a;pad[1]=tap[1]=b;now+=8;ms=8;match_step();}
+static void step(unsigned duration,unsigned a,unsigned b){for(unsigned i=0;i<duration&&screen==S_PLAY;i+=8){pad[0]=a;pad[1]=b;tap[0]=tap[1]=0;now+=8;ms=8;match_step();}}
+static void saves_test(void){
+ uint8_t legacy[36]={'P',1,3,2};for(unsigned i=0;i<16;i++){legacy[4+i*2]=(uint8_t)(i+50);legacy[5+i*2]=1;}
+ assert(save_decode(legacy,sizeof legacy));assert(sv.game==3&&sv.cpu==2);
+ for(unsigned g=0;g<4;g++)for(unsigned m=0;m<2;m++)for(unsigned p=0;p<2;p++)assert(sv.wins[g][m][p]==g*4+m*2+p+306);
+ for(int g=4;g<NG;g++)for(int a=0;a<2;a++)for(int p=0;p<2;p++)assert(!sv.wins[g][a][p]);
+ uint8_t v2[136]={'P',2,15,1};
+ for(unsigned i=0;i<64;i++){unsigned n=1000+i;v2[4+i*2]=(uint8_t)n;v2[5+i*2]=(uint8_t)(n>>8);}
+ uint32_t crc=save_crc(v2,132);for(int i=0;i<4;i++)v2[132+i]=(uint8_t)(crc>>(i*8));
+ assert(save_decode(v2,sizeof v2)&&sv.game==MEMORY);
+ for(int g=0;g<NG;g++)for(int m=0;m<2;m++)for(int p=0;p<2;p++)assert(sv.wins[g][m][p]==1000+(g==MEMORY?15:g)*4+m*2+p);
+ FILE*old=fopen("v2.sav","wb");assert(old);fwrite(v2,1,sizeof v2,old);fclose(old);
+ v2[2]=14;crc=save_crc(v2,132);for(int i=0;i<4;i++)v2[132+i]=(uint8_t)(crc>>(i*8));
+ assert(save_decode(v2,sizeof v2)&&sv.game==PONG);
+ game=MEMORY;cpu=3;uint8_t bytes[SAVE_BYTES];save_encode(bytes);assert(save_decode(bytes,sizeof bytes));assert(sv.game==MEMORY&&sv.cpu==3);
+ for(unsigned i=0;i<SAVE_BYTES;i++)for(unsigned bit=0;bit<8;bit++){
+ uint8_t bad[SAVE_BYTES];memcpy(bad,bytes,sizeof bad);bad[i]^=1u<<bit;
+ unsigned char before[sizeof sv];memcpy(before,&sv,sizeof sv);assert(!save_decode(bad,sizeof bad));assert(!memcmp(before,&sv,sizeof sv));
+ }
+ assert(!save_decode(legacy,sizeof legacy-1));assert(!save_decode(NULL,0));
+ FILE*f=fopen("legacy.sav","wb");assert(f);fwrite(legacy,1,sizeof legacy,f);fclose(f);
+}
+static void mechanics(void){
+ init(QUICK,0,1);tick(B_FIRE,0);assert(phase==1&&winner==1);
+ init(QUICK,0,1);now=party.signal;tick(B_FIRE,B_FIRE);assert(winner==2&&score[0]==0&&score[1]==0);
+ init(QUICK,0,1);now=party.signal;tick(0,B_FIRE);assert(winner==1);
+ init(QUICK,1,1);now=party.signal;tick(B_FIRE,B_FIRE);assert(winner==0); /* solo EXE alias */
+ init(TUG,0,1);tick(B_FIRE,B_FIRE);assert(fabsf(party.value)<.001f);tick(B_FIRE,0);assert(fabsf(party.value)<.001f);step(120,0,0);tick(B_FIRE,0);assert(party.value<0);
+ init(FOOTBALL,0,1);party.x=9;party.y=131;tick(0,0);assert(winner==1&&phase==1);
+ init(FOOTBALL,0,1);party.x=17;party.y=70;party.vx=-100;tick(0,0);assert(!phase&&party.vx>0);
+ init(FOOTBALL,0,1);party.x=party.p[0].x+14;party.y=party.p[0].y;party.vx=-100;tick(0,0);assert(party.vx>0);
+ init(VOLLEY,0,1);party.x=35;party.y=212;tick(0,0);assert(winner==1&&phase==1);
+ init(VOLLEY,0,1);party.x=160;party.y=135;party.vy=180;tick(0,0);assert(!phase&&party.vy<0);
+ init(ARCHERY,0,1);tick(B_FIRE,0);step(320,B_FIRE,0);tick(0,0);assert(party.shot[0].life>0&&party.shot[0].vx>0&&party.shot[0].vy<0);
+ init(ARCHERY,0,1);party.mark[1]=1;party.shot[0]=(PartyShot){party.p[1].x,185,0,0,1000,0,0};tick(0,0);assert(winner==0&&phase==1);
+ init(DODGE,0,1);party.mark[0]=party.mark[1]=1;for(int p=0;p<2;p++)party.shot[p]=(PartyShot){party.p[p].x,party.p[p].y,0,0,1000,1-p,0};tick(0,0);assert(winner==2);
+ init(METEORS,0,1);party.shot[0]=(PartyShot){80,207,0,0,1,0,10};tick(0,0);assert(winner==2&&party.mark[0]==0&&party.mark[1]==0);
+ init(ROCKETS,0,1);party.p[0].y=222;party.p[1].y=120;tick(0,0);assert(winner==1);
+ init(SUMO,0,1);party.p[0].x=10;tick(0,0);assert(winner==1);
+ init(SUMO,0,1);now+=20000;assert(ring_radius()<55);tick(B_FIRE,0);assert(party.p[0].ready>now);
+ init(FISHING,0,1);party.p[0].y=160;step(80,B_FIRE,0);assert(party.p[0].y>160);step(80,0,0);assert(party.p[0].y<160+8);
+ init(FISHING,0,1);party.p[0].x=party.p[1].x=100;party.p[0].y=party.p[1].y=150;party.shot[0]=(PartyShot){100,150,0,0,1,-1,0};tick(B_FIRE,B_FIRE);assert(winner==2&&phase==1);
+ init(MEMORY,0,1);tick(MEMORY_BIT[(party.seq[0]+1)%4],0);assert(!phase&&!party.index[0]);now=party.signal;
+ for(int i=0;i<party.n;i++){tick(MEMORY_BIT[party.seq[i]],0);assert(!party.flags[0]);}assert(phase==1&&winner==0);
+ init(MEMORY,0,1);now=party.signal;tick(MEMORY_BIT[(party.seq[0]+1)%4],MEMORY_BIT[(party.seq[0]+1)%4]);assert(winner==2);
+}
+static void balance_test(void){
+ assert(KEYS[0][4]==eadk_key_ok&&KEYS[1][4]==eadk_key_exe);
+ for(int g=0;g<NG;g++){game=g;for(int d=-1;d<=1;d+=2){int n=page_game(d);assert(n>=0&&n<NG);}}
+ unsigned quick_wins[3]={0},archery_wins[3]={0};
+ for(int level=1;level<=3;level++){
+ init(PONG,level,1);int y=py[1];step(160,0,0);assert(py[1]==y); /* no instant reaction */
+ init(FOOTBALL,level,1);float x=party.p[1].x;step(160,0,0);assert(party.p[1].x==x);
+ init(QUICK,level,1);assert(party.next-party.signal>=(uint32_t)(level==1?700:level==2?500:350));
+ init(TUG,level,1);for(int t=0;t<16000&&!phase;t+=8)tick(t%200==0?B_FIRE:0,0);assert(phase&&winner==0);
+ for(int run=0;run<20;run++){
+ init(QUICK,level,run+750);for(int t=0;t<300000&&screen==S_PLAY;t+=8)tick(!phase&&reached(party.signal+420)?B_FIRE:0,0);
+ assert(screen==S_OVER);if(score[0]>score[1])quick_wins[level-1]++;
+ init(ARCHERY,level,run+900);
+ for(int t=0;t<300000&&screen==S_PLAY;t+=8)tick(!phase&&ago(party.started)%1800<650?B_FIRE:0,0);
+ assert(screen==S_OVER);if(score[0]>score[1])archery_wins[level-1]++;
+ }
+ assert(quick_wins[level-1]>=(level<3?19:3));assert(archery_wins[level-1]>=12);
+ }
+ FILE*f=fopen("balance-report.json","w");assert(f);
+ fprintf(f,"{\"matches_per_difficulty\":20,\"quick_human_420ms_wins\":[%u,%u,%u],\"archery_human_650ms_charge_wins\":[%u,%u,%u]}\n",quick_wins[0],quick_wins[1],quick_wins[2],archery_wins[0],archery_wins[1],archery_wins[2]);fclose(f);
+}
+static void validate(void){
+ assert(game>=0&&game<NG&&score[0]>=0&&score[1]>=0&&score[0]<=TARGET[game]&&score[1]<=TARGET[game]);
+ if(game>=QUICK){
+ assert(isfinite(party.x)&&isfinite(party.y)&&isfinite(party.value));
+ for(int p=0;p<2;p++)assert(isfinite(party.p[p].x)&&isfinite(party.p[p].y)&&isfinite(party.p[p].vx)&&isfinite(party.p[p].vy));
+ for(int i=0;i<12;i++)assert(isfinite(party.shot[i].x)&&isfinite(party.shot[i].y)&&isfinite(party.shot[i].vx)&&isfinite(party.shot[i].vy));
+ }
+}
+static void playtests(void){
+ FILE*f=fopen("host-report.json","w");assert(f);fprintf(f,"{\"games\":%d,\"party_ram_bytes\":%u,\"save_bytes\":%u,\"ai_runs\":[",NG,(unsigned)sizeof party,SAVE_BYTES);
+ unsigned runs=0;
+ for(int g=QUICK;g<NG;g++)for(int level=1;level<=3;level++){
+ init(g,level,1300+g*19+level);unsigned t=0;
+ for(;t<480000&&screen==S_PLAY;t+=8){tick(0,0);validate();}
+ fprintf(f,"%s{\"game\":%d,\"cpu\":%d,\"elapsed_ms\":%u,\"score\":[%d,%d],\"complete\":%s}",runs++?",":"",g,level,t,score[0],score[1],screen==S_OVER?"true":"false");
+ if(screen!=S_OVER){fprintf(stderr,"CPU game %d level%d stalled, score %d-%d at %u\n",g,level,score[0],score[1],t);abort();}
+ assert(saves&&saved[0]=='P'&&saved[1]==3);
+ }
+ fprintf(f,"],\"random_runs\":150,\"screen\":%u,\"game\":%u,\"cpu\":%u,\"now\":%u,\"phase\":%u,\"score\":%u,\"sv\":%u,\"sv_size\":%u}\n",(unsigned)sizeof screen,(unsigned)sizeof game,(unsigned)sizeof cpu,(unsigned)sizeof now,(unsigned)sizeof phase,(unsigned)sizeof score,(unsigned)sizeof sv,(unsigned)sizeof sv);fclose(f);
+ for(int g=0;g<NG;g++)for(int run=0;run<10;run++){
+ init(g,run%4,g*1001+run+1);unsigned p0=0,p1=0;
+ for(int t=0;t<12000&&screen==S_PLAY;t+=8){unsigned a=p0,b=p1;if(t%88==0)p0=rnd()&31,p1=rnd()&31;pad[0]=p0;pad[1]=p1;tap[0]=p0&~a;tap[1]=p1&~b;now+=8;ms=8;match_step();validate();}
+ }
+}
+static void renders(void){
+ memset(sv.wins,0,sizeof sv.wins);
+ for(int g=0;g<NG;g++){
+ init(g,0,g+1);char path[80];screen=S_MENU;gfx_render(scene,0,0,240);if(g%4==0){sprintf(path,"menu-%d.ppm",g/4+1);shot(path);}
+ screen=S_RULES;gfx_render(scene,0,0,240);sprintf(path,"rules-%02d.ppm",g);shot(path);
+ int end=gfx_paragraph(&np_font_small,160,52,284,11,RULES[g],WHITE,256);if(end>100){fprintf(stderr,"rules too tall %d: %d\n",g,end);abort();}
+ screen=S_PLAY;step(g==ARCHERY?650:850,g==ARCHERY?B_FIRE:0,0);gfx_render(scene,0,0,240);sprintf(path,"game-%02d.ppm",g);shot(path);
+ for(int s=S_PAUSE;s<=S_SAVE_ERROR;s++){screen=s;sel=0;gfx_render(scene,0,0,240);}
+ }
+}
+int main(void){
+ assert(offsetof(__typeof__(party),signal)==328); /* ARM debugger fixture */
+ gfx_buf=strip;static const uint32_t colours[2]={0xEF4136,0x2E7CF6};
+ for(int p=0;p<2;p++)team[p]=gfx_rgb(colours[p]),light[p]=gfx_rgb(gfx_lerp888(colours[p],0xFFFFFF,120)),dark[p]=gfx_rgb(gfx_lerp888(colours[p],0,110));
+ saves_test();mechanics();balance_test();playtests();renders();
+ printf("PASS: fifteen games; 33 complete AI matches, 150 random runs, mechanics, legacy/CRC saves and all screens.\n");return 0;
+}
diff --git a/games/twoplayer/tests/test_arm.py b/games/twoplayer/tests/test_arm.py
new file mode 100644
index 00000000..3d4af1ef
--- /dev/null
+++ b/games/twoplayer/tests/test_arm.py
@@ -0,0 +1,128 @@
+"""Execute the actual ARM app, including firmware memory and clean-exit checks."""
+import argparse,io,json,os,re,shlex,struct,tempfile,types
+from pathlib import Path
+ROOT=Path(__file__).resolve().parents[1];REPO=ROOT.parents[1]
+emu_path=REPO/'tools/emu.py';emu=types.ModuleType('twoplayer_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('cmd = [nwlink, "nwa-elf",','cmd = nwlink + ["nwa-elf",')
+source=source.replace('chunk = CPU_HZ // 1000','chunk = CPU_HZ // 10000').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 presses(*items):return[(t,t+d,emu.KEYS[k])for t,k,d in items]
+def storage(path,items):
+ data=bytearray(emu.STORAGE_SIZE);at=0
+ for name,value in items:
+ r=name.encode()+b'\0'+value;n=2+len(r);struct.pack_into('<H',data,at,n);data[at+2:at+n]=r;at+=n
+ assert at+2<=len(data);path.write_bytes(data)
+def records(data):
+ result={};at=0
+ while at+2<=len(data):
+ n=struct.unpack_from('<H',data,at)[0]
+ if not n:break
+ assert n>=3 and at+n<=len(data);name,value=data[at+2:at+n].split(b'\0',1);result[name.decode()]=value;at+=n
+ return result
+def uint(c,name):return struct.unpack('<I',bytes(c.uc.mem_read(c.symbols[name],4)))[0]
+def exited(c,upsilon=False):
+ assert c.exited,'App did not exit';assert not c.violations,sorted(set(c.violations));assert not c.firmware_ram_changes();assert c.app_ram_clean();assert c.locks==0 and c.max_locks==(0 if upsilon else 1)
+
+def main():
+ ap=argparse.ArgumentParser();ap.add_argument('--nwlink',default='nwlink');ap.add_argument('--quick',action='store_true');a=ap.parse_args()
+ nw=['node',a.nwlink]if Path(a.nwlink).is_file()and not a.nwlink.endswith(('.exe','.cmd'))else shlex.split(a.nwlink)
+ out=ROOT/'output/arm';out.mkdir(parents=True,exist_ok=True);tempfile.tempdir=str(out);app=str(ROOT/'output/twoplayer-debug.nwa');report=[]
+ legacy=(ROOT/'output/legacy.sav').read_bytes();sentinel=b'print(42)\n'
+ profiles=[('n0120','n0120','epsilon',153676),('n0110','n0110','epsilon',148928),('n0115','n0110','epsilon',133652),('upsilon','n0110','upsilon',107674)]
+ def key(c,k,d=45):
+ t=int(c.now_ms)+10;c.keys+=presses((t,k,d));c.run(t+d+55)
+ def check(c):
+ assert not c.violations,sorted(set(c.violations));assert not c.firmware_ram_changes()
+ for profile,model,system,ram in profiles[:1]if a.quick else profiles:
+ emu.configure(model,system,ram);emu.CPU_HZ=216_000_000 if model=='n0120'else 86_400_000
+ st=out/(profile+'.bin');storage(st,[('keep.py',sentinel),('twoplayer.sav',legacy)])
+ c=emu.Calculator(app,storage_file=str(st),nwlink=nw);c.enable_checks();c.run(160)
+ assert uint(c,'screen')==0 and uint(c,'game')==3 and uint(c,'cpu')==2
+ # Select two-player mode, return to game 0, and navigate every page through real keys.
+ key(c,'left');key(c,'left')
+ for _ in range(3):key(c,'up')
+ assert uint(c,'cpu')==0 and uint(c,'game')==0
+ c.save_png(str(out/(profile+'-menu.png')))
+ for g in range(15):
+ assert uint(c,'screen')==0 and uint(c,'game')==g,(profile,g)
+ key(c,'ok');assert uint(c,'screen')==1
+ key(c,'ok');assert uint(c,'screen')==2
+ clock=uint(c,'now');c.run(c.now_ms+130);assert uint(c,'now')>clock
+ if g==8:
+ # New action keys really charge independently; Shift no longer acts.
+ key(c,'shift')
+ flags=c.symbols['party']+336
+ assert bytes(c.uc.mem_read(flags,2))==b'\x00\x00'
+ t=int(c.now_ms)+20;c.keys+=presses((t,'ok',650),(t,'exe',550))
+ c.run(t+400);assert bytes(c.uc.mem_read(flags,2))==b'\x01\x01'
+ c.save_png(str(out/(profile+'-archery-charge.png')))
+ c.run(t+740);assert bytes(c.uc.mem_read(flags,2))==b'\x00\x00'
+ assert any(struct.unpack('<h',bytes(c.uc.mem_read(c.symbols['party']+56+i*20+16,2)))[0]>0 for i in range(12))
+ c.save_png(str(out/(profile+'-archery-shot.png')))
+ # Both physical key sets are sampled together; pause stops only game time.
+ t=int(c.now_ms)+10
+ c.keys+=presses((t,'left',70),(t,'ok',60),(t,'minus',70),(t,'exe',60));c.run(t+100)
+ key(c,'back');assert uint(c,'screen')==3
+ frozen=uint(c,'now');c.run(c.now_ms+120);assert uint(c,'now')==frozen
+ key(c,'back');assert uint(c,'screen')==2
+ if g>=4:c.save_png(str(out/(profile+'-game-%02d.png'%g)))
+ key(c,'back');key(c,'down');key(c,'down');key(c,'ok');assert uint(c,'screen')==0
+ check(c)
+ if g<14:key(c,'down')
+ # Page jump wraps and retains the row; CPU mode remains independent.
+ key(c,'9');assert uint(c,'game')==2
+ key(c,'7');assert uint(c,'game')==14
+ key(c,'right');assert uint(c,'cpu')==1
+ key(c,'right');key(c,'right');assert uint(c,'cpu')==3
+ key(c,'ok');key(c,'ok');key(c,'back');key(c,'down');key(c,'ok');assert uint(c,'screen')==2 and uint(c,'phase')==0
+ # Real keys score for each human in Quick Draw; holding action does not
+ # leak an extra shot into the following round.
+ # 14 -> 2 -> 3 -> 4, then CPU hard -> two players.
+ key(c,'back');key(c,'down');key(c,'down');key(c,'ok')
+ key(c,'9');key(c,'down');key(c,'down');key(c,'right')
+ assert uint(c,'game')==4 and uint(c,'cpu')==0
+ key(c,'ok');key(c,'ok')
+ for player,k in enumerate(['ok','exe']):
+ if player:c.run(c.now_ms+1650)
+ assert uint(c,'phase')==0
+ # signal is a plain uint32 at the offset verified by the host.
+ signal=struct.unpack('<I',bytes(c.uc.mem_read(c.symbols['party']+328,4)))[0]
+ c.run(c.now_ms+max(0,signal-uint(c,'now'))+40)
+ key(c,k)
+ assert uint(c,'phase')==1 and uint(c,'winner')==player
+ assert struct.unpack('<ii',bytes(c.uc.mem_read(c.symbols['score'],8)))==((1,0)if player==0 else(1,1))
+ r=dict(profile=profile,games_opened=15,pause_freezes=True,both_human_keys_score=True,stack_bytes=c.stack_used())
+ key(c,'home',90);c.run(c.now_ms+160);exited(c,system=='upsilon')
+ recs=records(st.read_bytes());assert recs['keep.py']==sentinel
+ saved=recs['twoplayer.sav'];assert len(saved)==128 and saved[:4]==b'P\x03\x04\x00'
+ # All 16 legacy counters survive the expansion; none were won during these short tests.
+ assert saved[4:36]==legacy[4:36] and not any(saved[36:124])
+ d=emu.Calculator(app,storage_file=str(st),nwlink=nw);d.enable_checks();d.run(140);assert uint(d,'game')==4 and uint(d,'cpu')==0
+ key(d,'onoff',90);d.run(d.now_ms+150);exited(d,system=='upsilon');assert records(st.read_bytes())['twoplayer.sav']==saved
+ report.append(r);print(json.dumps(r),flush=True)
+ emu.configure()
+ import zlib
+ for old_game,expected in [(15,14),(14,0)]:
+ previous=bytearray((ROOT/'output/v2.sav').read_bytes());previous[2]=old_game
+ struct.pack_into('<I',previous,132,zlib.crc32(previous[:132]))
+ st=out/('migration-%d.bin'%old_game);storage(st,[('keep.py',sentinel),('twoplayer.sav',previous)])
+ c=emu.Calculator(app,storage_file=str(st),nwlink=nw);c.enable_checks();c.run(160)
+ assert uint(c,'game')==expected
+ key(c,'home',90);c.run(c.now_ms+160);exited(c)
+ migrated=records(st.read_bytes())['twoplayer.sav']
+ assert len(migrated)==128 and migrated[:3]==bytes([80,3,expected])
+ assert migrated[4:116]==previous[4:116] and migrated[116:124]==previous[124:132]
+ assert records(st.read_bytes())['keep.py']==sentinel
+ # No accidental actions when launching with OK held; a full file system stays intact.
+ emu.configure();c=emu.Calculator(app,nwlink=nw);c.enable_checks();c.keys=presses((0,'ok',350));c.run(450);assert uint(c,'screen')==0
+ key(c,'home',90);c.run(c.now_ms+150);exited(c)
+ st=out/'full.bin';filler=b'x'*(emu.STORAGE_SIZE-24);storage(st,[('full.py',filler)])
+ c=emu.Calculator(app,storage_file=str(st),nwlink=nw);c.enable_checks();c.run(150);key(c,'home');assert uint(c,'screen')==6
+ key(c,'ok');assert uint(c,'screen')==6
+ key(c,'down');key(c,'ok');c.run(c.now_ms+150);exited(c);assert records(st.read_bytes())=={'full.py':filler}
+ report.append(dict(legacy_migration=True,full_storage_retry_and_unsaved_exit=True,held_launch_key=True))
+ (out/'report.json').write_text(json.dumps(report,indent=2)+'\n');print('ARM tests passed',flush=True)
+if __name__=='__main__':main()
diff --git a/games/twoplayer/tests/test_integration.py b/games/twoplayer/tests/test_integration.py
new file mode 100644
index 00000000..31f33b91
--- /dev/null
+++ b/games/twoplayer/tests/test_integration.py
@@ -0,0 +1,121 @@
+"""Build the real NumPlay launcher with only this module for integration testing.
+
+This deliberately small test catalogue is not a release of NumPlay. Production
+builds still read the complete games/games.json and use the existing twoplayer ID.
+"""
+import argparse
+import json
+import shlex
+import subprocess
+import sys
+from elftools.elf.elffile import ELFFile
+from pathlib import Path
+import test_arm as arm
+
+ROOT = Path(__file__).resolve().parents[1]
+REPO = ROOT.parents[1]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('--nwlink', default='nwlink')
+ args = ap.parse_args()
+ nw = shlex.split(args.nwlink)
+ out = ROOT / 'output/integration'
+ out.mkdir(parents=True, exist_ok=True)
+ arm.tempfile.tempdir = str(out)
+
+ def run(*cmd):
+ subprocess.run([str(x) for x in cmd], cwd=REPO, check=True)
+
+ def py(tool, *args):
+ run(sys.executable, REPO / 'tools' / tool, *args)
+
+ device = shlex.split(subprocess.check_output(nw + ['eadk-cflags-device'], text=True))
+ cc = ['arm-none-eabi-gcc', *device, '-std=gnu11', '-Os', '-Wall', '-Wextra',
+ '-Wno-unused-parameter', '-fno-math-errno', '-ffunction-sections', '-fdata-sections',
+ '-fno-tree-loop-distribute-patterns', '-DNP_VERSION="local-2players"',
+ '-I' + str(REPO / 'launcher/src')]
+ games = json.loads((REPO / 'games/games.json').read_text())
+ index = next(i for i, g in enumerate(games, 1) if g['id'] == 'twoplayer')
+ game = games[index - 1]
+ assert game['app'] == 'TwoPlayers.nwa' and game['records'] == ['twoplayer.sav']
+ run('arm-none-eabi-ld', '-r', '-d', '-z', 'noexecstack', '--force-group-allocation', '-T', REPO / 'tools/module.ld',
+ ROOT / 'output/module.o', '-o', out / 'stage1.o')
+ run('arm-none-eabi-objcopy', '--keep-global-symbol=main',
+ '--redefine-sym', 'eadk_keyboard_scan=np_keyboard_scan',
+ '--redefine-sym', 'eadk_event_get=np_event_get',
+ '--redefine-sym', 'eadk_display_draw_string=np_display_draw_string',
+ out / 'stage1.o', out / 'stage2.o')
+ py('npmodule.py', out / 'stage2.o', out / 'twoplayer.o', '--game', 'twoplayer',
+ '--index', index, '--json', out / 'twoplayer.json')
+ py('gen_games.py', REPO / 'games/games.json', out, out, '--only', 'twoplayer')
+ py('shots.py', '--id', 'twoplayer', '--index', index, '--colors', 16,
+ out / 'shots.c', ROOT / 'docs/shot.png')
+ objects = [out / 'twoplayer.o']
+ entry = out / 'entry_twoplayer.c' if (out / 'entry_twoplayer.c').exists() else out / 'gametable.c'
+ sources = sorted((REPO / 'launcher/src').glob('*.c')) + [entry, out / 'shots.c']
+ for src in sources:
+ obj = out / ('launcher-' + src.stem + '.o')
+ run(*cc, '-c', src, '-o', obj)
+ objects.append(obj)
+ marks = 'marks_twoplayer' if (out / 'marks_twoplayer.s').exists() else 'marks'
+ for stem in ['arena', marks]:
+ obj = out / (stem + '.o')
+ run(*cc, '-c', out / (stem + '.s'), '-o', obj)
+ objects.append(obj)
+ run(*cc, '-DNP_APP_NAME="NumPlay integration test"', '-c', REPO / 'launcher/app_name.c', '-o', out / 'name.o')
+ run(*nw, 'png-icon-o', REPO / 'launcher/assets/icon.png', out / 'icon.o')
+ app = out / 'NumPlay-test.nwa'
+ run(*cc, '-nostartfiles', '--specs=nano.specs', '-Wl,--relocatable', '-Wl,--gc-sections',
+ '-Wl,-e,main', '-Wl,-u,eadk_app_name', '-Wl,-u,eadk_app_icon', '-Wl,-u,eadk_api_level',
+ '-Wl,-T,' + str(out / 'numplay.ld'), *objects, out / 'name.o', out / 'icon.o', '-lm', '-o', app)
+ report = []
+ for profile, model, system, ram in [('n0120', 'n0120', 'epsilon', 153676),
+ ('upsilon', 'n0110', 'upsilon', 107674)]:
+ arm.emu.configure(model, system, ram)
+ st = out / (profile + '.storage')
+ arm.storage(st, [('keep.py', b'print(42)\n')])
+ c = arm.emu.Calculator(str(app), storage_file=str(st), nwlink=nw)
+ # npmodule deliberately removes the module's private symbols. Recover
+ # their RAM offsets from its input solely for these debugger assertions.
+ with (out / 'stage1.o').open('rb') as f:
+ elf = ELFFile(f)
+ for sym in elf.get_section_by_name('.symtab').iter_symbols():
+ if sym.name in ('screen', 'game', 'phase'):
+ section = elf.get_section(sym['st_shndx']).name
+ assert section == '.bss'
+ c.symbols[sym.name] = c.symbols['np_twoplayer_bss'] + sym['st_value']
+ c.enable_checks()
+ c.run(1100)
+ c.save_png(str(out / (profile + '-launcher.png')))
+
+ def key(k, wait=200):
+ t = int(c.now_ms) + 20
+ c.keys += arm.presses((t, k, 70))
+ c.run(t + wait)
+
+ key('ok', 650) # Actual carousel -> existing 2 Players module.
+ assert arm.uint(c, 'screen') == 0
+ key('9'); key('ok'); key('ok')
+ assert arm.uint(c, 'screen') == 2 and arm.uint(c, 'game') == 4
+ key('back'); key('down'); key('down'); key('ok')
+ assert arm.uint(c, 'screen') == 0
+ key('back'); key('down'); key('ok', 800) # Module Quit -> carousel.
+ assert not c.exited
+ c.save_png(str(out / (profile + '-returned.png')))
+ key('ok', 650) # Re-enter: BSS reset, selection restored from real storage.
+ assert arm.uint(c, 'screen') == 0 and arm.uint(c, 'game') == 4
+ key('home', 600)
+ arm.exited(c, system == 'upsilon')
+ records = arm.records(st.read_bytes())
+ assert len(records['twoplayer.sav']) == 128 and records['keep.py'] == b'print(42)\n'
+ assert b'twoplayer.sav' in records['numplay_saves.py']
+ report.append(dict(profile=profile, launch_return_reenter=True, backup=True,
+ stack_bytes=c.stack_used()))
+ (out / 'report.json').write_text(json.dumps(report, indent=2) + '\n')
+ print('PASS: existing NumPlay module launch, return, re-entry, shared saves and backup.')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/games/twoplayer/tests/test_languages.py b/games/twoplayer/tests/test_languages.py
new file mode 100644
index 00000000..56c95ba8
--- /dev/null
+++ b/games/twoplayer/tests/test_languages.py
@@ -0,0 +1,26 @@
+"""Check translation coverage, mechanics and all layouts using the real fonts."""
+from pathlib import Path
+import shutil,importlib.util,subprocess,sys,re
+repo=Path(__file__).resolve().parents[3];out=repo/'games/twoplayer/output/languages';out.mkdir(parents=True,exist_ok=True)
+def load(name,p):
+ s=importlib.util.spec_from_file_location(name,p);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);return m
+lang=load('lang',repo/'tools/lang.py')
+for code in ['fr','zh']:
+ dst=out/code
+ for sub in ['games/twoplayer/src','games/twoplayer/tests','games/common','launcher/src']:
+ for p in (repo/sub).glob('*'):
+ if p.is_file() and p.suffix in ['.c','.h']:
+ target=dst/sub/p.name;target.parent.mkdir(parents=True,exist_ok=True);text=p.read_text(encoding='utf-8')
+ if sub=='games/twoplayer/src':
+ table=lang.load_table('twoplayer',code);missing=[s for s in lang.marked(p) if s not in table];assert not missing,missing
+ text=lang.MARK.sub(lambda m:'T("'+table[m.group(2)]+'")',text)
+ if p.name=='np_text.h':text=text.replace('#define NP_TEXT_EXTRA 0','#define NP_TEXT_EXTRA 1')
+ target.write_text(text,encoding='utf-8')
+ texts='\n'.join(lang.load_table('twoplayer',code).values());(dst/'texts.txt').write_text(texts,encoding='utf-8')
+ extra=','.join(str(c)for c in sorted({ord(c)for c in texts if 0x80<=ord(c)<0x180}))
+ subprocess.run([sys.executable,str(repo/'tools/fontgen.py'),str(dst/'launcher/src/font_data.c'),'--extra',extra],check=True)
+ subprocess.run([sys.executable,str(repo/'tools/xfont.py'),'table',str(repo/'assets/fonts/fusion-pixel-12px.bin'),str(dst/'launcher/src/np_xfont.h'),str(dst/'texts.txt')],check=True)
+ target=dst/'games/twoplayer';(target/'output').mkdir(exist_ok=True)
+ subprocess.run(['gcc','-std=c11','-O2','-Wall','-Wextra','-Wno-unused-parameter','-Wno-misleading-indentation','-Itests','tests/test.c','../../launcher/src/gfx.c','../../launcher/src/font_data.c','../../launcher/src/xfont.c','-lm','-o','output/test.exe'],cwd=target,check=True)
+ subprocess.run([str(target/'output/test.exe')],cwd=target/'output',check=True)
+ print('Translations and layout pass:',code)
diff --git a/games/twoplayer/tools/bot.py b/games/twoplayer/tools/bot.py
index 95501b2b..b19462b7 100644
--- a/games/twoplayer/tools/bot.py
+++ b/games/twoplayer/tools/bot.py
@@ -138,7 +138,7 @@ class Bot:
if abs(d) < 0.6 and math.hypot(x1 - x0, y1 - y0) > 50:
keys.append("up")
if abs(d) < 0.15 and self.c.now_ms - self.fired > 700:
- keys.append("shift")
+ keys.append("ok")
self.fired = self.c.now_ms
self.hold(keys)
diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txt
index bdef86b6..87824f2a 100644
--- a/launcher/lang/fr.txt
+++ b/launcher/lang/fr.txt
@@ -135,4 +135,6 @@ Needs Il manque
Sokoban Sokoban
Push every box home Pousse chaque caisse à sa place
-Levels: Microban by David W. Skinner Niveaux : Microban de David W. Skinner
\ No newline at end of file
+Levels: Microban by David W. Skinner Niveaux : Microban de David W. Skinner
+Fifteen mini-games, side by side Quinze mini-jeux, côte à côte
+Additional mini-games by Bobydeluxe Mini-jeux supplémentaires par Bobydeluxe
diff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txt
index 8194210b..3ca18325 100644
--- a/launcher/lang/zh.txt
+++ b/launcher/lang/zh.txt
@@ -134,4 +134,6 @@ Needs 内存还差
Sokoban 推箱子
Push every box home 把每个箱子推到位
-Levels: Microban by David W. Skinner 关卡:David W. Skinner 的 Microban
\ No newline at end of file
+Levels: Microban by David W. Skinner 关卡:David W. Skinner 的 Microban
+Fifteen mini-games, side by side 十五款小游戏,并肩对战
+Additional mini-games by Bobydeluxe 新增小游戏:Bobydeluxe
diff --git a/tests/test_games.py b/tests/test_games.py
index 8c397437..29e0c1b5 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -459,8 +459,8 @@ CHECKS = {
"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,
lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
# Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies kept
- "twoplayer": (lambda v: len(v) == 36 and v[:4] == b"P\1\1\1",
- lambda v: len(v) == 36 and v[:4] == b"P\1\2\2"),
+ "twoplayer": (lambda v: len(v) == 128 and v[:4] == b"P\3\1\1",
+ lambda v: len(v) == 128 and v[:4] == b"P\3\2\2"),
# a game kept (Easy, the guide read) with the two digits the hints wrote (the digits at 109); then three
"sudoku": (lambda v: len(v) == 352 and v[:4] == b"S\1\3\0" and sum(1 <= b <= 9 for b in v[109:190]) == 2,
lambda v: v[2] & 1 and sum(1 <= b <= 9 for b in v[109:190]) == 3),