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
Imposter: the party game, played by passing one calculator around
Mason363df0c034581c5
diff --git a/games/imposter/.gitignore b/games/imposter/.gitignorenew file mode 100644index 00000000..643bd909--- /dev/null+++ b/games/imposter/.gitignore@@ -0,0 +1,3 @@+output/+build/+__pycache__/diff --git a/games/imposter/Makefile b/games/imposter/Makefilenew file mode 100644index 00000000..5a86699d--- /dev/null+++ b/games/imposter/Makefile@@ -0,0 +1,83 @@+# Imposter on the NumWorks calculator (C), drawn with NumPlay's launcher (launcher/src/gfx.c and its fonts).+# make output/imposter.nwa+# make check link it like the calculator does (output/imposter.bin): RAM and the app space+# make host build/play: the game on a computer, for tests and screenshots+# make test the game played on a computer (tests/check.py, with the sanitizers)+Q ?= @+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded+SIZE = $(BIN)arm-none-eabi-size+BUILD_DIR = output++LAUNCHER = ../../launcher/src+SRC = $(filter-out src/plat_host.c,$(wildcard src/*.c)) $(LAUNCHER)/gfx.c $(LAUNCHER)/font_data.c $(LAUNCHER)/xfont.c+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h \+ $(LAUNCHER)/gfx.h $(LAUNCHER)/np.h $(LAUNCHER)/font.h++CFLAGS = -std=gnu11 $(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+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)+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+build: $(BUILD_DIR)/imposter.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones); installed on its+# own, the app must fit the calculator's space for apps (0x90200000 to 0x903F0000 in its flash)+RAM_LENGTH = 133652+APP_SPACE = 2031616+check: $(BUILD_DIR)/imposter.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length $(RAM_LENGTH) $< $(BUILD_DIR)/imposter.bin+ @n=$$(wc -c < $(BUILD_DIR)/imposter.bin); \+ echo "BIN $(BUILD_DIR)/imposter.bin: $$n bytes, $$(( $(APP_SPACE) - n )) to spare of the app space"; \+ [ $$n -le $(APP_SPACE) ] || { echo "imposter.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }++# compiled, then linked (the link options would upset the compiler)+OBJ = $(patsubst %.c,$(BUILD_DIR)/obj/%.o,$(notdir $(SRC)))+vpath %.c src $(LAUNCHER)+$(BUILD_DIR)/obj/%.o: %.c $(HEADERS)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -c $< -o $@++$(BUILD_DIR)/imposter.nwa: $(OBJ) $(BUILD_DIR)/icon.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(OBJ) $(BUILD_DIR)/icon.o -o $@+ $(Q) $(STRIP) $@+ $(Q) $(SIZE) $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++# on a computer: tests/play.c plays it with scripted keys and saves screenshots+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined+HOST_SRC = src/game.c src/ui.c src/words.c src/plat_host.c $(LAUNCHER)/gfx.c $(LAUNCHER)/font_data.c $(LAUNCHER)/xfont.c+host: build/play+build/play: $(HOST_SRC) tests/play.c $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c -lm -o $@+ @echo "HOST $@"++test: build/play+ python3 tests/check.py build/play++clean:+ $(Q) rm -rf $(BUILD_DIR) build++# the other targets (platform/port.mk): make port TARGET=sdl, ti84ce, nspire, web...+PORT_ID = imposter+PORT_NAME = Imposter+PORT_SRC = $(filter-out src/plat_host.c,$(wildcard src/*.c)) $(LAUNCHER)/gfx.c $(LAUNCHER)/xfont.c+PORT_FLAGS = -Isrc+include ../../platform/port.mkdiff --git a/games/imposter/src/game.c b/games/imposter/src/game.cnew file mode 100644index 00000000..85e3ad46--- /dev/null+++ b/games/imposter/src/game.c@@ -0,0 +1,229 @@+/* Imposter: the players, the settings, the rounds and the save. */+#include "game.h"+#include <string.h>+#include "plat.h"++save_t sv;+const uint8_t timer_minutes[N_TIMERS] = {0, 1, 2, 3, 5};++#define SAVE_NAME "imposter.sav"+#define COPY_NAME "imposter_saves.py"+#define VERSION 1+#define ALL_CATS (((uint32_t)1 << N_CATS) - 1)++/* ---- chance */+static uint32_t seed = 1;+void rnd_seed(uint32_t s) { seed = s ? s : 0x9E3779B9u; }+uint32_t rnd(void) {+ seed ^= seed << 13;+ seed ^= seed >> 17;+ seed ^= seed << 5;+ return seed;+}+static int rnd_below(int n) { return (int)(rnd() % (uint32_t)n); }++/* ---- the rules */+int max_imposters(int players) { return players >= 7 ? 3 : players >= 5 ? 2 : 1; }+int imposters_now(void) {+ int m = max_imposters(sv.nplayers);+ return sv.imposters < m ? sv.imposters : m;+}+bool cat_on(int c) { return !sv.cats || (sv.cats >> c & 1); }+int cats_chosen(void) {+ int n = 0;+ for (int c = 0; c < N_CATS; c++) n += cat_on(c);+ return n;+}+bool is_imposter(int p) { return sv.imps >> p & 1; }++static bool used(int c, int i) { return sv.used[c * 8 + i / 8] >> (i % 8) & 1; }+static void use(int c, int i) { sv.used[c * 8 + i / 8] |= (uint8_t)(1 << (i % 8)); }+static int unused_count(int c) {+ int n = 0, k = word_count(c);+ for (int i = 0; i < k; i++) n += !used(c, i);+ return n;+}++int word_text(uint16_t w, char *out) {+ int c = w >> 6;+ if (w == NO_WORD || c >= N_CATS) return out[0] = 0, 0;+ word_get(c, w & 63, out, WORD_MAX + 1);+ return c;+}++/* a word of the chosen categories not played yet, every one as likely; a category played through starts again+ * (without the word just played) */+static uint16_t pick_word(void) {+ int total = 0;+ for (int c = 0; c < N_CATS; c++) {+ if (!cat_on(c)) continue;+ if (!unused_count(c)) {+ memset(sv.used + c * 8, 0, 8);+ if (sv.last != NO_WORD && sv.last >> 6 == c) use(c, sv.last & 63);+ }+ total += unused_count(c);+ }+ int r = rnd_below(total);+ for (int c = 0; c < N_CATS; c++) {+ if (!cat_on(c)) continue;+ for (int i = 0, k = word_count(c); i < k; i++)+ if (!used(c, i) && r-- == 0) {+ use(c, i);+ return (uint16_t)(c << 6 | i);+ }+ }+ return 0; /* (never) */+}++void round_new(void) {+ int n = sv.nplayers, k = imposters_now();+ sv.word = pick_word();+ sv.last = sv.word;+ sv.imps = 0;+ while (k) {+ int p = rnd_below(n);+ if (!is_imposter(p)) sv.imps |= (uint16_t)(1 << p), k--;+ }+ sv.starter = (uint8_t)rnd_below(n);+ sv.turn = 0;+ sv.phase = PH_PASS;+ sv.time_left = (uint32_t)timer_minutes[sv.timer] * 60000;+ if (sv.rounds < 0xFFFF) sv.rounds++;+ game_save();+}++void round_end(void) {+ sv.phase = PH_NONE;+ game_save();+}++/* ---- the save, and its copy in a Python script: installing apps from the NumWorks website keeps only scripts */+void game_defaults(void) {+ memset(&sv, 0, sizeof sv);+ sv.imposters = 1, sv.hint = 1;+ sv.word = sv.last = NO_WORD;+}++static const char copy_head[] = "# Imposter's saves: keep this file\n#>" SAVE_NAME ":";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+#define COPY_SIZE (1 + sizeof copy_head - 1 + (sizeof(save_t) + 2) / 3 * 4 + 2)+static uint8_t copy[COPY_SIZE];++static void write_copy(void) {+ const uint8_t *d = (const uint8_t *)&sv;+ uint8_t *p = copy;+ *p++ = 0; /* (a script's first byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ for (uint32_t i = 0; i < sizeof sv; i += 3, p += 4) {+ uint32_t left = (uint32_t)sizeof sv - i;+ uint32_t v = (uint32_t)d[i] << 16 | (uint32_t)(left > 1 ? d[i + 1] : 0) << 8 | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63], p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ *p++ = 0;+ plat_save(COPY_NAME, copy, (uint32_t)(p - copy));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++/* the save in the copy, into out; false if it isn't one */+static bool read_copy(save_t *out) {+ uint32_t n;+ const uint8_t *c = plat_load(COPY_NAME, &n);+ uint32_t head = 1 + sizeof copy_head - 1, len = (sizeof(save_t) + 2) / 3 * 4;+ if (!c || n < head + len || memcmp(c + 1, copy_head, sizeof copy_head - 1)) return false;+ uint8_t *o = (uint8_t *)out;+ uint32_t k = 0;+ for (uint32_t i = 0; i < len; i += 4) {+ const uint8_t *q = c + head + i;+ int v[4];+ for (int j = 0; j < 4; j++) {+ v[j] = q[j] == '=' ? 0 : b64_value(q[j]);+ if (v[j] < 0) return false;+ }+ uint32_t w = (uint32_t)v[0] << 18 | (uint32_t)v[1] << 12 | (uint32_t)v[2] << 6 | (uint32_t)v[3];+ for (int j = 0; j < 3 && k < sizeof(save_t); j++) o[k++] = (uint8_t)(w >> (16 - 8 * j));+ }+ return true;+}++static bool name_ok(const char *s) {+ int n = 0;+ while (n <= NAME_MAX && s[n]) {+ char ch = s[n];+ if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == ' ')) return false;+ n++;+ }+ return n >= 1 && n <= NAME_MAX && s[0] != ' ' && s[n - 1] != ' ';+}++static bool word_ok(uint16_t w) { return w >> 6 < N_CATS && (int)(w & 63) < word_count(w >> 6); }++static bool usable(const save_t *s) {+ return !memcmp(s->magic, "IMPS", 4) && s->version == VERSION;+}++/* whatever the file held: a save this game could have written */+static void sanitize(void) {+ int n = 0;+ int count = sv.nplayers <= MAX_PLAYERS ? sv.nplayers : MAX_PLAYERS;+ bool same = true;+ for (int i = 0; i < count; i++) {+ sv.names[i][NAME_MAX] = 0;+ if (name_ok(sv.names[i])) {+ if (n != i) memcpy(sv.names[n], sv.names[i], NAME_MAX + 1);+ n++;+ } else {+ same = false;+ }+ }+ for (int i = n; i < MAX_PLAYERS; i++) memset(sv.names[i], 0, NAME_MAX + 1);+ sv.nplayers = (uint8_t)n;+ if (sv.imposters < 1 || sv.imposters > 3) sv.imposters = 1;+ if (sv.hint > 1) sv.hint = 1;+ if (sv.timer >= N_TIMERS) sv.timer = 0;+ sv.cats &= ALL_CATS;+ if (sv.cats == ALL_CATS) sv.cats = 0;+ if (sv.last != NO_WORD && !word_ok(sv.last)) sv.last = NO_WORD;+ sv.flags &= 1;+ /* a round in progress, if it still stands */+ int k = 0;+ for (int i = 0; i < MAX_PLAYERS; i++) k += sv.imps >> i & 1;+ if (sv.phase > PH_REVEAL || !same || n < MIN_PLAYERS || !word_ok(sv.word) || sv.imps >> n || k < 1 ||+ k > max_imposters(n) || sv.turn >= n || sv.starter >= n || sv.time_left > 5 * 60000u)+ sv.phase = PH_NONE;+ if (sv.phase == PH_NONE) sv.word = NO_WORD, sv.imps = 0, sv.turn = sv.starter = 0, sv.time_left = 0;+}++void game_load(void) {+ uint32_t n;+ const uint8_t *d = plat_load(SAVE_NAME, &n);+ save_t s;+ if (d && n == sizeof s) {+ memcpy(&s, d, sizeof s);+ if (usable(&s)) {+ sv = s;+ sanitize();+ return;+ }+ }+ if (read_copy(&s) && usable(&s)) {+ sv = s;+ sanitize();+ return;+ }+ game_defaults();+}++void game_save(void) {+ memcpy(sv.magic, "IMPS", 4);+ sv.version = VERSION;+ plat_save(SAVE_NAME, &sv, sizeof sv);+ write_copy();+}diff --git a/games/imposter/src/game.h b/games/imposter/src/game.hnew file mode 100644index 00000000..f14533f9--- /dev/null+++ b/games/imposter/src/game.h@@ -0,0 +1,50 @@+/* Imposter: the players, the settings, the rounds and the save (game.c). */+#ifndef IM_GAME_H+#define IM_GAME_H+#include <stdbool.h>+#include <stdint.h>+#include "words.h"++#define MIN_PLAYERS 3+#define MAX_PLAYERS 12+#define NAME_MAX 10 /* letters */+#define N_TIMERS 5+#define NO_WORD 0xFFFF++/* where a round is */+enum { PH_NONE, PH_PASS, PH_TALK, PH_REVEAL };++/* imposter.sav: everything, written whenever something changes */+typedef struct {+ char magic[4]; /* "IMPS" */+ uint8_t version, nplayers, imposters, hint; /* imposters: the setting (1-3); hint: the imposter sees the category */+ uint8_t timer, phase, turn, starter; /* timer: 0 off, then timer_minutes[]; turn: who sees their role next */+ uint8_t flags, pad[3]; /* flags: 1 How to play was shown */+ uint16_t word, last; /* the round's word, the one before: category * 64 + its number */+ uint16_t imps, rounds; /* the round's imposters (a bit a player) */+ uint32_t cats; /* the categories chosen (a bit each); 0: all */+ uint32_t time_left; /* ms left on the discussion timer */+ char names[MAX_PLAYERS][NAME_MAX + 1];+ uint8_t used[N_CATS * 8]; /* the words already played, 64 bits a category */+} save_t;++extern save_t sv;+extern const uint8_t timer_minutes[N_TIMERS];++void game_load(void);+void game_save(void);+void game_defaults(void);++int max_imposters(int players);+int imposters_now(void); /* the setting, as the players allow */+bool cat_on(int c);+int cats_chosen(void);+bool is_imposter(int p);+int word_text(uint16_t w, char *out); /* the word's text; its category in the result */++/* a round: its word (never one played until its category runs out), its imposters, who starts */+void round_new(void);+void round_end(void);+uint32_t rnd(void);+void rnd_seed(uint32_t s);+#endifdiff --git a/games/imposter/src/icon.png b/games/imposter/src/icon.pngnew file mode 100644index 00000000..d7742e86Binary files /dev/null and b/games/imposter/src/icon.png differdiff --git a/games/imposter/src/main.c b/games/imposter/src/main.cnew file mode 100644index 00000000..2f590b87--- /dev/null+++ b/games/imposter/src/main.c@@ -0,0 +1,32 @@+/* Imposter for the NumWorks calculator (and NumPlay's other targets): the party game played by passing one+ * calculator around.+ *+ * Inspired by the party game Imposter. Made by Mason Chen as part of NumPlay. */+#include "game.h"+#include "plat.h"+#include "ui.h"++#ifndef HOST+uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_max __attribute__((used));++int main(void) {+ plat_begin();+ app_init(plat_millis());+ for (;;) {+ uint32_t letters, keys = plat_keys(&letters);+ if (!app_step(keys, letters, plat_millis())) break;+ if (app_dirty()) {+ plat_vblank();+ uint32_t t0 = plat_millis();+ app_draw();+ uint32_t dt = plat_millis() - t0;+ if (dt > perf_max) perf_max = dt;+ perf_frames++;+ } else {+ plat_sleep(10);+ }+ }+ return plat_end();+}+#endifdiff --git a/games/imposter/src/plat.h b/games/imposter/src/plat.hnew file mode 100644index 00000000..1d24d013--- /dev/null+++ b/games/imposter/src/plat.h@@ -0,0 +1,36 @@+/* Imposter: the platform (the calculator, another target, or a computer for tests).+ *+ * plat_eadk.c: EADK's display, keyboard, time and files (the NumWorks, and every target of platform/).+ * plat_host.c: a frame buffer that tests save as images, scripted keys and simulated time (tests/play.c). */+#ifndef IM_PLAT_H+#define IM_PLAT_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++/* keys held now, as bits */+#define KB_LEFT ((uint32_t)1 << 0)+#define KB_RIGHT ((uint32_t)1 << 1)+#define KB_UP ((uint32_t)1 << 2)+#define KB_DOWN ((uint32_t)1 << 3)+#define KB_OK ((uint32_t)1 << 4) /* OK */+#define KB_EXE ((uint32_t)1 << 5) /* EXE: OK, and Done in the name editor */+#define KB_BACK ((uint32_t)1 << 6) /* Back: menu, back a screen */+#define KB_HOME ((uint32_t)1 << 7) /* Home, On/Off: save and quit */+#define KB_ERASE ((uint32_t)1 << 8) /* Backspace */+#define KB_ANY ((uint32_t)1 << 9) /* any key at all */++/* keys held, and in *letters the letters their keys carry (bit 0 A ... bit 25 Z, bit 26 a space) */+uint32_t plat_keys(uint32_t *letters);+/* the keys carry letters (the NumWorks: alpha + a key types its letter, alpha or not) */+bool plat_typing(void);+uint32_t plat_millis(void);+void plat_sleep(uint32_t ms);+void plat_vblank(void);+uint32_t plat_random(void);+void plat_push(int x, int y, int w, int h, const uint16_t *px);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */+void plat_begin(void);+int plat_end(void);+#endifdiff --git a/games/imposter/src/plat_eadk.c b/games/imposter/src/plat_eadk.cnew file mode 100644index 00000000..627d7760--- /dev/null+++ b/games/imposter/src/plat_eadk.c@@ -0,0 +1,61 @@+/* EADK: the NumWorks's display, keyboard, time and files, which every target of platform/ also gives. */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "plat.h"++#ifndef NP_PORT /* (another target: platform/port.mk names the app) */+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Imposter";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+#endif++#define KEY(k) ((uint64_t)1 << (k))++/* the letters printed over the NumWorks's keys, A on exp to Z on +, a space on - */+static const uint8_t letter_keys[27] = {+ eadk_key_exp, eadk_key_ln, eadk_key_log, eadk_key_imaginary, eadk_key_comma, eadk_key_power,+ eadk_key_sine, eadk_key_cosine, eadk_key_tangent, eadk_key_pi, eadk_key_sqrt, eadk_key_square,+ eadk_key_seven, eadk_key_eight, eadk_key_nine, eadk_key_left_parenthesis, eadk_key_right_parenthesis,+ eadk_key_four, eadk_key_five, eadk_key_six, eadk_key_multiplication, eadk_key_division,+ eadk_key_one, eadk_key_two, eadk_key_three, eadk_key_plus, eadk_key_minus};++/* (another target's keys carry other letters, or none: names are typed on the screen's letters there) */+bool plat_typing(void) {+#ifdef NP_PORT+ return false;+#else+ return true;+#endif+}++uint32_t plat_keys(uint32_t *letters) {+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0, l = 0;+ if (k & KEY(eadk_key_left)) r |= KB_LEFT;+ if (k & KEY(eadk_key_right)) r |= KB_RIGHT;+ if (k & KEY(eadk_key_up)) r |= KB_UP;+ if (k & KEY(eadk_key_down)) r |= KB_DOWN;+ if (k & KEY(eadk_key_ok)) r |= KB_OK;+ if (k & KEY(eadk_key_exe)) r |= KB_EXE;+ if (k & KEY(eadk_key_back)) r |= KB_BACK;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= KB_HOME;+ if (k & KEY(eadk_key_backspace)) r |= KB_ERASE;+ if (k) r |= KB_ANY;+ if (plat_typing())+ for (int i = 0; i < 27; i++)+ if (k & KEY(letter_keys[i])) l |= (uint32_t)1 << i;+ *letters = l;+ return r;+}++uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }+void plat_vblank(void) { eadk_display_wait_for_vblank(); }+uint32_t plat_random(void) { return eadk_random(); }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);+}+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }diff --git a/games/imposter/src/plat_host.c b/games/imposter/src/plat_host.cnew file mode 100644index 00000000..cf4cd6a7--- /dev/null+++ b/games/imposter/src/plat_host.c@@ -0,0 +1,70 @@+/* A computer: the screen goes to a frame buffer that tests save as images, keys come from a script, time is+ * simulated, files are in a folder. */+#include <stdio.h>+#include <stdlib.h>+#include "plat.h"++#define W 320+#define H 240+uint16_t host_fb[W * H];+uint32_t host_time; /* ms */+uint32_t host_keys, host_letters, host_seed = 1;+bool host_typing = true;++uint32_t plat_keys(uint32_t *letters) {+ *letters = host_typing ? host_letters : 0;+ return host_keys | (host_keys || *letters ? KB_ANY : 0);+}+bool plat_typing(void) { return host_typing; }+uint32_t plat_millis(void) { return host_time; }+void plat_sleep(uint32_t ms) { host_time += ms; }+void plat_vblank(void) {}+uint32_t plat_random(void) {+ host_seed ^= host_seed << 13, host_seed ^= host_seed >> 17, host_seed ^= host_seed << 5;+ return host_seed;+}+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ for (int r = 0; r < h; r++)+ for (int c = 0; c < w; c++)+ if ((unsigned)(x + c) < W && (unsigned)(y + r) < H) host_fb[(y + r) * W + x + c] = px[r * w + c];+}++static char save_dir[256] = "build/host-saves";+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }+bool plat_save(const char *name, const void *data, uint32_t len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "wb");+ if (!f) return false;+ bool ok = fwrite(data, 1, len, f) == len;+ fclose(f);+ return ok;+}+/* (each file read gets its own buffer: callers may hold two at once) */+static uint8_t loaded[4][1 << 14];+static int next_load;+const uint8_t *plat_load(const char *name, uint32_t *len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "rb");+ if (!f) return NULL;+ uint8_t *b = loaded[next_load++ & 3];+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);+ fclose(f);+ return b;+}+void plat_begin(void) {}+int plat_end(void) { return 0; }++/* writes the screen as a PPM image */+void host_shot(const char *path) {+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6\n%d %d\n255\n", W, H);+ for (int i = 0; i < W * H; i++) {+ uint16_t c = host_fb[i];+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};+ fwrite(rgb, 1, 3, f);+ }+ fclose(f);+}diff --git a/games/imposter/src/ui.c b/games/imposter/src/ui.cnew file mode 100644index 00000000..59a27363--- /dev/null+++ b/games/imposter/src/ui.c@@ -0,0 +1,846 @@+/* Imposter: the screens, drawn in strips with NumPlay's launcher (launcher/src/gfx.c and its Nunito fonts), and+ * what the keys do on each. */+#include "ui.h"+#include <string.h>+#include "../../../launcher/src/gfx.h"+#include "game.h"+#include "plat.h"+#ifdef HOST+#include <stdio.h>+extern int host_trace;+#endif++/* the launcher's drawing sends its strips here */+void np_push(int x, int y, int w, int h, const color_t *px) { plat_push(x, y, w, h, px); }+void *np_alloc(uint32_t size) { /* (gfx_init's: never called, the strip is ours) */+ (void)size;+ return 0;+}+static color_t strip[SCREEN_W * STRIP_H];++#define WHITE 0xFFFF+#define GOLD HEX(0xFFC83D)+#define INK HEX(0x171B3D) /* text on gold */+#define SOFT HEX(0xB4BCE8) /* quieter text */+#define CARD HEX(0x2C3570)+#define CARD_ON HEX(0x3D4894)+#define BAR HEX(0x0B0E22)+#define RED_TEXT HEX(0xFF6F6F)+#define BG_TOP 0x262D5E+#define BG_BOT 0x10142B+#define KEY_Y 222 /* the key line */++enum { SC_HELP, SC_SETUP, SC_PLAYERS, SC_NAME, SC_CATS, SC_PASS, SC_ROLE, SC_TALK, SC_REVEAL };+enum { DL_NONE, DL_PAUSE, DL_QUIT, DL_REVEAL, DL_REMOVE };+enum { ROW_START, ROW_PLAYERS, ROW_CATS, ROW_IMPS, ROW_HINT, ROW_TIMER, ROW_HELP, ROW_QUIT, N_ROWS };++static struct {+ int screen, dialog, dsel, dialog_back, help_back;+ int setup_sel, players_sel, cats_sel, cats_top;+ int name_idx, name_len, gr, gc; /* the name being typed; the letter chosen on the screen (row, column) */+ bool name_new, dirty;+ char name[NAME_MAX + 1];+ uint32_t cmask; /* the categories ticked on their screen */+ uint32_t now, msg_until, prev_keys, prev_letters, stale, repeat_at;+ uint32_t guard_until; /* a role shows, or the next player is named: OK waits a moment (a double press) */+ int shown_sec;+} u;++/* ------------------------------------------------------------ text */+static char *num(char *o, int v) { /* v in o; the end of it */+ char t[8];+ int n = 0;+ do t[n++] = (char)('0' + v % 10); while (v /= 10);+ while (n) *o++ = t[--n];+ *o = 0;+ return o;+}+static char *cat(char *o, const char *s) {+ while (*s) *o++ = *s++;+ *o = 0;+ return o;+}++/* ---- big letters: the title font scaled, each pixel sampled between the font's own and sharpened */+#define BIG (&np_font_title)+static const np_glyph_t *glyph_of(char ch) {+ unsigned i = (unsigned)(uint8_t)ch - BIG->first;+ return &BIG->glyphs[i < BIG->count ? i : (unsigned)('?' - BIG->first)];+}+static int width1(const char *s, int n) { /* at the font's size */+ int w = 0;+ for (int i = 0; i < n; i++) w += glyph_of(s[i])->advance;+ return w;+}+static int cap_height(void) { return -glyph_of('H')->y; }++static int cov_at(const uint8_t *d, int w, int h, int i, int j) {+ if ((unsigned)i >= (unsigned)w || (unsigned)j >= (unsigned)h) return 0;+ int n = j * w + i;+ return (d[n >> 1] >> ((n & 1) * 4)) & 15;+}++/* Catmull-Rom's weights at t (in 1/256), in 1/256 */+static void cubic(int t, int32_t *w) {+ int32_t t2 = (int32_t)t * t >> 8, t3 = t2 * t >> 8;+ w[0] = (-t3 + 2 * t2 - t) / 2;+ w[1] = (3 * t3 - 5 * t2 + 512) / 2;+ w[2] = (-3 * t3 + 4 * t2 + t) / 2;+ w[3] = 256 - w[0] - w[1] - w[2];+}++#ifndef BIG_SHARP+#define BIG_SHARP 2+#endif+/* n letters of s, s256/256 times the font's size, from x on the baseline: each pixel the font's coverage+ * between its pixels (bicubic), sharpened as much as the letters grow */+static void big_run(const char *s, int n, int x, int base, int s256, color_t c) {+ int32_t pen = (int32_t)x * 256; /* in 1/256 pixels */+ int32_t du = (int32_t)(((uint32_t)1 << 24) / (uint32_t)s256); /* the font's 1/65536 pixels a screen pixel */+ int sharp = 16 + (s256 - 256) * BIG_SHARP / 64; /* (in 1/16) */+ for (int k = 0; k < n; k++) {+ const np_glyph_t *g = glyph_of(s[k]);+ if (g->w) {+ const uint8_t *d = BIG->data + g->offset;+ int gw = g->w, gh = g->h;+ int32_t gx = pen + (int32_t)g->x * s256, gy = (int32_t)base * 256 + (int32_t)g->y * s256;+ int x0 = (int)((gx - s256) >> 8), x1 = (int)((gx + (int32_t)(gw + 1) * s256) >> 8) + 1;+ int y0 = (int)((gy - s256) >> 8), y1 = (int)((gy + (int32_t)(gh + 1) * s256) >> 8) + 1;+ if (y0 < gfx_y0) y0 = gfx_y0;+ if (y1 > gfx_y1) y1 = gfx_y1;+ if (x0 < 0) x0 = 0;+ if (x1 > SCREEN_W) x1 = SCREEN_W;+ for (int Y = y0; Y < y1; Y++) {+ int32_t v = ((int32_t)Y * 256 + 128 - gy) * 256 / s256 - 128; /* in the font's 1/256 pixels */+ int j = (int)(v >> 8);+ int32_t wy[4], wx[4];+ cubic((int)(v & 255), wy);+ int32_t uu = (int32_t)(((int32_t)x0 * 256 + 128 - gx) * (int32_t)65536 / s256) - 32768;+ color_t *p = gfx_buf + (Y - gfx_y0) * SCREEN_W;+ for (int X = x0; X < x1; X++, uu += du) {+ int i = (int)(uu >> 16);+ cubic((int)((uu >> 8) & 255), wx);+ int32_t val = 0;+ for (int r = 0; r < 4; r++) {+ int jj = j - 1 + r;+ if ((unsigned)jj >= (unsigned)gh) continue;+ int32_t row = 0;+ for (int q = 0; q < 4; q++) row += wx[q] * cov_at(d, gw, gh, i - 1 + q, jj);+ val += row * wy[r];+ }+ val >>= 8; /* 0 to 3840, a little past at the edges */+ if (val <= 0) continue;+ val = ((val - 1920) * sharp >> 4) + 1920;+ if (val <= 0) continue;+ int a = val >= 3840 ? 32 : (int)((val + 60) / 120);+ p[X] = gfx_mix(p[X], c, a);+ }+ }+ }+ pen += (int32_t)g->advance * s256;+ }+}++/* s as big as it goes (s256max at most) in a box maxw wide and maxh high, on one line or two, its middle at+ * (cx, cy) */+static void big_text(const char *s, int cx, int cy, int maxw, int maxh, int smax, color_t c) {+ int n = (int)strlen(s), lh = BIG->ascent + BIG->descent, w = width1(s, n), cap = cap_height();+ if (!w) return;+ int s1 = smax;+ if (maxw * 256 / w < s1) s1 = maxw * 256 / w;+ if (maxh * 256 / lh < s1) s1 = maxh * 256 / lh;+ /* two lines, split at the space that evens them best */+ int split = -1, best = 1 << 20;+ for (int k = 1; k < n - 1; k++)+ if (s[k] == ' ') {+ int a = width1(s, k), b = width1(s + k + 1, n - k - 1), m = a > b ? a : b;+ if (m < best) best = m, split = k;+ }+ if (split > 0) {+ int s2 = smax, gap = lh + cap; /* (two baselines apart, and the lines) */+ if (maxw * 256 / best < s2) s2 = maxw * 256 / best;+ if (maxh * 256 / gap < s2) s2 = maxh * 256 / gap;+ if (s2 > s1 * 9 / 8) {+ int step = (lh - 2) * s2 / 256, b0 = cy - step / 2 + cap * s2 / 512;+ int wa = width1(s, split) * s2 / 256, wb = width1(s + split + 1, n - split - 1) * s2 / 256;+ big_run(s, split, cx - wa / 2, b0, s2, c);+ big_run(s + split + 1, n - split - 1, cx - wb / 2, b0 + step, s2, c);+ return;+ }+ }+ big_run(s, n, cx - w * s1 / 256 / 2, cy + cap * s1 / 512, s1, c);+}++/* ---- the pieces of every screen */+static void background(uint32_t top, uint32_t bottom) { gfx_vgrad(0, 0, SCREEN_W, SCREEN_H, top, bottom); }++/* the keys at the bottom: key, what it does, key, what it does... */+static void keyline(const char *const *p) {+ if (gfx_y1 <= KEY_Y) return;+ gfx_fill(0, KEY_Y, SCREEN_W, SCREEN_H - KEY_Y, BAR);+ const np_font_t *f = &np_font_small;+ int w = 0;+ for (int i = 0; p[i]; i += 2)+ w += (i ? 16 : 0) + (p[i][0] ? gfx_text_width(f, p[i]) + 5 : 0) + gfx_text_width(f, p[i + 1]);+ int x = SCREEN_W / 2 - w / 2;+ for (int i = 0; p[i]; i += 2) {+ if (i) x += 16;+ if (p[i][0]) x = gfx_text(f, x, KEY_Y + 13, p[i], GOLD, 256) + 5;+ x = gfx_text(f, x, KEY_Y + 13, p[i + 1], SOFT, 256);+ }+}+#define KEYS(...) keyline((const char *const[]){__VA_ARGS__, 0})++static void heading(const char *s) { gfx_text_center(&np_font_title, SCREEN_W / 2, 27, s, WHITE, 256); }++static void button(int x, int y, int w, int h, const char *s, bool on) {+ gfx_rrect(x, y, w, h, h * 2 / 5, on ? GOLD : CARD, 256);+ gfx_text_center(&np_font_title, x + w / 2, y + h / 2 + 7, s, on ? INK : WHITE, 256);+}++/* the frame round what's chosen in a list */+static void focus(int x, int y, int w, int h, int r) {+ gfx_rrect(x, y, w, h, r, CARD_ON, 256);+ gfx_rrect_outline(x, y, w, h, r, 2, GOLD, 256);+}++static void chip(int cx, int y, const char *s, color_t fg, int alpha) {+ int w = gfx_text_width(&np_font_body, s) + 24;+ gfx_rrect(cx - w / 2, y, w, 24, 12, WHITE, alpha);+ gfx_text_center(&np_font_body, cx, y + 16, s, fg, 256);+}++/* ------------------------------------------------------------ the screens */+static void open_screen(int s) {+ if ((s == SC_PASS && u.screen == SC_ROLE) || s == SC_ROLE) u.guard_until = u.now + 600;+ u.screen = s;+ u.dirty = true;+}+static bool guarded(void) { return (int32_t)(u.guard_until - u.now) > 0; }++static void open_name(int idx, bool fresh) {+ u.name_idx = idx, u.name_new = fresh;+ memset(u.name, 0, sizeof u.name);+ if (!fresh) memcpy(u.name, sv.names[idx], NAME_MAX);+ u.name_len = (int)strlen(u.name);+ u.gr = u.gc = 0, u.msg_until = 0;+ open_screen(SC_NAME);+}++static void open_cats(void) {+ u.cmask = sv.cats ? sv.cats : ((uint32_t)1 << N_CATS) - 1;+ u.cats_sel = 0, u.cats_top = 0;+ open_screen(SC_CATS);+}++static void open_help(int back) {+ u.help_back = back;+ open_screen(SC_HELP);+}++/* the round's screen for where it stands */+static void open_round(void) {+ open_screen(sv.phase == PH_TALK ? SC_TALK : sv.phase == PH_REVEAL ? SC_REVEAL : SC_PASS);+ u.shown_sec = -1;+}++static void open_dialog(int d, int sel) {+ u.dialog_back = u.dialog;+ u.dialog = d, u.dsel = sel;+ u.dirty = true;+}++void app_init(uint32_t now) {+ memset(&u, 0, sizeof u);+ gfx_buf = strip;+ rnd_seed(plat_random() ^ now * 2654435761u);+ game_load();+ u.now = now;+ uint32_t l;+ u.stale = plat_keys(&l); /* keys still down from the launcher wait to be let go */+ if (sv.phase) open_round();+ else open_screen(SC_SETUP);+ if (!(sv.flags & 1)) {+ sv.flags |= 1;+ game_save();+ open_help(u.screen);+ }+}++bool app_dirty(void) { return u.dirty; }++/* ---- Setup */+static bool row_changes(int r) { return (r == ROW_IMPS && max_imposters(sv.nplayers) > 1) || r == ROW_HINT || r == ROW_TIMER; }++static void setup_change(int r, int d, bool wrap) {+ if (r == ROW_IMPS) {+ int m = max_imposters(sv.nplayers), v = imposters_now() + d;+ if (v < 1) v = wrap ? m : 1;+ if (v > m) v = wrap ? 1 : m;+ sv.imposters = (uint8_t)v;+ } else if (r == ROW_HINT) {+ sv.hint = !sv.hint;+ } else if (r == ROW_TIMER) {+ int v = sv.timer + d;+ if (v < 0) v = wrap ? N_TIMERS - 1 : 0;+ if (v >= N_TIMERS) v = wrap ? 0 : N_TIMERS - 1;+ sv.timer = (uint8_t)v;+ }+ game_save();+}++static bool setup_key(uint32_t hit) {+ int dy = !!(hit & KB_DOWN) - !!(hit & KB_UP), dx = !!(hit & KB_RIGHT) - !!(hit & KB_LEFT);+ u.setup_sel = (u.setup_sel + dy + N_ROWS) % N_ROWS;+ if (dx && row_changes(u.setup_sel)) setup_change(u.setup_sel, dx, false);+ if (hit & KB_BACK) open_dialog(DL_QUIT, 0);+ else if (hit & (KB_OK | KB_EXE)) switch (u.setup_sel) {+ case ROW_START:+ if (sv.nplayers < MIN_PLAYERS) {+ u.players_sel = sv.nplayers;+ open_screen(SC_PLAYERS);+ } else {+ round_new();+ open_round();+ }+ break;+ case ROW_PLAYERS: u.players_sel = 0; open_screen(SC_PLAYERS); break;+ case ROW_CATS: open_cats(); break;+ case ROW_HELP: open_help(SC_SETUP); break;+ case ROW_QUIT: open_dialog(DL_QUIT, 0); break;+ default:+ if (row_changes(u.setup_sel)) setup_change(u.setup_sel, 1, true);+ }+ return true;+}++static void setup_row(int r, const char *label, const char *value) {+ int y = 74 + (r - 1) * 21;+ bool on = u.setup_sel == r, arrows = on && row_changes(r);+ if (on) focus(16, y, 288, 20, 8);+ gfx_text(&np_font_body, 28, y + 14, label, on ? WHITE : SOFT, 256);+ if (!value) return;+ int rx = arrows ? 280 : 292;+ gfx_text_right(&np_font_body, rx, y + 14, value, on ? GOLD : WHITE, 256);+ if (arrows) {+ gfx_text_right(&np_font_body, rx - gfx_text_width(&np_font_body, value) - 7, y + 14, "<", GOLD, 256);+ gfx_text(&np_font_body, 286, y + 14, ">", GOLD, 256);+ }+}++static void draw_setup(void) {+ char a[16], b[16], t[16];+ background(BG_TOP, BG_BOT);+ heading("Imposter");+ bool ready = sv.nplayers >= MIN_PLAYERS;+ button(16, 38, 288, 30, ready ? "Start" : "Add players", u.setup_sel == ROW_START);+ if (sv.nplayers) num(a, sv.nplayers);+ else cat(a, "None");+ if (sv.cats) cat(num(b, cats_chosen()), " of 30");+ else cat(b, "All");+ if (sv.timer) cat(num(t, timer_minutes[sv.timer]), " min");+ else cat(t, "Off");+ char im[4];+ num(im, imposters_now());+ setup_row(ROW_PLAYERS, "Players", a);+ setup_row(ROW_CATS, "Categories", b);+ setup_row(ROW_IMPS, "Imposters", im);+ setup_row(ROW_HINT, "Imposter sees", sv.hint ? "The category" : "Nothing");+ setup_row(ROW_TIMER, "Timer", t);+ setup_row(ROW_HELP, "How to play", 0);+ setup_row(ROW_QUIT, "Quit game", 0);+ switch (u.setup_sel) {+ case ROW_START: KEYS("OK", ready ? "start" : "add players", "Back", "quit"); break;+ case ROW_PLAYERS: case ROW_CATS: case ROW_HELP: KEYS("OK", "open", "Back", "quit"); break;+ case ROW_IMPS:+ if (max_imposters(sv.nplayers) > 1) KEYS("Left Right", "change", "Back", "quit");+ else KEYS("", "2 imposters from 5 players");+ break;+ case ROW_HINT: case ROW_TIMER: KEYS("Left Right", "change", "Back", "quit"); break;+ default: KEYS("OK", "quit");+ }+}++/* ---- Players: two columns of six */+static int players_last(void) { return sv.nplayers < MAX_PLAYERS ? sv.nplayers : MAX_PLAYERS - 1; }++static bool players_key(uint32_t hit) {+ int s = u.players_sel, last = players_last();+ if (hit & KB_UP) s = s > 0 ? s - 1 : last;+ if (hit & KB_DOWN) s = s < last ? s + 1 : 0;+ if (hit & (KB_LEFT | KB_RIGHT)) {+ int t = s < 6 ? s + 6 : s - 6;+ if (t <= last) s = t;+ else if (s < 6 && last >= 6) s = last;+ }+ u.players_sel = s;+ if (hit & KB_BACK) {+ u.setup_sel = ROW_START;+ open_screen(SC_SETUP);+ } else if (hit & (KB_OK | KB_EXE)) {+ open_name(s, s >= sv.nplayers);+ } else if ((hit & KB_ERASE) && s < sv.nplayers) {+ open_dialog(DL_REMOVE, 0);+ }+ return true;+}++static void draw_players(void) {+ background(BG_TOP, BG_BOT);+ heading("Players");+ gfx_text_right(&np_font_small, 304, 25, "3 to 12", SOFT, 256);+ for (int i = 0; i <= players_last(); i++) {+ int x = 16 + i / 6 * 148, y = 40 + i % 6 * 29;+ bool on = u.players_sel == i;+ if (on) focus(x, y, 140, 26, 9);+ else gfx_rrect(x, y, 140, 26, 9, i < sv.nplayers ? CARD : HEX(0x1D2350), 256);+ if (i < sv.nplayers) {+ char n[4];+ num(n, i + 1);+ gfx_text_center(&np_font_small, x + 14, y + 17, n, on ? GOLD : SOFT, 256);+ gfx_text(&np_font_body, x + 28, y + 18, sv.names[i], WHITE, 256);+ } else {+ gfx_text(&np_font_body, x + 28, y + 18, "+ Add player", on ? GOLD : SOFT, 256);+ }+ }+ if (u.players_sel < sv.nplayers) KEYS("OK", "rename", "Backspace", "remove", "Back", "done");+ else KEYS("OK", "add", "Back", "done");+}++/* ---- a name: typed with the letters on the keys, or chosen among the screen's, laid out as on the keys */+static const uint8_t grid_cols[6] = {6, 6, 5, 5, 5, 2};+static const uint8_t grid_first[6] = {0, 6, 12, 17, 22, 27};+#define CELL_SPACE 26+#define CELL_ERASE 27+#define CELL_DONE 28++static void type_letter(int l) { /* 0 to 25, 26 a space */+ if (u.name_len >= NAME_MAX) return;+ if (l == CELL_SPACE) {+ if (!u.name_len || u.name[u.name_len - 1] == ' ') return;+ u.name[u.name_len++] = ' ';+ } else {+ bool up = !u.name_len || u.name[u.name_len - 1] == ' ';+ u.name[u.name_len++] = (char)((up ? 'A' : 'a') + l);+ }+ u.name[u.name_len] = 0;+}+static void erase_letter(void) {+ if (u.name_len) u.name[--u.name_len] = 0;+}++static bool same_name(const char *a, const char *b) {+ for (; *a && *b; a++, b++)+ if ((*a | 32) != (*b | 32)) return false;+ return *a == *b;+}++/* done with the name: kept (and the next one opened, after Done on a new player), or the screen's message */+static void name_done(bool next) {+ while (u.name_len && u.name[u.name_len - 1] == ' ') u.name[--u.name_len] = 0;+ bool taken = false;+ for (int i = 0; i < sv.nplayers; i++) taken |= i != u.name_idx && same_name(sv.names[i], u.name);+ if (u.name_len && taken && next) { /* (Back leaves it as it was) */+ u.msg_until = u.now + 1500;+ return;+ }+ if (u.name_len && !taken) {+ memcpy(sv.names[u.name_idx], u.name, NAME_MAX + 1);+ if (u.name_new) sv.nplayers++;+ game_save();+ if (next && u.name_new && sv.nplayers < MAX_PLAYERS) {+ open_name(sv.nplayers, true);+ return;+ }+ }+ u.players_sel = u.name_new ? players_last() : u.name_idx;+ open_screen(SC_PLAYERS);+}++static bool name_key(uint32_t hit, uint32_t letters) {+ for (int l = 0; l < 27; l++)+ if (letters >> l & 1) type_letter(l);+ if (hit & KB_UP) u.gc = (2 * u.gc + 1) * grid_cols[(u.gr + 5) % 6] / (2 * grid_cols[u.gr]), u.gr = (u.gr + 5) % 6;+ if (hit & KB_DOWN) u.gc = (2 * u.gc + 1) * grid_cols[(u.gr + 1) % 6] / (2 * grid_cols[u.gr]), u.gr = (u.gr + 1) % 6;+ if (hit & KB_LEFT) u.gc = (u.gc + grid_cols[u.gr] - 1) % grid_cols[u.gr];+ if (hit & KB_RIGHT) u.gc = (u.gc + 1) % grid_cols[u.gr];+ if (hit & KB_ERASE) erase_letter();+ if (hit & KB_OK) {+ int cell = grid_first[u.gr] + u.gc;+ if (cell == CELL_ERASE) erase_letter();+ else if (cell == CELL_DONE) name_done(true);+ else type_letter(cell);+ } else if (hit & KB_EXE) {+ name_done(true);+ } else if (hit & KB_BACK) {+ name_done(false);+ }+ return true;+}++static void draw_name(void) {+ char t[16];+ background(BG_TOP, BG_BOT);+ if ((int32_t)(u.msg_until - u.now) > 0) gfx_text_center(&np_font_title, SCREEN_W / 2, 27, "Already a player", RED_TEXT, 256);+ else num(cat(t, "Player "), u.name_idx + 1), heading(t);+ gfx_rrect(16, 36, 288, 44, 12, HEX(0x0C1029), 256);+ gfx_rrect_outline(16, 36, 288, 44, 12, 2, HEX(0x46519C), 256);+ int s = 420, cap = cap_height(), w = width1(u.name, u.name_len) * s / 256, x = SCREEN_W / 2 - (w + 6) / 2;+ int base = 58 + cap * s / 512;+ big_run(u.name, u.name_len, x, base, s, WHITE);+ gfx_fill(x + w + 3, base - cap * s / 256, 3, cap * s / 256, GOLD); /* where the next letter goes */+ for (int r = 0; r < 6; r++)+ for (int c = 0; c < grid_cols[r]; c++) {+ int cell = grid_first[r] + c, x0 = 16 + c * 288 / grid_cols[r], cw = 288 / grid_cols[r] - 3, y = 86 + r * 22;+ bool on = u.gr == r && u.gc == c;+ gfx_rrect(x0, y, cw, 20, 7, on ? GOLD : CARD, 256);+ char l[2] = {(char)('A' + cell), 0};+ const char *label = cell == CELL_SPACE ? "Space" : cell == CELL_ERASE ? "Erase" : cell == CELL_DONE ? "Done" : l;+ const np_font_t *f = cell < CELL_SPACE ? &np_font_title : &np_font_body;+ gfx_text_center(f, x0 + cw / 2, y + (cell < CELL_SPACE ? 17 : 14), label, on ? INK : WHITE, 256);+ }+ if (plat_typing()) KEYS("Letter keys", "type", "Backspace", "erase", "EXE", "done");+ else KEYS("OK", "pick", "Backspace", "erase", "EXE", "done");+}++/* ---- Categories: two columns, ten rows shown */+#define CAT_ROWS 10+static bool cats_key(uint32_t hit) {+ const uint32_t all = ((uint32_t)1 << N_CATS) - 1;+ int s = u.cats_sel;+ if (hit & KB_UP) s = s < 0 ? N_CATS - 2 : s < 2 ? -1 : s - 2;+ if (hit & KB_DOWN) s = s < 0 ? 0 : s + 2 >= N_CATS ? -1 : s + 2;+ if ((hit & (KB_LEFT | KB_RIGHT)) && s >= 0) s ^= 1;+ u.cats_sel = s;+ int row = s < 0 ? 0 : s / 2;+ if (row < u.cats_top) u.cats_top = row;+ if (row >= u.cats_top + CAT_ROWS) u.cats_top = row - CAT_ROWS + 1;+ if (hit & (KB_OK | KB_EXE)) {+ if (s < 0) u.cmask = u.cmask == all ? 0 : all;+ else u.cmask ^= (uint32_t)1 << s;+ sv.cats = u.cmask == all ? 0 : u.cmask; /* (none ticked: all, once left) */+ game_save();+ }+ if (hit & KB_BACK) {+ u.setup_sel = ROW_CATS;+ open_screen(SC_SETUP);+ }+ return true;+}++static const uint8_t tick[40] = {0, 0, 0, 16, 73, 0, 0, 0, 193, 191, 0, 0, 16, 252,+ 62, 182, 3, 144, 239, 3, 250, 62, 249, 62, 0, 193, 255, 255,+ 6, 0, 16, 252, 111, 0, 0, 0, 145, 5, 0, 0};+static void checkbox(int x, int y, bool on, bool focused) {+ if (on) {+ gfx_rrect(x, y, 14, 14, 4, GOLD, 256);+ gfx_mask(tick, 10, 8, x + 2, y + 3, INK, 256);+ } else {+ gfx_rrect_outline(x, y, 14, 14, 4, 2, focused ? GOLD : SOFT, 256);+ }+}++static void draw_cats(void) {+ const uint32_t all = ((uint32_t)1 << N_CATS) - 1;+ background(BG_TOP, BG_BOT);+ heading("Categories");+ bool on = u.cats_sel < 0;+ gfx_rrect(242, 8, 64, 24, 12, on ? GOLD : CARD, 256);+ if (on) gfx_rrect_outline(242, 8, 64, 24, 12, 2, GOLD, 256);+ checkbox(250, 13, u.cmask == all, on);+ gfx_text(&np_font_body, 270, 25, "All", on ? INK : WHITE, 256);+ for (int r = 0; r < CAT_ROWS; r++)+ for (int c = 0; c < 2; c++) {+ int k = (u.cats_top + r) * 2 + c;+ if (k >= N_CATS) continue;+ int x = c ? 166 : 12, y = 38 + r * 18;+ bool f = u.cats_sel == k;+ if (f) focus(x, y, c ? 138 : 150, 17, 6);+ checkbox(x + 5, y + 1, u.cmask >> k & 1, f);+ gfx_text(&np_font_body, x + 24, y + 13, categories[k].name, f ? WHITE : SOFT, 256);+ }+ /* where the list is */+ int rows = (N_CATS + 1) / 2, h = CAT_ROWS * 18 - 2;+ gfx_rrect(310, 38, 3, h, 1, HEX(0x262E62), 256);+ gfx_rrect(310, 38 + u.cats_top * h / rows, 3, CAT_ROWS * h / rows, 1, SOFT, 256);+ if (on) KEYS("OK", u.cmask == all ? "none" : "all", "Back", "done");+ else KEYS("OK", "on or off", "Back", "done");+}++/* ---- How to play */+static bool help_key(uint32_t hit) {+ if (hit & (KB_OK | KB_EXE | KB_BACK)) open_screen(u.help_back);+ return true;+}+static void draw_help(void) {+ background(BG_TOP, BG_BOT);+ heading("How to play");+ int y = gfx_paragraph(&np_font_body, 160, 52, 292, 15, "Everyone gets the same secret word, except the imposter.",+ WHITE, 256);+ y = gfx_paragraph(&np_font_body, 160, y + 7, 292, 15,+ "Pass the calculator around. Each player sees their role alone, then hides it.", WHITE, 256);+ y = gfx_paragraph(&np_font_body, 160, y + 7, 292, 15,+ "In turn, everyone says one word about the secret. Then vote out loud for the imposter.", WHITE,+ 256);+ gfx_paragraph(&np_font_body, 160, y + 7, 292, 15, "Caught, the imposter loses. Not caught, the imposter wins.",+ WHITE, 256);+ gfx_text_center(&np_font_small, 160, 198, "Inspired by the party game Imposter.", SOFT, 256);+ gfx_text_center(&np_font_small, 160, 211, "Made by Mason Chen as part of NumPlay.", SOFT, 256);+ KEYS("OK", "done");+}++/* ---- the round */+static bool pass_key(uint32_t hit) {+ if (hit & KB_BACK) open_dialog(DL_PAUSE, 0);+ else if ((hit & (KB_OK | KB_EXE)) && !guarded()) open_screen(SC_ROLE);+ return true;+}+static void draw_pass(void) {+ char t[16];+ background(BG_TOP, BG_BOT);+ gfx_text_center(&np_font_title, 160, 76, "Pass to", SOFT, 256);+ big_text(sv.names[sv.turn], 160, 118, 288, 64, 768, WHITE);+ num(cat(num(t, sv.turn + 1), " of "), sv.nplayers);+ gfx_text_center(&np_font_body, 160, 172, t, SOFT, 256);+ KEYS("OK", "see your role", "Back", "menu");+}++static bool role_key(uint32_t hit) {+ if (!(hit & (KB_OK | KB_EXE | KB_BACK)) || guarded()) return true;+ if (++sv.turn >= sv.nplayers) {+ sv.turn = 0, sv.phase = PH_TALK;+ game_save();+ open_round();+ } else {+ game_save();+ open_screen(SC_PASS);+ }+ return true;+}+static void draw_role(void) {+ char w[WORD_MAX + 1], h[WORD_MAX + 8];+ int c = word_text(sv.word, w);+ if (is_imposter(sv.turn)) {+ background(0xE3343F, 0x7A0D1B);+ gfx_text_center(&np_font_title, 160, 66, "You are the", WHITE, 256);+ big_text("Imposter", 160, 114, 296, 64, 768, WHITE);+ if (sv.hint) cat(cat(h, "Hint: "), categories[c].name), chip(160, 160, h, WHITE, 60);+ } else {+ background(0x2C6CE3, 0x14388C);+ gfx_text_center(&np_font_body, 160, 46, "The secret word", HEX(0xDCE6FF), 256);+ big_text(w, 160, 108, 296, 96, 720, WHITE);+ chip(160, 166, categories[c].name, WHITE, 60);+ }+ KEYS("OK", "hide");+}++static bool talk_key(uint32_t hit) {+ if (hit & KB_BACK) open_dialog(DL_PAUSE, 0);+ else if (hit & (KB_OK | KB_EXE)) open_dialog(DL_REVEAL, 0);+ return true;+}+static void draw_talk(void) {+ char t[24];+ background(BG_TOP, BG_BOT);+ int y = sv.timer ? 0 : 26; /* (without the timer, the rest in the middle) */+ cat(cat(t, sv.names[sv.starter]), " starts");+ big_text(t, 160, 70 + y, 296, 70, 560, WHITE);+ gfx_text_center(&np_font_body, 160, 128 + y, "One word each, in turn. Then vote out loud.", SOFT, 256);+ if (sv.timer) {+ if (sv.time_left) {+ int s = (int)((sv.time_left + 999) / 1000);+ char *e = num(t, s / 60);+ *e++ = ':', *e++ = (char)('0' + s % 60 / 10), *e++ = (char)('0' + s % 10), *e = 0;+ big_text(t, 160, 178, 200, 50, 640, s <= 10 ? GOLD : WHITE);+ } else {+ big_text("Time to vote", 160, 178, 280, 40, 400, GOLD);+ }+ }+ KEYS("OK", "reveal", "Back", "menu");+}++static bool reveal_key(uint32_t hit) {+ if (hit & (KB_OK | KB_EXE)) {+ round_new();+ open_round();+ } else if (hit & KB_BACK) {+ round_end();+ u.setup_sel = ROW_START;+ open_screen(SC_SETUP);+ }+ return true;+}+static void draw_reveal(void) {+ char w[WORD_MAX + 1], who[48];+ int c = word_text(sv.word, w), k = 0, n = imposters_now();+ background(BG_TOP, BG_BOT);+ gfx_text_center(&np_font_body, 160, 38, "The word was", SOFT, 256);+ big_text(w, 160, 70, 296, 50, 560, WHITE);+ chip(160, 104, categories[c].name, WHITE, 40);+ char *o = who;+ for (int p = 0; p < sv.nplayers; p++) {+ if (!is_imposter(p)) continue;+ if (k) o = cat(o, k == n - 1 ? " and " : ", ");+ o = cat(o, sv.names[p]);+ k++;+ }+ gfx_text_center(&np_font_body, 160, 154, k > 1 ? "The imposters were" : "The imposter was", SOFT, 256);+ big_text(who, 160, 186, 296, 50, 560, RED_TEXT);+ KEYS("OK", "next round", "Back", "setup");+}++/* ------------------------------------------------------------ dialogs */+static const char *const pause_items[] = {"Resume", "New round", "Setup", "Quit game"};+static const char *const quit_items[] = {"Quit", "Cancel"};+static const char *const reveal_items[] = {"Reveal", "Not yet"};+static const char *const remove_items[] = {"Remove", "Cancel"};++static int dialog_items(const char *const **items, char *q) {+ switch (u.dialog) {+ case DL_PAUSE: *items = pause_items, cat(q, "Paused"); return 4;+ case DL_QUIT: *items = quit_items, cat(q, "Quit Imposter?"); return 2;+ case DL_REVEAL: *items = reveal_items, cat(q, imposters_now() > 1 ? "Reveal the imposters?" : "Reveal the imposter?"); return 2;+ default: *items = remove_items, cat(cat(cat(q, "Remove "), sv.names[u.players_sel]), "?"); return 2;+ }+}++static void close_dialog(void) {+ u.dialog = u.dialog_back, u.dialog_back = DL_NONE, u.dsel = 0;+ u.dirty = true;+}++static bool dialog_key(uint32_t hit) {+ const char *const *items;+ char q[32];+ int n = dialog_items(&items, q);+ int dy = !!(hit & KB_DOWN) - !!(hit & KB_UP);+ u.dsel = (u.dsel + dy + n) % n;+ if (hit & KB_BACK) {+ close_dialog();+ return true;+ }+ if (!(hit & (KB_OK | KB_EXE))) return true;+ int d = u.dialog, s = u.dsel;+ u.dialog = DL_NONE, u.dialog_back = DL_NONE;+ if (d == DL_PAUSE) {+ if (s == 1) round_new(), open_round();+ else if (s == 2) round_end(), u.setup_sel = ROW_START, open_screen(SC_SETUP);+ else if (s == 3) u.dialog = DL_NONE, open_dialog(DL_QUIT, 0), u.dialog_back = DL_PAUSE;+ } else if (d == DL_QUIT) {+ if (s == 0) {+ game_save();+ return false;+ }+ if (u.screen != SC_SETUP) u.dialog = DL_PAUSE, u.dsel = 3;+ } else if (d == DL_REVEAL) {+ if (s == 0) {+ sv.phase = PH_REVEAL;+ game_save();+ open_round();+ }+ } else if (d == DL_REMOVE && s == 0) {+ int p = u.players_sel;+ for (int i = p; i + 1 < sv.nplayers; i++) memcpy(sv.names[i], sv.names[i + 1], NAME_MAX + 1);+ sv.nplayers--;+ memset(sv.names[sv.nplayers], 0, NAME_MAX + 1);+ if (u.players_sel > players_last()) u.players_sel = players_last();+ game_save();+ }+ u.dirty = true;+ return true;+}++static void draw_dialog(void) {+ const char *const *items;+ char q[32];+ int n = dialog_items(&items, q);+ int h = 58 + n * 34, y = (KEY_Y - h) / 2, x = 24, w = 272;+ gfx_fill_alpha(0, 0, SCREEN_W, KEY_Y, 0, 150);+ gfx_rrect(x, y, w, h, 14, HEX(0x1B2150), 256);+ gfx_rrect_outline(x, y, w, h, 14, 2, HEX(0x4A56A8), 256);+ gfx_text_center(&np_font_title, 160, y + 32, q, WHITE, 256);+ for (int i = 0; i < n; i++) button(x + 24, y + 46 + i * 34, w - 48, 28, items[i], u.dsel == i);+ KEYS("OK", "choose", "Back", u.dialog == DL_PAUSE ? "resume" : "cancel");+}++/* ------------------------------------------------------------ the frame, the keys */+static void scene(void *ctx) {+ (void)ctx;+ switch (u.screen) {+ case SC_HELP: draw_help(); break;+ case SC_SETUP: draw_setup(); break;+ case SC_PLAYERS: draw_players(); break;+ case SC_NAME: draw_name(); break;+ case SC_CATS: draw_cats(); break;+ case SC_PASS: draw_pass(); break;+ case SC_ROLE: draw_role(); break;+ case SC_TALK: draw_talk(); break;+ default: draw_reveal(); break;+ }+ if (u.dialog) draw_dialog();+}++#ifdef HOST+/* what the screen shows, for tests/check.py */+static void trace(void) {+ static const char *const names[] = {"help", "setup", "players", "name", "cats", "pass", "role", "talk", "reveal"};+ char w[WORD_MAX + 1];+ int c = word_text(sv.word, w);+ printf("DRAW %s dialog %d", names[u.screen], u.dialog);+ if (u.screen == SC_PASS) printf(" turn %d name %s", sv.turn, sv.names[sv.turn]);+ if (u.screen == SC_ROLE) {+ if (is_imposter(sv.turn)) printf(" turn %d imposter hint %s", sv.turn, sv.hint ? categories[c].name : "-");+ else printf(" turn %d word %s cat %s", sv.turn, w, categories[c].name);+ }+ if (u.screen == SC_TALK) printf(" starter %d %s left %u", sv.starter, sv.names[sv.starter], (unsigned)sv.time_left);+ if (u.screen == SC_REVEAL) printf(" word %s imps %u", w, (unsigned)sv.imps);+ if (u.screen == SC_NAME) printf(" typed %s", u.name);+ printf("\n");+}+#endif++void app_draw(void) {+ u.dirty = false;+ gfx_render(scene, 0, 0, SCREEN_H);+#ifdef HOST+ if (host_trace) trace();+#endif+}++bool app_step(uint32_t keys, uint32_t letters, uint32_t now) {+ uint32_t dt = now - u.now;+ u.now = now;+ if (keys & KB_HOME) {+ game_save();+ return false;+ }+ u.stale &= keys;+ uint32_t live = keys & ~u.stale, hit = live & ~u.prev_keys, lhit = letters & ~u.prev_letters;+ const uint32_t rep = KB_LEFT | KB_RIGHT | KB_UP | KB_DOWN | KB_ERASE;+ if (hit & rep) u.repeat_at = now + 350;+ else if ((live & rep) && (int32_t)(now - u.repeat_at) >= 0) hit |= live & rep, u.repeat_at = now + 90;+ u.prev_keys = live, u.prev_letters = letters;+ if (u.screen != SC_NAME) lhit = 0;+ /* the discussion timer runs on its screen */+ if (u.screen == SC_TALK && !u.dialog && sv.timer && sv.time_left) {+ sv.time_left = dt >= sv.time_left ? 0 : sv.time_left - dt;+ int s = (int)((sv.time_left + 999) / 1000);+ if (s != u.shown_sec) u.shown_sec = s, u.dirty = true;+ }+ if (u.msg_until && (int32_t)(now - u.msg_until) >= 0) u.msg_until = 0, u.dirty = true;+ hit &= ~(uint32_t)KB_ANY;+ if (!hit && !lhit) return true;+ u.dirty = true;+ if (u.dialog) return dialog_key(hit);+ switch (u.screen) {+ case SC_HELP: return help_key(hit);+ case SC_SETUP: return setup_key(hit);+ case SC_PLAYERS: return players_key(hit);+ case SC_NAME: return name_key(hit, lhit);+ case SC_CATS: return cats_key(hit);+ case SC_PASS: return pass_key(hit);+ case SC_ROLE: return role_key(hit);+ case SC_TALK: return talk_key(hit);+ default: return reveal_key(hit);+ }+}diff --git a/games/imposter/src/ui.h b/games/imposter/src/ui.hnew file mode 100644index 00000000..4e40493f--- /dev/null+++ b/games/imposter/src/ui.h@@ -0,0 +1,12 @@+/* Imposter: the screens and their keys (ui.c). */+#ifndef IM_UI_H+#define IM_UI_H+#include <stdbool.h>+#include <stdint.h>++void app_init(uint32_t now);+/* the keys held now and the letters on them (plat_keys); false: the game ends (saved) */+bool app_step(uint32_t keys, uint32_t letters, uint32_t now);+bool app_dirty(void);+void app_draw(void);+#endifdiff --git a/games/imposter/src/words.c b/games/imposter/src/words.cnew file mode 100644index 00000000..381e24b1--- /dev/null+++ b/games/imposter/src/words.c@@ -0,0 +1,257 @@+/* The categories and their words, each word once in all of them, at most 64 a category (a category's used words+ * are 64 bits of the save). New words go at the end of their category, so the save's bits keep their words. */+#include "words.h"++static const char FOOD[] =+ "Pizza|Burger|Hot dog|Spaghetti|Sushi|Taco|Burrito|Sandwich|Pancakes|Waffles|French fries|Fried chicken|"+ "Omelette|Soup|Salad|Rice|Noodles|Dumplings|Steak|Meatballs|Lasagna|Toast|Cereal|Porridge|Bacon|Sausage|"+ "Popcorn|Nachos|Cheese|Bread|Bagel|Croissant|Pretzel|Curry|Kebab|Fish and chips|Mashed potatoes|"+ "Grilled cheese|Chicken nuggets|Ramen|Hummus|Falafel|Ravioli|Risotto|Stew|Chili con carne|Peanut butter|Jam|"+ "Honey|Yogurt|Scrambled eggs|Fried rice|Spring rolls|Mac and cheese|Corn dog|Paella|Quesadilla|Garlic bread|"+ "Onion rings|Fish sticks";++static const char FRUITS[] =+ "Apple|Banana|Orange|Strawberry|Grape|Watermelon|Pineapple|Mango|Peach|Pear|Cherry|Lemon|Lime|Kiwi|Coconut|"+ "Blueberry|Raspberry|Blackberry|Plum|Apricot|Papaya|Pomegranate|Fig|Melon|Grapefruit|Avocado|Tangerine|"+ "Passion fruit|Dragon fruit|Lychee|Guava|Cranberry|Nectarine|Date|Persimmon|Starfruit|Gooseberry|Clementine|"+ "Cantaloupe|Jackfruit|Durian|Mandarin|Quince|Raisin|Prune|Honeydew|Kumquat|Mulberry|Plantain|Blood orange";++static const char VEGETABLES[] =+ "Carrot|Potato|Tomato|Onion|Garlic|Broccoli|Cauliflower|Cabbage|Lettuce|Spinach|Cucumber|Bell pepper|Corn|"+ "Peas|Green beans|Pumpkin|Zucchini|Eggplant|Mushroom|Celery|Asparagus|Beetroot|Radish|Leek|Sweet potato|"+ "Brussels sprouts|Kale|Artichoke|Turnip|Chili pepper|Olive|Squash|Ginger|Parsnip|Bean sprouts|Chickpeas|"+ "Lentils|Kidney beans|Okra|Shallot|Watercress|Rhubarb|Fennel|Yam|Bok choy|Pickle|Parsley|Basil|Arugula|"+ "Spring onion|Jalapeno";++static const char DESSERTS[] =+ "Ice cream|Chocolate cake|Cupcake|Cookie|Brownie|Donut|Cheesecake|Apple pie|Muffin|Pudding|Jelly|Tiramisu|"+ "Macaron|Crepe|Churros|Cotton candy|Lollipop|Candy cane|Marshmallow|Fudge|Toffee|Caramel|Meringue|Eclair|"+ "Cinnamon roll|Banana split|Sundae|Ice pop|Sorbet|Frozen yogurt|Custard|Gingerbread man|Fruit salad|"+ "Carrot cake|Birthday cake|Wedding cake|Gummy bears|Chocolate bar|Rice pudding|Baklava|Mochi|Shortbread|"+ "Lemon tart|Chocolate mousse|Panna cotta|Apple crumble|Jelly beans|Whipped cream|Cannoli|Waffle cone|"+ "Cake pop|Profiteroles|Key lime pie|Pecan pie";++static const char DRINKS[] =+ "Water|Milk|Orange juice|Apple juice|Lemonade|Hot chocolate|Tea|Coffee|Smoothie|Milkshake|Soda|Iced tea|"+ "Sparkling water|Coconut water|Chocolate milk|Fruit punch|Ginger ale|Cola|Bubble tea|Green tea|Herbal tea|"+ "Espresso|Cappuccino|Latte|Grape juice|Tomato juice|Cranberry juice|Pineapple juice|Mango lassi|Horchata|"+ "Sports drink|Slushie|Frappe|Mocha|Chai|Soy milk|Almond milk|Oat milk|Strawberry milk|Mint tea|Iced coffee|"+ "Carrot juice|Watermelon juice|Peach tea|Tonic water|Matcha|Buttermilk|Hot milk|Pink lemonade";++static const char KITCHEN[] =+ "Fridge|Oven|Microwave|Toaster|Kettle|Blender|Frying pan|Saucepan|Spatula|Whisk|Ladle|Rolling pin|"+ "Cutting board|Knife|Fork|Spoon|Plate|Bowl|Mug|Glass|Teapot|Dishwasher|Sink|Sponge|Apron|Oven mitt|Grater|"+ "Peeler|Colander|Can opener|Tongs|Measuring cup|Kitchen scale|Egg timer|Freezer|Stove|Lunch box|Napkin|"+ "Tablecloth|Chopsticks|Straw|Coffee machine|Mixer|Baking tray|Salt shaker|Pepper mill|Ice cube tray|"+ "Trash can|Dish soap|Tea towel|Jar|Wok|Rice cooker|Food processor|Cookbook|Placemat|Toothpick|Aluminum foil";++static const char ANIMALS[] =+ "Lion|Tiger|Elephant|Giraffe|Zebra|Monkey|Gorilla|Kangaroo|Koala|Panda|Bear|Polar bear|Wolf|Fox|Rabbit|"+ "Squirrel|Deer|Moose|Horse|Cow|Pig|Sheep|Goat|Chicken|Duck|Dog|Cat|Hamster|Mouse|Owl|Eagle|Parrot|Penguin|"+ "Flamingo|Peacock|Crocodile|Snake|Turtle|Frog|Camel|Hippo|Rhino|Cheetah|Leopard|Sloth|Hedgehog|Bat|Raccoon|"+ "Skunk|Beaver|Llama|Ostrich|Butterfly|Bee|Spider|Ant|Snail|Lizard|Chameleon|Donkey|Swan|Hyena|Ladybug|"+ "Guinea pig";++static const char SEA[] =+ "Shark|Whale|Dolphin|Octopus|Jellyfish|Starfish|Seahorse|Crab|Lobster|Shrimp|Squid|Clam|Oyster|Seal|"+ "Sea lion|Walrus|Sea turtle|Coral reef|Stingray|Swordfish|Clownfish|Pufferfish|Eel|Seaweed|Anchor|Shipwreck|"+ "Lighthouse|Wave|Tide|Island|Beach|Sand|Seashell|Pearl|Treasure chest|Pirate ship|Surfboard|Scuba diver|"+ "Snorkel|Fishing net|Buoy|Pier|Harbor|Iceberg|Seagull|Pelican|Orca|Narwhal|Sea urchin|Plankton|Sandcastle|"+ "Message in a bottle|Tuna|Salmon";++static const char COUNTRIES[] =+ "France|Spain|Italy|Germany|United Kingdom|Ireland|Portugal|Greece|Netherlands|Belgium|Switzerland|Sweden|"+ "Norway|Finland|Denmark|Iceland|Poland|Russia|Ukraine|Turkey|Egypt|Morocco|Nigeria|Kenya|South Africa|"+ "Ethiopia|Ghana|Madagascar|United States|Canada|Mexico|Brazil|Argentina|Chile|Peru|Colombia|Cuba|Jamaica|"+ "China|Japan|South Korea|India|Thailand|Vietnam|Indonesia|Philippines|Australia|New Zealand|Saudi Arabia|"+ "Austria|Hungary|Croatia|Pakistan|Nepal|Mongolia|Singapore|Malaysia|Venezuela|Senegal|Tunisia";++static const char CITIES[] =+ "Paris|London|New York|Tokyo|Rome|Madrid|Barcelona|Berlin|Amsterdam|Venice|Moscow|Beijing|Shanghai|"+ "Hong Kong|Seoul|Bangkok|Dubai|Cairo|Istanbul|Athens|Lisbon|Dublin|Vienna|Prague|Sydney|Melbourne|Toronto|"+ "Montreal|Vancouver|Los Angeles|San Francisco|Chicago|Las Vegas|Miami|Washington|Boston|Rio de Janeiro|"+ "Buenos Aires|Mexico City|Mumbai|Delhi|Cape Town|Nairobi|Marrakech|Stockholm|Copenhagen|Oslo|Brussels|"+ "Geneva|Florence|Milan|Naples|Edinburgh|Kyoto|Osaka|Havana|Lima|Honolulu|New Orleans|Seattle|Sao Paulo|"+ "Manila";++static const char PLACES[] =+ "Eiffel Tower|Great Wall of China|Pyramids of Giza|Statue of Liberty|Big Ben|Colosseum|Taj Mahal|"+ "Mount Everest|Niagara Falls|Grand Canyon|Stonehenge|Machu Picchu|Sydney Opera House|Golden Gate Bridge|"+ "Leaning Tower of Pisa|Mount Rushmore|Christ the Redeemer|Times Square|Amazon rainforest|Sahara Desert|"+ "North Pole|Buckingham Palace|White House|Acropolis|Petra|Angkor Wat|Louvre|Sagrada Familia|Notre Dame|"+ "Arc de Triomphe|Great Barrier Reef|Mount Fuji|Kilimanjaro|Victoria Falls|Dead Sea|Galapagos Islands|"+ "Yellowstone|Easter Island|Chichen Itza|Forbidden City|Tower Bridge|Trafalgar Square|Red Square|Central Park|"+ "Alcatraz|Hoover Dam|Panama Canal|Tower of London|Bermuda Triangle|Loch Ness|Mont Saint-Michel|Versailles|"+ "Uluru|Death Valley|South Pole|Brooklyn Bridge|Pompeii";++static const char JOBS[] =+ "Doctor|Nurse|Teacher|Firefighter|Police officer|Chef|Pilot|Farmer|Dentist|Vet|Lawyer|Judge|Mechanic|"+ "Plumber|Electrician|Carpenter|Builder|Architect|Engineer|Scientist|Artist|Musician|Singer|Actor|Dancer|"+ "Photographer|Journalist|Writer|Baker|Butcher|Cashier|Waiter|Hairdresser|Barber|Mail carrier|Taxi driver|"+ "Bus driver|Truck driver|Lifeguard|Soldier|Sailor|Fisherman|Gardener|Librarian|Cleaner|Programmer|Designer|"+ "Pharmacist|Surgeon|Paramedic|Zookeeper|Tailor|Florist|Banker|Accountant|Receptionist|Security guard|Coach|"+ "Referee|Magician|Clown|Detective|Principal|Babysitter";++static const char SPORTS[] =+ "Soccer|Basketball|Tennis|Baseball|Volleyball|Golf|Rugby|Ice hockey|Swimming|Running|Cycling|Boxing|Karate|"+ "Judo|Wrestling|Fencing|Archery|Skiing|Snowboarding|Ice skating|Surfing|Skateboarding|Gymnastics|"+ "Table tennis|Badminton|Bowling|Cricket|Handball|Diving|Rowing|Sailing|Rock climbing|Horse riding|Marathon|"+ "High jump|Long jump|Pole vault|Javelin|Triathlon|Water polo|Curling|Bobsled|Kayaking|Darts|Billiards|"+ "Weightlifting|Yoga|Parkour|Dodgeball|Lacrosse|Softball|Figure skating|Car racing|American football|"+ "Field hockey|Sumo|Taekwondo|Shot put|Hurdles";++static const char SCHOOL[] =+ "Classroom|Desk|Blackboard|Whiteboard|Chalk|Pencil|Pen|Eraser|Ruler|Backpack|Notebook|Textbook|Homework|"+ "Exam|Report card|Gym class|Cafeteria|Recess|School bus|Locker|Calculator|Scissors|Glue stick|Stapler|"+ "Highlighter|Pencil case|Pencil sharpener|Globe|Map|Math|History|Geography|Art class|Music class|Field trip|"+ "Graduation|Diploma|School bell|Hall pass|Detention|Spelling test|Science fair|School uniform|Timetable|"+ "Dictionary|Crayons|Marker|Protractor|Summer break|First day of school|Yearbook|Class photo|Quiz|Grades|"+ "Paper clip|Hole punch";++static const char HOME[] =+ "Sofa|Bed|Pillow|Blanket|Lamp|Television|Remote control|Armchair|Table|Chair|Bookshelf|Wardrobe|Mirror|"+ "Clock|Carpet|Curtains|Window|Door|Stairs|Bathtub|Shower|Toilet|Toothbrush|Towel|Soap|Shampoo|"+ "Washing machine|Vacuum cleaner|Iron|Ironing board|Broom|Mop|Bucket|Doorbell|Mailbox|Garage|Attic|Basement|"+ "Fireplace|Radiator|Ceiling fan|Light switch|Houseplant|Vase|Picture frame|Alarm clock|Laundry basket|"+ "Hair dryer|Doormat|House key|Garden|Balcony|Chimney|Bunk bed|Coat hanger|Smoke alarm|Toothpaste";++static const char CLOTHES[] =+ "T-shirt|Jeans|Dress|Skirt|Shorts|Sweater|Hoodie|Jacket|Coat|Raincoat|Scarf|Gloves|Mittens|Hat|Cap|Beanie|"+ "Socks|Shoes|Sneakers|Boots|Sandals|Flip-flops|Slippers|Pajamas|Swimsuit|Tie|Bow tie|Belt|Suit|Leggings|"+ "Overalls|Vest|Blouse|Shirt|Tracksuit|Cardigan|Bathrobe|Sunglasses|Earrings|Necklace|Bracelet|Ring|Watch|"+ "Handbag|Wallet|Umbrella|Tuxedo|Kimono|Poncho|High heels|Wedding dress|Costume|Headband|Earmuffs|"+ "Rain boots|Bandana|Turtleneck|Polo shirt";++static const char TRANSPORT[] =+ "Car|Bus|Train|Airplane|Bicycle|Motorcycle|Scooter|Skateboard|Boat|Cruise ship|Ferry|Submarine|Helicopter|"+ "Hot air balloon|Taxi|Truck|Tractor|Ambulance|Fire truck|Police car|Tram|Subway|Cable car|Canoe|Sailboat|"+ "Yacht|Jet|Glider|Parachute|Horse and carriage|Sled|Snowmobile|Limousine|Van|Camper van|Tow truck|"+ "Garbage truck|Bulldozer|Monorail|Rickshaw|Gondola|Unicycle|Tandem bike|Roller skates|Airship|"+ "Electric scooter|Go-kart|Steam train|Double-decker bus|Moped|Pickup truck|Raft|Speedboat|Rowboat|"+ "Cargo ship|Seaplane|Bullet train";++static const char INSTRUMENTS[] =+ "Piano|Guitar|Violin|Drums|Flute|Trumpet|Saxophone|Cello|Harp|Clarinet|Trombone|Tuba|Accordion|Harmonica|"+ "Ukulele|Banjo|Xylophone|Tambourine|Triangle|Bagpipes|Keyboard|Electric guitar|Bass guitar|Double bass|"+ "Viola|Oboe|Bassoon|French horn|Recorder|Maracas|Bongos|Cymbals|Organ|Synthesizer|Kazoo|Castanets|Gong|"+ "Sitar|Didgeridoo|Steel drum|Mandolin|Harpsichord|Bugle|Cowbell|Djembe|Pan flute|Glockenspiel|Snare drum|"+ "Lute|Marimba|Piccolo";++static const char NATURE[] =+ "Rain|Snow|Wind|Storm|Thunder|Lightning|Rainbow|Cloud|Fog|Hail|Tornado|Hurricane|Flood|Heatwave|Frost|"+ "Sunset|Sunrise|Mountain|Volcano|River|Lake|Waterfall|Forest|Jungle|Desert|Cave|Canyon|Valley|Hill|Meadow|"+ "Glacier|Swamp|Tree|Flower|Grass|Leaf|Rock|Mud|Puddle|Snowflake|Avalanche|Earthquake|Breeze|Sky|Pond|Cliff|"+ "Field|Icicle|Sunshine|Drizzle|Blizzard|Dew|Sandstorm|Hot spring|Geyser|Acorn|Pine cone|Moss|"+ "Northern lights";++static const char BODY[] =+ "Head|Hair|Eye|Ear|Nose|Mouth|Tooth|Tongue|Lips|Chin|Cheek|Forehead|Eyebrow|Eyelash|Neck|Shoulder|Arm|Elbow|"+ "Wrist|Hand|Finger|Thumb|Fingernail|Chest|Belly button|Stomach|Back|Knee|Leg|Ankle|Foot|Toe|Heel|Heart|"+ "Brain|Lungs|Bones|Skeleton|Skull|Muscle|Skin|Blood|Kidney|Hip|Spine|Ribs|Freckles|Dimple|Beard|Mustache|"+ "Throat|Palm|Jaw|Knuckle|Eyelid|Liver|Goosebumps|Hiccups";++static const char HOBBIES[] =+ "Reading|Painting|Drawing|Cooking|Baking|Gardening|Fishing|Hiking|Photography|Knitting|Sewing|Dancing|"+ "Singing|Video games|Jigsaw puzzles|Stamp collecting|Bird watching|Origami|Pottery|Magic tricks|Juggling|"+ "Writing stories|Karaoke|Woodworking|Scrapbooking|Calligraphy|Model trains|Coding|Blogging|Beekeeping|"+ "Kite flying|Stargazing|Coin collecting|Crochet|Embroidery|Film making|Comic books|Doodling|Building models|"+ "Learning languages|Cosplay|Volunteering|Geocaching|Metal detecting|Crosswords|Shell collecting|Camping|"+ "Journaling|Rock collecting|Tie-dye|Candle making|Making jewelry|Model rockets";++static const char HOLIDAYS[] =+ "Christmas|New Year's Eve|Halloween|Easter|Thanksgiving|Valentine's Day|Hanukkah|Diwali|Lunar New Year|Eid|"+ "Carnival|Mardi Gras|Independence Day|Mother's Day|Father's Day|April Fools' Day|St Patrick's Day|"+ "Summer vacation|Spring break|Fireworks|Santa Claus|Reindeer|Snowman|Christmas tree|Presents|Stocking|"+ "Jack-o'-lantern|Trick or treat|Easter egg|Easter bunny|Roast turkey|Candles|Wreath|Mistletoe|"+ "Gingerbread house|Advent calendar|Parade|Picnic|Road trip|Ugly sweater|Sleigh|Day of the Dead|"+ "Lantern festival|Kwanzaa|Holi|Groundhog Day|Boxing Day|Earth Day|Anniversary|Red envelope|Menorah|Bonfire|"+ "Birthday";++static const char TOWN[] =+ "Bank|Post office|Supermarket|Bakery|Library|Hospital|Police station|Fire station|Cinema|Museum|Park|"+ "Playground|Restaurant|Cafe|Hotel|Pharmacy|Train station|Bus stop|Airport|Gas station|Parking lot|"+ "Traffic light|Crosswalk|Bridge|Fountain|Statue|Market|Shopping mall|Gym|Swimming pool|Zoo|Stadium|"+ "Town hall|Skyscraper|Apartment|Bookstore|Toy store|Barber shop|Laundromat|Pet shop|Flower shop|Bench|"+ "Streetlight|Sidewalk|Roundabout|Ice cream truck|Food truck|Billboard|Car wash|Pizzeria|Bowling alley|"+ "Arcade|Theater|Aquarium|Factory|Construction site|Fire hydrant|Bike lane|Recycling bin";++static const char SPACE[] =+ "Sun|Moon|Earth|Mars|Venus|Jupiter|Saturn|Mercury|Neptune|Pluto|Star|Comet|Asteroid|Meteor|Galaxy|"+ "Black hole|Rocket|Astronaut|Alien|UFO|Satellite|Space station|Telescope|Planet|Orbit|Gravity|Milky Way|"+ "Nebula|Eclipse|Constellation|Big Dipper|Crater|Solar system|Spacesuit|Moon landing|Mars rover|"+ "Shooting star|Supernova|Launch pad|Mission control|Zero gravity|Spaceship|Light year|Big Bang|Sunspot|"+ "Spacewalk|Meteor shower|Space shuttle|Moon base|Asteroid belt|Wormhole|Dwarf planet|Observatory|"+ "Planetarium|Space food|Countdown|Solar flare";++static const char FANTASY[] =+ "Dragon|Unicorn|Wizard|Witch|Fairy|Elf|Dwarf|Giant|Troll|Goblin|Ogre|Mermaid|Vampire|Werewolf|Ghost|Zombie|"+ "Phoenix|Griffin|Centaur|Pegasus|Minotaur|Cyclops|Kraken|Sphinx|Genie|Magic wand|Spell book|Potion|"+ "Crystal ball|Castle|Knight|Princess|Prince|King|Queen|Treasure map|Sword|Shield|Crown|Flying carpet|"+ "Magic lamp|Cauldron|Broomstick|Gnome|Leprechaun|Yeti|Sea serpent|Hydra|Enchanted forest|Curse|Magic portal|"+ "Dungeon|Throne|Tooth fairy|Time machine|Orc|Pixie|Wishing well|Magic mirror|Bigfoot";++static const char TOYS[] =+ "Teddy bear|Doll|Ball|Kite|Yo-yo|Building blocks|Toy car|Train set|Board game|Chess|Checkers|Dominoes|"+ "Playing cards|Dice|Marbles|Jump rope|Spinning top|Rocking horse|Slide|Swing|Seesaw|Trampoline|Sandbox|"+ "Water gun|Soap bubbles|Action figure|Puppet|Dollhouse|Robot|Remote control car|Hopscotch|Hide and seek|Tag|"+ "Musical chairs|Tug of war|Treasure hunt|Rubber duck|Jack-in-the-box|Kaleidoscope|Piggy bank|Stickers|"+ "Snow globe|Pinball|Bingo|Tic-tac-toe|Rock paper scissors|Charades|Simon says|Water balloon|Stuffed animal|"+ "Pogo stick|Model plane|Paper airplane|Toy box|Rattle|Pinwheel";++static const char TOOLS[] =+ "Hammer|Screwdriver|Wrench|Saw|Drill|Pliers|Tape measure|Nail|Screw|Ladder|Shovel|Rake|Wheelbarrow|Axe|"+ "Chisel|Sandpaper|Paintbrush|Paint roller|Spirit level|Toolbox|Flashlight|Glue gun|Duct tape|Garden hose|"+ "Watering can|Lawn mower|Chainsaw|Crowbar|Mallet|Hacksaw|Utility knife|Clamp|Pickaxe|Sledgehammer|Anvil|"+ "Magnifying glass|Pitchfork|Trowel|Bolt|Hinge|Soldering iron|Extension cord|Padlock|Rope|Funnel|"+ "Garden shears|Hex key|Chain|Scraper|Workbench|Safety goggles|Hard hat|Tool belt|Leaf blower|Pocket knife|"+ "Car jack";++static const char SCIENCE[] =+ "Atom|Magnet|Microscope|Test tube|Laboratory|Experiment|Electricity|Battery|Light bulb|DNA|Cell|Bacteria|"+ "Virus|Fossil|Dinosaur|Thermometer|Periodic table|Oxygen|Hydrogen|Carbon|Water cycle|Photosynthesis|"+ "Evolution|Energy|Solar panel|Wind turbine|Circuit|Lab coat|Beaker|Chemical reaction|Formula|Laser|Prism|"+ "Gears|Pulley|Lever|Crystal|Static electricity|Molecule|Microchip|Germs|Vaccine|X-ray|Ecosystem|Climate|"+ "Recycling|Petri dish|Bunsen burner|Slime|Inventor|Hypothesis|Electron|Computer|Acid|Steam engine|"+ "Sound wave|Friction";++static const char PARTY[] =+ "Balloons|Confetti|Party hat|Streamers|Pinata|DJ|Dance floor|Disco ball|Invitation|Gift bag|Wrapping paper|"+ "Ribbon|Birthday card|Photo booth|Costume party|Pool party|Sleepover|Pizza party|Surprise party|Guest list|"+ "Snacks|Potato chips|Candy|Party favors|Garland|Banner|Fairy lights|Glow sticks|Bouncy castle|Face paint|"+ "Musical statues|Limbo|Conga line|Slow dance|Speaker|Microphone|Playlist|Group photo|Thank you card|"+ "Birthday song|Party popper|Paper plates|Masquerade|Dress code|Barbecue|Dance battle|Bubble machine|"+ "Game night|Movie night|Paper lanterns|Chocolate fountain";++static const char TECH[] =+ "Phone|Laptop|Tablet|Headphones|Smartwatch|Selfie|Emoji|Password|Text message|Video call|Hashtag|Meme|"+ "Podcast|Livestream|Notification|Screenshot|Download|Website|Email|Spam|Ringtone|Group chat|"+ "Profile picture|Username|Touchscreen|App|Game console|Drone|Virtual reality|Smart speaker|Printer|Webcam|"+ "Online shopping|Streaming|Autocorrect|Unboxing video|Tutorial|Robot vacuum|3D printer|Power bank|"+ "Computer mouse|Search engine|Hard drive|Cloud storage|Satellite dish|GPS|Voice assistant|Smart TV|Pixel|"+ "Loading screen|Software update|Earbuds|Selfie stick|Phone charger|Dark mode";++const category_t categories[N_CATS] = {+ {"Food", FOOD}, {"Fruits", FRUITS}, {"Vegetables", VEGETABLES}, {"Desserts", DESSERTS}, {"Drinks", DRINKS},+ {"Kitchen", KITCHEN}, {"Animals", ANIMALS}, {"The sea", SEA}, {"Countries", COUNTRIES}, {"Cities", CITIES},+ {"Famous places", PLACES}, {"Jobs", JOBS}, {"Sports", SPORTS}, {"School", SCHOOL}, {"At home", HOME},+ {"Clothes", CLOTHES}, {"Transport", TRANSPORT}, {"Instruments", INSTRUMENTS}, {"Nature and weather", NATURE},+ {"The body", BODY}, {"Hobbies", HOBBIES}, {"Holidays", HOLIDAYS}, {"In town", TOWN}, {"Space", SPACE},+ {"Fantasy", FANTASY}, {"Toys and games", TOYS}, {"Tools", TOOLS}, {"Science", SCIENCE}, {"Party", PARTY},+ {"Technology", TECH},+};++int word_count(int cat) {+ const char *s = categories[cat].words;+ int n = 1;+ while (*s) n += *s++ == '|';+ return n;+}++int word_get(int cat, int i, char *out, int cap) {+ const char *s = categories[cat].words;+ while (i > 0 && *s) i -= *s++ == '|';+ int n = 0;+ while (s[n] && s[n] != '|' && n < cap - 1) out[n] = s[n], n++;+ out[n] = 0;+ return n;+}diff --git a/games/imposter/src/words.h b/games/imposter/src/words.hnew file mode 100644index 00000000..0fdb2e65--- /dev/null+++ b/games/imposter/src/words.h@@ -0,0 +1,18 @@+/* Imposter: the categories and their words (words.c). */+#ifndef IM_WORDS_H+#define IM_WORDS_H++#define N_CATS 30+#define CAT_MAX 64 /* words a category at most */+#define WORD_MAX 24 /* a word's letters at most, and its end */++typedef struct {+ const char *name;+ const char *words; /* separated by '|' */+} category_t;+extern const category_t categories[N_CATS];++int word_count(int cat);+/* word i of a category into out (cap bytes with its end); its length */+int word_get(int cat, int i, char *out, int cap);+#endifdiff --git a/games/imposter/tests/play.c b/games/imposter/tests/play.cnew file mode 100644index 00000000..dbbba39d--- /dev/null+++ b/games/imposter/tests/play.c@@ -0,0 +1,220 @@+/* Plays Imposter on a computer, with scripted keys, and saves screenshots.+ *+ * play [--frames N] [--keys "10:ok,20-30:down,..."] [--shots "40:setup.ppm,..."] [--out DIR] [--saves DIR]+ * [--trace] [--no-typing] [--fuzz SEED] [--seed N] [--words] [--rounds N]+ *+ * A frame is 20 ms. Keys: left right up down ok exe back home erase, a to z (the letter keys), space. "a-b:key"+ * holds the key from frame a to b, "a:key" for one frame. --trace prints what each drawing shows (DRAW ...).+ * --fuzz presses random keys (Home now and then ends a session, the next one starts from the save).+ * --words checks the word lists; --rounds plays N rounds' draws straight away (ROUND ...).+ * At the end: STATE ... (the save). */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "../src/game.h"+#include "../src/plat.h"+#include "../src/ui.h"+#include "../../../launcher/src/font.h"++extern uint32_t host_keys, host_letters, host_time, host_seed;+extern bool host_typing;+void host_shot(const char *path);+void host_save_dir(const char *d);+int host_trace;++typedef struct {+ int a, b;+ uint32_t k, l;+} Hold;+static Hold holds[8192];+static int nholds;+typedef struct {+ int frame;+ char name[128];+} Shot;+static Shot shots[256];+static int nshots;+static char out_dir[512] = ".";++static void key_of(const char *s, uint32_t *k, uint32_t *l) {+ static const char *const names[] = {"left", "right", "up", "down", "ok", "exe", "back", "home", "erase"};+ static const uint32_t bits[] = {KB_LEFT, KB_RIGHT, KB_UP, KB_DOWN, KB_OK, KB_EXE, KB_BACK, KB_HOME, KB_ERASE};+ *k = *l = 0;+ for (int i = 0; i < 9; i++)+ if (!strcmp(s, names[i])) {+ *k = bits[i];+ return;+ }+ if (!strcmp(s, "space")) {+ *l = (uint32_t)1 << 26;+ return;+ }+ if (s[0] >= 'a' && s[0] <= 'z' && !s[1]) {+ *l = (uint32_t)1 << (s[0] - 'a');+ return;+ }+ fprintf(stderr, "unknown key %s\n", s);+ exit(2);+}++static void parse_keys(const char *spec) {+ char *buf = strdup(spec);+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {+ int a, b;+ char name[16];+ uint32_t k, l;+ if (sscanf(tok, "%d-%d:%15s", &a, &b, name) == 3) key_of(name, &k, &l), holds[nholds++] = (Hold){a, b, k, l};+ else if (sscanf(tok, "%d:%15s", &a, name) == 2) key_of(name, &k, &l), holds[nholds++] = (Hold){a, a, k, l};+ }+ free(buf);+}++static void parse_shots(const char *spec) {+ char *buf = strdup(spec);+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {+ Shot *s = &shots[nshots];+ if (sscanf(tok, "%d:%127s", &s->frame, s->name) == 2) nshots++;+ }+ free(buf);+}++static void print_state(void) {+ printf("STATE n %d names ", sv.nplayers);+ for (int i = 0; i < sv.nplayers; i++) printf("%s%s", i ? "," : "", sv.names[i]);+ printf(" imposters %d hint %d timer %d cats %u phase %d turn %d rounds %d word %d flags %d\n", sv.imposters, sv.hint,+ sv.timer, (unsigned)sv.cats, sv.phase, sv.turn, sv.rounds, sv.word, sv.flags);+}++/* the save always holds a game this one could have made */+static void invariants(int frame) {+ const char *bad = NULL;+ if (sv.nplayers > MAX_PLAYERS) bad = "players";+ for (int i = 0; i < sv.nplayers && !bad; i++) {+ size_t n = strlen(sv.names[i]);+ if (n < 1 || n > NAME_MAX || sv.names[i][0] == ' ' || sv.names[i][n - 1] == ' ') bad = "name";+ for (int j = 0; j < i && !bad; j++)+ if (!strcasecmp(sv.names[i], sv.names[j])) bad = "same names";+ }+ if (sv.phase) {+ int k = 0;+ for (int i = 0; i < MAX_PLAYERS; i++) k += sv.imps >> i & 1;+ if (sv.nplayers < MIN_PLAYERS) bad = "round with too few players";+ if (k < 1 || k > max_imposters(sv.nplayers) || sv.imps >> sv.nplayers) bad = "imposters";+ if (sv.turn >= sv.nplayers || sv.starter >= sv.nplayers) bad = "turn";+ if ((sv.word >> 6) >= N_CATS || (int)(sv.word & 63) >= word_count(sv.word >> 6)) bad = "word";+ if (sv.cats && !(sv.cats >> (sv.word >> 6) & 1)) bad = "word outside the categories";+ }+ if (bad) {+ printf("ERROR frame %d: %s\n", frame, bad);+ print_state();+ exit(3);+ }+}++static int check_words(void) {+ int bad = 0, total = 0, lo = 999, hi = 0;+ char a[WORD_MAX + 1], b[WORD_MAX + 1];+ for (int c = 0; c < N_CATS; c++) {+ int n = word_count(c);+ total += n;+ lo = n < lo ? n : lo, hi = n > hi ? n : hi;+ printf("CAT %s %d\n", categories[c].name, n);+ for (int i = 0; i < n; i++) {+ int len = word_get(c, i, a, sizeof a);+ if (len < 2 || len > WORD_MAX - 1 || a[0] == ' ' || a[len - 1] == ' ') printf("BAD word %s/%d '%s'\n", categories[c].name, i, a), bad++;+ for (int k = 0; k < len; k++)+ if ((uint8_t)a[k] < 32 || (uint8_t)a[k] > 126) printf("BAD letter in %s\n", a), bad++;+ for (int d = 0; d <= c; d++)+ for (int j = 0, m = word_count(d); j < m && (d < c || j < i); j++) {+ word_get(d, j, b, sizeof b);+ if (!strcasecmp(a, b)) printf("BAD twice %s (%s, %s)\n", a, categories[d].name, categories[c].name), bad++;+ }+ }+ }+ printf("WORDS cats %d total %d min %d max %d bad %d\n", N_CATS, total, lo, hi, bad);+ return bad ? 1 : 0;+}++int main(int argc, char **argv) {+ int frames = 600, fuzz = -1, rounds = 0;+ uint32_t seed = 1;+ char saves[512] = "build/host-saves";+ for (int i = 1; i < argc; i++) {+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) frames = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) parse_keys(argv[++i]);+ else if (!strcmp(argv[i], "--shots") && i + 1 < argc) parse_shots(argv[++i]);+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) snprintf(out_dir, sizeof out_dir, "%s", argv[++i]);+ else if (!strcmp(argv[i], "--saves") && i + 1 < argc) snprintf(saves, sizeof saves, "%s", argv[++i]);+ else if (!strcmp(argv[i], "--trace")) host_trace = 1;+ else if (!strcmp(argv[i], "--no-typing")) host_typing = false;+ else if (!strcmp(argv[i], "--fuzz") && i + 1 < argc) fuzz = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--seed") && i + 1 < argc) seed = (uint32_t)strtoul(argv[++i], 0, 10);+ else if (!strcmp(argv[i], "--words")) return check_words();+ else if (!strcmp(argv[i], "--rounds") && i + 1 < argc) rounds = atoi(argv[++i]);+ else {+ fprintf(stderr, "unknown option %s\n", argv[i]);+ return 2;+ }+ }+ host_save_dir(saves);+ host_seed = seed ? seed : 1;+ host_time = 1000;+ app_init(host_time);+ if (rounds) { /* the rules alone: the save's players and categories */+ for (int r = 0; r < rounds; r++) {+ round_new();+ char w[WORD_MAX + 1];+ int c = word_text(sv.word, w);+ printf("ROUND %d word %d %s cat %d %s imps %u starter %d\n", r, sv.word, w, c, categories[c].name,+ (unsigned)sv.imps, sv.starter);+ invariants(r);+ }+ print_state();+ return 0;+ }+ uint32_t fz = (uint32_t)(fuzz < 0 ? 1 : fuzz) * 2654435761u | 1, fkeys = 0, fletters = 0;+ int sessions = 1;+ for (int f = 0; f < frames; f++) {+ uint32_t k = 0, l = 0;+ for (int i = 0; i < nholds; i++)+ if (f >= holds[i].a && f <= holds[i].b) k |= holds[i].k, l |= holds[i].l;+ if (fuzz >= 0) {+ fz ^= fz << 13, fz ^= fz >> 17, fz ^= fz << 5;+ if (fz % 5 == 0) { /* a key held a few frames */+ static const uint32_t pool[] = {KB_LEFT, KB_RIGHT, KB_UP, KB_DOWN, KB_OK, KB_OK, KB_OK, KB_EXE, KB_BACK, KB_ERASE};+ uint32_t r = fz >> 8;+ fkeys = r % 41 == 0 ? KB_HOME : pool[r % 10];+ fletters = r % 3 == 0 ? (uint32_t)1 << (r / 7 % 27) : 0;+ if (r % 2) fkeys = 0;+ } else if (fz % 5 == 1) {+ fkeys = fletters = 0;+ }+ k |= fkeys, l |= fletters;+ }+ host_keys = k, host_letters = l;+ if (!app_step(k, l, host_time)) {+ printf("QUIT frame %d\n", f);+ if (fuzz < 0) {+ print_state();+ return 0;+ }+ sessions++;+ host_time += 20;+ app_init(host_time); /* the next session, from the save */+ fkeys = fletters = 0;+ }+ if (app_dirty()) app_draw();+ if (fuzz >= 0) invariants(f);+ for (int i = 0; i < nshots; i++)+ if (shots[i].frame == f) {+ char p[700];+ snprintf(p, sizeof p, "%s/%s", out_dir, shots[i].name);+ host_shot(p);+ }+ host_time += 20;+ }+ if (fuzz >= 0) printf("FUZZ sessions %d\n", sessions);+ game_save();+ print_state();+ return 0;+}diff --git a/games/imposter/tools/icon.py b/games/imposter/tools/icon.pynew file mode 100644index 00000000..fee28ffd--- /dev/null+++ b/games/imposter/tools/icon.py@@ -0,0 +1,40 @@+#!/usr/bin/env python3+"""Draws src/icon.png (55 x 56): a red figure with a question mark for a face, on the game's indigo.+Then round it as every NumPlay icon: python3 ../../tools/round_icons.py src/icon.png++Usage (in games/imposter): python3 tools/icon.py"""+import os+import sys++from PIL import Image, ImageDraw, ImageFont++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, os.path.join(HERE, "..", "..", "..", "tools"))+from fontgen import font_file # noqa: E402 (Nunito, NumPlay's font)++K = 8 # drawn 8 times bigger, then scaled down+W, H = 55 * K, 56 * K+++def lerp(a, b, t):+ return tuple(round(x + (y - x) * t) for x, y in zip(a, b))+++im = Image.new("RGB", (W, H))+top, bottom = (0x30, 0x38, 0x74), (0x12, 0x16, 0x30)+d = ImageDraw.Draw(im)+for y in range(H):+ d.line([(0, y), (W, y)], fill=lerp(top, bottom, y / (H - 1)))++red, dark_red = (0xE8, 0x36, 0x42), (0xB0, 0x1E, 0x2C)+cx = W / 2+# the shoulders, then the head+d.rounded_rectangle([cx - 21 * K, 37 * K, cx + 21 * K, 64 * K], radius=15 * K, fill=dark_red)+d.ellipse([cx - 14.5 * K, 7 * K, cx + 14.5 * K, 36 * K], fill=red)+font = ImageFont.truetype(font_file(), 26 * K)+font.set_variation_by_axes([1000])+d.text((cx, 22 * K), "?", font=font, fill=(255, 255, 255), anchor="mm")++im = im.resize((55, 56), Image.LANCZOS)+im.save(os.path.join(HERE, "..", "src", "icon.png"))+print("src/icon.png")