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.

Mahjong: Mahjong solitaire, an app of its own

Mason3633d4c5ef05340
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 6f236cda..b8ca7747 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -95,6 +95,7 @@ jobs:
make -C games/polytrack host test
make -C games/paperclips host test
make -C games/badtime host test
+ make -C games/mahjong host test
diff --git a/Makefile b/Makefile
index 75495277..a069999b 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,7 @@ PY ?= python3
CARGO ?= cargo
B = build/data
# Conventional games honor a configurable output directory; special layouts are kept local.
-GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune finalearth2 flappybird flappydunk fnaf fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz snake sokoban solitaire sonic stickmanhook subway sudoku suika tombofthemask towerblock turborush twoplayer undertale uno uttt
+GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune finalearth2 flappybird flappydunk fnaf fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz snake sokoban solitaire sonic stickmanhook subway sudoku suika tombofthemask towerblock turborush twoplayer undertale uno uttt
GAMES_OUT = dinorun
GAME_REDIRECT_ARG = $(if $(filter $(1),$(GAMES_OUT)),OUT=../../$(B)/games/$(1),BUILD_DIR=../../$(B)/games/$(1))
# the RAM the oldest calculator software that runs apps gives them (23.2: 148928 bytes; 25.2 gives 153676).
@@ -29,7 +29,7 @@ RAM_LIMIT = 148928
# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
-BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator
+BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong
# the calculator's space for installed apps: from the end of its software (64 KiB aligned) to 64 KiB before the
# end of its 4 MiB slot of flash, 0x903F0000. The software's size sets the start: 0x90200000 is the latest a
# NumPlay counts on (1.94 MB, APP_SPACE); Epsilon 26.4 on an N0120 ends at 0x90180000 (2.44 MB, the
@@ -47,7 +47,7 @@ XL_APP_SPACE = 6291456
# the spaces the customizer website offers (kit.json "spaces"; tools/kit.py links a NumPlay at each)
SPACES = std:$(APP_START):$(APP_END) e26:$(APP_START_26):$(APP_END) xl:$(APP_START):$(XL_END) xl26:$(APP_START_26):$(XL_END)
# big games that must install on their own without Enlarged Extra Apps: make check holds them to APP_SPACE
-APP_SPACE_APPS = HillClimbRacing FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator
+APP_SPACE_APPS = HillClimbRacing FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong
# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has
# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)
UPSILON_RAM = 107674
@@ -329,6 +329,7 @@ APP_angrybirds = $(B)/games/angrybirds/angrybirds.nwa:AngryBirds.nwa
APP_polytrack = $(B)/games/polytrack/polytrack.nwa:PolyTrack.nwa
APP_paperclips = $(B)/games/paperclips/paperclips.nwa:UniversalPaperclips.nwa
APP_badtime = $(B)/games/badtime/badtime.nwa:BadTimeSimulator.nwa
+APP_mahjong = $(B)/games/mahjong/mahjong.nwa:Mahjong.nwa
# the big games' modules are made from these (the kit)
$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))
@@ -369,6 +370,7 @@ apps: | $(B)
$(MAKE) -C games/polytrack build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/polytrack
$(MAKE) -C games/paperclips build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/paperclips
$(MAKE) -C games/badtime build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/badtime
+ $(MAKE) -C games/mahjong build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/mahjong
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))
@@ -407,6 +409,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_polytrack))) $(B)/apps/$(word 2,$(subst :, ,$(APP_polytrack)))
cp $(word 1,$(subst :, ,$(APP_paperclips))) $(B)/apps/$(word 2,$(subst :, ,$(APP_paperclips)))
cp $(word 1,$(subst :, ,$(APP_badtime))) $(B)/apps/$(word 2,$(subst :, ,$(APP_badtime)))
+ cp $(word 1,$(subst :, ,$(APP_mahjong))) $(B)/apps/$(word 2,$(subst :, ,$(APP_mahjong)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
@@ -486,5 +489,6 @@ clean:
-$(MAKE) -C games/polytrack clean
-$(MAKE) -C games/paperclips clean
-$(MAKE) -C games/badtime clean
+ -$(MAKE) -C games/mahjong clean
-cd games/tetris/tetris && $(CARGO) clean
-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/games/games.json b/games/games.json
index 65f808d5..c1ea0b77 100644
--- a/games/games.json
+++ b/games/games.json
@@ -677,7 +677,7 @@
},
{
"id": "championisland",
- "rank": 23,
+ "rank": 24,
"title": "Champion Island",
"tagline": "Seven sports, one island",
"credit": "Based on Google's Champion Island Games",
@@ -699,7 +699,7 @@
},
{
"id": "finalearth2",
- "rank": 24,
+ "rank": 25,
"title": "The Final Earth 2",
"tagline": "Build a city in space",
"credit": "Based on the game by Florian van Strien",
@@ -721,7 +721,7 @@
},
{
"id": "numpowder",
- "rank": 17,
+ "rank": 18,
"title": "NumPowder",
"tagline": "Sand, water, fire and more",
"credit": "Inspired by The Powder Toy",
@@ -775,7 +775,7 @@
},
{
"id": "fnaf",
- "rank": 15,
+ "rank": 16,
"title": "Five Nights at Freddy's",
"tagline": "Survive five nights",
"credit": "Based on the game by Scott Cawthon",
@@ -836,7 +836,7 @@
},
{
"id": "isaac",
- "rank": 19,
+ "rank": 20,
"title": "The Binding of Isaac",
"tagline": "Cry through the basement",
"credit": "Based on the game by Edmund McMillen",
@@ -858,7 +858,7 @@
},
{
"id": "hillclimb",
- "rank": 20,
+ "rank": 21,
"title": "Hill Climb Racing",
"tagline": "Drive up, don't flip",
"credit": "Based on Hill Climb Racing by Fingersoft",
@@ -902,7 +902,7 @@
},
{
"id": "sonic",
- "rank": 18,
+ "rank": 19,
"title": "Sonic the Hedgehog",
"tagline": "Run through six zones",
"credit": "Based on the game by Sonic Team",
@@ -923,7 +923,7 @@
},
{
"id": "cookieclicker",
- "rank": 26,
+ "rank": 27,
"title": "Cookie Clicker",
"tagline": "Bake billions of cookies",
"credit": "Based on Cookie Clicker by Orteil",
@@ -944,7 +944,7 @@
},
{
"id": "leveldevil",
- "rank": 25,
+ "rank": 26,
"title": "Level Devil",
"tagline": "Run to the door",
"credit": "Based on Level Devil by Unept",
@@ -1007,7 +1007,7 @@
},
{
"id": "donkeykong",
- "rank": 16,
+ "rank": 17,
"title": "Donkey Kong",
"tagline": "Climb the girders and save Pauline",
"credit": "Based on Donkey Kong by Nintendo",
@@ -1133,7 +1133,7 @@
},
{
"id": "turborush",
- "rank": 21,
+ "rank": 22,
"title": "Turbo Rush",
"tagline": "Race seven rivals on six circuits",
"credit": "A game by Bobydeluxe",
@@ -1195,7 +1195,7 @@
},
{
"id": "polytrack",
- "rank": 22,
+ "rank": 23,
"title": "PolyTrack",
"tagline": "Time trials on 17 low-poly tracks",
"credit": "Based on PolyTrack by Kodub",
@@ -1217,7 +1217,7 @@
},
{
"id": "paperclips",
- "rank": 27,
+ "rank": 28,
"title": "Universal Paperclips",
"tagline": "Turn everything into paperclips",
"credit": "Based on Universal Paperclips by Frank Lantz",
@@ -1238,7 +1238,7 @@
},
{
"id": "badtime",
- "rank": 28,
+ "rank": 29,
"title": "Bad Time Simulator",
"tagline": "Dodge the Judge's 24 attacks",
"credit": "Inspired by Bad Time Simulator by jcw87 and Undertale by Toby Fox",
@@ -1256,5 +1256,26 @@
"repo": "https://github.com/Mason363/NumPlay/tree/main/games/badtime",
"default": false,
"xl": true
+ },
+ {
+ "id": "mahjong",
+ "rank": 15,
+ "title": "Mahjong",
+ "tagline": "Match free tiles, clear the board",
+ "credit": "Layouts from KMahjongg",
+ "top": "0x23774D",
+ "bottom": "0x0E3524",
+ "accent": "0xFFC93C",
+ "colors": 16,
+ "records": [
+ "mahjong.sav",
+ "mahjong_saves.py"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/mahjong",
+ "default": false,
+ "xl": true
}
]
diff --git a/games/mahjong/.gitignore b/games/mahjong/.gitignore
new file mode 100644
index 00000000..342d9dda
--- /dev/null
+++ b/games/mahjong/.gitignore
@@ -0,0 +1,2 @@
+output/
+build/
diff --git a/games/mahjong/Makefile b/games/mahjong/Makefile
new file mode 100644
index 00000000..cf01dcc4
--- /dev/null
+++ b/games/mahjong/Makefile
@@ -0,0 +1,91 @@
+# Mahjong: Mahjong solitaire on the NumWorks calculator, an app of its own.
+# make output/mahjong.nwa
+# make check link it like the calculator does (output/mahjong.bin), within the RAM and the app space
+# make host build/play: the game on a computer, for tests and pictures
+# make test the rules, deals that can be won (every layout, many seeds), shuffles, a game won with the keys,
+# saves (kept, damaged, from the copy) and random keys, with the sanitizers
+# make data src/art.h and src/layouts.h (FONT: Fusion Pixel 12px's traditional Chinese BDF; LAYOUTS:
+# KMahjongg's layouts folder)
+Q ?= @
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+L = ../../launcher/src
+PYTHON ?= python3
+FONT ?= $(HOME)/Documents/Assets/gamesrc/mahjong/fusion/x/fusion-pixel-12px-monospaced-zh_hant.bdf
+LAYOUTS ?= $(HOME)/Documents/Assets/gamesrc/mahjong/kmahjongg
+
+SRC = src/main.c $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c
+HEADERS = src/art.h src/layouts.h $(L)/gfx.h $(L)/font.h $(L)/np.h ../common/epsilon_app.h ../common/epsilon_files.h \
+ ../common/np_text.h ../common/np_lz.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1 -I$(L)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections
+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
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones), and the
+# calculator's app space is 2031616 bytes
+RAM = 133652
+APP_SPACE = 2031616
+
+.PHONY: build check clean host test data perf
+build: $(BUILD_DIR)/mahjong.nwa
+
+check: $(BUILD_DIR)/mahjong.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM) $< $(BUILD_DIR)/mahjong.bin
+ $(Q) n=$$(wc -c < $(BUILD_DIR)/mahjong.bin); [ $$n -le $(APP_SPACE) ] || \
+ { echo "mahjong.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; \
+ echo "BIN $(BUILD_DIR)/mahjong.bin: $$n bytes, RAM within $(RAM) bytes"
+
+$(BUILD_DIR)/obj/%.o: src/%.c $(HEADERS) | $(BUILD_DIR)
+ @mkdir -p $(@D)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/obj/%.o: $(L)/%.c $(HEADERS) | $(BUILD_DIR)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+
+OBJ = $(patsubst %.c,$(BUILD_DIR)/obj/%.o,$(notdir $(SRC)))
+$(BUILD_DIR)/mahjong.nwa: $(OBJ) $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+ $(Q) $(STRIP) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# every frame drawn, at an N0110's speed in tools/emu.py: how long one takes (a game, the cursor going round)
+$(BUILD_DIR)/perf.nwa: $(SRC) $(HEADERS) $(BUILD_DIR)/icon.o
+ $(Q) $(CC) $(CFLAGS) -DPERF $(LDFLAGS) $(SRC) $(BUILD_DIR)/icon.o -o $@
+perf: $(BUILD_DIR)/perf.nwa
+ $(PYTHON) ../../tools/emu.py $< --nwlink "$(NWLINK)" --ms 9000 --out $(BUILD_DIR) \
+ --keys "600-700:ok,1200-1300:ok,2000-2100:shift,2500-4500:right,4600-6500:down,6600-8000:left,8100-8200:shift"
+
+data:
+ $(PYTHON) tools/art.py $(FONT)
+ $(PYTHON) -I tools/layouts.py $(LAYOUTS)
+
+# on a computer: tests/play.c checks the game and saves pictures
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -DPLATFORM_DEVICE=1 -DHOST -I$(L) \
+ $(shell $(NWLINK) eadk-cflags-simulator) -fsanitize=address,undefined -fno-sanitize-recover=undefined
+host: build/play
+build/play: tests/play.c $(SRC) $(HEADERS)
+ $(Q) mkdir -p build
+ $(Q) cc $(HOST_FLAGS) tests/play.c $(L)/gfx.c $(L)/font_data.c $(L)/xfont.c -lm -o $@
+ @echo "HOST $@"
+test: build/play
+ build/play test
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/mahjong/README.md b/games/mahjong/README.md
new file mode 100644
index 00000000..448a5b3f
--- /dev/null
+++ b/games/mahjong/README.md
@@ -0,0 +1,85 @@
+> **Mahjong is a [NumPlay](../../README.md) game that comes on its own.** NumPlay fills the calculator, so there is no room for it next to NumPlay. Get `Mahjong.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+<p align="center">
+ <img src="src/icon.png" width="84" alt="Mahjong icon">
+</p>
+
+<h1 align="center">Mahjong</h1>
+
+<p align="center">
+ <b>Mahjong solitaire for the NumWorks calculator.</b><br>
+ 144 tiles in the Turtle and three more layouts. Match free tiles until the board is clear.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/Mahjong.nwa"><b>Download Mahjong.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+<p align="center">
+ <img src="../../docs/media/gallery/mahjong.gif" width="640" alt="Pairs of matching tiles taken from the Turtle, then a hint lights up two tiles and a pair is undone">
+</p>
+
+## Highlights
+
+* **The full set of 144 tiles:** dots, bamboo and characters from 1 to 9, the four winds and the three dragons, four of each, plus the four flowers and the four seasons.
+* **Four layouts:** the classic Turtle, five layers high, and the Dragon, the Crab and the Spider.
+* **Every deal can be won.** If you get stuck, that's from the pairs you chose, and Undo or a shuffle gets you out.
+* **Hint** shows two free tiles that match, and another pair each time you ask. **Undo** goes back as far as you like.
+* **No moves left?** The game tells you and offers to shuffle the tiles still on the board, so you can still win.
+* **Tiles you can read:** ivory tiles with their edge and green back showing, higher layers lighter, and shadows under them. The arrows only stop on tiles you can take.
+* **Saved:** your game and your best time on each layout. Home saves and quits from anywhere. Everything is also copied into `mahjong_saves.py`, so installing the app again doesn't erase it.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/shot.png" width="390" alt="The Turtle, a tile picked in gold and the cursor on another"><br><sub>The Turtle</sub></td>
+ <td align="center"><img src="docs/dragon.png" width="390" alt="The Dragon layout"><br><sub>The Dragon</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/crab.png" width="390" alt="The Crab layout"><br><sub>The Crab</sub></td>
+ <td align="center"><img src="docs/spider.png" width="390" alt="The Spider layout"><br><sub>The Spider</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/layouts.png" width="390" alt="The four layouts with their best times"><br><sub>Your best time on each layout</sub></td>
+ <td align="center"><img src="docs/win.png" width="390" alt="You win! with the time and a new best"><br><sub>Board cleared</sub></td>
+ </tr>
+</table>
+
+## How to play
+
+Take the tiles away in pairs that match. You can only take a free tile: nothing lies on it, and its left or right side is open. Two tiles match when they are the same, and any flower goes with any flower, any season with any season. Clear the whole board to win.
+
+Move to a tile with the arrows and press **OK** to pick it: it turns gold. Then pick a free tile that matches it and both go away. Upper layers block what's under them, so start from the top and the ends of the rows.
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| Arrows | Jump to the nearest free tile that way |
+| OK or EXE | Pick a tile, or take it with the one you picked |
+| Shift | Hint: two free tiles that match |
+| Backspace | Undo the last pair |
+| Back | Pause: Resume, New game, How to play, Quit game |
+| Home | Save and quit |
+
+8, 4, 6 and 2 work as the arrows. The line at the bottom always shows the keys.
+
+## Good to know
+
+* **On its own:** installing Mahjong from the NumWorks website swaps out NumPlay and the other apps, and installing NumPlay again swaps it back out. Your progress in each one is kept.
+* **Quit game** in the pause menu asks first.
+* The clock only runs while you play, not while the game is paused.
+* A shuffle keeps the same tiles and lays them out again so the game can still be won.
+* There is no music or sound: the calculator has no speaker.
+
+## Credits
+
+Made by Mason Chen as part of NumPlay, inspired by Mahjong solitaire, first made by **Brodie Lockard** (Mah-Jongg, 1981) and made famous by Activision's **Shanghai** (1986). Not affiliated with them.
+
+* The tiles are drawn from scratch from the traditional designs. Their Chinese characters (the numbers, 萬, the winds and the dragons) come from **Fusion Pixel** 12px by TakWolf (SIL Open Font License).
+* The four layouts come from **KMahjongg** by the KDE Games team (the Dragon, the Crab and the Spider by alchark).
+* The key line and the menus use NumPlay's **Nunito** (SIL Open Font License).
+
+## License
+
+The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. KMahjongg is free software under the GNU GPL. Fusion Pixel and Nunito keep the SIL Open Font License (`LICENSES/OFL-1.1-Fusion-Pixel.txt`, `LICENSES/OFL-1.1-Nunito.txt`).
diff --git a/games/mahjong/docs/crab.png b/games/mahjong/docs/crab.png
new file mode 100644
index 00000000..2b5cd86f
Binary files /dev/null and b/games/mahjong/docs/crab.png differ
diff --git a/games/mahjong/docs/dragon.png b/games/mahjong/docs/dragon.png
new file mode 100644
index 00000000..eb1e84fa
Binary files /dev/null and b/games/mahjong/docs/dragon.png differ
diff --git a/games/mahjong/docs/layouts.png b/games/mahjong/docs/layouts.png
new file mode 100644
index 00000000..6be8ca19
Binary files /dev/null and b/games/mahjong/docs/layouts.png differ
diff --git a/games/mahjong/docs/shot.png b/games/mahjong/docs/shot.png
new file mode 100644
index 00000000..ad66c53a
Binary files /dev/null and b/games/mahjong/docs/shot.png differ
diff --git a/games/mahjong/docs/spider.png b/games/mahjong/docs/spider.png
new file mode 100644
index 00000000..025d608d
Binary files /dev/null and b/games/mahjong/docs/spider.png differ
diff --git a/games/mahjong/docs/win.png b/games/mahjong/docs/win.png
new file mode 100644
index 00000000..ea6378b3
Binary files /dev/null and b/games/mahjong/docs/win.png differ
diff --git a/games/mahjong/src/art.h b/games/mahjong/src/art.h
new file mode 100644
index 00000000..b0eadf1f
--- /dev/null
+++ b/games/mahjong/src/art.h
@@ -0,0 +1,96 @@
+/* Generated by tools/art.py: the faces of the 42 kinds of tiles, 18 x 24 pixels of 16 colours (0: none),
+ * four bits a pixel (the left one low), packed with np_lz.h. The characters are Fusion Pixel 12px's. */
+#define ART_W 18
+#define ART_H 24
+#define ART_KINDS 42
+#define ART_RAW 9072
+static const uint32_t art_pal[16] = {0x000000, 0x1A1A1A, 0x1F3C88, 0xC62828, 0x2E7D32, 0x7CC576, 0x1E66C8, 0x14532D, 0xF2A900, 0xE5508A, 0x9147C8, 0xEC6A12, 0x3FA9E6, 0xFFFFFF, 0x7A4A2A, 0xF7C6D6};
+static const uint8_t art_lz[2069] = {
+ 249, 0, 0, 240, 18, 240, 0, 64, 68, 68, 68, 125, 4, 42, 16, 68, 221, 221, 221, 68, 16, 16, 223, 221,
+ 102, 102, 102, 221, 18, 0, 212, 109, 255, 214, 221, 109, 214, 77, 0, 64, 212, 255, 214, 221, 51, 221, 109, 77,
+ 4, 64, 127, 109, 214, 51, 51, 51, 109, 214, 8, 0, 95, 221, 211, 51, 61, 221, 8, 16, 61, 17, 0, 1,
+ 211, 8, 160, 26, 96, 44, 80, 62, 80, 80, 96, 98, 112, 116, 96, 192, 134, 112, 181, 240, 199, 240, 217, 240,
+ 198, 0, 61, 64, 212, 221, 244, 96, 0, 198, 32, 68, 97, 32, 0, 64, 77, 68, 1, 212, 224, 48, 8, 0,
+ 107, 48, 17, 80, 35, 96, 53, 96, 71, 112, 142, 61, 241, 96, 102, 6, 82, 49, 22, 1, 16, 48, 221, 123,
+ 102, 221, 18, 32, 96, 109, 102, 214, 27, 32, 5, 102, 8, 0, 102, 17, 160, 35, 96, 53, 96, 71, 112, 160,
+ 241, 178, 178, 65, 102, 67, 32, 113, 0, 214, 109, 114, 48, 96, 193, 109, 95, 48, 8, 240, 35, 112, 53, 96,
+ 247, 145, 48, 51, 93, 3, 6, 50, 211, 221, 61, 8, 64, 51, 8, 224, 72, 26, 80, 44, 96, 57, 146, 68,
+ 158, 33, 39, 2, 212, 193, 1, 0, 79, 49, 78, 49, 8, 240, 35, 112, 53, 96, 131, 242, 149, 50, 73, 17,
+ 197, 64, 233, 32, 6, 129, 18, 233, 0, 55, 1, 68, 77, 59, 77, 4, 74, 1, 109, 0, 212, 177, 1, 8,
+ 112, 160, 26, 80, 44, 96, 62, 112, 226, 242, 244, 242, 0, 221, 18, 96, 202, 201, 32, 4, 195, 1, 102, 207,
+ 2, 6, 2, 102, 109, 59, 109, 6, 25, 2, 77, 0, 214, 186, 1, 8, 112, 0, 26, 80, 44, 96, 62, 112,
+ 78, 243, 25, 114, 206, 32, 93, 0, 175, 17, 0, 40, 17, 175, 33, 40, 17, 8, 240, 35, 96, 53, 96, 175,
+ 241, 175, 241, 0, 175, 241, 175, 241, 75, 48, 139, 0, 93, 48, 59, 2, 170, 33, 59, 18, 0, 8, 240, 35,
+ 96, 53, 96, 46, 244, 27, 4, 23, 20, 10, 20, 15, 4, 1, 64, 88, 3, 58, 33, 166, 17, 8, 96, 26,
+ 96, 44, 112, 119, 244, 248, 142, 130, 148, 4, 146, 18, 211, 221, 3, 0, 48, 254, 146, 2, 48, 211, 211, 51,
+ 0, 51, 61, 3, 61, 3, 8, 96, 26, 96, 44, 112, 62, 240, 62, 240, 62, 240, 196, 62, 224, 34, 100, 64,
+ 244, 67, 103, 2, 245, 67, 68, 221, 1, 68, 64, 52, 70, 4, 29, 240, 29, 240, 59, 192, 58, 244, 120, 35,
+ 6, 124, 35, 51, 221, 224, 0, 3, 0, 120, 35, 124, 35, 8, 96, 32, 26, 96, 44, 96, 53, 240, 53, 240,
+ 53, 240, 0, 114, 20, 118, 20, 17, 96, 142, 4, 3, 16, 212, 2, 109, 3, 32, 8, 112, 26, 96, 0, 44,
+ 96, 53, 240, 53, 240, 53, 240, 107, 240, 107, 240, 107, 240, 161, 240, 0, 161, 240, 161, 240, 15, 117, 2, 64,
+ 223, 0, 2, 48, 223, 0, 2, 192, 200, 26, 96, 44, 96, 254, 246, 0, 125, 2, 2, 32, 48, 221, 129, 3,
+ 2, 48, 197, 6, 2, 192, 26, 96, 44, 96, 70, 247, 0, 0, 38, 7, 2, 32, 72, 2, 2, 48, 72, 2,
+ 2, 192, 26, 96, 44, 96, 112, 142, 247, 160, 247, 163, 48, 185, 181, 51, 49, 67, 24, 55, 193, 51, 203, 85,
+ 69, 35, 244, 166, 195, 7, 204, 55, 84, 69, 206, 204, 55, 64, 85, 85, 184, 21, 199, 4, 85, 85, 172, 18,
+ 0, 160, 4, 68, 84, 18, 0, 100, 110, 37, 84, 67, 85, 68, 97, 38, 249, 7, 16, 16, 3, 40, 100, 114,
+ 54, 110, 70, 103, 176, 0, 11, 63, 56, 11, 176, 71, 56, 65, 238, 0, 16, 82, 248, 100, 248, 125, 245, 103,
+ 56, 69, 8, 208, 3, 112, 119, 26, 240, 53, 208, 195, 248, 213, 248, 107, 240, 107, 240, 0, 107, 240, 107, 240,
+ 47, 249, 65, 249, 215, 240, 215, 240, 215, 240, 215, 240, 48, 155, 249, 173, 249, 161, 105, 235, 86, 84, 4, 2,
+ 16, 8, 144, 3, 119, 7, 2, 16, 26, 240, 53, 144, 6, 250, 24, 250, 107, 240, 0, 107, 240, 107, 240, 107,
+ 240, 114, 250, 132, 250, 215, 240, 215, 240, 215, 240, 0, 215, 240, 222, 250, 240, 250, 66, 129, 111, 56, 63, 33,
+ 68, 17, 8, 96, 208, 63, 33, 68, 17, 26, 240, 160, 8, 3, 102, 72, 48, 63, 0, 80, 89, 8, 96, 168,
+ 99, 26, 192, 53, 96, 107, 240, 107, 240, 107, 144, 0, 210, 248, 193, 251, 26, 242, 152, 7, 26, 34, 95, 3,
+ 215, 48, 8, 64, 3, 119, 7, 95, 3, 215, 48, 26, 208, 53, 96, 33, 252, 51, 252, 0, 107, 240, 107, 240,
+ 107, 240, 107, 240, 141, 252, 159, 156, 120, 90, 103, 241, 0, 103, 241, 139, 97, 53, 96, 13, 241, 13, 241, 13,
+ 241, 13, 241, 85, 241, 160, 85, 241, 85, 241, 85, 241, 121, 253, 174, 177, 4, 174, 65, 64, 25, 69, 8, 96,
+ 174, 65, 112, 119, 26, 240, 53, 96, 208, 253, 0, 226, 253, 107, 240, 107, 240, 107, 240, 107, 240, 60, 254, 144,
+ 164, 225, 82, 24, 23, 3, 77, 51, 8, 64, 119, 7, 226, 9, 77, 51, 26, 208, 0, 77, 131, 71, 240, 71,
+ 240, 71, 240, 71, 240, 143, 240, 143, 240, 143, 240, 96, 143, 240, 41, 255, 59, 255, 77, 255, 95, 79, 32, 34,
+ 0, 16, 112, 108, 255, 126, 255, 242, 210, 154, 45, 48, 51, 51, 2, 0, 0, 17, 144, 232, 7, 234, 71, 34,
+ 16, 191, 45, 17, 224, 53, 0, 138, 15, 52, 224, 29, 163, 4, 3, 4, 0, 0, 48, 18, 16, 8, 32, 16,
+ 69, 152, 255, 255, 255, 63, 179, 16, 2, 110, 255, 128, 255, 146, 255, 0, 251, 240, 215, 240, 215, 240, 215, 240,
+ 233, 240, 215, 240, 215, 240, 255, 255, 0, 206, 240, 192, 255, 176, 225, 227, 255, 245, 255, 220, 193, 175, 241, 175,
+ 241, 224, 175, 241, 175, 241, 175, 241, 175, 241, 90, 210, 32, 0, 2, 7, 0, 2, 32, 8, 240, 26, 240, 144,
+ 18, 40, 0, 53, 48, 0, 225, 17, 53, 48, 8, 224, 215, 240, 135, 242, 135, 242, 135, 242, 135, 242, 128, 135,
+ 242, 255, 255, 126, 114, 154, 32, 8, 240, 162, 66, 226, 63, 2, 0, 37, 80, 8, 224, 18, 1, 8, 176, 175,
+ 241, 95, 243, 95, 243, 113, 243, 0, 95, 243, 95, 243, 49, 255, 171, 32, 8, 240, 37, 244, 65, 196, 197, 128,
+ 0, 64, 48, 154, 19, 8, 96, 193, 161, 55, 244, 55, 244, 55, 244, 55, 244, 160, 55, 244, 55, 244, 162, 176,
+ 166, 241, 184, 81, 32, 253, 52, 32, 0, 81, 52, 15, 5, 211, 241, 234, 240, 250, 97, 95, 243, 15, 245, 15,
+ 245, 0, 15, 245, 15, 245, 15, 245, 7, 245, 5, 117, 185, 209, 113, 3, 8, 224, 0, 117, 242, 191, 50, 175,
+ 161, 117, 83, 175, 241, 231, 245, 231, 245, 231, 245, 0, 231, 245, 231, 245, 134, 242, 143, 242, 173, 102, 224, 240,
+ 242, 192, 105, 4, 0, 8, 112, 60, 36, 43, 6, 127, 68, 91, 68, 191, 246, 191, 246, 191, 246, 0, 191, 246,
+ 191, 246, 191, 246, 202, 255, 220, 255, 238, 255, 122, 243, 158, 115, 96, 254, 102, 228, 17, 7, 39, 17, 240, 34,
+ 119, 2, 2, 171, 84, 12, 12, 49, 87, 5, 2, 0, 241, 247, 225, 255, 243, 255, 255, 255, 0, 82, 255, 100,
+ 255, 100, 244, 215, 240, 47, 246, 47, 54, 13, 6, 20, 54, 0, 166, 8, 11, 70, 79, 53, 17, 240, 237, 33,
+ 201, 248, 244, 255, 255, 255, 0, 255, 255, 192, 255, 210, 255, 71, 249, 71, 57, 122, 211, 7, 247, 16, 247, 0,
+ 245, 246, 236, 246, 232, 255, 250, 255, 255, 255, 255, 255, 196, 255, 214, 255, 0, 19, 150, 228, 86, 8, 144, 133,
+ 55, 212, 7, 99, 66, 120, 81, 44, 224, 13, 32, 62, 64, 32, 2, 53, 64, 62, 96, 25, 23, 121, 250, 0,
+ 244, 255, 255, 255, 255, 255, 190, 255, 208, 255, 181, 253, 190, 189, 148, 170, 0, 135, 42, 8, 240, 184, 106, 62,
+ 240, 80, 240, 231, 255, 249, 255, 255, 255, 112, 255, 255, 86, 255, 104, 255, 83, 127, 68, 68, 64, 107, 77, 123,
+ 64, 64, 253, 63, 4, 4, 0, 4, 160, 95, 29, 64, 134, 45, 68, 4, 64, 37, 0, 236, 31, 24, 0, 14,
+ 17, 64, 4, 0, 68, 44, 32, 65, 0, 35, 80, 179, 77, 0, 25, 64, 31, 0, 1, 16, 228, 255, 246, 255,
+ 255, 255, 255, 255, 192, 255, 47, 0, 0, 96, 102, 0, 16, 6, 8, 144, 12, 0, 190, 4, 32, 96, 6, 204,
+ 204, 204, 8, 48, 12, 3, 0, 192, 8, 240, 26, 240, 44, 240, 62, 240, 80, 192, 98, 96, 160, 116, 80, 143,
+ 224, 255, 255, 50, 255, 215, 95, 48, 96, 146, 153, 189, 153, 8, 144, 48, 51, 144, 153, 0, 0, 9, 188, 255,
+ 15, 8, 96, 153, 153, 137, 152, 37, 32, 144, 7, 153, 136, 136, 26, 64, 17, 0, 35, 16, 61, 0, 63, 48,
+ 30, 8, 240, 0, 144, 9, 148, 34, 32, 187, 33, 255, 31, 245, 85, 8, 96, 85, 116, 79, 80, 85, 5, 4,
+ 27, 80, 5, 27, 48, 4, 85, 8, 32, 249, 15, 39, 0, 192, 213, 79, 8, 240, 255, 255, 206, 144, 163, 45,
+ 65, 67, 170, 170, 92, 180, 77, 8, 48, 51, 160, 170, 0, 0, 10, 235, 15, 222, 8, 96, 170, 170, 138, 168,
+ 37, 32, 160, 170, 3, 136, 136, 26, 64, 17, 0, 35, 16, 61, 0, 63, 32, 8, 240, 6, 63, 0, 10, 164,
+ 34, 32, 215, 240, 215, 240, 215, 240, 215, 240, 152, 215, 240, 215, 240, 25, 132, 136, 136, 233, 64, 8, 32, 48,
+ 151, 3, 128, 136, 0, 0, 8, 255, 15, 8, 96, 136, 247, 136, 56, 131, 37, 32, 128, 136, 51, 51, 192, 26,
+ 64, 17, 0, 35, 16, 61, 0, 63, 48, 8, 240, 0, 128, 3, 8, 132, 34, 32, 175, 241, 175, 241, 175, 241,
+ 175, 241, 175, 241, 48, 126, 82, 166, 81, 8, 112, 168, 15, 187, 187, 193, 65, 8, 64, 203, 176, 187, 0, 0,
+ 11, 255, 15, 8, 96, 187, 187, 123, 139, 184, 37, 32, 176, 187, 136, 136, 26, 64, 224, 17, 0, 35, 16, 61,
+ 0, 63, 48, 8, 240, 0, 176, 11, 1, 180, 34, 32, 135, 242, 135, 242, 135, 242, 135, 242, 135, 242, 255, 95,
+ 16, 134, 83, 27, 36, 17, 160, 26, 112, 102, 255, 255, 255, 255, 42, 19, 112, 23, 35, 32, 3, 45, 19, 50,
+ 19, 85, 80, 85, 33, 19, 130, 5, 0, 84, 17, 32, 60, 3, 41, 83, 86, 69, 8, 240, 0, 15, 0, 238,
+ 238, 14, 7, 64, 9, 80, 233, 255, 251, 255, 4, 252, 196, 94, 100, 96, 233, 224, 32, 117, 250, 255, 210, 246,
+ 192, 102, 32, 243, 47, 229, 63, 228, 49, 230, 49, 8, 160, 51, 1, 18, 170, 36, 0, 26, 224, 53, 112, 71,
+ 80, 89, 112, 228, 246, 43, 255, 215, 240, 175, 209, 160, 233, 80, 202, 113, 113, 255, 253, 31, 89, 82, 176, 151,
+ 64, 11, 28, 8, 0, 144, 50, 176, 187, 176, 180, 50, 199, 66, 207, 34, 200, 227, 34, 216, 162, 245, 18, 187,
+ 44, 16, 199, 50, 48, 59, 0, 4, 248, 235, 255, 253, 255, 172, 166, 188, 96, 197, 96, 117, 98, 176, 113, 212,
+ 105, 255, 123, 159, 12, 7, 80, 12, 9, 32, 192, 0, 67, 192, 204, 4, 0, 24, 32, 1, 16, 18, 32, 12,
+ 16, 80, 52, 35, 0, 47, 0, 192, 7, 7, 204, 204, 17, 144, 35, 96, 0, 53, 96, 71, 112, 89, 80, 107,
+ 128, 251, 255, 255, 47,
+};
diff --git a/games/mahjong/src/icon.png b/games/mahjong/src/icon.png
new file mode 100644
index 00000000..e2da834e
Binary files /dev/null and b/games/mahjong/src/icon.png differ
diff --git a/games/mahjong/src/layouts.h b/games/mahjong/src/layouts.h
new file mode 100644
index 00000000..1f2cc33f
--- /dev/null
+++ b/games/mahjong/src/layouts.h
@@ -0,0 +1,62 @@
+/* Generated by tools/layouts.py from KMahjongg's layouts (GPL-2.0-or-later): each tile's x in half tiles,
+ * then its y in half tiles + 16 x its layer, in the order they're drawn (layer, x, y). */
+#define LAYOUTS 4
+static const char *const layout_name[LAYOUTS] = {T("Turtle"), T("Dragon"), T("Crab"), T("Spider")};
+static const uint8_t layout_tiles[LAYOUTS][288] = {
+ { /* Turtle */
+ 1, 7, 3, 0, 3, 6, 3, 8, 3, 14, 5, 0, 5, 4, 5, 6, 5, 8, 5, 10, 5, 14, 7, 0,
+ 7, 2, 7, 4, 7, 6, 7, 8, 7, 10, 7, 12, 7, 14, 9, 0, 9, 2, 9, 4, 9, 6, 9, 8,
+ 9, 10, 9, 12, 9, 14, 11, 0, 11, 2, 11, 4, 11, 6, 11, 8, 11, 10, 11, 12, 11, 14, 13, 0,
+ 13, 2, 13, 4, 13, 6, 13, 8, 13, 10, 13, 12, 13, 14, 15, 0, 15, 2, 15, 4, 15, 6, 15, 8,
+ 15, 10, 15, 12, 15, 14, 17, 0, 17, 2, 17, 4, 17, 6, 17, 8, 17, 10, 17, 12, 17, 14, 19, 0,
+ 19, 2, 19, 4, 19, 6, 19, 8, 19, 10, 19, 12, 19, 14, 21, 0, 21, 2, 21, 4, 21, 6, 21, 8,
+ 21, 10, 21, 12, 21, 14, 23, 0, 23, 4, 23, 6, 23, 8, 23, 10, 23, 14, 25, 0, 25, 6, 25, 8,
+ 25, 14, 27, 7, 29, 7, 9, 18, 9, 20, 9, 22, 9, 24, 9, 26, 9, 28, 11, 18, 11, 20, 11, 22,
+ 11, 24, 11, 26, 11, 28, 13, 18, 13, 20, 13, 22, 13, 24, 13, 26, 13, 28, 15, 18, 15, 20, 15, 22,
+ 15, 24, 15, 26, 15, 28, 17, 18, 17, 20, 17, 22, 17, 24, 17, 26, 17, 28, 19, 18, 19, 20, 19, 22,
+ 19, 24, 19, 26, 19, 28, 11, 36, 11, 38, 11, 40, 11, 42, 13, 36, 13, 38, 13, 40, 13, 42, 15, 36,
+ 15, 38, 15, 40, 15, 42, 17, 36, 17, 38, 17, 40, 17, 42, 13, 54, 13, 56, 15, 54, 15, 56, 14, 71,
+ },
+ { /* Dragon */
+ 1, 1, 1, 3, 1, 5, 3, 0, 3, 6, 5, 0, 5, 3, 5, 6, 5, 10, 5, 12, 5, 14, 7, 0,
+ 7, 6, 7, 8, 7, 10, 7, 14, 9, 1, 9, 6, 9, 10, 9, 13, 11, 2, 11, 4, 11, 6, 11, 8,
+ 11, 10, 11, 14, 13, 2, 13, 10, 13, 13, 15, 2, 15, 6, 15, 10, 15, 14, 17, 2, 17, 10, 17, 13,
+ 19, 2, 19, 4, 19, 6, 19, 8, 19, 10, 19, 14, 21, 1, 21, 6, 21, 10, 21, 13, 23, 0, 23, 6,
+ 23, 8, 23, 10, 23, 14, 24, 3, 25, 0, 25, 6, 25, 10, 25, 12, 25, 14, 27, 0, 27, 6, 29, 1,
+ 29, 3, 29, 5, 1, 17, 1, 19, 1, 21, 3, 16, 3, 22, 5, 16, 5, 19, 5, 22, 5, 26, 5, 28,
+ 5, 30, 7, 16, 7, 22, 7, 24, 9, 17, 9, 29, 11, 20, 11, 22, 11, 24, 11, 26, 13, 18, 13, 26,
+ 13, 29, 15, 18, 15, 22, 15, 26, 17, 18, 17, 26, 17, 29, 19, 20, 19, 22, 19, 24, 19, 26, 21, 17,
+ 21, 29, 23, 16, 23, 22, 23, 24, 24, 19, 25, 16, 25, 22, 25, 26, 25, 28, 25, 30, 27, 16, 27, 22,
+ 29, 17, 29, 19, 29, 21, 1, 35, 5, 32, 5, 38, 5, 42, 5, 44, 5, 46, 9, 33, 9, 45, 13, 45,
+ 15, 34, 17, 45, 21, 33, 21, 45, 25, 32, 25, 38, 25, 42, 25, 44, 25, 46, 29, 35, 1, 51, 5, 48,
+ 5, 54, 5, 58, 5, 60, 9, 61, 13, 61, 17, 61, 21, 61, 25, 48, 25, 54, 25, 58, 25, 60, 29, 51,
+ },
+ { /* Crab */
+ 2, 6, 2, 8, 2, 12, 2, 14, 3, 0, 3, 2, 4, 6, 4, 12, 4, 14, 5, 0, 5, 2, 6, 10,
+ 6, 12, 6, 14, 7, 0, 7, 2, 7, 4, 8, 10, 8, 12, 8, 14, 9, 0, 9, 2, 9, 4, 10, 8,
+ 10, 10, 11, 4, 11, 6, 12, 8, 12, 10, 12, 12, 13, 4, 13, 6, 13, 14, 14, 2, 14, 8, 14, 10,
+ 14, 12, 15, 4, 15, 6, 15, 14, 16, 2, 16, 8, 16, 10, 16, 12, 17, 4, 17, 6, 17, 14, 18, 8,
+ 18, 10, 18, 12, 19, 4, 19, 6, 20, 8, 20, 10, 21, 0, 21, 2, 21, 4, 22, 10, 22, 12, 22, 14,
+ 23, 0, 23, 2, 23, 4, 24, 10, 24, 12, 24, 14, 25, 0, 25, 2, 26, 6, 26, 12, 26, 14, 27, 0,
+ 27, 2, 28, 6, 28, 8, 28, 12, 28, 14, 2, 22, 2, 24, 4, 22, 4, 28, 4, 30, 5, 16, 5, 18,
+ 6, 28, 6, 30, 7, 16, 7, 18, 8, 28, 8, 30, 9, 16, 9, 18, 9, 20, 10, 26, 12, 24, 12, 26,
+ 13, 22, 13, 30, 14, 18, 14, 24, 14, 26, 15, 22, 15, 30, 16, 18, 16, 24, 16, 26, 17, 22, 17, 30,
+ 18, 24, 18, 26, 20, 26, 21, 16, 21, 18, 21, 20, 22, 28, 22, 30, 23, 16, 23, 18, 24, 28, 24, 30,
+ 25, 16, 25, 18, 26, 22, 26, 28, 26, 30, 28, 22, 28, 24, 5, 45, 6, 33, 7, 45, 8, 33, 14, 40,
+ 14, 42, 15, 34, 15, 38, 15, 46, 16, 40, 16, 42, 22, 33, 23, 45, 24, 33, 25, 45, 15, 56, 15, 58,
+ },
+ { /* Spider */
+ 1, 9, 2, 3, 2, 14, 3, 9, 4, 4, 4, 14, 5, 9, 6, 0, 6, 5, 6, 13, 7, 9, 8, 0,
+ 8, 2, 8, 5, 8, 12, 9, 8, 10, 3, 10, 6, 10, 10, 11, 8, 12, 4, 12, 6, 12, 10, 12, 12,
+ 13, 0, 13, 8, 14, 2, 14, 4, 14, 6, 14, 10, 14, 12, 14, 14, 15, 8, 16, 2, 16, 4, 16, 6,
+ 16, 10, 16, 12, 16, 14, 17, 0, 17, 8, 18, 4, 18, 6, 18, 10, 18, 12, 19, 8, 20, 3, 20, 6,
+ 20, 10, 21, 8, 22, 0, 22, 2, 22, 5, 22, 12, 23, 9, 24, 0, 24, 5, 24, 13, 25, 9, 26, 4,
+ 26, 14, 27, 9, 28, 3, 28, 14, 29, 9, 1, 25, 2, 19, 2, 30, 3, 25, 4, 20, 4, 30, 5, 25,
+ 6, 16, 6, 21, 6, 29, 7, 25, 8, 16, 8, 18, 8, 21, 8, 28, 10, 19, 11, 24, 12, 22, 12, 26,
+ 13, 16, 13, 24, 14, 20, 14, 22, 14, 26, 14, 28, 14, 30, 15, 24, 16, 20, 16, 22, 16, 26, 16, 28,
+ 16, 30, 17, 16, 17, 24, 18, 22, 18, 26, 19, 24, 20, 19, 22, 16, 22, 18, 22, 21, 22, 28, 23, 25,
+ 24, 16, 24, 21, 24, 29, 25, 25, 26, 20, 26, 30, 27, 25, 28, 19, 28, 30, 29, 25, 1, 41, 2, 35,
+ 2, 46, 5, 41, 6, 37, 6, 45, 8, 32, 10, 35, 13, 40, 14, 38, 14, 42, 14, 44, 15, 40, 16, 38,
+ 16, 42, 16, 44, 17, 40, 20, 35, 22, 32, 24, 37, 24, 45, 25, 41, 28, 35, 28, 46, 29, 41, 15, 57,
+ },
+};
diff --git a/games/mahjong/src/main.c b/games/mahjong/src/main.c
new file mode 100644
index 00000000..7d60e228
--- /dev/null
+++ b/games/mahjong/src/main.c
@@ -0,0 +1,599 @@
+/* Mahjong: Mahjong solitaire, the Shanghai kind.
+ *
+ * 144 tiles stacked in a layout: dots, bamboo and characters 1 to 9, the four winds and the three
+ * dragons, four of each, and the four flowers and four seasons, one of each. A tile is free when no
+ * tile lies on it and its left or right side is open; two free tiles that match go: the same tile,
+ * or any flower with any flower, any season with any season. Take them all away to win.
+ *
+ * Every deal can be won: the layout is played through first on blank tiles, two free tiles taken at
+ * a time, and the faces are laid on those pairs, matching pair by pair, so taking them in that order
+ * wins. Shuffling, when no two free tiles match, deals the tiles left the same way.
+ *
+ * The arrows jump from a free tile to the nearest free tile that way, so the cursor never lands on
+ * a blocked one. The faces are drawn in tools/art.py, the layouts come from tools/layouts.py. The
+ * screen is drawn in strips by NumPlay's launcher/src/gfx.c, which this app brings along. */
+#include <eadk.h>
+#include "gfx.h"
+#include "../../common/np_text.h"
+#include "../../common/np_lz.h"
+
+#ifdef HOST /* (tests/play.c: the files are the test's) */
+const uint8_t *host_read(const char *name, uint32_t *len);
+bool host_write(const char *name, const void *data, uint32_t len);
+#define file_read host_read
+#define file_write host_write
+#define np_app_begin()
+#define np_app_end() 0
+#else
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#define file_read ef_read
+#define file_write ef_write
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Mahjong";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+void np_push(int x, int y, int w, int h, const color_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+
+#include "art.h"
+#include "layouts.h"
+
+#define KEY(k) (1ull << (k))
+#define NT 144
+#define TW 20 /* a tile's face, outline included */
+#define TH 26
+#define DEP 4 /* its thickness: each layer is drawn this much up and left */
+#define BAR 224 /* the line of keys at the bottom */
+#define NONE 255
+#define FLOWER 34
+#define SEASON 38
+#define IVORY HEX(0xF5EFDD)
+#define FELT 0x1E6B45
+#define DEEP HEX(0x0E3524)
+#define GOLD HEX(0xFFC93C)
+#define FOCUS HEX(0xFF4A1C)
+
+/* mahjong.sav, and its copy in mahjong_saves.py */
+#define SAVE_NAME "mahjong.sav"
+#define COPY_NAME "mahjong_saves.py"
+static struct {
+ uint8_t magic, version, flags, layout; /* flags: 1 a game to go on with, 2 how to play was read */
+ uint8_t cur, pick, pairs, pad; /* the tile at the cursor, the tile picked (NONE), pairs taken */
+ uint32_t ms; /* the game's time */
+ uint32_t best[LAYOUTS]; /* each layout's best time, 0: none yet */
+ uint16_t wins[LAYOUTS];
+ uint8_t face[NT]; /* each tile's kind (0 to 41), + 128 once taken */
+ uint8_t hist[NT]; /* the tiles taken, two by two */
+ uint32_t sum; /* FNV-1a of everything before it */
+} sv;
+
+static color_t strip[SCREEN_W * STRIP_H];
+static uint8_t art[ART_RAW];
+static color_t pal[16];
+static uint32_t seed, now;
+
+/* the layout: each tile's place in half tiles and its layer, and the tiles around it */
+static uint8_t tx[NT], ty[NT], tz[NT];
+static uint8_t nup[NT], ndn[NT], nlf[NT], nrt[NT];
+static uint8_t up[NT][16], dn[NT][16], lf[NT][2], rt[NT][2]; /* on it, under it, beside it */
+static int ox, oy; /* where the layout is drawn */
+
+/* the game */
+static uint8_t fr[NT]; /* free tiles */
+static int left, moves; /* tiles left; pairs of free tiles that match */
+static int hint_a = -1, hint_b = -1;
+static uint32_t hint_t;
+static int ov, menu, quit_ok, best_new;
+
+static uint32_t rnd(void) {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ return seed ^= seed << 5;
+}
+static int iabs(int v) { return v < 0 ? -v : v; }
+static bool gone(int i) { return sv.face[i] >> 7; }
+static int kind(int i) { return sv.face[i] & 127; }
+static int family(int k) { return k < FLOWER ? k : k < SEASON ? FLOWER : SEASON; }
+static bool match(int a, int b) { return family(kind(a)) == family(kind(b)); }
+static int sx(int i) { return ox + tx[i] * TW / 2 - tz[i] * DEP; }
+static int sy(int i) { return oy + ty[i] * TH / 2 - tz[i] * DEP; }
+
+static void load_layout(int l) {
+ const uint8_t *p = layout_tiles[l];
+ int x0 = 999, x1 = -999, y0 = 999, y1 = -999;
+ for (int i = 0; i < NT; i++) tx[i] = p[2 * i], ty[i] = p[2 * i + 1] & 15, tz[i] = p[2 * i + 1] >> 4;
+ for (int i = 0; i < NT; i++) {
+ nup[i] = ndn[i] = nlf[i] = nrt[i] = 0;
+ for (int j = 0; j < NT; j++) {
+ int dx = tx[j] - tx[i], dy = iabs(ty[j] - ty[i]);
+ if (j == i || dy > 1) continue;
+ if (iabs(dx) < 2 && tz[j] > tz[i] && nup[i] < 16) up[i][nup[i]++] = (uint8_t)j;
+ if (iabs(dx) < 2 && tz[j] < tz[i] && ndn[i] < 16) dn[i][ndn[i]++] = (uint8_t)j;
+ if (tz[j] == tz[i] && dx == -2 && nlf[i] < 2) lf[i][nlf[i]++] = (uint8_t)j;
+ if (tz[j] == tz[i] && dx == 2 && nrt[i] < 2) rt[i][nrt[i]++] = (uint8_t)j;
+ }
+ int x = tx[i] * TW / 2 - tz[i] * DEP, y = ty[i] * TH / 2 - tz[i] * DEP;
+ x0 = x < x0 ? x : x0, x1 = x > x1 ? x : x1, y0 = y < y0 ? y : y0, y1 = y > y1 ? y : y1;
+ }
+ ox = (SCREEN_W - (x1 - x0 + TW + DEP)) / 2 - x0;
+ oy = (BAR - (y1 - y0 + TH + DEP)) / 2 - y0;
+}
+
+/* whether tile a is free among the tiles marked in `in` */
+static bool open_in(const uint8_t *in, int a) {
+ for (int k = 0; k < nup[a]; k++)
+ if (in[up[a][k]]) return false;
+ bool l = false, r = false;
+ for (int k = 0; k < nlf[a]; k++) l |= in[lf[a][k]] != 0;
+ for (int k = 0; k < nrt[a]; k++) r |= in[rt[a][k]] != 0;
+ return !(l && r);
+}
+
+/* ------------------------------------------------------------ deals that can be won */
+/* The game played through first, on blank tiles: two free tiles taken at a time, at random, until none
+ are left (or only one is free: then again). order: the tiles in the order they were taken. */
+static uint8_t order[NT];
+static bool play_through(const uint8_t *want, int n) {
+ uint8_t on[NT], fr_[NT];
+ for (int i = 0; i < NT; i++) on[i] = want[i];
+ for (int done = 0; done < n; done += 2) {
+ int nf = 0;
+ for (int t = 0; t < NT; t++)
+ if (on[t] && open_in(on, t)) fr_[nf++] = (uint8_t)t;
+ if (nf < 2) return false;
+ int a = (int)(rnd() % (uint32_t)nf), b = (int)(rnd() % (uint32_t)(nf - 1));
+ b += b >= a;
+ order[done] = fr_[a], order[done + 1] = fr_[b], on[fr_[a]] = on[fr_[b]] = 0;
+ }
+ return true;
+}
+
+/* the faces of the tiles of `want` dealt so the game can be won from there: paired as they match, the pairs
+ given in a random order to the pairs play_through() took; false if those tiles can't be won at all */
+static bool deal(const uint8_t *want, uint8_t *faces, int n) {
+ uint8_t pairs[NT];
+ for (int i = 1; i < n; i++) /* by family, so neighbours match */
+ for (int j = i; j > 0 && family(faces[j - 1]) > family(faces[j]); j--) {
+ uint8_t f = faces[j];
+ faces[j] = faces[j - 1], faces[j - 1] = f;
+ }
+ for (int i = n / 2 - 1; i > 0; i--) { /* the pairs in a random order */
+ int j = (int)(rnd() % (uint32_t)(i + 1));
+ for (int k = 0; k < 2; k++) {
+ uint8_t f = faces[2 * i + k];
+ faces[2 * i + k] = faces[2 * j + k], faces[2 * j + k] = f;
+ }
+ }
+ for (int i = 0; i < n / 2; i++) pairs[2 * i] = faces[2 * i + (rnd() & 1)], pairs[2 * i + 1] = faces[2 * i] ^ faces[2 * i + 1] ^ pairs[2 * i];
+ for (int tries = 0; tries < 200; tries++)
+ if (play_through(want, n)) {
+ for (int i = 0; i < n; i++) sv.face[order[i]] = pairs[i];
+ return true;
+ }
+ return false;
+}
+
+/* ------------------------------------------------------------ the game */
+static int dist2(int a, int b) {
+ int dx = sx(a) - sx(b), dy = sy(a) - sy(b);
+ return dx * dx + dy * dy;
+}
+/* the free tiles and the moves left; the cursor kept on a free tile, the nearest one if its own went */
+static void refresh(void) {
+ uint8_t on[NT];
+ left = moves = 0;
+ for (int i = 0; i < NT; i++) on[i] = !gone(i), left += on[i];
+ for (int i = 0; i < NT; i++) fr[i] = on[i] && open_in(on, i);
+ for (int a = 0; a < NT; a++)
+ for (int b = a + 1; b < NT && fr[a]; b++) moves += fr[b] && match(a, b);
+ if (sv.cur >= NT || !fr[sv.cur]) {
+ int best = -1, c = sv.cur < NT ? sv.cur : 0;
+ for (int i = 0; i < NT; i++)
+ if (fr[i] && (best < 0 || dist2(i, c) < dist2(best, c))) best = i;
+ sv.cur = (uint8_t)(best < 0 ? 0 : best);
+ }
+ if (sv.pick != NONE && (sv.pick >= NT || !fr[sv.pick])) sv.pick = NONE;
+}
+
+static uint32_t fnv(const void *p, uint32_t n) {
+ uint32_t h = 2166136261u;
+ for (uint32_t i = 0; i < n; i++) h = (h ^ ((const uint8_t *)p)[i]) * 16777619u;
+ return h;
+}
+#define SUMMED (uint32_t)((uint8_t *)&sv.sum - (uint8_t *)&sv)
+
+/* the copy: the save in base 64, in a comment of a script (installing apps keeps only scripts) */
+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+static const char head[] = "# Mahjong keeps a copy of your game here,\n# so that installing it again doesn't erase it.\n#>" SAVE_NAME ":";
+static uint8_t copy[1 + sizeof head + (sizeof sv + 2) / 3 * 4 + 1];
+static void save(void) {
+ sv.magic = 'M', sv.version = 1, sv.sum = fnv(&sv, SUMMED);
+ file_write(SAVE_NAME, &sv, sizeof sv);
+ const uint8_t *s = (const uint8_t *)&sv;
+ uint8_t *p = copy;
+ *p++ = 0; /* (a script's first byte: not imported) */
+ for (const char *h = head; *h;) *p++ = (uint8_t)*h++;
+ for (uint32_t i = 0; i < sizeof sv; i += 3, p += 4) {
+ uint32_t v = (uint32_t)s[i] << 16 | (i + 1 < sizeof sv ? s[i + 1] << 8 : 0) | (i + 2 < sizeof sv ? s[i + 2] : 0);
+ for (int k = 0; k < 4; k++) p[k] = (uint8_t)(i + k - 1 < sizeof sv || k < 2 ? b64[v >> (18 - 6 * k) & 63] : '=');
+ }
+ *p++ = '\n';
+ file_write(COPY_NAME, copy, (uint32_t)(p - copy));
+}
+static bool valid(void) {
+ if (sv.magic != 'M' || sv.version != 1 || sv.sum != fnv(&sv, SUMMED) || sv.layout >= LAYOUTS) return false;
+ int count[ART_KINDS] = {0}, taken = 0;
+ for (int i = 0; i < NT; i++) {
+ if (kind(i) >= ART_KINDS) return false;
+ count[kind(i)]++, taken += gone(i);
+ }
+ if (!(sv.flags & 1)) return true; /* no game: only the times and how to play matter */
+ for (int k = 0; k < ART_KINDS; k++)
+ if (count[k] != (k < FLOWER ? 4 : 1)) return false;
+ if (sv.pairs * 2 != taken || taken >= NT) return false;
+ for (int i = 0; i < taken; i++)
+ if (sv.hist[i] >= NT || !gone(sv.hist[i])) return false;
+ return true;
+}
+static void load(void) {
+ uint32_t n = 0;
+ const uint8_t *d = file_read(SAVE_NAME, &n);
+ uint8_t *v = (uint8_t *)&sv;
+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = d && n == sizeof sv ? d[i] : 0;
+ if (valid()) return;
+ d = file_read(COPY_NAME, &n); /* the copy, after an install */
+ uint32_t o = 0, at = sizeof head; /* (the 0, then the head without its own 0) */
+ for (uint32_t i = 0; d && n >= at + (sizeof sv + 2) / 3 * 4 && i < (sizeof sv + 2) / 3 * 4; i += 4) {
+ uint32_t w = 0;
+ for (int k = 0; k < 4; k++) {
+ const char *c = b64;
+ while (*c && *c != d[at + i + k]) c++;
+ if (!*c && d[at + i + k] != '=') o = sizeof sv + 1; /* not base 64: not the copy */
+ w = w << 6 | (uint32_t)(*c ? c - b64 : 0);
+ }
+ for (int k = 0; k < 3 && o < sizeof sv; k++) v[o++] = (uint8_t)(w >> (16 - 8 * k));
+ }
+ if (o == sizeof sv && valid()) return;
+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = 0; /* neither: a fresh start */
+}
+
+static void new_game(int l) {
+ uint8_t want[NT], faces[NT];
+ sv.layout = (uint8_t)l;
+ load_layout(l);
+ for (int i = 0; i < NT; i++) want[i] = 1, faces[i] = (uint8_t)(i < 4 * FLOWER ? i / 4 : i - 3 * FLOWER);
+ deal(want, faces, NT);
+ sv.ms = 0, sv.pairs = 0, sv.pick = NONE, sv.flags |= 1, sv.cur = NT;
+ hint_a = hint_b = -1;
+ refresh();
+ /* the cursor on the free tile nearest the middle */
+ int c = -1, cd = 0;
+ for (int i = 0; i < NT; i++) {
+ int dx = sx(i) + TW / 2 - SCREEN_W / 2, dy = sy(i) + TH / 2 - BAR / 2, d = dx * dx + dy * dy;
+ if (fr[i] && (c < 0 || d < cd)) c = i, cd = d;
+ }
+ sv.cur = (uint8_t)c;
+ save();
+}
+
+enum { OV_NONE, OV_MENU, OV_NEW, OV_HELP, OV_WON, OV_STUCK };
+
+static void after_move(void) {
+ hint_a = hint_b = -1;
+ refresh();
+ if (!left) {
+ sv.flags &= (uint8_t)~1;
+ best_new = !sv.best[sv.layout] || sv.ms < sv.best[sv.layout];
+ if (best_new) sv.best[sv.layout] = sv.ms;
+ if (sv.wins[sv.layout] < 65535) sv.wins[sv.layout]++;
+ ov = OV_WON, menu = 0;
+ } else if (!moves) {
+ ov = OV_STUCK, menu = 0;
+ }
+ save();
+}
+
+/* OK on tile t: picks it, or takes it with the tile picked if they match */
+static void choose(int t) {
+ if (t >= NT || !fr[t]) return;
+ if (sv.pick == t) {
+ sv.pick = NONE;
+ } else if (sv.pick != NONE && match(sv.pick, t)) {
+ sv.face[sv.pick] |= 128, sv.face[t] |= 128;
+ sv.hist[2 * sv.pairs] = sv.pick, sv.hist[2 * sv.pairs + 1] = (uint8_t)t, sv.pairs++;
+ sv.pick = NONE;
+ after_move();
+ } else {
+ sv.pick = (uint8_t)t;
+ }
+}
+
+static void undo(void) {
+ if (!sv.pairs) return;
+ sv.pairs--;
+ int a = sv.hist[2 * sv.pairs], b = sv.hist[2 * sv.pairs + 1];
+ sv.face[a] &= 127, sv.face[b] &= 127, sv.pick = NONE, sv.cur = (uint8_t)b;
+ after_move();
+}
+
+/* a pair of free tiles that match, the next one each time */
+static void hint(void) {
+ int start = hint_a < 0 ? 0 : hint_a * NT + hint_b + 1;
+ for (int n = 0; n < NT * NT; n++) {
+ int p = (start + n) % (NT * NT), a = p / NT, b = p % NT;
+ if (a < b && fr[a] && fr[b] && match(a, b)) {
+ hint_a = a, hint_b = b, hint_t = now;
+ return;
+ }
+ }
+ ov = OV_STUCK, menu = 0;
+}
+
+static void shuffle(void) {
+ uint8_t want[NT], faces[NT];
+ int n = 0;
+ for (int i = 0; i < NT; i++)
+ if ((want[i] = !gone(i))) faces[n++] = (uint8_t)kind(i);
+ if (!deal(want, faces, n)) { /* no order of these tiles can be won: mixed anyway */
+ for (int i = n - 1; i > 0; i--) {
+ int j = (int)(rnd() % (uint32_t)(i + 1));
+ uint8_t f = faces[i];
+ faces[i] = faces[j], faces[j] = f;
+ }
+ for (int i = 0, k = 0; i < NT; i++)
+ if (want[i]) sv.face[i] = faces[k++];
+ }
+ sv.pick = NONE;
+ after_move();
+}
+
+/* the arrows: the nearest free tile that way, first among those within 45 degrees of it */
+static void step(int dx, int dy) {
+ int best = -1, bs = 0, c = sv.cur;
+ for (int j = 0; j < NT; j++) {
+ if (!fr[j] || j == c) continue;
+ int ex = sx(j) - sx(c), ey = sy(j) - sy(c), along = dx ? ex * dx : ey * dy, side = iabs(dx ? ey : ex);
+ if (along <= 0) continue;
+ int s = along + 2 * side + (side > along ? 10000 : 0);
+ if (best < 0 || s < bs) best = j, bs = s;
+ }
+ if (best >= 0) sv.cur = (uint8_t)best;
+}
+
+/* ------------------------------------------------------------ drawing */
+static char *num(char *o, uint32_t v) { /* v in o; the end of it */
+ 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 *clock_text(char *o, uint32_t ms) { /* 4:05, or 1:04:05 */
+ uint32_t s = ms / 1000;
+ char *e = o;
+ if (s >= 3600) e = num(e, s / 3600), *e++ = ':', *e++ = (char)('0' + s / 600 % 6), *e++ = (char)('0' + s / 60 % 10);
+ else e = num(e, s / 60);
+ *e++ = ':', *e++ = (char)('0' + s % 60 / 10), *e++ = (char)('0' + s % 10), *e = 0;
+ return o;
+}
+static char *cat(char *o, const char *s) {
+ while (*s) *o++ = *s++;
+ *o = 0;
+ return o;
+}
+
+static void face_art(int k, int x, int y) {
+ const uint8_t *a = art + k * (ART_W / 2 * ART_H);
+ int r0 = y < gfx_y0 ? gfx_y0 - y : 0, r1 = y + ART_H > gfx_y1 ? gfx_y1 - y : ART_H;
+ for (int r = r0; r < r1; r++) {
+ color_t *o = gfx_buf + (y + r - gfx_y0) * SCREEN_W + x;
+ const uint8_t *s = a + r * (ART_W / 2);
+ for (int c = 0; c < ART_W; c += 2) {
+ int v = s[c >> 1];
+ if (v & 15) o[c] = pal[v & 15];
+ if (v >> 4) o[c + 1] = pal[v >> 4];
+ }
+ }
+}
+
+static void box(int x, int y, int w, int h, int t, color_t c) {
+ gfx_fill(x, y, w, t, c), gfx_fill(x, y + h - t, w, t, c);
+ gfx_fill(x, y + t, t, h - 2 * t, c), gfx_fill(x + w - t, y + t, t, h - 2 * t, c);
+}
+
+/* a tile: its sides (ivory, then the green back), its face, lighter the higher it lies, and its picture */
+static const uint32_t layer_face[6] = {0xD9CFB4, 0xE6DDC6, 0xF1EAD7, 0xF8F3E6, 0xFFFDF6, 0xFFFFFF};
+static void tile(int i) {
+ int x = sx(i), y = sy(i), z = tz[i];
+ if (y >= gfx_y1 || y + TH + DEP + 3 <= gfx_y0) return; /* (its shadow included) */
+ static const uint32_t sides[DEP] = {0xCDBF9C, 0xB9AA86, 0x2E8A57, 0x1D603B};
+ gfx_fill_alpha(x + TW + DEP, y + DEP + 2, 3, TH - 1, 0, 70); /* its shadow, on what lies below and right */
+ gfx_fill_alpha(x + DEP + 2, y + TH + DEP, TW + 1, 3, 0, 70);
+ for (int k = DEP; k >= 1; k--) {
+ color_t c = HEX(sides[k - 1]);
+ gfx_fill(x + TW - 1 + k, y + k, 1, TH - 1, c);
+ gfx_fill(x + k, y + TH - 1 + k, TW - 1, 1, c);
+ }
+ bool picked = sv.pick == i, hinted = (i == hint_a || i == hint_b) && (now - hint_t) % 700 < 450;
+ color_t edge = HEX(0x8E8368);
+ gfx_fill(x + 1, y, TW - 2, 1, edge), gfx_fill(x + 1, y + TH - 1, TW - 2, 1, edge);
+ gfx_fill(x, y + 1, 1, TH - 2, edge), gfx_fill(x + TW - 1, y + 1, 1, TH - 2, edge);
+ gfx_fill(x + 1, y + 1, TW - 2, TH - 2, picked ? GOLD : hinted ? HEX(0x8EE89A) : gfx_rgb(layer_face[z > 5 ? 5 : z]));
+ face_art(kind(i), x + 1, y + 1);
+}
+
+
+static const char *const cards[6][6] = {
+ {0},
+ {T("Paused"), T("Resume"), T("New game"), T("How to play"), T("Quit game")},
+ {T("New game"), 0, 0, 0, 0},
+ {T("How to play"), T("Play")},
+ {T("You win!"), T("New game"), T("Quit game")},
+ {T("No moves left"), T("Shuffle"), T("Undo"), T("New game")},
+};
+static const uint8_t buttons[6] = {0, 4, LAYOUTS, 1, 2, 3};
+
+static void overlay(void) {
+ char s[24];
+ int n = buttons[ov], extra = ov == OV_HELP ? 92 : ov == OV_WON ? 48 : ov == OV_STUCK ? 22 : 0;
+ int h = 52 + extra + 30 * n, y = (SCREEN_H - h) / 2;
+ gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 130);
+ gfx_rrect(50, y, 220, h, 12, DEEP, 256);
+ gfx_rrect_outline(50, y, 220, h, 12, 2, HEX(0xCDBF9C), 256);
+ gfx_text_center(&np_font_title, 160, y + 32, cards[ov][0], IVORY, 256);
+ y += 44;
+ if (ov == OV_HELP)
+ gfx_paragraph(&np_font_body, 160, y + 10, 196, 15,
+ T("Take the tiles away in pairs that match. A tile is free when nothing lies on it and its left or "
+ "right side is open. Any flower goes with any flower, any season with any season."),
+ IVORY, 256);
+ if (ov == OV_WON) {
+ gfx_text_center(&np_font_title, 160, y + 20, clock_text(s, sv.ms), GOLD, 256);
+ if (best_new) cat(s, T("New best!"));
+ else clock_text(cat(s, T("Best ")), sv.best[sv.layout]);
+ gfx_text_center(&np_font_body, 160, y + 40, s, IVORY, 256);
+ }
+ if (ov == OV_STUCK) gfx_text_center(&np_font_body, 160, y + 12, T("No two free tiles match."), IVORY, 256);
+ y += extra;
+ for (int i = 0; i < n; i++, y += 30) {
+ bool on = menu == i;
+ const char *t = ov == OV_NEW ? layout_name[i] : ov == OV_MENU && i == 3 && quit_ok ? T("OK again to quit") : cards[ov][i + 1];
+ gfx_rrect(66, y, 188, 26, 7, on ? GOLD : HEX(0x2B6E4C), 256);
+ if (ov == OV_NEW) {
+ gfx_text(&np_font_body, 80, y + 18, t, on ? DEEP : IVORY, 256);
+ if (sv.best[i]) gfx_text_right(&np_font_body, 240, y + 18, clock_text(s, sv.best[i]), on ? DEEP : GOLD, 256);
+ } else {
+ gfx_text_center(&np_font_body, 160, y + 18, t, on ? DEEP : IVORY, 256);
+ }
+ }
+}
+
+static void scene(void *ctx) {
+ char s[24];
+ gfx_vgrad(0, 0, SCREEN_W, BAR, 0x23774D, 0x14512F);
+ gfx_fill(0, BAR, SCREEN_W, SCREEN_H - BAR, DEEP);
+ for (int i = 0; i < NT && sv.flags & 1; i++)
+ if (!gone(i)) tile(i);
+ for (int h = 0; h < 2 && hint_a >= 0 && (now - hint_t) % 700 < 450; h++) { /* the hint's two tiles */
+ int t = h ? hint_b : hint_a;
+ box(sx(t) - 2, sy(t) - 2, TW + 4, TH + 4, 2, HEX(0x1FBF4A));
+ }
+ if (sv.flags & 1 && sv.cur < NT && !gone(sv.cur)) { /* the cursor: a frame no one can miss */
+ int x = sx(sv.cur), y = sy(sv.cur);
+ box(x - 3, y - 3, TW + 6, TH + 6, 3, FOCUS);
+ box(x - 1, y - 1, TW + 2, TH + 2, 1, 0xFFFF);
+ }
+ /* the time, the tiles left, the keys */
+ gfx_text(&np_font_body, 6, BAR + 12, clock_text(s, sv.ms), GOLD, 256);
+ cat(num(s, (uint32_t)left), T(" tiles"));
+ gfx_text(&np_font_small, 52, BAR + 12, s, HEX(0xA9C9B5), 256);
+ gfx_text_right(&np_font_small, 315, BAR + 12, T("OK pick shift hint DEL undo Back menu"), IVORY, 256);
+ if (ov) overlay();
+}
+
+#ifdef PERF /* (make perf: how long a frame takes, in tools/emu.py) */
+#define PERF_SYM __attribute__((used, externally_visible, visibility("default")))
+PERF_SYM uint32_t perf_frames, perf_max, perf_slow;
+#endif
+static void draw(void) {
+ eadk_display_wait_for_vblank();
+#ifdef PERF
+ uint32_t t0 = (uint32_t)eadk_timing_millis();
+#endif
+ gfx_render(scene, 0, 0, SCREEN_H);
+#ifdef PERF
+ uint32_t t = (uint32_t)eadk_timing_millis() - t0;
+ perf_frames++, perf_max = t > perf_max ? t : perf_max, perf_slow += t > 33;
+#endif
+}
+
+int main(void) {
+ np_app_begin();
+ color_t *their_strip = gfx_buf;
+ gfx_buf = strip;
+ np_lz_unpack(art_lz, sizeof art_lz, art, sizeof art);
+ for (int i = 0; i < 16; i++) pal[i] = gfx_rgb(art_pal[i]);
+ now = (uint32_t)eadk_timing_millis();
+ seed = eadk_random() ^ now;
+ if (!seed) seed = 1;
+ ov = menu = quit_ok = best_new = 0, hint_a = hint_b = -1;
+ load();
+ load_layout(sv.layout);
+ refresh();
+ if (!(sv.flags & 1)) ov = OV_NEW, menu = sv.layout;
+ if (!(sv.flags & 2)) ov = OV_HELP, sv.flags |= 2;
+ if ((sv.flags & 1) && !moves) ov = OV_STUCK;
+ uint64_t held = eadk_keyboard_scan(), stale = held; /* keys still down from the home screen wait to be let go */
+ const uint64_t arrows = KEY(eadk_key_left) | KEY(eadk_key_right) | KEY(eadk_key_up) | KEY(eadk_key_down) |
+ KEY(eadk_key_four) | KEY(eadk_key_six) | KEY(eadk_key_eight) | KEY(eadk_key_two);
+ uint32_t tick = now, repeat_at = 0, shown = ~0u;
+ bool dirty = true, lit = false;
+ for (;;) {
+ now = (uint32_t)eadk_timing_millis();
+ uint64_t k = eadk_keyboard_scan(), hit = k & ~held, rep = k & arrows & ~(stale &= k);
+ if (hit & arrows) repeat_at = now + 250; /* an arrow held repeats */
+ else if (rep && (int32_t)(now - repeat_at) >= 0) hit |= rep, repeat_at = now + 110;
+ held = k;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ int dx = !!(hit & (KEY(eadk_key_right) | KEY(eadk_key_six))) - !!(hit & (KEY(eadk_key_left) | KEY(eadk_key_four)));
+ int dy = !!(hit & (KEY(eadk_key_down) | KEY(eadk_key_two))) - !!(hit & (KEY(eadk_key_up) | KEY(eadk_key_eight)));
+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);
+ if (hit) dirty = true;
+ if (ov) {
+ int n = buttons[ov], was = ov;
+ if (dy) menu = (menu + dy + n) % n, quit_ok = 0;
+ if (back) {
+ if (ov == OV_NEW && !(sv.flags & 1)) break; /* no game to go back to */
+ if (ov == OV_HELP && !(sv.flags & 1)) ov = OV_NEW, menu = sv.layout;
+ else if (ov != OV_WON) ov = OV_NONE;
+ } else if (ok) {
+ int i = menu;
+ ov = OV_NONE, menu = 0;
+ if (was == OV_MENU) {
+ if (i == 1) ov = OV_NEW, menu = sv.layout;
+ if (i == 2) ov = OV_HELP;
+ if (i == 3 && quit_ok) break;
+ if (i == 3) ov = OV_MENU, menu = 3, quit_ok = 1; /* Quit game asks first */
+ } else if (was == OV_NEW) {
+ new_game(i);
+ } else if (was == OV_HELP) {
+ if (!(sv.flags & 1)) ov = OV_NEW, menu = sv.layout;
+ } else if (was == OV_WON) {
+ if (i == 0) ov = OV_NEW, menu = sv.layout;
+ else break;
+ } else if (was == OV_STUCK) {
+ if (i == 0) shuffle();
+ if (i == 1) undo();
+ if (i == 2) ov = OV_NEW, menu = sv.layout;
+ }
+ }
+ } else if (back) {
+ ov = OV_MENU, menu = quit_ok = 0;
+ save();
+ } else if (sv.flags & 1) {
+ if (dx) step(dx, 0);
+ if (dy) step(0, dy);
+ if (ok) choose(sv.cur);
+ if (hit & KEY(eadk_key_shift)) hint();
+ if (hit & KEY(eadk_key_backspace)) undo();
+ }
+ /* the clock runs while a game is played */
+ if (!ov && sv.flags & 1) sv.ms += now - tick;
+ tick = now;
+ if (hint_a >= 0 && now - hint_t > 3000) hint_a = hint_b = -1, dirty = true;
+ if (hint_a >= 0 && lit != ((now - hint_t) % 700 < 450)) lit = !lit, dirty = true; /* the hint blinks */
+#ifdef PERF
+ dirty = true; /* every frame drawn */
+#endif
+ if (dirty || sv.ms / 1000 != shown) {
+ shown = sv.ms / 1000, dirty = false;
+ draw();
+ }
+ eadk_timing_msleep(20);
+ }
+ save();
+ gfx_buf = their_strip;
+ return np_app_end();
+}
diff --git a/games/mahjong/tests/play.c b/games/mahjong/tests/play.c
new file mode 100644
index 00000000..17cde115
--- /dev/null
+++ b/games/mahjong/tests/play.c
@@ -0,0 +1,441 @@
+/* Mahjong on a computer, for tests and pictures (make host, make test).
+ *
+ * play test the layouts and the rules; deals of every layout won, many seeds; shuffles that can be won;
+ * undo and picking; saves kept, damaged and read back from the copy; a game won with the keys
+ * (the arrows reach every tile it takes); random keys
+ * play film DIR a game played with the keys, the screen saved as it goes (DIR/f_NNNN.ppm), and the
+ * screens of the docs (DIR/shot_N.ppm)
+ */
+#define main mahjong_main
+#include "../src/main.c"
+#undef main
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+static uint16_t fb[SCREEN_H][SCREEN_W];
+void eadk_display_push_rect(eadk_rect_t r, const eadk_color_t *p) {
+ for (int j = 0; j < r.height; j++)
+ for (int i = 0; i < r.width; i++) fb[r.y + j][r.x + i] = p[j * r.width + i];
+}
+void eadk_display_push_rect_uniform(eadk_rect_t r, eadk_color_t c) {
+ for (int j = 0; j < r.height; j++)
+ for (int i = 0; i < r.width; i++) fb[r.y + j][r.x + i] = c;
+}
+bool eadk_display_wait_for_vblank(void) { return true; }
+void *np_alloc(uint32_t size) { return malloc(size); }
+
+/* the files */
+static struct { char name[32]; uint8_t data[1024]; uint32_t len; } files[4];
+static int find(const char *name) {
+ for (int i = 0; i < 4; i++)
+ if (files[i].len && !strcmp(files[i].name, name)) return i;
+ return -1;
+}
+const uint8_t *host_read(const char *name, uint32_t *len) {
+ int i = find(name);
+ if (i < 0) return NULL;
+ *len = files[i].len;
+ return files[i].data;
+}
+bool host_write(const char *name, const void *data, uint32_t len) {
+ int i = find(name);
+ for (int k = 0; k < 4 && i < 0; k++)
+ if (!files[k].len) i = k;
+ if (i < 0 || len > sizeof files[i].data || !len) return false;
+ snprintf(files[i].name, sizeof files[i].name, "%s", name);
+ memcpy(files[i].data, data, len), files[i].len = len;
+ return true;
+}
+
+/* the keys: a script of presses, each held 60 ms; the clock moves on as the game sleeps */
+static uint64_t clock_ms;
+static struct { uint64_t t; int key; } script[8192];
+static int nscript, nshots, frame, quiet;
+static uint64_t shots[64], ft;
+static const char *dir;
+static uint32_t random_value = 0x9E3779B9u;
+uint64_t eadk_timing_millis(void) { return clock_ms; }
+uint32_t eadk_random(void) { return random_value; }
+static void ppm(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6 %d %d 255\n", SCREEN_W, SCREEN_H);
+ for (int y = 0; y < SCREEN_H; y++)
+ for (int x = 0; x < SCREEN_W; x++) {
+ uint16_t c = fb[y][x];
+ fputc((c >> 11) * 255 / 31, f), fputc((c >> 5 & 63) * 255 / 63, f), fputc((c & 31) * 255 / 31, f);
+ }
+ fclose(f);
+}
+void eadk_timing_msleep(uint32_t ms) {
+ for (uint32_t i = 0; i < ms; i++) {
+ clock_ms++;
+ char path[512];
+ for (int s = 0; s < nshots; s++)
+ if (shots[s] == clock_ms) snprintf(path, sizeof path, "%s/shot_%d.ppm", dir, s), ppm(path);
+ if (dir && clock_ms % 50 == 0 && !quiet) { /* (frames as tools/record.py --frames reads them) */
+ snprintf(path, sizeof path, "%s/frame_%06llu.raw", dir, (unsigned long long)clock_ms);
+ FILE *f = fopen(path, "wb");
+ if (f) fwrite(fb, 2, SCREEN_W * SCREEN_H, f), fclose(f);
+ frame++;
+ }
+ }
+}
+uint64_t eadk_keyboard_scan(void) {
+ uint64_t k = 0;
+ for (int i = 0; i < nscript; i++)
+ if (clock_ms >= script[i].t && clock_ms < script[i].t + 60) k |= 1ull << script[i].key;
+ return k;
+}
+static void press(int key, int wait) {
+ if (nscript < (int)(sizeof script / sizeof script[0])) script[nscript].t = ft, script[nscript++].key = key;
+ ft += (uint64_t)wait;
+}
+static void run(void) { /* the app, with the script from now on */
+ for (int i = 0; i < nscript; i++) script[i].t += clock_ms;
+ for (int s = 0; s < nshots; s++) shots[s] += clock_ms;
+ mahjong_main();
+ nscript = nshots = 0, ft = 0;
+}
+
+static uint8_t kept_files[sizeof files];
+static void keep_files(void) { memcpy(kept_files, files, sizeof files); }
+static void back_files(void) { memcpy(files, kept_files, sizeof files); }
+
+static int fails;
+#define CHECK(c, ...) do { if (!(c) && fails++ < 40) { printf("FAIL: " __VA_ARGS__); printf("\n"); } } while (0)
+
+/* free, from the tiles' places alone (not the lists the game keeps) */
+static bool free_by_hand(int a) {
+ bool l = false, r = false;
+ for (int j = 0; j < NT; j++) {
+ if (j == a || gone(j) || iabs(ty[j] - ty[a]) > 1) continue;
+ if (tz[j] > tz[a] && iabs(tx[j] - tx[a]) < 2) return false;
+ if (tz[j] == tz[a]) l |= tx[j] == tx[a] - 2, r |= tx[j] == tx[a] + 2;
+ }
+ return !(l && r);
+}
+
+static void check_layouts(void) {
+ for (int l = 0; l < LAYOUTS; l++) {
+ load_layout(l);
+ for (int i = 0; i < NT; i++) {
+ CHECK(sx(i) >= 0 && sx(i) + TW + DEP <= SCREEN_W && sy(i) >= 0 && sy(i) + TH + DEP <= BAR,
+ "%s: tile %d off the screen (%d, %d)", layout_name[l], i, sx(i), sy(i));
+ for (int j = 0; j < i; j++)
+ CHECK(tz[i] != tz[j] || iabs(tx[i] - tx[j]) > 1 || iabs(ty[i] - ty[j]) > 1, "%s: tiles %d and %d overlap",
+ layout_name[l], i, j);
+ if (i) CHECK(tz[i - 1] < tz[i] || (tz[i - 1] == tz[i] && (tx[i - 1] < tx[i] || (tx[i - 1] == tx[i] && ty[i - 1] < ty[i]))),
+ "%s: not in the order they're drawn", layout_name[l]);
+ }
+ }
+ /* the Turtle: 87, 36, 16, 4 and 1 tiles a layer, the top one on the four below it */
+ load_layout(0);
+ int per[5] = {0}, top = -1;
+ for (int i = 0; i < NT; i++) per[tz[i] < 5 ? tz[i] : 0]++, top = tz[i] == 4 ? i : top;
+ CHECK(per[0] == 87 && per[1] == 36 && per[2] == 16 && per[3] == 4 && per[4] == 1, "the Turtle's layers");
+ CHECK(top >= 0 && tx[top] == 14 && ty[top] == 7 && ndn[top] == 4 + 4 + 4 + 4, "the Turtle's top tile");
+}
+
+/* plays the deal back: the pairs in the order they were taken when it was made */
+static int solve(int n) {
+ for (int k = 0; k < n; k += 2) {
+ int a = order[k], b = order[k + 1];
+ if (!fr[a] || !fr[b] || !match(a, b)) return 0;
+ choose(a), choose(b);
+ if (!gone(a) || !gone(b)) return 0;
+ }
+ return 1;
+}
+
+static void check_rules(void) {
+ ov = 0, seed = 7;
+ new_game(0);
+ for (int i = 0; i < NT; i++) CHECK(fr[i] == free_by_hand(i), "tile %d's freedom", i);
+ int nf = 0;
+ for (int i = 0; i < NT; i++) nf += fr[i];
+ /* at the start of the Turtle: the ends of the first layer's rows but the middle two (shut in by the end tiles),
+ two of the three end tiles, the ends of the second and third layers' rows, and the top: 14 + 12 + 8 + 1 */
+ CHECK(nf == 35, "the Turtle starts with %d free tiles, not 35", nf);
+ /* matching */
+ for (int i = 0; i < NT; i++) sv.face[i] = (uint8_t)(i < 136 ? i / 4 : i - 102);
+ CHECK(family(34) == family(37) && family(38) == family(41) && family(34) != family(38) && family(33) != family(34),
+ "flowers and seasons");
+ sv.face[0] = 3, sv.face[1] = 3, sv.face[2] = 4, sv.face[3] = 35, sv.face[4] = 36, sv.face[5] = 39;
+ CHECK(match(0, 1) && !match(0, 2) && match(3, 4) && !match(4, 5), "what matches");
+ /* picking: a tile, another that doesn't match it (picked instead), the same again (put back) */
+ seed = 11;
+ new_game(0);
+ int a = order[0], b = order[1], c = -1;
+ for (int i = 0; i < NT && c < 0; i++)
+ if (fr[i] && !match(i, a)) c = i;
+ choose(a);
+ CHECK(sv.pick == a, "a tile picked");
+ if (c >= 0) {
+ choose(c);
+ CHECK(sv.pick == c, "picking one that doesn't match");
+ choose(c);
+ CHECK(sv.pick == NONE, "unpicked");
+ }
+ choose(a), choose(b);
+ CHECK(gone(a) && gone(b) && sv.pairs == 1 && left == NT - 2, "a pair taken");
+ undo();
+ CHECK(!gone(a) && !gone(b) && sv.pairs == 0 && left == NT, "undo");
+ undo();
+ CHECK(sv.pairs == 0 && left == NT, "nothing to undo");
+ /* a hint: two free tiles that match, another pair the next time */
+ hint();
+ int ha = hint_a, hb = hint_b;
+ CHECK(ha >= 0 && fr[ha] && fr[hb] && match(ha, hb), "a hint");
+ hint();
+ CHECK(hint_a >= 0 && (hint_a != ha || hint_b != hb || moves == 1), "the next hint");
+}
+
+static void check_deals(void) {
+ clock_t t0 = clock();
+ int deals = 0;
+ for (int l = 0; l < LAYOUTS; l++)
+ for (int s = 1; s <= 60; s++, deals++) {
+ seed = 0x2545F491u * (uint32_t)s + (uint32_t)l, ov = 0;
+ new_game(l);
+ int count[ART_KINDS] = {0};
+ for (int i = 0; i < NT; i++) count[kind(i)]++;
+ for (int k = 0; k < ART_KINDS; k++) CHECK(count[k] == (k < FLOWER ? 4 : 1), "%s: %d of kind %d", layout_name[l], count[k], k);
+ uint32_t before = sv.best[l];
+ sv.ms = 1000u * (uint32_t)s;
+ CHECK(solve(NT), "%s, seed %d: the deal can't be won as laid", layout_name[l], s);
+ CHECK(left == 0 && ov == OV_WON && !(sv.flags & 1), "%s: won", layout_name[l]);
+ CHECK(sv.best[l] == (before && before < sv.ms ? before : sv.ms), "%s: the best time", layout_name[l]);
+ }
+ printf("%d deals won, %.1f ms each\n", deals, (double)(clock() - t0) * 1000 / CLOCKS_PER_SEC / deals);
+ /* shuffles: halfway through, the tiles left laid again so they can still be won */
+ for (int l = 0; l < LAYOUTS; l++)
+ for (int s = 1; s <= 25; s++) {
+ seed = 977u * (uint32_t)s + (uint32_t)l, ov = 0;
+ new_game(l);
+ uint8_t ord[NT];
+ memcpy(ord, order, NT);
+ int take = 2 * (int)(rnd() % 60);
+ for (int k = 0; k < take; k += 2) choose(ord[k]), choose(ord[k + 1]);
+ int count[ART_KINDS] = {0}, after[ART_KINDS] = {0};
+ for (int i = 0; i < NT; i++)
+ if (!gone(i)) count[kind(i)]++;
+ shuffle();
+ for (int i = 0; i < NT; i++)
+ if (!gone(i)) after[kind(i)]++;
+ CHECK(!memcmp(count, after, sizeof count), "a shuffle changed the tiles");
+ CHECK(solve(left), "%s, seed %d: the shuffle can't be won as laid", layout_name[l], s);
+ }
+}
+
+static void check_saves(void) {
+ memset(files, 0, sizeof files);
+ seed = 5, ov = 0;
+ new_game(2);
+ choose(order[0]), choose(order[1]);
+ sv.ms = 123456, sv.best[1] = 99000;
+ save();
+ uint8_t kept[sizeof sv];
+ memcpy(kept, &sv, sizeof sv);
+ memset(&sv, 0, sizeof sv);
+ load();
+ CHECK(!memcmp(kept, &sv, sizeof sv), "the save read back");
+ files[find(SAVE_NAME)].data[40] ^= 1; /* damaged: from the copy */
+ memset(&sv, 0, sizeof sv);
+ load();
+ CHECK(!memcmp(kept, &sv, sizeof sv), "the copy read back");
+ files[find(SAVE_NAME)].len = 0; /* gone, as after an install: from the copy */
+ memset(&sv, 0, sizeof sv);
+ load();
+ CHECK(!memcmp(kept, &sv, sizeof sv), "the copy read back after an install");
+ files[find(COPY_NAME)].data[120] = files[find(COPY_NAME)].data[120] == 'A' ? 'B' : 'A'; /* both damaged */
+ files[0].len = 5;
+ load();
+ CHECK(sv.flags == 0 && sv.best[1] == 0, "a fresh start");
+ /* no game yet, how to play read: kept */
+ sv.flags = 2;
+ save();
+ memset(&sv, 0, sizeof sv);
+ load();
+ CHECK(sv.flags == 2, "how to play read, no game");
+}
+
+/* the keys that take the cursor from tile c to tile t (the arrows alone), found by trying them */
+static const int arrow_key[4] = {eadk_key_left, eadk_key_right, eadk_key_up, eadk_key_down};
+static bool path(int t) {
+ int from[NT], how[NT], queue[NT], qh = 0, qt = 0, c = sv.cur;
+ for (int i = 0; i < NT; i++) from[i] = -1;
+ from[c] = c, queue[qt++] = c;
+ while (qh < qt && from[t] < 0) {
+ int u = queue[qh++];
+ for (int d = 0; d < 4; d++) {
+ sv.cur = (uint8_t)u;
+ step(d < 2 ? (d ? 1 : -1) : 0, d < 2 ? 0 : (d == 3 ? 1 : -1));
+ int v = sv.cur;
+ if (from[v] < 0) from[v] = u, how[v] = d, queue[qt++] = v;
+ }
+ }
+ sv.cur = (uint8_t)c;
+ if (from[t] < 0) return false;
+ int keys[NT], n = 0;
+ for (int v = t; v != c; v = from[v]) keys[n++] = arrow_key[how[v]];
+ while (n) press(keys[--n], 130);
+ sv.cur = (uint8_t)t;
+ return true;
+}
+
+/* a game won with the keys: how to play, the Turtle, then every pair, reached with the arrows */
+static void check_keys_win(void) {
+ memset(files, 0, sizeof files);
+ clock_ms = 1000, random_value = 0x1234567u;
+ ft = 1500;
+ press(eadk_key_ok, 400); /* how to play read */
+ press(eadk_key_ok, 600); /* the Turtle */
+ press(eadk_key_home, 300);
+ run();
+ CHECK(sv.flags == 3 && sv.layout == 0, "a game started with the keys");
+ uint8_t ord[NT];
+ memcpy(ord, order, NT);
+ keep_files();
+ /* the keys, worked out on the game as it goes */
+ ft = 1500;
+ int unreached = 0;
+ for (int k = 0; k < NT; k += 2) {
+ for (int h = 0; h < 2; h++) {
+ int t = ord[k + h];
+ if (!path(t)) unreached++, sv.cur = (uint8_t)t; /* (not with the arrows: then it fails below) */
+ press(eadk_key_ok, 160);
+ choose(t);
+ }
+ ov = 0;
+ }
+ CHECK(!unreached, "%d tiles the arrows don't reach", unreached);
+ press(eadk_key_ok, 500); /* the win's card: New game */
+ press(eadk_key_back, 300); /* no game: back quits */
+ press(eadk_key_home, 300);
+ back_files();
+ int presses_made = nscript;
+ run();
+ CHECK(!(sv.flags & 1) && sv.wins[0] == 1 && sv.best[0] > 0 && sv.pairs == 72, "the game won with the keys");
+ printf("a Turtle won with %d keys in %u:%02u\n", presses_made, sv.best[0] / 60000, sv.best[0] / 1000 % 60);
+}
+
+static void fuzz(void) {
+ static const int keys[] = {eadk_key_left, eadk_key_right, eadk_key_up, eadk_key_down, eadk_key_ok, eadk_key_ok,
+ eadk_key_ok, eadk_key_exe, eadk_key_back, eadk_key_shift, eadk_key_backspace,
+ eadk_key_two, eadk_key_eight, eadk_key_four, eadk_key_six, eadk_key_zero};
+ uint32_t r = 2463534242u;
+ memset(files, 0, sizeof files);
+ for (int s = 0; s < 120; s++) {
+ random_value = r;
+ ft = 300;
+ int n = 40 + (int)(r % 200);
+ for (int i = 0; i < n; i++) {
+ r ^= r << 13, r ^= r >> 17, r ^= r << 5;
+ press(keys[r % 16], 20 + (int)(r >> 8) % 120);
+ }
+ press(r & 1 ? eadk_key_home : eadk_key_on_off, 100);
+ run();
+ if (s % 7 == 3 && find(SAVE_NAME) >= 0) files[find(SAVE_NAME)].data[r % sizeof sv] ^= (uint8_t)(1 + r % 255);
+ if (s % 11 == 5 && find(COPY_NAME) >= 0) files[find(COPY_NAME)].data[r % 300] = (uint8_t)r;
+ if (s % 13 == 6 && find(SAVE_NAME) >= 0) files[find(SAVE_NAME)].len = r % 400 + 1;
+ memset(&sv, 0, sizeof sv);
+ load();
+ CHECK(sv.magic == 0 || valid(), "session %d left a save that doesn't read back", s);
+ }
+}
+
+/* a film: how to play, the Turtle, a few pairs taken with the keys, a hint, a wrong pick, undo, the menu */
+static void film(void) {
+ memset(files, 0, sizeof files);
+ clock_ms = 1000, random_value = 0x2468ACEu, frame = 0;
+ ft = 1200;
+ shots[nshots++] = 1100; /* how to play */
+ press(eadk_key_ok, 700);
+ shots[nshots++] = ft - 100; /* the layouts */
+ press(eadk_key_ok, 800);
+ press(eadk_key_home, 300);
+ quiet = 1;
+ run();
+ quiet = 0;
+ uint8_t ord[NT];
+ memcpy(ord, order, NT);
+ keep_files();
+ ft = 900;
+ for (int k = 0; k < 12; k += 2) {
+ for (int h = 0; h < 2; h++) {
+ if (!path(ord[k + h])) sv.cur = ord[k + h];
+ ft += 150;
+ press(eadk_key_ok, 450);
+ choose(ord[k + h]);
+ if (k == 6 && !h) shots[nshots++] = ft - 100; /* a tile picked */
+ }
+ }
+ press(eadk_key_shift, 1500);
+ shots[nshots++] = ft - 600; /* a hint */
+ press(eadk_key_backspace, 900);
+ press(eadk_key_back, 900);
+ shots[nshots++] = ft - 300; /* the menu */
+ press(eadk_key_back, 600);
+ press(eadk_key_home, 200);
+ back_files();
+ run();
+}
+
+/* pictures for the docs: DIR/pic_N.ppm */
+static void pic(const char *path) {
+ gfx_buf = strip;
+ draw();
+ ppm(path);
+}
+static void pics(const char *d) {
+ char p[512];
+ memset(files, 0, sizeof files);
+ now = 0;
+ np_lz_unpack(art_lz, sizeof art_lz, art, sizeof art);
+ for (int i = 0; i < 16; i++) pal[i] = gfx_rgb(art_pal[i]);
+ for (int l = 0; l < LAYOUTS; l++) { /* each layout, a few pairs in, a tile picked */
+ seed = 0x51ED270Bu + (uint32_t)l * 77, ov = 0;
+ new_game(l);
+ for (int k = 0; k < 2 * (3 + l); k++) choose(order[k]);
+ sv.ms = 61000u + 23000u * (uint32_t)l;
+ step(1, 0), step(0, 1);
+ choose(sv.cur);
+ step(-1, 0);
+ snprintf(p, sizeof p, "%s/pic_%d.ppm", d, l), pic(p);
+ }
+ ov = OV_NEW, menu = 0, sv.best[0] = 512000, sv.best[2] = 431000;
+ snprintf(p, sizeof p, "%s/pic_4.ppm", d), pic(p);
+ ov = 0, seed = 99;
+ new_game(0);
+ for (int k = 0; k < NT; k++) choose(order[k]);
+ sv.ms = 488000;
+ snprintf(p, sizeof p, "%s/pic_5.ppm", d), pic(p);
+ ov = OV_STUCK, menu = 0, sv.flags |= 1;
+ snprintf(p, sizeof p, "%s/pic_6.ppm", d), pic(p);
+}
+
+int main(int argc, char **argv) {
+ if (argc > 2 && !strcmp(argv[1], "pics")) {
+ pics(argv[2]);
+ return 0;
+ }
+ setvbuf(stdout, NULL, _IONBF, 0);
+ if (argc > 2 && !strcmp(argv[1], "film")) {
+ dir = argv[2];
+ film();
+ return 0;
+ }
+ check_layouts();
+ check_rules();
+ printf("layouts and rules checked\n");
+ check_deals();
+ printf("rules checked\n");
+ check_saves();
+ check_keys_win();
+ fuzz();
+ printf(fails ? "%d checks failed\n" : "all checks passed\n", fails);
+ return fails != 0;
+}
diff --git a/games/mahjong/tools/art.py b/games/mahjong/tools/art.py
new file mode 100644
index 00000000..c9152527
--- /dev/null
+++ b/games/mahjong/tools/art.py
@@ -0,0 +1,329 @@
+#!/usr/bin/env python3
+"""Draws the faces of Mahjong's 42 kinds of tiles and writes src/art.h.
+
+ art.py FONT.bdf [--preview out.png]
+
+Each face is 18 x 24 pixels of 16 colours (0: the tile's own ivory shows through), packed four bits a pixel,
+then with np_lz.h's LZSS. The dots and bamboo are drawn here; the characters (the numerals, 萬, the winds and the
+dragons) are Fusion Pixel 12px's traditional Chinese letters (FONT: fusion-pixel-12px-monospaced-zh_hant.bdf, SIL
+Open Font License 1.1, LICENSES/OFL-1.1-Fusion-Pixel.txt); the bird, flowers and seasons are drawn below.
+Kinds: 0-8 dots, 9-17 bamboo, 18-26 characters, 27-30 the winds (east, south, west, north), 31-33 the dragons
+(red, green, white), 34-37 the flowers, 38-41 the seasons."""
+import math
+import os
+import re
+import sys
+
+W, H = 18, 24
+PAL = [0x000000, 0x1A1A1A, 0x1F3C88, 0xC62828, 0x2E7D32, 0x7CC576, 0x1E66C8, 0x14532D,
+ 0xF2A900, 0xE5508A, 0x9147C8, 0xEC6A12, 0x3FA9E6, 0xFFFFFF, 0x7A4A2A, 0xF7C6D6]
+INK, NAVY, RED, GREEN, LIGHT, BLUE, DARK, GOLD, PINK, PURPLE, ORANGE, SKY, WHITE, BROWN, BLUSH = range(1, 16)
+
+
+def blank():
+ return [[0] * W for _ in range(H)]
+
+
+def disc(f, cx, cy, r, c):
+ for y in range(H):
+ for x in range(W):
+ if (x + .5 - cx) ** 2 + (y + .5 - cy) ** 2 <= r * r:
+ f[y][x] = c
+
+
+def dot(f, cx, cy, r, c):
+ """a dot as on the tiles: a ring of its colour, white inside, its centre coloured"""
+ disc(f, cx, cy, r, c)
+ disc(f, cx, cy, r - 1.15, WHITE)
+ disc(f, cx, cy, max(r - 2.1, .75), c)
+
+
+def dots(n):
+ f = blank()
+ B, G, R = BLUE, GREEN, RED
+ if n == 1:
+ disc(f, 9, 12, 8.4, G)
+ disc(f, 9, 12, 7.2, WHITE)
+ disc(f, 9, 12, 6.2, BLUE)
+ disc(f, 9, 12, 5.0, WHITE)
+ for k in range(8):
+ a = k * math.pi / 4
+ disc(f, 9 + 3.3 * math.cos(a), 12 + 3.3 * math.sin(a), 1.1, RED)
+ disc(f, 9, 12, 1.6, RED)
+ return f
+ lay = {
+ 2: [(9, 6.5, 4.6, G), (9, 17.5, 4.6, B)],
+ 3: [(4, 4.5, 3.4, B), (9, 12, 3.4, R), (14, 19.5, 3.4, G)],
+ 4: [(4.5, 6, 3.6, B), (13.5, 6, 3.6, G), (4.5, 18, 3.6, G), (13.5, 18, 3.6, B)],
+ 5: [(4, 4.5, 3.3, B), (14, 4.5, 3.3, G), (9, 12, 3.3, R), (4, 19.5, 3.3, G), (14, 19.5, 3.3, B)],
+ 6: [(4.5, 4, 3.2, G), (13.5, 4, 3.2, G)] + [(x, y, 3.2, R) for y in (13, 20) for x in (4.5, 13.5)],
+ 7: [(3, 2.75, 2.75, G), (9, 5.75, 2.75, G), (15, 8.75, 2.75, G)] + [(x, y, 3, R) for y in (15, 21) for x in (5, 13)],
+ 8: [(x, y, 2.75, B) for y in (3, 9, 15, 21) for x in (5, 13)],
+ 9: [(x, y, 2.75, c) for y, c in ((4, B), (12, R), (20, G)) for x in (3, 9, 15)],
+ }[n]
+ for cx, cy, r, c in lay:
+ dot(f, cx, cy, r, c)
+ return f
+
+
+STICK = [".G.",
+ "GLG",
+ "GLG",
+ "ddd",
+ "GLG",
+ "GLG",
+ ".G."]
+
+
+def stick(f, x, y, c=GREEN, tall=7):
+ rows = STICK if tall == 7 else STICK[:3] + STICK[3:4] + STICK[5:]
+ for j, row in enumerate(rows):
+ for i, ch in enumerate(row):
+ if ch == '.':
+ continue
+ v = {'G': c, 'L': LIGHT if c == GREEN else BLUSH, 'd': DARK if c == GREEN else c}[ch]
+ if 0 <= x + i < W and 0 <= y + j < H:
+ f[y + j][x + i] = v
+
+
+BIRD = """
+......RR..........
+.....RRRR.........
+....RRKRRGG.......
+....RRRRR.........
+.....RRR..........
+.....GGGG.........
+....GGGGGG........
+...GGLLGGGG.......
+...GLLLLGGGG....B.
+..GGLLLLLGGGG..BB.
+..GGGLLLLLGGGBBBB.
+...GGGGLLLGGBBBB..
+....GGGGGGGBBBB...
+.....GGGGGGBBB....
+.......GGGG.......
+.......O..O.......
+......O..O........
+....NNNNNNNNNN....
+"""
+
+
+def picture(f, art, x0, y0, colours):
+ for j, row in enumerate(art.strip("\n").split("\n")):
+ for i, ch in enumerate(row):
+ if ch != '.':
+ f[y0 + j][x0 + i] = colours[ch]
+
+
+def bamboo(n):
+ f = blank()
+ if n == 1:
+ picture(f, BIRD, 0, 3, {'R': RED, 'K': INK, 'G': GREEN, 'L': LIGHT, 'B': BLUE, 'O': ORANGE, 'N': BROWN})
+ return f
+ xs3, xs2 = (2, 7, 12), (4, 10)
+ spots = {
+ 2: [(7, 2), (7, 14)],
+ 3: [(7, 2), (4, 14), (10, 14)],
+ 4: [(x, y) for y in (2, 14) for x in xs2],
+ 5: [(x, y) for y in (2, 14) for x in (2, 12)] + [(7, 8, RED)],
+ 6: [(x, y) for y in (2, 14) for x in xs3],
+ 7: [(7, 0, RED)] + [(x, y) for y in (8, 16) for x in xs3],
+ 8: [(x, y) for y in (2, 14) for x in (0, 5, 10, 15)],
+ 9: [(x, y, RED if x == 7 else GREEN) for y in (0, 8, 16) for x in xs3],
+ }[n]
+ for s in spots:
+ stick(f, s[0], s[1], s[2] if len(s) > 2 else GREEN)
+ return f
+
+
+def load_bdf(path, chars):
+ src = open(path, encoding="utf-8", errors="replace").read()
+ out = {}
+ for m in re.finditer(r"STARTCHAR.*?ENDCHAR", src, re.S):
+ b = m.group(0)
+ enc = int(re.search(r"ENCODING (-?\d+)", b).group(1))
+ if enc <= 0 or chr(enc) not in chars:
+ continue
+ w, h, xo, yo = map(int, re.search(r"BBX (-?\d+) (-?\d+) (-?\d+) (-?\d+)", b).group(1, 2, 3, 4))
+ rows = b.split("BITMAP\n")[1].split("\nENDCHAR")[0].split()
+ bits = []
+ for r in rows:
+ v, n = int(r, 16), len(r) * 4
+ bits.append([v >> (n - 1 - i) & 1 for i in range(w)])
+ out[chr(enc)] = (xo, 10 - (yo + h), bits) # (left, top in a 12 pixel line: 10 above the baseline)
+ missing = set(chars) - set(out)
+ if missing:
+ raise SystemExit(f"{path}: no {''.join(sorted(missing))}")
+ return out
+
+
+def letter(f, glyphs, ch, x, y, c):
+ xo, top, bits = glyphs[ch]
+ for j, row in enumerate(bits):
+ for i, b in enumerate(row):
+ if b:
+ f[y + top + j][x + xo + i] = c
+
+
+DIGITS = {1: ".X.XX..X..X.XXX", 2: "XX...X.X.X..XXX", 3: "XX...X.X...XXX.", 4: "X.XX.XXXX..X..X"}
+
+
+def corner(f, n, c):
+ for k, ch in enumerate(DIGITS[n]):
+ if ch == 'X':
+ f[1 + k // 3][1 + k % 3] = c
+
+
+def flower(n):
+ f = blank()
+ petal = (PINK, PURPLE, GOLD, ORANGE)[n - 1]
+ cx, cy = 10, 8.5
+ for k in range(5):
+ a = -math.pi / 2 + k * 2 * math.pi / 5
+ disc(f, cx + 3.3 * math.cos(a), cy + 3.3 * math.sin(a), 2.55, petal)
+ disc(f, cx, cy, 1.6, GOLD if n != 3 else RED)
+ for y in range(13, 23):
+ f[y][10 - (y > 19)] = GREEN
+ picture(f, "LL...\nLLLL.\n.LLLL\n..LL.", 4, 15, {'L': LIGHT})
+ picture(f, "..LL\n.LLL\nLLL.", 11, 17, {'L': LIGHT})
+ corner(f, n, RED)
+ return f
+
+
+SEASONS = [
+ # spring: a sprout
+ ("..GG.....GG..\n.GGGG...GGGG.\nGGGGGG.GGGGGG\n.GGGGGDGGGGG.\n...GGGDGGG...\n......D......\n......D......\n"
+ "......D......\n....NNNNN....\n..NNNNNNNNN..", {'G': LIGHT, 'D': GREEN, 'N': BROWN}),
+ # summer: the sun
+ ("......R......\n.R....R....R.\n..R.......R..\n....OOOOO....\n...OOOOOOO...\n...OOOOOOO...\nRR.OOOOOOO.RR\n"
+ "...OOOOOOO...\n...OOOOOOO...\n....OOOOO....\n..R.......R..\n.R....R....R.\n......R......",
+ {'R': RED, 'O': ORANGE}),
+ # autumn: a maple leaf
+ ("......O......\n.....OOO.....\n..O..OOO..O..\n..OO.OOO.OO..\nOOOOOOOOOOOOO\n.OOOOOOOOOOO.\n..OOOOOOOOO..\n"
+ ".OOOOOOOOOOO.\nOOOO.OOO.OOOO\n.....ROR.....\n......R......\n......R......", {'O': ORANGE, 'R': RED}),
+ # winter: a snowflake
+ ("......S......\n....S.S.S....\n.S...SSS...S.\n..S...S...S..\n...S..S..S...\nS...S.S.S...S\n.SSSSSSSSSSS.\n"
+ "S...S.S.S...S\n...S..S..S...\n..S...S...S..\n.S...SSS...S.\n....S.S.S....\n......S......", {'S': SKY}),
+]
+
+
+def season(n):
+ f = blank()
+ art, colours = SEASONS[n - 1]
+ rows = art.split("\n")
+ picture(f, art, (W - len(rows[0]) + 1) // 2 + 1, 6 + (13 - len(rows)) // 2 + 2, colours)
+ corner(f, n, BLUE)
+ return f
+
+
+def faces(glyphs):
+ out = [dots(n) for n in range(1, 10)] + [bamboo(n) for n in range(1, 10)]
+ for n in range(9):
+ f = blank()
+ letter(f, glyphs, "一二三四五六七八九"[n], 3, 0, NAVY)
+ letter(f, glyphs, "萬", 3, 11, RED)
+ out.append(f)
+ for ch, c in zip("東南西北中發", (NAVY,) * 4 + (RED, GREEN)):
+ f = blank()
+ letter(f, glyphs, ch, 3, 5, c)
+ out.append(f)
+ f = blank() # the white dragon: a blue frame
+ for y in range(3, 21):
+ for x in range(3, 15):
+ if x < 5 or x > 12 or y < 5 or y > 18:
+ f[y][x] = BLUE
+ for y in range(6, 18):
+ for x in range(6, 12):
+ if x == 6 or x == 11 or y == 6 or y == 17:
+ f[y][x] = SKY
+ out.append(f)
+ out += [flower(n) for n in range(1, 5)] + [season(n) for n in range(1, 5)]
+ assert len(out) == 42
+ return out
+
+
+def lz_pack(d):
+ """np_lz.h's stream, greedy, with the longest match up to 4096 back"""
+ out, i, n = bytearray(), 0, len(d)
+ while i < n:
+ flag_at, flags = len(out), 0
+ out.append(0)
+ for b in range(8):
+ if i >= n:
+ break
+ best, dist = 0, 0
+ for j in range(max(0, i - 4096), i):
+ k = 0
+ while k < 18 and i + k < n and d[j + k] == d[i + k]:
+ k += 1
+ if k > best:
+ best, dist = k, i - j
+ if best >= 3:
+ out += bytes([(dist - 1) & 255, ((dist - 1) >> 8) | (best - 3) << 4])
+ i += best
+ else:
+ flags |= 1 << b
+ out.append(d[i])
+ i += 1
+ out[flag_at] = flags
+ return bytes(out)
+
+
+def icon(glyphs, path):
+ """the app's icon: a red dragon tile, its face and green back, on the felt"""
+ from PIL import Image, ImageDraw
+ im = Image.new("RGBA", (55, 56), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ d.rounded_rectangle((0, 0, 54, 55), 11, fill=(0x14, 0x51, 0x2F, 255))
+ x, y, w, h = 10, 5, 30, 40
+ for k, c in ((5, 0x1D603B), (4, 0x2E8A57), (3, 0x2E8A57), (2, 0xB9AA86), (1, 0xCDBF9C)):
+ d.rounded_rectangle((x + k, y + k, x + k + w - 1, y + k + h - 1), 4, fill=(c >> 16, c >> 8 & 255, c & 255))
+ d.rounded_rectangle((x, y, x + w - 1, y + h - 1), 4, fill=(0xF8, 0xF3, 0xE6), outline=(0x8E, 0x83, 0x68))
+ xo, top, bits = glyphs["中"]
+ for j, row in enumerate(bits):
+ for i, b in enumerate(row):
+ if b:
+ d.rectangle((x + 4 + 2 * (xo + i), y + 7 + 2 * (top - 1 + j), x + 5 + 2 * (xo + i), y + 8 + 2 * (top - 1 + j)),
+ fill=(0xC6, 0x28, 0x28))
+ im.save(path)
+
+
+def main():
+ bdf = sys.argv[1]
+ glyphs = load_bdf(bdf, "一二三四五六七八九萬東南西北中發")
+ fs = faces(glyphs)
+ raw = bytearray()
+ for f in fs:
+ for y in range(H):
+ for x in range(0, W, 2):
+ raw.append(f[y][x] | f[y][x + 1] << 4)
+ packed = lz_pack(raw)
+ here = os.path.dirname(os.path.abspath(__file__))
+ L = ["/* Generated by tools/art.py: the faces of the 42 kinds of tiles, 18 x 24 pixels of 16 colours (0: none),",
+ " * four bits a pixel (the left one low), packed with np_lz.h. The characters are Fusion Pixel 12px's. */",
+ f"#define ART_W {W}", f"#define ART_H {H}", "#define ART_KINDS 42", f"#define ART_RAW {len(raw)}",
+ "static const uint32_t art_pal[16] = {" + ", ".join(f"0x{c:06X}" for c in PAL) + "};",
+ f"static const uint8_t art_lz[{len(packed)}] = {{"]
+ for k in range(0, len(packed), 24):
+ L.append(" " + ", ".join(str(b) for b in packed[k:k + 24]) + ",")
+ L.append("};")
+ open(os.path.join(here, "..", "src", "art.h"), "w").write("\n".join(L) + "\n")
+ print(f"src/art.h: {len(raw)} bytes packed to {len(packed)}")
+ icon(glyphs, os.path.join(here, "..", "src", "icon.png"))
+ if "--preview" in sys.argv:
+ from PIL import Image
+ s = 4
+ img = Image.new("RGB", (9 * (W + 4) * s, 5 * (H + 4) * s), (40, 90, 60))
+ for k, f in enumerate(fs):
+ ox, oy = k % 9 * (W + 4) * s, k // 9 * (H + 4) * s
+ for y in range(H):
+ for x in range(W):
+ c = PAL[f[y][x]] if f[y][x] else 0xF4EEDC
+ for dy in range(s):
+ for dx in range(s):
+ img.putpixel((ox + x * s + dx, oy + y * s + dy), (c >> 16, c >> 8 & 255, c & 255))
+ img.save(sys.argv[sys.argv.index("--preview") + 1])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/mahjong/tools/layouts.py b/games/mahjong/tools/layouts.py
new file mode 100644
index 00000000..6290fe58
--- /dev/null
+++ b/games/mahjong/tools/layouts.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Writes src/layouts.h: the four layouts of 144 tiles, from KMahjongg's layout files (GPL-2.0-or-later).
+
+ layouts.py DIR (DIR: KMahjongg's layouts folder: default.layout, the Turtle, and dragon, crab, spider)
+
+A tile takes 2 x 2 cells of a layout file, so its place is in half tiles: x 0 to 31, y 0 to 15, and its layer z.
+Each tile is two bytes, x then y + 16 z, ordered by layer, then x, then y: the order they are drawn in."""
+import os
+import sys
+
+LAYOUTS = [("Turtle", "default"), ("Dragon", "dragon"), ("Crab", "crab"), ("Spider", "spider")]
+
+
+def parse(path):
+ w = h = d = None
+ grid = []
+ for line in open(path).read().split("\n"):
+ line = line.rstrip()
+ if not line or line.startswith(("#", "kmahjongg")):
+ continue
+ if line[0] in "whd" and line[1:].isdigit():
+ w, h, d = (int(line[1:]) if line[0] == k else v for k, v in zip("whd", (w, h, d)))
+ continue
+ grid.append(line)
+ tiles = []
+ for z in range(d):
+ for y, row in enumerate(grid[z * h:(z + 1) * h]):
+ tiles += [(x, y, z) for x, ch in enumerate(row) if ch == "1"]
+ return sorted(tiles, key=lambda t: (t[2], t[0], t[1]))
+
+
+def main():
+ out = ["/* Generated by tools/layouts.py from KMahjongg's layouts (GPL-2.0-or-later): each tile's x in half tiles,",
+ " * then its y in half tiles + 16 x its layer, in the order they're drawn (layer, x, y). */",
+ f"#define LAYOUTS {len(LAYOUTS)}",
+ "static const char *const layout_name[LAYOUTS] = {" + ", ".join(f'T("{n}")' for n, _ in LAYOUTS) + "};",
+ f"static const uint8_t layout_tiles[LAYOUTS][288] = {{"]
+ for name, f in LAYOUTS:
+ t = parse(os.path.join(sys.argv[1], f + ".layout"))
+ assert len(t) == 144, (name, len(t))
+ assert all(x < 32 and y < 16 and z < 8 for x, y, z in t)
+ print(f"{name}: 144 tiles, {max(z for *_, z in t) + 1} layers, x {min(x for x, *_ in t)} to {max(x for x, *_ in t)}")
+ b = [v for x, y, z in t for v in (x, y + 16 * z)]
+ out.append(f" {{ /* {name} */")
+ for k in range(0, 288, 24):
+ out.append(" " + ", ".join(str(v) for v in b[k:k + 24]) + ",")
+ out.append(" },")
+ out.append("};")
+ open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src", "layouts.h"), "w").write("\n".join(out) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_games.py b/tests/test_games.py
index 4aabcb01..7126f3c2 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -279,6 +279,10 @@ GAMES = {
"badtime": ("BadTimeSimulator.nwa", "badtime.sav",
presses((1500, "ok"), (2200, "ok"), (2900, "ok"), (3600, "ok"), (5000, "ok")), 6500,
presses((1500, "ok")), 4000),
+ # how to play read, the Turtle dealt, a tile picked; Home keeps the game. Next time, from the copy, it goes on: the
+ # cursor moved, quit with On/Off
+ "mahjong": ("Mahjong.nwa", "mahjong.sav", presses((1500, "ok"), (2200, "ok"), (3000, "ok")), 4000,
+ presses((1500, "right"), (2000, "ok")), 3000),
# a level, its message, then play; then back to the level select
"portal": ("PortalReturns.nwa", "portal.sav",
presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,
@@ -347,7 +351,7 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p
"tombofthemask": "tombofthemask_saves.py", "uno": "uno_saves.py",
"fnf": "fnf_saves.py", "turborush": "turborush_saves.py",
"angrybirds": "angrybirds_saves.py", "polytrack": "polytrack_saves.py", "paperclips": "paperclips_saves.py",
- "badtime": "badtime_saves.py"}
+ "badtime": "badtime_saves.py", "mahjong": "mahjong_saves.py"}
def paperclips_ok(v):
@@ -370,6 +374,16 @@ def badtime_ok(v):
return struct.unpack_from("<I", v, 20)[0] == h
+def mahjong_ok(v):
+ """Mahjong's save: "M", version 1, 328 bytes, an FNV-1a sum of the rest at the end"""
+ if len(v) != 328 or v[:2] != b"M\1":
+ return False
+ h = 2166136261
+ for x in v[:-4]:
+ h = (h ^ x) * 16777619 & 0xFFFFFFFF
+ return struct.unpack_from("<I", v, 324)[0] == h
+
+
def polytrack_ok(v):
"""PolyTrack's save: "PTK1", version 1, 768 bytes, an FNV-1a sum of the rest at the end"""
if len(v) != 768 or v[:4] != b"PTK1" or struct.unpack_from("<HH", v, 4) != (1, 768):
@@ -553,6 +567,10 @@ CHECKS = {
# "BTS1", version 1, its size (24): how to play read (guide at 9), the first attack reached (best at 8); after the
# reinstall, from the copy, the same
"badtime": (lambda v: badtime_ok(v) and v[9] == 1 and v[8] >= 1,) * 2,
+ # "M", version 1: how to play read and a Turtle being played (flags 3 at 2, the layout at 3), its time at 8; after
+ # the reinstall, from the copy, it goes on
+ "mahjong": (lambda v: mahjong_ok(v) and v[2] == 3 and v[3] == 0 and struct.unpack_from("<I", v, 8)[0] > 0,
+ lambda v: mahjong_ok(v) and v[2] == 3 and struct.unpack_from("<I", v, 8)[0] > 1000),
"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,
lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
# Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies of the six games kept
diff --git a/tools/release.py b/tools/release.py
index 128888eb..5ca6126a 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -55,6 +55,7 @@ ALONE = {
"polytrack": ("PolyTrack", "Kodub's low-poly time trial racer: its 17 tracks, loops, wall rides and jumps, against your ghost"),
"paperclips": ("Universal Paperclips", "Frank Lantz's game of an AI making paperclips: business, the Earth, then the universe"),
"badtime": ("Bad Time Simulator", "the Judge's fight: 24 attacks of bones, gavels and the blue heart, after jcw87's Bad Time Simulator"),
+ "mahjong": ("Mahjong", "Mahjong solitaire: 144 tiles in the Turtle, the Dragon, the Crab and the Spider, every deal winnable"),
}
VARIANTS = [
("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),