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
Ultimate Tic-Tac-Toe: nine boards in one, for two or against the computer
Mason36303169b9e8b1c
diff --git a/games/games.json b/games/games.jsonindex c9eda7d2..0e80f13f 100644--- a/games/games.json+++ b/games/games.json@@ -416,6 +416,24 @@"app": "Sudoku.nwa","repo": "https://github.com/Mason363/NumPlay/tree/main/games/sudoku"},+ {+ "id": "uttt",+ "title": "Ultimate Tic-Tac-Toe",+ "tagline": "Tic-tac-toe in tic-tac-toe",+ "credit": null,+ "top": "0x2B3470",+ "bottom": "0x10132A",+ "accent": "0xFF4D6D",+ "colors": 6,+ "records": [+ "uttt.sav"+ ],+ "shots": [+ "docs/card.png"+ ],+ "app": "UltimateTicTacToe.nwa",+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/uttt"+ },{"id": "numvisuals","title": "NumVisuals",diff --git a/games/uttt/.gitignore b/games/uttt/.gitignorenew file mode 100644index 00000000..342d9dda--- /dev/null+++ b/games/uttt/.gitignore@@ -0,0 +1,2 @@+output/+build/diff --git a/games/uttt/Makefile b/games/uttt/Makefilenew file mode 100644index 00000000..df2e136c--- /dev/null+++ b/games/uttt/Makefile@@ -0,0 +1,83 @@+# Ultimate Tic-Tac-Toe — nine small boards in a big one, for two or against the computer.+# make build output/uttt.nwa+# make check link the app like the calculator does (output/uttt.bin)+# make test the rules and the computer's moves checked on a computer (tests/check.c)+#+# In NumPlay the game draws with the launcher's strips, shapes and fonts and saves through its+# file functions (module.o leaves them to the launcher); on its own it brings them along.+Q ?= @+CC = arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+BUILD_DIR = output+SRC = src/main.c+HEADERS = src/rules.h ../common/epsilon_app.h ../common/epsilon_files.h ../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+# (smaller still: NumPlay has little room left)+CFLAGS += -fno-schedule-insns2 -fno-reorder-blocks -fno-tree-loop-optimize+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+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)/uttt.nwa++check: $(BUILD_DIR)/uttt.nwa+ $(Q) $(NWLINK) nwa-bin $< $(BUILD_DIR)/uttt.bin+ @echo "BIN $(BUILD_DIR)/uttt.bin: $$(wc -c < $(BUILD_DIR)/uttt.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)/uttt.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) build++# 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_uttt_main \+ -c $(SRC) -o $(BUILD_DIR)/sim/main.o+ $(Q) ld -r $(BUILD_DIR)/sim/main.o -exported_symbol _np_uttt_main -o $@++# on a computer, with the sanitizers: the rules, and the computer's moves (tests/check.c)+.PHONY: host test+host: build/check+build/check: tests/check.c src/rules.h+ $(Q) mkdir -p build+ $(Q) cc -std=gnu11 -O2 -g -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=undefined tests/check.c -o $@+ @echo "HOST $@"+test: build/check+ build/checkdiff --git a/games/uttt/docs/card.png b/games/uttt/docs/card.pngnew file mode 100644index 00000000..a65899c6Binary files /dev/null and b/games/uttt/docs/card.png differdiff --git a/games/uttt/docs/shot.png b/games/uttt/docs/shot.pngnew file mode 100644index 00000000..0c88fe30Binary files /dev/null and b/games/uttt/docs/shot.png differdiff --git a/games/uttt/lang/fr.txt b/games/uttt/lang/fr.txtnew file mode 100644index 00000000..3b89c751--- /dev/null+++ b/games/uttt/lang/fr.txt@@ -0,0 +1,26 @@+# Ultimate Tic-Tac-Toe in French: the English text as in the source, a tab, the translation (see tools/lang.py).+vs a friend contre un ami+vs easy contre l'IA facile+vs normal contre l'IA normale+vs hard contre l'IA difficile+How to play Comment jouer+Win three small boards in a row. Your cell sends the other player to the small board in the same place; if it is won or full, they play anywhere. 1 to 9 take a cell, 7 at the top left (on a free move, pick the board first). The arrows and OK work too. Gagne trois petites grilles alignées. Ta case envoie l'autre joueur dans la petite grille au même endroit ; si elle est gagnée ou pleine, il joue où il veut. 1 à 9 prennent une case, 7 en haut à gauche (coup libre : choisis d'abord la grille). Les flèches et OK marchent aussi.+Play Jouer+Paused Pause+Resume Reprendre+New game Nouvelle partie+Quit game? Quitter le jeu ?+Quit game Quitter le jeu+Draw Égalité+You win! Gagné !+You lose Perdu+Thinking... Réflexion...+Your turn À toi+wins! gagne !+to play joue+Draws Nulles+You Toi+Computer IA+OK new game OK rejouer+1-9, OK play 1-9, OK jouer+Back menu Retour menudiff --git a/games/uttt/lang/zh.txt b/games/uttt/lang/zh.txtnew file mode 100644index 00000000..196c16d8--- /dev/null+++ b/games/uttt/lang/zh.txt@@ -0,0 +1,26 @@+# Ultimate Tic-Tac-Toe in Chinese: the English text as in the source, a tab, the translation (see tools/lang.py).+vs a friend 对战朋友+vs easy 对战电脑:简单+vs normal 对战电脑:普通+vs hard 对战电脑:困难+How to play 玩法+Win three small boards in a row. Your cell sends the other player to the small board in the same place; if it is won or full, they play anywhere. 1 to 9 take a cell, 7 at the top left (on a free move, pick the board first). The arrows and OK work too. 在大棋盘上赢下连成一线的三个小棋盘就获胜。你下在哪一格,对手就要去下同一位置的小棋盘;如果那个小棋盘已被赢下或已下满,对手可以下在任何地方。数字 1 到 9 选格子,7 是左上角(自由落子时先选小棋盘)。方向键和 OK 也可以。+Play 开始+Paused 暂停+Resume 继续+New game 新游戏+Quit game? 退出游戏?+Quit game 退出游戏+Draw 平局+You win! 你赢了!+You lose 你输了+Thinking... 思考中…+Your turn 轮到你+wins! 获胜!+to play 落子+Draws 平局+You 你+Computer 电脑+OK new game OK 再来一局+1-9, OK play 1-9, OK 落子+Back menu 返回 菜单diff --git a/games/uttt/src/icon.png b/games/uttt/src/icon.pngnew file mode 100644index 00000000..ef971aa8Binary files /dev/null and b/games/uttt/src/icon.png differdiff --git a/games/uttt/src/main.c b/games/uttt/src/main.cnew file mode 100644index 00000000..9e7a7bc6--- /dev/null+++ b/games/uttt/src/main.c@@ -0,0 +1,304 @@+/* Ultimate Tic-Tac-Toe: nine small boards in a big one. The cell you take sends the other player+ * to the small board in the same place; win three small boards in a row.+ *+ * Two players on one calculator, or one against the computer, easy, normal or hard (a search+ * deeper and deeper for a second: src/rules.h). The number pad is a small board, 7 at the top+ * left; the arrows and OK work too. The game in progress and the games won are kept.+ *+ * Inside NumPlay it draws with the launcher's strips, shapes and fonts (launcher/src/gfx.c) and+ * saves through its file functions, like Block Blast; on its own (UltimateTicTacToe.nwa) it+ * brings them along. The screen is drawn again only when something changes. */+#include <eadk.h>+#include "../../../launcher/src/gfx.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"))) = "Ultimate TTT";+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++/* the keys used, in 32 bits: 9, 4 to 6, 1 to 3 and EXE come down from the high word */+static uint32_t keys(void) {+ uint64_t s = eadk_keyboard_scan();+ return ((uint32_t)s & 0xC000017Fu) | ((uint32_t)(s >> 32) & 0x00101C71u) << 9;+}+#define KEY(k) (1u << ((k) < 32 ? (k) : (k) - 23))+/* the number pad as a small board, 7 at the top left: where each key's bit is in keys() */+static const uint8_t DIGIT[9] = {30, 31, 9, 13, 14, 15, 19, 20, 21};+#define QUIT (KEY(eadk_key_home) | KEY(eadk_key_on_off))+static uint32_t now, deadline, seed;+static bool quit;+static bool search_stop(void) {+ if (keys() & QUIT) quit = true;+ return quit || (int32_t)((uint32_t)eadk_timing_millis() - deadline) >= 0;+}+static uint32_t rnd(void) {+ seed ^= seed << 13;+ seed ^= seed >> 17;+ return seed ^= seed << 5;+}+#include "rules.h"++#define WHITE 0xFFFF+#define OX 12 /* the big board's first cell */+#define OY 13+#define BP 74 /* from one small board to the next; cells are 22 apart */+#define PX 275 /* the middle of the panel on the right */+#define PLATE HEX(0x262C4D)+#define SQUARE HEX(0x353D66)+#define PALE HEX(0xB9C2E8)++/* uttt.sav: the opponent, the game in progress as its moves, and the games won */+static struct {+ uint8_t magic, version, opp, human; /* opp: 0 a friend, 1 to 3 the computer, easy to hard; human: the+ player's side against it */+ uint8_t flags, n, cur, pad; /* flags: 1 how to play was read; n: moves played; cur: the cursor */+ uint16_t score[4][3]; /* [opp][X or the player, O or the computer, draws] */+ uint8_t moves[81];+} sv;+#define SAVE_NAME "uttt.sav"++static color_t strip[SCREEN_W * STRIP_H];+static pos_t pos;+static uint32_t turn_t;+static int pick = -1, ov, sel, sure, res, opp; /* pick: the small board chosen with a number on a free move;+ opp: the next game's opponent, chosen in the menu */+static color_t team[2]; /* X red, O blue */+enum { OV_NONE, OV_MENU, OV_HELP };++/* v's digits at o; where they end */+static char *num(char *o, unsigned v) {+ if (v >= 10) o = num(o, v / 10);+ *o = (char)('0' + v % 10);+ return o + 1;+}+static bool cpu_turn(void) { return sv.opp && pos.turn != sv.human && !res; }+static void save(void) {+ sv.magic = 'U', sv.version = 1;+ np_file_write(SAVE_NAME, &sv, sizeof sv);+}++/* ------------------------------------------------------------ the game */+/* the cursor on a cell that can be taken, in the small board to play: its middle if free */+static void aim(void) {+ uint16_t mv[9];+ int b = pick >= 0 ? pick : sv.cur / 9;+ legal(&pos, mv);+ while (!mv[b]) b = (b + 1) % 9;+ if (!(mv[b] >> sv.cur % 9 & 1) || b != sv.cur / 9) sv.cur = (uint8_t)(b * 9 + (mv[b] & 020 ? 4 : __builtin_ctz(mv[b])));+}++static void move(int m) {+ play(&pos, m);+ sv.moves[sv.n++] = (uint8_t)m, pick = -1, turn_t = now;+ if ((res = result(&pos)) != 0) {+ /* the score's column: X and O, or the player and the computer, then draws */+ int w = res - 1;+ if (sv.opp && w < 2) w = w != sv.human;+ sv.score[sv.opp][w]++;+ } else {+ aim();+ }+ save();+}++static void new_game(void) {+ sv.opp = (uint8_t)opp;+ pos = (pos_t){.next = -1};+ sv.n = 0, pick = -1, res = 0, turn_t = now;+ sv.human ^= sv.opp != 0; /* against the computer, X and O swap every game */+ aim();+ save();+}++/* ------------------------------------------------------------ drawing */+static void box(int x, int y, int w, int h, color_t c) { gfx_rrect(x, y, w, h, 7, c, 256); }+static void text(int x, int y, const char *s, color_t c) { gfx_text_center(&np_font_small, x, y, s, c, 256); }+/* a line of discs r across from (x0, y0) to (x1, y1), n steps */+static void stroke(int x0, int y0, int x1, int y1, int n, int r, color_t c) {+ for (int i = 0; i <= n; i++) gfx_circle(x0 + (x1 - x0) * i / n, y0 + (y1 - y0) * i / n, r, c, 256);+}+/* X (who 0) or O (who 1), s pixels across, around (x, y) */+static void mark(int who, int x, int y, int s, color_t c) {+ int t = s / 10 + 1, h = s / 2 - t;+ if (who) gfx_rrect_outline(x - s / 2, y - s / 2, s, s, s / 2, 2 * t, c, 256);+ else stroke(x - h, y - h, x + h, y + h, 2 * h, t, c), stroke(x - h, y + h, x + h, y - h, 2 * h, t, c);+}+static void button(int y, const char *s, bool on) {+ box(75, y, 170, 26, on ? WHITE : HEX(0x3A4374));+ gfx_text_center(&np_font_body, 160, y + 18, s, on ? PLATE : WHITE, 256);+}++static const char *const OPP[4] = {T("vs a friend"), T("vs easy"), T("vs normal"), T("vs hard")};++static void overlay(void) {+ gfx_fill_alpha(0, 0, SCREEN_W, SCREEN_H, 0, 130);+ if (ov == OV_HELP) {+ box(16, 18, 288, 204, PLATE);+ gfx_text_center(&np_font_title, 160, 46, T("How to play"), WHITE, 256);+ gfx_paragraph(&np_font_body, 160, 70, 264, 16,+ T("Win three small boards in a row. Your cell sends the other player to the small board in the same place; if it is won or full, they play anywhere. 1 to 9 take a cell, 7 at the top left (on a free move, pick the board first). The arrows and OK work too."),+ WHITE, 256);+ button(188, T("Play"), true);+ return;+ }+ box(60, 44, 200, 152, PLATE);+ gfx_text_center(&np_font_title, 160, 72, T("Paused"), WHITE, 256);+ const char *items[3] = {T("Resume"), T("New game"), sure ? T("Quit game?") : T("Quit game")};+ for (int i = 0; i < 3; i++) button(84 + 30 * i, items[i], sel == i);+ text(160, 188, OPP[opp], sel == 1 ? WHITE : PALE); /* the new game's opponent: Left, Right */+ if (sel == 1) text(100, 188, "<", WHITE), text(220, 188, ">", WHITE);+}++static void scene(void *ctx) {+ char s[6];+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, HEX(0x161A33));+ uint16_t mv[9];+ legal(&pos, mv);+ int who = pos.turn, last = sv.n ? sv.moves[sv.n - 1] : -1, w = res ? res - 1 : who;+ int cur = !res && !cpu_turn() ? sv.cur : -1;+ color_t tint = gfx_mix(team[!who], SQUARE, 10); /* the last move's cell */+ for (int b = 0; b < 9; b++) {+ int x0 = OX + b % 3 * BP, y0 = OY + b / 3 * BP, won = pos.won[1] >> b & 1;+ bool open = !(pos.over >> b & 1), taken = (pos.won[0] | pos.won[1]) >> b & 1;+ box(x0 - 3, y0 - 3, 70, 70, taken ? gfx_mix(team[won], PLATE, 9) : open ? PLATE : HEX(0x2B2E3D));+ if (mv[b] && !res) /* the small board(s) to play in, in the colour of who plays */+ gfx_rrect(x0 - 3, y0 - 3, 70, 70, 7, team[who], pick == b ? 120 : 50);+ for (int c = 0; c < 9; c++) {+ int x = x0 + c % 3 * 22, y = y0 + c / 3 * 22, m = b * 9 + c, t = pos.mark[1][b] >> c & 1;+ if (open) box(x, y, 20, 20, m == cur ? WHITE : m == last ? tint : SQUARE);+ if ((pos.mark[0][b] | pos.mark[1][b]) >> c & 1) mark(t, x + 10, y + 10, 12, open ? team[t] : HEX(0x5A6080));+ }+ if (taken) mark(won, x0 + 32, y0 + 32, 52, team[won]);+ }+ for (int i = 0; res && res < 3 && i < 8; i++) /* the winning line */+ if ((pos.won[w] & LINES[i]) == LINES[i]) {+ int a = __builtin_ctz(LINES[i]), z = 31 - __builtin_clz(LINES[i]);+ stroke(OX + 32 + a % 3 * BP, OY + 32 + a / 3 * BP, OX + 32 + z % 3 * BP, OY + 32 + z / 3 * BP, 74, 3, WHITE);+ }++ /* the panel: whose turn (or who won), the games won, the keys */+ box(236, 10, 78, 182, PLATE);+ if (res != 3) mark(w, PX, 44, 40, team[w]);+ text(PX, 95, res == 3 ? T("Draw")+ : sv.opp ? (res ? (w == sv.human ? T("You win!") : T("You lose")) : cpu_turn() ? T("Thinking...") : T("Your turn"))+ : res ? T("wins!") : T("to play"), WHITE);+ static const char *const SIDE[2][3] = {{"X", "O", T("Draws")}, {T("You"), T("Computer"), T("Draws")}};+ for (int i = 0; i < 3; i++) {+ int y = 136 + 22 * i;+ gfx_text(&np_font_small, 244, y, SIDE[sv.opp != 0][i], i < 2 ? team[i ^ (sv.opp && sv.human)] : PALE, 256);+ *num(s, sv.score[sv.opp][i]) = 0;+ gfx_text_right(&np_font_small, 306, y, s, WHITE, 256);+ }+ text(PX, 214, res ? T("OK new game") : T("1-9, OK play"), PALE);+ text(PX, 230, T("Back menu"), PALE);+ if (ov) overlay();+}++/* ------------------------------------------------------------ the loop */+static void load(void) {+ uint32_t len = 0;+ const uint8_t *d = np_file_read(SAVE_NAME, &len);+ uint8_t *v = (uint8_t *)&sv;+ bool ok = d && len == sizeof sv && d[0] == 'U' && d[1] == 1;+ for (uint32_t i = 0; i < sizeof sv; i++) v[i] = ok ? d[i] : 0;+ if (!ok) sv.human = 1; /* (the first game against the computer: the player is X) */+ sv.opp &= 3, sv.human &= 1;+ /* the game in progress, played again move by move: a move that can't be played ends it there */+ int n = sv.n;+ pos = (pos_t){.next = -1};+ for (sv.n = 0; sv.n < n && sv.n < 81 && !result(&pos); sv.n++) {+ uint16_t mv[9];+ int m = sv.moves[sv.n];+ legal(&pos, mv);+ if (m >= 81 || !(mv[m / 9] >> m % 9 & 1)) break;+ play(&pos, m);+ }+ res = result(&pos);+ if (sv.cur >= 81) sv.cur = 40;+}++int main(void) {+ np_app_begin();+ color_t *their_strip = gfx_buf;+ gfx_buf = strip;+ team[0] = HEX(0xFF4D6D), team[1] = HEX(0x3EC5FF);+ now = (uint32_t)eadk_timing_millis();+ seed = eadk_random() | 1;+ load();+ if (!res) aim();+ if (!(sv.flags & 1)) ov = OV_HELP, sv.flags |= 1;+ uint32_t held = keys(); /* (keys still down from the launcher are not pressed again) */+ bool dirty = true;+ while (!quit) {+ now = (uint32_t)eadk_timing_millis();+ uint32_t k = keys(), hit = k & ~held;+ held = k;+ if (k & QUIT) break;+ dirty |= hit != 0;+ bool ok = hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe)), back = hit & KEY(eadk_key_back);+ int dx = !!(hit & KEY(eadk_key_right)) - !!(hit & KEY(eadk_key_left));+ int dy = !!(hit & KEY(eadk_key_down)) - !!(hit & KEY(eadk_key_up));+ if (ov == OV_HELP) {+ if (ok || back) ov = OV_NONE;+ } else if (ov) { /* Resume, New game (against whom: Left, Right), Quit game (OK twice) */+ if (dy) sel = (sel + dy + 3) % 3, sure = 0;+ if (sel == 1) opp = (opp + dx + 4) % 4;+ if (back) ov = OV_NONE;+ if (ok) {+ if (sel == 2 && sure) break;+ sure = sel == 2, ov = sure;+ if (sel == 1) new_game();+ }+ } else if (back) {+ if (pick >= 0) pick = -1;+ else ov = OV_MENU, sel = sure = 0, opp = sv.opp;+ } else if (res) {+ if (ok) opp = sv.opp, new_game();+ } else if (cpu_turn()) {+ if (!dirty && now - turn_t > 450) { /* the board shown first, then the computer thinks */+ deadline = now + 1000;+ static const uint8_t DEPTH[4] = {0, 1, 3, 30}, NOISE[4] = {0, 90, 10, 0};+ int m = think(&pos, DEPTH[sv.opp], NOISE[sv.opp]);+ if (quit) break;+ move(m), dirty = true;+ }+ } else {+ uint16_t mv[9];+ legal(&pos, mv);+ int digit = -1, b = pos.next >= 0 ? pos.next : pick;+ for (int c = 0; c < 9; c++)+ if (hit >> DIGIT[c] & 1) digit = c;+ if (digit >= 0 && b < 0) { /* a free move: the number picks the small board first */+ if (mv[digit]) pick = digit, aim();+ } else if (digit >= 0) {+ if (mv[b] >> digit & 1) move(b * 9 + digit);+ } else if (dx || dy) { /* the cursor over the 9 x 9 cells */+ int gx = (sv.cur / 9 % 3 * 3 + sv.cur % 3 + dx + 9) % 9, gy = (sv.cur / 27 * 3 + sv.cur % 9 / 3 + dy + 9) % 9;+ sv.cur = (uint8_t)(gy / 3 * 27 + gx / 3 * 9 + gy % 3 * 3 + gx % 3), pick = -1;+ } else if (ok && mv[sv.cur / 9] >> sv.cur % 9 & 1) {+ move(sv.cur);+ }+ }+ if (dirty) {+ eadk_display_wait_for_vblank();+ gfx_render(scene, 0, 0, SCREEN_H);+ dirty = false;+ } else {+ eadk_timing_msleep(20);+ }+ }+ save();+ gfx_buf = their_strip;+ return np_app_end();+}diff --git a/games/uttt/src/rules.h b/games/uttt/src/rules.hnew file mode 100644index 00000000..7b0fb2e6--- /dev/null+++ b/games/uttt/src/rules.h@@ -0,0 +1,127 @@+/* Ultimate Tic-Tac-Toe's rules and the computer's search, apart from the screen (tests/check.c+ * plays them on a computer).+ *+ * A position is each player's marks in each small board, 9 bits a board (bit 3 row + column),+ * the small boards each has won and the ones that are over, won or full. The cell you take sends+ * the other player to the small board in the same place; if that one is over, they play anywhere.+ * Three small boards in a row win; all nine over without that is a draw.+ *+ * The includer defines search_stop(), true when the search must end now (out of time, or Home),+ * and rnd(), random numbers. */+#include <stdbool.h>+#include <stdint.h>++typedef struct {+ uint16_t mark[2][9];+ uint16_t won[2], over;+ int8_t next; /* the small board to play in, -1 for any */+ uint8_t turn; /* 0 X, 1 O */+} pos_t;++static const uint16_t LINES[8] = {0007, 0070, 0700, 0111, 0222, 0444, 0421, 0124};+/* the value of a place, the middle above the corners above the edges */+static const int8_t PLACE[9] = {3, 2, 3, 2, 4, 2, 3, 2, 3};++static bool three(unsigned m) {+ for (int i = 0; i < 8; i++)+ if ((m & LINES[i]) == LINES[i]) return true;+ return false;+}++/* the cells the player to move may take, as a mask per small board; how many */+static int legal(const pos_t *p, uint16_t *mv) {+ int n = 0;+ for (int b = 0; b < 9; b++) {+ mv[b] = (p->over >> b & 1) || (p->next >= 0 && p->next != b) ? 0 : ~(p->mark[0][b] | p->mark[1][b]) & 0777;+ n += __builtin_popcount(mv[b]);+ }+ return n;+}++static void play(pos_t *p, int m) {+ int t = p->turn, b = m / 9, c = m % 9;+ uint16_t *k = &p->mark[t][b];+ *k |= (uint16_t)(1 << c);+ if (three(*k)) p->won[t] |= (uint16_t)(1 << b);+ if (three(*k) || (p->mark[0][b] | p->mark[1][b]) == 0777) p->over |= (uint16_t)(1 << b);+ p->next = (int8_t)(p->over >> c & 1 ? -1 : c);+ p->turn ^= 1;+}++/* 0 the game goes on, 1 X has won, 2 O has, 3 a draw */+static int result(const pos_t *p) {+ return three(p->won[0]) ? 1 : three(p->won[1]) ? 2 : p->over == 0777 ? 3 : 0;+}++/* ------------------------------------------------------------ the computer */+/* X's lines still open on a board (x, o: the marks or boards won, dead: the places neither can use),+ the more of a line taken the better, less O's */+static int lines(unsigned x, unsigned o, unsigned dead, int k) {+ int s = 0;+ for (int i = 0; i < 8; i++) {+ unsigned L = LINES[i];+ int nx = __builtin_popcount(x & L), no = __builtin_popcount(o & L);+ if (!((o | dead) & L)) s += nx * nx * k;+ if (!((x | dead) & L)) s -= no * no * k;+ }+ return s;+}+/* How good the position looks for the player to move: small boards won, in good places, the+ lines still open on the big board and in each small one, and a free move. */+static int eval(const pos_t *p) {+ int s = lines(p->won[0], p->won[1], p->over & ~(p->won[0] | p->won[1]), 24);+ for (int b = 0; b < 9; b++) {+ int w = PLACE[b];+ if (p->won[0] >> b & 1) s += 30 * w;+ else if (p->won[1] >> b & 1) s -= 30 * w;+ else if (!(p->over >> b & 1)) s += lines(p->mark[0][b], p->mark[1][b], 0, w);+ }+ if (p->turn) s = -s;+ return p->next < 0 ? s + 20 : s;+}++#define WIN 100000+static bool stopped;+static int nodes, noise, best_move;++/* Negamax with alpha-beta: what the position is worth to the player to move, depth moves ahead.+ At the root (ply 0) the boards are tried from a random one, so that moves as good as each other+ take turns, and with noise every move is weighed exactly and given up to that much either way. */+static int search(const pos_t *p, int depth, int alpha, int beta, int ply) {+ int r = result(p);+ if (r) return r == 3 ? 0 : ply - WIN; /* only the player who just moved can have won */+ if (!depth) return eval(p);+ if (!(++nodes & 511) && search_stop()) stopped = true;+ if (stopped) return 0;+ uint16_t mv[9];+ legal(p, mv);+ for (int i = 0, b0 = ply ? 0 : (int)(rnd() % 9); i < 9; i++) {+ int b = (b0 + i) % 9;+ for (unsigned m = mv[b]; m; m &= m - 1) {+ pos_t q = *p;+ int k = b * 9 + __builtin_ctz(m);+ play(&q, k);+ int v = -search(&q, depth - 1, -beta, ply || !noise ? -alpha : 2 * WIN, ply + 1);+ if (!ply && noise) v += (int)(rnd() % (unsigned)(2 * noise + 1)) - noise;+ if (v > alpha) {+ alpha = v;+ if (!ply) best_move = k;+ if (alpha >= beta) return alpha;+ }+ }+ }+ return alpha;+}++/* The computer's move: searches 1, 2... up to `depth` moves ahead while search_stop() allows */+static int think(const pos_t *p, int depth, int n) {+ int best = 0;+ noise = n, stopped = false, nodes = 0;+ for (int d = 1; d <= depth; d++) {+ int v = search(p, d, -2 * WIN, 2 * WIN, 0);+ if (stopped && d > 1) break; /* (a depth not searched to the end: the one before stands) */+ best = best_move;+ if (v > WIN / 2 || v < -WIN / 2) break;+ }+ return best;+}diff --git a/games/uttt/tests/check.c b/games/uttt/tests/check.cnew file mode 100644index 00000000..5a4126f1--- /dev/null+++ b/games/uttt/tests/check.c@@ -0,0 +1,183 @@+/* Ultimate Tic-Tac-Toe's rules and computer, checked on a computer (make test):+ * - the rules on hand-made positions: where a move sends the other player, a small board won or full,+ * the big board won, a draw;+ * - thousands of random games: every move legal, the game always ends, never more than 81 moves;+ * - the computer at every level only ever plays legal moves, takes a win in one, never hands one+ * over, and the levels beat each other in order: hard over normal over easy over random. */+#include <stdbool.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <time.h>++static long budget;+static long ticks;+static bool search_stop(void) { return ++ticks > budget; }+static uint32_t seed = 12345;+static uint32_t rnd(void) {+ seed ^= seed << 13;+ seed ^= seed >> 17;+ return seed ^= seed << 5;+}+#include "../src/rules.h"++static int fails;+#define CHECK(c, ...) \+ do { \+ if (!(c)) { \+ fails++; \+ printf("FAIL %s:%d ", __FILE__, __LINE__); \+ printf(__VA_ARGS__); \+ printf("\n"); \+ } \+ } while (0)++static int random_move(const pos_t *p) {+ uint16_t mv[9];+ int n = legal(p, mv), k = (int)(rnd() % (unsigned)n);+ for (int b = 0; b < 9; b++)+ for (unsigned m = mv[b]; m; m &= m - 1)+ if (!k--) return b * 9 + __builtin_ctz(m);+ return -1;+}+static bool is_legal(const pos_t *p, int m) {+ uint16_t mv[9];+ legal(p, mv);+ return m >= 0 && m < 81 && (mv[m / 9] >> m % 9 & 1);+}+/* the computer's move at a level, as src/main.c sets them: 1 easy, 2 normal, 3 hard; the search+ may go on `calls` times 512 nodes */+static int cpu(const pos_t *p, int level, long calls) {+ static const int depth[4] = {0, 1, 3, 30}, noise[4] = {0, 90, 10, 0};+ ticks = 0, budget = calls;+ return think(p, depth[level], noise[level]);+}++static void rules(void) {+ pos_t p = {.next = -1};+ uint16_t mv[9];+ CHECK(legal(&p, mv) == 81, "81 moves to start");+ play(&p, 4 * 9 + 2); /* X in the middle board, top right cell: O goes to the top right board */+ CHECK(p.next == 2 && p.turn == 1, "sent to board 2");+ CHECK(legal(&p, mv) == 9 && mv[2] == 0777, "9 moves in board 2");+ /* O wins the top left board with its bottom row, X sending O back there each time */+ p = (pos_t){.next = -1};+ int seq[] = {0 * 9 + 0, 0 * 9 + 8, 8 * 9 + 0, 0 * 9 + 7, 7 * 9 + 0, 0 * 9 + 6};+ for (int i = 0; i < 6; i++) {+ CHECK(is_legal(&p, seq[i]), "move %d legal", i);+ play(&p, seq[i]);+ }+ CHECK(p.won[1] == 1 && p.won[0] == 0 && p.over == 1, "O has board 0: %o %o", p.won[0], p.won[1]);+ CHECK(p.next == 6 && !is_legal(&p, 0 * 9 + 1), "X sent to board 6, board 0 closed");+ p = (pos_t){.next = -1};+ p.mark[0][0] = 0003, p.turn = 0, p.next = 0;+ play(&p, 2);+ CHECK(p.won[0] == 1 && (p.over & 1), "X wins board 0");+ CHECK(p.next == 2, "sent to board 2: %d", p.next);+ /* sent to a board that is over: anywhere */+ p = (pos_t){.next = 3};+ p.over = 1, p.won[1] = 1, p.mark[1][0] = 0007;+ play(&p, 3 * 9 + 0);+ CHECK(p.next == -1, "board 0 over: a free move");+ CHECK(legal(&p, mv) == 81 - 9 - 1, "free move: every board but 0, %d", legal(&p, mv));+ /* a full board with no line is over but won by nobody */+ p = (pos_t){.next = 5, .turn = 1};+ p.mark[0][5] = 0b011100101, p.mark[1][5] = 0b100011000; /* O fills the last cell, 1: no line */+ int c = __builtin_ctz(~(p.mark[0][5] | p.mark[1][5]) & 0777);+ play(&p, 5 * 9 + c);+ CHECK((p.over >> 5 & 1) && !(p.won[0] >> 5 & 1) && !(p.won[1] >> 5 & 1), "board 5 full, nobody's: %o %o",+ p.mark[0][5], p.mark[1][5]);+ /* the big board: three in a row wins, a full one without is a draw */+ p = (pos_t){.next = -1};+ p.won[1] = 0124, p.over = 0124;+ CHECK(result(&p) == 2, "O wins on the diagonal");+ p.won[1] = 0, p.won[0] = 0, p.over = 0777;+ CHECK(result(&p) == 3, "draw");+}++static void random_games(void) {+ for (int g = 0; g < 20000; g++) {+ pos_t p = {.next = -1};+ int n = 0;+ while (!result(&p)) {+ int m = random_move(&p);+ CHECK(is_legal(&p, m), "random move legal");+ play(&p, m);+ CHECK(++n <= 81, "more than 81 moves");+ if (n > 81) break;+ }+ /* what result() says matches the marks */+ uint16_t won[2] = {0, 0};+ for (int b = 0; b < 9; b++)+ for (int t = 0; t < 2; t++)+ if (three(p.mark[t][b])) won[t] |= (uint16_t)(1 << b);+ CHECK((won[0] & won[1]) == 0, "a board won twice");+ CHECK(won[0] == p.won[0] && won[1] == p.won[1], "won boards kept right");+ }+}++/* a game between two levels (0: random), the hard one searching `calls` x 512 nodes a move; 1 if X+ wins, 2 if O does, 3 a draw */+static int match(int x, int o, long calls) {+ pos_t p = {.next = -1};+ while (!result(&p)) {+ int lv = p.turn ? o : x, m = lv ? cpu(&p, lv, lv == 3 ? calls : 1 << 30) : random_move(&p);+ CHECK(is_legal(&p, m), "level %d played an illegal move %d", lv, m);+ if (!is_legal(&p, m)) return 0;+ play(&p, m);+ }+ return result(&p);+}+/* the games a wins against b, playing X then O, `rounds` times */+static int duel(int a, int b, int rounds, long calls) {+ int w = 0;+ for (int i = 0; i < rounds; i++) w += (match(a, b, calls) == 1) + (match(b, a, calls) == 2);+ return w;+}++static void computer(void) {+ /* a win in one: X has two in the top row of board 0 and the boards 1 and 2 won */+ for (int lv = 1; lv <= 3; lv++) {+ pos_t p = {.next = 0};+ p.mark[0][0] = 0003, p.won[0] = 0006, p.over = 0006, p.mark[0][1] = 0007, p.mark[0][2] = 0007;+ p.mark[1][0] = 0300, p.mark[1][3] = 0001;+ int m = cpu(&p, lv, 100);+ CHECK(m == 2, "level %d misses the win: %d", lv, m);+ }+ /* no win in one handed over: O to play in board 0, where X threatens the top row and owns boards 1+ and 2. Sending X to a board that is over (1 or 2) or to board 0 would let X win. */+ for (int lv = 2; lv <= 3; lv++) {+ pos_t p = {.next = 0, .turn = 1};+ p.mark[0][0] = 0003, p.won[0] = 0006, p.over = 0006, p.mark[0][1] = 0007, p.mark[0][2] = 0007;+ p.mark[1][0] = 0100, p.mark[1][4] = 0001, p.mark[1][5] = 0020;+ int m = cpu(&p, lv, 100);+ CHECK(is_legal(&p, m), "level %d illegal: %d", lv, m);+ play(&p, m);+ uint16_t mv[9];+ legal(&p, mv);+ for (int b = 0; b < 9; b++)+ for (unsigned k = mv[b]; k; k &= k - 1) {+ pos_t q = p;+ play(&q, b * 9 + __builtin_ctz(k));+ CHECK(result(&q) != 1, "level %d plays %d and X wins with %d", lv, m, b * 9 + __builtin_ctz(k));+ }+ }+ /* each level beats the one below (hard with a small search, so that the check stays quick) */+ int er = duel(1, 0, 5, 0), nr = duel(2, 0, 5, 0), ne = duel(2, 1, 5, 0), hn = duel(3, 2, 3, 8);+ printf("out of 10: easy beat random %d, normal random %d, normal easy %d; out of 6: hard normal %d\n", er, nr, ne,+ hn);+ CHECK(er >= 8 && nr >= 9 && ne >= 8 && hn >= 5, "a level doesn't beat the one below");+ /* how fast: a hard move from the start, 200 x 512 nodes */+ clock_t t0 = clock();+ pos_t p = {.next = -1};+ cpu(&p, 3, 200);+ printf("%d nodes in %.2f s here\n", nodes, (double)(clock() - t0) / CLOCKS_PER_SEC);+}++int main(void) {+ rules();+ random_games();+ computer();+ printf(fails ? "%d FAILED\n" : "all checks passed\n", fails);+ return fails != 0;+}diff --git a/games/uttt/tools/icon.py b/games/uttt/tools/icon.pynew file mode 100644index 00000000..c15616e5--- /dev/null+++ b/games/uttt/tools/icon.py@@ -0,0 +1,38 @@+#!/usr/bin/env python3+"""Draws src/icon.png (55 x 56): the big board, X on the diagonal through its middle, O in a corner.++Usage: python3 tools/icon.py (from games/uttt)"""+from PIL import Image, ImageDraw++S = 8 # drawn 8 times bigger, then scaled down smoothly+W, H = 55, 56+NAVY, PLATE, SQUARE = (22, 26, 51), (46, 54, 94), (78, 89, 145)+RED, BLUE = (255, 77, 109), (62, 197, 255)+++def mix(a, b, t):+ return tuple(round(x * t + y * (1 - t)) for x, y in zip(a, b))+++im = Image.new("RGBA", (W * S, H * S), (0, 0, 0, 0))+d = ImageDraw.Draw(im)+d.rounded_rectangle((0, 0, W * S - 1, H * S - 1), radius=12 * S, fill=NAVY)+pitch, size, x0, y0 = 16, 14, 5, 5.5+for b in range(9):+ bx, by = (x0 + b % 3 * pitch) * S, (y0 + b // 3 * pitch) * S+ won = {4: RED, 2: BLUE, 6: RED}.get(b)+ d.rounded_rectangle((bx, by, bx + size * S, by + size * S), radius=3 * S, fill=mix(won, PLATE, 0.35) if won else PLATE)+ if won == RED:+ t = 2.2 * S+ for a, c in (((bx + 3.5 * S, by + 3.5 * S), (bx + 10.5 * S, by + 10.5 * S)),+ ((bx + 3.5 * S, by + 10.5 * S), (bx + 10.5 * S, by + 3.5 * S))):+ d.line((a, c), fill=RED, width=round(t))+ for p in (a, c):+ d.ellipse((p[0] - t / 2, p[1] - t / 2, p[0] + t / 2, p[1] + t / 2), fill=RED)+ elif won == BLUE:+ d.ellipse((bx + 2.5 * S, by + 2.5 * S, bx + 11.5 * S, by + 11.5 * S), outline=BLUE, width=round(2.2 * S))+ else: # its nine cells+ for c in range(9):+ cx, cy = bx + (1.5 + c % 3 * 4) * S, by + (1.5 + c // 3 * 4) * S+ d.rounded_rectangle((cx, cy, cx + 3 * S, cy + 3 * S), radius=S, fill=SQUARE)+im.resize((W, H), Image.LANCZOS).save("src/icon.png")diff --git a/launcher/lang/fr.txt b/launcher/lang/fr.txtindex bd8a8922..680be2d1 100644--- a/launcher/lang/fr.txt+++ b/launcher/lang/fr.txt@@ -100,6 +100,8 @@ Pong and more, side by side Pong et plus, côte à côteCookie Clicker Cookie ClickerClick the cookie, bake billions Clique le cookie, cuis des milliardsFill the grid, 1 to 9 Remplis la grille, de 1 à 9+Ultimate Tic-Tac-Toe Morpion ultime+Tic-tac-toe in tic-tac-toe Un morpion dans le morpionBackgrounds, clocks, timers Fonds, horloges, minuteursReach the door, trust nothing Atteins la porte, ne te fie à rienStop the invasion, one cannon Arrête l'invasion avec un seul canondiff --git a/launcher/lang/zh.txt b/launcher/lang/zh.txtindex 50857471..c1a964ce 100644--- a/launcher/lang/zh.txt+++ b/launcher/lang/zh.txt@@ -100,6 +100,8 @@ Cookie Clicker Cookie ClickerClick the cookie, bake billions 点击饼干,烤出亿万饼干Sudoku 数独Fill the grid, 1 to 9 填满九宫格,1 到 9+Ultimate Tic-Tac-Toe 终极井字棋+Tic-tac-toe in tic-tac-toe 井字棋里的井字棋Backgrounds, clocks, timers 背景、时钟、计时器Reach the door, trust nothing 走到门口,什么都别相信Space Invaders 太空侵略者diff --git a/tests/test_games.py b/tests/test_games.pyindex a0616e5f..abca373c 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -122,6 +122,10 @@ GAMES = {# past how to play, an Easy puzzle made, two hints; next time the game goes on: one more"sudoku": ("Sudoku.nwa", "sudoku.sav", presses((1500, "ok"), (2000, "ok"), (3500, "shift"), (4000, "shift")), 5500,presses((1500, "shift")), 3000),+ # past how to play, X in the middle of the middle board (5, 5), O sent there takes its top left (7);+ # 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),# 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",@@ -307,6 +311,9 @@ CHECKS = {# the best score ("I", version 1, the best at 4): some invaders shot; then kept, or beaten"invaders": (lambda v: len(v) == 8 and v[:2] == b"I\1" and struct.unpack_from("<I", v, 4)[0] >= 20,lambda v: len(v) == 8 and v[:2] == b"I\1" and struct.unpack_from("<I", v, 4)[0] >= 20),+ # 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),"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