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.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
A kit to make NumWorks games: setup on any computer, a template, a guide
Mason363caec5fe7d9c6
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 00000000..27973472--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,90 @@+# Contributing to NumPlay++Thanks for wanting to help! Bug reports, game ideas, fixes, translations and whole games are all welcome. This page says how, from setting up your computer to opening a pull request.++**Just want to make your own NumWorks game?** Read [Make your own NumWorks game](docs/make-a-game.md): it starts from NumPlay's template and doesn't need any of the rules below.++## Before you start++- **Found a bug?** [Open a bug report](https://github.com/Mason363/NumPlay/issues/new/choose) with your calculator's model and software (Settings, then About), the NumPlay version and what happened.+- **Want a game?** Check the [roadmap](README.md#roadmap) first, then [ask for it](https://github.com/Mason363/NumPlay/issues/new/choose), one game per issue.+- **Want to make a game for NumPlay?** Open an issue first and say what you'd like to build and how. Space on the calculator is short, so we'll agree on where it goes (inside NumPlay or as its own app) before you spend time on it.+- Small fixes (a typo, a crash, a clearer key hint) can go straight to a pull request.++## Set up your computer++NumPlay builds on **macOS**, **Linux** and **Windows**.++```bash+git clone https://github.com/Mason363/NumPlay.git+```++```bash+python3 NumPlay/tools/setup.py+```++`tools/setup.py` gets the ARM compiler, nwlink and the Python packages into `~/.numplay` and tells you the one line that puts them on your PATH (`source ~/.numplay/env.sh` on macOS and Linux). On macOS, run `xcode-select --install` first if `make` is missing. Rust is needed only for Tetris: [rustup.rs](https://rustup.rs), then `rustup target add thumbv7em-none-eabihf`. On Windows, building all of NumPlay needs GNU make (Git Bash or WSL); a single game builds with `make -C games/<game>` the same way.++Then:++| Command | What it does |+| --- | --- |+| `make -j4 NWLINK=nwlink` | NumPlay, its versions and every game on its own, in `build/` |+| `make check NWLINK=nwlink` | Checks that NumPlay fits the calculator's space and every game its RAM |+| `make lang NWLINK=nwlink` | The French and Chinese versions |+| `make -C games/<game> NWLINK=nwlink` | One game on its own |+| `make -C games/<game> test` | That game's tests on your computer (most games have them) |+| `python3 tests/test_games.py build/apps` | Plays every app in the emulator and checks its saves |+| `python3 tools/emu.py app.nwa --ms 5000 --shots 2000 --out shots` | Runs any `.nwa` in the emulator and takes pictures |++## How the code is laid out++| Folder | What's in it |+| --- | --- |+| `launcher/` | NumPlay itself: the home screen, settings, saves, the 2D drawing every small game shares |+| `games/<game>/` | One game: `src/` (with `icon.png`), `Makefile`, `README.md`, `docs/` pictures, `lang/` translations, `tests/` |+| `games/common/` | What every game uses: Home safety, files, text, compression |+| `games/games.json` | The games in NumPlay, in the launcher's order, with their colours and screenshots |+| `sdk/template/` | Star Catcher, the template new games start from |+| `tools/` | Builders, the emulator, icons, translations, sizes |+| `tests/` | Tests of NumPlay and every app |+| `docs/` | How to play, the guide to making games, the pictures |++A **small game inside NumPlay** follows Block Blast's pattern (`games/blockblast`): built with `-DNP_MODULE=1`, it draws with the launcher's `gfx_*` functions and fonts and saves with `np_file_read` and `np_file_write`, so it costs only its rules and its screen. On its own it compiles those files in. `tools/new_game.py "My Game" --numplay` starts one this way.++A **big game** builds as its own `.nwa` (like `games/finalearth2`), with a build for your computer to test it.++## What every game needs++- **Faithful to what it's based on**: its rules, numbers, levels and look. Nothing cheap, nothing important missing.+- **Keys anyone gets**: arrows move, OK or EXE acts, Back pauses or goes back, Home quits from anywhere. The keys are written on the screen whenever there's something to learn.+- **A pause menu in the game's own look**, with Quit game, which asks first.+- **An icon** of 55 x 56 pixels with NumPlay's rounded corners: `python3 tools/icon.py picture.png games/<game>/src/icon.png`. For a port, start from the original's own icon.+- **Saves that always come back**: packed bytes with a magic and a version number; old versions read or reset cleanly, never a crash. Save on Home, on quitting and every so often while playing.+- **Every calculator**: it runs on the N0110, N0115 and N0120 (the first two are 2.5 times slower: keep the game's speed with a fixed tick rate and catch-up), fits the RAM (`make check`), and says so if it needs more than Upsilon gives (107 KB).+- **Speed**: 30 frames a second on the N0120.+- **Honest credits**: the original's makers, every borrowed picture, font and library, and "not affiliated with" them.++## Translations++Texts players read are marked `T("...")` in the code. Each game has `lang/fr.txt` and `lang/zh.txt`: one line per text, the English, a tab, then the translation. `make lang` builds NumPlay in French and Chinese from them. To fix or add a translation, edit those files; new texts in the launcher go in `launcher/lang/`.++## Testing++Before a pull request:++1. `make -C games/<game> test` if your game has tests, and add some if it hasn't: its rules against the original, a scripted playthrough, and a few hundred random-key runs that must not crash.+2. Run it in the emulator (`tools/emu.py`), also with `--model n0110`.+3. `make -j4 check NWLINK=nwlink` if you touched NumPlay or a game inside it.+4. Play the first minute as someone who has never seen the game.++If you can, try it on a real calculator too, and say which one in the pull request.++## Pull requests++- One subject per pull request: a fix, a game, a translation.+- Say what it does, how you tested it (computer, emulator, which calculator) and include a screenshot or GIF for anything you can see.+- Keep the README's plain style if you change it: short sentences a beginner understands.+- By sending a pull request you agree that your code is shared under NumPlay's [GPL-3.0 license](LICENSE).++Thank you!diff --git a/README.md b/README.mdindex 103fde02..e77db761 100644--- a/README.md+++ b/README.md@@ -20,7 +20,7 @@</p><p align="center">- <a href="#how-to-install"><b>How to install</b></a> · <a href="docs/play.md"><b>How to play</b></a> · <a href="https://github.com/Mason363/NumPlay/releases/latest"><b>All downloads</b></a> · <a href="#roadmap"><b>Roadmap</b></a>+ <a href="#how-to-install"><b>How to install</b></a> · <a href="docs/play.md"><b>How to play</b></a> · <a href="https://github.com/Mason363/NumPlay/releases/latest"><b>All downloads</b></a> · <a href="#roadmap"><b>Roadmap</b></a> · <a href="docs/make-a-game.md"><b>Make a game</b></a></p><p align="center">@@ -191,6 +191,20 @@ Install any of them instead of NumPlay.nwa: your progress is the same in each. AFilmed on my own calculator, no emulator.+## Make your own NumWorks games++NumPlay is also a kit for making games and apps for the NumWorks calculator. Start from its template in one command, then use the same pieces its games are built with: 2D and 3D drawing that fits the calculator's memory, fonts in three languages, saves that survive a reinstall, physics, and an emulator that tests your game without a calculator. It works on macOS, Windows and Linux.++```bash+python3 tools/setup.py+```++```bash+python3 tools/new_game.py "My Game"+```++Read **[Make your own NumWorks game](docs/make-a-game.md)** to go from there, and **[Contributing](CONTRIBUTING.md)** if you'd like to help with NumPlay itself.+## Roadmap- [x] Celestediff --git a/_config.yml b/_config.ymlindex 59294d16..5da19ef6 100644--- a/_config.yml+++ b/_config.yml@@ -1,4 +1,9 @@title: NumPlay-description: "24 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Super Mario 64, Doom, Sonic, Plants vs. Zombies, Cookie Clicker and more on their own."+description: "24 games for the NumWorks calculator in one app: NumDash, Crossy Road, NumBlocks, NumDrive, Balatro, Buckshot Roulette, Block Blast, Portal Returns, Tetris, Chrome Dino, Chess, Space Invaders, Sudoku and more. And Super Mario 64, Doom, Sonic, Plants vs. Zombies, Cookie Clicker and more on their own. Free and open source, with a kit to make your own NumWorks games in C."+url: https://mason363.github.io+baseurl: /NumPlaytheme: jekyll-theme-cayman-exclude: [games, launcher, tools, tests, build, LICENSES, Makefile, .github]+plugins:+ - jekyll-sitemap+ - jekyll-seo-tag+exclude: [games, launcher, tools, tests, build, sdk, LICENSES, Makefile, .github]diff --git a/docs/make-a-game.md b/docs/make-a-game.mdnew file mode 100644index 00000000..a31a2e95--- /dev/null+++ b/docs/make-a-game.md@@ -0,0 +1,115 @@+---+title: Make your own NumWorks calculator game+description: "How to make a game or app for the NumWorks calculator (N0110, N0115, N0120) in C: set up on macOS, Windows or Linux, start from NumPlay's template, draw in 2D or 3D, save, test in an emulator, and share your .nwa."+---++# Make your own NumWorks game++NumPlay is a collection of games for the NumWorks calculator, and it is also a kit for making your own. Every piece its games use is here for you to use too: a 2D renderer that fits the calculator's small memory, fonts and text in three languages, saves that survive a reinstall, compression, 3D renderers, physics, an emulator to test without a calculator, and tools for icons and screenshots. It's all free and open source (GPL-3.0).++Games are written in C (Rust works too: see Tetris). A game becomes a `.nwa` file, a NumWorks app, that anyone can install from [my.numworks.com/apps](https://my.numworks.com/apps).++## 1. Get ready (10 minutes)++You need [Python 3](https://www.python.org/downloads/), [Node.js](https://nodejs.org) and git. Then, from a copy of NumPlay:++```bash+git clone https://github.com/Mason363/NumPlay.git+```++```bash+python3 NumPlay/tools/setup.py+```++`tools/setup.py` downloads the ARM compiler the calculator needs (xPack's arm-none-eabi-gcc, about 1 GB unpacked), nwlink (NumWorks' tool that makes `.nwa` apps) and the Python packages of the tools, all into one folder in your home, `~/.numplay`. No administrator password, nothing changed elsewhere. It works on:++| Computer | Notes |+| --- | --- |+| **macOS** (Apple silicon or Intel) | If `make` is missing, run `xcode-select --install` first. Then, in each new terminal: `source ~/.numplay/env.sh` |+| **Linux** | Same as macOS: `source ~/.numplay/env.sh` |+| **Windows** | `tools/setup.py` prints the PowerShell line to use. To build all of NumPlay, use Git Bash and GNU make, or WSL |++## 2. Start a game++```bash+python3 tools/new_game.py "My Game"+```++This copies NumPlay's template, **Star Catcher** (`sdk/template`), to `games/mygame/`. It's a whole small game in one file, already doing what every game should: it draws, reads the keys, runs at a steady speed on every calculator, pauses with Back, quits with Home, and saves the best score. Build it:++```bash+make -C games/mygame+```++You get `games/mygame/output/mygame.nwa`. Now change `games/mygame/src/main.c` into your game.++## 3. Try it without a calculator++`tools/emu.py` runs a `.nwa` in an emulator of the calculator's ARM chip, with its screen, keys, clock and files. It takes pictures and GIFs, so you can see your game without installing it:++```bash+python3 tools/emu.py games/mygame/output/mygame.nwa --ms 6000 --keys "1500-1600:ok,2000-4000:right" --shots 1400,3900 --out shots+```++`--keys` holds keys over time ranges in milliseconds (`ok`, `back`, `left`, `up`, `exe`, `home`, `1`...`9`, `shift`, `alpha`...). `--gif 0-5000` records a GIF, `--model n0110` emulates the slower N0110 and N0115 (if your game is smooth there, it's smooth everywhere), `--system upsilon` emulates Upsilon. It runs at about the speed of an N0110.++## 4. Put it on a calculator++Plug the calculator in, open [my.numworks.com/apps](https://my.numworks.com/apps) in Chrome or Edge, and drop your `.nwa` there. Or, from the terminal: `nwlink install-nwa games/mygame/output/mygame.nwa`.++## What you can build on++| What | Where | Used by |+| --- | --- | --- |+| **2D drawing** in 16-row strips, so no frame buffer has to fit in RAM: rectangles, rounded boxes, circles, gradients, see-through fills, palette pictures, masks | `launcher/src/gfx.h` | Block Blast, Sokoban, Sudoku, Space Invaders, 2 Players, the template |+| **Text**: NumPlay's three fonts, centered, right-aligned and word-wrapped | `launcher/src/gfx.h`, `font.h` | every small game |+| **Translations**: mark texts with `T("...")`, add `lang/fr.txt` and `lang/zh.txt`, and the French and Chinese builds are made for you (accents and Chinese letters included) | `games/common/np_text.h`, `tools/lang.py` | every game in NumPlay |+| **Saves**: files in the calculator's storage, read and written in place | `games/common/epsilon_files.h` (`ef_read`, `ef_write`) | almost every game |+| **Saves that survive a reinstall**: a copy kept in a Python script, which the NumWorks website keeps | `games/celeste/src/save.c` (`save_copy`) | Celeste, Hollow Knight, Undertale, the big games |+| **Safety**: Home handled cleanly, the slower models and Upsilon recognised, keys let go before quitting | `games/common/epsilon_app.h` | every game |+| **Compression**: LZ for pictures, DEFLATE for levels | `games/common/np_lz.h`, `launcher/src/inflate.c` | Chrome Dino, Sokoban, NumDash |+| **3D**: perspective-correct textured triangles drawn a few rows at a time, with fog and light | `games/sm64/src/render.c` | Super Mario 64 |+| **3D**: shaded, textured models and scenery | `games/subway/src/r3d.c` | Subway Surfers |+| **Voxels**: a Minecraft-style world renderer | `games/numblocks/src/render.c` | NumBlocks |+| **Physics**: rigid bodies, joints, contacts and raycasts | `games/numdrive/src` | NumDrive |+| **Vehicle physics** on hills | `games/hillclimb/src` | Hill Climb Racing |+| **A port of a C game engine** running on the calculator: Doom, Super Mario 64's decompilation, Sonic | `games/doom`, `games/sm64`, `games/sonic` | |++And the tools, all in `tools/`:++| Tool | What it does |+| --- | --- |+| `setup.py` | Gets the compiler, nwlink and the Python packages |+| `new_game.py` | Starts a game from the template |+| `emu.py` | Runs a `.nwa` in an emulator: pictures, GIFs, scripted keys, files kept between runs, profiling |+| `icon.py` | Makes the 55 x 56 app icon from any picture, with the rounded corners every NumPlay icon has |+| `record.py` | Makes GIFs from the emulator's frames |+| `sizes.py` | How much flash and RAM each game takes inside NumPlay |+| `lang.py` | Builds the French and Chinese versions |+| `../tests/test_games.py` | Plays every app in the emulator and checks its saves survive a reinstall |++## What the calculator gives you++| | |+| --- | --- |+| **Screen** | 320 x 240 pixels, 16-bit colour (RGB565) |+| **Speed** | N0120: 550 MHz. N0110 and N0115: 216 MHz, about 2.5 times slower. Run your game's logic at a fixed rate and catch up when drawing is slow, so it plays at the same speed everywhere |+| **RAM** | About 133 KB for your app on every recent NumWorks software (148 KB on most), plus a 32 KB stack; 107 KB on Upsilon. Put big buffers on `main`'s stack, not in global variables |+| **Space** | About 1.9 MB of flash for all installed apps together. Small games are 5 to 50 KB |+| **Files** | About 42 KB of storage for every app's saves and the user's scripts |+| **Keys** | The arrows, OK, Back, Home and the 40 others. No touch screen |+| **Sound** | None: the calculator has no speaker |++## Make it a good game++The games in NumPlay follow a few rules, and players notice when one doesn't:++- **The keys are obvious.** Arrows move, OK or EXE acts, Back pauses or goes back, Home quits from anywhere. Write the keys on the screen when there is anything to learn.+- **The pause menu fits the game.** Draw it in your game's own look, with a Quit game choice that asks first.+- **It never breaks.** No crash, no lost save: save as packed bytes with a version number, and read old or broken files without crashing.+- **It's fast.** 30 frames a second on the N0120, and the same game speed on the N0110.+- **Credit honestly.** If your game is based on another, say so and name the original's makers, and say you are not affiliated with them.++## Share it++Your game is yours: put the `.nwa` anywhere. If you'd like it in NumPlay, read [CONTRIBUTING.md](../CONTRIBUTING.md) and open an issue first, so we can talk about it before you build it.diff --git a/sdk/README.md b/sdk/README.mdnew file mode 100644index 00000000..072fb725--- /dev/null+++ b/sdk/README.md@@ -0,0 +1,7 @@+# NumPlay's game kit++`template/` is **Star Catcher**, a whole small NumWorks game in one file (`template/src/main.c`): it draws with NumPlay's 2D strips and fonts, reads the keys, keeps the same speed on every calculator, pauses with Back, quits with Home and saves the best score.++Start a game from it with `python3 tools/new_game.py "My Game"`, which copies it to `games/mygame/`. Or build it as it is: `make -C sdk/template` makes `output/starcatcher.nwa`.++The whole guide: [Make your own NumWorks game](../docs/make-a-game.md).diff --git a/sdk/template/.gitignore b/sdk/template/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/sdk/template/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/sdk/template/Makefile b/sdk/template/Makefilenew file mode 100644index 00000000..ce75007d--- /dev/null+++ b/sdk/template/Makefile@@ -0,0 +1,70 @@+# Star Catcher: NumPlay's game template (tools/new_game.py makes a new game from it).+# make build output/starcatcher.nwa+# make check link the app like the calculator does (output/starcatcher.bin)+#+# In NumPlay the game draws with the launcher's strips, shapes and fonts and saves through its+# file functions (module.o leaves them to the launcher); on its own it brings them along.+Q ?= @+CC = arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+BUILD_DIR = output+SRC = src/main.c+HEADERS = ../../games/common/epsilon_app.h ../../games/common/epsilon_files.h ../../games/common/np_text.h ../../launcher/src/gfx.h \+ ../../launcher/src/np.h ../../launcher/src/font.h++CFLAGS = -std=c11 $(shell $(NWLINK) eadk-cflags-device)+CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean+build: $(BUILD_DIR)/starcatcher.nwa++check: $(BUILD_DIR)/starcatcher.nwa+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/starcatcher.bin+ @echo "BIN $(BUILD_DIR)/starcatcher.bin: $$(wc -c < $(BUILD_DIR)/starcatcher.bin) bytes"++# compiled, then linked (the link options would upset the compiler)+$(BUILD_DIR)/main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ @echo "CC $<"+ $(Q) $(CC) $(CFLAGS) -c $(SRC) -o $@+$(BUILD_DIR)/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)/starcatcher.nwa: $(BUILD_DIR)/main.o $(BUILD_DIR)/gfx.o $(BUILD_DIR)/font_data.o $(BUILD_DIR)/xfont.o \+ $(BUILD_DIR)/icon.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $^ -o $@+ $(Q) arm-none-eabi-strip --strip-unneeded $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++clean:+ $(Q) rm -rf $(BUILD_DIR)++# NumPlay launcher: the app as a module (see ../../tools/npmodule.py) for the+# calculator, and as a relocatable object for the simulator build.+.PHONY: module sim-module+module: $(BUILD_DIR)/module.o+$(BUILD_DIR)/module-main.o: $(SRC) $(HEADERS) | $(BUILD_DIR)+ $(Q) $(CC) $(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) $(HEADERS) | $(BUILD_DIR)+ $(Q) mkdir -p $(BUILD_DIR)/sim+ $(Q) cc -std=c11 -O2 -fPIC $(shell $(NWLINK) eadk-cflags-simulator) -DNP_MODULE=1 -Dmain=np_starcatcher_main \+ -c $(SRC) -o $(BUILD_DIR)/sim/main.o+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_starcatcher_main -o $@diff --git a/sdk/template/src/icon.png b/sdk/template/src/icon.pngnew file mode 100644index 00000000..ad195886Binary files /dev/null and b/sdk/template/src/icon.png differdiff --git a/sdk/template/src/main.c b/sdk/template/src/main.cnew file mode 100644index 00000000..530f9155--- /dev/null+++ b/sdk/template/src/main.c@@ -0,0 +1,181 @@+/* Star Catcher: NumPlay's game template. Catch the falling stars, miss three and it's over.+ *+ * A whole small game in one file, written the way NumPlay's small games are (Block Blast, Sokoban, Sudoku):+ * - it draws with the launcher's strips, shapes and fonts (launcher/src/gfx.h): a scene function paints+ * the screen 16 rows at a time, so no frame buffer has to fit in RAM, and only the rows that changed are+ * sent to the screen;+ * - the game thinks at a fixed rate (TICK_MS), however fast the calculator draws, catching up when behind;+ * - Back pauses (Resume, Restart, Quit game, which asks first), Home quits from anywhere, and the keys are+ * written on the screen;+ * - the best score is saved as packed bytes with a magic letter and a version, read back or reset cleanly.+ *+ * Inside NumPlay (built with NP_MODULE=1) it uses the launcher's drawing, fonts and files; on its own+ * (StarCatcher.nwa) it brings them along. tools/new_game.py copies it into games/<your game>/ to start+ * a new game: see docs/make-a-game.md. */+#include <eadk.h>+#include "../../../launcher/src/gfx.h"+#include "../../../games/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 "../../../games/common/epsilon_app.h"+#include "../../../games/common/epsilon_files.h"+#define np_file_read ef_read+#define np_file_write ef_write+#ifndef HOST /* (a computer build has no app header) */+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Star Catcher";+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);+}+#endif++#define KEY(k) (1ull << (k))+#define TICK_MS 20 /* the game thinks 50 times a second */+#define SKY HEX(0x0B1638)+#define NIGHT HEX(0x1C2B5E)+#define GOLD HEX(0xFFD34E)+#define WHITE 0xFFFF+#define HUD 22 /* the band on top */++/* starcatcher.sav: the best score, packed, with a magic letter and a version */+#define SAVE_NAME "starcatcher.sav"+static struct {+ uint8_t magic, version, flags, pad; /* flags: 1 the guide was read */+ uint32_t best;+} sv;++static color_t strip[SCREEN_W * STRIP_H];+static int bx = 160, score, missed, sel, over;+static struct {+ int16_t x, y, speed; /* y and speed in 1/16 pixels */+} stars[4];+static uint32_t seed = 1;+enum { PLAY, PAUSE, ASK, GUIDE, OVER };+static int state = GUIDE;++static uint32_t rnd(uint32_t n) { /* a number from 0 to n - 1 */+ seed ^= seed << 13, seed ^= seed >> 17, seed ^= seed << 5;+ return seed % n;+}+static void drop(int i) {+ stars[i].x = (int16_t)(16 + rnd(SCREEN_W - 32));+ stars[i].y = (int16_t)(-(int)rnd(160) * 16 - 160);+ stars[i].speed = (int16_t)(20 + rnd(12) + score / 2);+}+static void restart(void) {+ bx = 160, score = missed = 0;+ for (int i = 0; i < 4; i++) drop(i);+ state = PLAY;+}+static void save(void) {+ sv.magic = 'C', sv.version = 1;+ np_file_write(SAVE_NAME, &sv, sizeof sv);+}+static void load(void) {+ uint32_t len = 0;+ const uint8_t *d = np_file_read(SAVE_NAME, &len);+ if (d && len == sizeof sv && d[0] == 'C' && d[1] == 1)+ for (uint32_t i = 0; i < len; i++) ((uint8_t *)&sv)[i] = d[i]; /* (a record isn't aligned: byte by byte) */+}++/* one step of the game, TICK_MS long */+static void tick(uint64_t keys) {+ int dx = (keys & KEY(eadk_key_right) ? 4 : 0) - (keys & KEY(eadk_key_left) ? 4 : 0);+ bx = bx + dx < 20 ? 20 : bx + dx > SCREEN_W - 20 ? SCREEN_W - 20 : bx + dx;+ for (int i = 0; i < 4; i++) {+ stars[i].y = (int16_t)(stars[i].y + stars[i].speed);+ int y = stars[i].y / 16;+ if (y >= 206 && y < 222 && stars[i].x > bx - 22 && stars[i].x < bx + 22) score++, drop(i); /* caught */+ else if (y > SCREEN_H) { /* missed */+ drop(i);+ if (++missed == 3) {+ over = score > (int)sv.best;+ if (over) sv.best = (uint32_t)score;+ save();+ state = OVER, sel = 0;+ }+ }+ }+}++/* a choice of a menu, the one picked in gold */+static void choice(int y, const char *s, bool on) {+ if (on) gfx_rrect(100, y - 17, 120, 24, 12, GOLD, 256);+ gfx_text_center(&np_font_body, 160, y, s, on ? SKY : WHITE, 256);+}+static void star(int x, int y, color_t c) {+ gfx_fill(x - 1, y - 6, 3, 13, c), gfx_fill(x - 6, y - 1, 13, 3, c), gfx_circle(x, y, 3, c, 256);+}+static void scene(void *ctx) {+ char s[24];+ gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, 0x0B1638, 0x1C2B5E);+ for (int i = 0; i < 4; i++) star(stars[i].x, stars[i].y / 16, GOLD);+ gfx_rrect(bx - 20, 210, 40, 10, 5, WHITE, 256); /* the basket */+ gfx_fill(0, 0, SCREEN_W, HUD, SKY);+ int n = 0;+ for (int v = score; v || !n; v /= 10) s[n++] = (char)('0' + v % 10);+ for (int i = 0; i < n / 2; i++) { char t = s[i]; s[i] = s[n - 1 - i], s[n - 1 - i] = t; }+ s[n] = 0;+ gfx_text(&np_font_body, 8, 16, s, GOLD, 256);+ for (int i = 0; i < 3; i++) star(300 - 16 * i, 11, i < 3 - missed ? WHITE : NIGHT);+ if (state == PLAY) {+ gfx_text_center(&np_font_small, 160, 236, T("Left Right: move Back: pause"), WHITE, 160);+ return;+ }+ gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 120);+ gfx_rrect(70, 56, 180, 132, 14, NIGHT, 256);+ if (state == GUIDE) {+ gfx_text_center(&np_font_title, 160, 86, T("Star Catcher"), GOLD, 256);+ gfx_paragraph(&np_font_body, 160, 112, 160, 16, T("Catch the stars in the basket. Miss three and it's over."),+ WHITE, 256);+ choice(174, T("Play"), true);+ } else if (state == OVER) {+ gfx_text_center(&np_font_title, 160, 86, over ? T("New best!") : T("Game over"), GOLD, 256);+ choice(142, T("Play again"), sel == 0), choice(172, T("Quit game"), sel == 1);+ } else {+ gfx_text_center(&np_font_title, 160, 86, state == PAUSE ? T("Paused") : T("Quit game?"), GOLD, 256);+ if (state == PAUSE) choice(118, T("Resume"), sel == 0), choice(146, T("Restart"), sel == 1), choice(174, T("Quit game"), sel == 2);+ else choice(132, T("No"), sel == 0), choice(162, T("Yes"), sel == 1);+ }+}++int main(void) {+ np_app_begin();+ color_t *their_strip = gfx_buf; /* (inside NumPlay, the launcher's: given back at the end) */+ gfx_buf = strip;+ load();+ seed = (uint32_t)eadk_timing_millis() | 1;+ restart();+ if (sv.flags & 1) state = PLAY;+ else state = GUIDE;+ uint64_t held = eadk_keyboard_scan(); /* keys still down from the launcher wait to be let go */+ uint32_t next = (uint32_t)eadk_timing_millis();+ for (bool quit = false; !quit;) {+ uint64_t k = eadk_keyboard_scan(), hit = k & ~held;+ held = k;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) break;+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);+ int n = state == PAUSE ? 3 : 2;+ if (state != PLAY && hit & KEY(eadk_key_up)) sel = (sel + n - 1) % n;+ if (state != PLAY && hit & KEY(eadk_key_down)) sel = (sel + 1) % n;+ if (state == PLAY && back) state = PAUSE, sel = 0;+ else if (state == GUIDE && ok) sv.flags |= 1, save(), state = PLAY;+ else if (state == PAUSE && (ok || back)) state = !ok || sel == 0 ? PLAY : sel == 1 ? (restart(), PLAY) : ASK, sel = 0;+ else if (state == ASK && (ok || back)) quit = ok && sel == 1, state = PAUSE, sel = 2;+ else if (state == OVER && ok) sel == 0 ? restart() : (void)(quit = true);+ /* the game's ticks since the last frame (at most 5: then it slows down instead of jumping) */+ uint32_t now = (uint32_t)eadk_timing_millis();+ for (int i = 0; i < 5 && (int32_t)(now - next) >= 0; i++, next += TICK_MS)+ if (state == PLAY) tick(k);+ if ((int32_t)(now - next) > 5 * TICK_MS) next = now;+ gfx_render(scene, 0, 0, SCREEN_H);+ eadk_timing_msleep(1);+ }+ save();+ gfx_buf = their_strip;+ return np_app_end();+}diff --git a/tools/icon.py b/tools/icon.pynew file mode 100644index 00000000..f02b45c1--- /dev/null+++ b/tools/icon.py@@ -0,0 +1,54 @@+#!/usr/bin/env python3+"""Makes a NumWorks app icon from any picture, the way every NumPlay icon is: 55 x 56 pixels, NumPlay's+rounded corners (tools/make_icon.corner_mask, a radius of 12) and white outside them, as the calculator's+home screen is white.++For a port, start from the original game's own app icon or key art, so it is recognised at a glance.++ python3 tools/icon.py picture.png games/mygame/src/icon.png+ python3 tools/icon.py picture.png out.png --fit the whole picture, on --background (white)+ python3 tools/icon.py picture.png out.png --crop 10,0,90,100 a part of it first (left,top,right,bottom %)++Python 3 with Pillow; macOS, Linux and Windows.+"""+import argparse+import os+import sys++from PIL import Image, ImageChops++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from make_icon import corner_mask # noqa: E402++W, H = 55, 56+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("picture")+ ap.add_argument("out")+ ap.add_argument("--fit", action="store_true", help="fit the whole picture instead of filling the icon")+ ap.add_argument("--background", default="ffffff", help="behind a fitted or transparent picture (hex)")+ ap.add_argument("--crop", help="left,top,right,bottom in percent of the picture, before anything else")+ a = ap.parse_args()+ im = Image.open(a.picture).convert("RGBA")+ if a.crop:+ l, t, r, b = (float(v) / 100 for v in a.crop.split(","))+ im = im.crop((round(l * im.width), round(t * im.height), round(r * im.width), round(b * im.height)))+ bg = tuple(int(a.background[i:i + 2], 16) for i in (0, 2, 4)) + (255,)+ scale = (min if a.fit else max)(W / im.width, H / im.height)+ big = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))), Image.LANCZOS)+ canvas = Image.new("RGBA", (W, H), bg)+ canvas.alpha_composite(big, ((W - big.width) // 2, (H - big.height) // 2)) if a.fit else \+ canvas.alpha_composite(big.crop(((big.width - W) // 2, (big.height - H) // 2,+ (big.width - W) // 2 + W, (big.height - H) // 2 + H)))+ alpha = ImageChops.darker(canvas.getchannel("A"), corner_mask(W, H))+ flat = Image.new("RGB", (W, H), (255, 255, 255))+ flat.paste(canvas.convert("RGB"), (0, 0), alpha)+ flat.putalpha(alpha)+ flat.save(a.out, optimize=True)+ print(f"{a.out}: {W}x{H}, NumPlay's corners")+++if __name__ == "__main__":+ main()diff --git a/tools/new_game.py b/tools/new_game.pynew file mode 100644index 00000000..3c9fa58f--- /dev/null+++ b/tools/new_game.py@@ -0,0 +1,70 @@+#!/usr/bin/env python3+"""Starts a new NumWorks game from NumPlay's template (sdk/template, "Star Catcher"): a small game that+already draws, reads the keys, pauses, saves and quits the way NumPlay's games do. Edit its src/main.c.++ python3 tools/new_game.py "My Game" games/mygame/, MyGame.nwa+ python3 tools/new_game.py "My Game" --id mg games/mg/+ python3 tools/new_game.py "My Game" --numplay also on NumPlay's home screen (games/games.json)++Then: make -C games/mygame output/mygame.nwa, ready to install+ python3 tools/emu.py games/mygame/output/mygame.nwa --ms 5000 --shots 2000 --out /tmp/shots+See docs/make-a-game.md for the whole guide. Works on macOS, Linux and Windows (Python 3 and Pillow).+"""+import argparse+import json+import os+import re+import shutil+import sys++ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")+TEMPLATE = os.path.join(ROOT, "sdk", "template")+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("title", help="the game's name, as players see it (\"My Game\")")+ ap.add_argument("--id", help="its folder and file name: lower case letters and digits (default: from the title)")+ ap.add_argument("--numplay", action="store_true", help="also add it to NumPlay's launcher (games/games.json)")+ a = ap.parse_args()+ gid = a.id or re.sub(r"[^a-z0-9]", "", a.title.lower())+ if not re.fullmatch(r"[a-z][a-z0-9]{1,15}", gid):+ sys.exit("new_game: the id must be 2 to 16 lower case letters and digits, starting with a letter (--id)")+ app = re.sub(r"[^A-Za-z0-9]", "", a.title.title()) or gid+ dest = os.path.join(ROOT, "games", gid)+ if os.path.exists(dest):+ sys.exit(f"new_game: games/{gid} is already there")+ if len(a.title.encode()) > 40:+ sys.exit("new_game: keep the title under 40 letters (the calculator's home screen shows it)")++ shutil.copytree(TEMPLATE, dest, ignore=shutil.ignore_patterns("output", "build"))+ for path in (os.path.join(dest, "Makefile"), os.path.join(dest, "src", "main.c")):+ s = open(path, encoding="utf-8").read()+ s = s.replace("Star Catcher", a.title).replace("StarCatcher", app).replace("starcatcher", gid)+ open(path, "w", encoding="utf-8").write(s)+ open(os.path.join(dest, "README.md"), "w", encoding="utf-8").write(+ f"# {a.title}\n\nA game for the NumWorks calculator, made with [NumPlay](../../docs/make-a-game.md)'s "+ f"template.\n\n## Controls\n\n| Key | Action |\n| --- | --- |\n| Left, Right | Move |\n"+ f"| OK or EXE | Choose |\n| Back | Pause: Resume, Restart, Quit game |\n| Home | Quit |\n\n"+ f"Build: `make` makes `output/{gid}.nwa` (needs `arm-none-eabi-gcc` and Node.js for nwlink).\n")++ if a.numplay:+ p = os.path.join(ROOT, "games", "games.json")+ games = json.load(open(p, encoding="utf-8"))+ games.append({"id": gid, "title": a.title, "tagline": "A new game", "credit": None, "top": "0x1C2B5E",+ "bottom": "0x0B1638", "accent": "0xFFD34E", "records": [f"{gid}.sav"], "shots": ["docs/shot.png"],+ "app": f"{app}.nwa", "repo": f"https://github.com/Mason363/NumPlay/tree/main/games/{gid}"})+ open(p, "w", encoding="utf-8").write(json.dumps(games, indent=2, ensure_ascii=False) + "\n")+ os.makedirs(os.path.join(dest, "docs"), exist_ok=True)+ print(f"Added to games/games.json. NumPlay's card needs games/{gid}/docs/shot.png (320x240): take one with\n"+ f" python3 tools/emu.py games/{gid}/output/{gid}.nwa --ms 4000 --keys 1500-1600:ok --shots 3000 "+ f"--out games/{gid}/docs\n and rename it shot.png.")+ print(f"games/{gid}/ is ready: its game is in games/{gid}/src/main.c, its icon in src/icon.png "+ f"(tools/icon.py makes one from any picture).\n"+ f" make -C games/{gid} builds output/{gid}.nwa\n"+ f" python3 tools/emu.py games/{gid}/output/{gid}.nwa --ms 5000 --keys 1500-1600:ok --shots 3000 --out shots\n"+ f"Install the .nwa from https://my.numworks.com/apps with the calculator plugged in.")+++if __name__ == "__main__":+ main()diff --git a/tools/setup.py b/tools/setup.pynew file mode 100644index 00000000..a4b1aa94--- /dev/null+++ b/tools/setup.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Gets a computer ready to build NumPlay and your own NumWorks games: macOS (Apple silicon or Intel), Linux+and Windows. Nothing is installed system-wide and no administrator password is needed: everything goes in+one folder in your home (~/.numplay), and the script tells you the one line that puts it on your PATH.++ python3 tools/setup.py check what's there and get what's missing+ python3 tools/setup.py --check only check++What it gets:+- the ARM compiler the calculator needs, xPack's arm-none-eabi-gcc (the version NumPlay's own builds use),+ checked against its published SHA-256 (the idea of LilyTheCuteCatgirl's Windows builder, PR #77);+- nwlink 1.0.0 (NumWorks' tool that turns a program into a .nwa app), with npm, from Node.js;+- the Python packages of the tools and the emulator (Pillow, NumPy, pyelftools, Unicorn, zopfli).+It needs Python 3.9 or newer and Node.js (https://nodejs.org) already installed, and GNU make (on macOS,+`xcode-select --install`; on Windows, see tools/build_windows.py). Rust is only needed for Tetris.+"""+import argparse+import hashlib+import os+import platform+import shutil+import subprocess+import sys+import tarfile+import tempfile+import urllib.request+import zipfile++GCC = "15.2.1-1.1"+HOME = os.path.join(os.path.expanduser("~"), ".numplay")+PY_PACKAGES = ["pillow", "numpy", "pyelftools", "unicorn==2.1.4", "zopfli"]+PY_IMPORTS = ["PIL", "numpy", "elftools", "unicorn", "zopfli"]+++def say(ok, what, hint=""):+ print(f" {'ok ' if ok else '-- '} {what}" + (f"\n {hint}" if hint and not ok else ""))+ return ok+++def gcc_asset():+ s, m = sys.platform, platform.machine().lower()+ arm = m in ("arm64", "aarch64")+ if s == "darwin":+ return f"darwin-{'arm64' if arm else 'x64'}", "tar.gz"+ if s.startswith("linux"):+ return f"linux-{'arm64' if arm else 'x64'}", "tar.gz"+ if s in ("win32", "cygwin"):+ return "win32-x64", "zip"+ sys.exit(f"setup: no ARM compiler build for {s} {m}")+++def gcc_bin():+ return os.path.join(HOME, f"xpack-arm-none-eabi-gcc-{GCC}", "bin")+++def get_gcc():+ plat, ext = gcc_asset()+ name = f"xpack-arm-none-eabi-gcc-{GCC}-{plat}.{ext}"+ url = f"https://github.com/xpack-dev-tools/arm-none-eabi-gcc-xpack/releases/download/v{GCC}/{name}"+ print(f" downloading {name} (about 150 MB)...")+ os.makedirs(HOME, exist_ok=True)+ with tempfile.TemporaryDirectory(dir=HOME) as d:+ path = os.path.join(d, name)+ urllib.request.urlretrieve(url, path)+ want = urllib.request.urlopen(url + ".sha").read().decode().split()[0].lower()+ h = hashlib.sha256()+ with open(path, "rb") as f:+ for chunk in iter(lambda: f.read(1 << 20), b""):+ h.update(chunk)+ if h.hexdigest() != want:+ sys.exit(f"setup: {name} doesn't match its published SHA-256: not used")+ if ext == "zip":+ with zipfile.ZipFile(path) as z:+ z.extractall(HOME)+ else:+ with tarfile.open(path) as t:+ t.extractall(HOME, filter="tar") if hasattr(tarfile, "data_filter") else t.extractall(HOME)+++def node_bin():+ return os.path.join(HOME, "node_modules", ".bin")+++def main():+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--check", action="store_true", help="only check, get nothing")+ a = ap.parse_args()+ win = sys.platform in ("win32", "cygwin")+ exe = ".exe" if win else ""+ print(f"NumPlay setup: {sys.platform} {platform.machine()}, tools in {HOME}")++ gcc = os.path.join(gcc_bin(), "arm-none-eabi-gcc" + exe)+ if not os.path.exists(gcc) and not shutil.which("arm-none-eabi-gcc") and not a.check:+ get_gcc()+ have_gcc = say(os.path.exists(gcc) or bool(shutil.which("arm-none-eabi-gcc")),+ f"ARM compiler (arm-none-eabi-gcc {GCC})", "python3 tools/setup.py downloads it")++ npm = shutil.which("npm")+ say(bool(npm), "Node.js and npm", "install Node.js from https://nodejs.org, then run this again")+ nw = os.path.join(node_bin(), "nwlink" + (".cmd" if win else ""))+ if npm and not os.path.exists(nw) and not shutil.which("nwlink") and not a.check:+ print(" installing nwlink 1.0.0...")+ subprocess.run([npm, "install", "--prefix", HOME, "[email protected]"], check=True)+ have_nw = say(os.path.exists(nw) or bool(shutil.which("nwlink")), "nwlink 1.0.0 (makes .nwa apps)",+ "needs npm: npm install --prefix ~/.numplay [email protected]")++ missing = []+ for mod, pkg in zip(PY_IMPORTS, PY_PACKAGES):+ try:+ __import__(mod)+ except ImportError:+ missing.append(pkg)+ if missing and not a.check:+ print(f" installing {' '.join(missing)} for this Python...")+ r = subprocess.run([sys.executable, "-m", "pip", "install", "--user", *missing])+ if r.returncode:+ print(" (pip refused: install them with your Python's own way, or in a venv)")+ missing = [p for m, p in zip(PY_IMPORTS, PY_PACKAGES) if subprocess.run(+ [sys.executable, "-c", f"import {m}"], capture_output=True).returncode]+ say(not missing, "Python packages (Pillow, NumPy, pyelftools, Unicorn, zopfli)",+ f"{sys.executable} -m pip install {' '.join(missing)}")+ say(bool(shutil.which("make")), "GNU make", "macOS: xcode-select --install; Windows: tools/build_windows.py")+ say(bool(shutil.which("cargo")), "Rust (only for Tetris)", "https://rustup.rs, then: rustup target add "+ "thumbv7em-none-eabihf")++ paths = [p for p in (gcc_bin(), node_bin()) if os.path.isdir(p)]+ os.makedirs(HOME, exist_ok=True)+ if win:+ line = "$env:Path = \"" + ";".join(paths) + ";$env:Path\""+ print(f"\nIn PowerShell, before building:\n {line}")+ else:+ env = os.path.join(HOME, "env.sh")+ with open(env, "w") as f:+ f.write("# NumPlay's tools (tools/setup.py): source this before building\n")+ f.write(f'export PATH="{":".join(paths)}:$PATH"\n')+ print(f"\nBefore building, in each new terminal:\n source {env}")+ print("Then:\n make -C sdk/template a small game, output/starcatcher.nwa\n"+ " make -j4 NWLINK=nwlink NumPlay and every game (build/)\n"+ "See docs/make-a-game.md.")+ return 0 if have_gcc and have_nw else 1+++if __name__ == "__main__":+ sys.exit(main())