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
NumBlocks: chat, commands, Allow Cheats and Open to LAN
Mason Chen6398f05ea243
diff --git a/Makefile b/Makefileindex fa3cac78..680f6696 100644--- a/Makefile+++ b/Makefile@@ -17,6 +17,8 @@ PY ?= python3CARGO ?= cargoB = buildRAM_LIMIT = 153676+# the calculator's space for installed apps (0x90200000 to 0x903F0000 in its flash)+APP_SPACE = 2031616# NumPlay and its discreet versions: the same app, with another name and icon# on the calculator's home screen. Each one is a release file.@@ -126,7 +128,9 @@ $(B)/%.nwa: $(ARM_OBJS) $(MODULES) $(B)/variant/%-name.o $(B)/variant/%-icon.ocheck: nwa@for v in $(VARIANTS); do $(NWLINK) nwa-bin --ram-length $(RAM_LIMIT) $(B)/$$v.nwa $(B)/$$v.bin || exit 1; \- echo "$$v.nwa installs as $$(wc -c < $(B)/$$v.bin) bytes; its RAM fits in $(RAM_LIMIT) bytes"; done+ n=$$(wc -c < $(B)/$$v.bin); \+ echo "$$v.nwa installs as $$n bytes ($$(( $(APP_SPACE) - n )) to spare); its RAM fits in $(RAM_LIMIT) bytes"; \+ [ $$n -le $(APP_SPACE) ] || { echo "$$v.nwa is bigger than the calculator's app space ($(APP_SPACE) bytes)"; exit 1; }; done# ------------------------------------------------------------------ games on their ownAPP_numdash = games/numdash/build/numdash.nwa:NumDash.nwadiff --git a/games/numblocks/Makefile b/games/numblocks/Makefileindex d6cd6309..6a3fe770 100644--- a/games/numblocks/Makefile+++ b/games/numblocks/Makefile@@ -10,7 +10,7 @@ BUILD_DIR = outputSTRIP ?= arm-none-eabi-strip --strip-unneededCLIENT_JAR ?= client.jarGEN ?= src/gen.c-GAME = src/main.c src/world.c src/edits.c src/render.c src/player.c src/phys.c src/inv.c src/entity.c src/mob.c src/tick.c src/gui.c src/hand.c src/save.c src/data.c $(GEN)+GAME = src/main.c src/world.c src/edits.c src/render.c src/player.c src/phys.c src/inv.c src/entity.c src/mob.c src/tick.c src/gui.c src/hand.c src/save.c src/data.c src/names.c src/command.c $(GEN)HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h MakefileCFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device)diff --git a/games/numblocks/src/command.c b/games/numblocks/src/command.cnew file mode 100644index 00000000..cf44ca48--- /dev/null+++ b/games/numblocks/src/command.c@@ -0,0 +1,729 @@+/* The commands typed in the chat, as Minecraft 1.8.8 has them (net.minecraft.command): what they+ * do, what they answer (its words, from en_US.lang), and how the toolbox key finishes their words+ * (addTabCompletionOptions). Without cheats only /help, /me and /seed work, as in a world of one's+ * own that does not allow them. */+#include <math.h>+#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */++extern uint32_t game_time;+#define PLAYER "Player"+#define MAX_ARGS 8++/* ---------------------------------------------------------------- what is said back */+static char out[160];+static int out_n;+static void put(const char *s) {+ while (*s && out_n < (int)sizeof out - 1) out[out_n++] = *s++;+ out[out_n] = 0;+}+static void put_int(long long v) {+ char b[24];+ int n = 0;+ unsigned long long u = v < 0 ? 0 - (unsigned long long)v : (unsigned long long)v;+ do b[n++] = (char)('0' + u % 10), u /= 10;+ while (u);+ if (v < 0) b[n++] = '-';+ char r[24];+ for (int i = 0; i < n; i++) r[i] = b[n - 1 - i];+ r[n] = 0;+ put(r);+}+/* a double as Java writes one: at least one decimal (64.0, 100.5) */+static void put_num(float v) {+ long long w = (long long)roundf(v * 1000);+ if (w < 0) put("-"), w = -w;+ put_int(w / 1000);+ put(".");+ int f = (int)(w % 1000);+ char d[4] = {(char)('0' + f / 100), (char)('0' + f / 10 % 10), (char)('0' + f % 10), 0};+ int n = 3;+ while (n > 1 && d[n - 1] == '0') d[--n] = 0;+ put(d);+}+/* a translation: %s and %d take the arguments in turn (strings, then numbers) */+static void say(int color, const char *f, const char *s1, const char *s2, long long d1, long long d2) {+ out_n = 0, out[0] = 0;+ const char *s[2] = {s1, s2};+ long long d[2] = {d1, d2};+ int si = 0, di = 0;+ for (; *f; f++) {+ if (*f == '%' && f[1] == 's') put(si < 2 && s[si] ? s[si] : ""), si++, f++;+ else if (*f == '%' && f[1] == 'd') put_int(di < 2 ? d[di] : 0), di++, f++;+ else {+ char c[2] = {*f, 0};+ put(c);+ }+ }+ chat_add(out, color);+}+static void ok(const char *f, const char *s1, long long d1) { say(CHAT_WHITE, f, s1, NULL, d1, 0); }+static void fail(const char *f, const char *s1, long long d1, long long d2) { say(CHAT_RED, f, s1, NULL, d1, d2); }++/* CommandException: the command stops, the chat says why (in red) */+static bool failed;+static void usage(const char *u) {+ if (!failed) say(CHAT_RED, "Usage: %s", u, NULL, 0, 0);+ failed = true;+}+static void error(const char *f, const char *s1, long long d1, long long d2) {+ if (!failed) fail(f, s1, d1, d2);+ failed = true;+}++/* ---------------------------------------------------------------- reading the words */+static bool is_num(const char *s, bool dec) {+ if (*s == '-' || *s == '+') s++;+ if (!*s) return false;+ bool dot = false;+ for (; *s; s++) {+ if (*s == '.' && dec && !dot) dot = true;+ else if (*s < '0' || *s > '9') return false;+ }+ return true;+}+/* CommandBase.parseInt: a whole number from lo to hi */+static long long num(const char *s, long long lo, long long hi) {+ if (failed) return lo;+ if (!is_num(s, false) || strlen(s) > 11) {+ error("'%s' is not a valid number", s, 0, 0);+ return lo;+ }+ long long v = 0;+ const char *p = s + (*s == '-' || *s == '+');+ for (; *p; p++) v = v * 10 + (*p - '0');+ if (*s == '-') v = -v;+ if (v < lo) error("The number you have entered (%d) is too small, it must be at least %d", NULL, v, lo);+ else if (v > hi) error("The number you have entered (%d) is too big, it must be at most %d", NULL, v, hi);+ return v;+}+static float to_float(const char *s) {+ float v = 0, f = 0.1f;+ bool neg = *s == '-';+ if (*s == '-' || *s == '+') s++;+ for (; *s >= '0' && *s <= '9'; s++) v = v * 10 + (*s - '0');+ if (*s == '.')+ for (s++; *s >= '0' && *s <= '9'; s++) v += (*s - '0') * f, f /= 10;+ return neg ? -v : v;+}+/* CommandBase.parseCoordinate: a number, or "~" (and "~5") from where the player is; whole numbers+ * of x and z at the middle of their block (center) */+static float coord(float base, const char *s, bool center) {+ if (failed) return base;+ bool rel = *s == '~';+ if (rel) s++;+ if (rel && !*s) return base;+ if (!is_num(s, true)) {+ error("'%s' is not a valid number", s - rel, 0, 0);+ return base;+ }+ float v = to_float(s);+ if (rel) return base + v;+ if (center && !strchr(s, '.')) v += 0.5f;+ return v;+}+/* the player named: "Player", or a selector (@p, @a, @r, @e: there is no one else) */+static bool player(const char *s) {+ if (failed) return false;+ if (!strcmp(s, PLAYER) || (s[0] == '@' && strchr("pare", s[1]) && (!s[2] || s[2] == '['))) return true;+ error("That player cannot be found", NULL, 0, 0);+ return false;+}+static int to_int(const char *s) {+ int v = 0;+ bool neg = *s == '-';+ if (*s == '-' || *s == '+') s++;+ for (; *s >= '0' && *s <= '9'; s++) v = v * 10 + (*s - '0');+ return neg ? -v : v;+}+static const char *strip_ns(const char *s) { return !strncmp(s, "minecraft:", 10) ? s + 10 : s; }+/* a block's id by name or number (Block.getBlockFromName); -1: none */+static int block_named(const char *s) {+ const char *n = strip_ns(s);+ if (is_num(n, false)) {+ int v = to_int(n);+ return v >= 0 && v < 198 && mc_block_name[v][0] ? v : -1;+ }+ for (int i = 0; i < 198; i++)+ if (mc_block_name[i][0] && !strcmp(mc_block_name[i], n)) return i;+ return -1;+}+/* an item's id by name or number (Item.getByNameOrId): items' names first, then blocks that are items */+static int item_named(const char *s) {+ const char *n = strip_ns(s);+ if (is_num(n, false)) {+ int v = to_int(n);+ if (v >= 256 && v < 432 && mc_item_name[v - 256][0]) return v;+ return v >= 0 && v < 198 && (mc_block_item[v >> 3] >> (v & 7) & 1) ? v : -1;+ }+ for (int i = 0; i < 176; i++)+ if (mc_item_name[i][0] && !strcmp(mc_item_name[i], n)) return 256 + i;+ for (int i = 0; i < 198; i++)+ if ((mc_block_item[i >> 3] >> (i & 7) & 1) && !strcmp(mc_block_name[i], n)) return i;+ return -1;+}+/* NumBlocks' item for Minecraft's id and data; -1: none */+static int give_of(int id, int data) {+ int k = id << 4 | data;+ for (int i = 0; i < n_give; i++)+ if (give_key[i] == k) return give_id[i];+ return -1;+}++/* ---------------------------------------------------------------- the commands */+enum { C_CLEAR, C_DIFFICULTY, C_EFFECT, C_GAMEMODE, C_GAMERULE, C_GIVE, C_HELP, C_KILL, C_ME, C_SAY, C_SEED,+ C_SETBLOCK, C_SPAWNPOINT, C_SUMMON, C_TIME, C_TOGGLEDOWNFALL, C_TP, C_WEATHER, C_XP, N_COMMANDS };+static const char *const cmd_name[N_COMMANDS] = {"clear", "difficulty", "effect", "gamemode", "gamerule", "give",+ "help", "kill", "me", "say", "seed", "setblock", "spawnpoint",+ "summon", "time", "toggledownfall", "tp", "weather", "xp"};+static const char *const cmd_usage[N_COMMANDS] = {+ "/clear [player] [item] [data] [maxCount] [dataTag]",+ "/difficulty <new difficulty>",+ "/effect <player> <effect> [seconds] [amplifier] [hideParticles] OR /effect <player> clear",+ "/gamemode <mode> [player]",+ "/gamerule <rule name> [value]",+ "/give <player> <item> [amount] [data] [dataTag]",+ "/help [page|command name]",+ "/kill [player|entity]",+ "/me <action ...>",+ "/say <message ...>",+ "/seed",+ "/setblock <x> <y> <z> <TileName> [dataValue] [oldBlockHandling] [dataTag]",+ "/spawnpoint [player] [<x> <y> <z>]",+ "/summon <EntityName> [x] [y] [z] [dataTag]",+ "/time <set|add|query> <value>",+ "/toggledownfall",+ "/tp [target player] <destination player> OR /tp [target player] <x> <y> <z> [<y-rot> <x-rot>]",+ "/weather <clear|rain|thunder> [duration in seconds]",+ "/xp <amount> [player] OR /xp <amount>L [player]"};+/* (permission level 0, or /seed in a world of one's own) */+static bool allowed(int c) { return cheats_on() || c == C_HELP || c == C_ME || c == C_SEED; }++static const char *const mode_name[2] = {"Survival Mode", "Creative Mode"};+static const char *const modes[4] = {"survival", "creative", "adventure", "spectator"};+static const char *const diffs[4] = {"peaceful", "easy", "normal", "hard"};+static const char *const diff_name[4] = {"Peaceful", "Easy", "Normal", "Hard"};+static const char *const rule_name[8] = {"keepInventory", "doDaylightCycle", "doMobSpawning", "mobGriefing",+ "naturalRegeneration", "doTileDrops", "doMobLoot", "doFireTick"};+static const char *const mob_name[8] = {"Zombie", "Skeleton", "Creeper", "Spider", "Pig", "Cow", "Sheep", "Chicken"};+/* the effects NumBlocks has: Potion's ids and names */+static const uint8_t eff_id[3] = {19, 17, 10};+static const char *const eff_key[3] = {"poison", "hunger", "regeneration"};+static const char *const eff_name[3] = {"Poison", "Hunger", "Regeneration"};++/* /gamemode, /difficulty: a name, its first letter, or its number */+static int choice(const char *s, const char *const *names, int n, const char *const *letters) {+ for (int i = 0; i < n; i++)+ if (!strcmp(s, names[i]) || (letters && !strcmp(s, letters[i]))) return i;+ return (int)num(s, 0, n - 1);+}++static void cmd_gamemode(char **a, int n) {+ if (n < 1) return usage(cmd_usage[C_GAMEMODE]);+ static const char *const l[4] = {"s", "c", "a", "sp"};+ int m = choice(a[0], modes, 4, l);+ if (n > 1) player(a[1]);+ if (failed) return;+ if (m > 1) return error("'%s' is not a valid number", a[0], 0, 0); /* (NumBlocks has no adventure or spectator) */+ pl.mode = (uint8_t)m;+ pl.fall = 0;+ if (m == 0) pl.flying = false;+ chat_add("Your game mode has been updated", CHAT_WHITE);+ ok("Set own game mode to %s", mode_name[m], 0);+}++static void cmd_time(char **a, int n) {+ if (n < 2) return usage(cmd_usage[C_TIME]);+ if (!strcmp(a[0], "set")) {+ long long v = !strcmp(a[1], "day") ? 1000 : !strcmp(a[1], "night") ? 13000 : num(a[1], 0, 0x7FFFFFFF);+ if (failed) return;+ game_time = (uint32_t)v;+ ok("Set the time to %d", NULL, v);+ } else if (!strcmp(a[0], "add")) {+ long long v = num(a[1], 0, 0x7FFFFFFF);+ if (failed) return;+ game_time += (uint32_t)v;+ ok("Added %d to the time", NULL, v);+ } else if (!strcmp(a[0], "query")) {+ if (!strcmp(a[1], "daytime")) ok("Time is %d", NULL, game_time % 24000);+ else if (!strcmp(a[1], "gametime")) ok("Time is %d", NULL, game_time);+ else usage(cmd_usage[C_TIME]);+ } else+ usage(cmd_usage[C_TIME]);+}++static void cmd_weather(char **a, int n) {+ if (n < 1 || n > 2) return usage(cmd_usage[C_WEATHER]);+ int t = (300 + rnd(600)) * 20;+ if (n == 2) t = (int)num(a[1], 1, 1000000) * 20;+ if (failed) return;+ if (!strcmp(a[0], "clear")) {+ weather.rain_time = weather.thunder_time = 0, weather.raining = weather.thundering = 0;+ ok("Changing to clear weather", NULL, 0);+ } else if (!strcmp(a[0], "rain")) {+ weather.rain_time = weather.thunder_time = t, weather.raining = 1, weather.thundering = 0;+ ok("Changing to rainy weather", NULL, 0);+ } else if (!strcmp(a[0], "thunder")) {+ weather.rain_time = weather.thunder_time = t, weather.raining = weather.thundering = 1;+ ok("Changing to rain and thunder", NULL, 0);+ } else+ usage(cmd_usage[C_WEATHER]);+}++static void cmd_give(char **a, int n) {+ if (n < 2) return usage(cmd_usage[C_GIVE]);+ player(a[0]);+ if (failed) return;+ int id = item_named(a[1]);+ if (id < 0) return error("There is no such item with name %s", a[1], 0, 0);+ int count = n > 2 ? (int)num(a[2], 1, 64) : 1, data = n > 3 ? (int)num(a[3], -2147483647, 2147483647) : 0;+ if (failed) return;+ /* data: which kind (wool's colour), or for tools how worn */+ int it = data >= 0 && data <= 15 ? give_of(id, data) : -1;+ if (it < 0) it = give_of(id, 0);+ if (it < 0) return error("There is no such item with name %s", a[1], 0, 0);+ int wear = item_dur(it) ? (data < 0 ? 0 : data > item_dur(it) ? item_dur(it) : data) : 0;+ /* InventoryPlayer.addItemStackToInventory; what does not fit falls at the player's feet */+ int left = inv_add(pl.inv, 36, it, count, wear);+ if (left) ent_drop(it, left, wear, pl.x, pl.y + 0.5f, pl.z, false);+ char lab[40] = "[";+ strcat(lab, item_label(it));+ strcat(lab, "]");+ say(CHAT_WHITE, "Given %s * %d to %s", lab, PLAYER, count, 0);+}++static void cmd_tp(char **a, int n) {+ if (n < 1) return usage(cmd_usage[C_TP]);+ int i = 0;+ if (n == 2 || n == 4 || n == 6) player(a[i++]);+ if (failed) return;+ if (n - i == 1) {+ /* to a player: the only one is here */+ player(a[i]);+ if (!failed) say(CHAT_WHITE, "Teleported %s to %s", PLAYER, PLAYER, 0, 0);+ return;+ }+ if (n - i != 3 && n - i != 5) return usage(cmd_usage[C_TP]);+ float x = coord(pl.x, a[i], true), y = coord(pl.y, a[i + 1], false), z = coord(pl.z, a[i + 2], true);+ float yaw = pl.yaw, pitch = pl.pitch;+ if (n - i == 5) yaw = coord(pl.yaw, a[i + 3], false), pitch = coord(pl.pitch, a[i + 4], false);+ if (failed) return;+ if (x < -30000000 || x > 30000000 || z < -30000000 || z > 30000000 || y < -512 || y > 512)+ return error("'%s' is not a valid number", a[i], 0, 0);+ pl.x = x, pl.y = y, pl.z = z, pl.vx = pl.vy = pl.vz = 0, pl.fall = 0;+ yaw = fmodf(yaw, 360);+ if (yaw >= 180) yaw -= 360;+ if (yaw < -180) yaw += 360;+ pl.yaw = yaw, pl.pitch = pitch < -90 ? -90 : pitch > 90 ? 90 : pitch;+ camera_reset();+ out_n = 0;+ put("Teleported " PLAYER " to "), put_num(x), put(", "), put_num(y), put(", "), put_num(z);+ chat_add(out, CHAT_WHITE);+}++static void cmd_kill(char **a, int n) {+ if (n > 0) player(a[0]);+ if (failed) return;+ /* EntityPlayer.onKillCommand: out of the world */+ player_hurt(3.4e38f, DMG_VOID);+ ok("Killed %s", PLAYER, 0);+}++static void cmd_difficulty(char **a, int n) {+ if (n < 1) return usage(cmd_usage[C_DIFFICULTY]);+ static const char *const l[4] = {"p", "e", "n", "h"};+ int d = choice(a[0], diffs, 4, l);+ if (failed) return;+ opt.difficulty = (uint8_t)d;+ save_options();+ ok("Set game difficulty to %s", diff_name[d], 0);+}++static void cmd_seed(void) {+ out_n = 0;+ put("Seed: "), put_int(world_seed);+ chat_add(out, CHAT_WHITE);+}++static void cmd_spawnpoint(char **a, int n) {+ if (n != 0 && n != 1 && n != 4) return usage(cmd_usage[C_SPAWNPOINT]);+ if (n) player(a[0]);+ int x = (int)floorf(pl.x), y = (int)floorf(pl.y + 0.5f), z = (int)floorf(pl.z);+ if (n == 4) x = (int)floorf(coord((float)x, a[1], false)), y = (int)floorf(coord((float)y, a[2], false)),+ z = (int)floorf(coord((float)z, a[3], false));+ if (failed) return;+ pl.spawn_x = x, pl.spawn_y = y, pl.spawn_z = z;+ out_n = 0;+ put("Set " PLAYER "'s spawn point to ("), put_int(x), put(", "), put_int(y), put(", "), put_int(z), put(")");+ chat_add(out, CHAT_WHITE);+}++static void cmd_xp(char **a, int n) {+ if (n < 1) return usage(cmd_usage[C_XP]);+ char v[16];+ strncpy(v, a[0], 15), v[15] = 0;+ int l = (int)strlen(v);+ bool levels = l && (v[l - 1] == 'l' || v[l - 1] == 'L');+ if (levels) v[l - 1] = 0;+ long long k = num(v, -2147483647, 2147483647);+ if (n > 1) player(a[1]);+ if (failed) return;+ if (levels) {+ /* EntityPlayer.addExperienceLevel */+ pl.xp_level += (int)k;+ if (pl.xp_level < 0) pl.xp_level = 0, pl.xp = 0, pl.xp_total = 0;+ if (k < 0) say(CHAT_WHITE, "Taken %d levels from %s", PLAYER, NULL, -k, 0);+ else say(CHAT_WHITE, "Given %d levels to %s", PLAYER, NULL, k, 0);+ } else {+ if (k < 0) return error("Cannot give player negative experience points", NULL, 0, 0);+ player_add_xp((int)k);+ say(CHAT_WHITE, "Given %d experience to %s", PLAYER, NULL, k, 0);+ }+}++static void cmd_clear(char **a, int n) {+ if (n > 0) player(a[0]);+ int id = -1, data = -1, most = -1;+ if (n > 1) {+ id = item_named(a[1]);+ if (id < 0 && !failed) error("There is no such item with name %s", a[1], 0, 0);+ }+ if (n > 2) data = (int)num(a[2], -1, 2147483647);+ if (n > 3) most = (int)num(a[3], -1, 2147483647);+ if (failed) return;+ /* InventoryPlayer.clearMatchingItems: the inventory, the armour, what the cursor holds */+ Stack *s[41];+ int k = 0;+ for (int i = 0; i < 36; i++) s[k++] = &pl.inv[i];+ for (int i = 0; i < 4; i++) s[k++] = &pl.armor[i];+ s[k++] = &pl.cursor;+ int gone = 0;+ for (int i = 0; i < k && (most < 0 || gone < most); i++) {+ Stack *t = s[i];+ if (!t->id) continue;+ if (id >= 0) {+ int want = data < 0 ? -1 : give_of(id, data & 15);+ bool match = false;+ for (int g = 0; g < n_give && !match; g++)+ if (give_id[g] == t->id && (give_key[g] >> 4) == id && (want < 0 || want == t->id)) match = true;+ if (!match) continue;+ }+ int c = item_count(t), take = most < 0 || most - gone >= c ? c : most - gone;+ gone += take;+ if (take == c) t->id = 0, t->aux = 0;+ else stack_take(t, take);+ }+ if (!gone) return error("Could not clear the inventory of %s, no items to remove", PLAYER, 0, 0);+ say(CHAT_WHITE, "Cleared the inventory of %s, removing %d items", PLAYER, NULL, gone, 0);+}++static void cmd_effect(char **a, int n) {+ if (n < 2) return usage(cmd_usage[C_EFFECT]);+ player(a[0]);+ if (failed) return;+ if (!strcmp(a[1], "clear")) {+ bool any = false;+ for (int i = 0; i < 3; i++) any |= pl.eff[i] > 0, pl.eff[i] = 0, pl.eff_amp[i] = 0;+ if (!any) return error("Couldn't take any effects from %s as they do not have any", PLAYER, 0, 0);+ ok("Took all effects from %s", PLAYER, 0);+ return;+ }+ const char *e = strip_ns(a[1]);+ int k = -1;+ for (int i = 0; i < 3; i++)+ if (!strcmp(e, eff_key[i]) || (is_num(e, false) && to_int(e) == eff_id[i])) k = i;+ if (k < 0) return error(is_num(e, false) ? "There is no such mob effect with ID %d" : "There is no such mob effect with ID %s",+ e, is_num(e, false) ? to_int(e) : 0, 0);+ int secs = n > 2 ? (int)num(a[2], 0, 1000000) : 30, amp = n > 3 ? (int)num(a[3], 0, 255) : 0;+ if (failed) return;+ if (!secs) {+ if (!pl.eff[k]) {+ out_n = 0;+ put("Couldn't take "), put(eff_name[k]), put(" from " PLAYER " as they do not have the effect");+ return error("%s", out, 0, 0);+ }+ pl.eff[k] = 0;+ out_n = 0;+ put("Took "), put(eff_name[k]), put(" from " PLAYER);+ chat_add(out, CHAT_WHITE);+ return;+ }+ pl.eff[k] = (uint16_t)(secs * 20 > 65535 ? 65535 : secs * 20), pl.eff_amp[k] = (uint8_t)amp;+ out_n = 0;+ put("Given "), put(eff_name[k]), put(" (ID "), put_int(eff_id[k]), put(") * "), put_int(amp + 1);+ put(" to " PLAYER " for "), put_int(secs), put(" seconds");+ chat_add(out, CHAT_WHITE);+}++static void cmd_summon(char **a, int n) {+ if (n < 1) return usage(cmd_usage[C_SUMMON]);+ float x = pl.x, y = pl.y, z = pl.z;+ if (n >= 4) x = coord(x, a[1], true), y = coord(y, a[2], false), z = coord(z, a[3], true);+ if (failed) return;+ if (y < 0 || y >= WORLD_H || !world_loaded((int)floorf(x), (int)floorf(y), (int)floorf(z)))+ return error("Cannot summon the object out of the world", NULL, 0, 0);+ if (!strcmp(a[0], "LightningBolt")) {+ bolt.x = x, bolt.y = y, bolt.z = z;+ bolt.on = 1, bolt.state = 2, bolt.living = (int8_t)(rnd(3) + 1), bolt.seed = (uint32_t)rnd(1 << 30);+ ok("Object successfully summoned", NULL, 0);+ return;+ }+ for (int i = 0; i < 8; i++)+ if (!strcmp(a[0], mob_name[i])) {+ if (!mob_summon(E_ZOMBIE + i, x, y, z)) return error("Unable to summon object", NULL, 0, 0);+ ok("Object successfully summoned", NULL, 0);+ return;+ }+ error("Unable to summon object", NULL, 0, 0);+}++static void cmd_setblock(char **a, int n) {+ if (n < 4) return usage(cmd_usage[C_SETBLOCK]);+ int x = (int)floorf(coord(floorf(pl.x), a[0], false)), y = (int)floorf(coord(floorf(pl.y + 0.5f), a[1], false)),+ z = (int)floorf(coord(floorf(pl.z), a[2], false));+ if (failed) return;+ int id = block_named(a[3]);+ if (id < 0) return error("There is no such block with ID/name %s", a[3], 0, 0);+ int data = n > 4 ? (int)num(a[4], 0, 15) : 0;+ if (failed) return;+ if (y < 0 || y >= WORLD_H || !world_loaded(x, y, z)) return error("Cannot place block outside of the world", NULL, 0, 0);+ /* the state: the block's with that data, else its first */+ int b = -1;+ for (int i = 0; i < B_COUNT && b < 0; i++)+ if (blk_id[i] == id && blk_meta[i] == data) b = i;+ for (int i = 0; i < B_COUNT && b < 0; i++)+ if (blk_id[i] == id) b = i;+ if (b < 0) return error("There is no such block with ID/name %s", a[3], 0, 0);+ int was = world_get(x, y, z);+ if (n > 5) {+ if (!strcmp(a[5], "keep") && was != B_AIR) return error("The block couldn't be placed", NULL, 0, 0);+ if (!strcmp(a[5], "destroy")) break_block_at(x, y, z, true);+ }+ if (world_get(x, y, z) == b) return error("The block couldn't be placed", NULL, 0, 0);+ /* (a chest or furnace replaced is emptied first, nothing falls out) */+ tiles_forget(x, y, z);+ world_set(x, y, z, b);+ neighbours_changed(x, y, z);+ ok("Block placed", NULL, 0);+}++static void cmd_gamerule(char **a, int n) {+ if (n == 0) {+ /* all of them */+ out_n = 0;+ for (int i = 0; i < 8; i++) put(i ? ", " : ""), put(rule_name[i]);+ chat_add(out, CHAT_WHITE);+ return;+ }+ int r = -1;+ for (int i = 0; i < 8; i++)+ if (!strcmp(a[0], rule_name[i])) r = i;+ if (r < 0) return error("No game rule called '%s' is available", a[0], 0, 0);+ if (n == 1) {+ out_n = 0;+ put(rule_name[r]), put(" = "), put(rule(1 << r) ? "true" : "false");+ chat_add(out, CHAT_WHITE);+ return;+ }+ /* (GameRules.setOrCreateGameRule: true is "true", anything else false) */+ if (!strcmp(a[1], "true")) game_rules |= (uint8_t)(1 << r);+ else game_rules &= (uint8_t)~(1 << r);+ ok("Game rule has been updated", NULL, 0);+}++static void cmd_help(char **a, int n) {+ /* the commands that may be used, by name, 7 a page */+ int list[N_COMMANDS], k = 0;+ for (int c = 0; c < N_COMMANDS; c++)+ if (allowed(c)) list[k++] = c;+ int pages = (k - 1) / 7, page = 0;+ if (n > 0) {+ for (int c = 0; c < N_COMMANDS; c++)+ if (!strcmp(a[0], cmd_name[c]) && allowed(c)) return usage(cmd_usage[c]);+ if (!is_num(a[0], false)) return error("Unknown command. Try /help for a list of commands", NULL, 0, 0);+ page = (int)num(a[0], 1, pages + 1) - 1;+ if (failed) return;+ }+ say(CHAT_DARK_GREEN, "--- Showing help page %d of %d (/help <page>) ---", NULL, NULL, page + 1, pages + 1);+ for (int i = page * 7; i < k && i < page * 7 + 7; i++) chat_add(cmd_usage[list[i]], CHAT_WHITE);+ if (page == 0)+ chat_add("Tip: Use the toolbox key while typing a command to auto-complete the command or its arguments",+ CHAT_GREEN);+}++/* ---------------------------------------------------------------- running a line */+/* the line cut into words (in place); how many */+static int words(char *s, char **w) {+ int n = 0;+ while (*s && n < MAX_ARGS + 1) {+ while (*s == ' ') *s++ = 0;+ if (!*s) break;+ w[n++] = s;+ while (*s && *s != ' ') s++;+ }+ return n;+}++void command_run(const char *line) {+ if (line[0] != '/') {+ /* said: "<Player> hello" */+ out_n = 0;+ put("<" PLAYER "> "), put(line);+ chat_add(out, CHAT_WHITE);+ return;+ }+ char b[64], *w[MAX_ARGS + 1];+ strncpy(b, line + 1, sizeof b - 1), b[sizeof b - 1] = 0;+ int n = words(b, w);+ int c = -1;+ for (int i = 0; i < N_COMMANDS && n; i++)+ if (!strcmp(w[0], cmd_name[i])) c = i;+ if (n && !strcmp(w[0], "?")) c = C_HELP;+ failed = false;+ if (c < 0) return error("Unknown command. Try /help for a list of commands", NULL, 0, 0);+ if (!allowed(c)) return error("You do not have permission to use this command", NULL, 0, 0);+ char **a = w + 1;+ n--;+ switch (c) {+ case C_CLEAR: cmd_clear(a, n); break;+ case C_DIFFICULTY: cmd_difficulty(a, n); break;+ case C_EFFECT: cmd_effect(a, n); break;+ case C_GAMEMODE: cmd_gamemode(a, n); break;+ case C_GAMERULE: cmd_gamerule(a, n); break;+ case C_GIVE: cmd_give(a, n); break;+ case C_HELP: cmd_help(a, n); break;+ case C_KILL: cmd_kill(a, n); break;+ case C_ME:+ case C_SAY:+ if (n < 1) return usage(cmd_usage[c]);+ out_n = 0;+ put(c == C_ME ? "* " PLAYER " " : "[" PLAYER "] ");+ for (int i = 0; i < n; i++) put(i ? " " : ""), put(a[i]);+ chat_add(out, CHAT_WHITE);+ break;+ case C_SEED: cmd_seed(); break;+ case C_SETBLOCK: cmd_setblock(a, n); break;+ case C_SPAWNPOINT: cmd_spawnpoint(a, n); break;+ case C_SUMMON: cmd_summon(a, n); break;+ case C_TIME: cmd_time(a, n); break;+ case C_TOGGLEDOWNFALL:+ weather.raining = !weather.raining;+ ok("Toggled downfall", NULL, 0);+ break;+ case C_TP: cmd_tp(a, n); break;+ case C_WEATHER: cmd_weather(a, n); break;+ case C_XP: cmd_xp(a, n); break;+ }+}++/* ---------------------------------------------------------------- finishing words */+/* CommandBase.getListOfStringsMatchingLastWord: the names that start as the word does; blocks and+ * items with "minecraft:" before them (found by the name without it too) */+static int cmp_n; /* (the ways found so far, while looking for the k-th) */+static bool offer(const char *word, const char *name, const char *ns, int k, char *o, int max) {+ int nl = (int)strlen(ns);+ bool full = !strncmp(word, ns, strlen(word) < (size_t)nl ? strlen(word) : (size_t)nl) &&+ (strlen(word) <= (size_t)nl || !strncmp(word + nl, name, strlen(word) - nl));+ bool bare = !strncmp(word, name, strlen(word));+ if (!full && !bare) return false;+ if (cmp_n++ != k) return false;+ int i = 0;+ for (const char *p = ns; *p && i < max - 1; p++) o[i++] = *p;+ for (const char *p = name; *p && i < max - 1; p++) o[i++] = *p;+ o[i] = 0;+ return true;+}+static bool offer_list(const char *word, const char *const *names, int n, int k, char *o, int max) {+ for (int i = 0; i < n; i++)+ if (offer(word, names[i], "", k, o, max)) return true;+ return false;+}++bool command_complete(const char *line, int k, int *at, char *o, int max) {+ if (line[0] != '/') return false;+ /* the words before the last one, and the last (maybe empty) */+ int len = (int)strlen(line), st = len;+ while (st > 1 && line[st - 1] != ' ') st--;+ *at = st;+ const char *word = line + st;+ char b[64], *w[MAX_ARGS + 1];+ int pl_len = st - 1 < (int)sizeof b - 1 ? st - 1 : (int)sizeof b - 1;+ memcpy(b, line + 1, (size_t)(pl_len > 0 ? pl_len : 0)), b[pl_len > 0 ? pl_len : 0] = 0;+ int n = words(b, w);+ cmp_n = 0;+ static const char *const players[1] = {PLAYER};+ if (n == 0) {+ /* the command's name */+ for (int c = 0; c < N_COMMANDS; c++)+ if (allowed(c) && offer(word, cmd_name[c], "", k, o, max)) return true;+ return false;+ }+ int c = -1;+ for (int i = 0; i < N_COMMANDS; i++)+ if (!strcmp(w[0], cmd_name[i]) && allowed(i)) c = i;+ int arg = n - 1; /* which argument the word is */+ static const char *const time_a[3] = {"set", "add", "query"}, *const time_set[2] = {"day", "night"},+ *const time_q[2] = {"daytime", "gametime"}, *const weathers[3] = {"clear", "rain", "thunder"},+ *const bools[2] = {"true", "false"}, *const handling[3] = {"replace", "destroy", "keep"};+ switch (c) {+ case C_GAMEMODE: return arg == 0 ? offer_list(word, modes, 4, k, o, max) : arg == 1 && offer_list(word, players, 1, k, o, max);+ case C_TIME:+ if (arg == 0) return offer_list(word, time_a, 3, k, o, max);+ if (arg == 1 && !strcmp(w[1], "set")) return offer_list(word, time_set, 2, k, o, max);+ if (arg == 1 && !strcmp(w[1], "query")) return offer_list(word, time_q, 2, k, o, max);+ return false;+ case C_WEATHER: return arg == 0 && offer_list(word, weathers, 3, k, o, max);+ case C_DIFFICULTY: return arg == 0 && offer_list(word, diffs, 4, k, o, max);+ case C_GAMERULE:+ if (arg == 0) return offer_list(word, rule_name, 8, k, o, max);+ return arg == 1 && offer_list(word, bools, 2, k, o, max);+ case C_EFFECT:+ if (arg == 0) return offer_list(word, players, 1, k, o, max);+ if (arg == 1) {+ for (int i = 0; i < 3; i++)+ if (offer(word, eff_key[i], "minecraft:", k, o, max)) return true;+ return offer(word, "clear", "", k, o, max);+ }+ return false;+ case C_SUMMON:+ if (arg == 0) {+ static const char *const bolt_name[1] = {"LightningBolt"};+ return offer_list(word, mob_name, 8, k, o, max) || offer_list(word, bolt_name, 1, k, o, max);+ }+ return false;+ case C_GIVE:+ case C_CLEAR:+ if (arg == 0) return offer_list(word, players, 1, k, o, max);+ if (arg == 1) {+ for (int i = 0; i < 198; i++)+ if ((mc_block_item[i >> 3] >> (i & 7) & 1) && offer(word, mc_block_name[i], "minecraft:", k, o, max)) return true;+ for (int i = 0; i < 176; i++)+ if (mc_item_name[i][0] && offer(word, mc_item_name[i], "minecraft:", k, o, max)) return true;+ }+ return false;+ case C_SETBLOCK:+ if (arg < 3) {+ /* the block looked at (CommandBase.func_175771_a) */+ if (pl.hit_face < 0) return false;+ int v = arg == 0 ? pl.hit_x : arg == 1 ? pl.hit_y : pl.hit_z;+ char t[12];+ out_n = 0, put_int(v), strcpy(t, out);+ return offer(word, t, "", k, o, max);+ }+ if (arg == 3) {+ for (int i = 0; i < 198; i++)+ if (mc_block_name[i][0] && offer(word, mc_block_name[i], "minecraft:", k, o, max)) return true;+ return false;+ }+ return arg == 5 && offer_list(word, handling, 3, k, o, max);+ case C_TP: case C_KILL: case C_SPAWNPOINT: case C_XP:+ return arg == (c == C_XP) && offer_list(word, players, 1, k, o, max);+ case C_HELP: {+ if (arg) return false;+ for (int i = 0; i < N_COMMANDS; i++)+ if (allowed(i) && offer(word, cmd_name[i], "", k, o, max)) return true;+ return false;+ }+ }+ return false;+}diff --git a/games/numblocks/src/edits.c b/games/numblocks/src/edits.cindex 370fd7d1..3b842345 100644--- a/games/numblocks/src/edits.c+++ b/games/numblocks/src/edits.c@@ -8,6 +8,7 @@* are merged into the records. */#include "edits.h"#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */typedef struct {int16_t rx, rz;diff --git a/games/numblocks/src/entity.c b/games/numblocks/src/entity.cindex e8c661da..2250003b 100644--- a/games/numblocks/src/entity.c+++ b/games/numblocks/src/entity.c@@ -375,6 +375,6 @@ void ents_tick(void) {static int spawn_wait;if (++spawn_wait >= 20) {spawn_wait = 0;- mobs_spawn();+ if (rule(GR_MOB_SPAWNING)) mobs_spawn();}}diff --git a/games/numblocks/src/gui.c b/games/numblocks/src/gui.cindex d7403d67..9373b500 100644--- a/games/numblocks/src/gui.c+++ b/games/numblocks/src/gui.c@@ -11,10 +11,9 @@#include <math.h>#include <stdlib.h>#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */int gui;-static char msg[64]; /* the message shown (gui_message) and for how long */-static int msg_timer;static int clip_y0, clip_y1; /* the strip: screen rows [clip_y0, clip_y1) */static uint16_t *clip_buf;static uint32_t frame_no;@@ -97,12 +96,14 @@ static void dark_background(void) {#define RGB(r, g, b) (uint16_t)(((r) & 0xF8) << 8 | ((g) & 0xFC) << 3 | (b) >> 3)/* ---------------------------------------------------------------- text (FontRenderer) */-/* three symbols the font lacks, for the key sheet: \1 pi, \2 the square root, \3 backspace */-static const uint8_t sym_bits[3][8] = {{0x00, 0x3F, 0x12, 0x12, 0x12, 0x12, 0x21, 0x00},+/* symbols the font lacks, for the key sheet: \1 pi, \2 the square root, \3 backspace, \4 times, \5 divided by */+static const uint8_t sym_bits[5][8] = {{0x00, 0x3F, 0x12, 0x12, 0x12, 0x12, 0x21, 0x00},{0x78, 0x08, 0x08, 0x08, 0x09, 0x0A, 0x04, 0x00},- {0xFC, 0x82, 0xA9, 0x91, 0xA9, 0x82, 0xFC, 0x00}};-static const uint8_t sym_w[3] = {7, 8, 9};-static int char_w(int c) { return c >= 1 && c <= 3 ? sym_w[c - 1] : c >= 32 && c < 127 ? font_w[c - 32] : 0; }+ {0xFC, 0x82, 0xA9, 0x91, 0xA9, 0x82, 0xFC, 0x00},+ {0x00, 0x11, 0x0A, 0x04, 0x0A, 0x11, 0x00, 0x00},+ {0x00, 0x04, 0x00, 0x1F, 0x00, 0x04, 0x00, 0x00}};+static const uint8_t sym_w[5] = {7, 8, 9, 6, 6};+static int char_w(int c) { return c >= 1 && c <= 5 ? sym_w[c - 1] : c >= 32 && c < 127 ? font_w[c - 32] : 0; }int text_width(const char *s) {int w = 0;for (; *s; s++) w += char_w((unsigned char)*s);@@ -174,19 +175,85 @@ static void draw_stack(const Stack *s, int x, int y) {}}-/* ---------------------------------------------------------------- messages (GuiNewChat) */-void gui_message(const char *s) {- int i = 0;- for (; s[i] && i < 63; i++) msg[i] = s[i];- msg[i] = 0;- msg_timer = 200;+/* ---------------------------------------------------------------- the chat (GuiNewChat) */+/* what was said, oldest first, each: its colour, the tick it came (2 bytes), the text, 0 */+#define CHAT_BUF 512+static char chat[CHAT_BUF];+static int chat_used;+static uint16_t chat_clock; /* ticks (GuiIngame.updateCounter) */+static bool chat_list; /* the last line is a list of completions (the next one replaces it) */+static const uint16_t chat_col[5] = {0xFFFF, RGB(0xFF, 0x55, 0x55), RGB(0x55, 0xFF, 0x55), RGB(0x00, 0xAA, 0x00),+ RGB(0xAA, 0xAA, 0xAA)};+static int chat_size(int i) { return 3 + (int)strlen(chat + i + 3) + 1; }+static void chat_drop_last(void) {+ int i = 0, last = -1;+ for (; i < chat_used; i += chat_size(i)) last = i;+ if (last >= 0) chat_used = last;+}+void chat_add(const char *s, int color) {+ int n = (int)strlen(s);+ if (n > CHAT_BUF - 4) n = CHAT_BUF - 4;+ if (chat_list) chat_drop_last(), chat_list = false;+ while (chat_used + n + 4 > CHAT_BUF) {+ int l = chat_size(0);+ memmove(chat, chat + l, (size_t)(chat_used - l));+ chat_used -= l;+ }+ char *d = chat + chat_used;+ d[0] = (char)color, d[1] = (char)(chat_clock & 255), d[2] = (char)(chat_clock >> 8);+ memcpy(d + 3, s, (size_t)n), d[3 + n] = 0;+ chat_used += n + 4;}-static void message(void) {- if (!msg_timer) return;- /* a dark band behind, fading for the last second */- int y = SCREEN_H - 48, a = msg_timer < 20 ? msg_timer : 20;- tint_rect(2, y - 1, text_width(msg) + 4, 9, 0, a * 16 / 20);- if (a > 4) text(msg, 4, y, 0xFFFF, true);+void gui_message(const char *s) { chat_add(s, CHAT_WHITE); }+static int chat_age(int i) { return (uint16_t)(chat_clock - ((uint8_t)chat[i + 1] | (uint8_t)chat[i + 2] << 8)); }++/* how much of s fits on a line w pixels wide: up to a space if it can (FontRenderer.sizeStringToWidth) */+static int wrap_len(const char *s, int w) {+ int x = 0, i = 0, sp = -1;+ for (; s[i]; i++) {+ if (s[i] == ' ') sp = i;+ x += char_w((unsigned char)s[i]);+ if (x > w) return sp > 0 ? sp : i > 0 ? i : 1;+ }+ return i;+}++/* GuiNewChat.drawChat: the newest at the bottom, 9 pixels a line on a dark band; each fades out after+ * 10 seconds (10 lines at most), or with the chat open all of them (20 lines) */+static void chat_lines(void) {+ bool open = gui == GUI_CHAT;+ if (SCREEN_H - 28 - (open ? 20 : 10) * 9 >= clip_y1 || SCREEN_H - 28 <= clip_y0) return;+ int at[64], n = 0;+ for (int i = 0; i < chat_used && n < 64; i += chat_size(i)) at[n++] = i;+ int line = 0, most = open ? 20 : 10;+ for (int m = n - 1; m >= 0 && line < most; m--) {+ int age = chat_age(at[m]), a = 32;+ if (!open) {+ if (age >= 200) break;+ float d = (1 - age / 200.0f) * 10;+ if (d > 1) d = 1;+ a = (int)(d * d * 32);+ }+ /* its lines, wrapped, drawn upwards from the last */+ const char *s = chat + at[m] + 3, *ls[8];+ int ll[8], k = 0;+ while (*s && k < 8) {+ int l = wrap_len(s, SCREEN_W - 4);+ ls[k] = s, ll[k++] = l, s += l;+ if (*s == ' ') s++;+ }+ for (int j = k - 1; j >= 0 && line < most; j--, line++) {+ int y = SCREEN_H - 28 - line * 9;+ if (y <= clip_y0 || y - 9 >= clip_y1) continue;+ tint_rect(2, y - 9, SCREEN_W - 2, 9, 0, a / 2);+ if (a > 3) {+ char t[64];+ int l = ll[j] < 63 ? ll[j] : 63;+ memcpy(t, ls[j], (size_t)l), t[l] = 0;+ text(t, 2, y - 8, chat_col[(int)chat[at[m]]], true);+ }+ }+ }}/* ---------------------------------------------------------------- the HUD (GuiIngame) */@@ -194,7 +261,7 @@ static int name_timer, last_slot = -1, last_id;static void hud(void) {int hx = (SCREEN_W - 182) / 2, hy = SCREEN_H - 22;- if (gui == GUI_NONE) {+ if (gui == GUI_NONE || gui == GUI_CHAT) {/* Minecraft draws its crosshair inverting what is behind it */for (int k = -4; k <= 4; k++) {int pts[2][2] = {{SCREEN_W / 2 + k, SCREEN_H / 2}, {SCREEN_W / 2, SCREEN_H / 2 + k}};@@ -329,6 +396,13 @@ void tiles_removed(int x, int y, int z) {if (s[i].id) ent_drop(s[i].id, item_count(&s[i]), s[i].aux, x + 0.5f, y + 0.5f, z + 0.5f, false);}+void tiles_forget(int x, int y, int z) {+ Chest *c = chest_at(x, y, z, false);+ if (c) c->used = 0;+ Furnace *f = furnace_at(x, y, z, false);+ if (f) f->used = 0;+}+/* TileEntityFurnace.update */static bool can_smelt(const Furnace *f) {if (!f->s[0].id) return false;@@ -338,7 +412,11 @@ static bool can_smelt(const Furnace *f) {return f->s[2].id == out && f->s[2].aux < item_max(out);}void gui_tick(void) {- if (msg_timer) msg_timer--;+ chat_clock++;+ /* (old lines kept old, as the clock comes round) */+ if (!(chat_clock & 255))+ for (int i = 0; i < chat_used; i += chat_size(i))+ if (chat_age(i) > 1000) chat[i + 1] = (char)((chat_clock - 1000) & 255), chat[i + 2] = (char)((chat_clock - 1000) >> 8);for (int i = 0; i < N_FURNACES; i++) {Furnace *f = &furnaces[i];if (!f->used) continue;@@ -749,9 +827,13 @@ static Button buttons[12];static int nbuttons, bcur;enum { B_NO, B_SINGLE, B_OPTIONS, B_QUITAPP, B_PLAY, B_CREATE, B_DELETE, B_CANCEL, B_MODE, B_SEED, B_DOCREATE,B_DODELETE, B_DIFF, B_GFX, B_LOOK, B_CLOUDS, B_BOB, B_DONE, B_BACK_GAME, B_SAVEQUIT, B_RESPAWN, B_TITLE,- B_CONTROLS, B_CONTROLS_DONE, B_NAME, B_RENAME, B_DORENAME, B_RECREATE };+ B_CONTROLS, B_CONTROLS_DONE, B_NAME, B_RENAME, B_DORENAME, B_RECREATE, B_CHEATS, B_LAN, B_LAN_MODE,+ B_LAN_CHEATS, B_LAN_START };int menu_choice; /* an action for main.c (ACT_*) */int create_mode; /* the new world's game mode */+bool create_cheats; /* and whether it allows cheats */+static bool cheats_set; /* (chosen, not following the game mode) */+static bool lan_mode, lan_allow; /* Open to LAN's settings: the game mode for others, cheats */char seed_text[21]; /* the new world's seed, as typed */char name_text[WORLD_NAME + 1]; /* the new world's name, or the world being renamed's */int play_slot; /* the world to play */@@ -834,6 +916,144 @@ static void field_input(void) {}}+/* ---------------------------------------------------------------- the chat line (GuiChat) */+/* typed as fields are, and some keys type what commands need: x,n,t ":", var "_", x10^x "~",+ * ans a space, and 0 among the letters "@"; toolbox finishes the word (as Tab does), up brings+ * back the line sent last; OK or EXE sends, Back closes */+#define CHAT_MAX 60+#define RK_TOOLBOX 16+static char chat_text[CHAT_MAX + 1], chat_last[CHAT_MAX + 1];+static char cmp_word[24]; /* completing: the word as it was typed, where it starts, the way shown */+static int cmp_at, cmp_k = -1;+static void chat_open(const char *s) {+ strcpy(chat_text, s);+ gui = GUI_CHAT;+ f_digits = 0, f_caps = 0, cmp_k = -1;+ raw_held = ~(uint64_t)0;+}+static char chat_key(int k) {+ switch (k) {+ case 14: return ':';+ case 15: return '_';+ case 50: return '~';+ case 51: return ' ';+ case 48: if (!f_digits) return '@'; break;+ }+ return key_char(k);+}+static void put_word(int at, const char *w) {+ int n = (int)strlen(w);+ if (at + n > CHAT_MAX) n = CHAT_MAX - at;+ memcpy(chat_text + at, w, (size_t)n), chat_text[at + n] = 0;+}+/* GuiChat.autocompletePlayerNames: the first press finishes the word as far as every way agrees,+ * else lists the ways and shows the first; each press after shows the next */+static void complete(void) {+ char line[CHAT_MAX + 25], w[40];+ int at;+ if (cmp_k >= 0) {+ memcpy(line, chat_text, (size_t)cmp_at);+ strcpy(line + cmp_at, cmp_word);+ if (!command_complete(line, cmp_k, &at, w, sizeof w)) cmp_k = 0, command_complete(line, 0, &at, w, sizeof w);+ put_word(cmp_at, w);+ cmp_k++;+ return;+ }+ char common[40];+ int n = 0;+ while (n < 400 && command_complete(chat_text, n, &at, w, sizeof w)) {+ if (!n) strcpy(common, w);+ else {+ int i = 0;+ while (common[i] && common[i] == w[i]) i++;+ common[i] = 0;+ }+ n++;+ }+ if (!n) return;+ if ((int)strlen(common) > (int)strlen(chat_text + at)) {+ put_word(at, common);+ return;+ }+ if (strlen(chat_text + at) >= sizeof cmp_word) return;+ strcpy(cmp_word, chat_text + at);+ cmp_at = at;+ if (n > 1) {+ /* the list, in the chat (as much as fits) */+ char list[200];+ int l = 0;+ for (int k = 0; k < n && command_complete(chat_text, k, &at, w, sizeof w); k++) {+ int wl = (int)strlen(w);+ if (l + wl + 7 > (int)sizeof list) {+ strcpy(list + l, ", ...");+ l += 5;+ break;+ }+ if (l) list[l++] = ',', list[l++] = ' ';+ memcpy(list + l, w, (size_t)wl), l += wl;+ }+ list[l] = 0;+ chat_add(list, CHAT_WHITE);+ chat_list = true;+ }+ memcpy(line, chat_text, (size_t)cmp_at);+ strcpy(line + cmp_at, cmp_word);+ command_complete(line, 0, &at, w, sizeof w);+ put_word(cmp_at, w);+ cmp_k = 1;+}+static void chat_input(void) {+ uint64_t raw = plat_scan(), down = raw & ~raw_held;+ raw_held = raw;+ for (int k = 0; k < 64; k++) {+ if (!(down >> k & 1)) continue;+ int n = (int)strlen(chat_text);+ if (k == RK_ALPHA) f_digits = !f_digits;+ else if (k == RK_SHIFT) f_caps = (uint8_t)((f_caps + 1) % 3);+ else if (k == RK_BACK) {+ gui = GUI_NONE;+ return;+ } else if (k == RK_OK || k == RK_EXE) {+ /* GuiChat.sendChatMessage: without the spaces around it */+ gui = GUI_NONE;+ char *t = chat_text;+ while (*t == ' ') t++;+ while (n > 0 && chat_text[n - 1] == ' ') chat_text[--n] = 0;+ if (*t) {+ strcpy(chat_last, t);+ command_run(t);+ }+ return;+ } else if (k == RK_TOOLBOX) complete();+ else {+ cmp_k = -1;+ if (k == 1 && chat_last[0]) strcpy(chat_text, chat_last); /* up */+ else if (k == RK_BACKSPACE) {+ if (n) chat_text[n - 1] = 0;+ } else {+ char c = chat_key(k);+ if (c && n < CHAT_MAX) chat_text[n] = c, chat_text[n + 1] = 0;+ }+ }+ }+}+/* the line being typed, on a dark band at the bottom, and the keys that type what */+static void chat_screen(void) {+ if (clip_y0 < 22) {+ tint_rect(0, 0, SCREEN_W, 22, 0, 16);+ text_center("alpha: abc/123 shift: Abc toolbox: finish the word", SCREEN_W / 2, 2, RGB(0xA0, 0xA0, 0xA0));+ text_center("x,n,t : var _ x10^x ~ ans space 0 @", SCREEN_W / 2, 12, RGB(0xA0, 0xA0, 0xA0));+ }+ if (clip_y1 <= SCREEN_H - 14) return;+ tint_rect(2, SCREEN_H - 14, SCREEN_W - 4, 12, 0, 16);+ const char *t = chat_text, *m = f_digits ? "123" : f_caps == 2 ? "ABC" : f_caps ? "Abc" : "abc";+ while (text_width(t) > SCREEN_W - 40) t++; /* (a long line: its end) */+ uint16_t c = RGB(0xE0, 0xE0, 0xE0);+ text(t, 4, SCREEN_H - 12, c, true);+ if (!((chat_clock / 6) & 1)) text("_", 4 + text_width(t), SCREEN_H - 12, c, true);+ text(m, SCREEN_W - 6 - text_width(m), SCREEN_H - 12, RGB(0x80, 0x80, 0x80), true);+}+static void add_button(int x, int y, int w, int on, int id, const char *label) {Button *b = &buttons[nbuttons++];*b = (Button){(int16_t)x, (int16_t)y, (int16_t)w, (uint8_t)on, (uint8_t)id, {0}};@@ -873,7 +1093,9 @@ static void menu(int screen) {case GUI_CREATE:add_button(w / 2 - 100, 60, 200, 1, B_NAME, name_text); /* (drawn as a field) */cat(t, "Game Mode: ", create_mode ? "Creative" : "Survival");- add_button(w / 2 - 75, 100, 150, 1, B_MODE, t);+ add_button(w / 2 - 155, 100, 150, 1, B_MODE, t);+ cat(t, "Allow Cheats: ", create_cheats ? "ON" : "OFF");+ add_button(w / 2 + 5, 100, 150, 1, B_CHEATS, t);cat(t, "Seed: ", seed_text[0] ? seed_text : (field == F_SEED ? "" : "(random)"));add_button(w / 2 - 100, 150, 200, 1, B_SEED, t);add_button(w / 2 - 155, h - 28, 150, 1, B_DOCREATE, "Create New World");@@ -917,9 +1139,18 @@ static void menu(int screen) {add_button(w / 2 - 100, h / 4 + 48 - 16, 98, 0, B_NO, "Achievements");add_button(w / 2 + 2, h / 4 + 48 - 16, 98, 0, B_NO, "Statistics");add_button(w / 2 - 100, h / 4 + 96 - 16, 98, 1, B_OPTIONS, "Options...");- add_button(w / 2 + 2, h / 4 + 96 - 16, 98, 0, B_NO, "Open to LAN");+ add_button(w / 2 + 2, h / 4 + 96 - 16, 98, !lan_open, B_LAN, "Open to LAN");add_button(w / 2 - 100, h / 4 + 120 - 16, 200, 1, B_SAVEQUIT, "Save and Quit to Title");break;+ case GUI_LAN:+ /* GuiShareToLan */+ cat(t, "Game Mode: ", lan_mode ? "Creative" : "Survival");+ add_button(w / 2 - 155, 100, 150, 1, B_LAN_MODE, t);+ cat(t, "Allow Cheats: ", lan_allow ? "ON" : "OFF");+ add_button(w / 2 + 5, 100, 150, 1, B_LAN_CHEATS, t);+ add_button(w / 2 - 155, h - 28, 150, 1, B_LAN_START, "Start LAN World");+ add_button(w / 2 + 5, h - 28, 150, 1, B_CANCEL, "Cancel");+ break;case GUI_DEATH:add_button(w / 2 - 100, h / 4 + 72, 200, 1, B_RESPAWN, "Respawn");add_button(w / 2 - 100, h / 4 + 96, 200, 1, B_TITLE, "Title screen");@@ -964,6 +1195,7 @@ static void press(int id) {break;case B_CREATE:create_mode = 0;+ create_cheats = cheats_set = false;seed_text[0] = 0;world_unique_name("New World", name_text);gui_menu(GUI_CREATE);@@ -976,6 +1208,7 @@ static void press(int id) {n[WORLD_NAME] = 0;world_unique_name(n, name_text);create_mode = wi.mode;+ create_cheats = wi.cheats, cheats_set = false;/* (its seed, as it would be typed) */uint64_t v = wi.seed < 0 ? 0 - (uint64_t)wi.seed : (uint64_t)wi.seed;char d[21];@@ -1004,8 +1237,24 @@ static void press(int id) {if (nworlds) delete_world(wlist[wsel]);gui_menu(GUI_WORLDS);break;- case B_CANCEL: gui_menu(gui == GUI_WORLDS ? GUI_TITLE : GUI_WORLDS); break;- case B_MODE: create_mode = !create_mode; break;+ case B_CANCEL: gui_menu(gui == GUI_WORLDS ? GUI_TITLE : gui == GUI_LAN ? GUI_PAUSE : GUI_WORLDS); break;+ case B_MODE:+ /* (cheats follow the game mode until they are chosen) */+ create_mode = !create_mode;+ if (!cheats_set) create_cheats = create_mode;+ break;+ case B_CHEATS: create_cheats = !create_cheats, cheats_set = true; break;+ case B_LAN:+ lan_mode = lan_allow = false;+ gui_menu(GUI_LAN);+ break;+ case B_LAN_MODE: lan_mode = !lan_mode; break;+ case B_LAN_CHEATS: lan_allow = !lan_allow; break;+ case B_LAN_START:+ /* IntegratedServer.shareToLAN: the game mode is for players who join; cheats for everyone */+ lan_open = true, lan_cheats = lan_allow;+ gui = GUI_NONE;+ break;case B_NAME: field_open(F_NAME); break;case B_SEED: field_open(F_SEED); break;case B_DOCREATE: menu_choice = ACT_NEW; break;@@ -1056,7 +1305,8 @@ static void menu_input(uint32_t keys, uint32_t pressed) {if (gui == GUI_PAUSE) gui = GUI_NONE;else if (gui == GUI_OPTIONS) press(B_DONE);else if (gui == GUI_CONTROLS) press(B_CONTROLS_DONE);- else if (gui == GUI_WORLDS || gui == GUI_CREATE || gui == GUI_CONFIRM || gui == GUI_RENAME) press(B_CANCEL);+ else if (gui == GUI_WORLDS || gui == GUI_CREATE || gui == GUI_CONFIRM || gui == GUI_RENAME || gui == GUI_LAN)+ press(B_CANCEL);}}@@ -1190,7 +1440,7 @@ static void key_sheet(void) {for (int r = 0; r < 3; r++)for (int c = 0; c < 6; c++)key(c < 2 ? 5 + c * 37 : 79 + (c - 2) * 60, 80 + r * 32, c < 2 ? 34 : 57, caps[r][c], acts[r][c]);- static const char *const notes[4] = {"1 to 9: hotbar slot. EXE: same as OK.",+ static const char *const notes[4] = {"1 to 9: hotbar slot. EXE: as OK. \4: chat. \5: command.","Forward twice: sprint. Jump twice: fly (Creative).","Menus: OK takes or puts, EXE one, shift+OK moves.","Hold OK and move over slots to spread a stack out."};@@ -1238,7 +1488,9 @@ static void menu_screen(void) {text(wi.name, x + 2, y + 1, 0xFFFF, true);char f[4] = {'n', 'b', (char)('0' + wlist[k]), 0};text(f, x + 2, y + 12, RGB(0x80, 0x80, 0x80), true);- text(wi.mode == 1 ? "Creative Mode" : "Survival Mode", x + 2, y + 22, RGB(0x80, 0x80, 0x80), true);+ char m[24];+ cat(m, wi.mode == 1 ? "Creative Mode" : "Survival Mode", wi.cheats ? ", Cheats" : "");+ text(m, x + 2, y + 22, RGB(0x80, 0x80, 0x80), true);}if (!nworlds) text_center("No worlds yet", w / 2, 60, RGB(0x80, 0x80, 0x80));char t[40], n[12];@@ -1275,6 +1527,10 @@ static void menu_screen(void) {case GUI_OPTIONS: text_center("Options", w / 2, 15, 0xFFFF); break;case GUI_CONTROLS: key_sheet(); break;case GUI_PAUSE: text_center("Game menu", w / 2, 40, 0xFFFF); break;+ case GUI_LAN:+ text_center("LAN World", w / 2, 50, 0xFFFF);+ text_center("Settings for Other Players", w / 2, 82, 0xFFFF);+ break;case GUI_LOADING:text_center("Loading world", w / 2, h / 2 - 50, 0xFFFF);text_center("Building terrain", w / 2, h / 2 - 20, 0xFFFF);@@ -1308,10 +1564,16 @@ void gui_input(uint32_t keys, uint32_t pressed) {menu_input(keys, pressed);return;}+ if (gui == GUI_CHAT) {+ chat_input();+ return;+ }if (gui == GUI_NONE) {nbuttons = 0;if (pressed & K_INV && !pl.dead) gui_open(pl.mode == 1 ? GUI_CREATIVE : GUI_INVENTORY, 0, 0, 0);else if (pressed & K_PAUSE) gui_menu(GUI_PAUSE);+ else if (pressed & K_COMMAND && !pl.dead) chat_open("/");+ else if (pressed & K_CHAT && !pl.dead) chat_open("");if (held()->id != last_id || pl.slot != last_slot) name_timer = 40, last_id = held()->id, last_slot = pl.slot;if (name_timer) name_timer--;return;@@ -1473,8 +1735,10 @@ void hud_strip(uint16_t *buf, int y0, int rows) {int a = pl.sleep_timer * 32 / 100;tint_rect(0, y0, SCREEN_W, rows, 0x0841, a > 30 ? 30 : a);}- if (gui < GUI_PAUSE || gui == GUI_PAUSE || gui == GUI_DEATH || (gui == GUI_OPTIONS && options_from == GUI_PAUSE)) hud();- if (gui == GUI_NONE) message();+ if (gui < GUI_PAUSE || gui == GUI_PAUSE || gui == GUI_DEATH || gui == GUI_LAN ||+ (gui == GUI_OPTIONS && options_from == GUI_PAUSE))+ hud();+ if (gui == GUI_NONE || gui == GUI_CHAT) chat_lines();if (pl.hurt_time > 0 && gui == GUI_NONE) {/* (Minecraft tilts the camera; a red flash says the same here) */tint_rect(0, y0, SCREEN_W, rows, RGB(0xFF, 0, 0), pl.hurt_time * 2 / 3);@@ -1484,10 +1748,11 @@ void hud_strip(uint16_t *buf, int y0, int rows) {dark_background();container();break;- case GUI_PAUSE:+ case GUI_PAUSE: case GUI_LAN:dark_background();menu_screen();break;+ case GUI_CHAT: chat_screen(); break;case GUI_OPTIONS: case GUI_CONTROLS:if (options_from == GUI_PAUSE) dark_background();else dirt_background();diff --git a/games/numblocks/src/inv.c b/games/numblocks/src/inv.cindex e8e794eb..7710a9f6 100644--- a/games/numblocks/src/inv.c+++ b/games/numblocks/src/inv.c@@ -2,6 +2,7 @@* and what blocks drop (Minecraft 1.8.8: InventoryPlayer, ShapedRecipes,* ShapelessRecipes, the Block*.getItemDropped and quantityDropped methods). */#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) *//* ---------------------------------------------------------------- items */int item_max(int id) {diff --git a/games/numblocks/src/main.c b/games/numblocks/src/main.cindex f0494e0b..93025cff 100644--- a/games/numblocks/src/main.c+++ b/games/numblocks/src/main.c@@ -3,6 +3,7 @@* placed between the last two ticks so it moves smoothly. */#include <math.h>#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */#ifndef HOSTconst char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "NumBlocks";@@ -11,6 +12,7 @@ const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level")))uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */uint32_t perf_max __attribute__((used)); /* (and the slowest frame in a world, ms) */+uint32_t ticks_run; /* ticks played (what waits a few ticks counts these: the time of day can stop or jump) */uint32_t game_time = 1000; /* Minecraft's time of day: 0 sunrise, 6000 noon */bool start_in_world; /* tests: straight into a new world */int64_t start_seed; /* (its seed) */@@ -20,7 +22,7 @@ static float px, py, pz;static bool in_world; /* playing; else the title screens, the world turning behind */static float title_yaw;-static void camera_reset(void) {+void camera_reset(void) {px = pl.x, py = pl.y, pz = pl.z;player_look(pl.x, pl.y + 1.62f, pl.z, pl.yaw, pl.pitch);}@@ -91,7 +93,7 @@ void game_init(void) {#endiflast = plat_millis();if (start_in_world) {- new_world(1, start_seed, 0, "New World");+ new_world(1, start_seed, 0, false, "New World");game_time = 1000;loading();return;@@ -137,7 +139,7 @@ bool game_frame(void) {while (b > a && name_text[b - 1] == ' ') b--;name_text[b] = 0;world_unique_name(name_text + a, name);- new_world(slot, parse_seed(), create_mode, name);+ new_world(slot, parse_seed(), create_mode, create_cheats, name);game_time = 0;loading();save_world();@@ -184,7 +186,7 @@ bool game_frame(void) {if (pl.pitch > 90) pl.pitch = 90;if (pl.pitch < -90) pl.pitch = -90;}- bool paused = gui == GUI_PAUSE || gui == GUI_OPTIONS || gui == GUI_CONTROLS;+ bool paused = gui == GUI_PAUSE || gui == GUI_OPTIONS || gui == GUI_CONTROLS || gui == GUI_LAN;if (!paused) acc += dt;/* a key pressed on a frame between ticks waits for the next tick (else that press is lost) */static uint32_t game_pressed;@@ -198,7 +200,8 @@ bool game_frame(void) {world_tick();gui_tick();hand_tick();- game_time++;+ ticks_run++;+ if (rule(GR_DAYLIGHT_CYCLE)) game_time++;acc -= 50;/* Minecraft saves every 45 seconds */if (++autosave >= 900) {diff --git a/games/numblocks/src/mob.c b/games/numblocks/src/mob.cindex f00b4ab2..2fc4ed4b 100644--- a/games/numblocks/src/mob.c+++ b/games/numblocks/src/mob.c@@ -212,6 +212,7 @@ static Entity *spawn(int type, float x, float y, float z) {e->gx = x, e->gz = z;return e;}+Entity *mob_summon(int type, float x, float y, float z) { return spawn(type, x, y, z); }/* SpawnerAnimals, made small: a try every second */void mobs_spawn(void) {@@ -256,7 +257,7 @@ static void drop(int id, int n, const Entity *e) {if (n > 0) ent_drop(id, n, 0, e->x, e->y + 0.5f, e->z, false);}static void loot(Entity *e) {- if (e->growth < 0) return; /* babies drop nothing */+ if (e->growth < 0 || !rule(GR_MOB_LOOT)) return; /* babies drop nothing */switch (e->type) {case E_ZOMBIE: drop(I_ROTTEN_FLESH, rnd(3), e); break;case E_SKELETON:@@ -431,8 +432,8 @@ static void push_player(float kx, float kz, float s) {}/* ---------------------------------------------------------------- explosions (Explosion, power 3) */-void explode(float x, float y, float z, float power) {- int r = (int)ceilf(power);+void explode(float x, float y, float z, float power, bool blocks) {+ int r = blocks ? (int)ceilf(power) : -1;for (int dy = -r; dy <= r; dy++)for (int dz = -r; dz <= r; dz++)for (int dx = -r; dx <= r; dx++) {@@ -453,7 +454,7 @@ void explode(float x, float y, float z, float power) {continue;}/* one in power of the blocks drop */- if (rnd((int)power) == 0) {+ if (rnd((int)power) == 0 && rule(GR_TILE_DROPS)) {Stack out[2];int n = block_drops(b, I_DIAMOND_PICKAXE, out);for (int i = 0; i < n; i++) ent_drop(out[i].id, out[i].aux, 0, bx + 0.5f, by + 0.5f, bz + 0.5f, false);@@ -570,7 +571,7 @@ static void tnt_tick(Entity *e) {if (ground) e->vx *= 0.7f, e->vz *= 0.7f, e->vy *= -0.5f;if (--e->delay <= 0) {e->type = E_NONE;- explode(e->x, e->y + 0.49f, e->z, 4);+ explode(e->x, e->y + 0.49f, e->z, 4, true);}}@@ -660,7 +661,7 @@ void mob_tick(Entity *e) {else if (e->delay > 0) e->delay++, go = dist > 2;if (e->delay >= 30) {e->type = E_NONE;- explode(e->x, e->y + 0.85f, e->z, opt.difficulty ? 3 : 0);+ explode(e->x, e->y + 0.85f, e->z, opt.difficulty ? 3 : 0, rule(GR_MOB_GRIEFING));return;}}diff --git a/games/numblocks/src/names.c b/games/numblocks/src/names.cnew file mode 100644index 00000000..7422df27--- /dev/null+++ b/games/numblocks/src/names.c@@ -0,0 +1,10 @@+/* Generated by tools/names.py: Minecraft 1.8.8's names for blocks and items (see nb.h). */+#include "nb.h"++const char *const mc_block_name[198] = {"air","stone","grass","dirt","cobblestone","planks","sapling","bedrock","flowing_water","water","flowing_lava","lava","sand","gravel","gold_ore","iron_ore","coal_ore","log","leaves","sponge","glass","lapis_ore","lapis_block","","sandstone","","bed","","","","web","tallgrass","deadbush","","","wool","","yellow_flower","red_flower","brown_mushroom","red_mushroom","gold_block","iron_block","double_stone_slab","stone_slab","brick_block","tnt","bookshelf","mossy_cobblestone","obsidian","torch","","mob_spawner","oak_stairs","chest","","diamond_ore","diamond_block","crafting_table","wheat","farmland","furnace","lit_furnace","","wooden_door","ladder","rail","stone_stairs","","","","","","redstone_ore","","","","","snow_layer","ice","snow","cactus","clay","reeds","","fence","pumpkin","","","glowstone","","lit_pumpkin","","","","","","monster_egg","stonebrick","brown_mushroom_block","red_mushroom_block","","glass_pane","melon_block","","","vine","","","","mycelium","waterlily","","","","","","","","","","","","","","","wooden_slab","","","emerald_ore","","","","emerald_block","","","","","","cobblestone_wall","","carrots","potatoes","","","","","","","","","","","","","","","","","stained_hardened_clay","","leaves2","log2","","","","","","","","hay_block","","hardened_clay","coal_block","packed_ice","double_plant","","","","red_sandstone","","","","","","","","","","","","","","","","","",""};+const char *const mc_item_name[176] = {"iron_shovel","iron_pickaxe","iron_axe","flint_and_steel","apple","bow","arrow","coal","diamond","iron_ingot","gold_ingot","iron_sword","wooden_sword","wooden_shovel","wooden_pickaxe","wooden_axe","stone_sword","stone_shovel","stone_pickaxe","stone_axe","diamond_sword","diamond_shovel","diamond_pickaxe","diamond_axe","stick","bowl","mushroom_stew","golden_sword","golden_shovel","golden_pickaxe","golden_axe","string","feather","gunpowder","wooden_hoe","stone_hoe","iron_hoe","diamond_hoe","golden_hoe","wheat_seeds","wheat","bread","leather_helmet","leather_chestplate","leather_leggings","leather_boots","chainmail_helmet","chainmail_chestplate","chainmail_leggings","chainmail_boots","iron_helmet","iron_chestplate","iron_leggings","iron_boots","diamond_helmet","diamond_chestplate","diamond_leggings","diamond_boots","golden_helmet","golden_chestplate","golden_leggings","golden_boots","flint","porkchop","cooked_porkchop","","golden_apple","","wooden_door","bucket","water_bucket","lava_bucket","","","","redstone","snowball","","leather","milk_bucket","brick","clay_ball","reeds","paper","book","slime_ball","","","egg","compass","fishing_rod","clock","glowstone_dust","fish","cooked_fish","dye","bone","sugar","","bed","","cookie","","shears","melon","","","beef","cooked_beef","chicken","cooked_chicken","rotten_flesh","","","","gold_nugget","","","","spider_eye","","","","","","","","","","","","","emerald","","","carrot","potato","baked_potato","poisonous_potato","","","","","","pumpkin_pie","","","","","","","","","","","","","","","","","","","","","","","mutton","cooked_mutton","","","","","","",""};+/* the blocks that are items too (their names are items' names) */+const uint8_t mc_block_item[25] = {254,240,127,193,233,255,119,55,14,194,103,10,196,196,0,64,34,8,0,128,6,244,8,0,0};+const uint16_t give_key[293] = {16,17,18,19,20,21,22,32,48,49,50,64,80,81,82,83,84,85,96,97,98,99,100,101,112,192,193,208,224,240,256,272,273,274,275,288,289,290,291,304,320,336,352,384,385,386,480,496,497,498,512,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,592,608,609,610,611,612,613,614,615,616,624,640,656,672,688,704,705,706,707,708,709,720,736,752,768,784,800,832,848,864,896,912,928,960,976,1040,1056,1072,1168,1248,1264,1280,1296,1312,1360,1376,1424,1456,1568,1569,1570,1571,1632,1648,1696,1760,1776,2016,2017,2018,2019,2020,2021,2064,2128,2224,2544,2545,2546,2547,2548,2549,2550,2551,2552,2553,2554,2555,2556,2557,2558,2559,2576,2577,2592,2593,2720,2752,2768,2784,2800,2801,2802,2803,2804,2805,2864,4096,4112,4128,4144,4160,4176,4192,4208,4209,4224,4240,4256,4272,4288,4304,4320,4336,4352,4368,4384,4400,4416,4432,4448,4464,4480,4496,4512,4528,4544,4560,4576,4592,4608,4624,4640,4656,4672,4688,4704,4720,4736,4752,4768,4784,4800,4816,4832,4848,4864,4880,4896,4912,4928,4944,4960,4976,4992,5008,5024,5040,5056,5072,5088,5104,5120,5152,5184,5200,5216,5232,5296,5312,5344,5360,5376,5392,5408,5424,5440,5456,5504,5520,5536,5552,5568,5584,5585,5586,5587,5600,5601,5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632,5648,5680,5712,5744,5760,5808,5824,5840,5856,5872,5936,6000,6208,6256,6272,6288,6304,6400,6768,6784};+const uint16_t give_id[293] = {1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,29,30,31,32,33,34,35,39,43,47,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,114,115,116,117,118,119,128,130,134,135,136,137,138,139,140,141,142,144,145,209,146,148,149,150,151,158,159,160,161,162,214,215,216,217,218,219,163,164,165,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,191,192,183,187,193,166,194,195,196,198,200,202,204,206,208,267,268,269,282,358,283,284,306,307,308,309,310,266,256,257,258,259,261,262,263,264,271,272,273,274,305,328,371,276,277,278,279,316,315,318,260,265,270,275,280,321,320,360,285,286,287,288,289,290,291,292,293,294,295,296,301,302,303,304,297,298,299,300,314,361,362,359,337,333,334,335,313,329,319,336,327,326,322,324,325,331,330,339,340,341,332,379,380,381,382,383,384,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,317,323,338,372,281,373,363,364,365,366,369,311,370,312,374,375,376,377,378,367,368};+const int n_give = 293;diff --git a/games/numblocks/src/nb.h b/games/numblocks/src/nb.hindex 6fa494a8..1fae9cbd 100644--- a/games/numblocks/src/nb.h+++ b/games/numblocks/src/nb.h@@ -27,8 +27,8 @@ enum {K_SHIFT = 1 << 27, /* shift (also K_JUMP): shift click in screens */K_BACK = 1 << 28, /* Back alone: closes screens */K_OK = 1 << 29, /* OK alone */- K_ZERO = 1 << 30, /* 0 (typing a seed) */- K_MINUS = 1u << 31 /* - (typing a seed) */+ K_CHAT = 1 << 30, /* x: the chat */+ K_COMMAND = 1u << 31 /* division: the chat, with "/" typed */};uint32_t plat_keys(void);uint64_t plat_scan(void); /* the keys down as the calculator numbers them (bit RK_*), for typing */@@ -184,6 +184,7 @@ typedef struct {#define N_ENT 24extern Entity ents[N_ENT];Entity *ent_new(int type, float x, float y, float z);+Entity *mob_summon(int type, float x, float y, float z); /* a mob as one spawns */Entity *ent_drop(int id, int count, int dmg, float x, float y, float z, bool thrown);void ents_tick(void);/* particles: a block's bits when it breaks; drops (a texel or two, falling@@ -202,7 +203,7 @@ void fish_cast(void);int fish_reel(Entity *e); /* how much it wears the rod */void mob_tick(Entity *e);void mobs_spawn(void);-void explode(float x, float y, float z, float power);+void explode(float x, float y, float z, float power, bool blocks);void throw_item(int id, float speed, bool from_player); /* arrows, snowballs, eggs */bool mob_attack(const Entity *e); /* the player hits this mob (with the held item) */bool mob_use(Entity *e); /* the player uses the held item on it (shears, bucket) */@@ -239,21 +240,23 @@ void neighbours_changed(int x, int y, int z);void break_block_at(int x, int y, int z, bool drops);/* ---------------------------------------------------------------- screens (gui.c) */-enum { GUI_NONE, GUI_INVENTORY, GUI_CRAFTING, GUI_FURNACE, GUI_CHEST, GUI_CREATIVE,+enum { GUI_NONE, GUI_INVENTORY, GUI_CRAFTING, GUI_FURNACE, GUI_CHEST, GUI_CREATIVE, GUI_CHAT,GUI_PAUSE, GUI_DEATH, GUI_OPTIONS, GUI_TITLE, GUI_WORLDS, GUI_CREATE, GUI_CONFIRM, GUI_LOADING, GUI_CONTROLS,- GUI_RENAME };+ GUI_RENAME, GUI_LAN };extern int gui; /* the screen open */void gui_open(int screen, int x, int y, int z);void gui_close(void);void gui_input(uint32_t keys, uint32_t pressed);void gui_tick(void); /* 20 a second: furnaces */void tiles_removed(int x, int y, int z); /* a chest or furnace broken: its items fall out */+void tiles_forget(int x, int y, int z); /* (or replaced by a command: they are gone) */void gui_menu(int screen); /* opens a menu screen */enum { ACT_NONE, ACT_PLAY, ACT_NEW, ACT_QUIT_APP, ACT_SAVE_QUIT, ACT_RESPAWN, ACT_TITLE };extern int menu_choice; /* what a menu asks main.c to do (ACT_*), 0 if nothing */extern int play_slot; /* (ACT_PLAY) the world chosen */extern char name_text[]; /* (ACT_NEW) the new world's name, as typed */extern int create_mode;+extern bool create_cheats;extern char seed_text[21];/* ---------------------------------------------------------------- saves and options (save.c) */@@ -266,7 +269,7 @@ typedef struct {uint8_t last_world; /* the world played last (its slot, 0: none): the title's backdrop */uint32_t plays; /* worlds opened so far: each world keeps the count when it was last played */} Options;-#define KEY_SHEET 2 /* (2: jump and sneak on shift and alpha) */+#define KEY_SHEET 3 /* (2: jump and sneak on shift and alpha; 3: chat and commands) */extern Options opt;extern int64_t world_seed;/* Worlds: up to MAX_WORLDS, each in a slot (1..MAX_WORLDS) whose records start "nb<slot>" */@@ -275,6 +278,7 @@ extern int64_t world_seed;typedef struct {char name[WORLD_NAME + 1];int mode; /* 0 survival, 1 creative */+ bool cheats;int64_t seed;uint32_t played; /* opt.plays when it was last played (the latest first in the list) */} WorldInfo;@@ -283,11 +287,31 @@ int world_free_slot(void); /* 0: all taken */void world_unique_name(const char *base, char *out); /* base, or "base (2)"... if taken */bool save_world(void);bool load_world(int slot);-void new_world(int slot, int64_t seed, int mode, const char *name);+void new_world(int slot, int64_t seed, int mode, bool cheats, const char *name);bool rename_world(int slot, const char *name);void delete_world(int slot);void load_options(void);void save_options(void);+/* the world's settings, saved with it: cheats (Allow Cheats; or opened to LAN with them, until it+ * is left) and the game rules (GameRules) */+extern bool world_cheats, lan_open, lan_cheats;+#define cheats_on() (world_cheats || lan_cheats)+extern uint8_t game_rules;+enum { GR_KEEP_INVENTORY = 1, GR_DAYLIGHT_CYCLE = 2, GR_MOB_SPAWNING = 4, GR_MOB_GRIEFING = 8, GR_NATURAL_REGEN = 16,+ GR_TILE_DROPS = 32, GR_MOB_LOOT = 64, GR_FIRE_TICK = 128 };+#define GR_DEFAULT 0xFE /* (all on but keepInventory) */+#define rule(r) ((game_rules & (r)) != 0)++/* ---------------------------------------------------------------- chat and commands (command.c) */+enum { CHAT_WHITE, CHAT_RED, CHAT_GREEN, CHAT_DARK_GREEN, CHAT_GRAY };+void chat_add(const char *s, int color); /* a line in the chat (gui.c) */+void command_run(const char *line); /* a line sent from the chat: a command ("/...") or said */+/* tab completion: the k-th way to finish the last word of line (the word starts at *at); false: no more */+bool command_complete(const char *line, int k, int *at, char *out, int max);+extern const char *const mc_block_name[198], *const mc_item_name[176]; /* (names.c) */+extern const uint8_t mc_block_item[25];+extern const uint16_t give_key[], give_id[]; /* Minecraft's id << 4 | data, and NumBlocks' id */+extern const int n_give;/* ---------------------------------------------------------------- drawing (render.c, hud.c) */#define RW 160@@ -296,4 +320,6 @@ typedef struct { float x, y, z, yaw, pitch; } Camera;void render_frame(const Camera *c, uint32_t time_of_day);/* the HUD and screens draw over each strip of the screen before it is sent */void hud_strip(uint16_t *buf, int y0, int rows);+void camera_reset(void);+extern uint32_t ticks_run; /* the player moved at once: the camera with them (main.c) */#endifdiff --git a/games/numblocks/src/plat_eadk.c b/games/numblocks/src/plat_eadk.cindex d9be24dc..8dfecf61 100644--- a/games/numblocks/src/plat_eadk.c+++ b/games/numblocks/src/plat_eadk.c@@ -30,8 +30,8 @@ uint32_t plat_keys(void) {if (k & KEY(eadk_key_exe)) r |= K_EXE;if (k & KEY(eadk_key_shift)) r |= K_SHIFT;if (k & KEY(eadk_key_back)) r |= K_BACK;- if (k & KEY(eadk_key_zero)) r |= K_ZERO;- if (k & KEY(eadk_key_minus)) r |= K_MINUS;+ if (k & KEY(eadk_key_multiplication)) r |= K_CHAT;+ if (k & KEY(eadk_key_division)) r |= K_COMMAND;if (k & KEY(eadk_key_back)) r |= K_ATTACK;if (k & KEY(eadk_key_var)) r |= K_INV;if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;diff --git a/games/numblocks/src/player.c b/games/numblocks/src/player.cindex 53d6496e..f5d151d7 100644--- a/games/numblocks/src/player.c+++ b/games/numblocks/src/player.c@@ -7,6 +7,7 @@* air, a 0.6 x 1.8 box that steps up 0.6, eyes at 1.62. */#include <math.h>#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */Player pl;@@ -162,7 +163,8 @@ void player_hurt(float amount, int kind) {if (pl.health <= 0) {pl.health = 0;pl.dead = true;- /* everything falls out (InventoryPlayer.dropAllItems) */+ /* everything falls out (InventoryPlayer.dropAllItems), unless the game rule keeps it */+ if (rule(GR_KEEP_INVENTORY)) return;for (int i = 0; i < 36; i++)if (pl.inv[i].id) ent_drop(pl.inv[i].id, item_count(&pl.inv[i]), pl.inv[i].aux, pl.x, pl.y + 1.3f, pl.z, false);for (int i = 0; i < 4; i++)@@ -176,8 +178,8 @@ void player_hurt(float amount, int kind) {extern uint32_t game_time;static void food_tick(void) {if (opt.difficulty == 0) {- if (pl.health < 20 && game_time % 20 == 0) pl.health = pl.health + 1 > 20 ? 20 : pl.health + 1;- if (pl.food < 20 && game_time % 10 == 0) pl.food++;+ if (pl.health < 20 && ticks_run % 20 == 0 && rule(GR_NATURAL_REGEN)) pl.health = pl.health + 1 > 20 ? 20 : pl.health + 1;+ if (pl.food < 20 && ticks_run % 10 == 0) pl.food++;return;}if (pl.exhaustion > 4) {@@ -185,7 +187,7 @@ static void food_tick(void) {if (pl.sat > 0) pl.sat = pl.sat > 1 ? pl.sat - 1 : 0;else if (pl.food > 0) pl.food--;}- if (pl.food >= 18 && pl.health > 0 && pl.health < 20) {+ if (pl.food >= 18 && pl.health > 0 && pl.health < 20 && rule(GR_NATURAL_REGEN)) {if (++pl.food_timer >= 80) {pl.health += 1;if (pl.health > 20) pl.health = 20;@@ -289,7 +291,7 @@ static void break_block(int x, int y, int z, bool drops) {if (b == B_CHEST || b == B_FURNACE || b == B_FURNACE_LIT) tiles_removed(x, y, z);if (depth == 1 && blk_model[b] != M_LIQUID) particles_break(x, y, z, b);world_set(x, y, z, B_AIR);- if (drops && pl.mode == 0) {+ if (drops && pl.mode == 0 && rule(GR_TILE_DROPS)) {Stack out[2];int n = block_drops(b, held()->id, out);for (int i = 0; i < n; i++)@@ -303,7 +305,7 @@ static void break_block(int x, int y, int z, bool drops) {if (world_get(x, y - 1, z) == b - 1) world_set(x, y - 1, z, B_AIR);if (is_door_lower(b) && world_get(x, y + 1, z) == B_DOOR_OAK_UPPER) world_set(x, y + 1, z, B_AIR);if (b == B_DOOR_OAK_UPPER && is_door_lower(world_get(x, y - 1, z))) {- if (drops && pl.mode == 0) ent_drop(I_WOODEN_DOOR, 1, 0, x + 0.5f, y - 0.5f, z + 0.5f, false);+ if (drops && pl.mode == 0 && rule(GR_TILE_DROPS)) ent_drop(I_WOODEN_DOOR, 1, 0, x + 0.5f, y - 0.5f, z + 0.5f, false);world_set(x, y - 1, z, B_AIR);}if (b == B_BED_FOOT || b == B_BED_HEAD)@@ -715,7 +717,7 @@ void player_respawn(void) {pl.x = pl.spawn_x + 0.5f, pl.y = (float)pl.spawn_y, pl.z = pl.spawn_z + 0.5f;pl.vx = pl.vy = pl.vz = 0;pl.health = 20, pl.food = 20, pl.sat = 5, pl.exhaustion = 0, pl.air = 300, pl.fall = 0, pl.fire = 0;- pl.xp = 0, pl.xp_level = 0, pl.xp_total = 0;+ if (!rule(GR_KEEP_INVENTORY)) pl.xp = 0, pl.xp_level = 0, pl.xp_total = 0;pl.dead = false;pl.pitch = 0;}diff --git a/games/numblocks/src/render.c b/games/numblocks/src/render.cindex 373a550c..c9b76e26 100644--- a/games/numblocks/src/render.c+++ b/games/numblocks/src/render.c@@ -1848,7 +1848,7 @@ static uint32_t strip_hash(void) {}static bool still_screen(void) {return gui == GUI_PAUSE || gui == GUI_OPTIONS || gui == GUI_CONTROLS || gui == GUI_WORLDS || gui == GUI_CREATE ||- gui == GUI_CONFIRM || gui == GUI_RENAME || gui == GUI_LOADING;+ gui == GUI_CONFIRM || gui == GUI_RENAME || gui == GUI_LOADING || gui == GUI_LAN;}static void send_strip(int py, bool still) {if (still) {diff --git a/games/numblocks/src/save.c b/games/numblocks/src/save.cindex aff60083..54935f5d 100644--- a/games/numblocks/src/save.c+++ b/games/numblocks/src/save.c@@ -3,7 +3,9 @@* saves every 45 seconds of play, as Minecraft does, and when you quit; block changes reach* storage as they fill the journal. Worlds live in slots: the records of slot 3 are* "nb3.nbw" and "nb3r..." (its regions). */+#include <stddef.h>#include "nb.h"+#pragma GCC optimize("Os") /* (not where the time goes: small) */#include "edits.h"#define OPTIONS_REC "numblocks.cfg"@@ -23,11 +25,17 @@ typedef struct {Head1 h;char name[WORLD_NAME + 1];uint32_t played;+} Head2; /* version 2 had no cheats or game rules */+typedef struct {+ Head2 h2;+ uint8_t cheats, rules, pad[2];} Head;extern uint32_t game_time;void *tiles_data(uint32_t *len);+uint8_t game_rules = GR_DEFAULT;+bool world_cheats, lan_open, lan_cheats;static int slot = 1; /* the world being played */static char cur_name[WORLD_NAME + 1]; /* its name */static uint32_t cur_played;@@ -51,16 +59,24 @@ static const uint8_t *read_head(int s, Head *h, uint32_t *len, uint32_t *head_leif (!d || *len < sizeof(Head1)) return NULL;memset(h, 0, sizeof *h);if (!memcmp(d, "NBW1", 4)) {- memcpy(&h->h, d, sizeof(Head1));- copy_name(h->name, "New World");+ memcpy(&h->h2.h, d, sizeof(Head1));+ copy_name(h->h2.name, "New World");*head_len = sizeof(Head1);- } else if (!memcmp(d, "NBW2", 4) && *len >= sizeof(Head)) {+ } else if (!memcmp(d, "NBW2", 4) && *len >= sizeof(Head2)) {+ memcpy(&h->h2, d, sizeof(Head2));+ *head_len = sizeof(Head2);+ } else if (!memcmp(d, "NBW3", 4) && *len >= sizeof(Head)) {memcpy(h, d, sizeof(Head));- h->name[WORLD_NAME] = 0;*head_len = sizeof(Head);} elsereturn NULL;- if (h->h.player_size != sizeof pl || *len < *head_len + sizeof pl) return NULL;+ h->h2.name[WORLD_NAME] = 0;+ if (h->h2.h.player_size != sizeof pl || *len < *head_len + sizeof pl) return NULL;+ if (*head_len < sizeof(Head)) {+ /* (older worlds: cheats as a new world of their mode would have them, the rules as they start) */+ h->cheats = d[*head_len + offsetof(Player, mode)] == 1;+ h->rules = GR_DEFAULT;+ }return d;}@@ -71,10 +87,11 @@ bool world_info(int s, WorldInfo *w) {if (!d) return false;Player p;memcpy(&p, d + hl, sizeof p);- copy_name(w->name, h.name);+ copy_name(w->name, h.h2.name);w->mode = p.mode;- w->seed = h.h.seed;- w->played = h.played;+ w->cheats = h.cheats;+ w->seed = h.h2.h.seed;+ w->played = h.h2.played;return true;}@@ -115,9 +132,10 @@ bool save_world(void) {void *t = tiles_data(&tl);Head h;memset(&h, 0, sizeof h);- h.h = (Head1){{'N', 'B', 'W', '2'}, (uint16_t)sizeof pl, (uint16_t)tl, world_seed, game_time, weather};- copy_name(h.name, cur_name);- h.played = cur_played;+ h.h2.h = (Head1){{'N', 'B', 'W', '3'}, (uint16_t)sizeof pl, (uint16_t)tl, world_seed, game_time, weather};+ copy_name(h.h2.name, cur_name);+ h.h2.played = cur_played;+ h.cheats = world_cheats, h.rules = game_rules;/* one record: the head, the player, the tiles (written from a buffer made in the merge scratch) */uint32_t n = sizeof h + sizeof pl + tl;uint8_t *b = (uint8_t *)edits_scratch(n);@@ -144,14 +162,15 @@ bool load_world(int s) {uint32_t len, hl, tl;const uint8_t *d = read_head(s, &h, &len, &hl);void *t = tiles_data(&tl);- if (!d || h.h.tiles_size != tl || len != hl + sizeof pl + tl) return false;+ if (!d || h.h2.h.tiles_size != tl || len != hl + sizeof pl + tl) return false;slot = s;- copy_name(cur_name, h.name);- cur_played = h.played;- world_seed = h.h.seed;- game_time = h.h.time;+ copy_name(cur_name, h.h2.name);+ cur_played = h.h2.played;+ world_seed = h.h2.h.seed;+ game_time = h.h2.h.time;+ world_cheats = h.cheats, lan_open = lan_cheats = false, game_rules = h.rules;/* World.calculateInitialWeather */- weather = h.h.weather;+ weather = h.h2.h.weather;rain_str = weather.raining ? 1 : 0;thunder_str = weather.thundering ? 1 : 0;memcpy(&pl, d + hl, sizeof pl);@@ -160,11 +179,11 @@ bool load_world(int s) {char pre[4];prefix_of(s, pre);world_new(world_seed, pre);- if (s != opt.last_world || h.played != opt.plays) played(s);+ if (s != opt.last_world || h.h2.played != opt.plays) played(s);return true;}-void new_world(int s, int64_t seed, int mode, const char *name) {+void new_world(int s, int64_t seed, int mode, bool cheats, const char *name) {char pre[4];prefix_of(s, pre);plat_remove_prefix(pre);@@ -176,6 +195,7 @@ void new_world(int s, int64_t seed, int mode, const char *name) {memset(ents, 0, sizeof ents);world_seed = seed;game_time = 0;+ world_cheats = cheats, lan_open = lan_cheats = false, game_rules = GR_DEFAULT;memset(&weather, 0, sizeof weather);rain_str = thunder_str = 0;world_new(seed, pre);@@ -194,8 +214,8 @@ bool rename_world(int s, const char *name) {uint8_t *b = (uint8_t *)edits_scratch(n);if (!b) return false;memcpy(b + sizeof h, d + hl, body); /* (first: the scratch may be where nothing else is) */- memcpy(h.h.magic, "NBW2", 4);- copy_name(h.name, name);+ memcpy(h.h2.h.magic, "NBW3", 4);+ copy_name(h.h2.name, name);memcpy(b, &h, sizeof h);char rec[8];record_of(s, rec);diff --git a/games/numblocks/src/tick.c b/games/numblocks/src/tick.cindex 43f89f35..a4a89203 100644--- a/games/numblocks/src/tick.c+++ b/games/numblocks/src/tick.c@@ -14,7 +14,7 @@ extern uint32_t game_time;typedef struct {int16_t x, z;uint8_t y, pad;- uint16_t due; /* the tick it runs (low 16 bits of game_time) */+ uint16_t due; /* the tick it runs (low 16 bits of ticks_run) */} Pending;#define N_PENDING 160static Pending pend[N_PENDING];@@ -27,7 +27,7 @@ void fluid_schedule(int x, int y, int z) {if (pend[i].x == x && pend[i].y == y && pend[i].z == z) return;if (npend >= N_PENDING) return;/* water moves every 5 ticks, lava every 30 */- pend[npend++] = (Pending){(int16_t)x, (int16_t)z, (uint8_t)y, 0, (uint16_t)(game_time + (is_lava(b) ? 30 : 5))};+ pend[npend++] = (Pending){(int16_t)x, (int16_t)z, (uint8_t)y, 0, (uint16_t)(ticks_run + (is_lava(b) ? 30 : 5))};}static int level_of(int b) { return blk_meta[b]; } /* 0 source, 1-7 flowing, 8 falling */@@ -164,7 +164,7 @@ static void fluid_update(int x, int y, int z) {}static void fluids_tick(void) {- uint16_t now = (uint16_t)game_time;+ uint16_t now = (uint16_t)ticks_run;int done = 0;for (int i = 0; i < npend && done < 24;) {if ((int16_t)(now - pend[i].due) < 0) {diff --git a/games/numblocks/tests/stubs.c b/games/numblocks/tests/stubs.cindex b32e9282..47b693d7 100644--- a/games/numblocks/tests/stubs.c+++ b/games/numblocks/tests/stubs.c@@ -2,3 +2,5 @@#include "nb.h"uint32_t game_time;uint32_t perf_frames;+uint32_t ticks_run;+void camera_reset(void) {}diff --git a/games/numblocks/tests/unit.c b/games/numblocks/tests/unit.cindex c6f28bd5..32937953 100644--- a/games/numblocks/tests/unit.c+++ b/games/numblocks/tests/unit.c@@ -99,7 +99,6 @@ int main(void) {}/* water: 7 blocks out on a flat floor, then dry when the source is gone; lava meets water */{- extern uint32_t game_time;world_new(0, "ut2");world_follow(8, 70, 8);int y = 70;@@ -110,20 +109,20 @@ int main(void) {}world_set(8, y, 8, B_WATER);neighbours_changed(8, y, 8);- for (int t = 0; t < 400; t++) game_time++, world_tick();+ for (int t = 0; t < 400; t++) ticks_run++, world_tick();CHECK(world_get(9, y, 8) == B_FLOWING_WATER);CHECK(world_get(15, y, 8) == B_FLOWING_WATER_7);CHECK(world_get(16, y, 8) == B_AIR);CHECK(world_get(11, y, 10) == B_FLOWING_WATER_5);world_set(8, y, 8, B_AIR);neighbours_changed(8, y, 8);- for (int t = 0; t < 600; t++) game_time++, world_tick();+ for (int t = 0; t < 600; t++) ticks_run++, world_tick();CHECK(world_get(9, y, 8) == B_AIR && world_get(12, y, 8) == B_AIR);/* lava source next to water: obsidian */world_set(4, y, 4, B_WATER);world_set(5, y, 4, B_LAVA);neighbours_changed(5, y, 4);- for (int t = 0; t < 60; t++) game_time++, world_tick();+ for (int t = 0; t < 60; t++) ticks_run++, world_tick();CHECK(world_get(5, y, 4) == B_OBSIDIAN);plat_remove_prefix("ut2");}@@ -320,12 +319,12 @@ int main(void) {WorldInfo w;world_unique_name("New World", n);CHECK(!strcmp(n, "New World"));- new_world(world_free_slot(), 5, 0, n);+ new_world(world_free_slot(), 5, 0, false, n);save_world();world_unique_name("New World", n);CHECK(!strcmp(n, "New World (2)"));int s2 = world_free_slot();- new_world(s2, 6, 1, n);+ new_world(s2, 6, 1, true, n);save_world();CHECK(s2 == 2 && world_info(1, &w) && !strcmp(w.name, "New World") && w.mode == 0 && w.seed == 5);CHECK(world_info(2, &w) && !strcmp(w.name, "New World (2)") && w.mode == 1 && w.seed == 6);@@ -362,6 +361,80 @@ int main(void) {CHECK(pl.hit_face == 2 && pl.hit_z == 10);plat_remove_prefix("ut10");}+ {+ /* commands: what they do; most need cheats */+ extern uint32_t game_time;+ new_world(1, 9, 0, false, "Commands");+ world_follow(pl.x, pl.y, pl.z);+ while (world_pending()) world_follow(pl.x, pl.y, pl.z);+ command_run("/gamemode 1");+ CHECK(pl.mode == 0);+ world_cheats = true;+ command_run("/gamemode c");+ CHECK(pl.mode == 1);+ command_run("/gamemode survival");+ CHECK(pl.mode == 0);+ memset(pl.inv, 0, sizeof pl.inv);+ command_run("/give @p minecraft:diamond_sword");+ CHECK(pl.inv[0].id == I_DIAMOND_SWORD);+ command_run("/give Player wool 5 14");+ CHECK(pl.inv[1].id == B_WOOL_RED && item_count(&pl.inv[1]) == 5);+ command_run("/give @p 5 64 2");+ CHECK(pl.inv[2].id == B_PLANKS_BIRCH && item_count(&pl.inv[2]) == 64);+ command_run("/give @p dye 1 15");+ CHECK(pl.inv[3].id == I_DYE_WHITE);+ command_run("/give @p 276 1 100");+ CHECK(pl.inv[4].id == I_DIAMOND_SWORD && pl.inv[4].aux == 100);+ command_run("/give @p nothing");+ CHECK(!pl.inv[5].id);+ command_run("/clear @p wool");+ CHECK(!pl.inv[1].id && pl.inv[0].id);+ command_run("/clear");+ CHECK(!pl.inv[0].id && !pl.inv[2].id);+ command_run("/time set night");+ CHECK(game_time == 13000);+ command_run("/time add 100");+ CHECK(game_time == 13100);+ command_run("/weather thunder 60");+ CHECK(weather.thundering && weather.raining && weather.rain_time == 1200);+ command_run("/weather clear");+ CHECK(!weather.raining);+ command_run("/xp 5L");+ CHECK(pl.xp_level == 5);+ command_run("/xp -2L");+ CHECK(pl.xp_level == 3);+ int sx = (int)floorf(pl.x), sy = (int)floorf(pl.y + 0.5f), sz = (int)floorf(pl.z);+ command_run("/setblock ~ ~3 ~ wool 4");+ CHECK(world_get(sx, sy + 3, sz) == B_WOOL_YELLOW);+ command_run("/gamerule keepInventory true");+ CHECK(rule(GR_KEEP_INVENTORY) && rule(GR_DAYLIGHT_CYCLE));+ command_run("/gamerule doDaylightCycle false");+ CHECK(!rule(GR_DAYLIGHT_CYCLE));+ command_run("/effect @p poison 10 1");+ CHECK(pl.eff[EF_POISON] == 200 && pl.eff_amp[EF_POISON] == 1);+ command_run("/effect @p clear");+ CHECK(!pl.eff[EF_POISON]);+ command_run("/tp 10 80 -20");+ CHECK(pl.x == 10.5f && pl.y == 80 && pl.z == -19.5f);+ command_run("/tp ~1 ~ ~-0.5");+ CHECK(pl.x == 11.5f && pl.z == -20);+ /* the world keeps its cheats and rules */+ save_world();+ world_cheats = false, game_rules = GR_DEFAULT;+ CHECK(load_world(1) && world_cheats && rule(GR_KEEP_INVENTORY) && !rule(GR_DAYLIGHT_CYCLE));+ WorldInfo wi;+ CHECK(world_info(1, &wi) && wi.cheats);+ /* finishing words, as Tab does */+ char o[40];+ int at;+ CHECK(command_complete("/gam", 0, &at, o, sizeof o) && at == 1 && !strcmp(o, "gamemode"));+ CHECK(command_complete("/gam", 1, &at, o, sizeof o) && !strcmp(o, "gamerule"));+ CHECK(!command_complete("/gam", 2, &at, o, sizeof o));+ CHECK(command_complete("/give @p diamond_sw", 0, &at, o, sizeof o) && at == 9 && !strcmp(o, "minecraft:diamond_sword"));+ CHECK(command_complete("/gamemode cr", 0, &at, o, sizeof o) && !strcmp(o, "creative"));+ CHECK(command_complete("/time set ", 1, &at, o, sizeof o) && !strcmp(o, "night"));+ delete_world(1);+ }printf("%s (%d recipes)\n", fails ? "FAILED" : "all good", N_RECIPES);return fails != 0;}diff --git a/games/numblocks/tools/names.py b/games/numblocks/tools/names.pynew file mode 100644index 00000000..6b86694a--- /dev/null+++ b/games/numblocks/tools/names.py@@ -0,0 +1,112 @@+#!/usr/bin/env python3+"""Minecraft 1.8.8's names for blocks and items, for the commands (/give, /setblock,+/clear) and their completion: writes src/names.c.++ python3 tools/names.py > src/names.c++Blocks go by their registry name or numeric id (Block.blockRegistry), items by+theirs (Item.itemRegistry, where a block's item has the block's name). Only what+NumBlocks has is listed."""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import blocks # noqa: E402+import items # noqa: E402++# Block.registerBlocks: the numeric ids 0..197+BLOCK = '''air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava lava sand gravel+gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock bed golden_rail+detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension yellow_flower red_flower+brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt bookshelf+mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block+crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever+stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch+stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal+lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick+brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate+brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart+enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp+lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire+emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots+potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate+unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs+activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime+barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant+standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2+stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence+birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door+dark_oak_door'''.split()+assert len(BLOCK) == 198, len(BLOCK)++# Item.registerItems: the numeric ids 256..431 (426 unused)+ITEM = '''iron_shovel iron_pickaxe iron_axe flint_and_steel apple bow arrow coal diamond iron_ingot gold_ingot iron_sword+wooden_sword wooden_shovel wooden_pickaxe wooden_axe stone_sword stone_shovel stone_pickaxe stone_axe diamond_sword+diamond_shovel diamond_pickaxe diamond_axe stick bowl mushroom_stew golden_sword golden_shovel golden_pickaxe+golden_axe string feather gunpowder wooden_hoe stone_hoe iron_hoe diamond_hoe golden_hoe wheat_seeds wheat bread+leather_helmet leather_chestplate leather_leggings leather_boots chainmail_helmet chainmail_chestplate+chainmail_leggings chainmail_boots iron_helmet iron_chestplate iron_leggings iron_boots diamond_helmet+diamond_chestplate diamond_leggings diamond_boots golden_helmet golden_chestplate golden_leggings golden_boots flint+porkchop cooked_porkchop painting golden_apple sign wooden_door bucket water_bucket lava_bucket minecart saddle+iron_door redstone snowball boat leather milk_bucket brick clay_ball reeds paper book slime_ball chest_minecart+furnace_minecart egg compass fishing_rod clock glowstone_dust fish cooked_fish dye bone sugar cake bed repeater cookie+filled_map shears melon pumpkin_seeds melon_seeds beef cooked_beef chicken cooked_chicken rotten_flesh ender_pearl+blaze_rod ghast_tear gold_nugget nether_wart potion glass_bottle spider_eye fermented_spider_eye blaze_powder+magma_cream brewing_stand cauldron ender_eye speckled_melon spawn_egg experience_bottle fire_charge writable_book+written_book emerald item_frame flower_pot carrot potato baked_potato poisonous_potato map golden_carrot skull+carrot_on_a_stick nether_star pumpkin_pie fireworks firework_charge enchanted_book comparator netherbrick quartz+tnt_minecart hopper_minecart prismarine_shard prismarine_crystals rabbit cooked_rabbit rabbit_stew rabbit_foot+rabbit_hide armor_stand iron_horse_armor golden_horse_armor diamond_horse_armor lead name_tag command_block_minecart+mutton cooked_mutton banner - spruce_door birch_door jungle_door acacia_door dark_oak_door'''.split()+assert len(ITEM) == 176, len(ITEM)++# NumBlocks' items that Minecraft names differently, or that share a name (told apart by their data value)+DYES = ['BLACK', 'RED', 'GREEN', 'BROWN', 'BLUE', 'PURPLE', 'CYAN', 'SILVER', 'GRAY', 'PINK', 'LIME', 'YELLOW',+ 'LIGHT_BLUE', 'MAGENTA', 'ORANGE', 'WHITE']+RENAME = {'CHARCOAL': ('coal', 1), 'MELON_SLICE': ('melon', 0), 'RAW_FISH': ('fish', 0), 'RAW_SALMON': ('fish', 1),+ 'CLOWNFISH': ('fish', 2), 'PUFFERFISH': ('fish', 3), 'COOKED_FISH': ('cooked_fish', 0),+ 'COOKED_SALMON': ('cooked_fish', 1)}+for k, d in enumerate(DYES):+ RENAME['DYE_' + d] = ('dye', k)+# a block's item has data 0 where the block's data is only its facing+FACING_ONLY = {50, 54, 61, 65}+++def main():+ give = [] # (mc id << 4 | data, NumBlocks id)+ have_block = set(s['id'] for s in blocks.S)+ item_block = set()+ for i, s in enumerate(blocks.S):+ if items.tab_of(i) is None:+ continue+ give.append(((s['id'] << 4) | (0 if s['id'] in FACING_ONLY else s['meta'] & 15), i))+ item_block.add(s['id'])+ have_item = set()+ for k, it in enumerate(items.I):+ name, data = RENAME.get(it['name'], (it['name'].lower(), 0))+ assert name in ITEM, name+ mid = 256 + ITEM.index(name)+ give.append(((mid << 4) | data, 256 + k))+ have_item.add(mid)+ give.sort()+ keys = [g[0] for g in give]+ assert len(keys) == len(set(keys)), 'two things with one id and data'+ out = ['/* Generated by tools/names.py: Minecraft 1.8.8\'s names for blocks and items (see nb.h). */',+ '#include "nb.h"', '']+ bl = [BLOCK[i] if i in have_block else '' for i in range(198)]+ il = [ITEM[i] if 256 + i in have_item else '' for i in range(176)]+ out.append('const char *const mc_block_name[198] = {' + ','.join(f'"{n}"' for n in bl) + '};')+ out.append('const char *const mc_item_name[176] = {' + ','.join(f'"{n}"' for n in il) + '};')+ out.append('/* the blocks that are items too (their names are items\' names) */')+ mask = [0] * 25+ for i in item_block:+ mask[i >> 3] |= 1 << (i & 7)+ out.append('const uint8_t mc_block_item[25] = {' + ','.join(str(v) for v in mask) + '};')+ out.append(f'const uint16_t give_key[{len(give)}] = {{' + ','.join(str(g[0]) for g in give) + '};')+ out.append(f'const uint16_t give_id[{len(give)}] = {{' + ','.join(str(g[1]) for g in give) + '};')+ out.append(f'const int n_give = {len(give)};')+ sys.stdout.write('\n'.join(out) + '\n')+++if __name__ == '__main__':+ main()diff --git a/tests/test_games.py b/tests/test_games.pyindex 9090f304..95c0c0fc 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -105,7 +105,7 @@ GAMES = {# Play Selected World"numblocks": ("NumBlocks.nwa", "nb1.nbw",presses((3000, "ok"), (3600, "ok"), (4200, "ok"), (4800, "down"), (5100, "down"), (5400, "down"),- (5700, "ok"), (8100, "comma", 1500)), 11600,+ (5700, "down"), (6000, "ok"), (8400, "comma", 1500)), 11900,presses((3000, "ok"), (3600, "ok")), 8000),# a level, its message, then play; then back to the level select"portal": ("PortalReturns.nwa", "portal.sav",@@ -167,8 +167,8 @@ CHECKS = {and v[34] == 5 and struct.unpack_from("<H", v, 14)[0] == 1,lambda v: v[32] == 9 and struct.unpack_from("<H", v, 14)[0] == 2),# the world's record: its magic, then (offset 16) the time of day, which goes on from one session to the next- "numblocks": (lambda v: v[:4] == b"NBW2" and struct.unpack_from("<I", v, 16)[0] > 0,- lambda v: v[:4] == b"NBW2" and struct.unpack_from("<I", v, 16)[0] > 60),+ "numblocks": (lambda v: v[:4] == b"NBW3" and struct.unpack_from("<I", v, 16)[0] > 0,+ lambda v: v[:4] == b"NBW3" and struct.unpack_from("<I", v, 16)[0] > 60),"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}