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
Plants vs. Zombies: Adventure's 50 levels, menus, saves, Dr. Zomboss
Mason3633f84052a8d04
diff --git a/games/pvz/Makefile b/games/pvz/Makefilenew file mode 100644index 00000000..8764a092--- /dev/null+++ b/games/pvz/Makefile@@ -0,0 +1,82 @@+# Plants vs. Zombies on the NumWorks calculator.+# make output/pvz.nwa+# make check link it like the calculator does (output/pvz.bin)+# make host build/play: the game on a computer, for tests and screenshots+# make test the game played on a computer (tests/check.py, with the sanitizers)+# make data src/data.bin and src/data.h from the public material tools/fetch.py gathers+# (REF=its folder, Python + Pillow + NumPy)+Q ?= @+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>+TOOLCHAIN ?=+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)+CC = $(BIN)arm-none-eabi-gcc+NWLINK ?= npx --yes -- [email protected]+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded+SIZE = $(BIN)arm-none-eabi-size+BUILD_DIR = output+REF ?=++# the drawing runs every frame at -O2; the rest is small at -Os+HOT = src/gfx.c+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c)) ../../launcher/src/inflate.c+COLD_OBJ = $(patsubst %.c,$(BUILD_DIR)/cold/%.o,$(notdir $(COLD)))+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h++CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel++.PHONY: build check clean host test data+build: $(BUILD_DIR)/pvz.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)+check: $(BUILD_DIR)/pvz.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/pvz.bin+ @echo "BIN $(BUILD_DIR)/pvz.bin: $$(wc -c < $(BUILD_DIR)/pvz.bin) bytes"++$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@++$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@+$(BUILD_DIR)/cold/inflate.o: ../../launcher/src/inflate.c ../../launcher/src/inflate.h+ @mkdir -p $(@D)+ $(Q) $(CC) $(CFLAGS) -O2 -c $< -o $@++$(BUILD_DIR)/pvz.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o+ @echo "LD $@"+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@+ $(Q) $(STRIP) $@+ $(Q) $(SIZE) $@++$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)+ @echo "ICON $<"+ $(Q) $(NWLINK) png-icon-o $< $@++$(BUILD_DIR):+ $(Q) mkdir -p $@++# on a computer: tests/play.c plays it with scripted keys and saves screenshots+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c)) ../../launcher/src/inflate.c+host: build/play+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)+ $(Q) mkdir -p $(dir $@)+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@+ @echo "HOST $@"++test: build/play+ python3 tests/check.py build/play++data:+ @test -n "$(REF)" || { echo "make data REF=<the folder tools/fetch.py filled>"; exit 1; }+ python3 -I tools/pack.py $(REF)++clean:+ $(Q) rm -rf $(BUILD_DIR) builddiff --git a/games/pvz/src/board.c b/games/pvz/src/board.cindex 23316d79..3f64e3b2 100644--- a/games/pvz/src/board.c+++ b/games/pvz/src/board.c@@ -540,7 +540,7 @@ static int next_conveyor_seed(void) {}if (empty <= 5) weight /= empty <= 2 ? 5 : 3;}- if (B.has_boss && boss.phase == 10 /* the RV */ && kind == P_FLOWERPOT) weight = 500;+ if (B.has_boss && boss.phase == BS_RV && kind == P_FLOWERPOT) weight = 500;w[i] = count >= 4 ? 1 : count >= 3 ? 5 : kind == B.last_conveyor ? weight / 2 : weight;total += w[i];}diff --git a/games/pvz/src/boss.c b/games/pvz/src/boss.cnew file mode 100644index 00000000..3f48cc73--- /dev/null+++ b/games/pvz/src/boss.c@@ -0,0 +1,172 @@+/* Dr. Zomboss, in his Zombot, on the roof at night (game.h). His moves follow the game's own: summoning+ * zombies, stomping, bungees, the RV, and lowering his head to spit fire and ice balls, when he can be hurt. */+#include <string.h>+#include "boss_art.h"+#include "game.h"++Boss boss;++/* the Zombot's animations: their first frame and length in its tracks (the .reanim), at 12 frames a second */+const BossClip boss_clips[N_CLIPS] = {+ [CL_ENTER] = {0, 40}, [CL_IDLE] = {40, 15}, [CL_SPAWN5] = {55, 21}, [CL_SPAWN4] = {76, 21},+ [CL_SPAWN3] = {97, 21}, [CL_SPAWN2] = {118, 21}, [CL_SPAWN1] = {139, 22}, [CL_BUNGEE_ENTER] = {161, 25},+ [CL_BUNGEE_LEAVE] = {186, 18}, [CL_STOMP1] = {205, 31}, [CL_STOMP2] = {236, 31}, [CL_STOMP3] = {267, 29},+ [CL_STOMP4] = {296, 29}, [CL_HEAD_ENTER] = {325, 57}, [CL_HEAD_IDLE] = {382, 17}, [CL_ATTACK1] = {399, 40},+ [CL_ATTACK2] = {439, 40}, [CL_ATTACK3] = {479, 40}, [CL_ATTACK4] = {519, 40}, [CL_ATTACK5] = {559, 43},+ [CL_HEAD_LEAVE] = {602, 45}, [CL_DEATH] = {647, 107}, [CL_RV] = {754, 38},+};++static const uint8_t enemies[12] = {Z_CONE, Z_BUCKET, Z_FOOTBALL, Z_POLE, Z_JACK, Z_LADDER, Z_ZOMBONI, Z_CATAPULT,+ Z_POGO, Z_NEWSPAPER, Z_DOOR, Z_GARGANTUAR};++static int range(int lo, int hi) { return lo + irand(hi - lo + 1); }++static void enter(int phase, int clip, float duration) {+ if (phase == BS_SPAWN || phase == BS_STOMP || phase == BS_BUNGEE || phase == BS_RV || phase == BS_DEATH) boss.chill = 0;+ boss.phase = (uint8_t)phase, boss.clip = (uint8_t)clip, boss.elapsed = 0;+ boss.fps = phase == BS_RV ? 16 : phase == BS_DEATH || phase == BS_BUNGEE_LEAVE ? 18 : 12;+ boss.duration = duration >= 0 ? duration : (float)((boss_clips[clip].len * 100 + boss.fps - 1) / boss.fps);+}++void boss_start(void) {+ memset(&boss, 0, sizeof boss);+ boss.health = BOSS_HEALTH;+ boss.summon_in = 500, boss.head_in = 5000, boss.stomp_in = -1, boss.bungee_in = -1;+ enter(BS_ENTER, CL_ENTER, -1);+}++bool boss_vulnerable(void) {+ return boss.phase == BS_HEAD_BEFORE || boss.phase == BS_SPIT || boss.phase == BS_HEAD_AFTER;+}++void boss_damage(int amount) {+ if (!boss_vulnerable()) return;+ boss.health = boss.health > amount ? boss.health - amount : 0;+ boss.hit_at = B.ticks;+}++static void crush(int row, int col, int cols) {+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->row >= row && p->row <= row + 1 && p->col >= col && p->col < col + cols) p->health = 0;+ }+ fx_add(FX_SMOKE, cell_x(col + cols / 2), row_y(row + 1, 600), 40, 0);+}++static void bungees(int col) {+ for (int i = 0; i < 3; i++) {+ int c = col + i, rows[MAX_ROWS], n = 0;+ for (int k = 0; k < B.nplants; k++)+ if (B.plants[k].col == c && B.plants[k].health > 0 && n < MAX_ROWS) rows[n++] = B.plants[k].row;+ int row = n ? rows[irand(n)] : irand(5);+ Zombie *z = spawn_zombie(Z_BUNGEE, row, cell_x(c), 0);+ if (z) z->row = (uint8_t)row, z->x = cell_x(c), z->phase = BP_DOWN, z->u.bungee.left = 100, z->u.bungee.column = (uint8_t)c,+ z->u.bungee.drop = 0xFF;+ }+}++static bool contact(float before, float frac) {+ return before < boss.duration * frac && boss.elapsed >= boss.duration * frac;+}++void boss_tick(void) {+ /* the fire or ice ball rolling down its lane, flattening what it meets */+ if (boss.ball.on) {+ boss.ball.age++;+ if (boss.ball.age > 100) {+ boss.ball.x -= boss.ball.kind == 0 ? 1036.9f / 56 * 0.02f : 1036.9f / 58 * 0.02f;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ float d = cell_x(p->col) - boss.ball.x;+ if (p->row == boss.ball.row && d <= 35 && d >= -35) p->health = 0;+ }+ }+ if (boss.ball.x < -100) boss.ball.on = 0;+ }+ if (boss.health == 0 && boss.phase != BS_DEATH) {+ boss.ball.on = 0, boss.frozen = 0;+ enter(BS_DEATH, CL_DEATH, -1);+ for (int i = 0; i < B.nzombies; i++) B.zombies[i].health = 0, B.zombies[i].flags |= ZF_SPAWNED;+ }+ boss.age++;+ if (boss.chill > 0) boss.chill--;+ if (boss.frozen > 0) {+ boss.frozen--;+ return;+ }+ boss.anim++;+ if (boss.summon_in > 0) boss.summon_in--;+ if (boss.head_in > 0) boss.head_in--;+ if (boss.stomp_in > 0) boss.stomp_in--;+ if (boss.bungee_in > 0) boss.bungee_in--;+ float before = boss.elapsed;+ bool timed = boss.phase == BS_IDLE || boss.phase == BS_HEAD_BEFORE || boss.phase == BS_HEAD_AFTER || boss.phase == BS_BUNGEE_WAIT;+ boss.elapsed += boss.chill > 0 && !timed ? 0.5f : 1;+ if (boss.phase == BS_HEAD_LEAVE && boss.elapsed > boss.duration * 0.23f) boss.chill = 0;+ if (boss.phase == BS_SPAWN && contact(before, 0.6f)) {+ int kind = boss.age < 3500 ? Z_NORMAL : boss.age < 8000 ? Z_CONE : boss.age < 12500 ? Z_BUCKET+ : enemies[irand(boss.row == 0 ? 11 : 12)];+ spawn_zombie(kind, boss.row, 630, 0);+ }+ if (boss.phase == BS_STOMP && contact(before, boss.row >= 2 ? 0.55f : 0.5f)) crush(boss.row, 5, 4);+ if (boss.phase == BS_RV && contact(before, 0.65f)) {+ crush(boss.row, boss.column, 3);+ boss.summon_in = 500, boss.head_in = 5000;+ if (boss.mode >= 1) boss.stomp_in = 4000;+ if (boss.mode >= 2) boss.bungee_in = 6500;+ }+ if (boss.phase == BS_BUNGEE && contact(before, 0.4f)) bungees(boss.column);+ if (boss.phase == BS_SPIT && contact(before, 0.42f)) {+ boss.ball.on = 1, boss.ball.kind = boss.ball_kind, boss.ball.row = boss.row, boss.ball.x = 530, boss.ball.age = 0;+ }+ if (boss.elapsed < boss.duration) return;+ if (boss.phase == BS_DEATH) {+ B.phase = PH_WON;+ B.nzombies = 0, B.nshots = 0;+ B.last_x = 600, B.last_y = row_y(2, 600);+ return;+ }+ if (boss.phase == BS_BUNGEE) enter(BS_BUNGEE_WAIT, CL_BUNGEE_ENTER, 1);+ else if (boss.phase == BS_BUNGEE_WAIT) {+ bool done = true;+ for (int i = 0; i < B.nzombies; i++)+ done &= !(B.zombies[i].kind == Z_BUNGEE && B.zombies[i].phase != BP_UP && B.zombies[i].health > 0);+ if (done) enter(BS_BUNGEE_LEAVE, CL_BUNGEE_LEAVE, -1);+ } else if (boss.phase == BS_HEAD_ENTER) enter(BS_HEAD_BEFORE, CL_HEAD_IDLE, 500);+ else if (boss.phase == BS_HEAD_BEFORE) {+ boss.row = (uint8_t)range(0, 4), boss.ball_kind = (uint8_t)(frand() < 0.5f ? 0 : 1);+ enter(BS_SPIT, CL_ATTACK1 + boss.row, -1);+ } else if (boss.phase == BS_SPIT) enter(BS_HEAD_AFTER, CL_HEAD_IDLE, 300);+ else if (boss.phase == BS_HEAD_AFTER) enter(BS_HEAD_LEAVE, CL_HEAD_LEAVE, -1);+ else if (boss.phase != BS_IDLE) enter(BS_IDLE, CL_IDLE, (float)range(100, 200));+ else {+ int mode = boss.health < BOSS_HEALTH / 3 ? 2 : boss.health < BOSS_HEALTH * 2 / 3 ? 1 : 0;+ if (mode != boss.mode) {+ boss.mode = (uint8_t)mode;+ if (mode == 1) boss.column = (uint8_t)range(0, 2), boss.bungee_in = (int16_t)range(4000, 5000), enter(BS_BUNGEE, CL_BUNGEE_ENTER, -1);+ else boss.row = (uint8_t)range(0, 3), boss.column = (uint8_t)range(0, 2), enter(BS_RV, CL_RV, -1);+ } else if (boss.stomp_in == 0) {+ boss.stomp_in = (int16_t)range(5500, 6500);+ int rows[4], n = 0;+ for (int r = 0; r < 4; r++) {+ bool any = false;+ for (int i = 0; i < B.nplants; i++)+ any |= B.plants[i].row >= r && B.plants[i].row <= r + 1 && B.plants[i].col >= 5 && B.plants[i].health > 0;+ if (any) rows[n++] = r;+ }+ if (n) boss.row = (uint8_t)rows[irand(n)], enter(BS_STOMP, CL_STOMP1 + boss.row, -1);+ else enter(BS_IDLE, CL_IDLE, (float)range(100, 200));+ } else if (boss.bungee_in == 0) {+ if (frand() < 0.25f) boss.row = (uint8_t)range(0, 3), boss.column = (uint8_t)range(0, 2), enter(BS_RV, CL_RV, -1);+ else boss.column = (uint8_t)range(0, 2), boss.bungee_in = (int16_t)range(4000, 5000), enter(BS_BUNGEE, CL_BUNGEE_ENTER, -1);+ } else if (boss.head_in == 0) {+ boss.head_in = (int16_t)range(4000, 5000);+ enter(BS_HEAD_ENTER, CL_HEAD_ENTER, -1);+ } else if (boss.summon_in == 0) {+ boss.row = (uint8_t)range(0, 4);+ boss.summon_in = (int16_t)(boss.mode == 0 ? range(450, 550) : boss.mode == 1 ? range(350, 450) : range(150, 250));+ enter(BS_SPAWN, CL_SPAWN1 + boss.row, -1);+ } else+ enter(BS_IDLE, CL_IDLE, (float)range(100, 200));+ }+}diff --git a/games/pvz/src/boss_art.c b/games/pvz/src/boss_art.cnew file mode 100644index 00000000..c6bf5853--- /dev/null+++ b/games/pvz/src/boss_art.c@@ -0,0 +1,186 @@+/* Dr. Zomboss's Zombot, drawn as the game draws it: parts moved, turned and scaled by the tracks of its .reanim,+ * one of every three frames kept and the others in between. Each part is a 4-bit picture drawn turned: every+ * screen pixel it covers looks up the part's pixel under it (boss_art.h). */+#include <string.h>+#include "boss_art.h"+#include "draw.h"+#include "game.h"+#include "gfx.h"+#include "res.h"++#define MAX_DRAWN 80+#define PART_K 1.25f /* the parts' pictures are 0.32 of the game's size; the screen is 0.4 */++enum { RIG_BODY, RIG_DRIVER, RIG_FIRE, RIG_ICE };+typedef struct { int16_t x, y, sx, sy, kx, ky; uint8_t part, alpha; } Pose;+typedef struct {+ float a, b, c, d, tx, ty; /* screen = (a c; b d) (u v) + t, u v the part's pixels */+ float ia, ib, ic, id; /* the inverse */+ int16_t x0, y0, x1, y1; /* what it covers on the screen */+ uint8_t part, alpha;+} Drawn;+/* (in gfx_scratch: no background is unpacked while a frame is drawn) */+#define drawn ((Drawn *)(void *)gfx_scratch)+_Static_assert(MAX_DRAWN * sizeof(Drawn) <= sizeof gfx_scratch, "the parts drawn");+static int ndrawn, tint;++static const uint8_t *base(void) { return table(T_BOSS); }++typedef struct { uint16_t w, h; const uint16_t *pal; const uint8_t *px; } Part;+static Part part(int i) {+ const uint8_t *b = base(), *t = b + rd32(b), *e = t + 4 + 12 * i;+ Part p = {rd16(e), rd16(e + 2), pal_colors(rd16(e + 4), NULL), b + rd32(e + 8)};+ return p;+}++typedef struct { uint16_t ntracks, kept, step, head; const uint8_t *flags, *offs; } Rig;+static Rig rig(int r) {+ const uint8_t *b = base(), *h = b + rd32(b + 4 + 4 * r);+ Rig g = {rd16(h), rd16(h + 2), rd16(h + 4), rd16(h + 6), h + 8, NULL};+ g.offs = h + 8 + ((g.ntracks + 3) & ~3);+ return g;+}++/* track i's pose in kept frame f, if it shows */+static bool pose(const Rig *g, int f, int i, Pose *p) {+ const uint8_t *fr = base() + rd32(g->offs + 4 * f), *mask = fr;+ if (!(mask[i >> 3] >> (i & 7) & 1)) return false;+ int n = 0;+ for (int k = 0; k < i; k++) n += mask[k >> 3] >> (k & 7) & 1;+ const uint8_t *q = fr + (g->ntracks + 7) / 8 + 14 * n;+ p->x = rds16(q), p->y = rds16(q + 2), p->sx = rds16(q + 4), p->sy = rds16(q + 6), p->kx = rds16(q + 8);+ p->ky = rds16(q + 10), p->part = q[12], p->alpha = q[13];+ return true;+}++static float fsin(float deg) {+ /* (sine of degrees, by its Taylor series around the nearest quarter turn) */+ float t = deg / 360.0f;+ t -= (float)(int)t;+ if (t < 0) t += 1;+ float x = t * 6.2831853f;+ if (x > 3.14159265f) x -= 6.2831853f;+ float x2 = x * x;+ return x * (1 - x2 / 6 * (1 - x2 / 20 * (1 - x2 / 42 * (1 - x2 / 72))));+}+static float fcos(float deg) { return fsin(deg + 90); }++/* adds the rig's parts at clip position pos (in the .reanim's frames, from the clip's start), moved by (ox, oy) */+static void add_rig(int r, int start, int len, float pos, bool loop, float ox, float oy, float scale,+ float arm_dx, float arm_dy, Pose *head) {+ Rig g = rig(r);+ if (loop) {+ while (pos >= len) pos -= len;+ } else if (pos > len - 1)+ pos = (float)(len - 1);+ if (pos < 0) pos = 0;+ /* the kept frames inside the clip */+ int first = (start + g.step - 1) / g.step, last = (start + len - 1) / g.step;+ if (last >= g.kept) last = g.kept - 1;+ if (first > last) first = last;+ float at = (start + pos) / g.step;+ if (at < first) at = (float)first;+ if (at > last) at = (float)last;+ int f0 = (int)at, f1 = f0 + 1 > last ? (loop ? first : last) : f0 + 1;+ float k = at - f0;+ for (int i = 0; i < g.ntracks && ndrawn < MAX_DRAWN; i++) {+ Pose a, b;+ if (!pose(&g, f0, i, &a)) continue;+ if (!pose(&g, f1, i, &b) || b.part != a.part) b = a;+ float x = (a.x + (b.x - a.x) * k) / 8, y = (a.y + (b.y - a.y) * k) / 8;+ float sx = (a.sx + (b.sx - a.sx) * k) / 4096, sy = (a.sy + (b.sy - a.sy) * k) / 4096;+ float kx = (a.kx + (b.kx - a.kx) * k) / 16, ky = (a.ky + (b.ky - a.ky) * k) / 16;+ if (i == g.head && head) *head = a, head->x = (int16_t)(x * 8), head->y = (int16_t)(y * 8);+ if (g.flags[i]) x += arm_dx, y += arm_dy;+ Part p = part(a.part);+ Drawn *d = &drawn[ndrawn];+ /* the part's matrix in the game's pixels, then the screen's */+ float ma = fcos(kx) * sx, mb = fsin(kx) * sx, mc = -fsin(ky) * sy, md = fcos(ky) * sy;+ float s = scale * PART_K;+ d->a = ma * s, d->b = mb * s, d->c = mc * s, d->d = md * s;+ d->tx = (ox + x * scale - cam_x) * 0.4f, d->ty = (oy + y * scale) * 0.4f;+ float det = d->a * d->d - d->c * d->b;+ if (det < 1e-6f && det > -1e-6f) continue;+ d->ia = d->d / det, d->ib = -d->b / det, d->ic = -d->c / det, d->id = d->a / det;+ float xs[4] = {0, (float)p.w, 0, (float)p.w}, ys[4] = {0, 0, (float)p.h, (float)p.h};+ float x0 = 1e9f, y0 = 1e9f, x1 = -1e9f, y1 = -1e9f;+ for (int c = 0; c < 4; c++) {+ float X = d->a * xs[c] + d->c * ys[c] + d->tx, Y = d->b * xs[c] + d->d * ys[c] + d->ty;+ x0 = X < x0 ? X : x0, x1 = X > x1 ? X : x1, y0 = Y < y0 ? Y : y0, y1 = Y > y1 ? Y : y1;+ }+ if (x1 < 0 || y1 < 0 || x0 >= SCREEN_W || y0 >= SCREEN_H) continue;+ d->x0 = (int16_t)(x0 < 0 ? 0 : x0), d->y0 = (int16_t)(y0 < 0 ? 0 : y0);+ d->x1 = (int16_t)(x1 + 1 > SCREEN_W ? SCREEN_W : x1 + 1), d->y1 = (int16_t)(y1 + 1 > SCREEN_H ? SCREEN_H : y1 + 1);+ d->part = a.part, d->alpha = (uint8_t)(a.alpha + (b.alpha - a.alpha) * k);+ ndrawn++;+ }+}++static uint16_t boss_color(uint16_t c) {+ int r = c >> 11, g = (c >> 5) & 63, b = c & 31;+ if (tint == 1) r = r * 9 / 16, g = g * 13 / 16 + 6, b = b * 3 / 4 + 11; /* frozen */+ else if (tint == 2) r = r + 6, g = g + 12, b = b + 6; /* hit */+ r = r > 31 ? 31 : r, g = g > 63 ? 63 : g, b = b > 31 ? 31 : b;+ return (uint16_t)(r << 11 | g << 5 | b);+}++static void band_fn(uint16_t *band, int y0, int y1, void *ctx) {+ (void)ctx;+ for (int i = 0; i < ndrawn; i++) {+ const Drawn *d = &drawn[i];+ if (d->y1 <= y0 || d->y0 >= y1) continue;+ Part p = part(d->part);+ uint16_t pal[16];+ for (int c = 0; c < 16; c++) pal[c] = boss_color(p.pal[c]);+ int stride = (p.w + 1) / 2;+ bool half = d->alpha < 190;+ if (d->alpha < 40) continue;+ /* 16.16 fixed point across each row */+ int32_t du = (int32_t)(d->ia * 65536), dv = (int32_t)(d->ib * 65536);+ int ya = d->y0 > y0 ? d->y0 : y0, yb = d->y1 < y1 ? d->y1 : y1;+ for (int y = ya; y < yb; y++) {+ uint16_t *out = band + (y % GFX_BAND) * SCREEN_W;+ float fx = d->x0 + 0.5f - d->tx, fy = y + 0.5f - d->ty;+ int32_t u = (int32_t)((d->ia * fx + d->ic * fy) * 65536), v = (int32_t)((d->ib * fx + d->id * fy) * 65536);+ for (int x = d->x0; x < d->x1; x++, u += du, v += dv) {+ uint32_t iu = (uint32_t)(u >> 16), iv = (uint32_t)(v >> 16);+ if (u < 0 || v < 0 || iu >= p.w || iv >= p.h) continue;+ int c = p.px[iv * stride + (iu >> 1)] >> ((iu & 1) * 4) & 15;+ if (!c) continue;+ out[x] = half ? mix565(pal[c], out[x], 16) : pal[c];+ }+ }+ }+}++void boss_draw(void) {+ ndrawn = 0;+ tint = boss.frozen > 0 ? 1 : B.ticks - boss.hit_at < 10 ? 2 : 0;+ const BossClip *c = &boss_clips[boss.clip];+ bool timed = boss.phase == BS_IDLE || boss.phase == BS_HEAD_BEFORE || boss.phase == BS_HEAD_AFTER;+ float elapsed = boss.phase == BS_BUNGEE_WAIT ? 1000 : boss.elapsed;+ float pos = elapsed * boss.fps * (boss.chill > 0 && timed ? 0.5f : 1) / 100;+ float adx = 0, ady = 0;+ if (boss.phase == BS_RV) adx = boss.column * 80.0f, ady = (boss.row - 1) * 85.0f - boss.column * 20.0f;+ else if (boss.phase == BS_BUNGEE || boss.phase == BS_BUNGEE_WAIT || boss.phase == BS_BUNGEE_LEAVE) adx = boss.column * 80.0f - 23;+ Pose head;+ memset(&head, 0, sizeof head);+ head.part = 0xFF;+ add_rig(RIG_BODY, c->start, c->len, pos, timed, 0, 0, 1, adx, ady, &head);+ /* the driver, in the Zombot's head */+ if (head.part != 0xFF) {+ static const uint16_t clip[3][2] = {{9, 15}, {24, 25}, {78, 86}};+ int k = boss.phase == BS_DEATH ? 2 : boss.phase == BS_SPIT ? 1 : 0;+ float dpos = k == 2 ? boss.elapsed * 18 / 100 : boss.anim * (k == 1 ? 36 : 18) / 100.0f;+ add_rig(RIG_DRIVER, clip[k][0], clip[k][1], dpos, k != 2, head.x / 8.0f + 28, head.y / 8.0f - 84, 1.2f, 0, 0, NULL);+ }+ /* the fire or ice ball */+ if (boss.ball.on) {+ bool ice = boss.ball.kind == 1;+ int start = boss.ball.age < 100 ? (ice ? 1 : 0) : (ice ? 17 : 16), len = boss.ball.age < 100 ? 16 : (ice ? 59 : 57);+ float bpos = boss.ball.age < 100 ? boss.ball.age * 16 / 100.0f : (boss.ball.age - 100) * 2 / 100.0f;+ float bx = boss.ball.x, by = row_y(boss.ball.row, boss.ball.x);+ add_rig(ice ? RIG_ICE : RIG_FIRE, start, len, bpos, boss.ball.age >= 100, bx - 75, by - 120, 1, 0, 0, NULL);+ }+ gfx_custom(band_fn, NULL);+}diff --git a/games/pvz/src/boss_art.h b/games/pvz/src/boss_art.hnew file mode 100644index 00000000..aa4c3ebe--- /dev/null+++ b/games/pvz/src/boss_art.h@@ -0,0 +1,13 @@+/* Dr. Zomboss's Zombot: its animations (boss.c) and its drawing from its parts (boss_art.c). */+#ifndef PVZ_BOSS_ART_H+#define PVZ_BOSS_ART_H+#include <stdint.h>++enum {+ CL_ENTER, CL_IDLE, CL_SPAWN1, CL_SPAWN2, CL_SPAWN3, CL_SPAWN4, CL_SPAWN5, CL_BUNGEE_ENTER, CL_BUNGEE_LEAVE,+ CL_STOMP1, CL_STOMP2, CL_STOMP3, CL_STOMP4, CL_HEAD_ENTER, CL_HEAD_IDLE, CL_ATTACK1, CL_ATTACK2, CL_ATTACK3,+ CL_ATTACK4, CL_ATTACK5, CL_HEAD_LEAVE, CL_DEATH, CL_RV, N_CLIPS+};+typedef struct { uint16_t start, len; } BossClip;+extern const BossClip boss_clips[N_CLIPS];+#endifdiff --git a/games/pvz/src/data.bin b/games/pvz/src/data.binindex f76f6c25..db39c237 100644Binary files a/games/pvz/src/data.bin and b/games/pvz/src/data.bin differdiff --git a/games/pvz/src/data.h b/games/pvz/src/data.hindex 0366a869..acc365f7 100644--- a/games/pvz/src/data.h+++ b/games/pvz/src/data.h@@ -358,11 +358,10 @@#define BG_POOL 3#define BG_FOG 4#define BG_ROOF 5-#define BG_ROOF_NIGHT 6-#define BG_MENU 7-#define BG_AWARD 8-#define BG_ALMANAC 9-#define BG_SHOP 10+#define BG_MENU 6+#define BG_AWARD 7+#define BG_ALMANAC 8+#define BG_SHOP 9#define F_BIG 0#define F_HEAD 1diff --git a/games/pvz/src/draw.c b/games/pvz/src/draw.cnew file mode 100644index 00000000..4453b700--- /dev/null+++ b/games/pvz/src/draw.c@@ -0,0 +1,674 @@+/* Drawing the lawn: plants, zombies, shots, sun and the dead, row by row (draw.h). */+#include <string.h>+#include "draw.h"+#include "game.h"+#include "gfx.h"+#include "res.h"++float cam_x; /* the view's left in the game's pixels (0: the lawn as it is played) */++/* the game's pixels to the screen's */+static inline int SX(float x) { float v = (x - cam_x) * 0.4f; return (int)(v < 0 ? v - 0.5f : v + 0.5f); }+static inline int SY(float y) { float v = y * 0.4f; return (int)(v < 0 ? v - 0.5f : v + 0.5f); }+int screen_x(float x) { return SX(x); }+int screen_y(float y) { return SY(y); }++/* ---------------------------------------------------------------- plants */++int plant_anim(int kind) {+ static const uint16_t a[N_PLANTS] = {+ A_PEASHOOTER, A_SUNFLOWER, A_CHERRYBOMB, A_WALLNUT, A_POTATOMINE, A_SNOWPEA, A_CHOMPER, A_REPEATER,+ A_PUFFSHROOM, A_SUNSHROOM, A_FUMESHROOM, A_GRAVEBUSTER, A_HYPNOSHROOM, A_SCAREDYSHROOM, A_ICESHROOM, A_DOOMSHROOM,+ A_LILYPAD, A_SQUASH, A_THREEPEATER, A_TANGLEKELP, A_JALAPENO, A_SPIKEWEED, A_TORCHWOOD, A_TALLNUT,+ A_SEASHROOM, A_PLANTERN, A_CACTUS, A_BLOVER, A_SPLITPEA, A_STARFRUIT, A_PUMPKIN, A_MAGNETSHROOM,+ A_CABBAGEPULT, A_FLOWERPOT, A_KERNELPULT, A_COFFEEBEAN, A_GARLIC, A_UMBRELLA, A_MARIGOLD, A_MELONPULT,+ A_EXPLODENUT,+ };+ return a[kind];+}++/* the plant's animation now, and its time in it */+static int plant_now(const Plant *p, uint32_t *t) {+ int kind = p->kind, a = plant_anim(kind);+ uint32_t since = B.ticks - p->shot;+ *t = B.ticks + p->id * 37u;+ int full = plant_defs[kind].health;+ switch (kind) {+ case P_WALLNUT: case P_TALLNUT: case P_PUMPKIN: case P_GARLIC: {+ static const uint16_t c1[] = {A_WALLNUT_CRACKED1, A_TALLNUT_CRACKED1, A_PUMPKIN_CRACKED1, A_GARLIC_CRACKED1};+ static const uint16_t c2[] = {A_WALLNUT_CRACKED2, A_TALLNUT_CRACKED2, A_PUMPKIN_CRACKED2, A_GARLIC_CRACKED2};+ int k = kind == P_WALLNUT ? 0 : kind == P_TALLNUT ? 1 : kind == P_PUMPKIN ? 2 : 3;+ if (p->health < full / 3) a = c2[k];+ else if (p->health < full * 2 / 3) a = c1[k];+ break;+ }+ case P_CHOMPER:+ if (p->state == CH_BITE) a = A_CHOMPER_BITE, *t = (uint32_t)(70 - p->aux) * anim_info(A_CHOMPER_BITE).cycle / 70;+ else if (p->state == CH_DIGEST) a = A_CHOMPER_DIGEST;+ break;+ case P_POTATOMINE:+ if (p->action > 0) a = A_POTATOMINE_UNARMED;+ break;+ case P_SUNSHROOM:+ if (p->flags & PF_GROWN) a = A_SUNSHROOM_BIG;+ break;+ case P_SCAREDYSHROOM:+ if (p->flags & PF_SCARED) a = A_SCAREDYSHROOM_SCARED;+ break;+ case P_SQUASH:+ if (p->state) a = A_SQUASH_ATTACK, *t = (uint32_t)(185 - p->aux) * anim_info(A_SQUASH_ATTACK).cycle / 185;+ break;+ case P_TANGLEKELP:+ if (p->state) a = A_TANGLEKELP_GRAB;+ break;+ case P_CACTUS:+ if (p->flags & PF_TALL) a = A_CACTUS_TALL;+ break;+ case P_MAGNETSHROOM:+ if (p->action > 0) a = A_MAGNETSHROOM_ATTACK;+ break;+ case P_CABBAGEPULT: case P_KERNELPULT: case P_MELONPULT: {+ int att = kind == P_CABBAGEPULT ? A_CABBAGEPULT_ATTACK : kind == P_KERNELPULT ? A_KERNELPULT_ATTACK : A_MELONPULT_ATTACK;+ uint32_t c = anim_info(att).cycle;+ if (since < c / 2) a = att, *t = since + c / 2;+ break;+ }+ case P_FUMESHROOM:+ if (since < 30) a = A_FUMESHROOM_ATTACK;+ break;+ case P_UMBRELLA:+ if (since < anim_info(A_UMBRELLA_BLOCK).cycle) a = A_UMBRELLA_BLOCK, *t = since;+ break;+ case P_BLOVER:+ if (B.ticks - p->born > 50) a = A_BLOVER_LOOP;+ break;+ case P_CHERRYBOMB: case P_JALAPENO: case P_ICESHROOM: case P_DOOMSHROOM: case P_COFFEEBEAN: case P_GRAVEBUSTER:+ /* the fuse, once */+ *t = (uint32_t)(B.ticks - p->born) * anim_info(a).cycle / (kind == P_GRAVEBUSTER ? 400 : 100);+ if (*t >= anim_info(a).cycle) *t = anim_info(a).cycle - 1;+ break;+ }+ return a;+}++static int plant_layer(const Plant *p) {+ return p->kind == P_LILYPAD || p->kind == P_FLOWERPOT ? 0 : p->kind == P_PUMPKIN ? 2 : p->kind == P_COFFEEBEAN ? 3 : 1;+}++void draw_plant_at(int kind, int x, int y, int alpha) {+ Plant fake;+ memset(&fake, 0, sizeof fake);+ fake.kind = (uint8_t)kind, fake.health = plant_defs[kind].health, fake.shot = (uint32_t)-1000;+ uint32_t t;+ int a = plant_now(&fake, &t);+ gfx_anim(a, anim_frame_at(a, B.ticks), x, y, 0, TINT_NONE, alpha);+}++static void draw_plant(const Plant *p) {+ float x = cell_x(p->col), y = row_y(p->row, x);+ if (B.env == ENV_ROOF && p->kind != P_FLOWERPOT && plant_at(p->col, p->row, P_FLOWERPOT)) y -= 12;+ if (water_row(p->row) && p->kind != P_LILYPAD && p->kind != P_TANGLEKELP && p->kind != P_SEASHROOM) y -= 3;+ uint32_t t;+ int a = plant_now(p, &t);+ if (p->kind == P_SQUASH && p->state) {+ /* the jump: up, over, down onto its zombie */+ float k = (185 - p->aux) / 185.0f;+ float k2 = k * 2 > 1 ? 1 : k * 2;+ x += (p->tx - x) * k2;+ y -= (k < 0.5f ? k * 2 : (1 - k) * 2) * 70;+ }+ int tint = sleeping(p) ? TINT_SLEEP : TINT_NONE;+ if (p->kind != P_LILYPAD && p->kind != P_FLOWERPOT && p->kind != P_TANGLEKELP && p->kind != P_SPIKEWEED &&+ p->kind != P_PUMPKIN && !water_row(p->row))+ gfx_ellipse(SX(x), SY(y) - 1, 9, 3, 0, 9);+ gfx_anim(a, anim_frame_at(a, t), SX(x), SY(y), 0, tint, 32);+ if (tint == TINT_SLEEP && (B.ticks / 60 + p->id) % 3 == 0) {+ int k = (int)((B.ticks + p->id * 13) % 120);+ gfx_text(F_SMALL, SX(x) + 6 + k / 20, SY(y) - 18 - k / 8, "z", rgb565(0x9EB8FF), GFX_OUTLINE);+ }+}++/* ---------------------------------------------------------------- zombies */++/* walk, eat, headless, die and burn of each kind */+static const uint16_t z_walk[N_ZOMBIES] = {+ A_ZOMBIE_WALK, A_FLAG_WALK, A_CONE_WALK, A_POLE_WALK, A_BUCKET_WALK, A_NEWSPAPER_WALK, A_DOOR_WALK, A_FOOTBALL_WALK,+ A_DANCER_WALK, A_BACKUP_WALK, A_DUCKY1_WALK, A_SNORKEL_WALK, A_ZOMBONI_WALK, A_BOBSLED_WALK, A_DOLPHIN_WALK,+ A_JACK_WALK, A_BALLOON_WALK, A_DIGGER_WALK, A_POGO_WALK, A_BUNGEE_IDLE, A_LADDER_WALK, A_CATAPULT_WALK,+ A_GARGANTUAR_WALK, A_IMP_WALK,+};+static const uint16_t z_eat[N_ZOMBIES] = {+ A_ZOMBIE_EAT, A_FLAG_EAT, A_CONE_EAT, A_POLE_EAT, A_BUCKET_EAT, A_NEWSPAPER_EAT, A_DOOR_EAT, A_FOOTBALL_EAT,+ A_DANCER_EAT, A_BACKUP_EAT, A_DUCKY1_EAT, A_SNORKEL_EAT, A_ZOMBONI_WALK, A_BOBSLED_EAT, A_DOLPHIN_EAT, A_JACK_EAT,+ A_BALLOON_EAT, A_DIGGER_EAT, A_POGO_EAT, A_BUNGEE_IDLE, A_LADDER_EAT, A_CATAPULT_IDLE, A_GARGANTUAR_SMASH, A_IMP_EAT,+};+static const uint16_t z_headless[N_ZOMBIES] = {+ A_ZOMBIE_HEADLESS, A_ZOMBIE_HEADLESS, A_ZOMBIE_HEADLESS, A_POLE_HEADLESS, A_ZOMBIE_HEADLESS, A_NEWSPAPER_HEADLESS,+ A_ZOMBIE_HEADLESS, A_FOOTBALL_HEADLESS, A_DANCER_HEADLESS, A_BACKUP_HEADLESS, A_DUCKY1_WALK, A_SNORKEL_WALK,+ A_ZOMBONI_CRITICAL, A_BOBSLED_WALK, A_DOLPHIN_WALK, A_JACK_HEADLESS, A_BALLOON_WALK, A_DIGGER_WALK, A_POGO_WALK,+ A_BUNGEE_IDLE, A_LADDER_BARE, A_CATAPULT_WALK, A_GARGANTUAR_WALK, A_IMP_WALK,+};+static const uint16_t z_die[N_ZOMBIES] = {+ A_ZOMBIE_DIE, A_ZOMBIE_DIE, A_ZOMBIE_DIE, A_POLE_DIE, A_ZOMBIE_DIE, A_NEWSPAPER_DIE, A_ZOMBIE_DIE, A_FOOTBALL_DIE,+ A_DANCER_DIE, A_BACKUP_DIE, A_DUCKY_DIE, A_SNORKEL_DIE, A_ZOMBONI_DIE, A_BOBSLED_DIE, A_DOLPHIN_DIE, A_JACK_DIE,+ A_BALLOON_DIE, A_DIGGER_DIE, A_POGO_DIE, A_BUNGEE_DIE, A_LADDER_DIE, A_CATAPULT_DIE, A_GARGANTUAR_DIE, A_IMP_DIE,+};+static const uint16_t z_burn[N_ZOMBIES] = {+ A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_POLE_BURN, A_ZOMBIE_BURN, A_NEWSPAPER_BURN, A_ZOMBIE_BURN,+ A_ZOMBIE_BURN, A_DANCER_BURN, A_BACKUP_BURN, A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_ZOMBONI_DIE, A_ZOMBIE_BURN, A_ZOMBIE_BURN,+ A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_ZOMBIE_BURN, A_BUNGEE_DIE, A_ZOMBIE_BURN, A_CATAPULT_DIE,+ A_GARGANTUAR_DIE, A_IMP_DIE,+};++/* in the pool's water, the zombie floats in a ducky tube */+static bool in_pool(const Zombie *z) { return water_row(z->row) && z->x > 100 && z->x < 770; }++static int walk_frame(const Zombie *z, int a) {+ float dist = 49.8f;+ switch (z->kind) {+ case Z_GARGANTUAR: dist = 124.1f; break;+ case Z_IMP: dist = 62.9f; break;+ case Z_DANCER: case Z_BACKUP: dist = 28.6f * 3; break;+ case Z_SNORKEL: dist = 59.9f; break;+ case Z_FOOTBALL: dist = 30 * 2; break;+ case Z_NEWSPAPER: dist = 57.8f; break;+ case Z_POLE: dist = z->flags & ZF_POLE ? 30 * 2 : 67.8f; break;+ case Z_DIGGER: case Z_LADDER: dist = 80; break;+ }+ if (z->flags & ZF_MINI) dist *= 0.5f;+ int n = anim_frames(a);+ return (int)(z->walk / dist * n) % n;+}++/* the animation a zombie shows now, its frame, and whether it is drawn turned round */+static int zombie_now(const Zombie *z, int *frame, int *flip) {+ int k = z->kind, a;+ bool eating = (z->flags & ZF_EATING) != 0;+ *flip = (z->flags & (ZF_HYPNO | ZF_BACKWARDS)) != 0;+ /* a cone or bucket knocked off: a plain zombie (a screen door lost, a football helmet...) */+ int look = k;+ if ((k == Z_CONE || k == Z_BUCKET) && z->armor <= 0) look = Z_NORMAL;+ if (k == Z_DOOR && z->shield <= 0) look = Z_NORMAL;+ if (look == Z_NORMAL || look == Z_CONE || look == Z_BUCKET || look == Z_FLAG) {+ if (in_pool(z)) {+ a = eating ? (look == Z_CONE ? A_DUCKY2_EAT : look == Z_BUCKET ? A_DUCKY3_EAT : A_DUCKY1_EAT)+ : (look == Z_CONE ? A_DUCKY2_WALK : look == Z_BUCKET ? A_DUCKY3_WALK : A_DUCKY1_WALK);+ *frame = eating ? anim_frame_at(a, (uint32_t)z->anim) : walk_frame(z, a);+ return a;+ }+ }+ if (zombie_headless(z) && k != Z_BUNGEE) {+ a = z_headless[look];+ *frame = walk_frame(z, a);+ return a;+ }+ a = eating ? z_eat[look] : z_walk[look];+ switch (k) {+ case Z_POLE:+ if (z->vault > 0) {+ a = A_POLE_JUMP;+ *frame = (int)((168 - z->vault) / 168 * anim_frames(a));+ return a;+ }+ if (z->flags & ZF_POLE) a = A_POLE_RUN;+ break;+ case Z_NEWSPAPER:+ if (z->rage > 0) {+ a = A_NEWSPAPER_GASP;+ *frame = (int)((150 - z->rage) / 150 * anim_frames(a));+ return a;+ }+ if (z->flags & ZF_PAPER_GONE) a = eating ? A_NEWSPAPER_MAD_EAT : A_NEWSPAPER_MAD_WALK;+ break;+ case Z_FOOTBALL:+ if (z->armor <= 0) a = eating ? A_FOOTBALL_BARE_EAT : A_FOOTBALL_BARE_WALK;+ break;+ case Z_DANCER:+ if (z->phase == DP_POINT) a = A_DANCER_SUMMON;+ break;+ case Z_SNORKEL:+ if (zombie_submerged(z)) a = A_SNORKEL_SWIM;+ break;+ case Z_DOLPHIN:+ if (z->vault > 0) {+ a = A_DOLPHIN_JUMP;+ *frame = (int)((120 - z->vault) / 120 * anim_frames(a));+ return a;+ }+ if (z->flags & ZF_DOLPHIN) a = in_pool(z) ? A_DOLPHIN_RIDE : A_DOLPHIN_WALK;+ else if (in_pool(z)) a = eating ? A_DOLPHIN_EAT : A_DOLPHIN_SWIM;+ break;+ case Z_JACK:+ if (z->flags & ZF_OPENING) {+ a = A_JACK_OPEN;+ *frame = (int)((110 - z->u.jack.in) * anim_frames(a) / 110);+ return a;+ }+ break;+ case Z_BALLOON:+ if (z->pop > 0) {+ a = A_BALLOON_POP;+ *frame = (50 - z->pop) * anim_frames(a) / 50;+ return a;+ }+ if (z->flags & ZF_FLYING) a = A_BALLOON_FLY;+ break;+ case Z_DIGGER:+ if (z->flags & ZF_UNDERGROUND) a = A_DIGGER_DIG;+ else if (z->emerge > 0) {+ a = A_DIGGER_RISE;+ int left = z->emerge > 230 ? 230 : z->emerge;+ *frame = (230 - left) * anim_frames(a) / 230;+ return a;+ }+ break;+ case Z_POGO:+ if (z->flags & ZF_POGO) a = A_POGO_BOUNCE;+ break;+ case Z_BUNGEE:+ a = z->phase == BP_WAIT ? A_BUNGEE_IDLE : A_BUNGEE_DROP;+ break;+ case Z_LADDER:+ if (z->ladder_in > 0) {+ a = A_LADDER_PLACE;+ *frame = (100 - z->ladder_in) * anim_frames(a) / 100;+ return a;+ }+ if (z->shield <= 0) a = eating ? A_LADDER_EAT : A_LADDER_BARE;+ break;+ case Z_CATAPULT:+ a = z->phase == CP_SHOOT ? A_CATAPULT_SHOOT : z->phase == CP_RELOAD ? A_CATAPULT_IDLE : A_CATAPULT_WALK;+ if (z->phase == CP_SHOOT) {+ *frame = (300 - z->u.catapult.left) * anim_frames(a) / 130;+ if (*frame >= anim_frames(a)) *frame = anim_frames(a) - 1;+ return a;+ }+ break;+ case Z_GARGANTUAR: {+ bool bare = z->u.giant.thrown != 0;+ if (z->phase == GP_SMASH) {+ a = bare ? A_GARGANTUAR_BARE_SMASH : A_GARGANTUAR_SMASH;+ *frame = (int)((134 - z->u.giant.left) / 134 * anim_frames(a));+ return a;+ }+ if (z->phase == GP_THROW) {+ a = A_GARGANTUAR_THROW;+ *frame = (int)((138 - z->u.giant.left) / 138 * anim_frames(a));+ return a;+ }+ a = bare ? A_GARGANTUAR_BARE_WALK : A_GARGANTUAR_WALK;+ break;+ }+ case Z_ZOMBONI:+ a = z->health < 1350 / 3 ? A_ZOMBONI_CRITICAL : z->health < 1350 * 2 / 3 ? A_ZOMBONI_DAMAGED : A_ZOMBONI_WALK;+ *frame = (int)(z->anim / 8) % anim_frames(a);+ return a;+ case Z_IMP:+ if (z->u.flight.left > 0) {+ a = A_IMP_THROWN;+ *frame = (z->u.flight.duration - z->u.flight.left) * anim_frames(a) / (z->u.flight.duration + 1);+ return a;+ }+ if (z->landing > 0) {+ a = A_IMP_LAND;+ *frame = (21 - z->landing) * anim_frames(a) / 21;+ return a;+ }+ break;+ }+ if (eating || a == A_DANCER_SUMMON || a == A_BALLOON_FLY || a == A_BUNGEE_IDLE || a == A_BUNGEE_DROP ||+ a == A_SNORKEL_SWIM || a == A_DIGGER_DIG || a == A_CATAPULT_IDLE || a == A_POGO_BOUNCE || a == A_DOLPHIN_RIDE)+ *frame = anim_frame_at(a, (uint32_t)z->anim);+ else+ *frame = walk_frame(z, a);+ return a;+}++static int zombie_tint(const Zombie *z) {+ if (B.ticks - z->hit_at < 10) return TINT_HIT;+ if (z->frozen > 0) return TINT_FROZEN;+ if (z->flags & ZF_HYPNO) return TINT_HYPNO;+ if (z->chill > 0) return TINT_CHILL;+ return TINT_NONE;+}++static void draw_zombie(const Zombie *z) {+ float x = z->x, y = row_y(z->row, z->x) + 1;+ int frame, flip, a = zombie_now(z, &frame, &flip);+ int tint = zombie_tint(z);+ int sc = z->flags & ZF_MINI ? 128 : 256;+ /* where it is off the ground */+ if (z->kind == Z_IMP && z->u.flight.left > 0) {+ float t = 1 - (float)z->u.flight.left / z->u.flight.duration;+ y -= t * (1 - t) * 4 * 120;+ }+ if (z->kind == Z_BUNGEE) {+ float up = z->phase == BP_DOWN ? z->u.bungee.left * 8.0f : z->phase == BP_UP ? (100 - z->u.bungee.left) * 8.0f : 0;+ float ty = row_y(z->row, x) - 15;+ if (z->phase != BP_UP || z->u.bungee.left > 50) gfx_image(I_BUNGEE_TARGET, SX(x), SY(ty));+ y -= up;+ /* the cord, up to the sky */+ int cx = SX(x), top = SY(y - 80);+ for (int cy = top - 26; cy > -26; cy -= 26) gfx_image(I_BUNGEE_CORD, cx - 1, cy);+ }+ if (z->kind == Z_BOBSLED && z->u.sled.sled && !z->u.sled.leader)+ gfx_image(I_SLED, SX(x + 70), SY(row_y(z->row, x) + 10));+ if (zombie_flying(z)) y -= 0;+ /* rising from a grave or the water: only what is above the ground */+ if (z->rise > 0) {+ int full = z->kind == Z_BACKUP ? 150 : 150;+ int ground = SY(row_y(z->row, x));+ int h = 80 * (full - z->rise) / full;+ gfx_clip(0, 0, SCREEN_W, ground + 2);+ y += (float)(80 - h) * 2.5f * (sc / 256.0f);+ }+ if (in_pool(z) && z->kind != Z_SNORKEL && z->kind != Z_DOLPHIN && z->kind != Z_BALLOON) y += 0;+ if (!zombie_flying(z) && !(z->flags & ZF_UNDERGROUND) && z->kind != Z_BUNGEE && !in_pool(z))+ gfx_ellipse(SX(x), SY(row_y(z->row, x)), sc == 256 ? 11 : 6, 3, 0, 9);+ gfx_anim_scaled(a, frame, SX(x), SY(y), sc, sc, flip ? GFX_FLIP : 0, tint, 32);+ gfx_clip_all();+ if (z->butter > 0) gfx_image(I_BUTTER, SX(x) + (flip ? 2 : -2), SY(y) - (sc == 256 ? 46 : 23));+}++/* the dead: their animation played once (fx_corpse) */+Fx *fx_corpse(const Zombie *z, int burn, int life, int burnt) {+ int k = z->kind;+ if ((k == Z_CONE || k == Z_BUCKET || k == Z_FLAG || k == Z_NORMAL) && in_pool(z)) k = Z_DUCKY;+ int a = burn ? z_burn[k] : z_die[k];+ if (k == Z_GARGANTUAR && z->u.giant.thrown) a = A_GARGANTUAR_BARE_DIE;+ if (k == Z_SNORKEL && zombie_submerged(z)) return NULL;+ if (k == Z_BUNGEE && z->phase != BP_WAIT) return NULL;+ fx_add(FX_CORPSE, z->x, row_y(z->row, z->x) + 1, life, z->row);+ Fx *f = &B.fx[B.nfx - 1];+ if (f->kind != FX_CORPSE) return NULL;+ f->anim = (uint16_t)a;+ f->flags = (uint8_t)((z->flags & (ZF_HYPNO | ZF_BACKWARDS) ? 1 : 0) | (z->flags & ZF_MINI ? 2 : 0) | (burnt ? 4 : 0));+ f->tint = (int16_t)(burn && a == z_die[k] ? TINT_BLACK : TINT_NONE);+ return f;+}++static void draw_corpse(const Fx *f) {+ int n = anim_frames(f->anim), sc = f->flags & 2 ? 128 : 256;+ int fade = f->life - 30;+ int frame = f->t * n / (fade > 10 ? fade : 10);+ if (frame >= n) frame = n - 1;+ int alpha = f->t < fade ? 32 : 32 * (f->life - f->t) / 30;+ int sy = 256;+ if (f->flags & 8) sy = 256 - 200 * (f->t < 20 ? f->t : 20) / 20; /* mowed: flattened */+ gfx_anim_scaled(f->anim, frame, SX(f->x), SY(f->y), sc, sy * sc / 256, f->flags & 1 ? GFX_FLIP : 0, f->tint, alpha);+}++/* ---------------------------------------------------------------- shots, sun and coins */++static void draw_shot(const Shot *s) {+ static const uint16_t img[] = {I_PEA, I_SNOW_PEA, 0, I_PUFF, I_SPIKE, I_STAR, I_CABBAGE, I_KERNEL, I_BUTTER, I_MELON,+ I_BASKETBALL};+ int x = SX(s->x), y = SY(s->y - (s->flags & SF_HIGH ? 72 : 0));+ if (s->kind < S_CABBAGE && s->kind != S_STAR) {+ /* straight shots cast a shadow on the ground */+ gfx_ellipse(x, SY(row_y(s->row, s->x)) - 1, 4, 1, 0, 8);+ }+ if (s->kind == S_FIRE) gfx_anim(A_FIRE_PEA, (int)(B.ticks / 4 + s->id), x, y, s->vx < 0 ? GFX_FLIP : 0, TINT_NONE, 32);+ else gfx_image(img[s->kind], x, y);+}++void draw_sun(float x, float y, int value, int alpha) {+ int sc = value == 15 ? 170 : 256;+ gfx_anim_scaled(A_SUN, anim_frame_at(A_SUN, B.ticks), SX(x), SY(y), sc, sc, 0, TINT_NONE, alpha);+}++static void draw_coin(float x, float y, int value) {+ gfx_image(value >= 1000 ? I_COIN_DIAMOND : value >= 50 ? I_COIN_GOLD : I_COIN_SILVER, SX(x), SY(y));+}++/* ---------------------------------------------------------------- effects */++static void draw_fx(const Fx *f) {+ int x = SX(f->x), y = SY(f->y), t = f->t, life = f->life > 0 ? f->life : 1;+ switch (f->kind) {+ case FX_BOOM: {+ int r = 6 + 30 * t / life, a = 32 - 32 * t / life;+ gfx_ellipse(x, y, r + 4, r * 3 / 4 + 3, rgb565(0xFF3A10), a * 3 / 4);+ gfx_ellipse(x, y, r, r * 3 / 4, rgb565(0xFFB020), a);+ gfx_ellipse(x, y, r / 2, r * 3 / 8, rgb565(0xFFF5B0), a);+ if (t < life * 2 / 3)+ gfx_text(F_BIG, x, y + 6, f->v == 1 ? "SPUDOW!" : "POWIE!", rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ break;+ }+ case FX_DOOM: {+ int r = 10 + 60 * t / life, a = 32 - 28 * t / life;+ gfx_ellipse(x, y, r, r * 2 / 3, rgb565(0x3A1A4A), a);+ gfx_ellipse(x, y - r / 2, r * 2 / 3, r / 2, rgb565(0x6B3A80), a);+ gfx_ellipse(x, y - r, r / 2, r / 3, rgb565(0xB080C0), a * 2 / 3);+ break;+ }+ case FX_FIRE: {+ int n = anim_frames(A_JALAPENO_FIRE), frame = t * n / life;+ gfx_anim(A_JALAPENO_FIRE, frame, SX(BOARD_LEFT - 20), y, 0, TINT_NONE, 32);+ gfx_anim(A_JALAPENO_FIRE, frame, SX(BOARD_LEFT + 330), y, 0, TINT_NONE, 32);+ break;+ }+ case FX_FREEZE:+ gfx_rect(0, 0, SCREEN_W, SCREEN_H, rgb565(0xD8F0FF), 20 - 20 * t / life);+ break;+ case FX_SPLAT: {+ uint16_t c = f->v == S_ICE ? rgb565(0xC8F0FF) : f->v == S_FIRE ? rgb565(0xFF9A20) : f->v == S_PUFF ? rgb565(0xD0A0E0)+ : f->v >= S_CABBAGE ? rgb565(0x9AD040) : rgb565(0x7AD030);+ int r = 2 + 3 * t / life;+ gfx_ellipse(x, y, r, r, c, 32 - 32 * t / life);+ break;+ }+ case FX_DIRT:+ gfx_ellipse(x - 4 - t / 6, y - t / 5, 3, 2, rgb565(0x6A4A2A), 32 - 32 * t / life);+ gfx_ellipse(x + 4 + t / 6, y - t / 5, 3, 2, rgb565(0x7A5A30), 32 - 32 * t / life);+ break;+ case FX_SPLASH:+ gfx_ellipse(x, y - t / 4, 6 + t / 8, 3, rgb565(0xE0F4FF), 28 - 28 * t / life);+ break;+ case FX_SMOKE: {+ uint16_t c = f->v == 2 ? rgb565(0xE070E0) : f->v == 3 ? rgb565(0xB49AD8) : rgb565(0xC8C0B0);+ int r = 4 + 8 * t / life;+ if (f->v == 3) {+ /* the fume cloud, over its lane */+ int n = anim_frames(A_FUME_CLOUD);+ gfx_anim(A_FUME_CLOUD, t * n / life, x, y + 12, 0, TINT_NONE, 32);+ } else+ gfx_ellipse(x, y - t / 4, r, r * 2 / 3, c, 24 - 24 * t / life);+ break;+ }+ case FX_POW:+ gfx_ellipse(x, y, 6 + t / 3, 4 + t / 4, C_WHITE, 28 - 28 * t / life);+ break;+ case FX_TEXT:+ break; /* (the screen's messages: hud.c) */+ case FX_CORPSE:+ draw_corpse(f);+ break;+ }+}++/* ---------------------------------------------------------------- the lawn */++int left_fog_column(void) {+ if (B.env != ENV_FOG) return 99;+ if (B.level == 31) return 6;+ if (B.level <= 36) return 5;+ return 4;+}++/* the fog over the right of the lawn, cleared round planterns, blown off by a blover */+static uint8_t fog_cells[MAX_ROWS][COLS + 1];+static void fog_band(uint16_t *band, int y0, int y1, void *ctx) {+ (void)ctx;+ uint16_t fog = rgb565(0x8A96B0);+ for (int y = y0; y < y1; y++) {+ uint16_t *out = band + (y % GFX_BAND) * SCREEN_W;+ float gy = y / 0.4f;+ int row = row_at(gy, 440);+ if (row < 0) row = 0;+ if (row >= B.nrows) row = B.nrows - 1;+ for (int x = 0; x < SCREEN_W; x++) {+ float gx = x / 0.4f + cam_x;+ int col = col_at(gx);+ if (col < 0) continue;+ int d = col > COLS ? fog_cells[row][COLS] : fog_cells[row][col];+ /* (a soft edge on its left) */+ if (col <= COLS && col > 0) {+ float in = (gx - BOARD_LEFT) / CELL_W - col;+ int prev = fog_cells[row][col - 1];+ if (in < 0.5f) d = prev + (int)((d - prev) * (in + 0.5f));+ }+ if (!d) continue;+ int n = ((x * 7 + y * 13 + (int)(B.ticks / 8)) & 7) - 3;+ int a = d + n;+ a = a < 0 ? 0 : a > 32 ? 32 : a;+ out[x] = mix565(fog, out[x], a);+ }+ }+}++static void draw_fog(void) {+ int left = left_fog_column();+ if (left >= COLS) return;+ /* blown away: off to the right, then back */+ float blow = 0;+ if (B.fog_blown > 0) blow = B.fog_blown > 3800 ? (4000 - B.fog_blown) / 200.0f : B.fog_blown > 400 ? 1 : B.fog_blown / 400.0f;+ float shift = blow * 9;+ for (int r = 0; r < B.nrows; r++)+ for (int c = 0; c <= COLS; c++) {+ float fc = c - shift;+ int d = fc >= left ? 26 : fc >= left - 1 ? 13 : 0;+ fog_cells[r][c] = (uint8_t)d;+ }+ /* planterns light their 3 x 3 (and a bit) */+ for (int i = 0; i < B.nplants; i++) {+ const Plant *p = &B.plants[i];+ if (p->kind != P_PLANTERN || p->health <= 0) continue;+ for (int r = p->row - 1; r <= p->row + 1; r++)+ for (int c = p->col - 1; c <= p->col + 1; c++)+ if (r >= 0 && r < B.nrows && c >= 0 && c <= COLS) fog_cells[r][c] = 0;+ for (int c = p->col - 2; c <= p->col + 2; c++)+ if (c >= 0 && c <= COLS && fog_cells[p->row][c]) fog_cells[p->row][c] /= 2;+ }+ gfx_custom(fog_band, NULL);+ /* and its clouds drifting over it */+ for (int r = 0; r < B.nrows; r++)+ for (int c = left; c <= COLS; c++) {+ if (!fog_cells[r][c]) continue;+ float x = cell_x(c) + shift * CELL_W + 20 * __builtin_sinf((B.ticks / 300.0f) + r * 1.7f + c);+ gfx_anim(I_FOG0 + (r * 3 + c) % 8, 0, SX(x), SY(BOARD_TOP + r * cell_h() + cell_h() / 2), 0, TINT_NONE, 14);+ }+}++void draw_lawn(bool hud_mower) {+ (void)hud_mower;+ /* on the ground: craters, graves, ice */+ for (int i = 0; i < B.ncraters; i++) {+ const Crater *c = &B.craters[i];+ float x = cell_x(c->col);+ gfx_anim(is_night() || B.has_boss ? I_CRATER1 : I_CRATER0, 0, SX(x), SY(row_y(c->row, x)), 0, TINT_NONE,+ c->left < 300 ? 32 * c->left / 300 : 32);+ }+ for (int r = 0; r < B.nrows; r++) {+ const Ice *ice = &B.ice[r];+ if (ice->left <= 0) continue;+ int a = ice->left < 200 ? 32 * ice->left / 200 : 32;+ for (float x = ice->x; x < 820; x += 75)+ gfx_anim(I_ICE_TRAIL, 0, SX(x), SY(row_y(r, x) - 22), 0, TINT_NONE, a);+ }+ if (B.mode == MODE_BOWLING) gfx_image(I_BOWLING_STRIPE, SX(BOARD_LEFT + 3 * CELL_W), SY(BOARD_TOP + 250));+ /* row by row, from the back */+ for (int r = 0; r < B.nrows; r++) {+ for (int i = 0; i < B.ngraves; i++)+ if (B.graves[i].row == r) {+ float x = cell_x(B.graves[i].col);+ gfx_image(I_GRAVE, SX(x), SY(row_y(r, x)) + 2);+ }+ for (int layer = 0; layer < 4; layer++)+ for (int i = 0; i < B.nplants; i++) {+ const Plant *p = &B.plants[i];+ if (p->row == r && p->health > 0 && plant_layer(p) == layer && layer < 2) draw_plant(p);+ }+ for (int i = 0; i < B.nvases; i++)+ if (B.vases[i].row == r) {+ const Vase *v = &B.vases[i];+ float x = cell_x(v->col);+ gfx_image(I_VASE0 + (v->green ? 1 : v->zombie ? 2 : 0), SX(x), SY(row_y(r, x)) + 2);+ }+ for (int i = 0; i < B.ndrops; i++)+ if (B.drops[i].row == r) {+ const Drop *d = &B.drops[i];+ float x = cell_x(d->col);+ int y = SY(row_y(r, x) - 40);+ if (d->left > 300 || (B.ticks / 10) % 2) {+ gfx_image(I_PACKET, SX(x) - 10, y - 14);+ gfx_image(I_PACKET_PEASHOOTER + d->kind, SX(x), y - 2);+ }+ }+ for (int i = 0; i < B.nladders; i++)+ if (B.ladders[i].row == r) {+ float x = cell_x(B.ladders[i].col) + 20;+ gfx_image(I_LADDER, SX(x), SY(row_y(r, x)));+ }+ /* the zombies of the row, the farthest first */+ int order[MAX_ZOMBIES], n = 0;+ for (int i = 0; i < B.nzombies; i++)+ if (B.zombies[i].row == r && B.zombies[i].health > 0) order[n++] = i;+ for (int a = 1; a < n; a++)+ for (int b = a; b > 0 && B.zombies[order[b]].x > B.zombies[order[b - 1]].x; b--) {+ int t = order[b];+ order[b] = order[b - 1], order[b - 1] = t;+ }+ for (int i = 0; i < B.nfx; i++)+ if (B.fx[i].kind == FX_CORPSE && B.fx[i].v == r) draw_fx(&B.fx[i]);+ for (int i = 0; i < n; i++) {+ const Zombie *z = &B.zombies[order[i]];+ if (!zombie_flying(z)) draw_zombie(z);+ }+ for (int i = 0; i < B.nplants; i++) {+ const Plant *p = &B.plants[i];+ if (p->row == r && p->health > 0 && plant_layer(p) >= 2) draw_plant(p);+ }+ for (int i = 0; i < B.nrollers; i++)+ if (B.rollers[i].row == r) {+ const Roller *o = &B.rollers[i];+ int a = o->kind == P_EXPLODENUT ? A_EXPLODENUT : A_WALLNUT_ROLL;+ gfx_anim(a, (int)(o->x / 8), SX(o->x), SY(o->y), 0, TINT_NONE, 32);+ }+ if (B.mowers[r].state < 2) {+ float x = B.mowers[r].x;+ int img = B.env == ENV_ROOF ? I_ROOF_CLEANER : water_row(r) ? I_POOL_CLEANER : I_MOWER;+ gfx_image(img, SX(x), SY(row_y(r, x) + 5));+ }+ for (int i = 0; i < B.nshots; i++)+ if (B.shots[i].row == r && B.shots[i].kind != S_STAR && B.shots[i].kind < S_CABBAGE) draw_shot(&B.shots[i]);+ }+ /* above the rows: what flies */+ for (int i = 0; i < B.nzombies; i++)+ if (zombie_flying(&B.zombies[i]) && B.zombies[i].health > 0) draw_zombie(&B.zombies[i]);+ for (int i = 0; i < B.nshots; i++)+ if (B.shots[i].kind == S_STAR || B.shots[i].kind >= S_CABBAGE) draw_shot(&B.shots[i]);+ if (B.has_boss) boss_draw();+ for (int i = 0; i < B.nfx; i++)+ if (B.fx[i].kind != FX_CORPSE && B.fx[i].kind != FX_SUNFLY && B.fx[i].kind != FX_COINFLY) draw_fx(&B.fx[i]);+ draw_fog();+ for (int i = 0; i < B.ncoins; i++) draw_coin(B.coins[i].x, B.coins[i].y, B.coins[i].value);+ for (int i = 0; i < B.nsuns; i++) {+ const Sun *s = &B.suns[i];+ draw_sun(s->x, s->y, s->value, s->left < 200 ? 16 + 16 * (s->left / 10 % 2) : 32);+ }+}++/* the zombies waiting on the street before a level (its kinds, standing about) */+void draw_street(const uint8_t *kinds, int n) {+ for (int i = 0; i < n; i++) {+ int k = kinds[i];+ float x = 900 + (i * 53) % 230 + (i % 3) * 10, y = 160 + ((i * 97) % 5) * 85.0f + (i % 2) * 20;+ int a = z_walk[k];+ if (k == Z_BUNGEE) continue;+ if (k == Z_BALLOON) a = A_BALLOON_FLY;+ if (k == Z_POLE) a = A_POLE_RUN;+ if (k == Z_DIGGER) a = A_DIGGER_WALK;+ gfx_anim(a, (int)((B.ticks / 12 + i * 5) % anim_frames(a)), SX(x), SY(y), 0, TINT_NONE, 32);+ }+}diff --git a/games/pvz/src/draw.h b/games/pvz/src/draw.hnew file mode 100644index 00000000..8c29cd13--- /dev/null+++ b/games/pvz/src/draw.h@@ -0,0 +1,38 @@+/* Plants vs. Zombies: drawing the lawn (draw.c) and what is over it (hud.c). */+#ifndef PVZ_DRAW_H+#define PVZ_DRAW_H+#include <stdbool.h>+#include <stdint.h>+#include "game.h"++extern float cam_x; /* the view's left in the game's pixels, 0 as the lawn is played */+extern uint32_t vis_ticks; /* hundredths of a second, always running (menus' animations) */+int screen_x(float x);+int screen_y(float y);+int plant_anim(int kind);+void draw_lawn(bool hud);+void draw_plant_at(int kind, int x, int y, int alpha);+void draw_sun(float x, float y, int value, int alpha);+void draw_street(const uint8_t *kinds, int n);+int left_fog_column(void);++/* hud.c: the seed bank, the progress meter, the cursor and the screen's messages */+typedef struct {+ int col, row; /* the cursor's cell */+ int selected; /* a packet (or a dropped seed), -1 none */+ bool shovel;+ int issue, issue_t; /* why it couldn't plant, and since when */+ int ready_t; /* "Ready... Set... PLANT!", ticks in */+} Hud;+extern Hud hud;+void hud_draw(bool cursor);+void hud_cursor_draw(void);+void hud_bank_draw(int x, int y, bool costs);+int bank_width(void);+void packet_draw(int kind, int x, int y, int cooldown, int cooldown_full, bool dim, bool selected, int key);+void draw_ready(int t);+void draw_message_band(const char *s);+void draw_dialog(int x, int y, int w, int h);+void draw_button(int x, int y, int w, const char *label, bool focus);+void draw_money(int x, int y, uint32_t money);+#endifdiff --git a/games/pvz/src/game.h b/games/pvz/src/game.hindex 5362ef5f..89a830be 100644--- a/games/pvz/src/game.h+++ b/games/pvz/src/game.h@@ -208,15 +208,6 @@ typedef struct {int16_t storm_in;uint8_t storm_flash;int16_t fog_blown, pool_frozen;- /* the things on the lawn */- int nplants, nzombies, nshots, nsuns, ncoins, nfx, nrollers;- Plant plants[MAX_PLANTS];- Zombie zombies[MAX_ZOMBIES];- Shot shots[MAX_SHOTS];- Sun suns[MAX_SUNS];- Coin coins[MAX_COINS];- Fx fx[MAX_FX];- Roller rollers[MAX_ROLLERS];Mower mowers[MAX_ROWS];uint8_t ngraves, ncraters, nladders, nvases, ndrops;Cell graves[16];@@ -235,6 +226,16 @@ typedef struct {/* the last zombie's place: where the reward drops */float last_x, last_y;uint8_t has_boss;+ struct { uint8_t on, row, col; int16_t age; } rake; /* on: 1 waiting, 2 a zombie on its way */+ /* the things on the lawn (a level's save keeps what is before them, then them as many as there are) */+ int nplants, nzombies, nshots, nsuns, ncoins, nfx, nrollers;+ Plant plants[MAX_PLANTS];+ Zombie zombies[MAX_ZOMBIES];+ Shot shots[MAX_SHOTS];+ Sun suns[MAX_SUNS];+ Coin coins[MAX_COINS];+ Fx fx[MAX_FX];+ Roller rollers[MAX_ROLLERS];} Board;extern Board B;@@ -278,6 +279,9 @@ bool has_conveyor(void);int waves_flag_every(void);bool is_flag_wave(int wave);void board_drop_reward(void);+void board_set_seeds(const uint8_t *seeds, int n);+void board_next_vase_stage(void);+void whack_graves(int count);/* ---------------------------------------------------------------- zombies.c */Zombie *spawn_zombie(int kind, int row, float x, int wave);@@ -299,6 +303,8 @@ void plant_new(Plant *p, int kind, int col, int row);/* ---------------------------------------------------------------- boss.c */#define BOSS_HEALTH 40000+enum { BS_ENTER, BS_IDLE, BS_SPAWN, BS_STOMP, BS_BUNGEE, BS_BUNGEE_WAIT, BS_BUNGEE_LEAVE, BS_HEAD_ENTER, BS_HEAD_BEFORE,+ BS_SPIT, BS_RV, BS_HEAD_AFTER, BS_HEAD_LEAVE, BS_DEATH };typedef struct {int32_t health;uint8_t phase, clip, mode, row, column, ball_kind;diff --git a/games/pvz/src/gfx.c b/games/pvz/src/gfx.cindex f5005b00..aff7f88b 100644--- a/games/pvz/src/gfx.c+++ b/games/pvz/src/gfx.c@@ -127,6 +127,8 @@ static const uint16_t *palette(int pal, int tint) {/* ---------------------------------------------------------------- the background */+uint32_t gfx_scratch[640 * 16 / 4];+bool gfx_load_back_rows(int b, int src_x, int y0, int y1, int x0, int x1) {Back bk = back_info(b);if (y1 <= y0) y0 = 0, y1 = bk.h;@@ -134,14 +136,14 @@ bool gfx_load_back_rows(int b, int src_x, int y0, int y1, int x0, int x1) {int n;const uint16_t *pal = pal_colors(bk.pal, &n);for (int i = 0; i < n && i < 256; i++) gfx_bg_pal[i] = pal[i];- static uint8_t chunk[640 * 16];+ uint8_t *chunk = (uint8_t *)gfx_scratch;uint8_t tables[3600];- if (np_inflate_tables_size() > sizeof tables || bk.w * bk.rows > (int)sizeof chunk) return false;+ if (np_inflate_tables_size() > sizeof tables || bk.w * bk.rows > (int)sizeof gfx_scratch) return false;for (int c = 0; c < bk.nchunks; c++) {int ry = c * bk.rows;if (ry + bk.rows <= y0 || ry >= y1) continue;uint32_t a = rd32(bk.chunks + 4 * c), e = rd32(bk.chunks + 4 * c + 4);- int got = np_inflate(chunk, sizeof chunk, pvz_bin + a, e - a, (np_inflate_tables_t *)(void *)tables);+ int got = np_inflate(chunk, sizeof gfx_scratch, pvz_bin + a, e - a, (np_inflate_tables_t *)(void *)tables);if (got < bk.w) return false;for (int r = 0; r < bk.rows && ry + r < SCREEN_H; r++) {int y = ry + r;diff --git a/games/pvz/src/gfx.h b/games/pvz/src/gfx.hindex 95a39a63..3f1717e2 100644--- a/games/pvz/src/gfx.h+++ b/games/pvz/src/gfx.h@@ -39,6 +39,8 @@ extern bool gfx_bg_on; /* false: the background is black *//* unpacks background b (BG_*) into gfx_bg, its columns from src_x on; rows y0 to y1 only, if y1 > y0 */bool gfx_load_back(int b, int src_x);bool gfx_load_back_rows(int b, int src_x, int y0, int y1, int x0, int x1);+/* where the backgrounds are unpacked; between two of those, free for a frame's own use */+extern uint32_t gfx_scratch[640 * 16 / 4];/* the band: SCREEN_W * GFX_BAND pixels, the caller's (main's stack on the calculator) */void gfx_set_band_memory(uint16_t *px);diff --git a/games/pvz/src/hud.c b/games/pvz/src/hud.cnew file mode 100644index 00000000..9ce0afca--- /dev/null+++ b/games/pvz/src/hud.c@@ -0,0 +1,239 @@+/* What is drawn over the lawn: the seed bank, the shovel, the progress meter, the cursor and the messages+ * (draw.h). */+#include <string.h>+#include "draw.h"+#include "game.h"+#include "gfx.h"+#include "res.h"+#include "save.h"++Hud hud;++static const uint16_t C_DARK = 0x0000;++/* ---------------------------------------------------------------- seed packets */++void packet_draw(int kind, int x, int y, int cooldown, int full, bool dim, bool selected, int key) {+ gfx_image(I_PACKET, x, y);+ gfx_image(I_PACKET_PEASHOOTER + kind, x + 10, y + 12);+ if (kind < N_SEEDS && plant_defs[kind].cost)+ gfx_text(F_SMALL, x + 10, y + 26, gfx_fmt("%d", plant_defs[kind].cost), C_DARK, GFX_CENTER);+ if (full > 0 && cooldown > 0) {+ int h = 28 * cooldown / full;+ gfx_rect(x, y, 20, h, C_DARK, 14);+ }+ if (dim) gfx_rect(x, y, 20, 28, C_DARK, 12);+ if (selected) gfx_frame_rect(x - 1, y - 1, 22, 30, 1, rgb565(0xFFE14A), 32);+ if (key) gfx_text(F_SMALL, x + 1, y + 6, gfx_fmt("%d", key % 10), C_WHITE, GFX_OUTLINE);+}++int bank_width(void) { return B.nseeds > 6 ? 178 + (B.nseeds - 6) * 21 : 178; }++/* the seed bank: the sun, then the packets */+void hud_bank_draw(int x0, int y0, bool costs) {+ int w = bank_width();+ if (w > 178) {+ /* longer for more slots: its middle stretched */+ gfx_clip(x0, y0, 160, 40);+ gfx_image(I_SEEDBANK, x0, y0);+ for (int x = 160; x < w - 10; x += 10) {+ gfx_clip(x0 + x, y0, 10, 40);+ gfx_image(I_SEEDBANK, x0 + x - 150, y0);+ }+ gfx_clip(x0 + w - 10, y0, 10, 40);+ gfx_image(I_SEEDBANK, x0 + w - 178, y0);+ gfx_clip_all();+ } else+ gfx_image(I_SEEDBANK, x0, y0);+ if (costs) gfx_text(F_SMALL, x0 + 16, y0 + 33, gfx_fmt("%d", (int)B.sun), C_DARK, GFX_CENTER);+}++static void conveyor_draw(void) {+ gfx_image(I_CONVEYOR, 0, 0);+ /* the belt's stripes, moving */+ int off = (int)(B.ticks / 4) % 6;+ for (int x = 6 - off; x < 202; x += 6) gfx_rect(x, 9, 1, 22, rgb565(0x3A3A3A), 32);+ for (int i = 0; i < B.npackets; i++) {+ int x = 6 + (int)(B.packets[i].x * 0.4f);+ if (x > 190) continue;+ packet_draw(B.packets[i].kind, x, 4, 0, 0, false, hud.selected == i, i + 1 <= 10 ? i + 1 : 0);+ }+}++static void meter_draw(void) {+ if (B.mode == MODE_VASE || B.has_boss) return;+ int x = 252, y = 228, w = 63;+ gfx_image(I_METER_EMPTY, x, y);+ int n = B.nwaves ? B.nwaves : 1;+ int fill = w * B.wave / n;+ if (fill > 0) {+ gfx_clip(x + w - fill, y, fill, 12);+ gfx_image(I_METER_FULL, x, y);+ gfx_clip_all();+ }+ int per = waves_flag_every();+ for (int k = 0; per && B.level != 1 && k < n; k++)+ if (k % per == per - 1) {+ int fx = x + w - (k + 1) * w / n;+ gfx_image(I_METER_FLAG, fx + 2, y - (B.wave > k ? 4 : 1));+ }+ gfx_image(I_METER_HEAD, x + w - fill, y + 5);+}++void draw_money(int x, int y, uint32_t money) {+ gfx_image(I_COIN_GOLD, x + 6, y);+ gfx_text(F_HEAD, x + 14, y + 4, gfx_fmt("$%u", (unsigned)money), rgb565(0xFFE14A), GFX_OUTLINE);+}++/* ---------------------------------------------------------------- messages */++void draw_message_band(const char *s) {+ gfx_rect(0, 196, SCREEN_W, 22, C_DARK, 20);+ gfx_paragraph(F_BODY, 160, 206, 300, s, rgb565(0xFFE14A), GFX_OUTLINE);+}++void draw_ready(int t) {+ /* "Ready... Set... PLANT!", a word at a time, each one jumping in */+ const char *w = t < 60 ? "Ready..." : t < 120 ? "Set..." : "PLANT!";+ int k = t < 60 ? t : t < 120 ? t - 60 : t - 120;+ uint16_t c = t < 120 ? rgb565(0xE02020) : rgb565(0xFF2828);+ int dy = k < 8 ? (8 - k) * 3 : 0;+ gfx_text(F_BIG, 160, 128 - dy, w, c, GFX_CENTER | GFX_OUTLINE);+}++static const char *tutorial_hint(void) {+ if (B.level == 1 && B.tutorial == 1) {+ int peas = 0;+ for (int i = 0; i < B.nplants; i++) peas += B.plants[i].kind == P_PEASHOOTER;+ if (hud.selected >= 0) return "Move to the middle row and press OK to plant your seed!";+ if (peas == 0) return "Press 1 to pick up the peashooter's seed packet!";+ if (B.sun < 100) return "Collect the falling sun: move the cursor onto it!";+ if (B.cooldown[0] > 0) return "Nice! Wait for the seed packet to recharge.";+ return "You have enough sun: plant another peashooter!";+ }+ if ((B.level == 2 || B.tutorial == 3) && B.tutorial) {+ if (B.sun < 50) return "Collect sun until you have 50, then plant a sunflower (2).";+ return "Sunflowers are very important! Plant at least three of them.";+ }+ if (B.level == 4 && B.ticks < 900 && B.started) return "Plant wall-nuts (4) in front of your peashooters to protect them.";+ if (B.mode == MODE_BOWLING && B.ticks < 800) return "Pick a wall-nut (1) and roll it from left of the red line: OK.";+ if (B.mode == MODE_CONVEYOR && B.ticks < 500) return "Pick plants from the conveyor belt with 1, 2, 3...";+ if (B.mode == MODE_WHACK && B.ticks < 700) return "Whack the zombies with OK before they get through!";+ if (B.mode == MODE_VASE && B.ticks < 700) return "Break the vases with OK. Pick up the seeds they hold with OK.";+ return NULL;+}++void hud_draw(bool cursor) {+ if (has_conveyor()) conveyor_draw();+ else if (B.mode != MODE_VASE && B.mode != MODE_WHACK) {+ hud_bank_draw(0, 0, true);+ for (int i = 0; i < B.nseeds; i++) {+ int kind = B.seeds[i];+ bool poor = B.sun < plant_cost(kind);+ packet_draw(kind, 34 + i * 21, 3, B.cooldown[i], plant_defs[kind].cooldown, poor || B.cooldown[i] > 0,+ hud.selected == i, i + 1);+ }+ } else if (B.mode == MODE_WHACK) {+ hud_bank_draw(0, 0, true);+ for (int i = 0; i < B.nseeds; i++) {+ int kind = B.seeds[i];+ packet_draw(kind, 34 + i * 21, 3, B.cooldown[i], plant_defs[kind].cooldown,+ B.sun < plant_cost(kind) || B.cooldown[i] > 0, hud.selected == i, i + 1);+ }+ }+ /* the shovel */+ if ((progress.items & ITEM_SHOVEL) && B.mode != MODE_VASE && B.mode != MODE_WHACK) {+ int x = has_conveyor() ? 208 : bank_width() + 2;+ gfx_image(I_SHOVELBANK, x, 3);+ if (!hud.shovel) gfx_image(I_SHOVEL, x + 14, 17);+ }+ meter_draw();+ gfx_text(F_SMALL, 248, 236, gfx_fmt("Level %d-%d", level_world(B.level), level_stage(B.level)), C_WHITE,+ GFX_RIGHT | GFX_OUTLINE);+ if (B.has_boss) {+ /* Dr. Zomboss's health */+ int w = 70 * boss.health / BOSS_HEALTH;+ gfx_rect(244, 228, 72, 8, C_DARK, 24);+ gfx_rect(245, 229, w, 6, rgb565(0xD83A2E), 32);+ }+ if (B.money || B.ncoins || (B.level >= 11 && progress.money)) draw_money(2, 228, progress.money);+ /* sun and coins flying home */+ for (int i = 0; i < B.nfx; i++) {+ const Fx *f = &B.fx[i];+ if (f->kind != FX_SUNFLY && f->kind != FX_COINFLY) continue;+ float t = (float)f->t / f->life, sx = (float)screen_x(f->x), sy = (float)screen_y(f->y);+ float tx = f->kind == FX_SUNFLY ? 16 : 8, ty = f->kind == FX_SUNFLY ? 14 : 228;+ float k = t * t * (3 - 2 * t);+ int x = (int)(sx + (tx - sx) * k), y = (int)(sy + (ty - sy) * k);+ if (f->kind == FX_SUNFLY) gfx_anim(A_SUN, (int)(vis_ticks / 8), x, y, 0, TINT_NONE, 32 - 16 * f->t / f->life);+ else gfx_image(f->v >= 1000 ? I_COIN_DIAMOND : f->v >= 50 ? I_COIN_GOLD : I_COIN_SILVER, x, y);+ }+ if (cursor) hud_cursor_draw();+ /* the big messages */+ for (int i = 0; i < B.nfx; i++) {+ const Fx *f = &B.fx[i];+ if (f->kind != FX_TEXT) continue;+ uint16_t red = rgb565(0xE82020);+ if (f->v == 0) {+ gfx_text(F_BIG, 160, 112, "A Huge Wave of Zombies", red, GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_BIG, 160, 132, "is Approaching!", red, GFX_CENTER | GFX_OUTLINE);+ } else if (f->t < 200) {+ int s = f->t < 20 ? 256 + (20 - f->t) * 20 : 256;+ (void)s;+ gfx_text(F_BIG, 160, 128, "FINAL WAVE", red, GFX_CENTER | GFX_OUTLINE);+ }+ }+ const char *hint = B.phase == PH_PLAY ? tutorial_hint() : NULL;+ if (hint) draw_message_band(hint);+ if (hud.issue && vis_ticks - (uint32_t)hud.issue_t < 150)+ gfx_text(F_BODY, 160, 190, issue_text[hud.issue], C_WHITE, GFX_CENTER | GFX_OUTLINE);+}++/* ---------------------------------------------------------------- the cursor */++void hud_cursor_draw(void) {+ int col = hud.col, row = hud.row;+ float gx = BOARD_LEFT + col * CELL_W, cx = cell_x(col);+ float top = row_y(row, cx) - (B.env == ENV_ROOF ? 58 : is_pool() ? 68 : 78);+ int x = screen_x(gx), y = screen_y(top), w = 32, h = (int)(cell_h() * 0.4f + 0.5f);+ if (B.mode == MODE_WHACK && hud.selected < 0) {+ gfx_anim(I_HAMMER, 0, x + 18, y + 10 + (B.hammer_t > 10 ? 4 : 0), 0, TINT_NONE, 32);+ return;+ }+ int kind = hud.selected >= 0 ? (B.mode == MODE_VASE ? B.drops[hud.selected].kind : seed_kind(hud.selected)) : -1;+ int issue = kind >= 0 ? plant_issue(kind, col, row) : 0;+ if (kind >= 0 && B.mode != MODE_BOWLING) {+ float py = row_y(row, cx);+ if (B.env == ENV_ROOF && kind != P_FLOWERPOT) py -= 12;+ if (!issue) draw_plant_at(kind, screen_x(cx), screen_y(py), 16);+ } else if (kind >= 0) {+ int a = kind == P_EXPLODENUT ? A_EXPLODENUT : A_WALLNUT;+ gfx_anim(a, 0, screen_x(cx), screen_y(row_y(row, cx)), 0, issue ? TINT_GRAY : TINT_NONE, 16);+ }+ uint16_t c = issue ? rgb565(0xFF5040) : hud.shovel ? rgb565(0xFFD36B) : C_WHITE;+ gfx_rect(x + 1, y + 1, w - 2, h - 2, C_WHITE, 4);+ /* its corners */+ int k = 6;+ gfx_rect(x, y, k, 2, c, 32), gfx_rect(x, y, 2, k, c, 32);+ gfx_rect(x + w - k, y, k, 2, c, 32), gfx_rect(x + w - 2, y, 2, k, c, 32);+ gfx_rect(x, y + h - 2, k, 2, c, 32), gfx_rect(x, y + h - k, 2, k, c, 32);+ gfx_rect(x + w - k, y + h - 2, k, 2, c, 32), gfx_rect(x + w - 2, y + h - k, 2, k, c, 32);+ if (hud.shovel) gfx_image(I_SHOVEL, x + w - 4, y + 6);+}++/* ---------------------------------------------------------------- menus' parts */++void draw_dialog(int x, int y, int w, int h) {+ /* a stone tablet, like the game's menus */+ gfx_round_rect(x + 3, y + 4, w, h, 8, C_DARK, 12);+ gfx_round_rect(x, y, w, h, 8, rgb565(0x5A5E78), 32);+ gfx_round_rect(x + 3, y + 3, w - 6, h - 6, 6, rgb565(0x8A8FA8), 32);+ gfx_round_rect(x + 6, y + 6, w - 12, h - 12, 5, rgb565(0x6C7190), 32);+}++void draw_button(int x, int y, int w, const char *label, bool focus) {+ gfx_round_rect(x, y + 2, w, 20, 5, C_DARK, 14);+ gfx_round_rect(x, y, w, 20, 5, focus ? rgb565(0x3F7F2A) : rgb565(0x5A3A1E), 32);+ gfx_round_rect(x + 2, y + 2, w - 4, 16, 4, focus ? rgb565(0x6CBF3A) : rgb565(0x8A5A2E), 32);+ gfx_text(F_HEAD, x + w / 2, y + 14, label, focus ? rgb565(0xFFF5B0) : rgb565(0xF0D8A8), GFX_CENTER | GFX_OUTLINE);+}diff --git a/games/pvz/src/icon.png b/games/pvz/src/icon.pngnew file mode 100644index 00000000..0e5c3de3Binary files /dev/null and b/games/pvz/src/icon.png differdiff --git a/games/pvz/src/main.c b/games/pvz/src/main.cnew file mode 100644index 00000000..3e6bae7e--- /dev/null+++ b/games/pvz/src/main.c@@ -0,0 +1,47 @@+/* Plants vs. Zombies for the NumWorks calculator.+ *+ * Inspired by Plants vs. Zombies by PopCap Games, not affiliated with PopCap Games or Electronic Arts.+ * Made by Mason Chen as part of NumPlay. */+#include "gfx.h"+#include "plat.h"+#include "res.h"+#include "screens.h"++const uint8_t *pvz_bin;++#ifndef HOST+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Plants vs. Zombies";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+extern const uint8_t pvz_data[];++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_updates __attribute__((used));++int main(void) {+ uint16_t band[SCREEN_W * GFX_BAND]; /* (here: on the stack, out of the RAM apps get) */+ gfx_set_band_memory(band);+ plat_begin();+ pvz_bin = pvz_data;+ game_init();+ uint32_t next = plat_millis();+ /* the game's ticks are hundredths of a second; drawn when caught up, at most 8 ticks a drawing */+ while (g_running) {+ int n = 0;+ uint32_t now = plat_millis();+ while ((int32_t)(now - next) >= 0 && n < 8 && g_running) {+ game_frame(plat_keys());+ perf_updates++;+ next += 10;+ n++;+ }+ if (!g_running) break;+ if ((int32_t)(now - next) > 200) next = now; /* far behind: slower, rather than rushing */+ if (n) {+ game_draw();+ perf_frames++;+ } else+ plat_sleep(1);+ }+ return plat_end();+}+#endifdiff --git a/games/pvz/src/plants.c b/games/pvz/src/plants.cnew file mode 100644index 00000000..2a919b6c--- /dev/null+++ b/games/pvz/src/plants.c@@ -0,0 +1,645 @@+/* The plants: what each one does, and what they shoot (game.h). */+#include <string.h>+#include "game.h"++/* ---------------------------------------------------------------- shooting */++static Shot *new_shot(int kind, int row, float x, float y) {+ if (B.nshots >= MAX_SHOTS) return NULL;+ Shot *s = &B.shots[B.nshots++];+ memset(s, 0, sizeof *s);+ s->id = new_id(), s->kind = (uint8_t)kind, s->row = (uint8_t)row, s->x = x, s->y = y, s->vx = 3.33f;+ s->torch = 0xFF;+ return s;+}++static bool targetable(const Zombie *z) {+ return !(z->flags & ZF_HYPNO) && z->health > 0 && z->rise == 0;+}++static void fire_pea(Plant *p, int row, bool force) {+ float x = cell_x(p->col);+ float range = p->kind == P_PUFFSHROOM || p->kind == P_SEASHROOM ? 250 : p->kind == P_FUMESHROOM ? 360 : 825 - x;+ if (p->kind == P_CACTUS) {+ bool air = false;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ air |= targetable(z) && (z->flags & ZF_FLYING) && z->row == row && z->x > x - 10 && z->x < 825;+ }+ if (air) p->flags |= PF_TALL;+ else p->flags &= (uint8_t)~PF_TALL;+ }+ bool tall = (p->flags & PF_TALL) != 0, any = false;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (!targetable(z) || zombie_flying(z) != tall || (z->flags & ZF_UNDERGROUND) || z->emerge > 0) continue;+ if (zombie_submerged(z) && !(z->kind == Z_SNORKEL && p->kind == P_FUMESHROOM)) continue;+ if (z->row != row || z->x <= x - 10 || z->x >= x + range) continue;+ any = true;+ if (p->kind == P_FUMESHROOM && z->vault <= 0) {+ damage_zombie(z, 20, true);+ z->hit_at = B.ticks;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ }+ }+ if (!any && !force) return;+ p->shot = B.ticks;+ if (p->kind == P_FUMESHROOM) {+ fx_add(FX_SMOKE, x + 25, row_y(row, x) - 45, 32, 3);+ return;+ }+ int kind = p->kind == P_SNOWPEA ? S_ICE : p->kind == P_PUFFSHROOM || p->kind == P_SCAREDYSHROOM || p->kind == P_SEASHROOM+ ? S_PUFF : p->kind == P_CACTUS ? S_SPIKE : S_PEA;+ Shot *s = new_shot(kind, row, x + 27, row_y(p->row, x) - 43);+ if (!s) return;+ if (tall) s->flags |= SF_HIGH;+ if (p->kind == P_SCAREDYSHROOM) s->flags |= SF_LONG;+ if (B.env == ENV_ROOF) s->flags |= SF_ROOFCHECK;+}++static void fire_rear(Plant *p) {+ float x = cell_x(p->col);+ bool any = false;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ any |= targetable(z) && !zombie_flying(z) && !zombie_submerged(z) && z->row == p->row && z->x < x;+ }+ if (!any) return;+ Shot *s = new_shot(S_PEA, p->row, x - 25, row_y(p->row, x) - 43);+ if (s) s->vx = -3.33f;+ if (s && B.env == ENV_ROOF) s->flags |= SF_ROOFCHECK;+ p->shot = B.ticks;+}++static void fire_stars(Plant *p) {+ bool any = false;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ any |= targetable(z) && !zombie_flying(z) && !zombie_submerged(z) && z->x < 825;+ }+ if (!any) return;+ static const float v[5][2] = {{-3.33f, 0}, {0, -3.33f}, {0, 3.33f}, {2.35f, -2.35f}, {2.35f, 2.35f}};+ float x = cell_x(p->col);+ for (int k = 0; k < 5; k++) {+ Shot *s = new_shot(S_STAR, p->row, x, row_y(p->row, x) - 35);+ if (s) s->vx = v[k][0], s->vy = v[k][1];+ }+ p->shot = B.ticks;+}++/* cabbage, kernel (or butter), melon: lobbed at the first zombie, where it will be when it lands */+static void fire_lob(Plant *p) {+ float x = cell_x(p->col);+ Zombie *t = NULL;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (!targetable(z) || zombie_flying(z) || (z->kind == Z_IMP && z->u.flight.left > 0) || z->landing > 0 ||+ (z->flags & ZF_UNDERGROUND) || z->emerge > 0 || (z->kind == Z_BUNGEE && z->phase != BP_WAIT))+ continue;+ if (z->row != p->row || z->x <= x - 10 || z->x >= 825) continue;+ if (!t || z->x < t->x) t = z;+ }+ bool at_boss = !t && B.has_boss && boss_vulnerable();+ if (!t && !at_boss) return;+ int kind = p->kind == P_MELONPULT ? S_MELON : p->kind == P_CABBAGEPULT ? S_CABBAGE : frand() < 0.25f ? S_BUTTER : S_KERNEL;+ float ex = 740;+ if (t) {+ bool still = (t->flags & ZF_EATING) || t->kind == Z_BUNGEE || (t->kind == Z_GARGANTUAR && t->phase != GP_WALK) ||+ (t->kind == Z_CATAPULT && t->phase != CP_WALK);+ ex = t->x - (still ? 0 : walking_speed(t) * 100);+ }+ Shot *s = new_shot(kind, p->row, x, row_y(p->row, x) - 60);+ if (!s) return;+ s->target = t ? t->id : 0, s->sx = x, s->ex = ex, s->sy = row_y(p->row, x) - 60, s->ey = row_y(p->row, ex) - 55;+ s->duration = 100;+ p->shot = B.ticks;+}++/* ---------------------------------------------------------------- the plants' own ways */++static void explode(float x, float y, int row, float range_x, int rows, bool through) {+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if ((z->flags & ZF_HYPNO) || z->health <= 0) continue;+ int dr = z->row - row;+ if (dr < -rows || dr > rows || z->x - x > range_x || x - z->x > range_x) continue;+ damage_zombie(z, 1800, through);+ if (z->health <= 0) kill_zombie(z, DIE_BURN);+ }+ (void)y;+}++static void remove_ladders(int col, int row, int dc, int dr) {+ for (int i = 0; i < B.nladders; i++) {+ int c = B.ladders[i].col - col, r = B.ladders[i].row - row;+ if (c >= -dc && c <= dc && r >= -dr && r <= dr) B.ladders[i--] = B.ladders[--B.nladders];+ }+}++static void update_kelp(Plant *p) {+ if (!p->state) {+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (!targetable(z) || zombie_flying(z) || z->vault > 0 || zombie_headless(z) || z->row != p->row) continue;+ if (z->x <= 90 || z->x >= 780 || z->x - cell_x(p->col) >= 60 || cell_x(p->col) - z->x >= 60) continue;+ bool held = false;+ for (int k = 0; k < B.nplants; k++)+ held |= B.plants[k].kind == P_TANGLEKELP && B.plants[k].state && B.plants[k].target == z->id;+ if (held) continue;+ p->state = 1, p->target = z->id, p->aux = 100;+ return;+ }+ } else if (--p->aux <= 0 || p->health <= 0) {+ Zombie *z = zombie_by_id(p->target);+ if (z) kill_zombie(z, DIE_GONE), fx_add(FX_SPLASH, z->x, row_y(z->row, z->x), 50, 1);+ p->health = 0;+ }+}++static void update_squash(Plant *p) {+ float x = cell_x(p->col);+ if (!p->state) {+ Zombie *best = NULL;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (!targetable(z) || zombie_flying(z) || (z->kind == Z_IMP && z->u.flight.left > 0) || z->landing > 0 ||+ zombie_headless(z) || z->row != p->row || z->vault > 0)+ continue;+ float d = z->x - x;+ d = d < 0 ? -d : d;+ if (d < 100 && (!best || d < (best->x - x < 0 ? x - best->x : best->x - x))) best = z;+ }+ if (best) p->state = 1, p->aux = 185, p->tx = best->x, p->target = best->id, p->shot = B.ticks;+ return;+ }+ p->aux--;+ if (p->aux == 60) {+ Zombie *z = zombie_by_id(p->target);+ if (z) p->tx = z->x - 30 * walking_speed(z);+ }+ if (p->aux <= 0) {+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if ((z->flags & ZF_HYPNO) || zombie_flying(z) || (z->kind == Z_IMP && z->u.flight.left > 0) || z->landing > 0 ||+ z->row != p->row || z->vault > 0 || z->health <= 0)+ continue;+ if (z->x - p->tx < 65 && p->tx - z->x < 65) {+ damage_zombie(z, 1800, true);+ if (z->health <= 0) kill_zombie(z, DIE_SQUASH);+ }+ }+ p->health = 0, p->state = 0xEE;+ fx_add(FX_SMOKE, p->tx, row_y(p->row, p->tx), 30, 0);+ }+}++static void update_chomper(Plant *p) {+ float x = cell_x(p->col);+ Zombie *t = NULL;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (!targetable(z) || zombie_flying(z) || (z->kind == Z_IMP && z->u.flight.left > 0) || z->landing > 0 ||+ (z->flags & ZF_UNDERGROUND) || (z->kind == Z_BUNGEE && z->phase != BP_WAIT) || z->row != p->row)+ continue;+ float d = z->x - x;+ if (d >= -10 && d <= 100 && (!t || z->x < t->x)) t = z;+ }+ if (p->state == CH_READY) {+ if (t) p->state = CH_BITE, p->aux = 70, p->shot = B.ticks;+ return;+ }+ if (--p->aux > 0) return;+ if (p->state == CH_BITE) {+ if (t && (t->kind == Z_ZOMBONI || t->kind == Z_CATAPULT || t->kind == Z_GARGANTUAR)) {+ damage_zombie(t, 40, true);+ if (t->health <= 0) kill_zombie(t, DIE_NORMAL);+ p->state = CH_RECOVER, p->aux = 30;+ } else if (t && !(t->flags & ZF_POLE) && t->vault <= 0) {+ kill_zombie(t, DIE_GONE);+ p->state = CH_DIGEST, p->aux = 4000;+ } else+ p->state = CH_RECOVER, p->aux = 30;+ } else+ p->state = CH_READY;+}++static void update_magnet(Plant *p) {+ if (p->action > 0) {+ p->action--;+ return;+ }+ float x = cell_x(p->col);+ Zombie *best = NULL;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if ((z->flags & ZF_HYPNO) || zombie_headless(z) || z->health <= 0) continue;+ int dr = z->row - p->row;+ if (dr < -2 || dr > 2) continue;+ float dx = z->x - x, dy = dr * cell_h();+ float reach = z->flags & ZF_EATING ? 320 : 270;+ if (dx * dx + dy * dy >= reach * reach) continue;+ bool metal = ((z->kind == Z_BUCKET || z->kind == Z_FOOTBALL) && z->armor > 0) ||+ ((z->kind == Z_DOOR || z->kind == Z_LADDER) && z->shield > 0) || (z->flags & ZF_POGO) ||+ (z->kind == Z_DIGGER && !(z->flags & ZF_METAL_GONE)) ||+ (z->kind == Z_JACK && !(z->flags & (ZF_METAL_GONE | ZF_OPENING)));+ if (!metal) continue;+ if (!best || (dx < 0 ? -dx : dx) < (best->x - x < 0 ? x - best->x : best->x - x)) best = z;+ }+ if (best) {+ Zombie *z = best;+ if (z->kind == Z_BUCKET || z->kind == Z_FOOTBALL) z->armor = 0;+ else if (z->kind == Z_DOOR || z->kind == Z_LADDER) z->shield = 0, z->ladder_in = 0, z->speed = 0.3f;+ else if (z->kind == Z_POGO) z->flags &= (uint16_t)~ZF_POGO, z->speed = 0.3f;+ else if (z->kind == Z_DIGGER && (z->flags & ZF_UNDERGROUND)) {+ z->flags &= (uint16_t)~(ZF_UNDERGROUND | ZF_BACKWARDS), z->emerge = 330, z->speed = 0.3f;+ }+ z->flags |= ZF_METAL_GONE;+ p->action = 1500, p->shot = B.ticks, p->aux = (int16_t)z->kind;+ return;+ }+ for (int i = 0; i < B.nladders; i++) {+ int dr = B.ladders[i].row - p->row;+ float dx = (B.ladders[i].col - p->col) * 80.0f, dy = dr * cell_h();+ if (dr >= -2 && dr <= 2 && dx * dx + dy * dy < 270 * 270) {+ B.ladders[i] = B.ladders[--B.nladders];+ p->action = 1500, p->shot = B.ticks, p->aux = Z_LADDER;+ return;+ }+ }+}++static bool scared(const Plant *p) {+ float x = cell_x(p->col);+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if ((z->flags & ZF_HYPNO) || z->health <= 0 || zombie_headless(z)) continue;+ int dr = z->row - p->row;+ if (dr < -1 || dr > 1) continue;+ float dx = z->x - x;+ dx = dx < 0 ? -dx : dx;+ dx = dx > 20 ? dx - 20 : 0;+ float dy = (dr < 0 ? -dr : dr) * cell_h() - 50;+ dy = dy > 0 ? dy : 0;+ if (dx * dx + dy * dy <= 120 * 120) return true;+ }+ return false;+}++void plants_tick(void) {+ int n = B.nplants;+ for (int i = 0; i < n; i++) {+ Plant *p = &B.plants[i];+ if (p->kind == P_MARIGOLD && B.wave == B.nwaves && p->tx == 0) p->tx = (float)(B.ticks + 6000);+ if (p->kind == P_TANGLEKELP) {+ update_kelp(p);+ continue;+ }+ if (p->health <= 0 || sleeping(p)) continue;+ switch (p->kind) {+ case P_WALLNUT: case P_TALLNUT: case P_TORCHWOOD: case P_HYPNOSHROOM: case P_LILYPAD: case P_FLOWERPOT:+ case P_PUMPKIN: case P_GARLIC: case P_PLANTERN: case P_UMBRELLA:+ continue;+ }+ if (p->kind == P_SUNSHROOM && B.ticks - p->born >= 12000) p->flags |= PF_GROWN;+ if (p->kind == P_MAGNETSHROOM) {+ update_magnet(p);+ continue;+ }+ if (p->kind == P_COFFEEBEAN) {+ if (--p->action <= 0) {+ for (int k = 0; k < B.nplants; k++) {+ Plant *m = &B.plants[k];+ if (m->col == p->col && m->row == p->row && sleeping(m)) m->flags |= PF_AWAKE;+ }+ p->health = 0, p->state = 0xEE;+ }+ continue;+ }+ if (p->kind == P_SPLITPEA && p->aux > 0 && --p->aux == 0) fire_rear(p);+ if (p->kind == P_SPIKEWEED) {+ if (--p->action <= 0) {+ bool hit = false;+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || zombie_flying(z) || (z->flags & ZF_UNDERGROUND) || z->health <= 0 ||+ z->row != p->row || z->vault > 0 || z->x - cell_x(p->col) >= 45 || cell_x(p->col) - z->x >= 45)+ continue;+ damage_zombie(z, 20, true);+ z->hit_at = B.ticks;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ hit = true;+ }+ if (hit) p->shot = B.ticks, p->action = 100;+ }+ continue;+ }+ if (p->kind == P_SQUASH) {+ update_squash(p);+ continue;+ }+ if (p->kind == P_SCAREDYSHROOM) {+ if (scared(p)) {+ p->flags |= PF_SCARED, p->action = 150;+ continue;+ }+ p->flags &= (uint8_t)~PF_SCARED;+ }+ if (p->kind == P_SUNSHROOM && B.ticks - p->born >= 12000 && B.ticks - p->born < 12092) continue;+ if (p->kind == P_GRAVEBUSTER) {+ if (--p->action <= 0) {+ for (int k = 0; k < B.ngraves; k++)+ if (B.graves[k].row == p->row && B.graves[k].col == p->col) B.graves[k--] = B.graves[--B.ngraves];+ p->health = 0, p->state = 0xEE;+ fx_add(FX_SMOKE, cell_x(p->col), row_y(p->row, cell_x(p->col)) - 20, 30, 0);+ }+ continue;+ }+ if (p->kind == P_CHOMPER) {+ update_chomper(p);+ continue;+ }+ if (p->kind == P_POTATOMINE) {+ if (p->action > 0) {+ p->action--;+ if (p->action == 0) fx_add(FX_DIRT, cell_x(p->col), row_y(p->row, cell_x(p->col)), 30, 0);+ continue;+ }+ float x = cell_x(p->col);+ bool near = false;+ for (int k = 0; k < B.nzombies; k++) {+ const Zombie *z = &B.zombies[k];+ near |= !(z->flags & ZF_HYPNO) && !zombie_flying(z) && z->health > 0 && z->vault <= 0 && z->rise == 0 &&+ z->row == p->row && z->x - x < 35 && x - z->x < 35;+ }+ if (near) {+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || zombie_flying(z) || z->vault > 0 || z->rise > 0 || z->row != p->row) continue;+ if (z->x - x <= 60 && x - z->x <= 60) {+ damage_zombie(z, 1800, true);+ if (z->health <= 0) kill_zombie(z, DIE_BURN);+ }+ }+ p->health = 0, p->state = 0xEE;+ fx_add(FX_BOOM, x, row_y(p->row, x) - 20, 60, 1); /* spudow! */+ }+ continue;+ }+ p->action--;+ if (p->kind == P_REPEATER && p->action == 25) fire_pea(p, p->row, false);+ if (p->action > 0) continue;+ float x = cell_x(p->col), y = row_y(p->row, x);+ switch (p->kind) {+ case P_BLOVER:+ if (B.ticks - p->born <= 50) {+ for (int k = 0; k < B.nzombies; k++)+ if (B.zombies[k].flags & ZF_FLYING) B.zombies[k].blown = 100;+ B.fog_blown = 4000, p->action = 100, p->shot = B.ticks;+ } else+ p->health = 0, p->state = 0xEE;+ break;+ case P_JALAPENO:+ if (B.has_boss) {+ boss_damage(1800);+ boss.frozen = 0, boss.chill = 0;+ if (boss.ball.on && boss.ball.kind == 1 && boss.ball.row == p->row) boss.ball.on = 0;+ }+ remove_ladders(0, p->row, 99, 0);+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || z->row != p->row) continue;+ damage_zombie(z, 1800, true);+ z->chill = 0, z->frozen = 0;+ if (z->health <= 0) kill_zombie(z, DIE_BURN);+ }+ if (B.ice[p->row].left > 20) B.ice[p->row].left = 20;+ p->health = 0, p->state = 0xEE;+ fx_add(FX_FIRE, 0, y, 100, p->row);+ break;+ case P_ICESHROOM:+ if (B.has_boss) {+ if (boss.ball.on && boss.ball.kind == 0) boss.ball.on = 0;+ if (boss_vulnerable()) {+ boss_damage(20);+ boss.frozen = (int16_t)(boss.chill > 0 ? 300 + irand(101) : 400 + irand(201));+ boss.chill = 2000;+ }+ }+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || z->health <= 0 || z->kind == Z_ZOMBONI || z->kind == Z_CATAPULT ||+ (z->kind == Z_BOBSLED && z->u.sled.sled))+ continue;+ bool cold = z->chill > 0 || z->frozen > 0;+ z->frozen = (int16_t)(water_row(z->row) ? 300 : cold ? 300 + irand(101) : 400 + irand(201));+ z->chill = 2000;+ damage_zombie(z, 20, true);+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ }+ B.pool_frozen = 300, p->health = 0, p->state = 0xEE;+ fx_add(FX_FREEZE, 400, 300, 60, 0);+ break;+ case P_DOOMSHROOM:+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || z->health <= 0) continue;+ int dr = z->row - p->row;+ float dx = z->x - x, dy = row_y(z->row, z->x) - y;+ if (dr >= -3 && dr <= 3 && dx * dx + dy * dy <= 250 * 250) {+ damage_zombie(z, 1800, true);+ if (z->health <= 0) kill_zombie(z, DIE_BURN);+ }+ }+ for (int k = 0; k < B.nplants; k++)+ if (B.plants[k].col == p->col && B.plants[k].row == p->row) B.plants[k].health = 0, B.plants[k].state = 0xEE;+ if (B.ncraters < 16)+ B.craters[B.ncraters].row = p->row, B.craters[B.ncraters].col = p->col, B.craters[B.ncraters++].left = 18000;+ fx_add(FX_DOOM, x, y - 35, 120, 0);+ break;+ case P_SPLITPEA:+ fire_pea(p, p->row, false);+ fire_rear(p);+ p->aux = 25, p->action = (int16_t)(150 - irand(15));+ break;+ case P_STARFRUIT:+ fire_stars(p);+ p->action = (int16_t)(150 - irand(15));+ break;+ case P_CABBAGEPULT: case P_KERNELPULT: case P_MELONPULT:+ fire_lob(p);+ p->action = (int16_t)(300 - irand(15));+ break;+ case P_THREEPEATER: {+ bool any = false;+ for (int k = 0; k < B.nzombies; k++) {+ const Zombie *z = &B.zombies[k];+ int dr = z->row - p->row;+ any |= targetable(z) && !zombie_flying(z) && !zombie_submerged(z) && dr >= -1 && dr <= 1 && z->x > x && z->x < 825;+ }+ if (any)+ for (int r = p->row - 1; r <= p->row + 1; r++)+ if (r >= 0 && r < B.nrows && (B.rows >> r & 1)) fire_pea(p, r, true);+ p->shot = B.ticks, p->action = (int16_t)(150 - irand(15));+ break;+ }+ case P_MARIGOLD:+ if (p->tx != 0 && B.ticks >= (uint32_t)p->tx) break;+ add_coin(x + 12, y - 10, frand() < 0.1f ? 50 : 10);+ p->action = (int16_t)(2500 - 150 + irand(151)), p->shot = B.ticks;+ break;+ case P_CHERRYBOMB:+ remove_ladders(p->col, p->row, 1, 1);+ explode(x, y, p->row, 115, 1, true);+ p->health = 0, p->state = 0xEE;+ fx_add(FX_BOOM, x, y - 35, 60, 0);+ break;+ case P_SUNFLOWER: case P_SUNSHROOM:+ add_sun(x + 12, y - 55, y - 15, p->kind == P_SUNSHROOM && !(p->flags & PF_GROWN) ? 15 : 25, false);+ p->action = (int16_t)(2500 - 150 + irand(151)), p->shot = B.ticks;+ break;+ default:+ p->action = (int16_t)(150 - irand(15));+ fire_pea(p, p->row, false);+ }+ }+}++/* ---------------------------------------------------------------- the shots */++static void hit_fx(float x, float y, int kind) { fx_add(FX_SPLAT, x, y, 18, kind); }++void shots_tick(void) {+ for (int i = 0; i < B.nshots; i++) {+ Shot *s = &B.shots[i];+ s->age++;+ bool gone = false;+ if (s->kind >= S_CABBAGE) {+ /* lobbed: a parabola to where its zombie will be */+ float t = (float)s->age / s->duration;+ s->x = s->sx + (s->ex - s->sx) * t;+ float arc = t * (1 - t) * 4;+ s->y = s->sy + (s->ey - s->sy) * t - arc * 150;+ if (t >= 1) {+ gone = true;+ if (s->kind == S_BASKETBALL) {+ for (int k = 0; k < B.nplants; k++) {+ Plant *p = &B.plants[k];+ if (p->id != s->target || p->health <= 0) continue;+ Plant *u = NULL;+ for (int j = 0; j < B.nplants; j++) {+ Plant *q = &B.plants[j];+ if (q->kind == P_UMBRELLA && q->health > 0 && q->col - p->col <= 1 && p->col - q->col <= 1 &&+ q->row - p->row <= 1 && p->row - q->row <= 1)+ u = q;+ }+ if (u) u->shot = B.ticks;+ else p->health = (int16_t)(p->health - 75), p->shot = B.ticks;+ }+ } else if (!s->target && B.has_boss) {+ boss_damage(s->kind == S_MELON ? 80 : s->kind == S_KERNEL ? 20 : 40);+ hit_fx(s->x, s->y, s->kind);+ } else {+ Zombie *t = zombie_by_id(s->target);+ if (t && t->health > 0 && !(t->flags & ZF_UNDERGROUND) && (t->kind != Z_BUNGEE || t->phase == BP_WAIT) &&+ t->x - s->ex < 65 && s->ex - t->x < 65) {+ if (s->kind == S_MELON) {+ int near = 0;+ for (int k = 0; k < B.nzombies; k++) {+ const Zombie *z = &B.zombies[k];+ int dr = z->row - t->row;+ near += z != t && !(z->flags & ZF_HYPNO) && !zombie_flying(z) && !zombie_submerged(z) && z->health > 0 &&+ dr >= -1 && dr <= 1 && z->x - t->x <= 80 && t->x - z->x <= 80;+ }+ int splash = near * 26 > 560 ? (80 * 560 / (near * 26 * 3) > 1 ? 80 * 560 / (near * 26 * 3) : 1) : 26;+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ int dr = z->row - t->row;+ bool hit = z == t || (!(z->flags & ZF_HYPNO) && !zombie_flying(z) && !zombie_submerged(z) && z->health > 0 &&+ dr >= -1 && dr <= 1 && z->x - t->x <= 80 && t->x - z->x <= 80);+ if (!hit) continue;+ int dmg = z == t ? 80 : splash;+ if (z->shield > 0) damage_zombie(z, z->shield < dmg ? z->shield : dmg, false);+ damage_zombie(z, dmg, true);+ z->hit_at = B.ticks;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ }+ } else {+ damage_zombie(t, s->kind == S_KERNEL ? 20 : 40, true);+ t->hit_at = B.ticks;+ if (s->kind == S_BUTTER && t->kind != Z_CATAPULT && t->kind != Z_ZOMBONI) t->butter = 400;+ if (t->health <= 0) kill_zombie(t, DIE_NORMAL);+ }+ hit_fx(s->x, s->y, s->kind);+ }+ }+ }+ } else if (s->kind == S_STAR) {+ s->x += s->vx, s->y += s->vy;+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || zombie_flying(z) || zombie_submerged(z) || z->health <= 0) continue;+ float dy = row_y(z->row, z->x) - 43 - s->y;+ if (z->x - s->x < 22 && s->x - z->x < 22 && dy < 32 && dy > -32) {+ damage_zombie(z, 20, false);+ z->hit_at = B.ticks;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ hit_fx(s->x, s->y, S_STAR);+ gone = true;+ break;+ }+ }+ if (s->y < -80 || s->y > 650) gone = true;+ } else {+ float old = s->x;+ s->x += s->vx;+ if ((s->flags & SF_ROOFCHECK) && s->y > row_y(s->row, s->x) - 20) gone = true;+ if (s->kind == S_PEA || s->kind == S_ICE) {+ for (int k = 0; k < B.nplants; k++) {+ const Plant *p = &B.plants[k];+ if (p->kind != P_TORCHWOOD || p->row != s->row || p->col == s->torch || p->health <= 0) continue;+ float cx = cell_x(p->col);+ if ((s->vx > 0 && old <= cx + 10 && s->x >= cx - 10) || (s->vx < 0 && old >= cx - 10 && s->x <= cx + 10)) {+ s->torch = p->col;+ s->kind = s->kind == S_ICE ? S_PEA : S_FIRE;+ }+ }+ }+ if (s->kind == S_PUFF && !(s->flags & SF_LONG) && s->age >= 75) gone = true;+ Zombie *t = NULL;+ float lo = old < s->x ? old : s->x, hi = old < s->x ? s->x : old;+ for (int k = 0; k < B.nzombies && !gone; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || !(s->flags & SF_HIGH) != !zombie_flying(z) || zombie_submerged(z) || z->health <= 0 ||+ z->row != s->row || z->vault > 0 || z->rise > 0)+ continue;+ if (lo <= z->x + 18 && hi >= z->x - 18 && (!t || (s->vx > 0 ? z->x < t->x : z->x > t->x))) t = z;+ }+ if (t) {+ bool body = t->shield < 20;+ if ((s->flags & SF_HIGH) && (t->flags & ZF_FLYING)) {+ t->flags &= (uint16_t)~ZF_FLYING, t->pop = 50;+ } else if (s->kind == S_FIRE) {+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || zombie_flying(z) || zombie_submerged(z) || z->health <= 0 || z->row != s->row) continue;+ if (z->x - t->x <= 50 && t->x - z->x <= 50) {+ damage_zombie(z, 40, false);+ z->chill = 0, z->frozen = 0;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ }+ }+ } else {+ damage_zombie(t, 20, false);+ if (t->health <= 0) kill_zombie(t, DIE_NORMAL);+ }+ if (s->kind == S_ICE && body && t->kind != Z_ZOMBONI && t->kind != Z_CATAPULT && !(t->kind == Z_BOBSLED && t->u.sled.sled))+ t->chill = 1000;+ t->hit_at = B.ticks;+ hit_fx(s->x, s->y, s->kind);+ gone = true;+ }+ if (s->x > 850 || s->x < -60) gone = true;+ }+ if (gone) B.shots[i--] = B.shots[--B.nshots];+ }+}diff --git a/games/pvz/src/res.h b/games/pvz/src/res.hindex 5274a43d..a48a8687 100644--- a/games/pvz/src/res.h+++ b/games/pvz/src/res.h@@ -14,7 +14,7 @@ static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] <<static inline int16_t rds16(const uint8_t *p) { return (int16_t)rd16(p); }static inline uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }static inline const uint8_t *table(int t) { return pvz_bin + rd32(pvz_bin + 4 + 4 * t); }-enum { T_ANIMS, T_FRAMES, T_PALS, T_BACKS, T_FONTS };+enum { T_ANIMS, T_FRAMES, T_PALS, T_BACKS, T_FONTS, T_BOSS };typedef struct {uint16_t first, pal, cycle, base; /* base: the animation an overlay is drawn over, 0xFFFF none */diff --git a/games/pvz/src/save.c b/games/pvz/src/save.cnew file mode 100644index 00000000..e77478c1--- /dev/null+++ b/games/pvz/src/save.c@@ -0,0 +1,209 @@+/* Saves (save.h). The copy in pvz_saves.py is a comment line "#>name:base64" for each file (the way NumPlay and+ * its big games keep theirs). */+#include <stddef.h>+#include <string.h>+#include "game.h"+#include "plat.h"+#include "save.h"++#define SAVE_NAME "pvz.sav"+#define LEVEL_NAME "pvzlevel.sav"+#define COPY_NAME "pvz_saves.py"+#define MAGIC 0x315A5650u /* "PVZ1" */+#define LEVEL_MAGIC 0x4C5A5650u /* "PVZL" */++Progress progress;++static const char *const kept[] = {SAVE_NAME, LEVEL_NAME};+#define NKEPT (int)(sizeof kept / sizeof kept[0])+static const char copy_head[] =+ "# Plants vs. Zombies keeps a copy of your progress here, so\n"+ "# that reinstalling it doesn't erase it. If you delete this\n"+ "# file, the game writes it again: your progress stays.\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++static void copy_write(void) {+ uint32_t total = 1 + (sizeof copy_head - 1) + 1, len;+ int n = 0;+ for (int k = 0; k < NKEPT; k++)+ if (plat_load(kept[k], &len) && len) total += 2 + (uint32_t)strlen(kept[k]) + 1 + (len + 2) / 3 * 4 + 1, n++;+ plat_remove(COPY_NAME);+ if (!n) return;+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;+ if (!o) return;+ *p++ = 0; /* (the script's status byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ for (int k = 0; k < NKEPT; k++) {+ const uint8_t *d = plat_load(kept[k], &len);+ if (!d || !len) continue;+ uint32_t nl = (uint32_t)strlen(kept[k]);+ *p++ = '#', *p++ = '>';+ memcpy(p, kept[k], nl), p += nl;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's+ * launcher/src/storage.c) */+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63];+ p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ }+ *p++ = 0;+ plat_reserved(COPY_NAME, (uint32_t)(p - o));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++static const uint8_t *copy_line(int k, uint32_t *len) {+ uint32_t n, nl = (uint32_t)strlen(kept[k]);+ const uint8_t *c = plat_load(COPY_NAME, &n);+ if (!c) return NULL;+ for (uint32_t i = 0; i + nl + 3 <= n; i++)+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, kept[k], nl) && c[i + 2 + nl] == ':') {+ const uint8_t *l = c + i + 3 + nl;+ uint32_t m = 0;+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;+ *len = m;+ return l;+ }+ return NULL;+}++void save_restore_copy(void) {+ for (int k = 0; k < NKEPT; k++) {+ uint32_t have, len;+ if (plat_load(kept[k], &have)) continue;+ const uint8_t *l = copy_line(k, &len);+ if (!l || !len || len % 4) continue;+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');+ uint8_t *out = plat_reserve(kept[k], size);+ if (!out) continue;+ l = copy_line(k, &len);+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;+ uint32_t o = 0;+ for (uint32_t i = 0; ok && i < len; i += 4) {+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;+ uint32_t wd = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);+ if (o < size) out[o++] = (uint8_t)(wd >> 16);+ if (o < size) out[o++] = (uint8_t)(wd >> 8);+ if (o < size) out[o++] = (uint8_t)wd;+ }+ if (ok && o == size) plat_reserved(kept[k], size);+ else plat_remove(kept[k]);+ }+}++/* ---------------------------------------------------------------- the progress */++void progress_load(void) {+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ memset(&progress, 0, sizeof progress);+ progress.level = 1, progress.slots = 6;+ if (d && len == 4 + sizeof progress) {+ uint32_t m;+ memcpy(&m, d, 4);+ if (m == MAGIC) memcpy(&progress, d + 4, sizeof progress);+ }+ if (progress.level < 1 || progress.level > N_LEVELS) progress.level = 1;+ if (progress.slots < 6 || progress.slots > 10) progress.slots = 6;+ if (progress.nlast > 10) progress.nlast = 0;+}++bool progress_save(void) {+ uint8_t buf[4 + sizeof progress];+ uint32_t m = MAGIC;+ memcpy(buf, &m, 4);+ memcpy(buf + 4, &progress, sizeof progress);+ bool ok = plat_save(SAVE_NAME, buf, sizeof buf);+ copy_write();+ return ok;+}++bool plant_unlocked(int kind) {+ if (progress.finished || kind == P_PEASHOOTER) return true;+ for (int l = 1; l < progress.level && l <= N_LEVELS; l++)+ if (level_defs[l - 1].reward == kind) return true;+ return false;+}+int level_world(int level) { return (level - 1) / 10 + 1; }+int level_stage(int level) { return (level - 1) % 10 + 1; }++/* ---------------------------------------------------------------- the level in progress */++/* the board before its arrays, then each array as long as it is: what is in flight (shots, effects) is left */+#define HEAD offsetof(Board, nplants)+bool board_save(void) {+ uint32_t n = 8 + HEAD + 7 * 4 + B.nplants * sizeof(Plant) + B.nzombies * sizeof(Zombie) + B.nsuns * sizeof(Sun) ++ B.ncoins * sizeof(Coin) + B.nrollers * sizeof(Roller) + (B.has_boss ? sizeof boss : 0);+ uint8_t *o = plat_reserve(LEVEL_NAME, n), *p = o;+ if (!o) {+ plat_remove(LEVEL_NAME);+ copy_write();+ return false;+ }+ uint32_t m = LEVEL_MAGIC;+ memcpy(p, &m, 4), p += 4;+ memcpy(p, &n, 4), p += 4;+ memcpy(p, &B, HEAD), p += HEAD;+ int32_t counts[7] = {B.nplants, B.nzombies, 0, B.nsuns, B.ncoins, 0, B.nrollers};+ memcpy(p, counts, sizeof counts), p += sizeof counts;+ memcpy(p, B.plants, B.nplants * sizeof(Plant)), p += B.nplants * sizeof(Plant);+ memcpy(p, B.zombies, B.nzombies * sizeof(Zombie)), p += B.nzombies * sizeof(Zombie);+ memcpy(p, B.suns, B.nsuns * sizeof(Sun)), p += B.nsuns * sizeof(Sun);+ memcpy(p, B.coins, B.ncoins * sizeof(Coin)), p += B.ncoins * sizeof(Coin);+ memcpy(p, B.rollers, B.nrollers * sizeof(Roller)), p += B.nrollers * sizeof(Roller);+ if (B.has_boss) memcpy(p, &boss, sizeof boss), p += sizeof boss;+ plat_reserved(LEVEL_NAME, n);+ copy_write();+ return true;+}++bool board_saved(void) {+ uint32_t len, m;+ const uint8_t *d = plat_load(LEVEL_NAME, &len);+ if (!d || len < 8 + HEAD) return false;+ memcpy(&m, d, 4);+ return m == LEVEL_MAGIC;+}++void board_forget(void) {+ if (plat_remove(LEVEL_NAME)) copy_write();+}++bool board_load(void) {+ uint32_t len, m, n;+ const uint8_t *d = plat_load(LEVEL_NAME, &len);+ if (!d || len < 8 + HEAD + 28) return false;+ memcpy(&m, d, 4), memcpy(&n, d + 4, 4);+ if (m != LEVEL_MAGIC || n != len) return false;+ const uint8_t *head = d + 8, *p = head + HEAD;+ uint8_t level = head[offsetof(Board, level)], has_boss = head[offsetof(Board, has_boss)];+ int32_t c[7];+ memcpy(c, p, sizeof c), p += sizeof c;+ if (c[0] < 0 || c[0] > MAX_PLANTS || c[1] < 0 || c[1] > MAX_ZOMBIES || c[3] < 0 || c[3] > MAX_SUNS || c[4] < 0 ||+ c[4] > MAX_COINS || c[6] < 0 || c[6] > MAX_ROLLERS)+ return false;+ uint32_t need = 8 + HEAD + 28 + c[0] * sizeof(Plant) + c[1] * sizeof(Zombie) + c[3] * sizeof(Sun) + c[4] * sizeof(Coin) ++ c[6] * sizeof(Roller) + (has_boss ? sizeof boss : 0);+ if (need != len || level < 1 || level > N_LEVELS) return false;+ memcpy(&B, head, HEAD);+ B.nplants = c[0], B.nzombies = c[1], B.nshots = 0, B.nsuns = c[3], B.ncoins = c[4], B.nfx = 0, B.nrollers = c[6];+ memcpy(B.plants, p, c[0] * sizeof(Plant)), p += c[0] * sizeof(Plant);+ memcpy(B.zombies, p, c[1] * sizeof(Zombie)), p += c[1] * sizeof(Zombie);+ memcpy(B.suns, p, c[3] * sizeof(Sun)), p += c[3] * sizeof(Sun);+ memcpy(B.coins, p, c[4] * sizeof(Coin)), p += c[4] * sizeof(Coin);+ memcpy(B.rollers, p, c[6] * sizeof(Roller)), p += c[6] * sizeof(Roller);+ if (B.has_boss) memcpy(&boss, p, sizeof boss);+ board_forget();+ return true;+}diff --git a/games/pvz/src/save.h b/games/pvz/src/save.hnew file mode 100644index 00000000..1501bfc2--- /dev/null+++ b/games/pvz/src/save.h@@ -0,0 +1,38 @@+/* Saves: the adventure's progress (pvz.sav), the level being played when Home quits (pvzlevel.sav), and a+ * copy of both in a Python script (pvz_saves.py): installing apps keeps only scripts. */+#ifndef PVZ_SAVE_H+#define PVZ_SAVE_H+#include <stdbool.h>+#include <stdint.h>++enum {+ ITEM_SHOVEL = 1, ITEM_ALMANAC = 2, ITEM_SHOP = 4, ITEM_POOL_CLEANER = 8, ITEM_ROOF_CLEANER = 16, ITEM_FIRST_AID = 32,+ ITEM_TROPHY = 64,+};+typedef struct {+ uint8_t level; /* the adventure's next level, 1 to 50 */+ uint8_t finished; /* times the adventure was won */+ uint8_t slots; /* seed slots: 6, more bought from Crazy Dave */+ uint8_t rakes; /* the rake's uses left */+ uint16_t items; /* ITEM_* */+ uint8_t declined; /* times Crazy Dave's seed slot was turned down */+ uint8_t keys_seen; /* 0: the keys sheet not seen yet */+ uint32_t money;+ uint32_t talks; /* Crazy Dave's talks already heard (bit n) */+ uint8_t nlast, last[10]; /* the seeds chosen last */+ uint8_t pad[2];+} Progress;+extern Progress progress;++void save_restore_copy(void); /* the saves back from the script, where installing erased them */+void progress_load(void);+bool progress_save(void);+bool board_save(void); /* the level in progress */+bool board_load(void); /* (and forgets it) */+bool board_saved(void);+void board_forget(void);+/* the plants found so far (the adventure's rewards) */+bool plant_unlocked(int kind);+int level_world(int level);+int level_stage(int level);+#endifdiff --git a/games/pvz/src/screens.c b/games/pvz/src/screens.cnew file mode 100644index 00000000..62808449--- /dev/null+++ b/games/pvz/src/screens.c@@ -0,0 +1,1105 @@+/* The screens: the title, the main menu, a level's start (Crazy Dave, the street, the seed chooser, "Ready... Set...+ * PLANT!"), the lawn, pausing, the rewards, the zombies eating your brains, the Almanac and Crazy Dave's shop+ * (screens.h). */+#include <string.h>+#include "draw.h"+#include "game.h"+#include "gfx.h"+#include "plat.h"+#include "res.h"+#include "save.h"+#include "screens.h"++#define C_DARK 0x0000++bool g_running = true;+int g_state;+uint32_t vis_ticks;++static uint32_t prev_keys, pressed, held;+static int repeat_t[4];+static int state_t; /* ticks in the state */+static int sel, sel2; /* the focus in menus */+static int confirm; /* a question being asked: 0 none */+static int play_level; /* the level being started or played */++static void go(int st) {+ g_state = st, state_t = 0, sel = 0, sel2 = 0, confirm = 0;+}++/* ---------------------------------------------------------------- keys */++static bool hit(uint32_t k) { return (pressed & k) != 0; }+/* arrows pressed, or held: again after a while, then often */+static uint32_t arrows(void) {+ static const uint32_t a[4] = {K_LEFT, K_RIGHT, K_UP, K_DOWN};+ uint32_t out = 0;+ for (int i = 0; i < 4; i++) {+ if (!(held & a[i])) {+ repeat_t[i] = 0;+ continue;+ }+ int t = repeat_t[i]++;+ if (t == 0 || (t >= 28 && (t - 28) % 9 == 0)) out |= a[i];+ }+ return out;+}++/* ---------------------------------------------------------------- the background */++static int loaded_bg = -1, loaded_x = -9999, loaded_sod = -1;++static void show_back(int bg) {+ if (loaded_bg == bg && loaded_x == 0) return;+ gfx_load_back(bg, 0);+ loaded_bg = bg, loaded_x = 0, loaded_sod = -1;+}++static int lawn_back(void) {+ switch (B.env) {+ case ENV_NIGHT: return BG_NIGHT;+ case ENV_POOL: return BG_POOL;+ case ENV_FOG: return BG_FOG;+ case ENV_ROOF: return BG_ROOF;+ default: return B.level <= 3 ? BG_YARD : BG_LAWN;+ }+}++/* the lawn as the camera sees it; sod: how far the sod rows are rolled out (-1 all) */+static void show_lawn(int sod) {+ int bg = lawn_back(), sx = 88 + (int)(cam_x * 0.4f + (cam_x < 0 ? -0.5f : 0.5f));+ if (B.level > 3 || B.env != ENV_DAY) sod = 0;+ else if (sod < 0) sod = 1000;+ if (loaded_bg == bg && loaded_x == sx && loaded_sod == sod) return;+ gfx_load_back(bg, sx);+ if (B.level == 50)+ /* the roof by night: Dr. Zomboss comes in the dark */+ for (int i = 0; i < 256; i++) {+ uint16_t c = gfx_bg_pal[i];+ int r = c >> 11, g = (c >> 5) & 63, b = c & 31;+ gfx_bg_pal[i] = (uint16_t)((r * 3 / 8) << 11 | (g * 3 / 8 + 2) << 5 | (b / 2 + 6 > 31 ? 31 : b / 2 + 6));+ }+ if (sod > 0) {+ int y0 = B.level == 1 ? 108 : 68, y1 = B.level == 1 ? 156 : 196;+ int x1 = 100 + sod - sx;+ if (x1 > SCREEN_W) x1 = SCREEN_W;+ if (x1 > 0) gfx_load_back_rows(BG_LAWN, sx, y0, y1, 0, x1);+ }+ loaded_bg = bg, loaded_x = sx, loaded_sod = sod;+}++/* ---------------------------------------------------------------- Crazy Dave */++typedef struct { int16_t id; const char *text; } Line;+static const Line talks[] = {+ {201, "Evening, neighbor."}, {202, "Those zombies just won't let up, will they?"},+ {203, "You'll notice that fighting zombies at night is different than in the day."},+ {204, "For one, you won't get any sun falling from the sky."}, {205, "You can still get sun from sunflowers, though."},+ {206, "And lucky for you, you got yourself some puff-shrooms."},+ {207, "Plant as many of those as you can and you'll be A-O-GOOD."}, {0, 0},+ {301, "Hey, you found my car key!"}, {302, "You know what that means..."},+ {303, "Crazy Dave's Twiddydinkies is open for business!"}, {304, "Have a look! See if you can't find something you like!"},+ {0, 0},+ {401, "Ever play a game called Whack-a-Zombie?"}, {402, "It's just like huntin' squirbos."},+ {403, "You know, those furry little rodents that dig holes in your lawn?"},+ {404, "Yeah, just like that, but instead of squirbos, it's zombies."},+ {405, "And instead of a shovel, it's a mallet."}, {406, "And instead of ME, it's YOU!"}, {0, 0},+ {501, "Looks like the zombies gave up attacking your front yard."}, {502, "Now they're trying your backyard."},+ {503, "And to top it all off, you can't even use your mushrooms!"}, {504, "'cause they'll fall asleep during the day!"},+ {505, "Well isn't that just dandy!"}, {0, 0},+ {701, "Funny thing about the zombie process. Sometimes it makes 'em come out real little."},+ {702, "Real little and REAL MEAN!"}, {703, "Defend your shins!"}, {0, 0},+ {801, "You know, they used to call me \"Fog Man\""}, {802, "'cause I would hang out in the fog and JUMP OUT AT PEOPLE!"},+ {803, "Ah, those were the days."}, {0, 0},+ {1101, "Why'd it get so dark all of a sudden?"}, {1102, "This can't be good."}, {1103, "Oh well, hope you survive the night!"},+ {0, 0},+ {1201, "Whoa! They even found a way onto your roof!"}, {1202, "Those are some persistent zombies, dude."},+ {1203, "You'll need to use cabbage-pults here due to your roof's angle."}, {1204, "Remember that, and you're good to go!"},+ {0, 0},+ {1304, "I have to warn you..."}, {1305, "You are going to hate this next level."},+ {1306, "Why? Because it's non-stop bungee zombie after bungee zombie."}, {1307, "I hate those confounded bungees!!!"},+ {1308, "I hate them!!"}, {1309, "Hate them with a passion!"}, {1310, "And a vengeance!"},+ {1311, "A-Whoop-a-dee-doo! Here come those idiots now!"}, {0, 0},+ {1401, "Hey, you've collected $%u in coins so far!"}, {1402, "When you collect $750, I'll sell you something really neat-o!"},+ {0, 0},+ {1501, "Hey! Wanna buy an extra seed slot?"},+ {1502, "It'll cost you $750, but you'll be able to choose 7 seeds per level instead of 6!"}, {1503, "How's that sound?"},+ {0, 0},+ {1510, "All right! And hey, when you save up to $5000, I'll sell you the 8-seed slot upgrade!"}, {1511, "Check you later!"},+ {0, 0}, {1520, "Bummer, dude!"}, {0, 0},+ {1551, "Hey! Wanna buy an extra seed slot?"},+ {1552, "It'll cost you $5000, but you'll be able to choose 8 seeds per level instead of 7!"}, {1553, "How's that sound?"},+ {0, 0}, {1560, "All right!"}, {0, 0}, {1570, "Bummer, dude!"}, {0, 0},+ {2300, "Uh oh, he's here."}, {2301, "Better get ready."}, {2302, "It's gonna be one heckuva fight!"},+ {2303, "Listen, though, I know what his weakness is:"}, {2304, "You have to hit him in the pancreas!"},+ {2305, "No, that was a different guy..."}, {2306, "You have to... um... kick him in the..."}, {2307, "Hmm..."},+ {2308, "You have to press up up down down left right..."}, {2309, "er..."}, {2310, "Wait, I remember! It's..."},+ {0, 0},+ {2400, "Greetings, neighbor!"}, {2401, "The name's Crazy Dave."}, {2402, "But you can just call me Crazy Dave."},+ {2403, "Listen, I've got a surprise for you."}, {2404, "But first, I'll need you to clear your lawn."},+ {2405, "Use your shovel and dig up those plants! (the delete key, then OK)"}, {2406, "LET THE DIGGING COMMENCE!"},+ {0, 0},+ {2410, "Ok goody, now for the surprise..."}, {2411, "We're going BOWLING!"}, {2412, "HERE, TAKE THIS WALL-NUT!!"},+ {2413, "Why'd I put a wall-nut in your hand?"}, {2414, "Because I'm CRAAAZY!!!!!"},+ {2415, "NOW GO! BOWL ME A WINNER!"}, {0, 0},+ {2500, "Me and my buddy Harvey Flaxcaster used to break vases when we were bored."},+ {2501, "Well Harvey's outta town, so you're coming with me, Harvey #2!"}, {2502, "BREAK IT LIKE YOU MEAN IT, HARVEY!"},+ {0, 0},+};+#define NTALKS (int)(sizeof talks / sizeof talks[0])++static int talk_at; /* the line being said (its index), -1 none */+static int talk_after; /* what follows: TA_* */+enum { TA_PAN, TA_SHOVEL, TA_BOWL, TA_SLOT_ASK, TA_SLOT_ASK8, TA_MENU, TA_SHOP };+static int talk_bit(int id) {+ switch (id / 100) {+ case 2: return 0; case 3: return 1; case 4: return 2; case 5: return 3; case 7: return 4; case 8: return 5;+ case 11: return 6; case 12: return 7; case 13: return 8; case 14: return 9; case 23: return 10; case 24: return 11;+ case 25: return 12;+ }+ return 31;+}+static void say(int id, int after) {+ talk_at = -1;+ for (int i = 0; i < NTALKS; i++)+ if (talks[i].id == id) talk_at = i;+ talk_after = after;+ progress.talks |= 1u << talk_bit(id);+ go(ST_DAVE);+}++/* ---------------------------------------------------------------- a level */++static uint8_t street[12];+static int nstreet;+static float pan_from, pan_to;+static int pan_then; /* ST_CHOOSE or ST_READY */+static int sod_t = -1;+static uint8_t choose_list[N_SEEDS];+static int nchoose;++static bool usable_here(int kind) {+ if ((kind == P_LILYPAD || kind == P_TANGLEKELP || kind == P_SEASHROOM) && !is_pool()) return false;+ if (kind == P_GRAVEBUSTER && B.ngraves == 0) return false;+ if (B.env == ENV_ROOF && (kind == P_SPIKEWEED || kind == P_GRAVEBUSTER)) return false;+ return true;+}+static bool needs_choice(void) { return B.mode == MODE_LAWN && level_defs[B.level - 1].nseeds == 0; }+static int bank_slots(void) {+ int n = 0;+ for (int k = 0; k < N_SEEDS; k++) n += plant_unlocked(k) && usable_here(k);+ return n < progress.slots ? n : progress.slots;+}++static void street_zombies(void) {+ /* the level's kinds, standing about on the street */+ bool kinds[N_ZOMBIES] = {false};+ for (int w = 0; w < B.nwaves; w++)+ for (int i = 0; i < 24 && B.waves[w][i] != 0xFF; i++) kinds[B.waves[w][i]] = true;+ if (B.mode == MODE_WHACK) kinds[Z_NORMAL] = kinds[Z_CONE] = kinds[Z_BUCKET] = true;+ if (B.has_boss) kinds[Z_NORMAL] = true;+ nstreet = 0;+ for (int k = 0; k < N_ZOMBIES && nstreet < 12; k++)+ if (kinds[k] && k != Z_FLAG && k != Z_BACKUP && k != Z_IMP && k != Z_BOBSLED && k != Z_DUCKY) {+ street[nstreet++] = (uint8_t)k;+ if (nstreet < 12 && (k == Z_NORMAL || k == Z_CONE)) street[nstreet++] = (uint8_t)k;+ }+}++static void start_pan(float from, float to, int then) {+ pan_from = from, pan_to = to, pan_then = then;+ go(ST_PAN);+}++static void begin_level(int level) {+ play_level = level;+ board_start(level);+ hud.col = 2, hud.row = B.nrows / 2, hud.selected = -1, hud.shovel = false, hud.issue = 0;+ cam_x = 0, sod_t = -1;+ street_zombies();+ if (B.level <= 3 && B.env == ENV_DAY) sod_t = 0;+ /* Crazy Dave, the first time */+ int talk = 0, after = TA_PAN;+ bool first = !(progress.finished) && level >= progress.level;+ if (first) {+ if (level == 11) talk = 201;+ else if (level == 12 && progress.money < 750) talk = 1401;+ else if (level == 5) talk = 2400, after = TA_SHOVEL;+ else if (level == 15) talk = 401;+ else if (level == 21) talk = 501;+ else if (level == 25) talk = 701;+ else if (level == 31) talk = 801;+ else if (level == 35) talk = 2500;+ else if (level == 40) talk = 1101;+ else if (level == 41) talk = 1201;+ else if (level == 45) talk = 1304;+ else if (level == 50) talk = 2300;+ if (!talk && level >= 13 && level <= 24 && level != 15 && level != 20 && level != 21 && progress.declined < 2) {+ if (progress.slots == 6 && progress.money >= 750) talk = 1501, after = TA_SLOT_ASK;+ else if (level >= 16 && progress.slots == 7 && progress.money >= 5000) talk = 1551, after = TA_SLOT_ASK8;+ }+ } else if (level == 5)+ talk = 2411, after = TA_PAN;+ if (talk) say(talk, after);+ else start_pan(0, 380, needs_choice() ? ST_CHOOSE : ST_READY);+}++static void start_play(void) {+ B.phase = PH_PLAY;+ if (B.level == 1) B.tutorial = 1;+ if (B.level == 2 && !progress.finished) B.tutorial = 2, B.wave_in = 5000;+ if (B.mode != MODE_WHACK && (progress.rakes > 0) && B.mode != MODE_VASE && !B.has_boss) {+ /* the rake waits in a lane */+ int rows[MAX_ROWS], n = 0;+ for (int r = 0; r < B.nrows; r++)+ if ((B.rows >> r & 1) && !water_row(r)) rows[n++] = r;+ if (n) B.rake.on = 1, B.rake.row = (uint8_t)rows[irand(n)], B.rake.col = 7, B.rake.age = -1, progress.rakes--;+ }+ go(ST_PLAY);+}++/* the shovel lesson of level 1-5: three peashooters to dig up */+static void shovel_lesson(void) {+ static const uint8_t at[3][2] = {{5, 1}, {7, 2}, {6, 3}};+ progress.items |= ITEM_SHOVEL;+ for (int i = 0; i < 3; i++) plant_new(&B.plants[B.nplants++], P_PEASHOOTER, at[i][0], at[i][1]);+ B.tutorial = 4;+ B.phase = PH_PLAY;+ B.started = 0;+ hud.shovel = true;+ go(ST_PLAY);+}++static void finish_level(void) {+ /* the level won: the next one opens */+ const LevelDef *d = &level_defs[B.level - 1];+ if (B.level >= progress.level) {+ if (d->reward == REWARD_SHOVEL) progress.items |= ITEM_SHOVEL;+ if (d->reward == REWARD_ALMANAC) progress.items |= ITEM_ALMANAC;+ if (d->reward == REWARD_KEYS) progress.items |= ITEM_SHOP;+ if (d->reward == REWARD_MONEY) progress.money += 500;+ if (d->reward == REWARD_TROPHY) progress.items |= ITEM_TROPHY, progress.finished++;+ progress.level = B.level < N_LEVELS ? (uint8_t)(B.level + 1) : 1;+ } else if (d->reward == REWARD_MONEY)+ progress.money += 250;+ if (B.level == N_LEVELS && !(progress.items & ITEM_TROPHY)) progress.items |= ITEM_TROPHY;+ board_forget();+ progress_save();+}++/* ---------------------------------------------------------------- the lawn */++static void play_input(void) {+ uint32_t a = arrows();+ if (a & K_LEFT && hud.col > 0) hud.col--;+ if (a & K_RIGHT && hud.col < COLS - 1) hud.col++;+ if (a & K_UP && hud.row > 0) hud.row--;+ if (a & K_DOWN && hud.row < B.nrows - 1) hud.row++;+ /* sun and coins under the cursor are picked up */+ float cx = cell_x(hud.col), cy = row_y(hud.row, cx) - 30;+ if (board_collect(cx, cy, 52)) {+ if (B.tutorial == 1 && B.level == 1) {}+ }+ for (int n = 1; n <= 10; n++) {+ if (!hit(K_DIGIT(n))) continue;+ int slot = n - 1;+ hud.shovel = false;+ if (has_conveyor() ? slot < B.npackets : slot < B.nseeds && B.mode != MODE_VASE) {+ if (hud.selected == slot) hud.selected = -1;+ else if (!has_conveyor() && B.sun < plant_cost(B.seeds[slot])) hud.issue = ISSUE_SUN, hud.issue_t = (int)vis_ticks;+ else if (!has_conveyor() && B.cooldown[slot] > 0) hud.issue = ISSUE_RECHARGE, hud.issue_t = (int)vis_ticks;+ else hud.selected = slot;+ }+ }+ if (hit(K_SHOVEL) && (progress.items & ITEM_SHOVEL) && B.mode != MODE_WHACK && B.mode != MODE_VASE)+ hud.shovel = !hud.shovel, hud.selected = -1;+ if (hit(K_OK)) {+ int col = hud.col, row = hud.row;+ if (hud.shovel) {+ if (board_dig(col, row) && B.tutorial != 4) hud.shovel = false;+ } else if (hud.selected >= 0) {+ int kind = B.mode == MODE_VASE ? B.drops[hud.selected].kind : seed_kind(hud.selected);+ int issue = plant_issue(kind, col, row);+ if (!issue && !has_conveyor() && B.mode != MODE_VASE) {+ if (B.sun < plant_cost(kind)) issue = ISSUE_SUN;+ else if (B.cooldown[hud.selected] > 0) issue = ISSUE_RECHARGE;+ }+ if (issue) hud.issue = issue, hud.issue_t = (int)vis_ticks;+ else if (board_plant(hud.selected, col, row)) hud.selected = -1;+ } else if (B.mode == MODE_WHACK) {+ board_whack(cx, row_y(row, cx) - 40);+ } else if (B.mode == MODE_VASE) {+ for (int i = 0; i < B.ndrops; i++)+ if (B.drops[i].col == col && B.drops[i].row == row) {+ hud.selected = i;+ if (B.drops[i].times == 0 && B.drops[i].left < 300) B.drops[i].left = 300;+ B.drops[i].times++;+ break;+ }+ if (hud.selected < 0) board_break_vase(col, row);+ }+ }+ if (B.mode == MODE_VASE && hud.selected >= B.ndrops) hud.selected = -1;+ if (has_conveyor() && hud.selected >= B.npackets) hud.selected = -1;+}++/* ---------------------------------------------------------------- the frame */++void game_init(void) {+ save_restore_copy();+ progress_load();+ go(ST_TITLE);+}++static void quit_saving(void) {+ if (g_state == ST_PLAY || g_state == ST_PAUSE || (g_state == ST_WON)) {+ if (B.phase == PH_PLAY) board_save();+ }+ progress_save();+ g_running = false;+}++static int menu_items(int *items) {+ int n = 0;+ items[n++] = 0; /* Adventure */+ if (progress.level > 1 || progress.finished) items[n++] = 1; /* Choose a level */+ if (progress.items & ITEM_ALMANAC) items[n++] = 2;+ if (progress.items & ITEM_SHOP) items[n++] = 3;+ items[n++] = 4; /* How to play */+ items[n++] = 5; /* Quit */+ return n;+}++static int almanac_page; /* 0 index, 1 plants, 2 zombies */+static int shop_first;++void game_frame(uint32_t keys) {+ pressed = keys & ~prev_keys, held = keys, prev_keys = keys;+ vis_ticks++, state_t++;+ if (keys & K_HOME) {+ quit_saving();+ return;+ }+ switch (g_state) {+ case ST_TITLE:+ if (state_t > 30 && hit(K_OK | (K_ANY & ~K_BACK))) go(ST_MENU);+ if (hit(K_BACK)) g_running = false;+ break;++ case ST_MENU: {+ int items[8], n = menu_items(items);+ if (confirm) {+ if (hit(K_LEFT | K_RIGHT)) sel2 ^= 1;+ if (hit(K_OK)) {+ if (sel2 == 0) quit_saving();+ confirm = 0;+ }+ if (hit(K_BACK)) confirm = 0;+ break;+ }+ uint32_t a = arrows();+ if (a & K_UP) sel = (sel + n - 1) % n;+ if (a & K_DOWN) sel = (sel + 1) % n;+ if (hit(K_BACK)) confirm = 1, sel2 = 1;+ if (hit(K_ALMANAC) && (progress.items & ITEM_ALMANAC)) almanac_page = 0, go(ST_ALMANAC);+ if (hit(K_OK)) {+ switch (items[sel]) {+ case 0:+ if (board_saved() && board_load()) {+ play_level = B.level;+ hud.col = 2, hud.row = B.nrows / 2, hud.selected = -1, hud.shovel = false;+ cam_x = 0, sod_t = -1, loaded_bg = -1;+ go(ST_PAUSE); /* (back where it was left, paused) */+ } else+ begin_level(progress.level);+ break;+ case 1: go(ST_LEVELS), sel = progress.level - 1; break;+ case 2: almanac_page = 0, go(ST_ALMANAC); break;+ case 3:+ go(ST_SHOP);+ if (!(progress.talks & (1u << 1))) shop_first = 1, say(301, TA_SHOP);+ break;+ case 4: go(ST_HELP); break;+ case 5: confirm = 1, sel2 = 1; break;+ }+ }+ break;+ }++ case ST_LEVELS: {+ int top = progress.finished ? N_LEVELS : progress.level;+ uint32_t a = arrows();+ if (a & K_LEFT && sel % 10 > 0) sel--;+ if (a & K_RIGHT && sel % 10 < 9 && sel + 1 < top) sel++;+ if (a & K_UP && sel >= 10) sel -= 10;+ if (a & K_DOWN && sel + 10 < top) sel += 10;+ if (hit(K_BACK)) go(ST_MENU);+ if (hit(K_OK)) board_forget(), begin_level(sel + 1);+ break;+ }++ case ST_DAVE:+ if (state_t < 25) break;+ if (talk_after == TA_SLOT_ASK || talk_after == TA_SLOT_ASK8) {+ bool last = talk_at + 1 >= NTALKS || talks[talk_at + 1].id == 0;+ if (last) {+ if (hit(K_LEFT | K_RIGHT)) sel2 ^= 1;+ if (hit(K_OK)) {+ bool eight = talk_after == TA_SLOT_ASK8;+ uint32_t cost = eight ? 5000 : 750;+ if (sel2 == 0 && progress.money >= cost) {+ progress.money -= cost, progress.slots++;+ say(eight ? 1560 : 1510, TA_PAN);+ } else {+ progress.declined++;+ say(eight ? 1570 : 1520, TA_PAN);+ }+ progress_save();+ }+ break;+ }+ }+ if (hit(K_OK | K_BACK)) {+ bool skip = hit(K_BACK);+ if (!skip && talk_at + 1 < NTALKS && talks[talk_at + 1].id != 0) {+ talk_at++, state_t = 10;+ break;+ }+ switch (talk_after) {+ case TA_SHOVEL: show_lawn(-1), shovel_lesson(); break;+ case TA_BOWL: go(ST_READY); break;+ case TA_SHOP: go(ST_SHOP); break;+ case TA_MENU: go(ST_MENU); break;+ case TA_SLOT_ASK: case TA_SLOT_ASK8:+ if (skip) progress.declined++, start_pan(0, 380, needs_choice() ? ST_CHOOSE : ST_READY);+ break;+ default:+ if (B.level == 5 && B.mode == MODE_BOWLING && B.tutorial == 0 && talks[talk_at].id >= 2410) go(ST_READY);+ else start_pan(0, 380, needs_choice() ? ST_CHOOSE : ST_READY);+ }+ }+ break;++ case ST_PAN: {+ float t = state_t / 150.0f;+ if (pan_to > pan_from && state_t > 150 + 100 && pan_then != ST_CHOOSE) {+ /* (shown long enough: back to the lawn) */+ start_pan(pan_to, 0, ST_READY);+ break;+ }+ if (t > 1) t = 1;+ float k = t * t * (3 - 2 * t);+ cam_x = pan_from + (pan_to - pan_from) * k;+ if (pan_to > pan_from && pan_then == ST_CHOOSE && state_t >= 150) {+ int n = 0;+ for (int k2 = 0; k2 < N_SEEDS; k2++)+ if (plant_unlocked(k2)) choose_list[n++] = (uint8_t)k2;+ nchoose = n;+ /* the seeds of last time, as far as they go here */+ uint8_t pick[10];+ int np = 0, cap = bank_slots();+ for (int i = 0; i < progress.nlast && np < cap; i++)+ if (progress.last[i] < N_SEEDS && plant_unlocked(progress.last[i]) && usable_here(progress.last[i]))+ pick[np++] = progress.last[i];+ board_set_seeds(pick, np);+ go(ST_CHOOSE);+ break;+ }+ if (pan_to < pan_from && state_t >= 150) {+ cam_x = 0;+ if (sod_t >= 0) {+ sod_t++;+ if (sod_t < 120) {+ state_t = 150;+ break;+ }+ sod_t = -1;+ }+ go(ST_READY);+ }+ break;+ }++ case ST_CHOOSE: {+ int cap = bank_slots();+ uint32_t a = arrows();+ int rows = (nchoose + 7) / 8;+ /* sel: the packet in the grid, or nchoose: "Let's Rock!" */+ if (a & K_LEFT && sel < nchoose && sel % 8 > 0) sel--;+ if (a & K_RIGHT && sel < nchoose && sel % 8 < 7 && sel + 1 < nchoose) sel++;+ if (a & K_UP) sel = sel == nchoose ? (rows - 1) * 8 : sel >= 8 ? sel - 8 : sel;+ if (a & K_DOWN) sel = sel == nchoose ? sel : sel + 8 < nchoose ? sel + 8 : nchoose;+ if (hit(K_BACK)) {+ board_forget();+ go(ST_MENU);+ break;+ }+ if (hit(K_ALMANAC) && (progress.items & ITEM_ALMANAC)) {}+ if (hit(K_OK)) {+ if (sel == nchoose) {+ if (B.nseeds == cap) {+ progress.nlast = B.nseeds;+ memcpy(progress.last, B.seeds, B.nseeds);+ start_pan(380, 0, ST_READY);+ }+ } else {+ int kind = choose_list[sel], at = -1;+ for (int i = 0; i < B.nseeds; i++)+ if (B.seeds[i] == kind) at = i;+ uint8_t s[10];+ int n = B.nseeds;+ memcpy(s, B.seeds, (size_t)n);+ if (at >= 0) memmove(s + at, s + at + 1, (size_t)(n - at - 1)), n--;+ else if (n < cap && usable_here(kind)) s[n++] = (uint8_t)kind;+ board_set_seeds(s, n);+ if (B.nseeds == cap && at < 0) sel = nchoose;+ }+ }+ break;+ }++ case ST_READY:+ show_lawn(-1);+ if (state_t >= 180) start_play();+ break;++ case ST_PLAY:+ show_lawn(-1);+ if (hit(K_BACK)) {+ if (hud.selected >= 0 || hud.shovel) hud.selected = -1, hud.shovel = false;+ else {+ go(ST_PAUSE);+ break;+ }+ }+ play_input();+ board_tick();+ if (B.tutorial == 4) {+ /* the shovel lesson done: on to bowling */+ bool left = false;+ for (int i = 0; i < B.nplants; i++) left |= B.plants[i].health > 0;+ if (!left) {+ B.tutorial = 0, B.nplants = 0, hud.shovel = false;+ say(2410, TA_BOWL);+ }+ break;+ }+ if (B.phase == PH_WON) {+ hud.selected = -1, hud.shovel = false;+ go(ST_WON);+ } else if (B.phase == PH_LOST) {+ board_forget();+ go(ST_LOST);+ }+ break;++ case ST_PAUSE:+ show_lawn(-1);+ if (confirm) {+ if (hit(K_LEFT | K_RIGHT)) sel2 ^= 1;+ if (hit(K_BACK)) confirm = 0;+ if (hit(K_OK)) {+ if (sel2 == 0) {+ if (confirm == 1) quit_saving();+ else if (confirm == 2) begin_level(play_level);+ return;+ }+ confirm = 0;+ }+ break;+ }+ {+ uint32_t a = arrows();+ if (a & K_UP) sel = (sel + 3) % 4;+ if (a & K_DOWN) sel = (sel + 1) % 4;+ }+ if (hit(K_BACK)) go(ST_PLAY);+ if (hit(K_OK)) {+ if (sel == 0) go(ST_PLAY);+ else if (sel == 1) confirm = 2, sel2 = 1;+ else if (sel == 2) {+ if (B.phase == PH_PLAY) board_save();+ progress_save();+ go(ST_MENU);+ } else+ confirm = 1, sel2 = 1;+ }+ break;++ case ST_WON:+ show_lawn(-1);+ /* what is left of the lawn goes on (the dead fall, sun can be picked up) */+ for (int i = 0; i < B.nfx; i++)+ if (++B.fx[i].t >= B.fx[i].life) B.fx[i--] = B.fx[--B.nfx];+ {+ float cx = cell_x(hud.col);+ board_collect(cx, row_y(hud.row, cx) - 30, 52);+ }+ B.ticks++;+ if (state_t > 60 && hit(K_OK)) {+ /* the sun and coins left are picked up too */+ board_collect(400, 300, 2000);+ finish_level();+ go(ST_AWARD);+ }+ break;++ case ST_AWARD:+ if (state_t > 40 && hit(K_OK)) {+ if (B.level == N_LEVELS) go(ST_MENU);+ else begin_level(B.level + 1);+ }+ if (state_t > 40 && hit(K_BACK)) go(ST_MENU);+ break;++ case ST_LOST: {+ if (state_t <= 120) cam_x = -220 * (state_t / 120.0f);+ show_lawn(-1);+ if (state_t > 300) {+ if (hit(K_LEFT | K_RIGHT | K_UP | K_DOWN)) sel ^= 1;+ if (hit(K_OK)) {+ progress_save();+ if (sel == 0) begin_level(play_level);+ else go(ST_MENU);+ }+ }+ break;+ }++ case ST_ALMANAC: {+ if (almanac_page == 0) {+ if (hit(K_LEFT | K_RIGHT | K_UP | K_DOWN)) sel ^= 1;+ if (hit(K_OK)) almanac_page = 1 + sel, sel = 0;+ if (hit(K_BACK)) go(ST_MENU);+ break;+ }+ int n = almanac_page == 1 ? N_SEEDS : N_ZOMBIES, per = almanac_page == 1 ? 8 : 6;+ uint32_t a = arrows();+ if (a & K_LEFT && sel % per > 0) sel--;+ if (a & K_RIGHT && sel % per < per - 1 && sel + 1 < n) sel++;+ if (a & K_UP && sel >= per) sel -= per;+ if (a & K_DOWN && sel + per < n) sel += per;+ if (hit(K_BACK)) almanac_page = 0, sel = 0;+ break;+ }++ case ST_SHOP: {+ uint32_t a = arrows();+ if (a & K_LEFT) sel = (sel + 4) % 5;+ if (a & K_RIGHT) sel = (sel + 1) % 5;+ if (hit(K_BACK)) {+ progress_save();+ go(ST_MENU);+ }+ if (hit(K_OK)) {+ static const uint32_t slot_cost[4] = {750, 5000, 20000, 80000};+ uint32_t cost = 0;+ bool ok = false;+ switch (sel) {+ case 0: if (progress.slots < 10) cost = slot_cost[progress.slots - 6], ok = true; break;+ case 1: if (!(progress.items & ITEM_POOL_CLEANER)) cost = 1000, ok = progress.level > 21 || progress.finished; break;+ case 2: if (!(progress.items & ITEM_ROOF_CLEANER)) cost = 3000, ok = progress.level > 41 || progress.finished; break;+ case 3: if (progress.rakes == 0) cost = 200, ok = true; break;+ case 4: if (!(progress.items & ITEM_FIRST_AID)) cost = 2000, ok = progress.level > 21 || progress.finished; break;+ }+ if (ok && progress.money >= cost) {+ progress.money -= cost;+ if (sel == 0) progress.slots++;+ if (sel == 1) progress.items |= ITEM_POOL_CLEANER;+ if (sel == 2) progress.items |= ITEM_ROOF_CLEANER;+ if (sel == 3) progress.rakes = 3;+ if (sel == 4) progress.items |= ITEM_FIRST_AID;+ progress_save();+ }+ }+ break;+ }++ case ST_HELP:+ if (hit(K_OK | K_BACK)) go(ST_MENU);+ break;+ }+}++/* ---------------------------------------------------------------- drawing the screens */++static const char *const menu_names[] = {"Adventure", "Choose a Level", "Almanac", "Shop", "How to Play", "Quit"};++static void draw_menu(void) {+ show_back(BG_MENU);+ gfx_anim(I_LOGO, 0, 20, 4, 0, TINT_NONE, 32);+ int items[8], n = menu_items(items);+ /* the tombstone's slabs */+ for (int i = 0; i < n; i++) {+ int y = 64 + i * 27, x = 166;+ bool f = i == sel;+ gfx_anim(I_BUTTON, 0, x, y, 0, f ? TINT_HIT : TINT_DARK, 32);+ const char *label = menu_names[items[i]];+ if (items[i] == 0) {+ gfx_text(F_HEAD, x + 50, y + 15, board_saved() ? "Continue" : "Adventure", f ? rgb565(0xFFF5B0) : rgb565(0xD8D8E8),+ GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_SMALL, x + 50, y + 25,+ progress.finished && progress.level == 1 ? "Play again!" : gfx_fmt("Level %d-%d", level_world(progress.level),+ level_stage(progress.level)),+ rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ } else+ gfx_text(F_HEAD, x + 50, y + 19, label, f ? rgb565(0xFFF5B0) : rgb565(0xD8D8E8), GFX_CENTER | GFX_OUTLINE);+ }+ if (progress.money) draw_money(4, 226, progress.money);+ if (confirm) {+ draw_dialog(60, 80, 200, 80);+ gfx_text(F_HEAD, 160, 104, "Quit the game?", C_WHITE, GFX_CENTER | GFX_OUTLINE);+ draw_button(80, 124, 70, "Quit", sel2 == 0);+ draw_button(170, 124, 70, "Cancel", sel2 == 1);+ }+}++static void draw_levels(void) {+ show_back(BG_MENU);+ gfx_rect(0, 0, SCREEN_W, SCREEN_H, 0, 14);+ gfx_text(F_BIG, 160, 22, "Choose a Level", rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ static const char *const worlds[5] = {"Day", "Night", "Pool", "Fog", "Roof"};+ int top = progress.finished ? N_LEVELS : progress.level;+ for (int w = 0; w < 5; w++) {+ gfx_text(F_HEAD, 6, 54 + w * 34, worlds[w], C_WHITE, GFX_OUTLINE);+ for (int s = 0; s < 10; s++) {+ int l = w * 10 + s, x = 52 + s * 26, y = 40 + w * 34;+ bool open = l < top, f = l == sel;+ gfx_round_rect(x, y, 24, 20, 4, f ? rgb565(0x6CBF3A) : open ? rgb565(0x8A5A2E) : rgb565(0x404040), 32);+ gfx_text(F_SMALL, x + 12, y + 13, gfx_fmt("%d-%d", w + 1, s + 1), open ? C_WHITE : rgb565(0x909090),+ GFX_CENTER | GFX_OUTLINE);+ }+ }+ gfx_text(F_SMALL, 160, 232, "OK: play Back: menu", C_WHITE, GFX_CENTER | GFX_OUTLINE);+}++static void draw_dave(void) {+ /* the lawn behind him */+ show_lawn(B.level <= 3 ? 0 : -1);+ draw_lawn(false);+ int in = state_t < 25 ? (25 - state_t) * 4 : 0;+ gfx_image(I_DAVE, 4 - in, 66);+ const Line *l = talk_at >= 0 ? &talks[talk_at] : NULL;+ if (!l || state_t < 18) return;+ int x = 84, y = 70, w = 226, h = 74;+ gfx_round_rect(x, y, w, h, 10, C_DARK, 32);+ gfx_round_rect(x + 2, y + 2, w - 4, h - 4, 9, C_WHITE, 32);+ for (int i = 0; i < 8; i++) gfx_rect(x - 6 + i, y + 40 + i / 2, 8 - i, 2, i ? C_WHITE : C_DARK, 32);+ const char *s = l->id == 1401 ? gfx_fmt(l->text, (unsigned)progress.money) : l->text;+ gfx_paragraph(F_BODY, x + w / 2, y + 22, w - 20, s, C_DARK, 0);+ bool ask = (talk_after == TA_SLOT_ASK || talk_after == TA_SLOT_ASK8) &&+ (talk_at + 1 >= NTALKS || talks[talk_at + 1].id == 0);+ if (ask) {+ draw_button(x + 30, y + h + 6, 70, "Yes", sel2 == 0);+ draw_button(x + w - 100, y + h + 6, 70, "No", sel2 == 1);+ } else if ((vis_ticks / 40) % 2)+ gfx_text(F_SMALL, x + w - 8, y + h - 6, "OK", rgb565(0x707070), GFX_RIGHT);+}++static void draw_chooser(void) {+ show_lawn(0);+ draw_street(street, nstreet);+ hud_bank_draw(0, 0, false);+ int cap = bank_slots();+ for (int i = 0; i < cap; i++) {+ int x = 34 + i * 21;+ if (i < B.nseeds) packet_draw(B.seeds[i], x, 3, 0, 0, false, false, i + 1);+ else gfx_rect(x, 3, 20, 28, 0, 10);+ }+ int px = 0, py = 36;+ gfx_image(I_CHOOSER, px, py);+ gfx_text(F_HEAD, px + 93, py + 15, "Choose your plants!", rgb565(0xF2C94C), GFX_CENTER | GFX_OUTLINE);+ for (int i = 0; i < nchoose; i++) {+ int kind = choose_list[i], x = px + 10 + (i % 8) * 21, y = py + 24 + (i / 8) * 30;+ bool chosen = false;+ for (int k = 0; k < B.nseeds; k++) chosen |= B.seeds[k] == kind;+ packet_draw(kind, x, y, 0, 0, chosen || !usable_here(kind), false, 0);+ if (i == sel) gfx_frame_rect(x - 1, y - 1, 22, 30, 1, rgb565(0xFFE14A), 32);+ }+ bool ready = B.nseeds == cap;+ int bx = px + 51, by = py + 178;+ gfx_anim(ready ? I_START : I_START_OFF, 0, bx, by, 0, sel == nchoose ? TINT_HIT : TINT_NONE, 32);+ gfx_text(F_HEAD, bx + 42, by + 15, "Let's Rock!", ready ? rgb565(0xFFE14A) : rgb565(0x9A9A9A), GFX_CENTER | GFX_OUTLINE);+ if (sel == nchoose) gfx_frame_rect(bx - 2, by - 2, 88, 26, 1, rgb565(0xFFE14A), 32);+ /* what the plant does */+ if (sel < nchoose) {+ int kind = choose_list[sel];+ gfx_round_rect(190, 150, 126, 86, 6, C_DARK, 22);+ gfx_text(F_HEAD, 253, 164, plant_defs[kind].name, rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_SMALL, 253, 175, gfx_fmt("Cost: %d Recharge: %s", plant_defs[kind].cost,+ plant_defs[kind].cooldown >= 5000 ? "very slow" : plant_defs[kind].cooldown >= 3000 ? "slow"+ : "fast"),+ C_WHITE, GFX_CENTER);+ gfx_paragraph(F_SMALL, 253, 186, 118, plant_blurbs[kind], C_WHITE, 0);+ }+}++static void draw_pause(void) {+ draw_lawn(true);+ hud_draw(false);+ gfx_rect(0, 0, SCREEN_W, SCREEN_H, 0, 10);+ int x = 70, y = 28, w = 180;+ gfx_anim(I_DIALOG, 0, x + w / 2 - 82, y - 6, 0, TINT_NONE, 32);+ gfx_text(F_BIG, 160, y + 46, "Paused", rgb565(0xE8E8F0), GFX_CENTER | GFX_OUTLINE);+ static const char *const items[4] = {"Back to Game", "Restart Level", "Main Menu", "Quit Game"};+ for (int i = 0; i < 4; i++) draw_button(x + 30, y + 62 + i * 25, w - 60, items[i], i == sel);+ if (confirm) {+ draw_dialog(50, 84, 220, 82);+ gfx_paragraph(F_BODY, 160, 104, 200,+ confirm == 1 ? "Quit the game? This level is kept for next time." : "Restart this level from the start?",+ C_WHITE, GFX_OUTLINE);+ draw_button(70, 138, 80, confirm == 1 ? "Quit" : "Restart", sel2 == 0);+ draw_button(170, 138, 80, "Cancel", sel2 == 1);+ }+}++static void draw_reward(int x, int y, bool big) {+ const LevelDef *d = &level_defs[B.level - 1];+ if (d->reward >= 0) {+ if (big) gfx_image(I_BIG_PEASHOOTER + d->reward, x, y + 10);+ else {+ gfx_image(I_PACKET, x - 10, y - 14);+ gfx_image(I_PACKET_PEASHOOTER + d->reward, x, y - 2);+ }+ } else if (d->reward == REWARD_SHOVEL) gfx_anim_scaled(I_SHOVEL, 0, x, y, big ? 512 : 256, big ? 512 : 256, 0, 0, 32);+ else if (d->reward == REWARD_TROPHY) gfx_anim_scaled(I_TROPHY, 0, x - (big ? 31 : 16), y - (big ? 27 : 14), big ? 256 : 128,+ big ? 256 : 128, 0, 0, 32);+ else if (d->reward == REWARD_ALMANAC) {+ gfx_round_rect(x - 12, y - 15, 24, 30, 3, rgb565(0x7A4A20), 32);+ gfx_round_rect(x - 10, y - 13, 20, 26, 2, rgb565(0x3F7F2A), 32);+ gfx_image(I_PACKET_PEASHOOTER, x, y - 2);+ } else if (d->reward == REWARD_KEYS) {+ gfx_ellipse(x - 4, y, 6, 6, rgb565(0xD8C060), 32);+ gfx_ellipse(x - 4, y, 3, 3, 0, 32);+ gfx_rect(x, y - 1, 12, 3, rgb565(0xD8C060), 32);+ gfx_rect(x + 8, y + 2, 2, 4, rgb565(0xD8C060), 32);+ } else {+ gfx_ellipse(x, y + 2, 10, 9, rgb565(0x8A6A3A), 32);+ gfx_ellipse(x, y - 8, 5, 3, rgb565(0x6A4A2A), 32);+ gfx_text(F_HEAD, x, y + 6, "$", rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ }+}++static void draw_won(void) {+ draw_lawn(true);+ hud_draw(false);+ int x = screen_x(B.last_x), y = screen_y(B.last_y) - 20;+ if (x < 20) x = 20;+ if (x > 300) x = 300;+ if (y < 40) y = 40;+ int bob = (int)(vis_ticks / 6 % 8);+ bob = bob < 4 ? bob : 8 - bob;+ for (int r = 18; r > 4; r -= 4) gfx_ellipse(x, y - bob, r, r, rgb565(0xFFF5B0), 6);+ draw_reward(x, y - bob, false);+ if (state_t > 60 && (vis_ticks / 40) % 2) draw_message_band("Press OK to pick it up!");+}++static void draw_award(void) {+ show_back(BG_AWARD);+ const LevelDef *d = &level_defs[B.level - 1];+ const char *head, *name, *text;+ static char buf[40];+ if (d->reward >= 0) {+ head = "You got a new plant!", name = plant_defs[d->reward].name, text = plant_blurbs[d->reward];+ } else if (d->reward == REWARD_SHOVEL) {+ head = "You found the shovel!", name = "Shovel", text = "Lets you dig up unwanted plants: the delete key, then OK.";+ } else if (d->reward == REWARD_ALMANAC) {+ head = "You found the Suburban Almanac!", name = "Suburban Almanac",+ text = "Keeps track of all the plants and zombies you encounter. Open it from the menu or with the toolbox key.";+ } else if (d->reward == REWARD_KEYS) {+ head = "You found Crazy Dave's car keys!", name = "Car Keys", text = "Crazy Dave's shop is open: find it in the menu.";+ } else if (d->reward == REWARD_TROPHY) {+ head = "You beat the zombies!", name = "Silver Sunflower Trophy",+ text = "Dr. Zomboss is defeated and your lawn is safe. Play the adventure again, with Crazy Dave picking some of your "+ "seeds!";+ } else {+ memcpy(buf, "You found a money bag!", 23);+ head = buf, name = "Money Bag", text = "$500 for Crazy Dave's shop.";+ }+ gfx_text(F_HEAD, 160, 22, head, rgb565(0xF2C94C), GFX_CENTER | GFX_OUTLINE);+ draw_reward(160, 82, true);+ gfx_text(F_HEAD, 160, 152, name, rgb565(0x3A2410), GFX_CENTER);+ gfx_paragraph(F_BODY, 160, 172, 200, text, rgb565(0x3A2410), 0);+ draw_button(110, 214, 100, B.level == N_LEVELS ? "Main Menu" : "Next Level", true);+}++static void draw_lost(void) {+ /* the zombie walks into the house */+ draw_lawn(false);+ if (state_t > 120) {+ int k = state_t - 120;+ int dx = (k / 2) % 3 - 1;+ gfx_rect(0, 0, SCREEN_W, SCREEN_H, 0, k < 60 ? k / 3 : 20);+ gfx_text(F_BIG, 160 + dx, 104, "THE ZOMBIES", rgb565(0x7AD030), GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_BIG, 160 - dx, 128, "ATE YOUR BRAINS!", rgb565(0x7AD030), GFX_CENTER | GFX_OUTLINE);+ }+ if (state_t > 300) {+ draw_button(60, 168, 90, "Try Again", sel == 0);+ draw_button(170, 168, 90, "Main Menu", sel == 1);+ }+}++static bool zombie_seen(int k) {+ if (progress.finished) return true;+ if (k == Z_DUCKY) return progress.level > 21;+ if (k == Z_BACKUP) return progress.level > 18;+ if (k == Z_IMP) return progress.level > 48;+ return zombie_defs[k].starting < progress.level || (k == Z_FLAG && progress.level > 2);+}++static void draw_almanac(void) {+ show_back(BG_ALMANAC);+ if (almanac_page == 0) {+ gfx_text(F_BIG, 160, 40, "Suburban Almanac", rgb565(0x5A3A1E), GFX_CENTER);+ gfx_image(I_BIG_PEASHOOTER, 92, 120);+ gfx_image(I_PORTRAIT_NORMAL, 228, 170);+ draw_button(40, 182, 104, "View Plants", sel == 0);+ draw_button(176, 182, 104, "View Zombies", sel == 1);+ gfx_text(F_SMALL, 160, 230, "Back: menu", rgb565(0x5A3A1E), GFX_CENTER);+ return;+ }+ if (almanac_page == 1) {+ gfx_text(F_HEAD, 86, 24, "Plants", rgb565(0x5A3A1E), GFX_CENTER);+ for (int i = 0; i < N_SEEDS; i++) {+ int x = 4 + (i % 8) * 21, y = 32 + (i / 8) * 30;+ if (plant_unlocked(i)) packet_draw(i, x, y, 0, 0, false, false, 0);+ else gfx_round_rect(x, y, 20, 28, 2, rgb565(0x8A7A5A), 32);+ if (i == sel) gfx_frame_rect(x - 1, y - 1, 22, 30, 1, rgb565(0xE83020), 32);+ }+ int k = sel;+ gfx_image(I_CARD, 180, 16);+ if (plant_unlocked(k)) {+ gfx_image(I_BIG_PEASHOOTER + k, 245, 76);+ gfx_text(F_HEAD, 245, 108, plant_defs[k].name, rgb565(0x3A2410), GFX_CENTER);+ int y = gfx_paragraph(F_SMALL, 245, 120, 116, plant_blurbs[k], rgb565(0x3A2410), 0);+ gfx_paragraph(F_SMALL, 245, y + 2, 116, plant_stats[k], rgb565(0x7A2010), 0);+ gfx_text(F_SMALL, 192, 205, gfx_fmt("Cost: %d", plant_defs[k].cost), rgb565(0x3A2410), 0);+ gfx_text(F_SMALL, 298, 205,+ gfx_fmt("Recharge: %s", plant_defs[k].cooldown >= 5000 ? "very slow" : plant_defs[k].cooldown >= 3000 ? "slow" : "fast"),+ rgb565(0x3A2410), GFX_RIGHT);+ } else+ gfx_text(F_HEAD, 245, 110, "???", rgb565(0x3A2410), GFX_CENTER);+ } else {+ gfx_text(F_HEAD, 86, 24, "Zombies", rgb565(0x5A3A1E), GFX_CENTER);+ for (int i = 0; i < N_ZOMBIES; i++) {+ int x = 6 + (i % 6) * 28, y = 30 + (i / 6) * 46;+ gfx_round_rect(x, y, 26, 42, 3, i == sel ? rgb565(0xC88A4A) : rgb565(0x9A7A50), 32);+ if (zombie_seen(i)) gfx_anim_scaled(I_PORTRAIT_NORMAL + i, 0, x + 13, y + 40, 112, 112, 0, TINT_NONE, 32);+ else gfx_text(F_HEAD, x + 13, y + 26, "?", rgb565(0x5A3A1E), GFX_CENTER);+ }+ int k = sel;+ gfx_round_rect(176, 14, 140, 216, 6, rgb565(0x4A4E66), 32);+ gfx_round_rect(180, 18, 132, 208, 5, rgb565(0xF2E2C0), 32);+ if (zombie_seen(k)) {+ gfx_rect(194, 22, 104, 88, rgb565(0x2E3A2A), 32);+ gfx_clip(194, 22, 104, 88);+ gfx_image(I_PORTRAIT_NORMAL + k, 246, 108);+ gfx_clip_all();+ gfx_text(F_HEAD, 246, 124, zombie_defs[k].name, rgb565(0x3A2410), GFX_CENTER);+ int y = gfx_paragraph(F_SMALL, 246, 136, 124, zombie_blurbs[k], rgb565(0x3A2410), 0);+ gfx_paragraph(F_SMALL, 246, y + 2, 124, zombie_stats[k], rgb565(0x7A2010), 0);+ } else+ gfx_text(F_HEAD, 246, 120, "???", rgb565(0x3A2410), GFX_CENTER);+ }+ gfx_text(F_SMALL, 86, 232, "Back: the Almanac's index", rgb565(0x5A3A1E), GFX_CENTER);+}++static void draw_shop(void) {+ show_back(BG_SHOP);+ gfx_image(I_DAVE, 6, 64);+ static const char *const names[5] = {"Extra Seed Slot", "Pool Cleaner", "Roof Cleaner", "Rake", "Wall-nut First Aid"};+ static const char *const what[5] = {+ "Lets you take one more seed into each level.", "Clears a pool lane of zombies, like a lawn mower.",+ "Clears a roof lane of zombies, like a lawn mower.", "Whacks the first zombie that steps on it. Three uses.",+ "Plant wall-nuts, tall-nuts and pumpkins over worn ones to make them whole again."};+ static const uint32_t slot_cost[4] = {750, 5000, 20000, 80000};+ static const uint16_t icons[5] = {I_SHOP_SLOTS, I_POOL_CLEANER, I_SHOP_ROOF, I_SHOP_RAKE, I_SHOP_FIRSTAID};+ gfx_round_rect(84, 100, 232, 70, 6, rgb565(0x6A4424), 32);+ gfx_round_rect(87, 103, 226, 64, 5, rgb565(0x8A5A2E), 32);+ for (int i = 0; i < 5; i++) {+ int x = 92 + i * 45, y = 108;+ bool sold = (i == 0 && progress.slots >= 10) || (i == 1 && (progress.items & ITEM_POOL_CLEANER)) ||+ (i == 2 && (progress.items & ITEM_ROOF_CLEANER)) || (i == 3 && progress.rakes) ||+ (i == 4 && (progress.items & ITEM_FIRST_AID));+ bool avail = i == 0 || i == 3 || (i == 2 ? progress.level > 41 : progress.level > 21) || progress.finished;+ uint32_t cost = i == 0 ? (progress.slots < 10 ? slot_cost[progress.slots - 6] : 0) : i == 1 ? 1000 : i == 2 ? 3000 : i == 3 ? 200 : 2000;+ gfx_round_rect(x, y, 40, 54, 4, i == sel ? rgb565(0xF2C94C) : rgb565(0xE8D8B0), 32);+ if (i == 1) gfx_anim(icons[i], 0, x + 20, y + 34, 0, avail ? TINT_NONE : TINT_GRAY, 32);+ else gfx_anim(icons[i], 0, x + 20 - 13, y + 8, 0, avail ? TINT_NONE : TINT_GRAY, 32);+ gfx_text(F_SMALL, x + 20, y + 49, sold ? "SOLD" : avail ? gfx_fmt("$%u", (unsigned)cost) : "Soon", rgb565(0x3A2410),+ GFX_CENTER);+ }+ gfx_round_rect(84, 176, 232, 50, 8, C_WHITE, 32);+ gfx_text(F_HEAD, 200, 190, names[sel], rgb565(0x3A2410), GFX_CENTER);+ gfx_paragraph(F_SMALL, 200, 202, 220, what[sel], rgb565(0x3A2410), 0);+ draw_money(214, 8, progress.money);+ gfx_text(F_BIG, 150, 30, "Crazy Dave's", rgb565(0xF2C94C), GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_HEAD, 150, 50, "Twiddydinkies", rgb565(0xF2C94C), GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_SMALL, 200, 236, "OK: buy Back: menu", C_WHITE, GFX_CENTER | GFX_OUTLINE);+}++static void draw_help(void) {+ show_back(BG_ALMANAC);+ gfx_text(F_BIG, 160, 34, "How to Play", rgb565(0x5A3A1E), GFX_CENTER);+ static const char *const keys[][2] = {+ {"Arrows", "Move over the lawn"},+ {"1 2 3 ... 0", "Pick a seed packet"},+ {"OK", "Plant it (or whack, or break a vase)"},+ {"Cursor", "Moving over sun and coins picks them up"},+ {"Delete", "The shovel: then OK digs up a plant"},+ {"Back", "Put the seed back, or pause"},+ {"Toolbox", "The Almanac (in the menu)"},+ {"Home", "Save and quit"},+ };+ for (int i = 0; i < 8; i++) {+ int y = 62 + i * 19;+ gfx_text(F_HEAD, 116, y, keys[i][0], rgb565(0x7A2010), GFX_RIGHT);+ gfx_text(F_BODY, 126, y, keys[i][1], rgb565(0x3A2410), 0);+ }+ gfx_text(F_SMALL, 160, 226, "OK: back", rgb565(0x5A3A1E), GFX_CENTER);+}++void game_draw(void) {+ gfx_begin();+ switch (g_state) {+ case ST_TITLE:+ show_back(BG_MENU);+ gfx_rect(0, 0, SCREEN_W, SCREEN_H, 0, 8);+ gfx_image(I_LOGO, 20, 50);+ if ((vis_ticks / 50) % 2)+ gfx_text(F_HEAD, 160, 200, "Press OK to start!", rgb565(0xFFE14A), GFX_CENTER | GFX_OUTLINE);+ gfx_text(F_SMALL, 160, 232, "A fan version of PopCap's game, for the NumWorks calculator", C_WHITE,+ GFX_CENTER | GFX_OUTLINE);+ break;+ case ST_MENU: draw_menu(); break;+ case ST_LEVELS: draw_levels(); break;+ case ST_DAVE: draw_dave(); break;+ case ST_PAN:+ show_lawn(sod_t >= 0 ? (sod_t * 3 > 320 ? 320 : sod_t * 3) : -1);+ if (cam_x > 0) draw_street(street, nstreet);+ draw_lawn(false);+ if (cam_x > 300 && pan_to > pan_from)+ gfx_text(F_HEAD, 160, 220, gfx_fmt("Level %d-%d", level_world(B.level), level_stage(B.level)), C_WHITE,+ GFX_CENTER | GFX_OUTLINE);+ break;+ case ST_CHOOSE: draw_chooser(); break;+ case ST_READY:+ draw_lawn(true);+ hud_draw(false);+ draw_ready(state_t);+ break;+ case ST_PLAY:+ draw_lawn(true);+ hud_draw(true);+ if (B.tutorial == 4) draw_message_band("Dig up the three peashooters: the delete key, then OK on each!");+ break;+ case ST_PAUSE: draw_pause(); break;+ case ST_WON: draw_won(); break;+ case ST_AWARD: draw_award(); break;+ case ST_LOST: draw_lost(); break;+ case ST_ALMANAC: draw_almanac(); break;+ case ST_SHOP: draw_shop(); break;+ case ST_HELP: draw_help(); break;+ }+ gfx_end();+}diff --git a/games/pvz/src/screens.h b/games/pvz/src/screens.hnew file mode 100644index 00000000..61f27528--- /dev/null+++ b/games/pvz/src/screens.h@@ -0,0 +1,16 @@+/* Plants vs. Zombies: the screens, from the title to the lawn and back (screens.c). */+#ifndef PVZ_SCREENS_H+#define PVZ_SCREENS_H+#include <stdbool.h>+#include <stdint.h>++void game_init(void);+void game_frame(uint32_t keys); /* a hundredth of a second */+void game_draw(void);+extern bool g_running;+extern int g_state;+enum {+ ST_TITLE, ST_MENU, ST_LEVELS, ST_DAVE, ST_PAN, ST_CHOOSE, ST_READY, ST_PLAY, ST_PAUSE, ST_WON, ST_AWARD, ST_LOST,+ ST_ALMANAC, ST_SHOP, ST_HELP+};+#endifdiff --git a/games/pvz/tests/play.c b/games/pvz/tests/play.cnew file mode 100644index 00000000..bd6c9686--- /dev/null+++ b/games/pvz/tests/play.c@@ -0,0 +1,283 @@+/* Plays Plants vs. Zombies on a computer, and saves frames.+ *+ * play [--frames N] [--keys "10-40:right,50:ok,..."] [--shots 30,60|every:N] [--out DIR] [--saves DIR]+ * [--progress L] [--money M]+ * play --sim L [--frames N] [--shots ...] [--out DIR] [--quiet]+ *+ * Keys: left right up down ok back shovel home almanac 0-9. "a-b:key" holds the key from tick a to b, "a:key" for+ * one tick (ticks are hundredths of a second; a frame is drawn every 3).+ * --progress L sets the adventure at level L with what it has found by then (then the menus play as scripted).+ * --sim L plays level L straight away, a robot planting (with all the sun it wants, so that every level's zombies+ * come and go): it prints how the level went and fails if it isn't won. Screenshots are DIR/shot_<tick>.ppm. */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include "../src/draw.h"+#include "../src/game.h"+#include "../src/gfx.h"+#include "../src/res.h"+#include "../src/save.h"+#include "../src/screens.h"++extern uint32_t host_keys, host_time;+extern uint16_t host_fb[SCREEN_W * SCREEN_H];+void host_shot(const char *path);+void host_save_dir(const char *d);+extern const uint8_t pvz_data[];+extern const uint8_t *pvz_bin;+const uint8_t *pvz_bin;++typedef struct { int a, b; uint32_t k; } Hold;+static Hold holds[4096];+static int nholds;++static uint32_t key_named(const char *s) {+ static const struct { const char *n; uint32_t k; } t[] = {+ {"left", K_LEFT}, {"right", K_RIGHT}, {"up", K_UP}, {"down", K_DOWN}, {"ok", K_OK}, {"back", K_BACK},+ {"shovel", K_SHOVEL}, {"home", K_HOME}, {"almanac", K_ALMANAC},+ };+ for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++)+ if (!strcmp(s, t[i].n)) return t[i].k;+ if (s[0] >= '0' && s[0] <= '9' && !s[1]) return K_DIGIT(s[0] == '0' ? 10 : s[0] - '0');+ fprintf(stderr, "unknown key %s\n", s);+ exit(2);+}++static void parse_keys(const char *spec) {+ char buf[65536];+ snprintf(buf, sizeof buf, "%s", spec);+ for (char *tok = strtok(buf, ","); tok; tok = strtok(NULL, ",")) {+ char *colon = strchr(tok, ':');+ if (!colon) continue;+ *colon = 0;+ int a, b;+ if (sscanf(tok, "%d-%d", &a, &b) != 2) b = a = atoi(tok);+ holds[nholds].a = a, holds[nholds].b = b, holds[nholds].k = key_named(colon + 1);+ if (nholds < 4095) nholds++;+ }+}++static int shots[1024], nshots_at, every;+static void parse_shots(const char *s) {+ if (!strncmp(s, "every:", 6)) {+ every = atoi(s + 6);+ return;+ }+ char buf[8192];+ snprintf(buf, sizeof buf, "%s", s);+ for (char *t = strtok(buf, ","); t && nshots_at < 1024; t = strtok(NULL, ",")) shots[nshots_at++] = atoi(t);+}+static bool shot_now(int tick) {+ if (every && tick % every == 0) return true;+ for (int i = 0; i < nshots_at; i++)+ if (shots[i] == tick) return true;+ return false;+}++/* ---------------------------------------------------------------- the robot */++static const int prefer[] = {P_SUNFLOWER, P_REPEATER, P_SNOWPEA, P_PEASHOOTER, P_THREEPEATER, P_MELONPULT, P_KERNELPULT,+ P_CABBAGEPULT, P_FUMESHROOM, P_STARFRUIT, P_TALLNUT, P_WALLNUT, P_CACTUS, P_PUMPKIN,+ P_PLANTERN, P_LILYPAD, P_FLOWERPOT, P_PUFFSHROOM, P_CHERRYBOMB, P_SQUASH, P_TORCHWOOD,+ P_SPIKEWEED, P_GRAVEBUSTER, P_UMBRELLA, P_MAGNETSHROOM, P_COFFEEBEAN, P_BLOVER, P_JALAPENO};++static void robot_seeds(int level) {+ if (B.nseeds || level_defs[level - 1].nseeds) return;+ uint8_t s[10];+ int n = 0;+ for (unsigned i = 0; i < sizeof prefer / sizeof prefer[0] && n < 10; i++) {+ int k = prefer[i];+ if (!plant_unlocked(k)) continue;+ if ((k == P_LILYPAD) && !is_pool()) continue;+ if (k == P_FLOWERPOT && B.env != ENV_ROOF) continue;+ if (k == P_GRAVEBUSTER && !B.ngraves) continue;+ if ((k == P_SPIKEWEED || k == P_GRAVEBUSTER) && B.env == ENV_ROOF) continue;+ if (k == P_PLANTERN && B.env != ENV_FOG) continue;+ if (k == P_COFFEEBEAN && is_night()) continue;+ s[n++] = (uint8_t)k;+ }+ board_set_seeds(s, n);+}++/* what the robot would like in a cell, in order (the first it can plant) */+static int want(int col, int row, int *kinds) {+ int n = 0;+ bool shooter_ok = B.env != ENV_ROOF;+ if (water_row(row)) kinds[n++] = P_LILYPAD;+ if (B.env == ENV_ROOF) kinds[n++] = P_FLOWERPOT;+ if (col == 0) kinds[n++] = P_SUNFLOWER, kinds[n++] = P_SUNSHROOM;+ if (col >= 1 && col <= 4) {+ if (shooter_ok) kinds[n++] = P_REPEATER, kinds[n++] = P_THREEPEATER, kinds[n++] = P_SNOWPEA, kinds[n++] = P_PEASHOOTER;+ kinds[n++] = P_MELONPULT, kinds[n++] = P_KERNELPULT, kinds[n++] = P_CABBAGEPULT;+ kinds[n++] = P_FUMESHROOM, kinds[n++] = P_STARFRUIT, kinds[n++] = P_CACTUS, kinds[n++] = P_PUFFSHROOM;+ kinds[n++] = P_SCAREDYSHROOM, kinds[n++] = P_SEASHROOM;+ }+ if (col == 5) kinds[n++] = P_TORCHWOOD, kinds[n++] = P_PLANTERN, kinds[n++] = P_UMBRELLA;+ if (col == 6) kinds[n++] = P_TALLNUT, kinds[n++] = P_WALLNUT, kinds[n++] = P_PUMPKIN;+ if (col == 7) kinds[n++] = P_SPIKEWEED, kinds[n++] = P_GRAVEBUSTER;+ kinds[n++] = P_COFFEEBEAN, kinds[n++] = P_PUMPKIN;+ return n;+}++static void robot(void) {+ if (B.phase != PH_PLAY) return;+ B.sun = 5000;+ /* sun and coins: picked up */+ board_collect(400, 300, 5000);+ if (B.mode == MODE_WHACK) {+ for (int i = 0; i < B.nzombies; i++)+ if (B.zombies[i].x < 700 && B.zombies[i].rise == 0 && (B.ticks + i) % 7 == 0)+ board_whack(B.zombies[i].x, row_y(B.zombies[i].row, B.zombies[i].x) - 40);+ for (int g = 0; g < B.ngraves; g++)+ for (int s = 0; s < B.nseeds; s++)+ if (B.seeds[s] == P_GRAVEBUSTER && !B.cooldown[s]) board_plant(s, B.graves[g].col, B.graves[g].row);+ return;+ }+ if (B.mode == MODE_VASE) {+ if (B.ndrops) {+ for (int r = 0; r < B.nrows; r++)+ for (int c = 0; c < 5 && B.ndrops; c++)+ if (!plant_issue(B.drops[0].kind, c, r)) board_plant(0, c, r);+ if (B.ndrops && B.drops[0].left < 50) B.drops[0] = B.drops[--B.ndrops];+ } else if (B.nvases && B.ticks % 120 == 0)+ board_break_vase(B.vases[0].col, B.vases[0].row);+ return;+ }+ if (has_conveyor()) {+ if (!B.npackets || B.ticks % 25) return;+ int kind = B.packets[0].kind;+ for (int r = 0; r < B.nrows; r++)+ for (int c = 0; c < (B.mode == MODE_BOWLING ? 3 : COLS - 2); c++) {+ int rr = (r + (int)(B.ticks / 25)) % B.nrows, cc = B.mode == MODE_BOWLING ? 2 : c;+ if (!plant_issue(kind, cc, rr) && board_plant(0, cc, rr)) return;+ }+ /* nowhere: dropped */+ memmove(&B.packets[0], &B.packets[1], (size_t)(B.npackets - 1) * sizeof B.packets[0]);+ B.npackets--;+ return;+ }+ /* plants: every cell, what it wants first */+ for (int r = 0; r < B.nrows; r++) {+ if (!(B.rows >> r & 1)) continue;+ for (int c = 0; c < 8; c++) {+ int kinds[24], n = want(c, r, kinds);+ for (int k = 0; k < n; k++)+ for (int s = 0; s < B.nseeds; s++)+ if (B.seeds[s] == kinds[k] && !B.cooldown[s] && !plant_issue(kinds[k], c, r)) {+ board_plant(s, c, r);+ goto next;+ }+ next:;+ }+ }+ /* a cherry bomb where the zombies are thickest */+ for (int s = 0; s < B.nseeds; s++) {+ if ((B.seeds[s] != P_CHERRYBOMB && B.seeds[s] != P_JALAPENO) || B.cooldown[s]) continue;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if (z->x < 500 && z->x > 100 && !(z->flags & ZF_HYPNO)) {+ int c = col_at(z->x);+ if (!plant_issue(B.seeds[s], c, z->row)) board_plant(s, c, z->row);+ break;+ }+ }+ }+}++static int sim(int level, int frames, const char *out, bool quiet) {+ progress_load();+ progress.level = (uint8_t)level, progress.slots = 10, progress.items = 0x7F;+ board_start(level);+ robot_seeds(level);+ B.phase = PH_PLAY;+ cam_x = 0;+ int bg = B.env == ENV_NIGHT ? BG_NIGHT : B.env == ENV_POOL ? BG_POOL : B.env == ENV_FOG ? BG_FOG+ : B.env == ENV_ROOF ? BG_ROOF : BG_LAWN;+ gfx_load_back(bg, 88);+ int t;+ int most = 0;+ for (t = 0; t < frames && B.phase == PH_PLAY; t++) {+ robot();+ board_tick();+ vis_ticks++;+ if (B.nzombies > most) most = B.nzombies;+ if (shot_now(t)) {+ gfx_begin();+ draw_lawn(true);+ hud.col = -10;+ hud_draw(false);+ gfx_end();+ char p[512];+ snprintf(p, sizeof p, "%s/shot_%06d.ppm", out, t);+ host_shot(p);+ }+ }+ const char *how = B.phase == PH_WON ? "won" : B.phase == PH_LOST ? "LOST" : "UNFINISHED";+ if (!quiet || B.phase != PH_WON)+ printf("level %2d-%-2d %-10s ticks %6d waves %2d/%-2d kills %4d planted %3d most zombies %d\n", level_world(level),+ level_stage(level), how, t, B.wave, B.nwaves, B.kills, B.planted, most);+ return B.phase == PH_WON ? 0 : 1;+}++int main(int argc, char **argv) {+ int frames = 2000, simlevel = 0, prog = 0;+ long money = -1;+ bool quiet = false;+ const char *out = "build/shots", *saves = "build/host-saves";+ for (int i = 1; i < argc; i++) {+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) frames = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) parse_keys(argv[++i]);+ else if (!strcmp(argv[i], "--shots") && i + 1 < argc) parse_shots(argv[++i]);+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i];+ else if (!strcmp(argv[i], "--saves") && i + 1 < argc) saves = argv[++i];+ else if (!strcmp(argv[i], "--sim") && i + 1 < argc) simlevel = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--progress") && i + 1 < argc) prog = atoi(argv[++i]);+ else if (!strcmp(argv[i], "--money") && i + 1 < argc) money = atol(argv[++i]);+ else if (!strcmp(argv[i], "--quiet")) quiet = true;+ }+ mkdir(out, 0755);+ mkdir(saves, 0755);+ host_save_dir(saves);+ static uint16_t band[SCREEN_W * GFX_BAND];+ gfx_set_band_memory(band);+ pvz_bin = pvz_data;+ B.rng = 20251019;+ if (simlevel) {+ if (simlevel < 0) {+ int bad = 0;+ for (int l = 1; l <= N_LEVELS; l++) B.rng = (uint32_t)(l * 7919), bad += sim(l, frames, out, quiet);+ printf("%d of %d levels not won\n", bad, N_LEVELS);+ return bad ? 1 : 0;+ }+ return sim(simlevel, frames, out, quiet);+ }+ game_init();+ if (prog) {+ progress.level = (uint8_t)prog, progress.slots = 6;+ for (int l = 1; l < prog; l++) {+ int r = level_defs[l - 1].reward;+ if (r == REWARD_SHOVEL) progress.items |= ITEM_SHOVEL;+ if (r == REWARD_ALMANAC) progress.items |= ITEM_ALMANAC;+ if (r == REWARD_KEYS) progress.items |= ITEM_SHOP;+ }+ }+ if (money >= 0) progress.money = (uint32_t)money;+ for (int t = 0; t < frames && g_running; t++) {+ host_keys = 0;+ for (int i = 0; i < nholds; i++)+ if (t >= holds[i].a && t <= holds[i].b) host_keys |= holds[i].k;+ if (host_keys) host_keys |= K_ANY;+ game_frame(host_keys);+ host_time += 10;+ if (t % 3 == 0 || shot_now(t)) game_draw();+ if (shot_now(t)) {+ char p[512];+ snprintf(p, sizeof p, "%s/shot_%06d.ppm", out, t);+ host_shot(p);+ }+ }+ printf("state %d level %d phase %d sun %d zombies %d plants %d wave %d/%d\n", g_state, B.level, B.phase, (int)B.sun,+ B.nzombies, B.nplants, B.wave, B.nwaves);+ return 0;+}diff --git a/games/pvz/tests/sheet.py b/games/pvz/tests/sheet.pynew file mode 100644index 00000000..fe451142--- /dev/null+++ b/games/pvz/tests/sheet.py@@ -0,0 +1,15 @@+#!/usr/bin/env python3+"""Puts screenshots (PPM or PNG) side by side, scaled up: sheet.py OUT.png COLS FILE..."""+import sys++from PIL import Image++out, cols, files = sys.argv[1], int(sys.argv[2]), sys.argv[3:]+ims = [Image.open(f).convert("RGB") for f in files]+w, h = ims[0].size+rows = (len(ims) + cols - 1) // cols+sheet = Image.new("RGB", (cols * w, rows * h))+for i, im in enumerate(ims):+ sheet.paste(im, ((i % cols) * w, (i // cols) * h))+scale = 2 if cols * w <= 700 else 1+sheet.resize((sheet.width * scale, sheet.height * scale), Image.NEAREST).save(out)diff --git a/games/pvz/tools/pack.py b/games/pvz/tools/pack.pyindex d95db1ee..1b02700f 100644--- a/games/pvz/tools/pack.py+++ b/games/pvz/tools/pack.py@@ -5,7 +5,7 @@The game is drawn at 0.4 of its own size: its 800 x 600 screen becomes the calculator's 320 x 240.-data.bin: "PVZ1", the offsets (u32) of its 5 tables, the number of animations, frames, and the file's size (u32 x 3),+data.bin: "PVZ1", the offsets (u32) of its 6 tables, the number of animations, frames, and the file's size (u32 x 3),then the tables (offsets are from the start of the file):- ANIMS: 12 bytes each (A_* and I_* in data.h): first frame, palette, the time a loop takes in hundredths of asecond, the animation it is drawn over (u16 x 4; 0xFFFF none: an overlay holds only what differs from the@@ -21,6 +21,13 @@ then the tables (offsets are from the start of the file):offsets (u32). Each chunk (one offset more for the end) is w x rows colour indices, raw DEFLATE- FONTS: the offset (u32) of each (F_*): first character, count, ascent, descent (u8 x 4), then 8 bytes a glyph(w, h, x, y, advance, 0, its data's offset u16 from the glyphs' end): 4-bit coverage, 2 pixels a byte+- BOSS: Dr. Zomboss's Zombot as the game draws it, from parts the .reanim moves: the parts' table and the 4 rigs'+ offsets (u32 x 5). Parts: their number (u32), then 12 bytes each: w, h, palette (u16 x 3), 0 (u16), its pixels'+ offset (u32): rows of 4-bit colour indices (0 transparent), the first pixel lowest. A rig (the Zombot, its driver,+ the fire ball, the ice ball): tracks, frames kept, the frames' step (from the .reanim's), the track the driver is+ fixed to (u16 x 4), then a flag for each track (u8: 1 the arm and RV the attacks move), padded to 4, then for each+ frame its offset (u32): which tracks show (a bit each), then their poses, 14 bytes each: x, y in eighths of a pixel,+ scales in 4096ths, skews in sixteenths of a degree (s16 x 6), the part, the opacity (u8 x 2)"""import jsonimport os@@ -47,51 +54,51 @@ NONE = 0xFFFFDEFAULT_KEEP = 8ANIMS = {# zombies: a headless body, and the heads and hats over it- "zombie-headless": (14, None), "zombie-walk": (14, "zombie-headless"), "cone-walk": (14, "zombie-headless"),- "bucket-walk": (14, "zombie-headless"), "flag-walk": (12, None), "zombie-eat": (10, None),- "cone-eat": (10, "zombie-eat"), "bucket-eat": (10, "zombie-eat"), "flag-eat": (8, None),- "zombie-die": (10, None), "zombie-burn": (6, None),- "pole-headless": (12, None), "pole-walk": (12, "pole-headless"), "pole-run": (12, None), "pole-jump": (10, None),- "pole-land": (5, None), "pole-eat": (8, None), "pole-die": (8, None), "pole-burn": (6, None),- "newspaper-headless": (10, None), "newspaper-walk": (10, "newspaper-headless"),- "newspaper-mad-walk": (10, "newspaper-headless"), "newspaper-mad-eat": (8, None),- "newspaper-eat": (8, "newspaper-mad-eat"), "newspaper-gasp": (6, None), "newspaper-die": (8, None),+ "zombie-headless": (12, None), "zombie-walk": (12, "zombie-headless"), "cone-walk": (12, "zombie-headless"),+ "bucket-walk": (12, "zombie-headless"), "flag-walk": (10, None), "zombie-eat": (8, None),+ "cone-eat": (8, "zombie-eat"), "bucket-eat": (8, "zombie-eat"), "flag-eat": (7, None),+ "zombie-die": (8, None), "zombie-burn": (6, None),+ "pole-headless": (10, None), "pole-walk": (10, "pole-headless"), "pole-run": (10, None), "pole-jump": (8, None),+ "pole-land": (5, None), "pole-eat": (7, None), "pole-die": (7, None), "pole-burn": (6, None),+ "newspaper-headless": (8, None), "newspaper-walk": (8, "newspaper-headless"),+ "newspaper-mad-walk": (8, "newspaper-headless"), "newspaper-mad-eat": (7, None),+ "newspaper-eat": (7, "newspaper-mad-eat"), "newspaper-gasp": (6, None), "newspaper-die": (7, None),"newspaper-burn": (6, None),- "door-walk": (10, None), "door-eat": (8, None),- "football-headless": (10, None), "football-walk": (10, "football-headless"),- "football-bare-walk": (10, "football-headless"), "football-bare-eat": (8, None),- "football-eat": (8, "football-bare-eat"), "football-die": (8, None),- "dancer-walk": (10, None), "dancer-eat": (8, None), "dancer-summon": (7, None), "dancer-headless": (8, None),- "dancer-die": (8, None), "dancer-burn": (6, None),- "backup-walk": (10, None), "backup-eat": (8, None), "backup-headless": (8, None), "backup-die": (8, None),+ "door-walk": (8, None), "door-eat": (7, None),+ "football-headless": (8, None), "football-walk": (8, "football-headless"),+ "football-bare-walk": (8, "football-headless"), "football-bare-eat": (7, None),+ "football-eat": (7, "football-bare-eat"), "football-die": (7, None),+ "dancer-walk": (8, None), "dancer-eat": (7, None), "dancer-summon": (7, None), "dancer-headless": (8, None),+ "dancer-die": (7, None), "dancer-burn": (6, None),+ "backup-walk": (8, None), "backup-eat": (7, None), "backup-headless": (8, None), "backup-die": (7, None),"backup-burn": (6, None),- "ducky1-walk": (10, None), "ducky2-walk": (10, "ducky1-walk"), "ducky3-walk": (10, "ducky1-walk"),- "ducky1-eat": (8, None), "ducky2-eat": (8, "ducky1-eat"), "ducky3-eat": (8, "ducky1-eat"), "ducky-die": (8, None),- "snorkel-walk": (10, None), "snorkel-swim": (4, None), "snorkel-eat": (8, None), "snorkel-die": (8, None),+ "ducky1-walk": (8, None), "ducky2-walk": (8, "ducky1-walk"), "ducky3-walk": (8, "ducky1-walk"),+ "ducky1-eat": (7, None), "ducky2-eat": (7, "ducky1-eat"), "ducky3-eat": (7, "ducky1-eat"), "ducky-die": (7, None),+ "snorkel-walk": (8, None), "snorkel-swim": (4, None), "snorkel-eat": (7, None), "snorkel-die": (7, None),"zomboni-walk": (4, None), "zomboni-damaged": (3, None), "zomboni-critical": (3, None), "zomboni-die": (4, None),- "bobsled-walk": (8, None), "bobsled-eat": (8, None), "bobsled-die": (8, None),- "dolphin-walk": (10, None), "dolphin-ride": (4, None), "dolphin-jump": (8, None), "dolphin-swim": (10, None),- "dolphin-eat": (8, None), "dolphin-die": (6, None),- "jack-walk": (10, None), "jack-eat": (8, None), "jack-open": (8, None), "jack-headless": (8, None),- "jack-die": (8, None),- "balloon-fly": (8, None), "balloon-pop": (8, None), "balloon-walk": (10, None), "balloon-eat": (8, None),- "balloon-die": (8, None),- "digger-dig": (6, None), "digger-rise": (8, None), "digger-walk": (10, None), "digger-eat": (8, None),- "digger-die": (8, None),- "pogo-bounce": (8, None), "pogo-walk": (8, None), "pogo-eat": (8, None), "pogo-die": (8, None),+ "bobsled-walk": (8, None), "bobsled-eat": (7, None), "bobsled-die": (7, None),+ "dolphin-walk": (8, None), "dolphin-ride": (4, None), "dolphin-jump": (8, None), "dolphin-swim": (8, None),+ "dolphin-eat": (7, None), "dolphin-die": (6, None),+ "jack-walk": (8, None), "jack-eat": (7, None), "jack-open": (8, None), "jack-headless": (8, None),+ "jack-die": (7, None),+ "balloon-fly": (8, None), "balloon-pop": (8, None), "balloon-walk": (8, None), "balloon-eat": (7, None),+ "balloon-die": (7, None),+ "digger-dig": (6, None), "digger-rise": (8, None), "digger-walk": (8, None), "digger-eat": (7, None),+ "digger-die": (7, None),+ "pogo-bounce": (8, None), "pogo-walk": (8, None), "pogo-eat": (7, None), "pogo-die": (7, None),"bungee-drop": (4, None), "bungee-idle": (8, None), "bungee-die": (6, None),- "ladder-bare": (10, None), "ladder-walk": (10, "ladder-bare"), "ladder-place": (6, None), "ladder-eat": (8, None),- "ladder-die": (8, None),- "catapult-walk": (5, None), "catapult-idle": (3, None), "catapult-shoot": (8, None), "catapult-die": (5, None),- "gargantuar-bare-walk": (8, None), "gargantuar-walk": (8, "gargantuar-bare-walk"),- "gargantuar-bare-smash": (7, None), "gargantuar-smash": (7, "gargantuar-bare-smash"), "gargantuar-throw": (7, None),- "gargantuar-bare-die": (7, None), "gargantuar-die": (7, "gargantuar-bare-die"),- "imp-thrown": (6, None), "imp-land": (4, None), "imp-walk": (10, None), "imp-eat": (8, None), "imp-die": (8, None),+ "ladder-bare": (8, None), "ladder-walk": (8, "ladder-bare"), "ladder-place": (6, None), "ladder-eat": (7, None),+ "ladder-die": (7, None),+ "catapult-walk": (3, None), "catapult-idle": (3, None), "catapult-shoot": (6, None), "catapult-die": (3, None),+ "gargantuar-bare-walk": (6, None), "gargantuar-walk": (6, "gargantuar-bare-walk"),+ "gargantuar-bare-smash": (5, None), "gargantuar-smash": (5, "gargantuar-bare-smash"), "gargantuar-throw": (5, None),+ "gargantuar-bare-die": (5, None), "gargantuar-die": (5, "gargantuar-bare-die"),+ "imp-thrown": (6, None), "imp-land": (4, None), "imp-walk": (8, None), "imp-eat": (7, None), "imp-die": (7, None),# plants- "peashooter": (12, None), "sunflower": (12, None), "cherrybomb": (8, None), "wallnut": (8, None),+ "peashooter": (10, None), "sunflower": (10, None), "cherrybomb": (8, None), "wallnut": (8, None),"wallnut-cracked1": (8, "wallnut"), "wallnut-cracked2": (8, "wallnut"), "wallnut-roll": (8, None),- "explodenut": (4, None), "potatomine": (6, None), "potatomine-unarmed": (1, None), "snowpea": (10, None),- "chomper": (10, None), "chomper-bite": (9, None), "chomper-digest": (6, None), "repeater": (10, None),+ "explodenut": (4, None), "potatomine": (6, None), "potatomine-unarmed": (1, None), "snowpea": (8, None),+ "chomper": (8, None), "chomper-bite": (9, None), "chomper-digest": (6, None), "repeater": (8, None),"puffshroom": (8, None), "sunshroom": (8, None), "sunshroom-big": (8, None), "fumeshroom": (8, None),"fumeshroom-attack": (1, None), "fume-cloud": (6, None), "gravebuster": (8, None), "hypnoshroom": (8, None),"scaredyshroom": (8, None), "scaredyshroom-scared": (6, None), "iceshroom": (8, None), "doomshroom": (8, None),@@ -106,7 +113,7 @@ ANIMS = {"kernelpult-attack": (8, None), "coffeebean": (8, None), "garlic": (6, None), "garlic-cracked1": (6, "garlic"),"garlic-cracked2": (6, "garlic"), "umbrella": (8, None), "umbrella-block": (4, None), "marigold": (8, None),"melonpult": (8, None), "melonpult-attack": (8, None),- "sun": (11, None),+ "sun": (9, None),}# the plants, in the Almanac's order: their seed packets' pictures and their Almanac portraitsPLANTS = ["peashooter", "sunflower", "cherrybomb", "wallnut", "potatomine", "snowpea", "chomper", "repeater",@@ -288,6 +295,7 @@ class Pack:self.fonts = [] # (key, bytes)self.names = {}self.scaled = {} # name -> its frames before trimming (for overlays)+ self.boss = b""def palette(self, pal):self.pals.append([rgb565(c) for c in pal])@@ -316,13 +324,18 @@ class Pack:def add_image(self, name, arr, x0=0, y0=0, ncolors=16):return self.add_anim("I_" + name.upper().replace("-", "_"), [(arr, x0, y0)], 0, ncolors)- def add_back(self, name, img, ncolors=128, rows=16):+ def add_back(self, name, img, ncolors=128, rows=16, shared=None):+ """shared: (palette, its index) from an earlier background, for pictures drawn into each other"""img = img.convert("RGB")w, h = img.size- px = np.asarray(img).reshape(-1, 3).astype(np.float32)- pal = kmeans_palette(px, ncolors, iters=5)+ if shared:+ pal, p = shared+ else:+ px = np.asarray(img).reshape(-1, 3).astype(np.float32)+ pal = kmeans_palette(px, ncolors, iters=5)+ p = self.palette(pal)idx = index_pixels(np.asarray(img), pal).astype(np.uint8)- p = self.palette(pal)+ self.last_palette = (pal, p)chunks = [deflate(idx[y:y + rows].tobytes()) for y in range(0, h, rows)]key = "BG_" + name.upper().replace("-", "_")self.names[key] = len(self.backs)@@ -357,7 +370,7 @@ class Pack:print(f"font {key}: cap {cap}, ascent {asc}, descent {desc}, {len(blob)} bytes")def write(self):- out = bytearray(b"PVZ1" + bytes(4 * 8))+ out = bytearray(b"PVZ1" + bytes(4 * 9))def align():while len(out) % 4:@@ -404,7 +417,10 @@ class Pack:struct.pack_into("<I", out, font_at + 4 * i, len(out))out += blobalign()- struct.pack_into("<5I3I", out, 4, *tables, len(self.anims), len(self.frames), len(out))+ tables.append(len(out))+ out += self.boss+ align()+ struct.pack_into("<6I3I", out, 4, *tables, len(self.anims), len(self.frames), len(out))with open(OUT_BIN, "wb") as f:f.write(out)lines = ["/* Generated by tools/pack.py: what data.bin holds. */", "#ifndef PVZ_DATA_H", "#define PVZ_DATA_H",@@ -535,9 +551,94 @@ def centred(img, scale, ax=0.5, ay=0.5):return premul_resize(img, (sw, sh)), -int(round(sw * ax)), -int(round(sh * ay))+BOSS_PART = 0.16 # of the parts' pictures (twice the game's size): drawn 1.25 times bigger+BOSS_SKIP = ("MULTIPLY", "ADDITIVE", "SUPERGLOW", "HIGHLIGHT", "ICEFIRE_SHADOW")+++def pack_boss(P, ref):+ """the Zombot's parts and its rigs' tracks (see BOSS above)"""+ d = json.load(open(os.path.join(ref, "pvz", "runtime", "boss", "tracks.json")))+ names = sorted({p[8] for rig in d.values() for t in rig["tracks"] for p in t["poses"] if p[8]})+ names = [n for n in names if not any(k in n for k in BOSS_SKIP)]+ part_id = {n: i for i, n in enumerate(names)}+ parts = []+ for n in names:+ im = Image.open(os.path.join(ref, "pvz", "runtime", "boss", n + ".webp")).convert("RGBA")+ w, h = im.size+ arr = premul_resize(im, (max(1, int(round(w * BOSS_PART))), max(1, int(round(h * BOSS_PART)))))+ px = arr[arr[..., 3] >= 0.5][:, :3] * 255+ pal = kmeans_palette(px, 15)+ idx = index_pixels(arr[..., :3] * 255, pal) + 1+ idx[arr[..., 3] < 0.5] = 0+ p = P.palette(np.concatenate([np.zeros((1, 3), np.float32), pal]))+ rows = b""+ for y in range(idx.shape[0]):+ r = list(idx[y]) + [0]+ rows += bytes(int(r[i]) | int(r[i + 1]) << 4 for i in range(0, idx.shape[1], 2))+ parts.append((idx.shape[1], idx.shape[0], p, rows))+ out = bytearray(bytes(4 * 5))++ def align():+ while len(out) % 4:+ out.append(0)+ struct.pack_into("<I", out, 0, len(out))+ table = len(out)+ out += struct.pack("<I", len(parts)) + bytes(12 * len(parts))+ for i, (w, h, p, rows) in enumerate(parts):+ align()+ struct.pack_into("<HHHHI", out, table + 4 + 12 * i, w, h, p, 0, len(out))+ out += rows+ for r, key in enumerate(("body", "driver", "fire", "ice")):+ rig = d[key]+ tracks = rig["tracks"]+ nf = len(tracks[0]["poses"])+ step = 3+ head = next((i for i, t in enumerate(tracks) if t["name"] == "Boss_head2"), 0xFFFF)+ align()+ struct.pack_into("<I", out, 4 + 4 * r, len(out))+ kept = (nf + step - 1) // step+ out += struct.pack("<HHHH", len(tracks), kept, step, head)+ out += bytes(1 if t["name"].startswith(("Boss_innerarm", "Boss_RV")) else 0 for t in tracks)+ align()+ offs = len(out)+ out += bytes(4 * kept)+ for f in range(kept):+ align()+ struct.pack_into("<I", out, offs + 4 * f, len(out))+ mask = bytearray((len(tracks) + 7) // 8)+ poses = b""+ for i, t in enumerate(tracks):+ x, y, sx, sy, kx, ky, fr, al, img = t["poses"][f * step]+ if not img or fr < 0 or al <= 0 or img not in part_id:+ continue+ mask[i >> 3] |= 1 << (i & 7)+ poses += struct.pack("<hhhhhhBB", round(x * 8), round(y * 8), round(sx * 4096), round(sy * 4096),+ round(kx * 16), round(ky * 16), part_id[img], min(255, round(al * 255)))+ out += bytes(mask) + poses+ align()+ P.boss = bytes(out)+ print(f"boss: {len(parts)} parts, {len(out)} bytes")+++def make_icon(ref, at):+ """src/icon.png: a peashooter on the lawn, a zombie's head coming (rounded by NumPlay's tools/round_icons.py)"""+ lawn = Image.open(os.path.join(ref, "pvz", "lawn.jpg")).convert("RGB")+ icon = lawn.crop((420, 250, 420 + 165, 250 + 168)).resize((55, 56), Image.LANCZOS).convert("RGBA")+ for name, scale, x, y in (("zombie-walk", 0.42, 44, 66), ("peashooter", 0.62, 19, 50)):+ fr, _ = at.frames(name, 1, scale)+ arr, x0, y0 = fr[0]+ im = Image.fromarray((np.clip(arr, 0, 1) * 255).astype(np.uint8), "RGBA")+ icon.alpha_composite(im, (x + x0, y + y0))+ out = os.path.join(HERE, "..", "src", "icon.png")+ icon.save(out)+ import subprocess+ subprocess.run([sys.executable, os.path.join(HERE, "..", "..", "..", "tools", "round_icons.py"), out], check=True)++def main(ref):P = Pack()at = Atlas(ref)+ make_icon(ref, at)pvz = os.path.join(ref, "pvz")for name, (keep, base) in ANIMS.items():frames, cycle = at.frames(name, keep)@@ -617,14 +718,22 @@ def main(ref):# the lawns, whole (the screen shows 320 pixels of their 560, from 88), and the menus' backgroundslawns = {"lawn": "lawn.jpg", "yard": "yard.jpg", "night": "original/night.jpg", "pool": "original/pool.png",- "fog": "original/fog.png", "roof": "original/roof.png", "roof-night": "runtime/boss/background.webp"}+ "fog": "original/fog.png", "roof": "original/roof.png"}+ # (the day's lawn and its bare yard share a palette: levels 1-1 to 1-3 roll the lawn's sod over the yard)+ day = [Image.open(os.path.join(pvz, lawns[n])).convert("RGB").resize((560, 240), Image.LANCZOS) for n in ("lawn", "yard")]+ both = np.concatenate([np.asarray(im).reshape(-1, 3) for im in day]).astype(np.float32)+ shared = kmeans_palette(both, 160, iters=5)+ shared = (shared, P.palette(shared))for name, rel in lawns.items():- P.add_back(name, Image.open(os.path.join(pvz, rel)).resize((560, 240), Image.LANCZOS))+ img = day[0] if name == "lawn" else day[1] if name == "yard" else \+ Image.open(os.path.join(pvz, rel)).resize((560, 240), Image.LANCZOS)+ P.add_back(name, img, shared=shared if name in ("lawn", "yard") else None)for name, rel in [("menu", R + "menu.webp"), ("award", "original/award.jpg"),("almanac", "runtime/ui/challenge-background.webp"), ("shop", R + "shop-background.webp")]:P.add_back(name, Image.open(os.path.join(pvz, rel)).resize((320, 240), Image.LANCZOS))backs = sum(sum(len(c) for c in b[6]) for b in P.backs)+ pack_boss(P, ref)fonts = os.path.join(ref, "fonts")P.add_font("big", os.path.join(fonts, "RammettoOne.ttf"), 12)P.add_font("head", os.path.join(fonts, "RammettoOne.ttf"), 8, spacing=1)@@ -641,6 +750,9 @@ def main(ref):if __name__ == "__main__":+ if len(sys.argv) == 3 and sys.argv[2] == "--icon":+ make_icon(sys.argv[1], Atlas(sys.argv[1]))+ sys.exit(0)if len(sys.argv) != 2:raise SystemExit(__doc__)main(sys.argv[1])