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.

Nine more games: All the Apps in C, and four new ones

Mason3630c8fa1e1a624
diff --git a/.github/release.md b/.github/release.md
index 11f9744e..9c22c3ad 100644
--- a/.github/release.md
+++ b/.github/release.md
@@ -2,7 +2,7 @@
| File | |
| --- | --- |
-| **NumPlay.nwa** | All 5 games and NumVisuals in one app. Start here! |
+| **NumPlay.nwa** | All 14 games and NumVisuals in one app. Start here! |
| NumPlay-Invisible.nwa | The same app, hidden: a blank icon with no name |
| NumPlay-Matrices.nwa | The same app, disguised as a math app called Matrices |
| NumDash.nwa | Only NumDash: jump to the beat |
@@ -10,4 +10,13 @@
| NumDrive.nwa | Only NumDrive: drive, flip, finish |
| Tetris.nwa | Only Tetris: stack and clear lines |
| NumChess.nwa | Only Chess: bots, puzzles, 2 players |
+| FlappyBird.nwa | Only Flappy Bird: flap through the pipes |
+| PacMan.nwa | Only Pac-Man: eat dots, dodge ghosts |
+| Snake.nwa | Only Snake: eat apples, grow long |
+| ConnectFour.nwa | Only Connect Four: four in a row wins |
+| Solitaire.nwa | Only Solitaire: the classic card game |
+| NumDance.nwa | Only NumDance: hit the arrows on the beat |
+| 2048.nwa | Only 2048: slide, merge, reach 2048 |
+| Minesweeper.nwa | Only Minesweeper: clear the field, flag the mines |
+| Breakout.nwa | Only Breakout: break every brick |
| NumVisuals.nwa | Only NumVisuals: backgrounds, clocks, timers |
diff --git a/Makefile b/Makefile
index 2d00d200..84fd1375 100644
--- a/Makefile
+++ b/Makefile
@@ -83,6 +83,9 @@ $(B)/modules/%.o: FORCE | $(B)
$(PY) tools/npmodule.py $(B)/modules/$*.2.o $@ --game $* --index $(INDEX_$*) \
--entry $(or $(ENTRY_$*),$(ENTRY)) --json $(B)/modules/$*.json
+# games in the standard layout (see tools/games_mk.py)
+$(foreach g,$(STD_GAMES),$(eval MOD_$(g) = games/$(g)/output/module.o)$(eval SIM_$(g) = games/$(g)/output/sim-module.o))
+
MODULES = $(foreach g,$(GAMES),$(B)/modules/$(g).o)
# ------------------------------------------------------------------ generated glue
@@ -145,6 +148,12 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_numvisuals))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numvisuals)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
+STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
+apps: $(STD_APPS)
+$(STD_APPS): $(B)/apps/%.nwa: FORCE | $(B)
+ $(MAKE) --no-print-directory -C games/$(APPID_$*) build NWLINK="$(NWLINK)"
+ cp games/$(APPID_$*)/output/$(APPID_$*).nwa $@
+
# ------------------------------------------------------------------ simulator
SIM_numdash = games/numdash/build/sim-module.o
SIM_crossyroad = games/crossyroad/output/sim-module.o
@@ -184,3 +193,4 @@ clean:
-$(MAKE) -C games/chess clean
-$(MAKE) -C games/numvisuals clean
-cd games/tetris/tetris && $(CARGO) clean
+ -$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/README.md b/README.md
index 24c00959..5a28d798 100644
--- a/README.md
+++ b/README.md
@@ -5,8 +5,8 @@
<h1 align="center">NumPlay</h1>
<p align="center">
- <b>5 free games for your NumWorks calculator, in one app.</b><br>
- NumDash, Crossy Road, NumDrive, Tetris and Chess, plus NumVisuals: moving backgrounds with a clock, a timer and more.
+ <b>14 free games for your NumWorks calculator, in one app.</b><br>
+ NumDash, Crossy Road, NumDrive, Tetris, Chess, Flappy Bird, Pac-Man, Snake, Connect Four, Solitaire, NumDance, 2048, Minesweeper and Breakout, plus NumVisuals: moving backgrounds with a clock, a timer and more.
</p>
<p align="center">
@@ -32,7 +32,7 @@ Click a file to download it. Not sure which one? Take the first.
<table>
<tr>
<td width="120" align="center"><img src="docs/media/icon.png" width="64" alt="NumPlay icon"></td>
- <td><b><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay.nwa">NumPlay.nwa</a></b><br><b>All 5 games and NumVisuals in one app. Start here!</b></td>
+ <td><b><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay.nwa">NumPlay.nwa</a></b><br><b>All 14 games and NumVisuals in one app. Start here!</b></td>
</tr>
<tr>
<td width="120" align="center"><img src="docs/media/icon-invisible.png" width="64" alt="A blank white icon"></td>
@@ -66,6 +66,42 @@ Click a file to download it. Not sure which one? Take the first.
<td width="120" align="center"><img src="docs/media/thumb_chess.png" width="112" alt="Chess"></td>
<td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumChess.nwa">NumChess.nwa</a><br>Only Chess: bots, puzzles, 2 players</td>
</tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_flappybird.png" width="112" alt="Flappy Bird"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FlappyBird.nwa">FlappyBird.nwa</a><br>Only Flappy Bird: flap through the pipes</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_pacman.png" width="112" alt="Pac-Man"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/PacMan.nwa">PacMan.nwa</a><br>Only Pac-Man: eat dots, dodge ghosts</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_snake.png" width="112" alt="Snake"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Snake.nwa">Snake.nwa</a><br>Only Snake: eat apples, grow long</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_connectfour.png" width="112" alt="Connect Four"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/ConnectFour.nwa">ConnectFour.nwa</a><br>Only Connect Four: four in a row wins, against a friend or the computer</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_solitaire.png" width="112" alt="Solitaire"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Solitaire.nwa">Solitaire.nwa</a><br>Only Solitaire: the classic card game</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_numdance.png" width="112" alt="NumDance"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumDance.nwa">NumDance.nwa</a><br>Only NumDance: hit the arrows on the beat</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_g2048.png" width="112" alt="2048"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/2048.nwa">2048.nwa</a><br>Only 2048: slide, merge, reach 2048</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_minesweeper.png" width="112" alt="Minesweeper"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Minesweeper.nwa">Minesweeper.nwa</a><br>Only Minesweeper: clear the field, flag the mines</td>
+ </tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_breakout.png" width="112" alt="Breakout"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/Breakout.nwa">Breakout.nwa</a><br>Only Breakout: break every brick</td>
+ </tr>
<tr>
<td width="120" align="center"><img src="docs/media/thumb_numvisuals.png" width="112" alt="NumVisuals"></td>
<td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumVisuals.nwa">NumVisuals.nwa</a><br>Only NumVisuals: backgrounds, clocks, timers</td>
@@ -109,14 +145,31 @@ You need your calculator, its USB cable, and a computer with **Google Chrome** o
</tr>
<tr>
<td><img src="docs/media/numvisuals.gif" alt="NumVisuals: picking a background, then a clock"></td>
- <td></td>
+ <td><img src="games/flappybird/docs/shot.png" width="100%" alt="Flappy Bird"></td>
+ </tr>
+ <tr>
+ <td><img src="games/pacman/docs/shot.png" width="100%" alt="Pac-Man"></td>
+ <td><img src="games/snake/docs/shot.png" width="100%" alt="Snake"></td>
+ </tr>
+ <tr>
+ <td><img src="games/connectfour/docs/shot.png" width="100%" alt="Connect Four"></td>
+ <td><img src="games/solitaire/docs/shot.png" width="100%" alt="Solitaire"></td>
+ </tr>
+ <tr>
+ <td><img src="games/numdance/docs/shot.png" width="100%" alt="NumDance"></td>
+ <td><img src="games/g2048/docs/shot.png" width="100%" alt="2048"></td>
+ </tr>
+ <tr>
+ <td><img src="games/minesweeper/docs/shot.png" width="100%" alt="Minesweeper"></td>
+ <td><img src="games/breakout/docs/shot.png" width="100%" alt="Breakout"></td>
</tr>
</table>
## Acknowledgements
-- **[Tatone26](https://github.com/Tatone26/Numworks-games/tree/main/apps/tetris)** made Tetris and released it into the public domain.
+- **[Tatone26](https://github.com/Tatone26/Numworks-games)** made Tetris and **All the Apps**, and released them into the public domain. NumPlay's Flappy Bird, Pac-Man, Snake, Connect Four and Solitaire are rewritten in C from All the Apps and keep its options, and our 2048 started from Tatone26's Python version.
+- **[Gabriele Cirulli](https://github.com/gabrielecirulli/2048)** made 2048.
- **[gd3ds](https://github.com/AleFunky/gd3ds)** by AleFunky and friends, whose research into Geometry Dash made NumDash possible.
- The **Nunito** and **Rammetto One** fonts, under the SIL Open Font License ([LICENSES](LICENSES)).
-<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road) or the makers of Drive Mad. Tetris is a trademark of The Tetris Company.</sub>
+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Atari (Breakout) or Microsoft (Solitaire, Minesweeper). Tetris is a trademark of The Tetris Company, Pac-Man of Bandai Namco, Connect Four of Hasbro and Breakout of Atari.</sub>
diff --git a/VERSION b/VERSION
index 6085e946..f0bb29e7 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.2.1
+1.3.0
diff --git a/docs/media/thumb_breakout.png b/docs/media/thumb_breakout.png
new file mode 100644
index 00000000..fc9db0b4
Binary files /dev/null and b/docs/media/thumb_breakout.png differ
diff --git a/docs/media/thumb_connectfour.png b/docs/media/thumb_connectfour.png
new file mode 100644
index 00000000..c66d0f5d
Binary files /dev/null and b/docs/media/thumb_connectfour.png differ
diff --git a/docs/media/thumb_flappybird.png b/docs/media/thumb_flappybird.png
new file mode 100644
index 00000000..1bb796a4
Binary files /dev/null and b/docs/media/thumb_flappybird.png differ
diff --git a/docs/media/thumb_g2048.png b/docs/media/thumb_g2048.png
new file mode 100644
index 00000000..948d4eb7
Binary files /dev/null and b/docs/media/thumb_g2048.png differ
diff --git a/docs/media/thumb_minesweeper.png b/docs/media/thumb_minesweeper.png
new file mode 100644
index 00000000..4e9b61d1
Binary files /dev/null and b/docs/media/thumb_minesweeper.png differ
diff --git a/docs/media/thumb_numdance.png b/docs/media/thumb_numdance.png
new file mode 100644
index 00000000..9fab8f1f
Binary files /dev/null and b/docs/media/thumb_numdance.png differ
diff --git a/docs/media/thumb_pacman.png b/docs/media/thumb_pacman.png
new file mode 100644
index 00000000..922ea0c7
Binary files /dev/null and b/docs/media/thumb_pacman.png differ
diff --git a/docs/media/thumb_snake.png b/docs/media/thumb_snake.png
new file mode 100644
index 00000000..3c51963e
Binary files /dev/null and b/docs/media/thumb_snake.png differ
diff --git a/docs/media/thumb_solitaire.png b/docs/media/thumb_solitaire.png
new file mode 100644
index 00000000..870e6491
Binary files /dev/null and b/docs/media/thumb_solitaire.png differ
diff --git a/docs/play.md b/docs/play.md
index 8ec80ab9..0ffc8bbc 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -94,6 +94,135 @@ Don't floor it the whole way: too much gas flips the car.
<br clear="right">
+## Flappy Bird
+
+<img src="../games/flappybird/docs/shot.png" width="320" align="right" alt="Flappy Bird">
+
+| Key | What it does |
+| --- | --- |
+| **OK**, **Up** or **EXE** | Flap |
+| **Back** | Pause menu (with Quit game) |
+
+**Classic** plays like the original. **Custom** brings All the Apps' extras from Settings: speed, pipe density, gap size, moving pipes, jump strength, and events like wind gusts, gravity changes and narrow gaps. Medals at 10, 20, 30 and 40.
+
+<br clear="right">
+
+## Pac-Man
+
+<img src="../games/pacman/docs/shot.png" width="320" align="right" alt="Pac-Man">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Steer (a turn pressed early is taken at the next gap) |
+| **Back** | Pause menu (with Quit game) |
+
+The arcade maze and its four ghosts, each with its own way of hunting you. Leave in the middle of a game and **Continue** it later. Options: game speed, lives, input buffer, starting level.
+
+<br clear="right">
+
+## Snake
+
+<img src="../games/snake/docs/shot.png" width="320" align="right" alt="Snake">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Turn (two turns can wait in line) |
+| **Back** | Pause menu (with Quit game) |
+
+Settings: speed, board size, 1, 3 or 5 apples, walls, wrapping through the edges, and portals (eat one apple of a pair to come out of the other).
+
+<br clear="right">
+
+## Connect Four
+
+<img src="../games/connectfour/docs/shot.png" width="320" align="right" alt="Connect Four">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** | Choose a column |
+| **OK**, **Down** or **1-8** | Drop a disc |
+| **⌫** | Undo (against the computer) |
+| **Back** | Pause menu (with Quit game) |
+
+Against a friend, or the computer at three strengths, or three players at once. Wins are counted across rounds.
+
+<br clear="right">
+
+## Solitaire
+
+<img src="../games/solitaire/docs/shot.png" width="320" align="right" alt="Solitaire">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Move (Up / Down on a column picks how many cards) |
+| **OK** | Pick up, put down; twice sends a card home |
+| **EXE** | Draw |
+| **Toolbox** | Send every card you can home |
+| **⌫** | Undo |
+| **Shift** | Hint |
+| **Back** | Put cards back, or the pause menu |
+
+Klondike like Windows: draw 1 or 3, Standard or Vegas scoring, and the bouncing cards when you win. Your game is kept for next time.
+
+<br clear="right">
+
+## NumDance
+
+<img src="../games/numdance/docs/shot.png" width="320" align="right" alt="NumDance">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows**, or **4 5 8 6**, or **1 2 3 +** | Hit the arrows as they land on the gray targets; hold along trails |
+| **Back** | Pause (with Quit game) |
+
+Arrows fall down four lanes: press the matching key as each one reaches its target. 6 songs, each in Easy, Normal, Hard and Expert, and an Endless mode. The calculator has no speaker, so the beat is in the lights and the stage. Options: scroll speed, timing offset (with a calibration), direction, no-fail.
+
+<br clear="right">
+
+## 2048
+
+<img src="../games/g2048/docs/shot.png" width="320" align="right" alt="2048">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Slide the tiles |
+| **⌫** | Undo one move |
+| **Left / Right** (title) | Board size, 3x3 to 6x6 |
+| **Back** | Pause menu (with Quit game) |
+
+Merge equal tiles to reach 2048, then keep going. Each board size keeps its game and best score.
+
+<br clear="right">
+
+## Minesweeper
+
+<img src="../games/minesweeper/docs/shot.png" width="320" align="right" alt="Minesweeper">
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Move |
+| **OK** | Open a square; on a number with all its flags, open around it |
+| **Shift**, **⌫** or **0** | Flag |
+| **Back** | Pause menu (with Help and Quit game) |
+
+Beginner, Intermediate, Expert or your own size. The first square is always safe. Options: **No guessing** (only boards you can solve by logic) and ? marks.
+
+<br clear="right">
+
+## Breakout
+
+<img src="../games/breakout/docs/shot.png" width="320" align="right" alt="Breakout">
+
+| Key | What it does |
+| --- | --- |
+| **Left / Right** | Move the paddle (hold to speed up) |
+| **OK** or **Up** | Launch, fire the laser |
+| **Back** | Pause menu (with Quit game) |
+
+**Classic** is the 1976 arcade game. **Arcade+** has hand-made rounds, tough bricks and power-ups: wide paddle, three balls, slow ball, catch, laser and an extra life.
+
+<br clear="right">
+
## NumVisuals
<img src="media/numvisuals.gif" width="320" align="right" alt="NumVisuals: picking a background, then a clock">
diff --git a/games/breakout/.gitignore b/games/breakout/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/breakout/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/breakout/Makefile b/games/breakout/Makefile
new file mode 100644
index 00000000..82e0eebc
--- /dev/null
+++ b/games/breakout/Makefile
@@ -0,0 +1,51 @@
+# Breakout — the Atari classic, and an Arcade+ mode with rounds and power-ups.
+# make build output/breakout.nwa
+# make check link the app like the calculator does (output/breakout.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/breakout.nwa
+
+check: $(BUILD_DIR)/breakout.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/breakout.bin
+ @echo "BIN $(BUILD_DIR)/breakout.bin: $$(wc -c < $(BUILD_DIR)/breakout.bin) bytes"
+
+$(BUILD_DIR)/breakout.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_breakout_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_breakout_main -o $@
diff --git a/games/breakout/README.md b/games/breakout/README.md
new file mode 100644
index 00000000..ee9aeb3f
--- /dev/null
+++ b/games/breakout/README.md
@@ -0,0 +1,28 @@
+# Breakout
+
+The brick breaker, for the NumWorks calculator: Atari's 1976 arcade game as it was, and an **Arcade+** mode in the spirit of Arkanoid.
+
+<img src="docs/shot.png" width="320" alt="Classic Breakout: the wall of bricks, the ball and the paddle">
+
+- **Classic** plays like the arcade: eight rows of bricks in red, orange, green and yellow (7, 5, 3 and 1 points), three balls, and a second wall once you clear the first. The ball speeds up after 4 and 12 hits and when it reaches the orange and red rows, and your paddle shrinks to half once the ball breaks through to the top wall. Like on the real cabinet, where colour came from strips of film on the screen, the ball takes the colour of the rows it flies through.
+- **Arcade+** has 12 hand-made rounds with silver bricks that take a few hits, gold ones that never break, and capsules that fall from broken bricks: **E**nlarge, **C**atch, **L**aser, **S**low, **D**isruption (three balls), **P**layer (an extra life) and **B**reak, which opens a way out to the next round. Pick any round you have reached from the title screen.
+
+Where the ball lands on the paddle decides where it goes. Bricks burst into sparks and the wall rattles when you hit it, the whole screen shakes when you lose a ball, and the ball leaves a short trail.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Left / Right, or 4 / 6 | Move the paddle (tap to nudge it, hold to speed up) |
+| OK or Up | Launch the ball, fire the laser, let go of a caught ball |
+| Back | Pause: Resume, Restart, Quit game |
+
+**Settings:** difficulty (Easy, Normal, Hard: the ball's speed and the paddle's size), screen shake, and the ball's trail. Your best score in each mode, the rounds you have reached and your settings are kept for next time (`breakout.sav`).
+
+It comes inside [NumPlay](../../README.md), or on its own as `Breakout.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+## Credits
+
+Inspired by *Breakout* (Atari, 1976; designed by Nolan Bushnell and Steve Bristow, with a prototype built by Steve Wozniak) and its home version for the Atari 2600, and by *Arkanoid* (Taito, 1986) for the Arcade+ mode. Written from scratch in C for NumPlay; everything is drawn with code, so the whole game is about 14 KB.
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/breakout/docs/shot.png b/games/breakout/docs/shot.png
new file mode 100644
index 00000000..f66bcec2
Binary files /dev/null and b/games/breakout/docs/shot.png differ
diff --git a/games/breakout/src/icon.png b/games/breakout/src/icon.png
new file mode 100644
index 00000000..a5d4707b
Binary files /dev/null and b/games/breakout/src/icon.png differ
diff --git a/games/breakout/src/main.c b/games/breakout/src/main.c
new file mode 100644
index 00000000..7f3e0e1a
--- /dev/null
+++ b/games/breakout/src/main.c
@@ -0,0 +1,1218 @@
+/* Breakout: Atari's 1976 brick breaker, and an Arcade+ mode in the spirit of
+ * Arkanoid (hand-made rounds, silver and gold bricks, power-up capsules).
+ *
+ * Nothing is drawn straight to the screen: whatever moves or changes marks
+ * the rectangle it covers, and each marked rectangle is composed in a small
+ * buffer (background, walls, bricks, paddle, balls, particles, text) and
+ * pushed once. A frame costs a few thousand pixels and nothing flickers. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Breakout";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+#define W 320
+#define H 240
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define GRAY RGB(0x8E8E8E)
+#define BLUE RGB(0x4A6CE8)
+#define DIM RGB(0xB0B0B0)
+#define KEY(k) (1ull << (k))
+
+/* the playfield */
+#define FX0 10 /* inside of the side walls */
+#define FX1 310
+#define TOP 28 /* the top wall, 8 pixels thick */
+#define FY0 36
+#define COLS 15
+#define ROWS 12
+#define CW 20 /* a brick's cell */
+#define CH 8
+#define BY0 52 /* the first row of bricks */
+#define PY 222 /* the top of the paddle */
+#define BS 5 /* the ball's size */
+#define ONE 256 /* positions and speeds are in 256ths of a pixel */
+
+static int imin(int a, int b) { return a < b ? a : b; }
+static int imax(int a, int b) { return a > b ? a : b; }
+static int iabs(int v) { return v < 0 ? -v : v; }
+
+static uint32_t seed = 0x2545F491;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+static int rndi(int n) { return (int)(rnd() % (uint32_t)n); }
+
+/* f over b; a from 0 (all b) to 32 (all f) */
+static color mix(color f, color b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (color)(y | y >> 16);
+}
+
+/* ------------------------------------------------------------------ bricks */
+enum {
+ K_NONE, K_RED, K_ORANGE, K_GREEN, K_YELLOW, /* the classic wall */
+ K_WHITE, K_ORANGE2, K_CYAN, K_GREEN2, K_RED2, K_BLUE, K_PINK, K_YELLOW2, K_SILVER, K_GOLD, K_RAINBOW
+};
+static const color kcol[15] = {
+ 0, RGB(0xC84848), RGB(0xC66C3A), RGB(0x48A048), RGB(0xA2A22A),
+ RGB(0xF4F4F4), RGB(0xFF8A1C), RGB(0x30D8F0), RGB(0x3CD040), RGB(0xF03C3C), RGB(0x3868F8), RGB(0xF058D0),
+ RGB(0xF8E040), RGB(0xA8B0BC), RGB(0xD8A030)};
+/* a round's "rainbow" bricks take their colour from their row */
+static const uint8_t rainbow[ROWS] = {K_WHITE, K_ORANGE2, K_RED2, K_YELLOW2, K_BLUE, K_PINK,
+ K_GREEN2, K_CYAN, K_ORANGE2, K_RED2, K_YELLOW2, K_BLUE};
+
+/* Arcade+ rounds, all symmetric: a row is its 8 left cells (the 8th is the
+ middle one), 2 bits each, picking one of the round's 3 kinds. Q() reads
+ them as digits after a leading 1. */
+#define QD(n, p) ((n) / (p) % 10)
+#define Q(n) (uint16_t)(QD(n, 10000000) | QD(n, 1000000) << 2 | QD(n, 100000) << 4 | QD(n, 10000) << 6 | \
+ QD(n, 1000) << 8 | QD(n, 100) << 10 | QD(n, 10) << 12 | QD(n, 1) << 14)
+#define PAL(a, b, c) (uint16_t)((a) | (b) << 4 | (c) << 8)
+typedef struct {
+ uint16_t pal, row[ROWS];
+} round_t;
+static const round_t rounds[] = {
+ {PAL(K_RAINBOW, K_SILVER, 0), /* welcome */
+ {0, Q(122222222), Q(111111111), Q(111111111), Q(111111111), Q(111111111), Q(111111111)}},
+ {PAL(K_RAINBOW, K_GOLD, 0), /* pyramid */
+ {Q(100000001), Q(100000011), Q(100000111), Q(100001111), Q(100011111), Q(100111111), Q(101111111),
+ Q(111111111), 0, Q(120002000)}},
+ {PAL(K_CYAN, K_PINK, K_SILVER), /* checkers */
+ {0, Q(133333333), Q(112121212), Q(121212121), Q(112121212), Q(121212121), Q(112121212), Q(121212121)}},
+ {PAL(K_GREEN2, K_SILVER, 0), /* invader */
+ {0, Q(100001000), Q(100000100), Q(100001111), Q(100011011), Q(100111111), Q(100101111), Q(100101000),
+ Q(100000110), 0, Q(102200220)}},
+ {PAL(K_RAINBOW, K_SILVER, K_GOLD), /* gates */
+ {0, Q(111111111), Q(111111111), 0, Q(133333302), 0, Q(111111111), 0, Q(130333333)}},
+ {PAL(K_RAINBOW, K_SILVER, K_GOLD), /* diamond */
+ {Q(130000002), Q(100000021), Q(100000211), Q(100002111), Q(100021111), Q(100002111), Q(100000211),
+ Q(100000021), Q(130000002)}},
+ {PAL(K_BLUE, K_SILVER, K_GOLD), /* pillars */
+ {Q(122222222), Q(110101010), Q(110101010), Q(110101010), Q(110101010), Q(110101010), Q(110101010),
+ Q(110101010), Q(130003000)}},
+ {PAL(K_CYAN, K_PINK, K_YELLOW2), /* chevrons */
+ {0, Q(112312312), Q(123123123), Q(131231231), Q(112312312), Q(123123123), Q(131231231), Q(112312312),
+ Q(123123123)}},
+ {PAL(K_RED2, K_SILVER, K_GOLD), /* fortress */
+ {Q(111111111), 0, Q(100333333), Q(100311111), Q(100312221), Q(100312221), Q(100311111), Q(100333000), 0,
+ Q(111000111)}},
+ {PAL(K_BLUE, K_ORANGE2, K_SILVER), /* target */
+ {0, Q(111111111), Q(112222222), Q(112111111), Q(112133333), Q(112131111), Q(112133333), Q(112111111),
+ Q(112222222), Q(111111111)}},
+ {PAL(K_RED2, K_PINK, K_GOLD), /* heart */
+ {Q(130000000), Q(100022200), Q(100211110), Q(100111111), Q(100111111), Q(100011111), Q(100001111),
+ Q(100000111), Q(100000011), Q(100000001), Q(130000000)}},
+ {PAL(K_RAINBOW, K_SILVER, K_GOLD), /* the last one */
+ {Q(122222222), Q(111111111), Q(131111111), Q(122222222), Q(111111111), Q(111133111), Q(111111111),
+ Q(122222222), 0, Q(130303030)}},
+};
+#define NROUNDS (int)(sizeof rounds / sizeof rounds[0])
+
+/* a brick: its kind (4 bits), hits left (2 bits), and a flash when hit (2 bits) */
+static uint8_t brick[ROWS][COLS];
+
+/* ------------------------------------------------------------------ the game */
+enum { CLASSIC, ARCADE };
+enum { S_TITLE, S_SET, S_READY, S_PLAY, S_LOST, S_CLEAR, S_PAUSE, S_QUIT, S_OVER };
+enum { P_NONE, P_ENLARGE, P_CATCH, P_LASER };
+/* capsules: Slow, Catch, Laser, Enlarge, Disruption (three balls), Player (a
+ life) and Break (a way out to the next round), in Arkanoid's colours */
+static const char cap_letter[7] = {16, 11, 14, 13, 12, 15, 10}; /* in mini[] */
+static const color cap_col[7] = {RGB(0xF08C20), RGB(0x38C848), RGB(0xE83838), RGB(0x3C6CF0), RGB(0x30C8E8),
+ RGB(0x9098A8), RGB(0xE858C8)};
+static const uint8_t cap_odds[7] = {20, 18, 18, 20, 14, 4, 6};
+
+typedef struct {
+ int32_t x, y, vx, vy;
+ int16_t off; /* where it sits on the paddle when caught, in pixels */
+ int16_t tx[3], ty[3]; /* the trail */
+ uint8_t on, stuck;
+} ball_t;
+typedef struct {
+ int16_t x, y; /* in 16ths of a pixel */
+ int8_t vx, vy;
+ color c;
+ uint8_t life, max;
+} part_t;
+typedef struct {
+ int16_t x, y;
+ uint8_t on, type;
+} thing_t; /* a capsule or a laser shot */
+
+#define NBALL 3
+#define NPART 48
+#define NSHOT 6
+static ball_t ball[NBALL];
+static part_t part[NPART];
+static thing_t cap, shot[NSHOT];
+static int mode, state, resume_state, st_t, tk, sel, tsel, round_no, start_round, bricks_left, rows_shown;
+static int32_t score;
+static int lives, wall, hits, power, laser_cd, catch_t, warp;
+static bool demo, got_orange, got_red, shrunk, won, fresh_best, full;
+static int px, pv, spd, spd0; /* the paddle's centre and speed, the balls' speed (in 256ths) */
+static int pw, pw_to; /* the paddle's width, and the width it is going to */
+static int demo_aim; /* where the self-playing paddle aims */
+/* the shake: time left, strength, and the offsets of the bricks (bx, by) and of
+ everything else (sx, sy), which only moves in a big shake */
+static int shake_t, shake_a, bx, by, sx, sy;
+static bool shake_all;
+
+/* ------------------------------------------------------------------ save */
+static struct {
+ uint8_t magic, version, reached, diff, shake, trail, pad[2];
+ uint32_t best[2];
+} sv, saved;
+#define SAVE_NAME "breakout.sav"
+
+static void save(void) {
+ const uint8_t *a = (const uint8_t *)&sv, *b = (const uint8_t *)&saved;
+ unsigned i = 0;
+ while (i < sizeof sv && a[i] == b[i]) i++;
+ if (i < sizeof sv && ef_write(SAVE_NAME, &sv, sizeof sv)) saved = sv;
+}
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ sv.magic = 'B', sv.version = 1, sv.reached = 1, sv.diff = 1, sv.shake = 1, sv.trail = 1;
+ if (d && n == sizeof sv && d[0] == 'B' && d[1] == 1 && d[2] >= 1 && d[2] <= NROUNDS && d[3] < 3 && d[4] < 2 &&
+ d[5] < 2) {
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&sv)[i] = d[i];
+ for (int m = 0; m < 2; m++)
+ if (sv.best[m] > 999999) sv.best[m] = 0;
+ saved = sv;
+ }
+ start_round = sv.reached;
+}
+
+/* ------------------------------------------------------------------ dirty rectangles */
+typedef struct {
+ int16_t x0, y0, x1, y1;
+} rect_t;
+#define NDIRTY 40
+static rect_t dirty[NDIRTY];
+static int ndirty;
+
+/* marks an area to redraw, merged with another when that wastes little
+ (overlapping areas are simply drawn twice) */
+static void mark(int x0, int y0, int x1, int y1) {
+ x0 = imax(x0, 0), y0 = imax(y0, 0), x1 = imin(x1, W), y1 = imin(y1, H);
+ if (x0 >= x1 || y0 >= y1) return;
+ for (int i = 0; i < ndirty;) {
+ rect_t *d = &dirty[i];
+ int u0 = imin(x0, d->x0), v0 = imin(y0, d->y0), u1 = imax(x1, d->x1), v1 = imax(y1, d->y1);
+ if ((u1 - u0) * (v1 - v0) <= (x1 - x0) * (y1 - y0) + (d->x1 - d->x0) * (d->y1 - d->y0) + 256) {
+ x0 = u0, y0 = v0, x1 = u1, y1 = v1;
+ *d = dirty[--ndirty];
+ i = 0;
+ } else {
+ i++;
+ }
+ }
+ if (ndirty == NDIRTY) { /* too many: the last one takes this one in */
+ rect_t *d = &dirty[NDIRTY - 1];
+ x0 = imin(x0, d->x0), y0 = imin(y0, d->y0), x1 = imax(x1, d->x1), y1 = imax(y1, d->y1);
+ ndirty--;
+ }
+ dirty[ndirty++] = (rect_t){(int16_t)x0, (int16_t)y0, (int16_t)x1, (int16_t)y1};
+}
+/* something in the playfield, which shakes */
+static void mark_at(int x, int y, int w, int h) { mark(x + sx, y + sy, x + sx + w, y + sy + h); }
+static void mark_cell(int r, int c) { /* however it shakes, and its shadow */
+ int x = FX0 + c * CW, y = BY0 + r * CH;
+ mark(x - 4, y - 4, x + CW + 7, y + CH + 7);
+}
+
+/* ------------------------------------------------------------------ drawing */
+#define BUFN (W * 16)
+static color buf[BUFN];
+static int rx0, ry0, rx1, ry1, rw; /* the area buf holds */
+static int cx0, cx1; /* and the columns drawing may touch */
+
+static void rect(int x, int y, int w, int h, color c, int a) {
+ int x0 = imax(x, cx0), x1 = imin(x + w, cx1), y0 = imax(y, ry0), y1 = imin(y + h, ry1);
+ for (int j = y0; j < y1; j++)
+ for (color *p = buf + (j - ry0) * rw + x0 - rx0, *e = p + x1 - x0; p < e; p++) *p = a >= 32 ? c : mix(c, *p, a);
+}
+static __attribute__((noinline)) void fill(int x, int y, int w, int h, color c) { rect(x, y, w, h, c, 32); }
+static bool seen(int x, int y, int w, int h) { return x < rx1 && x + w > rx0 && y < ry1 && y + h > ry0; }
+
+/* ASCII 32..90 (lowercase is drawn as capitals), columns of 7 bits, top bit first */
+static const uint8_t font[59][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x07,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14},
+ {0x24,0x2A,0x7F,0x2A,0x12},{0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00},
+ {0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},{0x14,0x08,0x3E,0x08,0x14},{0x08,0x08,0x3E,0x08,0x08},
+ {0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},{0x20,0x10,0x08,0x04,0x02},
+ {0x3E,0x51,0x49,0x45,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},
+ {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},
+ {0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00},
+ {0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},
+ {0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22},
+ {0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x49,0x49,0x7A},
+ {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41},
+ {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x02,0x0C,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},
+ {0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},
+ {0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},{0x3F,0x40,0x38,0x40,0x3F},
+ {0x63,0x14,0x08,0x14,0x63},{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},
+};
+/* 3x5 blocky figures, like the arcade's score, then the capsule letters
+ B C D E L P S: five rows of three bits (an octal digit each) */
+static const uint16_t mini[17] = {075557, 026227, 071747, 071717, 055711, 074717, 074757, 071111, 075757,
+ 075717, 065656, 074447, 065556, 074647, 044447, 065644, 034216};
+
+static int glyph_of(char ch) {
+ if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 32);
+ return ch < 32 || ch > 'Z' ? '?' - 32 : ch - 32;
+}
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static int tw(const char *s, int k) { return slen(s) * 6 * k - k; }
+/* text from x, with a dark shadow so it reads over anything */
+static void text(const char *s, int x, int y, int k, color c) {
+ if (!seen(x, y, tw(s, k) + k, 8 * k)) return;
+ for (int pass = 0; pass < 2; pass++)
+ for (int n = 0; s[n]; n++) {
+ const uint8_t *g = font[glyph_of(s[n])];
+ int o = pass ? 0 : (k + 1) / 2;
+ for (int i = 0; i < 5; i++)
+ for (int j = 0, b = g[i]; b; j++, b >>= 1)
+ if (b & 1) rect(x + n * 6 * k + i * k + o, y + j * k + o, k, k, pass ? c : 0, pass ? 32 : 20);
+ }
+}
+static void ctext(const char *s, int y, int k, color c) { text(s, 160 - tw(s, k) / 2, y, k, c); } /* centred */
+
+static void mini_glyph(int g, int x, int y, int kx, int ky, color c) {
+ for (int j = 0; j < 5; j++)
+ for (int i = 0; i < 3; i++)
+ if (mini[g] >> (14 - j * 3 - i) & 1) fill(x + i * kx, y + j * ky, kx, ky, c);
+}
+static char *cat(char *o, const char *t) {
+ while ((*o = *t++)) o++;
+ return o;
+}
+static char *itoa_(char *o, int32_t v) {
+ char t[12];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+/* a number in blocky figures along the top, at least `pad` of them, from x
+ (or ending at x when right-aligned) */
+static void figures(int32_t v, int pad, int x, color c, bool right) {
+ char s[12];
+ int n = (int)(itoa_(s, v) - s), z = imax(pad - n, 0), all = n + z;
+ if (right) x -= all * 16 - 4;
+ for (int i = 0; i < all; i++) mini_glyph(i < z ? 0 : s[i - z] - '0', x + i * 16, 4, 4, 4, c);
+}
+
+/* ------------------------------------------------------------------ the scene */
+static color bg_lo, bg_mid, bg_hi; /* Arcade+ backgrounds, a colour per round */
+static bool fancy(void) { return mode == ARCADE && !demo; }
+
+static void background(void) {
+ if (!fancy()) {
+ for (color *p = buf, *e = buf + rw * (ry1 - ry0); p < e; p++) *p = 0;
+ return;
+ }
+ /* bevelled tiles, turned into diamonds every other round: a row of one
+ tile, repeated */
+ for (int y = ry0; y < ry1; y++) {
+ color *p = buf + (y - ry0) * rw, t[16];
+ int v = (y - FY0) & 15;
+ for (int u = 0; u < 16; u++) {
+ int d = iabs(u - 8) + iabs(v - 8);
+ t[u] = round_no & 1 ? (d == 8 ? bg_hi : d == 7 || d < 2 ? bg_lo : bg_mid)
+ : !u || !v ? bg_hi : u == 15 || v == 15 ? bg_lo : bg_mid;
+ }
+ for (int x = rx0; x < rx1; x++) *p++ = y >= FY0 && x >= FX0 && x < FX1 ? t[(x - FX0) & 15] : 0;
+ }
+}
+
+static color pipe_shade(int i, int n) { /* a metal pipe, lit from the top left */
+ int t = i * 2 - n / 2;
+ return mix(RGB(0xECF0FA), RGB(0x2A3244), imin(iabs(t) * 32 / n + 2, 32));
+}
+static void walls(void) {
+ int ox = sx, oy = sy;
+ if (!fancy()) {
+ fill(ox, oy + TOP, W, 8, GRAY);
+ for (int e = 0; e <= FX1; e += FX1) /* both sides, with the arcade's blue strip where the paddle plays */
+ fill(ox + e, oy + TOP, FX0, H - TOP, GRAY), fill(ox + e, oy + PY - 8, FX0, 22, BLUE);
+ return;
+ }
+ for (int i = 0; i < 8; i++) fill(ox, oy + TOP + i, W, 1, pipe_shade(i, 8));
+ for (int x = 40; x < W; x += 80) rect(ox + x, oy + TOP, 3, 8, 0, 14);
+ for (int e = 0; e <= FX1; e += FX1) {
+ for (int i = 0; i < FX0; i++) fill(ox + e + i, oy + FY0, 1, H - FY0, pipe_shade(i, FX0));
+ for (int y = FY0 + 36; y < H; y += 56) /* joints, with a lamp */
+ rect(ox + e, oy + y, FX0, 3, 0, 14), fill(ox + e + 3, oy + y + 7, 4, 10, RGB(0x2A60D0));
+ }
+ if (warp) { /* the way out, blinking */
+ fill(ox + FX1, oy + PY - 10, FX0, 22, 0);
+ for (int j = 0; j < 3; j++)
+ rect(ox + FX1 + 2, oy + PY - 7 + j * 6, 6, 3, RGB(0xF058D0), ((tk >> 3) + j) % 3 ? 10 : 32);
+ }
+}
+
+static void draw_brick(int r, int c, int x, int y) {
+ uint8_t v = brick[r][c];
+ int k = v & 15, f = v >> 6;
+ color col = kcol[k];
+ if (!fancy()) {
+ fill(x, y + 1, CW - 2, CH - 2, col);
+ return;
+ }
+ fill(x, y, CW - 1, CH - 1, col);
+ rect(x, y, CW - 1, 1, WHITE, k >= K_SILVER ? 22 : 14);
+ rect(x, y + 1, 1, CH - 2, WHITE, 8);
+ rect(x + 1, y + CH - 2, CW - 2, 1, 0, 12);
+ rect(x + CW - 2, y + 1, 1, CH - 2, 0, 10);
+ if (k >= K_SILVER) rect(x + 3, y + 2, 3, 2, WHITE, 24); /* a shine */
+ if (f) rect(x + (3 - f) * 6, y, 6, CH - 1, WHITE, 24); /* a glint runs across when hit */
+}
+static void bricks(void) {
+ int ox = bx + FX0, oy = by + BY0;
+ int r0 = imax((ry0 - oy - CH - 3) / CH, 0), r1 = imin((ry1 - oy) / CH + 1, rows_shown);
+ int c0 = imax((rx0 - ox - CW - 3) / CW, 0), c1 = imin((rx1 - ox) / CW + 1, COLS);
+ if (ry1 <= oy - 4) return;
+ cx0 = imax(rx0, FX0), cx1 = imin(rx1, FX1); /* shaken bricks slide under the walls */
+ if (fancy()) /* shadows first, so the bricks cover the ones that fall on bricks */
+ for (int r = r0; r < r1; r++)
+ for (int c = c0; c < c1; c++)
+ if (brick[r][c]) rect(ox + c * CW + 3, oy + r * CH + 3, CW - 1, CH - 1, 0, 15);
+ for (int r = r0; r < r1; r++)
+ for (int c = c0; c < c1; c++)
+ if (brick[r][c]) draw_brick(r, c, ox + c * CW, oy + r * CH);
+ cx0 = rx0, cx1 = rx1;
+}
+
+static bool paddle_shown(void) { return state != S_LOST && (state != S_OVER || won); }
+static void paddle(void) {
+ if (!paddle_shown()) return;
+ int x = ((px + ONE / 2) >> 8) - pw / 2 + sx, y = PY + sy;
+ if (!seen(x, y - 3, pw, 10)) return;
+ if (!fancy()) {
+ fill(x, y, pw, 4, BLUE);
+ return;
+ }
+ /* the Vaus: a silver capsule with red ends, lit from above */
+ static const uint8_t inset[7] = {2, 1, 0, 0, 0, 1, 2}, lit[7] = {20, 31, 25, 18, 12, 7, 3};
+ for (int j = 0; j < 7; j++) {
+ int i = inset[j];
+ color red = mix(RGB(0xFF6060), RGB(0x400808), lit[j]);
+ fill(x + i, y + j, pw - 2 * i, 1, mix(WHITE, RGB(0x303848), lit[j]));
+ fill(x + i, y + j, 7 - i, 1, red);
+ fill(x + pw - 7, y + j, 7 - i, 1, red);
+ }
+ rect(x + 7, y + 1, 1, 5, 0, 12);
+ rect(x + pw - 8, y + 1, 1, 5, 0, 12);
+ rect(x + pw / 2 - 3, y + 2, 6, 3, RGB(0x40A0F8), power == P_CATCH ? 32 : 12);
+ if (power == P_LASER) { /* two cannons */
+ fill(x + 2, y - 3, 3, 3, RGB(0x505868));
+ fill(x + pw - 5, y - 3, 3, 3, RGB(0x505868));
+ }
+}
+
+/* in the arcade, colour came from strips of film on the screen: the ball
+ takes the colour of the rows it flies through */
+static color ball_col(int y) {
+ if (fancy()) return RGB(0xE8F0FF);
+ if (y + 2 >= PY - 8) return BLUE;
+ int r = (y + 2 - BY0) / CH;
+ if (!demo && y + 2 >= BY0 + CH && r <= 8) return kcol[(r + 1) / 2];
+ return WHITE;
+}
+static void balls(void) {
+ for (int i = 0; i < NBALL; i++) {
+ ball_t *b = &ball[i];
+ if (!b->on) continue;
+ if (sv.trail && !b->stuck)
+ for (int t = 2; t >= 0; t--) {
+ int s = BS - 1 - t / 2;
+ rect(b->tx[t] + sx + (BS - s) / 2, b->ty[t] + sy + (BS - s) / 2, s, s, ball_col(b->ty[t]), 16 - t * 5);
+ }
+ int x = (b->x >> 8) + sx, y = (b->y >> 8) + sy;
+ color c = ball_col(b->y >> 8);
+ if (!fancy()) {
+ fill(x, y, BS, BS, c);
+ } else {
+ fill(x + 1, y, BS - 2, BS, c);
+ fill(x, y + 1, BS, BS - 2, c);
+ fill(x + BS - 2, y + BS - 2, 1, 1, RGB(0x8090B0));
+ fill(x + 1, y + 1, 1, 1, WHITE);
+ }
+ }
+}
+
+static void things(void) {
+ if (cap.on) { /* a capsule: a little lit pill with its letter, and a shine going round */
+ static const uint8_t inset[8] = {2, 1, 0, 0, 0, 0, 1, 2}, lit[8] = {14, 8, 0, 0, 4, 9, 14, 18};
+ int x = cap.x + sx, y = cap.y + sy, sh = (st_t >> 1) & 31;
+ color c = cap_col[cap.type];
+ for (int j = 0; j < 8; j++)
+ fill(x + inset[j], y + j, 16 - 2 * inset[j], 1, j < 2 ? mix(WHITE, c, lit[j]) : mix(0, c, lit[j]));
+ if (sh < 14) rect(x + 1 + sh, y + 1, 2, 6, WHITE, 12);
+ mini_glyph(cap_letter[cap.type], x + 7, y + 2, 1, 1, mix(0, c, 20));
+ mini_glyph(cap_letter[cap.type], x + 6, y + 1, 1, 1, WHITE);
+ }
+ for (int i = 0; i < NSHOT; i++)
+ if (shot[i].on) {
+ fill(shot[i].x + sx, shot[i].y + sy, 2, 7, RGB(0xFF5030));
+ fill(shot[i].x + sx, shot[i].y + sy, 2, 3, RGB(0xFFF0A0));
+ }
+ for (int i = 0; i < NPART; i++) {
+ part_t *p = &part[i];
+ if (p->life) rect((p->x >> 4) + sx, (p->y >> 4) + sy, 2, 2, p->c, 8 + 24 * p->life / p->max);
+ }
+}
+
+static void hud(void) {
+ if (ry0 >= TOP) return;
+ int32_t best = (int32_t)sv.best[mode] > score ? (int32_t)sv.best[mode] : score;
+ if (mode == CLASSIC) { /* score, ball, best: like the arcade's two scores and ball; the
+ title shows the last game's score, as arcades do */
+ figures(score, 3, 18, GRAY, false);
+ if (!demo) figures(4 - imax(lives, 1), 1, 154, GRAY, false);
+ figures(best, 3, 302, mix(GRAY, 0, 18), true);
+ return;
+ }
+ char s[12] = "HI ";
+ figures(score, 1, 18, WHITE, false);
+ int x = 160 - (round_no >= 9 ? 31 : 23);
+ text("ROUND", x, 17, 1, RGB(0xF05050));
+ figures(round_no + 1, 1, x + 34, RGB(0xF05050), false);
+ itoa_(s + 3, best);
+ text(s, 302 - tw(s, 1), 4, 1, RGB(0xA0A0A0));
+ for (int i = 0; i < imin(lives - 1, 6); i++) { /* spare lives, as little paddles */
+ int x = 294 - i * 13;
+ fill(x, 16, 10, 4, RGB(0xB8C0CC));
+ fill(x, 16, 2, 4, RGB(0xE03030));
+ fill(x + 8, 16, 2, 4, RGB(0xE03030));
+ }
+}
+
+/* ------------------------------------------------------------------ overlays */
+static const char *const diff_names[3] = {"EASY", "NORMAL", "HARD"};
+
+/* where each screen's text is, so a change redraws only that */
+static void ui_area(int s) {
+ if (s <= S_SET) mark(20, 100, 300, 214);
+ else if (s < S_PAUSE) mark(40, 146, 280, 196); /* the banner */
+ else full = true; /* a menu over the dimmed game */
+}
+
+static void panel(int x, int y, int w, int h) {
+ fill(x, y, w, h, GRAY);
+ fill(x + 3, y + 3, w - 6, h - 6, 0);
+}
+static void item(const char *s, int cy, bool on) {
+ if (on) {
+ fill(100, cy - 4, 120, 22, BLUE);
+ }
+ ctext(s, cy, 2, on ? WHITE : DIM);
+}
+
+static void logo(void) {
+ /* BREAKOUT in bold letters built of bricks, in the four colours of the wall */
+ static const char name[] = "BREAKOUT";
+ int x0 = 23, y0 = 46;
+ if (!seen(x0, y0, 275, 42)) return;
+ for (int n = 0; n < 8; n++) {
+ const uint8_t *g = font[name[n] - 32];
+ for (int i = 0; i < 6; i++) {
+ int b = (i < 5 ? g[i] : 0) | (i ? g[i - 1] : 0);
+ for (int j = 0; j < 7; j++)
+ if (b >> j & 1) fill(x0 + (n * 7 + i) * 5, y0 + j * 6, 5, 5, kcol[1 + j * 4 / 7]);
+ }
+ }
+ for (int j = 0; j < 7; j++) /* the mortar between bricks */
+ for (int x = x0 + (j & 1) * 5 + 9; x < x0 + 275; x += 10) fill(x, y0 + j * 6, 1, 5, 0);
+}
+
+static void overlay(void) {
+ char s[24];
+ if (state == S_TITLE || state == S_SET) {
+ logo();
+ if (state == S_TITLE) {
+ static const char *const items[3] = {"CLASSIC", "ARCADE+", "SETTINGS"};
+ for (int i = 0; i < 3; i++) item(items[i], 108 + i * 28, tsel == i);
+ char *o = s;
+ if (tsel == 1) /* the round to start from, among those reached */
+ o = cat(itoa_(cat(s, sv.reached > 1 ? "< ROUND " : "ROUND "), start_round), sv.reached > 1 ? " > " : " ");
+ itoa_(cat(o, "BEST "), (int32_t)sv.best[tsel & 1]);
+ if (tsel < 2) ctext(s, 198, 1, DIM);
+ } else {
+ static const char *const names[3] = {"DIFFICULTY", "SCREEN SHAKE", "BALL TRAIL"};
+ for (int i = 0; i < 3; i++) {
+ color c = sel == i ? WHITE : DIM;
+ if (sel == i) fill(24, 104 + i * 28, 272, 22, BLUE);
+ text(names[i], 32, 108 + i * 28, 2, c);
+ const char *v = i == 0 ? diff_names[sv.diff] : (i == 1 ? sv.shake : sv.trail) ? "ON" : "OFF";
+ text(v, 288 - tw(v, 2), 108 + i * 28, 2, c);
+ }
+ ctext("LEFT/RIGHT: CHANGE BACK: DONE", 198, 1, DIM);
+ }
+ return;
+ }
+ if (state == S_CLEAR) ctext(mode == CLASSIC ? "WALL CLEARED" : warp ? "WARP!" : "ROUND CLEAR", 152, 2, WHITE);
+ if (state == S_READY && !demo) {
+ itoa_(cat(s, mode == CLASSIC ? (wall == 2 ? "WALL 2 BALL " : "BALL ") : "ROUND "),
+ mode == CLASSIC ? 4 - lives : round_no + 1);
+ ctext(s, 152, 2, WHITE);
+ if (st_t > 20) ctext("OK: LAUNCH", 176, 1, DIM);
+ }
+ if (state == S_PAUSE) {
+ static const char *const items[3] = {"RESUME", "RESTART", "QUIT GAME"};
+ panel(84, 62, 152, 116);
+ ctext("PAUSED", 74, 2, kcol[K_YELLOW]);
+ for (int i = 0; i < 3; i++) item(items[i], 104 + i * 24, sel == i);
+ } else if (state == S_QUIT) {
+ panel(84, 74, 152, 92);
+ ctext("QUIT GAME?", 88, 2, WHITE);
+ for (int i = 0; i < 2; i++) {
+ int x = 102 + i * 62;
+ if (sel == i) fill(x, 124, 54, 24, i ? RGB(0xC84848) : BLUE);
+ text(i ? "YES" : "NO", x + 16 - i * 6, 129, 2, sel == i ? WHITE : DIM);
+ }
+ } else if (state == S_OVER) {
+ panel(50, 50, 220, 140);
+ ctext(won ? (mode == CLASSIC ? "YOU WIN!" : "ALL CLEAR!") : "GAME OVER", 64, 3, won ? RGB(0xA2E22A) : RGB(0xE05050));
+ itoa_(cat(s, "SCORE "), score);
+ ctext(s, 104, 2, WHITE);
+ itoa_(cat(s, "BEST "), (int32_t)sv.best[mode]);
+ if (fresh_best) cat(s, st_t & 16 ? "NEW BEST!" : "");
+ ctext(s, 128, 2, fresh_best ? kcol[K_YELLOW2] : DIM);
+ ctext("OK: PLAY AGAIN BACK: MENU", 166, 1, DIM);
+ }
+}
+
+/* one area of the screen, in layers */
+static void render(void) {
+ background();
+ walls();
+ bricks();
+ things();
+ paddle();
+ balls();
+ hud();
+ if (state >= S_PAUSE) /* dimmed under a menu */
+ for (color *p = buf, *e = buf + rw * (ry1 - ry0); p < e; p++) *p = (color)((*p >> 1 & 0x7BEF) + (*p >> 2 & 0x39E7));
+ overlay();
+}
+
+static void flush(void) {
+ if (full) ndirty = 0, mark(0, 0, W, H), full = false;
+ for (int i = 0; i < ndirty; i++) {
+ rect_t r = dirty[i];
+ int w = r.x1 - r.x0, band = BUFN / w;
+ for (int y = r.y0; y < r.y1; y += band) {
+ cx0 = rx0 = r.x0, cx1 = rx1 = r.x1, ry0 = y, ry1 = imin(y + band, r.y1), rw = w;
+ render();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)rx0, (uint16_t)ry0, (uint16_t)w, (uint16_t)(ry1 - ry0)}, buf);
+ }
+ }
+ ndirty = 0;
+}
+
+/* everything that moves, where it is now (called before and after moving) */
+static int paddle_key, paddle_mx;
+static void mark_moving(void) {
+ for (int i = 0; i < NBALL; i++) {
+ ball_t *b = &ball[i];
+ if (!b->on) continue;
+ int x0 = b->x >> 8, y0 = b->y >> 8, x1 = x0 + BS, y1 = y0 + BS;
+ if (sv.trail)
+ for (int t = 0; t < 3; t++)
+ x0 = imin(x0, b->tx[t]), y0 = imin(y0, b->ty[t]), x1 = imax(x1, b->tx[t] + BS), y1 = imax(y1, b->ty[t] + BS);
+ mark_at(x0, y0, x1 - x0, y1 - y0);
+ }
+ if (cap.on) mark_at(cap.x, cap.y, 16, 8);
+ for (int i = 0; i < NSHOT; i++)
+ if (shot[i].on) mark_at(shot[i].x, shot[i].y, 2, 7);
+ for (int i = 0; i < NPART; i++)
+ if (part[i].life) mark_at(part[i].x >> 4, part[i].y >> 4, 2, 2);
+ /* the paddle, only when it changed: where it was drawn, and where it is */
+ int x = (px + ONE / 2) >> 8, key = x | pw << 9 | power << 16 | paddle_shown() << 18 | (sx + 8) << 20 | (sy + 8) << 25;
+ if (key != paddle_key) {
+ x -= pw / 2;
+ mark(paddle_mx, PY - 3 - 4, paddle_mx + (paddle_key >> 9 & 127) + 8, PY + 7 + 4);
+ mark_at(x, PY - 3, pw, 10);
+ paddle_key = key, paddle_mx = x + sx - 4;
+ }
+}
+
+/* ------------------------------------------------------------------ effects */
+/* n sparks flying out of an area; f: how hard, in 16ths of a pixel a tick */
+static void burst(int x, int y, int w, int h, color c, int n, int f) {
+ static int next;
+ while (n--) {
+ part_t *p = &part[next];
+ next = (next + 1) % NPART;
+ if (p->life) mark_at(p->x >> 4, p->y >> 4, 2, 2);
+ p->x = (int16_t)((x + rndi(w)) * 16), p->y = (int16_t)((y + rndi(h)) * 16);
+ p->vx = (int8_t)(rndi(2 * f + 1) - f), p->vy = (int8_t)(rndi(2 * f + 1) - f * 13 / 10);
+ p->c = c;
+ p->max = p->life = (uint8_t)(16 + rndi(20));
+ }
+}
+static void shake(int a, int t) {
+ if (!sv.shake) return;
+ shake_a = imax(shake_a, a), shake_t = imax(shake_t, t), shake_all |= a > 2;
+}
+
+/* ------------------------------------------------------------------ rules */
+static int isqrt(int v) { return (int)__builtin_sqrtf((float)v); }
+static void set_speed(int s) {
+ spd = s;
+ for (int i = 0; i < NBALL; i++) {
+ ball_t *b = &ball[i];
+ int l = isqrt(b->vx * b->vx + b->vy * b->vy);
+ if (l) b->vx = b->vx * s / l, b->vy = b->vy * s / l;
+ }
+}
+static int diff_k(void) { return sv.diff == 0 ? 82 : sv.diff == 2 ? 118 : 100; } /* percent */
+static void classic_speed(void) { /* faster after 4 and 12 hits, and at the orange and red rows */
+ set_speed(spd0 * (100 + 17 * ((hits >= 4) + (hits >= 12) + got_orange + got_red)) / 100);
+}
+
+static int base_width(void) { return (mode == ARCADE ? 40 : 38) + (sv.diff == 0 ? 8 : sv.diff == 2 ? -6 : 0); }
+
+static void load_wall(void) {
+ bricks_left = 0;
+ for (int r = 0; r < ROWS; r++)
+ for (int c = 0; c < COLS; c++) {
+ int k = 0;
+ if (demo) {
+ } else if (mode == CLASSIC) {
+ if (r >= 1 && r <= 8) k = (r + 1) / 2;
+ } else {
+ const round_t *rd = &rounds[round_no];
+ int v = rd->row[r] >> 2 * (c < 8 ? c : 14 - c) & 3;
+ if (v) k = rd->pal >> 4 * (v - 1) & 15;
+ if (k == K_RAINBOW) k = rainbow[r];
+ }
+ int hp = k == K_SILVER ? 2 + (round_no >= 6) : 1;
+ brick[r][c] = (uint8_t)(k ? k | hp << 4 : 0);
+ bricks_left += k && k != K_GOLD;
+ }
+ rows_shown = 0;
+ if (mode == ARCADE) { /* this round's background colour */
+ static const uint32_t hue[4] = {0x14286C, 0x0C4A3A, 0x4A1848, 0x3A2A10};
+ color b = RGB(hue[round_no & 3]);
+ bg_mid = mix(b, 0, 16), bg_hi = mix(b, 0, 22), bg_lo = mix(b, 0, 8);
+ }
+}
+
+static void ball_tick(ball_t *b);
+static void serve(void) { /* a new ball, on the paddle */
+ for (int i = 0; i < NBALL; i++) ball[i].on = 0;
+ ball_t *b = &ball[0];
+ b->on = b->stuck = 1;
+ b->off = (int16_t)(demo ? 0 : rndi(9) - 4);
+ b->vx = 154, b->vy = -ONE;
+ pw = pw_to = base_width(), demo_aim = 0;
+ power = P_NONE;
+ if (warp) warp = 0, mark_at(FX1, PY - 10, FX0, 22); /* the gate closes */
+ cap.on = 0;
+ for (int i = 0; i < NSHOT; i++) shot[i].on = 0;
+ if (mode == CLASSIC) {
+ hits = 0, got_orange = got_red = shrunk = false;
+ spd0 = 589 * diff_k() / 100; /* 2.3 pixels a tick */
+ classic_speed();
+ } else {
+ spd0 = (538 + 20 * imin(round_no, 10)) * diff_k() / 100;
+ set_speed(spd0);
+ }
+ ball_tick(b);
+}
+
+static void set_state(int s) {
+ ui_area(state);
+ state = s, st_t = 0, sel = 0;
+ ui_area(state);
+}
+
+static void start_round_(void) {
+ load_wall();
+ serve();
+ set_state(S_READY);
+ if (mode == ARCADE && round_no + 1 > sv.reached) sv.reached = (uint8_t)(round_no + 1), save();
+}
+
+static void new_game(int m) {
+ mode = m, demo = false;
+ score = 0, lives = 3, wall = 1, fresh_best = false, won = false;
+ round_no = m == ARCADE ? start_round - 1 : 0;
+ for (int i = 0; i < NPART; i++) part[i].life = 0;
+ px = (FX0 + FX1) / 2 * ONE;
+ start_round_();
+ full = true;
+}
+
+static void title(void) {
+ mode = CLASSIC, demo = true;
+ load_wall();
+ serve();
+ set_state(S_TITLE);
+ full = true;
+}
+
+/* keeps the best score, for a finished or abandoned game */
+static void keep_best(void) {
+ if (!demo && (uint32_t)score > sv.best[mode]) sv.best[mode] = (uint32_t)score, fresh_best = true;
+ save();
+}
+
+static void add_score(int n) {
+ score += n;
+ if (score > 999999) score = 999999;
+ mark(0, 0, W, TOP);
+}
+
+#ifndef CAP_CHANCE
+#define CAP_CHANCE 22 /* percent of bricks that drop a capsule */
+#endif
+static void drop_capsule(int x, int y) {
+ if (cap.on || rndi(100) >= CAP_CHANCE) return;
+ int r = rndi(100), t = 0;
+ while (r >= cap_odds[t]) r -= cap_odds[t++];
+ if (t == 4 && (ball[1].on || ball[2].on)) t = 3;
+ cap = (thing_t){(int16_t)(x + 2), (int16_t)y, 1, (uint8_t)t};
+}
+
+static void hit_brick(int r, int c) {
+ uint8_t v = brick[r][c];
+ int k = v & 15, hp = v >> 4 & 3;
+ mark_cell(r, c);
+ if (k == K_GOLD || hp > 1) { /* it holds, and shines */
+ brick[r][c] = (uint8_t)(k | (k == K_GOLD ? hp : hp - 1) << 4 | 3 << 6);
+ shake(1, 3);
+ return;
+ }
+ brick[r][c] = 0;
+ bricks_left--;
+ int x = FX0 + c * CW, y = BY0 + r * CH;
+ burst(x, y, CW - 2, CH - 2, kcol[k], 9, 22);
+ shake(1 + (k >= K_SILVER), 5);
+ if (demo) return;
+ if (mode == CLASSIC) {
+ add_score(9 - 2 * k);
+ hits++;
+ if (k == K_ORANGE) got_orange = true;
+ if (k == K_RED) got_red = true;
+ classic_speed();
+ } else {
+ add_score(k == K_SILVER ? 50 * (round_no + 1) : 50 + 10 * (k - K_WHITE));
+ if (k != K_SILVER) drop_capsule(x, y);
+ }
+}
+
+/* the brick under the ball, if any: hit it */
+static bool hit_bricks(const ball_t *b) {
+ int x0 = (b->x >> 8) - FX0, y0 = (b->y >> 8) - BY0;
+ if (y0 + BS <= 0 || y0 >= ROWS * CH) return false;
+ for (int r = imax(y0, 0) / CH; r <= imin(y0 + BS - 1, ROWS * CH - 1) / CH; r++)
+ for (int c = imax(x0, 0) / CW; c <= imin(x0 + BS - 1, COLS * CW - 1) / CW; c++)
+ if (brick[r][c]) {
+ hit_brick(r, c);
+ return true;
+ }
+ return false;
+}
+
+/* a: the angle from straight up, in 256ths of a radian (a sine good to 1 %) */
+static void aim(ball_t *b, int a) {
+ int a2 = a * a / 256, s = a * (256 - a2 * (256 - a2 / 20) / 1536) / 256;
+ b->vx = spd * s / 256, b->vy = -spd * isqrt(65536 - s * s) / 256;
+}
+static int untouched; /* ticks since a ball last met the paddle */
+/* Long without the paddle, a bounce turns the ball about 6 degrees, so it
+ can't loop forever between the walls and gold bricks. */
+static void nudge(ball_t *b) {
+ if (untouched < 600) return;
+ untouched = 420;
+ for (int k = 0, t = rndi(2) ? 25 : -25; k < 2; k++, t = -t) {
+ int vx = (b->vx * 255 - b->vy * t) / 256, vy = (b->vy * 255 + b->vx * t) / 256;
+ if (iabs(vx) * 256 <= spd * 228 && iabs(vy) * 256 >= spd * 60) {
+ b->vx = vx, b->vy = vy;
+ return;
+ }
+ }
+}
+static void launch(ball_t *b) {
+ untouched = 0;
+ b->stuck = 0;
+ int o = b->off * 256 / (pw / 2);
+ aim(b, (o < 0 ? -90 : 90) + o / 2);
+}
+
+static void lose_life(void) {
+ shake(4, 14);
+ burst((px >> 8) - pw / 2, PY, pw, 5, fancy() ? RGB(0xC0C8D8) : BLUE, 16, 35);
+ set_state(S_LOST);
+}
+
+static void ball_tick(ball_t *b) {
+ for (int t = 2; t > 0; t--) b->tx[t] = b->tx[t - 1], b->ty[t] = b->ty[t - 1];
+ b->tx[0] = (int16_t)(b->x >> 8), b->ty[0] = (int16_t)(b->y >> 8);
+ if (b->stuck) {
+ int x = (px >> 8) + b->off - BS / 2;
+ x = x < FX0 ? FX0 : x > FX1 - BS ? FX1 - BS : x;
+ b->x = x * ONE, b->y = (PY - BS) * ONE;
+ for (int t = 0; t < 3; t++) b->tx[t] = (int16_t)x, b->ty[t] = PY - BS;
+ return;
+ }
+ int n = imax(iabs(b->vx), iabs(b->vy)) / ONE + 1; /* steps of a pixel at most */
+ for (int i = 0; i < n; i++) {
+ int dx = b->vx / n, dy = b->vy / n;
+ b->x += dx;
+ if (b->x < FX0 * ONE) b->x = FX0 * ONE, b->vx = iabs(b->vx), nudge(b);
+ else if (b->x > (FX1 - BS) * ONE) b->x = (FX1 - BS) * ONE, b->vx = -iabs(b->vx), nudge(b);
+ else if (hit_bricks(b)) b->x -= dx, b->vx = -b->vx, nudge(b);
+ b->y += dy;
+ if (b->y < FY0 * ONE) {
+ b->y = FY0 * ONE, b->vy = iabs(b->vy), nudge(b);
+ if (mode == CLASSIC && !demo && !shrunk) { /* broke through: the paddle shrinks to half */
+ shrunk = true, pw_to = base_width() / 2;
+ shake(2, 8);
+ }
+ } else if (hit_bricks(b)) {
+ b->y -= dy, b->vy = -b->vy, nudge(b);
+ }
+ int half = pw * ONE / 2, bot = b->y + BS * ONE, mid = b->x + BS * ONE / 2 - px;
+ if (b->vy > 0 && bot >= PY * ONE && bot - dy <= (PY + 1) * ONE && mid > -half - BS * ONE / 2 &&
+ mid < half + BS * ONE / 2) { /* the paddle: where it lands decides where it goes */
+ b->y = (PY - BS) * ONE, untouched = 0;
+ if (mode == ARCADE && !demo && spd < spd0 * 17 / 10) spd = spd * 65 / 64;
+ if (power == P_CATCH) {
+ b->stuck = 1, b->off = (int16_t)(mid / ONE), catch_t = 0;
+ } else { /* up to 1.1 radians off vertical, and never too steep */
+ int a = mid * 282 / (half + BS * ONE / 2);
+ if (a > -56 && a < 56) a = b->vx < 0 ? -56 : 56;
+ aim(b, a);
+ }
+ demo_aim = rndi(pw * 4 / 5 + 1) - pw * 2 / 5;
+ return;
+ }
+ if (b->y > H * ONE) {
+ b->on = 0;
+ return;
+ }
+ }
+}
+
+static void clear_round(void) {
+ for (int i = 0; i < NBALL; i++) ball[i].on = 0;
+ for (int i = 0; i < NSHOT; i++) shot[i].on = 0;
+ cap.on = 0;
+ set_state(S_CLEAR);
+}
+
+static void catch_capsule(int t) {
+ add_score(1000);
+ burst(cap.x, PY - 2, 16, 4, cap_col[t], 8, 19);
+ if (t == 0) set_speed(spd0); /* slow */
+ if (t == 4) { /* three balls */
+ ball_t *b = &ball[0];
+ for (int i = 0; i < NBALL; i++)
+ if (ball[i].on) b = &ball[i];
+ b->stuck = 0;
+ int a = b->vx * 256 / spd;
+ for (int i = 0; i < NBALL; i++)
+ if (!ball[i].on) {
+ ball[i] = *b;
+ a += 128;
+ int t = a > 282 ? a - 564 : a;
+ if (t > -56 && t < 56) t = t < 0 ? -56 : 56; /* never steeper than the paddle sends it */
+ aim(&ball[i], t);
+ }
+ }
+ if (t == 5 && lives < 9) lives++, mark(0, 0, W, TOP);
+ if (t == 6) warp = 1, mark_at(FX1, PY - 10, FX0, 22);
+ if (t == 1 || t == 2 || t == 3) {
+ power = t == 1 ? P_CATCH : t == 2 ? P_LASER : P_ENLARGE;
+ pw_to = t == 3 ? base_width() * 8 / 5 : base_width();
+ } else if (t != 5) {
+ power = P_NONE, pw_to = base_width();
+ }
+ if (power != P_CATCH)
+ for (int i = 0; i < NBALL; i++)
+ if (ball[i].stuck && ball[i].on && state == S_PLAY) launch(&ball[i]);
+}
+
+/* one 60th of a second of play; d is the paddle's direction, fire is OK */
+static void play_tick(int d, bool fire) {
+ /* the paddle: a tap nudges it, holding speeds it up */
+ if (!d) pv = 0;
+ else if (pv * d <= 0) pv = d * 282;
+ else if ((pv += d * 115) * d > 7 * ONE) pv = d * 7 * ONE;
+ px += pv;
+ if (pw != pw_to) pw += pw < pw_to ? 1 : -1;
+ int lo = (FX0 * 2 + pw) * ONE / 2, hi = (FX1 * 2 - pw) * ONE / 2;
+ if (warp && d > 0 && px >= hi - ONE / 2 && state == S_PLAY) { /* out through the gate */
+ add_score(10000);
+ clear_round();
+ return;
+ }
+ if (px < lo) px = lo, pv = 0;
+ if (px > hi) px = hi, pv = 0;
+
+ if (demo ? ball[0].stuck : state == S_READY) {
+ ball_tick(&ball[0]);
+ if (rows_shown < ROWS && !(st_t & 1)) { /* the wall builds up, row by row */
+ mark_at(FX0 - 3, BY0 + rows_shown * CH - 3, COLS * CW + 6, CH + 7);
+ rows_shown++;
+ }
+ if (fire) {
+ launch(&ball[0]);
+ if (rows_shown < ROWS) rows_shown = ROWS, full = true;
+ if (!demo) set_state(S_PLAY);
+ }
+ return;
+ }
+ if (!demo && state != S_PLAY) return;
+ int alive = 0;
+ for (int i = 0; i < NBALL; i++)
+ if (ball[i].on) {
+ ball_tick(&ball[i]);
+ alive += ball[i].on;
+ }
+ if (!alive) {
+ if (demo) serve();
+ else lose_life();
+ return;
+ }
+ /* catch: OK lets go, or it goes by itself */
+ if (power == P_CATCH)
+ for (int i = 0; i < NBALL; i++)
+ if (ball[i].on && ball[i].stuck && (fire || ++catch_t > 150)) launch(&ball[i]);
+ if (power == P_LASER && fire && laser_cd <= 0) {
+ int x = (px >> 8) - pw / 2;
+ for (int k = 0, i = 0; k < 2 && i < NSHOT; i++)
+ if (!shot[i].on) shot[i] = (thing_t){(int16_t)(k++ ? x + pw - 5 : x + 3), PY - 9, 1, 0};
+ laser_cd = 12;
+ }
+ laser_cd--;
+ for (int i = 0; i < NSHOT; i++) {
+ thing_t *s = &shot[i];
+ if (!s->on) continue;
+ s->y -= 6;
+ if (s->y < FY0) {
+ s->on = 0;
+ continue;
+ }
+ int r = (s->y - BY0) / CH, c = (s->x - FX0) / CW;
+ if (s->y >= BY0 && r < ROWS && brick[r][c]) hit_brick(r, c), s->on = 0;
+ }
+ if (cap.on && (cap.y += (st_t & 1) + 1) > H) cap.on = 0;
+ int pl = (px >> 8) - pw / 2;
+ if (cap.on && cap.y + 8 >= PY && cap.y <= PY + 6 && cap.x + 16 > pl && cap.x < pl + pw) {
+ cap.on = 0;
+ catch_capsule(cap.type);
+ }
+ if (!bricks_left && !demo) {
+ shake(3, 10);
+ clear_round();
+ }
+}
+
+/* the title screen's paddle plays by itself, after the lowest ball */
+static int demo_dir(void) {
+ ball_t *b = &ball[0];
+ for (int i = 1; i < NBALL; i++)
+ if (ball[i].on && (!b->on || ball[i].y > b->y)) b = &ball[i];
+ int dd = (b->x >> 8) + BS / 2 - demo_aim - (px >> 8);
+ return dd > 3 ? 1 : dd < -3 ? -1 : 0;
+}
+
+static void tick(int d, bool fire) {
+ st_t++, tk++, untouched++;
+ if (shake_t) {
+ shake_t--;
+ int a = imin(shake_a, shake_t / 2 + 1);
+ bx = shake_t ? rndi(2 * a + 1) - a : 0, by = shake_t ? rndi(2 * a + 1) - a : 0;
+ sx = shake_all ? bx : 0, sy = shake_all ? by : 0;
+ if (!shake_t) shake_a = 0, shake_all = false;
+ }
+ for (int r = 0; r < ROWS; r++) /* glints fade */
+ for (int c = 0; c < COLS; c++)
+ if (brick[r][c] >> 6 && !(st_t & 1)) brick[r][c] = (uint8_t)(brick[r][c] - 64), mark_cell(r, c);
+ for (int i = 0; i < NPART; i++) {
+ part_t *p = &part[i];
+ if (!p->life) continue;
+ p->x += p->vx, p->y += p->vy, p->vy += 2, p->vx -= p->vx / 16;
+ p->life--;
+ }
+ if (demo) d = demo_dir(), fire = !(st_t & 63);
+#ifdef AUTOPLAY /* a test build that plays by itself */
+ if (state == S_READY || state == S_PLAY) d = demo_dir(), fire = fire || !(st_t & 31);
+#endif
+ if (state == S_READY && st_t == 21) ui_area(S_READY); /* the hint shows up */
+ if (warp && !(tk & 7)) mark_at(FX1, PY - 10, FX0, 22); /* the gate's lights */
+ if (demo || state == S_READY || state == S_PLAY) play_tick(d, fire);
+ bool over = false;
+ if (state == S_LOST && st_t > 70) {
+ if (--lives > 0) serve(), set_state(S_READY), mark(0, 0, W, TOP);
+ else over = true;
+ }
+ if (state == S_CLEAR && st_t > 100) {
+ if (mode == CLASSIC ? wall == 2 : round_no + 1 == NROUNDS) won = over = true;
+ else wall++, round_no += mode == ARCADE, start_round_(), full = true;
+ }
+ if (over) keep_best(), set_state(S_OVER);
+}
+
+/* n ticks of play, and the areas they change */
+static void frame(int n, int d, bool fire) {
+ mark_moving();
+ int psx = sx, psy = sy, pbx = bx, pby = by;
+ while (n-- > 0) {
+ tick(d, fire);
+ fire = false;
+ }
+ mark_moving();
+ if (sx != psx || sy != psy) { /* the walls shake */
+ mark(0, TOP - 4, W, FY0 + 4);
+ mark(0, FY0, FX0 + 4, H);
+ mark(FX1 - 4, FY0, W, H);
+ }
+ if (bx != pbx || by != pby) { /* the bricks shake */
+ int r0 = ROWS, r1 = 0;
+ for (int r = 0; r < ROWS; r++)
+ for (int c = 0; c < COLS; c++)
+ if (brick[r][c]) r0 = imin(r0, r), r1 = r + 1;
+ if (r1) mark(FX0, BY0 + r0 * CH - 4, FX1, BY0 + r1 * CH + 8);
+ }
+}
+
+/* ------------------------------------------------------------------ menus */
+static bool leave, ask_title; /* Quit game: back to NumPlay (or the calculator) */
+static void menu_input(uint64_t hit) {
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);
+ int ud = (hit & KEY(eadk_key_down) ? 1 : 0) - (hit & KEY(eadk_key_up) ? 1 : 0);
+ int lr = (hit & KEY(eadk_key_right) ? 1 : 0) - (hit & KEY(eadk_key_left) ? 1 : 0);
+ int before = sel + tsel * 4 + start_round * 16;
+ switch (state) {
+ case S_TITLE:
+ tsel = (tsel + ud + 3) % 3;
+ if (tsel == 1 && lr) start_round = (start_round + lr + sv.reached - 1) % sv.reached + 1;
+ if (back) {
+ ask_title = true, sel = 0;
+ set_state(S_QUIT);
+ } else if (ok) {
+ if (tsel == 2) set_state(S_SET);
+ else new_game(tsel);
+ }
+ break;
+ case S_SET:
+ sel = (sel + ud + 3) % 3;
+ if (lr || ok) {
+ if (sel == 0) sv.diff = (uint8_t)((sv.diff + (lr ? lr : 1) + 3) % 3);
+ else if (sel == 1) sv.shake ^= 1;
+ else sv.trail ^= 1;
+ ui_area(S_SET);
+ }
+ if (back) {
+ save();
+ set_state(S_TITLE);
+ }
+ break;
+ case S_READY:
+ case S_PLAY:
+ if (back) resume_state = state, set_state(S_PAUSE);
+ break;
+ case S_PAUSE:
+ sel = (sel + ud + 3) % 3;
+ if (back || (ok && sel == 0)) {
+ state = resume_state, st_t = 30, full = true;
+ } else if (ok && sel == 1) {
+ keep_best();
+ new_game(mode);
+ } else if (ok) {
+ set_state(S_QUIT);
+ }
+ break;
+ case S_QUIT:
+ if (lr) sel ^= 1;
+ if ((back || (ok && !sel)) && ask_title) ask_title = false, title();
+ else if (back || (ok && !sel)) set_state(S_PAUSE), sel = 2;
+ else if (ok) {
+ keep_best();
+ leave = true;
+ }
+ break;
+ case S_OVER:
+ if (ok) new_game(mode);
+ else if (back) title();
+ break;
+ }
+ if (before != sel + tsel * 4 + start_round * 16) ui_area(state);
+}
+
+int main(void) {
+ np_app_begin();
+ load();
+ seed ^= (uint32_t)eadk_timing_millis() * 2654435761u;
+ title();
+ uint64_t ignore = eadk_keyboard_scan(), held = 0;
+ const uint64_t rep = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down);
+ uint32_t t0 = (uint32_t)eadk_timing_millis(), ticks = 0, frames = 0, repeat_at = 0;
+ for (;;) {
+ uint32_t now = (uint32_t)eadk_timing_millis();
+ uint64_t k = eadk_keyboard_scan();
+ ignore &= k; /* keys held from before start count once released */
+ k &= ~ignore;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ uint64_t hit = k & ~held;
+ held = k;
+ bool in_menu = state == S_TITLE || state == S_SET || state >= S_PAUSE;
+ if (hit & rep) repeat_at = now + 350;
+ else if (in_menu && (k & rep) && (int32_t)(now - repeat_at) >= 0) hit |= k & rep, repeat_at = now + 90;
+ int s = state;
+ menu_input(hit);
+ if (leave) break;
+ bool fire = s == state && (s == S_READY || s == S_PLAY) && (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_up)));
+ int d = (k & (KEY(eadk_key_right) | KEY(eadk_key_six)) ? 1 : 0) - (k & (KEY(eadk_key_left) | KEY(eadk_key_four)) ? 1 : 0);
+ /* the game runs 60 ticks a second, whatever the frame rate */
+ uint32_t due = (now - t0) * 3 / 50;
+ static bool fire_due; /* a press waits for a tick to use it */
+ if ((int32_t)(due - ticks) > 4) ticks = due - 4;
+ if (state < S_PAUSE) {
+ /* the ticks owed, or one ahead: every frame moves, and none twice as much */
+ int n = (int32_t)(due - ticks) > 0 ? (int)(due - ticks) : (int32_t)(ticks - due) < 1;
+ fire_due |= fire;
+ frame(n, d, fire_due);
+ if (n) fire_due = false;
+ ticks += (uint32_t)n;
+ } else {
+ ticks = due, fire_due = false;
+ st_t++;
+ if (state == S_OVER && !(st_t & 15) && fresh_best) mark(60, 124, 260, 148);
+ }
+ eadk_display_wait_for_vblank();
+ flush();
+ /* at most 60 frames a second */
+ frames++;
+ uint32_t next = t0 + frames * 50 / 3, after = (uint32_t)eadk_timing_millis();
+ if ((int32_t)(next - after) > 0) eadk_timing_msleep(next - after);
+ else if (after - next > 100) frames = (after - t0) * 3 / 50;
+ }
+ keep_best();
+ return np_app_end();
+}
diff --git a/games/connectfour/.gitignore b/games/connectfour/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/connectfour/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/connectfour/Makefile b/games/connectfour/Makefile
new file mode 100644
index 00000000..8cf2951b
--- /dev/null
+++ b/games/connectfour/Makefile
@@ -0,0 +1,51 @@
+# Connect 4 — the classic four-in-a-row, against a friend or the computer.
+# make build output/connectfour.nwa
+# make check link the app like the calculator does (output/connectfour.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/connectfour.nwa
+
+check: $(BUILD_DIR)/connectfour.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/connectfour.bin
+ @echo "BIN $(BUILD_DIR)/connectfour.bin: $$(wc -c < $(BUILD_DIR)/connectfour.bin) bytes"
+
+$(BUILD_DIR)/connectfour.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_connectfour_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_connectfour_main -o $@
diff --git a/games/connectfour/README.md b/games/connectfour/README.md
new file mode 100644
index 00000000..6b727f9c
--- /dev/null
+++ b/games/connectfour/README.md
@@ -0,0 +1,38 @@
+> **Connect 4 is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `ConnectFour.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+# Connect 4
+
+The classic four-in-a-row game for the NumWorks calculator. Drop red and yellow discs into the blue grid; the first to line up four, across, down or diagonally, wins.
+
+<img src="docs/shot.png" width="320" alt="A game in progress on the blue grid">
+
+- **Against a friend or the computer**, at three levels. Weak makes mistakes, Normal looks a few moves ahead, and Strong is hard to beat: it thinks for up to a second and knows the row-parity rules that decide endgames.
+- **Two or three players.** Three players (red, yellow and green) play on a wider grid, 8 columns instead of 7. Against the computer, you play red against two of them.
+- **The real thing**: the blue plastic grid with its round holes and stand, discs with a raised rim that fall behind the grid with a little bounce, the winning four lit up, and all the discs dropping out of the bottom before the next round.
+- **A tally** of wins for each player, kept between sessions (it starts over when you change the opponent, the players or the level). Who starts takes turns each round.
+- **Undo** a move you regret, and a **dark theme**.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Left / Right | Choose a column |
+| OK, Down or EXE | Drop the disc |
+| 1 to 8 | Drop straight into that column |
+| ⌫ | Undo (against the computer: your last move and its answer) |
+| Back | Pause: Resume, Undo move, Restart, Quit game |
+| Home | Leave |
+
+In the menu, Up and Down pick a line and Left / Right change it.
+
+## Credits
+
+Rewritten in C for NumPlay from **[Tatone26](https://github.com/Tatone26)**'s version in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/connectfour) (All the Apps), which is released into the public domain ([UNLICENSE](UNLICENSE)). Its modes are all here: solo or not, two or three players on the same grid sizes, three computer levels, and the dark mode. What changed:
+
+- It looks like the Milton Bradley / Hasbro game (invented by Howard Wexler and Ned Strongin, 1974): the blue grid and stand, embossed discs that fall with gravity, instead of flat discs on a plain grid.
+- A new computer player: bitboards, alpha-beta search with a transposition table, moves that make threats tried first, and an evaluation that knows which rows win endgames. It answers in under a second (the original's strongest level could take many seconds), and a disc sways over the board while it thinks.
+- Undo, a tally of wins, alternating first player, the winning four highlighted, the discs dropping out between rounds, a pause menu, and saved settings.
+
+## Build
+
+`make` (needs `arm-none-eabi-gcc` and Node.js for nwlink) writes `output/connectfour.nwa`.
diff --git a/games/connectfour/UNLICENSE b/games/connectfour/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/connectfour/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/connectfour/docs/shot.png b/games/connectfour/docs/shot.png
new file mode 100644
index 00000000..060daa4a
Binary files /dev/null and b/games/connectfour/docs/shot.png differ
diff --git a/games/connectfour/src/icon.png b/games/connectfour/src/icon.png
new file mode 100644
index 00000000..fc3e0ec1
Binary files /dev/null and b/games/connectfour/src/icon.png differ
diff --git a/games/connectfour/src/main.c b/games/connectfour/src/main.c
new file mode 100644
index 00000000..53c7964e
--- /dev/null
+++ b/games/connectfour/src/main.c
@@ -0,0 +1,978 @@
+/* Connect 4: drop discs into the blue grid, four in a row wins. Against a
+ * friend or the computer (three levels), with two or three players.
+ *
+ * Nothing is a bitmap. Each pixel of a changed rectangle is worked out from
+ * the board, the discs and the moving disc (a falling disc is behind the
+ * plastic, so it only shows through the holes, like the real one), text is
+ * laid on top, and the rectangle goes to the screen in bands of a small
+ * buffer. The computer searches with bitboards (alpha-beta, a transposition
+ * table, threats and row parity), and gives up thinking after ~0.8 s. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Connect 4";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define NAVY RGB(0x0B1B42)
+#define KEY(k) (1ull << (k))
+#define SAVE_NAME "connect4.sav"
+
+/* base, shade, light */
+static const color DISC[3][3] = {
+ {RGB(0xE0252B), RGB(0x86101A), RGB(0xFF8672)},
+ {RGB(0xF8CB1C), RGB(0xB27A00), RGB(0xFFF5A8)},
+ {RGB(0x1FAE4F), RGB(0x0A5E2A), RGB(0x8AF0A6)},
+};
+static const color BLUE[3] = {RGB(0x1E5BC6), RGB(0x0B2F7A), RGB(0x78A6FF)};
+/* background top and bottom, text, soft text */
+static const color THEME[2][4] = {
+ {RGB(0xF2F6FC), RGB(0xC4D4EA), RGB(0x17264A), RGB(0x5A6C8E)},
+ {RGB(0x1F2740), RGB(0x080B14), RGB(0xE9EEF8), RGB(0x8C98B4)},
+};
+
+static color mix(color f, color b, int a) { /* f over b, a from 0 to 32 */
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (color)(y | y >> 16);
+}
+static int clamp(int v, int a, int b) { return v < a ? a : v > b ? b : v; }
+static int iabs(int v) { return v < 0 ? -v : v; }
+static int isin(int a) { /* a parabola sine: period 256, -256..256 */
+ int x = a & 127, v = x * (128 - x) >> 4;
+ return a & 128 ? -v : v;
+}
+static uint32_t seed = 0x2545F491;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+
+/* ------------------------------------------------------------------ saved */
+static struct {
+ uint8_t magic, version;
+ uint8_t cpu, players, level, dark; /* the options */
+ uint8_t tcfg; /* the options the tally below belongs to */
+ uint8_t starter; /* who starts the next round */
+ uint16_t wins[4]; /* and draws */
+} V, saved;
+
+static void save(void) {
+ uint8_t *a = (uint8_t *)&V, *b = (uint8_t *)&saved;
+ bool same = true;
+ for (unsigned i = 0; i < sizeof V; i++) same &= a[i] == b[i];
+ if (!same && ef_write(SAVE_NAME, &V, sizeof V)) saved = V;
+}
+
+static void load(void) {
+ V.magic = 'C', V.version = 1, V.cpu = 1, V.players = 2, V.level = 1, V.tcfg = 0xFF;
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ if (d && n == sizeof V && d[0] == 'C' && d[1] == 1) {
+ __typeof__(V) t;
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&t)[i] = d[i];
+ /* (any tcfg or starter is harmless) */
+ bool ok = t.cpu < 2 && t.players - 2u < 2 && t.level < 3 && t.dark < 2;
+ for (int i = 0; i < 4; i++) ok &= t.wins[i] < 1000;
+ if (ok) V = saved = t;
+ }
+}
+
+/* ------------------------------------------------------------------ game state */
+enum { S_TITLE, S_TURN, S_CPU, S_AIM, S_DROP, S_OVER, S_DRAIN, S_PAUSE, S_CONFIRM };
+static int st, under; /* the state, and the one under the pause menu */
+static uint32_t now, t_state; /* milliseconds; when the state began */
+static uint64_t held = ~0ull, hit;
+static bool quit, at_title; /* at_title: "Quit game?" asked from the title */
+
+typedef uint64_t bb;
+/* The board as bitboards: bit c * 7 + r is column c, row r (from the
+ bottom); the 7th bit of each column stays empty so that lines never wrap. */
+static bb disc[4]; /* each player's discs, then all of them (the search plays on them too) */
+static uint8_t height[8];
+__attribute__((noinline)) static bb bit(int i) { return (bb)1 << i; }
+__attribute__((noinline)) static int get(bb x, int i) { return (int)(x >> i) & 1; }
+static uint8_t hist[48]; /* the columns played */
+static int nh, first, cur, winner, hov[3];
+static int np = 2, NC = 7, C = 30, R = 12, rr = 24, BX, BY, HY; /* layout */
+#define F 6 /* the frame around the holes */
+static bool mv; /* the current player's disc is shown */
+static int mcol = -1, mx2, my2; /* the column it falls in, its centre (half pixels) */
+static int fy, vy, ty, dfall, dv; /* falls, in 1/16 px */
+static int drain; /* how far the discs have dropped out, in px */
+static bool pend_pause;
+static bb wmask; /* the winning discs */
+static int glow;
+static int msel, psel, nitems, qsel;
+static uint8_t items[4];
+enum { I_RESUME, I_UNDO, I_RESTART, I_QUIT };
+static const char *const ITEM[] = {"Resume", "Undo move", "Restart", "Quit game"};
+
+static int ccx2(int c) { return 2 * (BX + c * C) + C; } /* a column's centre, in half pixels */
+static int cy2(int r) { return 2 * (BY + (5 - r) * C) + C; } /* a row's */
+static int hover_y2(void) { return 2 * HY + 1; }
+static bool human(int p) { return !V.cpu || p == 0; }
+
+/* for each screen column and row: the board's column and row (from the top,
+ -1 off the grid), and the pixel's place in its cell */
+static int8_t gcol[320], gdx[320], grow[240], gdy[240];
+
+static void layout(void) {
+ np = V.players, NC = np + 5, C = np == 3 ? 28 : 30, R = C * 2 / 5, rr = 2 * R;
+ BX = (320 - NC * C) / 2, BY = 240 - 14 - F - 6 * C, HY = BY - F - R - 3;
+ for (int i = 0; i < 320; i++) {
+ int g = i - BX, h = i - BY;
+ gcol[i] = (int8_t)(g >= 0 && g < NC * C ? g / C : -1), gdx[i] = (int8_t)(g % C);
+ if (i < 240) grow[i] = (int8_t)(h >= 0 && h < 6 * C ? h / C : -1), gdy[i] = (int8_t)(h % C);
+ }
+}
+
+/* ------------------------------------------------------------------ dirty rectangles */
+static int16_t dr[12][4];
+static int nd;
+static void flush(void);
+static void dirty(int x, int y, int w, int h) {
+ int x1 = clamp(x + w, 0, 320), y1 = clamp(y + h, 0, 240);
+ x = clamp(x, 0, 320), y = clamp(y, 0, 240);
+ if (x >= x1 || y >= y1) return;
+ for (int i = 0; i < nd; i++) {
+ int16_t *d = dr[i];
+ if (d[0] <= x && d[1] <= y && d[2] >= x1 && d[3] >= y1) return; /* already in */
+ if (d[0] >= x && d[1] >= y && d[2] <= x1 && d[3] <= y1) d[2] = d[0]; /* inside the new one: drop it */
+ }
+ if (nd == 12) flush(); /* full: draw what is there now */
+ dr[nd][0] = (int16_t)x, dr[nd][1] = (int16_t)y, dr[nd][2] = (int16_t)x1, dr[nd][3] = (int16_t)y1, nd++;
+}
+static void dirty_all(void) { dirty(0, 0, 320, 240); }
+static void dirty_top(void) { dirty(0, 0, 320, BY - F); }
+static void dirty_board(void) { dirty(BX, BY, NC * C, 6 * C); }
+static void dirty_cell(int c, int r) { dirty(BX + c * C, BY + (5 - r) * C, C, C); }
+static void dirty_panels(void) {
+ dirty(0, 0, BX - F - 6, 240);
+ dirty(320 - (BX - F - 6), 0, BX - F - 6, 240);
+}
+
+/* ------------------------------------------------------------------ pixels */
+static color buf[320 * 20];
+static int cx0, cy0, cx1, cy1, bw; /* the band being drawn */
+static color rb[2]; /* the background on this row, dithered */
+
+static struct { /* the rings of a disc of radius r, worked out once */
+ int r, rim, band, step, inv, ho, hr, hk;
+} dk;
+/* A disc of radius r (half pixels) at offset (dx, dy) from its centre: a
+ raised rim, a step down to a flat middle, lit from the top left. */
+static color shade(int dx, int dy, int r, int p) {
+ int d2 = dx * dx + dy * dy;
+ if (dk.r != r) {
+ int b = r * 7 / 10, m = r * 3 / 5;
+ dk.r = r, dk.rim = (r - 3) * (r - 3), dk.band = b * b, dk.step = m * m, dk.inv = 65536 / r;
+ dk.ho = r * 11 / 20, dk.hr = r * r / 30, dk.hk = 20 * 65536 / dk.hr;
+ }
+ const color *k = DISC[p];
+ int s = (dx + dy) * dk.inv, a;
+ if (d2 > dk.rim) a = -s * 18 >> 16; /* the rim's edge, facing out */
+ else if (d2 > dk.band) a = (-s * 6 >> 16) + 2; /* the rim */
+ else if (d2 > dk.step) a = s * 22 >> 16; /* the step, facing in */
+ else a = (-s * 3 >> 16) - 7; /* the middle */
+ color c = a > 0 ? mix(k[2], k[0], a > 32 ? 32 : a) : mix(k[1], k[0], a < -32 ? 32 : -a);
+ int hx = dx + dk.ho, hy = dy + dk.ho, h2 = dk.hr - hx * hx - hy * hy;
+ return h2 > 0 ? mix(WHITE, c, h2 * dk.hk >> 16) : c; /* a shine on the rim */
+}
+/* the winners' rims glow, the others fade */
+static color light(color c, color bg, int lit, bool rim) {
+ return !lit ? c : lit < 0 ? mix(c, bg, 13) : rim ? mix(WHITE, c, 8 + lit * 2) : mix(WHITE, c, lit / 3);
+}
+static color over_disc(color bg, int dx, int dy, int r, int p, int lit) {
+ int d2 = dx * dx + dy * dy, e = r * r - d2;
+ if (e <= -2 * r) return bg;
+ color c = light(shade(dx, dy, r, p), bg, lit, d2 > (r - 5) * (r - 5));
+ return e < 2 * r ? mix(c, bg, 8 * e / r + 16) : c;
+}
+
+/* One cell of the board, worked out once: for each pixel, the plastic's
+ shade, how much of the hole it shows (0..32), the plastic's shadow (64),
+ the edge of a disc (128); and each player's disc, lined up with it. */
+static int8_t cshade[30 * 30];
+static uint8_t chole[30 * 30];
+static color cdisc[3][30 * 30];
+static void cell_setup(void) {
+ int o2 = (rr + 7) * (rr + 7), rr2 = rr * rr;
+ for (int k = 0; k < C * C; k++) {
+ int dx = 2 * (k % C) + 1 - C, dy = 2 * (k / C) + 1 - C, d2 = dx * dx + dy * dy, e = rr2 - d2, sx = dx - 5, sy = dy - 5;
+ cshade[k] = (int8_t)clamp(d2 < o2 ? (dx + dy) * (o2 - d2) * 14 / rr / (o2 - rr2) : 0, -32, 32); /* the hole's bevel */
+ chole[k] = (uint8_t)(clamp(8 * e / rr + 16, 0, 32) | (sx * sx + sy * sy > rr2) << 6 | (d2 > (rr - 5) * (rr - 5)) << 7);
+ for (int p = 0; p < 3; p++) cdisc[p][k] = shade(dx, dy, rr, p);
+ }
+}
+
+/* The blue plastic, shade from -32 (dark) to 32 (light). */
+static color pl[65];
+static color plastic(int s) { return pl[clamp(s, -32, 32) + 32]; }
+
+/* A row of the game screen, from x0 to x1. What only depends on the row is
+ worked out first: the frame's edges, which disc shows through each hole
+ (the drain moves them all down), whether the moving disc crosses it. */
+static void row_game(color *p, int y, int x0, int x1) {
+ int fx0 = BX - F, fx1 = BX + NC * C + F, fy0 = BY - F, fy1 = BY + 6 * C + F;
+ int ey = y < fy0 + 8 ? fy0 + 8 - y : y > fy1 - 9 ? y - (fy1 - 9) : 0, ey2 = y >= fy0 && y < fy1 ? ey * ey : 999;
+ int sy = y < fy0 + 2 ? 16 : y >= fy1 - 2 ? -18 : 0, rt = grow[y], g = y - drain, gr = g >= 0 ? grow[g] : -1;
+ int md = 2 * y + 1 - my2, ky = gdy[y] * C, kd = gr >= 0 ? gdy[g] * C : 0;
+ bool mrow = mv && md > -rr - 2 && md < rr + 2;
+ int8_t who[8], lit[8];
+ for (int c = 0; c < NC; c++) {
+ int i = c * 7 + 5 - gr;
+ who[c] = -1, lit[c] = 0;
+ for (int q = 0; q < np && gr >= 0; q++)
+ if (get(disc[q], i)) who[c] = (int8_t)q, lit[c] = (int8_t)(!wmask ? 0 : get(wmask, i) ? glow : -1);
+ }
+ for (int x = x0; x < x1; x++) {
+ color c = rb[(x ^ y) & 1];
+ int ex = x < fx0 + 8 ? fx0 + 8 - x : x > fx1 - 9 ? x - (fx1 - 9) : 0;
+ if (x < fx0 || x >= fx1 || ex * ex + ey2 > 70) {
+ if ((x >= fx1 || y >= fy1) && x >= fx0 + 6 && x < fx1 + 6 && y >= fy0 + 6 && y < fy1 + 4) c = mix(0, c, 3); /* the board's shadow */
+ /* the stand: a post on each side, on a foot */
+ int o = x < 160 ? fx0 - 1 - x : x - fx1, f = x < 160 ? x - (fx0 - 4) : x - (fx1 + 3);
+ if (o >= 0 && o < 6 && y > fy0 + 12 && y < 232) c = pl[o < 2 ? 26 : o > 3 ? 10 : 20];
+ if (y >= 229 && y < 239 && f * f + (y - 229) * (y - 229) * 3 < 300) c = pl[y < 231 ? 36 : 14];
+ if (mrow) c = over_disc(c, 2 * x + 1 - mx2, md, rr, cur, 0);
+ } else {
+ int s = sy + (x < fx0 + 2 ? 10 : x >= fx1 - 2 ? -12 : 0), col = gcol[x];
+ if (col >= 0 && rt >= 0) {
+ int kx = gdx[x], k = ky + kx, a = chole[k] & 63;
+ s = cshade[k];
+ if (a) { /* through the hole: the wall, a disc, the falling disc */
+ if (who[col] >= 0) {
+ int q = kd + kx, h = chole[q];
+ c = mix(light(cdisc[who[col]][q], c, lit[col], h >> 7), c, h & 63);
+ }
+ if (mrow && col == mcol) c = over_disc(c, 2 * kx + 1 - C, md, rr, cur, 0);
+ if (chole[k] & 64) c = mix(0, c, 9); /* the plastic's shadow */
+ *p++ = a < 32 ? mix(c, plastic(s), a) : c;
+ continue;
+ }
+ }
+ c = plastic(s);
+ }
+ *p++ = c;
+ }
+}
+
+/* The title's background: a close-up of the board, some discs in it. */
+static color pix_title(int x, int y) {
+ const int P = 48, r = 38;
+ int gx = x + 16, gy = y + 14, col = gx / P, rt = gy / P;
+ int dx = 2 * (gx - col * P) + 1 - P, dy = 2 * (gy - rt * P) + 1 - P, d2 = dx * dx + dy * dy, e = r * r - d2;
+ static const char pat[] = "RY YR" " Y Y" " R" "Y Y" "RR RY" "YRY YR" "RYRYRR"; /* by columns */
+ int s = (dx + dy) * 16 / r - 2;
+ int o2 = (r + 9) * (r + 9);
+ s = d2 < o2 ? s * (o2 - d2) / (o2 - r * r) : -2;
+ color h = RGB(0x0A1430), c;
+ char q = pat[(col % 7) * 6 + rt % 6];
+ if (e <= -2 * r) {
+ c = plastic(s);
+ } else {
+ if (q != ' ') h = over_disc(h, dx, dy, r, q == 'Y', 0);
+ int sx = dx - 7, sy = dy - 7;
+ if (sx * sx + sy * sy > r * r) h = mix(0, h, 10);
+ c = e >= 2 * r ? h : mix(h, plastic(s), 8 * e / r + 16);
+ }
+ return mix(NAVY, c, y < 80 ? 6 : y < 216 ? 12 : 20); /* dimmed, so the words stand out */
+}
+
+/* ------------------------------------------------------------------ painting on the band */
+static void fill(int x, int y, int w, int h, color c, int a) {
+ int x0 = x < cx0 ? cx0 : x, x1 = x + w > cx1 ? cx1 : x + w, y0 = y < cy0 ? cy0 : y, y1 = y + h > cy1 ? cy1 : y + h;
+ for (int j = y0; j < y1; j++)
+ for (color *p = buf + (j - cy0) * bw + x0 - cx0, *e = p + x1 - x0; p < e; p++) *p = a >= 32 ? c : mix(c, *p, a);
+}
+static void rrect(int x, int y, int w, int h, int r, color c, int a) {
+ for (int j = clamp(cy0 - y, 0, h), je = clamp(cy1 - y, 0, h); j < je; j++) {
+ int e = j < r ? r - j : j >= h - r ? j - (h - 1 - r) : 0, in = 0;
+ while (e && (r - in) * (r - in) + e * e > r * r + r) in++;
+ fill(x + in, y + j, w - 2 * in, 1, c, a);
+ }
+}
+/* a disc of radius r (half pixels) centred on (cx2, cy2) in half pixels */
+static void disc_at(int cx2, int cy2, int r, int p, int lit) {
+ int x0 = clamp((cx2 - r) / 2 - 1, cx0, cx1), x1 = clamp((cx2 + r) / 2 + 2, cx0, cx1);
+ int y0 = clamp((cy2 - r) / 2 - 1, cy0, cy1), y1 = clamp((cy2 + r) / 2 + 2, cy0, cy1);
+ for (int y = y0; y < y1; y++)
+ for (int x = x0; x < x1; x++) {
+ color *q = buf + (y - cy0) * bw + x - cx0;
+ *q = over_disc(*q, 2 * x + 1 - cx2, 2 * y + 1 - cy2, r, p, lit);
+ }
+}
+
+/* The characters the game writes, and their 5 columns of 8 bits (top row
+ first, row 7 for descenders). Add any new one to both. */
+static const char GLYPHS[] = " !'0123456789:<>?ABCDEFGIKLNOPQRSTUWYabdeghiklmnoprstuvxy";
+static const uint8_t font[][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x05,0x03,0x00,0x00},{0x3E,0x41,0x41,0x41,0x3E},{0x00,0x42,0x7F,0x40,0x00},
+ {0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},{0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},
+ {0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},{0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},
+ {0x00,0x36,0x36,0x00,0x00},{0x08,0x14,0x22,0x41,0x00},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},
+ {0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22},{0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},
+ {0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x49,0x49,0x7A},{0x00,0x41,0x7F,0x41,0x00},{0x7F,0x08,0x14,0x22,0x41},
+ {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},{0x7F,0x09,0x09,0x09,0x06},
+ {0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},{0x01,0x01,0x7F,0x01,0x01},
+ {0x3F,0x40,0x40,0x40,0x3F},{0x3F,0x40,0x38,0x40,0x3F},{0x07,0x08,0x70,0x08,0x07},{0x20,0x54,0x54,0x54,0x78},
+ {0x7F,0x48,0x44,0x44,0x38},{0x38,0x44,0x44,0x48,0x7F},{0x38,0x54,0x54,0x54,0x18},{0x18,0xA4,0xA4,0xA4,0x7C},
+ {0x7F,0x08,0x04,0x04,0x78},{0x00,0x44,0x7D,0x40,0x00},{0x7F,0x10,0x28,0x44,0x00},{0x00,0x41,0x7F,0x40,0x00},
+ {0x7C,0x04,0x18,0x04,0x78},{0x7C,0x08,0x04,0x04,0x78},{0x38,0x44,0x44,0x44,0x38},{0xFC,0x24,0x24,0x24,0x18},
+ {0x7C,0x08,0x04,0x04,0x08},{0x48,0x54,0x54,0x54,0x20},{0x04,0x3F,0x44,0x40,0x20},{0x3C,0x40,0x40,0x20,0x7C},
+ {0x1C,0x20,0x40,0x20,0x1C},{0x44,0x28,0x10,0x28,0x44},{0x0C,0x90,0x90,0x90,0x7C},
+};
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static int tw(const char *s, int k) { return slen(s) * 6 * k - k; }
+/* text from x; each dot a k x k square grown by g on every side */
+static void text(const char *s, int x, int y, int k, int g, color c, int a) {
+ if (y - g >= cy1 || y + 8 * k + g <= cy0) return;
+ for (; *s; s++, x += 6 * k) {
+ int ch = 0;
+ while (GLYPHS[ch] && GLYPHS[ch] != *s) ch++;
+ for (int i = 0; i < 5 && GLYPHS[ch]; i++)
+ for (int j = 0, b = font[ch][i]; b; j++, b >>= 1)
+ if (b & 1) fill(x + i * k - g, y + j * k - g, k + 2 * g, k + 2 * g, c, a);
+ }
+}
+static void ctext(const char *s, int cx, int y, int k, color c, int a) { text(s, cx - tw(s, k) / 2, y, k, 0, c, a); }
+/* white (or c) with a dark outline */
+static void otext(const char *s, int cx, int y, int k, color c) {
+ int x = cx - tw(s, k) / 2;
+ text(s, x, y + 1, k, 1, 0, 14);
+ text(s, x, y, k, 1, NAVY, 32);
+ text(s, x, y, k, 0, c, 32);
+}
+static char *num(char *o, unsigned v) {
+ char t[6];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+
+/* ------------------------------------------------------------------ what goes on top */
+/* the players' names, and what their wins are called */
+static const char *const NAME[2][8] = {
+ {"P1", "P2", "P3", "", "RED WINS!", "YELLOW WINS!", "GREEN WINS!", "DRAW!"},
+ {"YOU", "CPU 1", "CPU 2", "CPU", "YOU WIN!", "CPU 1 WINS", "CPU 2 WINS", "CPU WINS"},
+};
+static const char *name(int p) { return NAME[V.cpu][p == 1 && np == 2 && V.cpu ? 3 : p]; }
+static int panel_w(void) { return BX - F - 6; }
+
+static void panels(void) {
+ const color *t = THEME[V.dark];
+ int w = panel_w();
+ if (cx0 >= w && cx1 <= 320 - w) return;
+ for (int p = 0; p < np; p++) {
+ int cx = p == 1 ? 320 - w / 2 : w / 2, y = np == 2 ? 88 : p == 2 ? 146 : 66;
+ int s = st >= S_PAUSE ? under : st;
+ bool on = p == cur && s >= S_TURN && s <= S_DROP;
+ if (on) rrect(cx - w / 2 + 1, y - 9, w - 2, 70, 10, DISC[p][0], 32);
+ rrect(cx - w / 2 + 3, y - 7, w - 6, 66, 8, on ? mix(DISC[p][0], rb[0], 8) : mix(t[2], rb[0], 3), 32);
+ ctext(name(p), cx, y, 1, t[2], 32);
+ disc_at(2 * cx, 2 * (y + 23), 22, p, 0);
+ char n[6];
+ num(n, V.wins[p]);
+ ctext(n, cx, y + 40, 2, t[2], 32);
+ }
+}
+
+static void top_message(void) {
+ const color *t = THEME[V.dark];
+ const char *m = winner < 0 ? NAME[0][7] : NAME[V.cpu][winner == 1 && np == 2 && V.cpu ? 7 : 4 + winner];
+ int y = np == 2 ? 3 : 8;
+ otext(m, 160, y, 2, winner < 0 ? WHITE : DISC[winner][0]);
+ ctext("OK: next round", 160, y + 20, 1, t[3], 32);
+}
+
+static void card(int h, const char *title) {
+ int y = (240 - h) / 2;
+ rrect(80, y + 3, 160, h, 12, 0, 10);
+ rrect(80, y, 160, h, 12, NAVY, 30);
+ ctext(title, 160, y + 10, 2, WHITE, 32);
+}
+
+static void overlay(void) {
+ for (color *p = buf, *e = buf + bw * (cy1 - cy0); p < e; p++) *p = mix(0, *p, 13);
+ if (st == S_PAUSE) {
+ int h = 40 + nitems * 24, y = (240 - h) / 2 + 34;
+ card(h, "PAUSED");
+ for (int i = 0; i < nitems; i++) {
+ if (i == psel) rrect(96, y + i * 24 - 5, 128, 22, 8, DISC[1][0], 32);
+ ctext(ITEM[items[i]], 160, y + i * 24, 2, i == psel ? NAVY : WHITE, 32);
+ }
+ } else {
+ card(76, "Quit game?");
+ for (int i = 0; i < 2; i++) {
+ bool on = i == qsel;
+ rrect(98 + i * 66, 128, 58, 24, 8, on ? DISC[1][0] : WHITE, on ? 32 : 6);
+ ctext(i ? "Yes" : "No", 127 + i * 66, 133, 2, on ? NAVY : WHITE, 32);
+ }
+ }
+}
+
+static const char *const OPT_NAME[] = {"Opponent", "Players", "Level", "Theme"};
+static const char *const OPT_VAL[] = {"Friend", "Computer", "2", "3", "Weak", "Normal", "Strong", "Light", "Dark"};
+static int opt(int i) { return i == 0 ? V.cpu : i == 1 ? V.players : i == 2 ? 4 + V.level : 7 + V.dark; }
+
+static void title_ui(void) {
+ /* CONNECT and a red disc with a 4 */
+ if (cy0 < 80) {
+ text("CONNECT", 22, 29, 5, 3, 0, 12);
+ text("CONNECT", 20, 25, 5, 2, NAVY, 32);
+ text("CONNECT", 20, 25, 5, 0, WHITE, 32);
+ disc_at(2 * 268, 2 * 42, 62, 0, 0);
+ text("4", 256, 26, 5, 2, NAVY, 32);
+ text("4", 256, 26, 5, 0, WHITE, 32);
+ }
+ rrect(34, 92, 252, 124, 14, 0, 10);
+ rrect(32, 88, 256, 124, 14, NAVY, 32);
+ bool on = msel == 0;
+ rrect(100, 98, 120, 26, 10, on ? DISC[1][0] : WHITE, on ? 32 : 5);
+ ctext("PLAY", 160, 104, 2, on ? NAVY : WHITE, 32);
+ for (int i = 0; i < 4; i++) {
+ int y = 132 + i * 19, a = i == 2 && !V.cpu ? 12 : 32;
+ on = msel == i + 1;
+ if (on) rrect(40, y - 4, 240, 18, 7, WHITE, 5);
+ text(OPT_NAME[i], 50, y + 4, 1, 0, RGB(0xA9BCE0), a);
+ ctext(OPT_VAL[opt(i)], 220, y, 2, on ? DISC[1][0] : WHITE, a);
+ if (on) {
+ text("<", 152, y, 2, 0, DISC[1][0], 32);
+ text(">", 278, y, 2, 0, DISC[1][0], 32);
+ }
+ }
+ ctext("Based on Tatone26's version", 160, 226, 1, WHITE, 26);
+}
+
+/* ------------------------------------------------------------------ to the screen */
+static void paint(int x, int y, int w, int h) {
+ int rows = (int)(sizeof buf / sizeof buf[0]) / w;
+ bool title = st == S_TITLE || (st == S_CONFIRM && at_title);
+ for (int y0 = y; y0 < y + h; y0 += rows) {
+ cx0 = x, cx1 = x + w, cy0 = y0, cy1 = y0 + rows < y + h ? y0 + rows : y + h, bw = w;
+ color *p = buf;
+ for (int j = cy0; j < cy1; j++, p += w) {
+ int g = j * 64 / 240;
+ rb[0] = mix(THEME[V.dark][1], THEME[V.dark][0], g / 2), rb[1] = mix(THEME[V.dark][1], THEME[V.dark][0], (g + 1) / 2);
+ if (!title) row_game(p, j, cx0, cx1);
+ else
+ for (int i = cx0; i < cx1; i++) /* (under the menu's card: nothing to work out) */
+ p[i - cx0] = (i >= 46 && i < 274 && j >= 88 && j < 212) || (i >= 32 && i < 288 && j >= 102 && j < 198) ? 0 : pix_title(i, j);
+ }
+ if (title) {
+ title_ui();
+ if (st == S_CONFIRM) overlay();
+ } else {
+ panels();
+ if (st == S_OVER || ((st == S_PAUSE || st == S_CONFIRM) && under == S_OVER)) top_message();
+ if (st >= S_PAUSE) overlay();
+ }
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)cy0, (uint16_t)w, (uint16_t)(cy1 - cy0)}, buf);
+ }
+}
+static void flush(void) {
+ for (int i = 0; i < nd; i++)
+ if (dr[i][2] > dr[i][0]) paint(dr[i][0], dr[i][1], dr[i][2] - dr[i][0], dr[i][3] - dr[i][1]);
+ nd = 0;
+}
+
+static void scan(void) {
+ uint64_t k = eadk_keyboard_scan();
+ hit = k & ~held, held = k;
+ if (hit & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) quit = true;
+}
+
+/* ------------------------------------------------------------------ the computer */
+/* every cell, the bottom row, the rows that suit each player */
+static bb full, bot, good[3];
+static int me, ply, noise, abort_s, psum[3], root;
+static uint8_t order[8], cw[56]; /* centre-out columns, fours through each cell */
+static uint32_t nodes, t0, t_anim, t_hard, gseed;
+typedef struct {
+ uint32_t k;
+ int16_t v;
+ uint8_t d, f; /* depth; bound (2 bits) and best column */
+} tte;
+#define TTN 4096
+static tte tt[TTN];
+#define WIN 10000
+#define INF 30000
+
+static int pc32(uint32_t v) {
+ v = v - ((v >> 1) & 0x55555555);
+ v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
+ return (int)((((v + (v >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24);
+}
+static int pc(bb x) { return pc32((uint32_t)x) + pc32((uint32_t)(x >> 32)); }
+static bb cm[8]; /* each column */
+static const int8_t DIR[4][2] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}};
+static bool on(int c, int r) { return (unsigned)c < (unsigned)NC && (unsigned)r < 6; }
+
+/* the empty cells that would make four for p */
+static bb wins(bb p, bb o) {
+ bb r = (p << 1) & (p << 2) & (p << 3);
+ for (int s = 6; s <= 8; s++) {
+ bb a = (p << s) & (p << 2 * s), b = (p >> s) & (p >> 2 * s);
+ r |= (a & ((p << 3 * s) | (p >> s))) | (b & ((p << s) | (p >> 3 * s)));
+ }
+ return r & full & ~o;
+}
+
+/* the discs of p that make fours */
+static bb four(bb p, int d) {
+ bb m = p & p >> d;
+ m &= m >> 2 * d; /* where fours start */
+ return m | m << d | m << 2 * d | m << 3 * d;
+}
+static bb fours(bb p) { return four(p, 1) | four(p, 6) | four(p, 7) | four(p, 8); } /* the four directions */
+
+static void ai_setup(void) {
+ full = bot = 0;
+ for (int c = 0; c < NC; c++) cm[c] = bit(c * 7) * 0x3F, full |= cm[c], bot |= bit(c * 7);
+ for (int i = 0; i < NC; i++) order[i] = (uint8_t)((NC - 1) / 2 + (i & 1 ? 1 : -1) * ((i + 1) / 2));
+ for (int c = 0; c < NC; c++)
+ for (int r = 0; r < 6; r++) {
+ int n = 0;
+ for (int d = 0; d < 4; d++)
+ for (int k = 0; k < 4; k++) { /* the window starting k cells back */
+ int c0 = c - k * DIR[d][0], r0 = r - k * DIR[d][1];
+ n += on(c0, r0) && on(c0 + 3 * DIR[d][0], r0 + 3 * DIR[d][1]);
+ }
+ cw[c * 7 + r] = (uint8_t)n;
+ }
+}
+
+/* t: each player's threats. A threat above another player's threat in the
+ same column rarely matters: the lower one decides the column. Threats on
+ the rows that suit the player (odd rows for whoever started, in
+ two-player games) are what win endgames: if the second player answers
+ every move in the same column, the first gets the odd rows and the second
+ the even ones, so fill the board that way and see who has a four. Discs
+ near the middle take part in more fours (psum). */
+static int eval(const bb *t) {
+ int s = 0;
+ if (np == 2) {
+ bb e = full & ~disc[3], o = e & good[first];
+ int v = ((fours(disc[first] | o) != 0) - (fours(disc[!first] | (e & ~o)) != 0)) * 150;
+ s = first == me ? v : -v;
+ }
+ bb all = t[0] | t[1] | t[2];
+ for (int p = 0; p < np; p++) {
+ bb a = (all & ~t[p]) << 1 & full; /* the cells above the others' threats */
+ for (int i = 0; i < 4; i++) a |= a << 1 & full;
+ bb u = t[p] & ~a;
+ int v = pc(t[p]) * 4 + pc(u) * 12 + pc(u & good[p]) * 16 + psum[p];
+ s += p == me ? v : -v;
+ }
+ if (noise) {
+ uint32_t h = (uint32_t)(((disc[3] ^ disc[0]) * 0x9E3779B97F4A7C15ull) >> 32) ^ gseed;
+ h ^= h >> 15, h *= 0x2C1B3C6Du, h ^= h >> 12;
+ s += (int)(h % (2u * noise + 1)) - noise;
+ }
+ return s;
+}
+
+static void think_anim(void);
+static void hook(void) {
+ uint32_t t = (uint32_t)eadk_timing_millis();
+ if (t >= t_hard) abort_s = 1;
+ if (t - t_anim >= 30) {
+ t_anim = t;
+ think_anim();
+ }
+}
+
+static int search(int side, int depth, int alpha, int beta, const bb *t);
+/* plays column c for side, searches, takes it back */
+static int try_move(int side, int c, int depth, int alpha, int beta, const bb *t, bb w) {
+ int i = c * 7 + height[c], nx = side + 1 == np ? 0 : side + 1;
+ bb m = bit(i), ct[3] = {t[0] & ~m, t[1] & ~m, t[2] & ~m};
+ ct[side] = w; /* the mover's threats, already worked out */
+ disc[side] |= m, disc[3] |= m, height[c]++, ply++, psum[side] += cw[i];
+ int v = depth < 0 ? eval(ct) : search(nx, depth, alpha, beta, ct);
+ disc[side] ^= m, disc[3] ^= m, height[c]--, ply--, psum[side] -= cw[i];
+ return v;
+}
+
+/* Paranoid minimax: the computer (me) against everyone else. Scores are
+ from me's side; a win sooner is worth more. */
+static int search(int side, int depth, int alpha, int beta, const bb *t) {
+ if (!(++nodes & 255)) hook();
+ if (abort_s) return 0;
+ bb poss = (disc[3] + bot) & full;
+ if (!poss) return 0;
+ int win = WIN - ply, nx = side + 1 == np ? 0 : side + 1;
+ bool mx = side == me;
+ if (t[side] & poss) return mx ? win : -win;
+ if (!depth) return eval(t);
+ if (mx != (nx == me)) { /* the next player is against us: block, and don't help */
+ bb ow = t[nx], forced = poss & ow;
+ int lose = nx == me ? win - 1 : 1 - win;
+ if (forced) {
+ if (forced & (forced - 1)) return lose;
+ poss = forced;
+ }
+ poss &= ~(ow >> 1);
+ if (!poss) return lose;
+ }
+ bb h = disc[0] * 0x9E3779B97F4A7C15ull ^ disc[1] * 0xC2B2AE3D27D4EB4Full ^ disc[2] * 0x165667B19E3779F9ull;
+ tte *e = &tt[(uint32_t)h >> 20];
+ uint32_t k = (uint32_t)(h >> 32);
+ int tm = -1;
+ if (e->k == k) {
+ tm = e->f >> 2;
+ if (e->d >= depth) {
+ int v = e->v, f = e->f & 3;
+ if (f == 0 || (f == 1 && v >= beta) || (f == 2 && v <= alpha)) return v;
+ }
+ }
+ /* moves: the table's first, then those making the most threats, centre first */
+ int8_t mv_[8];
+ int16_t sc[8];
+ bb ws[8];
+ int n = 0;
+ for (int i = 0; i < NC; i++) {
+ int c = order[i];
+ bb m = poss & cm[c];
+ if (!m) continue;
+ bb w = wins(disc[side] | m, disc[3] | m);
+ int s = c == tm ? 1000 : pc(w) * 4 - i, j = n++;
+ while (j && sc[j - 1] < s) sc[j] = sc[j - 1], mv_[j] = mv_[j - 1], ws[j] = ws[j - 1], j--;
+ sc[j] = (int16_t)s, mv_[j] = (int8_t)c, ws[j] = w;
+ }
+ int best = mx ? -INF : INF, bc = mv_[0], a0 = alpha, b0 = beta;
+ for (int i = 0; i < n; i++) {
+ int v = try_move(side, mv_[i], depth - 1, alpha, beta, t, ws[i]);
+ if (abort_s) break;
+ if (mx ? v > best : v < best) {
+ best = v, bc = mv_[i];
+ if (!ply) root = bc; /* the computer's move, so far */
+ }
+ if (mx) alpha = best > alpha ? best : alpha;
+ else beta = best < beta ? best : beta;
+ if (alpha >= beta) break;
+ }
+ if (!abort_s) e->k = k, e->v = (int16_t)best, e->d = (uint8_t)depth, e->f = (uint8_t)((best <= a0 ? 2 : best >= b0 ? 1 : 0) | bc << 2);
+ return best;
+}
+
+/* The computer's column for player cur. */
+static int think(void) {
+ for (int p = 0; p < 3; p++) {
+ psum[p] = 0;
+ for (int i = 0; i < 56; i++) psum[p] += get(disc[p], i) * cw[i];
+ }
+ me = cur, ply = 0, abort_s = 0, nodes = 0;
+ t0 = t_anim = (uint32_t)eadk_timing_millis();
+ t_hard = t0 + (V.level == 2 ? 850 : 4000);
+ gseed = rnd();
+ bb odd = full & 0x2A54A952A54A95ull, t[3]; /* rows 1, 3 and 5 */
+ for (int p = 0; p < 3; p++) good[p] = 0, t[p] = wins(disc[p], disc[3]);
+ if (np == 2) good[first] = odd, good[!first] = full & ~odd;
+ for (unsigned i = 0; i < sizeof tt / sizeof tt[0]; i++) tt[i].k = 0;
+ bb poss = (disc[3] + bot) & full;
+ for (int i = NC; i--;)
+ if (poss & cm[order[i]]) {
+ root = order[i];
+ if (t[me] & poss & cm[root]) return root; /* a four: always seen, at once */
+ }
+ /* deeper paranoid searches only get gloomier with three players */
+ int lv = V.level, maxd = lv == 0 ? 1 : lv == 1 ? 9 - np * 2 : np == 2 ? 42 - nh : 4, best = root;
+ noise = lv == 0 ? 50 : lv == 1 ? 6 : 1;
+ for (int d = lv == 2 ? 1 : maxd; d <= maxd; d++) { /* deeper while there is time */
+ int v = search(me, d, -INF, INF, t);
+ /* every move loses against perfect play: keep the last answer, the
+ opponent may not find the win */
+ if (v <= 64 - WIN && d > 1) break;
+ best = root; /* (even out of time: the moves searched in time are fine) */
+ if (abort_s || v >= WIN - 64 || v <= 64 - WIN || (uint32_t)eadk_timing_millis() - t0 > 300) break;
+ }
+ while (!abort_s && (uint32_t)eadk_timing_millis() - t0 < 500) /* a quick answer still looks thought about */
+ eadk_timing_msleep(15), hook();
+ return best;
+}
+
+/* ------------------------------------------------------------------ playing */
+static void set_state(int s) { st = s, t_state = now; }
+
+static void show_turn(void) { /* the current player's disc above the board */
+ mv = true, mcol = -1, mx2 = ccx2(hov[cur]), my2 = hover_y2();
+ set_state(human(cur) ? S_TURN : S_CPU);
+ dirty_top();
+ dirty_panels();
+}
+
+static void new_round(void) {
+ disc[0] = disc[1] = disc[2] = disc[3] = 0;
+ for (int c = 0; c < 8; c++) height[c] = 0;
+ nh = 0, wmask = 0, drain = 0, pend_pause = false;
+ cur = first = V.starter % np;
+ V.starter = (uint8_t)((first + 1) % np);
+ for (int p = 0; p < 3; p++) hov[p] = (NC - 1) / 2;
+ dirty_all();
+ show_turn();
+}
+
+static void start_game(void) {
+ int cfg = V.cpu | (V.players - 2) << 1 | V.level << 2;
+ if (cfg != V.tcfg) {
+ V.tcfg = (uint8_t)cfg, V.starter = 0;
+ V.wins[0] = V.wins[1] = V.wins[2] = V.wins[3] = 0;
+ }
+ layout();
+ cell_setup();
+ ai_setup();
+ new_round();
+ save();
+}
+
+static void drop(int c) {
+ if (height[c] >= 6) return;
+ hov[cur] = c, mcol = c, mx2 = ccx2(c);
+ fy = my2 * 8, vy = 0, ty = cy2(height[c]) * 8;
+ dirty_top();
+ set_state(S_DROP);
+}
+
+static void open_pause(void);
+/* the disc has landed: four in a row, a full board, or the next player */
+static void landed(void) {
+ int c = mcol;
+ bb m = bit(c * 7 + height[c]++);
+ disc[cur] |= m, disc[3] |= m;
+ hist[nh++] = (uint8_t)c;
+ mv = false, mcol = -1;
+ wmask = fours(disc[cur]);
+ if (wmask || nh == NC * 6) {
+ winner = wmask ? cur : -1;
+ int w = wmask ? cur : 3;
+ V.wins[w] += V.wins[w] < 999;
+ save();
+ set_state(S_OVER);
+ dirty_top();
+ dirty_panels();
+ dirty_board();
+ } else {
+ cur = (cur + 1) % np;
+ show_turn();
+ }
+ if (pend_pause) pend_pause = false, open_pause();
+}
+
+static bool can_undo(void) { /* back to a human turn */
+ return nh > (V.cpu ? (np - first) % np : 0);
+}
+static void undo(void) {
+ while (nh) {
+ int c = hist[--nh];
+ bb m = ~bit(c * 7 + --height[c]);
+ for (int p = 0; p < 4; p++) disc[p] &= m;
+ dirty_cell(c, height[c]);
+ cur = (first + nh) % np;
+ if (human(cur)) break;
+ }
+ show_turn();
+}
+
+static void open_pause(void) {
+ under = st;
+ nitems = 0, psel = 0;
+ items[nitems++] = I_RESUME;
+ if (under != S_OVER && can_undo()) items[nitems++] = I_UNDO;
+ items[nitems++] = I_RESTART;
+ items[nitems++] = I_QUIT;
+ set_state(S_PAUSE);
+ dirty_all();
+}
+static void close_pause(void) {
+ st = under;
+ if (st == S_TURN) show_turn();
+ dirty_all();
+}
+
+static void dirty_hover(int old) { /* where the hovering disc was and is */
+ dirty((old < mx2 ? old : mx2) / 2 - R - 2, HY - R - 2, iabs(old - mx2) / 2 + 2 * R + 6, 2 * R + 5);
+}
+
+/* while thinking: the disc sways over the board, and keys still work */
+static bool want_pause;
+static void think_anim(void) {
+ scan();
+ if (quit) abort_s = 1;
+ if (hit & KEY(eadk_key_back)) want_pause = true, abort_s = 1;
+ int old = mx2;
+ mx2 = clamp(ccx2(hov[cur]) + isin((int)(t_anim - t0) / 5) * C * 3 / 256, ccx2(0), ccx2(NC - 1));
+ dirty_hover(old);
+ flush(); /* no wait for the refresh: thinking time is precious */
+}
+
+static void slide(void) { /* the hovering disc glides to its column */
+ int tx = ccx2(hov[cur]), old = mx2, d = (tx - mx2) / 3;
+ mx2 += d ? d : tx > mx2 ? 1 : tx < mx2 ? -1 : 0;
+ if (mx2 != old) dirty_hover(old);
+}
+
+static uint32_t rep_at;
+static void step(int ticks) {
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);
+ const uint64_t rep = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down);
+ uint64_t h = hit;
+ if (hit & rep) rep_at = now + 300;
+ else if ((held & rep) && (int32_t)(now - rep_at) >= 0) h |= held & rep, rep_at = now + 90;
+ int lr = (h & KEY(eadk_key_right) ? 1 : 0) - (h & KEY(eadk_key_left) ? 1 : 0);
+ int ud = (h & KEY(eadk_key_down) ? 1 : 0) - (h & KEY(eadk_key_up) ? 1 : 0);
+ switch (st) {
+ case S_TITLE:
+ if (back) {
+ qsel = 0, at_title = true, set_state(S_CONFIRM), dirty_all();
+ break;
+ }
+ if (ud) {
+ do msel = (msel + ud + 5) % 5; while (msel == 3 && !V.cpu);
+ dirty(32, 88, 256, 124);
+ }
+ if ((lr || ok) && msel) {
+ int d = lr ? lr : 1;
+ if (msel == 1) V.cpu ^= 1;
+ if (msel == 2) V.players ^= 1;
+ if (msel == 3) V.level = (uint8_t)((V.level + d + 3) % 3);
+ if (msel == 4) V.dark ^= 1;
+ dirty(32, 88, 256, 124);
+ } else if (ok) {
+ start_game();
+ }
+ break;
+ case S_TURN: {
+ static const uint8_t digit[8] = {42, 43, 44, 36, 37, 38, 30, 31};
+ for (int i = 0; i < NC; i++)
+ if (hit & KEY(digit[i])) hov[cur] = i, ok = true;
+ if (lr) hov[cur] = clamp(hov[cur] + lr, 0, NC - 1);
+ if (ok || (hit & KEY(eadk_key_down))) drop(hov[cur]);
+ else if ((hit & KEY(eadk_key_backspace)) && can_undo()) undo();
+ else if (back) open_pause();
+ slide();
+ break;
+ }
+ case S_CPU: {
+ want_pause = false;
+ int c = think();
+ if (quit) return;
+ if (want_pause) {
+ mx2 = ccx2(hov[cur]);
+ open_pause();
+ return;
+ }
+ hov[cur] = c;
+ set_state(S_AIM);
+ break;
+ }
+ case S_AIM:
+ slide();
+ if (back) open_pause();
+ else if (mx2 == ccx2(hov[cur]) && now - t_state > 200) drop(hov[cur]);
+ break;
+ case S_DROP: {
+ int old = my2;
+ while (ticks--) {
+ vy += 20, fy += vy;
+ if (fy >= ty) {
+ fy = ty;
+ if (vy < 90) {
+ vy = 0;
+ break;
+ }
+ vy = -vy / 4;
+ }
+ }
+ my2 = fy / 8;
+ int y0 = (old < my2 ? old : my2) / 2 - R - 2, y1 = (old > my2 ? old : my2) / 2 + R + 3;
+ dirty(BX + mcol * C, y0, C, y1 - y0);
+ if (back) pend_pause = true;
+ if (fy == ty && !vy) landed();
+ break;
+ }
+ case S_OVER:
+ glow = (isin((int)(now - t_state) / 4) + 256) * 12 / 512;
+ for (int b = 0; b < 56; b++)
+ if (get(wmask, b)) dirty_cell(b / 7, b % 7);
+ if (ok) {
+ wmask = 0, dfall = dv = 0;
+ set_state(S_DRAIN);
+ dirty_all();
+ } else if (back) {
+ open_pause();
+ }
+ break;
+ case S_DRAIN: { /* the discs drop out of the bottom: from the top one down */
+ int top = 0, y;
+ for (int c = 0; c < NC; c++) top = height[c] > top ? height[c] : top;
+ y = BY + (6 - top) * C + drain;
+ while (ticks--) dv += 10, dfall += dv;
+ drain = dfall / 16;
+ if (drain > top * C) new_round();
+ else dirty(BX, y, NC * C, BY + 6 * C - y);
+ break;
+ }
+ case S_PAUSE:
+ if (ud) psel = (psel + ud + nitems) % nitems, dirty(80, 40, 160, 160);
+ if (back) close_pause();
+ else if (ok) {
+ int it = items[psel];
+ if (it == I_RESUME) close_pause();
+ if (it == I_UNDO) st = S_TURN, undo(), dirty_all();
+ if (it == I_RESTART) V.starter = (uint8_t)first, new_round();
+ if (it == I_QUIT) qsel = 0, at_title = false, set_state(S_CONFIRM), dirty_all();
+ }
+ break;
+ case S_CONFIRM:
+ if (lr) qsel ^= 1, dirty(80, 80, 160, 80);
+ if (back || (ok && !qsel)) set_state(at_title ? S_TITLE : S_PAUSE), dirty_all();
+ else if (ok) quit = true; /* back to NumPlay (or the calculator); main saves */
+ break;
+ }
+}
+
+int main(void) {
+ np_app_begin();
+ for (int i = 0; i < 65; i++) /* the plastic's shades */
+ pl[i] = i > 32 ? mix(BLUE[2], BLUE[0], i - 32) : mix(BLUE[1], BLUE[0], 32 - i);
+ load();
+ now = (uint32_t)eadk_timing_millis();
+ seed ^= now ^ eadk_random();
+ layout();
+ set_state(S_TITLE);
+ dirty_all();
+ uint32_t last = now;
+ for (;;) {
+ now = (uint32_t)eadk_timing_millis();
+ int ticks = (int)(now - last) / 16; /* 60 Hz steps for the falling discs */
+ if (ticks > 4) ticks = 4, last = now;
+ else last += (uint32_t)ticks * 16;
+ scan();
+ if (quit) break;
+ step(ticks);
+ if (quit) break;
+ eadk_display_wait_for_vblank();
+ flush();
+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;
+ if (spent < 16) eadk_timing_msleep(16 - spent);
+ }
+ save();
+ return np_app_end();
+}
diff --git a/games/flappybird/.gitignore b/games/flappybird/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/flappybird/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/flappybird/Makefile b/games/flappybird/Makefile
new file mode 100644
index 00000000..5c787b2c
--- /dev/null
+++ b/games/flappybird/Makefile
@@ -0,0 +1,51 @@
+# Flappy Bird, with the settings and random events of All the Apps.
+# make build output/flappybird.nwa
+# make check link the app like the calculator does (output/flappybird.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/flappybird.nwa
+
+check: $(BUILD_DIR)/flappybird.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/flappybird.bin
+ @echo "BIN $(BUILD_DIR)/flappybird.bin: $$(wc -c < $(BUILD_DIR)/flappybird.bin) bytes"
+
+$(BUILD_DIR)/flappybird.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_flappybird_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_flappybird_main -o $@
diff --git a/games/flappybird/README.md b/games/flappybird/README.md
new file mode 100644
index 00000000..c5ca8732
--- /dev/null
+++ b/games/flappybird/README.md
@@ -0,0 +1,36 @@
+# Flappy Bird
+
+Tap to flap, slip between the pipes, and beat your best. It looks and plays like Dong Nguyen's 2013 original, and keeps the settings and random events of Tatone26's version for when you want something different.
+
+<img src="docs/shot.png" width="320" alt="The yellow bird between two green pipes">
+
+- **Classic** is the real game: day or night, a yellow, blue or red bird, the Get Ready screen, the white flash when you crash, and the score board with bronze, silver, gold and platinum medals (10, 20, 30 and 40 points).
+- **Custom** plays by your own rules, set in **Settings**:
+ - the starting speed and how often it goes up, how close the pipes are (Sparse to Extreme), the gap (Easy, Normal or Hard), moving pipes, and how strong a flap is (Floaty, Bouncy, Normal, Snappy or Heavy);
+ - random events, from rare to frequent: a pipe surge, tailwind and headwind, narrow or wide gaps, dense pipes, low and high gravity. Each one is announced on the ground as it comes, and they can stack if you like;
+ - No collisions, to practise (those scores don't count).
+- The bird and the sky can be chosen in Settings too, for both games.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| OK, EXE, Up, 8 or 5 | Flap |
+| Back | Pause: Resume, Restart or Quit game |
+| Arrows, OK | Menus and settings |
+| Home | Leave |
+
+Your best scores (one for Classic, one for Custom) and your settings are kept in `flappy.sav`.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `FlappyBird.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+## Credits
+
+Flappy Bird was made by Dong Nguyen (.GEARS, 2013). This version was rewritten in C for NumPlay from Tatone26's in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/flappybird) (All the Apps), which is released into the public domain ([UNLICENSE](UNLICENSE)). What changed:
+
+- The look of the original: the sky with clouds, a city and bushes, by day or by night; the green pipes; the striped ground; a bird in three colours that flaps and tilts; the big outlined score; the title, Get Ready, Game Over and score board screens, with a fade between them.
+- A Classic game with the original's rules next to the Custom one, each with its own best score.
+- The events are announced by a tag on the ground instead of the sunflowers; moving pipes are Off, Rarely, Often, Slow or Fast; the gap setting also changes the gap's size.
+- Smooth at 60 frames a second: nothing in the background moves, so only the pipes, the bird and the ground are redrawn. The whole game is about 16 KB.
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/flappybird/UNLICENSE b/games/flappybird/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/flappybird/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/flappybird/docs/shot.png b/games/flappybird/docs/shot.png
new file mode 100644
index 00000000..c36f91f0
Binary files /dev/null and b/games/flappybird/docs/shot.png differ
diff --git a/games/flappybird/src/icon.png b/games/flappybird/src/icon.png
new file mode 100644
index 00000000..fd6a28c3
Binary files /dev/null and b/games/flappybird/src/icon.png differ
diff --git a/games/flappybird/src/main.c b/games/flappybird/src/main.c
new file mode 100644
index 00000000..e923077d
--- /dev/null
+++ b/games/flappybird/src/main.c
@@ -0,0 +1,1197 @@
+/* Flappy Bird: Dong Nguyen's game, with the settings and random events of
+ * Tatone26's version in All the Apps (wind, gravity changes, moving pipes,
+ * narrow and wide gaps...).
+ *
+ * The background never moves, so a frame only repaints what changed: the
+ * pipe columns whose colour changed, the bird's box, the ground's stripes, a
+ * few streaks. Each region is composed in a small buffer from the whole scene
+ * (the skyline comes from a few heights per column, then the pipes, the bird
+ * and the text on top) and pushed once, so nothing flickers. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Flappy Bird";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+#define W 320
+#define H 240
+#define GY 200 /* the ground's top */
+#define BX 96 /* the bird's centre, across */
+#define LW 38 /* a pipe's cap (the shaft is 2 pixels narrower each side) */
+#define LH 16
+#define NP 8
+#define NS 24 /* wind streaks */
+#define BUFN (W * 24)
+#define OFF (-999)
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define KEY(k) (1ull << (k))
+#define WHITE 0xFFFF
+#define DARK RGB(0x543847)
+#define ORANGE RGB(0xE86101)
+#define BEIGE RGB(0xDED895)
+#define ADV(k) (5 * (k) + ((k) + 1) / 2) /* letter advance */
+
+static color buf[BUFN];
+static int rx, ry, rw, rh; /* the region being composed */
+
+static uint32_t seed = 0x2545F491;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+static int rr(int a, int b) { return a + (int)(rnd() % (uint32_t)(b - a + 1)); } /* a..b */
+static int imin(int a, int b) { return a < b ? a : b; }
+static int imax(int a, int b) { return a > b ? a : b; }
+static int iabs(int v) { return v < 0 ? -v : v; }
+static int clamp(int v, int a, int b) { return v < a ? a : v > b ? b : v; }
+static int16_t sn[256]; /* sine, -256..256 */
+#define SIN(a) sn[(a) & 255]
+#define COS(a) sn[((a) + 64) & 255]
+
+/* f over b; a from 0 (all b) to 32 (all f) */
+static color mix(color f, color b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (color)(y | y >> 16);
+}
+
+/* ------------------------------------------------------------------ drawing */
+static void shade(int x, int y, int w, int h, color c, int a) {
+ int x0 = imax(x, rx), x1 = imin(x + w, rx + rw), y0 = imax(y, ry), y1 = imin(y + h, ry + rh);
+ if (x0 >= x1) return;
+ for (int j = y0; j < y1; j++)
+ for (color *p = buf + (j - ry) * rw + (x0 - rx), *e = p + (x1 - x0); p < e; p++) *p = a >= 32 ? c : mix(c, *p, a);
+}
+static int ga = 32; /* how opaque fill() paints, for things fading out */
+static void fill(int x, int y, int w, int h, color c) { shade(x, y, w, h, c, ga); }
+static void rrect(int x, int y, int w, int h, color c) { /* corners cut */
+ fill(x + 1, y, w - 2, h, c);
+ fill(x, y + 1, w, h - 2, c);
+}
+/* the beige board of the original: dark outline, light rim, a shadow inside */
+static void board(int x, int y, int w, int h) {
+ rrect(x, y, w, h, DARK);
+ rrect(x + 1, y + 1, w - 2, h - 2, RGB(0xFCF8CF));
+ fill(x + 3, y + 3, w - 6, h - 6, RGB(0xCFC286));
+ fill(x + 3, y + 3, w - 6, h - 8, BEIGE);
+}
+
+/* ASCII 32..122, columns of 8 bits, top first; the last row is for g, j, p, q, y */
+static const uint8_t font[91][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x07,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14},
+ {0x24,0x2A,0x7F,0x2A,0x12},{0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00},
+ {0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},{0x14,0x08,0x3E,0x08,0x14},{0x08,0x08,0x3E,0x08,0x08},
+ {0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},{0x20,0x10,0x08,0x04,0x02},
+ {0x3E,0x41,0x41,0x41,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},
+ {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},
+ {0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00},
+ {0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},
+ {0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22},
+ {0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x41,0x49,0x3A},
+ {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41},
+ {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x02,0x0C,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},
+ {0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},
+ {0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},{0x3F,0x40,0x38,0x40,0x3F},
+ {0x63,0x14,0x08,0x14,0x63},{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},{0x00,0x7F,0x41,0x41,0x00},
+ {0x02,0x04,0x08,0x10,0x20},{0x00,0x41,0x41,0x7F,0x00},{0x04,0x02,0x01,0x02,0x04},{0x40,0x40,0x40,0x40,0x40},
+ {0x00,0x01,0x02,0x04,0x00},{0x20,0x54,0x54,0x54,0x78},{0x7F,0x48,0x44,0x44,0x38},{0x38,0x44,0x44,0x44,0x20},
+ {0x38,0x44,0x44,0x48,0x7F},{0x38,0x54,0x54,0x54,0x18},{0x08,0x7E,0x09,0x01,0x02},{0x18,0xA4,0xA4,0xA4,0x7C},
+ {0x7F,0x08,0x04,0x04,0x78},{0x00,0x44,0x7D,0x40,0x00},{0x40,0x80,0x84,0x7D,0x00},{0x7F,0x10,0x28,0x44,0x00},
+ {0x00,0x41,0x7F,0x40,0x00},{0x7C,0x04,0x18,0x04,0x78},{0x7C,0x08,0x04,0x04,0x78},{0x38,0x44,0x44,0x44,0x38},
+ {0xFC,0x24,0x24,0x24,0x18},{0x18,0x24,0x24,0x18,0xFC},{0x7C,0x08,0x04,0x04,0x08},{0x48,0x54,0x54,0x54,0x20},
+ {0x04,0x3F,0x44,0x40,0x20},{0x3C,0x40,0x40,0x20,0x7C},{0x1C,0x20,0x40,0x20,0x1C},{0x3C,0x40,0x30,0x40,0x3C},
+ {0x44,0x28,0x10,0x28,0x44},{0x1C,0xA0,0xA0,0xA0,0x7C},{0x44,0x64,0x54,0x4C,0x44},
+};
+static bool fpix(char ch, int i, int j) { /* is pixel (i, j) of a letter set */
+ unsigned g = (uint8_t)ch - 32u;
+ return g < 91 && (unsigned)i < 5 && (font[g][i] >> j & 1);
+}
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static int tw(const char *s, int k) { return slen(s) * ADV(k) - ADV(k) + 5 * k; }
+static void text(const char *s, int x, int y, int k, color c) {
+ if (y >= ry + rh || y + 8 * k <= ry) return;
+ for (; *s; s++, x += ADV(k))
+ for (int i = 0; i < 5; i++)
+ for (int j = 0; j < 8; j++)
+ if (fpix(*s, i, j)) fill(x + i * k, y + j * k, k, k, c);
+}
+static void ctext(const char *s, int cx, int y, int k, color c) { text(s, cx - tw(s, k) / 2, y, k, c); }
+static void otext(const char *s, int x, int y, int k, color c) { /* with a dark outline */
+ for (int d = 0; d < 9; d++) text(s, x + d % 3 - 1, y + d / 3 - 1, k, DARK);
+ text(s, x, y, k, c);
+}
+static char *num(char *o, int v) {
+ char t[8];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+
+/* the score's bold digits, 5x7 ("1" is 3 wide), a bit per column */
+static const uint8_t digs[10][7] = {
+ {0x0E,0x1B,0x1B,0x1B,0x1B,0x1B,0x0E},{0x06,0x07,0x06,0x06,0x06,0x06,0x06},{0x0E,0x1B,0x18,0x0C,0x06,0x03,0x1F},
+ {0x0E,0x1B,0x18,0x0C,0x18,0x1B,0x0E},{0x1B,0x1B,0x1B,0x1F,0x18,0x18,0x18},{0x1F,0x03,0x0F,0x18,0x18,0x1B,0x0E},
+ {0x0E,0x1B,0x03,0x0F,0x1B,0x1B,0x0E},{0x1F,0x18,0x0C,0x0C,0x06,0x06,0x06},{0x0E,0x1B,0x1B,0x0E,0x1B,0x1B,0x0E},
+ {0x0E,0x1B,0x1B,0x1E,0x18,0x1B,0x0E},
+};
+static int bigw(const char *s, int k) {
+ int w = -k;
+ for (; *s; s++) w += (*s == '1' ? 4 : 6) * k;
+ return w;
+}
+/* white digits with a black outline, from x (or centred on x when c) */
+static void big(int n, int x, int y, int k, bool c) {
+ char s[8];
+ num(s, n);
+ int o = k > 2 ? 2 : 1;
+ if (c) x -= bigw(s, k) / 2;
+ if (y - o >= ry + rh || y + 7 * k + o <= ry) return;
+ for (int pass = 0; pass < 2; pass++)
+ for (int i = 0, px = x; s[i]; px += (s[i++] == '1' ? 4 : 6) * k)
+ for (int r = 0; r < 7; r++)
+ for (int b = 0; b < 5; b++)
+ if (digs[s[i] - '0'][r] >> b & 1) {
+ if (pass) fill(px + b * k, y + r * k, k, k, WHITE);
+ else fill(px + b * k - o, y + r * k - o, k + 2 * o, k + 2 * o, 0);
+ }
+}
+
+/* big lettering ("Get Ready!", "Game Over"...): the letters scaled up, a white
+ ring and a dark ring around them, taller below; made once, 2 bits a pixel */
+#define LMW 232
+#define LMH 42
+static uint8_t lmap[LMW * LMH / 4];
+static int lw, lh;
+static color lfill[LMH];
+static void letters(const char *s, int k, int drop, color top, color bot) {
+ const int p = 3, R = p + drop + 1, n = slen(s), a = ADV(k) + 1; /* strokes a pixel bolder */
+ lw = n * a - a + 5 * k + 1 + 2 * p, lh = 8 * k + 2 * p + drop;
+ uint8_t *hd = (uint8_t *)buf; /* distance to the nearest letter pixel in the row */
+ for (int y = 0; y < lh; y++) {
+ uint8_t *h = hd + y * lw;
+ int d = R;
+ for (int x = 0; x < lw; x++) {
+ int u = x - p, v = y - p, c = u % a; /* strokes widened to the right */
+ bool on = u >= 0 && v >= 0 && v < 8 * k && (fpix(s[u / a], c / k, v / k) || (c && fpix(s[u / a], (c - 1) / k, v / k)));
+ d = on ? 0 : imin(d + 1, R);
+ h[x] = (uint8_t)d;
+ }
+ for (int x = lw - 2; x >= 0; x--) h[x] = (uint8_t)imin(h[x], h[x + 1] + 1);
+ }
+ for (int i = 0; i < LMW * LMH / 4; i++) lmap[i] = 0;
+ for (int y = 0; y < lh; y++)
+ for (int x = 0; x < lw; x++) {
+ int da = 99, db = 99; /* squared distances: plain, and stretched down */
+ for (int dy = -R; dy <= R; dy++) {
+ int yy = y + dy;
+ if (yy < 0 || yy >= lh) continue;
+ int e = hd[yy * lw + x], v = dy < 0 ? imax(-dy - drop, 0) : dy;
+ da = imin(da, e * e + dy * dy);
+ db = imin(db, e * e + v * v);
+ }
+ int i = y * lw + x, c = !da ? 3 : da <= 2 ? 2 : db <= 12 ? 1 : 0;
+ lmap[i >> 2] |= (uint8_t)(c << (i & 3) * 2);
+ }
+ for (int y = 0; y < lh; y++) {
+ int t = clamp((y - p) * 32 / (7 * k), 0, 32);
+ lfill[y] = mix(bot, top, t);
+ }
+}
+static void lettering(int x0, int y0, int a) {
+ int xa = imax(x0, rx), xb = imin(x0 + lw, rx + rw);
+ if (xa >= xb) return;
+ for (int y = imax(y0, ry); y < imin(y0 + lh, ry + rh); y++) {
+ color *d = buf + (y - ry) * rw + xa - rx;
+ for (int x = xa, i = (y - y0) * lw + xa - x0; x < xb; x++, i++, d++) {
+ int v = lmap[i >> 2] >> (i & 3) * 2 & 3;
+ if (!v) continue;
+ color c = v == 3 ? lfill[y - y0] : v == 2 ? WHITE : DARK;
+ *d = a >= 32 ? c : mix(c, *d, a);
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ scene */
+/* sky, cloud, cloud top, building, building edge, window, lit window, bush,
+ bush top; day then night */
+static const color themes[2][9] = {
+ {RGB(0x4EC0CA), RGB(0xE6F9DC), RGB(0xD2F2E6), RGB(0xCDECD4), RGB(0xA8DCBC), RGB(0xB6E3C6), RGB(0xB6E3C6), RGB(0x5EE270), RGB(0x4AC45E)},
+ {RGB(0x008793), RGB(0x1CA3AE), RGB(0x2DB2BC), RGB(0x0B5F66), RGB(0x084A50), RGB(0x0F6C73), RGB(0xF7E27A), RGB(0x1E8A4C), RGB(0x16703D)},
+};
+static const color *th;
+static uint8_t cl[W], ct[W], bt[W], bf[W]; /* cloud, city and bush tops; building columns */
+static bool night;
+static int32_t gx; /* how far the ground went, 1/256 pixel */
+static int gph, gph_drawn; /* ...and its stripes' phase */
+
+static int hnext(uint32_t *h, int n) {
+ *h = *h * 1103515245u + 12345u;
+ return (int)((*h >> 16) % (uint32_t)n);
+}
+/* a band of round puffs, without deep notches between them */
+static void bumps(uint8_t *a, int base, int r0, int r1, uint32_t *h) {
+ for (int x = 0; x < W; x++) a[x] = (uint8_t)(base - r0 / 2);
+ for (int cx = -6; cx < W + 6; cx += r0 + hnext(h, r1)) {
+ int r = r0 + hnext(h, r1 - r0 + 1);
+ for (int dx = -r; dx <= r; dx++) {
+ int x = cx + dx, y = base - (int)__builtin_sqrtf((float)(r * r - dx * dx));
+ if (x >= 0 && x < W && y < a[x]) a[x] = (uint8_t)y;
+ }
+ }
+ for (int x = 1; x < W; x++) a[x] = (uint8_t)imin(a[x], a[x - 1] + 2);
+ for (int x = W - 2; x >= 0; x--) a[x] = (uint8_t)imin(a[x], a[x + 1] + 2);
+}
+static void make_scene(void) {
+ th = themes[night];
+ uint32_t h = 11; /* the same skyline every time */
+ bumps(cl, 158, 9, 19, &h);
+ for (int x = 0, i = 0, w = 0, top = 0; x < W; x++, i++) {
+ if (i >= w) w = 10 + 4 * hnext(&h, 4), top = 176 - hnext(&h, 26), i = 0;
+ ct[x] = (uint8_t)top;
+ bf[x] = !i ? 1 : (i & 3) >= 2 && i < w - 2 ? 2 : 0;
+ }
+ bumps(bt, 196, 5, 11, &h);
+}
+
+static void ground_row(color *d, int y) {
+ int t = y - GY;
+ if (t >= 2 && t < 12) { /* the green stripes, leaning, moving with the pipes */
+ for (int x = 0, k = (rx + gph + 140 - t) % 14; x < rw; x++, k = k == 13 ? 0 : k + 1)
+ d[x] = k < 7 ? RGB(0x9CE659) : RGB(0x73BF2E);
+ return;
+ }
+ color c = t == 0 ? DARK : t == 1 ? RGB(0xE4FD8B) : t == 12 ? RGB(0x558022) : t == 13 ? RGB(0xD7A84C) : BEIGE;
+ for (int x = 0; x < rw; x++) d[x] = c;
+}
+static void background(void) {
+ for (int y = ry; y < ry + rh; y++) {
+ color *d = buf + (y - ry) * rw;
+ if (y >= GY) {
+ ground_row(d, y);
+ continue;
+ }
+ for (int x = rx; x < rx + rw; x++, d++) {
+ int i;
+ if (y >= bt[x]) i = y == bt[x] ? 8 : 7;
+ else if (y >= ct[x]) {
+ int t = y - ct[x];
+ i = 3;
+ if (!t || (bf[x] & 1)) i = 4;
+ else if ((bf[x] & 2) && (t & 3) >= 2) i = night && ((x >> 2) * 7 + (t >> 2) * 5 + ct[x]) % 4 == 0 ? 6 : 5;
+ } else if (y >= cl[x]) i = y == cl[x] ? 2 : 1;
+ else i = 0;
+ *d = th[i];
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ pipes */
+typedef struct {
+ int32_t x; /* left edge, 1/256 pixel */
+ int16_t c, g, o, v; /* gap centre; gap and wobble (1/256 pixel); wobble speed */
+ int8_t lo, hi; /* wobble range */
+ uint8_t on, scored, osc, dense;
+ int16_t dx, dt, db; /* what the screen shows: left, gap top, gap bottom */
+} pipe_t;
+static pipe_t P[NP];
+static color pcol[2][LW]; /* shaft, cap colour by column */
+static uint8_t psig[LW];
+static int gap_top(const pipe_t *p) { return p->c + (p->o >> 8) - (p->g >> 9); }
+static int gap_bot(const pipe_t *p) { return gap_top(p) + (p->g >> 8); }
+
+static void make_pipes(void) {
+ static const char shaft[] = " OLLHHHLLMMMMMMMMMMMMMMMDMDDDDDDDEO ", cap[] = "OLLHHHHLLMMMMMMMMMMMMMMMMMDMDDDDDDDDEO";
+ static const char key[] = " OLHMDE";
+ static const color cols[] = {0, DARK, RGB(0x9CE659), RGB(0xE4FD8B), RGB(0x73BF2E), RGB(0x558022), RGB(0x4A7320)};
+ for (int u = 0; u < LW; u++) {
+ int a = 0, b = 0;
+ while (key[a] != shaft[u]) a++;
+ while (key[b] != cap[u]) b++;
+ pcol[0][u] = cols[a], pcol[1][u] = cols[b];
+ psig[u] = (uint8_t)(a | b << 3);
+ }
+}
+static void pipes_draw(void) {
+ for (int i = 0; i < NP; i++) {
+ const pipe_t *p = &P[i];
+ int px = p->x >> 8, x0 = imax(px, rx), x1 = imin(px + LW, rx + rw);
+ if (!p->on || x0 >= x1) continue;
+ int gt = gap_top(p), gb = gap_bot(p);
+ for (int y = ry; y < imin(ry + rh, GY); y++) {
+ int r = y < gt - LH ? -1 : y < gt ? y - gt + LH : y < gb ? -2 : y < gb + LH ? y - gb : -1;
+ if (r == -2) continue;
+ color *d = buf + (y - ry) * rw;
+ if (r == 0 || r == LH - 1) { /* the cap's outline */
+ for (int x = x0; x < x1; x++) d[x - rx] = DARK;
+ continue;
+ }
+ const color *c = pcol[r > 0];
+ for (int x = imax(x0, r < 0 ? px + 2 : px); x < imin(x1, r < 0 ? px + LW - 2 : px + LW); x++) d[x - rx] = c[x - px];
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ the bird */
+/* 24x17, 3 bits a pixel: none, outline, white, body, light, belly, lips (2) */
+static const uint8_t bird_body[154] = {
+ 0x00,0x00,0x00,0x48,0x92,0x04,0x00,0x00,0x00,0x00,0x00,0x20,0x21,0x49,0x26,0x09,0x00,0x00,0x00,0x00,0x84,0x24,
+ 0xC9,0x48,0x52,0x00,0x00,0x00,0x80,0x90,0xDB,0x16,0x49,0x92,0x02,0x00,0x00,0x90,0x6D,0xDB,0x22,0x49,0x92,0x14,
+ 0x00,0x00,0xB2,0x6D,0xDB,0x22,0x49,0x4A,0x14,0x00,0x40,0xB6,0x6D,0xDB,0x22,0x49,0x4A,0x14,0x00,0xC8,0xB6,0x6D,
+ 0xDB,0x22,0x49,0x4A,0x14,0x00,0xC8,0xB6,0x6D,0xDB,0x16,0x49,0x92,0x02,0x00,0xD9,0xB6,0x6D,0xDB,0xB6,0x24,0x49,
+ 0x92,0x00,0xD9,0xB6,0x6D,0xDB,0x16,0xDB,0xB6,0x6D,0x07,0xD9,0xB6,0x6D,0xDB,0x62,0x27,0x49,0x92,0x00,0x48,0xBB,
+ 0x6D,0xDB,0xE2,0xFF,0xFF,0xFF,0x00,0x40,0xDA,0xB6,0x6D,0x9B,0x24,0x49,0x12,0x00,0x00,0x92,0xB6,0x6D,0xDB,0x36,
+ 0x00,0x00,0x00,0x00,0x80,0x24,0x6D,0xDB,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x49,0x12,0x00,0x00,0x00,0x00,0x00,
+};
+/* the wing, up, level and down: 8x7, 2 bits (none, outline, white, light) */
+static const uint8_t bird_wing[3][7][2] = {
+ {{0x50,0x01},{0xA4,0x06},{0xA9,0x06},{0xA9,0x1A},{0xAD,0x1A},{0xF4,0x1B},{0x50,0x05}},
+ {{0x54,0x05},{0xA9,0x1A},{0xAD,0x6A},{0xF4,0x1F},{0x50,0x05}},
+ {{0x54,0x05},{0xA9,0x1A},{0xAD,0x1A},{0xB4,0x1A},{0xD0,0x07},{0x40,0x01}},
+};
+static const uint8_t wing_y[3] = {3, 6, 7};
+/* body, light, belly: yellow, blue, red */
+static const color bird_cols[3][3] = {{RGB(0xF8C136), RGB(0xFCE88A), RGB(0xF39A22)},
+ {RGB(0x55B8E8), RGB(0xA6E2F8), RGB(0x2F86C8)},
+ {RGB(0xF0553A), RGB(0xFBA28A), RGB(0xC53A2A)}};
+static color bpal[8];
+static int bird_x, bird_y, bird_a, bird_f, bird_on, bird_s; /* what is drawn: centre, angle (256 a turn), wing, 2x */
+static int bd_x, bd_y, bd_a, bd_f; /* ...and what the screen shows */
+
+static void bird_colors(int c) {
+ static const color fixed[8] = {0, DARK, WHITE, 0, 0, 0, RGB(0xF76A2C), RGB(0xDB4A26)};
+ for (int i = 0; i < 8; i++) bpal[i] = i >= 3 && i <= 5 ? bird_cols[c][i - 3] : fixed[i];
+}
+static int bird_pix(int i, int j) {
+ int wj = j - wing_y[bird_f];
+ if ((unsigned)wj < 7 && i < 8) {
+ int v = bird_wing[bird_f][wj][i >> 2] >> (i & 3) * 2 & 3;
+ if (v) return "\1\2\4"[v - 1];
+ }
+ int b = (j * 24 + i) * 3;
+ return (bird_body[b >> 3] | bird_body[(b >> 3) + 1] << 8) >> (b & 7) & 7;
+}
+static void bird_draw(void) {
+ int r = 15 << bird_s, x0 = imax(bird_x - r, rx), x1 = imin(bird_x + r, rx + rw), y1 = imin(bird_y + r, ry + rh);
+ if (!bird_on || x0 >= x1) return;
+ int a = iabs(bird_a) < 6 ? 0 : bird_a, c = COS(a), s = SIN(a), sh = 8 + bird_s; /* level: the plain sprite */
+ for (int y = imax(bird_y - r, ry); y < y1; y++) {
+ color *d = buf + (y - ry) * rw + (x0 - rx);
+ int dy = 2 * (y - bird_y) + 1;
+ for (int x = x0; x < x1; x++, d++) { /* turn back to the sprite, in half pixels */
+ int dx = 2 * (x - bird_x) + 1, u = ((dx * c + dy * s) >> sh) + 24, v = ((dy * c - dx * s) >> sh) + 17;
+ if (u < 0 || v < 0 || u >= 48 || v >= 34) continue;
+ int i = bird_pix(u >> 1, v >> 1);
+ if (i) *d = bpal[i];
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ dirty regions */
+#define ND 128
+static int16_t dq[ND][4];
+static int nd;
+static bool full;
+static void add(int x, int y, int w, int h) {
+ int x1 = imin(x + w, W), y1 = imin(y + h, H);
+ x = imax(x, 0), y = imax(y, 0);
+ if (x >= x1 || y >= y1) return;
+ if (nd == ND) {
+ full = true;
+ return;
+ }
+ dq[nd][0] = (int16_t)x, dq[nd][1] = (int16_t)y, dq[nd][2] = (int16_t)(x1 - x), dq[nd][3] = (int16_t)(y1 - y);
+ nd++;
+}
+/* both boxes, as one when they overlap */
+static void add2(int x0, int y0, int x1, int y1, int w, int h) {
+ if (iabs(x1 - x0) < w && iabs(y1 - y0) < h) add(imin(x0, x1), imin(y0, y1), w + iabs(x1 - x0), h + iabs(y1 - y0));
+ else add(x0, y0, w, h), add(x1, y1, w, h);
+}
+
+static void pipe_dirty(pipe_t *p) {
+ int nx = p->on ? p->x >> 8 : OFF, nt = p->on ? gap_top(p) : 0, nb = p->on ? gap_bot(p) : 0;
+ int ox = p->dx, ot = p->dt, ob = p->db;
+ if (nx == ox && nt == ot && nb == ob) return;
+ p->dx = (int16_t)nx, p->dt = (int16_t)nt, p->db = (int16_t)nb;
+ if (nx == OFF || ox == OFF || iabs(nx - ox) >= LW) {
+ if (ox != OFF) add(ox, 0, LW, GY);
+ if (nx != OFF) add(nx, 0, LW, GY);
+ return;
+ }
+ /* the columns whose colours changed, above and below the gap */
+ int lo = imin(ox, nx), hi = imax(ox, nx) + LW, top = imax(ot, nt), bot = imin(ob, nb), run = -1, end = 0;
+ for (int x = lo; x <= hi; x++) { /* (runs a few columns apart go as one) */
+ int a = x - ox, b = x - nx;
+ if (x < hi && ((unsigned)a < LW ? psig[a] : 255) != ((unsigned)b < LW ? psig[b] : 255)) {
+ if (run < 0) run = x;
+ end = x + 1;
+ } else if (run >= 0 && (x - end >= 3 || x == hi)) {
+ add(run, 0, end - run, top), add(run, bot, end - run, GY - bot), run = -1;
+ }
+ }
+ if (nt != ot) add(lo, imin(ot, nt) - LH, hi - lo, iabs(nt - ot) + LH);
+ if (nb != ob) add(lo, imin(ob, nb), hi - lo, iabs(nb - ob) + LH);
+}
+
+/* ------------------------------------------------------------------ settings, save */
+enum { O_SPEED, O_SPEEDUP, O_PIPES, O_GAP, O_MOVING, O_JUMP, O_EVENTS, O_SURGE, O_WIND, O_NARROW, O_WIDE, O_DENSE,
+ O_GRAV, O_STACK, O_NOCOLL, O_BIRD, O_SKY, O_RESET, NOPT };
+static const char opt_names[] = /* one after the other, see nth() */
+ "Speed\0Speed up\0Pipes\0Gap\0Moving pipes\0Jump\0Events\0- Pipe surge\0- Wind\0- Narrow gaps\0- Wide gaps\0"
+ "- Dense pipes\0- Gravity\0Stack events\0No collisions\0Bird\0Sky\0Reset all";
+/* the values of the options that are not Off/On, one list after the other */
+static const char opt_vals[] =
+ "Very slow\0Slow\0Normal\0Fast\0Insane\0Impossible\0Never\0Every 15\0Every 10\0Every 5\0Each pipe\0"
+ "Sparse\0Normal\0Dense\0Extreme\0Easy\0Normal\0Hard\0Off\0Rarely\0Sometimes\0Often\0Slow\0Fast\0"
+ "Floaty\0Bouncy\0Normal\0Snappy\0Heavy\0Never\0Rare\0Normal\0Frequent\0Random\0Yellow\0Blue\0Red\0"
+ "Random\0Day\0Night\0OK";
+static const uint8_t opt_count[NOPT] = {6, 5, 4, 3, 6, 5, 4, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 1};
+static const uint8_t opt_default[NOPT] = {2, 2, 1, 1, 0, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
+/* Classic: the real game (the bird and sky settings still apply) */
+static const uint8_t classic[NOPT] = {2, 0, 1, 1, 0, 2, 0};
+
+static struct {
+ uint8_t magic, version, mode, pad;
+ uint16_t best[2]; /* Classic, Custom */
+ uint8_t opt[NOPT];
+} sv;
+#define SAVE_NAME "flappy.sav"
+static bool save_dirty;
+
+static const char *nth(const char *s, int i) {
+ while (i--) s += slen(s) + 1;
+ return s;
+}
+static const char *opt_text(int r) {
+ int k = sv.opt[r];
+ if (opt_count[r] == 2) return nth("Off\0On", k);
+ for (int i = 0; i < r; i++) k += opt_count[i] == 2 ? 0 : opt_count[i];
+ return nth(opt_vals, k);
+}
+static void save(void) {
+ if (!save_dirty) return;
+ sv.magic = 'F', sv.version = 1, sv.pad = 0;
+ if (ef_write(SAVE_NAME, &sv, sizeof sv)) save_dirty = false;
+}
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ bool ok = d && n == sizeof sv && d[0] == 'F' && d[1] == 1;
+ if (ok)
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&sv)[i] = d[i];
+ if (!ok || sv.mode > 1) sv.mode = 0;
+ for (int i = 0; i < 2; i++)
+ if (!ok || sv.best[i] > 9999) sv.best[i] = 0;
+ for (int i = 0; i < NOPT; i++)
+ if (!ok || sv.opt[i] >= opt_count[i]) sv.opt[i] = opt_default[i];
+}
+
+/* ------------------------------------------------------------------ the game */
+enum { S_TITLE, S_SETTINGS, S_READY, S_PLAY, S_DEAD, S_OVER };
+enum { EV_NONE, EV_SURGE, EV_TAIL, EV_HEAD, EV_NARROW, EV_WIDE, EV_DENSE, EV_LOW, EV_HIGH };
+static const char ev_names[] =
+ "\0Pipe surge!\0Tailwind!\0Headwind!\0Narrow gaps!\0Wide gaps!\0Dense pipes!\0Low gravity!\0High gravity!";
+static int state, tick, sel, top_row, paused, psel; /* paused: 1 the menu, 2 "Quit game?" */
+static bool leave; /* Quit game: back to NumPlay (or the calculator) */
+static int32_t by, vy; /* the bird's height and speed, 1/256 pixel */
+static int score, shown, done_t, countdown, flash, flashed, landed, newbest, sparkle;
+static int spd, spd0, space, gap0, diff, moving, up_every, grav, jump, maxfall, nocoll;
+static int apex, gmin, last_c, last_w; /* a flap's height; the narrowest gap; the last pipe's centre and wobble */
+static const uint8_t *opts;
+/* events, as in All the Apps: a pipe event and a weather event can overlap */
+static uint8_t ev_list[8], ev_n, ev_freq, ev_stack, pev, fev, ev_last, ban_e;
+static int pwarm, ptime, fwarm, ftime, fdown, cool, ban_t;
+static struct {
+ int16_t x, y, b[4]; /* the head; the box on the screen */
+ int8_t vx, vy;
+ uint8_t len, life, drawn;
+} st[NS];
+
+static int ev_cooldown(void) {
+ static const int16_t lo[4] = {1000, 420, 180, 40}, span[4] = {1, 240, 120, 40};
+ return rr(lo[ev_freq], lo[ev_freq] + span[ev_freq]);
+}
+static bool try_event(int e, bool steep) {
+ if (e == EV_SURGE || e == EV_NARROW || e == EV_WIDE || e == EV_DENSE) {
+ /* low gravity with narrow or surging gaps can make a pipe impossible */
+ if (pev || (e == EV_DENSE && fev) || ((e == EV_NARROW || e == EV_SURGE) && fev == EV_LOW)) return false;
+ pev = (uint8_t)e, pwarm = 48, ptime = e == EV_SURGE ? rr(280, 360) : e == EV_DENSE ? rr(240, 310) : rr(260, 340);
+ } else {
+ if (fev || pev == EV_DENSE || (steep && (e == EV_TAIL || e == EV_HIGH)) ||
+ (e == EV_LOW && (pev == EV_NARROW || pev == EV_SURGE)))
+ return false;
+ bool wind = e == EV_TAIL || e == EV_HEAD;
+ fev = (uint8_t)e, fwarm = wind ? 42 : 32, ftime = wind ? rr(220, 290) : rr(200, 260), fdown = 0;
+ }
+ ban_e = (uint8_t)e, ban_t = 0;
+ return true;
+}
+static void events_step(bool dense_left, bool steep) {
+ if (!ev_freq) return;
+ if (pwarm) pwarm--;
+ else if (ptime && !--ptime && pev != EV_DENSE) pev = 0, cool = fev ? cool : ev_cooldown();
+ else if (!ptime && pev == EV_DENSE && !dense_left) pev = 0, cool = fev ? cool : ev_cooldown();
+ if (fwarm) fwarm--;
+ else if (ftime) {
+ if (!--ftime) fdown = fev == EV_TAIL || fev == EV_HEAD ? 28 : 22;
+ } else if (fdown && !--fdown) fev = 0, cool = pev ? cool : ev_cooldown();
+ bool active = pev || fev;
+ if (cool) {
+ if (ev_stack || !active) cool--;
+ } else if (ev_n && (!active || (ev_stack && rr(0, 99) < (ev_freq == 3 ? 20 : ev_freq == 2 ? 12 : 6)))) {
+ int s = rr(0, ev_n - 1);
+ cool = 24;
+ for (int i = 0; i < ev_n; i++) {
+ int e = ev_list[(s + i) % ev_n];
+ if ((ev_n > 1 && e == ev_last) || !try_event(e, steep)) continue;
+ ev_last = (uint8_t)e, cool = ev_stack ? ev_cooldown() : 0;
+ break;
+ }
+ }
+}
+static int weather(void) { return fev && !fwarm ? fev : 0; } /* in effect */
+/* gravity events change the pull and the flap together, so a flap still lifts
+ the bird as high: it only hangs longer or shorter in the air */
+static int pull(bool up) {
+ int w = weather();
+ return w == EV_LOW ? (up ? 205 : 164) : w == EV_HIGH ? (up ? 297 : 343) : 256;
+}
+static int gap_target(void) { /* always room for a flap and some */
+ return imax(pwarm ? gap0 << 8 : pev == EV_NARROW ? gap0 * 184 : pev == EV_WIDE ? gap0 * 307 : gap0 << 8, (apex + 28) << 8);
+}
+static bool dense_now(void) { return pev == EV_DENSE && !pwarm && ptime; }
+
+/* where the next gap goes: never further than the bird can climb or dive
+ between two pipes (the whole range in the classic game). The bird can use
+ the room a gap leaves beside a flap, then climb with flaps or fall from rest
+ in the frames between the pipes; wobbling pipes take some of that away. */
+static int next_centre(int prev, int wob) {
+ static const uint8_t fac[3] = {100, 154, 218}, most[3] = {36, 90, 130};
+ int g = gap_target() >> 8, lo = 24 + g / 2, hi = GY - 24 - g / 2;
+ int sp = dense_now() ? space * 174 >> 8 : space, f = imax(((sp - LW - 18) << 8) / imax(spd, spd0), 0);
+ int room = imax(imin(g, gmin) - 12 - apex, 0) << 8, fall = room;
+ for (int t = 1; t <= f; t++) fall += imin(grav * t, maxfall);
+ int up = imin((room + f * (jump - 5 * grav)) * fac[diff] >> 16, most[diff]) - wob;
+ int dn = imin(fall * fac[diff] >> 16, most[diff]) - wob;
+ int a = imax(lo, prev - imax(up, 4)), b = imin(hi, prev + imax(dn, 4));
+ if (a > b) return clamp(prev, lo, hi);
+ int c = rr(a, b);
+ if (diff == 2 && iabs(c - prev) < 16) c = c < prev ? imax(a, prev - 16) : imin(b, prev + 16);
+ return c;
+}
+static int reach(int g) { return clamp((g >> 8) - 12 - apex, 6, 20); } /* how far a pipe may wobble */
+static void wobble(pipe_t *p, int v, int reach) {
+ int g = p->g >> 9;
+ p->v = (int16_t)(rnd() & 1 ? v : -v);
+ p->lo = (int8_t)-imin(reach, imax(p->c - g - 24, 0)), p->hi = (int8_t)imin(reach, imax(GY - 24 - g - p->c, 0));
+ if (p->lo >= p->hi) p->v = 0;
+}
+static void spawn(pipe_t *p, int32_t x) {
+ static const uint8_t how_often[6] = {0, 25, 50, 75, 100, 100}; /* moving pipes, % */
+ p->on = 1, p->scored = 0, p->x = x, p->o = 0, p->v = 0;
+ p->g = (int16_t)gap_target();
+ p->dense = dense_now();
+ int r = rr(0, 99), w = 0;
+ p->osc = r < how_often[moving];
+ bool fast = moving == 5 || (moving == 3 && r < 22);
+ if (p->osc || (pev == EV_SURGE && !pwarm)) w = reach(p->g);
+ p->c = (int16_t)(last_c = next_centre(last_c, last_w + w));
+ last_w = w;
+ if (w) wobble(p, w < 12 ? 51 : fast ? 128 : 82, w);
+}
+
+static void flap(void) {
+ vy = -(jump * pull(true) >> 8);
+ bird_a = -18; /* the beak goes up at once, as in the original */
+}
+
+static void new_game(void) {
+ opts = sv.mode ? sv.opt : classic;
+ /* pixels a frame, in 1/256: pipe speeds; gravity, flap and fall speed */
+ static const uint16_t speeds[6] = {197, 269, 358, 466, 591, 752}, jumps[5][3] = {
+ {36, 740, 900}, {46, 912, 1152}, {51, 870, 1152}, {72, 1000, 1400}, {72, 820, 1536}};
+ static const uint8_t spaces[4] = {150, 120, 96, 76}, gaps[3] = {80, 70, 60}, ups[5] = {0, 15, 10, 5, 1};
+ spd = spd0 = speeds[opts[O_SPEED]], space = spaces[opts[O_PIPES]], diff = opts[O_GAP], gap0 = gaps[diff];
+ moving = opts[O_MOVING], up_every = ups[opts[O_SPEEDUP]], nocoll = sv.mode && sv.opt[O_NOCOLL];
+ grav = jumps[opts[O_JUMP]][0], jump = jumps[opts[O_JUMP]][1], maxfall = jumps[opts[O_JUMP]][2];
+ apex = jump * jump / (grav * 512);
+ ev_freq = opts[O_EVENTS], ev_stack = sv.mode && sv.opt[O_STACK], ev_n = 0;
+ for (int e = EV_SURGE; e <= EV_HIGH; e++) /* both winds share a setting, and both gravities */
+ if (sv.opt[O_SURGE + e - EV_SURGE - (e > EV_TAIL) - (e > EV_LOW)]) ev_list[ev_n++] = (uint8_t)e;
+ pev = fev = ev_last = ban_e = 0, pwarm = ptime = fwarm = ftime = fdown = 0, cool = ev_freq ? ev_cooldown() : 0;
+ night = sv.opt[O_SKY] ? sv.opt[O_SKY] == 2 : rnd() & 1;
+ bird_colors(sv.opt[O_BIRD] ? sv.opt[O_BIRD] - 1 : (int)(rnd() % 3));
+ make_scene();
+ for (int i = 0; i < NP; i++) P[i].on = 0;
+ for (int i = 0; i < NS; i++) st[i].life = 0;
+ gmin = imax(ev_freq && sv.opt[O_NARROW] ? gap0 * 184 >> 8 : gap0, apex + 28); /* the gap's smallest size */
+ last_c = GY / 2, last_w = 0, by = 100 << 8, vy = 0, score = 0, bird_a = 0, countdown = 0, flash = 0, landed = 0;
+ letters("Get Ready!", 3, 2, RGB(0xB8F07A), RGB(0x4DB33D));
+ state = S_READY, tick = 0, paused = 0, full = true;
+}
+static void to_title(void) {
+ night = 0;
+ bird_colors(0);
+ make_scene();
+ for (int i = 0; i < NP; i++) P[i].on = 0;
+ for (int i = 0; i < NS; i++) st[i].life = 0;
+ letters("FlappyBird", 3, 3, RGB(0xFFF3B8), RGB(0xF7A93A));
+ state = S_TITLE, tick = 0, sel = sv.mode, paused = 0, bird_a = 0, full = true;
+}
+static void to_settings(void) {
+ letters("Settings", 3, 2, RGB(0xB8F07A), RGB(0x4DB33D));
+ state = S_SETTINGS, sel = 0, top_row = 0, full = true;
+}
+static void die(void) {
+ state = S_DEAD, tick = 0, flash = 32;
+ if (vy < 0) vy = 0;
+ for (int i = 0; i < NS; i++) st[i].life = 0;
+ ban_e = 0;
+}
+#define PY 52 /* the score board's place, */
+#define BTY 148 /* and the buttons' */
+static int panel_y(int t) { /* the board slides up, slowing down */
+ int u = clamp(t - 16, 0, 20);
+ return PY + (20 - u) * (20 - u) * 188 / 400;
+}
+static bool keep_best(void) { /* a game ended or was left: is it a new best? */
+ if (nocoll || score <= sv.best[sv.mode]) return false;
+ sv.best[sv.mode] = (uint16_t)imin(score, 9999), save_dirty = true;
+ return true;
+}
+static void game_over(void) {
+ state = S_OVER, tick = 0, sel = 0, shown = 0, done_t = 9999, sparkle = 0;
+ newbest = keep_best();
+ save();
+ letters("Game Over", 3, 2, RGB(0xFFD27A), RGB(0xE86101));
+ full = true;
+}
+
+/* a bird that flaps its wings, with a bob */
+static int bob(int period, int amp) { return SIN(tick * 256 / period) * amp / 256; }
+static void flutter(int every) {
+ static const uint8_t cyc[4] = {0, 1, 2, 1};
+ bird_f = cyc[tick / every & 3];
+}
+
+static bool hits(void) {
+ int y = by >> 8, t = y - 6, b = y + 6, l = BX - 9, r = BX + 9;
+ if (b >= GY) return true;
+ for (int i = 0; i < NP; i++) {
+ const pipe_t *p = &P[i];
+ int px = p->x >> 8, gt = gap_top(p), gb = gap_bot(p);
+ if (!p->on || r <= px || l >= px + LW) continue;
+ bool shaft = r > px + 2 && l < px + LW - 2;
+ if ((t < gt && (b > gt - LH || shaft)) || (b > gb && (t < gb + LH || shaft))) return true;
+ }
+ return false;
+}
+
+static void streaks_step(void) {
+ int e = fwarm || ftime ? fev : 0;
+ if (e == EV_TAIL || e == EV_HEAD || e == EV_LOW || e == EV_HIGH)
+ for (int i = 0; i < NS && tick % 2 == 0; i++)
+ if (!st[i].life) {
+ bool side = e == EV_TAIL || e == EV_HEAD;
+ int v = rr(6, 9) * (e == EV_TAIL || e == EV_HIGH ? 1 : -1);
+ st[i].x = (int16_t)(side ? (v > 0 ? rr(-30, -10) : rr(W + 10, W + 30)) : rr(20, W - 20));
+ st[i].y = (int16_t)(side ? rr(20, GY - 20) : v > 0 ? rr(-30, -10) : rr(GY, GY + 20));
+ st[i].vx = (int8_t)(side ? v : 0), st[i].vy = (int8_t)(side ? 0 : v);
+ st[i].len = (uint8_t)rr(8, 18), st[i].life = 60;
+ break;
+ }
+ for (int i = 0; i < NS; i++)
+ if (st[i].life) {
+ st[i].x = (int16_t)(st[i].x + st[i].vx), st[i].y = (int16_t)(st[i].y + st[i].vy), st[i].life--;
+ if (st[i].x < -40 || st[i].x > W + 40 || st[i].y < -40 || st[i].y > GY + 30) st[i].life = 0;
+ }
+}
+/* a streak's box, trailing behind its head */
+static void streak_box(int x, int y, int vx, int vy, int len, int *b) {
+ b[0] = vx > 0 ? x - len : x, b[1] = vy > 0 ? y - len : y, b[2] = vx ? len : 2, b[3] = vx ? 2 : len;
+}
+static void streaks_draw(void) {
+ for (int i = 0; i < NS; i++)
+ if (st[i].life) {
+ int b[4];
+ streak_box(st[i].x, st[i].y, st[i].vx, st[i].vy, st[i].len, b);
+ /* wind is white; light air rises pale blue, heavy air falls warm */
+ shade(b[0], b[1], b[2], imin(b[3], GY - b[1]), st[i].vx ? WHITE : st[i].vy < 0 ? RGB(0xCFF4FF) : RGB(0xFFE0A0), 26);
+ }
+}
+
+static void play_step(void) {
+ if (tick <= 8) add(W / 2 - lw / 2, 48, lw, lh), add(138, 94, 96, 56); /* Get Ready fades out */
+ if (countdown) {
+ if (!(--countdown % 50)) add(120, 82, 80, 56);
+ return;
+ }
+ bool dense_left = false;
+ int n0 = -1, n1 = -1; /* the next two pipes */
+ for (int i = 0; i < NP; i++)
+ if (P[i].on && (P[i].x >> 8) + LW >= BX) {
+ dense_left |= P[i].dense;
+ if (n0 < 0 || P[i].x < P[n0].x) n1 = n0, n0 = i;
+ else if (n1 < 0 || P[i].x < P[n1].x) n1 = i;
+ }
+ bool steep = n1 >= 0 && iabs(P[n0].c - P[n1].c) >= 54;
+ int was = pev == EV_SURGE && !pwarm;
+ events_step(dense_left, steep);
+ int surge = pev == EV_SURGE && !pwarm, w = weather();
+ /* the pipes' speed follows the wind, smoothly */
+ int target = spd0 * (w == EV_TAIL ? 422 : w == EV_HEAD ? 154 : 256) >> 8;
+ spd += (target - spd) / 12 + (target > spd) - (target < spd);
+ gx += spd, gph = (int)(gx >> 8) % 14;
+ int32_t right = -(1 << 30);
+ int gt = gap_target();
+ for (int i = 0; i < NP; i++) {
+ pipe_t *p = &P[i];
+ if (!p->on) continue;
+ p->x -= spd;
+ if (surge != was) {
+ if (surge && !p->v) wobble(p, 77 + rr(0, 2) * 20, 16);
+ else if (!surge && !p->osc) p->v = 0;
+ }
+ if (p->v) {
+ p->o = (int16_t)(p->o + p->v);
+ if ((p->v < 0 && p->o <= p->lo * 256) || (p->v > 0 && p->o >= p->hi * 256)) p->v = (int16_t)-p->v;
+ }
+ if (iabs(p->g - gt) > 64) p->g = (int16_t)(p->g + (gt - p->g) * 20 / 256);
+ if (!p->scored && (p->x >> 8) + LW / 2 < BX) {
+ p->scored = 1, score++;
+ add(100, 8, 120, 34);
+ if (up_every && score % up_every == 0) spd0 = imin(spd0 * 294 >> 8, imax(1024, spd0));
+ }
+ if ((p->x >> 8) < -LW - 4) p->on = 0;
+ else if (p->x > right) right = p->x;
+ }
+ if (right < (W << 8)) {
+ int sp = dense_now() ? space * 174 >> 8 : space;
+ for (int i = 0; i < NP; i++)
+ if (!P[i].on) {
+ spawn(&P[i], right < -(1 << 29) ? W << 8 : right + (sp << 8));
+ break;
+ }
+ }
+ /* the bird */
+ vy = imin(vy + (grav * pull(false) >> 8), maxfall);
+ by += vy;
+ if (by < 0) by = 0, vy = imax(vy, 0);
+ bird_a = vy < 300 ? imax(bird_a - 6, -18) : imin(bird_a + 3, 64);
+ if (bird_a > 40) bird_f = 1;
+ else flutter(4);
+ if (nocoll) {
+ if ((by >> 8) + 8 > GY) by = (GY - 8) << 8, vy = imin(vy, 0);
+ } else if (hits()) {
+ die();
+ }
+ streaks_step();
+ if (ban_e && ++ban_t > 170) ban_e = 0, add(0, 210, 190, 30);
+ if (ban_e && (ban_t < 50 || ban_t > 158)) add(0, 210, 190, 30);
+}
+
+static void (*fade_next)(void);
+static int fade_t; /* a quick fade through black between screens, as in the original */
+static void go(void (*f)(void)) { fade_next = f, fade_t = 1, paused = 0, full = true; }
+
+static void step(void) {
+ if (fade_t) {
+ full = true;
+ if (++fade_t == 7) fade_next();
+ if (fade_t == 13) fade_t = 0;
+ if (fade_t && fade_t < 7) return;
+ }
+ tick++;
+ switch (state) {
+ case S_TITLE:
+ case S_SETTINGS:
+ case S_READY:
+ gx += 358, gph = (int)(gx >> 8) % 14; /* the ground keeps running */
+ flutter(6);
+ break;
+ case S_PLAY:
+ play_step();
+ break;
+ case S_DEAD:
+ if (flash) flash = imax(flash - 4, 0);
+ if (!landed) {
+ vy = imin(vy + grav, maxfall);
+ by += vy;
+ bird_a = imin(bird_a + 6, 64), bird_f = 1;
+ if ((by >> 8) + 8 >= GY) by = (GY - 8) << 8, landed = tick;
+ } else if (tick - landed > 30) {
+ game_over();
+ }
+ break;
+ case S_OVER:
+ if (tick <= 9) add(W / 2 - lw / 2, 4, lw, lh + 10);
+ if (tick >= 16 && tick <= 36) add(75, panel_y(tick), 170, panel_y(tick - 1) - panel_y(tick) + 90);
+ if (tick >= 40 && shown < score && tick % 2 == 0) shown = imin(score, shown + imax(1, score / 24)), add(150, PY + 20, 84, 20);
+ if (tick >= 40 && shown == score && done_t == 9999) done_t = tick, add(75, PY, 170, 88);
+ if (tick == done_t + 6) add(76, BTY - 4, 168, 36);
+ if (tick > done_t && score >= 10 && tick % 6 == 0) sparkle = (int)(rnd() & 0xFFFF), add(95, PY + 30, 32, 32);
+ break;
+ }
+}
+
+/* ------------------------------------------------------------------ screens */
+static void play_icon(int x, int y) { /* the green arrow of the original's Play button */
+ for (int i = -1; i < 12; i++) fill(x - 1, y + i, imin(i + 1, 11 - i) + 2, 1, DARK);
+ for (int i = 0; i < 11; i++) fill(x, y + i, imin(i, 10 - i) + 1, 1, RGB(0x5AC54B));
+}
+/* the original's buttons; the chosen one is lifted, in an orange ring */
+static void button(int x, int y, int w, int h, const char *s, bool on, bool icon, int k) {
+ if (on) y -= 2, rrect(x - 2, y - 2, w + 4, h + 6, ORANGE);
+ rrect(x, y + 2, w, h, mix(DARK, BEIGE, 12)); /* a soft shadow */
+ rrect(x, y, w, h, DARK);
+ rrect(x + 1, y + 1, w - 2, h - 2, WHITE);
+ fill(x + 3, y + 3, w - 6, h - 6, RGB(0xF3EBCF));
+ int tx = x + (w - tw(s, k) - (icon ? 16 : 0)) / 2;
+ if (icon) play_icon(tx, y + h / 2 - 5), tx += 16;
+ text(s, tx, y + (h - 7 * k) / 2, k, DARK);
+}
+
+static void disc(int cx, int cy, int r, color c) {
+ for (int dy = -r; dy <= r; dy++) {
+ int h = (int)__builtin_sqrtf((float)(r * r + r - dy * dy));
+ fill(cx - h, cy + dy, 2 * h + 1, 1, c);
+ }
+}
+static void medal(int cx, int cy, int tier) {
+ static const color cols[4][3] = {{RGB(0xE8A36A), RGB(0xC77A3C), RGB(0xF6CFA0)}, {RGB(0xE3E3E3), RGB(0xAFAFAF), WHITE},
+ {RGB(0xF8D23A), RGB(0xD39A14), RGB(0xFFF1A8)}, {RGB(0xE9F6F8), RGB(0x9CC8D4), WHITE}};
+ color base = cols[tier][0], rim = cols[tier][1];
+ disc(cx, cy, 13, rim);
+ disc(cx - 1, cy - 1, 11, cols[tier][2]); /* a shine, top left */
+ disc(cx + 1, cy + 1, 10, base);
+ disc(cx, cy, 7, rim); /* the embossed ring */
+ disc(cx, cy, 5, base);
+ int s = sparkle, sx = cx - 9 + (s & 15) * 18 / 16, sy = cy - 9 + (s >> 4 & 15) * 18 / 16, k = s >> 8 & 1;
+ fill(sx - 1 - k, sy, 3 + 2 * k, 1, WHITE), fill(sx, sy - 1 - k, 1, 3 + 2 * k, WHITE);
+}
+
+static void panel(int y) { /* the score board */
+ const int x = 75, w = 170;
+ char n[8];
+ board(x, y, w, 88);
+ text("MEDAL", x + 16, y + 10, 1, ORANGE);
+ text("SCORE", x + w - 14 - tw("SCORE", 1), y + 10, 1, ORANGE);
+ text("BEST", x + w - 14 - tw("BEST", 1), y + 46, 1, ORANGE);
+ disc(x + 36, y + 46, 16, RGB(0xCFC285)); /* the medal's hollow */
+ num(n, shown);
+ big(shown, x + w - 14 - bigw(n, 2), y + 22, 2, false);
+ int best = sv.best[sv.mode];
+ num(n, best);
+ big(best, x + w - 14 - bigw(n, 2), y + 58, 2, false);
+ if (shown == score && tick >= done_t) {
+ if (score >= 10) medal(x + 36, y + 46, score >= 40 ? 3 : score >= 30 ? 2 : score >= 20 ? 1 : 0);
+ if (newbest) {
+ int bx = x + w - 14 - bigw(n, 2) - 30;
+ rrect(bx, y + 60, 24, 11, RGB(0xFC3800));
+ text("NEW", bx + 3, y + 62, 1, WHITE);
+ }
+ }
+}
+
+static void tap_hint(int cx, int y) { /* the original's tutorial, with the OK key */
+ for (int i = 0; i < 10; i++) fill(cx - i - 1, y + i, 2 * i + 2, 1, DARK), fill(cx - i, y + i + 1, 2 * i, 1, WHITE);
+ fill(cx - 4, y + 10, 8, 10, DARK), fill(cx - 3, y + 10, 6, 9, WHITE);
+ rrect(cx - 20, y + 26, 40, 24, DARK);
+ rrect(cx - 19, y + 27, 38, 22, WHITE);
+ fill(cx - 17, y + 45, 34, 2, RGB(0xD0D0D0));
+ ctext("OK", cx, y + 31, 2, DARK);
+ text("TAP", cx - 46, y + 34, 1, RGB(0xF4561D));
+ text("TAP", cx + 28, y + 34, 1, RGB(0xF4561D));
+}
+
+static void settings_draw(void) {
+ lettering(160 - lw / 2, 4, 32);
+ board(8, 40, 304, 158);
+ for (int i = 0; i < 8 && top_row + i < NOPT; i++) {
+ int r = top_row + i, y = 50 + i * 18;
+ bool on = r == sel;
+ const char *v = opt_text(r);
+ if (on) rrect(14, y - 3, 292, 20, ORANGE);
+ color c = on ? WHITE : DARK;
+ text(nth(opt_names, r), 22, y, 2, c);
+ bool arrows = on && opt_count[r] > 1;
+ int vx = 298 - tw(v, 2) - (arrows ? 12 : 0);
+ if (on || r != O_RESET) text(v, vx, y, 2, on ? WHITE : ORANGE);
+ if (arrows) text("<", vx - 12, y, 2, c), text(">", 294, y, 2, c);
+ }
+ fill(306, 44 + top_row * 146 / NOPT, 3, 8 * 146 / NOPT, mix(DARK, BEIGE, 14)); /* where we are */
+ ctext(nth("For Custom games\0For both games\0Back to the defaults", sel < O_BIRD ? 0 : sel < O_RESET ? 1 : 2), 160, 216, 1, DARK);
+ ctext("Left/Right: change Back: done", 160, 228, 1, RGB(0x9A7F4E));
+}
+
+static void pause_draw(void) {
+ shade(0, 0, W, H, 0, 12);
+ board(80, 58, 160, 118);
+ if (paused == 2) {
+ ctext("Quit game?", 160, 76, 2, DARK);
+ button(94, 120, 60, 28, "Yes", psel == 1, false, 2);
+ button(166, 120, 60, 28, "No", psel == 0, false, 2);
+ return;
+ }
+ ctext("Paused", 160, 68, 2, ORANGE);
+ for (int i = 0; i < 3; i++) {
+ int y = 92 + i * 26;
+ if (psel == i) rrect(92, y - 4, 136, 22, ORANGE);
+ ctext(nth("Resume\0Restart\0Quit game", i), 160, y, 2, psel == i ? WHITE : DARK);
+ }
+}
+
+static void ui(void) {
+ switch (state) {
+ case S_TITLE: {
+ int b = bob(90, 4), lx = (W - lw - 56) / 2;
+ lettering(lx, 28 + b, 32);
+ button(44, 112, 110, 38, "Classic", sel == 0, true, 2);
+ button(166, 112, 110, 38, "Custom", sel == 1, true, 2);
+ for (int i = 0; i < 2; i++) {
+ char t[16] = "Best ";
+ num(t + 5, sv.best[i]);
+ otext(t, 99 + 122 * i - tw(t, 1) / 2, 158, 1, WHITE);
+ }
+ button(116, 172, 88, 20, "Settings", sel == 2, false, 1); /* small, like the original's Rate */
+ ctext("Based on Tatone26's version", 160, 222, 1, RGB(0x9A7F4E));
+ break;
+ }
+ case S_SETTINGS:
+ settings_draw();
+ break;
+ case S_READY:
+ big(0, W / 2, 14, 3, true);
+ lettering(W / 2 - lw / 2, 48, 32);
+ tap_hint(186, 96);
+ break;
+ case S_PLAY:
+ case S_DEAD:
+ if (tick < 8 && state == S_PLAY) { /* Get Ready fades out */
+ ga = 32 - tick * 4;
+ lettering(W / 2 - lw / 2, 48, ga);
+ tap_hint(186, 96);
+ ga = 32;
+ }
+ big(score, W / 2, 14, 3, true);
+ if (countdown) big((countdown + 49) / 50, W / 2, 88, 6, true);
+ if (ban_e) { /* the event's name, on the ground */
+ const char *s = nth(ev_names, ban_e);
+ int w = tw(s, 2) + 16, t = ban_t, out = t < 10 ? 10 - t : t > 160 ? t - 160 : 0, x = 8 - (w + 8) * out / 10;
+ if (!(pwarm || fwarm) || (t & 8)) {
+ rrect(x, 213, w, 22, DARK);
+ rrect(x + 1, 214, w - 2, 20, ORANGE);
+ text(s, x + 8, 217, 2, WHITE);
+ }
+ }
+ break;
+ case S_OVER: {
+ int t = tick;
+ lettering(W / 2 - lw / 2, 14 - imax(0, 8 - t), imin(32, t * 4));
+ if (t >= 16) panel(panel_y(t));
+ if (t >= done_t + 6) {
+ button(80, BTY, 76, 26, "Play", sel == 0, true, 2);
+ button(164, BTY, 76, 26, "Menu", sel == 1, false, 2);
+ }
+ break;
+ }
+ }
+ if (nocoll && state >= S_READY && state <= S_DEAD) otext("PRACTICE", W / 2 - 23, 42, 1, WHITE); /* scores don't count */
+ if (paused) pause_draw();
+ if (flash) shade(0, 0, W, H, WHITE, flash);
+ if (fade_t) shade(0, 0, W, H, 0, (fade_t < 7 ? fade_t : 13 - fade_t) * 5);
+}
+
+static void compose(void) {
+ background();
+ pipes_draw();
+ streaks_draw();
+ bird_draw();
+ ui();
+}
+static void paint(int x, int y, int w, int h) {
+ for (int band = BUFN / w, y1 = y + h; y < y1; y += band) {
+ rx = x, ry = y, rw = w, rh = imin(band, y1 - y);
+ compose();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)rx, (uint16_t)ry, (uint16_t)rw, (uint16_t)rh}, buf);
+ }
+}
+
+/* what moved since the last frame goes to the screen */
+static int logo_y;
+static void flush(void) {
+ bird_on = state != S_SETTINGS, bird_s = state == S_TITLE;
+ switch (state) {
+ case S_TITLE: bird_x = (W + lw + 56) / 2 - 24, bird_y = 30 + lh / 2 + bob(90, 4); break;
+ case S_READY: bird_x = BX, bird_y = 100 + bob(60, 4); break;
+ default: bird_x = BX, bird_y = by >> 8;
+ }
+ if (state == S_TITLE && bob(90, 4) != logo_y) {
+ int b = bob(90, 4);
+ add((W - lw - 56) / 2, 28 + imin(b, logo_y), lw, lh + iabs(b - logo_y));
+ logo_y = b;
+ }
+ for (int i = 0; i < NP; i++) pipe_dirty(&P[i]);
+ /* (the bird only appears, goes or changes size with a new screen, drawn whole) */
+ int h = 15 << bird_s;
+ if (bird_x != bd_x || bird_y != bd_y || bird_a != bd_a || bird_f != bd_f) {
+ add2(bd_x - h, bd_y - h, bird_x - h, bird_y - h, 2 * h, 2 * h);
+ bd_x = bird_x, bd_y = bird_y, bd_a = bird_a, bd_f = bird_f;
+ }
+ for (int i = 0; i < NS; i++) { /* a streak that moved: where it was and where it is, as one box */
+ int b[4] = {0, 0, 0, 0};
+ int16_t *o = st[i].b;
+ if (st[i].life) streak_box(st[i].x, st[i].y, st[i].vx, st[i].vy, st[i].len, b);
+ if (st[i].drawn && st[i].life && o[2] == b[2] && o[3] == b[3]) add2(o[0], o[1], b[0], b[1], b[2], b[3]);
+ else {
+ if (st[i].drawn) add(o[0], o[1], o[2], o[3]);
+ add(b[0], b[1], b[2], b[3]);
+ }
+ for (int j = 0; j < 4; j++) o[j] = (int16_t)b[j];
+ st[i].drawn = st[i].life != 0;
+ }
+ if (gph != gph_drawn) add(0, GY + 2, W, 10), gph_drawn = gph;
+ if (flash || flashed) full = true;
+ flashed = flash;
+ eadk_display_wait_for_vblank();
+ if (full)
+ for (int y = 0; y < H; y += BUFN / W) paint(0, y, W, BUFN / W);
+ else
+ for (int i = 0; i < nd; i++) paint(dq[i][0], dq[i][1], dq[i][2], dq[i][3]);
+ nd = 0, full = false;
+}
+
+/* ------------------------------------------------------------------ input */
+#define FLAP (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_up) | KEY(eadk_key_eight) | KEY(eadk_key_five))
+
+static void input(uint64_t hit) {
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);
+ int lr = !!(hit & (KEY(eadk_key_right) | KEY(eadk_key_six))) - !!(hit & (KEY(eadk_key_left) | KEY(eadk_key_four)));
+ int ud = !!(hit & (KEY(eadk_key_down) | KEY(eadk_key_two))) - !!(hit & (KEY(eadk_key_up) | KEY(eadk_key_eight)));
+ if (paused) {
+ int was = paused * 4 + psel;
+ if (paused == 2) {
+ if (lr || ud) psel ^= 1;
+ if (ok && psel) keep_best(), leave = true;
+ else if ((back || ok) && state == S_TITLE) paused = 0; /* asked from the title */
+ else if (back || ok) paused = 1, psel = 2;
+ } else {
+ psel = clamp(psel + ud, 0, 2);
+ if (back || (ok && psel == 0)) {
+ paused = 0;
+ if (state == S_PLAY) countdown = 150;
+ } else if (ok && psel == 1) {
+ keep_best();
+ go(new_game);
+ } else if (ok) {
+ paused = 2, psel = 0;
+ }
+ }
+ if (paused * 4 + psel != was || !paused) full = true;
+ return;
+ }
+ switch (state) {
+ case S_TITLE: {
+ int was = sel;
+ if (sel < 2 && lr) sel ^= 1;
+ if (ud > 0) sel = 2;
+ if (ud < 0 && sel == 2) sel = sv.mode;
+ if (sel != was) add(40, 106, 240, 90);
+ if (back) paused = 2, psel = 0, full = true;
+ else if (ok && sel == 2) to_settings();
+ else if (ok) {
+ if (sv.mode != sel) sv.mode = (uint8_t)sel, save_dirty = true;
+ go(new_game);
+ }
+ break;
+ }
+ case S_SETTINGS:
+ if (back) {
+ save();
+ to_title();
+ sel = 2;
+ break;
+ }
+ if (ud || lr || ok) add(8, 40, 304, 158), add(0, 214, W, 12);
+ sel = clamp(sel + ud, 0, NOPT - 1);
+ top_row = clamp(top_row, sel - 7, sel);
+ if (sel == O_RESET) {
+ if (ok)
+ for (int i = 0; i < NOPT; i++) sv.opt[i] = opt_default[i], save_dirty = true;
+ } else if (lr || ok) {
+ int n = opt_count[sel];
+ sv.opt[sel] = (uint8_t)((sv.opt[sel] + (lr ? lr : 1) + n) % n), save_dirty = true;
+ }
+ break;
+ case S_READY:
+ if (back) paused = 1, psel = 0, full = true;
+ else if (hit & FLAP) by = (100 + bob(60, 4)) << 8, state = S_PLAY, tick = 0, flap();
+ break;
+ case S_PLAY:
+ if (back) paused = 1, psel = 0, full = true;
+ else if ((hit & FLAP) && !countdown) flap();
+ break;
+ case S_OVER:
+ if (tick < done_t + 6) break;
+ if (lr) sel ^= 1, add(76, BTY - 4, 168, 36);
+ if (back || (ok && sel)) go(to_title);
+ else if (ok) go(new_game);
+ break;
+ }
+}
+
+int main(void) {
+ np_app_begin();
+ for (int i = 0; i < 128; i++) { /* Bhaskara's sine */
+ float x = i * (3.14159265f / 128), q = x * (3.14159265f - x);
+ sn[i] = (int16_t)(16 * q / (49.348022f - 4 * q) * 256 + 0.5f);
+ sn[i + 128] = (int16_t)-sn[i];
+ }
+ uint32_t last = (uint32_t)eadk_timing_millis();
+ seed ^= last ^ eadk_random();
+ make_pipes();
+ for (int i = 0; i < NP; i++) P[i].dx = OFF;
+ load();
+ to_title();
+ uint64_t held = ~0ull; /* keys still down from the launcher count only once released */
+ uint32_t repeat_at = 0;
+ int acc = 0;
+ for (;;) {
+ uint32_t now = (uint32_t)eadk_timing_millis();
+ acc = imin(acc + (int)(now - last) * 3, 200), last = now;
+ uint64_t k = eadk_keyboard_scan(), hit = k & ~held;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) {
+ keep_best();
+ break;
+ }
+ const uint64_t rep = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down) |
+ KEY(eadk_key_two) | KEY(eadk_key_four) | KEY(eadk_key_six) | KEY(eadk_key_eight);
+ if (hit & rep) repeat_at = now + 350;
+ else if ((k & rep) && (int32_t)(now - repeat_at) >= 0 && (state == S_SETTINGS || paused))
+ hit |= k & rep, repeat_at = now + 90;
+ held = k;
+ if (!fade_t) input(hit);
+ if (leave) break;
+ for (; acc >= 25; acc -= 50) /* 60 steps a second, whatever the frame rate */
+ if (!paused || fade_t) step();
+ flush();
+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;
+ if (spent < 15) eadk_timing_msleep(15 - spent);
+ }
+ save();
+ return np_app_end();
+}
diff --git a/games/g2048/.gitignore b/games/g2048/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/g2048/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/g2048/Makefile b/games/g2048/Makefile
new file mode 100644
index 00000000..fe5cdc22
--- /dev/null
+++ b/games/g2048/Makefile
@@ -0,0 +1,56 @@
+# 2048 — slide the tiles, join equal numbers, get to 2048.
+# make build output/g2048.nwa
+# make check link the app like the calculator does (output/g2048.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/g2048.nwa
+
+check: $(BUILD_DIR)/g2048.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/g2048.bin
+ @echo "BIN $(BUILD_DIR)/g2048.bin: $$(wc -c < $(BUILD_DIR)/g2048.bin) bytes"
+
+# compiled, then linked (the link options would upset the compiler)
+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@
+
+$(BUILD_DIR)/g2048.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(BUILD_DIR)/main.o
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_g2048_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_g2048_main -o $@
diff --git a/games/g2048/README.md b/games/g2048/README.md
new file mode 100644
index 00000000..47914d92
--- /dev/null
+++ b/games/g2048/README.md
@@ -0,0 +1,40 @@
+# 2048
+
+Slide the tiles, join equal numbers, get to 2048. Gabriele Cirulli's puzzle for the NumWorks calculator, looking and moving like the original.
+
+<img src="docs/shot.png" width="320" alt="A game of 2048 in progress">
+
+- **Four board sizes:** 3×3, 4×4 (the classic), 5×5 and 6×6. On 3×3 the goal is 512.
+- **Undo:** take back your last move, even from the Game over screen.
+- **Keep going** after 2048: the tiles go on to 4096, 8192 and beyond.
+- Your game and your best score are kept for each size, so you can stop and carry on later.
+- Tiles slide, pop when they merge and zoom in when they appear, the big ones glow, and the points you win rise from the score.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows, or 8 4 6 2 | Slide the tiles |
+| ⌫ | Undo |
+| Back | Pause: Resume, New game, Quit game |
+| OK | Choose |
+
+On the title screen, **Left / Right** pick the board size and **Up / Down** choose between Continue and New game.
+
+Everything is drawn with code, and all the text comes from one small stroke font drawn with a round pen at any size, so the whole game is about 12 KB.
+
+## Credits
+
+2048 is **[Gabriele Cirulli](https://github.com/gabrielecirulli/2048)**'s game (2014), itself based on 1024 by Veewo Studio and similar in concept to Threes by Asher Vollmer.
+
+The starting point for this version was **[Tatone26](https://github.com/Tatone26)**'s Python 2048 in [Numworks-games](https://github.com/Tatone26/Numworks-games/blob/main/python%20games/g2048.py) (All the Apps), released into the public domain. This one is written in C for NumPlay. Compared with it:
+
+- the look of Cirulli's original: its colours, rounded tiles and bold numbers, the score and best boxes, and the You win! and Game over! messages;
+- smooth animations, and Undo;
+- winning, then keeping on after 2048;
+- the game in progress and the best score saved for each size;
+- sizes from 3×3 to 6×6 (7×7 and 8×8 left out: their numbers would be too small to read).
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `2048.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/g2048/docs/shot.png b/games/g2048/docs/shot.png
new file mode 100644
index 00000000..7678d179
Binary files /dev/null and b/games/g2048/docs/shot.png differ
diff --git a/games/g2048/src/icon.png b/games/g2048/src/icon.png
new file mode 100644
index 00000000..19227b82
Binary files /dev/null and b/games/g2048/src/icon.png differ
diff --git a/games/g2048/src/main.c b/games/g2048/src/main.c
new file mode 100644
index 00000000..932a7d85
--- /dev/null
+++ b/games/g2048/src/main.c
@@ -0,0 +1,971 @@
+/* 2048: slide the tiles, join equal numbers, get to 2048.
+ *
+ * Gabriele Cirulli's game, looking like his: the beige page, the brown board,
+ * warm tiles that slide, pop when they merge and zoom in when they appear,
+ * and "+N" rising from the score. Only what changes is drawn, composed in RAM
+ * a few rows at a time, and every letter comes from one small stroke font (a
+ * handful of points and curves each) drawn with a round pen at any size. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "2048";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+#define W 320
+#define H 240
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define PAGE RGB(0xFAF8EF)
+#define BOARD RGB(0xBBADA0)
+#define SLOT RGB(0xCDC1B4)
+#define INK RGB(0x776E65)
+#define LIGHT RGB(0xF9F6F2)
+#define BROWN RGB(0x8F7A66)
+#define LABEL RGB(0xEEE4DA)
+#define KEY(k) (1ull << (k))
+#define WT 2.4f /* the bold pen, in font units (a capital is 12 units tall) */
+
+/* 2, 4, 8 ... 2048, and everything above */
+static const color tile_bg[12] = {RGB(0xEEE4DA), RGB(0xEDE0C8), RGB(0xF2B179), RGB(0xF59563),
+ RGB(0xF67C5F), RGB(0xF65E3B), RGB(0xEDCF72), RGB(0xEDCC61),
+ RGB(0xEDC850), RGB(0xEDC53F), RGB(0xEDC22E), RGB(0x3C3A32)};
+
+static uint32_t now, seed = 0x9E3779B9u, useed;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+static int fl(float v) { return (int)__builtin_floorf(v); }
+static float ease(float t) {
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
+ return t * t * (3 - 2 * t);
+}
+/* fast, then slowing down: how pops and new tiles grow */
+static float grow(float t) {
+ t = 1 - t;
+ return 1 - t * t * t;
+}
+static char *num(char *o, uint32_t v) {
+ char t[10];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+
+/* ------------------------------------------------------------ drawing */
+/* A rectangle of the screen is composed in buf, bx1 - bx0 pixels a row, then
+ pushed: every pixel is written once, so nothing flickers. */
+#define BUF (W * 16)
+#define GH 48 /* at most this many rows at a time */
+static color buf[BUF];
+static int bx0, by0, bx1, by1;
+
+/* Colours spread out as 0x0GGRRBB-ish words, so one multiply blends all three */
+#define SPREAD(c) (((c) | (uint32_t)(c) << 16) & 0x07E0F81F)
+/* c over the pixel at p; v from 0 (none) to 32 (all c). Inlined: it runs for
+ every smooth or see-through pixel. */
+static inline __attribute__((always_inline)) void put(color *p, color c, int v) {
+ if (v >= 32) *p = c;
+ else if (v > 0) {
+ uint32_t y = SPREAD(*p);
+ y = (y * (uint32_t)(32 - v) + SPREAD(c) * (uint32_t)v) >> 5 & 0x07E0F81F;
+ *p = (color)(y | y >> 16);
+ }
+}
+/* n pixels of c, two at a time */
+static void span(color *p, int n, color c) {
+ if (n <= 0) return;
+ if ((uintptr_t)p & 2) *p++ = c, n--;
+ uint32_t cc = c | (uint32_t)c << 16, *q = (uint32_t *)(void *)p;
+ for (; n >= 2; n -= 2) *q++ = cc;
+ if (n) *(color *)q = c;
+}
+/* n pixels of c at opacity v over what is there (the washes over the board) */
+static void blend(color *p, int n, color c, int v) {
+ uint32_t f = SPREAD(c) * (uint32_t)v, k = 32 - (uint32_t)v;
+ for (; n > 0; n--, p++) {
+ uint32_t y = (SPREAD(*p) * k + f) >> 5 & 0x07E0F81F;
+ *p = (color)(y | y >> 16);
+ }
+}
+static bool hits(float x, float y, float w, float h) { return x < bx1 && x + w > bx0 && y < by1 && y + h > by0; }
+static color *row(int y) { return buf + (y - by0) * (bx1 - bx0) - bx0; }
+
+/* coverage of a pixel whose centre is d pixels outside an edge that fades
+ over soft pixels (1 for a sharp edge) */
+static float soft = 1;
+static int cover(float d) {
+ int v = (int)((0.5f - d / soft) * 32);
+ return v < 0 ? 0 : v > 32 ? 32 : v;
+}
+
+/* A rounded box with smooth edges, at any position and size; a: 0..32 */
+static void rbox(float x, float y, float w, float h, float r, color c, int a) {
+ float o = soft * 0.5f - 0.5f; /* how far a soft edge fades out beyond the box */
+ if (w <= 0 || h <= 0 || a <= 0 || !hits(x - o, y - o, w + 2 * o, h + 2 * o)) return;
+ float hx = w * 0.5f, hy = h * 0.5f, mx = x + hx, my = y + hy;
+ if (r > hx) r = hx;
+ if (r > hy) r = hy;
+ float ix = hx - r, iy = hy - r;
+ int x0 = fl(x - o), x1 = -fl(o - x - w), y0 = fl(y - o), y1 = -fl(o - y - h);
+ if (x0 < bx0) x0 = bx0;
+ if (x1 > bx1) x1 = bx1;
+ if (y0 < by0) y0 = by0;
+ if (y1 > by1) y1 = by1;
+ for (int j = y0; j < y1; j++) {
+ float qy = __builtin_fabsf(j + 0.5f - my) - iy;
+ color *p = row(j);
+ /* the middle of the row is all alike: all covered between the straight
+ sides, or as much as the row between the corners */
+ float e = qy <= 0 && r >= 0.5f * soft ? hx - 0.5f * soft : ix;
+ int s0 = -fl(e + 0.5f - mx), s1 = fl(mx + e - 0.5f) + 1, rv = cover((qy > -1 ? qy : -1) - r) * a >> 5;
+ if (s0 < x0) s0 = x0;
+ if (s1 > x1) s1 = x1;
+ if (s1 <= s0) s0 = s1 = x1;
+ if (rv >= 32) span(p + s0, s1 - s0, c);
+ else if (rv > 0) blend(p + s0, s1 - s0, c, rv);
+ for (int i = x0; i < x1; i++) { /* the edges */
+ if (i == s0) i = s1;
+ if (i >= x1) break;
+ float qx = __builtin_fabsf(i + 0.5f - mx) - ix, d;
+ if (qx > 0 && qy > 0) d = __builtin_sqrtf(qx * qx + qy * qy) - r;
+ else d = (qx > qy ? qx : qy) - r;
+ put(p + i, c, cover(d) * a >> 5);
+ }
+ }
+}
+
+/* ------------------------------------------------------------ the font */
+/* Each letter is a few strokes through points on a grid of half units: x
+ from 0, y from 0 (capital height) through 6 (x-height) to 24 (baseline)
+ and 30 (descenders). Points are on the stroke, or C: the control point of
+ a curve (two in a row imply an on-point halfway, as in TrueType fonts). E
+ ends a stroke, Z ends it by closing it, G ends the letter. */
+#define P(x, y) ((x) | (y) << 5)
+#define C(x, y) (P(x, y) | 1 << 10)
+#define E (1 << 11)
+#define Z (3 << 11)
+#define G (1 << 13 | E)
+#define BOWL P(6, 6), C(12, 6), P(12, 15), C(12, 24), P(6, 24), C(0, 24), P(0, 15), C(0, 6) | Z
+static const char font_chars[] = "0123456789BCEGJKMNOPQRSTUYabdeghilmnoprstuvwy!?+-'*<>\x7f~";
+static const uint16_t font[] = {
+ /* 0 */ P(7, 0), C(14, 0), P(14, 8), P(14, 16), C(14, 24), P(7, 24), C(0, 24), P(0, 16), P(0, 8), C(0, 0) | Z | G,
+ /* 1 */ P(3, 5), P(9, 0), P(9, 24) | G,
+ /* 2 */ P(1, 5), C(1, 0), P(7, 0), C(14, 0), P(14, 7), C(14, 11), P(11, 14), P(0, 24), P(14, 24) | G,
+ /* 3 */ P(1, 4), C(2, 0), P(7, 0), C(13, 0), P(13, 6), C(13, 11), P(6, 11), C(14, 11), P(14, 17), C(14, 24),
+ P(7, 24), C(1, 24), P(0, 20) | G,
+ /* 4 */ P(10, 24), P(10, 0), P(0, 16), P(14, 16) | G,
+ /* 5 */ P(13, 0), P(2, 0), P(1, 11), C(3, 8), P(8, 8), C(14, 8), P(14, 16), C(14, 24), P(7, 24), C(1, 24),
+ P(0, 20) | G,
+ /* 6 */ P(13, 3), C(11, 0), P(7, 0), C(0, 0), P(0, 9), P(0, 16), C(0, 24), P(7, 24), C(14, 24), P(14, 16),
+ C(14, 9), P(7, 9), C(0, 9), P(0, 15) | G,
+ /* 7 */ P(0, 0), P(14, 0), P(4, 24) | G,
+ /* 8 */ P(7, 0), C(13, 0), P(13, 6), C(13, 11), P(7, 11), C(1, 11), P(1, 6), C(1, 0) | Z, P(7, 11), C(14, 11),
+ P(14, 18), C(14, 24), P(7, 24), C(0, 24), P(0, 18), C(0, 11) | Z | G,
+ /* 9 */ P(1, 21), C(3, 24), P(7, 24), C(14, 24), P(14, 15), P(14, 8), C(14, 0), P(7, 0), C(0, 0), P(0, 8),
+ C(0, 15), P(7, 15), C(14, 15), P(14, 9) | G,
+ /* B */ P(0, 12), P(8, 12), C(14, 12), P(14, 18), C(14, 24), P(8, 24), P(0, 24), P(0, 0), P(7, 0), C(13, 0),
+ P(13, 6), C(13, 12), P(7, 12) | G,
+ /* C */ P(15, 4), C(13, 0), P(8, 0), C(0, 0), P(0, 8), P(0, 16), C(0, 24), P(8, 24), C(13, 24), P(15, 20) | G,
+ /* E */ P(13, 0), P(0, 0), P(0, 24), P(13, 24) | E, P(0, 12), P(11, 12) | G,
+ /* G */ P(15, 4), C(13, 0), P(8, 0), C(0, 0), P(0, 8), P(0, 16), C(0, 24), P(8, 24), C(15, 24), P(15, 16),
+ P(15, 13), P(9, 13) | G,
+ /* J */ P(10, 0), P(10, 17), C(10, 24), P(5, 24), C(0, 24), P(0, 19) | G,
+ /* K */ P(0, 0), P(0, 24) | E, P(13, 0), P(1, 14) | E, P(5, 10), P(14, 24) | G,
+ /* M */ P(0, 24), P(0, 0), P(9, 16), P(18, 0), P(18, 24) | G,
+ /* N */ P(0, 24), P(0, 0), P(14, 24), P(14, 0) | G,
+ /* O */ P(8, 0), C(16, 0), P(16, 8), P(16, 16), C(16, 24), P(8, 24), C(0, 24), P(0, 16), P(0, 8), C(0, 0) | Z | G,
+ /* P */ P(0, 24), P(0, 0), P(7, 0), C(14, 0), P(14, 7), C(14, 14), P(7, 14), P(0, 14) | G,
+ /* Q */ P(8, 0), C(16, 0), P(16, 8), P(16, 16), C(16, 24), P(8, 24), C(0, 24), P(0, 16), P(0, 8), C(0, 0) | Z,
+ P(10, 18), P(16, 25) | G,
+ /* R */ P(0, 24), P(0, 0), P(7, 0), C(14, 0), P(14, 7), C(14, 13), P(7, 13), P(0, 13) | E, P(7, 13),
+ P(14, 24) | G,
+ /* S */ P(14, 4), C(12, 0), P(7, 0), C(0, 0), P(0, 6), C(0, 11), P(7, 12), C(14, 13), P(14, 18), C(14, 24),
+ P(7, 24), C(2, 24), P(0, 20) | G,
+ /* T */ P(0, 0), P(14, 0) | E, P(7, 0), P(7, 24) | G,
+ /* U */ P(0, 0), P(0, 16), C(0, 24), P(7, 24), C(14, 24), P(14, 16), P(14, 0) | G,
+ /* Y */ P(0, 0), P(7, 12), P(14, 0) | E, P(7, 12), P(7, 24) | G,
+ /* a */ P(1, 9), C(3, 6), P(7, 6), C(12, 6), P(12, 11), P(12, 24) | E, P(12, 15), P(6, 15), C(0, 15), P(0, 20),
+ C(0, 24), P(5, 24), C(10, 24), P(12, 21) | G,
+ /* b */ P(0, 0), P(0, 24) | E, BOWL | G,
+ /* d */ BOWL, P(12, 0), P(12, 24) | G,
+ /* e */ P(0, 15), P(12, 15), C(12, 6), P(6, 6), C(0, 6), P(0, 15), C(0, 24), P(6, 24), C(10, 24), P(12, 21) | G,
+ /* g */ BOWL, P(12, 6), P(12, 25), C(12, 30), P(6, 30), C(2, 30), P(1, 28) | G,
+ /* h */ P(0, 0), P(0, 24) | E, P(0, 13), C(0, 6), P(6, 6), C(12, 6), P(12, 12), P(12, 24) | G,
+ /* i */ P(0, 0), P(0, 0) | E, P(0, 7), P(0, 24) | G,
+ /* l */ P(0, 0), P(0, 24) | G,
+ /* m */ P(0, 6), P(0, 24) | E, P(0, 12), C(0, 6), P(5, 6), C(10, 6), P(10, 12), P(10, 24) | E, P(10, 12),
+ C(10, 6), P(15, 6), C(20, 6), P(20, 12), P(20, 24) | G,
+ /* n */ P(0, 6), P(0, 24) | E, P(0, 12), C(0, 6), P(6, 6), C(12, 6), P(12, 12), P(12, 24) | G,
+ /* o */ BOWL | G,
+ /* p */ BOWL, P(0, 6), P(0, 30) | G,
+ /* r */ P(0, 6), P(0, 24) | E, P(0, 14), C(0, 6), P(8, 6) | G,
+ /* s */ P(11, 8), C(10, 6), P(6, 6), C(1, 6), P(1, 10), C(1, 14), P(6, 15), C(12, 16), P(12, 20), C(12, 24),
+ P(6, 24), C(1, 24), P(0, 22) | G,
+ /* t */ P(3, 1), P(3, 20), C(3, 24), P(8, 24) | E, P(0, 6), P(9, 6) | G,
+ /* u */ P(0, 6), P(0, 18), C(0, 24), P(6, 24), C(12, 24), P(12, 18) | E, P(12, 6), P(12, 24) | G,
+ /* v */ P(0, 6), P(6, 24), P(12, 6) | G,
+ /* w */ P(0, 6), P(4, 24), P(9, 10), P(14, 24), P(18, 6) | G,
+ /* y */ P(0, 6), P(6, 24) | E, P(12, 6), P(5, 27), C(4, 30), P(1, 30) | G,
+ /* ! */ P(0, 0), P(0, 16) | E, P(0, 24), P(0, 24) | G,
+ /* ? */ P(0, 5), C(1, 0), P(6, 0), C(12, 0), P(12, 6), C(12, 11), P(6, 12), P(6, 16) | E, P(6, 24), P(6, 24) | G,
+ /* + */ P(0, 12), P(12, 12) | E, P(6, 6), P(6, 18) | G,
+ /* - */ P(0, 14), P(8, 14) | G,
+ /* ' */ P(0, 0), P(0, 6) | G,
+ /* * (times) */ P(0, 7), P(10, 17) | E, P(10, 7), P(0, 17) | G,
+ /* < */ P(8, 4), P(0, 12), P(8, 20) | G,
+ /* > */ P(0, 4), P(8, 12), P(0, 20) | G,
+ /* the Backspace key */ P(6, 4), P(24, 4), P(24, 20), P(6, 20), P(0, 12) | Z, P(11, 8), P(18, 16) | E, P(18, 8),
+ P(11, 16) | G,
+ /* the Back key */ P(10, 4), C(17, 4), P(17, 9), C(17, 14), P(10, 14), P(1, 14) | E, P(5, 10), P(1, 14),
+ P(5, 18) | G,
+};
+#define NCH (int)(sizeof font_chars - 1)
+static uint16_t font_at[NCH];
+static uint8_t font_w[NCH]; /* in half units; digits all get the same width */
+#define TRACK 1.0f /* space between letters, in units */
+
+static int8_t font_of[96]; /* the letter for each character from ' ', or -1 */
+static int gi(char c) { return (unsigned)(c - 32) < 96 ? font_of[c - 32] : -1; }
+static float advance(char c, float wt) {
+ int i = gi(c);
+ return i < 0 ? 3.6f : font_w[i] * 0.5f + wt + TRACK;
+}
+/* the width of s, in units */
+static float tw(const char *s, float wt) {
+ float w = -TRACK;
+ for (; *s; s++) w += advance(*s, wt);
+ return w;
+}
+
+static void font_init(void) {
+ for (int i = 0, k = 0; i < NCH; i++) { /* where each letter starts, and its width */
+ font_at[i] = (uint16_t)k;
+ int m = 0;
+ do
+ if ((font[k] & 31) > m) m = font[k] & 31;
+ while (!(font[k++] & 1 << 13));
+ font_w[i] = (uint8_t)(i < 10 ? 14 : m);
+ }
+ for (int c = 0; c < 96; c++) {
+ font_of[c] = -1;
+ for (int i = 0; i < NCH; i++)
+ if (font_chars[i] == c + 32) font_of[c] = (int8_t)i;
+ }
+}
+
+/* The pen draws into a coverage mask (0..32), mw x mh pixels at (mx0, my0);
+ each round-ended segment keeps the higher coverage, which is exactly the
+ coverage of the whole stroke. */
+static uint8_t gm[4096], *mk;
+static int mx0, my0, mw, mh, nseg;
+static float pen;
+
+static void seg(float ax, float ay, float bx, float by) {
+ float ro = pen + 0.5f, ri = pen - 0.5f, ro2 = ro * ro, ri2 = ri > 0 ? ri * ri : -1;
+ int x0 = fl((ax < bx ? ax : bx) - ro), x1 = fl((ax > bx ? ax : bx) + ro) + 1;
+ int y0 = fl((ay < by ? ay : by) - ro), y1 = fl((ay > by ? ay : by) + ro) + 1;
+ if (x0 < mx0) x0 = mx0;
+ if (x1 > mx0 + mw) x1 = mx0 + mw;
+ if (y0 < my0) y0 = my0;
+ if (y1 > my0 + mh) y1 = my0 + mh;
+ float ex = bx - ax, ey = by - ay, l2 = ex * ex + ey * ey, inv = l2 > 1e-4f ? 1 / l2 : 0;
+ for (int j = y0; j < y1; j++) {
+ uint8_t *m = mk + (j - my0) * mw - mx0;
+ for (int i = x0; i < x1; i++) {
+ float dx = i + 0.5f - ax, dy = j + 0.5f - ay, t = (dx * ex + dy * ey) * inv;
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
+ dx -= t * ex, dy -= t * ey;
+ float d2 = dx * dx + dy * dy;
+ if (d2 >= ro2) continue;
+ int v = d2 <= ri2 ? 32 : (int)((ro - __builtin_sqrtf(d2)) * 32);
+ if (v > m[i]) m[i] = (uint8_t)v;
+ }
+ }
+}
+
+/* the strokes of letter g, its grid's origin at (ox, oy), h pixels a half unit */
+static void strokes(const uint16_t *g, float ox, float oy, float h) {
+#define PX(p) (ox + ((p) & 31) * h)
+#define PY(p) (oy + ((p) >> 5 & 31) * h)
+ for (;;) {
+ const uint16_t *s = g;
+ while (!(*g & E)) g++;
+ int n = (int)(g - s) + 1, closed = (*g >> 12) & 1;
+ float px = PX(s[0]), py = PY(s[0]);
+ for (int i = 1; i < n + closed; i++) {
+ uint16_t p = s[i % n];
+ float x = PX(p), y = PY(p);
+ if (!(p & 1 << 10)) {
+ seg(px, py, x, y);
+ } else { /* a curve through control point p, flattened */
+ uint16_t q = s[(i + 1) % n];
+ float ex = PX(q), ey = PY(q);
+ if (q & 1 << 10) ex = (ex + x) * 0.5f, ey = (ey + y) * 0.5f;
+ else i++;
+ for (int k = 1; k <= nseg; k++) {
+ float t = (float)k / nseg, u = 1 - t;
+ float cx = u * u * px + 2 * u * t * x + t * t * ex, cy = u * u * py + 2 * u * t * y + t * t * ey;
+ seg(px, py, cx, cy);
+ px = cx, py = cy;
+ }
+ x = ex, y = ey;
+ }
+ px = x, py = y;
+ }
+ if (*g++ & 1 << 13) return;
+ }
+}
+
+/* s into the mask (cleared first), its left edge at x and the top of its
+ capitals at y; u pixels a unit, wt the pen's width in units */
+static void raster(const char *s, float x, float y, float u, float wt) {
+ for (int i = 0; i < mw * mh; i++) mk[i] = 0;
+ pen = wt * u * 0.5f;
+ nseg = 2 + (int)(u * 1.5f);
+ if (nseg > 8) nseg = 8;
+ for (; *s; s++) {
+ int i = gi(*s);
+ if (i >= 0) strokes(font + font_at[i], x + pen, y + pen, u * 0.5f);
+ x += advance(*s, wt) * u;
+ }
+}
+
+/* a w x h mask with its corner at (x, y), in colour c, opacity a (0..32) */
+static void blit(const uint8_t *m, int x, int y, int w, int h, color c, int a) {
+ for (int j = y < by0 ? by0 : y; j < y + h && j < by1; j++) {
+ color *p = row(j);
+ const uint8_t *q = m + (j - y) * w - x;
+ for (int i = x < bx0 ? bx0 : x; i < x + w && i < bx1; i++)
+ if (q[i]) put(p + i, c, q[i] * a >> 5);
+ }
+}
+
+/* s drawn as for raster, in colour c, opacity a (0..32) */
+static void text(const char *s, float x, float y, float u, float wt, color c, int a) {
+ float w = tw(s, wt) * u, h = (15 + wt) * u;
+ if (a <= 0 || !hits(x, y, w, h)) return;
+ mx0 = fl(x), my0 = fl(y), mw = fl(x + w) + 1, mh = fl(y + h) + 1;
+ if (mx0 < bx0) mx0 = bx0;
+ if (my0 < by0) my0 = by0;
+ if (mw > bx1) mw = bx1;
+ if (mh > by1) mh = by1;
+ mw -= mx0, mh -= my0;
+ if (mw * mh > (int)sizeof gm) mh = (int)sizeof gm / mw; /* never with this game's text */
+ mk = gm;
+ raster(s, x, y, u, wt);
+ blit(gm, mx0, my0, mw, mh, c, a);
+}
+/* centred on (cx, cy), the middle of the capitals */
+static void ctext(const char *s, float cx, float cy, float u, float wt, color c, int a) {
+ text(s, cx - tw(s, wt) * u * 0.5f, cy - (12 + wt) * u * 0.5f, u, wt, c, a);
+}
+
+/* ------------------------------------------------------------ the game */
+static int n = 4; /* the board is n x n */
+static uint8_t cell[36], ucell[36]; /* 2 to the power of each, 0 when empty */
+static uint32_t score, uscore, moves, umoves;
+static bool can_undo, won;
+
+/* the last move, for its animation: every tile's slide, then what merged (1)
+ or appeared (2) where */
+static uint8_t sl_from[36], sl_to[36], sl_e[36], fx[36];
+static int nsl, lines; /* lines: the rows or columns that moved */
+static bool anim, slid, dir_rows; /* slid: the tiles reached their cells; dir_rows: left or right */
+static float slide_t; /* how far the tiles were drawn in their slide, 0..1 */
+static uint32_t t_move, t_add, added;
+#define SLIDE 100
+#define POP 200
+#define RISE 600
+
+static int at(int dir, int l, int k) { /* the k-th cell of line l, from the side the tiles go to */
+ switch (dir) {
+ case 0: return l * n + k;
+ case 3: return l * n + n - 1 - k;
+ case 1: return k * n + l;
+ default: return (n - 1 - k) * n + l;
+ }
+}
+
+static void spawn(void) {
+ int empty = 0;
+ for (int i = 0; i < n * n; i++) empty += !cell[i];
+ if (!empty) return;
+ int k = (int)(rnd() % (uint32_t)empty);
+ for (int i = 0; i < n * n; i++)
+ if (!cell[i] && !k--) {
+ cell[i] = rnd() % 10 ? 1 : 2; /* a 4 one time in ten */
+ fx[i] = 2;
+ return;
+ }
+}
+
+static bool can_move(void) {
+ for (int r = 0; r < n; r++)
+ for (int c = 0; c < n; c++) {
+ int e = cell[r * n + c]; /* 2^30 is as far as tiles go: two of them stay apart */
+ if (!e || (e < 30 && ((c + 1 < n && cell[r * n + c + 1] == e) || (r + 1 < n && cell[(r + 1) * n + c] == e))))
+ return true;
+ }
+ return false;
+}
+
+/* slides everything towards dir (0 left, 1 up, 2 down, 3 right); false if
+ nothing moved. Returns the merged tiles' highest power in *top. */
+static bool move(int dir, int *top) {
+ uint8_t nc[36] = {0}, nfx[36] = {0}, from[36], to[36], es[36]; /* kept only if something moves */
+ uint32_t gain = 0;
+ int ns = 0, ls = 0;
+ *top = 0;
+ for (int l = 0; l < n; l++) {
+ int k = 0, last = -1; /* last: where the previous tile went, while it can still merge */
+ for (int j = 0; j < n; j++) {
+ int s = at(dir, l, j), e = cell[s], d;
+ if (!e) continue;
+ if (last >= 0 && nc[last] == e && e < 30) {
+ d = last, nc[d] = (uint8_t)(e + 1), nfx[d] = 1, gain += 2u << e, last = -1;
+ if (e + 1 > *top) *top = e + 1;
+ } else {
+ d = at(dir, l, k++), nc[d] = (uint8_t)e, last = d;
+ }
+ from[ns] = (uint8_t)s, to[ns] = (uint8_t)d, es[ns++] = (uint8_t)e;
+ if (s != d) ls |= 1 << l;
+ }
+ }
+ if (!ls) return false;
+ for (int i = 0; i < 36; i++) ucell[i] = cell[i], cell[i] = nc[i], fx[i] = nfx[i];
+ for (int i = 0; i < ns; i++) sl_from[i] = from[i], sl_to[i] = to[i], sl_e[i] = es[i];
+ uscore = score, umoves = moves, can_undo = true;
+ score = score + gain < score ? 0xFFFFFFFFu : score + gain;
+ moves++;
+ nsl = ns, lines = ls, dir_rows = dir == 0 || dir == 3;
+ if (gain) added = gain, t_add = now;
+ useed = seed; /* Undo puts it back: the same move then brings the same tile */
+ spawn();
+ /* one frame in already: the frame of the key press shows the tiles moving */
+ anim = true, slid = false, slide_t = 0, t_move = now - 16;
+ return true;
+}
+
+/* ------------------------------------------------------------ saving */
+/* g2048.sav: the size last played, and for each size the best score and the
+ game in progress */
+static struct {
+ uint8_t magic, version, size, flags[4], pad; /* flags: 1 a game to continue, 2 won already */
+ uint32_t best[4], score[4], moves[4];
+ uint8_t cells[86];
+} sv;
+static const uint8_t cells_at[4] = {0, 9, 25, 50};
+#define SAVE_NAME "g2048.sav"
+
+static void check_save(void);
+static void load(void) {
+ uint32_t len = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &len);
+ uint8_t *v = (uint8_t *)&sv;
+ bool ok = d && len == sizeof sv && d[0] == '2' && d[1] == 1;
+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = ok ? d[i] : 0;
+ if (!ok) sv.size = 1; /* 4 x 4 */
+ check_save();
+}
+
+/* whatever sv holds, makes it a save this game could have written */
+static void check_save(void) {
+ sv.size &= 3;
+ for (int s = 0; s < 4; s++) {
+ int tiles = 0, k = s + 3;
+ sv.flags[s] &= 3;
+ for (int i = 0; i < k * k; i++) {
+ uint8_t *e = &sv.cells[cells_at[s] + i];
+ if (*e > 30) sv.flags[s] = 0; /* not a board this game made */
+ tiles += *e != 0;
+ }
+ if (!tiles) sv.flags[s] &= 2;
+ if (!(sv.flags[s] & 1))
+ for (int i = 0; i < k * k; i++) sv.cells[cells_at[s] + i] = 0;
+ if (sv.best[s] < sv.score[s]) sv.best[s] = sv.score[s];
+ }
+}
+
+static void save(void) {
+ sv.magic = '2', sv.version = 1;
+ ef_write(SAVE_NAME, &sv, sizeof sv);
+}
+
+/* ------------------------------------------------------------ screens */
+enum { O_NONE, O_WIN, O_OVER, O_PAUSE, O_QUIT };
+static int scene; /* 0 the title, 1 the game */
+static int ov, ov_under; /* the message over the board, and the one under the pause menu */
+static int sel, tsel; /* the button chosen in the message, on the title */
+static uint32_t ov_t; /* when the message starts to show */
+static bool over;
+
+typedef struct {
+ int x, y, n, cell, gap, size;
+ float r, tr; /* the board's and the tiles' corners */
+} geo_t;
+static geo_t gb;
+
+static geo_t board_geo(int k, int cx, int cy, int room) {
+ geo_t g;
+ g.n = k;
+ g.gap = room > 150 ? (k <= 4 ? 8 : 6) : (k <= 4 ? 4 : 3);
+ g.cell = (room - (k + 1) * g.gap) / k;
+ g.size = k * g.cell + (k + 1) * g.gap;
+ g.x = cx - g.size / 2, g.y = cy - g.size / 2;
+ g.r = g.gap * 0.4f + 1, g.tr = g.cell / 32.0f + 1; /* crisp, nearly square, like Cirulli's */
+ return g;
+}
+static float cell_x(const geo_t *g, int i) { return (float)(g->x + g->gap + (i % g->n) * (g->cell + g->gap)); }
+static float cell_y(const geo_t *g, int i) { return (float)(g->y + g->gap + (i / g->n) * (g->cell + g->gap)); }
+
+/* The numbers on the game's tiles are drawn once each (for the board's
+ size) and kept as masks: tiles at rest or sliding are always on whole
+ pixels, so the masks are exact. */
+static uint8_t tcm[12288];
+static uint16_t tc_at[32]; /* where 2^e's mask starts in tcm, plus 1 (0: not drawn yet) */
+static uint8_t tc_x[32], tc_y[32], tc_w[32], tc_h[32];
+static int tc_used;
+
+/* the tile 2^e in the cell at (x, y), scaled by s around its middle */
+static void tile(const geo_t *g, int e, float x, float y, float s, int a) {
+ float c = (float)g->cell, h = c * s, o = (c - h) * 0.5f;
+ if (e <= 0 || h < 1 || !hits(x + o - g->gap, y + o - g->gap, h + 2 * g->gap, h + 2 * g->gap)) return;
+ if (e >= 7 && e <= 11) { /* from 128 to 2048, a golden glow that fades out halfway to the next tile */
+ float m = g->gap * 0.25f * s;
+ soft = 2 * m;
+ rbox(x + o - m, y + o - m, h + 2 * m, h + 2 * m, g->tr * s + m, RGB(0xF3D774), (e - 3) * 2 * a >> 5);
+ soft = 1;
+ }
+ rbox(x + o, y + o, h, h, g->tr * s, tile_bg[e > 12 ? 11 : e - 1], a);
+ if (g->cell < 16 || s < 0.5f) return; /* a tile still too small for its number */
+ color col = e <= 2 ? INK : LIGHT;
+ bool keep = s == 1 && g == &gb;
+ if (!(keep && tc_at[e])) {
+ /* Cirulli's sizes for 1, 2, 3, 4... digits; small tiles have no room to
+ spare, so there every number is as big as it fits */
+ static const float big[] = {0.368f, 0.368f, 0.368f, 0.301f, 0.234f, 0.2f, 0.18f, 0.16f, 0.14f, 0.13f, 0.12f};
+ char str[12];
+ int len = (int)(num(str, 1u << e) - str);
+ float w = tw(str, WT), u = big[g->cell < 40 ? 2 : len] * h / (12 + WT), fit = h * 0.86f / w;
+ if (u > fit) u = fit;
+ float tx = (c - w * u) * 0.5f, ty = (c - (12 + WT) * u) * 0.5f; /* from the cell's corner */
+ mx0 = fl(tx), my0 = fl(ty), mw = fl(tx + w * u) + 1 - mx0, mh = fl(ty + (12 + WT) * u) + 1 - my0;
+ if (!keep || tc_used + mw * mh > (int)sizeof tcm) {
+ text(str, x + tx, y + ty, u, WT, col, a);
+ return;
+ }
+ mk = tcm + tc_used;
+ raster(str, tx, ty, u, WT);
+ tc_at[e] = (uint16_t)(tc_used + 1), tc_used += mw * mh;
+ tc_x[e] = (uint8_t)mx0, tc_y[e] = (uint8_t)my0, tc_w[e] = (uint8_t)mw, tc_h[e] = (uint8_t)mh;
+ }
+ blit(tcm + tc_at[e] - 1, (int)x + tc_x[e], (int)y + tc_y[e], tc_w[e], tc_h[e], col, a);
+}
+
+/* a board: cells, with the last move's animation when it is the game's */
+static void board(const geo_t *g, const uint8_t *cells, bool live) {
+ if (!hits((float)g->x, (float)g->y, (float)g->size, (float)g->size)) return;
+ rbox((float)g->x, (float)g->y, (float)g->size, (float)g->size, g->r, BOARD, 32);
+ int k = g->n * g->n;
+ uint32_t dt = now - t_move;
+ bool sliding = live && anim && dt < SLIDE;
+ uint8_t hide[36]; /* the cells under a tile at rest hide theirs */
+ for (int i = 0; i < k; i++) hide[i] = !sliding && cells[i] && !(live && anim && fx[i]);
+ for (int j = 0; sliding && j < nsl; j++) hide[sl_from[j]] |= sl_from[j] == sl_to[j];
+ for (int i = 0; i < k; i++)
+ if (!hide[i]) rbox(cell_x(g, i), cell_y(g, i), (float)g->cell, (float)g->cell, g->tr, SLOT, 32);
+ if (sliding) {
+ float t = ease((float)dt / SLIDE);
+ for (int j = 0; j < nsl; j++) {
+ float x0 = cell_x(g, sl_from[j]), y0 = cell_y(g, sl_from[j]); /* on whole pixels */
+ tile(g, sl_e[j], (float)fl(x0 + (cell_x(g, sl_to[j]) - x0) * t + 0.5f),
+ (float)fl(y0 + (cell_y(g, sl_to[j]) - y0) * t + 0.5f), 1, 32);
+ }
+ return;
+ }
+ float t = live && anim ? (float)(dt - SLIDE) / POP : 1;
+ for (int i = 0; i < k; i++) {
+ float x = cell_x(g, i), y = cell_y(g, i);
+ if (t >= 1 || !fx[i]) {
+ tile(g, cells[i], x, y, 1, 32);
+ } else if (fx[i] == 1) { /* the two tiles that merged, then the new one pops out of them */
+ tile(g, cells[i] - 1, x, y, 1, 32);
+ tile(g, cells[i], x, y, t < 0.5f ? 1.2f * grow(t * 2) : 1.2f - 0.2f * ease(t * 2 - 1), 32);
+ } else {
+ float s = grow(t);
+ tile(g, cells[i], x, y, s, (int)(s * 32));
+ }
+ }
+}
+
+static void score_box(float x, float y, float w, float h, const char *label, uint32_t v) {
+ char s[12];
+ rbox(x, y, w, h, 3, BOARD, 32);
+ ctext(label, x + w * 0.5f, y + 10, 0.6f, 2.8f, LABEL, 32);
+ num(s, v);
+ float u = 1.05f, fit = (w - 10) / tw(s, WT);
+ ctext(s, x + w * 0.5f, y + h - 12, u < fit ? u : fit, WT, LIGHT, 32);
+}
+
+static void button(float cx, float y, float w, float h, const char *s, bool on, int a) {
+ rbox(cx - w * 0.5f, y, w, h, 3, on ? BROWN : RGB(0xDDD3C8), a);
+ ctext(s, cx, y + h * 0.5f, 0.85f, 2.1f, on ? LIGHT : INK, a);
+}
+
+/* game screen: the left column */
+#define PX0 6
+#define PW 76
+#define SCORE_Y 62
+#define BEST_Y 108
+#define UNDO_Y 172
+#define MENU_Y 204
+
+/* how far the message has faded in, 0..32: quickly for the menus, slowly
+ for You win! and Game over!, as in the original */
+static int fade(void) {
+ int32_t d = (int32_t)(now - ov_t), len = ov >= O_PAUSE ? 120 : 500;
+ return d <= 0 ? 0 : d >= len ? 32 : d * 32 / len;
+}
+static int nbuttons(void) { return ov == O_PAUSE ? 3 : ov == O_OVER && !can_undo ? 1 : 2; }
+/* the middle of a gap between two rows of the board (k rows below the middle
+ one): there the message's title and buttons cover no tile's number */
+static float gap_y(int k) { return gb.y + (n / 2 + k) * (gb.cell + gb.gap) + gb.gap * 0.5f; }
+
+static void message(void) {
+ static const char *const titles[] = {"", "You win!", "Game over!", "Paused", "Quit game?"};
+ static const char *const labels[][3] = {{0}, {"Keep going", "Try again"}, {"Try again", "Undo"},
+ {"Resume", "New game", "Quit game"}, {"No", "Yes"}};
+ int f = fade(), nb = nbuttons();
+ if (!ov || !f) return;
+ float x = (float)gb.x, y = (float)gb.y, b = (float)gb.size, cx = x + b * 0.5f;
+ rbox(x, y, b, b, gb.r, ov == O_WIN ? RGB(0xEDC22E) : LABEL, (ov == O_WIN ? 20 : ov == O_OVER ? 27 : 29) * f >> 5);
+ ctext(titles[ov], cx, ov == O_PAUSE ? y + b * 0.2f : gap_y(0), b / 124, WT, ov == O_WIN ? LIGHT : INK, f);
+ for (int i = 0; i < nb; i++) {
+ if (ov == O_PAUSE) button(cx, y + b * 0.36f + i * 36, 132, 28, labels[ov][i], sel == i, f);
+ else button(cx + (nb == 1 ? 0 : (i * 2 - 1) * 50), gap_y(1) - 14, 92, 28, labels[ov][i], sel == i || nb == 1, f);
+ }
+}
+
+static uint32_t best0; /* the best score when this game started */
+static bool nbest; /* "New best!" is up */
+
+static void game_screen(void) {
+ char s[12];
+ text("2048", PX0 + 3, 8, 1.72f, WT, INK, 32);
+ score_box(PX0, SCORE_Y, PW, 40, "SCORE", score);
+ score_box(PX0, BEST_Y, PW, 40, "BEST", sv.best[n - 3]);
+ if (nbest) ctext("New best!", PX0 + PW * 0.5f, BEST_Y + 52, 0.62f, 2.6f, RGB(0xF65E3B), 32);
+ button(PX0 + PW * 0.5f, UNDO_Y, PW, 26, "\x7f Undo", can_undo, 32);
+ button(PX0 + PW * 0.5f, MENU_Y, PW, 26, "~ Menu", true, 32);
+ board(&gb, cell, true);
+ uint32_t dt = now - t_add;
+ if (added && dt < RISE) { /* the points of the last move rise out of the score box */
+ float t = (float)dt / RISE, u;
+ t *= t; /* slow, then faster, as it fades */
+ s[0] = '+';
+ num(s + 1, added);
+ u = (PW - 2) / tw(s, WT);
+ ctext(s, PX0 + PW * 0.5f, SCORE_Y - 7 - 16 * t, u < 0.8f ? u : 0.8f, WT, INK, (int)((1 - t) * 29));
+ }
+ message();
+}
+
+/* the title: size, best, and the game to continue */
+static const uint8_t demo[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
+static void title_screen(void) {
+ int s = sv.size, k = s + 3;
+ char str[8] = {(char)('0' + k), '*', (char)('0' + k), 0};
+ uint8_t cells[36];
+ geo_t g = board_geo(k, 82, 150, 114);
+ for (int i = 0; i < k * k; i++) { /* the game to continue, or a snake of tiles */
+ int r = i / k, c = r & 1 ? k - 1 - i % k : i % k, j = r * k + c;
+ cells[i] = sv.flags[s] & 1 ? sv.cells[cells_at[s] + i] : 0;
+ if (!(sv.flags[s] & 1) && j < 11 - (k == 3) * 2) cells[i] = demo[j + (k == 3) * 2];
+ }
+ text("2048", 20, 14, 3.0f, WT, INK, 32);
+ score_box(214, 16, 90, 42, "BEST", sv.best[s]);
+ const char *join = "Join the numbers and get to the ";
+ text(join, 20, 68, 0.62f, 2.0f, INK, 32);
+ /* then the goal, in bold */
+ text(k == 3 ? "512 tile!" : "2048 tile!", 20 + (tw(join, 2.0f) + 0.4f) * 0.62f, 68, 0.62f, 2.6f, INK, 32);
+ board(&g, cells, false);
+ text("<", 166, 104, 1.3f, WT, s ? INK : SLOT, 32);
+ text(">", 292, 104, 1.3f, WT, s < 3 ? INK : SLOT, 32);
+ ctext(str, 236, 114, 1.3f, WT, INK, 32);
+ if (sv.flags[s] & 1) button(236, 140, 132, 28, "Continue", tsel == 0, 32);
+ button(236, sv.flags[s] & 1 ? 176 : 150, 132, 28, "New game", tsel == 1 || !(sv.flags[s] & 1), 32);
+ ctext("Game by Gabriele Cirulli - based on Tatone26's version", 160, 226, 0.5f, 1.9f, BROWN, 32);
+}
+
+/* paints a rectangle of the screen, a few rows at a time */
+static void paint(int x, int y, int w, int h) {
+ if (x < 0) w += x, x = 0;
+ if (y < 0) h += y, y = 0;
+ if (x + w > W) w = W - x;
+ if (y + h > H) h = H - y;
+ if (w <= 0 || h <= 0) return;
+ int rows = BUF / w > GH ? GH : BUF / w;
+ for (int t = y; t < y + h; t += rows) {
+ bx0 = x, bx1 = x + w, by0 = t, by1 = t + rows < y + h ? t + rows : y + h;
+ span(buf, w * (by1 - by0), PAGE);
+ if (scene) game_screen();
+ else title_screen();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)t, (uint16_t)w, (uint16_t)(by1 - by0)}, buf);
+ }
+}
+
+/* what to paint this frame */
+static int16_t dirty[40][4];
+static int nd;
+static void mark(float x, float y, float w, float h) {
+ int x0 = fl(x), y0 = fl(y), x1 = fl(x + w) + 1, y1 = fl(y + h) + 1;
+ for (int i = 0; i < nd; i++) { /* one with any rectangle that costs no more together than apart */
+ int16_t *d = dirty[i];
+ int u0 = x0 < d[0] ? x0 : d[0], v0 = y0 < d[1] ? y0 : d[1];
+ int u1 = x1 > d[0] + d[2] ? x1 : d[0] + d[2], v1 = y1 > d[1] + d[3] ? y1 : d[1] + d[3];
+ if ((u1 - u0) * (v1 - v0) <= (x1 - x0) * (y1 - y0) + d[2] * d[3]) {
+ x0 = u0, y0 = v0, x1 = u1, y1 = v1, nd--, i = -1; /* and the union may take in more */
+ for (int k = 0; k < 4; k++) d[k] = dirty[nd][k];
+ }
+ }
+ if (nd == 40) nd = 0, x0 = y0 = 0, x1 = W, y1 = H;
+ int16_t *d = dirty[nd++];
+ d[0] = (int16_t)x0, d[1] = (int16_t)y0, d[2] = (int16_t)(x1 - x0), d[3] = (int16_t)(y1 - y0);
+}
+static void mark_all(void) { nd = 0, mark(0, 0, W, H); }
+static void mark_board(void) { mark((float)gb.x, (float)gb.y, (float)gb.size, (float)gb.size); }
+static void mark_pops(void) { /* the cells that pop or appear, and room to grow */
+ for (int i = 0; i < n * n; i++)
+ if (fx[i]) {
+ float m = gb.cell * 0.1f + gb.gap * 0.6f + 1;
+ mark(cell_x(&gb, i) - m, cell_y(&gb, i) - m, gb.cell + 2 * m, gb.cell + 2 * m);
+ }
+}
+/* in each line that moves, what the moving tiles sweep from slide_t to t1 */
+static void mark_slide(float t1) {
+ float m = gb.gap * 0.5f + 1, pitch = (float)(gb.cell + gb.gap);
+ for (int l = 0; l < n; l++)
+ if (lines >> l & 1) {
+ float lo = 999, hi = -999;
+ for (int j = 0; j < nsl; j++) {
+ int f = sl_from[j], d = sl_to[j];
+ if (f == d || (dir_rows ? f / n : f % n) != l) continue;
+ float a = dir_rows ? cell_x(&gb, f) : cell_y(&gb, f), b = (dir_rows ? cell_x(&gb, d) : cell_y(&gb, d)) - a;
+ float p0 = a + b * slide_t, p1 = a + b * t1;
+ if (p0 > p1) a = p0, p0 = p1, p1 = a;
+ if (p0 < lo) lo = p0;
+ if (p1 > hi) hi = p1;
+ }
+ if (lo > hi) continue;
+ float q = (dir_rows ? cell_y(&gb, l * n) : cell_x(&gb, l)) - gb.gap * 0.5f, len = hi - lo + gb.cell + 2 * m;
+ if (dir_rows) mark(lo - m, q, len, pitch);
+ else mark(q, lo - m, pitch, len);
+ }
+ slide_t = t1;
+}
+static void mark_score(void) { mark(PX0, SCORE_Y, PW, 40); }
+static void mark_buttons(void) { /* the message's buttons, when the choice changes */
+ if (ov == O_PAUSE) mark((float)gb.x, gb.y + gb.size * 0.36f, (float)gb.size, 100);
+ else mark((float)gb.x, gap_y(1) - 14, (float)gb.size, 28);
+}
+
+static void start(bool fresh) {
+ n = sv.size + 3;
+ gb = board_geo(n, 201, 120, 226);
+ for (int i = 0; i < 32; i++) tc_at[i] = 0; /* the numbers change size */
+ tc_used = 0;
+ for (int i = 0; i < 36; i++) cell[i] = 0, fx[i] = 0;
+ score = moves = 0, won = over = can_undo = false, added = 0, ov = O_NONE, best0 = sv.best[sv.size];
+ if (!fresh && sv.flags[sv.size] & 1) {
+ for (int i = 0; i < n * n; i++) cell[i] = sv.cells[cells_at[sv.size] + i];
+ score = sv.score[sv.size], moves = sv.moves[sv.size], won = sv.flags[sv.size] & 2;
+ anim = false;
+ } else {
+ spawn();
+ spawn();
+ anim = slid = true, t_move = now - SLIDE, nsl = 0;
+ }
+ over = !can_move();
+ if (over) ov = O_OVER, ov_t = now, sel = 0;
+ scene = 1;
+ mark_all();
+}
+
+/* keeps the game in sv (a finished game is not kept) */
+static void store(void) {
+ int s = sv.size;
+ for (int i = 0; i < n * n; i++) sv.cells[cells_at[s] + i] = over ? 0 : cell[i];
+ sv.flags[s] = (uint8_t)((over ? 0 : 1) | (won ? 2 : 0));
+ sv.score[s] = score, sv.moves[s] = moves;
+ if (sv.best[s] < score) sv.best[s] = score;
+}
+
+/* Quit game (and Back on the title): back to NumPlay's games, or the
+ calculator's home screen; main keeps the game on the way out */
+static bool leave;
+static void quit_game(void) { leave = true; }
+
+static void new_game(void) {
+ over = true; /* the old one is dropped */
+ store();
+ save();
+ start(true);
+}
+
+/* the message o, after delay ms (a negative delay: already faded in) */
+static void show(int o, int32_t delay) {
+ ov = o, sel = 0, ov_t = now + (uint32_t)delay;
+}
+
+static void undo(void) {
+ if (anim) mark_pops(); /* a pop reaches past the board's edge */
+ for (int i = 0; i < 36; i++) cell[i] = ucell[i], fx[i] = 0;
+ score = uscore, moves = umoves, seed = useed, can_undo = over = anim = false, added = 0, ov = O_NONE;
+ mark_board();
+ mark(PX0, SCORE_Y - 30, PW, 70); /* the score, and the points still rising */
+ mark(PX0, UNDO_Y, PW, 26);
+}
+
+/* the keys, in the game */
+static void game_keys(uint64_t hit) {
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);
+ bool bksp = hit & KEY(eadk_key_backspace);
+ int lr = (hit & KEY(eadk_key_right) ? 1 : 0) - (hit & KEY(eadk_key_left) ? 1 : 0);
+ int ud = (hit & KEY(eadk_key_down) ? 1 : 0) - (hit & KEY(eadk_key_up) ? 1 : 0);
+ if (back) { /* one level back: the pause menu, or out of it (menu to menu without fading) */
+ if (ov == O_QUIT) show(O_PAUSE, -999), sel = 2;
+ else if (ov == O_PAUSE) show(ov_under, -999);
+ else ov_under = ov, show(O_PAUSE, 0);
+ mark_board();
+ return;
+ }
+ if (bksp && can_undo && (!ov || ov == O_OVER)) {
+ undo();
+ return;
+ }
+ if (ov) {
+ int nb = nbuttons(), step = ov == O_PAUSE ? ud : lr + ud;
+ if ((int32_t)(now - ov_t) < 0) return; /* not shown yet */
+ if (step && nb > 1) sel = (sel + step + nb) % nb, mark_buttons();
+ if (!ok) return;
+ mark_board();
+ if (ov == O_WIN) {
+ if (sel) new_game();
+ else ov = O_NONE; /* keep going */
+ } else if (ov == O_OVER) {
+ if (sel) undo();
+ else new_game();
+ } else if (ov == O_PAUSE) {
+ if (sel == 0) show(ov_under, -999);
+ else if (sel == 1) new_game();
+ else show(O_QUIT, -999);
+ } else {
+ if (sel) quit_game();
+ else show(O_PAUSE, -999), sel = 2;
+ }
+ return;
+ }
+ int dir = hit & (KEY(eadk_key_left) | KEY(eadk_key_four)) ? 0
+ : hit & (KEY(eadk_key_up) | KEY(eadk_key_eight)) ? 1
+ : hit & (KEY(eadk_key_down) | KEY(eadk_key_two)) ? 2
+ : hit & (KEY(eadk_key_right) | KEY(eadk_key_six)) ? 3
+ : -1;
+ if (dir < 0) return;
+ if (anim) { /* the last move's tiles may still be sliding or growing */
+ if (!slid) mark_slide(1);
+ mark_pops();
+ }
+ bool was = can_undo;
+ int top;
+ if (!move(dir, &top)) return;
+ if (added && now == t_add) mark_score();
+ if (sv.best[n - 3] < score) sv.best[n - 3] = score, mark(PX0, BEST_Y, PW, 40);
+ if (!was) mark(PX0, UNDO_Y, PW, 26);
+ /* the messages wait for the pop to land, then fade in slowly */
+ if (!won && top >= (n == 3 ? 9 : 11)) won = true, show(O_WIN, SLIDE + POP + 700);
+ if (!can_move()) over = true, show(O_OVER, SLIDE + POP + 700), store(), save();
+}
+
+/* the keys, on the title */
+static void title_keys(uint64_t hit) {
+ int lr = (hit & KEY(eadk_key_right) ? 1 : 0) - (hit & KEY(eadk_key_left) ? 1 : 0);
+ int ud = (hit & KEY(eadk_key_down) ? 1 : 0) - (hit & KEY(eadk_key_up) ? 1 : 0);
+ if (lr && sv.size + lr >= 0 && sv.size + lr <= 3) {
+ sv.size = (uint8_t)(sv.size + lr), tsel = sv.flags[sv.size] & 1 ? 0 : 1;
+ mark(214, 16, 90, 42); /* what the size changes: the best, the goal, the board, the choices */
+ mark(16, 66, 300, 16);
+ mark(24, 92, 290, 118);
+ }
+ if (ud && sv.flags[sv.size] & 1) tsel = !tsel, mark(160, 130, 160, 80);
+ if (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) start(tsel == 1);
+ else if (hit & KEY(eadk_key_back)) leave = true;
+}
+
+int main(void) {
+ np_app_begin();
+ font_init();
+ load();
+ now = (uint32_t)eadk_timing_millis();
+ seed ^= eadk_random() ^ now;
+ if (!seed) seed = 1;
+ tsel = sv.flags[sv.size] & 1 ? 0 : 1;
+ mark_all();
+ /* keys still down from the launcher do nothing until let go, nor repeat */
+ uint64_t held = eadk_keyboard_scan(), stale = held;
+ uint32_t repeat_at = 0;
+ int ov_f = 0; /* how far the message was faded in when last painted */
+ for (;;) {
+ now = (uint32_t)eadk_timing_millis();
+ uint64_t k = eadk_keyboard_scan(), hit = k & ~held;
+ const uint64_t rep = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down);
+ stale &= k;
+ if (hit & rep) repeat_at = now + 400;
+ else if ((k & rep & ~stale) && (int32_t)(now - repeat_at) >= 0 && (!scene || ov))
+ hit |= k & rep & ~stale, repeat_at = now + 110;
+ held = k;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ if (scene) game_keys(hit);
+ else title_keys(hit);
+ if (leave) break;
+ if (scene && anim) {
+ uint32_t dt = now - t_move;
+ if (!slid) mark_slide(ease((float)dt / SLIDE)), slid = dt >= SLIDE;
+ if (dt >= SLIDE) mark_pops();
+ if (dt >= SLIDE + POP) anim = false;
+ }
+ if (scene && added && now - t_add < RISE + 40) mark(PX0, SCORE_Y - 30, PW, 30); /* above the score box */
+ bool nb = scene && best0 && score > best0;
+ if (nb != nbest) nbest = nb, mark(PX0, BEST_Y + 44, PW, 16);
+ if (scene && ov && fade() != ov_f) ov_f = fade(), mark_board(); /* only while it fades */
+ /* many rectangles over each other (keys pressed fast): one around them
+ all may be less to paint */
+ int area = 0, x0 = W, y0 = H, x1 = 0, y1 = 0;
+ for (int i = 0; i < nd; i++) {
+ int16_t *d = dirty[i];
+ area += d[2] * d[3];
+ if (d[0] < x0) x0 = d[0];
+ if (d[1] < y0) y0 = d[1];
+ if (d[0] + d[2] > x1) x1 = d[0] + d[2];
+ if (d[1] + d[3] > y1) y1 = d[1] + d[3];
+ }
+ if (nd > 1 && (x1 - x0) * (y1 - y0) <= area) nd = 0, mark(x0, y0, x1 - x0 - 1, y1 - y0 - 1);
+ eadk_display_wait_for_vblank();
+ for (int i = 0; i < nd; i++) paint(dirty[i][0], dirty[i][1], dirty[i][2], dirty[i][3]);
+ nd = 0;
+ uint32_t spent = (uint32_t)eadk_timing_millis() - now; /* about 60 frames a second */
+ if (spent < 16) eadk_timing_msleep(16 - spent);
+ }
+ if (scene) store();
+ save();
+ return np_app_end();
+}
diff --git a/games/games.json b/games/games.json
index 9a9e4608..331af580 100644
--- a/games/games.json
+++ b/games/games.json
@@ -58,7 +58,7 @@
"id": "tetris",
"title": "Tetris",
"tagline": "Stack and clear lines",
- "credit": "Tatone26",
+ "credit": "By Tatone26, from All the Apps",
"top": "0x8A4DFF",
"bottom": "0x1E0B45",
"accent": "0xFF4FA3",
@@ -87,6 +87,159 @@
],
"repo": "https://github.com/Mason363/NumChess"
},
+ {
+ "id": "flappybird",
+ "title": "Flappy Bird",
+ "tagline": "Flap through the pipes",
+ "credit": "From All the Apps by Tatone26",
+ "top": "0x4EC0CA",
+ "bottom": "0x10474C",
+ "accent": "0xF8B733",
+ "records": [
+ "flappy.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "FlappyBird.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/flappybird"
+ },
+ {
+ "id": "pacman",
+ "title": "Pac-Man",
+ "tagline": "Eat dots, dodge ghosts",
+ "credit": "From All the Apps by Tatone26",
+ "top": "0x2A2AE0",
+ "bottom": "0x05052A",
+ "accent": "0xFFD800",
+ "records": [
+ "pacman.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "PacMan.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/pacman"
+ },
+ {
+ "id": "snake",
+ "title": "Snake",
+ "tagline": "Eat apples, grow long",
+ "credit": "From All the Apps by Tatone26",
+ "top": "0x5B9A36",
+ "bottom": "0x16330B",
+ "accent": "0x4E7CF6",
+ "records": [
+ "snake.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "Snake.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/snake"
+ },
+ {
+ "id": "connectfour",
+ "title": "Connect Four",
+ "tagline": "Four in a row wins",
+ "credit": "From All the Apps by Tatone26",
+ "top": "0x2A66D0",
+ "bottom": "0x0A1F4A",
+ "accent": "0xF4C20D",
+ "records": [
+ "connect4.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "ConnectFour.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/connectfour"
+ },
+ {
+ "id": "solitaire",
+ "title": "Solitaire",
+ "tagline": "The classic card game",
+ "credit": "From All the Apps by Tatone26",
+ "top": "0x17964A",
+ "bottom": "0x053A1B",
+ "accent": "0xD62828",
+ "records": [
+ "solitaire.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "Solitaire.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/solitaire"
+ },
+ {
+ "id": "numdance",
+ "title": "NumDance",
+ "tagline": "Hit the arrows on the beat",
+ "credit": null,
+ "top": "0xC24B99",
+ "bottom": "0x1E0A33",
+ "accent": "0x2FE3FF",
+ "records": [
+ "numdance.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "NumDance.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/numdance"
+ },
+ {
+ "id": "g2048",
+ "title": "2048",
+ "tagline": "Slide, merge, reach 2048",
+ "credit": "Based on 2048 by Gabriele Cirulli",
+ "top": "0xC9A26B",
+ "bottom": "0x3C2E22",
+ "accent": "0xEDC22E",
+ "records": [
+ "g2048.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "2048.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/g2048"
+ },
+ {
+ "id": "minesweeper",
+ "title": "Minesweeper",
+ "tagline": "Clear the field, flag the mines",
+ "credit": null,
+ "top": "0x6F7C8C",
+ "bottom": "0x1C222B",
+ "accent": "0xE0301E",
+ "records": [
+ "mines.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "Minesweeper.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/minesweeper"
+ },
+ {
+ "id": "breakout",
+ "title": "Breakout",
+ "tagline": "Break every brick",
+ "credit": null,
+ "top": "0xD24B3A",
+ "bottom": "0x1C0A08",
+ "accent": "0xE8C43A",
+ "records": [
+ "breakout.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "Breakout.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/breakout"
+ },
{
"id": "numvisuals",
"title": "NumVisuals",
diff --git a/games/minesweeper/.gitignore b/games/minesweeper/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/minesweeper/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/minesweeper/Makefile b/games/minesweeper/Makefile
new file mode 100644
index 00000000..d032178e
--- /dev/null
+++ b/games/minesweeper/Makefile
@@ -0,0 +1,55 @@
+# Minesweeper — the Windows classic, with a no-guessing option.
+# make build output/minesweeper.nwa
+# make check link the app like the calculator does (output/minesweeper.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/minesweeper.nwa
+
+check: $(BUILD_DIR)/minesweeper.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/minesweeper.bin
+ @echo "BIN $(BUILD_DIR)/minesweeper.bin: $$(wc -c < $(BUILD_DIR)/minesweeper.bin) bytes"
+
+# compiled once (link-time optimization bytecode), then linked for each use
+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@
+
+$(BUILD_DIR)/minesweeper.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $< $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(BUILD_DIR)/main.o
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_minesweeper_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_minesweeper_main -o $@
diff --git a/games/minesweeper/README.md b/games/minesweeper/README.md
new file mode 100644
index 00000000..a7e90daf
--- /dev/null
+++ b/games/minesweeper/README.md
@@ -0,0 +1,32 @@
+# Minesweeper
+
+The Windows classic for the NumWorks calculator: the gray field, the red LED counters and the smiley, on the teal desktop.
+
+<img src="docs/shot.png" width="320" alt="A game of Beginner in progress">
+
+- **Beginner** (9 x 9, 10 mines), **Intermediate** (16 x 16, 40) and **Expert** (30 x 16, 99), or a **Custom** field up to 30 x 16. Every size fits the screen whole.
+- **Your first square is always safe** and opens an area.
+- **No guessing** (in Options): every field you get can be cleared by logic alone, so a loss is always your mistake, never bad luck. (Very crowded custom fields are the exception: after a second of looking, you get a normal one.)
+- **Marks (?)** like the original, if you want them.
+- Best times and games won for each level, and your game is kept when you leave, to finish later. Starting another field doesn't lose it until you open that field's first square.
+
+Open a number whose mines are all flagged to open everything around it at once, like clicking both buttons on Windows; hold OK on a number to see the squares around it pressed down. The cursor wraps around the edges.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows, or 8 4 6 2 | Move |
+| OK, EXE or 5 | Open (on a number: open around it; hold to see around it) |
+| ⌫, Shift or 0 | Flag |
+| Back | Pause: Resume, New game, Help, Quit game |
+
+After a game, OK starts the next one, like clicking the smiley.
+
+## Credits
+
+Minesweeper was written by Robert Donner and Curt Johnson for Microsoft Windows (1990). This version was made from scratch for NumPlay, after the look of the Windows 95 game.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `Minesweeper.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/minesweeper/docs/shot.png b/games/minesweeper/docs/shot.png
new file mode 100644
index 00000000..30084b61
Binary files /dev/null and b/games/minesweeper/docs/shot.png differ
diff --git a/games/minesweeper/src/icon.png b/games/minesweeper/src/icon.png
new file mode 100644
index 00000000..529e90d4
Binary files /dev/null and b/games/minesweeper/src/icon.png differ
diff --git a/games/minesweeper/src/main.c b/games/minesweeper/src/main.c
new file mode 100644
index 00000000..7bc6e5da
--- /dev/null
+++ b/games/minesweeper/src/main.c
@@ -0,0 +1,1099 @@
+/* Minesweeper, like the one that came with Windows: the gray field, the red
+ * LED counters and the smiley, on the teal desktop. On top of the classic
+ * rules it has a "no guessing" option that only deals fields you can clear by
+ * logic alone, a cursor that wraps around, and it keeps your game when you
+ * leave.
+ *
+ * Drawing uses dirty rectangles: a cell is composed in a tiny buffer and
+ * pushed only when it changes. Cells that change together (an opening, the
+ * mines after a loss) go through a queue a ring at a time, so an opening
+ * spreads out like a wave. Text uses the calculator's own font. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Minesweeper";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define GRAY RGB(0xC0C0C0)
+#define DARK RGB(0x808080)
+#define WHITE 0xFFFF
+#define BLACK 0
+#define NAVY RGB(0x000080)
+#define TEAL RGB(0x008080)
+#define RED RGB(0xFF0000)
+#define YELLOW RGB(0xFFFF00)
+
+/* what the keys do: the arrows (or 8 4 6 2), open (OK, EXE, 5), flag (Backspace, Shift, 0) */
+enum { K_UP = 1, K_DOWN = 2, K_LEFT = 4, K_RIGHT = 8, K_OK = 16, K_FLAG = 32, K_BACK = 64, K_HOME = 128, K_ANY = 256 };
+static const uint8_t keymap[][2] = {
+ {eadk_key_up, K_UP}, {eadk_key_eight, K_UP}, {eadk_key_down, K_DOWN}, {eadk_key_two, K_DOWN},
+ {eadk_key_left, K_LEFT}, {eadk_key_four, K_LEFT}, {eadk_key_right, K_RIGHT}, {eadk_key_six, K_RIGHT},
+ {eadk_key_ok, K_OK}, {eadk_key_exe, K_OK}, {eadk_key_five, K_OK}, {eadk_key_backspace, K_FLAG},
+ {eadk_key_shift, K_FLAG}, {eadk_key_zero, K_FLAG}, {eadk_key_back, K_BACK}, {eadk_key_home, K_HOME},
+ {eadk_key_on_off, K_HOME},
+};
+static int keys(void) {
+ uint64_t k = eadk_keyboard_scan();
+ int a = k ? K_ANY : 0;
+ for (unsigned i = 0; i < sizeof keymap / 2; i++)
+ if (k >> keymap[i][0] & 1) a |= keymap[i][1];
+ return a;
+}
+
+static uint32_t now, seed = 0x9E3779B9u;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+static int iabs(int v) { return v < 0 ? -v : v; }
+static int imin(int a, int b) { return a < b ? a : b; }
+
+/* ------------------------------------------------------------------ drawing */
+static void fill(int x, int y, int w, int h, color c) {
+ if (w > 0 && h > 0) eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+/* pix: a small picture composed in RAM, pw pixels wide, then pushed at once */
+static color pix[34 * 34];
+static int pw;
+static void pfill(int x, int y, int w, int h, color c) {
+ for (int j = y; j < y + h; j++)
+ for (int i = x; i < x + w; i++) pix[j * pw + i] = c;
+}
+static void push(int x, int y, int h) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)pw, (uint16_t)h}, pix);
+}
+typedef void (*filler)(int, int, int, int, color);
+/* a 3D edge t pixels thick: lt on the top and left, dk on the bottom and right */
+static void edge(filler f, int x, int y, int w, int h, int t, color lt, color dk) {
+ for (; t--; x++, y++, w -= 2, h -= 2) {
+ f(x, y, w - 1, 1, lt);
+ f(x, y + 1, 1, h - 2, lt);
+ f(x, y + h - 1, w, 1, dk);
+ f(x + w - 1, y, 1, h - 1, dk);
+ }
+}
+/* Windows 95's raised edge (buttons, windows, menus) and sunken one (fields) */
+static void raised(int x, int y, int w, int h) {
+ edge(fill, x, y, w, h, 1, WHITE, BLACK);
+ edge(fill, x + 1, y + 1, w - 2, h - 2, 1, GRAY, DARK);
+}
+static void sunken(int x, int y, int w, int h) {
+ edge(fill, x, y, w, h, 1, DARK, WHITE);
+ edge(fill, x + 1, y + 1, w - 2, h - 2, 1, BLACK, GRAY);
+}
+/* fills (x, y, w, h) except the rectangle (X, Y, W, H) inside it */
+static void around(int x, int y, int w, int h, int X, int Y, int W, int H, color c) {
+ fill(x, y, w, Y - y, c);
+ fill(x, Y + H, w, y + h - Y - H, c);
+ fill(x, Y, X - x, H, c);
+ fill(X + W, Y, x + w - X - W, H, c);
+}
+
+static void text(const char *s, int x, int y, color fg, color bg) {
+ eadk_display_draw_string(s, (eadk_point_t){(uint16_t)x, (uint16_t)y}, false, fg, bg);
+}
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static void centered(const char *s, int cx, int y, color fg, color bg) { text(s, cx - slen(s) * 7 / 2, y, fg, bg); }
+static char *num(char *o, int v) {
+ char t[8];
+ int n = 0;
+ if (v < 0) *o++ = '-', v = -v;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+static char *cat(char *o, const char *s) {
+ while (*s) *o++ = *s++;
+ *o = 0;
+ return o;
+}
+/* "12.3 s" from tenths of a second */
+static char *secs(char *o, int t) {
+ o = num(o, t / 10);
+ *o++ = '.';
+ o = num(o, t % 10);
+ return cat(o, " s");
+}
+
+/* ------------------------------------------------------------------ pictures */
+/* 1 to 8 and ?, bold like Windows' */
+static const uint8_t glyphs[9][7] = {
+ {0x0C, 0x1C, 0x3C, 0x0C, 0x0C, 0x0C, 0x3F}, {0x1E, 0x33, 0x03, 0x0E, 0x18, 0x30, 0x3F},
+ {0x1E, 0x33, 0x03, 0x0E, 0x03, 0x33, 0x1E}, {0x06, 0x0E, 0x1E, 0x36, 0x3F, 0x06, 0x06},
+ {0x3F, 0x30, 0x3E, 0x03, 0x03, 0x33, 0x1E}, {0x1E, 0x30, 0x3E, 0x33, 0x33, 0x33, 0x1E},
+ {0x3F, 0x03, 0x06, 0x06, 0x0C, 0x0C, 0x0C}, {0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E},
+ {0x1E, 0x33, 0x03, 0x0E, 0x0C, 0x00, 0x0C},
+};
+static const color ink[9] = {RGB(0x0000FF), RGB(0x008000), RGB(0xFF0000), RGB(0x000080), RGB(0x800000),
+ RGB(0x008080), BLACK, DARK, BLACK};
+/* glyph g (0 is "1") at q/2 times its size (q 2 to 4, so 1.5 too), centred in
+ the s x s square at (x, y); a glyph pixel i starts at (i * q + 1) / 2 */
+static void glyph(int g, int x, int y, int s, int q) {
+ x += (s - (6 * q + 1) / 2 + 1) / 2, y += (s - (7 * q + 1) / 2 + 1) / 2;
+ for (int j = 0; j < 7; j++)
+ for (int i = 0; i < 6; i++) {
+ int x0 = (i * q + 1) / 2, y0 = (j * q + 1) / 2;
+ if (glyphs[g][j] >> (5 - i) & 1) pfill(x + x0, y + y0, (i * q + q + 1) / 2 - x0, (j * q + q + 1) / 2 - y0, ink[g]);
+ }
+}
+/* a mine m pixels across (m odd): a ball with spikes and a glint */
+static void mine(int x, int y, int m) {
+ int c = m / 2, r = (c - 2) * (c - 1), g = c / 3;
+ for (int j = 0; j < m; j++)
+ for (int i = 0; i < m; i++) {
+ int dx = i - c, dy = j - c;
+ if (dx * dx + dy * dy <= r || !dx || !dy || (iabs(dx) == iabs(dy) && iabs(dx) == c - 2))
+ pix[(y + j) * pw + x + i] = dx < 0 && dy < 0 && dx >= -g && dy >= -g ? WHITE : BLACK;
+ }
+}
+/* the red flag on its pole and stand, for an s x s square (bolder in small ones) */
+static void flag(int s) {
+ int t = s < 14, p = s / 2, y = t ? 1 : s / 5, h = t ? 4 : s / 3 | 1, b = s * 2 / 3 + t, a = s / 6 + t, c = s / 4 + t;
+ for (int r = 0; r < h; r++) {
+ int w = imin(2 + 2 * imin(r, h - 1 - r), p - 2 + t); /* clear of the bevel */
+ pfill(p - w, y + r, w, 1, RED);
+ }
+ pfill(p, y, 1, b - y, BLACK);
+ pfill(p - a, b, a * 2 + 1, 1, BLACK);
+ pfill(p - c, b + 1, c * 2 + 1, s / 8, BLACK);
+}
+
+/* the smiley's eyes and mouth, rows 5 to 13 of 17, left half (the other is mirrored) */
+enum { F_SMILE, F_OH, F_COOL, F_DEAD };
+static const uint16_t faces[4][9] = {
+ {0, 0x60, 0x60, 0, 0, 0x10, 0x20, 0x1C0, 0},
+ {0x60, 0x60, 0x60, 0, 0, 0x180, 0x40, 0x40, 0x180},
+ {0x1FE, 0xF8, 0x70, 0, 0, 0x10, 0x20, 0x1C0, 0},
+ {0x50, 0x20, 0x50, 0, 0, 0x1C0, 0x20, 0x10, 0},
+};
+static void face(int x, int y, int k, int f) {
+ for (int j = 0; j < 17; j++)
+ for (int i = 0; i < 17; i++) {
+ int d = (i - 8) * (i - 8) + (j - 8) * (j - 8);
+ if (d > 72) continue;
+ color c = d > 56 ? BLACK : YELLOW;
+ if (j >= 5 && j < 14 && faces[f][j - 5] >> (i < 9 ? i : 16 - i) & 1) c = BLACK;
+ pfill(x + i * k, y + j * k, k, k, c);
+ }
+}
+
+/* the LED counters: seven segments, lit ones red */
+static const uint8_t segs[11] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, 0x40};
+/* the segment (a to g, 0 to 6) at (x, y) of an 11x21 digit, or -1 */
+static int seg(int x, int y) {
+ if ((unsigned)x > 10 || (unsigned)y > 20) return -1;
+ int m = iabs(y - 10);
+ if (y < 3 && x > y && x < 10 - y) return 0;
+ if (y > 17 && x > 20 - y && x < y - 10) return 3;
+ if (m < 2 && x > m && x < 10 - m) return 6;
+ int d = x < 3 ? x : x > 7 ? 10 - x : -1;
+ if (d < 0) return -1;
+ if (y > d && y < 10 - d) return x < 3 ? 5 : 1;
+ if (y > 10 + d && y < 20 - d) return x < 3 ? 4 : 2;
+ return -1;
+}
+/* three digits (a minus sign below zero) in a sunken box 41x25 */
+static void led(int x, int y, int v) {
+ v = v > 999 ? 999 : v < -99 ? -99 : v;
+ int d[3] = {v < 0 ? 10 : v / 100, iabs(v) / 10 % 10, iabs(v) % 10};
+ edge(fill, x, y, 41, 25, 1, DARK, WHITE);
+ pw = 13;
+ for (int k = 0; k < 3; k++) {
+ for (int j = 0; j < 23; j++)
+ for (int i = 0; i < 13; i++) {
+ int s = seg(i - 1, j - 1);
+ pix[j * 13 + i] = s < 0 ? BLACK : segs[d[k]] >> s & 1 ? RED : RGB(0x600000);
+ }
+ push(x + 1 + 13 * k, y + 1, 23);
+ }
+}
+
+/* ------------------------------------------------------------------ windows */
+/* rows of 8 pixels, the leftmost the top bit */
+static void bitmap(const uint8_t *rows, int n, int x, int y, color c) {
+ for (int j = 0; j < n; j++)
+ for (int i = 0; i < 8; i++)
+ if (rows[j] << i & 0x80) fill(x + i, y + j, 1, 1, c);
+}
+/* the caption buttons' close, maximize and minimize, Windows' check mark, restore */
+static const uint8_t glyph8[5][7] = {
+ {0xC3, 0x66, 0x3C, 0x18, 0x3C, 0x66, 0xC3}, {0xFF, 0xFF, 0x81, 0x81, 0x81, 0x81, 0xFF},
+ {0, 0, 0, 0, 0, 0xFC, 0xFC}, {0x02, 0x06, 0x8E, 0xDC, 0xF8, 0x70, 0x20},
+ {0x3F, 0x3F, 0xFD, 0xFD, 0x87, 0x84, 0xFC},
+};
+/* a raised button with a label; the focused one has a black frame and a dotted rectangle */
+static void button(int x, int y, int w, int h, const char *s, bool focus) {
+ if (focus) edge(fill, x, y, w, h, 1, BLACK, BLACK), x++, y++, w -= 2, h -= 2;
+ raised(x, y, w, h);
+ fill(x + 2, y + 2, w - 4, h - 4, GRAY);
+ centered(s, x + w / 2, y + (h - 14) / 2, BLACK, GRAY);
+ if (focus) /* Windows' dotted focus rectangle */
+ for (int i = 3; i < w - 3 || i < h - 3; i += 2) {
+ if (i < w - 3) fill(x + i, y + 3, 1, 1, BLACK), fill(x + i, y + h - 4, 1, 1, BLACK);
+ if (i < h - 3) fill(x + 3, y + i, 1, 1, BLACK), fill(x + w - 4, y + i, 1, 1, BLACK);
+ }
+}
+/* the navy title bar: the app's icon (not on dialogs), the title and the buttons */
+static void caption(int x, int y, int w, const char *s, int buttons) {
+ fill(x, y, w, 18, NAVY);
+ if (buttons > 1) {
+ pw = 14;
+ pfill(0, 0, 14, 14, GRAY);
+ edge(pfill, 0, 0, 14, 14, 1, WHITE, DARK);
+ mine(2, 2, 11);
+ push(x + 2, y + 2, 14);
+ }
+ text(s, x + (buttons > 1 ? 20 : 4), y + 2, WHITE, NAVY);
+ for (int b = 0; b < buttons; b++) {
+ int bx = x + w - 18 - (b ? 2 + 16 * b : 0);
+ /* Minesweeper's window can't be resized: maximize (restore when it fills the screen) is grayed out */
+ const uint8_t *g = glyph8[b == 1 && !x ? 4 : b];
+ raised(bx, y + 2, 16, 14);
+ fill(bx + 2, y + 4, 12, 10, GRAY);
+ if (b == 1) bitmap(g, 7, bx + 5, y + 6, WHITE);
+ bitmap(g, 7, bx + 4, y + 5, b == 1 ? DARK : BLACK);
+ }
+}
+/* a window: frame, title bar and a gray inside; returns where the inside starts */
+static int wx0, wy0;
+static void window(int x, int y, int w, int h, const char *s, int buttons) {
+ edge(fill, x, y, w, h, 1, GRAY, BLACK);
+ edge(fill, x + 1, y + 1, w - 2, h - 2, 1, WHITE, DARK);
+ edge(fill, x + 2, y + 2, w - 4, h - 4, 2, GRAY, GRAY);
+ caption(x + 4, y + 4, w - 8, s, buttons);
+ wx0 = x + 4, wy0 = y + 22;
+}
+/* a dialog in the middle of the screen */
+static void dialog(int w, int h, const char *s) {
+ int x = (320 - w) / 2, y = (240 - h) / 2;
+ window(x, y, w, h, s, 1);
+ fill(wx0, wy0, w - 8, h - 26, GRAY);
+}
+/* a menu row: a check mark, a label and two notes, white on navy when selected */
+static void row(int x, int y, int w, const char *s, const char *mid, const char *note, bool sel, bool check) {
+ color bg = sel ? NAVY : GRAY, fg = sel ? WHITE : BLACK;
+ fill(x, y, w, 17, bg);
+ if (check) bitmap(glyph8[3], 7, x + 4, y + 5, fg);
+ text(s, x + 18, y + 2, fg, bg);
+ if (mid) text(mid, x + 124, y + 2, fg, bg);
+ if (note) text(note, x + w - 6 - slen(note) * 7, y + 2, fg, bg);
+}
+/* the etched line between groups of a menu */
+static void rule(int x, int y, int w) {
+ fill(x, y, w, 5, GRAY);
+ fill(x + 1, y + 2, w - 2, 1, DARK);
+ fill(x + 1, y + 3, w - 2, 1, WHITE);
+}
+
+/* ------------------------------------------------------------------ the field */
+#define MW 30
+#define MH 16
+#define MINE 0x10
+#define DIRTY 0x80
+enum { HID, OPEN, FLAG, ASK };
+enum { G_NEW, G_PLAY, G_WON, G_LOST };
+static uint8_t cell[MW * MH], kn[MW * MH], fr[MW * MH]; /* cell: count, mine, state << 5, dirty */
+static uint16_t bfs[MW * MH], fifo[1024];
+static unsigned qh, qt;
+static int bw = 9, bh = 9, nm = 10, cur, gs, flags, left;
+static uint32_t elapsed; /* ms */
+static const uint8_t levels[3][3] = {{9, 9, 10}, {16, 16, 40}, {30, 16, 99}};
+
+static int state(int i) { return cell[i] >> 5 & 3; }
+static void set_state(int i, int s) { cell[i] = (uint8_t)((cell[i] & 0x9F) | s << 5); }
+static int nbrs(int i, int *o) {
+ int x = i % bw, y = i / bw, n = 0;
+ for (int dy = -1; dy <= 1; dy++)
+ for (int dx = -1; dx <= 1; dx++)
+ if ((dx || dy) && (unsigned)(x + dx) < (unsigned)bw && (unsigned)(y + dy) < (unsigned)bh) o[n++] = i + dy * bw + dx;
+ return n;
+}
+static void count(void) {
+ for (int i = 0, o[8]; i < bw * bh; i++) {
+ int n = 0;
+ for (int k = nbrs(i, o); k--;) n += cell[o[k]] >> 4 & 1;
+ cell[i] = (uint8_t)((cell[i] & 0xF0) | n);
+ }
+}
+/* the level being played (3 when custom) */
+static int level(void) {
+ for (int d = 0; d < 3; d++)
+ if (bw == levels[d][0] && bh == levels[d][1] && nm == levels[d][2]) return d;
+ return 3;
+}
+
+/* the drawing queue: cells to redraw, with a mark (0xFFFF) where a frame ends */
+static void dirty(int i) {
+ if (cell[i] & DIRTY) return;
+ cell[i] |= DIRTY;
+ fifo[qt++ & 1023] = (uint16_t)i;
+}
+static void wave(void) {
+ if (qt != qh && fifo[(qt - 1) & 1023] != 0xFFFF) fifo[qt++ & 1023] = 0xFFFF;
+}
+
+/* ------------------------------------------------------------------ no guessing */
+/* A small solver plays the field from the first click with what a person can
+ * see: a number whose mines are all flagged frees its other neighbors, one
+ * with as many hidden neighbors as missing mines flags them all, and two
+ * numbers close together are compared (the 1-2 patterns): if B needs as many
+ * more mines than A as it has cells A does not touch, those cells are mines
+ * and the cells only A touches are safe. When the solver gets stuck, a mine
+ * where it stopped is moved away and it tries again. kn: 0 unknown, 1 open,
+ * 2 mine; fr: open cells next to unknown ones. */
+static int todo, found;
+static void s_open(int i) {
+ int n = 1, o[8];
+ bfs[0] = (uint16_t)i, kn[i] = 1;
+ while (n) {
+ int j = bfs[--n];
+ todo--;
+ if (!(cell[j] & 15))
+ for (int k = nbrs(j, o); k--;)
+ if (!kn[o[k]]) kn[o[k]] = 1, bfs[n++] = (uint16_t)o[k];
+ }
+}
+/* the unknown neighbors of i as bits of the 5x5 square at (x0, y0); *r: its mines not found yet */
+static uint32_t unknown(int i, int x0, int y0, int *r) {
+ int o[8], n = nbrs(i, o);
+ uint32_t m = 0;
+ *r = cell[i] & 15;
+ while (n--) {
+ int j = o[n];
+ if (kn[j] == 2) --*r;
+ else if (!kn[j]) m |= 1u << ((j / bw - y0) * 5 + j % bw - x0);
+ }
+ return m;
+}
+static int bits(uint32_t m) {
+ int n = 0;
+ for (; m; m &= m - 1) n++;
+ return n;
+}
+/* the squares of m are all mines, or all safe */
+static void settle(uint32_t m, int x0, int y0, bool mines) {
+ for (int q = 0; m; q++, m >>= 1) {
+ int j = (y0 + q / 5) * bw + x0 + q % 5;
+ if ((m & 1) && !kn[j]) {
+ if (mines) kn[j] = 2, found++;
+ else s_open(j);
+ }
+ }
+}
+static bool solvable(int first) {
+ int n = bw * bh;
+ for (int i = 0; i < n; i++) kn[i] = 0;
+ todo = n - nm, found = 0;
+ s_open(first);
+ for (bool more = true; more && todo;) {
+ more = false;
+ for (int i = 0; i < n; i++) {
+ int r, x0 = i % bw - 2, y0 = i / bw - 2;
+ fr[i] = 0;
+ if (kn[i] != 1) continue;
+ uint32_t m = unknown(i, x0, y0, &r);
+ int u = bits(m);
+ if (!u) kn[i] = 3; /* nothing more to learn from it */
+ else if (!r || r == u) settle(m, x0, y0, r), more = true;
+ else fr[i] = 1;
+ }
+ if (more) continue;
+ for (int a = 0; a < n; a++) {
+ if (!fr[a]) continue;
+ int ax = a % bw, ay = a / bw, ra, rb;
+ for (int oy = -2; oy <= 2; oy++)
+ for (int ox = -2; ox <= 2; ox++) {
+ int x = ax + ox, y = ay + oy;
+ if ((!ox && !oy) || (unsigned)x >= (unsigned)bw || (unsigned)y >= (unsigned)bh || !fr[y * bw + x]) continue;
+ int x0 = ax + (ox < 0 ? ox : 0) - 1, y0 = ay + (oy < 0 ? oy : 0) - 1;
+ uint32_t ma = unknown(a, x0, y0, &ra), mb = unknown(y * bw + x, x0, y0, &rb), d = mb & ~ma, e = ma & ~mb;
+ if (!ma || !mb || !(d | e) || rb - ra != bits(d)) continue;
+ settle(d, x0, y0, true);
+ settle(e, x0, y0, false);
+ more = true;
+ }
+ }
+ if (!more && found == nm) /* every mine found: the rest is safe */
+ for (int i = 0; i < n; i++)
+ if (!kn[i]) s_open(i);
+ }
+ return !todo;
+}
+/* mines go in anywhere but around the first square opened */
+static void deal(int first, bool sure) {
+ int n = bw * bh, fx = first % bw, fy = first / bw;
+ uint32_t t0 = eadk_timing_millis();
+ seed ^= t0 * 2654435761u;
+ for (bool again = true;;) {
+ if (again) {
+ for (int i = 0; i < n; i++) cell[i] &= 0xE0;
+ for (int k = 0; k < nm;) {
+ int i = (int)(rnd() % (uint32_t)n), dx = i % bw - fx, dy = i / bw - fy;
+ if (cell[i] & MINE || (dx * dx <= 1 && dy * dy <= 1)) continue;
+ cell[i] |= MINE, k++;
+ }
+ }
+ count();
+ /* a second at most (dense custom fields), and Home still quits */
+ if (!sure || solvable(first) || eadk_timing_millis() - t0 > 1000 || keys() & K_HOME) break;
+ /* stuck: a mine next to what is open trades places with a safe square
+ away from it (or deal again) */
+ int f = -1, g = -1, nf = 0, ng = 0;
+ for (int i = 0, o[8]; i < n; i++) {
+ if (kn[i]) continue;
+ bool front = false;
+ for (int k = nbrs(i, o); k--;) front |= kn[o[k]] & 1;
+ if (front && (cell[i] & MINE) && !(rnd() % (uint32_t)++nf)) f = i;
+ if (!front && !(cell[i] & MINE) && !(rnd() % (uint32_t)++ng)) g = i;
+ }
+ again = f < 0 || g < 0;
+ if (!again) cell[f] &= ~MINE, cell[g] |= MINE;
+ }
+ left = n - nm;
+}
+
+/* ------------------------------------------------------------------ the game */
+static struct {
+ uint8_t magic, version, diff, opts; /* diff: 0-2, 3 custom; opts: 1 marks (?), 2 no guessing */
+ uint32_t elapsed; /* the game in progress (ms) */
+ uint16_t best[3], played[3], won[3]; /* best: tenths of a second, 0 for none */
+ uint16_t cmines, gmines; /* custom mines; the game's mines */
+ uint8_t cw, ch, gw, gh, gx, gy; /* custom size; the game's size (gw 0: none) and cursor */
+ uint8_t board[MW * MH / 2]; /* the game, a nibble a cell: mine | state << 1 */
+} V;
+#define SAVE_NAME "mines.sav"
+#define O_MARKS 1
+#define O_SURE 2
+
+static void save(void) {
+ V.magic = 'M', V.version = 1;
+ if (gs != G_PLAY) {
+ if (gs) V.gw = 0; /* over; a new field keeps the saved game until its first square */
+ } else {
+ V.gw = (uint8_t)bw, V.gh = (uint8_t)bh, V.gmines = (uint16_t)nm;
+ V.gx = (uint8_t)(cur % bw), V.gy = (uint8_t)(cur / bw), V.elapsed = elapsed > 999000 ? 999000 : elapsed;
+ for (int i = 0; i < MW * MH; i++) {
+ int v = i < bw * bh ? (cell[i] >> 4 & 1) | state(i) << 1 : 0;
+ V.board[i / 2] = (uint8_t)(i & 1 ? V.board[i / 2] | v << 4 : v);
+ }
+ }
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ if (d && n == sizeof V) {
+ uint32_t i = 0;
+ while (i < n && d[i] == ((uint8_t *)&V)[i]) i++;
+ if (i == n) return; /* nothing new */
+ }
+ ef_write(SAVE_NAME, &V, sizeof V);
+}
+/* unpacks the saved game into the field; false if it makes no sense */
+static bool unpack(void) {
+ int mines = 0;
+ bw = V.gw, bh = V.gh, nm = V.gmines, flags = 0, left = bw * bh - nm;
+ if (bw < 8 || bw > MW || bh < 8 || bh > MH || V.gx >= bw || V.gy >= bh || V.elapsed > 999000u) return false;
+ for (int i = 0; i < bw * bh; i++) {
+ int v = V.board[i / 2] >> (i & 1) * 4, st = v >> 1 & 3;
+ cell[i] = (uint8_t)((v & 1) << 4 | st << 5);
+ mines += v & 1, flags += st == FLAG, left -= st == OPEN;
+ if ((v & 1) && st == OPEN) return false;
+ }
+ count();
+ cur = V.gy * bw + V.gx, elapsed = V.elapsed;
+ return mines == nm && nm <= (bw - 1) * (bh - 1) && left > 0 && left < bw * bh - nm;
+}
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ bool ok = d && n == sizeof V && d[0] == 'M' && d[1] == 1;
+ for (uint32_t i = 0; i < sizeof V; i++) ((uint8_t *)&V)[i] = ok ? d[i] : 0;
+ if (V.diff > 3) V.diff = 0;
+ V.opts &= 3;
+ if (V.cw < 8 || V.cw > MW || V.ch < 8 || V.ch > MH) V.cw = 16, V.ch = 12;
+ if (!V.cmines || V.cmines > (V.cw - 1) * (V.ch - 1)) V.cmines = (uint16_t)(V.cw * V.ch / 6);
+ for (int k = 0; k < 3; k++) {
+ if (V.best[k] > 9999) V.best[k] = 0;
+ if (V.won[k] > V.played[k]) V.won[k] = V.played[k] = 0;
+ }
+}
+
+/* where things are on the screen */
+#define HH 33 /* the counters' panel */
+static int cs, bx, by, hx, hy, hw, wx, wy, ww, wh;
+static bool framed;
+static void layout(void) {
+ /* cells as big as fit: maximized, or in a window on the desktop (at most 20 pixels, as bh >= 8) */
+ int m = imin(308 / bw, (218 - HH - 9) / bh), f = imin(292 / bw, (240 - 26 - 25 - HH) / bh);
+ framed = f >= 16 || f == m;
+ cs = framed ? f : m;
+ int cw = bw * cs + 20 < 150 ? 150 : bw * cs + 20, ch = bh * cs + 25 + HH;
+ if (framed) {
+ ww = cw + 8, wh = ch + 26, wx = (320 - ww) / 2, wy = (240 - wh) / 2;
+ hy = wy + 29, by = hy + HH + 8;
+ } else { /* maximized: the rows to spare go above, between and below */
+ int e = 218 - HH - 6 - bh * cs;
+ wx = wy = 0, ww = 320, wh = 240;
+ hy = 20 + e / 3, by = hy + HH + 3 + (e + 1) / 3;
+ }
+ hx = wx + (ww - cw) / 2 + 7, hw = cw - 14;
+ bx = (320 - bw * cs) / 2;
+}
+
+/* ------------------------------------------------------------------ drawing the game */
+static int shown[3] = {-1000, -1000, -1}; /* on the counters and the face */
+static bool cur_on = true; /* no cursor after a game (like Windows) until an arrow is pressed */
+static void draw_cell(int i) {
+ int s = cs, n = s - 1, st = state(i), m = cell[i] & MINE, q = s < 14 ? 2 : s < 19 ? 3 : 4;
+ /* open, or shown after a loss: the mines missed and the wrong flags */
+ bool seen = st == OPEN || (gs == G_LOST && (m ? st != FLAG : st == FLAG));
+ bool flat = seen || (st == HID && kn[i] == 4); /* pressed (see press) */
+ cell[i] &= ~DIRTY;
+ pw = s;
+ pfill(0, 0, s, s, st == OPEN && m ? RED : GRAY);
+ if (flat) {
+ pfill(0, 0, s, 1, DARK);
+ pfill(0, 0, 1, s, DARK);
+ } else {
+ edge(pfill, 0, 0, s, s, s < 15 ? 1 : 2, WHITE, DARK);
+ }
+ if (i == cur && cur_on) { /* under the number or flag, so small cells stay readable */
+ edge(pfill, 0, 0, s, s, 1, BLACK, BLACK);
+ edge(pfill, 1, 1, s - 2, s - 2, 1, YELLOW, YELLOW);
+ }
+ if (seen) {
+ if (m || st == FLAG) {
+ int k = s < 14 ? 9 : (s - 3) | 1;
+ mine(1 + (n - k) / 2, 1 + (n - k) / 2, k);
+ if (st == FLAG) /* a flag where there was no mine */
+ for (int j = 2; j < n - 1; j++) pfill(j, j, 2, 1, RED), pfill(n - j, j, 2, 1, RED);
+ } else if (cell[i] & 15) {
+ glyph((cell[i] & 15) - 1, 1, 1, n, q);
+ }
+ } else if (!flat) {
+ if (st == FLAG) flag(s);
+ else if (st == ASK) glyph(8, 0, 0, s, q);
+ }
+ push(bx + i % bw * s, by + i / bw * s, s);
+}
+/* the counters' panel: two LEDs and the face (drawn by update) */
+static void panel(void) {
+ edge(fill, hx, hy, hw, HH, 2, DARK, WHITE);
+ int ix = hx + 2, iw = hw - 4, y = hy + 4, l = ix + 5, f = hx + hw / 2 - 12, r = ix + iw - 46;
+ fill(ix, hy + 2, iw, 2, GRAY);
+ fill(ix, hy + 29, iw, 2, GRAY);
+ fill(ix, y, 5, 25, GRAY);
+ fill(l + 41, y, f - l - 41, 25, GRAY);
+ fill(f + 25, y, r - f - 25, 25, GRAY);
+ fill(r + 41, y, 5, 25, GRAY);
+ shown[0] = shown[1] = -1000, shown[2] = -1;
+}
+/* puts new numbers on the LEDs and the face */
+static void update(int l, int r, int f) {
+ if (l != shown[0]) led(hx + 7, hy + 4, shown[0] = l);
+ if (r != shown[1]) led(hx + hw - 48, hy + 4, shown[1] = r);
+ if (f != shown[2]) {
+ int p = f >> 2; /* pressed */
+ shown[2] = f;
+ pw = 25;
+ pfill(0, 0, 25, 25, GRAY);
+ edge(pfill, 0, 0, 25, 25, 1, DARK, DARK);
+ if (!p) edge(pfill, 1, 1, 23, 23, 2, WHITE, DARK);
+ face(4 + p, 4 + p, 1, f & 3);
+ push(hx + hw / 2 - 12, hy + 4, 25);
+ }
+}
+static void draw_game(void) {
+ if (framed) {
+ around(0, 0, 320, 240, wx, wy, ww, wh, TEAL);
+ window(wx, wy, ww, wh, "Minesweeper", 3);
+ } else {
+ caption(0, 0, 320, "Minesweeper", 3);
+ }
+ int cx = framed ? wx + 4 : 0, cy = framed ? wy + 22 : 18, cw = framed ? ww - 8 : 320, ch = framed ? wh - 26 : 222;
+ int split = hy + HH, fw = bw * cs + 6, fh = bh * cs + 6;
+ edge(fill, cx, cy, cw, ch, 2, WHITE, DARK);
+ around(cx + 2, cy + 2, cw - 4, split - cy - 2, hx, hy, hw, HH, GRAY);
+ around(cx + 2, split, cw - 4, cy + ch - 2 - split, bx - 3, by - 3, fw, fh, GRAY);
+ panel();
+ edge(fill, bx - 3, by - 3, fw, fh, 3, DARK, WHITE);
+ /* everything is drawn now: what the queue held (maybe for a bigger field) is done */
+ qh = qt;
+ for (int i = 0; i < MW * MH; i++)
+ if (i < bw * bh) draw_cell(i);
+ else cell[i] &= ~DIRTY;
+}
+static void game_counters(int f) {
+ /* a win shows whole seconds, like the time in tenths it gets */
+ update(nm - flags, gs == G_NEW ? 0 : (int)(elapsed / 1000) + (gs != G_WON), gs >= G_WON ? gs : f); /* F_COOL, F_DEAD */
+}
+
+/* ------------------------------------------------------------------ playing */
+static int pressed_until, win_at; /* win_at: when the game that ended takes OK again (a win shows its box) */
+static uint32_t last; /* the last frame's time */
+static void new_game(void) {
+ gs = G_NEW, elapsed = 0, flags = 0, win_at = 0, cur_on = true;
+ for (int i = 0; i < bw * bh; i++) cell[i] &= DIRTY;
+ /* a quick wipe from the top left corner */
+ for (int d = 0; d < bw + bh - 1; d++) {
+ for (int x = 0; x < bw; x++)
+ if ((unsigned)(d - x) < (unsigned)bh) dirty((d - x) * bw + x);
+ if (d & 1) wave();
+ }
+ wave();
+}
+/* opens bfs[0..n) and the empty areas they touch, a ring per frame */
+static void open_cells(int n) {
+ for (int k = 0; k < n; k++) set_state(bfs[k], OPEN), dirty(bfs[k]);
+ wave();
+ for (int h = 0, end = n, o[8]; h < n;) {
+ int i = bfs[h++];
+ left--;
+ if (!(cell[i] & 15))
+ for (int k = nbrs(i, o); k--;) {
+ int j = o[k];
+ if (state(j) != OPEN && state(j) != FLAG) set_state(j, OPEN), dirty(j), bfs[n++] = (uint16_t)j;
+ }
+ if (h == end) wave(), end = n;
+ }
+}
+/* after the game: the mines (or flags) show up ring by ring around c */
+static void ripple(int c) {
+ for (int d = 0; d < MW; d++) {
+ for (int i = 0; i < bw * bh; i++) {
+ int dx = iabs(i % bw - c % bw), dy = iabs(i / bw - c / bw);
+ if ((dx > dy ? dx : dy) == d && (cell[i] & MINE || state(i) == FLAG)) dirty(i);
+ }
+ wave();
+ }
+}
+static int last_time, new_best;
+static void ended(int c) {
+ cur_on = false, dirty(cur);
+ ripple(c);
+ win_at = (int)now + 700;
+ save();
+}
+static void won(void) {
+ int lv = level(), t = (int)(elapsed / 100);
+ gs = G_WON, flags = nm;
+ for (int i = 0; i < bw * bh; i++)
+ if (cell[i] & MINE) set_state(i, FLAG);
+ last_time = t > 9999 ? 9999 : t, new_best = 0;
+ if (lv < 3) {
+ V.won[lv]++;
+ if (!V.best[lv] || last_time < V.best[lv]) V.best[lv] = (uint16_t)(last_time ? last_time : 1), new_best = 1;
+ }
+ ended(cur);
+}
+static void lost(int i) {
+ gs = G_LOST;
+ set_state(i, OPEN);
+ ended(i);
+}
+static void play(int i) {
+ int st = state(i), o[8], n = 0, boom = -1;
+ if (st == FLAG) return;
+ if (gs == G_NEW) {
+ update(shown[0], shown[1], F_OH); /* dealing a no-guessing field can take a moment */
+ deal(i, V.opts & O_SURE);
+ gs = G_PLAY, last = (uint32_t)eadk_timing_millis(), V.gw = 0; /* this game replaces the saved one */
+ int lv = level();
+ if (lv < 3) V.played[lv]++;
+ }
+ if (st == OPEN) { /* a number with all its flags: open the rest around it */
+ int f = 0, k = nbrs(i, o);
+ for (int j = 0; j < k; j++) f += state(o[j]) == FLAG;
+ if (!(cell[i] & 15) || f != (cell[i] & 15)) return;
+ for (int j = 0; j < k; j++)
+ if (state(o[j]) == HID || state(o[j]) == ASK) {
+ if (cell[o[j]] & MINE) boom = o[j];
+ else bfs[n++] = (uint16_t)o[j];
+ }
+ } else if (cell[i] & MINE) {
+ boom = i;
+ } else {
+ bfs[n++] = (uint16_t)i;
+ }
+ if (n) open_cells(n);
+ if (boom >= 0) lost(boom);
+ else if (!left) won();
+}
+static void mark(int i) {
+ int st = state(i), to = st == HID ? FLAG : st == FLAG && (V.opts & O_MARKS) ? ASK : HID;
+ if (st == OPEN) return;
+ flags += (to == FLAG) - (st == FLAG);
+ set_state(i, to);
+ dirty(i);
+}
+/* OK held on a number shows its hidden neighbors pressed, like Windows' two
+ buttons; kn (the solver's, free while playing) marks them with a 4 */
+static int held_on = -1;
+static void press(int c, int on) {
+ int o[8];
+ for (int j = nbrs(c, o); j--;) kn[o[j]] = (uint8_t)on, dirty(o[j]);
+}
+static void move_to(int i) {
+ int was = cur;
+ cur = i, cur_on = true;
+ if (was != i) draw_cell(was);
+ draw_cell(i);
+}
+
+/* ------------------------------------------------------------------ screens */
+enum { S_TITLE, S_GAME };
+enum { D_NONE, D_PAUSE, D_QUIT, D_WIN, D_HELP, D_OPTIONS, D_CUSTOM };
+static int scr, dlg, sel, stack[3][2], depth; /* the dialogs under the open one */
+static const char *const names[] = {"Continue", "Beginner", "Intermediate", "Expert", "Custom...", "Options...", "Help"};
+static int first, nitems; /* the title's rows are names[first..6]: Continue only with a game */
+
+/* the title: a window on the desktop, its menu under the counters */
+#define TX 16
+#define TY 4
+#define TW 288
+/* rows of 17 pixels, with a rule after Continue and before Options */
+static int title_y(int k) { return TY + 67 + k * 17 + (!first && k > 0 ? 5 : 0) + (k >= nitems - 2 ? 5 : 0); }
+static void size_note(char *o, int w, int h) {
+ o = num(o, w);
+ o = cat(o, " x ");
+ num(o, h);
+}
+/* the size of each field, then the time played, the best time or the mines */
+static void title_row(int k) {
+ int id = k + first, w = V.cw, h = V.ch;
+ char size[12] = "", note[12] = "";
+ if (id == 0) w = V.gw, h = V.gh, cat(num(note, (int)(elapsed / 1000) + 1), " s");
+ else if (id < 4) w = levels[id - 1][0], h = levels[id - 1][1], V.best[id - 1] && secs(note, V.best[id - 1]);
+ else if (id == 4) cat(num(note, V.cmines), " mines");
+ if (id < 5) size_note(size, w, h);
+ row(TX + 8, title_y(k), TW - 16, names[id], size, note, k == sel, id && id - 1 == V.diff && id < 5);
+}
+/* what the counters show for the selected line: mines and best time, or the saved game */
+static void title_counters(int f) {
+ int id = sel + first, l, r = 0;
+ if (id > 4) id = V.gw ? 0 : V.diff + 1; /* Options and Help: the game or level at hand */
+ if (!id) l = nm - flags, r = (int)(elapsed / 1000) + 1;
+ else if (id < 4) l = levels[id - 1][2], r = (V.best[id - 1] + 9) / 10;
+ else l = V.cmines;
+ update(l, r, f);
+}
+static void draw_title(void) {
+ first = !V.gw, nitems = 7 - first;
+ int th = title_y(nitems) + 10 - TY;
+ around(0, 0, 320, 216, TX, TY, TW, th, TEAL);
+ window(TX, TY, TW, th, "Minesweeper", 3);
+ hx = TX + 12, hy = TY + 28, hw = TW - 24;
+ around(wx0, wy0, TW - 8, th - 26, hx, hy, hw, HH, GRAY);
+ panel();
+ for (int k = 0; k < nitems; k++) {
+ title_row(k);
+ if (k == nitems - 3 || (k == 0 && !first)) rule(TX + 8, title_y(k) + 17, TW - 16);
+ }
+ /* the taskbar */
+ fill(0, 216, 320, 1, GRAY);
+ fill(0, 217, 320, 1, WHITE);
+ fill(0, 218, 320, 22, GRAY);
+ raised(2, 220, 56, 18);
+ fill(4, 222, 52, 14, GRAY);
+ static const color logo[4] = {RGB(0xFF0000), RGB(0x00A000), RGB(0x0000FF), RGB(0xFFD000)};
+ for (int q = 0; q < 4; q++) fill(7 + (q & 1) * 6, 223 + (q >> 1) * 6, 5, 5, logo[q]);
+ text("Start", 21, 222, BLACK, GRAY);
+ edge(fill, 62, 220, 130, 18, 1, BLACK, WHITE);
+ edge(fill, 63, 221, 128, 16, 1, DARK, GRAY);
+ fill(64, 222, 126, 14, RGB(0xD8D8D8));
+ text("Minesweeper", 70, 222, BLACK, RGB(0xD8D8D8));
+ title_counters(F_SMILE);
+}
+
+/* the dialogs; after a key only what changes is redrawn (whole is false) */
+static bool whole;
+static void draw_pause(void) {
+ static const char *const p[4] = {"Resume", "New game", "Help", "Quit game"};
+ int x = wx + (framed ? 4 : 0) + 2, y = wy + (framed ? 22 : 18), w = 118;
+ raised(x, y, w, 4 * 17 + 5 + 6);
+ edge(fill, x + 2, y + 2, w - 4, 4 * 17 + 5 + 2, 1, GRAY, GRAY);
+ for (int k = 0; k < 4; k++) row(x + 3, y + 3 + k * 17 + (k > 2) * 5, w - 6, p[k], 0, 0, k == sel, false);
+ rule(x + 3, y + 3 + 3 * 17, w - 6);
+}
+static void draw_ask(const char *q) {
+ if (whole) {
+ dialog(200, 100, "Minesweeper");
+ pw = 26;
+ pfill(0, 0, 26, 26, GRAY);
+ for (int j = 0; j < 26; j++)
+ for (int i = 0; i < 26; i++) {
+ int d = (i - 13) * (i - 13) + (j - 12) * (j - 12);
+ if (d < 150) pix[j * 26 + i] = d < 110 ? WHITE : BLACK;
+ }
+ push(wx0 + 12, wy0 + 10, 26);
+ text("?", wx0 + 22, wy0 + 15, RGB(0x0000FF), WHITE);
+ text(q, wx0 + 50, wy0 + 16, BLACK, GRAY);
+ }
+ button(wx0 + 34, wy0 + 46, 56, 22, "Yes", sel == 0);
+ button(wx0 + 102, wy0 + 46, 56, 22, "No", sel == 1);
+}
+static void draw_win(void) {
+ char s[40], *o;
+ dialog(230, 118, "Minesweeper");
+ pw = 34;
+ pfill(0, 0, 34, 34, GRAY);
+ face(0, 0, 2, F_COOL);
+ push(wx0 + 10, wy0 + 12, 34);
+ text(new_best ? "New best time!" : "You win!", wx0 + 56, wy0 + 8, BLACK, GRAY);
+ o = cat(s, "Time ");
+ secs(o, last_time);
+ text(s, wx0 + 56, wy0 + 26, BLACK, GRAY);
+ int lv = level();
+ if (lv < 3) {
+ o = cat(s, "Won ");
+ o = num(o, V.won[lv]);
+ o = cat(o, " of ");
+ num(o, V.played[lv]);
+ text(s, wx0 + 56, wy0 + 44, BLACK, GRAY);
+ }
+ button(wx0 + 77, wy0 + 66, 68, 22, "OK", true);
+}
+static void draw_help(void) {
+ static const char *const lines[12] = {
+ "Open every square without a mine.", "A number counts the mines around it.",
+ "Arrows, 8 4 6 2", "Move (wraps around)",
+ "OK, EXE, 5", "Open",
+ "OK on a number", "Open all around it",
+ "Backspace, Shift, 0", "Flag",
+ "Back", "Pause",
+ };
+ dialog(304, 224, "Help");
+ text(lines[0], wx0 + 8, wy0 + 6, BLACK, GRAY);
+ text(lines[1], wx0 + 8, wy0 + 22, BLACK, GRAY);
+ for (int k = 1; k < 6; k++) {
+ text(lines[2 * k], wx0 + 8, wy0 + 28 + k * 18, BLACK, GRAY);
+ text(lines[2 * k + 1], wx0 + 150, wy0 + 28 + k * 18, NAVY, GRAY);
+ }
+ text("Original by Robert Donner & Curt Johnson", wx0 + 8, wy0 + 142, BLACK, GRAY);
+ button(wx0 + 114, wy0 + 170, 68, 22, "OK", true);
+}
+static void draw_options(void) {
+ static const char *const o[2] = {"Marks (?)", "No guessing"};
+ if (whole) {
+ dialog(236, 132, "Options");
+ text("No guessing: every field can", wx0 + 10, wy0 + 50, BLACK, GRAY);
+ text("be cleared by logic alone.", wx0 + 10, wy0 + 66, BLACK, GRAY);
+ text("OK: on/off Back: done", wx0 + 10, wy0 + 88, BLACK, GRAY);
+ }
+ for (int k = 0; k < 2; k++) row(wx0 + 8, wy0 + 8 + k * 18, 212, o[k], 0, 0, k == sel, V.opts >> k & 1);
+}
+static int cf[3]; /* the custom field: height, width, mines */
+static void draw_custom(void) {
+ static const char *const f[3] = {"Height:", "Width:", "Mines:"};
+ if (whole) {
+ dialog(220, 136, "Custom Field");
+ for (int k = 0; k < 3; k++) text(f[k], wx0 + 12, wy0 + 12 + k * 26, BLACK, GRAY);
+ button(wx0 + 136, wy0 + 10, 64, 22, "OK", true);
+ button(wx0 + 136, wy0 + 40, 64, 22, "Cancel", false);
+ text("Arrows: change", wx0 + 12, wy0 + 88, BLACK, GRAY);
+ }
+ for (int k = 0; k < 3; k++) {
+ int x = wx0 + 66, y = wy0 + 9 + k * 26;
+ char s[6];
+ bool on = k == sel;
+ sunken(x, y, 50, 20);
+ fill(x + 2, y + 2, 46, 16, WHITE);
+ num(s, cf[k]);
+ fill(x + 4, y + 3, slen(s) * 7 + 2, 14, on ? NAVY : WHITE);
+ text(s, x + 5, y + 3, on ? WHITE : BLACK, on ? NAVY : WHITE);
+ }
+}
+static void draw_dialog(bool all) {
+ whole = all;
+ switch (dlg) {
+ case D_PAUSE: draw_pause(); break;
+ case D_QUIT: draw_ask("Quit game?"); break;
+ case D_WIN: draw_win(); break;
+ case D_HELP: draw_help(); break;
+ case D_OPTIONS: draw_options(); break;
+ case D_CUSTOM: draw_custom(); break;
+ }
+}
+static void draw_all(void) {
+ if (scr == S_GAME) layout(), draw_game(), game_counters(F_SMILE);
+ else draw_title();
+ draw_dialog(true);
+}
+static void open_dialog(int d, int s) {
+ stack[depth][0] = dlg, stack[depth][1] = sel, depth++;
+ dlg = d, sel = s;
+ draw_dialog(true);
+}
+/* back to what was under the dialog */
+static void close_dialog(void) {
+ depth--;
+ dlg = stack[depth][0], sel = stack[depth][1];
+ draw_all();
+}
+
+/* a new game; the same field again is only wiped clean */
+static void start(int d) {
+ int w = bw, h = bh, again = scr == S_GAME && !dlg;
+ V.diff = (uint8_t)d;
+ if (d < 3) bw = levels[d][0], bh = levels[d][1], nm = levels[d][2];
+ else bw = V.cw, bh = V.ch, nm = V.cmines;
+ new_game();
+ scr = S_GAME, dlg = D_NONE, depth = 0;
+ save();
+ if (again && w == bw && h == bh) return;
+ cur = bh / 2 * bw + bw / 2;
+ draw_all();
+}
+static bool leave; /* Quit game: back to NumPlay (or the calculator); main saves */
+static void to_title(bool keep) {
+ if (keep) save();
+ /* the saved game, ready to continue */
+ if (gs != G_PLAY && V.gw) {
+ if (unpack()) gs = G_PLAY;
+ else V.gw = 0;
+ }
+ scr = S_TITLE, dlg = D_NONE, depth = 0;
+ sel = V.gw ? 0 : V.diff; /* Continue, or the level last played */
+ draw_all();
+}
+
+int main(void) {
+ np_app_begin();
+ load();
+ now = (uint32_t)eadk_timing_millis();
+ seed ^= now;
+ to_title(false);
+ int held = 0, repeats = 0, arrows = K_UP | K_DOWN | K_LEFT | K_RIGHT, stuck = K_HOME, grip = -1;
+ bool armed = false; /* once every key held from before is let go */
+ uint32_t repeat_at = 0;
+ last = now;
+ for (;;) {
+ now = (uint32_t)eadk_timing_millis();
+ uint32_t dt = now - last;
+ last = now;
+ int k = keys(), hit = armed ? k & ~held : 0, fresh = hit;
+ stuck &= k; /* Home quits unless held since the start, whatever else is held */
+ if (k & ~stuck & K_HOME) break;
+ if (leave) break;
+ if (!armed) armed = !k, k = 0;
+ if (hit & arrows) repeat_at = now + 280, repeats = 0;
+ else if ((k & arrows) && (int32_t)(now - repeat_at) >= 0) hit |= k & arrows, repeat_at = now + 55, repeats++;
+ held = k;
+ /* what the keys change is drawn right after the refresh, so it never tears */
+ eadk_display_wait_for_vblank();
+ bool ok = hit & K_OK, back = hit & K_BACK;
+ int ud = !!(hit & K_DOWN) - !!(hit & K_UP), lr = !!(hit & K_RIGHT) - !!(hit & K_LEFT);
+ int face_now = k & K_OK ? F_OH : F_SMILE;
+
+ if (dlg == D_NONE && scr == S_TITLE) {
+ if (ud) {
+ int was = sel;
+ sel = (sel + ud + nitems) % nitems;
+ title_row(was), title_row(sel);
+ }
+ if (back) open_dialog(D_QUIT, 1); /* "Quit game?" from the title, on No */
+ else if (ok) {
+ int id = sel + first;
+ if (id == 0) {
+ V.diff = (uint8_t)level(), scr = S_GAME;
+ draw_all();
+ } else if (id < 4) {
+ start(id - 1);
+ } else if (id == 4) {
+ cf[0] = V.ch, cf[1] = V.cw, cf[2] = V.cmines;
+ open_dialog(D_CUSTOM, 0);
+ } else {
+ open_dialog(id == 5 ? D_OPTIONS : D_HELP, 0);
+ }
+ }
+ } else if (dlg == D_NONE) {
+ if (hit & arrows) {
+ int x = cur % bw + lr, y = cur / bw + ud;
+ /* a new press wraps around the edge, a held key stops there */
+ if ((unsigned)x < (unsigned)bw && (unsigned)y < (unsigned)bh) move_to(y * bw + x);
+ else if (fresh & arrows) move_to((y + bh) % bh * bw + (x + bw) % bw);
+ }
+ if (ok) {
+ if (gs < G_WON) grip = state(cur) == OPEN ? cur : -1, play(cur);
+ else if (!win_at) pressed_until = (int)now + 120, start(V.diff); /* like clicking the face */
+ }
+ if ((hit & K_FLAG) && gs < G_WON) mark(cur);
+ if (back) open_dialog(D_PAUSE, 0);
+ else if (win_at && (int)(now - win_at) >= 0) {
+ win_at = 0;
+ if (gs == G_WON) open_dialog(D_WIN, 0);
+ }
+ } else if (dlg == D_PAUSE) {
+ if (ud) sel = (sel + ud + 4) % 4, draw_dialog(false);
+ if (back || (ok && sel == 0)) close_dialog();
+ else if (ok && sel == 1) {
+ if (gs) V.gw = 0; /* given up: no Continue for it */
+ dlg = D_NONE, depth = 0, new_game(), draw_all();
+ }
+ else if (ok && sel == 2) open_dialog(D_HELP, 0);
+ else if (ok) open_dialog(D_QUIT, 0);
+ } else if (dlg == D_QUIT) {
+ if (lr) sel = !sel, draw_dialog(false);
+ if (back || (ok && sel)) close_dialog();
+ else if (ok) leave = true;
+ } else if (dlg == D_OPTIONS) {
+ if (ud) sel = !sel;
+ if (ok) V.opts ^= (uint8_t)(1 << sel);
+ if (ud || ok) draw_dialog(false);
+ if (back) save(), close_dialog();
+ } else if (dlg == D_CUSTOM) {
+ if (ud) sel = (sel + ud + 3) % 3;
+ if (lr) { /* held, the mines go by fives */
+ static const uint8_t hi[2] = {MH, MW};
+ int v = cf[sel] + lr * (repeats > 12 && sel == 2 ? 5 : 1), top = sel < 2 ? hi[sel] : (cf[1] - 1) * (cf[0] - 1), lo = sel < 2 ? 8 : 1;
+ cf[sel] = v < lo ? lo : v > top ? top : v;
+ top = (cf[1] - 1) * (cf[0] - 1);
+ if (cf[2] > top) cf[2] = top;
+ }
+ if (ud || lr) draw_dialog(false);
+ if (ok) V.ch = (uint8_t)cf[0], V.cw = (uint8_t)cf[1], V.cmines = (uint16_t)cf[2], start(3);
+ else if (back) close_dialog();
+ } else { /* help, the win */
+ if (ok || back) close_dialog();
+ }
+
+ if (scr == S_GAME && gs == G_PLAY && dlg == D_NONE) elapsed += dt;
+ /* OK held on a number where it was pressed: its hidden neighbors go down */
+ int h = scr == S_GAME && !dlg && gs == G_PLAY && (k & K_OK) && cur == grip ? cur : -1;
+ if (h != held_on) {
+ if (held_on >= 0) press(held_on, 0);
+ if ((held_on = h) >= 0) press(h, 4);
+ }
+ if (dlg == D_NONE) {
+ if (scr == S_GAME) {
+ for (int drawn = 0; qh != qt;) {
+ uint16_t i = fifo[qh++ & 1023];
+ if (i == 0xFFFF) {
+ if (drawn) break;
+ } else if (cell[i] & DIRTY) {
+ draw_cell(i), drawn++;
+ }
+ }
+ game_counters((int)(now - pressed_until) < 0 ? F_SMILE | 4 : face_now);
+ } else {
+ title_counters(face_now);
+ }
+ }
+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;
+ if (spent < 16) eadk_timing_msleep(16 - spent);
+ }
+ save();
+ return np_app_end();
+}
diff --git a/games/numdance/.gitignore b/games/numdance/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/numdance/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/numdance/Makefile b/games/numdance/Makefile
new file mode 100644
index 00000000..78158010
--- /dev/null
+++ b/games/numdance/Makefile
@@ -0,0 +1,51 @@
+# NumDance — a rhythm game: hit the arrows as they reach the targets.
+# make build output/numdance.nwa
+# make check link the app like the calculator does (output/numdance.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/numdance.nwa
+
+check: $(BUILD_DIR)/numdance.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/numdance.bin
+ @echo "BIN $(BUILD_DIR)/numdance.bin: $$(wc -c < $(BUILD_DIR)/numdance.bin) bytes"
+
+$(BUILD_DIR)/numdance.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_numdance_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_numdance_main -o $@
diff --git a/games/numdance/README.md b/games/numdance/README.md
new file mode 100644
index 00000000..b9c0f769
--- /dev/null
+++ b/games/numdance/README.md
@@ -0,0 +1,45 @@
+# NumDance
+
+A rhythm game for the NumWorks calculator, in the style of Friday Night Funkin' and Dance Dance Revolution. Arrows fall toward a row of gray targets: press the matching key just as each one lands.
+
+<img src="docs/shot.png" width="320" alt="NumDance in the middle of a song">
+
+- **7 songs and Endless:** Warm Up, Slow Jam, Bubble Pop, Neon Nights, Starlight, Hyperdrive and Boss Rush, from 84 to 180 BPM and about a minute each, plus Endless, which never stops and gets faster.
+- **4 difficulties** for every song: Easy, Normal, Hard and Expert.
+- **Taps, holds and jumps:** keep the key down along a trail, and press two keys at once for a jump.
+- **Judgments** Perfect, Great, Good and Miss, with Early or Late when you are off, a combo counter, a health bar, your score and accuracy.
+- **A grade at the end** (S+, S, A, B, C or D), with your best score, grade and full combos kept for every song and difficulty.
+
+The calculator has no speaker, so the music is something you see: the stage lights, the speakers, the LED bars, the health icons and the targets all pulse on the beat, a faint line scrolls by on every beat, and every chart sits on the beat grid, so the arrows themselves feel like a song.
+
+## Controls
+
+| Lane | Keys |
+| --- | --- |
+| Left | Left, 4 or 1 |
+| Down | Down, 5 or 2 |
+| Up | Up, 8 or 3 |
+| Right | Right, 6 or + |
+
+All three groups work at once: the arrow keys, the 4 5 8 6 cross, or the 1 2 3 + row. **Back** pauses (Resume, Restart, Quit game), **Home** leaves the app.
+
+In the song list, **Up / Down** picks a song and **Left / Right** the difficulty.
+
+## Options
+
+- **Scroll speed** from 1x to 4x.
+- **Direction:** arrows falling down (the default) or rising up.
+- **Offset:** moves every key press earlier or later by up to 120 ms. **Calibrate offset** measures it for you: press as eight arrows land, and it keeps the average.
+- **No-fail:** the song goes on even when the health bar is empty.
+
+## How the songs are made
+
+Each song is a few bytes: a tempo, a seed and a list of sections (intro, verse, build-up, chorus, break, drop, outro). The notes are made bar by bar from them, so a chorus comes back the same every time (mirrored the second time), and the difficulties share one rhythm: Easy plays the strong beats, Expert fills in the rest. The patterns are streams, staircases, trills, shapes and jacks, with jumps and holds, and they are checked to be playable with two thumbs: never more than two keys at once, enough time between notes for the difficulty, and no fast repeats on one key.
+
+## Credits
+
+A new game, inspired by [Friday Night Funkin'](https://github.com/FunkinCrew/Funkin) by ninjamuffin99, PhantomArcade, evilsk8r and Kawai Sprite (the arrow colours, the gray targets, the health bar with its two faces, "Ready? Set Go!") and by Konami's Dance Dance Revolution (the judgments, the combo and the grades). No code, art or music comes from either.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `NumDance.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/numdance/docs/shot.png b/games/numdance/docs/shot.png
new file mode 100644
index 00000000..8036abc5
Binary files /dev/null and b/games/numdance/docs/shot.png differ
diff --git a/games/numdance/src/icon.png b/games/numdance/src/icon.png
new file mode 100644
index 00000000..92a48a92
Binary files /dev/null and b/games/numdance/src/icon.png differ
diff --git a/games/numdance/src/main.c b/games/numdance/src/main.c
new file mode 100644
index 00000000..f5ac4a22
--- /dev/null
+++ b/games/numdance/src/main.c
@@ -0,0 +1,1419 @@
+/* NumDance: a rhythm game in the style of Friday Night Funkin' and Dance
+ * Dance Revolution. Arrows scroll to a row of gray targets; press the
+ * matching key just as each one lands.
+ *
+ * The calculator has no speaker, so the music is something you see: the
+ * stage pulses on every beat and every chart sits on the beat grid. A song is
+ * a list of sections (verse, chorus, break...) that becomes notes bar by bar
+ * from a seed, so a whole song takes a few bytes and its choruses come back
+ * like in a real song.
+ *
+ * Only what changes is redrawn. The screen is cut into sixteen columns of 20
+ * pixels with a bit per row that says "repaint me"; marked parts are composed
+ * in a small buffer and pushed, which keeps the game at 60 frames a second.
+ * Keys are read every millisecond between frames, so presses are timed to
+ * the millisecond, not to the frame. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumDance";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+#define W 320
+#define H 240
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define INK RGB(0x0B0712) /* outlines */
+#define KEY(k) (1ull << (k))
+
+static int mini(int a, int b) { return a < b ? a : b; }
+static int maxi(int a, int b) { return a > b ? a : b; }
+static int clamp(int v, int a, int b) { return v < a ? a : v > b ? b : v; }
+static int iabs(int v) { return v < 0 ? -v : v; }
+static void zero(void *p, int n) {
+ for (volatile uint8_t *q = p; n--;) *q++ = 0; /* volatile: no call to memset */
+}
+
+/* f over b; a from 0 (all b) to 32 (all f) */
+static color mix(color f, color b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (color)(y | y >> 16);
+}
+
+/* ------------------------------------------------------------------ drawing */
+#define BUFPX (W * 24)
+static color buf[BUFPX] __attribute__((aligned(4)));
+static int bx, by, bw, bh; /* the part of the screen buf holds */
+
+/* n pixels of c, two at a time */
+typedef uint32_t __attribute__((may_alias)) pair_t;
+static void fill(color *p, int n, color c) {
+ if (n <= 0) return;
+ if ((uintptr_t)p & 2) *p++ = c, n--;
+ pair_t *q = (pair_t *)(void *)p, v = c | (uint32_t)c << 16;
+ for (; n > 1; n -= 2) *q++ = v;
+ if (n) *(color *)q = c;
+}
+
+static void rect(int x, int y, int w, int h, color c, int a) {
+ int x0 = maxi(x, bx), x1 = mini(x + w, bx + bw), y0 = maxi(y, by), y1 = mini(y + h, by + bh);
+ if (x0 >= x1 || a <= 0) return;
+ for (int j = y0; j < y1; j++) {
+ color *p = buf + (j - by) * bw + x0 - bx, *e = p + x1 - x0;
+ if (a >= 32) fill(p, x1 - x0, c);
+ else
+ for (; p < e; p++) *p = mix(c, *p, a);
+ }
+}
+
+/* a disc, or a ring t pixels thick, with soft edges */
+static void disc(int cx, int cy, int r, int t, color c, int a) {
+ int x0 = maxi(cx - r - 1, bx), x1 = mini(cx + r + 2, bx + bw), y0 = maxi(cy - r - 1, by), y1 = mini(cy + r + 2, by + bh);
+ int ri = t ? r - t : 0, ir = (16 << 16) / maxi(r, 1), iri = (16 << 16) / maxi(ri, 1);
+ for (int y = y0; y < y1; y++)
+ for (int x = x0; x < x1; x++) {
+ int d = (x - cx) * (x - cx) + (y - cy) * (y - cy), e = r * r - d + r, k;
+ if (e <= 0) continue;
+ k = e >= 2 * r ? 32 : e * ir >> 16; /* about a pixel of soft edge */
+ if (ri > 0) {
+ e = d - ri * ri + ri;
+ if (e <= 0) continue;
+ if (e < 2 * ri) k = mini(k, e * iri >> 16);
+ }
+ color *p = buf + (y - by) * bw + x - bx;
+ *p = mix(c, *p, k * a >> 5);
+ }
+}
+
+/* ------------------------------------------------------------------ arrows */
+/* One arrow shape (pointing up) drawn at four sizes when the app starts:
+ 0 empty, 1-15 the soft outer edge, 16 outline, 17 inner rim, 18-49 body
+ from the tip to the tail. Palettes give it colours; the other directions
+ read the same pixels turned. */
+static const uint8_t SZ[4] = {32, 36, 38, 40};
+static uint16_t soff[4];
+static uint8_t spr[32 * 32 + 36 * 36 + 38 * 38 + 40 * 40];
+enum { P_NOTE, P_PRESS = 4, P_CONF = 8, P_STRUM = 12, P_BEAT, P_MISS, NPAL };
+static color pal[NPAL][50];
+static const color lanec[4] = {RGB(0xC24B99), RGB(0x00FFFF), RGB(0x12FA05), RGB(0xF9393F)};
+
+static void make_arrows(void) {
+ static const int8_t vx[7] = {0, 88, 37, 37, -37, -37, -88}, vy[7] = {-88, 2, 2, 86, 86, 2, 2};
+ int o = 0;
+ for (int s = 0; s < 4; s++) {
+ int n = SZ[s];
+ float h = n * .5f, ol = n * .075f;
+ soff[s] = (uint16_t)o;
+ for (int j = 0; j < n; j++)
+ for (int i = 0; i < n; i++) {
+ float x = (i + .5f) / h - 1, y = (j + .5f) / h - 1, dd = 9;
+ bool in = false;
+ for (int k = 0, l = 6; k < 7; l = k++) { /* distance to the outline, and inside or not */
+ float ax = vx[k] * .01f, ay = vy[k] * .01f, ex = vx[l] * .01f - ax, ey = vy[l] * .01f - ay;
+ float wx = x - ax, wy = y - ay, u = (wx * ex + wy * ey) / (ex * ex + ey * ey);
+ u = u < 0 ? 0 : u > 1 ? 1 : u;
+ float qx = wx - ex * u, qy = wy - ey * u;
+ if (qx * qx + qy * qy < dd) dd = qx * qx + qy * qy;
+ if ((ay > y) != (ay + ey > y) && x < ax + ex * (y - ay) / ey) in = !in;
+ }
+ float d = __builtin_sqrtf(dd) * h * (in ? -1 : 1) - n * .07f; /* in pixels, corners rounded */
+ int q = d > .5f ? 0 : d > -.5f ? 1 + (int)((.5f - d) * 14.9f) : d > -ol ? 16 : d > -ol - 1.4f ? 17 : 18 + clamp((int)((y + 1) * 16), 0, 31);
+ spr[o++] = (uint8_t)q;
+ }
+ }
+}
+
+static void mkpal(int i, color out, color rim, color hi, color lo) {
+ pal[i][16] = out, pal[i][17] = rim;
+ for (int k = 0; k < 32; k++) pal[i][18 + k] = mix(lo, hi, k);
+}
+
+static void make_palettes(void) {
+ color gray = RGB(0x87A3AD);
+ for (int l = 0; l < 4; l++) {
+ color c = lanec[l], pc = mix(c, gray, 12);
+ mkpal(P_NOTE + l, mix(0, c, 26), mix(WHITE, c, 15), mix(WHITE, c, 6), mix(0, c, 10));
+ mkpal(P_PRESS + l, RGB(0x1B2127), mix(WHITE, pc, 8), pc, mix(0, pc, 12));
+ mkpal(P_CONF + l, mix(0, c, 14), WHITE, mix(WHITE, c, 22), mix(WHITE, c, 6));
+ }
+ mkpal(P_STRUM, RGB(0x1C242B), RGB(0xC6D6DC), RGB(0xA0B6BF), RGB(0x6B838D));
+ mkpal(P_BEAT, RGB(0x26313A), RGB(0xEEF5F8), RGB(0xC2D4DB), RGB(0x8AA2AC));
+ mkpal(P_MISS, INK, RGB(0x5A5A70), RGB(0x46465A), RGB(0x2A2A38));
+}
+
+static void arrow(int dir, int cx, int cy, int s, const color *pl, int a) {
+ int n = SZ[s], x0 = cx - n / 2, y0 = cy - n / 2, sx, sy, base;
+ switch (dir) {
+ case 0: sx = n, sy = -1, base = n - 1; break;
+ case 1: sx = 1, sy = -n, base = n * (n - 1); break;
+ case 2: sx = 1, sy = n, base = 0; break;
+ default: sx = -n, sy = 1, base = n * (n - 1);
+ }
+ int xa = maxi(x0, bx), xb = mini(x0 + n, bx + bw), ya = maxi(y0, by), yb = mini(y0 + n, by + bh);
+ for (int y = ya; y < yb; y++) {
+ color *p = buf + (y - by) * bw + xa - bx;
+ const uint8_t *q = spr + soff[s] + base + (y - y0) * sy + (xa - x0) * sx;
+ for (int x = xa; x < xb; x++, p++, q += sx) {
+ int v = *q;
+ if (v) *p = v < 16 ? mix(pl[16], *p, v * a >> 4) : a >= 32 ? pl[v] : mix(pl[v], *p, a);
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ text */
+/* ASCII 32..95, columns of 7 bits, top bit first; lower case is drawn upper */
+static const uint8_t font[64][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x07,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14},
+ {0x24,0x2A,0x7F,0x2A,0x12},{0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00},
+ {0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},{0x14,0x08,0x3E,0x08,0x14},{0x08,0x08,0x3E,0x08,0x08},
+ {0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},{0x20,0x10,0x08,0x04,0x02},
+ {0x3E,0x41,0x41,0x41,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},
+ {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},
+ {0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00},
+ {0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},
+ {0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22},
+ {0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x49,0x49,0x7A},
+ {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41},
+ {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x02,0x0C,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},
+ {0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},
+ {0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},{0x3F,0x40,0x38,0x40,0x3F},
+ {0x63,0x14,0x08,0x14,0x63},{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},{0x00,0x7F,0x41,0x41,0x00},
+ {0x02,0x04,0x08,0x10,0x20},{0x00,0x41,0x41,0x7F,0x00},{0x04,0x02,0x01,0x02,0x04},{0x40,0x40,0x40,0x40,0x40},
+};
+
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static int ga = 32, gsl, gp; /* text alpha, slant (pixels per dot row) and letter spacing */
+static int tw(const char *s, int k) { return slen(s) ? slen(s) * (6 * k + gp) - k - gp : 0; }
+
+/* each dot a k-square grown by g pixels; c at the top to c2 (if not 0) at the bottom */
+static void glyphs(const char *s, int x, int y, int k, int g, color c, color c2) {
+ if (y - g >= by + bh || y + 7 * k + g <= by) return;
+ for (; *s; s++, x += 6 * k + gp) {
+ unsigned ch = (uint8_t)*s;
+ if (ch >= 'a' && ch <= 'z') ch -= 32;
+ ch -= 32;
+ if (ch > 63) ch = '?' - 32;
+ if (x - g >= bx + bw || x + 5 * k + g + 6 * gsl <= bx) continue;
+ for (int i = 0; i < 5; i++)
+ for (int j = 0, b = font[ch][i]; b; j++, b >>= 1)
+ if (b & 1) rect(x + i * k - g + (6 - j) * gsl, y + j * k - g, k + 2 * g, k + 2 * g, c2 ? mix(c2, c, j * 5) : c, ga);
+ }
+}
+/* text with a dark outline g pixels wide */
+static void text(const char *s, int x, int y, int k, int g, color c, color c2) {
+ if (g) glyphs(s, x, y, k, g, INK, INK);
+ glyphs(s, x, y, k, 0, c, c2);
+}
+static void ctext(const char *s, int cx, int y, int k, int g, color c, color c2) {
+ text(s, cx - tw(s, k) / 2, y, k, g, c, c2);
+}
+static void small(const char *s, int cx, int y, color c) { ctext(s, cx, y, 1, 1, c, 0); }
+static void heading(const char *s, int y) { ctext(s, 160, y, 3, 2, WHITE, RGB(0xFFE070)); }
+
+/* a menu choice: the chosen one bright, between two arrows */
+static void item(const char *t, int cx, int y, bool on) {
+ ctext(t, cx, y, 2, on ? 2 : 1, on ? WHITE : RGB(0x8A82A8), on ? RGB(0xFFE070) : RGB(0x6A6288));
+ if (on) {
+ int d = tw(t, 2) / 2 + 20;
+ arrow(3, cx - d, y + 6, 0, pal[P_NOTE + 3], 32);
+ arrow(0, cx + d, y + 6, 0, pal[P_NOTE], 32);
+ }
+}
+
+static char *num(char *o, uint32_t v) {
+ char t[10];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+static char *cat(char *o, const char *s) {
+ while (*s) *o++ = *s++;
+ *o = 0;
+ return o;
+}
+static char *signed_ms(char *o, int v) {
+ *o++ = v < 0 ? '-' : '+';
+ return cat(num(o, (uint32_t)iabs(v)), " ms");
+}
+/* v/100 with two decimals */
+static char *pct(char *o, int v) {
+ o = num(o, (uint32_t)v / 100);
+ *o++ = '.';
+ *o++ = (char)('0' + v / 10 % 10);
+ *o++ = (char)('0' + v % 10);
+ return cat(o, "%");
+}
+
+/* ------------------------------------------------------------------ repainting */
+enum { S_TITLE, S_SONGS, S_OPTIONS, S_HELP, S_CALIB, S_PLAY, S_RESULTS };
+static int screen, sel, menu_beat;
+static uint16_t dirt[H]; /* a bit per column of 20 pixels that must be repainted, for each row */
+static int dirty_px;
+
+static void mark(int x, int y, int w, int h) {
+ int x0 = maxi(x, 0), x1 = mini(x + w, W), y0 = maxi(y, 0), y1 = mini(y + h, H);
+ if (x0 >= x1 || y0 >= y1) return;
+ unsigned m = (2u << (x1 - 1) / 20) - (1u << x0 / 20);
+ for (int r = y0; r < y1; r++)
+ for (unsigned n = m & ~dirt[r]; n; n &= n - 1) dirty_px += 20;
+ for (int r = y0; r < y1; r++) dirt[r] |= (uint16_t)m;
+}
+static void mark_all(void) { mark(0, 0, W, H); }
+
+static void scene(void);
+
+static void paint(int x, int y, int w, int h) {
+ int rows = BUFPX / w;
+ for (int y0 = y; y0 < y + h; y0 += rows) {
+ bx = x, by = y0, bw = w, bh = mini(rows, y + h - y0);
+ scene();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y0, (uint16_t)w, (uint16_t)bh}, buf);
+ }
+}
+
+/* rows that need the same columns go together, as few rectangles as possible */
+static void flush(void) {
+ for (int y = 0; y < H;) {
+ int m = dirt[y], y1 = y + 1;
+ while (y1 < H && dirt[y1] == m) y1++;
+ for (int b = 0; b < 16;) {
+ if (!(m >> b & 1)) {
+ b++;
+ continue;
+ }
+ int e = b;
+ while (e < 16 && (m >> e & 1)) e++;
+ paint(b * 20, y, (e - b) * 20, y1 - y);
+ b = e;
+ }
+ y = y1;
+ }
+ for (int y = 0; y < H; y++) dirt[y] = 0;
+ dirty_px = 0;
+}
+
+/* things with a fixed place that change now and then: repainted when their
+ key or their rectangle changes */
+typedef struct {
+ int16_t x, y, w, h;
+ int32_t key;
+ uint8_t wait; /* frames the stage has been kept waiting */
+} watch_t;
+#define NW 26 /* 0-11 the play screen or menus, 12-19 and 24-25 the stage, 20-23 the rest */
+static watch_t wt[NW];
+static void watch(int i, int x, int y, int w, int h, int32_t key) {
+ watch_t *o = &wt[i];
+ if (o->key == key && o->x == x && o->y == y && o->w == w && o->h == h) return;
+ /* when a lot changes, the stage can wait a frame or two, never longer */
+ if ((i >= 24 || (i >= 12 && i < 20)) && dirty_px > 22000 && screen == S_PLAY && o->wait++ < 2) return;
+ mark(o->x, o->y, o->w, o->h);
+ mark(x, y, w, h);
+ *o = (watch_t){(int16_t)x, (int16_t)y, (int16_t)w, (int16_t)h, key, 0};
+}
+
+/* ------------------------------------------------------------------ saved */
+#define NSONG 8 /* 7 songs, then Endless */
+#define SAVE_NAME "numdance.sav"
+static struct {
+ uint8_t magic, version, speed, up, nofail, song, diff;
+ int8_t offset; /* ms taken off every key press */
+ uint8_t grade[NSONG][4]; /* 1-6 D..S+, 8: full combo */
+ uint32_t best[NSONG][4];
+} S;
+static bool save_due;
+
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ if (d && n == sizeof S && d[0] == 'D' && d[1] == 1) {
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&S)[i] = d[i];
+ if (S.speed > 6) S.speed = 2;
+ S.up &= 1, S.nofail &= 1;
+ if (S.song >= NSONG) S.song = 0;
+ S.diff &= 3;
+ S.offset = (int8_t)clamp(S.offset, -120, 120);
+ for (int i = 0; i < NSONG; i++)
+ for (int j = 0; j < 4; j++) {
+ if ((S.grade[i][j] & 7) > 6 || S.grade[i][j] > 15) S.grade[i][j] = 0;
+ if (S.best[i][j] > 99999999) S.best[i][j] = 0;
+ }
+ } else {
+ zero(&S, sizeof S);
+ S.speed = 2, S.diff = 1;
+ }
+}
+static void save(void) {
+ S.magic = 'D', S.version = 1;
+ ef_write(SAVE_NAME, &S, sizeof S);
+ save_due = false;
+}
+
+/* ------------------------------------------------------------------ songs */
+enum { STREAM, STAIRS, TRILL, SHAPES, JACKS }; /* what the lanes do */
+enum { INTRO, VERSE, BUILD, CHORUS, BREAK, DROP, OUTRO }; /* song sections */
+#define STY(fam, hold, jump, sync) ((fam) | (hold) << 3 | (jump) << 5 | (sync) << 7)
+#define SC(t, n) ((t) << 4 | ((n) - 1))
+typedef struct {
+ char name[12];
+ uint8_t bpm, seed, style, sec[9];
+ color c;
+} song_t;
+static const song_t songs[NSONG] = {
+ {"Warm Up", 96, 3, STY(STAIRS, 1, 0, 0),
+ {SC(INTRO, 2), SC(VERSE, 4), SC(CHORUS, 4), SC(VERSE, 4), SC(CHORUS, 4), SC(BREAK, 2), SC(CHORUS, 4), SC(OUTRO, 2)},
+ RGB(0x2F9BFF)},
+ {"Slow Jam", 84, 5, STY(STREAM, 3, 1, 0),
+ {SC(INTRO, 2), SC(VERSE, 4), SC(CHORUS, 4), SC(BREAK, 2), SC(VERSE, 4), SC(CHORUS, 4), SC(OUTRO, 2)},
+ RGB(0xFF8A2A)},
+ {"Bubble Pop", 112, 21, STY(TRILL, 1, 1, 1),
+ {SC(INTRO, 2), SC(VERSE, 4), SC(BUILD, 4), SC(CHORUS, 8), SC(BREAK, 2), SC(VERSE, 4), SC(BUILD, 4), SC(CHORUS, 8), SC(OUTRO, 2)},
+ RGB(0xFF6FC8)},
+ {"Neon Nights", 124, 7, STY(SHAPES, 1, 2, 1),
+ {SC(INTRO, 2), SC(VERSE, 8), SC(BUILD, 4), SC(CHORUS, 8), SC(VERSE, 8), SC(CHORUS, 8), SC(OUTRO, 2)},
+ RGB(0xB03CFF)},
+ {"Starlight", 140, 13, STY(JACKS, 2, 2, 1),
+ {SC(INTRO, 2), SC(VERSE, 8), SC(CHORUS, 8), SC(BREAK, 4), SC(CHORUS, 8), SC(DROP, 8), SC(OUTRO, 2)},
+ RGB(0x4F6BFF)},
+ {"Hyperdrive", 160, 9, STY(STREAM, 0, 1, 0),
+ {SC(INTRO, 4), SC(VERSE, 8), SC(BUILD, 4), SC(DROP, 8), SC(BREAK, 2), SC(VERSE, 8), SC(BUILD, 4), SC(DROP, 8), SC(OUTRO, 2)},
+ RGB(0x00C89A)},
+ {"Boss Rush", 180, 17, STY(STAIRS, 1, 3, 1),
+ {SC(INTRO, 4), SC(VERSE, 8), SC(BUILD, 4), SC(DROP, 16), SC(BREAK, 2), SC(CHORUS, 8), SC(DROP, 8), SC(OUTRO, 2)},
+ RGB(0xFF3344)},
+ {"Endless", 100, 0, 0, {0}, RGB(0xB8B8C8)}, /* its sections are in gen_bar */
+};
+static const char *const diff_name[4] = {"Easy", "Normal", "Hard", "Expert"};
+static const color diff_c[4] = {RGB(0x12FA05), RGB(0xFFD400), RGB(0xF9393F), RGB(0xC24B99)};
+
+/* rhythms for a bar, a bit per 16th: each level adds to the ones below */
+static const uint16_t tpl[5][4] = {
+ {0x1111, 0x0101, 0x0111, 0x1101}, /* quarters, halves */
+ {0x0404, 0x4040, 0x1040, 0x4400}, /* some eighths */
+ {0x5555, 0x4444, 0x4848, 0x2424}, /* eighths, off-beats */
+ {0x8080, 0x0808, 0x0202, 0x8888}, /* sixteenth pick-ups */
+ {0x7777, 0x2222, 0x0A0A, 0x6666}, /* bursts */
+};
+static const uint8_t shapes[4][4] = {{0, 1, 2, 3}, {3, 2, 1, 0}, {0, 2, 1, 3}, {1, 3, 0, 2}};
+/* what a thumb can do: time between any two notes, and two in one lane */
+static const int16_t min_gap[4] = {290, 160, 125, 85}, jack_gap[4] = {600, 380, 250, 170};
+
+typedef struct {
+ int32_t t; /* ms of song time */
+ uint16_t len; /* a hold's length, or 0 */
+ uint8_t lane, st;
+} note_t;
+enum { N_WAIT, N_HOLD, N_DONE, N_MISS, N_DROP };
+#define NR 128
+static note_t notes[NR];
+static int nh, nt; /* the ring's next free slot and oldest note */
+
+typedef struct {
+ int32_t t16; /* 1/16 ms */
+ uint16_t beat16;
+ uint8_t type;
+} bar_t;
+static bar_t bars[8];
+static int nbars;
+
+static struct {
+ const song_t *s; /* 0: Endless */
+ int d, sec, bis, type, nb, occ[7], count, bpm;
+ int32_t t16, last_t, busy[4], hold_end, jump_t;
+ int last, dir, mir, fam, ta, tb, shape, idx, lastp, lastn, quick;
+ bool done, counting;
+} G;
+static uint32_t rs;
+static uint32_t crand(void) {
+ rs ^= rs << 13;
+ rs ^= rs >> 17;
+ rs ^= rs << 5;
+ return rs;
+}
+
+static void gen_start(int song, int d) {
+ zero(&G, sizeof G);
+ G.s = song < NSONG - 1 ? &songs[song] : 0;
+ G.d = d, G.bpm = songs[song].bpm;
+ G.last_t = G.hold_end = G.jump_t = -99999;
+ for (int l = 0; l < 4; l++) G.busy[l] = -99999;
+ nbars = nh = nt = 0;
+}
+
+static void add_note(int32_t t, int lane, int len) {
+ G.count++;
+ if (G.counting) return;
+ notes[nh] = (note_t){t, (uint16_t)len, (uint8_t)lane, N_WAIT};
+ nh = (nh + 1) & (NR - 1);
+}
+
+/* the next lane of this bar's figure, or -1 if all are busy */
+static int pick(int32_t t) {
+ int l;
+ switch (G.fam) {
+ case STREAM: l = (G.last + 1 + (int)(crand() % 3)) & 3; break;
+ case STAIRS:
+ l = G.last + G.dir;
+ if (l < 0 || l > 3) G.dir = -G.dir, l = G.last + G.dir;
+ break;
+ case TRILL: l = G.idx & 1 ? G.tb : G.ta; break;
+ case SHAPES: l = shapes[G.shape][G.idx & 3]; break;
+ default: l = G.idx & 1 ? G.last : (G.last + 1 + (int)(crand() % 3)) & 3; /* jacks: each twice */
+ }
+ G.idx++;
+ for (int k = 0; k < 4; k++, l = (l + 1) & 3) {
+ int p = G.mir ? 3 - l : l;
+ if (t >= G.busy[p]) {
+ G.last = l;
+ return p;
+ }
+ }
+ return -1;
+}
+
+/* the notes of the next bar */
+static void gen_bar(void) {
+ const song_t *s = G.s;
+ int seed = s ? s->seed : 99 + G.sec / 5;
+ if (G.done) return;
+ if (!G.bis) { /* a new section */
+ int sc;
+ if (!s) { /* Endless: the same loop of sections, faster each time */
+ static const uint8_t loop[5] = {SC(VERSE, 4), SC(BUILD, 4), SC(CHORUS, 8), SC(BREAK, 2), SC(DROP, 8)};
+ sc = loop[G.sec % 5];
+ G.bpm = mini(100 + G.sec / 5 * 8, 196);
+ } else if (G.sec >= 9 || !(sc = s->sec[G.sec])) {
+ G.done = true;
+ return;
+ }
+ G.type = sc >> 4, G.nb = (sc & 15) + 1;
+ G.mir = G.occ[G.type]++ & 1; /* a section's second time is mirrored */
+ rs = (uint32_t)seed * 0x9E3779B1u + (uint32_t)G.type * 7919u + 1;
+ crand();
+ G.last = (int)(crand() & 3), G.dir = crand() & 1 ? 1 : -1;
+ }
+ int d = G.d, type = G.type, bis = G.bis, style = s ? s->style : STY(STREAM, 1, 2, 1);
+ int32_t bar16 = 3840000 / G.bpm, step16 = bar16 / 16; /* 4 beats of 60000/bpm ms */
+ if (!G.counting) bars[nbars & 7] = (bar_t){G.t16, (uint16_t)(bar16 / 4), (uint8_t)type};
+ nbars++;
+ /* the bars of a section go A B A C, and the same seed makes the same bar */
+ int v = bis & 1 ? 1 + (bis >> 1 & 1) : 0;
+ rs = (uint32_t)seed * 0x9E3779B1u ^ (uint32_t)(type << 24 | v << 16 | (bis >> 2) << 8 | 0x55);
+ crand();
+ uint32_t r = crand();
+ int tier = d + (type == INTRO || type == OUTRO ? -1 : type == CHORUS || type == DROP ? 1 : type == BUILD ? bis * 2 >= G.nb : 0);
+ bool fast = step16 >> 4 < min_gap[d]; /* sixteenths too fast to run */
+ tier = clamp(tier + (s ? 0 : G.sec / 10), 0, fast && d < 3 ? 3 : 4);
+ fast &= d == 3;
+ uint16_t m = 0;
+ for (int k = 0; k <= tier; k++) {
+ int i = (int)(r >> (k * 2) & 3);
+ if (!(style >> 7) && (k == 1 || k == 2)) i &= 1; /* straight songs keep to the beat */
+ m |= tpl[k][i];
+ }
+ for (int k = 0, run = 0; k < 16; k++) { /* no more than 5 sixteenths in a row */
+ run = m >> k & 1 ? run + 1 : 0;
+ if (run > 5) m &= (uint16_t)~(1 << k), run = 0;
+ /* too fast on Expert: runs become pairs, a pick-up into the next step */
+ if (fast && (k & 1) && (m >> k & 3) == 3) m &= (uint16_t)~(1 << (k - 1));
+ }
+ bool brk = type == BREAK;
+ if (brk) m = d >= 2 ? 0x0101 : 1;
+ G.fam = type == BUILD ? STAIRS : crand() % 3 ? (style & 7) : (int)(crand() % 5);
+ G.ta = (int)(crand() & 3), G.tb = (G.ta + 1 + (int)(crand() % 3)) & 3, G.shape = (int)(crand() & 3), G.idx = 0;
+ int holdp = (style >> 3 & 3) + (brk ? 8 : 0);
+ int jumpp = type == CHORUS || type == DROP ? (style >> 5 & 3) + 1 + (d == 3) : type == VERSE ? (style >> 5 & 3) / 2 : 0;
+ int steps[17], ns = 0, prev = -8;
+ for (int k = 0; k < 16; k++)
+ if (m >> k & 1) steps[ns++] = k;
+ steps[ns] = 16;
+ for (int i = 0; i < ns; i++) {
+ int st = steps[i], gap = steps[i + 1] - st, l, len = 0;
+ int32_t t = (G.t16 + st * step16) >> 4;
+ bool quick = t - G.last_t < min_gap[d];
+ if (quick) { /* Expert: a quick note on the other thumb, one at a time, with room after it */
+ l = 3 - G.lastp;
+ if (d < 3 || t - G.last_t < 75 || (gap * step16 >> 4) < min_gap[d] || G.quick || G.lastn > 1 || t < G.hold_end || t < G.busy[l]) continue;
+ G.last = 3 - G.last;
+ } else {
+ l = pick(t);
+ if (l < 0) continue;
+ if (gap >= 4 && t >= G.hold_end && (int)(crand() & 7) < holdp) { /* one hold at a time */
+ int n = gap - 2;
+ if (d >= 2 && !brk && !(crand() & 3)) n = 6 + (int)(crand() & 3) * 2; /* long: other notes come meanwhile */
+ len = n * step16 >> 4;
+ }
+ }
+ add_note(t, l, len);
+ G.busy[l] = t + len + jack_gap[d];
+ G.quick = quick, G.lastp = l, G.lastn = 1;
+ /* a jump: two arrows on a beat, with room around it, at most every other beat */
+ if (!quick && d && !(st & 3) && (d > 1 || !st) && gap >= 2 && st - prev >= 2 && t >= G.hold_end && t - G.jump_t >= bar16 >> 5 &&
+ (int)(crand() & 7) < jumpp) {
+ int l2 = pick(t);
+ if (l2 >= 0) add_note(t, l2, len), G.busy[l2] = t + len + jack_gap[d], G.lastn = 2, G.jump_t = t;
+ }
+ G.hold_end = maxi(G.hold_end, t + len);
+ G.last_t = t, prev = st;
+ }
+ G.t16 += bar16;
+ if (++G.bis == G.nb) G.bis = 0, G.sec++;
+}
+
+/* ms since the last beat at song time t; *n: that beat's number */
+static int beat_at(int32_t t, int *n, int *type) {
+ int i = nbars - 1;
+ while (i > 0 && i > nbars - 8 && (bars[i & 7].t16 >> 4) > t) i--;
+ if (i < 0) return *n = 0, *type = 0, 0;
+ const bar_t *b = &bars[i & 7];
+ int32_t d = t * 16 - b->t16, k = d >= 0 ? d / b->beat16 : -1 - (-d - 1) / b->beat16;
+ *n = i * 4 + (int)k, *type = b->type;
+ return (int)((d - k * b->beat16) >> 4);
+}
+
+/* ------------------------------------------------------------------ keys */
+static uint32_t now;
+static uint64_t held, hit, press, rep_ok; /* rep_ok: keys pressed on this screen, which may repeat */
+static uint32_t rep_at;
+static bool quit, tq; /* tq: "Quit game?" over the title */
+static int tsel;
+static uint8_t lanes; /* lanes held */
+typedef struct {
+ uint32_t t;
+ uint8_t lane, down;
+} ev_t;
+static ev_t evq[32];
+static int nev;
+/* left, down, up, right: the arrows, 4 5 8 6, and 1 2 3 + */
+static const uint8_t lane_key[12] = {0, 36, 42, 2, 37, 43, 1, 31, 44, 3, 38, 45};
+
+/* between frames too, so presses get the right time */
+static void poll(void) {
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t ms = (uint32_t)eadk_timing_millis();
+ hit |= k & ~held;
+ held = k;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) quit = true;
+ int ls = 0;
+ for (int i = 0; i < 12; i++)
+ if (k >> lane_key[i] & 1) ls |= 1 << (i / 3);
+ for (int l = 0; l < 4; l++)
+ if (((ls ^ lanes) >> l & 1) && nev < 32) evq[nev++] = (ev_t){ms, (uint8_t)l, (uint8_t)(ls >> l & 1)};
+ lanes = (uint8_t)ls;
+}
+
+static void input(void) {
+ poll();
+ press = hit, hit = 0;
+ rep_ok = (rep_ok | press) & held;
+ const uint64_t rep = (KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down)) & rep_ok;
+ if (press & rep) rep_at = now + 380;
+ else if ((held & rep) && (int32_t)(now - rep_at) >= 0) press |= held & rep, rep_at = now + 90;
+}
+static void go(int s, int i) {
+ screen = s, sel = i, rep_ok = 0; /* a key still held from the last screen does not repeat */
+ mark_all();
+}
+
+static bool pressed(int k) { return press >> k & 1; }
+static bool ok_key(void) { return pressed(eadk_key_ok) || pressed(eadk_key_exe); }
+static int ud(void) { return pressed(eadk_key_down) - pressed(eadk_key_up); }
+static int lr(void) { return pressed(eadk_key_right) - pressed(eadk_key_left); }
+
+/* ------------------------------------------------------------------ the stage */
+static color bgrow[H], lanerow[H];
+
+static void make_stage(void) {
+ for (int y = 0; y < H; y++) {
+ color c = y < 212 ? mix(RGB(0x331552), RGB(0x0A0514), y * 32 / 212) : y == 212 ? RGB(0x6E48A8) : mix(RGB(0x0C0714), RGB(0x2A1A40), (y - 213) * 32 / 27);
+ bgrow[y] = c;
+ lanerow[y] = mix(RGB(0x05030A), c, 21);
+ }
+}
+
+/* a speaker cone in one pass: rim, surround, cone, dust cap and its shine */
+static void cone(int cx, int cy, int r, int glow) {
+ int R = r + 3, x0 = maxi(cx - R, bx), x1 = mini(cx + R + 1, bx + bw), y0 = maxi(cy - R, by), y1 = mini(cy + R + 1, by + bh);
+ int cap = (r / 3 + 1) * (r / 3 + 1), in = (r - 1) * (r - 1), out = (r + 1) * (r + 1), fold = r * r * 4 / 9;
+ int grad = (26 << 16) / (in - cap), hl = r / 7 + 1;
+ color sur = mix(RGB(0x6E62A0), RGB(0x2B2440), glow), body = mix(RGB(0x544A80), RGB(0x2A2340), glow);
+ color capc = mix(RGB(0xA89EDA), RGB(0x585080), glow);
+ for (int y = y0; y < y1; y++)
+ for (int x = x0; x < x1; x++) {
+ int dx = x - cx, dy = y - cy, d = dx * dx + dy * dy;
+ if (d > R * R) continue;
+ color c = d > out ? RGB(0x07050B) : d > in ? sur : d > cap ? mix(RGB(0x100C18), body, (d - cap) * grad >> 16) : capc;
+ if (iabs(d - fold) < 2 * r) c = mix(0, c, 12);
+ if ((dx + r / 9) * (dx + r / 9) + (dy + r / 9) * (dy + r / 9) <= hl * hl) c = mix(WHITE, c, 18);
+ buf[(y - by) * bw + x - bx] = c;
+ }
+}
+
+/* what the beat does to the stage, a frame apart so it doesn't all repaint at once */
+static int beat_n, beat_ph, beat_type, spk, bop, rbeat;
+static uint8_t lamp[4];
+static void pulses(void) {
+ spk = beat_ph >= 16 && beat_ph < 116 ? 2 : 0;
+ bop = beat_ph >= 33 && beat_ph < 133 ? 2 : 0;
+ rbeat = beat_ph < 90;
+ for (int l = 0; l < 4; l++) /* the beat's lamp flashes; in a chorus the others stay on */
+ lamp[l] = (uint8_t)((beat_n & 3) == l ? (beat_ph < 150 ? 2 : beat_ph < 300) : beat_type == CHORUS || beat_type == DROP);
+}
+
+/* LED bars on the floor: they jump on the beat and fall */
+static int vu(int i) {
+ int top = 3 + (int)(((uint32_t)(beat_n * 12 + i) * 2654435761u >> 28) % 5);
+ return clamp(top - beat_ph / 60, 1, 7);
+}
+
+/* lamps sit in the middle of 40-pixel columns: a flash repaints just those */
+static int lamp_x(int l) { return 20 + 40 * l + (l >> 1) * 160; }
+
+/* the stage: a back wall, a floor with LED bars, a speaker each side, four lamps */
+static void stage(bool lanes_on) {
+ int a = lanes_on ? clamp(80 - bx, 0, bw) : bw, b = lanes_on ? clamp(240 - bx, 0, bw) : bw;
+ for (int j = 0; j < bh; j++) {
+ color *p = buf + j * bw, c = bgrow[by + j];
+ fill(p, a, c);
+ fill(p + a, b - a, lanerow[by + j]);
+ fill(p + b, bw - b, c);
+ }
+ for (int s = 0; s < 2; s++) {
+ int cx = s ? 280 : 40;
+ if (bx >= cx + 32 || bx + bw <= cx - 32) continue;
+ rect(cx - 30, 102, 60, 111, RGB(0x2E2742), 32);
+ rect(cx - 28, 104, 56, 107, RGB(0x17131F), 32);
+ rect(cx - 30, 102, 60, 1, RGB(0x4A3F66), 32);
+ cone(cx, 132, 12 + spk / 2, spk * 12);
+ cone(cx, 180, 20 + spk, spk * 12);
+ for (int i = 0; i < 6; i++)
+ for (int k = 0, n = vu(s * 6 + i); k < n; k++)
+ rect(cx - 27 + i * 9, 234 - k * 3, 7, 2, k > 5 ? RGB(0xFF3B4A) : k > 3 ? RGB(0xFFD23A) : RGB(0x3BE37A), 32);
+ }
+ /* lamps on a bar: the one of this beat is lit, all of them in a chorus */
+ rect(0, 0, 80, 5, RGB(0x2A2A36), 32);
+ rect(240, 0, 80, 5, RGB(0x2A2A36), 32);
+ for (int l = 0; l < 4; l++) {
+ int lx = lamp_x(l), lv = lamp[l];
+ if (bx >= lx + 22 || bx + bw <= lx - 22) continue;
+ if (lv) /* the beam */
+ for (int y = maxi(by, 12); y < mini(by + bh, 100); y++) {
+ int hw = 2 + (y - 12) / 5;
+ rect(lx - hw, y, 2 * hw + 1, 1, lanec[l], (100 - y) * lv / 22);
+ }
+ disc(lx, 9, 7, 0, RGB(0x15141C), 32);
+ disc(lx, 10, 4, 0, lv ? mix(WHITE, lanec[l], lv == 2 ? 16 : 4) : mix(0, lanec[l], 22), 32);
+ }
+ if (lanes_on)
+ for (int k = 0; k < 5; k++) rect(80 + 40 * k - (k == 4), 0, 1, H, WHITE, k % 4 ? 2 : 4);
+}
+
+static void stage_watches(void) {
+ pulses();
+ for (int s = 0; s < 2; s++) {
+ int cx = s ? 280 : 40;
+ watch(16 + s * 2, cx - 26, 154, 52, 52, spk);
+ watch(17 + s * 2, cx - 17, 115, 34, 34, spk);
+ int key = 0;
+ for (int i = 0; i < 6; i++) key = key << 3 | vu(s * 6 + i);
+ watch(24 + s, cx - 27, 214, 54, 22, key);
+ }
+ for (int l = 0; l < 4; l++) watch(12 + l, lamp_x(l) - 20, 0, 40, 100, lamp[l]);
+}
+
+/* ------------------------------------------------------------------ playing */
+#define WIN 140 /* later than this, a note is missed */
+static const char *const judge_name[4] = {"Perfect", "Great", "Good", "Miss"};
+static const color judge_c[4][2] = {{RGB(0xFFF4A8), RGB(0xFFA800)}, {RGB(0xC6FFB0), RGB(0x2BD35A)}, {RGB(0x9FE8FF), RGB(0x2E7BFF)}, {RGB(0xFFB0B8), RGB(0xE0203A)}};
+
+static struct {
+ int32_t t0; /* millis at song time 0 */
+ int32_t t, pt, end;
+ int song, d, score, combo, maxc, health, judged, acc, cnt[4], held_mask;
+ uint32_t jt, ht[4], ct;
+ int jk, late, hk[4];
+ int pxms, ry, sgn, ahead; /* 1/256 pixel per ms; the targets' row; +1 when arrows go down */
+ bool failed, paused, confirm;
+ int menu;
+ uint32_t resume;
+} P;
+static int info_notes, info_len;
+
+static int pxms(void) { return (2 + S.speed) * 31 / 2; } /* 1/256 pixel per ms */
+static int note_y(int32_t dt) { return P.ry - P.sgn * (int)(dt * P.pxms >> 8); }
+static int lane_x(int l) { return 100 + 40 * l; }
+static bool gone(int y) { return P.sgn > 0 ? y > H + 24 : y < -24; }
+static bool not_yet(int y) { return P.sgn > 0 ? y < -24 : y > H + 24; }
+
+/* what a note covers now: its arrow and the end of its trail */
+static void note_mark(const note_t *n, int32_t t) {
+ int x = lane_x(n->lane);
+ if (n->st == N_WAIT || n->st == N_MISS) mark(x - 20, note_y(n->t - t) - 20, 40, 40);
+ if (n->len) mark(x - 8, note_y(n->t + n->len - t) - 8, 16, 16);
+}
+/* all of it, when it changes look */
+static void note_mark_all(const note_t *n) {
+ int x = lane_x(n->lane), y0 = n->st == N_HOLD ? P.ry : note_y(n->t - P.t), y1 = note_y(n->t + n->len - P.t);
+ mark(x - 20, mini(y0, y1) - 20, 40, iabs(y1 - y0) + 40);
+}
+
+static void start_song(void) {
+ int song = S.song, d = S.diff;
+ zero(&P, sizeof P);
+ P.song = song, P.d = d, P.health = 500;
+ gen_start(song, d);
+ gen_bar(); /* the first bar gives the beat of the count-in */
+ P.pxms = pxms();
+ P.sgn = S.up ? -1 : 1;
+ P.ry = S.up ? 40 : 200;
+ P.ahead = 250 * 256 / P.pxms;
+ int beat = 60000 / G.bpm, lead = maxi(4, (P.ahead + 300) / beat + 1) * beat;
+ P.t = P.pt = -lead;
+ P.t0 = (int32_t)now + lead;
+ for (int l = 0; l < 4; l++) P.ht[l] = now - 9999;
+ P.jt = P.ct = now - 9999;
+ nev = 0, rep_ok = 0;
+ screen = S_PLAY;
+ for (int i = 0; i < NW; i++) wt[i].key = -1;
+ mark_all();
+}
+
+static void judge_show(int k, int late) {
+ P.jk = k, P.late = late, P.jt = now;
+ if (k < 3) P.combo++, P.ct = now;
+ else P.combo = 0;
+ P.maxc = maxi(P.maxc, P.combo);
+}
+
+static void hit_note(note_t *n, int d) {
+ static const int16_t pts[3] = {350, 200, 100}, hp[3] = {20, 14, 5}, acc[3] = {100, 75, 40};
+ int ad = iabs(d), k = ad <= 45 ? 0 : ad <= 90 ? 1 : 2;
+ P.cnt[k]++, P.judged++, P.acc += acc[k], P.score += pts[k];
+ P.health = mini(P.health + hp[k], 1000);
+ judge_show(k, k ? (d > 0 ? 2 : 1) : 0);
+ P.ht[n->lane] = now, P.hk[n->lane] = k;
+ note_mark_all(n);
+ n->st = n->len ? N_HOLD : N_DONE;
+}
+
+static void miss(void) {
+ P.cnt[3]++, P.judged++;
+ P.health -= P.d ? 40 : 25; /* a dozen misses in a row from the start fail a song */
+ judge_show(3, 0);
+}
+
+static void press_lane(int l, int32_t tp) {
+ for (int i = nt; i != nh; i = (i + 1) & (NR - 1)) {
+ note_t *n = &notes[i];
+ if (n->lane != l || n->st != N_WAIT) continue;
+ int d = (int)(tp - n->t);
+ if (d < -WIN) return; /* too early for anything: a free tap */
+ if (d <= WIN) {
+ hit_note(n, d);
+ return;
+ }
+ }
+}
+
+static void end_hold(note_t *n, int32_t tr) {
+ note_mark_all(n);
+ if (tr >= n->t + n->len - 100) { /* held to the end */
+ n->st = N_DONE;
+ P.score += 150, P.health = mini(P.health + 10, 1000);
+ P.ht[n->lane] = now;
+ } else { /* let go: the rest of the trail goes gray */
+ n->len = (uint16_t)(n->t + n->len - tr), n->t = tr, n->st = N_DROP;
+ P.cnt[3]++, P.judged++, P.health -= 25;
+ judge_show(3, 0);
+ note_mark_all(n);
+ }
+}
+
+static void release_lane(int l, int32_t tr) {
+ for (int i = nt; i != nh; i = (i + 1) & (NR - 1))
+ if (notes[i].lane == l && notes[i].st == N_HOLD) end_hold(&notes[i], tr);
+}
+
+static void results(void);
+/* "Song - Difficulty" */
+static void song_line(char *s) { cat(cat(cat(s, songs[P.song].name), " - "), diff_name[P.d]); }
+
+static void play_update(void) {
+ P.pt = P.t;
+ P.t = (int32_t)(now - (uint32_t)P.t0);
+ int32_t tj = P.t - S.offset;
+ while (!G.done && (G.t16 >> 4) < P.t + P.ahead + 400 && ((nh - nt) & (NR - 1)) < NR - 40) gen_bar();
+ if (G.done && !P.end) P.end = G.t16 >> 4;
+ for (int i = 0; i < nev; i++) {
+ int32_t tp = (int32_t)(evq[i].t - (uint32_t)P.t0) - S.offset;
+ if (evq[i].down) press_lane(evq[i].lane, tp);
+ else release_lane(evq[i].lane, tp);
+ }
+ nev = 0;
+ bool left = false;
+ P.held_mask = 0;
+ for (int i = nt; i != nh; i = (i + 1) & (NR - 1)) {
+ note_t *n = &notes[i];
+ if (n->st == N_WAIT && tj - n->t > WIN) {
+ note_mark_all(n);
+ n->st = N_MISS;
+ miss();
+ } else if (n->st == N_HOLD) {
+ if (tj >= n->t + n->len) end_hold(n, tj);
+ else if (!(lanes >> n->lane & 1)) end_hold(n, tj);
+ else P.held_mask |= 1 << n->lane;
+ }
+ left |= n->st <= N_HOLD;
+ note_mark(n, P.pt);
+ note_mark(n, P.t);
+ }
+ while (nt != nh) { /* forget what is done and off the screen */
+ note_t *n = &notes[nt];
+ if (n->st == N_DONE || (n->st >= N_MISS && gone(note_y(n->t + n->len - P.t)))) nt = (nt + 1) & (NR - 1);
+ else break;
+ }
+ /* beat lines */
+ for (int i = maxi(0, nbars - 8); i < nbars; i++)
+ for (int k = i ? 0 : -8; k < 4; k++) {
+ int32_t tb = (bars[i & 7].t16 + k * bars[i & 7].beat16) >> 4;
+ mark(80, note_y(tb - P.t), 160, 1);
+ mark(80, note_y(tb - P.pt), 160, 1);
+ }
+ if (P.health <= 0) {
+ P.health = 0;
+ if (!S.nofail || !G.s) P.failed = true;
+ }
+ if (P.failed || (P.end && !left && tj > P.end + 500)) results();
+}
+
+/* the parts of the play screen that change in place */
+static void play_watches(void) {
+ for (int l = 0; l < 4; l++) {
+ int age = (int)(now - P.ht[l]), x = lane_x(l);
+ int key = age < 160 || (P.held_mask >> l & 1) ? (age < 50 ? 3 : 2) | 8 : lanes >> l & 1 ? 16 : 1 + rbeat;
+ watch(l, x - 20, P.ry - 20, 40, 40, key);
+ watch(4 + l, x - 30, P.ry - 30, 60, 60, age < 170 && !P.hk[l] ? age / 34 : -1);
+ }
+ int ja = (int)(now - P.jt), jy = S.up ? 118 : 96;
+ char s[12];
+ int w = tw(judge_name[P.jk], 3) + 8;
+ watch(8, 160 - w / 2, jy - 14, w, 42, ja < 500 ? P.jk | P.late << 2 | (ja < 50) << 4 : -1);
+ num(s, (uint32_t)P.combo);
+ w = maxi(tw(s, 4), 30) + 8;
+ watch(9, 160 - w / 2, jy + 24, w, 46, P.combo >= 4 ? P.combo << 4 | (now - P.ct < 80) : -1);
+ int hy = S.up ? 222 : 4, split = 62 + 196 * (1000 - P.health) / 1000;
+ watch(23, split - 25, hy - 8, 50, 27, split | bop << 10 | (P.health < 200) << 12 | (P.health > 800) << 13); /* and the bar */
+ watch(11, 60, S.up ? 206 : 26, 200, 11, P.score * 7 + P.cnt[3] * 131 + P.acc * 3 + P.judged);
+ int n, ty, ph = beat_at(P.t, &n, &ty);
+ watch(20, 60, 90, 200, 40, P.t < 0 && n >= -3 && ph < 300 ? n * 4 + (ph < 50) : -1);
+}
+
+static void draw_notes(void) {
+ for (int pass = 0; pass < 2; pass++)
+ for (int i = nt; i != nh; i = (i + 1) & (NR - 1)) {
+ const note_t *n = &notes[i];
+ int x = lane_x(n->lane), y = note_y(n->t - P.t);
+ if (not_yet(y)) break;
+ if (n->st == N_DONE || x + 20 <= bx || x - 20 >= bx + bw) continue;
+ if (!pass && n->len) { /* the trail */
+ int ya = n->st == N_HOLD ? P.ry : y, yb = note_y(n->t + n->len - P.t), y0 = mini(ya, yb), y1 = maxi(ya, yb);
+ color c = n->st >= N_MISS ? RGB(0x34344A) : lanec[n->lane]; /* gray once missed */
+ rect(x - 6, y0, 12, y1 - y0, INK, 32);
+ rect(x - 4, y0, 8, y1 - y0, c, 32);
+ rect(x - 2, y0, 2, y1 - y0, mix(WHITE, c, 8), 32);
+ disc(x, yb, 6, 0, INK, 32);
+ disc(x, yb, 4, 0, c, 32);
+ }
+ if (pass && (n->st == N_WAIT || n->st == N_MISS))
+ arrow(n->lane, x, y, 1, pal[n->st == N_MISS ? P_MISS : P_NOTE + n->lane], n->st == N_MISS ? 18 : 32);
+ }
+}
+
+
+static void icon(int cx, int cy, int r, color c, bool sad) {
+ disc(cx, cy, r + 2, 0, INK, 32);
+ disc(cx, cy, r, 0, c, 32);
+ rect(cx - r / 2 - 1, cy - r / 3, 3, 4, INK, 32);
+ rect(cx + r / 2 - 1, cy - r / 3, 3, 4, INK, 32);
+ int m = cy + r / 3 + 1, e = sad ? 2 : -2; /* the mouth's corners go up or down */
+ rect(cx - 3, m, 7, 2, INK, 32);
+ rect(cx - 5, m + e, 2, 2, INK, 32);
+ rect(cx + 4, m + e, 2, 2, INK, 32);
+}
+
+static void hud(void) {
+ char s[48], *o;
+ /* the health bar, with the two singers' faces where the colours meet */
+ int hy = S.up ? 222 : 4, split = 62 + 196 * (1000 - P.health) / 1000;
+ if (by < hy + 20 && by + bh > hy - 6) {
+ rect(60, hy, 200, 10, INK, 32);
+ rect(62, hy + 2, split - 62, 6, RGB(0xFF2A3D), 32);
+ rect(split, hy + 2, 258 - split, 6, RGB(0x57F23B), 32);
+ rect(62, hy + 2, 196, 2, WHITE, 6);
+ icon(split - 11, hy + 5, 9 + bop, RGB(0xB164E8), P.health > 800);
+ icon(split + 11, hy + 5, 9 + bop, RGB(0x39B8E6), P.health < 200);
+ }
+ int sy = S.up ? 207 : 27;
+ if (by < sy + 10 && by + bh > sy - 2) {
+ o = cat(s, "Score ");
+ o = num(o, (uint32_t)P.score);
+ o = cat(o, " Misses ");
+ o = num(o, (uint32_t)P.cnt[3]);
+ o = cat(o, " ");
+ if (P.judged) pct(o, P.acc * 100 / P.judged);
+ else cat(o, "--%");
+ small(s, 160, sy, WHITE);
+ }
+}
+
+static void scene_play(void) {
+ stage(true);
+ /* beat lines, brighter at the start of a bar */
+ for (int i = maxi(0, nbars - 8); i < nbars; i++)
+ for (int k = i ? 0 : -8; k < 4; k++) {
+ int y = note_y(((bars[i & 7].t16 + k * bars[i & 7].beat16) >> 4) - P.t);
+ rect(81, y, 158, 1, WHITE, k ? 3 : 6);
+ }
+ /* the targets */
+ for (int l = 0; l < 4; l++) {
+ int age = (int)(now - P.ht[l]), x = lane_x(l);
+ if (age < 160 || (P.held_mask >> l & 1)) arrow(l, x, P.ry, age < 50 ? 3 : 2, pal[P_CONF + l], 32);
+ else if (lanes >> l & 1) arrow(l, x, P.ry, 0, pal[P_PRESS + l], 32);
+ else arrow(l, x, P.ry, 1 + rbeat, pal[rbeat ? P_BEAT : P_STRUM], 32);
+ }
+ /* the judgment and the combo */
+ int ja = (int)(now - P.jt), jy = S.up ? 118 : 96;
+ if (ja < 500) {
+ int y = jy + (ja < 50) * 3;
+ ctext(judge_name[P.jk], 160, y, 3, 2, judge_c[P.jk][0], judge_c[P.jk][1]);
+ if (P.late) small(P.late == 2 ? "Late" : "Early", 160, y - 11, P.late == 2 ? RGB(0xFFB070) : RGB(0x80C8FF));
+ }
+ if (P.combo >= 4) {
+ char s[12];
+ num(s, (uint32_t)P.combo);
+ int pop = now - P.ct < 80;
+ ctext(s, 160, jy + 30 - pop * 2, 4, 2, WHITE, RGB(0xC8C8DC));
+ small("Combo", 160, jy + 60, RGB(0xD8D8E8));
+ }
+ draw_notes();
+ /* a splash on a perfect hit */
+ for (int l = 0; l < 4; l++) {
+ int age = (int)(now - P.ht[l]);
+ if (age >= 170 || P.hk[l]) continue;
+ age = age / 34 * 34; /* in five steps */
+ int r = 16 + age / 14, a = 30 - age * 30 / 170, x = lane_x(l);
+ disc(x, P.ry, r, 3 - age / 60, mix(WHITE, lanec[l], 12), a);
+ for (int k = 0; k < 4; k++) disc(x + (k & 1 ? r : -r) * 3 / 4, P.ry + (k & 2 ? r : -r) * 3 / 4, 2, 0, WHITE, a);
+ }
+ hud();
+ /* ready, set, go! on the beats before the song */
+ int n, ty, ph = beat_at(P.t, &n, &ty);
+ if (P.t < 0 && n >= -3 && ph < 300) {
+ static const char *const cd[3] = {"Ready?", "Set", "Go!"};
+ ctext(cd[n + 3], 160, 96 + (ph < 50) * 3, 4, 2, WHITE, RGB(0xFFE070));
+ }
+ if (P.resume) {
+ char s[2] = {(char)('1' + (P.resume - now) / 400), 0};
+ rect(0, 0, W, H, 0, 10);
+ rect(122, 78, 76, 72, INK, 26);
+ ctext(s, 160, 90, 7, 3, WHITE, RGB(0xFFE070));
+ }
+ if (P.paused) {
+ static const char *const items[3] = {"Resume", "Restart", "Quit game"};
+ rect(0, 0, W, H, 0, 20);
+ rect(70, 52, 180, 136, INK, 28);
+ rect(70, 52, 180, 2, lanec[P.song & 3], 32);
+ ctext(P.confirm ? "Quit game?" : "Paused", 160, 64, 3, 2, WHITE, RGB(0xC8C8DC));
+ char s[32];
+ song_line(s);
+ small(s, 160, 92, RGB(0x9A94B8));
+ for (int i = 0; i < (P.confirm ? 2 : 3); i++) {
+ item(P.confirm ? (i ? "No" : "Yes") : items[i], 160, 112 + i * 24, i == P.menu);
+ }
+ }
+}
+
+static void play_frame(void) {
+ if (P.paused) {
+ int n = P.confirm ? 2 : 3, m = clamp(P.menu + ud(), 0, n - 1);
+ if (m != P.menu) P.menu = m, mark_all();
+ if (pressed(eadk_key_back)) {
+ if (P.confirm) P.confirm = false, P.menu = 2;
+ else P.paused = false, P.resume = now + 1199;
+ mark_all();
+ } else if (ok_key()) {
+ if (P.confirm) {
+ if (!P.menu) quit = true; /* back to NumPlay (or the calculator) */
+ else P.confirm = false, P.menu = 2;
+ } else if (P.menu == 0) P.paused = false, P.resume = now + 1199;
+ else if (P.menu == 1) start_song();
+ else P.confirm = true, P.menu = 1;
+ mark_all();
+ }
+ nev = 0;
+ return;
+ }
+ if (P.resume) {
+ nev = 0;
+ if ((int32_t)(now - P.resume) >= 0) P.resume = 0, P.t0 = (int32_t)now - P.t, P.pt = P.t, mark_all();
+ else watch(21, 100, 80, 120, 70, (int)(P.resume - now) / 400);
+ return;
+ }
+ if (pressed(eadk_key_back)) {
+ P.paused = true, P.menu = 0, P.confirm = false, rep_ok = 0;
+ mark_all();
+ return;
+ }
+ play_update();
+ if (screen != S_PLAY) return;
+ beat_ph = beat_at(P.t, &beat_n, &beat_type);
+ pulses();
+ play_watches();
+ stage_watches();
+}
+
+/* ------------------------------------------------------------------ results */
+static int grade, grade_bars, new_best;
+static void results(void) {
+ int acc = P.judged ? P.acc * 100 / P.judged : 0, ty;
+ beat_at(P.t, &grade_bars, &ty);
+ grade_bars /= 4;
+ bool fc = !P.cnt[3] && !P.failed;
+ static const int16_t need[5] = {7000, 8000, 9000, 9500, 9900}; /* accuracy for C, B, A, S, S+ */
+ grade = 1;
+ while (grade < 6 && acc >= need[grade - 1] && (grade < 5 || fc)) grade++;
+ if (P.failed && G.s) grade = 0;
+ new_best = 0;
+ if (!P.failed || !G.s) {
+ uint8_t *g = &S.grade[P.song][P.d], ng = (uint8_t)(maxi(grade, *g & 7) | (*g & 8) | (fc ? 8 : 0));
+ if ((uint32_t)P.score > S.best[P.song][P.d]) S.best[P.song][P.d] = (uint32_t)P.score, new_best = 1;
+ if (ng != *g || new_best) *g = ng, save_due = true;
+ }
+ if (save_due) save();
+ go(S_RESULTS, 0);
+}
+
+static const char *const grade_name[7] = {"F", "D", "C", "B", "A", "S", "S+"};
+static const color grade_c[7] = {RGB(0xFF4050), RGB(0xB0A0C0), RGB(0xC080FF), RGB(0x40B8FF), RGB(0x40E070), RGB(0xFFD040), RGB(0xFFF0A0)};
+
+static void scene_results(void) {
+ char s[40], *o;
+ stage(false);
+ rect(0, 0, W, H, 0, 20);
+ song_line(s);
+ ctext(s, 160, 8, 2, 2, WHITE, RGB(0xC8C8DC));
+ /* the grade on a badge */
+ color gc = grade_c[grade];
+ disc(80, 94, 52, 0, INK, 24);
+ disc(80, 94, 52, 4, gc, 32);
+ if (P.failed && G.s) ctext("Failed", 80, 87, 2, 2, RGB(0xFFB0B8), RGB(0xE0203A));
+ else ctext(grade_name[grade], 80, 66, 8, 3, gc, mix(0, gc, 9));
+ if (!P.cnt[3] && !P.failed) small("Full combo!", 80, 156, RGB(0x9FE8FF));
+ if (!G.s) {
+ o = cat(s, "Bars: ");
+ num(o, (uint32_t)grade_bars);
+ small(s, 80, 172, WHITE);
+ }
+ static const char *const lbl[6] = {"Perfect", "Great", "Good", "Miss", "Max combo", "Accuracy"};
+ rect(160, 34, 150, 100, INK, 18);
+ for (int i = 0; i < 6; i++) {
+ int y = 40 + i * 16;
+ text(lbl[i], 168, y, 1, 1, i < 4 ? judge_c[i][0] : WHITE, i < 4 ? judge_c[i][1] : 0);
+ if (i == 5) pct(s, P.judged ? P.acc * 100 / P.judged : 0);
+ else num(s, (uint32_t)(i < 4 ? P.cnt[i] : P.maxc));
+ text(s, 302 - tw(s, 1), y, 1, 1, WHITE, 0);
+ }
+ small("Score", 235, 142, RGB(0xC8C8DC));
+ num(s, (uint32_t)P.score);
+ ctext(s, 235, 154, 3, 2, WHITE, RGB(0xFFE070));
+ if (new_best && now % 600 < 400) small("New best!", 235, 182, RGB(0xFFE070));
+ static const char *const items[2] = {"Retry", "Songs"};
+ for (int i = 0; i < 2; i++) item(items[i], 100 + i * 120, 212, sel == i);
+}
+
+/* ------------------------------------------------------------------ menus */
+static int lpos; /* the song list's scroll, 1/16 of an item */
+
+static void song_info(void) {
+ if (S.song == NSONG - 1) return;
+ gen_start(S.song, S.diff);
+ G.counting = true;
+ while (!G.done) gen_bar();
+ info_notes = G.count, info_len = (G.t16 >> 4) / 1000;
+}
+
+static void scene_title(void) {
+ stage(false);
+ /* the name hops, letter after letter, on every beat */
+ static const char *const words[2] = {"Num", "Dance"};
+ for (int w = 0, i = 0; w < 2; w++) {
+ const char *s = words[w];
+ int x = 160 - tw(s, 6) / 2, y = 14 + w * 50;
+ for (int k = 0; s[k]; k++, i++) {
+ int p = beat_ph - i * 30, hop = p >= 0 && p < 160 ? (p < 60 ? p / 8 : (160 - p) * 7 / 100) : 0;
+ char c[2] = {s[k], 0};
+ color lc = lanec[i & 3];
+ text(c, x + k * 36, y - hop, 6, 3, mix(WHITE, lc, 10), mix(0, lc, 6));
+ }
+ }
+ for (int l = 0; l < 4; l++) {
+ bool on = (menu_beat & 3) == l && beat_ph < 250;
+ arrow(l, 100 + 40 * l, 134, on ? 3 : 1, pal[on ? P_CONF + l : P_STRUM], 32);
+ }
+ static const char *const items[3] = {"Play", "Options", "How to play"};
+ for (int i = 0; i < 3; i++) item(items[i], 160, 166 + i * 24, sel == i);
+ if (tq) {
+ rect(0, 0, W, H, 0, 12);
+ rect(60, 140, 200, 94, INK, 32); /* over the menu */
+ rect(60, 140, 200, 2, lanec[0], 32);
+ ctext("Quit game?", 160, 150, 3, 2, WHITE, RGB(0xC8C8DC));
+ for (int i = 0; i < 2; i++) item(i ? "No" : "Yes", 160, 184 + i * 24, tsel == i);
+ }
+}
+
+static void scene_songs(void) {
+ int song = S.song;
+ color c = songs[song].c;
+ for (int j = 0; j < bh; j++) {
+ int y = by + j;
+ color *p = buf + j * bw;
+ for (int i = 0; i < bw; i++) {
+ int x = bx + i;
+ p[i] = mix(c, RGB(0x0C0614), (((x + y * 2) >> 4) & 1 ? 11 : 9) - y * 7 / H);
+ }
+ }
+ for (int i = 0; i < NSONG; i++) {
+ int off = i * 16 - lpos, y = 128 + off * 34 / 16, x = 20 + iabs(off) / 2;
+ if (y < 56 || y > H) continue;
+ bool on = i == song;
+ const char *name = songs[i].name;
+ text(name, x, y, 3, 2, on ? WHITE : mix(c, RGB(0x9890B0), 6), on ? RGB(0xFFE070) : mix(c, RGB(0x686080), 6));
+ int g = S.grade[i][S.diff] & 7;
+ if (g && i < NSONG - 1) text(grade_name[g], x + tw(name, 3) + 10, y + 4, 2, 1, grade_c[g], 0);
+ }
+ /* the score box */
+ char s[40], *o;
+ rect(176, 0, 144, 60, 0, 18);
+ o = cat(s, "< ");
+ o = cat(o, diff_name[S.diff]);
+ cat(o, " >");
+ ctext(s, 248, 8, 2, 1, diff_c[S.diff], mix(0, diff_c[S.diff], 10));
+ o = cat(s, "Best ");
+ o = num(o, S.best[song][S.diff]);
+ if (S.grade[song][S.diff] & 8) cat(o, " FC");
+ small(s, 248, 28, WHITE);
+ if (song < NSONG - 1) {
+ o = num(s, songs[song].bpm);
+ o = cat(o, " BPM ");
+ o = num(o, (uint32_t)info_len / 60);
+ *o++ = ':';
+ *o++ = (char)('0' + info_len % 60 / 10);
+ *o++ = (char)('0' + info_len % 10);
+ o = cat(o, " ");
+ o = num(o, (uint32_t)info_notes);
+ cat(o, " notes");
+ } else cat(s, "Faster and faster");
+ small(s, 248, 42, RGB(0xC8C0E0));
+ rect(0, 226, W, 14, 0, 18);
+ small("OK: play Left/Right: difficulty Back: menu", 160, 229, RGB(0xC8C0E0));
+}
+
+static const char *const opt_name[5] = {"Scroll speed", "Direction", "Offset", "Calibrate offset", "No-fail"};
+static void scene_options(void) {
+ stage(false);
+ rect(0, 0, W, H, 0, 16);
+ heading("Options", 12);
+ for (int i = 0; i < 5; i++) {
+ char s[24] = "", *o = s;
+ bool on = sel == i;
+ int y = 58 + i * 28;
+ color c = on ? WHITE : RGB(0x9A94B8);
+ if (on) rect(12, y - 6, 296, 26, WHITE, 5);
+ text(opt_name[i], 20, y, 2, on, c, 0);
+ if (on && i != 3) o = cat(o, "< ");
+ if (i == 0) o = num(o, 1 + S.speed / 2), *o++ = '.', *o++ = S.speed & 1 ? '5' : '0', o = cat(o, "x");
+ else if (i == 1) o = cat(o, S.up ? "Up" : "Down");
+ else if (i == 2) o = signed_ms(o, S.offset);
+ else if (i == 4) o = cat(o, S.nofail ? "On" : "Off");
+ if (on && i != 3) cat(o, " >");
+ text(s, 300 - tw(s, 2), y, 2, on, on ? RGB(0xFFE070) : c, 0);
+ }
+ small("Offset: + if you tend to press late", 160, 206, RGB(0x9A94B8));
+ small("Up/Down: choose Left/Right: change Back: done", 160, 222, RGB(0x9A94B8));
+}
+
+static void scene_help(void) {
+ stage(false);
+ rect(0, 0, W, H, 0, 18);
+ heading("How to play", 10);
+ static const char *const keys[4] = {"Left 4 1", "Down 5 2", "Up 8 3", "Right 6 +"};
+ for (int l = 0; l < 4; l++) {
+ arrow(l, 70 + 60 * l, 62, 1, pal[P_NOTE + l], 32);
+ small(keys[l], 70 + 60 * l, 86, WHITE);
+ }
+ static const char *const lines[6] = {"Press an arrow's key just as it", "reaches the gray target. Keep holding",
+ "the key along a trail. Misses drain", "the health bar; empty, the song fails.",
+ "Back: pause Home: quit", "The beat shows on the stage lights."};
+ for (int i = 0; i < 6; i++) small(lines[i], 160, 110 + i * 14 + (i > 3) * 6, i > 3 ? RGB(0xB8B0D0) : WHITE);
+ static const uint16_t jx[4] = {49, 143, 219, 289};
+ for (int k = 0; k < 4; k++) ctext(judge_name[k], jx[k], 212, 2, 1, judge_c[k][0], judge_c[k][1]);
+}
+
+/* calibration: an arrow every half second, press as it lands */
+static int cal_n, cal_sum, cal_last;
+static uint32_t cal_t0;
+static void scene_calib(void) {
+ char s[16];
+ stage(false);
+ rect(0, 0, W, H, 0, 20);
+ rect(120, 0, 80, H, 0, 14);
+ int t = (int)(now - cal_t0), ry = S.up ? 40 : 200, sgn = S.up ? -1 : 1, px = pxms(), beat = t % 500 < 90;
+ arrow(2, 160, ry, 1 + beat, pal[beat ? P_BEAT : P_STRUM], 32);
+ for (int k = t / 500 - 1; k <= t / 500 + 8; k++) {
+ int y = ry - sgn * ((k * 500 - t) * px >> 8);
+ if (k >= 2) arrow(2, 160, y, 1, pal[P_NOTE + 2], 32);
+ }
+ ctext("Calibrate", 60, 10, 2, 1, WHITE, RGB(0xFFE070));
+ if (cal_n) {
+ small("Last tap", 60, 96, WHITE);
+ signed_ms(s, cal_last);
+ ctext(s, 60, 110, 2, 1, cal_last < 0 ? RGB(0x80C8FF) : RGB(0xFFB070), 0);
+ }
+ small(cal_n < 8 ? "Taps" : "Offset", 260, 96, WHITE);
+ if (cal_n < 8) s[0] = (char)('0' + cal_n), cat(s + 1, " of 8");
+ else signed_ms(s, cal_sum / 8);
+ ctext(s, 260, 110, 2, 1, RGB(0xFFE070), 0);
+ small(cal_n < 8 ? "Press any arrow as each one lands" : "OK: keep it Back: cancel", 160, 226, WHITE);
+}
+
+static void scene(void) {
+ switch (screen) {
+ case S_TITLE: scene_title(); break;
+ case S_SONGS: scene_songs(); break;
+ case S_OPTIONS: scene_options(); break;
+ case S_HELP: scene_help(); break;
+ case S_CALIB: scene_calib(); break;
+ case S_PLAY: scene_play(); break;
+ default: scene_results();
+ }
+}
+
+static void menu_frame(void) {
+ int u = ud(), v = lr();
+ bool ok = ok_key(), back = pressed(eadk_key_back);
+ switch (screen) {
+ case S_TITLE:
+ if (tq) {
+ if (u) tsel = clamp(tsel + u, 0, 1), mark_all();
+ if (back || (ok && tsel)) tq = false, mark_all();
+ else if (ok) quit = true;
+ break;
+ }
+ if (back) {
+ tq = true, tsel = 1, mark_all();
+ break;
+ }
+ if (u) sel = clamp(sel + u, 0, 2), mark_all();
+ if (ok) {
+ if (sel == 0) song_info(), go(S_SONGS, 0), lpos = S.song * 16;
+ else go(sel == 1 ? S_OPTIONS : S_HELP, 0);
+ }
+ break;
+ case S_SONGS:
+ if (u) S.song = (uint8_t)((S.song + NSONG + u) % NSONG), song_info(), save_due = true;
+ if (v) S.diff = (uint8_t)((S.diff + 4 + v) & 3), song_info(), save_due = true, mark_all();
+ if (lpos != S.song * 16) {
+ int d = S.song * 16 - lpos;
+ lpos += d / 3 ? d / 3 : d > 0 ? 1 : -1;
+ mark_all();
+ }
+ if (ok) start_song();
+ else if (back) go(S_TITLE, 0);
+ break;
+ case S_OPTIONS:
+ if (u) sel = clamp(sel + u, 0, 4), mark_all();
+ if (v) {
+ if (sel == 0) S.speed = (uint8_t)clamp(S.speed + v, 0, 6);
+ if (sel == 1) S.up ^= 1;
+ if (sel == 2) S.offset = (int8_t)clamp(S.offset + v * 5, -120, 120);
+ if (sel == 4) S.nofail ^= 1;
+ save_due = true, mark_all();
+ }
+ if (ok && sel == 3) cal_n = cal_sum = 0, cal_t0 = now, nev = 0, go(S_CALIB, 0);
+ else if (back) {
+ if (save_due) save();
+ go(S_TITLE, 1);
+ }
+ break;
+ case S_HELP:
+ if (ok || back) go(S_TITLE, 2);
+ break;
+ case S_CALIB:
+ for (int i = 0; i < nev; i++)
+ if (evq[i].down && cal_n < 8) {
+ int t = (int)(evq[i].t - cal_t0), e = t - (t + 250) / 500 * 500;
+ if ((t + 250) / 500 >= 2) cal_last = e, cal_sum += e, cal_n++;
+ }
+ nev = 0;
+ if (ok && cal_n >= 8) S.offset = (int8_t)clamp(cal_sum / 8, -120, 120), save_due = true, go(S_OPTIONS, 2);
+ else if (back) go(S_OPTIONS, 3);
+ mark_all(); /* it all moves */
+ break;
+ case S_RESULTS:
+ if (v) sel = clamp(sel + v, 0, 1), mark_all();
+ if (ok && !sel) start_song();
+ else if (ok || back) song_info(), go(S_SONGS, 0), lpos = S.song * 16;
+ else if (new_best) watch(22, 190, 180, 90, 12, now % 600 < 400);
+ break;
+ }
+ nev = 0;
+ if (screen == S_TITLE) { /* the title's letters and targets move to a 120 BPM beat */
+ beat_ph = (int)(now % 500), menu_beat = (int)(now / 500), beat_n = menu_beat, beat_type = 0;
+ watch(0, 40, 0, 240, 120, beat_ph < 400 ? beat_ph / 16 : 99);
+ for (int l = 0; l < 4; l++) watch(1 + l, 80 + 40 * l, 114, 40, 40, (menu_beat & 3) == l && beat_ph < 250);
+ stage_watches();
+ }
+}
+
+int main(void) {
+ np_app_begin();
+ make_arrows();
+ make_palettes();
+ make_stage();
+ load();
+ now = (uint32_t)eadk_timing_millis();
+ held = eadk_keyboard_scan();
+ poll();
+ nev = 0, hit = 0;
+ for (int i = 0; i < NW; i++) wt[i].key = -1;
+ go(S_TITLE, 0);
+ while (!quit) {
+ now = (uint32_t)eadk_timing_millis();
+ input();
+ if (quit) break;
+ if (screen == S_PLAY) play_frame();
+ else menu_frame();
+ flush();
+ /* keep reading the keys until it is nearly time for the next frame */
+ do {
+ eadk_timing_msleep(1);
+ poll();
+ } while ((uint32_t)eadk_timing_millis() - now < 12);
+ eadk_display_wait_for_vblank();
+ while ((uint32_t)eadk_timing_millis() - now < 16) eadk_timing_msleep(1), poll(); /* where vblank does not wait */
+ }
+ if (save_due) save();
+ return np_app_end();
+}
diff --git a/games/pacman/.gitignore b/games/pacman/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/pacman/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/pacman/Makefile b/games/pacman/Makefile
new file mode 100644
index 00000000..103e3598
--- /dev/null
+++ b/games/pacman/Makefile
@@ -0,0 +1,51 @@
+# Pac-Man — the 1980 arcade game.
+# make build output/pacman.nwa
+# make check link the app like the calculator does (output/pacman.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/pacman.nwa
+
+check: $(BUILD_DIR)/pacman.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/pacman.bin
+ @echo "BIN $(BUILD_DIR)/pacman.bin: $$(wc -c < $(BUILD_DIR)/pacman.bin) bytes"
+
+$(BUILD_DIR)/pacman.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $(SRC) -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_pacman_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_pacman_main -o $@
diff --git a/games/pacman/README.md b/games/pacman/README.md
new file mode 100644
index 00000000..dce6f0a1
--- /dev/null
+++ b/games/pacman/README.md
@@ -0,0 +1,36 @@
+# Pac-Man
+
+The 1980 arcade game for the NumWorks calculator: the maze, the four ghosts, the fruit, and the rules of the original.
+
+<img src="docs/shot.png" width="320" alt="Pac-Man in the maze, chased by Blinky and Pinky">
+
+- **The arcade's maze**, all 28 x 31 tiles with its blue double walls, the pink ghost house door, dots and flashing energizers. The scores sit at the sides: 1UP, HIGH SCORE, your spare lives and the fruit of the last levels.
+- **Four ghosts, four personalities**, as in the arcade: Blinky goes straight for you, Pinky aims four tiles ahead, Inky works from Blinky's position, and Clyde gets shy up close. They scatter to their corners and chase in waves, turn blue and flee after an energizer, and race home as eyes once eaten (200, 400, 800, 1600).
+- **The original's rules**: the speed and fright tables of every level, Blinky's "Cruise Elroy" speed-up near the end of a level, the ghost house counters, the slow tunnel, cornering, fruit from the cherry to the key, an extra life, the death animation, the flashing maze and the first intermission.
+- **Options** from the All the Apps version: game speed, lives (1, 2, 3 or 5), how long a turn is remembered (input buffer), the level to start from, the score for the bonus life, and No collisions (no high score then).
+- **Quit any time and continue later**: the level, score, lives and every dot left are kept, with the high score and the options.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows, or 8 4 6 2 | Steer. Press a turn early and Pac-Man takes it at the next gap |
+| Back | Pause: Resume, Restart, Quit game |
+| OK | Choose in the menus, skip the intermission |
+| Home | Leave (the game is saved) |
+
+## Credits
+
+Pac-Man was created by Toru Iwatani at Namco in 1980; this remake follows the arcade's look and rules.
+
+It is rewritten in C for NumPlay from Tatone26's version in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/pacman) (All the Apps), which is released into the public domain ([UNLICENSE](UNLICENSE)). What changed:
+
+- The full arcade maze (the ghost house was one row shorter to fit the screen) drawn with 7-pixel tiles, and the arcade's colours, sprites, screens and HUD instead of the original's.
+- The arcade's ghost behaviour, wave timers, house counters, Cruise Elroy, dot pauses and fruit timings.
+- Options added: 5 lives, start levels up to 21, the bonus life score. The saved game now keeps the dots left.
+- The first intermission, the attract screen with the ghosts' names, and 60 frames a second that redraw only what moves.
+- About 14 KB, with every picture drawn by code or packed at 2 bits a pixel.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `PacMan.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/pacman/UNLICENSE b/games/pacman/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/pacman/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/pacman/docs/shot.png b/games/pacman/docs/shot.png
new file mode 100644
index 00000000..9392979a
Binary files /dev/null and b/games/pacman/docs/shot.png differ
diff --git a/games/pacman/src/icon.png b/games/pacman/src/icon.png
new file mode 100644
index 00000000..d31a1fb2
Binary files /dev/null and b/games/pacman/src/icon.png differ
diff --git a/games/pacman/src/main.c b/games/pacman/src/main.c
new file mode 100644
index 00000000..f2887d46
--- /dev/null
+++ b/games/pacman/src/main.c
@@ -0,0 +1,1254 @@
+/* Pac-Man for the NumWorks calculator: Namco's 1980 arcade game.
+ *
+ * The rules follow the arcade: four ghosts that hunt each in their own way,
+ * scatter and chase waves, the speed and fright tables of every level,
+ * Cruise Elroy, the ghost house counters, cornering, the fruit and the extra
+ * life. The options and the saved game come from Tatone26's version in All
+ * the Apps.
+ *
+ * The 28x31 maze uses 7-pixel tiles so it fits the 240-pixel screen, with the
+ * scores at the sides. Its walls are traced once from a bit map of the maze
+ * (a distance field gives the arcade's rounded double lines); after that only
+ * the few tiles under the sprites are redrawn, 60 times a second. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Pac-Man";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define KEY(k) (1ull << (k))
+
+/* the arcade's colours */
+#define BLACK 0
+#define WALL RGB(0x2121DE)
+#define PEACH RGB(0xFFB8AE)
+#define YELLOW RGB(0xFFFF00)
+#define WHITE RGB(0xDEDEFF)
+#define BLUE RGB(0x2121FF)
+#define RED RGB(0xFF0000)
+#define PINK RGB(0xFFB8FF)
+#define CYAN RGB(0x00FFFF)
+#define ORANGE RGB(0xFFB852)
+#define GREY RGB(0x7C7C9C)
+
+/* the maze: 28x31 tiles of 7 pixels, in the middle of the screen */
+#define MX 62
+#define MY 11
+#define MW 196
+#define MH 217
+
+enum { UP, LEFT, DOWN, RIGHT, NONE }; /* ghosts break ties in this order */
+static const int8_t DX[5] = {0, -1, 0, 1, 0}, DY[5] = {-1, 0, 1, 0, 0};
+
+static uint32_t seed = 0x9E3779B9;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+
+/* ------------------------------------------------------------------ drawing */
+/* Everything is composed in this buffer, a rectangle of the screen at a time,
+ then pushed: each pixel is written once, so nothing flickers. */
+#define BUFPX (320 * 16)
+static color buf[BUFPX];
+static int bx, by, bw, cx0, cy0, cx1, cy1; /* the buffer's place, and the clip */
+static void (*scene)(void); /* draws everything in the clip */
+
+static void fill(int x, int y, int w, int h, color c) {
+ int x0 = x > cx0 ? x : cx0, x1 = x + w < cx1 ? x + w : cx1;
+ int y0 = y > cy0 ? y : cy0, y1 = y + h < cy1 ? y + h : cy1;
+ for (; y0 < y1; y0++)
+ for (color *p = buf + (y0 - by) * bw + x0 - bx, *e = p + (x1 - x0); p < e; p++) *p = c;
+}
+static void pset(int x, int y, color c) {
+ if (x >= cx0 && x < cx1 && y >= cy0 && y < cy1) buf[(y - by) * bw + x - bx] = c;
+}
+static bool hits(int x, int y, int w, int h) { return x < cx1 && y < cy1 && x + w > cx0 && y + h > cy0; }
+
+/* redraws a rectangle of the screen, in bands that fit the buffer */
+static void refresh(int x, int y, int w, int h) {
+ if (x < 0) w += x, x = 0;
+ if (y < 0) h += y, y = 0;
+ if (x + w > 320) w = 320 - x;
+ if (y + h > 240) h = 240 - y;
+ if (w <= 0 || h <= 0) return;
+ for (int band = BUFPX / w, j = y; j < y + h; j += band) {
+ int n = y + h - j < band ? y + h - j : band;
+ bx = cx0 = x, by = cy0 = j, bw = w, cx1 = x + w, cy1 = j + n;
+ scene();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)j, (uint16_t)w, (uint16_t)n}, buf);
+ }
+}
+/* a thin frame with its corners cut, like the maze's walls */
+static void frame(int x, int y, int w, int h, color c) {
+ fill(x + 1, y, w - 2, 1, c);
+ fill(x + 1, y + h - 1, w - 2, 1, c);
+ fill(x, y + 1, 1, h - 2, c);
+ fill(x + w - 1, y + 1, 1, h - 2, c);
+}
+
+/* ------------------------------------------------------------------ text */
+/* ASCII 32..90, columns of 7 bits, top bit first. Each column is drawn two
+ pixels wide, which gives the arcade's font: thick uprights, thin bars, one
+ character per 7-pixel tile. */
+static const uint8_t font[59][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x07,0x00,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14},{0x24,0x2A,0x7F,0x2A,0x12},
+ {0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00},{0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},
+ {0x14,0x08,0x3E,0x08,0x14},{0x08,0x08,0x3E,0x08,0x08},{0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},
+ {0x20,0x10,0x08,0x04,0x02},{0x3E,0x41,0x41,0x41,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},
+ {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},{0x36,0x49,0x49,0x49,0x36},
+ {0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00},{0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},
+ {0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},{0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},
+ {0x3E,0x41,0x41,0x41,0x22},{0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x49,0x49,0x7A},
+ {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41},{0x7F,0x40,0x40,0x40,0x40},
+ {0x7F,0x02,0x04,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},{0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},
+ {0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},{0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},
+ {0x7F,0x20,0x10,0x20,0x7F},{0x63,0x14,0x08,0x14,0x63},{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},
+};
+
+static void glyph(int ch, int x, int y, int k, color c) {
+ if (!hits(x, y, 6 * k, 7 * k)) return;
+ unsigned g = (unsigned)ch - 32u;
+ if (g > 58) g = '?' - 32;
+ for (int i = 0; i < 5; i++)
+ for (int j = 0, b = font[g][i]; b; j++, b >>= 1)
+ if (b & 1) fill(x + i * k, y + j * k, 2 * k, k, c);
+}
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static int tw(const char *s, int k) { return slen(s) * 7 * k - k; }
+static void text(const char *s, int x, int y, int k, color c) {
+ for (; *s; s++, x += 7 * k) glyph(*s, x, y, k, c);
+}
+static void ctext(const char *s, int cx, int y, int k, color c) { text(s, cx - tw(s, k) / 2, y, k, c); }
+static void rtext(const char *s, int rx, int y, int k, color c) { text(s, rx - tw(s, k), y, k, c); }
+
+static char nb[12];
+static char *num(uint32_t v) {
+ char *o = nb + 11;
+ do *--o = (char)('0' + v % 10); while (v /= 10);
+ return o;
+}
+
+/* the small digits of the points shown in the maze, 3x5 */
+static const uint16_t mini_font[10] = {0x7B6F, 0x2C97, 0x73E7, 0x73CF, 0x5BC9, 0x79CF, 0x79EF, 0x7249, 0x7BEF, 0x7BCF};
+static void mini(uint32_t v, int cx, int y, color c) {
+ char *s = num(v);
+ for (int x = cx - (slen(s) * 4 - 1) / 2; *s; s++, x += 4)
+ for (int b = 0; b < 15; b++)
+ if (mini_font[*s - '0'] >> b & 1) pset(x + 2 - b % 3, y + 4 - b / 3, c);
+}
+
+/* ------------------------------------------------------------------ sprites */
+/* Pac-Man centred on (x, y), r pixels round (6 in the maze), facing d, the
+ mouth open from 0 (closed) to 4 (wide); with die > 0 it is his death: a
+ mouth opening from the top until nothing is left (die up to 32) */
+static void pac_r(int x, int y, int d, int open, int die, int r) {
+ if (!hits(x - r, y - r, 2 * r + 1, 2 * r + 1)) return;
+ for (int j = -r; j <= r; j++)
+ for (int i = -r; i <= r; i++) {
+ if (i * i + j * j > r * r + r) continue;
+ if (die) {
+ int p = i < 0 ? -i : i, s = p + (j < 0 ? -j : j);
+ if ((j <= 0 ? p : s + j) * 16 < die * s) continue;
+ } else {
+ int a = i * DX[d] + j * DY[d], p = i * DY[d] - j * DX[d];
+ if (a > 0 && 4 * (p < 0 ? -p : p) < open * a) continue;
+ }
+ pset(x + i, y + j, YELLOW);
+ }
+}
+static void pac_draw(int x, int y, int d, int open, int die) { pac_r(x, y, d, open, die, 6); }
+
+/* the ghost, 13x13: the body's rows (bit i is column i), then two frames of the skirt */
+static const uint16_t ghost_body[11] = {0x01F0, 0x07FC, 0x0FFE, 0x0FFE, 0x0FFE, 0x1FFF,
+ 0x1FFF, 0x1FFF, 0x1FFF, 0x1FFF, 0x1FFF};
+static const uint16_t ghost_skirt[4] = {0x1BBB, 0x11B1, 0x1FFF, 0x0CE6};
+static const color ghost_col[4] = {RED, PINK, CYAN, ORANGE};
+enum { LOOK_NORMAL, LOOK_BLUE, LOOK_FLASH, LOOK_EYES };
+
+/* a ghost centred on (x, y), looking towards d */
+static void ghost_draw(int x, int y, color body, int d, int look, int fr) {
+ x -= 6, y -= 6;
+ if (!hits(x, y, 13, 13)) return;
+ if (look != LOOK_EYES) {
+ if (look) body = look == LOOK_FLASH ? WHITE : BLUE;
+ for (int r = 0; r < 13; r++)
+ for (unsigned c = 0, b = r < 11 ? ghost_body[r] : ghost_skirt[fr * 2 + r - 11]; b; c++, b >>= 1)
+ if (b & 1) pset(x + (int)c, y + r, body);
+ }
+ if (look == LOOK_BLUE || look == LOOK_FLASH) { /* frightened: little eyes and a wavy mouth */
+ color f = look == LOOK_FLASH ? RED : PEACH;
+ fill(x + 3, y + 4, 2, 2, f);
+ fill(x + 8, y + 4, 2, 2, f);
+ for (int c = 1; c < 12; c++) pset(x + c, y + 8 + (c >> 1 & 1), f);
+ return;
+ }
+ for (int e = 2; e < 9; e += 5) { /* the eyes look where the ghost goes */
+ int ox = x + e + DX[d], oy = y + 2 + DY[d];
+ fill(ox + 1, oy, 2, 5, WHITE);
+ fill(ox, oy + 1, 4, 3, WHITE);
+ fill(ox + 1 + DX[d], oy + 2 + 2 * DY[d] - (DY[d] > 0), 2, 2, BLUE);
+ }
+}
+
+/* cherry, strawberry, orange, apple, melon, Galaxian, bell, key: 12x12, 2 bits a pixel */
+static const uint8_t fruit_bits[8][36] = {
+ {0x00,0x00,0xA0,0x00,0x00,0x2A,0x00,0x80,0x20,0x00,0x20,0x20,0x00,0x08,0x08,0x50,0x09,0x02,0x54,0x45,0x16,0x55,0x55,0x55,0x5D,0x55,0x55,0x75,0xD5,0x55,0x54,0x51,0x5D,0x50,0x40,0x15},
+ {0x00,0x28,0x00,0xA0,0xAA,0x0A,0x94,0x96,0x16,0x75,0x55,0x5D,0x55,0x5D,0x55,0x5D,0x55,0x75,0x55,0x57,0x55,0x54,0xD5,0x55,0x74,0x55,0x15,0x50,0x75,0x01,0x40,0x55,0x01,0x00,0x55,0x00},
+ {0x00,0x8C,0x02,0x00,0xAC,0x0A,0x40,0x5D,0x01,0x50,0x55,0x05,0x54,0x55,0x15,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x54,0x55,0x15,0x50,0x55,0x05,0x40,0x55,0x01},
+ {0x00,0x08,0x00,0x40,0x59,0x00,0x54,0x59,0x15,0x55,0x55,0x55,0x7D,0x55,0x55,0x5D,0x55,0x55,0x5D,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x55,0x54,0x55,0x15,0x50,0x55,0x05,0x40,0x41,0x01},
+ {0x00,0x28,0x00,0x00,0x20,0x00,0x40,0x55,0x01,0xD0,0xD5,0x05,0x54,0x77,0x15,0x74,0x5D,0x1D,0xD5,0xD5,0x55,0x5D,0x5D,0x5D,0xD4,0xD5,0x15,0x74,0x5D,0x1D,0x50,0x75,0x05,0x40,0x55,0x01},
+ {0x00,0x14,0x00,0x00,0x55,0x00,0x02,0xFF,0x80,0xCA,0xFF,0xA3,0x2A,0xFF,0xA8,0xAA,0x14,0xAA,0x8A,0x55,0xA2,0x02,0x96,0x80,0x00,0x14,0x00,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
+ {0x00,0x14,0x00,0x00,0x55,0x00,0x40,0x55,0x01,0xD0,0x55,0x05,0xD0,0x55,0x05,0xD0,0x55,0x05,0x74,0x55,0x15,0x74,0x55,0x15,0x55,0x55,0x55,0x55,0x55,0x55,0x00,0xAA,0x00,0x00,0x28,0x00},
+ {0x40,0x55,0x01,0x50,0xFF,0x05,0x50,0x55,0x05,0x00,0x28,0x00,0x00,0xA8,0x00,0x00,0x28,0x00,0x00,0xA8,0x00,0x00,0x28,0x00,0x00,0xA8,0x00,0x00,0x28,0x00,0x00,0x28,0x00,0x00,0x20,0x00},
+};
+#define BROWN RGB(0xDE9751)
+#define GREEN RGB(0x00DE00)
+static const color fruit_pal[8][3] = {
+ {RED, BROWN, WHITE}, {RED, GREEN, WHITE}, {ORANGE, GREEN, BROWN}, {RED, BROWN, WHITE},
+ {GREEN, BROWN, WHITE}, {YELLOW, BLUE, RED}, {YELLOW, CYAN, WHITE}, {CYAN, WHITE, BLACK},
+};
+static const uint16_t fruit_pts[8] = {100, 300, 500, 700, 1000, 2000, 3000, 5000};
+
+static void fruit_draw(int x, int y, int f) {
+ if (!hits(x, y, 12, 12)) return;
+ const uint8_t *b = fruit_bits[f];
+ for (int r = 0; r < 12; r++, b += 3)
+ for (uint32_t c = 0, v = b[0] | b[1] << 8 | (uint32_t)b[2] << 16; c < 12; c++, v >>= 2)
+ if (v & 3) pset(x + (int)c, y + r, fruit_pal[f][(v & 3) - 1]);
+}
+static int fruit_of(int level) { return level < 3 ? level - 1 : level > 12 ? 7 : (level + 1) / 2; }
+
+/* ------------------------------------------------------------------ the maze */
+/* the left half of each row (the right half mirrors it): a bit for each tile
+ that is not a corridor (walls, the ghost house, the outside) */
+static const uint16_t maze_rows[31] = {
+ 0x3FFF, 0x2001, 0x2FBD, 0x2FBD, 0x2FBD, 0x0001, 0x3DBD, 0x3DBD, 0x2181, 0x2FBF, 0x2FBF,
+ 0x01BF, 0x3DBF, 0x3DBF, 0x3C00, 0x3DBF, 0x3DBF, 0x01BF, 0x3DBF, 0x3DBF, 0x2001, 0x2FBD,
+ 0x2FBD, 0x0031, 0x3DB7, 0x3DB7, 0x2181, 0x2FFD, 0x2FFD, 0x0001, 0x3FFF,
+};
+static bool solid(int tx, int ty) {
+ if ((unsigned)ty > 30) return true;
+ if ((unsigned)tx > 27) return ty != 14; /* the tunnel goes on off screen */
+ return maze_rows[ty] >> (tx < 14 ? tx : 27 - tx) & 1;
+}
+static int tile(int v) { return (v + 21) / 7 - 3; } /* floor(v / 7), for v >= -21 */
+
+static uint64_t wpix[31][28]; /* the wall pixels of each tile */
+static float hyp(float a, float b) { return __builtin_sqrtf(a * a + b * b); }
+
+/* The walls run half a tile inside the wall tiles: a pixel is on a line when
+ its distance to the nearest corridor is 3 to 4 pixels (and 5 to 6 for the
+ second line of the outer wall and the ghost house). Concave corners come
+ round by themselves; convex ones are rounded around a point inside. */
+static void build_walls(void) {
+ const float R = 7;
+ for (int ty = 0; ty < 31; ty++)
+ for (int tx = 0; tx < 28; tx++) {
+ int c = tx < 14 ? tx : 27 - tx;
+ uint64_t m = 0;
+ bool out = ((ty >= 10 && ty <= 12) || (ty >= 16 && ty <= 18)) && c < 5;
+ bool house = ty >= 12 && ty <= 16 && c >= 10, inside = house && ty != 12 && ty != 16 && c > 10;
+ bool dbl = !c || !ty || ty == 30 || (ty >= 9 && ty <= 19 && c <= 5) || (ty >= 24 && ty <= 25 && c <= 2) ||
+ (c == 13 && ty <= 4) || house;
+ if (solid(tx, ty) && !out && !inside && !(ty == 12 && c == 13)) {
+ bool o[9];
+ for (int k = 0; k < 9; k++) o[k] = !solid(tx + k % 3 - 1, ty + k / 3 - 1);
+ for (int py = 0; py < 7; py++)
+ for (int px = 0; px < 7; px++) {
+ float u = px + .5f, v = py + .5f, U = 7 - u, V = 7 - v, d = 99;
+ if (o[3] && u < d) d = u;
+ if (o[5] && U < d) d = U;
+ if (o[1] && v < d) d = v;
+ if (o[7] && V < d) d = V;
+ if (o[0] && hyp(u, v) < d) d = hyp(u, v);
+ if (o[2] && hyp(U, v) < d) d = hyp(U, v);
+ if (o[6] && hyp(u, V) < d) d = hyp(u, V);
+ if (o[8] && hyp(U, V) < d) d = hyp(U, V);
+ float a = o[3] ? u : o[5] ? U : R, b = o[1] ? v : o[7] ? V : R;
+ if (a < R && b < R) d = R - hyp(R - a, R - b);
+ if ((d >= 3 && d < 4) || (dbl && d >= 5 && d < 6)) m |= 1ull << (py * 7 + px);
+ }
+ }
+ wpix[ty][tx] = m;
+ }
+ /* the pink door, and the ends of the walls beside it */
+ wpix[12][13] = wpix[12][14] = 0x3FFFull << 28;
+ wpix[12][12] |= 0x4081ull << 27;
+ wpix[12][15] |= 0x4081ull << 21;
+}
+
+/* ------------------------------------------------------------------ the game's state */
+enum { PH_START, PH_READY, PH_PLAY, PH_EAT, PH_DIE, PH_CLEAR, PH_OVER, PH_CUT };
+enum { G_HOUSE, G_LEAVE, G_OUT, G_EYES, G_ENTER };
+
+typedef struct {
+ int16_t x, y; /* in maze pixels, the centre */
+ uint16_t acc; /* sub-pixel progress, in 1/256 */
+ uint8_t dir, st, fright, rev, dots;
+} ghost_t;
+static ghost_t G[4];
+static struct {
+ int16_t x, y;
+ uint16_t acc;
+ uint8_t dir, want, wait, stall, anim;
+} P;
+static uint8_t cell[31][28]; /* 1 a dot, 2 an energizer */
+static uint8_t level, lives, phase, wave, combo, global_on, global_dots, extra, cheat, eaten_g, died;
+static uint16_t phase_t, wave_t, fright_t, fruit_t, pop_t, idle_t, dots_left, ticks;
+static uint32_t score, pop_v;
+static int16_t pop_x, pop_y;
+static color pop_c;
+
+/* the options and the saved game (pacman.sav) */
+static struct {
+ uint8_t magic, version, speed, lives, buffer, start, bonus, cheat;
+ uint32_t best;
+ uint8_t has, level, glives, flags; /* a game to continue: flags 1 extra life given, 2 no collisions */
+ uint32_t score;
+ uint8_t dots[32]; /* the dots and energizers left, in reading order */
+} S, saved;
+#define SAVE_NAME "pacman.sav"
+static const char *const speed_names[3] = {"SLOW", "NORMAL", "FAST"};
+static const uint8_t speed_mul[3] = {16, 20, 25};
+static const uint8_t lives_opt[4] = {1, 2, 3, 5};
+static const char *const buffer_names[5] = {"STRICT", "SNAPPY", "NORMAL", "FORGIVING", "INFINITE"};
+static const uint8_t buffer_ticks[5] = {0, 6, 15, 25, 255};
+static const uint16_t bonus_at[4] = {10000, 15000, 20000, 0};
+
+/* dots of a fresh maze: every corridor, except in the middle band and next
+ to Pac-Man's start */
+static int dot_at(int tx, int ty) {
+ int c = tx < 14 ? tx : 27 - tx;
+ if (solid(tx, ty) || !(((ty < 9 || ty > 19) && !(ty == 23 && c == 13)) || c == 6)) return 0;
+ return c == 1 && (ty == 3 || ty == 23) ? 2 : 1;
+}
+
+/* ------------------------------------------------------------------ rules */
+static int grp(void) { return level == 1 ? 0 : level < 5 ? 1 : level < 21 ? 2 : 3; }
+/* speeds in % of the arcade's top speed: Pac-Man, Pac-Man frightening, ghosts, frightened, in the tunnel */
+static const uint8_t speeds[4][5] = {
+ {80, 90, 75, 50, 40}, {90, 95, 85, 55, 45}, {100, 100, 95, 60, 50}, {90, 90, 95, 60, 50}};
+/* 100 % is 75.76 arcade pixels a second: 9.47 tiles, 1.105 of our pixels a tick */
+static int per_tick(int pct) { return pct * 283 * speed_mul[S.speed] / 2000; }
+
+static const uint8_t fright_secs[18] = {6, 5, 4, 3, 2, 5, 2, 2, 1, 5, 2, 1, 1, 3, 1, 1, 0, 1};
+static int flash_ticks(void) {
+ int l = level;
+ return l == 9 || l == 12 || l == 13 || l == 15 || l == 16 || l == 18 ? 48 : 80;
+}
+/* scatter, chase, scatter... in ticks; the last chase lasts forever */
+static const uint16_t waves[3][7] = {
+ {420, 1200, 420, 1200, 300, 1200, 300}, {420, 1200, 420, 1200, 300, 61980, 1}, {300, 1200, 300, 1200, 300, 62220, 1}};
+/* Cruise Elroy: Blinky speeds up when this few dots are left, and again at half */
+static const uint8_t elroy_dots[19] = {20, 30, 40, 40, 40, 50, 50, 50, 60, 60, 60, 80, 80, 80, 100, 100, 100, 100, 120};
+static int elroy(void) {
+ if (died && G[3].st == G_HOUSE) return 0; /* after a death, not before Clyde is out */
+ int n = elroy_dots[level < 19 ? level - 1 : 18];
+ return dots_left <= n / 2 ? 2 : dots_left <= n;
+}
+
+#define MAX_SCORE 9999999 /* 7 digits fit the side panels */
+static void add_score(uint32_t v) {
+ uint32_t b = bonus_at[S.bonus];
+ if (b && !extra && score + v >= b) extra = 1, lives += lives < 9;
+ score = score + v < MAX_SCORE ? score + v : MAX_SCORE;
+ if (!cheat && score > S.best) S.best = score;
+}
+
+static void wrap(int16_t *x) {
+ if (*x < -14) *x += 224;
+ else if (*x >= 210) *x -= 224;
+}
+
+/* the tile a ghost heads for */
+static void target(int i, int *x, int *y) {
+ static const int8_t corner[4][2] = {{25, -3}, {2, -3}, {27, 32}, {0, 32}};
+ int px = tile(P.x), py = tile(P.y), d = P.dir, n = i == 1 ? 4 : 2;
+ bool scatter = !(wave & 1) && !(i == 0 && elroy());
+ if (G[i].st == G_EYES) {
+ *x = 13, *y = 11;
+ return;
+ }
+ *x = px, *y = py;
+ if (i == 1 || i == 2) { /* ahead of Pac-Man (and left of it when he faces up, as in the arcade) */
+ *x += n * DX[d] - (d == UP ? n : 0);
+ *y += n * DY[d];
+ }
+ if (i == 2) { /* Inky: twice the way from Blinky to there */
+ *x = 2 * *x - tile(G[0].x);
+ *y = 2 * *y - tile(G[0].y);
+ }
+ if (i == 3) { /* Clyde: shy within 8 tiles */
+ int dx = tile(G[3].x) - px, dy = tile(G[3].y) - py;
+ if (dx * dx + dy * dy < 64) scatter = true;
+ }
+ if (scatter) *x = corner[i][0], *y = corner[i][1];
+}
+
+/* at the centre of a tile: the way closest to the target, never back */
+static void decide(ghost_t *g, int i) {
+ int tx = tile(g->x), ty = tile(g->y), gx, gy, best = -1, start = g->fright ? (int)(rnd() & 3) : 0;
+ int32_t bd = 0x7FFFFFFF;
+ target(i, &gx, &gy);
+ for (int k = 0; k < 4; k++) {
+ int d = (start + k) & 3, nx = tx + DX[d], ny = ty + DY[d];
+ if (d == (g->dir ^ 2) || solid(nx, ny)) continue;
+ if (g->fright) { /* frightened: a random way */
+ best = d;
+ break;
+ }
+ /* no turning up just above the house and above Pac-Man's start */
+ if (d == UP && g->st == G_OUT && (ty == 11 || ty == 23) && (tx == 12 || tx == 15)) continue;
+ int32_t dd = (nx - gx) * (nx - gx) + (ny - gy) * (ny - gy);
+ if (dd < bd) bd = dd, best = d;
+ }
+ g->dir = (uint8_t)(best < 0 ? g->dir ^ 2 : best);
+}
+
+#define DOOR_X 97
+#define OUT_Y 80
+#define HOUSE_Y 101
+static const int16_t home_x[4] = {97, 97, 83, 111};
+
+static void ghost_px(ghost_t *g, int i) {
+ int tx = tile(g->x), ty = tile(g->y);
+ switch (g->st) {
+ case G_HOUSE: /* bobbing */
+ if (g->y <= HOUSE_Y - 3) g->dir = DOWN;
+ else if (g->y >= HOUSE_Y + 3) g->dir = UP;
+ break;
+ case G_LEAVE:
+ if (g->x != DOOR_X) {
+ g->dir = g->x < DOOR_X ? RIGHT : LEFT;
+ } else if (g->y > OUT_Y) {
+ g->dir = UP;
+ } else {
+ g->st = G_OUT, g->dir = LEFT;
+ return;
+ }
+ break;
+ case G_ENTER: /* eyes: down through the door, then to their place */
+ if (g->y < HOUSE_Y) g->dir = g->x != DOOR_X ? (g->x < DOOR_X ? RIGHT : LEFT) : DOWN;
+ else if (g->x != home_x[i]) g->dir = g->x < home_x[i] ? RIGHT : LEFT;
+ else {
+ g->st = G_LEAVE;
+ return;
+ }
+ break;
+ default: {
+ bool at = g->x == tx * 7 + 3 && g->y == ty * 7 + 3;
+ if (g->st == G_EYES && g->y == OUT_Y && g->x >= 94 && g->x <= 101) {
+ g->st = G_ENTER;
+ return;
+ }
+ if (g->rev) {
+ g->rev = 0, g->dir ^= 2;
+ if (at && solid(tx + DX[g->dir], ty + DY[g->dir])) decide(g, i);
+ } else if (at) {
+ decide(g, i);
+ }
+ }
+ }
+ g->x += DX[g->dir], g->y += DY[g->dir];
+ wrap(&g->x);
+}
+
+static int ghost_speed(int i) {
+ const ghost_t *g = &G[i];
+ const uint8_t *s = speeds[grp()];
+ int tx = tile(g->x), ty = tile(g->y);
+ if (g->st >= G_EYES) return per_tick(160);
+ if (g->st != G_OUT) return per_tick(50);
+ if (ty == 14 && (tx <= 5 || tx >= 22)) return per_tick(s[4]);
+ if (g->fright) return per_tick(s[3]);
+ return per_tick(s[2] + (i ? 0 : 5 * elroy()));
+}
+
+static void frighten(void) {
+ combo = 0;
+ fright_t = level <= 18 ? fright_secs[level - 1] * 60 : 0;
+ for (int i = 0; i < 4; i++) {
+ if (G[i].st == G_OUT) G[i].rev = 1;
+ if (fright_t && G[i].st <= G_OUT) G[i].fright = 1;
+ }
+}
+
+/* the first ghost still at home, or 4 */
+static int in_house(void) {
+ int i = 1;
+ while (i < 4 && G[i].st != G_HOUSE) i++;
+ return i;
+}
+
+static void eat(void) {
+ int tx = tile(P.x), ty = tile(P.y), k;
+ if ((unsigned)tx > 27 || !(k = cell[ty][tx])) return;
+ cell[ty][tx] = 0;
+ dots_left--, idle_t = 0;
+ P.stall = k == 2 ? 3 : 1; /* Pac-Man stops a frame for each dot, three for an energizer */
+ add_score(k == 2 ? 50 : 10);
+ int h = in_house();
+ if (global_on) global_dots++;
+ else if (h < 4) G[h].dots++;
+ if (k == 2) frighten();
+ if (dots_left == 244 - 70 || dots_left == 244 - 170) fruit_t = (uint16_t)(560 + rnd() % 40);
+ if (!dots_left) phase = PH_CLEAR, phase_t = 0;
+}
+
+static void pac_px(void) {
+ int tx = tile(P.x), ty = tile(P.y), ox = P.x - tx * 7 - 3, oy = P.y - ty * 7 - 3, w = P.want, d;
+ /* turn back at once; turn sideways anywhere in the tile (cornering) */
+ if (w != NONE && w != P.dir && (w == (P.dir ^ 2) || !solid(tx + DX[w], ty + DY[w]))) P.dir = (uint8_t)w;
+ d = P.dir;
+ if (DX[d] * ox + DY[d] * oy >= 0 && solid(tx + DX[d], ty + DY[d])) return; /* against a wall */
+ P.x += DX[d], P.y += DY[d];
+ if (DX[d]) P.y -= (oy > 0) - (oy < 0); /* back onto the middle of the corridor */
+ else P.x -= (ox > 0) - (ox < 0);
+ wrap(&P.x);
+ P.anim++;
+ eat();
+}
+
+static void reset_actors(void) {
+ static const int16_t gx[4] = {97, 97, 83, 111};
+ for (int i = 0; i < 4; i++) {
+ ghost_t *g = &G[i];
+ g->x = gx[i], g->y = i ? HOUSE_Y : OUT_Y, g->acc = 0;
+ g->st = i ? G_HOUSE : G_OUT, g->dir = i == 0 ? LEFT : i == 1 ? DOWN : UP;
+ g->fright = g->rev = 0;
+ }
+ P.x = 97, P.y = 23 * 7 + 3, P.dir = LEFT, P.want = NONE, P.wait = 0, P.acc = 0, P.stall = 0, P.anim = 0;
+ wave = 0, wave_t = 0, fright_t = 0, fruit_t = 0, pop_t = 0, idle_t = 0;
+}
+
+static void new_level(void) {
+ dots_left = 0;
+ for (int ty = 0; ty < 31; ty++)
+ for (int tx = 0; tx < 28; tx++) dots_left += (cell[ty][tx] = (uint8_t)dot_at(tx, ty)) != 0;
+ for (int i = 0; i < 4; i++) G[i].dots = 0;
+ global_on = global_dots = 0, died = 0;
+ reset_actors();
+}
+
+static void play_tick(void) {
+ if (fright_t) {
+ if (!--fright_t)
+ for (int i = 0; i < 4; i++) G[i].fright = 0;
+ } else if (wave < 7 && ++wave_t >= waves[level == 1 ? 0 : level < 5 ? 1 : 2][wave]) {
+ wave++, wave_t = 0; /* scatter <-> chase: the ghosts turn around */
+ for (int i = 0; i < 4; i++) G[i].rev |= G[i].st == G_OUT;
+ }
+ if (fruit_t) fruit_t--;
+ if (pop_t) pop_t--;
+ /* the ghost house: the first ghost at home leaves when its dot counter (or,
+ after a death, the shared one) says so, or when no dot was eaten for a while */
+ int h = in_house();
+ if (h < 4) {
+ bool go;
+ if (global_on) {
+ go = global_dots >= (h == 1 ? 7 : h == 2 ? 17 : 32);
+ if (go && h == 3) global_on = 0;
+ } else {
+ go = G[h].dots >= (level == 1 ? (h == 2 ? 30 : h == 3 ? 60 : 0) : level == 2 && h == 3 ? 50 : 0);
+ }
+ if (++idle_t >= (level < 5 ? 240 : 180)) idle_t = 0, go = true;
+ if (go) G[h].st = G_LEAVE;
+ }
+ if (P.stall) {
+ P.stall--;
+ } else {
+ P.acc += per_tick(speeds[grp()][fright_t ? 1 : 0]);
+ for (; P.acc >= 256; P.acc -= 256) {
+ pac_px();
+ if (phase != PH_PLAY) return;
+ }
+ }
+ if (fruit_t && P.y == 17 * 7 + 3 && P.x >= 94 && P.x <= 101) {
+ fruit_t = 0;
+ add_score(pop_v = fruit_pts[fruit_of(level)]);
+ pop_x = 98, pop_y = 122, pop_c = PINK, pop_t = 120;
+ }
+ for (int i = 0; i < 4; i++)
+ for (G[i].acc += ghost_speed(i); G[i].acc >= 256; G[i].acc -= 256) ghost_px(&G[i], i);
+ for (int i = 0; i < 4; i++) {
+ ghost_t *g = &G[i];
+ int dx = g->x - P.x, dy = g->y - P.y;
+ dx += dx < -112 ? 224 : dx > 112 ? -224 : 0; /* the tunnel's two ends are neighbours */
+ if (g->st != G_OUT || dx < -4 || dx > 4 || dy < -4 || dy > 4) continue;
+ if (g->fright) { /* eaten: 200, 400, 800, 1600, and a pause to see it */
+ g->fright = 0, g->st = G_EYES;
+ add_score(pop_v = 200u << combo);
+ combo += combo < 3;
+ pop_x = g->x, pop_y = g->y, pop_c = CYAN, pop_t = 60;
+ eaten_g = (uint8_t)i, phase = PH_EAT, phase_t = 0;
+ return;
+ }
+ if (!cheat) {
+ phase = PH_DIE, phase_t = 0;
+ return;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ the game screen */
+static bool paused;
+static const char *const *menu_items;
+static const char *menu_title;
+static int menu_n, menu_sel;
+static bool ready_shown(void) { return phase <= PH_READY; }
+static bool ghosts_shown(void) {
+ return phase != PH_START && phase < PH_OVER && !((phase == PH_DIE || phase == PH_CLEAR) && phase_t >= 60);
+}
+static bool pac_shown(void) {
+ return phase != PH_START && phase != PH_EAT && phase < PH_OVER && !(phase == PH_DIE && phase_t >= 150);
+}
+static int lives_shown(void) { return lives - (phase != PH_START); }
+
+/* where sprite i is drawn (the ghosts, Pac-Man, the fruit, points); w = 0 when hidden */
+static void obj_rect(int i, int16_t *r) {
+ int x = 98, y = 122, w = 12, h = 12;
+ bool on = fruit_t && phase <= PH_DIE && (phase != PH_DIE || phase_t < 60);
+ if (i < 4) x = G[i].x, y = G[i].y, w = h = 13, on = ghosts_shown() && !(phase == PH_EAT && i == eaten_g);
+ if (i == 4) x = P.x, y = P.y, w = h = 13, on = pac_shown();
+ if (i == 6) x = pop_x, y = pop_y, w = 17, h = 7, on = pop_t;
+ r[0] = (int16_t)(MX + x - w / 2), r[1] = (int16_t)(MY + y - h / 2), r[2] = (int16_t)(on ? w : 0), r[3] = (int16_t)h;
+}
+
+static color wallc;
+static bool energizers_on;
+
+static void maze_draw(void) {
+ int x0 = cx0 > MX ? cx0 : MX, x1 = cx1 < MX + MW ? cx1 : MX + MW;
+ int y0 = cy0 > MY ? cy0 : MY, y1 = cy1 < MY + MH ? cy1 : MY + MH;
+ for (int y = y0; y < y1; y++) {
+ int my = y - MY, ty = my / 7, py = my - ty * 7, mx = x0 - MX, tx = mx / 7, px = mx - tx * 7;
+ color *p = buf + (y - by) * bw + x0 - bx;
+ for (int x = x0; x < x1; x++, p++) {
+ color c = BLACK;
+ int k = cell[ty][tx];
+ if (wpix[ty][tx] >> (py * 7 + px) & 1) {
+ c = ty == 12 && (tx == 13 || tx == 14) ? PINK : wallc;
+ } else if (k == 1) { /* a dot, mirrored in the right half */
+ if ((py == 3 || py == 4) && (px == 3 || px == (tx < 14 ? 4 : 2))) c = PEACH;
+ } else if (k == 2 && energizers_on) {
+ int a = px - 3, b = py - 3;
+ if (a * a + b * b <= 10) c = PEACH;
+ }
+ *p = c;
+ if (++px == 7) px = 0, tx++;
+ }
+ }
+}
+
+/* The intermissions, as in the arcade. 0: Blinky chases Pac-Man away, and a
+ giant Pac-Man comes back after him. 1: Blinky's cloak catches on a nail and
+ tears. 2: Blinky, his cloak patched, chases Pac-Man, then runs back
+ without it, dragging it along. */
+#define CUT_Y (MY + 108)
+#define NAIL_X (MX + 98)
+static uint8_t cut;
+static void cut_draw(void) {
+ int t = phase_t, f = t >> 1 & 3, fr = t >> 3 & 1, x = MX + MW + 10 - t * 6 / 5, g = x + 28 - t / 10;
+ f = f == 3 ? 2 : f * 2;
+ if (cut == 1) {
+ int s = t - 114; /* ticks since the cloak caught */
+ fill(NAIL_X, CUT_Y + 3, 1, 4, PEACH);
+ fill(NAIL_X - 1, CUT_Y + 7, 3, 1, PEACH);
+ pac_draw(x, CUT_Y, LEFT, f, 0);
+ g = MX + MW + 38 - t * 5 / 4;
+ if (s > 0) g = NAIL_X - 6 - (s < 64 ? s : 64) / 8; /* straining: the cloak stretches */
+ if (s > 0 && s < 64) fill(g + 6, CUT_Y + 4, NAIL_X - g - 6, 3, RED);
+ ghost_draw(g, CUT_Y, RED, s < 64 ? LEFT : s < 150 ? RIGHT : DOWN, LOOK_NORMAL, s > 0 || fr);
+ if (s >= 64) { /* torn: a rag on the nail, a leg showing */
+ fill(g + 2, CUT_Y + 3, 5, 4, BLACK);
+ fill(g + 3, CUT_Y + 3, 2, 4, PEACH);
+ fill(NAIL_X - 2, CUT_Y + 4, 2, 3, RED);
+ }
+ } else if (t < 200) {
+ pac_draw(x, CUT_Y, LEFT, f, 0);
+ ghost_draw(g, CUT_Y, RED, LEFT, LOOK_NORMAL, fr);
+ if (cut) fill(g + 2, CUT_Y + 1, 3, 3, PEACH); /* the patch */
+ } else if (t >= 240) {
+ x = MX - 10 + (t - 240);
+ if (cut) { /* no cloak: a little red body on two legs, the cloak dragged behind */
+ fill(x - 4, CUT_Y - 1, 9, 5, RED);
+ fill(x - 3 + fr, CUT_Y + 4, 1, 2, RED);
+ fill(x + 2 - fr, CUT_Y + 4, 1, 2, RED);
+ fill(x - 10, CUT_Y + 2, 6, 1, RED);
+ for (int r = 0; r < 4; r++)
+ for (int c = 0, b = r < 2 ? 0x1FFF : ghost_skirt[fr * 2 + r - 2]; b; c++, b >>= 1)
+ if (b & 1) pset(x - 23 + c, CUT_Y + 2 + r, RED);
+ ghost_draw(x, CUT_Y + 1, RED, RIGHT, LOOK_EYES, 0);
+ } else {
+ ghost_draw(x, CUT_Y, RED, RIGHT, LOOK_BLUE, fr);
+ pac_r(x - 44 + (t - 240) / 12, CUT_Y, RIGHT, f, 0, 13);
+ }
+ }
+}
+
+static void box_draw(void) {
+ int h = 36 + menu_n * 20, y = MY + MH / 2 - h / 2;
+ fill(70, y, 180, h, BLACK);
+ frame(70, y, 180, h, WALL);
+ frame(73, y + 3, 174, h - 6, WALL);
+ ctext(menu_title, 160, y + 11, 2, YELLOW);
+ for (int i = 0; i < menu_n; i++) {
+ int iy = y + 34 + i * 20;
+ text(menu_items[i], 110, iy, 2, i == menu_sel ? WHITE : GREY);
+ if (i == menu_sel) pac_draw(96, iy + 7, RIGHT, (ticks >> 2 & 3) == 3 ? 2 : (ticks >> 2 & 3) * 2, 0);
+ }
+}
+
+static void game_scene(void) {
+ fill(cx0, cy0, cx1 - cx0, cy1 - cy0, BLACK);
+ if (cx0 < MX || cx1 > MX + MW) { /* the sides: scores, lives, fruit (the latest at the right) */
+ if (phase != PH_PLAY || ticks & 16) text("1UP", 21, 12, 1, WHITE);
+ rtext(score ? num(score) : "00", 48, 21, 1, WHITE);
+ ctext("HIGH", 289, 12, 1, WHITE);
+ ctext("SCORE", 289, 21, 1, WHITE);
+ if (S.best) rtext(num(S.best), 306, 30, 1, WHITE);
+ if (cheat) ctext("CHEAT", 289, 46, 1, RED);
+ for (int i = 0, n = lives_shown(); i < n && i < 8; i++) pac_draw(10 + i % 4 * 14, 222 - i / 4 * 14, LEFT, 3, 0);
+ for (int i = 0, l = level; l > 0 && i < 7; i++, l--) fruit_draw(303 - i % 4 * 14, 216 - i / 4 * 14, fruit_of(l));
+ }
+ int s0 = cx0, s1 = cx1; /* sprites stay in the maze (the tunnel) */
+ if (cx0 < MX) cx0 = MX;
+ if (cx1 > MX + MW) cx1 = MX + MW;
+ if (phase == PH_CUT) cut_draw();
+ else maze_draw();
+ int16_t r[4];
+ obj_rect(5, r);
+ if (r[2]) fruit_draw(MX + 92, MY + 116, fruit_of(level));
+ obj_rect(4, r);
+ if (r[2]) {
+ int f = P.anim >> 1 & 3;
+ if (phase == PH_DIE && phase_t >= 60) {
+ int t = phase_t - 60;
+ if (t < 80) pac_draw(MX + P.x, MY + P.y, UP, 0, t * 2 / 5 + 1);
+ else /* a little flash where he was */
+ for (int k = 2; k < 5; k++) {
+ int x = MX + P.x, y = MY + P.y;
+ pset(x + k + 1, y, YELLOW), pset(x - k - 1, y, YELLOW), pset(x, y + k + 1, YELLOW), pset(x, y - k - 1, YELLOW);
+ pset(x + k, y + k, YELLOW), pset(x - k, y + k, YELLOW), pset(x + k, y - k, YELLOW), pset(x - k, y - k, YELLOW);
+ }
+ } else {
+ pac_draw(MX + P.x, MY + P.y, P.dir, phase < PH_PLAY || phase == PH_CLEAR ? 0 : f == 3 ? 2 : f * 2, 0);
+ }
+ }
+ for (int i = 3; i >= 0; i--) {
+ obj_rect(i, r);
+ if (!r[2]) continue;
+ ghost_t *g = &G[i];
+ int look = g->st >= G_EYES ? LOOK_EYES : !g->fright ? LOOK_NORMAL
+ : fright_t <= flash_ticks() && fright_t & 8 ? LOOK_FLASH : LOOK_BLUE;
+ ghost_draw(MX + g->x, MY + g->y, ghost_col[i], g->dir, look, ticks >> 3 & 1);
+ }
+ if (pop_t) mini(pop_v, MX + pop_x, MY + pop_y - 2, pop_c);
+ cx0 = s0, cx1 = s1;
+ if (ready_shown()) ctext("READY!", MX + 98, MY + 119, 1, YELLOW);
+ if (phase == PH_START) ctext("PLAYER ONE", MX + 98, MY + 77, 1, CYAN);
+ if (phase == PH_OVER) ctext("GAME OVER", MX + 98, MY + 119, 1, RED);
+ if (paused) box_draw();
+}
+
+/* ------------------------------------------------------------------ keys and frames */
+static uint64_t held, hit, fresh; /* fresh: pressed since last time, without repeats */
+static uint64_t stale; /* held into this screen: ignored until released */
+static bool quit; /* Home or On/Off: leave the app */
+static uint32_t frame_t, repeat_at;
+static const uint64_t K_UP = KEY(eadk_key_up) | KEY(eadk_key_eight), K_DOWN = KEY(eadk_key_down) | KEY(eadk_key_two);
+static const uint64_t K_LEFT = KEY(eadk_key_left) | KEY(eadk_key_four), K_RIGHT = KEY(eadk_key_right) | KEY(eadk_key_six);
+static const uint64_t K_OK = KEY(eadk_key_ok) | KEY(eadk_key_exe), K_BACK = KEY(eadk_key_back);
+
+/* reads the keyboard: `hit` has the keys pressed since last time, arrows repeating */
+static void keys(void) {
+ uint64_t k = eadk_keyboard_scan(), arrows = K_UP | K_DOWN | K_LEFT | K_RIGHT;
+ uint32_t now = eadk_timing_millis();
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) quit = true;
+ k &= ~(stale &= k);
+ hit = fresh = k & ~held;
+ if (hit & arrows) repeat_at = now + 350;
+ else if ((k & arrows) && (int32_t)(now - repeat_at) >= 0) hit |= k & arrows, repeat_at = now + 90;
+ held = k;
+}
+/* a new screen: the keys down now count only once pressed again */
+static void settle(void) { stale = eadk_keyboard_scan(); }
+/* ends a frame: at most 60 a second */
+static void frame_end(void) {
+ uint32_t spent = (uint32_t)eadk_timing_millis() - frame_t;
+ if (spent < 16) eadk_timing_msleep(16 - spent);
+ frame_t = eadk_timing_millis();
+}
+
+/* ------------------------------------------------------------------ saving */
+static void save(void) {
+ const uint8_t *a = (const uint8_t *)&S;
+ uint8_t *b = (uint8_t *)&saved;
+ for (unsigned i = 0; i < sizeof S; i++)
+ if (a[i] != b[i]) { /* changed: write it (and try again next time if that failed) */
+ if (ef_write(SAVE_NAME, &S, sizeof S))
+ for (i = 0; i < sizeof S; i++) b[i] = a[i];
+ return;
+ }
+}
+/* the game in progress, to continue later */
+static void keep_game(void) {
+ int n = 0, left = lives - (phase == PH_DIE), next = !dots_left && level < 255; /* cleared: the next level */
+ S.has = phase != PH_OVER && left > 0;
+ S.level = (uint8_t)(level + next), S.glives = (uint8_t)left, S.flags = (uint8_t)(extra | cheat << 1), S.score = score;
+ for (int i = 0; i < 32; i++) S.dots[i] = 0;
+ for (int ty = 0; ty < 31; ty++)
+ for (int tx = 0; tx < 28; tx++)
+ if (dot_at(tx, ty)) S.dots[n >> 3] |= (uint8_t)((next || cell[ty][tx]) << (n & 7)), n++;
+}
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ uint8_t *s = (uint8_t *)&S;
+ if (d && n == sizeof S && d[0] == 'P' && d[1] == 1)
+ for (unsigned i = 0; i < sizeof S; i++) s[i] = d[i];
+ else
+ for (unsigned i = 0; i < sizeof S; i++) s[i] = 0;
+ /* anything out of range gets its default */
+ if (S.magic != 'P') S.speed = 1, S.lives = 2, S.buffer = 2;
+ S.magic = 'P', S.version = 1;
+ if (S.speed > 2) S.speed = 1;
+ if (S.lives > 3) S.lives = 2;
+ if (S.buffer > 4) S.buffer = 2;
+ if (S.start < 1 || S.start > 21) S.start = 1;
+ if (S.bonus > 3) S.bonus = 0;
+ if (S.cheat > 1) S.cheat = 0;
+ if (S.best > MAX_SCORE) S.best = 0;
+ int left = 0;
+ for (int i = 0; i < 244; i++) left += S.dots[i >> 3] >> (i & 7) & 1;
+ if (S.has != 1 || !S.level || !S.glives || S.glives > 9 || S.flags > 3 || !left || S.score > MAX_SCORE) S.has = 0;
+ for (unsigned i = 0; i < sizeof S; i++) ((uint8_t *)&saved)[i] = s[i];
+}
+
+/* ------------------------------------------------------------------ menus */
+static int menu_box(const char *title, const char *const *items, int n, int sel) {
+ int h = 36 + n * 20, y = MY + MH / 2 - h / 2;
+ menu_title = title, menu_items = items, menu_n = n, menu_sel = sel, paused = true;
+ settle();
+ refresh(70, MY + MH / 2 - 48, 180, 96); /* also clears a bigger box shown before */
+ for (;;) {
+ keys();
+ if (quit) break;
+ if (hit & (K_UP | K_DOWN)) menu_sel = (menu_sel + (hit & K_UP ? n - 1 : 1)) % n;
+ if (hit & (K_OK | K_BACK)) break;
+ ticks++;
+ eadk_display_wait_for_vblank();
+ refresh(70, y + 30, 180, n * 20);
+ frame_end();
+ }
+ paused = false;
+ return hit & K_OK ? menu_sel : -1;
+}
+
+/* ------------------------------------------------------------------ playing */
+enum { END_TITLE, END_RESTART };
+
+/* one tick of the game (1/60 s); true when it is over */
+static bool redraw_all;
+static bool step(void) {
+ ticks++, phase_t++;
+ switch (phase) {
+ case PH_START:
+ case PH_READY:
+ if (phase_t >= 120) phase++, phase_t = 0;
+ break;
+ case PH_PLAY: play_tick(); break;
+ case PH_EAT:
+ if (phase_t >= 60) phase = PH_PLAY, pop_t = 0;
+ break;
+ case PH_DIE:
+ if (phase_t >= 190) {
+ phase_t = 0;
+ if (!--lives) {
+ phase = PH_OVER;
+ break;
+ }
+ reset_actors();
+ died = 1, global_on = 1, global_dots = 0;
+ phase = PH_READY;
+ }
+ break;
+ case PH_CLEAR:
+ if (phase_t >= 60 + 8 * 12) {
+ int l = level; /* intermissions after levels 2, 5, 9, 13 and 17, like the arcade */
+ if (level < 255) level++;
+ new_level();
+ phase = l == 2 || l == 5 || l == 9 || l == 13 || l == 17 ? PH_CUT : PH_READY;
+ cut = l == 2 ? 0 : l == 5 ? 1 : 2;
+ phase_t = 0, redraw_all = true;
+ }
+ break;
+ case PH_CUT:
+ if (phase_t >= (cut == 1 ? 360 : 500) || (fresh & K_OK)) phase = PH_READY, phase_t = 0, redraw_all = true;
+ break;
+ case PH_OVER: return phase_t >= 240 || (hit & (K_OK | K_BACK));
+ }
+ return false;
+}
+
+static const char *const yes_no[2] = {"NO", "YES"};
+static int play(void) {
+ static const char *const pause_items[3] = {"RESUME", "RESTART", "QUIT GAME"};
+ static int16_t orect[7][4];
+ static uint32_t sig[8];
+ uint32_t last = eadk_timing_millis(), acc = 0;
+ redraw_all = true;
+ scene = game_scene;
+ for (;;) {
+ keys();
+ if (quit) {
+ keep_game();
+ return END_TITLE;
+ }
+ if ((hit & K_BACK) && phase != PH_OVER) {
+ int c = 0;
+ do /* "Quit game?": No goes back to the pause menu */
+ c = menu_box("PAUSED", pause_items, 3, c);
+ while (c == 2 && !quit && menu_box("QUIT GAME?", yes_no, 2, 0) != 1);
+ if (quit || c == 2) { /* Quit game: back to NumPlay (or the calculator) */
+ keep_game();
+ quit = true;
+ return END_TITLE;
+ }
+ if (c == 1) return END_RESTART;
+ redraw_all = true, last = eadk_timing_millis(), acc = 0;
+ held = eadk_keyboard_scan(), stale = 0; /* an arrow still held steers */
+ }
+ /* the wanted direction: the arrow pressed last, while it is held and for
+ the input buffer's time after (even if another arrow is still held) */
+ int d = NONE;
+ static const uint64_t dk[4] = {KEY(eadk_key_up) | KEY(eadk_key_eight), KEY(eadk_key_left) | KEY(eadk_key_four),
+ KEY(eadk_key_down) | KEY(eadk_key_two), KEY(eadk_key_right) | KEY(eadk_key_six)};
+ for (int i = 0; i < 4; i++)
+ if (fresh & dk[i]) d = i;
+ if (d == NONE && P.want != NONE && (held & dk[P.want])) d = P.want;
+ if (d == NONE && P.wait != 255 && !(P.wait && --P.wait))
+ for (int i = 0; i < 4 && d == NONE; i++) /* the turn is forgotten: back to an arrow still held */
+ if (held & dk[i]) d = i;
+ if (d != NONE) P.want = (uint8_t)d, P.wait = buffer_ticks[S.buffer];
+ else if (P.wait != 255 && !P.wait) P.want = NONE;
+
+ /* the rules run 60 times a second: one tick a frame while the frames come
+ at about that rate (the arcade too runs at its screen's rate), else as
+ many as the time says, 4 at most */
+ uint32_t now = eadk_timing_millis(), dt = now - last, todo;
+ last = now;
+ if (dt >= 15 && dt <= 18) todo = 1, acc = 0;
+ else acc += dt * 3, todo = acc / 50, acc %= 50;
+ for (todo = todo < 4 ? todo : 4; todo; todo--)
+ if (step()) {
+ keep_game();
+ return END_TITLE;
+ }
+
+ /* what the screen shows, to redraw only what changed */
+ energizers_on = phase < PH_PLAY || phase == PH_CLEAR || ticks & 8;
+ wallc = phase == PH_CLEAR && phase_t >= 60 && (phase_t - 60) / 12 % 2 ? WHITE : WALL;
+ uint32_t s[8] = {score, S.best, (uint32_t)lives_shown(), phase == PH_PLAY && !(ticks & 16), energizers_on, wallc,
+ (uint32_t)(ready_shown() | (phase == PH_START) << 1 | (phase == PH_OVER) << 2), level};
+ eadk_display_wait_for_vblank();
+ bool full = redraw_all || s[7] != sig[7];
+ if (full) {
+ refresh(0, 0, 320, 240);
+ redraw_all = false;
+ } else {
+ if (s[0] != sig[0]) refresh(0, 21, 62, 7);
+ if (s[1] != sig[1]) refresh(258, 30, 62, 7);
+ if (s[2] != sig[2]) refresh(0, 200, 62, 30);
+ if (s[3] != sig[3]) refresh(0, 12, 62, 7);
+ if (s[4] != sig[4])
+ for (int i = 0; i < 4; i++) refresh(MX + (i & 1 ? 26 : 1) * 7, MY + (i & 2 ? 23 : 3) * 7, 7, 7);
+ if (s[5] != sig[5]) refresh(MX, MY, MW, MH);
+ if (s[6] != sig[6]) refresh(MX + 60, MY + 77, 76, 49);
+ if (phase == PH_CUT) refresh(MX, CUT_Y - 14, MW, 28);
+ }
+ for (int i = 0; i < 8; i++) sig[i] = s[i];
+ for (int i = 0; i < 7; i++) { /* the sprites: where they were and where they are */
+ int16_t n[4], *o = orect[i];
+ obj_rect(i, n);
+ int dx = n[0] - o[0], dy = n[1] - o[1];
+ if (full) {
+ } else if (n[2] && o[2] && dx > -20 && dx < 20 && dy > -20 && dy < 20) {
+ int x = dx < 0 ? n[0] : o[0], y = dy < 0 ? n[1] : o[1];
+ refresh(x, y, (dx < 0 ? -dx : dx) + (n[2] > o[2] ? n[2] : o[2]), (dy < 0 ? -dy : dy) + n[3]);
+ } else {
+ if (o[2]) refresh(o[0], o[1], o[2], o[3]);
+ if (n[2]) refresh(n[0], n[1], n[2], n[3]);
+ }
+ for (int k = 0; k < 4; k++) o[k] = n[k];
+ }
+ frame_end();
+ }
+}
+
+static int game(bool resume) {
+ int r;
+ do {
+ level = S.start, lives = lives_opt[S.lives], score = 0, extra = 0, cheat = S.cheat, phase = PH_START;
+ if (resume) /* the saved game: its level, score, lives and dots */
+ level = S.level, lives = S.glives, score = S.score, extra = S.flags & 1, cheat = S.flags >> 1, phase = PH_READY;
+ new_level();
+ if (resume) {
+ dots_left = 0;
+ for (int ty = 0, n = 0; ty < 31; ty++)
+ for (int tx = 0; tx < 28; tx++)
+ if (cell[ty][tx]) {
+ if (!(S.dots[n >> 3] >> (n & 7) & 1)) cell[ty][tx] = 0;
+ dots_left += cell[ty][tx] != 0, n++;
+ }
+ }
+ S.has = 0;
+ phase_t = 0, resume = false;
+ r = play();
+ save();
+ } while (r == END_RESTART && !quit);
+ return r;
+}
+
+/* ------------------------------------------------------------------ title and options */
+static int sel, osel;
+static uint16_t tt; /* the title's clock, in ticks */
+
+static const char *const title_items[3] = {"PLAY", "CONTINUE", "OPTIONS"};
+
+/* the attract chase: Pac-Man runs from the ghosts, eats the energizer and
+ turns the tables; each ghost he catches stops the chase for a moment, its
+ points in its place */
+#define LANE_Y 197
+static void lane_draw(void) {
+ int t = tt % 640, px, gx0, eat = -1;
+ bool back = t >= 250;
+ if (!back) {
+ px = 335 - t * 6 / 5, gx0 = px + 24;
+ } else { /* he gains a pixel a tick: ghost i is caught 24 + 16 i ticks in */
+ int d = t - 250;
+ for (int i = 0; i < 4; i++) {
+ int c = 24 + 16 * i;
+ if (d < c) break;
+ if (d < c + 40) {
+ eat = i, d = c;
+ break;
+ }
+ d -= 40;
+ }
+ px = 35 + d * 3 / 2, gx0 = 59 + d / 2;
+ }
+ for (int x = 45; x < 310; x += 10)
+ if (!back && x < px - 5) fill(x, LANE_Y - 1, 2, 2, PEACH);
+ if (!back && tt & 8) {
+ fill(33, LANE_Y - 3, 5, 7, PEACH);
+ fill(32, LANE_Y - 2, 7, 5, PEACH);
+ }
+ for (int i = 0; i < 4; i++) {
+ int gx = gx0 + 16 * i;
+ if (i == eat) mini(200u << i, gx, LANE_Y - 2, CYAN);
+ else if (!back || px < gx)
+ ghost_draw(gx, LANE_Y, ghost_col[i], back ? RIGHT : LEFT, back ? LOOK_BLUE : LOOK_NORMAL, tt >> 3 & 1);
+ }
+ int f = tt >> 1 & 3;
+ if (eat < 0) pac_draw(px, LANE_Y, back ? RIGHT : LEFT, f == 3 ? 2 : f * 2, 0);
+}
+
+/* The logo: fat letters from the font (5-pixel blocks, rounded where two
+ sides are open), Pac-Man as the C, chomping, all ringed in orange. */
+#define LOGO_X 45
+#define LOGO_Y 10
+static bool logo_blk(const uint8_t *g, int w, int bx, int by) {
+ if (bx < 0 || bx >= w || by < 0 || by > 6) return false;
+ return ((bx < 5 ? g[bx] : 0) | (bx ? g[bx - 1] : 0)) >> by & 1;
+}
+static bool logo_in(int x, int y) {
+ static const uint8_t at[6] = {0, 35, 110, 130, 165, 200};
+ x -= LOGO_X, y -= LOGO_Y;
+ if (y < 0 || y >= 35) return false;
+ int dx = x - 87, dy = y - 17, f = tt >> 3 & 3, open = f == 3 ? 2 : f * 2;
+ if (dx * dx + dy * dy <= 17 * 18) return !(dx > 0 && 4 * (dy < 0 ? -dy : dy) < open * dx);
+ for (int i = 0; i < 6; i++) {
+ int u = x - at[i], w = i == 2 ? 3 : 6; /* the hyphen is short */
+ if (u < 0 || u >= w * 5) continue;
+ const uint8_t *g = font["PA-MAN"[i] - 32];
+ int bx = u / 5, by = y / 5, px = u % 5 - 2, py = y % 5 - 2;
+ if (!logo_blk(g, w, bx, by)) return false;
+ /* round the outer corners: a quarter circle as big as the block, around its far corner */
+ for (int q = 0; q < 4; q++) {
+ int qx = q & 1 ? 1 : -1, qy = q & 2 ? 1 : -1, ax = 2 * px + 5 * qx, ay = 2 * py + 5 * qy;
+ if (px * qx >= 0 && py * qy >= 0 && !logo_blk(g, w, bx + qx, by) && !logo_blk(g, w, bx, by + qy) &&
+ ax * ax + ay * ay > 100)
+ return false;
+ }
+ return true;
+ }
+ return false;
+}
+static void logo_draw(void) {
+ static const int8_t ring[12][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {2, 0}, {-2, 0},
+ {0, 2}, {0, -2}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
+ if (!hits(LOGO_X - 2, LOGO_Y - 2, 236, 39)) return;
+ for (int y = LOGO_Y - 2; y < LOGO_Y + 37; y++)
+ for (int x = LOGO_X - 2; x < LOGO_X + 234; x++) {
+ if (x < cx0 || x >= cx1 || y < cy0 || y >= cy1) continue;
+ color c = YELLOW;
+ if (!logo_in(x, y)) {
+ int k = 0;
+ while (k < 12 && !logo_in(x + ring[k][0], y + ring[k][1])) k++;
+ if (k == 12) continue;
+ c = RGB(0xDE5A00);
+ }
+ buf[(y - by) * bw + x - bx] = c;
+ }
+}
+
+static void title_scene(void) {
+ static const char *const names[4] = {"-SHADOW \"BLINKY\"", "-SPEEDY \"PINKY\"", "-BASHFUL \"INKY\"",
+ "-POKEY \"CLYDE\""};
+ fill(cx0, cy0, cx1 - cx0, cy1 - cy0, BLACK);
+ logo_draw();
+ ctext("CHARACTER / NICKNAME", 160, 58, 1, WHITE);
+ for (int i = 0; i < 4; i++) {
+ ghost_draw(88, 76 + i * 14, ghost_col[i], RIGHT, LOOK_NORMAL, 0);
+ text(names[i], 102, 73 + i * 14, 1, ghost_col[i]);
+ }
+ for (int i = 0; i < 3; i++) {
+ bool off = i == 1 && !S.has;
+ text(title_items[i], 118, 132 + i * 18, 2, off ? RGB(0x3A3A4A) : i == sel ? WHITE : GREY);
+ if (i == sel) pac_draw(104, 139 + i * 18, RIGHT, (tt >> 2 & 3) == 3 ? 2 : (tt >> 2 & 3) * 2, 0);
+ }
+ lane_draw();
+ if (S.best) { /* HIGH SCORE and the score, centred together */
+ char *n = num(S.best);
+ int x = 160 - ((11 + slen(n)) * 7 - 1) / 2;
+ text("HIGH SCORE", x, 214, 1, WHITE);
+ text(n, x + 77, 214, 1, WHITE);
+ }
+ ctext("BASED ON TATONE26'S VERSION", 160, 228, 1, GREY);
+ if (paused) box_draw(); /* "Quit game?" */
+}
+
+static const char *const opt_names[6] = {"GAME SPEED", "LIVES", "BUFFER", "START LEVEL", "BONUS LIFE", "NO COLLISIONS"};
+static const char *opt_value(int i) {
+ switch (i) {
+ case 0: return speed_names[S.speed];
+ case 1: return num(lives_opt[S.lives]);
+ case 2: return buffer_names[S.buffer];
+ case 3: return num(S.start);
+ case 4: return S.bonus == 3 ? "NONE" : num(bonus_at[S.bonus]);
+ default: return S.cheat ? "ON" : "OFF";
+ }
+}
+static void options_scene(void) {
+ fill(cx0, cy0, cx1 - cx0, cy1 - cy0, BLACK);
+ ctext("OPTIONS", 160, 10, 2, YELLOW);
+ for (int i = 0; i < 6; i++) {
+ int y = 38 + i * 26;
+ bool on = i == osel;
+ const char *v = opt_value(i);
+ color c = i == 5 && S.cheat ? RED : on ? YELLOW : CYAN;
+ if (on) {
+ pac_draw(13, y + 7, RIGHT, (tt >> 2 & 3) == 3 ? 2 : (tt >> 2 & 3) * 2, 0);
+ text("<", 292 - tw(v, 2) - 18, y, 2, c);
+ text(">", 300, y, 2, c);
+ }
+ text(opt_names[i], 26, y, 2, on ? WHITE : GREY);
+ rtext(v, 292, y, 2, c);
+ if (i == 3) fruit_draw(292 - tw(v, 2) - (on ? 34 : 16), y + 1, fruit_of(S.start));
+ }
+ static const char *const help[6] = {"HOW FAST EVERYTHING MOVES", "PAC-MEN TO START WITH",
+ "HOW LONG A TURN WAITS FOR A GAP", "LATER LEVELS ARE FASTER",
+ "THE SCORE FOR AN EXTRA PAC-MAN", "GHOSTS CANNOT CATCH YOU: NO HIGH SCORE"};
+ ctext(help[osel], 160, 200, 1, osel == 5 ? RED : WHITE);
+ ctext("LEFT/RIGHT: CHANGE BACK: DONE", 160, 222, 1, GREY);
+}
+
+static void options(void) {
+ static const uint8_t count[6] = {3, 4, 5, 21, 4, 2};
+ osel = 0;
+ scene = options_scene;
+ settle();
+ refresh(0, 0, 320, 240);
+ for (;;) {
+ keys();
+ if (quit || (hit & K_BACK)) break;
+ int was = osel;
+ if (hit & (K_UP | K_DOWN)) osel = (osel + (hit & K_UP ? 5 : 1)) % 6;
+ int lr = (hit & K_RIGHT || hit & K_OK ? 1 : 0) - (hit & K_LEFT ? 1 : 0);
+ if (lr) {
+ uint8_t *v = osel == 0 ? &S.speed : osel == 1 ? &S.lives : osel == 2 ? &S.buffer : osel == 3 ? &S.start
+ : osel == 4 ? &S.bonus : &S.cheat;
+ int base = osel == 3, n = count[osel];
+ *v = (uint8_t)((*v - base + lr + n) % n + base);
+ }
+ tt++;
+ eadk_display_wait_for_vblank();
+ if (was != osel) refresh(0, 36 + was * 26, 320, 18), refresh(0, 198, 320, 11); /* the help line */
+ if (was != osel || lr) refresh(0, 36 + osel * 26, 320, 18);
+ else refresh(6, 39 + osel * 26, 14, 14); /* the cursor's mouth */
+ frame_end();
+ }
+ save();
+}
+
+int main(void) {
+ np_app_begin();
+ quit = false, paused = false, tt = 0, ticks = 0;
+ seed ^= eadk_random() | 1;
+ build_walls();
+ load();
+ settle();
+ frame_t = eadk_timing_millis();
+ sel = S.has ? 1 : 0;
+ bool full = true;
+ while (!quit) {
+ scene = title_scene;
+ keys();
+ if (quit) break;
+ if (hit & (K_UP | K_DOWN)) {
+ do sel = (sel + (hit & K_UP ? 2 : 1)) % 3; while (sel == 1 && !S.has);
+ refresh(96, 130, 136, 54);
+ }
+ if (hit & K_BACK) { /* "Quit game?" from the title */
+ if (menu_box("QUIT GAME?", yes_no, 2, 0) == 1) break;
+ full = true;
+ continue;
+ }
+ if (hit & K_OK) {
+ if (sel == 2) options();
+ else game(sel == 1);
+ sel = S.has ? 1 : sel == 1 ? 0 : sel;
+ full = true;
+ settle();
+ continue;
+ }
+ tt++;
+ eadk_display_wait_for_vblank();
+ if (full) {
+ refresh(0, 0, 320, 240);
+ full = false;
+ } else { /* what moves: the chase, and the mouths of the cursor and the logo */
+ refresh(0, LANE_Y - 8, 320, 16);
+ if (!(tt & 3)) refresh(96, 132 + sel * 18, 16, 14);
+ if (!(tt & 7)) refresh(LOGO_X + 68, LOGO_Y - 2, 39, 39);
+ }
+ frame_end();
+ }
+ save();
+ return np_app_end();
+}
diff --git a/games/snake/.gitignore b/games/snake/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/snake/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/snake/Makefile b/games/snake/Makefile
new file mode 100644
index 00000000..24fc02db
--- /dev/null
+++ b/games/snake/Makefile
@@ -0,0 +1,56 @@
+# Snake — the snake game of Google's search page, with the options of All the Apps.
+# make build output/snake.nwa
+# make check link the app like the calculator does (output/snake.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/snake.nwa
+
+check: $(BUILD_DIR)/snake.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/snake.bin
+ @echo "BIN $(BUILD_DIR)/snake.bin: $$(wc -c < $(BUILD_DIR)/snake.bin) bytes"
+
+# compiled once (link-time optimization happens when linking)
+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@
+
+$(BUILD_DIR)/snake.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(BUILD_DIR)/main.o
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_snake_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_snake_main -o $@
diff --git a/games/snake/README.md b/games/snake/README.md
new file mode 100644
index 00000000..d1f511b2
--- /dev/null
+++ b/games/snake/README.md
@@ -0,0 +1,36 @@
+# Snake
+
+The snake game of Google's search page, for the NumWorks calculator: a blue snake glides over a checkered lawn, turns with round corners, looks where it goes and opens wide for apples.
+
+<img src="docs/shot.png" width="320" alt="The snake about to eat an apple on the small board">
+
+- **Smooth:** the snake moves at 60 frames a second, between cells rather than from one to the next.
+- **Options:** speed (Slow, Normal, Fast), board (Small, Medium, Large), 1, 3 or 5 apples, walls, wrapping and portals.
+- **Walls:** a new wall grows every two apples.
+- **Wrap:** leave by one edge, come back by the other.
+- **Portals:** apples come in pairs with the same colored ring. Eat one and you come out of the other, still going the same way.
+- **Best scores** for every board and speed, kept with your options.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows, or 8 4 6 2 | Turn (two turns can wait in line, and the snake never turns back on itself) |
+| OK | Start, choose |
+| Back | Pause (Resume, Restart, Quit game); back one step in menus |
+| Home | Quit |
+
+## Credits
+
+Rewritten in C for NumPlay from **[Tatone26](https://github.com/Tatone26)**'s Snake in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/snake) (All the Apps), which is released into the public domain ([UNLICENSE](UNLICENSE)). It keeps its options (speed, board size, walls every two apples, wrapping) and changes the rest:
+
+- the look and feel of Google's Snake, drawn from shapes as it goes (no images): the lawn, the blue snake with its eyes and mouth, the apples and the band with the score and best;
+- smooth movement, a two-turn input buffer, apples and walls that pop in, and a snake that stops and flashes when it crashes;
+- new options from Google's game: 3 or 5 apples, and portals;
+- a best score for each board and speed, and the options, saved as `snake.sav`.
+
+Snake itself goes back to the arcade game Blockade (Gremlin, 1976) and was made famous by Nokia's phones; the look is that of Google's Snake.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `Snake.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/snake/UNLICENSE b/games/snake/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/snake/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/snake/docs/shot.png b/games/snake/docs/shot.png
new file mode 100644
index 00000000..8a02d0f4
Binary files /dev/null and b/games/snake/docs/shot.png differ
diff --git a/games/snake/src/icon.png b/games/snake/src/icon.png
new file mode 100644
index 00000000..b48eed12
Binary files /dev/null and b/games/snake/src/icon.png differ
diff --git a/games/snake/src/main.c b/games/snake/src/main.c
new file mode 100644
index 00000000..a3fb806b
--- /dev/null
+++ b/games/snake/src/main.c
@@ -0,0 +1,744 @@
+/* Snake: the snake of Google's search page game, for the NumWorks calculator,
+ * with the options of Tatone26's Snake from All the Apps (speed, board size,
+ * walls, wrapping) and a few of Google's (more apples, portals).
+ *
+ * The snake is a chain of capsules through the centres of its cells, so it
+ * glides from cell to cell and turns with round corners. Each frame only the
+ * cells around the head, the tail and the popping apples are drawn again: one
+ * cell at a time, composed in a small buffer, then pushed. Menus are drawn in
+ * bands of 20 rows. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Snake";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+/* the keys used, in 32 bits: 4, 6, 2 and EXE come down from the high word */
+#define KEY(k) (1u << ((k) - ((k) >= 32) * 24))
+static uint32_t keys(void) {
+ uint64_t s = eadk_keyboard_scan();
+ return ((uint32_t)s & 0x800001FFu) | ((uint32_t)(s >> 32) & 0x00100850u) << 8;
+}
+
+/* Google Snake's colours */
+#define C_BAR RGB(0x4A752C) /* the band on top, and the panels */
+#define C_EDGE RGB(0x578A34) /* around the field, and the walls */
+#define C_LIGHT RGB(0xAAD751) /* the checkerboard */
+#define C_DARK RGB(0xA2D149)
+#define C_SNAKE RGB(0x4E7CF6)
+#define C_APPLE RGB(0xE7471D)
+#define C_GOLD RGB(0xFFC53D)
+#define C_PALE RGB(0xCFE6B0) /* small text on green */
+#define HDR 26 /* the band on top */
+
+/* ------------------------------------------------------------------ drawing */
+#define BUFPX (320 * 20)
+static color buf[BUFPX];
+static int rx, ry, rw, rh; /* the part of the screen in buf */
+static int kx0, ky0, kx1, ky1; /* where drawing lands, inside it */
+
+static int imin(int a, int b) { return a < b ? a : b; }
+static int imax(int a, int b) { return a > b ? a : b; }
+
+static void clip(int x, int y, int w, int h) {
+ kx0 = imax(x, rx), ky0 = imax(y, ry), kx1 = imin(x + w, rx + rw), ky1 = imin(y + h, ry + rh);
+}
+static void unclip(void) { clip(0, 0, 320, 240); }
+
+/* f over b; a from 0 (all b) to 32 (all f) */
+static color mix(color f, color b, int a) {
+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;
+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;
+ return (color)(y | y >> 16);
+}
+
+static void fill(int x, int y, int w, int h, color c) {
+ for (int j = imax(y, ky0), j1 = imin(y + h, ky1); j < j1; j++)
+ for (int i = imax(x, kx0), i1 = imin(x + w, kx1); i < i1; i++) buf[(j - ry) * rw + i - rx] = c;
+}
+
+/* A capsule from a to b, its radius going from ra to rb, with soft edges.
+ Everything round is one: discs, the snake, letters, leaves. */
+static void blob(float ax, float ay, float bx, float by, float ra, float rb, color c) {
+ float dx = bx - ax, dy = by - ay, l = dx * dx + dy * dy, inv = l > 0 ? 1 / l : 0, r = (ra > rb ? ra : rb) + 2;
+ int x0 = imax(kx0, (int)((ax < bx ? ax : bx) - r)), x1 = imin(kx1, (int)((ax > bx ? ax : bx) + r));
+ int y0 = imax(ky0, (int)((ay < by ? ay : by) - r)), y1 = imin(ky1, (int)((ay > by ? ay : by) + r));
+ for (int y = y0; y < y1; y++) {
+ float qy = y + 0.5f - ay;
+ color *p = buf + (y - ry) * rw - rx;
+ for (int x = x0; x < x1; x++) {
+ float qx = x + 0.5f - ax, t = (qx * dx + qy * dy) * inv;
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
+ float ex = qx - t * dx, ey = qy - t * dy, e = ra + (rb - ra) * t + 0.5f, d = ex * ex + ey * ey;
+ if (d >= e * e) continue;
+ float a = e - __builtin_sqrtf(d);
+ p[x] = a >= 1 ? c : mix(c, p[x], (int)(a * 32));
+ }
+ }
+}
+static void disc(float x, float y, float r, color c) { blob(x, y, x, y, r, r, c); }
+static void box(int x, int y, int w, int h, int r, color c) {
+ fill(x + r, y, w - 2 * r, h, c);
+ fill(x, y + r, w, h - 2 * r, c);
+ for (int i = 0; i < 4; i++) disc(x + r + (i & 1) * (w - 2 * r), y + r + (i >> 1) * (h - 2 * r), r, c);
+}
+/* darkens everything under the band on top, behind a panel */
+static void dim(void) {
+ clip(0, HDR, 320, 240);
+ for (int j = ky0; j < ky1; j++)
+ for (color *p = buf + (j - ry) * rw, *e = p + rw; p < e; p++) *p = mix(*p, 0, 14);
+ unclip();
+}
+
+/* ------------------------------------------------------------------ the game */
+#define MAXN (25 * 17)
+static const uint8_t BW[3] = {15, 20, 25}, BH[3] = {10, 13, 17}, CS[3] = {20, 15, 12};
+static const uint8_t STEP_MS[3] = {190, 135, 90};
+static const int8_t DX[4] = {1, 0, -1, 0}, DY[4] = {0, 1, 0, -1}; /* right, down, left, up */
+
+/* everything kept between visits (snake.sav) */
+static struct {
+ uint8_t magic, version;
+ uint8_t opt[6]; /* speed, size, apples, walls, wrap, portals */
+ uint16_t best[9]; /* per size and speed */
+} V;
+static const uint8_t OPT_N[6] = {3, 3, 3, 2, 2, 2}, OPT_DEF[6] = {1, 1, 0, 0, 0, 0};
+#define SAVE_NAME "snake.sav"
+#define O_SPEED V.opt[0]
+#define O_SIZE V.opt[1]
+#define O_APPLES V.opt[2]
+#define O_WALLS V.opt[3]
+#define O_WRAP V.opt[4]
+#define O_PORTAL V.opt[5]
+
+static int bw, bh, cs, fx, fy; /* board in cells, cell size, where the field starts */
+static uint16_t body[MAXN]; /* the snake's cells (x | y << 8), a ring from tl to hd */
+static uint8_t ndir[MAXN]; /* the direction each was entered in */
+static uint8_t occ[MAXN]; /* per cell */
+#define O_BODY 1
+#define O_WALL 2
+static int hd, tl, len, grow, score, nq, hop, otail, acc, wpop, gate[3][2]; /* gate: each pair's portals last used */
+static uint8_t q[2]; /* turns asked for, not made yet */
+static bool tmove; /* the tail left otail in the last step */
+static uint32_t now, wborn, chew_t, seed;
+
+typedef struct {
+ uint16_t p;
+ uint8_t kind; /* 0 an apple, else the pair of portals it belongs to */
+ uint8_t eat; /* being eaten: steps left before it goes */
+ bool live;
+ uint32_t born;
+} apple_t;
+static apple_t ap[8];
+
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+static int iabs(int v) { return v < 0 ? -v : v; }
+static int at(int p) { return (p >> 8) * bw + (p & 255); }
+static int step_ms(void) { return STEP_MS[O_SPEED]; }
+static uint16_t *best(void) { return &V.best[O_SIZE * 3 + O_SPEED]; }
+
+static bool far(int p, int h) { return iabs((p & 255) - (h & 255)) + iabs((p >> 8) - (h >> 8)) > 2; }
+/* a cell for an apple or a wall: free, and (first try) not right by the head,
+ or the portal it is about to come out of */
+static bool vacant(int p, int pass) {
+ if (occ[at(p)]) return false;
+ for (int i = 0; i < 8; i++)
+ if (ap[i].live && ap[i].p == p) return false;
+ return pass || (far(p, body[hd]) && (hop < 0 || far(p, hop)));
+}
+/* the n-th vacant cell, or (1 << 20) less the number of them */
+static int nth(int pass, int n) {
+ for (int y = 0; y < bh; y++)
+ for (int x = 0; x < bw; x++)
+ if (vacant(x | y << 8, pass) && !n--) return x | y << 8;
+ return n;
+}
+static int pick(void) {
+ for (int pass = 0; pass < 2; pass++) {
+ int n = (1 << 20) - nth(pass, 1 << 20);
+ if (n) return nth(pass, (int)(rnd() % (uint32_t)n));
+ }
+ return -1;
+}
+static bool spawn(int kind) {
+ int p = pick();
+ for (int i = 0; i < 8 && p >= 0; i++)
+ if (!ap[i].live) {
+ ap[i] = (apple_t){(uint16_t)p, (uint8_t)kind, 0, true, now};
+ return true;
+ }
+ return false;
+}
+
+static void new_game(void) {
+ bw = BW[O_SIZE], bh = BH[O_SIZE], cs = CS[O_SIZE];
+ fx = (320 - bw * cs) / 2, fy = HDR + (240 - HDR - bh * cs) / 2;
+ for (int i = 0; i < MAXN; i++) occ[i] = 0;
+ for (int i = 0; i < 8; i++) ap[i].live = false;
+ int row = bh / 2;
+ for (int i = 0; i < 4; i++) body[i] = (uint16_t)((1 + i) | row << 8), ndir[i] = 0, occ[row * bw + 1 + i] = O_BODY;
+ for (int i = 0; i < 6; i++) gate[i / 2][i & 1] = -1;
+ tl = 0, hd = 3, len = 4, grow = score = nq = 0, hop = wpop = -1, tmove = false, acc = step_ms();
+ chew_t = now - 1000;
+ /* the first apple straight ahead, like Google's */
+ int n = O_APPLES * 2 + 1, k = O_PORTAL;
+ ap[0] = (apple_t){(uint16_t)((bw - 5) | row << 8), (uint8_t)k, 0, true, 0};
+ if (k) {
+ spawn(1);
+ for (k = 2; k <= (n + 1) / 2; k++) spawn(k), spawn(k);
+ } else {
+ while (--n) spawn(0);
+ }
+ for (int i = 0; i < 8; i++) ap[i].born = 0; /* no popping in the menus */
+}
+
+/* One cell forward; false if the snake crashes. */
+static bool step(void) {
+ int h = body[hd], d = ndir[hd], np;
+ if (hop >= 0) { /* out of the other portal, the same way */
+ np = hop, hop = -1;
+ } else {
+ if (nq) d = q[0], q[0] = q[1], nq--;
+ int x = (h & 255) + DX[d], y = (h >> 8) + DY[d];
+ if (x < 0 || y < 0 || x >= bw || y >= bh) {
+ if (!O_WRAP) return false;
+ x = (x + bw) % bw, y = (y + bh) % bh;
+ }
+ np = x | y << 8;
+ }
+ int c = at(np);
+ bool moving = !grow;
+ if ((occ[c] & O_WALL) || ((occ[c] & O_BODY) && !(moving && np == body[tl]))) return false;
+ for (int i = 0; i < 8; i++)
+ if (ap[i].eat && !--ap[i].eat) ap[i].live = false, chew_t = now;
+ if (moving) {
+ otail = body[tl];
+ occ[at(otail)] &= (uint8_t)~O_BODY;
+ tl = (tl + 1) % MAXN, len--;
+ } else {
+ grow--;
+ }
+ tmove = moving;
+ hd = (hd + 1) % MAXN, len++;
+ body[hd] = (uint16_t)np, ndir[hd] = (uint8_t)d, occ[c] |= O_BODY;
+ for (int i = 0; i < 8; i++) {
+ apple_t *a = &ap[i];
+ if (!a->live || a->eat || a->p != np) continue;
+ a->eat = 1, score++, grow++;
+ if (a->kind) {
+ for (int j = 0; j < 8; j++)
+ if (j != i && ap[j].live && !ap[j].eat && ap[j].kind == a->kind) hop = gate[a->kind - 1][1] = ap[j].p, ap[j].eat = 2;
+ gate[a->kind - 1][0] = np;
+ if (spawn(a->kind) && !spawn(a->kind)) /* no room for two: a plain apple */
+ for (int j = 0; j < 8; j++)
+ if (ap[j].live && !ap[j].eat && ap[j].kind == a->kind) ap[j].kind = 0;
+ } else {
+ spawn(0);
+ }
+ if (O_WALLS && !(score & 1)) { /* Tatone26's walls: one more every two apples */
+ int w = pick();
+ if (w >= 0) occ[at(w)] |= O_WALL, wpop = w, wborn = now;
+ }
+ break;
+ }
+ return true;
+}
+
+/* ------------------------------------------------------------------ the board */
+enum { S_TITLE, S_SET, S_READY, S_PLAY, S_PAUSE, S_QUIT, S_DIE, S_OVER };
+static int state, sel;
+static bool dead, newbest, won;
+static float prog, mouth; /* how far into the step; how open the mouth is */
+static color scol; /* the snake's colour (it flashes when it dies) */
+static int qx0, qy0, qx1, qy1; /* the cells the drawn part of the screen touches */
+
+static int fl(int v) { return (v + cs * 16) / cs - 16; } /* floor(v / cs) */
+static bool near(int p) {
+ int x = p & 255, y = p >> 8;
+ return x >= qx0 && x <= qx1 && y >= qy0 && y <= qy1;
+}
+static float ux(int p) { return fx + (p & 255) * cs + cs * 0.5f; }
+static float uy(int p) { return fy + (p >> 8) * cs + cs * 0.5f; }
+static void cellclip(int p) { clip(fx + (p & 255) * cs, fy + (p >> 8) * cs, cs, cs); }
+static void fieldclip(void) { clip(fx, fy, bw * cs, bh * cs); }
+
+static void ground(void) {
+ for (int j = 0; j < rh; j++) {
+ int y = ry + j, cy = fl(y - fy), cx = fl(rx - fx), e = fx + cx * cs + cs;
+ bool in = y >= HDR && cy >= 0 && cy < bh;
+ color *p = buf + j * rw;
+ for (int i = 0; i < rw; i++) {
+ if (rx + i >= e) cx++, e += cs;
+ p[i] = y < HDR ? C_BAR : in && cx >= 0 && cx < bw ? ((cx + cy) & 1 ? C_DARK : C_LIGHT) : C_EDGE;
+ }
+ }
+}
+
+static color checker(int p) { return ((p & 255) + (p >> 8)) & 1 ? C_DARK : C_LIGHT; }
+
+/* an apple of s pixels centred on (x, y); a portal has a ring in its pair's
+ colour (and only the ring once it is in use: kind | 8) */
+static const uint32_t ring[3] = {0x9A5CF6, 0xFF8A1E, 0x1EB8E8};
+static void apple(float x, float y, float s, int kind, color bg) {
+ if (kind) { /* a ring, and a smaller apple in it */
+ disc(x, y, s * 0.5f, RGB(ring[(kind & 3) - 1]));
+ disc(x, y, s * 0.35f, bg);
+ if (kind & 8) return;
+ s *= 0.72f;
+ }
+ blob(x + s * 0.02f, y - s * 0.2f, x + s * 0.08f, y - s * 0.42f, s * 0.05f, s * 0.04f, RGB(0x6D4C2F));
+ disc(x, y + s * 0.05f, s * 0.37f, C_APPLE);
+ disc(x - s * 0.14f, y - s * 0.05f, s * 0.09f, RGB(0xF58A67));
+ blob(x + s * 0.1f, y - s * 0.34f, x + s * 0.33f, y - s * 0.44f, s * 0.09f, s * 0.035f, RGB(0x4E9F2D));
+}
+
+static float ease(uint32_t born, int ms) { /* 0 to 1 with a little overshoot */
+ int a = (int)(now - born);
+ if (a >= ms) return 1;
+ float t = (float)a / ms - 1;
+ return 1 + t * t * (2.70158f * t + 1.70158f);
+}
+
+static void items(void) {
+ for (int y = imax(qy0, 0); y <= imin(qy1, bh - 1); y++)
+ for (int x = imax(qx0, 0); x <= imin(qx1, bw - 1); x++)
+ if (occ[y * bw + x] & O_WALL) { /* a block of hedge */
+ int p = x | y << 8, m = (int)(cs * (1 - (p == wpop ? ease(wborn, 300) : 1)) / 2) + 1, w = cs - 2 * m;
+ int bx = fx + x * cs + m, by = fy + y * cs + m;
+ box(bx, by, w, w, cs / 5, RGB(0x3D6624));
+ box(bx, by, w, w - cs / 7 - 1, cs / 5, C_EDGE);
+ }
+ for (int i = 0; i < 6; i++) { /* portals the snake is going through: a dark hole under it */
+ int g = gate[i / 2][i & 1];
+ if (g >= 0 && near(g) && (occ[at(g)] & O_BODY)) disc(ux(g), uy(g), cs * 0.36f, mix(RGB(ring[i / 2]), 0, 16));
+ }
+ for (int i = 0; i < 8; i++) {
+ apple_t *a = &ap[i];
+ if (a->live && near(a->p)) apple(ux(a->p), uy(a->p), cs * ease(a->born, 260), a->kind, checker(a->p));
+ }
+}
+
+/* the rings of portals the snake is going through, over it: it goes into
+ one and comes out of the other */
+static void rings(void) {
+ for (int i = 0; i < 6; i++) {
+ int g = gate[i / 2][i & 1];
+ if (g < 0 || !near(g) || !(occ[at(g)] & O_BODY)) continue;
+ float c = 1, sn = 0, r = cs * 0.43f;
+ for (int k = 0; k < 16; k++) { /* 16 dots around, turning by 22.5 degrees */
+ disc(ux(g) + c * r, uy(g) + sn * r, cs * 0.085f, RGB(ring[i / 2]));
+ float c2 = c * 0.92388f - sn * 0.38268f;
+ sn = sn * 0.92388f + c * 0.38268f, c = c2;
+ }
+ }
+}
+
+/* The head at (x, y), looking along (ax, ay), r its radius: an open mouth,
+ and eyes that look where it goes. */
+static void face(float x, float y, float ax, float ay, float r) {
+ if (mouth > 0.05f) {
+ float mx = x + ax * r * 0.5f, my = y + ay * r * 0.5f, w = r * 0.45f * mouth, m = r * 0.42f * mouth;
+ blob(mx - ay * w, my + ax * w, mx + ay * w, my - ax * w, m, m, RGB(0x7A1F1A));
+ }
+ for (int s = -1; s <= 1; s += 2) {
+ float ex = x - ax * r * 0.1f - ay * r * 0.5f * s, ey = y - ay * r * 0.1f + ax * r * 0.5f * s, k = r * 0.22f;
+ disc(ex, ey, r * 0.47f, WHITE);
+ if (dead) {
+ blob(ex - k, ey - k, ex + k, ey + k, r * 0.07f, r * 0.07f, 0);
+ blob(ex - k, ey + k, ex + k, ey - k, r * 0.07f, r * 0.07f, 0);
+ } else {
+ disc(ex + ax * r * 0.2f, ey + ay * r * 0.2f, r * 0.25f, RGB(0x1B1B1B));
+ }
+ }
+}
+
+static float rad(float s) { return cs * (s >= 1.5f ? 0.41f : 0.25f + 0.107f * s); } /* thinner near the tail */
+
+/* The snake from cell a to cell b (entered going d), from u0 to u1 of the
+ way. Across an edge (wrapping) or a portal, a and b are not side by side:
+ each gets its own half, cut at its cell's border. */
+static void piece(int a, int b, int d, float u0, float u1, float r0, float r1) {
+ float sx = DX[d] * cs, sy = DY[d] * cs, ax = ux(a), ay = uy(a);
+ bool side = (a & 255) + DX[d] == (b & 255) && (a >> 8) + DY[d] == (b >> 8);
+ if (!side) cellclip(a);
+ blob(ax + sx * u0, ay + sy * u0, ax + sx * u1, ay + sy * u1, r0, r1, scol);
+ if (side) return;
+ ax = ux(b) - sx, ay = uy(b) - sy;
+ cellclip(b);
+ blob(ax + sx * u0, ay + sy * u0, ax + sx * u1, ay + sy * u1, r0, r1, scol);
+ fieldclip();
+}
+
+static void snake(void) {
+ fieldclip();
+ float p = prog, s = tmove ? 1 - p : 0;
+ int k = tl;
+ if (tmove && (near(otail) || near(body[tl]))) piece(otail, body[tl], ndir[tl], p, 1, rad(0), rad(s));
+ for (int i = 0; i < len - 1; i++) {
+ int k1 = (k + 1) % MAXN;
+ float u = i == len - 2 ? p : 1;
+ if (near(body[k]) || near(body[k1])) piece(body[k], body[k1], ndir[k1], 0, u, rad(s + i), rad(s + i + u));
+ k = k1;
+ }
+ int h = body[hd], b = body[(hd + MAXN - 1) % MAXN], d = ndir[hd], d0 = ndir[(hd + MAXN - 1) % MAXN];
+ if (near(h) || near(b)) {
+ /* the head turns over the first third of a step */
+ float w = p * 3 > 1 ? 1 : p * 3, ax = DX[d0] + (DX[d] - DX[d0]) * w, ay = DY[d0] + (DY[d] - DY[d0]) * w;
+ float n = 1 / __builtin_sqrtf(ax * ax + ay * ay), r = cs * 0.41f;
+ bool side = (b & 255) + DX[d] == (h & 255) && (b >> 8) + DY[d] == (h >> 8);
+ if (!side) cellclip(h);
+ face(ux(h) - DX[d] * cs * (1 - p), uy(h) - DY[d] * cs * (1 - p), ax * n, ay * n, r);
+ if (!side) {
+ cellclip(b);
+ face(ux(b) + DX[d] * cs * p, uy(b) + DY[d] * cs * p, ax * n, ay * n, r);
+ }
+ }
+ unclip();
+}
+
+/* ------------------------------------------------------------------ text and panels */
+static int pass, ty0, ty1; /* 0: shapes into buf; 1: the text whose last row is in ty0..ty1 */
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static void lab(const char *s, int x, int y, int large, color fg, color bg) {
+ int b = y + (large ? 17 : 13);
+ if (pass && b >= ty0 && b < ty1) eadk_display_draw_string(s, (eadk_point_t){(uint16_t)x, (uint16_t)y}, large, fg, bg);
+}
+static void clab(const char *s, int cx, int y, int large, color fg, color bg) {
+ lab(s, cx - slen(s) * (large ? 10 : 7) / 2, y, large, fg, bg);
+}
+static void button(const char *s, int x, int y, int w, int h, bool on) {
+ color c = on ? C_SNAKE : C_EDGE;
+ if (!pass) box(x, y, w, h, h / 2, c);
+ clab(s, x + w / 2, y + (h - 18) / 2, 1, WHITE, c);
+}
+/* n buttons from names[0], the first at (x, y), the others dx, dy further */
+static void buttons(const char *const *names, int n, int x, int y, int w, int dx, int dy) {
+ for (int i = 0; i < n; i++) button(names[i], x + i * dx, y + i * dy, w, 32, sel == i);
+}
+static const char *const BUTTONS[] = {"Play", "Settings", "Resume", "Restart", "Quit game", "No", "Yes", "Play", "Menu"};
+static void panel(int x, int y, int w, int h) {
+ if (pass) return;
+ dim();
+ box(x, y + 3, w, h, 14, RGB(0x2A4A18));
+ box(x, y, w, h, 14, C_BAR);
+}
+static char *itoa(char *o, int v) {
+ char t[8];
+ int n = 0;
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+
+static void trophy(float x, float y, float k, color bg) {
+ for (int s = -1; s <= 1; s += 2) {
+ disc(x + 6 * k * s, y - 4 * k, 3 * k, C_GOLD);
+ disc(x + 6 * k * s, y - 4 * k, 1.4f * k, bg);
+ }
+ clip(0, (int)(y - 7 * k), 320, 240);
+ blob(x, y - 7 * k, x, y, 7 * k, 2 * k, C_GOLD);
+ unclip();
+ fill((int)(x - k), (int)(y), (int)(2 * k + 1), (int)(4 * k), C_GOLD);
+ box((int)(x - 5 * k), (int)(y + 3 * k), (int)(10 * k), (int)(3 * k), (int)k, C_GOLD);
+}
+
+/* SNAKE in the snake's own tube: points x << 4 | y on a 4 x 8 grid, 0xF0 lifts
+ the pen, 0xF1 goes to the next letter */
+static const uint8_t LOGO[] = {
+ 0x41, 0x30, 0x10, 0x01, 0x03, 0x14, 0x34, 0x45, 0x47, 0x38, 0x18, 0x07, 0xF1,
+ 0x08, 0x00, 0x48, 0x40, 0xF1,
+ 0x08, 0x02, 0x20, 0x42, 0x48, 0xF0, 0x05, 0x45, 0xF1,
+ 0x00, 0x08, 0xF0, 0x40, 0x04, 0x48, 0xF1,
+ 0x40, 0x00, 0x08, 0x48, 0xF0, 0x04, 0x34,
+};
+static void logo(int x, int y) {
+ for (int k = 0; k < 2; k++) { /* a shadow, then the snake */
+ float px = 0, py = 0, u = 4.5f;
+ int lx = x, ly = y + 3 - 3 * k;
+ bool pen = false;
+ for (unsigned i = 0; i < sizeof LOGO; i++) {
+ int c = LOGO[i];
+ if (c >= 0xF0) {
+ pen = false, lx += c & 1 ? 30 : 0;
+ continue;
+ }
+ float nx = lx + (c >> 4) * u, ny = ly + (c & 15) * u;
+ if (pen) blob(px, py, nx, ny, 4.6f, 4.6f, k ? C_SNAKE : RGB(0x2A4A18));
+ px = nx, py = ny, pen = true;
+ }
+ }
+ disc(x + 19, y + 4.5f, 6.5f, C_SNAKE); /* the head, on the S */
+ mouth = 0, dead = false;
+ face(x + 20, y + 4.5f, 1, 0, 6.5f);
+}
+
+static const char *const OPT_NAME[6] = {"Speed", "Size", "Apples", "Walls", "Wrap", "Portals"};
+static const char *const OPT_VAL[] = {"Slow", "Normal", "Fast", "Small", "Medium", "Large", "1", "3", "5", "Off", "On"};
+
+/* the band on top, and the panel of the moment */
+static void ui(void) {
+ char t[8];
+ if (!pass) apple(15, 13, 24, 0, C_BAR), trophy(84, 13, 1, C_BAR);
+ itoa(t, score);
+ lab(t, 30, 4, 1, WHITE, C_BAR);
+ itoa(t, *best());
+ lab(t, 98, 4, 1, WHITE, C_BAR);
+ switch (state) {
+ case S_READY: /* the arrow keys, until the first move */
+ if (pass) break;
+ box(116, 104, 88, 58, 10, C_BAR);
+ for (int d = 0; d < 4; d++) {
+ int x = 160 + DX[d] * 26, y = d == 3 ? 119 : 146;
+ box(x - 11, y - 11, 22, 22, 5, RGB(0xE4EEDA));
+ for (int t = 0, a; (a = 5 - t) >= 0; t++) /* a triangle, one line at a time */
+ fill(x + DX[d] * (t - 2) - a * !DX[d], y + DY[d] * (t - 2) - a * !DY[d], DX[d] ? 1 : 2 * a + 1, DX[d] ? 2 * a + 1 : 1, C_BAR);
+ }
+ break;
+ case S_TITLE:
+ panel(46, 42, 228, 176);
+ if (!pass) {
+ logo(70, 56);
+ apple(238, 72, 34, 0, C_BAR);
+ }
+ buttons(BUTTONS, 2, 85, 114, 150, 0, 42);
+ clab("Based on Tatone26's version", 160, 196, 0, C_PALE, C_BAR);
+ break;
+ case S_SET:
+ panel(28, 34, 264, 200);
+ clab("Settings", 160, 44, 1, WHITE, C_BAR);
+ for (int i = 0; i < 6; i++) {
+ int y = 70 + i * 26, on = sel == i;
+ color c = on ? C_SNAKE : C_BAR;
+ if (on && !pass) box(40, y, 240, 24, 12, C_SNAKE);
+ lab(OPT_NAME[i], 54, y + 3, 1, WHITE, c);
+ clab(OPT_VAL[(i < 3 ? i * 3 : 9) + V.opt[i]], 226, y + 3, 1, WHITE, c);
+ if (on) lab("<", 174, y + 3, 1, WHITE, c), lab(">", 268, y + 3, 1, WHITE, c);
+ }
+ break;
+ case S_PAUSE:
+ panel(80, 54, 160, 160);
+ clab("Paused", 160, 66, 1, WHITE, C_BAR);
+ buttons(BUTTONS + 2, 3, 95, 94, 130, 0, 40);
+ break;
+ case S_QUIT:
+ panel(80, 76, 160, 100);
+ clab("Quit game?", 160, 92, 1, WHITE, C_BAR);
+ buttons(BUTTONS + 5, 2, 94, 127, 62, 70, 0);
+ break;
+ case S_OVER:
+ panel(64, 54, 192, 140);
+ if (!pass) apple(104, 88, 36, 0, C_BAR), trophy(190, 88, 1.6f, C_BAR);
+ itoa(t, score);
+ lab(t, 126, 79, 1, WHITE, C_BAR);
+ itoa(t, *best());
+ lab(t, 212, 79, 1, WHITE, C_BAR);
+ if (won || newbest) clab(won ? "You win!" : "New best!", 160, 114, 1, C_GOLD, C_BAR);
+ buttons(BUTTONS + 7, 2, 78, 147, 80, 84, 0);
+ break;
+ }
+}
+
+/* Draws a part of the screen, band by band; text comes right after the band
+ that holds its last row. */
+static void area(int x, int y, int w, int h) {
+ int band = BUFPX / w;
+ for (int y0 = y; y0 < y + h; y0 += band) {
+ rx = x, ry = y0, rw = w, rh = imin(band, y + h - y0);
+ qx0 = fl(rx - fx), qx1 = fl(rx + rw - 1 - fx), qy0 = fl(ry - fy), qy1 = fl(ry + rh - 1 - fy);
+ unclip();
+ ground();
+ items();
+ snake();
+ rings();
+ pass = 0;
+ ui();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)rx, (uint16_t)ry, (uint16_t)rw, (uint16_t)rh}, buf);
+ if (w == 320) pass = 1, ty0 = ry, ty1 = ry + rh, ui();
+ }
+}
+
+/* In play: only the cells that change, and those that changed last time
+ (so they are left in their final state). */
+static uint16_t dcur[24], dprev[24];
+static int ncur, nprev;
+static void mark(int p) {
+ for (int i = 0; i < ncur; i++)
+ if (dcur[i] == p) return;
+ if (ncur < 24) dcur[ncur++] = (uint16_t)p;
+}
+static void cells(void) {
+ ncur = 0;
+ for (int i = 0; i < 3 && i < len; i++) mark(body[(hd + MAXN - i) % MAXN]), mark(body[(tl + i) % MAXN]);
+ if (tmove) mark(otail);
+ for (int i = 0; i < 8; i++)
+ if (ap[i].live && (ap[i].eat || (int)(now - ap[i].born) < 300)) mark(ap[i].p);
+ if (wpop >= 0 && (int)(now - wborn) < 350) mark(wpop);
+ int n = ncur;
+ for (int i = 0; i < nprev; i++) mark(dprev[i]);
+ for (int i = 0; i < ncur; i++) {
+ int p = dcur[i];
+ area(fx + (p & 255) * cs, fy + (p >> 8) * cs, cs, cs);
+ }
+ for (nprev = 0; nprev < n; nprev++) dprev[nprev] = dcur[nprev]; /* only this frame's own */
+}
+
+static void save(void) {
+ V.magic = 'S', V.version = 1;
+ ef_write(SAVE_NAME, &V, sizeof V);
+}
+
+/* the arrow keys, or 6 2 4 8, as directions */
+static const uint32_t DIR_KEYS[4] = {KEY(eadk_key_right) | KEY(eadk_key_six), KEY(eadk_key_down) | KEY(eadk_key_two),
+ KEY(eadk_key_left) | KEY(eadk_key_four), KEY(eadk_key_up) | KEY(eadk_key_eight)};
+
+int main(void) {
+ np_app_begin();
+ now = eadk_timing_millis();
+ seed = eadk_random() ^ now ^ 0x9E3779B9u;
+ if (!seed) seed = 1;
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ if (d && n == sizeof V && d[0] == 'S' && d[1] == 1) {
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&V)[i] = d[i];
+ for (int i = 0; i < 9; i++)
+ if (V.best[i] > MAXN) V.best[i] = 0;
+ }
+ for (int i = 0; i < 6; i++)
+ if (!d || V.opt[i] >= OPT_N[i]) V.opt[i] = OPT_DEF[i];
+ new_game();
+ state = S_TITLE, scol = C_SNAKE;
+ bool full = true, hdr = false, dirty = false;
+ int resume = S_PLAY, flash = -1;
+ uint32_t last = now, die_t = 0, rep_t = 0;
+ uint32_t held = keys();
+ for (;;) {
+ now = eadk_timing_millis();
+ int dt = (int)(now - last);
+ dt = dt < 0 ? 0 : dt > 100 ? 100 : dt;
+ last = now;
+ uint32_t k = keys(), edge = k & ~held, hit = edge, arrows = DIR_KEYS[0] | DIR_KEYS[1] | DIR_KEYS[2] | DIR_KEYS[3];
+ held = k;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ int dk = -1; /* a direction, repeated while held (menus) */
+ if (hit & arrows) rep_t = now + 350;
+ else if ((k & arrows) && (int)(now - rep_t) >= 0) hit |= k & arrows, rep_t = now + 90;
+ for (int i = 3; i >= 0; i--)
+ if (hit & DIR_KEYS[i]) dk = i;
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back), redraw = true;
+ switch (state) {
+ case S_TITLE:
+ if (dk == 1 || dk == 3) sel ^= 1;
+ else if (ok) state = sel ? S_SET : S_READY, sel = 0;
+ else if (back) resume = S_TITLE, state = S_QUIT, sel = 0; /* "Quit game?" from the title */
+ else redraw = false;
+ break;
+ case S_SET:
+ if (dk == 1 || dk == 3) {
+ sel = (sel + (dk == 1 ? 1 : 5)) % 6;
+ } else if (dk == 0 || dk == 2) {
+ V.opt[sel] = (uint8_t)((V.opt[sel] + (dk ? OPT_N[sel] - 1 : 1)) % OPT_N[sel]);
+ new_game(), dirty = true;
+ } else if (ok || back) {
+ state = S_TITLE, sel = 1;
+ if (dirty) save(), dirty = false;
+ } else {
+ redraw = false;
+ }
+ break;
+ case S_READY:
+ case S_PLAY:
+ redraw = false;
+ if (back) {
+ resume = state, state = S_PAUSE, sel = 0, redraw = true;
+ break;
+ }
+ for (int i = 0; i < 4; i++) { /* up to two turns ahead, never straight back */
+ int l = nq ? q[nq - 1] : ndir[hd];
+ if ((edge & DIR_KEYS[i]) && nq < 2 && i != l && i != (l ^ 2)) q[nq++] = (uint8_t)i;
+ }
+ if (state == S_READY) {
+ if (!nq && !(edge & (arrows | KEY(eadk_key_ok) | KEY(eadk_key_exe)))) break;
+ state = S_PLAY, full = true;
+ }
+ int ate = score;
+ bool crash = false, left = false;
+ for (acc += dt; acc >= step_ms() && !crash; acc -= step_ms()) crash = !step();
+ hdr |= score != ate;
+ for (int i = 0; i < 8; i++) left |= ap[i].live && !ap[i].eat;
+ if (crash || !left) { /* crashed, or no room left for an apple: the board is full */
+ state = S_DIE, die_t = now, acc = step_ms(), dead = crash, won = !crash, newbest = score > *best();
+ if (newbest) *best() = (uint16_t)score, save();
+ }
+ break;
+ case S_PAUSE:
+ if (dk == 1 || dk == 3) sel = (sel + (dk == 1 ? 1 : 2)) % 3;
+ else if (back || (ok && !sel)) state = S_READY; /* it waits for a key: no surprise start */
+ else if (ok && sel == 1) new_game(), state = S_READY;
+ else if (ok) state = S_QUIT, sel = 0;
+ else redraw = false;
+ break;
+ case S_QUIT:
+ if (dk == 0 || dk == 2) sel ^= 1;
+ else if (ok && sel) goto quit;
+ else if (ok || back) state = resume == S_TITLE ? S_TITLE : S_PAUSE, sel = resume == S_TITLE ? 0 : 2;
+ else redraw = false;
+ break;
+ case S_DIE:
+ redraw = (int)(now - die_t) > 1100;
+ if (redraw) state = S_OVER, sel = 0, scol = C_SNAKE;
+ break;
+ case S_OVER:
+ if (dk == 0 || dk == 2) sel ^= 1;
+ else if (ok || back) state = ok && !sel ? S_READY : S_TITLE, sel = 0, new_game();
+ else redraw = false;
+ break;
+ }
+ if (state != S_DIE && state != S_OVER) dead = won = false;
+ full |= redraw;
+ prog = (float)acc / step_ms();
+ if (prog > 1) prog = 1;
+ /* the mouth opens on an apple just ahead, and shuts after a bite */
+ int h = body[hd], ahead = ((h & 255) + DX[ndir[hd]]) | ((h >> 8) + DY[ndir[hd]]) << 8;
+ mouth = 1 - (int)(now - chew_t) / 160.0f;
+ for (int i = 0; i < 8; i++)
+ if (ap[i].live && (ap[i].p == h || (ap[i].p == ahead && !ap[i].eat && prog > mouth))) mouth = ap[i].p == h ? 1 : prog;
+ if (dead) mouth = 0;
+ eadk_display_wait_for_vblank();
+ if (full) {
+ area(0, 0, 320, 240);
+ full = hdr = false, nprev = 0, flash = -1;
+ } else if (state == S_DIE) {
+ int f = (int)(now - die_t) / 150;
+ if (f != flash && f < 7) { /* the snake flashes */
+ flash = f, scol = f & 1 ? RGB(0xC9D8FF) : C_SNAKE;
+ area(0, HDR, 320, 240 - HDR);
+ }
+ } else if (state == S_PLAY || state == S_READY) {
+ if (hdr) area(0, 0, 320, HDR), hdr = false;
+ cells();
+ }
+ uint32_t spent = (uint32_t)eadk_timing_millis() - now;
+ if (spent < 16) eadk_timing_msleep(16 - spent);
+ }
+quit:
+ if (dirty) save();
+ return np_app_end();
+}
diff --git a/games/solitaire/.gitignore b/games/solitaire/.gitignore
new file mode 100644
index 00000000..ea1472ec
--- /dev/null
+++ b/games/solitaire/.gitignore
@@ -0,0 +1 @@
+output/
diff --git a/games/solitaire/Makefile b/games/solitaire/Makefile
new file mode 100644
index 00000000..da104886
--- /dev/null
+++ b/games/solitaire/Makefile
@@ -0,0 +1,56 @@
+# Solitaire — Klondike like Windows Solitaire.
+# make build output/solitaire.nwa
+# make check link the app like the calculator does (output/solitaire.bin)
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h ../common/jump.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean
+build: $(BUILD_DIR)/solitaire.nwa
+
+check: $(BUILD_DIR)/solitaire.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/solitaire.bin
+ @echo "BIN $(BUILD_DIR)/solitaire.bin: $$(wc -c < $(BUILD_DIR)/solitaire.bin) bytes"
+
+# compiled once to link-time-optimization bytecode, then linked for each target
+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@
+
+$(BUILD_DIR)/solitaire.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR)
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module.o: $(BUILD_DIR)/main.o
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -Dmain=np_solitaire_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_solitaire_main -o $@
diff --git a/games/solitaire/README.md b/games/solitaire/README.md
new file mode 100644
index 00000000..81d2d726
--- /dev/null
+++ b/games/solitaire/README.md
@@ -0,0 +1,48 @@
+# Solitaire
+
+Klondike for the NumWorks calculator, the way Windows Solitaire plays it: green felt, the blue lattice card backs, Draw One or Draw Three, Standard or Vegas scoring, and the famous ending where the cards bounce off the bottom of the screen.
+
+<img src="docs/shot.png" width="320" alt="A game in progress">
+
+- **Windows rules:** draw 1, 2 or 3 cards (Easy, Normal, Hard), and Standard, Vegas or no scoring. Vegas starts at -$52, pays $5 a card and limits the passes through the deck (as many as the cards you draw); **Keep score** adds your Vegas games up.
+- **Timed game:** the clock starts with your first move. In Standard scoring you lose 2 points every 10 seconds, and a fast win earns Windows' bonus (700,000 divided by your time).
+- **Help when you want it:** unlimited Undo, a Hint, OK twice to send a card up like a double click, a key that plays everything it can to the foundations, and an automatic finish once every card is face up.
+- **Saved as you go:** leave in the middle of a game and continue it later. Statistics count your games, wins, streaks, best time, best score and your Vegas bank.
+
+Every card is drawn from a few tiny bitmaps (pips, court figures and one small font), and only what changes is redrawn, so the whole game is about 15 KB.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows | Move |
+| Up / Down on a column | Pick up more or fewer cards |
+| OK | Pick up, put down (on the deck: draw) |
+| OK twice | Send the card to a foundation |
+| EXE | Draw from the deck |
+| Toolbox | Play all you can to the foundations |
+| ⌫ | Undo |
+| Shift | Hint |
+| Back | Put the cards back, or pause |
+
+Picked-up cards turn dark, like a selection in Windows. When you put a run down, the game finds how many cards fit there.
+
+## Scoring
+
+| Move | Standard | Vegas |
+| --- | --- | --- |
+| To a foundation | +10 | +$5 |
+| Waste to a column | +5 | |
+| Turning a card over | +5 | |
+| Foundation back to a column | -15 | -$5 |
+| Recycling the deck | -100 (draw 1), -20 after 3 passes | not after the last pass |
+
+## Credits
+
+Rewritten in C for NumPlay from Tatone26's Solitaire in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/solitaire) (All the Apps), released into the public domain ([UNLICENSE](UNLICENSE)). It keeps that version's Difficulty option (how many cards you draw) and adds the Windows look, the deal and win animations, Standard and Vegas scoring, the clock, Undo, Hint, the automatic finish and statistics.
+
+The look and the rules follow Microsoft's Windows Solitaire (Wes Cherry, with cards by Susan Kare).
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `Solitaire.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink).
diff --git a/games/solitaire/UNLICENSE b/games/solitaire/UNLICENSE
new file mode 100644
index 00000000..fdddb29a
--- /dev/null
+++ b/games/solitaire/UNLICENSE
@@ -0,0 +1,24 @@
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/games/solitaire/docs/shot.png b/games/solitaire/docs/shot.png
new file mode 100644
index 00000000..9a4ccb86
Binary files /dev/null and b/games/solitaire/docs/shot.png differ
diff --git a/games/solitaire/src/icon.png b/games/solitaire/src/icon.png
new file mode 100644
index 00000000..117febdd
Binary files /dev/null and b/games/solitaire/src/icon.png differ
diff --git a/games/solitaire/src/main.c b/games/solitaire/src/main.c
new file mode 100644
index 00000000..6b852630
--- /dev/null
+++ b/games/solitaire/src/main.c
@@ -0,0 +1,1261 @@
+/* Solitaire: Klondike, the way Windows Solitaire plays it, for the NumWorks
+ * calculator. Rewritten in C for NumPlay from Tatone26's Solitaire in All the
+ * Apps, which is in the public domain.
+ *
+ * The table is drawn only where something changed: each changed rectangle is
+ * composed in a small buffer, strip by strip, and pushed once, so nothing
+ * flickers. Cards, pips and court figures come from a few tiny bitmaps. */
+#include <eadk.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "../../common/jump.h"
+
+#ifdef __ELF__ /* app name and API level, for the calculator's installer */
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Solitaire";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+typedef uint16_t color;
+#define RGB(c) (color)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define BLACK 0
+#define FELT RGB(0x008000)
+#define SLOT RGB(0x003800)
+#define RED RGB(0xD00000)
+#define FACE RGB(0xC0C0C0)
+#define LIGHT RGB(0xDFDFDF)
+#define SHADOW RGB(0x808080)
+#define NAVY RGB(0x000080)
+#define GOLD RGB(0xFFD800)
+#define KEY(k) (1ull << (k))
+
+/* ------------------------------------------------------------------ art */
+/* art begin */
+/* suits: spades, hearts, clubs, diamonds (left half and middle column of each row) */
+static const uint8_t pip7[4][7] = {{0x01,0x03,0x07,0x0F,0x06,0x01,0x03}, {0x06,0x0F,0x0F,0x0F,0x07,0x03,0x01}, {0x03,0x03,0x06,0x0F,0x06,0x01,0x03}, {0x01,0x03,0x07,0x0F,0x07,0x03,0x01}};
+static const uint8_t pip13[4][15] = {
+ {0x01,0x03,0x07,0x0F,0x1F,0x3F,0x7F,0x7F,0x7F,0x3D,0x19,0x01,0x03,0x0F,0x00},
+ {0x00,0x38,0x7C,0x7E,0x7F,0x7F,0x7F,0x7F,0x3F,0x1F,0x0F,0x07,0x03,0x01,0x00},
+ {0x00,0x03,0x07,0x07,0x07,0x33,0x79,0x7F,0x7F,0x79,0x31,0x01,0x03,0x0F,0x00},
+ {0x01,0x03,0x07,0x07,0x0F,0x1F,0x3F,0x7F,0x3F,0x1F,0x0F,0x07,0x07,0x03,0x01}};
+/* court figures, top half, 22x16 at 3 bits a pixel (see court()) */
+static const uint8_t figs[3][133] = {
+ {0x00,0x00,0x20,0x49,0x92,0x04,0x00,0x00,0x00,0x00,0x10,0x49,0x92,0xA4,0x00,0x40,0x00,0x00,0x88,0x24,0x49,0x92,0x94,0x84,0x01,0x00,0x20,0x24,0x49,0x92,0x64,0x48,0x06,0x00,0x00,0xE4,0x6D,0xDB,0x3E,0x48,0x02,0x00,0x00,0xF0,0x37,0x6D,0x7A,0x00,0x00,0x00,0x00,0xC0,0xDF,0xB6,0xED,0x01,0x00,0x00,0x00,0x00,0x7F,0xDB,0xB6,0x05,0x00,0x00,0x00,0x00,0xFC,0xAD,0xA4,0x16,0x00,0x00,0x00,0x00,0x80,0xBF,0x6D,0x0B,0x00,0x01,0x00,0x00,0x00,0x90,0xB6,0x0D,0x80,0x30,0x00,0x00,0x00,0xD9,0x48,0x72,0x0B,0xC2,0x00,0x00,0x80,0x6C,0x1B,0xB9,0x6D,0x09,0x03,0x00,0x40,0x36,0x69,0xDB,0xA4,0x2D,0x0C,0x00,0x20,0x9B,0x24,0xCD,0x9E,0xA4,0x85,0x01,0x80,0x6C,0x93,0x36,0x7B,0x93,0x16,0x06},
+ {0x00,0x00,0x00,0x41,0x12,0x04,0x00,0x00,0x00,0x00,0x00,0x84,0x49,0x18,0x00,0x00,0x00,0x00,0x00,0x1E,0x92,0x64,0x0E,0x00,0x00,0x00,0x00,0x7F,0x92,0x24,0xF9,0x01,0x00,0x00,0x00,0xFC,0x6D,0xDB,0xB6,0x3F,0x00,0x00,0x00,0xFE,0x37,0x6D,0xD3,0xFF,0x00,0x00,0x00,0xF8,0xDF,0xB6,0x6D,0xFB,0x1F,0x00,0x00,0xE0,0x7F,0x5B,0xB5,0xED,0x7F,0x00,0x00,0x80,0xFF,0x6F,0xDB,0xF6,0xFF,0x41,0x00,0x00,0xF0,0x3F,0x6D,0x1B,0xFC,0xA0,0x08,0x00,0x40,0x42,0xB6,0x2D,0x99,0x00,0x04,0x00,0x20,0x92,0x48,0x92,0x94,0x14,0x04,0x00,0x10,0x49,0x93,0x48,0x69,0x92,0x12,0x00,0x88,0xA4,0x6D,0x92,0xB4,0x4D,0x52,0x00,0x44,0xD2,0x66,0x7B,0xB3,0xBD,0x49,0x0A,0x10,0x69,0x9B,0xED,0xCD,0xF6,0x36,0x29},
+ {0x00,0x00,0x00,0x41,0x10,0x04,0x00,0x00,0x00,0x00,0x00,0x84,0x61,0x18,0x00,0x00,0x00,0x00,0x00,0x10,0x92,0x64,0x00,0x00,0x00,0x00,0x00,0x40,0x28,0x8E,0x01,0x00,0x00,0x00,0x00,0x20,0x49,0x92,0x24,0x00,0x00,0x00,0x00,0x80,0xBC,0x6D,0xDB,0x07,0x00,0x00,0x00,0x00,0xDE,0xB4,0xE9,0x11,0x00,0x00,0x00,0x00,0x78,0xDB,0xB6,0x3D,0x02,0x00,0x00,0x00,0xFC,0x6D,0xD3,0xF6,0x47,0x00,0x00,0x00,0xF0,0xBF,0x92,0xFA,0x1F,0x01,0x00,0x00,0xC0,0xFF,0xFF,0xFF,0xFF,0x24,0x00,0x00,0x20,0xDB,0xFF,0xFF,0xDF,0xC2,0x00,0x00,0x90,0x6D,0xFC,0xFF,0x73,0x5B,0x02,0x00,0xC8,0xA6,0x8D,0x24,0xB9,0x69,0x0B,0x00,0x64,0x93,0xB4,0xD9,0xDE,0x24,0x6D,0x01,0x90,0x6D,0xDA,0x66,0x7B,0x9B,0xB6,0x05}};
+/* art end */
+
+/* ASCII 32..122 (space to z), columns of 7 bits, top bit first */
+static const uint8_t font[91][5] = {
+ {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x07,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14},
+ {0x24,0x2A,0x7F,0x2A,0x12},{0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00},
+ {0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},{0x14,0x08,0x3E,0x08,0x14},{0x08,0x08,0x3E,0x08,0x08},
+ {0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},{0x20,0x10,0x08,0x04,0x02},
+ {0x3E,0x41,0x41,0x41,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31},
+ {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03},
+ {0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00},
+ {0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06},
+ {0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22},
+ {0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x09,0x01},{0x3E,0x41,0x49,0x49,0x7A},
+ {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41},
+ {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x02,0x0C,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E},
+ {0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31},
+ {0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},{0x3F,0x40,0x38,0x40,0x3F},
+ {0x63,0x14,0x08,0x14,0x63},{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},{0x00,0x7F,0x41,0x41,0x00},
+ {0x02,0x04,0x08,0x10,0x20},{0x00,0x41,0x41,0x7F,0x00},{0x04,0x02,0x01,0x02,0x04},{0x40,0x40,0x40,0x40,0x40},
+ {0x00,0x01,0x02,0x04,0x00},{0x20,0x54,0x54,0x54,0x78},{0x7F,0x48,0x44,0x44,0x38},{0x38,0x44,0x44,0x44,0x20},
+ {0x38,0x44,0x44,0x48,0x7F},{0x38,0x54,0x54,0x54,0x18},{0x08,0x7E,0x09,0x01,0x02},{0x0C,0x52,0x52,0x52,0x3E},
+ {0x7F,0x08,0x04,0x04,0x78},{0x00,0x44,0x7D,0x40,0x00},{0x20,0x40,0x44,0x3D,0x00},{0x7F,0x10,0x28,0x44,0x00},
+ {0x00,0x41,0x7F,0x40,0x00},{0x7C,0x04,0x18,0x04,0x78},{0x7C,0x08,0x04,0x04,0x78},{0x38,0x44,0x44,0x44,0x38},
+ {0x7C,0x14,0x14,0x14,0x08},{0x08,0x14,0x14,0x18,0x7C},{0x7C,0x08,0x04,0x04,0x08},{0x48,0x54,0x54,0x54,0x20},
+ {0x04,0x3F,0x44,0x40,0x20},{0x3C,0x40,0x40,0x20,0x7C},{0x1C,0x20,0x40,0x20,0x1C},{0x3C,0x40,0x30,0x40,0x3C},
+ {0x44,0x28,0x10,0x28,0x44},{0x0C,0x50,0x50,0x50,0x3C},{0x44,0x64,0x54,0x4C,0x44},
+};
+
+/* ------------------------------------------------------------------ drawing */
+/* Everything is composed in buf, one region of the screen at a time: the
+ region's pixels, row after row (rw wide). Drawing outside it is clipped. */
+#define BUFPX (320 * 24)
+static color buf[BUFPX];
+static int rx, ry, rw, rh;
+
+static int min(int a, int b) { return a < b ? a : b; }
+static int max(int a, int b) { return a > b ? a : b; }
+
+static void fill(int x, int y, int w, int h, color c) {
+ int x0 = max(x, rx), x1 = min(x + w, rx + rw), y0 = max(y, ry), y1 = min(y + h, ry + rh);
+ if (x0 >= x1) return;
+ for (int j = y0; j < y1; j++)
+ for (color *p = buf + (j - ry) * rw + (x0 - rx), *e = p + (x1 - x0); p < e; p++) *p = c;
+}
+static void px(int x, int y, color c) {
+ if ((unsigned)(x - rx) < (unsigned)rw && (unsigned)(y - ry) < (unsigned)rh) buf[(y - ry) * rw + x - rx] = c;
+}
+static void frame(int x, int y, int w, int h, int t, color c) {
+ fill(x, y, w, t, c), fill(x, y + h - t, w, t, c), fill(x, y, t, h, c), fill(x + w - t, y, t, h, c);
+}
+/* the top and left edges in one colour, the bottom and right in another */
+static void bevel(int x, int y, int w, int h, color tl, color br) {
+ fill(x, y, w, 1, tl), fill(x, y, 1, h, tl), fill(x, y + h - 1, w, 1, br), fill(x + w - 1, y, 1, h, br);
+}
+/* a card's shape: rounded corners, an outline o, filled with f */
+static void rrect(int x, int y, int w, int h, color o, color f) {
+ fill(x + 2, y, w - 4, h, o), fill(x + 1, y + 1, w - 2, h - 2, o), fill(x, y + 2, w, h - 4, o);
+ fill(x + 2, y + 1, w - 4, h - 2, f), fill(x + 1, y + 2, w - 2, h - 4, f);
+}
+/* a ring between radii r0 and r1 (a disc when r0 is 0) */
+static void ring(int cx, int cy, int r0, int r1, color c) {
+ for (int dy = -r1; dy <= r1; dy++)
+ for (int dx = -r1; dx <= r1; dx++) {
+ int d = dx * dx + dy * dy;
+ if (d >= r0 * r0 && d <= r1 * r1 + r1) px(cx + dx, cy + dy, c);
+ }
+}
+/* a left-right symmetric bitmap: each row holds the left half and the middle
+ column, first column in the top bit; upside down when flip */
+static void sym(const uint8_t *rows, int n, int half, int x, int y, color c, int flip) {
+ for (int j = 0; j < n; j++) {
+ int r = rows[flip ? n - 1 - j : j];
+ for (int i = 0; i < half; i++)
+ if (r >> (half - 1 - i) & 1) px(x + i, y + j, c), px(x + 2 * half - 2 - i, y + j, c);
+ }
+}
+/* a character of the 5x7 font, k times bigger, turned upside down when flip */
+static void glyph(int ch, int x, int y, int k, color c, int flip) {
+ const uint8_t *g = font[(unsigned)(ch - 32) < 91 ? ch - 32 : '?' - 32];
+ for (int i = 0; i < 5; i++)
+ for (int j = 0; j < 7; j++)
+ if (g[i] >> j & 1) fill(x + (flip ? 4 - i : i) * k, y + (flip ? 6 - j : j) * k, k, k, c);
+}
+static int slen(const char *s) {
+ int n = 0;
+ while (s[n]) n++;
+ return n;
+}
+static void text(const char *s, int x, int y, int k, color c) {
+ for (; *s; s++, x += 6 * k) glyph(*s, x, y, k, c, 0);
+}
+/* the firmware's fonts, straight to the screen: 7x14 or 10x18 cells */
+static void str(const char *s, int x, int y, int large, color fg, color bg) {
+ eadk_display_draw_string(s, (eadk_point_t){(uint16_t)x, (uint16_t)y}, large, fg, bg);
+}
+
+static char *cat(char *o, const char *s) {
+ while (*s) *o++ = *s++;
+ *o = 0;
+ return o;
+}
+static char *num(char *o, int32_t v) {
+ char t[11];
+ int n = 0;
+ uint32_t u = v < 0 ? 0u - (uint32_t)v : (uint32_t)v;
+ if (v < 0) *o++ = '-';
+ do t[n++] = (char)('0' + u % 10); while (u /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+/* Vegas dollars, written like Windows: -$52 */
+static char *money(char *o, int32_t v) {
+ char *s = o;
+ o = num(cat(o, "$"), v);
+ if (v < 0) s[0] = '-', s[1] = '$';
+ return o;
+}
+
+/* ------------------------------------------------------------------ cards */
+enum { STOCK, WASTE, F0, T0 = 6, NP = 13 }; /* the piles */
+
+/* everything kept between visits (solitaire.sav): options, statistics and
+ the game in progress */
+static struct {
+ uint8_t magic, version, draw, scoring; /* scoring: 0 Standard, 1 Vegas, 2 none */
+ uint8_t timed, keep, live, started; /* live: a game to continue */
+ uint8_t gdraw, gscoring, gtimed, passes; /* the game's own options; recycled decks */
+ uint8_t wfan, back, pad[2]; /* cards spread on the waste; the card back */
+ uint16_t played, won, streak, best_streak, best_time, moves;
+ int32_t best_score, bank, score; /* bank: all Vegas games added up */
+ uint32_t seed, ms;
+ uint8_t n[NP], cards[52], pad2[3];
+} V;
+#define SAVE_NAME "solitaire.sav"
+
+/* A card is rank * 4 + suit (suits: spades, hearts, clubs, diamonds, so bit 0
+ is red), plus UP when it lies face up. */
+#define UP 0x80
+#define RANK(c) (((c) & 63) >> 2)
+#define SUIT(c) ((c) & 3)
+#define CW 40
+#define CH 54
+#define COLX(i) (5 + (i) * 45)
+#define TOPY 2
+#define TABY 60
+#define STY 230 /* the status bar */
+#define FAN 15 /* the waste's spread, drawing 2 or 3 */
+
+/* where the pips of 2..10 go: groups of pips on a 3x13 grid, and which groups
+ each rank uses. A group: column (bits 6-7), row (0-3), mirrored across the
+ middle column (bit 4) and the middle row (bit 5). */
+static const uint8_t pip_group[8] = {0x60, 0x46, 0x30, 0x16, 0x43, 0x49, 0x34, 0x62};
+static const uint8_t pip_ranks[9] = {0x01, 0x03, 0x04, 0x06, 0x0C, 0x1C, 0x3C, 0x46, 0xC4};
+
+static void pip(int s, int col, int row, int x, int y, color c) {
+ sym(pip7[s], 7, 4, x + 9 + col * 8, y + 10 + row * 9 / 4, c, row > 6);
+}
+
+/* the index in a corner: the rank in bold and a small suit; flip draws the
+ one in the bottom right corner, upside down */
+static void corner(int c, int x, int y, color ink, int flip) {
+ int r = RANK(c), u = 3;
+ const char *s = r == 9 ? "10" : &"A23456789?JQK"[r];
+ for (int n = r == 9 ? 2 : 1, i = 0; i < n; i++) {
+ int w = s[i] == '1' ? 4 : 6, gx = s[i] == '1' ? u - 1 : u; /* the 1 of 10 is narrow */
+ for (int b = 0; b < 2; b++) glyph(s[i], x + (flip ? CW - gx - 6 : gx) + b, y + (flip ? CH - 9 : 2), 1, ink, flip);
+ u += w + (n == 2 && !i);
+ }
+ u++;
+ sym(pip7[SUIT(c)], 7, 4, x + (flip ? CW - u - 7 : u), y + (flip ? CH - 9 : 2), ink, flip);
+}
+
+/* a court card: a framed figure, the bottom half the top one turned round */
+static void court(int c, int x, int y, color ink, color inv) {
+ const uint8_t *f = figs[RANK(c) - 10];
+ color pal[8] = {WHITE, BLACK, RED, RGB(0x2040C0), RGB(0xF0C020), RGB(0xF8D8B0), ink ^ inv, RGB(0x8C5014)};
+ frame(x + 8, y + 10, 24, 34, 1, ink);
+ for (int b = 0; b < 22 * 16; b++) {
+ int v = (f[b * 3 >> 3] | f[(b * 3 >> 3) + 1] << 8) >> (b * 3 & 7) & 7, i = b % 22, j = b / 22;
+ if (v) px(x + 9 + i, y + 11 + j, pal[v] ^ inv), px(x + 30 - i, y + 42 - j, pal[v] ^ inv);
+ }
+}
+
+/* the backs of the Deck dialog, inside a white border: the classic blue
+ lattice, a red one, a basket weave and diamonds */
+static const color backs[4][2] = {{RGB(0x1830A8), RGB(0x7890F0)}, {RGB(0xA01010), RGB(0xF07070)},
+ {RGB(0x005850), RGB(0x50C8B0)}, {RGB(0x704000), RGB(0xF0C040)}};
+/* How much of a covered back shows. Squeezed under 6 px, the border shrinks
+ so the pattern still shows; under 3 px even the edge takes its colour. */
+static int sq = 6;
+static void back(int x, int y) {
+ int s = V.back & 3, t = sq < 6;
+ rrect(x, y, CW, CH, sq < 3 ? backs[s][0] : BLACK, WHITE);
+ int x0 = max(x + 3 - t, rx), x1 = min(x + CW - 3 + t, rx + rw), y0 = max(y + 3 - 2 * t, ry), y1 = min(y + CH - 3, ry + rh);
+ for (int j = y0; j < y1; j++)
+ for (int i = x0; i < x1; i++) {
+ int a = i - x, b = j - y;
+ buf[(j - ry) * rw + i - rx] = backs[s][s < 2 ? ((a + b) & 3) == 1 || ((a - b) & 3) == 1
+ : s == 2 ? (((a >> 2) + (b >> 2)) & 1 ? a : b) & 1
+ : ((a + b) & 7) < 2 || ((a - b) & 7) < 2];
+ }
+}
+
+/* a card at (x, y); inv shows it selected (colours inverted, as in Windows) */
+static void card(int c, int x, int y, color inv) {
+ if (x >= rx + rw || x + CW <= rx || y >= ry + rh || y + CH <= ry) return;
+ if (!(c & UP)) {
+ back(x, y);
+ return;
+ }
+ int s = SUIT(c), r = RANK(c);
+ color ink = (s & 1 ? RED : BLACK) ^ inv;
+ rrect(x, y, CW, CH, BLACK ^ inv, WHITE ^ inv);
+ corner(c, x, y, ink, 0);
+ corner(c, x, y, ink, 1);
+ if (!r) {
+ sym(pip13[s], 15, 7, x + 14, y + 20, ink, 0);
+ } else if (r < 10) {
+ for (int g = 0, m = pip_ranks[r - 1]; g < 8; g++) {
+ if (!(m >> g & 1)) continue;
+ int b = pip_group[g], col = b >> 6, row = b & 15;
+ pip(s, col, row, x, y, ink);
+ if (b & 0x10) pip(s, 2 - col, row, x, y, ink);
+ if (b & 0x20) pip(s, col, 12 - row, x, y, ink);
+ if ((b & 0x30) == 0x30) pip(s, 2 - col, 12 - row, x, y, ink);
+ }
+ } else {
+ court(c, x, y, ink, inv);
+ }
+}
+/* an empty place, etched in the felt */
+static void slot(int x, int y) {
+ rrect(x, y, CW, CH, RGB(0x00A800), FELT);
+ rrect(x, y, CW - 1, CH - 1, SLOT, FELT);
+}
+
+/* ------------------------------------------------------------------ state */
+static uint8_t pl[NP][52], pn[NP]; /* the piles, bottom card first */
+static uint8_t fd[7], od[7], ou[7]; /* per column: face-down cards, their spread, the face-up spread */
+
+static uint32_t now, seed = 0x9E3779B9;
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ return seed;
+}
+
+/* the waste shows the last cards drawn, spread (none left in the spread: the
+ top card alone) */
+static int fan(void) { return min(min(max(V.wfan, 1), V.gdraw), pn[WASTE]); }
+
+/* each column's spread, squeezed until it fits above the status bar */
+static void relayout(void) {
+ for (int i = 0; i < 7; i++) {
+ int n = pn[T0 + i], d = 0, a = 6, b = 13;
+ while (d < n && !(pl[T0 + i][d] & UP)) d++;
+ /* face up to 9 px (the index still shows whole), face down to 3, face
+ up to 8, then whatever it takes */
+ while (d * a + max(n - d - 1, 0) * b > STY - 2 - TABY - CH) {
+ if (b > 9 || (a < 4 && b > 8)) b--;
+ else if (a > 1) a--;
+ else if (b > 1) b--;
+ else break;
+ }
+ fd[i] = (uint8_t)d, od[i] = (uint8_t)a, ou[i] = (uint8_t)b;
+ }
+}
+
+/* where card k of pile p lies (k may be the free place above the top) */
+static void pos(int p, int k, int *x, int *y) {
+ *y = TOPY;
+ if (p == STOCK) {
+ *x = COLX(0);
+ } else if (p == WASTE) {
+ *x = COLX(1) + max(k - (pn[WASTE] - fan()), 0) * FAN;
+ } else if (p < T0) {
+ *x = COLX(p + 1);
+ } else {
+ int i = p - T0, d = fd[i];
+ *x = COLX(i);
+ *y = TABY + (k < d ? k * od[i] : d * od[i] + (k - d) * ou[i]);
+ }
+}
+
+/* how many cards from the top can be picked up together */
+static int run(int p) {
+ int n = pn[p], k = 1;
+ if (!n || !(pl[p][n - 1] & UP)) return 0;
+ if (p < T0) return 1;
+ for (; k < n; k++) {
+ int a = pl[p][n - k - 1], b = pl[p][n - k];
+ if (!(a & UP) || RANK(a) != RANK(b) + 1 || !((a ^ b) & 1)) break;
+ }
+ return k;
+}
+
+/* can the top n cards of f go on t? */
+static int legal(int f, int n, int t) {
+ if (f == t || t < F0 || (f >= F0 && f < T0 && t < T0) || n < 1 || n > run(f)) return 0;
+ int c = pl[f][pn[f] - n], top = pn[t] ? pl[t][pn[t] - 1] : -1;
+ if (t < T0) return n == 1 && (top < 0 ? RANK(c) == 0 : SUIT(top) == SUIT(c) && RANK(top) + 1 == RANK(c));
+ return top < 0 ? RANK(c) == 12 : RANK(top) == RANK(c) + 1 && ((top ^ c) & 1);
+}
+
+/* ------------------------------------------------------------------ screen */
+static np_jump_t leave; /* Home and On/Off leave from anywhere through it */
+static uint64_t held, pend, rep; /* keys down, presses not handled yet, arrows that repeat */
+static uint32_t repeat_at, last_frame;
+static int layer; /* what the screen shows: 0 the table, 1 the title, 2 one widget */
+static int ticking; /* the game's clock runs (not in dialogs) */
+static void scene(void);
+
+/* draws the scene over a rectangle of the screen and pushes it */
+static void paint(int x, int y, int w, int h) {
+ if (x < 0) w += x, x = 0;
+ if (y < 0) h += y, y = 0;
+ w = min(w, 320 - x), h = min(h, 240 - y);
+ if (w <= 0 || h <= 0) return;
+ for (int y0 = y, sh = BUFPX / w; y0 < y + h; y0 += sh) {
+ rx = x, ry = y0, rw = w, rh = min(sh, y + h - y0);
+ scene();
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)rx, (uint16_t)ry, (uint16_t)rw, (uint16_t)rh}, buf);
+ }
+}
+
+/* rectangles to repaint at the next frame, merged when they overlap */
+static int16_t dr[12][4];
+static int ndr;
+static void dirty(int x, int y, int w, int h) {
+ int x1 = x + w, y1 = y + h;
+ for (int i = 0; i < ndr; i++) {
+ int16_t *d = dr[i];
+ if (x < d[2] && d[0] < x1 && y < d[3] && d[1] < y1) {
+ d[0] = (int16_t)min(d[0], x), d[1] = (int16_t)min(d[1], y), d[2] = (int16_t)max(d[2], x1), d[3] = (int16_t)max(d[3], y1);
+ return;
+ }
+ }
+ if (ndr == 12) {
+ int16_t *d = dr[11];
+ d[0] = (int16_t)min(d[0], x), d[1] = (int16_t)min(d[1], y), d[2] = (int16_t)max(d[2], x1), d[3] = (int16_t)max(d[3], y1);
+ return;
+ }
+ dr[ndr][0] = (int16_t)x, dr[ndr][1] = (int16_t)y, dr[ndr][2] = (int16_t)x1, dr[ndr][3] = (int16_t)y1;
+ ndr++;
+}
+static void dirty_pile(int p) {
+ if (p < T0) dirty(COLX(p == STOCK ? 0 : p == WASTE ? 1 : p + 1) - 2, 0, CW + 4 + (p == WASTE) * 2 * FAN, TABY - 2);
+ else dirty(COLX(p - T0) - 2, TABY - 2, CW + 4, STY - TABY + 2);
+}
+static void dirty_status(void) { dirty(0, STY, 320, 10); }
+
+/* keys: presses since the last look, arrows repeating while held */
+static void poll(void) {
+ uint64_t k = eadk_keyboard_scan(), e = k & ~held;
+ const uint64_t arrows = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down);
+ if (e & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) np_jump(leave);
+ rep &= k; /* only arrows pressed here repeat, not one still held from the launcher */
+ if (e & arrows) rep |= e & arrows, repeat_at = now + 320;
+ else if (rep && (int32_t)(now - repeat_at) >= 0) e |= rep, repeat_at = now + 80;
+ held = k;
+ pend |= e;
+}
+
+static void tick(uint32_t dt);
+/* one frame: repaint what changed, at most 60 times a second. Timed from the
+ refresh, so a long repaint does not make the next frame miss one. */
+static void next_frame(void) {
+ uint32_t t = (uint32_t)eadk_timing_millis();
+ if (t - last_frame < 14) eadk_timing_msleep(14 - (t - last_frame));
+ eadk_display_wait_for_vblank();
+ last_frame = (uint32_t)eadk_timing_millis();
+ for (int i = 0; i < ndr; i++) paint(dr[i][0], dr[i][1], dr[i][2] - dr[i][0], dr[i][3] - dr[i][1]);
+ ndr = 0;
+ t = (uint32_t)eadk_timing_millis();
+ if (ticking) tick((uint32_t)min((int)(t - now), 100)); /* animations count too */
+ now = t;
+ poll();
+}
+static uint64_t take(void) {
+ uint64_t e = pend;
+ pend = 0;
+ return e;
+}
+#define OK_KEYS (KEY(eadk_key_ok) | KEY(eadk_key_exe))
+
+/* ------------------------------------------------------------------ widgets */
+/* Windows 95 style: grey faces, bevelled edges, a navy title bar, and navy
+ for the focus too. Widgets are painted one at a time (layer 2); their text
+ is the firmware's font, drawn over them afterwards. */
+enum { W_WIN, W_BTN, W_RADIO, W_CHECK, W_GROUP, W_ITEM, W_BACK };
+#define F_ON 1 /* a radio button or a box that is on */
+#define F_FOCUS 2
+#define F_OFF 4 /* greyed out */
+static int wt, wx, wy, ww, wh, wf;
+static const char *wl;
+
+static void button(int x, int y, int w, int h, int focus) {
+ if (focus) frame(x, y, w, h, 1, BLACK), x++, y++, w -= 2, h -= 2;
+ fill(x, y, w, h, focus ? NAVY : FACE);
+ bevel(x, y, w, h, WHITE, BLACK);
+ bevel(x + 1, y + 1, w - 2, h - 2, LIGHT, SHADOW);
+}
+/* a navy title bar and n of its buttons: close, maximize, minimize */
+static void caption(int x, int y, int w, int n) {
+ fill(x, y, w, 20, NAVY);
+ for (int i = 0; i < n; i++) {
+ int bx = x + w - 18 - i * 16 - (i > 0) * 2;
+ button(bx, y + 3, 16, 14, 0);
+ if (!i) glyph('x', bx + 5, y + 6, 1, BLACK, 0);
+ else if (i == 1) frame(bx + 3, y + 5, 9, 9, 1, BLACK), fill(bx + 3, y + 6, 9, 1, BLACK);
+ else fill(bx + 4, y + 12, 6, 2, BLACK);
+ }
+}
+static void widget_draw(void) {
+ int x = wx, y = wy, f = wf & F_FOCUS;
+ fill(x, y, ww, wh, wt == W_ITEM && f ? NAVY : FACE);
+ if (wt == W_WIN) {
+ bevel(x, y, ww, wh, LIGHT, BLACK);
+ bevel(x + 1, y + 1, ww - 2, wh - 2, WHITE, SHADOW);
+ caption(x + 3, y + 3, ww - 6, 1);
+ if (wf) { /* the question mark */
+ ring(x + 30, y + 46, 0, 14, RGB(0x1040D0));
+ ring(x + 30, y + 46, 13, 14, BLACK);
+ glyph('?', x + 25, y + 39, 2, WHITE, 0);
+ }
+ } else if (wt == W_BTN) {
+ button(x, y, ww, wh, f);
+ } else if (wt == W_GROUP) {
+ bevel(x, y + 7, ww - 1, wh - 8, SHADOW, WHITE);
+ bevel(x + 1, y + 8, ww - 1, wh - 8, WHITE, SHADOW);
+ } else if (wt == W_BACK) { /* a card back to pick, style in the high bits */
+ int s = V.back;
+ if (f) frame(x, y, ww, wh, 2, NAVY);
+ V.back = (uint8_t)(wf >> 4), back(x + 4, y + 4), V.back = (uint8_t)s;
+ } else if (wt != W_ITEM) {
+ if (wt == W_RADIO) {
+ ring(x + 6, y + 8, 0, 6, SHADOW);
+ ring(x + 6, y + 8, 0, 5, WHITE);
+ if (wf & F_ON) ring(x + 6, y + 8, 0, 2, BLACK);
+ } else {
+ bevel(x, y + 2, 13, 13, SHADOW, WHITE);
+ bevel(x + 1, y + 3, 11, 11, BLACK, LIGHT);
+ fill(x + 2, y + 4, 9, 9, wf & F_OFF ? FACE : WHITE);
+ for (int i = 0; (wf & F_ON) && i < 7; i++) fill(x + 3 + i, y + 5 + (i <= 2 ? i + 2 : 6 - i), 1, 3, wf & F_OFF ? SHADOW : BLACK);
+ }
+ if (f) fill(x + 16, y, slen(wl) * 7 + 4, 16, NAVY);
+ }
+}
+/* paints a widget, then its label */
+static void widget(int t, int x, int y, int w, int h, const char *label, int f) {
+ int l = layer;
+ wt = t, wx = x, wy = y, ww = w, wh = h, wl = label, wf = f, layer = 2;
+ paint(x, y, w, h);
+ layer = l;
+ if (!label) return;
+ if (t == W_BTN) x += (w - slen(label) * 7) / 2 - 18, y += (h - 14) / 2 - 1;
+ else if (t == W_GROUP) x -= 11, y--;
+ else if (t == W_ITEM) y++;
+ str(label, x + 18, y + 1, 0, f & F_OFF ? SHADOW : f & F_FOCUS ? WHITE : BLACK, f & F_FOCUS ? NAVY : FACE);
+}
+static void win(int x, int y, int w, int h, const char *title, int icon) {
+ widget(W_WIN, x, y, w, h, 0, icon);
+ str(title, x + 7, y + 6, 0, WHITE, NAVY);
+}
+
+/* A dialog box: text lines, then buttons (in a column when vert). Returns the
+ button chosen, or -1 for Back. box keeps where it was. */
+static int16_t box[4];
+static int dialog(const char *title, const char *body, const char *const *btn, int nb, int vert, int icon) {
+ int lines = 0, tw = 0, bw = 76, ix = icon ? 48 : 0;
+ for (const char *s = body; s && *s; lines++) {
+ int n = 0;
+ while (s[n] && s[n] != '\n') n++;
+ tw = max(tw, n * 7);
+ s += n + (s[n] == '\n');
+ }
+ for (int i = 0; i < nb; i++) bw = max(bw, slen(btn[i]) * 7 + 28);
+ int bb = vert ? bw : nb * bw + (nb - 1) * 10, w = max(max(tw + ix, bb) + 36, slen(title) * 7 + 44);
+ int th = max(lines * 16, icon ? 36 : 0), h = 34 + th + (th ? 12 : 0) + (vert ? nb * 30 - 6 : 24) + 12;
+ int x = (320 - w) / 2, y = (240 - h) / 2, by = y + 34 + th + (th ? 12 : 0), f = 0;
+ box[0] = (int16_t)x, box[1] = (int16_t)y, box[2] = (int16_t)w, box[3] = (int16_t)h;
+ ndr = 0, ticking = 0; /* nothing of the table shows through, and the clock stops */
+ win(x, y, w, h, title, icon);
+ char ln[48];
+ for (int i = 0, n; body && *body; i++, body += n + (body[n] == '\n')) {
+ for (n = 0; body[n] && body[n] != '\n' && n < 47; n++) ln[n] = body[n];
+ ln[n] = 0;
+ str(ln, x + 18 + ix, y + 34 + (th - lines * 16) / 2 + i * 16, 0, BLACK, FACE);
+ }
+ for (uint64_t e = 0;; e = take()) {
+ int d = (e & KEY(vert ? eadk_key_down : eadk_key_right) ? 1 : 0) - (e & KEY(vert ? eadk_key_up : eadk_key_left) ? 1 : 0);
+ for (int i = 0; i < nb; i++)
+ if (!e || (d && (i == f || i == (f + d + nb) % nb)))
+ widget(W_BTN, vert ? x + (w - bw) / 2 : x + (w - bb) / 2 + i * (bw + 10), vert ? by + i * 30 : by, bw, 24, btn[i],
+ (i == (f + d + nb) % nb) * F_FOCUS);
+ f = (f + d + nb) % nb;
+ if (e & OK_KEYS) return f;
+ if (e & KEY(eadk_key_back)) return -1;
+ next_frame();
+ }
+}
+
+/* ------------------------------------------------------------------ the table */
+static int cp = T0 + 3, cd = 1; /* the cursor: pile, and cards picked with Up in a column */
+static int sp = -1, sn; /* the cards picked up: pile and count */
+static int hint_p = -1; /* the pile a hint points to */
+static int nocur; /* hides the cursor: dealing, winning */
+static uint32_t hint_until, msg_until;
+static const char *msg;
+
+/* cards in flight: they are hidden in their pile until they land */
+typedef struct {
+ uint8_t c;
+ int8_t t; /* frames flown; waits while negative */
+ int16_t x0, y0, x1, y1;
+} fly_t;
+#define NFLY 28
+static fly_t fl[NFLY];
+static int nfl, dur = 9;
+static uint64_t hid;
+
+static void fly_pos(const fly_t *f, int *x, int *y) {
+ int t = f->t * (2 * dur - f->t), d = dur * dur; /* easing out */
+ *x = f->x0 + (f->x1 - f->x0) * t / d, *y = f->y0 + (f->y1 - f->y0) * t / d;
+}
+static int shown(int c) { return !(hid >> (c & 63) & 1); }
+
+/* the cursor's rectangle: the cards it points at */
+static void cur_rect(int *x, int *y, int *h) {
+ int n = pn[cp], y1;
+ pos(cp, max(n - (cp >= T0 ? cd : 1), 0), x, y);
+ pos(cp, max(n - 1, 0), x, &y1);
+ *h = y1 - *y + CH;
+}
+static void dirty_cursor(void) {
+ int x, y, h;
+ cur_rect(&x, &y, &h);
+ dirty(x - 2, y - 2, CW + 4, h + 4);
+}
+static void set_cursor(int p, int d) {
+ dirty_cursor();
+ cp = p, cd = p >= T0 ? max(min(d, run(p)), 1) : 1;
+ dirty_cursor();
+}
+static void say(const char *s) {
+ msg = s, msg_until = now + 1800;
+ dirty_status();
+}
+
+/* with Keep score, Vegas shows the bank, which already holds a finished game */
+static int32_t shown_score(void) { return V.gscoring == 1 && V.keep ? V.bank + (V.live ? V.score : 0) : V.score; }
+
+static void status_bar(void) {
+ char s[64], *o = s;
+ fill(0, STY, 320, 10, FACE);
+ fill(0, STY, 320, 1, WHITE);
+ o = num(cat(o, "Moves: "), V.moves);
+ if (V.gscoring < 2) o = (V.gscoring ? money : num)(cat(o, " Score: "), shown_score());
+ if (V.gtimed) o = num(cat(o, " Time: "), (int32_t)(V.ms / 1000));
+ text(s, 316 - (int)(o - s) * 6, STY + 2, 1, BLACK);
+ if (msg) fill(0, STY + 1, slen(msg) * 6 + 8, 9, FACE), text(msg, 4, STY + 2, 1, BLACK);
+}
+
+static int can_recycle(void) { return V.gscoring != 1 || V.passes < V.gdraw - 1; }
+
+static void game_scene(void) {
+ fill(rx, ry, rw, rh, FELT);
+ if (ry < TABY) {
+ int k = pn[STOCK] - 1, x, y;
+ while (k >= 0 && !shown(pl[STOCK][k])) k--;
+ if (k >= 0) { /* the deck, a little thicker when it holds more */
+ for (int i = min(k / 8, 2); i; i--) fill(COLX(0) + CW - 1 + i, TOPY + 1 + i, 1, CH - 2, BLACK), fill(COLX(0) + 1 + i, TOPY + CH - 1 + i, CW - 2, 1, BLACK);
+ card(pl[STOCK][k], COLX(0), TOPY, 0);
+ } else { /* the empty stock: O to deal again, X when that is over */
+ slot(COLX(0), TOPY);
+ if (can_recycle()) {
+ ring(COLX(0) + 19, TOPY + 26, 8, 11, RGB(0x30E030));
+ } else {
+ for (int i = -8; i <= 8; i++) fill(COLX(0) + 18 + i, TOPY + 25 + i, 3, 3, RED), fill(COLX(0) + 18 + i, TOPY + 25 - i, 3, 3, RED);
+ }
+ }
+ for (k = max(pn[WASTE] - fan() - 1, 0); k < pn[WASTE]; k++)
+ if (shown(pl[WASTE][k])) pos(WASTE, k, &x, &y), card(pl[WASTE][k], x, y, sp == WASTE && k == pn[WASTE] - 1 ? 0xFFFF : 0);
+ for (int p = F0; p < T0; p++) {
+ k = pn[p] - 1;
+ while (k >= 0 && !shown(pl[p][k])) k--;
+ if (k >= 0) card(pl[p][k], COLX(p + 1), TOPY, sp == p && k == pn[p] - 1 ? 0xFFFF : 0);
+ else slot(COLX(p + 1), TOPY);
+ }
+ }
+ for (int p = T0; p < NP; p++) {
+ int x, y;
+ if (!pn[p] || !shown(pl[p][0])) slot(COLX(p - T0), TABY);
+ for (int k = 0; k < pn[p]; k++, sq = 6)
+ if (shown(pl[p][k])) sq = k + 1 < pn[p] ? od[p - T0] : 6, pos(p, k, &x, &y), card(pl[p][k], x, y, p == sp && k >= pn[p] - sn ? 0xFFFF : 0);
+ }
+ if (hint_p >= 0 && (now / 200 & 1)) {
+ int x, y;
+ pos(hint_p, max(pn[hint_p] - 1, 0), &x, &y);
+ frame(x - 2, y - 2, CW + 4, CH + 4, 2, RGB(0x40E8FF));
+ }
+ if (!nocur) {
+ int x, y, h;
+ cur_rect(&x, &y, &h);
+ frame(x - 2, y - 2, CW + 4, h + 4, 2, GOLD);
+ }
+ for (int i = 0; i < nfl; i++) {
+ int x, y;
+ if (fl[i].t >= 0) fly_pos(&fl[i], &x, &y), card(fl[i].c, x, y, 0);
+ }
+ if (ry + rh > STY) status_bar();
+}
+
+/* ------------------------------------------------------------------ moves */
+/* flies every card in flight to its place; skip lets a key land them all */
+static void animate(int skip) {
+ while (nfl) {
+ int j = 0, x, y;
+ for (int i = 0; i < nfl; i++) {
+ fly_t *f = &fl[i];
+ if (f->t >= 0) fly_pos(f, &x, &y), dirty(x, y, CW, CH);
+ if (++f->t >= dur || (skip && pend)) {
+ hid &= ~(1ull << (f->c & 63));
+ dirty(f->x1, f->y1, CW, CH);
+ continue;
+ }
+ if (f->t >= 0) fly_pos(f, &x, &y), dirty(x, y, CW, CH);
+ fl[j++] = *f;
+ }
+ nfl = j;
+ if (skip && pend) pend = 0;
+ next_frame();
+ }
+}
+static void launch(int c, int x0, int y0, int x1, int y1, int t) {
+ if (nfl == NFLY) return;
+ fl[nfl++] = (fly_t){(uint8_t)c, (int8_t)t, (int16_t)x0, (int16_t)y0, (int16_t)x1, (int16_t)y1};
+ hid |= 1ull << (c & 63);
+}
+
+/* Moving cards: begin() notes where they are and moves them in the state,
+ fly() sends them from there to their new places. turn: one at a time,
+ turned over (the stock and the waste); else as a block. */
+static int16_t mx[NFLY], my[NFLY];
+static int mn, mt, mturn;
+static void begin(int f, int t, int n, int turn) {
+ for (int k = 0; k < n && k < NFLY; k++) {
+ int x, y;
+ pos(f, turn ? pn[f] - 1 - k : pn[f] - n + k, &x, &y);
+ mx[k] = (int16_t)x, my[k] = (int16_t)y;
+ }
+ dirty_pile(f), dirty_pile(t);
+ for (int k = 0; k < n; k++) {
+ int c = pl[f][turn ? pn[f] - 1 - k : pn[f] - n + k];
+ pl[t][pn[t] + k] = (uint8_t)(turn ? (c & 63) | (t == WASTE ? UP : 0) : c);
+ }
+ pn[t] = (uint8_t)(pn[t] + n), pn[f] = (uint8_t)(pn[f] - n);
+ mn = n, mt = t, mturn = turn;
+}
+static void fly(int frames, int stagger) {
+ relayout();
+ dur = frames;
+ for (int k = 0; k < mn && k < NFLY; k++) {
+ int i = pn[mt] - mn + k, x, y;
+ pos(mt, i, &x, &y);
+ launch(pl[mt][i], mx[k], my[k], x, y, -k * stagger);
+ }
+ animate(0);
+ dirty_pile(mt);
+}
+
+/* the undo history: each move, and what it changed */
+typedef struct {
+ uint8_t f, t, n, fl; /* fl: 1 turned one at a time, 2 turned a card up after; the waste's spread << 4 */
+ int16_t ds; /* the score it gave */
+} undo_t;
+static undo_t U[256];
+static uint8_t ut;
+static int nu;
+static void push_undo(int f, int t, int n, int flags, int ds) {
+ U[ut++] = (undo_t){(uint8_t)f, (uint8_t)t, (uint8_t)n, (uint8_t)(flags | V.wfan << 4), (int16_t)ds};
+ nu = min(nu + 1, 256);
+}
+
+static int add_score(int d) { /* what actually changed: Standard stops at 0 */
+ int32_t s = V.score + d;
+ if (!V.gscoring && s < 0) s = 0;
+ d = (int)(s - V.score);
+ V.score = s;
+ dirty_status();
+ return d;
+}
+/* the clock, while a game is on; Standard loses 2 points every 10 seconds */
+static void tick(uint32_t dt) {
+ if (!V.live || !V.started) return;
+ uint32_t t0 = V.ms;
+ V.ms += dt;
+ if (V.ms / 10000 != t0 / 10000 && !V.gscoring && V.gtimed) add_score(-2);
+ if (V.ms / 1000 != t0 / 1000 && V.gtimed) dirty_status();
+}
+static void counted(void) {
+ if (!V.started) V.started = 1, V.played++;
+ V.moves++;
+ hint_p = -1;
+ dirty_status();
+}
+static void deselect(void) {
+ if (sp >= 0) dirty_pile(sp);
+ sp = -1;
+}
+
+static void move(int f, int n, int t, int frames) {
+ push_undo(f, t, n, 0, 0);
+ undo_t *u = &U[(uint8_t)(ut - 1)];
+ begin(f, t, n, 0);
+ if (f == WASTE && V.wfan > 1) V.wfan--;
+ u->ds = (int16_t)add_score(!V.gscoring ? (t < T0 ? 10 : f == WASTE ? 5 : f < T0 ? -15 : 0) :
+ V.gscoring == 1 ? (t < T0 ? 5 : f >= F0 && f < T0 ? -5 : 0) : 0);
+ if (f >= T0 && pn[f] && !(pl[f][pn[f] - 1] & UP)) { /* turn the card underneath */
+ pl[f][pn[f] - 1] |= UP;
+ u->fl |= 2;
+ if (!V.gscoring) u->ds = (int16_t)(u->ds + add_score(5));
+ }
+ counted();
+ fly(frames, 0);
+}
+
+static void draw_cards(void) {
+ if (sp == WASTE) deselect();
+ if (pn[STOCK]) {
+ int n = min(V.gdraw, pn[STOCK]);
+ push_undo(STOCK, WASTE, n, 1, 0);
+ begin(STOCK, WASTE, n, 1);
+ V.wfan = (uint8_t)n;
+ } else if (!pn[WASTE]) {
+ return;
+ } else if (!can_recycle()) {
+ say("No more passes");
+ return;
+ } else { /* the waste goes back to the stock */
+ int d = V.gscoring ? 0 : V.gdraw == 1 ? -100 : V.passes >= 2 ? -20 : 0;
+ push_undo(WASTE, STOCK, pn[WASTE], 1, 0);
+ begin(WASTE, STOCK, pn[WASTE], 1);
+ U[(uint8_t)(ut - 1)].ds = (int16_t)add_score(d);
+ V.passes++, V.wfan = 0;
+ counted();
+ fly(8, 0);
+ return;
+ }
+ counted();
+ fly(8, 3);
+}
+
+static void undo(void) {
+ if (!nu) {
+ say("Nothing to undo");
+ return;
+ }
+ deselect();
+ nu--;
+ undo_t u = U[--ut];
+ if (u.fl & 2) pl[u.f][pn[u.f] - 1] &= (uint8_t)~UP;
+ begin(u.t, u.f, u.n, u.fl & 1);
+ V.wfan = u.fl >> 4;
+ add_score(-u.ds);
+ if (u.f == WASTE && u.t == STOCK) V.passes--;
+ if (V.moves) V.moves--;
+ hint_p = -1;
+ fly(8, 0);
+}
+
+/* the lowest card that can go to a foundation, or 0 */
+static int to_foundation(int frames) {
+ int best = 99, bf = 0, bt = 0;
+ for (int f = WASTE; f < NP; f++) {
+ if (f >= F0 && f < T0) continue;
+ for (int t = F0; t < T0; t++)
+ if (legal(f, 1, t) && RANK(pl[f][pn[f] - 1]) < best) best = RANK(pl[f][pn[f] - 1]), bf = f, bt = t;
+ }
+ if (best == 99) return 0;
+ move(bf, 1, bt, frames);
+ return 1;
+}
+
+static void hint(void) {
+ int f, t, n = 1;
+ for (f = WASTE; f < NP; f++)
+ for (t = F0; t < T0; t++)
+ if ((f < F0 || f >= T0) && legal(f, 1, t)) goto found;
+ for (f = T0; f < NP; f++) { /* a run that turns a card up or empties its column */
+ n = run(f);
+ int base = pn[f] - n;
+ if (n && (base ? !(pl[f][base - 1] & UP) : 1))
+ for (t = T0; t < NP; t++)
+ if (legal(f, n, t) && (base || pn[t])) goto found;
+ }
+ for (f = WASTE, n = 1, t = T0; t < NP; t++)
+ if (legal(WASTE, 1, t)) goto found;
+ if (pn[STOCK] || (pn[WASTE] && can_recycle())) {
+ set_cursor(STOCK, 1);
+ say("Draw a card");
+ } else {
+ say("No more moves");
+ }
+ return;
+found:
+ deselect();
+ set_cursor(f, n);
+ hint_p = t, hint_until = now + 1600;
+ say("Hint");
+}
+
+/* OK: pick up, put down, or draw */
+static void act(void) {
+ if (cp == STOCK) {
+ draw_cards();
+ return;
+ }
+ int n = cp >= T0 ? cd : 1;
+ if (sp < 0) {
+ if (n <= run(cp)) sp = cp, sn = n, dirty_pile(cp);
+ return;
+ }
+ if (cp == sp) { /* a second OK sends the card up, like a double click */
+ int f = sp;
+ deselect();
+ for (int t = F0; t < T0 && sn == 1; t++)
+ if (legal(f, 1, t)) {
+ move(f, 1, t, 9);
+ return;
+ }
+ return;
+ }
+ for (n = 1; n <= run(sp) && !legal(sp, n, cp); n++) {} /* only one count can fit */
+ if (n > run(sp)) {
+ say("Not there");
+ return;
+ }
+ int f = sp;
+ deselect();
+ move(f, n, cp, 9);
+}
+
+/* ------------------------------------------------------------------ games */
+static void deal(uint32_t s) {
+ uint8_t d[52];
+ for (int i = 0; i < 52; i++) d[i] = (uint8_t)i;
+ V.seed = s;
+ s |= 1;
+ for (int i = 51; i > 0; i--) {
+ s ^= s << 13, s ^= s >> 17, s ^= s << 5;
+ int j = (int)(s % (uint32_t)(i + 1));
+ uint8_t c = d[i];
+ d[i] = d[j], d[j] = c;
+ }
+ for (int p = 0; p < NP; p++) pn[p] = 0;
+ int k = 0;
+ for (int r = 0; r < 7; r++)
+ for (int c = r; c < 7; c++) pl[T0 + c][pn[T0 + c]++] = (uint8_t)(d[k++] | (c == r ? UP : 0));
+ while (k < 52) pl[STOCK][pn[STOCK]++] = d[k++];
+ V.live = 1, V.started = 0, V.moves = 0, V.ms = 0, V.passes = 0, V.wfan = 0;
+ V.gdraw = V.draw, V.gscoring = V.scoring, V.gtimed = V.timed;
+ V.score = V.gscoring == 1 ? -52 : 0;
+ nu = 0, sp = -1, hint_p = -1, cd = 1;
+ relayout();
+}
+/* the cards fly from the stock to the columns, row by row */
+static void deal_fly(void) {
+ for (int r = 0, k = 0; r < 7; r++)
+ for (int c = r; c < 7; c++, k++) {
+ int x, y;
+ pos(T0 + c, r, &x, &y);
+ launch(pl[T0 + c][r], COLX(0), TOPY, x, y, -k * 2);
+ }
+ dirty(0, 0, 320, 240);
+ dur = 10;
+ animate(1);
+}
+
+static void save(void) {
+ V.magic = 'S', V.version = 1;
+ for (int p = 0, k = 0; p < NP; p++) {
+ V.n[p] = pn[p];
+ for (int i = 0; i < pn[p] && k < 52; i++) V.cards[k++] = pl[p][i];
+ }
+ ef_write(SAVE_NAME, &V, sizeof V);
+}
+
+/* reads the save, keeping only what makes sense */
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = ef_read(SAVE_NAME, &n);
+ V.draw = 3, V.timed = 1;
+ if (!d || n != sizeof V || d[0] != 'S' || d[1] != 1) return;
+ for (uint32_t i = 0; i < n; i++) ((uint8_t *)&V)[i] = d[i];
+ if (V.draw < 1 || V.draw > 3) V.draw = 3;
+ V.scoring %= 3, V.timed &= 1, V.keep &= 1;
+ uint64_t seen = 0;
+ int k = 0, ok = V.live == 1 && V.gdraw >= 1 && V.gdraw <= 3 && V.gscoring < 3 && V.gtimed < 2;
+ for (int p = 0; p < NP && ok; p++) {
+ if (V.n[p] > 52 - k) ok = 0;
+ for (int i = 0; ok && i < V.n[p]; i++, k++) {
+ int c = V.cards[k] & 63, up = p == WASTE || (p >= F0 && p < T0) || (p >= T0 && (V.cards[k] & UP || i == V.n[p] - 1 || (i && pl[p][i - 1] & UP)));
+ if (c >= 52 || seen >> c & 1) ok = 0;
+ if (p >= F0 && p < T0 && (RANK(c) != i || (i && SUIT(c) != SUIT(pl[p][0])))) ok = 0;
+ seen |= 1ull << c;
+ pl[p][i] = (uint8_t)(c | (up ? UP : 0));
+ }
+ pn[p] = V.n[p];
+ }
+ if (!ok || k != 52) {
+ V.live = 0;
+ for (int p = 0; p < NP; p++) pn[p] = 0;
+ }
+ V.started &= 1;
+}
+
+static void abandon(void) {
+ if (V.live && V.started) {
+ V.streak = 0;
+ if (V.gscoring == 1) V.bank += V.score;
+ }
+ V.live = 0;
+}
+
+/* ------------------------------------------------------------------ the win */
+/* one card straight onto the screen, over whatever is there */
+static void stamp(int c, int x, int y) {
+ rx = max(x, 0), ry = max(y, 0), rw = min(x + CW, 320) - rx, rh = min(y + CH, 240) - ry;
+ if (rw <= 0 || rh <= 0) return;
+ eadk_rect_t r = {(uint16_t)rx, (uint16_t)ry, (uint16_t)rw, (uint16_t)rh};
+ eadk_display_pull_rect(r, buf);
+ if (c < 0) fill(x, y, CW, CH, FELT), slot(x, y);
+ else card(c, x, y, 0);
+ eadk_display_push_rect(r, buf);
+}
+
+/* The famous ending: the cards leave the foundations one by one, kings
+ first, bounce along the bottom of the screen and leave a trail. */
+static void bounce(void) {
+ ndr = 0;
+ take();
+ for (int r = 12; r >= 0; r--)
+ for (int p = F0; p < T0; p++) {
+ if (!pn[p]) continue;
+ int c = pl[p][--pn[p]], x = COLX(p + 1) * 16, y = TOPY * 16;
+ int vx = (int)(rnd() % 40 + 20) * (rnd() & 1 ? 1 : -1), vy = -(int)(rnd() % 90);
+ stamp(pn[p] ? pl[p][pn[p] - 1] : -1, COLX(p + 1), TOPY);
+ while (x > -CW * 16 && x < 320 * 16) {
+ for (int s = 0; s < 5; s++) {
+ x += vx, vy += 9, y += vy;
+ if (y > (240 - CH) * 16) y = (240 - CH) * 16, vy = -vy * 13 / 16;
+ stamp(c, x >> 4, y >> 4);
+ }
+ next_frame();
+ if (take()) return;
+ }
+ }
+}
+
+static int won(void) { return pn[F0] + pn[F0 + 1] + pn[F0 + 2] + pn[F0 + 3] == 52; }
+
+/* after every move: finish by itself once every card is face up */
+static void settle(void) {
+ if (!pn[STOCK] && !pn[WASTE] && !won()) {
+ for (int i = 0; i < 7; i++)
+ if (fd[i]) return;
+ deselect();
+ while (to_foundation(6)) {}
+ }
+}
+
+static void finish(void) {
+ uint32_t secs = V.ms / 1000;
+ V.live = 0, V.won++, V.streak++;
+ if (V.streak > V.best_streak) V.best_streak = V.streak;
+ if (!V.gscoring && V.gtimed && secs >= 30) V.score += (int32_t)(700000 / secs); /* Windows' bonus */
+ if (V.gscoring == 1) V.bank += V.score;
+ if (!V.best_time || secs < V.best_time) V.best_time = (uint16_t)min((int)secs, 65535);
+ if (!V.gscoring && V.score > V.best_score) V.best_score = V.score;
+ save();
+}
+
+/* ------------------------------------------------------------------ play */
+static const char *const yes_no[] = {"Yes", "No"}, *const ok_btn[] = {"OK"};
+
+static void new_deal(uint32_t s) {
+ abandon();
+ deal(s);
+ layer = 0;
+ set_cursor(T0 + 3, 1);
+ deal_fly();
+}
+
+/* the game, until the player leaves it */
+static void play(void) {
+ static const char *const pause_items[] = {"Resume", "Restart", "New deal", "Quit game"};
+ layer = 0, sp = -1, hint_p = -1, msg = 0;
+ relayout();
+ set_cursor(cp, cd);
+ dirty(0, 0, 320, 240);
+ uint32_t last = now;
+ for (;;) {
+ next_frame();
+ uint64_t e = take();
+ uint32_t dt = min((int)(now - last), 100);
+ last = now;
+ if (V.started) { /* the clock; Standard loses 2 points every 10 seconds */
+ uint32_t t0 = V.ms;
+ V.ms += dt;
+ if (V.ms / 10000 != t0 / 10000 && !V.gscoring && V.gtimed) add_score(-2);
+ if (V.ms / 1000 != t0 / 1000 && V.gtimed) dirty_status();
+ }
+ if (msg && (int32_t)(now - msg_until) > 0) msg = 0, dirty_status();
+ if (hint_p >= 0) {
+ if ((int32_t)(now - hint_until) > 0) dirty_pile(hint_p), hint_p = -1;
+ else if (now / 200 != (now - dt) / 200) dirty_pile(hint_p);
+ }
+ int lr = (e & KEY(eadk_key_right) ? 1 : 0) - (e & KEY(eadk_key_left) ? 1 : 0);
+ if (lr) {
+ if (cp >= T0) set_cursor(T0 + (cp - T0 + lr + 7) % 7, 1);
+ else set_cursor((cp + lr + 6) % 6, 1); /* stock, waste, foundations */
+ }
+ if (e & KEY(eadk_key_up)) {
+ if (cp >= T0 && sp < 0 && cd < run(cp)) set_cursor(cp, cd + 1);
+ else if (cp >= T0) set_cursor(cp == T0 ? STOCK : cp < T0 + 3 ? WASTE : cp - 7, 1);
+ }
+ if (e & KEY(eadk_key_down)) {
+ if (cp >= T0) set_cursor(cp, cd - 1);
+ else set_cursor(cp == STOCK ? T0 : cp == WASTE ? T0 + 1 : cp + 7, 1);
+ }
+ if (e & KEY(eadk_key_ok)) act();
+ if (e & KEY(eadk_key_exe)) draw_cards();
+ if (e & KEY(eadk_key_toolbox)) {
+ deselect();
+ if (!to_foundation(7)) say("Nothing to play");
+ while (to_foundation(7)) {}
+ }
+ if (e & KEY(eadk_key_backspace)) undo();
+ if (e & KEY(eadk_key_shift)) hint();
+ if (e & KEY(eadk_key_back)) {
+ if (sp >= 0) {
+ deselect();
+ } else {
+ for (;;) {
+ int r = dialog("Paused", 0, pause_items, 4, 1, 0);
+ if (r == 3) {
+ if (!dialog("Solitaire", "Quit game?", yes_no, 2, 0, 1)) np_jump(leave); /* saves, then leaves */
+ paint(0, 0, 320, 240);
+ continue;
+ }
+ dirty(0, 0, 320, 240);
+ if (r == 1 || r == 2) new_deal(r == 1 ? V.seed : rnd());
+ break;
+ }
+ last = now;
+ }
+ }
+ if (cp >= T0 && cd > max(run(cp), 1)) set_cursor(cp, cd); /* the column changed */
+ settle();
+ if (won() && V.live) {
+ char s[96], *o = s;
+ finish();
+ o = num(cat(o, "You win!\nTime: "), (int32_t)(V.ms / 1000));
+ o = num(cat(o, " seconds\nMoves: "), V.moves);
+ if (V.gscoring < 2) o = (V.gscoring ? money : num)(cat(o, "\nScore: "), shown_score());
+ cat(o, "\n\nDeal again?");
+ next_frame();
+ bounce();
+ if (dialog("Solitaire", s, yes_no, 2, 0, 0)) return;
+ new_deal(rnd());
+ last = now;
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ menus */
+static const char *const menu_items[] = {"Continue", "New game", "Options", "Statistics", "How to play"};
+static int menu_first, menu_at;
+static int menu_y(int i) { return 131 - (5 - menu_first) * 15 + (i - menu_first) * 30; }
+
+static void title_scene(void) {
+ static const uint8_t hand[5] = {0, (12 * 4 + 1) | UP, (11 * 4 + 2) | UP, (10 * 4 + 3) | UP, UP};
+ fill(rx, ry, rw, rh, FELT);
+ text("Solitaire", 57, 14, 4, RGB(0x004000));
+ text("Solitaire", 54, 11, 4, WHITE);
+ for (int i = 0; i < 5; i++) card(hand[i], 14 + i * 26, 96 + (i - 2) * (i - 2) * 3, 0);
+ for (int i = menu_first; i < 5; i++) button(184, menu_y(i), 124, 24, i == menu_at);
+ char m[24], *o = num(cat(m, "Draw "), V.draw);
+ cat(o, V.scoring ? V.scoring == 1 ? ", Vegas" : "" : ", Standard");
+ text("Based on Tatone26's version", 4, 229, 1, RGB(0x9CD89C));
+ text(m, 316 - slen(m) * 6, 229, 1, RGB(0x9CD89C));
+}
+static void scene(void) {
+ if (layer == 2) widget_draw();
+ else if (layer == 1) title_scene();
+ else game_scene();
+}
+static void title_labels(void) {
+ for (int i = menu_first; i < 5; i++)
+ str(menu_items[i], 184 + (124 - slen(menu_items[i]) * 7) / 2, menu_y(i) + 5, 0, i == menu_at ? WHITE : BLACK,
+ i == menu_at ? NAVY : FACE);
+}
+
+static void options(void) {
+ static const char *const lbl[8] = {"One (Easy)", "Two (Normal)", "Three (Hard)", "Timed game", "Standard", "Vegas", "None", "Keep score"};
+ int x = 22, y = 28, f = 0;
+ ndr = 0;
+ win(x, y, 276, 184, "Options", 0);
+ widget(W_GROUP, x + 10, y + 32, 124, 80, "Draw", 0);
+ widget(W_GROUP, x + 142, y + 32, 124, 80, "Scoring", 0);
+ for (uint64_t e = 0;; e = take()) {
+ int o = f;
+ if (e & KEY(eadk_key_up)) f = f == 8 ? 3 : f % 4 ? f - 1 : f;
+ if (e & KEY(eadk_key_down)) f = f == 8 ? 8 : f % 4 == 3 ? 8 : f + 1;
+ if ((e & (KEY(eadk_key_left) | KEY(eadk_key_right))) && f < 8) f ^= 4;
+ if (e & OK_KEYS) {
+ if (f == 8) break;
+ if (f == 3) V.timed ^= 1;
+ else if (f == 7) V.keep ^= 1;
+ else if (f < 3) V.draw = (uint8_t)(f + 1);
+ else V.scoring = (uint8_t)(f - 4);
+ }
+ if (e & KEY(eadk_key_back)) break;
+ for (int i = 0; i < 9; i++) {
+ if (e && i != f && i != o && !(e & OK_KEYS)) continue;
+ if (i == 8) {
+ widget(W_BTN, x + 103, y + 150, 70, 24, "OK", f == 8);
+ continue;
+ }
+ int on = i == 3 ? V.timed : i == 7 ? V.keep : i < 3 ? V.draw == i + 1 : V.scoring == i - 4;
+ widget(i % 4 == 3 ? W_CHECK : W_RADIO, x + 20 + (i / 4) * 132, y + 50 + (i % 4) * 20 + (i % 4 == 3) * 10, 110, 16,
+ lbl[i], on | (i == f) << 1);
+ }
+ next_frame();
+ }
+ save();
+}
+
+static void stats(void) {
+ char s[200], *o = s;
+ o = num(cat(o, "Games played: "), V.played);
+ o = num(cat(o, "\nGames won: "), V.won);
+ if (V.played) o = cat(num(cat(o, " ("), V.won * 100 / V.played), "%)");
+ o = num(cat(o, "\nStreak: "), V.streak);
+ o = num(cat(o, " Best: "), V.best_streak);
+ o = cat(o, "\nBest time: ");
+ if (V.best_time) {
+ o = num(o, V.best_time / 60);
+ *o++ = ':', *o++ = (char)('0' + V.best_time % 60 / 10), *o++ = (char)('0' + V.best_time % 10), *o = 0;
+ } else {
+ o = cat(o, "-");
+ }
+ o = num(cat(o, "\nBest score: "), V.best_score);
+ money(cat(o, "\nVegas bank: "), V.bank);
+ dialog("Statistics", s, ok_btn, 1, 0, 0);
+}
+
+static void help(void) {
+ dialog("How to play",
+ "Build four piles, ace to king, one\n"
+ "suit each. In the columns, go down\n"
+ "and alternate red and black.\n"
+ "OK Pick up, put down\n"
+ "OK twice Send to a foundation\n"
+ "Up, Down Pick more or fewer\n"
+ "EXE Draw from the deck\n"
+ "Toolbox Play all you can up\n"
+ "Backspace Undo Shift Hint",
+ ok_btn, 1, 0, 0);
+}
+
+int main(void) {
+ np_app_begin();
+ if (np_save_jump(leave)) {
+ save();
+ return np_app_end();
+ }
+ now = last_frame = (uint32_t)eadk_timing_millis();
+ seed ^= eadk_random() ^ now;
+ load();
+ held = eadk_keyboard_scan();
+ for (;;) {
+ menu_first = V.live ? 0 : 1;
+ menu_at = max(menu_at, menu_first);
+ if (menu_at > 4) menu_at = menu_first;
+ layer = 1;
+ paint(0, 0, 320, 240);
+ title_labels();
+ for (uint64_t e = 0;; e = take()) {
+ int d = (e & KEY(eadk_key_down) ? 1 : 0) - (e & KEY(eadk_key_up) ? 1 : 0);
+ if (d) {
+ int o = menu_at;
+ menu_at = menu_first + (menu_at - menu_first + d + 5 - menu_first) % (5 - menu_first);
+ for (int i = 0; i < 2; i++) {
+ int k = i ? menu_at : o;
+ widget(W_BTN, 184, menu_y(k), 124, 24, menu_items[k], k == menu_at ? F_FOCUS : 0);
+ }
+ }
+ if (e & OK_KEYS) break;
+ if ((e & KEY(eadk_key_back)) && !dialog("Solitaire", "Quit game?", yes_no, 2, 0, 1)) np_jump(leave);
+ if (e & KEY(eadk_key_back)) layer = 1, paint(0, 0, 320, 240), title_labels();
+ next_frame();
+ }
+ if (menu_at == 0) play();
+ else if (menu_at == 1) new_deal(rnd()), play();
+ else if (menu_at == 2) options();
+ else if (menu_at == 3) stats();
+ else help();
+ }
+}
diff --git a/launcher/src/games.c b/launcher/src/games.c
index 3e051ff8..07729476 100644
--- a/launcher/src/games.c
+++ b/launcher/src/games.c
@@ -9,7 +9,7 @@
#define TAIL_MAGIC 0x444E4550u /* "PEND" */
#if NP_SIMULATOR
-bool np_sim_removed[16];
+bool np_sim_removed[NP_MAX_GAMES];
#endif
bool np_game_installed(int i) {
diff --git a/launcher/src/home.c b/launcher/src/home.c
index 747a09d1..5f8cce67 100644
--- a/launcher/src/home.c
+++ b/launcher/src/home.c
@@ -18,7 +18,7 @@
typedef struct {
int n;
- int8_t item[16]; /* game index, or -1 for the settings card */
+ int8_t item[NP_MAX_GAMES + 1]; /* game index, or -1 for the settings card */
int sel;
float pos; /* scroll position, in cards */
int shot; /* screenshot shown on the selected card */
@@ -132,13 +132,13 @@ static void scene(void *ctx) {
if (gfx_y0 < 26 && ui_alpha > 0) {
gfx_icon(&np_icon_logo, 12, 6, 0xFFFF, ui_alpha);
gfx_text(&np_font_body, 40, 18, "NumPlay", 0xFFFF, ui_alpha);
- /* where we are in the carousel */
- int dots_w = h->n * 10 + 8;
- int dx = SCREEN_W - 12 - dots_w;
+ /* where we are in the carousel; with many cards the dots get closer */
+ int pitch = NP_MIN(10, 190 / (h->n + 1));
+ int dx = SCREEN_W - 10 - (h->n + 1) * pitch;
for (int i = 0; i < h->n; i++) {
float near = 1 - NP_MIN(absf(i - h->pos), 1.f);
- int w = 6 + (int)(10 * near);
- gfx_rrect(dx, 11, w, 6, 3, 0xFFFF, (int)((90 + 166 * near) * ui_alpha / 256));
+ int w = pitch - 4 + (int)(pitch * near);
+ gfx_rrect(dx, 11, w, 6, NP_MIN(3, w / 2), 0xFFFF, (int)((90 + 166 * near) * ui_alpha / 256));
dx += w + 4;
}
}
@@ -169,6 +169,9 @@ static void scene(void *ctx) {
if (fill >= 4) gfx_rrect(x, 185, fill, 4, 2, 0xFFFF, text_alpha * 230 / 256);
}
}
+ /* who made the game, when it isn't ours: under the card */
+ if (game >= 0 && np_games[game].credit && np_games[game].nshots <= 1)
+ gfx_text_center(&np_font_small, CARD_CX, 193, np_games[game].credit, 0xFFFF, text_alpha * 150 / 256);
gfx_text_center(&np_font_title, CARD_CX, 213, item_title(game), 0xFFFF, text_alpha);
gfx_text_center(&np_font_body, CARD_CX, 231, item_tagline(game), 0xFFFF, text_alpha * 190 / 256);
}
@@ -177,7 +180,7 @@ static void scene(void *ctx) {
/* ---- behaviour */
static int build_items(home_t *h) {
h->n = 0;
- for (int i = 0; i < np_game_count && h->n < 15; i++)
+ for (int i = 0; i < np_game_count && h->n < NP_MAX_GAMES; i++)
if (np_game_installed(i)) h->item[h->n++] = (int8_t)i;
h->item[h->n++] = -1;
return h->n;
diff --git a/launcher/src/np.h b/launcher/src/np.h
index 32383620..38cadfad 100644
--- a/launcher/src/np.h
+++ b/launcher/src/np.h
@@ -62,6 +62,7 @@ typedef struct {
uint32_t est_size; /* code and data, for the simulator */
} np_game_t;
+#define NP_MAX_GAMES 32 /* tools/gen_games.py checks games.json against it */
extern const np_game_t np_games[];
extern const int np_game_count;
diff --git a/launcher/src/settings.c b/launcher/src/settings.c
index 8968ba31..6306e04d 100644
--- a/launcher/src/settings.c
+++ b/launcher/src/settings.c
@@ -32,7 +32,7 @@ static char *fmt_kb(char *out, uint32_t bytes) {
enum { ROW_GAME, ROW_RESET_ALL, ROW_DISGUISE, ROW_SECRET, ROW_HINT };
typedef struct {
int n, sel, top, action; /* action: on a game, 0 Reset, 1 Uninstall */
- int8_t kind[20], game[20];
+ int8_t kind[NP_MAX_GAMES + 4], game[NP_MAX_GAMES + 4];
int ngames;
np_config_t cfg;
float cursor; /* animated selection */
diff --git a/tests/test_games.py b/tests/test_games.py
index eb2c1367..278c4cc4 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -60,6 +60,39 @@ GAMES = {
presses((1500, "ok"), (2000, "right"), (2300, "right"), (2600, "right"), (2900, "right"),
(3300, "ok"), (3700, "up"), (4000, "up")), 5000,
presses((1500, "up")), 2500),
+ # settings: Speed to Fast, back, then a Custom game; next time Speed goes on to Insane
+ "flappybird": ("FlappyBird.nwa", "flappy.sav",
+ presses((1500, "down"), (1800, "ok"), (2100, "right"), (2400, "back"), (2700, "up"),
+ (2900, "right"), (3100, "ok"), (3900, "ok")) + every(4300, 7500, 450, "ok"), 9000,
+ presses((1500, "down"), (1800, "ok"), (2100, "right"), (2400, "back")), 3500),
+ # continue the saved game (level 2) and play a bit; then set Fast in the options
+ "pacman": ("PacMan.nwa", "pacman.sav", presses((1500, "ok")), 8000,
+ presses((1500, "down"), (1800, "ok"), (2100, "right"), (2400, "back")), 3500),
+ # Play, straight through the first apple into the wall: a best of 1; next
+ # time, Settings, Speed to Fast and back: saved, the best kept
+ "snake": ("Snake.nwa", "snake.sav", presses((1500, "ok"), (2000, "right")), 7000,
+ presses((1500, "down"), (1800, "ok"), (2100, "right"), (2400, "back")), 3500),
+ # vs the computer: the settings are saved; next time, the dark theme
+ "connectfour": ("ConnectFour.nwa", "connect4.sav", presses((1500, "ok"), (2500, "4")), 5000,
+ presses((1500, "down"), (1700, "down"), (1900, "down"), (2100, "down"), (2300, "right")), 3500),
+ # a new game (Vegas, draw 1 from the seeded options), two draws; then Continue and one more
+ "solitaire": ("Solitaire.nwa", "solitaire.sav", presses((1500, "ok"), (3500, "exe"), (4000, "exe")), 5000,
+ presses((1500, "ok"), (2500, "exe")), 3500),
+ # Play, one difficulty up (Hard), start the song and tap along; next time one more (Expert)
+ "numdance": ("NumDance.nwa", "numdance.sav",
+ presses((1500, "ok"), (2000, "right"), (2500, "ok")) + every(4000, 9000, 250, "up"), 10000,
+ presses((1500, "ok"), (2000, "right"), (2500, "ok")), 5000),
+ # the 4x4 game in the save (40 moves): Continue, two moves; next time three more
+ "g2048": ("2048.nwa", "g2048.sav", presses((1500, "ok"), (2500, "left"), (3000, "right")), 4000,
+ presses((1500, "ok"), (2500, "left"), (3000, "right"), (3500, "left")), 4500),
+ # Beginner, the first square, leave mid-game; next time Continue, then a
+ # new game from the pause menu and its first square
+ "minesweeper": ("Minesweeper.nwa", "mines.sav", presses((1500, "ok"), (2000, "ok"), (2400, "right")), 3000,
+ presses((1500, "ok"), (2000, "back"), (2300, "down"), (2600, "ok"), (3000, "ok")), 3600),
+ # Classic, serve, a brick or more: the best is kept; next time, Settings, screen shake off, back
+ "breakout": ("Breakout.nwa", "breakout.sav", presses((1500, "ok"), (2500, "ok")), 6000,
+ presses((1500, "down"), (1800, "down"), (2100, "ok"), (2500, "down"), (2800, "ok"), (3200, "back")),
+ 4500),
}
@@ -69,12 +102,50 @@ SEEDS = {
"numdrive": b"MD" + bytes([1] + [0] * 24) + b"\0\0\0",
# puzzle rating 1234, a streak of 3, the bot Hugo, side 1, a 10-minute clock
"chess": bytes([ord("C"), 1, 1234 & 255, 1234 >> 8, 3, 0, 7, 1 | 4 << 2]),
+ # options (normal speed, 3 lives), best 9000, a game at level 2 with 5000 points, 3 lives, every dot
+ "pacman": bytes([ord("P"), 1, 1, 2, 2, 1, 0, 0]) + struct.pack("<I", 9000) + bytes([1, 2, 3, 0])
+ + struct.pack("<I", 5000) + bytes([255] * 30 + [15, 0]),
+ # draw 1, Vegas, timed; 5 played, 2 won, a Vegas bank of -$100; no game in progress
+ "solitaire": b"S\1\1\1\1\0\0\0" + bytes(8) + struct.pack("<6H3i2I", 5, 2, 1, 2, 200, 0, 1234, -100, 0, 0, 0)
+ + bytes(68),
+ # 4x4 last played, with a game to continue: best 1000, score 500, 40 moves, a 2, a 4 and a 2
+ "g2048": b"2\1\1" + bytes([0, 1, 0, 0, 0]) + struct.pack("<12I", 0, 1000, 0, 0, 0, 500, 0, 0, 0, 40, 0, 0)
+ + bytes(9) + bytes([1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) + bytes(61 + 2),
}
CHECKS = {
"numdrive": (lambda v: v[27] == 1, lambda v: v[27] == 0), # last played level
"chess": (lambda v: v == SEEDS["chess"],) * 2, # read back and kept
"numvisuals": (lambda v: v[:2] == b"V\1" and v[3] == 4 and struct.unpack_from("<i", v, 8)[0] == 2,
lambda v: struct.unpack_from("<i", v, 8)[0] == 3), # the add-on and its count
+ "flappybird": (lambda v: len(v) == 26 and v[:3] == b"F\1\1" and v[8] == 3, # Custom, Speed Fast
+ lambda v: v[2] == 1 and v[8] == 4), # read back, Speed Insane
+ # the game went on (more points, fewer dots), then Fast was chosen and the game kept
+ "pacman": (lambda v: v[:2] == b"P\1" and v[12:14] == bytes([1, 2]) and struct.unpack_from("<I", v, 16)[0] > 5000
+ and struct.unpack_from("<I", v, 8)[0] == 9000 and sum(bin(b).count("1") for b in v[20:52]) < 244,
+ lambda v: v[2] == 2 and v[12:14] == bytes([1, 2]) and struct.unpack_from("<I", v, 16)[0] > 5000),
+ # the default options, then the best for Medium at Normal speed
+ "snake": (lambda v: len(v) == 26 and v[:8] == b"S\1\1\1\0\0\0\0" and struct.unpack_from("<H", v, 16)[0] == 1,
+ lambda v: len(v) == 26 and v[2] == 2 and struct.unpack_from("<H", v, 16)[0] == 1),
+ "connectfour": (lambda v: v == b"C\1\1\2\1\0\5\1" + bytes(8), # vs computer, 2 players, Normal, light
+ lambda v: v[5] == 1 and v[6] == 5), # dark now; the tally's settings read back
+ # the seeded options made a Vegas draw-1 game (-$52), counted as played; two moves, then three
+ "solitaire": (lambda v: len(v) == 116 and v[:4] == b"S\1\1\1" and v[6] == 1 and v[8:10] == b"\1\1"
+ and struct.unpack_from("<2H", v, 16) == (6, 2) and struct.unpack_from("<H", v, 26)[0] == 2
+ and struct.unpack_from("<2i", v, 32) == (-100, -52),
+ lambda v: v[6] == 1 and struct.unpack_from("<H", v, 16)[0] == 6
+ and struct.unpack_from("<H", v, 26)[0] == 3),
+ # scroll speed 2x by default, the difficulty chosen
+ "numdance": (lambda v: len(v) == 168 and v[:3] == b"D\1\2" and v[6] == 2, lambda v: v[6] == 3),
+ # continued (moves 40 + 2, then + 3), still in progress, score and best kept or higher
+ "g2048": (lambda v: v[:3] == b"2\1\1" and v[4] & 1 and struct.unpack_from("<I", v, 44)[0] == 42
+ and struct.unpack_from("<I", v, 28)[0] >= 500 and struct.unpack_from("<I", v, 12)[0] >= 1000,
+ lambda v: v[4] & 1 and struct.unpack_from("<I", v, 44)[0] == 45),
+ # a Beginner game kept (9x9, 10 mines, cursor moved right), one game played; then two
+ "minesweeper": (lambda v: len(v) == 276 and v[:2] == b"M\1" and v[32:34] == bytes([9, 9]) and v[28] == 10
+ and v[34] == 5 and struct.unpack_from("<H", v, 14)[0] == 1,
+ lambda v: v[32] == 9 and struct.unpack_from("<H", v, 14)[0] == 2),
+ "breakout": (lambda v: len(v) == 16 and v[:2] == b"B\1" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 1,
+ lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
}
diff --git a/tools/games_mk.py b/tools/games_mk.py
index 2d4690ed..526cbbae 100644
--- a/tools/games_mk.py
+++ b/tools/games_mk.py
@@ -1,5 +1,10 @@
#!/usr/bin/env python3
-"""Turns games/games.json into make variables (order, screenshots)."""
+"""Turns games/games.json into make variables (order, screenshots).
+
+A game with an "app" entry (its release file, e.g. "Snake.nwa") is in the
+standard layout of games/numvisuals: its Makefile's `build`, `module` and
+`sim-module` targets make output/<id>.nwa, module.o and sim-module.o, so the
+top-level Makefile needs nothing else for it (STD_GAMES)."""
import json
import sys
@@ -13,3 +18,7 @@ for n, g in enumerate(games, 1):
print(f"SHOTS_REL_{i} := " + " ".join(g["shots"]))
if g.get("colors"):
print(f"COLORS_{i} := --colors {g['colors']}")
+ if g.get("app"):
+ print(f"NWA_{i} := {g['app']}")
+ print(f"APPID_{g['app'][:-4]} := {i}")
+print("STD_GAMES := " + " ".join(g["id"] for g in games if g.get("app")))
diff --git a/tools/gen_games.py b/tools/gen_games.py
index 6667b0e2..9b5d06f1 100644
--- a/tools/gen_games.py
+++ b/tools/gen_games.py
@@ -14,6 +14,7 @@ Usage: gen_games.py games.json MODULE_DIR OUT_DIR [--simulator]
import argparse
import json
import os
+import re
LAUNCHER_RAM = 96 * 1024 # the launcher adapts its screenshot cache to the arena
HEAD, TAIL = 0x3147504E, 0x444E4550
@@ -31,6 +32,10 @@ def main():
ap.add_argument("--simulator", action="store_true")
a = ap.parse_args()
games = json.load(open(a.manifest))
+ np_h = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "launcher", "src", "np.h")).read()
+ limit = int(re.search(r"#define NP_MAX_GAMES (\d+)", np_h).group(1))
+ if len(games) > limit:
+ raise SystemExit(f"{len(games)} games, but the launcher holds {limit} (NP_MAX_GAMES in launcher/src/np.h)")
os.makedirs(a.out, exist_ok=True)
sizes = {}
for g in games: