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.

2 Players: Quick Draw and Tug of War, player 1 on OK, a fairer computer

Mason363b4933c713bd8
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index dc29f093..03a0c171 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -80,6 +80,7 @@ jobs:
make -C games/sudoku host test
make -C games/uttt host test
make -C games/sokoban host test
+ make -C games/twoplayer host test
make -C games/flappydunk host test
make -C games/towerblock host test
make -C games/suika host test
diff --git a/.github/workflows/twoplayer.yml b/.github/workflows/twoplayer.yml
deleted file mode 100644
index ad6df47d..00000000
--- a/.github/workflows/twoplayer.yml
+++ /dev/null
@@ -1,52 +0,0 @@
-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 35e025dc..f2fc2527 100644
--- a/README.md
+++ b/README.md
@@ -256,7 +256,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] [2 Players](games/twoplayer/README.md): fifteen mini-games, with local two-player controls or three computer difficulties
+- [x] Pong and more two-player games: 2 Players, with Pong, Air Hockey, Tanks and Light Cycles
- [x] Cookie Clicker
- [x] Level Devil
- [x] Sonic the Hedgehog: the whole 1991 game, Green Hill to the Final Zone, with the Special Stages
@@ -310,8 +310,6 @@ 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 7d952a9a..7e805e2a 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 c6167ad9..75ccd0e6 100644
--- a/games/games.json
+++ b/games/games.json
@@ -479,8 +479,8 @@
"id": "twoplayer",
"rank": 14,
"title": "2 Players",
- "tagline": "Fifteen mini-games, side by side",
- "credit": "Additional mini-games by Bobydeluxe",
+ "tagline": "Pong and more, side by side",
+ "credit": null,
"top": "0xD33B3B",
"bottom": "0x172A72",
"accent": "0x2E7CF6",
diff --git a/games/twoplayer/.gitignore b/games/twoplayer/.gitignore
index 179b4868..ea1472ec 100644
--- a/games/twoplayer/.gitignore
+++ b/games/twoplayer/.gitignore
@@ -1,3 +1 @@
output/
-__pycache__/
-*.pyc
diff --git a/games/twoplayer/Makefile b/games/twoplayer/Makefile
index f95d1be3..c378a398 100644
--- a/games/twoplayer/Makefile
+++ b/games/twoplayer/Makefile
@@ -1,6 +1,7 @@
-# 2 Players — fifteen mini-games inside the existing NumPlay app/module.
+# 2 Players: Pong, Air Hockey, Tanks, Light Cycles, Quick Draw and Tug of War, for two on one calculator.
# make build output/twoplayer.nwa
# make check link the app like the calculator does (output/twoplayer.bin)
+# make test the tests on a computer (tests/play.c)
#
# In NumPlay the game draws with the launcher's strips, shapes and fonts and saves through its
# file functions (module.o leaves them to the launcher); on its own it brings them along.
@@ -10,27 +11,22 @@ 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 src/party.h
-HOST_CC ?= cc
-PYTHON ?= python3
+ ../../launcher/src/np.h ../../launcher/src/font.h
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 host test test-arm test-integration
+.PHONY: build check clean host test
build: $(BUILD_DIR)/twoplayer.nwa
check: $(BUILD_DIR)/twoplayer.nwa
- $(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
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/twoplayer.bin
@echo "BIN $(BUILD_DIR)/twoplayer.bin: $$(wc -c < $(BUILD_DIR)/twoplayer.bin) bytes"
# compiled, then linked (the link options would upset the compiler)
@@ -44,22 +40,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-debug.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \
+$(BUILD_DIR)/twoplayer.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)"
+# on a computer, with the sanitizers: the rules, bots against bots, random sessions, old saves (tests/play.c)
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -DPLATFORM_DEVICE=1 -DHOST -ffp-contract=off \
+ $(shell $(NWLINK) eadk-cflags-simulator) -fsanitize=address,undefined -fno-sanitize-recover=undefined
+host: output/play
+output/play: $(SRC) tests/play.c $(HEADERS)
+ $(Q) mkdir -p output
+ $(Q) cc $(HOST_FLAGS) tests/play.c ../../launcher/src/gfx.c ../../launcher/src/font_data.c \
+ ../../launcher/src/xfont.c -lm -o $@
+ @echo "HOST $@"
+test: output/play
+ output/play test
$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
@echo "ICON $<"
diff --git a/games/twoplayer/README.md b/games/twoplayer/README.md
index 9bb9685d..37bd77ef 100644
--- a/games/twoplayer/README.md
+++ b/games/twoplayer/README.md
@@ -1,87 +1,43 @@
# 2 Players
-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.
+Six games for two people on one calculator, side by side: player 1 on the arrows and OK, player 2 on the keys around + and EXE, both at once. No one to play with? Player 2 can be the computer, easy, normal or hard.
-<img src="docs/games.png" width="640" alt="The fifteen 2 Players mini-games">
+<img src="docs/games.png" width="720" alt="Pong, Air Hockey, Tanks, Light Cycles, Quick Draw and Tug of War">
- **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.
+- **Quick Draw**: wait for DRAW!, then press your key before the other one. Press too soon and you lose the round. First to 5.
+- **Tug of War**: tap your key as fast as you can to pull the flag past your line. The rope slides back a little, and after 30 seconds the one ahead takes the round. First to 5.
- **Before each game**, a map of the calculator's keyboard lights up each player's keys in their colour, with the rules.
-- **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 computer** plays at a player's pace: it reacts after a moment, misjudges a little and moves slower than you, more so on easy. In Pong it works out where the ball will come, in Air Hockey it gets behind the puck to shoot or guards its goal, its tank finds its way through the maze and looks for a shot, and its light cycle keeps the most room for itself.
- **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 |
-| Action (shoot, jump, pull, dash, fish) | OK | EXE |
+| Fire, draw, pull | 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, 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.
-
-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.
+| Home | Save and quit |
-## 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">
+Against the computer, EXE works as OK too.
## 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.
-**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.
+**Quick Draw** and **Tug of War** are by [Bobydeluxe](https://github.com/Bobydeluxe), in the spirit of the short duels of 12 MiniBattles and GoBattle 2, with no code or art from them. Bobydeluxe also put player 1's key on OK and made the computer fairer.
-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 and verification
+Inside NumPlay it draws with the launcher's own shapes and fonts and saves through its file functions, so the six games take about 15 KB.
-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.
+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).
-See [VALIDATION.md](VALIDATION.md) for measured results and limits. No physical calculator was connected for these checks. `output/` holds generated reports and screenshots.
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink). `make test` plays every game on a computer, bots against bots. `tools/bot.py` plays it against the computer in the emulator.
diff --git a/games/twoplayer/VALIDATION.md b/games/twoplayer/VALIDATION.md
deleted file mode 100644
index dcf33487..00000000
--- a/games/twoplayer/VALIDATION.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# 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
deleted file mode 100644
index 943d3f8d..00000000
Binary files a/games/twoplayer/docs/archery.png and /dev/null differ
diff --git a/games/twoplayer/docs/games.png b/games/twoplayer/docs/games.png
index b2b77613..ad6c71ea 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
deleted file mode 100644
index d36f1e7c..00000000
Binary files a/games/twoplayer/docs/pages.png and /dev/null differ
diff --git a/games/twoplayer/docs/shot.png b/games/twoplayer/docs/shot.png
index 98ab65ca..7e91494f 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 95a4a34f..b9f4b40f 100644
--- a/games/twoplayer/lang/fr.txt
+++ b/games/twoplayer/lang/fr.txt
@@ -3,72 +3,64 @@ Pong Pong
Air Hockey Air hockey
Tanks Tanks
Light Cycles Motos de lumière
+Quick Draw Duel éclair
+Tug of War Tir à la corde
+Volleyball Volley
+Sumo Sumo
+Rocket Race Course de fusées
+Archery Tir à l'arc
+Dodgeball Balle aux prisonniers
+Football Football
+Meteor Run Pluie de météores
+Fishing Pêche
+Memory Duel Duel de mémoire
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.
+Wait for DRAW!, then press your key: the first one wins. Too soon loses the round. Attends FEU !, puis appuie sur ta touche : le premier gagne. Trop tôt, tu perds la manche.
+Tap your key fast to pull the rope. Pull the flag past your line. Appuie vite sur ta touche pour tirer la corde. Fais passer le drapeau derrière ta ligne.
+Jump with up or your key. Hit the ball over the net and don't let it land on your side. Saute avec haut ou ta touche. Renvoie la balle par-dessus le filet sans la laisser tomber de ton côté.
+Push the other one out of the ring. Your key dashes. The ring shrinks. Pousse l'autre hors du cercle. Ta touche fonce. Le cercle rétrécit.
+Tap up or your key to fly through the gaps. Don't touch the walls or the edges. Appuie sur haut ou ta touche pour passer dans les trous. Ne touche ni les murs ni les bords.
+Up and down aim. Hold your key to draw the bow, let go to shoot. Three hits win. Haut et bas visent. Maintiens ta touche pour bander l'arc, relâche pour tirer. Trois touches gagnent.
+Your key throws at the other one. Dodge their balls. Three hits win. Ta touche lance sur l'autre. Évite ses balles. Trois touches gagnent.
+Push the ball into the other goal. Near it, your key kicks it at the goal. Pousse le ballon dans l'autre but. Tout près, ta touche le tire vers le but.
+Dodge the falling rocks. Both lanes get the same ones. Last one standing wins. Évite les rochers qui tombent : les mêmes dans les deux couloirs. Le dernier debout gagne.
+Hold your key to lower the hook, let go to reel in. Land a fish first. Maintiens ta touche pour descendre l'hameçon, relâche pour remonter. Attrape un poisson le premier.
+Watch the arrows, then repeat them. First to finish without a mistake wins. Regarde les flèches, puis refais-les. Le premier à finir sans erreur gagne.
Computer IA
Player 2 Joueur 2
You Toi
Player 1 Joueur 1
+Back pause Retour pause
+DRAW! FEU !
+Wait... Attends...
+Your turn! À toi !
+Watch Regarde
Computer: easy IA : facile
Computer: normal IA : normale
Computer: hard IA : difficile
2 Players 2 joueurs
+OK play Back quit OK jouer Retour quitter
+arrows flèches
First to Premier à
Play Jouer
+Back games Retour jeux
Draw! Égalité !
Resume Reprendre
Restart Recommencer
Other games Autres jeux
Quit game Quitter
Paused Pause
+OK choose Back resume OK choisir Retour reprendre
Player 1 wins! Joueur 1 gagne !
Player 2 wins! Joueur 2 gagne !
You win! Gagné !
The computer wins L'IA gagne
Rematch Revanche
+OK choose Back games OK choisir Retour jeux
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
+OK choose Back no OK choisir Retour non
diff --git a/games/twoplayer/lang/zh.txt b/games/twoplayer/lang/zh.txt
index 66fc60ef..67658497 100644
--- a/games/twoplayer/lang/zh.txt
+++ b/games/twoplayer/lang/zh.txt
@@ -3,72 +3,64 @@ Pong 乒乓
Air Hockey 桌上冰球
Tanks 坦克大战
Light Cycles 光速摩托
+Quick Draw 快枪对决
+Tug of War 拔河
+Volleyball 排球
+Sumo 相扑
+Rocket Race 火箭穿越
+Archery 射箭
+Dodgeball 躲避球
+Football 足球
+Meteor Run 流星雨
+Fishing 钓鱼
+Memory Duel 箭头对决
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. 驾驶你的光速摩托,让对方撞上墙壁或光轨。摩托从不停下,也不能掉头。
+Wait for DRAW!, then press your key: the first one wins. Too soon loses the round. 等到出现「拔枪!」再按你的键,先按的获胜。按太快就输了这一局。
+Tap your key fast to pull the rope. Pull the flag past your line. 快速连按你的键,把旗子拉过你的线。
+Jump with up or your key. Hit the ball over the net and don't let it land on your side. 用上或你的键跳起。把球打过网,别让它落在你这边。
+Push the other one out of the ring. Your key dashes. The ring shrinks. 把对方推出场地。你的键是冲撞。场地会变小。
+Tap up or your key to fly through the gaps. Don't touch the walls or the edges. 按上或你的键飞过缺口。别碰到墙或上下边缘。
+Up and down aim. Hold your key to draw the bow, let go to shoot. Three hits win. 上下调整角度。按住你的键拉弓,松开射箭。命中三次获胜。
+Your key throws at the other one. Dodge their balls. Three hits win. 你的键向对方投球。躲开对方的球。命中三次获胜。
+Push the ball into the other goal. Near it, your key kicks it at the goal. 把球推进对方球门。靠近时,你的键把球踢向球门。
+Dodge the falling rocks. Both lanes get the same ones. Last one standing wins. 躲开落下的石头。两边落下的石头相同。最后留下的获胜。
+Hold your key to lower the hook, let go to reel in. Land a fish first. 按住你的键放下鱼钩,松开收线。先钓到鱼的获胜。
+Watch the arrows, then repeat them. First to finish without a mistake wins. 看好箭头,再照着按一遍。先全部按对的获胜,按错就输。
Computer 电脑
Player 2 玩家 2
You 你
Player 1 玩家 1
+Back pause 返回 暂停
+DRAW! 拔枪!
+Wait... 等待…
+Your turn! 轮到你了!
+Watch 看好
Computer: easy 电脑:简单
Computer: normal 电脑:普通
Computer: hard 电脑:困难
2 Players 双人对战
+OK play Back quit OK 开始 返回 退出
+arrows 方向键
First to 先得
Play 开始
+Back games 返回 游戏
Draw! 平局!
Resume 继续
Restart 重新开始
Other games 其他游戏
Quit game 退出游戏
Paused 暂停
+OK choose Back resume OK 选择 返回 继续
Player 1 wins! 玩家 1 获胜!
Player 2 wins! 玩家 2 获胜!
You win! 你赢了!
The computer wins 电脑获胜
Rematch 再来一局
+OK choose Back games OK 选择 返回 游戏
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
+OK choose Back no OK 选择 返回 否
diff --git a/games/twoplayer/src/main.c b/games/twoplayer/src/main.c
index eba40770..2a5d5310 100644
--- a/games/twoplayer/src/main.c
+++ b/games/twoplayer/src/main.c
@@ -1,17 +1,16 @@
-/* 2 Players: fifteen mini-games for two people on one calculator.
+/* 2 Players: Pong and more games for two people on one calculator.
*
- * 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
+ * Player 1 holds the left of the keyboard (the arrows, and OK to act), player 2 the right (the keys
+ * around +, and EXE to act), 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, Light Cycles, and Bobydeluxe's party games. A match is first to a few points, and the
* matches each side has won are kept for every game.
*
* Inside NumPlay it draws with the launcher's strips, shapes and fonts (launcher/src/gfx.c) and
* saves through its file functions, like Block Blast; on its own (TwoPlayers.nwa) it brings them
* along. Positions are in 256ths of a pixel and time in milliseconds, but for the round things
- * of Air Hockey. */
+ * of Air Hockey and the party games, in pixels and seconds. */
#include <eadk.h>
-#include <string.h>
#include "../../../launcher/src/gfx.h"
#include "../../common/np_text.h"
@@ -34,35 +33,24 @@ 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)
-/* 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};
+/* (in the menu's order, and the saves': a new game goes last) */
+enum { PONG, HOCKEY, TANKS, CYCLES, QUICK, TUG, NG };
+static const char *const NAME[NG] = {T("Pong"), T("Air Hockey"), T("Tanks"), T("Light Cycles"), T("Quick Draw"),
+ T("Tug of War")};
+static const uint8_t TARGET[NG] = {11, 7, 5, 5, 5, 5}; /* first to */
+/* the keys each game uses, for its keyboard: left 1, up 2, down 4, right 8, the action 16 */
+static const uint8_t KEYS_USED[NG] = {6, 15, 31, 15, 16, 16};
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("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("Drive through the maze and hit the other tank. Shells bounce off the walls: watch out for your own!"),
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."),
+ T("Wait for DRAW!, then press your key: the first one wins. Too soon loses the round."),
+ T("Tap your key fast to pull the rope. Pull the flag past your line."),
};
-/* twoplayer.sav: the game last chosen, who player 2 is, and the matches won */
+/* twoplayer.sav: the game last chosen, who player 2 is, and the matches won (version 1 had four
+ games: a shorter file of the same layout, read as it is) */
static struct {
uint8_t magic, version, game, cpu; /* cpu: 0 a second player, 1 to 3 the computer, easy to hard */
uint16_t wins[NG][2][2]; /* [game][against the computer][player 1, player 2] */
@@ -73,10 +61,11 @@ static color_t strip[SCREEN_W * STRIP_H];
static color_t team[2], light[2], dark[2]; /* player 1 red, player 2 blue */
static uint32_t now, seed, phase_t; /* now: the game's clock, stopped while paused */
static int ms; /* this frame's milliseconds */
+static float dt; /* ...in seconds */
static int game, cpu, score[2], phase, winner; /* phase: 0 playing, 1 a point just won, 2 the match over */
static int pad[2], tap[2]; /* each player's keys held, and just pressed */
enum { B_LEFT = 1, B_UP = 2, B_DOWN = 4, B_RIGHT = 8, B_FIRE = 16 };
-/* the keys: left, up, down, right, fire */
+/* the keys: left, up, down, right, action */
static const uint8_t KEYS[2][5] = {
{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}};
@@ -91,20 +80,12 @@ static int clampi(int v, int a, int b) { return v < a ? a : v > b ? b : v; }
static float clampf(float v, float a, float b) { return v < a ? a : v > b ? b : v; }
static float len(float x, float y) { return __builtin_sqrtf(x * x + y * y); }
static uint32_t ago(uint32_t t) { return now - t; }
+static bool due(uint32_t t) { return (int32_t)(now - t) >= 0; }
static bool down(uint64_t keys, int k) { return (uint32_t)(keys >> (k & 32)) >> (k & 31) & 1; }
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; }
+static int acted(int p) { return tap[p] >> 4 & 1; } /* the action key just pressed */
/* 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) {
@@ -112,6 +93,18 @@ static int sin64(int a) {
return a & 32 ? -v : v;
}
static int cos64(int a) { return sin64(a + 16); }
+/* The computer sees and thinks at a human's pace: it decides again every so often, not every
+ frame, and holds its keys in between. */
+static struct {
+ uint32_t next;
+ float x, y;
+} bot;
+static bool bot_due(void) {
+ static const uint16_t EVERY[4] = {0, 340, 240, 160};
+ if (!due(bot.next)) return false;
+ bot.next = now + EVERY[cpu] + rn(EVERY[cpu] / 2);
+ return true;
+}
static char *num(char *o, uint32_t v) { /* v in o, then the end of it */
char t[10];
@@ -157,26 +150,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;bot.y=120<<8;
+ hits = aim = 0;
bx = (160 - BS / 2) << 8, by = (70 + rn(100)) << 8, bvx = to ? 1 : -1, bvy = rn(9) - 4;
- serve_at = now + 900;
+ serve_at = now + 900, bot.y = 120 << 8;
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 */
+/* the computer's paddle (player 2): to where it sees the ball will come, off centre by its aim
+ and by how much it misjudges, slower than a player's */
static int pong_cpu(void) {
- 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;
+ static const uint8_t SPEED[4] = {0, 20, 30, 40}, MISS[4] = {0, 20, 12, 7};
+ static const int16_t SEES[4] = {0, 190, 145, 90}; /* where the ball must be before it looks */
+ if (bot_due()) {
+ int to = 120 << 8;
+ if (bvx > 0 && !serve_at && bx > SEES[cpu] << 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);
+ bot.y = (float)(to + (rn(2 * MISS[cpu] + 1) - MISS[cpu]) * 256);
}
- int delta=(int)bot.y-py[1]-(PH<<7);
- return clampi(delta/40,-SPEED[cpu],SPEED[cpu]);
+ return clampi(((int)bot.y - py[1] - (PH << 7)) / 40, -SPEED[cpu], SPEED[cpu]);
}
static void pong_step(void) {
for (int p = 0; p < 2; p++)
@@ -192,7 +185,10 @@ static void pong_step(void) {
bvx = p ? -s : s, bvy = SEG[clampi((y + BS - top) * 8 / (PH + BS), 0, 7)] * s / 10;
bx = (p ? PX[p] - BS : PX[p] + PW) << 8;
/* where the computer means to take the next one: off centre, by how much it misjudges */
- if (!p) aim = cpu == 3 ? (rn(2) ? 2816 : -2816) + rn(1536) - 768 : (rn(512) - 256) * (cpu == 1 ? 25 : 14);
+ if (!p) {
+ aim = rn(1536) - 768;
+ aim = cpu == 3 ? aim + (rn(2) ? 2816 : -2816) : aim / 3 * (cpu == 1 ? 25 : 14);
+ }
}
if (x < -BS - 10 || x > SCREEN_W + 10) {
point(x < 0);
@@ -210,6 +206,7 @@ static void pong_paint(void) {
gfx_fill(0, PTOP - 4, SCREEN_W, 4, WHITE);
gfx_fill(0, PBOT, SCREEN_W, 4, WHITE);
for (int y = PTOP + 4; y < PBOT; y += 16) gfx_fill(158, y, 4, 8, WHITE);
+ gfx_text_center(&np_font_small, 80, 227, T("Back pause"), HEX(0x6E6E6E), 256); /* (under the paddles and the ball) */
for (int p = 0; p < 2; p++) {
gfx_fill(PX[p], py[p] >> 8, PW, PH, WHITE);
for (int v = score[p], n = v > 9, d = n; d >= 0; d--, v /= 10)
@@ -234,8 +231,8 @@ 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 */
+ bot.x = RX1 - 40, bot.y = RYM;
}
/* the puck off something round at (x, y) moving at (vx, vy) */
static void knock(float x, float y, float vx, float vy, float r) {
@@ -246,26 +243,31 @@ static void knock(float x, float y, float vx, float vy, float r) {
float vn = (qvx - vx) * dx + (qvy - vy) * dy;
if (vn < 0) qvx -= 1.85f * vn * dx, qvy -= 1.85f * vn * dy;
}
-static void hockey_step(void) {
+/* the computer's mallet (player 2): behind the puck to shoot it at the other goal, or guarding
+ its own, where it saw them last; its speed (tx, ty) */
+static void hockey_cpu(float *tx, float *ty) {
static const float V[4] = {0, 90, 130, 175};
+ static const uint8_t MISS[4] = {0, 18, 11, 6};
+ if (bot_due()) {
+ float x = RX1 - 36, y = RYM + (qy - RYM) / 2;
+ if (qx > 160 - QR && !phase) {
+ float ax = RX0 - qx, ay = RYM + qaim - qy, l = len(ax, ay);
+ ax /= l, ay /= l;
+ x = qx - ax * (MR + QR + 3), y = qy - ay * (MR + QR + 3);
+ if (mx[1] < qx + 2) x = qx + MR + QR + 10, y = qy + (qy > RYM ? -28 : 28); /* in front of it: go round */
+ else if (len(x - mx[1], y - my[1]) < 7) x = qx + ax * 24, y = qy + ay * 24; /* strike */
+ if (x > RX1 - MR || y < RY0 + MR || y > RY1 - MR) x = qx, y = qy; /* it can't get behind it: at it */
+ }
+ bot.x = x, bot.y = y + (float)(rn(2 * MISS[cpu] + 1) - MISS[cpu]);
+ }
+ float x = bot.x - mx[1], y = bot.y - my[1], l = len(x, y) + 0.01f, v = V[cpu] * (l < 16 ? l / 16 : 1) / l;
+ *tx = x * v, *ty = y * v;
+}
+static void hockey_step(void) {
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);
- ax /= l, ay /= l;
- tx = qx - ax * (MR + QR + 3), ty = qy - ay * (MR + QR + 3);
- 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 */
- }
- 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 {
+ if (is_cpu(p)) hockey_cpu(&tx, &ty);
+ else {
int x = dirx(p), y = diry(p);
float s = x && y ? 175 : 245;
tx = x * s, ty = y * s;
@@ -277,6 +279,8 @@ static void hockey_step(void) {
if (phase) return;
for (int i = 0; i < ms; i++) {
qx += qvx / 1000, qy += qvy / 1000;
+ for (int k = 0; k < 4; k++) knock(k & 1 ? RX1 : RX0, k & 2 ? GY1 : GY0, 0, 0, 0); /* the goal posts */
+ for (int p = 0; p < 2; p++) knock(mx[p], my[p], mvx[p], mvy[p], MR);
/* the boards: back on their edge, and off them only when moving into them (a mallet can push the
puck into a board, and a slow puck flipped back and forth there stayed in it) */
if (qy < RY0 + QR) qy = RY0 + QR, qvy = qvy < 0 ? -qvy * 0.9f : qvy;
@@ -289,8 +293,10 @@ static void hockey_step(void) {
point(qx < 160);
return;
}
- for (int k = 0; k < 4; k++) knock(k & 1 ? RX1 : RX0, k & 2 ? GY1 : GY0, 0, 0, 0); /* the goal posts */
- for (int p = 0; p < 2; p++) knock(mx[p], my[p], mvx[p], mvy[p], MR);
+ for (int p = 0; p < 2; p++) { /* and a mallet pressing it into a corner gives way */
+ float dx = mx[p] - qx, dy = my[p] - qy, d = len(dx, dy) + .01f;
+ if (d < MR + QR) mx[p] = qx + dx / d * (MR + QR), my[p] = qy + dy / d * (MR + QR);
+ }
}
float s = len(qvx, qvy), f = 1 - 0.00035f * ms;
if (s * f > 560) f = 560 / s;
@@ -428,17 +434,17 @@ static bool shot_finds(int a, int b) {
}
return false;
}
-/* 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) */
+/* the computer's tank: a shot when it sees one, a little off, 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, 2300, 1700, 1200};
+ static const int16_t RELOAD[4] = {0, 2300, 1700, 1200}, LOOK[4] = {0, 700, 500, 350};
static const int8_t BOUNCES[4] = {0, 0, 0, 1};
int dir = ta[1] >> 8, want = dir;
- if (ago(ai_t) > (uint32_t)(cpu==1?700:cpu==2?500:350)) {
+ if (ago(ai_t) > (uint32_t)LOOK[cpu]) {
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 + rn(cpu==1?11:cpu==2?7:3) - (cpu==1?5:cpu==2?3:1)) & 63;
+ if (shot_finds(a, BOUNCES[cpu])) ai_aim = (a + rn(9 - 2 * cpu) - (4 - cpu)) & 63;
}
}
if (ai_aim >= 0) {
@@ -460,10 +466,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) * (cpu==1?45:cpu==2?55:64);
+ *v = clampi(6 - (((want - dir + 32) & 63) - 32) * (((want - dir + 32) & 63) - 32), 0, 1) * (36 + 9 * cpu);
}
int d = ((want - dir + 32) & 63) - 32;
- *turn = d > 0 ? 4+cpu : d < 0 ? -4-cpu : 0;
+ *turn = d > 0 ? 4 + cpu : d < 0 ? -4 - cpu : 0;
}
static void tanks_step(void) {
for (int p = 0; p < 2; p++) {
@@ -472,7 +478,7 @@ static void tanks_step(void) {
if (is_cpu(p)) tanks_cpu(&v, &turn);
else {
v = diry(p) < 0 ? 70 : diry(p) * -50, turn = dirx(p) * 8;
- if (tap[p] & B_FIRE) fire(p);
+ if (acted(p)) fire(p);
}
ta[p] = (ta[p] + turn * ms) & 0x3FFF; /* 8 a ms: half a turn a second */
int x = tx_[p], y = ty_[p], dx = cos64(ta[p] >> 8) * v * ms / 496, dy = sin64(ta[p] >> 8) * v * ms / 496;
@@ -573,18 +579,16 @@ static int room(int x, int y, int cap) {
}
return n;
}
-/* 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. */
+/* the computer's way, at a human's pace: the turn that leaves it the most room and the longest
+ way ahead, without guessing the player's next move */
static int cycles_cpu(void) {
- if(!bot_due())return hd[1];
static const int16_t CAP[4] = {0, 12, 70, 220};
+ if (!bot_due()) return hd[1];
int best = hd[1], bv = -(1 << 30);
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);
- int ahead=0;
- while(ahead<7&&free_at(x+ahead*DX[d],y+ahead*DY[d]))ahead++;
- v+=ahead*48;
+ int d = (hd[1] + t + (t == 2)) & 3, x = hx[1] + DX[d], y = hy[1] + DY[d], r = room(x, y, CAP[cpu]), a = 0;
+ while (a < 7 && free_at(x + a * DX[d], y + a * DY[d])) a++;
+ int v = r * 8 + a * 48 + (t ? 0 : 6) + rn(cpu == 1 ? 120 : 6);
if (!r) v = -(1 << 29);
if (v > bv) bv = v, best = d;
}
@@ -635,76 +639,92 @@ static void cycles_paint(void) {
}
}
-#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, S_SAVE_ERROR };
-static int screen, sel, back_to;
+/* ------------------------------------------------------------ the party games
+ Bobydeluxe's: short rounds, a key each. */
+static struct {
+ float rope; /* Tug of War: -100 (player 1's side) to 100 */
+ uint32_t t0, at, next; /* the round's start, the signal (Quick Draw), the computer's next press */
+} pg;
+static void party(void) { /* a new round */
+ pg.rope = 0, pg.t0 = now, pg.next = now + 600;
+}
+static uint32_t round_ms(void) { return now - pg.t0; }
+static void arena(uint32_t bg) {
+ gfx_fill(0, 22, SCREEN_W, SCREEN_H - 22, INK);
+ box(6, 28, 308, 206, 12, gfx_rgb(bg));
+}
+static void person(int x, int feet, int p) { /* a player seen from the side, its key under it */
+ disc(x, feet, 9, HEX(0x232944));
+ box(x - 7, feet - 19, 14, 17, 5, team[p]);
+ disc(x, feet - 25, 7, light[p]);
+ disc(x + (p ? -3 : 3), feet - 26, 1, INK);
+ if (!is_cpu(p)) gfx_text_center(&np_font_body, clampi(x, 30, 290), 222, p ? "EXE" : "OK", light[p], 256);
+}
-#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;
+/* Quick Draw: the first to press after the signal wins; before it, loses */
+static void quick_start(void) {
+ static const uint16_t REACT[4] = {0, 360, 280, 210};
+ party();
+ pg.at = now + 1500 + rn(2500);
+ if (cpu) pg.next = pg.at + REACT[cpu] + rn(REACT[cpu] / 2);
+}
+static void quick_step(void) {
+ if (phase) return;
+ if (cpu && due(pg.next)) tap[1] = B_FIRE;
+ int a = acted(0), b = acted(1);
+ if (a | b) point(a & b ? 2 : due(pg.at) ? b : a);
}
-static bool save(void) {
- uint8_t packed[SAVE_BYTES];save_encode(packed);
- return np_file_write(SAVE_NAME,packed,sizeof packed);
+static void quick_paint(void) {
+ bool go = due(pg.at);
+ arena(go ? 0x3A2F1C : 0x262D52);
+ for (int p = 0; p < 2; p++) person(80 + 160 * p, 196, p);
+ say(go ? &np_font_title : &np_font_body, 160, 130, go ? T("DRAW!") : T("Wait..."), go ? GOLD : WHITE);
}
-static void start_round(void) {
- memset(&bot,0,sizeof bot);bot.next=now+(cpu==1?750:cpu==2?600:450);START[game]();
+
+/* Tug of War: every tap pulls; the rope slides back to the middle a little */
+static void tug_step(void) {
+ static const uint16_t EVERY[4] = {0, 300, 200, 150};
+ if (phase) return;
+ if (cpu && due(pg.next)) tap[1] = B_FIRE, pg.next = now + EVERY[cpu] + rn(EVERY[cpu] / 5);
+ float r = pg.rope + (acted(1) - acted(0)) * 7.5f, d = 3 * dt;
+ pg.rope = r > d ? r - d : r < -d ? r + d : 0;
+ if (pg.rope < -67 || pg.rope > 67 || round_ms() > 30000) point(pg.rope < -1 ? 0 : pg.rope > 1 ? 1 : 2);
+}
+static void tug_paint(void) {
+ int x = 160 + (int)pg.rope;
+ char s[8], *e = num(s, round_ms() < 30000 ? (30999 - round_ms()) / 1000 : 0); /* the seconds left */
+ arena(0x262D52);
+ e[0] = 's', e[1] = 0;
+ say(&np_font_body, 160, 56, s, GOLD);
+ for (int p = 0; p < 2; p++) gfx_fill(p ? 227 : 91, 96, 2, 100, team[p]);
+ gfx_fill(x - 86, 150, 172, 4, HEX(0xC5CBE4));
+ for (int p = 0; p < 2; p++) person(x + (p ? 86 : -86), 186, p);
+ box(x - 6, 140, 12, 20, 3, GOLD);
}
-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 (*const START[NG])(void) = {pong_start, hockey_start, tanks_start, cycles_start, quick_start, party};
+static void (*const STEP_[NG])(void) = {pong_step, hockey_step, tanks_step, cycles_step, quick_step, tug_step};
+static void (*const PAINT[NG])(void) = {pong_paint, hockey_paint, tanks_paint, cycles_paint, quick_paint, tug_paint};
+
+/* ------------------------------------------------------------ screens */
+enum { S_MENU, S_RULES, S_PLAY, S_PAUSE, S_ASK, S_OVER };
+static int screen, sel, back_to, top; /* top: the first game the menu shows */
+static uint32_t shown; /* when the screen came (the clock's time) */
+
+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);
}
static void new_match(void) {
- score[0] = score[1] = 0, phase = 0, winner = 2, screen = S_PLAY;
- start_round();
+ score[0] = score[1] = 0, phase = 0, winner = 2, screen = S_PLAY, bot.next = now + 450;
+ START[game]();
}
-static void match_step(void) {
- if(cpu)pad[1]=tap[1]=0; /* EXE is a solo action alias, never an input to the bot. */
+static void play(void) { /* a frame of the match */
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();
- }
+ if (phase == 1 && ago(phase_t) > 1500) {
+ phase = 0;
+ if (score[0] < TARGET[game] && score[1] < TARGET[game]) bot.next = now + 450, START[game]();
+ else phase = 2, screen = S_OVER, sel = 0, sv.wins[game][cpu > 0][score[1] > score[0]]++, save();
}
}
static const char *opponent(void) {
@@ -720,7 +740,7 @@ static void tri(int x, int y, int d, color_t c) { /* a little arrow, pointing ri
}
}
/* The calculator's keyboard, the keys of this game in each player's colour: arrows on the keys
- that move, a dot on the one that fires. */
+ that move, a dot on the one that acts. */
static void keyboard(int x0, int y0) {
static const int8_t ARROW[4][2] = {{0, 9}, {13, 0}, {13, 18}, {26, 9}}, DIR[4] = {2, 3, 1, 0};
box(x0 - 4, y0 - 4, 132, 136, 10, HEX(0x0E1124));
@@ -734,8 +754,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 && (CONTROL[game] & (1<<i)) && !is_cpu(q))
- p = q, b = i;
+ if (KEYS[q][i] == k && KEYS_USED[game] >> i & 1 && !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);
else if (p >= 0) tri(x + w / 2, y + h / 2, DIR[b], WHITE);
@@ -746,11 +765,15 @@ static void button(int x, int y, int w, const char *s, bool on) {
box(x, y, w, 26, 13, on ? GOLD : HEX(0x3A4372));
gfx_text_center(&np_font_body, x + w / 2, y + 18, s, on ? INK : WHITE, 256);
}
-/* a card over the game: its title, then its buttons from by down. Over a game it is drawn in that game's
- 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) {
+static void keys_line(int y, const char *s) { say(&np_font_small, 160, y, s, HEX(0xD6DCF5)); }
+/* a card over the game: its title, then its buttons from by down, and its keys under it. Over
+ the first four games it is drawn in that game's 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 and the party games, in the menu's */
+static void card(int y, int h, const char *title, const char *const *items, int n, int by, const char *keys) {
gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 130);
- if (screen <= S_RULES || (screen == S_ASK && back_to == S_MENU) || game>=QUICK || screen==S_SAVE_ERROR) {
+ keys_line(232, keys);
+ if (screen <= S_RULES || (screen == S_ASK && back_to == S_MENU) || game > CYCLES) {
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);
@@ -758,7 +781,7 @@ static void card(int y, int h, const char *title, const char *const *items, int
return;
}
static const uint32_t LOOK[4][3] = {{0x000000, 0xFFFFFF, 0xFFFFFF}, {0xF4F6FA, 0x9AA3B8, 0x161A33},
- {0xE6E6EA, 0x3A3D4F, 0x3A3D4F}, {0x0B1230, 0x3E8BFF, 0xFFFFFF}};
+ {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);
gfx_fill(60, y, 200, h, bg);
@@ -775,80 +798,74 @@ static void card(int y, int h, const char *title, const char *const *items, int
}
}
-/* the little picture of each game in the menu: x, y, w, h, roundness, colour (red, blue, white) */
+/* the little picture of each game in the menu: x, y, w, h, roundness, colour (red, blue, white, gold) */
static const int8_t ICON[][6] = {
{4, 6, 3, 10, 0, 0}, {19, 10, 3, 10, 0, 1}, {12, 11, 3, 3, 0, 2}, /* Pong */
{3, 8, 10, 10, 5, 0}, {14, 6, 10, 10, 5, 1}, {10, 16, 6, 6, 3, 2}, /* Air Hockey */
{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 */
+ {3, 8, 10, 10, 5, 0}, {13, 8, 10, 10, 5, 1}, {11, 5, 4, 16, 2, 3}, /* Quick Draw */
+ {3, 12, 20, 3, 0, 2}, {11, 8, 5, 11, 2, 3}, /* Tug of War */
};
-static const uint8_t ICON_AT[5] = {0, 3, 6, 7, 11};
+static const uint8_t ICON_AT[NG + 1] = {0, 3, 6, 7, 11, 14, 16};
static void icon(int g, int x, int y) {
- const color_t C[3] = {team[0], team[1], WHITE};
+ const color_t C[4] = {team[0], team[1], WHITE, GOLD};
box(x, y, 26, 26, 6, INK);
- 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);
+ 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]]);
}
+#define ROWS 5 /* the games the menu shows at once */
static void scene(void *ctx) {
- char s[48];
+ char s[24];
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);
- 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 i = 0; i < ROWS; i++) {
+ int g = top + i, y = 38 + 33 * i, on = g == game;
+ gfx_rrect(24, y, 272, 30, 10, on ? WHITE : INK, on ? 256 : 170);
+ icon(g, 26, y + 2);
+ gfx_text(&np_font_body, 62, y + 20, NAME[g], on ? INK : WHITE, 256);
for (int p = 0; p < 2; p++) { /* the matches each side has won */
- 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);
+ num(s, sv.wins[g][cpu > 0][p]);
+ gfx_text_center(&np_font_body, 248 + 30 * p, y + 20, s, team[p], 256);
}
- gfx_text_center(&np_font_body, 263, y + 21, "-", on ? INK : WHITE, 256);
+ gfx_text_center(&np_font_body, 263, y + 20, "-", on ? INK : WHITE, 256);
}
+ if (top) tri(306, 44, 3, WHITE); /* more above, more below */
+ if (top < NG - ROWS) tri(306, 194, 1, WHITE);
+ keys_line(207, T("OK play Back quit"));
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) {
+ static const char *const KEY[2][5] = {{"", "", "", "", "OK"}, {"3", "x", "Ans", "-", "EXE"}};
gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 140);
- box(8, 8, 304, 224, 14, HEX(0x262D52));
+ box(8, 8, 304, 232, 14, HEX(0x262D52));
say(&np_font_title, 160, 34, NAME[game], WHITE);
- gfx_paragraph(&np_font_small, 160, 52, 284, 11, RULES[game], HEX(0xD6DCF5), 256);
+ gfx_paragraph(&np_font_small, 160, 54, 284, 12, RULES[game], HEX(0xD6DCF5), 256);
+ keyboard(26, 100);
+ for (int p = 0; p < 2; p++) { /* who plays, and with which keys */
+ int y = 100 + 36 * p, u = KEYS_USED[game], x = 188;
+ box(166, y, 14, 14, 4, team[p]);
+ gfx_text(&np_font_body, 188, y + 12, p ? opponent() : who(0), WHITE, 256);
+ if (!p && u & 15) x = gfx_text(&np_font_small, x, y + 27, T("arrows"), light[p], 256) + 6;
+ for (int i = 0; i < 5; i++)
+ if (u >> i & 1 && !is_cpu(p)) x = gfx_text(&np_font_small, x, y + 27, KEY[p][i], i < 4 ? light[p] : GOLD, 256) + 6;
+ }
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);
- }
- button(166, 196, 130, T("Play"), true);
+ gfx_text_center(&np_font_body, 231, 182, s, GOLD, 256);
+ button(166, 190, 130, T("Play"), true);
+ say(&np_font_small, 231, 233, T("Back games"), HEX(0xD6DCF5));
}
} else {
PAINT[game]();
- if (game != PONG) { /* the score bar: each side's name and points */
+ if (game != PONG) { /* the score bar: each side's name and points, and the pause key */
gfx_fill(0, 0, SCREEN_W, 22, INK);
for (int p = 0; p < 2; p++) {
box(p ? 214 : 4, 3, 102, 17, 8, team[p]);
@@ -857,6 +874,7 @@ static void scene(void *ctx) {
gfx_text_right(&np_font_body, p ? 308 : 98, 16, s, WHITE, 256);
}
}
+ if (game) gfx_text_center(&np_font_small, 160, 15, T("Back pause"), HEX(0xD6DCF5), 256);
if (phase == 1 && screen == S_PLAY) {
int t = (int)ago(phase_t), y = 120 - (t < 200 ? (200 - t) / 10 : 0);
gfx_rrect(70, y - 26, 180, 62, 14, INK, 200);
@@ -865,11 +883,11 @@ static void scene(void *ctx) {
}
if (screen == S_PAUSE) {
static const char *const ITEM[4] = {T("Resume"), T("Restart"), T("Other games"), T("Quit game")};
- card(40, 172, T("Paused"), ITEM, 4, 82);
+ card(40, 172, T("Paused"), ITEM, 4, 82, T("OK choose Back resume"));
} else if (screen == S_OVER) {
static const char *const WON[2][2] = {{T("Player 1 wins!"), T("Player 2 wins!")}, {T("You win!"), T("The computer wins")}};
static const char *const ITEM[2] = {T("Rematch"), T("Other games")};
- card(46, 158, WON[cpu > 0][score[1] > score[0]], ITEM, 2, 140);
+ card(46, 158, WON[cpu > 0][score[1] > score[0]], ITEM, 2, 140, T("OK choose Back games"));
for (int p = 0; p < 2; p++) {
num(s, (uint32_t)score[p]);
say(&np_font_title, 124 + 72 * p, 118, s, light[p]);
@@ -879,86 +897,81 @@ 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);
+ card(60, 120, T("Quit game?"), ITEM, 2, 104, T("OK choose Back no"));
}
}
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,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){
+ 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 >= 4 && n <= sizeof sv && d[0] == 'P' && d[1] == 1) /* (a save with fewer games: the first ones) */
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&sv)[i] = d[i];
+ game = sv.game % NG, cpu = sv.cpu & 3;
+ top = clampi(game - 2, 0, NG - ROWS);
+ 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, dt = ms * .001f;
+ if (screen == S_PLAY) now += (uint32_t)ms;
+ uint64_t k = eadk_keyboard_scan();
+ if (cpu) k |= (uint64_t)down(k, eadk_key_exe) << eadk_key_ok; /* alone, EXE is OK: one key, either */
+ 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) pad[1] = tap[1] = 0; /* (player 2's keys are the computer's) */
+ int dx = down(hit, eadk_key_right) - down(hit, eadk_key_left), dy = down(hit, eadk_key_down) - down(hit, eadk_key_up);
+ int was = screen;
+ switch (screen) {
case S_MENU:
case S_RULES:
- 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;}
+ 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, top = clampi(top, game - ROWS + 1, game);
+ } 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;}
- /* 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;
+ if (back) {
+ screen = S_PAUSE, sel = 0;
+ break;
}
+ play();
break;
- 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;}
+ default: /* the cards: Paused, the match over, Quit game? */
+ sel = (sel + dy) & (screen == S_PAUSE ? 3 : 1);
+ if (screen == S_OVER && t - shown < 700) break; /* (a key still being mashed doesn't choose) */
+ if (screen == S_ASK) {
+ if (back || (ok && !sel)) screen = back_to;
+ else quit = ok;
+ } else if (back) {
+ screen = screen == S_PAUSE ? S_PLAY : S_MENU;
+ } 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;
}
- 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_timing_msleep(2);
+ if (screen != was) shown = t;
+ eadk_display_wait_for_vblank();
+ gfx_render(scene, 0, 0, SCREEN_H);
}
- gfx_buf=their_strip;
+ save();
+ gfx_buf = their_strip;
return np_app_end();
}
diff --git a/games/twoplayer/src/party.h b/games/twoplayer/src/party.h
deleted file mode 100644
index c917cb4e..00000000
--- a/games/twoplayer/src/party.h
+++ /dev/null
@@ -1,492 +0,0 @@
-/* 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
deleted file mode 100644
index c36bc437..00000000
--- a/games/twoplayer/tests/eadk.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/* 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/play.c b/games/twoplayer/tests/play.c
new file mode 100644
index 00000000..8eef5914
--- /dev/null
+++ b/games/twoplayer/tests/play.c
@@ -0,0 +1,408 @@
+/* 2 Players on a computer, for tests and pictures (make host, make test).
+ *
+ * play test the rules of every game; bots against bots: player 1 played by the computer's
+ * own mind (at a player's speed) against the computer, at every level, and a
+ * quick or slow player in Quick Draw and Tug of War; random sessions through the
+ * menus and the games, quitting and opening again, that never break a rule; the
+ * old saves (four games) come back with their tallies, damaged ones reset
+ * play shot DIR pictures (DIR/NAME.ppm): the menu, each game's page, each game, the cards
+ *
+ * Built with -ffp-contract=off, and the game uses no libc randomness, sorting or unordered
+ * arguments: the same results on any computer. */
+#define NP_MODULE 1
+#define main tp_main
+#include "../src/main.c"
+#undef main
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static uint16_t fb[SCREEN_H][SCREEN_W];
+static uint8_t disk[1024];
+static uint32_t disk_len;
+static int writes, fails, unfinished;
+void np_push(int x, int y, int w, int h, const color_t *p) {
+ for (int j = 0; j < h; j++)
+ for (int i = 0; i < w; i++) fb[y + j][x + i] = p[j * w + i];
+}
+void *np_alloc(uint32_t size) { return malloc(size); }
+const uint8_t *np_file_read(const char *name, uint32_t *len) {
+ *len = disk_len;
+ return disk_len ? disk : 0;
+}
+bool np_file_write(const char *name, const void *d, uint32_t len) {
+ if (strcmp(name, "twoplayer.sav") || len > sizeof disk) return false;
+ memcpy(disk, d, disk_len = len), writes++;
+ return true;
+}
+#define CHECK(c, ...) do { if (!(c)) { printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); fails++; } } while (0)
+
+/* ---------------------------------------------------------------- whole sessions, scripted */
+static uint32_t clock_ms, frames, fseed = 1;
+static int session_frames;
+static uint64_t (*script)(uint32_t frame);
+static uint32_t frnd(void) { return fseed = fseed * 1664525u + 1013904223u; }
+static uint64_t K(int k) { return (uint64_t)1 << k; }
+static uint64_t no_keys(uint32_t f) { return 0; }
+uint64_t eadk_keyboard_scan(void) {
+ clock_ms += 15 + frnd() % 30, frames++;
+ if (session_frames && frames >= (uint32_t)session_frames) return K(eadk_key_home);
+ if (script) return script(frames);
+ /* mostly play keys, sometimes the menus' and Back */
+ static const uint8_t KEY[] = {eadk_key_left, eadk_key_up, eadk_key_down, eadk_key_right, eadk_key_ok, eadk_key_exe,
+ eadk_key_three, eadk_key_multiplication, eadk_key_ans, eadk_key_minus, eadk_key_back};
+ uint64_t k = 0;
+ for (int i = 0; i < 3; i++) {
+ uint32_t a = frnd(), b = frnd(), c = frnd(); /* (one at a time: the same order on any compiler) */
+ if (a % 3 == 0) k |= K(KEY[b % (sizeof KEY - (c % 8 ? 1 : 0))]);
+ }
+ return k;
+}
+uint64_t eadk_timing_millis(void) { return clock_ms; }
+uint32_t eadk_random(void) { return frnd(); }
+bool eadk_display_wait_for_vblank(void) { return true; }
+void eadk_timing_msleep(uint32_t ms) { (void)ms; }
+
+/* the game's state is sane */
+static void sane(const char *where) {
+ CHECK(game >= 0 && game < NG && cpu >= 0 && cpu <= 3, "%s: game %d cpu %d", where, game, cpu);
+ CHECK(score[0] >= 0 && score[1] >= 0 && score[0] <= TARGET[game] && score[1] <= TARGET[game], "%s: score %d-%d in %d", where,
+ score[0], score[1], game);
+ CHECK(screen >= S_MENU && screen <= S_OVER && top >= 0 && top <= NG - ROWS && game >= top && game < top + ROWS, "%s: screen %d top %d",
+ where, screen, top);
+ CHECK(pg.rope >= -75 && pg.rope <= 75, "%s: rope %f", where, (double)pg.rope);
+}
+static void reset_all(void) { /* as a fresh start of the app */
+ memset(&sv, 0, sizeof sv), memset(&pg, 0, sizeof pg), memset(&bot, 0, sizeof bot);
+ screen = sel = back_to = top = game = cpu = 0, now = 0, phase = 0, score[0] = score[1] = 0;
+}
+
+/* ---------------------------------------------------------------- matches, frame by frame */
+static void begin(int g, int level, uint32_t s) {
+ reset_all();
+ game = g, cpu = level, seed = s ? s : 1, now = 1000, ms = 20, dt = ms * .001f, top = clampi(g - 2, 0, NG - ROWS);
+ new_match();
+}
+static void frame(int p1pad, int p1tap, int p2pad, int p2tap) { /* as main's loop in a match */
+ ms = 20, dt = .02f, now += 20;
+ pad[0] = p1pad, tap[0] = p1tap, pad[1] = p2pad, tap[1] = p2tap;
+ if (cpu) pad[1] = tap[1] = 0;
+ play();
+}
+
+/* Player 1 played by the computer's own mind at a level, at a player's speed: the court mirrored
+ so player 1 is player 2, the computer's thinking (with its own memory) run, its keys read. */
+static __typeof__(bot) mind;
+static int ai_aim1;
+static uint32_t ai_t1, ai_shot1;
+#define SWAP(a, b) do { __typeof__(a) t_ = a; a = b; b = t_; } while (0)
+static void think(int level, int *p, int *t) {
+ int keep = cpu;
+ __typeof__(bot) b = bot;
+ memcpy(&bot, &mind, sizeof bot), cpu = level, *p = *t = 0;
+ if (game == PONG) {
+ int y = py[1], x = bx, vx = bvx, a = aim; /* (a player aims at the middle) */
+ py[1] = py[0], bx = ((SCREEN_W - BS) << 8) - bx, bvx = -bvx, aim = 0;
+ int v = pong_cpu();
+ py[1] = y, bx = x, bvx = vx, aim = a;
+ *p = v > 3 ? B_DOWN : v < -3 ? B_UP : 0;
+ } else if (game == HOCKEY) {
+ float s[8] = {mx[0], my[0], mvx[0], mvy[0], mx[1], my[1], mvx[1], mvy[1]}, q[2] = {qx, qvx}, tx, ty;
+ mx[1] = SCREEN_W - s[0], my[1] = s[1], mvx[1] = -s[2], mvy[1] = s[3];
+ mx[0] = SCREEN_W - s[4], my[0] = s[5], mvx[0] = -s[6], mvy[0] = s[7], qx = SCREEN_W - qx, qvx = -qvx;
+ hockey_cpu(&tx, &ty);
+ mx[0] = s[0], my[0] = s[1], mvx[0] = s[2], mvy[0] = s[3], mx[1] = s[4], my[1] = s[5], mvx[1] = s[6], mvy[1] = s[7];
+ qx = q[0], qvx = q[1], tx = -tx;
+ *p = (tx > 40 ? B_RIGHT : tx < -40 ? B_LEFT : 0) | (ty > 40 ? B_DOWN : ty < -40 ? B_UP : 0);
+ } else if (game == TANKS) {
+ int v, turn;
+ SWAP(tx_[0], tx_[1]); SWAP(ty_[0], ty_[1]); SWAP(ta[0], ta[1]); SWAP(dead[0], dead[1]); SWAP(dead_t[0], dead_t[1]);
+ SWAP(ai_aim, ai_aim1); SWAP(ai_t, ai_t1); SWAP(ai_shot, ai_shot1);
+ for (int i = 0; i < SHELLS; i++) sh[i].own = sh[i].own < 0 ? -1 : 1 - sh[i].own;
+ tanks_cpu(&v, &turn);
+ SWAP(tx_[0], tx_[1]); SWAP(ty_[0], ty_[1]); SWAP(ta[0], ta[1]); SWAP(dead[0], dead[1]); SWAP(dead_t[0], dead_t[1]);
+ SWAP(ai_aim, ai_aim1); SWAP(ai_t, ai_t1); SWAP(ai_shot, ai_shot1);
+ for (int i = 0; i < SHELLS; i++) sh[i].own = sh[i].own < 0 ? -1 : 1 - sh[i].own;
+ *p = (v > 0 ? B_UP : 0) | (turn > 0 ? B_RIGHT : turn < 0 ? B_LEFT : 0);
+ } else if (game == CYCLES) {
+ static const uint8_t BIT[4] = {B_RIGHT, B_DOWN, B_LEFT, B_UP};
+ uint32_t next = bot.next;
+ SWAP(hx[0], hx[1]); SWAP(hy[0], hy[1]); SWAP(hd[0], hd[1]);
+ int d = cycles_cpu();
+ SWAP(hx[0], hx[1]); SWAP(hy[0], hy[1]); SWAP(hd[0], hd[1]);
+ int last = nturns[0] ? turns[0][nturns[0] - 1] : hd[0];
+ if (bot.next != next && d != last) *t = BIT[d]; /* (a turn when it decided one) */
+ }
+ memcpy(&mind, &bot, sizeof bot), bot = b, cpu = keep;
+}
+/* a match of player 1 (a mind at level l1, or for Quick Draw and Tug of War a player who reacts
+ in r ms, or taps every r ms) against the computer at l2; who won */
+static int match(int g, int l1, int r, int l2, uint32_t s) {
+ begin(g, l2, s);
+ memset(&mind, 0, sizeof mind), ai_aim1 = -1, ai_t1 = ai_shot1 = now;
+ uint32_t last_tap = 0;
+ for (int f = 0; f < 60000 && screen == S_PLAY; f++) { /* (20 minutes: two minds can pin the puck forever) */
+ int p = 0, t = 0;
+ if (g == QUICK) t = !phase && due(pg.at + r) ? B_FIRE : 0;
+ else if (g == TUG) {
+ if (!phase && now - last_tap >= (uint32_t)r) t = B_FIRE, last_tap = now;
+ } else think(l1, &p, &t);
+ frame(p | t, t, 0, 0);
+ sane("match");
+ }
+ if (screen != S_OVER) unfinished++, printf("unfinished: game %d %d-%d screen %d\n", g, score[0], score[1], screen);
+ return score[1] >= score[0];
+}
+
+/* ---------------------------------------------------------------- the rules */
+static void rules(void) {
+ /* Quick Draw: too soon loses, after the signal the first wins, together a draw */
+ begin(QUICK, 0, 7);
+ frame(B_FIRE, B_FIRE, 0, 0);
+ CHECK(phase == 1 && winner == 1 && score[1] == 1, "quick: too soon %d %d", phase, winner);
+ begin(QUICK, 0, 7), now = pg.at - 20;
+ frame(0, 0, B_FIRE, B_FIRE);
+ CHECK(winner == 1, "quick: player 2 first %d", winner);
+ begin(QUICK, 0, 7), now = pg.at - 20;
+ frame(B_FIRE, B_FIRE, B_FIRE, B_FIRE);
+ CHECK(winner == 2 && !score[0] && !score[1], "quick: together %d", winner);
+ begin(QUICK, 0, 7), now = pg.at - 25;
+ frame(0, 0, 0, 0);
+ CHECK(!phase, "quick: nothing yet");
+ begin(QUICK, 3, 7); /* the computer's keys are its own */
+ int f = 0;
+ while (!phase && f++ < 1000) frame(0, 0, B_FIRE, B_FIRE);
+ CHECK(winner == 1 && now >= pg.next, "quick: the computer drew at %u (%u)", now, pg.next);
+ /* Tug of War: a tap pulls 7.5, the rope slides back 3 a second, past 67 wins, 30 s ends it */
+ begin(TUG, 0, 7);
+ frame(B_FIRE, B_FIRE, 0, 0);
+ CHECK(pg.rope < -7.4f && pg.rope > -7.5f, "tug: one tap %f", (double)pg.rope);
+ frame(B_FIRE, B_FIRE, B_FIRE, B_FIRE);
+ CHECK(pg.rope < -7.3f && pg.rope > -7.5f, "tug: together %f", (double)pg.rope);
+ for (int i = 0; i < 50; i++) frame(0, 0, 0, 0);
+ CHECK(pg.rope < -4.3f && pg.rope > -4.5f, "tug: slides back %f", (double)pg.rope);
+ frame(B_FIRE, 0, 0, 0);
+ CHECK(pg.rope > -4.5f, "tug: holding doesn't pull");
+ for (int i = 0; i < 9 && !phase; i++) frame(B_FIRE, B_FIRE, 0, 0), frame(0, 0, 0, 0);
+ CHECK(phase == 1 && winner == 0, "tug: player 1 pulls it over %d %f", phase, (double)pg.rope);
+ begin(TUG, 0, 7);
+ frame(0, 0, B_FIRE, B_FIRE);
+ while (!phase) frame(0, 0, 0, 0);
+ CHECK(winner == 2 && round_ms() > 30000, "tug: time up, the rope back in the middle: a draw %d", winner);
+ begin(TUG, 0, 7);
+ while (!phase) frame(0, 0, 0, 0), frame(0, 0, B_FIRE, B_FIRE);
+ CHECK(winner == 1, "tug: player 2 wins");
+ /* a match: first to its points, the tally kept */
+ begin(TUG, 0, 7);
+ sv.wins[TUG][0][1] = 41;
+ for (int r = 0; r < 5; r++) {
+ while (!phase) frame(0, 0, 0, 0), frame(0, 0, B_FIRE, B_FIRE);
+ for (int i = 0; i < 80 && phase; i++) frame(0, 0, 0, 0);
+ }
+ CHECK(screen == S_OVER && score[1] == 5 && sv.wins[TUG][0][1] == 42, "tug: the match %d %d %d", screen, score[1], sv.wins[TUG][0][1]);
+ /* Pong: a ball past a paddle is the other's point; the serve goes to the one who lost it */
+ begin(PONG, 0, 7);
+ bx = 2 << 8, bvx = -40, serve_at = 0, by = 120 << 8, bvy = 0, py[0] = 20 << 8;
+ for (int i = 0; i < 20 && !phase; i++) frame(0, 0, 0, 0);
+ CHECK(phase == 1 && winner == 1, "pong: past player 1");
+ for (int i = 0; i < 80 && phase; i++) frame(0, 0, 0, 0);
+ CHECK(!phase && bvx < 0, "pong: served to player 1");
+ /* Light Cycles: into a wall */
+ begin(CYCLES, 0, 7);
+ for (int i = 0; i < 400 && !phase; i++) frame(0, 0, 0, 0);
+ CHECK(phase == 1 && winner == 2, "cycles: both into the walls together %d", winner);
+}
+
+/* ---------------------------------------------------------------- saves */
+static void saves(void) {
+ /* version 1, four games: its tallies, game and opponent come back, the new games at 0 */
+ uint8_t v1[36] = {'P', 1, 3, 2};
+ for (int i = 0; i < 16; i++) v1[4 + 2 * i] = (uint8_t)(10 + i), v1[5 + 2 * i] = (uint8_t)i;
+ reset_all(), memcpy(disk, v1, disk_len = 36), writes = 0;
+ session_frames = 3, frames = 0, script = no_keys, tp_main(), session_frames = 0;
+ CHECK(game == CYCLES && cpu == 2, "v1: game %d cpu %d", game, cpu);
+ for (int g = 0; g < NG; g++)
+ for (int i = 0; i < 4; i++) {
+ int want = g < 4 ? (10 + g * 4 + i) | (g * 4 + i) << 8 : 0;
+ CHECK(sv.wins[g][i / 2][i % 2] == want, "v1: game %d tally %d: %d", g, i, sv.wins[g][i / 2][i % 2]);
+ }
+ CHECK(writes && disk_len == sizeof sv && disk[0] == 'P' && disk[1] == 1 && !memcmp(disk + 4, v1 + 4, 32), "v1: saved again, the same");
+ /* the new length comes back as it is */
+ uint8_t full[sizeof sv];
+ memcpy(full, disk, sizeof full);
+ reset_all(), session_frames = 3, frames = 0, tp_main(), session_frames = 0;
+ CHECK(!memcmp(disk, full, sizeof full), "a save comes back the same");
+ /* damaged ones: another magic, a later version, too long: a fresh start */
+ for (int k = 0; k < 3; k++) {
+ memcpy(disk, full, disk_len = sizeof full);
+ if (k == 0) disk[0] = 'Q';
+ if (k == 1) disk[1] = 2;
+ if (k == 2) disk_len = sizeof full + 2;
+ reset_all(), sv.wins[0][0][0] = 0, session_frames = 3, frames = 0, tp_main(), session_frames = 0;
+ CHECK(sv.wins[0][0][0] == 0 && sv.wins[1][0][0] == 0, "damaged save %d read", k);
+ }
+ disk_len = 0, script = 0;
+}
+
+/* ---------------------------------------------------------------- random sessions */
+static void sessions(int n) {
+ disk_len = 0;
+ for (int s = 0; s < n; s++) {
+ reset_all();
+ session_frames = 300 + (int)(frnd() % 1500), frames = 0, script = 0;
+ tp_main();
+ sane("session");
+ CHECK(disk_len == sizeof sv && disk[0] == 'P', "session %d: saved", s);
+ }
+ session_frames = 0;
+}
+
+/* Back pauses, Quit game asks first, Home saves and quits */
+static uint64_t walk_script(uint32_t f) {
+ /* OK (its page), OK (play), Back (pause), down x3 (Quit game), OK, OK (No), Back (play), Back (pause), down x3, OK,
+ down (Yes), OK: out */
+ static const uint8_t STEPS[] = {eadk_key_ok, eadk_key_ok, eadk_key_back, eadk_key_down, eadk_key_down, eadk_key_down,
+ eadk_key_ok, eadk_key_ok, eadk_key_back, eadk_key_back, eadk_key_down, eadk_key_down,
+ eadk_key_down, eadk_key_ok, eadk_key_down, eadk_key_ok};
+ static const uint8_t SCREEN[] = {S_MENU, S_RULES, S_PLAY, S_PAUSE, S_PAUSE, S_PAUSE, S_PAUSE, S_ASK, S_PAUSE, S_PLAY,
+ S_PAUSE, S_PAUSE, S_PAUSE, S_PAUSE, S_ASK, S_ASK};
+ if (f % 4 || f / 4 < 1 || f / 4 > sizeof STEPS) return 0;
+ CHECK(screen == SCREEN[f / 4 - 1], "keys: step %u on screen %d", f / 4, screen);
+ return K(STEPS[f / 4 - 1]);
+}
+/* Tug of War against the computer: down to it, the computer, OK, OK, then OK mashed; once the match is
+ over, mashing on doesn't pick Rematch (for 600 ms) */
+static uint32_t over_at;
+static uint64_t mash_script(uint32_t f) {
+ if (f < 30) return f % 2 ? 0 : K(f < 12 ? eadk_key_down : f < 14 ? eadk_key_right : eadk_key_ok);
+ if (screen == S_OVER && !over_at) over_at = clock_ms;
+ if (over_at && clock_ms - over_at > 600) {
+ CHECK(screen == S_OVER, "a mashed key picked from the end card");
+ return K(eadk_key_home);
+ }
+ return f % 2 ? K(eadk_key_ok) : 0;
+}
+/* alone, EXE is OK: Tug of War against the computer, OK and EXE pressed in turn, one always held: a single pull */
+static float rope_was;
+static int pulls;
+static uint64_t both_script(uint32_t f) {
+ if (f < 30) return f % 2 ? 0 : K(f < 12 ? eadk_key_down : f < 14 ? eadk_key_right : f < 18 ? eadk_key_exe : 0);
+ if (f == 30) CHECK(screen == S_PLAY && game == TUG && cpu == 1 && round_ms() < 600, "exe: in the match %d %d", screen, game);
+ pulls += pg.rope < rope_was - 5, rope_was = pg.rope;
+ if (f < 90) return f % 4 == 0 ? K(eadk_key_ok) : f % 4 == 2 ? K(eadk_key_exe) : K(eadk_key_ok) | K(eadk_key_exe);
+ CHECK(pulls == 1, "exe: %d pulls", pulls);
+ return K(eadk_key_home);
+}
+static void keys(void) {
+ reset_all(), frames = 0, script = both_script, pulls = 0, rope_was = 0;
+ tp_main();
+ reset_all(), disk_len = 0, frames = 0, script = walk_script, session_frames = 0;
+ tp_main();
+ CHECK(frames == 64 && disk_len == sizeof sv, "quit game asks first, then quits and saves (frame %u)", frames);
+ reset_all(), frames = 0, script = mash_script, over_at = 0;
+ tp_main();
+ CHECK(over_at && game == TUG && cpu == 1, "tug: over %u game %d cpu %d", over_at, game, cpu);
+ script = 0;
+}
+
+/* ---------------------------------------------------------------- bots against bots */
+static void bots(void) {
+ static const char *const GAME[] = {"Pong", "Air Hockey", "Tanks", "Light Cycles"};
+ int n = 12;
+ for (int g = PONG; g <= CYCLES; g++) {
+ printf("%-12s player 1 at easy/normal/hard against the computer at easy/normal/hard, of %d:\n", GAME[g], n);
+ int won[4][4] = {{0}};
+ for (int l1 = 1; l1 <= 3; l1++) {
+ printf(" ");
+ for (int l2 = 1; l2 <= 3; l2++) {
+ for (int i = 0; i < n; i++) won[l1][l2] += !match(g, l1, 0, l2, 1000u * g + 100u * l1 + 10u * l2 + i);
+ printf(" %2d", won[l1][l2]);
+ }
+ printf("\n");
+ }
+ /* the levels: a harder computer wins more; a good player beats easy, and can beat hard; hard beats a
+ weak player */
+ CHECK(won[2][1] >= won[2][3] && won[3][1] > n / 2 && won[3][3] > 0 && won[1][3] < n, "%s: the levels", GAME[g]);
+ }
+ /* Quick Draw: a quick player (250 ms) and a slow one (400 ms); Tug of War: 7 and 5 taps a second */
+ int quick[4][2] = {{0}}, tug[4][2] = {{0}};
+ for (int l2 = 1; l2 <= 3; l2++)
+ for (int i = 0; i < n; i++) {
+ quick[l2][0] += !match(QUICK, 0, 250, l2, 50u + 10u * l2 + i), quick[l2][1] += !match(QUICK, 0, 400, l2, 90u + 10u * l2 + i);
+ tug[l2][0] += !match(TUG, 0, 143, l2, 50u + 10u * l2 + i), tug[l2][1] += !match(TUG, 0, 200, l2, 90u + 10u * l2 + i);
+ }
+ printf("Quick Draw a 250 ms / 400 ms player against easy, normal, hard, of %d: %d/%d %d/%d %d/%d\n", n, quick[1][0], quick[1][1],
+ quick[2][0], quick[2][1], quick[3][0], quick[3][1]);
+ printf("Tug of War 7 / 5 taps a second against easy, normal, hard, of %d: %d/%d %d/%d %d/%d\n", n, tug[1][0], tug[1][1], tug[2][0],
+ tug[2][1], tug[3][0], tug[3][1]);
+ printf("unfinished (the puck pinned by two minds): %d\n", unfinished);
+ CHECK(unfinished <= 4, "unfinished matches");
+ CHECK(quick[1][1] > n / 2 && quick[3][0] > 0 && quick[3][1] < n, "quick draw: levels");
+ CHECK(tug[1][1] > n / 2 && tug[3][0] > 0 && tug[3][1] < n, "tug of war: levels");
+}
+
+/* ---------------------------------------------------------------- pictures */
+static void shot(const char *dir, const char *name) {
+ char path[256];
+ snprintf(path, sizeof path, "%s/%s.ppm", dir, name);
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ gfx_render(scene, 0, 0, SCREEN_H);
+ for (int y = 0; y < SCREEN_H; y++)
+ for (int x = 0; x < SCREEN_W; x++) {
+ unsigned c = fb[y][x];
+ unsigned char p[3] = {(unsigned char)((c >> 11) * 255 / 31), (unsigned char)((c >> 5 & 63) * 255 / 63), (unsigned char)((c & 31) * 255 / 31)};
+ fwrite(p, 1, 3, f);
+ }
+ fclose(f);
+}
+static void shots(const char *dir) {
+ char name[32];
+ reset_all();
+ sv.wins[QUICK][1][0] = 3, sv.wins[QUICK][1][1] = 1, sv.wins[PONG][1][0] = 2, sv.wins[TUG][1][1] = 1;
+ static const uint16_t AT[NG] = {170, 120, 400, 160, 20, 90}; /* (frames into a round: the README's pictures) */
+ for (int g = 0; g < NG; g++) {
+ begin(g, 3, 11u + g);
+ memset(&mind, 0, sizeof mind), ai_aim1 = -1, ai_t1 = ai_shot1 = now;
+ for (int i = 0; i < AT[g] && screen == S_PLAY; i++) {
+ int p = 0, t = 0;
+ if (g <= CYCLES) think(3, &p, &t);
+ else if (g == TUG) t = i % 6 == 0 ? B_FIRE : 0;
+ frame(p | t, t, 0, 0);
+ }
+ if (g == QUICK) now = pg.at + 150; /* (the signal) */
+ snprintf(name, sizeof name, "game_%02d", g), shot(dir, name);
+ screen = S_RULES, top = clampi(top, g - ROWS + 1, g), shot(dir, (snprintf(name, sizeof name, "rules_%02d", g), name));
+ if (g == 0 || g == QUICK) screen = S_MENU, shot(dir, (snprintf(name, sizeof name, "menu_%02d", g), name));
+ }
+ begin(PONG, 0, 3), shot(dir, "pong_2p");
+ begin(TUG, 0, 3), screen = S_RULES, shot(dir, "rules_tug_2p");
+ begin(HOCKEY, 1, 5);
+ for (int i = 0; i < 60; i++) frame(0, 0, 0, 0);
+ screen = S_PAUSE, sel = 1, shot(dir, "pause_hockey");
+ begin(TUG, 1, 5), screen = S_PAUSE, shot(dir, "pause_tug");
+ score[0] = 5, score[1] = 3, screen = S_OVER, sel = 0, shot(dir, "over_tug");
+ screen = S_ASK, back_to = S_PAUSE, sel = 0, shot(dir, "ask_tug");
+ begin(TUG, 1, 5);
+ for (int i = 0; i < 100; i++) frame(i % 6 ? 0 : B_FIRE, i % 6 ? 0 : B_FIRE, 0, 0);
+ point(0), now += 300, shot(dir, "point_tug");
+}
+
+int main(int argc, char **argv) {
+ 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));
+ if (argc > 2 && !strcmp(argv[1], "shot")) {
+ shots(argv[2]);
+ return 0;
+ }
+ rules();
+ saves();
+ keys();
+ sessions(argc > 2 ? atoi(argv[2]) : 300);
+ bots();
+ printf(fails ? "%d FAILED\n" : "all passed\n", fails);
+ return fails != 0;
+}
diff --git a/games/twoplayer/tests/test.c b/games/twoplayer/tests/test.c
deleted file mode 100644
index 0bafeefb..00000000
--- a/games/twoplayer/tests/test.c
+++ /dev/null
@@ -1,136 +0,0 @@
-#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
deleted file mode 100644
index 3d4af1ef..00000000
--- a/games/twoplayer/tests/test_arm.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""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
deleted file mode 100644
index 31f33b91..00000000
--- a/games/twoplayer/tests/test_integration.py
+++ /dev/null
@@ -1,121 +0,0 @@
-"""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
deleted file mode 100644
index 56c95ba8..00000000
--- a/games/twoplayer/tests/test_languages.py
+++ /dev/null
@@ -1,26 +0,0 @@
-"""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 b19462b7..56f779bc 100644
--- a/games/twoplayer/tools/bot.py
+++ b/games/twoplayer/tools/bot.py
@@ -2,9 +2,9 @@
"""Plays 2 Players in the ARM emulator for the README's pictures.
Runs the calculator build (TwoPlayers.nwa) in tools/emu.py as player 1 against the hard computer,
-game after game: it reads the screen (the ball, the puck, the tanks, the light cycles) and presses
-the keys a player would. Saves the raw frames, then the gallery's GIF (a few seconds of each game)
-and a screenshot of each game.
+game after game: it reads the screen (the ball, the puck, the tanks, the light cycles, the signal)
+and presses the keys a player would. Saves the raw frames, then the gallery's GIF (a few seconds of
+each game) and a screenshot of each game.
Usage: bot.py TwoPlayers.nwa OUT [--fps 25] [--seconds 8] (needs NumPy; gifsicle for small GIFs)
"""
@@ -42,6 +42,7 @@ class Bot:
self.last = None
self.dir = 0
self.fired = 0
+ self.seen = None
def grab(self, calc):
open(os.path.join(self.out, f"{self.frame:06d}_{int(calc.now_ms):06d}.raw"), "wb").write(bytes(calc.screen))
@@ -183,6 +184,14 @@ class Bot:
best, bv = d, v
self.hold([] if best == self.dir else [["right", "down", "left", "up"][best]])
+ def quick(self): # Quick Draw: OK a quarter of a second after the ground turns at the signal
+ go = near(self.screen()[100:101, 20:21], 0x3A2F1C, 12).any()
+ self.seen = (self.seen or self.c.now_ms) if go else None
+ self.hold(["ok"] if go and self.c.now_ms - self.seen >= 250 else [])
+
+ def tug(self): # Tug of War: OK, let go, OK...
+ self.hold(["ok"] if int(self.c.now_ms // STEP) % 4 == 0 else [])
+
def play(self, game, seconds):
self.tap("ok", 1400) # the rules
self.tap("ok", 300) # play
@@ -190,7 +199,7 @@ class Bot:
self.last = None
end = self.c.now_ms + seconds * 1000
while self.c.now_ms < end:
- [self.pong, self.hockey, self.tanks, self.cycles][game]()
+ [self.pong, self.hockey, self.tanks, self.cycles, self.quick, self.tug][game]()
self.marks.append((self.c.now_ms, -1))
self.tap("back") # Paused, Other games
self.tap("down")
@@ -212,7 +221,7 @@ def main():
for _ in range(3): # the hard computer
bot.tap("right", 150)
bot.run(500)
- for g in range(4):
+ for g in range(6):
bot.play(g, a.seconds)
bot.tap("down", 300)
frames = record.load_frames(raw)
diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txt
index 87824f2a..bdef86b6 100644
--- a/launcher/lang/fr.txt
+++ b/launcher/lang/fr.txt
@@ -135,6 +135,4 @@ 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
-Fifteen mini-games, side by side Quinze mini-jeux, côte à côte
-Additional mini-games by Bobydeluxe Mini-jeux supplémentaires par Bobydeluxe
+Levels: Microban by David W. Skinner Niveaux : Microban de David W. Skinner
\ No newline at end of file
diff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txt
index 3ca18325..8194210b 100644
--- a/launcher/lang/zh.txt
+++ b/launcher/lang/zh.txt
@@ -134,6 +134,4 @@ Needs 内存还差
Sokoban 推箱子
Push every box home 把每个箱子推到位
-Levels: Microban by David W. Skinner 关卡:David W. Skinner 的 Microban
-Fifteen mini-games, side by side 十五款小游戏,并肩对战
-Additional mini-games by Bobydeluxe 新增小游戏:Bobydeluxe
+Levels: Microban by David W. Skinner 关卡:David W. Skinner 的 Microban
\ No newline at end of file
diff --git a/tests/test_games.py b/tests/test_games.py
index 5a481820..0313aaf7 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -466,9 +466,9 @@ CHECKS = {
and struct.unpack_from("<H", v, 682)[0] == 1,) * 2,
"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) == 128 and v[:4] == b"P\3\1\1",
- lambda v: len(v) == 128 and v[:4] == b"P\3\2\2"),
+ # Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies of the six games kept
+ "twoplayer": (lambda v: len(v) == 52 and v[:4] == b"P\1\1\1",
+ lambda v: len(v) == 52 and v[:4] == b"P\1\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),