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.

Sokoban: Microban's 155 levels, undo, the level list

Mason3637b88c574c359
diff --git a/games/games.json b/games/games.json
index 987b737c..caf1f13b 100644
--- a/games/games.json
+++ b/games/games.json
@@ -416,6 +416,24 @@
"app": "UltimateTicTacToe.nwa",
"repo": "https://github.com/Mason363/NumPlay/tree/main/games/uttt"
},
+ {
+ "id": "sokoban",
+ "title": "Sokoban",
+ "tagline": "Push every box home",
+ "credit": "Levels: Microban by David W. Skinner",
+ "top": "0xC9843F",
+ "bottom": "0x2B2730",
+ "accent": "0xF2B53C",
+ "colors": 8,
+ "records": [
+ "sokoban.sav"
+ ],
+ "shots": [
+ "docs/shot.png"
+ ],
+ "app": "Sokoban.nwa",
+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/sokoban"
+ },
{
"id": "numvisuals",
"title": "NumVisuals",
diff --git a/games/sokoban/.gitignore b/games/sokoban/.gitignore
new file mode 100644
index 00000000..342d9dda
--- /dev/null
+++ b/games/sokoban/.gitignore
@@ -0,0 +1,2 @@
+output/
+build/
diff --git a/games/sokoban/Makefile b/games/sokoban/Makefile
new file mode 100644
index 00000000..0f0f26c6
--- /dev/null
+++ b/games/sokoban/Makefile
@@ -0,0 +1,99 @@
+# Sokoban — push every box onto a goal, with David W. Skinner's Microban.
+# make build output/sokoban.nwa
+# make check link the app like the calculator does (output/sokoban.bin)
+# make test every level solved on a computer with its solution (tests/play.c, tests/solutions.txt)
+# make media the pictures of the README and How to play
+#
+# tools/levels.py packs levels/microban.txt into output/levels.inc (Python 3; zopfli if installed): all
+# 155 levels on its own, the first NUMPLAY_LEVELS inside NumPlay, where room is short.
+# In NumPlay the game draws with the launcher's strips, shapes and fonts, saves through its file
+# functions and unpacks its levels with its inflater (module.o leaves them to the launcher); on its
+# own it brings them along.
+Q ?= @
+CC = arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+BUILD_DIR = output
+SRC = src/main.c
+LEVELS = $(BUILD_DIR)/levels.inc
+NUMPLAY_LEVELS ?= 60
+HEADERS = ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h ../../launcher/src/gfx.h \
+ ../../launcher/src/np.h ../../launcher/src/font.h ../../launcher/src/inflate.h
+
+CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device) -I$(BUILD_DIR)
+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test media
+build: $(BUILD_DIR)/sokoban.nwa
+
+check: $(BUILD_DIR)/sokoban.nwa
+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/sokoban.bin
+ @echo "BIN $(BUILD_DIR)/sokoban.bin: $$(wc -c < $(BUILD_DIR)/sokoban.bin) bytes"
+
+$(LEVELS): tools/levels.py levels/microban.txt | $(BUILD_DIR)
+ $(Q) python3 tools/levels.py $(BUILD_DIR)
+$(BUILD_DIR)/numplay/levels.inc: tools/levels.py levels/microban.txt Makefile | $(BUILD_DIR)
+ $(Q) python3 tools/levels.py $(BUILD_DIR)/numplay $(NUMPLAY_LEVELS)
+
+# compiled, then linked (the link options would upset the compiler)
+$(BUILD_DIR)/main.o: $(SRC) $(LEVELS) $(HEADERS) | $(BUILD_DIR)
+ @echo "CC $<"
+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@
+$(BUILD_DIR)/gfx.o: ../../launcher/src/gfx.c $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/font_data.o: ../../launcher/src/font_data.c ../../launcher/src/font.h | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/xfont.o: ../../launcher/src/xfont.c ../../launcher/src/np_xfont.h $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/inflate.o: ../../launcher/src/inflate.c ../../launcher/src/inflate.h | $(BUILD_DIR)
+ $(Q) $(CC) $(CFLAGS) -c $< -o $@
+
+$(BUILD_DIR)/sokoban.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \
+ $(BUILD_DIR)/inflate.o $(BUILD_DIR)/icon.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@
+ $(Q) arm-none-eabi-strip --strip-unneeded $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
+
+# on a computer, with the sanitizers: every level solved, and pictures
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -DPLATFORM_DEVICE=1 -DHOST -I$(BUILD_DIR) \
+ $(shell $(NWLINK) eadk-cflags-simulator) -fsanitize=address,undefined -fno-sanitize-recover=undefined
+host: build/play
+build/play: $(SRC) $(LEVELS) tests/play.c $(HEADERS)
+ $(Q) mkdir -p build
+ $(Q) cc $(HOST_FLAGS) tests/play.c ../../launcher/src/gfx.c ../../launcher/src/font_data.c \
+ ../../launcher/src/xfont.c ../../launcher/src/inflate.c -lm -o $@
+ @echo "HOST $@"
+test: build/play
+ build/play solve tests/solutions.txt
+# the README's and How to play's pictures (tools/media.py)
+media: build/play
+ python3 tools/media.py
+
+# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the
+# calculator, and as a relocatable object for the simulator build.
+.PHONY: module sim-module
+module: $(BUILD_DIR)/module.o
+$(BUILD_DIR)/module-main.o: $(SRC) $(BUILD_DIR)/numplay/levels.inc $(HEADERS) | $(BUILD_DIR)
+ $(Q) $(CC) -I$(BUILD_DIR)/numplay $(CFLAGS) -DNP_MODULE=1 -c $(SRC) -o $@
+$(BUILD_DIR)/module.o: $(BUILD_DIR)/module-main.o
+ $(Q) $(CC) $(CFLAGS) -Wl,--relocatable -nostartfiles -nostdlib -Wl,-e,main -flinker-output=nolto-rel $< -o $@
+
+sim-module: $(BUILD_DIR)/sim-module.o
+$(BUILD_DIR)/sim-module.o: $(SRC) $(BUILD_DIR)/numplay/levels.inc $(HEADERS) | $(BUILD_DIR)
+ $(Q) mkdir -p $(BUILD_DIR)/sim
+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -I$(BUILD_DIR)/numplay -DNP_MODULE=1 \
+ -Dmain=np_sokoban_main -c $(SRC) -o $(BUILD_DIR)/sim/main.o
+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_sokoban_main -o $@
diff --git a/games/sokoban/README.md b/games/sokoban/README.md
new file mode 100644
index 00000000..8a5edc5d
--- /dev/null
+++ b/games/sokoban/README.md
@@ -0,0 +1,33 @@
+# Sokoban
+
+Push every box onto a goal. Hiroyuki Imabayashi's warehouse puzzle on the NumWorks calculator, with David W. Skinner's Microban: 155 levels, from the very first push to The Dungeon.
+
+<img src="docs/shot.png" width="320" alt="Sokoban: the keeper next to a crate, two crates already on their goals, one goal left">
+
+- **Microban's 155 levels**, small ones that each show an idea, the easy ones first. **Sokoban.nwa** has all 155; **inside NumPlay** there's room for the first 60. Both keep the same progress, so a level solved in one is solved in the other.
+- **The rules of the original:** the keeper pushes the boxes one at a time and can never pull them, so a box pushed into a corner stays there.
+- **Undo** takes back your steps, one at a time, as far as you like; **Restart** puts the level back as it began.
+- **Moves and pushes** are counted, and the fewest moves you solved each level in are kept.
+- **The levels**, ten to a row: the ones you solved are green. A level opens while fewer than three before it are still unsolved, so one that blocks you never stops you for good.
+- Steps glide from cell to cell, the keeper looks where he goes, and a box turns green on its goal. Big levels shrink to fit the screen.
+
+<img src="docs/levels.png" width="320" alt="The level list: the first sixteen levels solved in green, the next three open">
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Arrows, or 8 4 6 2 | Walk, and push a box (hold to keep going) |
+| Backspace | Undo a step (hold to undo more) |
+| OK or EXE | Choose |
+| Back | Pause: Resume, Restart, Levels, How to play, Quit game |
+
+## Credits
+
+**Sokoban** is Hiroyuki Imabayashi's game, first published by Thinking Rabbit in 1982. This version is written in C for NumPlay and drawn from shapes as it goes, with no code or art from any Sokoban.
+
+The levels are **Microban** by **David W. Skinner** (2000), from [his Sokoban page](http://users.bentonrea.com/~sasquatch/sokoban/) as kept on [Scott Lindhurst's Sokoban levels page](http://www.sneezingtiger.com/sokoban/levels.html); they are his, used with credit to him. `levels/microban.txt` holds them as he wrote them. `tools/levels.py` keeps what the keeper can reach (the walls are put back around the floor), and `tools/solve.py` solves every one of them for the tests.
+
+It comes inside [NumPlay](https://github.com/Mason363/NumPlay), or on its own as `Sokoban.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+Build: `make` (needs `arm-none-eabi-gcc`, Node.js for nwlink and Python 3). `make test` plays every level through on a computer with its solution, then undoes it all.
diff --git a/games/sokoban/docs/shot.png b/games/sokoban/docs/shot.png
new file mode 100644
index 00000000..7c8069df
Binary files /dev/null and b/games/sokoban/docs/shot.png differ
diff --git a/games/sokoban/lang/fr.txt b/games/sokoban/lang/fr.txt
new file mode 100644
index 00000000..1ae9f27a
--- /dev/null
+++ b/games/sokoban/lang/fr.txt
@@ -0,0 +1,21 @@
+# Sokoban in French: the English text as in the source, a tab, the translation (see tools/lang.py).
+Resume Reprendre
+Restart Recommencer
+Levels Niveaux
+How to play Comment jouer
+Quit game Quitter le jeu
+Quit game? Quitter le jeu ?
+No Non
+Yes Oui
+Paused Pause
+Solved! Réussi !
+Push every box onto a goal: one at a time, and never pulled.\nArrows: walk and push\nBackspace: undo Back: pause Pousse chaque caisse sur une cible : une à la fois, et jamais en tirant.\nFlèches : marcher et pousser\nEffacer : annuler Retour : pause
+Play Jouer
+Next level Niveau suivant
+Level Niveau
+Moves Pas
+Pushes Poussées
+Solve the levels before it to open it Réussis les niveaux d'avant pour l'ouvrir
+Solved in moves: Réussi en pas :
+Not solved yet Pas encore réussi
+Your best: Ton record :
diff --git a/games/sokoban/lang/zh.txt b/games/sokoban/lang/zh.txt
new file mode 100644
index 00000000..bce4c0e8
--- /dev/null
+++ b/games/sokoban/lang/zh.txt
@@ -0,0 +1,21 @@
+# Sokoban in Chinese: the English text as in the source, a tab, the translation (see tools/lang.py).
+Resume 继续
+Restart 重来
+Levels 关卡
+How to play 玩法
+Quit game 退出游戏
+Quit game? 退出游戏?
+No 否
+Yes 是
+Paused 暂停
+Solved! 过关!
+Push every box onto a goal: one at a time, and never pulled.\nArrows: walk and push\nBackspace: undo Back: pause 把每个箱子推到目标上:一次推一个,不能拉。\n方向键:走路、推箱子\n退格:撤销 返回:暂停
+Play 开始
+Next level 下一关
+Level 关卡
+Moves 步数
+Pushes 推动
+Solve the levels before it to open it 先过前面的关卡才能打开
+Solved in moves: 过关步数:
+Not solved yet 还没过关
+Your best: 最佳:
diff --git a/games/sokoban/levels/microban.txt b/games/sokoban/levels/microban.txt
new file mode 100644
index 00000000..8cb111d8
--- /dev/null
+++ b/games/sokoban/levels/microban.txt
@@ -0,0 +1,1670 @@
+; Microban, by David W. Skinner (2000): 155 levels, from his Sokoban page
+; (users.bentonrea.com/~sasquatch/sokoban), here as kept at http://www.sneezingtiger.com/sokoban/levels/microbanText.html
+
+; 1
+####
+# .#
+# ###
+#*@ #
+# $ #
+# ###
+####
+
+; 2
+######
+# #
+# #@ #
+# $* #
+# .* #
+# #
+######
+
+; 3
+ ####
+### ####
+# $ #
+# # #$ #
+# . .#@ #
+#########
+
+; 4
+########
+# #
+# .**$@#
+# #
+##### #
+ ####
+
+; 5
+ #######
+ # #
+ # .$. #
+## $@$ #
+# .$. #
+# #
+########
+
+; 6
+###### #####
+# ### #
+# $$ #@#
+# $ #... #
+# ########
+#####
+
+; 7
+#######
+# #
+# .$. #
+# $.$ #
+# .$. #
+# $.$ #
+# @ #
+#######
+
+; 8
+ ######
+ # ..@#
+ # $$ #
+ ## ###
+ # #
+ # #
+#### #
+# ##
+# # #
+# # #
+### #
+ #####
+
+; 9
+#####
+#. ##
+#@$$ #
+## #
+ ## #
+ ##.#
+ ###
+
+; 10
+ #####
+ #. #
+ #.# #
+#######.# #
+# @ $ $ $ #
+# # # # ###
+# #
+#########
+
+; 11
+ ######
+ # #
+ # ##@##
+### # $ #
+# ..# $ #
+# #
+# ######
+####
+
+; 12
+#####
+# ##
+# $ #
+## $ ####
+ ###@. #
+ # .# #
+ # #
+ #######
+
+; 13
+####
+#. ##
+#.@ #
+#. $#
+##$ ###
+ # $ #
+ # #
+ # ###
+ ####
+
+; 14
+#######
+# #
+# # # #
+#. $*@#
+# ###
+#####
+
+; 15
+ ###
+######@##
+# .* #
+# # #
+#####$# #
+ # #
+ #####
+
+; 16
+ ####
+ # ####
+ # ##
+## ## #
+#. .# @$##
+# # $$ #
+# .# #
+##########
+
+; 17
+#####
+# @ #
+#...#
+#$$$##
+# #
+# #
+######
+
+; 18
+#######
+# #
+#. . #
+# ## ##
+# $ #
+###$ #
+ #@ #
+ # #
+ ####
+
+; 19
+########
+# .. #
+# @$$ #
+##### ##
+ # #
+ # #
+ # #
+ ####
+
+; 20
+#######
+# ###
+# @$$..#
+#### ## #
+ # #
+ # ####
+ # #
+ ####
+
+; 21
+####
+# ####
+# . . #
+# $$#@#
+## #
+ ######
+
+; 22
+#####
+# ###
+#. . #
+# # #
+## # #
+ #@$$ #
+ # #
+ # ###
+ ####
+
+; 23
+#######
+# * #
+# #
+## # ##
+ #$@.#
+ # #
+ #####
+
+; 24
+# #####
+ # #
+###$$@#
+# ###
+# #
+# . . #
+#######
+
+; 25
+ ####
+ # ###
+ # $$ #
+##... #
+# @$ #
+# ###
+#####
+
+; 26
+ #####
+ # @ #
+ # #
+###$ #
+# ...#
+# $$ #
+### #
+ ####
+
+; 27
+######
+# .#
+# ## ##
+# $$@#
+# # #
+#. ###
+#####
+
+; 28
+#####
+# #
+# @ #
+# $$###
+##. . #
+ # #
+ ######
+
+; 29
+ #####
+ # ##
+ # #
+ ###### #
+## #. #
+# $ $ @ ##
+# ######.#
+# #
+##########
+
+; 30
+####
+# ###
+# $$ #
+#... #
+# @$ #
+# ##
+#####
+
+; 31
+ ####
+ ## #
+##@$.##
+# $$ #
+# . . #
+### #
+ #####
+
+; 32
+ ####
+## ###
+# #
+#.**$@#
+# ###
+## #
+ ####
+
+; 33
+#######
+#. # #
+# $ #
+#. $#@#
+# $ #
+#. # #
+#######
+
+; 34
+ ####
+### ####
+# #
+#@$***. #
+# #
+#########
+
+; 35
+ ####
+ ## #
+ #. $#
+ #.$ #
+ #.$ #
+ #.$ #
+ #. $##
+ # @#
+ ## #
+ #####
+
+; 36
+####
+# ############
+# $ $ $ $ $ @ #
+# ..... #
+###############
+
+; 37
+ ###
+##### #.#
+# ###.#
+# $ #.#
+# $ $ #
+#####@# #
+ # #
+ #####
+
+; 38
+##########
+# #
+# ##.### #
+# # $$ . #
+# . @$## #
+##### #
+ ######
+
+; 39
+#####
+# ####
+# # # .#
+# $ ###
+### #$. #
+# #@ #
+# # ######
+# #
+#####
+
+; 40
+ #####
+ # #
+## ##
+# $$$ #
+# .+. #
+#######
+
+; 41
+#######
+# #
+#@$$$ ##
+# #...#
+## ##
+ ######
+
+; 42
+ ####
+ # #
+ #@ #
+####$.#
+# $.#
+# # $.#
+# ##
+######
+
+; 43
+ ####
+ # @#
+ # #
+###### .#
+# $ .#
+# $$# .#
+# ####
+### #
+ ####
+
+; 44 'Duh!'
+#####
+#@$.#
+#####
+
+; 45
+######
+#... #
+# $ #
+# #$##
+# $ #
+# @ #
+######
+
+; 46
+ ######
+## #
+# ## #
+# # $ #
+# * .#
+## #@##
+ # #
+ #####
+
+; 47
+ #######
+### #
+# $ $ #
+# ### #####
+# @ . . #
+# ### #
+##### #####
+
+; 48
+######
+# @ #
+# # ##
+# .# ##
+# .$$$ #
+# .# #
+#### #
+ #####
+
+; 49
+######
+# @ #
+# $# #
+# $ #
+# $ ##
+### ####
+ # # #
+ #... #
+ # #
+ #######
+
+; 50
+ ####
+### #####
+# $ @..#
+# $ # #
+### #### #
+ # #
+ ########
+
+; 51
+####
+# ###
+# ###
+# $*@ #
+### .# #
+ # #
+ ######
+
+; 52
+ ####
+### @#
+# $ #
+# *.#
+# *.#
+# $ #
+### #
+ ####
+
+; 53
+ #####
+##. .##
+# * * #
+# # #
+# $ $ #
+## @ ##
+ #####
+
+; 54
+ ######
+ # #
+ ##### . #
+### ###. #
+# $ $ . ##
+# @$$ # . #
+## #####
+ ######
+
+; 55
+########
+# @ # #
+# #
+#####$ #
+ # ###
+ ## #$ ..#
+ ## # ###
+ ####
+
+; 56
+#####
+# ###
+# $ #
+##* . #
+ # @#
+ ######
+
+; 57
+ ####
+ # #
+ #@ #
+ # #
+### ####
+# * #
+# $ #
+#####. #
+ ####
+
+; 58
+####
+# ####
+#.*$ #
+# .$# #
+## @ #
+ # ##
+ #####
+
+; 59
+############
+# #
+# ####### @##
+# # #
+# # $ # #
+# $$ ##### #
+### # # ...#
+ #### # #
+ ######
+
+; 60
+ #########
+ # #
+##@##### #
+# # # #
+# # $.#
+# ##$##.#
+##$## #.#
+# $ #.#
+# # ###
+########
+
+; 61
+########
+# #
+# #### #
+# #...@#
+# ###$###
+# # #
+# $$ $ #
+#### ##
+ #.###
+ ###
+
+; 62
+ ##########
+#### ## #
+# $$$....$@#
+# ### #
+# #### ####
+#####
+
+; 63
+##### ####
+# ##### .#
+# $ ########
+### #### .$ @ #
+ # # # #### #
+ #### #### #####
+
+; 64
+ ######
+## #
+# $ #
+# $$ #
+### .#####
+ ##.# @ #
+ #. $ #
+ #. ####
+ ####
+
+; 65
+ ######
+ # #
+ # $ #
+ ####$ #
+## $ $ #
+#....# ##
+# @ #
+## # #
+ ########
+
+; 66
+ ###
+ #@#
+ ###$###
+## . ##
+# # # #
+# # # #
+# # # #
+# # # #
+# # # #
+## $ $ ##
+ ##. .##
+ # #
+ # #
+ #####
+
+; 67
+#####
+# ##
+# # #
+#@$*.##
+## . #
+ # $# #
+ ## #
+ #####
+
+; 68
+ ####
+ # ######
+## $ #
+# .# $ #
+# .#$#####
+# .@ #
+######
+
+; 69
+#### ####
+# #### #
+# # # #
+# # $##
+# . .#$ #
+#@ ## # $ #
+# . # #
+###########
+
+; 70
+#####
+# @ ####
+# #
+# $ $$ #
+##$## #
+# ####
+# .. #
+##.. #
+ ### #
+ ####
+
+; 71
+###########
+# # ###
+# $@$ # . .#
+# ## ### ## #
+# # # #
+# # # # #
+# ######### #
+# #
+#############
+
+; 72
+ ####
+ ## #####
+ # $ @ #
+ # $# #
+#### #####
+# # #
+# $ #
+# ..# #
+# .####
+# ##
+####
+
+; 73
+####
+# #####
+# $$ $ #
+# #
+## ## ##
+#...#@#
+# ### ##
+# #
+# # #
+########
+
+; 74
+ ####
+ # #######
+ #$ @# .#
+## #$$ .#
+# $ ##..#
+# # #####
+### #
+ #####
+
+; 75
+ #######
+## ....##
+# ######
+# $ $ @#
+### $ $ #
+ ### #
+ ######
+
+; 76
+ #####
+## #
+# #####
+# #.# #
+#@ #.# $ #
+# #.# ##
+# # #
+## ##$$#
+ ## #
+ # ####
+ ####
+
+; 77
+##########
+# @ .... #
+# ####$##
+## # $ $ #
+ # $ #
+ # ######
+ #####
+
+; 78
+ #######
+## ##
+# $ $ #
+# $ $ $ #
+## ### ####
+ #@ .....#
+ ## ###
+ #######
+
+; 79
+ #########
+ # # #
+## $#$# #
+# .$.@ #
+# .# #
+##########
+
+; 80
+####
+# #######
+# . ## .#
+# $# .#
+## ## # .#
+ # # #
+ #### # #
+ # @$ ###
+ # $$ #
+ # #
+ ######
+
+; 81
+ #####
+ # #
+ # . #
+## * #
+# *##
+# @##
+## $ #
+ # #
+ #####
+
+; 82
+#####
+# ###
+# . ##
+##*#$ #
+# .# $ #
+# @## ##
+# #
+#######
+
+; 83
+######
+# ##
+# $ $ ##
+## $$ #
+ # # #
+ # ## ##
+ # . .#
+ # @. .#
+ # ####
+ ####
+
+; 84
+########
+# ... #
+# ### ##
+# # $ #
+## #@$ #
+ # # $ #
+ # ### #####
+ # #
+ # ### #
+ ##### #####
+
+; 85
+ ####
+ ####### #
+ # $ #
+ # $ $ #
+ # ########
+## # . #
+# # # #
+# @ . ##
+## # # #
+ # . #
+ #######
+
+; 86
+ ####
+ ### ##
+ ## $ #
+## $ # #
+# @#$$ #
+# .. ###
+# ..###
+#####
+
+; 87
+ ####
+###### #
+# #
+# ... .#
+##$######
+# $ #
+# $###
+## $ #
+ ## @ #
+ ######
+
+; 88
+ ####
+ # ### #
+ # # #
+ # # # #
+ # #$ #.#
+ # # # # #
+ # #$ #.# #
+ # # # #
+####$ #.# #
+# @ # #
+# # ## #
+########
+
+; 89
+##########
+# ## #
+# $ $@# #
+#### # $ #
+ #.# ##
+ # #.# $#
+ # #. #
+ # #. #
+ ######
+
+; 90
+ ########
+ # @ #
+ # $ $ #
+### ## ###
+# $..$ #
+# .. #
+##########
+
+; 91
+###########
+# .## #
+# $$@..$$ #
+# ##. #
+###########
+
+; 92
+ ####
+ # # #####
+ # # # #
+ # ######.# #
+#### $ . #
+# $$# ###.# #
+# # # # #
+######### #@ ##
+ # #
+ ####
+
+; 93
+ #########
+## # ##
+# # #
+# $ # $ #
+# *.* #
+####.@.####
+# *.* #
+# $ # $ #
+# # #
+## # ##
+ #########
+
+; 94
+#########
+# @ # #
+# $ $ #
+##$### ##
+# ... #
+# # #
+###### #
+ ####
+
+; 95
+########
+#@ #
+# .$$. #
+# $..$ #
+# $..$ #
+# .$$. #
+# #
+########
+
+; 96
+ ######
+ # #
+ # #
+##### #
+# #.#####
+# $@$ #
+#####.# #
+ ## ## ##
+ # $.#
+ # ###
+ #####
+
+; 97
+ ####
+ # ########
+#### $ $.....#
+# $ ######
+#@### ###
+# $ #
+# $ # #
+## # #
+ # #
+ ######
+
+; 98
+#####
+# ## ####
+# $ ### .#
+# $ $ .#
+## $#####.# ####
+# $ # # .### #
+# # # .# @ #
+### # # #
+ #### ## ##
+ #######
+
+; 99
+ #####
+ # #
+####### ####### # #
+# # # # #
+# @ #### # ####
+# # ....## #### #
+# ##### ## $$ $ $ #
+###### # #
+ # ##########
+ ####
+
+; 100
+#######
+# @# #
+#.$ #
+#. # $##
+#.$# #
+#. # $ #
+# # #
+########
+
+; 101 'Lockdown'
+ #####
+ # #
+ # # #######
+ # * # #
+ ## ## # #
+ # #* #
+### # # # ###
+# *#$+ #
+# # ## ##
+# # * #
+####### # #
+ # #
+ #####
+
+; 102
+###########
+#....# #
+# # $$ #
+# @ ## #
+# ##$ #
+###### $ #
+ # #
+ ######
+
+; 103
+ #####
+ # . ##
+### $ #
+# . $#@#
+# #$ . #
+# $ ###
+## . #
+ #####
+
+; 104
+ #####
+##### #
+# $ #
+# $#$#@#
+### # #
+ # ... #
+ ### ##
+ # #
+ ####
+
+; 105
+ #### ####
+## ### ##
+# # # #
+# *. .* #
+###$ $###
+ # @ #
+###$ $###
+# *. .* #
+# # # #
+## ### ##
+ #### ####
+
+; 106
+ ########
+ # #
+ #@ $ #
+## ###$ #
+# .....###
+# $ $ $ #
+###### # #
+ # #
+ #####
+
+; 107
+########
+# #
+# $*** #
+# * * #
+# * * #
+# ***. #
+# @#
+########
+
+; 108
+#### #####
+# ### # ##
+# # #$ $ #
+#..# ##### # #
+# @ # $ $ #
+#..# ##
+## #########
+ #####
+
+; 109
+ #######
+# # #
+# # # # #
+ # @ $ #
+### ### #
+# ### #
+# $ ##.#
+## $ #.#
+ ## $ .#
+# ## $#.#
+## ## #.#
+### # #
+### #####
+
+; 110
+ ####
+ # #
+ # $####
+###. . #
+# $ # $ #
+# . .###
+####$ #
+ # @#
+ ####
+
+; 111
+######
+# ####
+# ...#
+# ...#
+###### #
+ # # #
+ # $$ ##
+ # @$ #
+ # $$ #
+ ## $# #
+ # #
+ ######
+
+; 112
+ #####
+## ####
+# $$$ #
+# # $ #
+# $## ##
+### #. #
+ # # #
+ ##### ###
+ # # ##
+ # @....#
+ # #
+ # # #
+ ########
+
+; 113
+ #####
+ ## #
+### # #
+# . #
+# ## #####
+# . . # ##
+# # @ $ ###
+#####. # $ #
+ #### $ #
+ ## $ ##
+ # ##
+ # #
+ ####
+
+; 114
+######
+# ###
+# # $ #
+# $ @ #
+## ## #####
+# #......#
+# $ $ $ $ #
+## ######
+ #####
+
+; 115
+ #####
+##### ####
+# # #
+# #..... #
+## ## # ###
+ #$$@$$$ #
+ # ###
+ #######
+
+; 116
+ #####
+ ### #
+####.....#
+# @$$$$$ #
+# # ##
+##### #
+ #####
+
+; 117
+ #### ####
+ # ### ##
+ # @ #
+##..### #
+# # #
+#...#$ # #
+# ## $$ $ #
+# $ ###
+#### ###
+ ####
+
+; 118
+ #####
+## ##
+# $ ##
+# $ $ ##
+###$# . ##
+ # # . #
+ ## ##. #
+ # @ . ##
+ # # #
+ ########
+
+; 119
+ ######
+ # ##
+ ## ## #
+ # $$ # #
+ # @$ # #
+ # # #
+#### # #
+# ... ##
+# ##
+#######
+
+; 120
+ ####
+####### #
+# $ ##
+# $##### #
+# @# # #
+## ##.. #
+# # ..####
+# $ ###
+# $###
+# #
+####
+
+; 121
+ ######
+ # . #
+##$.# #
+# * #
+# ..###
+##$ # #####
+## ## # #
+# #### # #
+# @ $ $ #
+## # #
+ ##########
+
+; 122
+#####
+# ###
+# #$ #
+# $ #
+# $ $ #
+# $# #
+# @###
+## ########
+# ...#
+# #
+########..#
+ ####
+
+; 123
+########
+# #
+# $ $$ ########
+##### @##. . #
+ #$ # . #
+ # #. . ##
+ #$# ## # #
+ # #
+ # ### ##
+ # # ####
+ ####
+
+; 124
+##############
+# # #
+# $@$$ # . ..#
+## ## ### ## #
+ # # # #
+ # # # # #
+ # ######### #
+ # #
+ #############
+
+; 125
+ #####
+ # ##
+ # $ #
+######## #@##
+# . # $ $ #
+# $# #
+#...##### #
+##### #####
+
+; 126
+ ###########
+##....... #
+# $$$$$$$@ #
+# # # # ##
+# # # #
+# #######
+#####
+
+; 127
+## ####
+#### ####
+ # $ $. #
+## # .$ #
+# ##.###
+# $ . #
+# @ # #
+# ######
+####
+
+; 128
+ #########
+### # #
+# * $ . . #
+# $ ## ##
+####*# #
+ # @ ###
+ # ###
+ #####
+
+; 129
+ #########
+### @ # #
+# * $ *.. #
+# $ # #
+####*# ###
+ # ##
+ # ###
+ #####
+
+; 130
+##### #####
+# ####.. #
+# $$$ #
+# $# .. #
+### @# ## #
+ # ## #
+ ##########
+
+; 131
+#####
+# #
+# . #
+#.@.###
+##.# #
+# $ #
+# $ #
+##$$ #
+ # ###
+ # #
+ ####
+
+; 132
+####
+# @###
+#.* #####
+#..#$$ $ #
+## #
+ # # ## #
+ # #####
+ #####
+
+; 133
+ #######
+ # . .###
+ # . . . #
+### #### #
+# @$ $ #
+# $$ $ #
+#### ###
+ #####
+
+; 134
+ ####
+######### #
+# ## $ #
+# $ ## #
+### #. .# ##
+ # #. .#$##
+ # # # #
+ # @ $ #
+ # #######
+ ####
+
+; 135
+#######
+# #####
+# $$#@##..#
+# # #
+# $ # # #
+#### $ ..#
+ ########
+
+; 136
+ #######
+ # #
+## ###$##
+#.$ @ #
+# .. #$ #
+#.## $ #
+# ####
+######
+
+; 137
+ ####
+ ## ###
+#### # $ #
+# #### $ $ #
+# ..# #$ #
+# # @ ###
+## #..# ###
+ # ## # #
+ # #
+ ########
+
+; 138
+ ####
+### #
+# ###
+# # . .#
+# @ ...####
+# # # # ##
+# # $$ #
+##### $ $ #
+ ##$ # ##
+ # #
+ ######
+
+; 139
+ ####
+## ####
+# ...#
+# ...#
+# # ##
+# #@ #### ####
+##### $ ### #
+ # ##$ $ #
+ ### $$ #
+ # $ ## ###
+ # ######
+ ######
+
+; 140
+######## #####
+# # ### #
+# ## $ #
+#.# @ ## $ ##
+#.# # $ ##
+#.# $ ##
+#. ## #####
+## #
+ ######
+
+; 141
+ ########
+ # # . #
+ # .*.#
+ # # * #
+####$##.##
+# $ #
+# $ ## $ #
+# @# #
+##########
+
+; 142
+ ####
+ # #
+ # ####
+###$.$ #
+# .@. #
+# $.$###
+#### #
+ # #
+ ####
+
+; 143
+####
+# ####
+# $ #
+# .# #
+# $# ##
+# . #
+#### #
+ # #
+ ### ###
+ # $ #
+## #$# ##
+# $ @ $ #
+# ..#.. #
+### ###
+ #####
+
+; 144
+ ####
+ ### #####
+ # $$ # #
+ # $ . .$$##
+ # .. #. $ #
+### #** . #
+# . **# ###
+# $ .# .. #
+##$$.@. $ #
+ # # $$ #
+ ##### ###
+ ####
+
+; 145
+ #####
+ # @ #
+ ## ##
+###.$$$.###
+# $...$ #
+# $.#.$ #
+# $...$ #
+###.$$$.###
+ ## ##
+ # #
+ #####
+
+; 146
+ #######
+## . ##
+# .$$$. #
+# $. .$ #
+#.$ @ $.#
+# $. .$ #
+# .$$$. #
+## . ##
+ #######
+
+; 147 'reduction of (Mas Sasquatch 8)'
+ #####
+######## #
+#. . @#.#
+# ### #
+## $ # #
+ # $ #####
+ # $# #
+ ## # #
+ # ##
+ #####
+
+; 148 'from (Original 18)'
+###########
+# . # #
+# #. @ #
+# #..# #######
+## ## $$ $ $ #
+ ## #
+ #############
+
+; 149 'from (Boxxle 43)'
+ ####
+## ###
+#@$ #
+### $ #
+ # ######
+ # $....#
+ # # ####
+ ## # #
+ # $# #
+ # #
+ # ###
+ ####
+
+; 150 'from (Original 47)'
+ ####
+ ##### #
+ # $#######
+## ## ..# ...#
+# $ $$#$ @ #
+# ### #
+####### # ####
+ ####
+
+; 151 'from (Original 47)'
+ ####
+ # #
+ ### #
+## $ #
+# # #
+# #$$ ######
+# # # .#
+# $ @ .#
+### ####..#
+ #### ####
+
+; 152 'reduced (Mas Sasquatch 23)'
+###### ####
+# # #
+#.## #$## #
+# # # #
+#$ # ### # #
+# # # # #
+# # #### # # #
+#. @ $ * . #
+###############
+
+; 153 'reduction of (Revenge 306)'
+#############
+#.# @# # #
+#.#$$ # $ #
+#.# # $# #
+#.# $# # $##
+#.# # $# #
+#.# $# # $#
+#.. # $ #
+#.. # # #
+############
+
+; 154 'Take the long way home.'
+ ############################
+ # #
+ # ######################## #
+ # # # #
+ # # #################### # #
+ # # # # # #
+ # # # ################ # # #
+ # # # # # # # #
+ # # # # ############ # # # #
+ # # # # # # # # #
+ # # # # # ############ # # #
+ # # # # # # # #
+ # # # # ################ # #
+ # # # # # #
+##$# # #################### #
+#. @ # #
+#############################
+
+; 155 'The Dungeon'
+ ###### ####
+#####*# ################# ##
+# ### #
+# ######## #### ## #
+### #### # #### #### ##
+#*# # .# # # # # # #
+#*# # # # ## # ## ## #
+### ### ### # ## # ## ##
+ # # #*# # # # #
+ # # ### ##### #### # #
+ ##### ##### ####### ######
+ # # # #**# #
+## # # #**# ####### ## #
+# ######### # ##### ###
+# # # $ #*#
+# ######### ### @##### #*#
+##### #### #### ######
diff --git a/games/sokoban/src/icon.png b/games/sokoban/src/icon.png
new file mode 100644
index 00000000..aa0bd4e3
Binary files /dev/null and b/games/sokoban/src/icon.png differ
diff --git a/games/sokoban/src/main.c b/games/sokoban/src/main.c
new file mode 100644
index 00000000..cddd3023
--- /dev/null
+++ b/games/sokoban/src/main.c
@@ -0,0 +1,328 @@
+/* Sokoban: push every box onto a goal.
+ *
+ * Hiroyuki Imabayashi's warehouse puzzle (Thinking Rabbit, 1982), with David W. Skinner's Microban:
+ * 155 small levels, from the first push to The Dungeon. The keeper walks the floor and pushes the
+ * boxes one at a time, never pulling them; every step can be undone. A level opens while fewer
+ * than three levels are left unsolved before it, and the fewest moves each was solved in are kept.
+ *
+ * The levels are packed by tools/levels.py: only the floor, the goals, the boxes and the keeper (the
+ * walls are the cells around the floor), compressed with DEFLATE and unpacked into the strip buffer
+ * when a level opens. Only the rows a step changes are drawn again, in the launcher's strips
+ * (launcher/src/gfx.c). Inside NumPlay it uses the launcher's shapes, fonts, files and inflater; on
+ * its own it brings them along. */
+#include <eadk.h>
+#include "../../../launcher/src/gfx.h"
+#include "../../../launcher/src/inflate.h"
+#include "../../common/np_text.h"
+
+#if NP_MODULE /* (np_file_read and np_file_write: NumPlay's, launcher/src/np.h) */
+#define np_app_begin()
+#define np_app_end() 0
+#else
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#define np_file_read ef_read
+#define np_file_write ef_write
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Sokoban";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+void np_push(int x, int y, int w, int h, const color_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+#endif
+
+#include "levels.inc" /* levels_z, LEVELS (inside NumPlay, fewer: see the Makefile), ALL_LEVELS, TEXT_BYTES, MAXW, MAXH */
+
+/* the keys used, in 32 bits: those past the 32nd (4 5 6 2 EXE) come down by 22 */
+#define KEY(k) (1u << ((k) - ((k) >= 32) * 22))
+static uint32_t keys(void) {
+ uint64_t s = eadk_keyboard_scan();
+ return ((uint32_t)s & 0x800201FFu) | ((uint32_t)(s >> 32) & 0x00100870u) << 10;
+}
+#define HDR 22 /* the band on top */
+#define STEPS 4 /* frames a step slides over */
+#define HIST 1024
+#define F_FLOOR 1
+#define F_GOAL 2
+#define F_BOX 4
+#define F_WALL 8
+
+#define WHITE 0xFFFF
+#define BG HEX(0x2B2730) /* around the warehouse */
+#define BAR HEX(0x1C1A20)
+#define CREAM HEX(0xF2E6CF)
+#define GOLD HEX(0xF2B53C)
+#define GREEN HEX(0x5DAE45)
+
+/* sokoban.sav: the level played last, and the fewest moves each level was solved in (0: not yet), for
+ all of Microban whatever this build holds, so NumPlay and Sokoban.nwa share it */
+static struct {
+ uint8_t magic, version, flags, level; /* flags: 1 the keys were shown */
+ uint16_t best[ALL_LEVELS];
+} sv;
+#define SAVE_NAME "sokoban.sav"
+
+/* the level: a wall's width around its floor, MAXW cells a row (g has room for the neighbours of
+ the first and last cells) */
+static uint8_t g[MAXW * (MAXH + 2) + 2];
+#define G (g + MAXW + 1)
+static const int8_t off[4] = {-MAXW, 1, MAXW, -1}, ddx[4] = {0, 1, 0, -1}, ddy[4] = {-1, 0, 1, 0}; /* up, right... */
+static uint8_t hist[HIST]; /* the steps taken: the way, and 4 for a push */
+static color_t strip[SCREEN_W * STRIP_H];
+static int level, rows, size, ox, oy, keeper, face, left, moves, pushes, nh, anim, moved;
+static int scr, ov, sel, pick, top, dlo, dhi;
+enum { OV_NONE, OV_PAUSE, OV_QUIT, OV_HELP, OV_DONE };
+static char line[64], msg[48]; /* any text; what the Solved! panel says */
+
+static char *cat(char *o, const char *s) { /* s at o; returns its end */
+ while ((*o = *s++)) o++;
+ return o;
+}
+static char *put(char *o, const char *s, uint32_t v) { /* a text and a number at o; returns its end */
+ char t[10];
+ int n = 0;
+ o = cat(o, s);
+ do t[n++] = (char)('0' + v % 10); while (v /= 10);
+ while (n) *o++ = t[--n];
+ *o = 0;
+ return o;
+}
+static void save(void) {
+ sv.magic = 'S', sv.version = 1;
+ np_file_write(SAVE_NAME, &sv, sizeof sv);
+}
+static bool unlocked(int i) {
+ int n = 0;
+ for (int j = 0; j < LEVELS; j++) n += !sv.best[j];
+ return sv.best[i] || i < LEVELS - n + 3;
+}
+static void mark(int a, int b) { /* rows a to b to draw again */
+ if (a < dlo) dlo = a;
+ if (b > dhi) dhi = b;
+}
+static void mark_cell(int i) { mark(oy + (i / MAXW - 1) * size, oy + (i / MAXW + 2) * size); }
+
+/* ------------------------------------------------------------ the level */
+static void open_level(int n) {
+ uint32_t tables[816]; /* np_inflate's two Huffman tables, 2 x 1632 bytes */
+ const uint8_t *t = (const uint8_t *)strip;
+ np_inflate((uint8_t *)strip, TEXT_BYTES, levels_z, sizeof levels_z, (np_inflate_tables_t *)(void *)tables);
+ for (int k = n; k; t++)
+ if (t[0] == '\n' && t[1] == '\n') k--, t++;
+ for (unsigned i = 0; i < sizeof g; i++) g[i] = 0;
+ int x = 1, y = 1, w = 0;
+ for (left = 0; *t != '\n' || x > 1; t++) {
+ int c = *t, i = y * MAXW + x++;
+ if (c == '\n') y++, x = 1;
+ else if (c != ' ') {
+ for (int k = 0; k < 6; k++) /* floor, goal, box, box on a goal, the keeper, on a goal */
+ if (c == "-.$*@+"[k]) G[i] = (uint8_t)"\1\3\5\7\1\3"[k], keeper = k > 3 ? i : keeper;
+ left += c == '$';
+ }
+ if (x > w) w = x;
+ }
+ rows = y + 1;
+ for (int i = 0; i < rows * MAXW; i++) /* walls on every cell next to the floor */
+ for (int d = 0; d < 9; d++)
+ if (!(G[i] & F_FLOOR) && G[i + (d / 3 - 1) * MAXW + d % 3 - 1] & F_FLOOR) G[i] = F_WALL;
+ size = (SCREEN_W - 8) / (w + 1);
+ if ((SCREEN_H - HDR - 8) / rows < size) size = (SCREEN_H - HDR - 8) / rows;
+ if (size > 24) size = 24;
+ ox = (SCREEN_W - (w + 1) * size) / 2, oy = HDR + (SCREEN_H - HDR - rows * size) / 2;
+ level = sv.level = (uint8_t)n, moves = pushes = nh = anim = ov = 0, face = 2, scr = 1;
+ mark(0, SCREEN_H);
+ save();
+}
+
+/* a box from one cell to the next */
+static void shove(int from, int to) {
+ G[from] ^= F_BOX, G[to] |= F_BOX, left += !(G[to] & F_GOAL) - !(G[from] & F_GOAL);
+}
+/* the keeper steps one way, pushing a box if there is one and it can go; or a step back */
+static void step(int d) {
+ int o = off[d], to = keeper + o, b = to + o;
+ face = d, moved = -1;
+ mark_cell(keeper);
+ if (!(G[to] & F_FLOOR) || (G[to] & F_BOX && (!(G[b] & F_FLOOR) || G[b] & F_BOX))) return;
+ if (nh == HIST) { /* the oldest steps can't be undone any more */
+ for (int i = 0; i < HIST / 2; i++) hist[i] = hist[i + HIST / 2];
+ nh = HIST / 2;
+ }
+ hist[nh++] = (uint8_t)d;
+ if (G[to] & F_BOX) {
+ shove(to, b);
+ pushes++, hist[nh - 1] |= 4, moved = b;
+ }
+ moves++, keeper = to, anim = STEPS;
+}
+static void undo(void) {
+ int h = hist[--nh], o = off[h & 3];
+ if (h & 4) shove(keeper + o, keeper), pushes--;
+ mark_cell(keeper);
+ keeper -= o, face = h & 3, moves--;
+}
+
+/* ------------------------------------------------------------ drawing */
+static void box(int i, int dx, int dy) {
+ int s = size, x = ox + i % MAXW * s + dx, y = oy + i / MAXW * s + dy;
+ color_t dark = G[i] & F_GOAL ? HEX(0x3F7A2C) : HEX(0x8A5422);
+ gfx_rrect(x + 1, y + 1, s - 2, s - 2, s / 5, dark, 256);
+ gfx_rrect(x + 3, y + 3, s - 6, s - 6, s / 5 - 1, G[i] & F_GOAL ? GREEN : HEX(0xD6943E), 256);
+ gfx_fill(x + 3, y + s / 2 - 1, s - 6, 2, dark);
+}
+/* the panels in the middle (OV_PAUSE to OV_DONE): a title, a few lines, then the choices, the one
+ picked in gold */
+static const char *const panels[4][6] = {
+ {T("Paused"), T("Resume"), T("Restart"), T("Levels"), T("How to play"), T("Quit game")},
+ {T("Quit game?"), T("No"), T("Yes")},
+ {T("How to play"), T("Play")},
+ {T("Solved!"), T("Next level")},
+};
+static const uint8_t choices[4] = {5, 2, 1, 1}, lines[4] = {0, 0, 4, 1};
+static void overlay(void) {
+ int n = choices[ov - 1], h = 54 + 16 * lines[ov - 1] + 28 * n, y = (SCREEN_H - h) / 2;
+ gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 110);
+ gfx_rrect(40, y, 240, h, 12, BAR, 256);
+ gfx_text_center(&np_font_title, 160, y + 32, panels[ov - 1][0], GOLD, 256);
+ y = gfx_paragraph(&np_font_body, 160, y + 54, 224, 16, ov == OV_HELP ? T("Push every box onto a goal: one at a time, and never pulled.\nArrows: walk and push\nBackspace: undo Back: pause") : ov == OV_DONE ? msg : "", CREAM, 256) - 12;
+ for (int i = 0; i < n; i++, y += 28) {
+ if (sel == i) gfx_rrect(96, y, 128, 24, 12, GOLD, 256);
+ gfx_text_center(&np_font_body, 160, y + 17, panels[ov - 1][i + 1], sel == i ? BAR : CREAM, 256);
+ }
+}
+
+static void play_scene(void *ctx) {
+ int s = size, sh = s * anim / STEPS, ex = -ddx[face] * sh, ey = -ddy[face] * sh;
+ gfx_fill(0, gfx_y0, SCREEN_W, gfx_y1 - gfx_y0, BG);
+ for (int i = 0; i < rows * MAXW; i++) {
+ int x = ox + i % MAXW * s, y = oy + i / MAXW * s, f = G[i];
+ if (y >= gfx_y1 || y + s <= gfx_y0) continue;
+ if (f & F_WALL) {
+ gfx_fill(x, y, s, s, HEX(0x5B3A26));
+ gfx_fill(x, y, s - 1, s - 1, HEX(0xB57D55));
+ gfx_fill(x + 1, y + 1, s - 2, s - 2, HEX(0x8C5A3A));
+ } else if (f) {
+ gfx_fill(x, y, s, s, (i ^ i / MAXW) & 1 ? HEX(0xE4D7BC) : HEX(0xDCCDAF));
+ if (f & F_GOAL) gfx_circle(x + s / 2, y + s / 2, s / 5 + 1, HEX(0xD2452F), 256);
+ if (f & F_BOX && (!anim || i != moved)) box(i, 0, 0);
+ }
+ }
+ if (anim && moved >= 0) box(moved, ex, ey);
+ /* the keeper, looking the way he goes */
+ int cx = ox + keeper % MAXW * s + ex + s / 2, cy = oy + keeper / MAXW * s + ey + s / 2, r = s * 3 / 8;
+ int lx = ddx[face] * s / 8, ly = ddy[face] * s / 8;
+ gfx_circle(cx, cy, r, HEX(0x3C7BE8), 256);
+ for (int e = -s / 7; e <= s / 7; e += 2 * (s / 7)) {
+ gfx_circle(cx + e + lx, cy - s / 12 + ly, s / 8 + 1, WHITE, 256);
+ gfx_circle(cx + e + lx * 3 / 2, cy - s / 12 + ly * 3 / 2, s / 16 + 1, BAR, 256);
+ }
+ gfx_fill(0, 0, SCREEN_W, HDR, BAR);
+ put(line, T("Level "), (uint32_t)level + 1);
+ gfx_text(&np_font_body, 8, 16, line, GOLD, 256);
+ put(cat(put(line, T("Moves "), (uint32_t)moves), " "), T("Pushes "), (uint32_t)pushes);
+ gfx_text_right(&np_font_body, 312, 16, line, CREAM, 256);
+ if (ov) overlay();
+}
+
+/* the levels, ten a row, six rows on the screen at a time */
+static void hub_scene(void *ctx) {
+ char s[8];
+ int n = 0;
+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, BG);
+ gfx_fill(0, 0, SCREEN_W, 36, BAR);
+ gfx_text(&np_font_title, 12, 27, "SOKOBAN", GOLD, 256);
+ for (int i = 0; i < LEVELS; i++) {
+ int x = 12 + 30 * (i % 10), y = 46 + 27 * (i / 10 - top);
+ n += sv.best[i] != 0;
+ if (y < 40 || y > 190) continue;
+ gfx_rrect(x, y, 26, 22, 6, sv.best[i] ? GREEN : unlocked(i) ? CREAM : HEX(0x57505E), 256);
+ if (i == pick) gfx_rrect_outline(x - 3, y - 3, 32, 28, 8, 2, GOLD, 256);
+ put(s, "", (uint32_t)i + 1);
+ gfx_text_center(&np_font_small, x + 13, y + 15, s, sv.best[i] ? WHITE : BG, 256);
+ }
+ put(cat(put(line, "", (uint32_t)n), " / "), "", LEVELS);
+ gfx_text_right(&np_font_body, 308, 24, line, CREAM, 256);
+ gfx_fill(0, 214, SCREEN_W, 26, BAR);
+ put(line, T("Solved in moves: "), sv.best[pick]);
+ if (sv.best[pick]) gfx_text_center(&np_font_body, 160, 232, line, CREAM, 256);
+ if (ov) overlay();
+}
+
+int main(void) {
+ np_app_begin();
+ color_t *their_strip = gfx_buf;
+ gfx_buf = strip;
+ uint32_t len = 0;
+ const uint8_t *d = np_file_read(SAVE_NAME, &len);
+ for (uint32_t i = 0; d && len == sizeof sv && d[0] == 'S' && d[1] == 1 && i < len; i++) ((uint8_t *)&sv)[i] = d[i];
+ if (sv.level >= LEVELS) sv.level = 0;
+ pick = sv.level, top = pick / 10 > 3 ? pick / 10 - 3 : 0;
+ if (!(sv.flags & 1)) ov = OV_HELP;
+ static const uint32_t ways[5] = {KEY(eadk_key_up) | KEY(eadk_key_eight), KEY(eadk_key_right) | KEY(eadk_key_six),
+ KEY(eadk_key_down) | KEY(eadk_key_two), KEY(eadk_key_left) | KEY(eadk_key_four),
+ KEY(eadk_key_backspace)};
+ const uint32_t ok = KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_five), back = KEY(eadk_key_back);
+ uint32_t held = keys(), stale = held; /* keys still down from the launcher wait to be let go */
+ uint32_t again = 0;
+ mark(0, SCREEN_H);
+ for (int quit = 0; !quit;) {
+ uint32_t now = (uint32_t)eadk_timing_millis();
+ uint32_t k = keys(), hit = k & ~held;
+ stale &= k, held = k, k &= ~stale;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;
+ int way = -1, tap = -1; /* the way held, and pressed just now (0 up, 1 right, 2 down, 3 left, 4 undo) */
+ for (int i = 0; i < 5; i++) {
+ if (k & ways[i]) way = i;
+ if (hit & ways[i]) tap = i;
+ }
+ if (hit && (ov || !scr)) mark(0, SCREEN_H);
+ if (ov) {
+ int n = choices[ov - 1], c = hit & ok ? sel : hit & back ? -1 : -2;
+ if (tap == 0 || tap == 2) sel = (sel + tap - 1 + n) % n;
+ if (c > -2) {
+ int was = ov;
+ ov = OV_NONE, sel = 0, sv.flags |= 1;
+ if (was == OV_PAUSE && c == 1) open_level(level);
+ if (was == OV_PAUSE && c == 2) scr = 0, pick = level;
+ if (was == OV_PAUSE && c > 2) ov = c == 3 ? OV_HELP : OV_QUIT;
+ if (was == OV_QUIT) c == 1 ? quit = 1 : scr ? (ov = OV_PAUSE, sel = 4) : 0;
+ if (was == OV_DONE) c == 0 && level + 1 < LEVELS ? open_level(level + 1) : (void)(scr = 0, pick = level);
+ }
+ } else if (!scr) {
+ if (tap >= 0 && tap < 4) pick += tap & 1 ? 2 - tap : 10 * (tap - 1);
+ pick = pick < 0 ? 0 : pick >= LEVELS ? LEVELS - 1 : pick;
+ top = pick / 10 < top ? pick / 10 : pick / 10 > top + 5 ? pick / 10 - 5 : top;
+ if (hit & ok && unlocked(pick)) open_level(pick);
+ if (hit & back) ov = OV_QUIT;
+ } else if (hit & back) {
+ ov = OV_PAUSE, sel = 0;
+ mark(0, SCREEN_H);
+ } else if (!anim && way >= 0 && (tap >= 0 || (int32_t)(now - again) >= 0)) { /* held, it goes on */
+ if (way < 4) step(way);
+ else if (nh) undo();
+ again = now + (tap >= 0 ? 240 : 100);
+ }
+ if (anim) {
+ anim--;
+ if (moved >= 0) mark_cell(moved);
+ mark_cell(keeper);
+ mark(0, HDR);
+ if (!anim && !left) { /* solved */
+ if (!sv.best[level] || moves < sv.best[level]) sv.best[level] = (uint16_t)moves;
+ put(cat(put(msg, T("Moves "), (uint32_t)moves), " "), T("Your best: "), sv.best[level]);
+ ov = OV_DONE;
+ save();
+ mark(0, SCREEN_H);
+ }
+ }
+ if (dlo < dhi) {
+ eadk_display_wait_for_vblank();
+ gfx_render(scr ? play_scene : hub_scene, 0, dlo < 0 ? 0 : dlo, dhi > SCREEN_H ? SCREEN_H : dhi);
+ dlo = SCREEN_H, dhi = 0;
+ } else {
+ eadk_timing_msleep(8);
+ }
+ }
+ save();
+ gfx_buf = their_strip;
+ return np_app_end();
+}
diff --git a/games/sokoban/tests/play.c b/games/sokoban/tests/play.c
new file mode 100644
index 00000000..8728df5a
--- /dev/null
+++ b/games/sokoban/tests/play.c
@@ -0,0 +1,141 @@
+/* Sokoban on a computer, for tests and pictures (make host, make test).
+ *
+ * play solve FILE every level played through with its moves (tests/solutions.txt, from
+ * tools/solve.py): each step must go, each push push, the level must end
+ * solved; then every step is undone, back to the level as it started
+ * play shot L OUT [MOVES] a picture of level L (from 1) after these moves (u r d l), with the
+ * keeper half way through the last one
+ * play hub OUT [SOLVED] a picture of the level select, the first SOLVED levels solved
+ */
+#define main sk_main
+#include "../src/main.c"
+#undef main
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.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; }
+uint64_t eadk_keyboard_scan(void) { return 0; }
+uint64_t eadk_timing_millis(void) { return 0; }
+void eadk_timing_msleep(uint32_t ms) { (void)ms; }
+uint32_t eadk_random(void) { return 0x9E3779B9u; }
+void *np_alloc(uint32_t size) { return malloc(size); }
+
+static void picture(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) exit(2);
+ fprintf(f, "P6 320 240 255\n");
+ for (int y = 0; y < SCREEN_H; y++)
+ for (int x = 0; x < SCREEN_W; x++) {
+ uint16_t c = fb[y][x];
+ fputc((c >> 11) * 255 / 31, f), fputc((c >> 5 & 63) * 255 / 63, f), fputc((c & 31) * 255 / 31, f);
+ }
+ fclose(f);
+}
+
+static int way(char c) {
+ const char *p = strchr("urdl", c | 0x20);
+ return p ? (int)(p - "urdl") : -1;
+}
+
+static int solve(const char *file) {
+ static char text[1 << 18];
+ FILE *f = fopen(file, "r");
+ size_t n = f ? fread(text, 1, sizeof text - 1, f) : 0;
+ if (f) fclose(f);
+ text[n] = 0;
+ int done = 0, bad = 0;
+ for (char *line = strtok(text, "\n"); line; line = strtok(0, "\n")) {
+ int l, at;
+ if (line[0] == '#' || sscanf(line, "%d:%n", &l, &at) < 1) continue;
+ open_level(l - 1);
+ uint8_t start[sizeof g];
+ memcpy(start, g, sizeof g);
+ int boxes = 0, goals = 0, start_left = left, start_keeper = keeper, problem = 0;
+ for (int i = 0; i < rows * MAXW; i++) boxes += !!(G[i] & F_BOX), goals += !!(G[i] & F_GOAL);
+ if (boxes != goals || !boxes || !left || !(G[keeper] & F_FLOOR) || G[keeper] & F_BOX) problem = 1;
+ for (const char *p = line + at; *p && !problem; p++) {
+ int d = way(*p), m = moves, q = pushes;
+ if (d < 0) continue;
+ step(d);
+ anim = 0;
+ if (moves != m + 1 || pushes != q + (*p < 'a')) problem = 2;
+ }
+ if (!problem && left) problem = 3;
+ if (!problem && moves != nh) problem = 4;
+ while (!problem && nh) undo();
+ if (!problem && (memcmp(start, g, sizeof g) || left != start_left || keeper != start_keeper || moves || pushes))
+ problem = 5;
+ if (problem) {
+ printf("level %d: %s\n", l,
+ (const char *[]){"", "not a level", "a step didn't go", "not solved", "steps lost", "undo"}[problem]);
+ bad++;
+ }
+ done++;
+ }
+ printf("%d levels played, %d solved and undone%s\n", done, done - bad, done == LEVELS ? "" : ": some are missing");
+ return bad || done != LEVELS;
+}
+
+int main(int argc, char **argv) {
+ gfx_buf = strip;
+ if (argc >= 3 && !strcmp(argv[1], "solve")) return solve(argv[2]);
+ if (argc >= 4 && !strcmp(argv[1], "shot")) {
+ open_level(atoi(argv[2]) - 1);
+ const char *m = argc > 4 ? argv[4] : "";
+ for (const char *p = m; *p; p++)
+ if (way(*p) >= 0) step(way(*p)), anim = p[1] ? 0 : STEPS / 2;
+ if (argc > 5) { /* and a panel on top: 1 paused, 2 quit, 3 how to play, 4 solved */
+ ov = atoi(argv[5]);
+ if (ov == OV_DONE) put(cat(put(msg, T("Moves "), (uint32_t)moves), " "), T("Your best: "), (uint32_t)moves);
+ }
+ gfx_render(play_scene, 0, 0, SCREEN_H);
+ picture(argv[3]);
+ return 0;
+ }
+ if (argc >= 5 && !strcmp(argv[1], "film")) { /* film L DIR MOVES: two pictures a step, then Solved! */
+ char path[256];
+ int n = 0;
+ open_level(atoi(argv[2]) - 1);
+ gfx_render(play_scene, 0, 0, SCREEN_H);
+ snprintf(path, sizeof path, "%s/f_%04d.ppm", argv[3], n++);
+ picture(path);
+ for (const char *p = argv[4]; *p; p++) {
+ if (way(*p) < 0) continue;
+ step(way(*p));
+ for (int a = STEPS / 2; a >= 0; a -= STEPS / 2) {
+ anim = a;
+ gfx_render(play_scene, 0, 0, SCREEN_H);
+ snprintf(path, sizeof path, "%s/f_%04d.ppm", argv[3], n++);
+ picture(path);
+ }
+ }
+ if (!left) {
+ put(cat(put(msg, T("Moves "), (uint32_t)moves), " "), T("Your best: "), (uint32_t)moves);
+ ov = OV_DONE;
+ gfx_render(play_scene, 0, 0, SCREEN_H);
+ snprintf(path, sizeof path, "%s/f_%04d.ppm", argv[3], n++);
+ picture(path);
+ }
+ printf("%d\n", n);
+ return 0;
+ }
+ if (argc >= 3 && !strcmp(argv[1], "hub")) {
+ for (int i = 0; i < (argc > 3 ? atoi(argv[3]) : 0); i++) sv.best[i] = (uint16_t)(20 + i);
+ pick = argc > 3 && atoi(argv[3]) > 0 ? atoi(argv[3]) - 1 : 0;
+ gfx_render(hub_scene, 0, 0, SCREEN_H);
+ picture(argv[2]);
+ return 0;
+ }
+ fprintf(stderr, "play solve FILE | shot L OUT [MOVES] | hub OUT [SOLVED]\n");
+ return 2;
+}
diff --git a/games/sokoban/tools/fetch.py b/games/sokoban/tools/fetch.py
new file mode 100644
index 00000000..4dc70c77
--- /dev/null
+++ b/games/sokoban/tools/fetch.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Writes levels/microban.txt: David W. Skinner's Microban (155 levels), in the usual Sokoban text
+format, from the copy on Scott Lindhurst's Sokoban levels page. Run once; the file is kept in the
+repository, so building needs no network.
+
+ # wall @ the keeper $ a box . a goal
+ floor + keeper on goal * box on goal
+
+Usage: fetch.py [levels/microban.txt]
+"""
+import html
+import os
+import re
+import sys
+import urllib.request
+
+URL = "http://www.sneezingtiger.com/sokoban/levels/microbanText.html"
+
+page = urllib.request.urlopen(URL, timeout=30).read().decode("latin-1")
+pre = page[page.index('<pre class="sokFont">') + len('<pre class="sokFont">'):]
+pre = html.unescape(pre[:pre.index("</pre>")])
+out = ["; Microban, by David W. Skinner (2000): 155 levels, from his Sokoban page",
+ "; (users.bentonrea.com/~sasquatch/sokoban), here as kept at " + URL, ""]
+n = 0
+for block in re.split(r"\n\s*\n", pre.strip()):
+ lines = block.split("\n")
+ assert lines[0].startswith("Level ")
+ n += 1
+ out.append(f"; {n}" + "".join(f" {l.strip()}" for l in lines[1:] if l.startswith("'")))
+ out += [l.rstrip() for l in lines[1:] if l.strip() and not l.startswith("'")]
+ out.append("")
+assert n == 155
+path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "..", "levels", "microban.txt")
+os.makedirs(os.path.dirname(path), exist_ok=True)
+open(path, "w").write("\n".join(out))
+print(f"{path}: {n} levels")
diff --git a/games/sokoban/tools/icon.py b/games/sokoban/tools/icon.py
new file mode 100644
index 00000000..30f52fb2
--- /dev/null
+++ b/games/sokoban/tools/icon.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Draws src/icon.png (55 x 56): the keeper pushing a crate onto a goal, between brick walls, in the
+game's colours. Drawn 8 times bigger, then scaled down.
+
+Usage: icon.py [src/icon.png]
+"""
+import os
+import sys
+
+from PIL import Image, ImageDraw
+
+K = 8
+W, H = 55 * K, 56 * K
+im = Image.new("RGBA", (W, H), (0, 0, 0, 0))
+d = ImageDraw.Draw(im)
+cell = 13 * K
+x0, y0 = (W - 4 * cell) // 2, (H - 4 * cell) // 2
+
+
+def rgb(v):
+ return (v >> 16, v >> 8 & 255, v & 255, 255)
+
+
+# the floor, a checkerboard, inside a rounded tile of walls
+d.rounded_rectangle((0, 0, W - 1, H - 1), radius=12 * K, fill=rgb(0x8C5A3A))
+for r in range(4):
+ for c in range(4):
+ x, y = x0 + c * cell, y0 + r * cell
+ if r in (0, 3) or c in (0, 3): # bricks around
+ d.rectangle((x, y, x + cell - 1, y + cell - 1), fill=rgb(0x5B3A26))
+ d.rectangle((x, y, x + cell - K - 1, y + cell - K - 1), fill=rgb(0xB57D55))
+ d.rectangle((x + K, y + K, x + cell - K - 1, y + cell - K - 1), fill=rgb(0x8C5A3A))
+ else:
+ d.rectangle((x, y, x + cell - 1, y + cell - 1), fill=rgb(0xE4D7BC if (r ^ c) & 1 else 0xDCCDAF))
+# a crate pushed onto its goal, the keeper behind it looking at it; below, a crate and a goal to go
+def crate(x, y, dark, face):
+ d.rounded_rectangle((x + K, y + K, x + cell - K, y + cell - K), radius=3 * K, fill=rgb(dark))
+ d.rounded_rectangle((x + 3 * K, y + 3 * K, x + cell - 3 * K, y + cell - 3 * K), radius=2 * K, fill=rgb(face))
+ d.rectangle((x + 3 * K, y + cell // 2 - K, x + cell - 3 * K, y + cell // 2 + K), fill=rgb(dark))
+
+
+crate(x0 + 2 * cell, y0 + cell, 0x3F7A2C, 0x5DAE45)
+crate(x0 + cell, y0 + 2 * cell, 0x8A5422, 0xD6943E)
+gx, gy = x0 + 2 * cell + cell // 2, y0 + 2 * cell + cell // 2
+d.ellipse((gx - 3 * K, gy - 3 * K, gx + 3 * K, gy + 3 * K), fill=rgb(0xD2452F))
+x, y = x0 + cell, y0 + cell
+cx, cy, rr = x + cell // 2, y + cell // 2, cell * 3 // 8
+d.ellipse((cx - rr, cy - rr + K, cx + rr, cy + rr + K), fill=rgb(0x1D3F8A))
+d.ellipse((cx - rr, cy - rr, cx + rr, cy + rr), fill=rgb(0x3C7BE8))
+for e in (-1, 1):
+ ex, ey = cx + e * cell // 7 + 2 * K, cy - cell // 12
+ d.ellipse((ex - 2 * K, ey - 2 * K, ex + 2 * K, ey + 2 * K), fill=(255, 255, 255, 255))
+ d.ellipse((ex, ey - K, ex + 2 * K, ey + K), fill=rgb(0x1C1A20))
+out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "..", "src", "icon.png")
+im.resize((55, 56), Image.LANCZOS).save(out)
diff --git a/games/sokoban/tools/levels.py b/games/sokoban/tools/levels.py
new file mode 100644
index 00000000..df39f707
--- /dev/null
+++ b/games/sokoban/tools/levels.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+"""Packs levels/microban.txt into output/levels.inc for the game.
+
+Only what the keeper can reach is kept: the floor ('-'), the goals, the boxes and the keeper, in
+the usual letters (. $ * @ +); everything else is a space. The walls are not stored: the game puts
+one on every cell next to the floor, which is where they are (decorations that touch no floor
+are left out). Rows end with a newline and a level with an empty line. The text is compressed with
+raw DEFLATE (zopfli when it is there); the game inflates it when it opens a level.
+
+ python3 tools/levels.py OUTDIR [LEVELS] (the first LEVELS levels; all of them by default)
+
+Each level is checked as it is packed: one keeper, as many goals as boxes, the floor walled in and
+small enough for the game's grid (tools/solve.py solves them all).
+"""
+import os
+import sys
+import zlib
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+SOURCE = os.path.join(HERE, "..", "levels", "microban.txt")
+MAXW, MAXH = 32, 18 # with the walls around: what the game's grid holds
+
+
+def read(path=SOURCE):
+ levels, rows = [], []
+ for line in open(path).read().split("\n") + [""]:
+ if line.startswith(";"):
+ continue
+ if line.strip():
+ rows.append(line.rstrip())
+ elif rows:
+ levels.append(rows)
+ rows = []
+ return levels
+
+
+def reach(rows):
+ """The cells the keeper can reach, boxes or not, from the keeper."""
+ h, w = len(rows), max(map(len, rows))
+ g = [r.ljust(w) for r in rows]
+ start = [(y, x) for y in range(h) for x in range(w) if g[y][x] in "@+"]
+ assert len(start) == 1, "one keeper"
+ seen, todo = {start[0]}, [start[0]]
+ while todo:
+ y, x = todo.pop()
+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ n = (y + dy, x + dx)
+ if 0 <= n[0] < h and 0 <= n[1] < w and g[n[0]][n[1]] != "#" and n not in seen:
+ assert 0 < n[0] < h - 1 and 0 < n[1] < w - 1, "the floor is walled in"
+ seen.add(n)
+ todo.append(n)
+ return g, seen
+
+
+def pack(rows):
+ g, inside = reach(rows)
+ ys = [y for y, _ in inside]
+ xs = [x for _, x in inside]
+ out = []
+ for y in range(min(ys), max(ys) + 1):
+ r = "".join(("-" if g[y][x] == " " else g[y][x]) if (y, x) in inside else " "
+ for x in range(min(xs), max(xs) + 1))
+ out.append(r.rstrip())
+ text = "".join(out)
+ assert text.count("$") + text.count("*") == text.count(".") + text.count("+") + text.count("*") > 0
+ assert text.count("$") > 0, "something to push"
+ assert max(map(len, out)) + 2 <= MAXW and len(out) + 2 <= MAXH, "fits the grid"
+ return out
+
+
+def deflate(data):
+ try:
+ import zopfli.zlib
+ return zopfli.zlib.compress(data, numiterations=100)[2:-4]
+ except ImportError:
+ c = zlib.compressobj(9, zlib.DEFLATED, -15, 9)
+ return c.compress(data) + c.flush()
+
+
+def main():
+ outdir = sys.argv[1]
+ levels = [pack(r) for r in read()]
+ every = len(levels)
+ if len(sys.argv) > 2:
+ levels = levels[:int(sys.argv[2])]
+ text = "".join("\n".join(r) + "\n\n" for r in levels).encode()
+ z = deflate(text)
+ lines = ["/* Generated by tools/levels.py from levels/microban.txt. */",
+ f"#define LEVELS {len(levels)}", f"#define ALL_LEVELS {every}", f"#define TEXT_BYTES {len(text)}",
+ f"#define MAXW {MAXW} /* the grid, walls around included */", f"#define MAXH {MAXH}",
+ f"static const uint8_t levels_z[{len(z)}] = {{"]
+ for i in range(0, len(z), 24):
+ lines.append(" " + ",".join(str(b) for b in z[i:i + 24]) + ",")
+ lines.append("};")
+ os.makedirs(outdir, exist_ok=True)
+ open(os.path.join(outdir, "levels.inc"), "w").write("\n".join(lines) + "\n")
+ print(f"levels: {len(levels)}, {len(text)} bytes of text, {len(z)} packed")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/sokoban/tools/media.py b/games/sokoban/tools/media.py
new file mode 100644
index 00000000..16704449
--- /dev/null
+++ b/games/sokoban/tools/media.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""The pictures of the README and How to play, from the host build (make host; make media):
+
+ docs/shot.png, docs/levels.png a level, and the level select (shot.png is NumPlay's card too)
+ ../../docs/media/sokoban.gif levels 2 and 4 solved, for How to play
+ ../../docs/media/gallery/sokoban.gif level 9, for the README's gallery
+ ../../docs/media/thumb_sokoban.png the README's table
+
+The moves come from tests/solutions.txt. Python 3 with Pillow.
+"""
+import os
+import subprocess
+import tempfile
+
+from PIL import Image
+
+HERE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
+PLAY = os.path.join(HERE, "build", "play")
+MEDIA = os.path.join(HERE, "..", "..", "docs", "media")
+
+
+def solution(level):
+ for line in open(os.path.join(HERE, "tests", "solutions.txt")):
+ if line.startswith(f"{level}:"):
+ return line.split(":", 1)[1].strip()
+ raise SystemExit(f"no solution for level {level}")
+
+
+def film(level):
+ with tempfile.TemporaryDirectory() as d:
+ subprocess.run([PLAY, "film", str(level), d, solution(level)], check=True, capture_output=True)
+ return [Image.open(os.path.join(d, f)).convert("RGB") for f in sorted(os.listdir(d))]
+
+
+def gif(path, clips):
+ """Clips of frames, each shown 50 ms; a clip's first frame and last (Solved!) are held."""
+ frames, times = [], []
+ for c in clips:
+ for i, f in enumerate(c):
+ frames.append(f)
+ times.append(700 if i == 0 else 1600 if i == len(c) - 1 else 50)
+ sheet = Image.new("RGB", (320, 240 * len(frames[::8])))
+ for i, f in enumerate(frames[::8]):
+ sheet.paste(f, (0, 240 * i))
+ pal = sheet.quantize(64, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
+ out = [f.quantize(palette=pal, dither=Image.Dither.NONE) for f in frames]
+ out[0].save(path, save_all=True, append_images=out[1:], duration=times, loop=0, optimize=True, disposal=1)
+ print(f"{path}: {len(out)} frames, {os.path.getsize(path)} bytes")
+
+
+def main():
+ for args, name in (([PLAY, "shot", "2", "build/shot.ppm"], "shot.png"), ([PLAY, "hub", "build/hub.ppm", "17"], "levels.png")):
+ subprocess.run(args, check=True, cwd=HERE)
+ Image.open(os.path.join(HERE, args[-1] if name == "shot.png" else args[2])).convert("RGB").save(
+ os.path.join(HERE, "docs", name), optimize=True)
+ gif(os.path.join(MEDIA, "sokoban.gif"), [film(2), film(4)])
+ nine = film(9)
+ gif(os.path.join(MEDIA, "gallery", "sokoban.gif"), [nine])
+ thumb = os.path.join(MEDIA, "thumb_sokoban.png")
+ nine[len(nine) // 2].crop((40, 30, 280, 210)).resize((160, 120), Image.LANCZOS).save(thumb, optimize=True)
+ subprocess.run(["python3", os.path.join(HERE, "..", "..", "tools", "media", "round_corners.py"), thumb], check=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/sokoban/tools/solve.py b/games/sokoban/tools/solve.py
new file mode 100644
index 00000000..d1cc6263
--- /dev/null
+++ b/games/sokoban/tools/solve.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Solves every level as the game gets it (tools/levels.py) and writes tests/solutions.txt: a line a
+level, its moves in the usual letters (u r d l to walk, U R D L to push), for the host test (make test),
+which plays each one through the game's own rules.
+
+The search goes a push at a time, the most promising first: how many pushes the boxes need at least,
+each to a goal of its own (an assignment of the boxes to the goals), plus a little for the pushes made.
+Squares a box could never get from to a goal, and boxes frozen together (four cells in a square, all
+boxes or walls, one box off its goal), are left out. The solutions aren't the shortest; they only show
+every level can be solved as packed.
+
+Usage: solve.py [tests/solutions.txt]
+"""
+import heapq
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import levels # noqa: E402
+
+WAYS = ((-1, 0, "u"), (0, 1, "r"), (1, 0, "d"), (0, -1, "l"))
+BIG = 1 << 20
+
+
+def assignment(cost):
+ """The cheapest way to give each row a column of its own (the Hungarian method)."""
+ n = len(cost)
+ u, v, p, way = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1), [0] * (n + 1)
+ for i in range(1, n + 1):
+ p[0], j0 = i, 0
+ minv, used = [BIG * BIG] * (n + 1), [False] * (n + 1)
+ while True:
+ used[j0] = True
+ i0, delta, j1 = p[j0], BIG * BIG, 0
+ for j in range(1, n + 1):
+ if not used[j]:
+ c = cost[i0 - 1][j - 1] - u[i0] - v[j]
+ if c < minv[j]:
+ minv[j], way[j] = c, j0
+ if minv[j] < delta:
+ delta, j1 = minv[j], j
+ for j in range(n + 1):
+ if used[j]:
+ u[p[j]] += delta
+ v[j] -= delta
+ else:
+ minv[j] -= delta
+ j0 = j1
+ if not p[j0]:
+ break
+ while j0:
+ j1 = way[j0]
+ p[j0] = p[j1]
+ j0 = j1
+ return -v[0]
+
+
+def solve(rows, limit=3000000):
+ cells = {(y, x) for y, r in enumerate(rows) for x, c in enumerate(r) if c != " "}
+ at = {(y, x): c for y, r in enumerate(rows) for x, c in enumerate(r)}
+ goals = sorted(p for p in cells if at[p] in ".*+")
+ goal_set = frozenset(goals)
+ boxes = frozenset(p for p in cells if at[p] in "$*")
+ keeper = next(p for p in cells if at[p] in "@+")
+
+ # the pushes from each square to each goal, the box pulled back from the goal
+ dist = {}
+ for gi, g in enumerate(goals):
+ d, todo = {g: 0}, [g]
+ while todo:
+ nxt = []
+ for p in todo:
+ for dy, dx, _ in WAYS:
+ q, k = (p[0] + dy, p[1] + dx), (p[0] + 2 * dy, p[1] + 2 * dx)
+ if q in cells and k in cells and q not in d:
+ d[q] = d[p] + 1
+ nxt.append(q)
+ todo = nxt
+ for p, n in d.items():
+ dist.setdefault(p, [BIG] * len(goals))[gi] = n
+
+ def area(k, bx):
+ seen, todo = {k}, [k]
+ while todo:
+ y, x = todo.pop()
+ for dy, dx, _ in WAYS:
+ n = (y + dy, x + dx)
+ if n in cells and n not in bx and n not in seen:
+ seen.add(n)
+ todo.append(n)
+ return seen
+
+ def frozen(b, bx):
+ """A square of four cells around b, all walls or boxes, with a box off its goal."""
+ for oy in (-1, 0):
+ for ox in (-1, 0):
+ sq = [(b[0] + oy + a, b[1] + ox + c) for a in (0, 1) for c in (0, 1)]
+ if all(q not in cells or q in bx for q in sq) and any(q in bx and q not in goal_set for q in sq):
+ return True
+ return False
+
+ def guess(bx):
+ return assignment([dist[b] for b in bx])
+
+ first = area(keeper, boxes)
+ start = (boxes, min(first))
+ parent = {start: None}
+ heap = [(guess(boxes), 0, 0, start, first)]
+ tie = 0
+ while heap and len(parent) < limit:
+ _, c, _, key, ar = heapq.heappop(heap)
+ bx = key[0]
+ if bx <= goal_set:
+ return moves(key, parent, keeper, boxes, cells)
+ for b in bx:
+ for dy, dx, _ in WAYS:
+ frm, to = (b[0] - dy, b[1] - dx), (b[0] + dy, b[1] + dx)
+ if frm in ar and to in cells and to not in bx and to in dist:
+ nb = (bx - {b}) | {to}
+ if frozen(to, nb):
+ continue
+ na = area(b, nb)
+ nk = (nb, min(na))
+ if nk in parent:
+ continue
+ h = guess(nb)
+ if h >= BIG:
+ continue
+ parent[nk] = (key, b, (dy, dx))
+ tie += 1
+ heapq.heappush(heap, (3 * h + c + 1, c + 1, tie, nk, na))
+ return None
+
+
+def walk(frm, to, bx, cells):
+ """The keeper's way from frm to to around the boxes, in letters."""
+ prev, todo = {frm: None}, [frm]
+ while todo:
+ nxt = []
+ for p in todo:
+ if p == to:
+ out = []
+ while prev[p]:
+ p, ch = prev[p]
+ out.append(ch)
+ return "".join(reversed(out))
+ for dy, dx, ch in WAYS:
+ n = (p[0] + dy, p[1] + dx)
+ if n in cells and n not in bx and n not in prev:
+ prev[n] = (p, ch)
+ nxt.append(n)
+ todo = nxt
+ raise AssertionError("no way")
+
+
+def moves(key, parent, keeper, boxes, cells):
+ pushes = []
+ while parent[key]:
+ key, b, d = parent[key]
+ pushes.append((b, d))
+ out, k, bx = "", keeper, set(boxes)
+ for b, (dy, dx) in reversed(pushes):
+ out += walk(k, (b[0] - dy, b[1] - dx), bx, cells)
+ out += next(ch for y, x, ch in WAYS if (y, x) == (dy, dx)).upper()
+ bx.remove(b)
+ bx.add((b[0] + dy, b[1] + dx))
+ k = b
+ return out
+
+
+def main():
+ path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "..", "tests", "solutions.txt")
+ only = [int(a) for a in sys.argv[2:]]
+ lines = ["# tools/solve.py: each level's moves (u r d l walk, U R D L push), for tests/play.c"]
+ for i, rows in enumerate([levels.pack(r) for r in levels.read()], 1):
+ if only and i not in only:
+ continue
+ s = solve(rows)
+ assert s, f"level {i} not solved"
+ print(f"level {i}: {len(s)} moves, {sum(ch.isupper() for ch in s)} pushes", flush=True)
+ lines.append(f"{i}: {s}")
+ open(path, "w").write("\n".join(lines) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txt
index c6e9451f..d9f3b6d2 100644
--- a/launcher/lang/fr.txt
+++ b/launcher/lang/fr.txt
@@ -120,3 +120,7 @@ Based on Space Invaders by Taito D'après Space Invaders de Taito
# a game the RAM of the calculator's software is too small for
Needs Il manque
KB more memory Ko de mémoire
+
+Sokoban Sokoban
+Push every box home Pousse chaque caisse à sa place
+Levels: Microban by David W. Skinner Niveaux : Microban de David W. Skinner
\ No newline at end of file
diff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txt
index 68da149e..98951e8b 100644
--- a/launcher/lang/zh.txt
+++ b/launcher/lang/zh.txt
@@ -119,3 +119,7 @@ Based on Space Invaders by Taito 改编自 Taito 的 Space Invaders
# a game the RAM of the calculator's software is too small for
Needs 内存还差
KB more memory KB
+
+Sokoban 推箱子
+Push every box home 把每个箱子推到位
+Levels: Microban by David W. Skinner 关卡:David W. Skinner 的 Microban
\ No newline at end of file
diff --git a/tests/test_games.py b/tests/test_games.py
index abca373c..7c3316ef 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -126,6 +126,9 @@ GAMES = {
# next time the game goes on: X, sent to the top left board, takes its top right (9)
"uttt": ("UltimateTicTacToe.nwa", "uttt.sav", presses((1500, "ok"), (2000, "5"), (2300, "5"), (2700, "7")), 4000,
presses((1500, "9")), 3000),
+ # past how to play, the first level and a few steps; next time the second level, picked in the list
+ "sokoban": ("Sokoban.nwa", "sokoban.sav", presses((1500, "ok"), (2000, "ok"), (2600, "right"), (2900, "right")), 4000,
+ presses((1500, "right"), (1900, "ok"), (2500, "up")), 4000),
# the intro film is skipped (seen), Lucky walks up the dock and talks to the
# guardians; next time the game starts where it was left
"championisland": ("ChampionIsland.nwa", "champion.sav",
@@ -314,6 +317,8 @@ CHECKS = {
# how to play read, the game's moves (at 32) kept: 40 then 36; then 2 more
"uttt": (lambda v: len(v) == 114 and v[:2] == b"U\1" and v[4] & 1 and v[5] == 2 and v[32:34] == bytes([40, 36]),
lambda v: v[5] == 3 and v[34] == 2),
+ # how to play seen and the first level played last; then the second
+ "sokoban": (lambda v: len(v) == 314 and v[:4] == b"S\1\1\0", lambda v: len(v) == 314 and v[:4] == b"S\1\1\1"),
"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,
lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off
# Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies kept