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: the game's pictures packed, drawing, the lawn's rules begun
Mason3630a92b10111c9
diff --git a/games/pvz/.gitignore b/games/pvz/.gitignorenew file mode 100644index 00000000..643bd909--- /dev/null+++ b/games/pvz/.gitignore@@ -0,0 +1,3 @@+output/+build/+__pycache__/diff --git a/games/pvz/src/board.c b/games/pvz/src/board.cnew file mode 100644index 00000000..23316d79--- /dev/null+++ b/games/pvz/src/board.c@@ -0,0 +1,926 @@+/* The lawn: a level's start, its waves, sun, planting and digging (game.h). */+#include <string.h>+#include "game.h"+#include "save.h"++Board B;++/* ---------------------------------------------------------------- places */++float cell_h(void) { return B.env == ENV_POOL || B.env == ENV_FOG || B.env == ENV_ROOF ? 85 : 100; }+static float slope(float x) { return B.env == ENV_ROOF ? (x < 440 ? (440 - x) * 0.25f : 0) : 0; }+float row_y(int row, float x) {+ return BOARD_TOP + row * cell_h() + (B.env == ENV_ROOF ? 58 + slope(x) : is_pool() ? 68 : 78);+}+float cell_x(int col) { return BOARD_LEFT + col * CELL_W + 40; }+int row_at(float y, float x) {+ float r = (y - BOARD_TOP - slope(x) + (B.env == ENV_ROOF ? 10 : 0)) / cell_h();+ return r < 0 ? -1 : (int)r;+}+int col_at(float x) { return x < BOARD_LEFT ? -1 : (int)((x - BOARD_LEFT) / CELL_W); }+bool is_pool(void) { return B.env == ENV_POOL || B.env == ENV_FOG; }+bool is_night(void) { return B.env == ENV_NIGHT || B.env == ENV_FOG; }+bool water_row(int row) { return is_pool() && (row == 2 || row == 3); }+bool has_conveyor(void) { return B.mode == MODE_BOWLING || B.mode == MODE_CONVEYOR; }++/* ---------------------------------------------------------------- chance (the game's own: a linear congruence) */++uint32_t rnd(void) { return B.rng = B.rng * 1664525u + 1013904223u; }+float frand(void) { return (float)(rnd() >> 8) / 16777216.0f; }+int irand(int n) { return n > 0 ? (int)(frand() * n) : 0; }+uint16_t new_id(void) {+ if (!++B.next_id) B.next_id = 1;+ return B.next_id;+}++/* ---------------------------------------------------------------- lookups */++Plant *plant_at(int col, int row, int kind) {+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->col != col || p->row != row || p->health <= 0) continue;+ if (kind >= 0 ? p->kind == kind : p->kind != P_LILYPAD && p->kind != P_FLOWERPOT && p->kind != P_PUMPKIN) return p;+ }+ return NULL;+}+Zombie *zombie_by_id(uint16_t id) {+ for (int i = 0; i < B.nzombies; i++)+ if (B.zombies[i].id == id) return &B.zombies[i];+ return NULL;+}+bool sleeping(const Plant *p) {+ return !B.has_boss && !(p->flags & PF_AWAKE) && !is_night() && plant_defs[p->kind].mushroom;+}+int seed_kind(int slot) {+ if (has_conveyor()) return slot < B.npackets ? B.packets[slot].kind : -1;+ return slot < B.nseeds ? B.seeds[slot] : -1;+}+int plant_cost(int kind) { return plant_defs[kind].cost; }++/* ---------------------------------------------------------------- effects */++void fx_add(int kind, float x, float y, int life, int v) {+ if (B.nfx >= MAX_FX) {+ /* the oldest splat or puff gives its place */+ int k = -1;+ for (int i = 0; i < B.nfx; i++)+ if (B.fx[i].kind == FX_SPLAT || B.fx[i].kind == FX_DIRT || B.fx[i].kind == FX_SMOKE) k = i;+ if (k < 0) return;+ B.fx[k] = B.fx[--B.nfx];+ }+ Fx *f = &B.fx[B.nfx++];+ memset(f, 0, sizeof *f);+ f->kind = (uint8_t)kind, f->x = x, f->y = y, f->life = (int16_t)life, f->v = (int16_t)v;+}++/* ---------------------------------------------------------------- sun and coins */++void add_sun(float x, float y, float ty, int value, bool sky) {+ if (B.nsuns >= MAX_SUNS) return;+ Sun *s = &B.suns[B.nsuns++];+ s->x = x, s->y = y, s->ty = ty, s->left = 1200, s->value = (uint8_t)value, s->flags = sky;+}+void add_coin(float x, float y, int value) {+ if (B.ncoins >= MAX_COINS) return;+ Coin *c = &B.coins[B.ncoins++];+ c->x = x, c->y = y - 45, c->ty = y, c->left = 1500, c->value = (uint16_t)value;+}++int board_collect(float x, float y, float r) {+ int n = 0;+ for (int i = 0; i < B.nsuns; i++) {+ Sun *s = &B.suns[i];+ float dx = s->x - x, dy = s->y - y;+ if (dx * dx + dy * dy > r * r) continue;+ B.sun += s->value;+ fx_add(FX_SUNFLY, s->x, s->y, 50, s->value);+ B.suns[i--] = B.suns[--B.nsuns];+ n++;+ }+ for (int i = 0; i < B.ncoins; i++) {+ Coin *c = &B.coins[i];+ float dx = c->x - x, dy = c->y - y;+ if (dx * dx + dy * dy > r * r) continue;+ B.money += c->value;+ fx_add(FX_COINFLY, c->x, c->y, 60, c->value);+ B.coins[i--] = B.coins[--B.ncoins];+ n++;+ }+ return n;+}++/* ---------------------------------------------------------------- waves (Board::PickZombieWaves) */++int waves_flag_every(void) { return B.nwaves < 10 ? B.nwaves : 10; }+bool is_flag_wave(int wave) {+ int per = waves_flag_every();+ return B.level != 1 && per && wave % per == per - 1;+}++static void put(uint8_t *wave, int *n, int *points, int kind) {+ if (*n < 23) wave[(*n)++] = (uint8_t)kind;+ *points -= zombie_defs[kind].value;+}++static void generate_waves(void) {+ int L = B.level, count = B.nwaves;+ uint8_t allowed[N_ZOMBIES];+ int nallowed = 0, introduced = -1;+ for (int k = 0; k < N_ZOMBIES; k++) {+ const ZombieDef *d = &zombie_defs[k];+ bool ok = L == 25 ? (k == Z_NORMAL || k == Z_CONE || k == Z_FOOTBALL || k == Z_SNORKEL)+ : d->starting <= L && d->weight && (d->allowed >> (L - 1) & 1);+ if (ok) allowed[nallowed++] = (uint8_t)k;+ if (introduced < 0 && L > 1 && d->starting == L) introduced = k;+ }+ for (int w = 0; w < count && w < 50; w++) {+ uint8_t *wave = B.waves[w];+ int n = 0;+ memset(wave, 0xFF, 24);+ /* Bungee Blitz: every flag wave brings five bungee zombies */+ if (L == 45 && is_flag_wave(w)) {+ for (int i = 0; i < 5; i++) wave[n++] = Z_BUNGEE;+ if (w != count - 1) continue;+ }+ int points = w / 3 + 1;+ if (is_flag_wave(w)) {+ int normals = points < 8 ? points : 8;+ points = (int)(points * 2.5f);+ for (int i = 0; i < normals; i++) put(wave, &n, &points, Z_NORMAL);+ put(wave, &n, &points, Z_FLAG);+ }+ if (L == 5 || L == 25) points *= 4;+ if (L == 10 || L == 20 || L == 30 || L == 40) points *= 3;+ if (L == 45) points *= 2;+ if (introduced >= 0 &&+ (w == (introduced == Z_DIGGER ? 6 : count / 2) || w == count - 1))+ put(wave, &n, &points, introduced);+ if (w == count - 1)+ for (int i = 0; i < nallowed; i++) {+ bool there = false;+ for (int j = 0; j < n; j++) there |= wave[j] == allowed[i];+ if (!there) put(wave, &n, &points, allowed[i]);+ }+ while (points > 0 && n < 23) {+ int total = 0;+ for (int i = 0; i < nallowed; i++) {+ const ZombieDef *d = &zombie_defs[allowed[i]];+ if (d->value <= points && d->first_wave <= w + 1) total += d->weight;+ }+ if (!total) break;+ int pick = irand(total);+ for (int i = 0; i < nallowed; i++) {+ const ZombieDef *d = &zombie_defs[allowed[i]];+ if (d->value > points || d->first_wave > w + 1) continue;+ pick -= d->weight;+ if (pick < 0) {+ put(wave, &n, &points, allowed[i]);+ break;+ }+ }+ }+ }+}++/* Board::PickRowForNewZombie: rows weighed by how lately they had a zombie, and spared after a mower */+static int pick_row(uint8_t allowed) {+ float weight[MAX_ROWS], adj[MAX_ROWS], total = 0, sum = 0;+ for (int r = 0; r < B.nrows; r++) {+ weight[r] = 0;+ if (!(B.rows >> r & 1) || !(allowed >> r & 1)) continue;+ int since = B.wave - B.row_mowed[r];+ weight[r] = since <= 1 ? 0.01f : since <= 2 ? 0.5f : 1;+ total += weight[r];+ }+ if (total <= 0) {+ for (int r = 0; r < B.nrows; r++)+ if (allowed >> r & 1) return r;+ return 0;+ }+ for (int r = 0; r < B.nrows; r++) {+ float w = weight[r] / total;+ float first = 2 * w * (B.row_last[r] + 1) - 1, second = w * (B.row_second[r] + 1) - 1;+ float v = 0.75f * first + 0.25f * second;+ v = v < 0.01f ? 0.01f : v > 100 ? 100 : v;+ adj[r] = weight[r] > 0 ? w * v : 0;+ sum += adj[r];+ }+ float choice = frand() * sum;+ int pick = 0;+ while (pick < B.nrows - 1 && (adj[pick] == 0 || choice >= adj[pick])) choice -= adj[pick++];+ for (int r = 0; r < B.nrows; r++)+ if (B.row_last[r] < 250) B.row_last[r]++, B.row_second[r]++;+ B.row_second[pick] = B.row_last[pick], B.row_last[pick] = 0;+ return pick;+}++static bool ice_row(int row) { return B.ice[row].left > 0 && B.ice[row].x < 700; }++static void spawn_wave(void) {+ const uint8_t *wave = B.waves[B.wave];+ bool flag = is_flag_wave(B.wave);+ for (int i = 0; i < 24 && wave[i] != 0xFF; i++) {+ int kind = wave[i];+ int copies = 1;+ if (kind == Z_BOBSLED) {+ bool any = false;+ for (int r = 0; r < B.nrows; r++) any |= ice_row(r);+ if (!any) kind = Z_NORMAL, copies = 4; /* (no ice to ride: four zombies instead, as the game does) */+ }+ for (int c = 0; c < copies; c++) {+ uint8_t allowed = 0;+ for (int r = 0; r < B.nrows; r++) {+ bool ok;+ if (kind == Z_BOBSLED) ok = ice_row(r);+ else if (kind == Z_DUCKY || kind == Z_SNORKEL || kind == Z_DOLPHIN) ok = water_row(r);+ else if (water_row(r))+ ok = kind == Z_BALLOON || (B.wave >= 5 && (kind == Z_NORMAL || kind == Z_CONE || kind == Z_BUCKET || kind == Z_FLAG));+ else ok = kind != Z_DANCER || is_pool() || (r > 0 && r < 4);+ if (ok) allowed |= (uint8_t)(1 << r);+ }+ int row = pick_row(allowed);+ float x = 810 + irand(40) + (flag ? 40 : 0);+ if (B.level == 45 && kind != Z_BUNGEE) {+ drop_from_sky(kind, row, B.wave);+ continue;+ }+ Zombie *z = spawn_zombie(kind, row, kind == Z_FLAG ? 830 : x, B.wave);+ if (z && kind == Z_BOBSLED) {+ uint16_t lead = z->id;+ float lx = z->x;+ z->armor = 300, z->u.sled.sled = lead, z->u.sled.leader = 0;+ for (int k = 1; k < 4; k++) {+ Zombie *m = spawn_zombie(Z_BOBSLED, row, lx + k * 45, B.wave);+ if (m) m->u.sled.sled = lead, m->u.sled.leader = lead;+ }+ }+ }+ }+ B.wave++;+ if (B.wave == B.nwaves && B.env != ENV_DAY) B.grave_wave_in = 200;+ B.wave_elapsed = 0;+ bool before_flag = B.mode != MODE_BOWLING && is_flag_wave(B.wave);+ int32_t sum = 0;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if (!(z->flags & ZF_HYPNO) && z->wave == B.wave - 1 && !zombie_headless(z)) sum += zombie_total_health(z);+ }+ B.wave_threshold = before_flag ? 0 : (int32_t)(sum * (0.5f + frand() * 0.15f));+ B.wave_in = (int16_t)(before_flag ? 4500 : 2500 + irand(600));+ if (B.wave == B.nwaves && B.mode != MODE_WHACK) fx_add(FX_TEXT, 400, 300, 350, 2); /* "Final Wave" */+}++/* ---------------------------------------------------------------- the start of a level */++static void add_grave(int col, int row) {+ if (B.ngraves < 16) B.graves[B.ngraves].col = (uint8_t)col, B.graves[B.ngraves++].row = (uint8_t)row;+}++static void populate_vases(void);++void board_start(int level) {+ uint32_t seed = B.rng;+ memset(&B, 0, sizeof B);+ B.rng = seed ? seed : 12345;+ const LevelDef *d = &level_defs[level - 1];+ B.level = (uint8_t)level, B.env = d->env, B.mode = d->mode, B.rows = d->rows;+ B.nrows = is_pool() ? 6 : 5;+ B.sun = d->sun;+ B.nwaves = d->waves;+ B.has_boss = level == 50;+ B.sun_in = 400, B.wave_in = 1800;+ for (int r = 0; r < MAX_ROWS; r++) B.row_mowed[r] = -100;+ /* the seed packets: the level's own, else the ones chosen (screens.c fills them in) */+ if (B.mode == MODE_LAWN && !d->nseeds) B.nseeds = 0;+ else if (B.mode != MODE_CONVEYOR && B.mode != MODE_BOWLING) {+ B.nseeds = d->nseeds;+ for (int i = 0; i < d->nseeds; i++) B.seeds[i] = d->seeds[i];+ }+ generate_waves();+ if (B.mode == MODE_BOWLING) {+ B.npackets = 1, B.packets[0].kind = P_WALLNUT, B.packets[0].x = 0;+ B.started = 1, B.wave_in = 200;+ }+ if (B.mode == MODE_CONVEYOR) B.started = 1, B.conveyor_in = 1;+ if (B.mode == MODE_WHACK) {+ B.started = 1, B.wave_in = 200;+ extern void whack_graves(int n);+ whack_graves(9);+ }+ if (B.env == ENV_NIGHT && B.mode != MODE_WHACK && B.mode != MODE_VASE)+ for (int c = 0; c < 6 && grave_columns[level - 1][c][1]; c++) {+ uint8_t rows[MAX_ROWS];+ int n = 0;+ for (int r = 0; r < B.nrows; r++)+ if (B.rows >> r & 1) rows[n++] = (uint8_t)r;+ for (int k = 0; k < grave_columns[level - 1][c][1] && n; k++) {+ int i = irand(n);+ add_grave(grave_columns[level - 1][c][0], rows[i]);+ rows[i] = rows[--n];+ }+ }+ if (B.mode == MODE_VASE) B.started = 1, populate_vases();+ if (B.env == ENV_ROOF)+ for (int c = 0; c < (level == 41 ? 5 : level == 42 ? 4 : 3); c++)+ for (int r = 0; r < B.nrows; r++)+ if (B.nplants < MAX_PLANTS) plant_new(&B.plants[B.nplants++], P_FLOWERPOT, c, r);+ /* the mowers: the pool's lanes and the roof only with what Crazy Dave sells */+ for (int r = 0; r < B.nrows; r++) {+ B.mowers[r].x = 20;+ bool has = B.mode != MODE_VASE && (B.rows >> r & 1);+ if (water_row(r)) has = has && (progress.items & ITEM_POOL_CLEANER);+ if (B.env == ENV_ROOF) has = has && (progress.items & ITEM_ROOF_CLEANER);+ B.mowers[r].state = has ? 0 : 2;+ }+ if (B.env == ENV_FOG && level == 40) B.storm_in = 400;+ else B.storm_in = 650;+ B.storm_flash = 1;+ /* the seeds recharging from the start: the slow ones (the game's SeedPacket) */+ for (int i = 0; i < B.nseeds; i++) {+ int cd = plant_defs[B.seeds[i]].cooldown;+ B.cooldown[i] = (int16_t)(cd >= 3000 ? cd : 0);+ }+ if (B.has_boss) boss_start();+ B.phase = PH_INTRO;+ B.tutorial = 0;+}++/* the chosen seeds start recharging like the level's own */+void board_set_seeds(const uint8_t *seeds, int n) {+ B.nseeds = (uint8_t)n;+ for (int i = 0; i < n; i++) {+ B.seeds[i] = seeds[i];+ int cd = plant_defs[seeds[i]].cooldown;+ B.cooldown[i] = (int16_t)(cd >= 3000 ? cd : 0);+ }+}++/* ---------------------------------------------------------------- planting */++const char *const issue_text[] = {+ "", "You can't plant there", "There's already a plant there", "Not enough sun!", "That seed is recharging",+ "That plant goes in the water", "Plant a lily pad there first", "Plant a flower pot there first",+ "You can't plant that on the roof", "Remove the grave first", "You can't plant on a crater",+ "Plant coffee beans on sleeping mushrooms", "Roll your wall-nuts from left of the red line",+ "You can't plant on the ice",+};++int plant_issue(int kind, int col, int row) {+ if (row < 0 || row >= B.nrows || !(B.rows >> row & 1) || col < 0 || col >= (B.has_boss ? 8 : COLS)) return ISSUE_PLACE;+ for (int i = 0; i < B.nvases; i++)+ if (B.vases[i].col == col && B.vases[i].row == row) return ISSUE_PLACE;+ if (B.ice[row].left > 0 && cell_x(col) + 30 >= B.ice[row].x) return ISSUE_ICE;+ for (int i = 0; i < B.ncraters; i++)+ if (B.craters[i].col == col && B.craters[i].row == row) return ISSUE_CRATER;+ bool lily = false, pot = false, pumpkin = false, coffee = false, sleeper = false, other = false, any = false;+ for (int i = 0; i < B.nplants; i++) {+ const Plant *p = &B.plants[i];+ if (p->col != col || p->row != row || p->health <= 0) continue;+ any = true;+ if (p->kind == P_LILYPAD) lily = true;+ else if (p->kind == P_FLOWERPOT) pot = true;+ else if (p->kind == P_PUMPKIN) pumpkin = true;+ else if (p->kind == P_COFFEEBEAN) coffee = true;+ else {+ other = true;+ if (sleeping(p)) sleeper = true;+ }+ }+ bool aquatic = kind == P_LILYPAD || kind == P_TANGLEKELP || kind == P_SEASHROOM;+ if (aquatic && (!water_row(row) || any)) return ISSUE_WATER;+ if (water_row(row) && !aquatic && (kind == P_POTATOMINE || kind == P_SPIKEWEED || !lily))+ return kind == P_POTATOMINE || kind == P_SPIKEWEED ? ISSUE_WATER : ISSUE_LILY;+ if (B.env == ENV_ROOF) {+ if (kind == P_SPIKEWEED || kind == P_GRAVEBUSTER || aquatic) return ISSUE_ROOF;+ if (kind != P_FLOWERPOT && !pot) return ISSUE_POT;+ }+ bool grave = false;+ for (int i = 0; i < B.ngraves; i++) grave |= B.graves[i].col == col && B.graves[i].row == row;+ if (kind == P_GRAVEBUSTER ? !grave : grave) return kind == P_GRAVEBUSTER ? ISSUE_PLACE : ISSUE_GRAVE;+ if (B.mode == MODE_BOWLING) return col < 3 ? ISSUE_NONE : ISSUE_BOWLING;+ bool occupied;+ if (kind == P_COFFEEBEAN) {+ if (!sleeper || coffee) return ISSUE_COFFEE;+ occupied = false;+ } else if (kind == P_PUMPKIN) occupied = pumpkin;+ else if (kind == P_FLOWERPOT) occupied = any;+ else occupied = other || (kind == P_LILYPAD && any);+ /* the wall-nut first aid: a worn wall-nut, tall-nut or pumpkin made whole again */+ if (occupied && (progress.items & ITEM_FIRST_AID) && (kind == P_WALLNUT || kind == P_TALLNUT || kind == P_PUMPKIN)) {+ Plant *p = plant_at(col, row, kind);+ if (p && p->health < plant_defs[kind].health * 2 / 3) occupied = false;+ }+ if (occupied) return ISSUE_OCCUPIED;+ return ISSUE_NONE;+}++void plant_new(Plant *p, int kind, int col, int row) {+ memset(p, 0, sizeof *p);+ p->id = new_id(), p->kind = (uint8_t)kind, p->col = (uint8_t)col, p->row = (uint8_t)row;+ p->health = plant_defs[kind].health;+ p->born = B.ticks, p->shot = (uint32_t)-1000;+ switch (kind) {+ case P_SUNFLOWER: case P_SUNSHROOM: case P_MARIGOLD: p->action = (int16_t)(300 + irand(951)); break;+ case P_JALAPENO: case P_CHERRYBOMB: case P_ICESHROOM: case P_DOOMSHROOM: case P_COFFEEBEAN: p->action = 100; break;+ case P_POTATOMINE: p->action = 1500; break;+ case P_GRAVEBUSTER: p->action = 400; break;+ case P_PEASHOOTER: case P_SNOWPEA: case P_REPEATER: case P_PUFFSHROOM: case P_FUMESHROOM: case P_SCAREDYSHROOM:+ case P_THREEPEATER: case P_SEASHROOM: case P_CACTUS: case P_SPLITPEA: case P_STARFRUIT: case P_CABBAGEPULT:+ case P_KERNELPULT: case P_MELONPULT:+ p->action = (int16_t)irand(151);+ break;+ default: p->action = 50;+ }+}++bool board_plant(int slot, int col, int row) {+ int kind = seed_kind(slot);+ if (B.phase != PH_PLAY || kind < 0) return false;+ if (B.mode == MODE_VASE) kind = B.drops[slot].kind;+ if (plant_issue(kind, col, row)) return false;+ if (B.mode == MODE_BOWLING) {+ if (B.nrollers >= MAX_ROLLERS) return false;+ Roller *r = &B.rollers[B.nrollers++];+ memset(r, 0, sizeof *r);+ r->id = new_id(), r->kind = (uint8_t)kind, r->row = (uint8_t)row, r->x = cell_x(col), r->y = row_y(row, r->x);+ memmove(&B.packets[slot], &B.packets[slot + 1], (size_t)(B.npackets - slot - 1) * sizeof B.packets[0]);+ B.npackets--;+ B.planted++;+ return true;+ }+ if (B.mode == MODE_VASE) {+ B.drops[slot] = B.drops[--B.ndrops];+ } else if (B.mode == MODE_CONVEYOR) {+ memmove(&B.packets[slot], &B.packets[slot + 1], (size_t)(B.npackets - slot - 1) * sizeof B.packets[0]);+ B.npackets--;+ } else {+ if (B.sun < plant_cost(kind) || B.cooldown[slot] > 0) return false;+ B.sun -= plant_cost(kind);+ B.cooldown[slot] = (int16_t)plant_defs[kind].cooldown;+ }+ if ((kind == P_WALLNUT || kind == P_TALLNUT || kind == P_PUMPKIN) && (progress.items & ITEM_FIRST_AID)) {+ Plant *old = plant_at(col, row, kind);+ if (old) old->health = 0;+ }+ if (B.nplants >= MAX_PLANTS) {+ /* (room from the dead first) */+ for (int i = 0; i < B.nplants; i++)+ if (B.plants[i].health <= 0) B.plants[i--] = B.plants[--B.nplants];+ if (B.nplants >= MAX_PLANTS) return false;+ }+ plant_new(&B.plants[B.nplants++], kind, col, row);+ B.started = 1;+ B.planted++;+ fx_add(water_row(row) ? FX_SPLASH : FX_DIRT, cell_x(col), row_y(row, cell_x(col)), 40, 0);+ if (B.tutorial == 1) {+ int peas = 0;+ for (int i = 0; i < B.nplants; i++) peas += B.plants[i].kind == P_PEASHOOTER;+ if (peas >= 2) B.tutorial = 0, B.wave_in = 99;+ }+ if (B.tutorial == 2 || B.tutorial == 3) {+ int sf = 0;+ for (int i = 0; i < B.nplants; i++) sf += B.plants[i].kind == P_SUNFLOWER;+ if (sf >= 3) {+ if (B.tutorial == 2 && B.wave == 0) B.wave_in = 999;+ B.tutorial = 0;+ }+ }+ return true;+}++Plant *dig_target(int col, int row) {+ Plant *pumpkin = NULL, *main = NULL, *base = NULL;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->col != col || p->row != row || p->health <= 0) continue;+ if (p->kind == P_PUMPKIN) pumpkin = p;+ else if (p->kind == P_LILYPAD || p->kind == P_FLOWERPOT) base = p;+ else main = p;+ }+ return pumpkin ? pumpkin : main ? main : base;+}++bool board_dig(int col, int row) {+ Plant *p = dig_target(col, row);+ if (!p || B.phase != PH_PLAY) return false;+ for (int i = 0; i < B.nladders; i++)+ if (B.ladders[i].col == col && B.ladders[i].row == row) B.ladders[i--] = B.ladders[--B.nladders];+ if (p->kind == P_TANGLEKELP && p->state) {+ Zombie *z = zombie_by_id(p->target);+ if (z) z->health = 0;+ }+ p->health = 0;+ fx_add(FX_DIRT, cell_x(col), row_y(row, cell_x(col)), 30, 0);+ return true;+}++/* ---------------------------------------------------------------- the conveyor belt (Challenge::UpdateConveyor) */++static int next_conveyor_seed(void) {+ if (B.mode == MODE_BOWLING) return frand() < 0.85f ? P_WALLNUT : P_EXPLODENUT;+ const LevelDef *d = &level_defs[B.level - 1];+ int w[10], total = 0;+ for (int i = 0; i < d->nseeds; i++) {+ int kind = d->seeds[i], weight = d->weights[i];+ int count = 0, planted = 0;+ for (int k = 0; k < B.npackets; k++) count += B.packets[k].kind == kind;+ for (int k = 0; k < B.nplants; k++) planted += B.plants[k].kind == kind;+ int all = count + planted;+ if (kind == P_GRAVEBUSTER && B.ngraves <= all) weight = 0;+ if (kind == P_FLOWERPOT || kind == P_LILYPAD) {+ float f = all / (kind == P_FLOWERPOT ? 35.0f : 18.0f);+ if (f > 1) f = 1;+ weight = (int)(weight + (1 - weight) * f + 0.5f);+ }+ if (B.has_boss && (kind == P_MELONPULT || kind == P_KERNELPULT || kind == P_CABBAGEPULT)) {+ int empty = 0;+ for (int k = 0; k < B.nplants; k++) {+ const Plant *p = &B.plants[k];+ if (p->kind == P_FLOWERPOT && p->health > 0 && !plant_at(p->col, p->row, -1)) empty++;+ }+ if (empty <= 5) weight /= empty <= 2 ? 5 : 3;+ }+ if (B.has_boss && boss.phase == 10 /* the RV */ && kind == P_FLOWERPOT) weight = 500;+ w[i] = count >= 4 ? 1 : count >= 3 ? 5 : kind == B.last_conveyor ? weight / 2 : weight;+ total += w[i];+ }+ int pick = irand(total), i = 0;+ while (i < d->nseeds - 1 && pick >= w[i]) pick -= w[i++];+ B.last_conveyor = d->seeds[i];+ return d->seeds[i];+}++static void conveyor_tick(void) {+ if (B.ticks % 4 == 0)+ for (int i = 0; i < B.npackets; i++) {+ float m = (float)(i * 50);+ if (B.packets[i].x - 1 > m) B.packets[i].x -= 1;+ else B.packets[i].x = m;+ }+ if (--B.conveyor_in <= 0) {+ int n = B.npackets;+ B.conveyor_in = (int16_t)((n > 8 ? 1000 : n > 6 ? 500 : n > 4 ? 425 : 400) * (B.has_boss ? 0.875f : 1));+ if (n < 10) {+ float x = n == 0 ? 500 : B.packets[n - 1].x + 50;+ B.packets[n].kind = (uint8_t)next_conveyor_seed();+ B.packets[n].x = x < 500 ? 500 : x;+ B.npackets++;+ }+ }+}++/* ---------------------------------------------------------------- Vasebreaker */++static const struct { uint8_t first, green, n; struct { uint8_t zombie, kind, count; } c[8]; } vase_stages[3] = {+ {6, 0, 4, {{0, P_PEASHOOTER, 5}, {0, P_SQUASH, 5}, {1, Z_NORMAL, 4}, {1, Z_BUCKET, 1}}},+ {5, 2, 6, {{0, P_PEASHOOTER, 4}, {0, P_SNOWPEA, 5}, {0, P_SQUASH, 4}, {1, Z_NORMAL, 5}, {1, Z_BUCKET, 1},+ {1, Z_FOOTBALL, 1}}},+ {4, 3, 7, {{0, P_PEASHOOTER, 5}, {0, P_SNOWPEA, 5}, {0, P_HYPNOSHROOM, 5}, {1, Z_NORMAL, 6}, {1, Z_BUCKET, 2},+ {1, Z_DANCER, 1}, {1, Z_JACK, 1}}},+};++static void populate_vases(void) {+ Cell cells[45];+ int n = 0;+ const typeof(vase_stages[0]) *st = &vase_stages[B.vase_stage];+ for (int r = 0; r < B.nrows; r++)+ for (int c = st->first; c < COLS; c++) cells[n].row = (uint8_t)r, cells[n++].col = (uint8_t)c;+ B.nvases = 0;+ for (int i = 0; i < st->n; i++)+ for (int k = 0; k < st->c[i].count && n; k++) {+ int j = irand(n);+ Vase *v = &B.vases[B.nvases++];+ v->row = cells[j].row, v->col = cells[j].col, v->zombie = st->c[i].zombie, v->kind = st->c[i].kind, v->green = 0;+ cells[j] = cells[--n];+ }+ /* green vases always hold a plant */+ for (int g = 0; g < st->green; g++) {+ int seeds[45], m = 0;+ for (int i = 0; i < B.nvases; i++)+ if (!B.vases[i].zombie && !B.vases[i].green) seeds[m++] = i;+ if (m) B.vases[seeds[irand(m)]].green = 1;+ }+ B.wave = (uint8_t)(B.vase_stage + 1);+}++void board_break_vase(int col, int row) {+ for (int i = 0; i < B.nvases; i++) {+ Vase *v = &B.vases[i];+ if (v->col != col || v->row != row) continue;+ if (v->zombie) spawn_zombie(v->kind, row, cell_x(col), B.vase_stage);+ else if (B.ndrops < 30) {+ Drop *d = &B.drops[B.ndrops++];+ d->kind = v->kind, d->row = (uint8_t)row, d->col = (uint8_t)col, d->left = 1500, d->times = 0;+ }+ fx_add(FX_SMOKE, cell_x(col), row_y(row, cell_x(col)) - 40, 40, 1);+ B.vases[i] = B.vases[--B.nvases];+ return;+ }+}++void board_next_vase_stage(void) {+ B.vase_stage++;+ B.nplants = B.nzombies = B.nshots = B.ndrops = B.nsuns = 0;+ populate_vases();+}++/* ---------------------------------------------------------------- Whack a Zombie */++void whack_graves(int count) {+ Cell places[45];+ int n = 0;+ for (int r = 0; r < B.nrows; r++)+ for (int c = 3; c < 9; c++) {+ bool there = false;+ for (int i = 0; i < B.ngraves; i++) there |= B.graves[i].row == r && B.graves[i].col == c;+ if (!there) places[n].row = (uint8_t)r, places[n++].col = (uint8_t)c;+ }+ for (int k = 0; k < count && n; k++) {+ float w[45], total = 0;+ for (int i = 0; i < n; i++) w[i] = plant_at(places[i].col, places[i].row, -1) ? 1 : 100000, total += w[i];+ float pick = frand() * total;+ int i = 0;+ while (i < n - 1 && pick >= w[i]) pick -= w[i++];+ for (int j = 0; j < B.nplants; j++)+ if (B.plants[j].row == places[i].row && B.plants[j].col == places[i].col) B.plants[j].health = 0;+ add_grave(places[i].col, places[i].row);+ places[i] = places[--n];+ }+}++static void whack_tick(void) {+ if (B.whack_final) return;+ B.wave_in--;+ if (B.wave_in == 100 && B.wave > 0) whack_graves(5 - B.ngraves > 1 ? 5 - B.ngraves : 1);+ if (B.wave_in == 5 && B.wave == B.nwaves - 1) fx_add(FX_TEXT, 400, 280, 400, 1);+ if (B.wave_in == 0) {+ B.wave_in = 2000, B.wave++;+ B.whack_spawn_in = B.wave == B.nwaves ? 300 : 1;+ } else if (B.wave_in < 300)+ return;+ if (--B.whack_spawn_in != 0) return;+ int phase = (B.wave - 1) * 6 / 12;+ phase = phase < 0 ? 0 : phase > 5 ? 5 : phase;+ static const uint8_t doubles[6] = {0, 30, 10, 10, 15, 18}, triples[6] = {0, 0, 0, 0, 10, 13};+ static const uint8_t pails[6] = {0, 0, 0, 10, 15, 15}, cones[6] = {0, 0, 30, 30, 30, 30};+ int group = irand(100), type = irand(100);+ bool final = B.wave == B.nwaves;+ int count = final ? 20 : group < triples[phase] ? 3 : group < triples[phase] + doubles[phase] ? 2 : 1;+ int kind = type < pails[phase] && count < 3 ? Z_BUCKET : type < pails[phase] + cones[phase] ? Z_CONE : Z_NORMAL;+ Cell graves[16];+ int ng = 0;+ for (int i = 0; i < B.ngraves; i++)+ if (!plant_at(B.graves[i].col, B.graves[i].row, P_GRAVEBUSTER)) graves[ng++] = B.graves[i];+ float wf = (B.wave - 1) / 11.0f;+ int max_speed = final ? 2 : (int)(1 + 2 * wf * wf + 0.5f);+ for (int i = 0; i < count && ng; i++) {+ int g = irand(ng);+ Zombie *z = spawn_zombie(final ? (frand() < 0.5f ? Z_CONE : Z_BUCKET) : kind, graves[g].row,+ cell_x(graves[g].col) - 35, B.wave - 1);+ if (z) z->rise = 50, z->speed = 0.5f + frand() * (max_speed - 0.5f);+ graves[g] = graves[--ng];+ }+ int lo = (int)(100 - (B.wave - 1) * 70 / 11.0f + 0.5f), hi = (int)(200 - (B.wave - 1) * 140 / 11.0f + 0.5f);+ B.whack_spawn_in = (int16_t)(lo + irand(hi - lo + 1));+ if (final) B.whack_final = 1, B.wave_in = 0, B.whack_spawn_in = 0;+}++bool board_whack(float x, float y) {+ B.hammer_t = 20;+ Zombie *best = NULL;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (z->health <= 0 || zombie_headless(z)) continue;+ float dx = x - z->x, dy = y - 20 - (row_y(z->row, z->x) - 60);+ dx = dx < 0 ? -dx : dx, dy = dy < 0 ? -dy : dy;+ dx = dx > 24 ? dx - 24 : 0, dy = dy > 55 ? dy - 55 : 0;+ if (dx * dx + dy * dy > 45 * 45) continue;+ if (!best || z->row > best->row || (z->row == best->row && z->id > best->id)) best = z;+ }+ if (!best) return false;+ if (best->armor > 0) best->armor = (int16_t)(best->armor > 900 ? best->armor - 900 : 0);+ else kill_zombie(best, DIE_NORMAL);+ best->hit_at = B.ticks;+ fx_add(FX_POW, x, y, 25, 0);+ return true;+}++/* ---------------------------------------------------------------- a tick */++static void mowers_tick(void) {+ for (int r = 0; r < B.nrows; r++) {+ Mower *m = &B.mowers[r];+ if (m->state == 0) {+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if ((z->flags & (ZF_HYPNO | ZF_UNDERGROUND)) || zombie_flying(z) || z->kind == Z_BUNGEE || z->health <= 0) continue;+ if (z->row == r && z->x < 28) {+ m->state = 1;+ B.row_mowed[r] = (int8_t)(B.wave > 120 ? 120 : B.wave);+ break;+ }+ }+ }+ if (m->state == 1) {+ m->x += 3.5f;+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if ((z->flags & (ZF_HYPNO | ZF_UNDERGROUND)) || zombie_flying(z) || z->kind == Z_BUNGEE || z->health <= 0) continue;+ if (z->row == r && z->x - m->x < 45 && m->x - z->x < 45) kill_zombie(z, DIE_MOWED);+ }+ if (m->x > 890) m->state = 2;+ }+ }+}++static void graves_wave(void) {+ if (B.env == ENV_ROOF)+ for (int i = 0; i < (B.level < 43 ? 2 : 3); i++) drop_from_sky(frand() < 0.5f ? Z_NORMAL : Z_CONE, irand(5), B.wave - 1);+ if (is_pool() && B.pool_frozen == 0) {+ Cell cells[8];+ int n = 0;+ for (int r = 2; r <= 3; r++)+ for (int c = 5; c <= 8; c++) cells[n].row = (uint8_t)r, cells[n++].col = (uint8_t)c;+ for (int i = 0; i < (B.level <= 22 ? 2 : 3); i++) {+ int k = irand(n);+ Zombie *z = spawn_zombie(frand() < 0.5f ? Z_NORMAL : Z_CONE, cells[k].row, cell_x(cells[k].col) - 35, B.wave - 1);+ if (z) z->rise = 50;+ cells[k] = cells[--n];+ }+ }+ for (int i = 0; i < B.ngraves; i++) {+ int kind = (zombie_defs[Z_CONE].allowed >> (B.level - 1) & 1) && frand() < 0.5f ? Z_CONE : Z_NORMAL;+ Zombie *z = spawn_zombie(kind, B.graves[i].row, cell_x(B.graves[i].col) - 35, B.wave - 1);+ if (z) z->rise = 150;+ }+}++bool board_won(void) {+ if (B.mode == MODE_VASE) return false;+ for (int i = 0; i < B.nzombies; i++)+ if (!(B.zombies[i].flags & ZF_HYPNO) && B.zombies[i].health > 0) return false;+ return true;+}++void board_tick(void) {+ if (B.phase != PH_PLAY) return;+ B.ticks++;+ if (B.hammer_t > 0) B.hammer_t--;+ if (B.level == 40) {+ B.storm_in--;+ if (B.storm_in <= 0) {+ int max = frand() < 0.5f ? 750 : 400;+ B.storm_in = (int16_t)(450 + irand(max - 299));+ B.storm_flash = (uint8_t)(1 + irand(3));+ }+ }+ for (int r = 0; r < B.nrows; r++)+ if (B.ice[r].left > 0) B.ice[r].left--;+ if (B.fog_blown > 0) B.fog_blown--;+ for (int i = 0; i < B.ndrops; i++)+ if (--B.drops[i].left <= 0) B.drops[i--] = B.drops[--B.ndrops];+ for (int i = 0; i < B.ncraters; i++)+ if (--B.craters[i].left <= 0) B.craters[i--] = B.craters[--B.ncraters];+ if (B.pool_frozen > 0) B.pool_frozen--;+ for (int i = 0; i < B.nseeds; i++)+ if (B.cooldown[i] > 0) B.cooldown[i]--;+ /* the effects */+ for (int i = 0; i < B.nfx; i++)+ if (++B.fx[i].t >= B.fx[i].life) B.fx[i--] = B.fx[--B.nfx];+ if (!B.started) return;+ if (has_conveyor()) conveyor_tick();++ plants_tick();+ zombies_tick();+ shots_tick();+ /* the bowling wall-nuts */+ for (int i = 0; i < B.nrollers; i++) {+ Roller *n = &B.rollers[i];+ n->x += 3.3f;+ if (n->dir) {+ n->y += n->dir * 2;+ if (n->y <= row_y(0, n->x)) n->dir = 1;+ if (n->y >= row_y(4, n->x)) n->dir = -1;+ n->row = (uint8_t)((n->y - row_y(0, n->x)) / 100 + 0.5f);+ }+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *z = &B.zombies[k];+ if ((z->flags & ZF_HYPNO) || z->health <= 0 || z->row != n->row || z->x - n->x >= 40 || n->x - z->x >= 40) continue;+ float dy = n->y - row_y(z->row, z->x);+ if (dy > 2 || dy < -2) continue;+ bool seen = false;+ for (int h = 0; h < n->nhit; h++) seen |= n->hit[h] == z->id;+ if (seen) continue;+ if (n->nhit < 6) n->hit[n->nhit++] = z->id;+ if (n->kind == P_EXPLODENUT) {+ for (int j = 0; j < B.nzombies; j++) {+ Zombie *o = &B.zombies[j];+ int dr = o->row - n->row;+ if (dr >= -1 && dr <= 1 && o->x - n->x <= 90 && n->x - o->x <= 90) {+ damage_zombie(o, 1800, true);+ if (o->health <= 0) kill_zombie(o, DIE_BURN);+ }+ }+ fx_add(FX_BOOM, n->x, n->y - 35, 60, 0);+ n->x = 1000;+ break;+ }+ damage_zombie(z, z->armor > 0 ? 900 : 1800, false);+ z->hit_at = B.ticks;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ n->dir = n->row == 0 ? 1 : n->row == 4 ? -1 : n->dir == 0 ? (frand() < 0.5f ? -1 : 1) : -n->dir;+ fx_add(FX_POW, n->x, n->y - 35, 20, 0);+ }+ if (n->x > 900) B.rollers[i--] = B.rollers[--B.nrollers];+ }+ /* sun lands and fades; coins too */+ for (int i = 0; i < B.nsuns; i++) {+ Sun *s = &B.suns[i];+ if (s->y < s->ty) s->y = s->y + 0.65f > s->ty ? s->ty : s->y + 0.65f;+ else if (--s->left <= 0) B.suns[i--] = B.suns[--B.nsuns];+ }+ for (int i = 0; i < B.ncoins; i++) {+ Coin *c = &B.coins[i];+ if (c->y < c->ty) c->y = c->y + 1.5f > c->ty ? c->ty : c->y + 1.5f;+ else if (--c->left <= 0) B.coins[i--] = B.coins[--B.ncoins];+ }+ mowers_tick();+ /* the dead go */+ for (int i = 0; i < B.nplants; i++)+ if (B.plants[i].health <= 0) {+ for (int k = 0; k < B.nladders; k++)+ if (B.ladders[k].col == B.plants[i].col && B.ladders[k].row == B.plants[i].row &&+ !dig_target(B.ladders[k].col, B.ladders[k].row))+ B.ladders[k--] = B.ladders[--B.nladders];+ B.plants[i--] = B.plants[--B.nplants];+ }+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ bool gone = (z->flags & (ZF_HYPNO | ZF_BACKWARDS)) && z->x > 900;+ if (z->health <= 0 || gone) {+ if (z->health <= 0 && !(z->flags & ZF_HYPNO)) B.kills++;+ B.zombies[i--] = B.zombies[--B.nzombies];+ }+ }+ /* a zombie in the house */+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if (!(z->flags & (ZF_HYPNO | ZF_UNDERGROUND | ZF_BACKWARDS)) && z->x < -35 && z->kind != Z_BUNGEE) {+ B.phase = PH_LOST;+ B.last_x = z->x, B.last_y = (float)z->row;+ return;+ }+ }+ /* sun from the sky */+ if (B.mode == MODE_LAWN && !is_night() && --B.sun_in <= 0) {+ int rows[MAX_ROWS], n = 0;+ for (int r = 0; r < B.nrows; r++)+ if (B.rows >> r & 1) rows[n++] = r;+ int row = rows[irand(n)];+ add_sun(100 + frand() * 549, 70, row_y(row, 440) - 30, 25, true);+ B.suns_fallen++;+ int base = 425 + B.suns_fallen * 10;+ B.sun_in = (int16_t)((base < 950 ? base : 950) + irand(275));+ }+ if (B.has_boss) {+ boss_tick();+ return;+ }+ if (B.mode == MODE_VASE) {+ bool zombies = false;+ for (int i = 0; i < B.nzombies; i++) zombies |= !(B.zombies[i].flags & ZF_HYPNO);+ if (B.nvases == 0 && !zombies) {+ if (B.vase_stage == 2) B.phase = PH_WON;+ else board_next_vase_stage();+ }+ return;+ }+ if (B.grave_wave_in > 0 && --B.grave_wave_in == 0) graves_wave();+ if (B.mode == MODE_WHACK) {+ whack_tick();+ if (B.whack_final && B.nzombies == 0) B.phase = PH_WON;+ return;+ }+ if (B.tutorial == 1) return;+ if (B.wave < B.nwaves) {+ B.wave_elapsed++;+ int32_t remaining = 0;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *z = &B.zombies[i];+ if (!(z->flags & ZF_HYPNO) && z->wave == B.wave - 1 && !zombie_headless(z)) remaining += zombie_total_health(z);+ }+ if (B.flag_warning > 0) {+ if (--B.flag_warning == 0) spawn_wave();+ return;+ }+ if (B.wave > 0 && B.wave_elapsed > 400 && B.wave_in > 200 && remaining <= B.wave_threshold) B.wave_in = 200;+ B.wave_in--;+ if (B.wave_in == 5 && is_flag_wave(B.wave)) {+ B.flag_warning = 750;+ fx_add(FX_TEXT, 400, 280, 450, 0); /* "A Huge Wave of Zombies is Approaching!" */+ } else if (B.wave_in <= 0)+ spawn_wave();+ } else if (board_won() && B.grave_wave_in == 0) {+ B.phase = PH_WON;+ }+}diff --git a/games/pvz/src/data.S b/games/pvz/src/data.Snew file mode 100644index 00000000..4368b8dc--- /dev/null+++ b/games/pvz/src/data.S@@ -0,0 +1,19 @@+/* data.bin (tools/pack.py) in the app's read-only data */+#ifdef __APPLE__+ .const_data+ .p2align 2+ .globl _pvz_data+_pvz_data:+ .incbin DATA_BIN+ .p2align 2+#else+ .section .rodata.pvz_data,"a"+ .balign 4+ .global pvz_data+pvz_data:+ .incbin DATA_BIN+ .balign 4+#endif+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/pvz/src/data.bin b/games/pvz/src/data.binnew file mode 100644index 00000000..f76f6c25Binary files /dev/null and b/games/pvz/src/data.bin differdiff --git a/games/pvz/src/data.h b/games/pvz/src/data.hnew file mode 100644index 00000000..0366a869--- /dev/null+++ b/games/pvz/src/data.h@@ -0,0 +1,372 @@+/* Generated by tools/pack.py: what data.bin holds. */+#ifndef PVZ_DATA_H+#define PVZ_DATA_H++#define A_ZOMBIE_HEADLESS 0+#define A_ZOMBIE_WALK 1+#define A_CONE_WALK 2+#define A_BUCKET_WALK 3+#define A_FLAG_WALK 4+#define A_ZOMBIE_EAT 5+#define A_CONE_EAT 6+#define A_BUCKET_EAT 7+#define A_FLAG_EAT 8+#define A_ZOMBIE_DIE 9+#define A_ZOMBIE_BURN 10+#define A_POLE_HEADLESS 11+#define A_POLE_WALK 12+#define A_POLE_RUN 13+#define A_POLE_JUMP 14+#define A_POLE_LAND 15+#define A_POLE_EAT 16+#define A_POLE_DIE 17+#define A_POLE_BURN 18+#define A_NEWSPAPER_HEADLESS 19+#define A_NEWSPAPER_WALK 20+#define A_NEWSPAPER_MAD_WALK 21+#define A_NEWSPAPER_MAD_EAT 22+#define A_NEWSPAPER_EAT 23+#define A_NEWSPAPER_GASP 24+#define A_NEWSPAPER_DIE 25+#define A_NEWSPAPER_BURN 26+#define A_DOOR_WALK 27+#define A_DOOR_EAT 28+#define A_FOOTBALL_HEADLESS 29+#define A_FOOTBALL_WALK 30+#define A_FOOTBALL_BARE_WALK 31+#define A_FOOTBALL_BARE_EAT 32+#define A_FOOTBALL_EAT 33+#define A_FOOTBALL_DIE 34+#define A_DANCER_WALK 35+#define A_DANCER_EAT 36+#define A_DANCER_SUMMON 37+#define A_DANCER_HEADLESS 38+#define A_DANCER_DIE 39+#define A_DANCER_BURN 40+#define A_BACKUP_WALK 41+#define A_BACKUP_EAT 42+#define A_BACKUP_HEADLESS 43+#define A_BACKUP_DIE 44+#define A_BACKUP_BURN 45+#define A_DUCKY1_WALK 46+#define A_DUCKY2_WALK 47+#define A_DUCKY3_WALK 48+#define A_DUCKY1_EAT 49+#define A_DUCKY2_EAT 50+#define A_DUCKY3_EAT 51+#define A_DUCKY_DIE 52+#define A_SNORKEL_WALK 53+#define A_SNORKEL_SWIM 54+#define A_SNORKEL_EAT 55+#define A_SNORKEL_DIE 56+#define A_ZOMBONI_WALK 57+#define A_ZOMBONI_DAMAGED 58+#define A_ZOMBONI_CRITICAL 59+#define A_ZOMBONI_DIE 60+#define A_BOBSLED_WALK 61+#define A_BOBSLED_EAT 62+#define A_BOBSLED_DIE 63+#define A_DOLPHIN_WALK 64+#define A_DOLPHIN_RIDE 65+#define A_DOLPHIN_JUMP 66+#define A_DOLPHIN_SWIM 67+#define A_DOLPHIN_EAT 68+#define A_DOLPHIN_DIE 69+#define A_JACK_WALK 70+#define A_JACK_EAT 71+#define A_JACK_OPEN 72+#define A_JACK_HEADLESS 73+#define A_JACK_DIE 74+#define A_BALLOON_FLY 75+#define A_BALLOON_POP 76+#define A_BALLOON_WALK 77+#define A_BALLOON_EAT 78+#define A_BALLOON_DIE 79+#define A_DIGGER_DIG 80+#define A_DIGGER_RISE 81+#define A_DIGGER_WALK 82+#define A_DIGGER_EAT 83+#define A_DIGGER_DIE 84+#define A_POGO_BOUNCE 85+#define A_POGO_WALK 86+#define A_POGO_EAT 87+#define A_POGO_DIE 88+#define A_BUNGEE_DROP 89+#define A_BUNGEE_IDLE 90+#define A_BUNGEE_DIE 91+#define A_LADDER_BARE 92+#define A_LADDER_WALK 93+#define A_LADDER_PLACE 94+#define A_LADDER_EAT 95+#define A_LADDER_DIE 96+#define A_CATAPULT_WALK 97+#define A_CATAPULT_IDLE 98+#define A_CATAPULT_SHOOT 99+#define A_CATAPULT_DIE 100+#define A_GARGANTUAR_BARE_WALK 101+#define A_GARGANTUAR_WALK 102+#define A_GARGANTUAR_BARE_SMASH 103+#define A_GARGANTUAR_SMASH 104+#define A_GARGANTUAR_THROW 105+#define A_GARGANTUAR_BARE_DIE 106+#define A_GARGANTUAR_DIE 107+#define A_IMP_THROWN 108+#define A_IMP_LAND 109+#define A_IMP_WALK 110+#define A_IMP_EAT 111+#define A_IMP_DIE 112+#define A_PEASHOOTER 113+#define A_SUNFLOWER 114+#define A_CHERRYBOMB 115+#define A_WALLNUT 116+#define A_WALLNUT_CRACKED1 117+#define A_WALLNUT_CRACKED2 118+#define A_WALLNUT_ROLL 119+#define A_EXPLODENUT 120+#define A_POTATOMINE 121+#define A_POTATOMINE_UNARMED 122+#define A_SNOWPEA 123+#define A_CHOMPER 124+#define A_CHOMPER_BITE 125+#define A_CHOMPER_DIGEST 126+#define A_REPEATER 127+#define A_PUFFSHROOM 128+#define A_SUNSHROOM 129+#define A_SUNSHROOM_BIG 130+#define A_FUMESHROOM 131+#define A_FUMESHROOM_ATTACK 132+#define A_FUME_CLOUD 133+#define A_GRAVEBUSTER 134+#define A_HYPNOSHROOM 135+#define A_SCAREDYSHROOM 136+#define A_SCAREDYSHROOM_SCARED 137+#define A_ICESHROOM 138+#define A_DOOMSHROOM 139+#define A_LILYPAD 140+#define A_SQUASH 141+#define A_SQUASH_ATTACK 142+#define A_THREEPEATER 143+#define A_TANGLEKELP 144+#define A_TANGLEKELP_GRAB 145+#define A_JALAPENO 146+#define A_JALAPENO_FIRE 147+#define A_SPIKEWEED 148+#define A_TORCHWOOD 149+#define A_TALLNUT 150+#define A_TALLNUT_CRACKED1 151+#define A_TALLNUT_CRACKED2 152+#define A_SEASHROOM 153+#define A_PLANTERN 154+#define A_CACTUS 155+#define A_CACTUS_TALL 156+#define A_BLOVER 157+#define A_BLOVER_LOOP 158+#define A_SPLITPEA 159+#define A_STARFRUIT 160+#define A_PUMPKIN 161+#define A_PUMPKIN_CRACKED1 162+#define A_PUMPKIN_CRACKED2 163+#define A_MAGNETSHROOM 164+#define A_MAGNETSHROOM_ATTACK 165+#define A_CABBAGEPULT 166+#define A_CABBAGEPULT_ATTACK 167+#define A_FLOWERPOT 168+#define A_KERNELPULT 169+#define A_KERNELPULT_ATTACK 170+#define A_COFFEEBEAN 171+#define A_GARLIC 172+#define A_GARLIC_CRACKED1 173+#define A_GARLIC_CRACKED2 174+#define A_UMBRELLA 175+#define A_UMBRELLA_BLOCK 176+#define A_MARIGOLD 177+#define A_MELONPULT 178+#define A_MELONPULT_ATTACK 179+#define A_SUN 180+#define I_PACKET_PEASHOOTER 181+#define I_PACKET_SUNFLOWER 182+#define I_PACKET_CHERRYBOMB 183+#define I_PACKET_WALLNUT 184+#define I_PACKET_POTATOMINE 185+#define I_PACKET_SNOWPEA 186+#define I_PACKET_CHOMPER 187+#define I_PACKET_REPEATER 188+#define I_PACKET_PUFFSHROOM 189+#define I_PACKET_SUNSHROOM 190+#define I_PACKET_FUMESHROOM 191+#define I_PACKET_GRAVEBUSTER 192+#define I_PACKET_HYPNOSHROOM 193+#define I_PACKET_SCAREDYSHROOM 194+#define I_PACKET_ICESHROOM 195+#define I_PACKET_DOOMSHROOM 196+#define I_PACKET_LILYPAD 197+#define I_PACKET_SQUASH 198+#define I_PACKET_THREEPEATER 199+#define I_PACKET_TANGLEKELP 200+#define I_PACKET_JALAPENO 201+#define I_PACKET_SPIKEWEED 202+#define I_PACKET_TORCHWOOD 203+#define I_PACKET_TALLNUT 204+#define I_PACKET_SEASHROOM 205+#define I_PACKET_PLANTERN 206+#define I_PACKET_CACTUS 207+#define I_PACKET_BLOVER 208+#define I_PACKET_SPLITPEA 209+#define I_PACKET_STARFRUIT 210+#define I_PACKET_PUMPKIN 211+#define I_PACKET_MAGNETSHROOM 212+#define I_PACKET_CABBAGEPULT 213+#define I_PACKET_FLOWERPOT 214+#define I_PACKET_KERNELPULT 215+#define I_PACKET_COFFEEBEAN 216+#define I_PACKET_GARLIC 217+#define I_PACKET_UMBRELLA 218+#define I_PACKET_MARIGOLD 219+#define I_PACKET_MELONPULT 220+#define I_BIG_PEASHOOTER 221+#define I_BIG_SUNFLOWER 222+#define I_BIG_CHERRYBOMB 223+#define I_BIG_WALLNUT 224+#define I_BIG_POTATOMINE 225+#define I_BIG_SNOWPEA 226+#define I_BIG_CHOMPER 227+#define I_BIG_REPEATER 228+#define I_BIG_PUFFSHROOM 229+#define I_BIG_SUNSHROOM 230+#define I_BIG_FUMESHROOM 231+#define I_BIG_GRAVEBUSTER 232+#define I_BIG_HYPNOSHROOM 233+#define I_BIG_SCAREDYSHROOM 234+#define I_BIG_ICESHROOM 235+#define I_BIG_DOOMSHROOM 236+#define I_BIG_LILYPAD 237+#define I_BIG_SQUASH 238+#define I_BIG_THREEPEATER 239+#define I_BIG_TANGLEKELP 240+#define I_BIG_JALAPENO 241+#define I_BIG_SPIKEWEED 242+#define I_BIG_TORCHWOOD 243+#define I_BIG_TALLNUT 244+#define I_BIG_SEASHROOM 245+#define I_BIG_PLANTERN 246+#define I_BIG_CACTUS 247+#define I_BIG_BLOVER 248+#define I_BIG_SPLITPEA 249+#define I_BIG_STARFRUIT 250+#define I_BIG_PUMPKIN 251+#define I_BIG_MAGNETSHROOM 252+#define I_BIG_CABBAGEPULT 253+#define I_BIG_FLOWERPOT 254+#define I_BIG_KERNELPULT 255+#define I_BIG_COFFEEBEAN 256+#define I_BIG_GARLIC 257+#define I_BIG_UMBRELLA 258+#define I_BIG_MARIGOLD 259+#define I_BIG_MELONPULT 260+#define I_PORTRAIT_NORMAL 261+#define I_PORTRAIT_FLAG 262+#define I_PORTRAIT_CONE 263+#define I_PORTRAIT_POLE 264+#define I_PORTRAIT_BUCKET 265+#define I_PORTRAIT_NEWSPAPER 266+#define I_PORTRAIT_DOOR 267+#define I_PORTRAIT_FOOTBALL 268+#define I_PORTRAIT_DANCER 269+#define I_PORTRAIT_BACKUP 270+#define I_PORTRAIT_DUCKY 271+#define I_PORTRAIT_SNORKEL 272+#define I_PORTRAIT_ZOMBONI 273+#define I_PORTRAIT_BOBSLED 274+#define I_PORTRAIT_DOLPHIN 275+#define I_PORTRAIT_JACK 276+#define I_PORTRAIT_BALLOON 277+#define I_PORTRAIT_DIGGER 278+#define I_PORTRAIT_POGO 279+#define I_PORTRAIT_BUNGEE 280+#define I_PORTRAIT_LADDER 281+#define I_PORTRAIT_CATAPULT 282+#define I_PORTRAIT_GARGANTUAR 283+#define I_PORTRAIT_IMP 284+#define I_PEA 285+#define I_SNOW_PEA 286+#define I_PUFF 287+#define I_STAR 288+#define I_SPIKE 289+#define I_CABBAGE 290+#define I_KERNEL 291+#define I_BUTTER 292+#define I_MELON 293+#define I_BASKETBALL 294+#define I_COIN_SILVER 295+#define I_COIN_GOLD 296+#define I_COIN_DIAMOND 297+#define I_BUNGEE_TARGET 298+#define I_HAMMER 299+#define I_METER_FLAG 300+#define I_METER_HEAD 301+#define I_MOWER 302+#define I_POOL_CLEANER 303+#define I_ROOF_CLEANER 304+#define I_GRAVE 305+#define I_LADDER 306+#define I_SLED 307+#define I_CRATER0 308+#define I_CRATER1 309+#define I_VASE0 310+#define I_VASE1 311+#define I_VASE2 312+#define I_VASE3 313+#define I_VASE4 314+#define I_VASE5 315+#define I_FOG0 316+#define I_FOG1 317+#define I_FOG2 318+#define I_FOG3 319+#define I_FOG4 320+#define I_FOG5 321+#define I_FOG6 322+#define I_FOG7 323+#define A_FIRE_PEA 324+#define I_ICE_TRAIL 325+#define I_BUNGEE_CORD 326+#define I_BOWLING_STRIPE 327+#define I_SEEDBANK 328+#define I_SHOVELBANK 329+#define I_SHOVEL 330+#define I_PACKET 331+#define I_METER_EMPTY 332+#define I_METER_FULL 333+#define I_CONVEYOR 334+#define I_LOGO 335+#define I_DIALOG 336+#define I_BUTTON 337+#define I_DAVE 338+#define I_TROPHY 339+#define I_CHOOSER 340+#define I_START 341+#define I_START_OFF 342+#define I_CARD 343+#define I_SHOP_SLOTS 344+#define I_SHOP_ROOF 345+#define I_SHOP_RAKE 346+#define I_SHOP_FIRSTAID 347+#define N_ANIMS 348++#define BG_LAWN 0+#define BG_YARD 1+#define BG_NIGHT 2+#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 F_BIG 0+#define F_HEAD 1+#define F_BODY 2+#define F_SMALL 3++#endifdiff --git a/games/pvz/src/defs.c b/games/pvz/src/defs.cnew file mode 100644index 00000000..96dd1b79--- /dev/null+++ b/games/pvz/src/defs.c@@ -0,0 +1,307 @@+/* The game's facts: its plants, zombies and Adventure's 50 levels. */+#include "game.h"++/* cost in sun, recharge in ticks (7.5 s, 30 s or 50 s), health */+const PlantDef plant_defs[N_PLANTS] = {+ {"Peashooter", 100, 750, 300, 0, 0},+ {"Sunflower", 50, 750, 300, 0, 0},+ {"Cherry Bomb", 150, 5000, 300, 0, 0},+ {"Wall-nut", 50, 3000, 4000, 0, 0},+ {"Potato Mine", 25, 3000, 300, 0, 0},+ {"Snow Pea", 175, 750, 300, 0, 0},+ {"Chomper", 150, 750, 300, 0, 0},+ {"Repeater", 200, 750, 300, 0, 0},+ {"Puff-shroom", 0, 750, 300, 1, 0},+ {"Sun-shroom", 25, 750, 300, 1, 0},+ {"Fume-shroom", 75, 750, 300, 1, 0},+ {"Grave Buster", 75, 750, 300, 0, 0},+ {"Hypno-shroom", 75, 3000, 300, 1, 0},+ {"Scaredy-shroom", 25, 750, 300, 1, 0},+ {"Ice-shroom", 75, 5000, 300, 1, 0},+ {"Doom-shroom", 125, 5000, 300, 1, 0},+ {"Lily Pad", 25, 750, 300, 0, 0},+ {"Squash", 50, 3000, 300, 0, 0},+ {"Threepeater", 325, 750, 300, 0, 0},+ {"Tangle Kelp", 25, 3000, 300, 0, 0},+ {"Jalapeno", 125, 5000, 300, 0, 0},+ {"Spikeweed", 100, 750, 300, 0, 0},+ {"Torchwood", 175, 750, 300, 0, 0},+ {"Tall-nut", 125, 3000, 8000, 0, 0},+ {"Sea-shroom", 0, 3000, 300, 1, 0},+ {"Plantern", 25, 3000, 300, 0, 0},+ {"Cactus", 125, 750, 300, 0, 0},+ {"Blover", 100, 750, 300, 0, 0},+ {"Split Pea", 125, 750, 300, 0, 0},+ {"Starfruit", 125, 750, 300, 0, 0},+ {"Pumpkin", 125, 3000, 4000, 0, 0},+ {"Magnet-shroom", 100, 750, 300, 1, 0},+ {"Cabbage-pult", 100, 750, 300, 0, 0},+ {"Flower Pot", 25, 750, 300, 0, 0},+ {"Kernel-pult", 100, 750, 300, 0, 0},+ {"Coffee Bean", 75, 750, 300, 0, 0},+ {"Garlic", 50, 750, 400, 0, 0},+ {"Umbrella Leaf", 100, 750, 300, 0, 0},+ {"Marigold", 50, 3000, 300, 0, 0},+ {"Melon-pult", 300, 750, 300, 0, 0},+ {"Explode-o-nut", 0, 0, 4000, 0, 0},+};++const char *const plant_blurbs[N_SEEDS] = {+ "Peashooters are your first line of defense. They shoot peas at attacking zombies.",+ "Sunflowers are essential for you to produce extra sun. Try planting as many as you can!",+ "Cherry Bombs can blow up all zombies in an area. They have a short fuse so plant them near zombies.",+ "Wall-nuts have hard shells which you can use to protect other plants.",+ "Potato Mines pack a powerful punch, but they need a while to arm themselves. Plant them ahead of zombies: "+ "they explode on contact.",+ "Snow Peas shoot frozen peas that damage and slow the enemy.",+ "Chompers can devour a zombie whole, but they are vulnerable while chewing.",+ "Repeaters fire two peas at a time.",+ "Puff-shrooms are cheap, but can only fire a short distance.",+ "Sun-shrooms give small sun at first and normal sun later.",+ "Fume-shrooms shoot fumes that can pass through screen doors.",+ "Plant Grave Busters on graves to remove the graves.",+ "When eaten, Hypno-shrooms will make a zombie turn around and fight for you.",+ "Scaredy-shrooms are long-ranged shooters that hide when enemies get near them.",+ "Ice-shrooms temporarily immobilize all zombies on the screen.",+ "Doom-shrooms destroy everything in a large area and leave a crater that can't be planted on.",+ "Lily pads let you plant non-aquatic plants on top of them.",+ "Squashes will smash the first zombie that gets close to it.",+ "Threepeaters shoot peas in three lanes.",+ "Tangle Kelp are aquatic plants that pull the first zombie that nears them underwater.",+ "Jalapenos destroy an entire lane of zombies.",+ "Spikeweeds pop tires and hurt any zombies that step on them.",+ "Torchwoods turn peas that pass through them into fireballs that deal twice as much damage.",+ "Tall-nuts are heavy-duty wall plants that can't be jumped over.",+ "Sea-shrooms are aquatic plants that shoot short ranged spores.",+ "Planterns light up an area, letting you see through fog.",+ "Cacti shoot spikes that can pop balloons.",+ "Blovers can blow away all balloon zombies and fog.",+ "Split Peas shoot forward and backwards.",+ "Starfruits shoot stars in five directions.",+ "Pumpkins protect plants that are within their shells.",+ "Magnet-shrooms remove helmets and other metal objects from zombies.",+ "Cabbage-pults hurl cabbages at the enemy.",+ "Flower Pots let you plant on roofs.",+ "Kernel-pults fling corn kernels and butter at zombies.",+ "Plant Coffee Beans on sleeping mushrooms to wake them up.",+ "Garlic diverts zombies into other lanes.",+ "Umbrella Leaves protect nearby plants from bungees and catapults.",+ "Marigolds give you silver and gold coins.",+ "Melon-pults do heavy damage to groups of zombies.",+};++const char *const plant_stats[N_SEEDS] = {+ "Damage: normal",+ "Sun production: normal",+ "Damage: massive\nRange: all zombies in a medium area\nUsage: single use, instant",+ "Toughness: high",+ "Damage: massive\nRange: all zombies in a small area\nUsage: single use, delayed activation",+ "Damage: normal, slows zombies",+ "Damage: massive\nRange: very short\nUsage: long delay between chomps",+ "Damage: normal (for each pea)\nFiring speed: 2x",+ "Damage: normal\nRange: short\nSleeps during the day",+ "Sun production: low, then normal\nSleeps during the day",+ "Damage: normal, penetrates screen doors\nRange: all zombies in the fume cloud\nSleeps during the day",+ "Range: plant it on a grave to remove the grave\nUsage: single use, instant\nCan only be planted on graves",+ "Usage: single use, on contact\nSleeps during the day",+ "Damage: normal\nRange: long\nSleeps during the day",+ "Damage: very light, immobilizes zombies\nRange: all zombies on the screen\nUsage: single use, instant\n"+ "Sleeps during the day",+ "Damage: massive\nRange: all zombies in a large area\nUsage: single use, instant\nSleeps during the day",+ "Must be planted in water",+ "Damage: massive\nRange: short, hits all zombies it lands on\nUsage: single use",+ "Damage: normal\nRange: three lanes",+ "Damage: massive\nUsage: single use, on contact\nMust be planted in water",+ "Damage: massive\nRange: all zombies in a lane\nUsage: single use, instant",+ "Damage: normal\nRange: all zombies that walk over it\nCan't be eaten by zombies",+ "Damage: doubles the damage of peas that pass through it",+ "Toughness: very high\nCan't be jumped over",+ "Damage: normal\nRange: short\nMust be planted in water\nSleeps during the day",+ "Range: lights up a large area through the fog",+ "Damage: normal\nRange: ground and air",+ "Range: all balloon zombies, and the fog\nUsage: single use, instant",+ "Damage: normal\nRange: forward and backward\nFiring speed: 1x forward, 2x backward",+ "Damage: normal\nRange: five directions",+ "Toughness: high",+ "Range: nearby zombies\nUsage: one piece of metal at a time\nSleeps during the day",+ "Damage: normal\nRange: lobbed",+ "Must be planted on roofs",+ "Damage: light (kernel), normal (butter)\nRange: lobbed\nButter immobilizes zombies",+ "Wakes up a sleeping mushroom\nUsage: single use, instant",+ "Range: diverts zombies that bite it\nToughness: medium",+ "Range: protects the plants around it",+ "Makes coins",+ "Damage: heavy\nRange: lobbed, hits a group of zombies",+};++/* value (a wave's budget), first level, first wave, how often, and the levels it may come in (bit n: level n + 1),+ * as the game's own table */+const ZombieDef zombie_defs[N_ZOMBIES] = {+ {"Zombie", 1, 1, 1, 4000, 0x3FFFFFFFFFFFFull},+ {"Flag Zombie", 1, 1, 1, 0, 0x3FFFFFFFFFFFFull},+ {"Conehead Zombie", 2, 3, 1, 4000, 0x3FFFFFFFFFBFCull},+ {"Pole Vaulting Zombie", 2, 6, 5, 2000, 0x0020010806360ull},+ {"Buckethead Zombie", 4, 8, 1, 3000, 0x312D034A04B80ull},+ {"Newspaper Zombie", 2, 11, 1, 1000, 0x0000000A04C00ull},+ {"Screen Door Zombie", 4, 13, 5, 3500, 0x00000000D3000ull},+ {"Football Zombie", 7, 16, 5, 2000, 0x0080081298000ull},+ {"Dancing Zombie", 5, 18, 5, 1000, 0x00000000E0000ull},+ {"Backup Dancer", 1, 18, 1, 0, 0x00000000E0000ull},+ {"Ducky Tube Zombie", 1, 21, 5, 0, 0x0000000000000ull},+ {"Snorkel Zombie", 3, 23, 10, 2000, 0x0000025C00000ull},+ {"Zomboni", 7, 26, 10, 2000, 0x0000036000000ull},+ {"Zombie Bobsled Team", 3, 26, 10, 2000, 0x0000036000000ull},+ {"Dolphin Rider Zombie", 3, 28, 10, 1500, 0x0000238000000ull},+ {"Jack-in-the-Box Zombie", 3, 31, 10, 1000, 0x30090C0000000ull},+ {"Balloon Zombie", 2, 33, 10, 2000, 0x000C300000000ull},+ {"Digger Zombie", 4, 36, 10, 1000, 0x0009800000000ull},+ {"Pogo Zombie", 4, 38, 10, 1000, 0x008E000000000ull},+ {"Bungee Zombie", 3, 41, 10, 1000, 0x3430000000000ull},+ {"Ladder Zombie", 4, 43, 10, 1000, 0x35C0000000000ull},+ {"Catapult Zombie", 5, 46, 10, 1500, 0x3600000000000ull},+ {"Gargantuar", 10, 48, 15, 1500, 0x3800000000000ull},+ {"Imp", 10, 48, 1, 0, 0x3800000000000ull},+};++const char *const zombie_blurbs[N_ZOMBIES] = {+ "Regular garden-variety zombie.",+ "Flag Zombie marks the arrival of a huge pile, or \"horde,\" of zombies.",+ "His traffic cone headpiece makes him twice as tough as normal zombies.",+ "Pole Vaulting Zombie vaults with a pole.",+ "His bucket hat makes him extremely resistant to damage.",+ "His newspaper provides limited defense.",+ "His screen door is an effective shield.",+ "Football Zombie is very tough and fast.",+ "Dancing Zombie summons backup dancers.",+ "Backup Dancers are summoned by Dancing Zombie.",+ "Ducky Tube allows Zombie to float in water.",+ "Snorkel Zombie can swim underwater.",+ "Zomboni crushes plants and leaves an ice trail.",+ "Zombie Bobsled Team rides a bobsled down the Zomboni's ice.",+ "Dolphin Rider Zombies exploit your pool's weakness.",+ "This zombie carries an explosive surprise.",+ "Balloon Zombie floats above the fray, immune to most attacks.",+ "This zombie digs to bypass your defenses.",+ "Pogo Zombie hops to bypass your defenses.",+ "Bungee Zombie attacks from above.",+ "Ladder Zombie climbs over obstacles.",+ "Catapult Zombie operates heavy machinery.",+ "Gargantuar is a gigantic zombie.",+ "Imps are tiny zombies hurled by Gargantuar deep into your defenses.",+};++const char *const zombie_stats[N_ZOMBIES] = {+ "Toughness: low",+ "Toughness: low",+ "Toughness: medium",+ "Toughness: medium\nSpeed: fast, then normal (after jump)\nSpecial: jumps the first plant he runs into",+ "Toughness: medium\nWeakness: magnet-shroom",+ "Toughness: low\nNewspaper toughness: low\nSpeed: normal, then fast (after losing newspaper)",+ "Toughness: low\nScreen door toughness: high\nWeakness: fume-shrooms and magnet-shrooms",+ "Toughness: high\nSpeed: fast\nWeakness: magnet-shroom",+ "Toughness: medium\nSpecial: summons backup dancers",+ "Toughness: low",+ "Special: can only appear in the pool",+ "Toughness: low\nSpecial: swims underwater\nSpecial: can only appear in the pool",+ "Toughness: high\nSpecial: crushes plants\nSpecial: leaves an ice trail\nWeakness: spikeweed",+ "Toughness: low\nSpecial: can only appear on ice",+ "Toughness: medium\nSpeed: fast, then normal (after jump)\nSpecial: jumps the first plant he runs into\n"+ "Special: can only appear in the pool",+ "Toughness: medium\nSpeed: fast\nSpecial: jack-in-the-box explodes",+ "Toughness: medium\nSpecial: flying\nWeakness: cactus and blover",+ "Toughness: medium\nSpeed: fast, then slow\nSpecial: digs, bypassing your defenses\nSpecial: appears behind "+ "your plants\nWeakness: split pea and magnet-shroom",+ "Toughness: medium\nSpeed: fast\nSpecial: hops over the first plant he runs into\nWeakness: magnet-shroom",+ "Toughness: medium\nSpecial: steals your plants from above",+ "Toughness: medium\nSpeed: fast, then slow\nSpecial: puts a ladder on wall-nuts\nWeakness: magnet-shroom",+ "Toughness: medium\nSpecial: lobs basketballs at your plants",+ "Toughness: extremely high\nSpecial: smashes plants, throws his imp",+ "Toughness: low",+};++/* environment, mode, rows (bits), sun at the start, waves, reward, seeds (and the conveyor's weights) */+#define ALL5 0x1F+#define ALL6 0x3F+const LevelDef level_defs[N_LEVELS] = {+ /* the day */+ {ENV_DAY, MODE_LAWN, 1 << 2, 150, 4, P_SUNFLOWER, 1, {P_PEASHOOTER}, {0}},+ {ENV_DAY, MODE_LAWN, 0x0E, 50, 6, P_CHERRYBOMB, 2, {P_PEASHOOTER, P_SUNFLOWER}, {0}},+ {ENV_DAY, MODE_LAWN, 0x0E, 50, 8, P_WALLNUT, 3, {P_PEASHOOTER, P_SUNFLOWER, P_CHERRYBOMB}, {0}},+ {ENV_DAY, MODE_LAWN, ALL5, 50, 10, REWARD_SHOVEL, 4, {P_PEASHOOTER, P_SUNFLOWER, P_CHERRYBOMB, P_WALLNUT}, {0}},+ {ENV_DAY, MODE_BOWLING, ALL5, 0, 8, P_POTATOMINE, 2, {P_WALLNUT, P_EXPLODENUT}, {0}},+ {ENV_DAY, MODE_LAWN, ALL5, 50, 10, P_SNOWPEA, 5,+ {P_PEASHOOTER, P_SUNFLOWER, P_CHERRYBOMB, P_WALLNUT, P_POTATOMINE}, {0}},+ {ENV_DAY, MODE_LAWN, ALL5, 50, 20, P_CHOMPER, 6,+ {P_PEASHOOTER, P_SUNFLOWER, P_CHERRYBOMB, P_WALLNUT, P_POTATOMINE, P_SNOWPEA}, {0}},+ {ENV_DAY, MODE_LAWN, ALL5, 50, 10, P_REPEATER, 0, {0}, {0}},+ {ENV_DAY, MODE_LAWN, ALL5, 50, 20, REWARD_MONEY, 0, {0}, {0}},+ {ENV_DAY, MODE_CONVEYOR, ALL5, 0, 20, P_PUFFSHROOM, 7,+ {P_PEASHOOTER, P_CHERRYBOMB, P_WALLNUT, P_REPEATER, P_SNOWPEA, P_CHOMPER, P_POTATOMINE},+ {20, 20, 15, 20, 10, 5, 10}},+ /* the night */+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 10, P_SUNSHROOM, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 20, P_FUMESHROOM, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 10, P_GRAVEBUSTER, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 20, REWARD_ALMANAC, 0, {0}, {0}},+ {ENV_NIGHT, MODE_WHACK, ALL5, 0, 8, P_HYPNOSHROOM, 3, {P_POTATOMINE, P_GRAVEBUSTER, P_CHERRYBOMB}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 10, P_SCAREDYSHROOM, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 20, P_ICESHROOM, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 10, P_DOOMSHROOM, 0, {0}, {0}},+ {ENV_NIGHT, MODE_LAWN, ALL5, 50, 20, REWARD_MONEY, 0, {0}, {0}},+ {ENV_NIGHT, MODE_CONVEYOR, ALL5, 0, 20, P_LILYPAD, 7,+ {P_GRAVEBUSTER, P_ICESHROOM, P_DOOMSHROOM, P_HYPNOSHROOM, P_SCAREDYSHROOM, P_FUMESHROOM, P_PUFFSHROOM},+ {20, 15, 15, 10, 15, 15, 10}},+ /* the pool */+ {ENV_POOL, MODE_LAWN, ALL6, 50, 10, P_SQUASH, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 20, P_THREEPEATER, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 20, P_TANGLEKELP, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 30, REWARD_KEYS, 0, {0}, {0}},+ {ENV_POOL, MODE_CONVEYOR, ALL6, 0, 20, P_JALAPENO, 4, {P_LILYPAD, P_WALLNUT, P_PEASHOOTER, P_CHERRYBOMB},+ {25, 15, 25, 35}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 20, P_SPIKEWEED, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 30, P_TORCHWOOD, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 20, P_TALLNUT, 0, {0}, {0}},+ {ENV_POOL, MODE_LAWN, ALL6, 50, 30, REWARD_MONEY, 0, {0}, {0}},+ {ENV_POOL, MODE_CONVEYOR, ALL6, 0, 30, P_SEASHROOM, 8,+ {P_LILYPAD, P_SQUASH, P_THREEPEATER, P_TANGLEKELP, P_JALAPENO, P_SPIKEWEED, P_TORCHWOOD, P_TALLNUT},+ {25, 5, 25, 5, 10, 10, 10, 10}},+ /* the fog */+ {ENV_FOG, MODE_LAWN, ALL6, 50, 10, P_PLANTERN, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 20, P_CACTUS, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 10, P_BLOVER, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 20, REWARD_MONEY, 0, {0}, {0}},+ {ENV_NIGHT, MODE_VASE, ALL5, 0, 3, P_SPLITPEA, 4, {P_PEASHOOTER, P_SNOWPEA, P_SQUASH, P_HYPNOSHROOM}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 10, P_STARFRUIT, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 20, P_PUMPKIN, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 10, P_MAGNETSHROOM, 0, {0}, {0}},+ {ENV_FOG, MODE_LAWN, ALL6, 50, 20, REWARD_MONEY, 0, {0}, {0}},+ {ENV_FOG, MODE_CONVEYOR, ALL6, 0, 20, P_CABBAGEPULT, 8,+ {P_LILYPAD, P_SEASHROOM, P_MAGNETSHROOM, P_BLOVER, P_CACTUS, P_STARFRUIT, P_SPLITPEA, P_PUMPKIN},+ {25, 10, 5, 5, 15, 25, 5, 10}},+ /* the roof */+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 10, P_FLOWERPOT, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 20, P_KERNELPULT, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 20, P_COFFEEBEAN, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 30, REWARD_MONEY, 0, {0}, {0}},+ {ENV_ROOF, MODE_CONVEYOR, ALL5, 0, 20, P_GARLIC, 4, {P_FLOWERPOT, P_CHOMPER, P_PUMPKIN, P_CHERRYBOMB},+ {50, 25, 15, 10}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 20, P_UMBRELLA, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 30, P_MARIGOLD, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 20, P_MELONPULT, 0, {0}, {0}},+ {ENV_ROOF, MODE_LAWN, ALL5, 50, 30, REWARD_MONEY, 0, {0}, {0}},+ {ENV_ROOF, MODE_CONVEYOR, ALL5, 0, 0, REWARD_TROPHY, 6,+ {P_FLOWERPOT, P_MELONPULT, P_JALAPENO, P_CABBAGEPULT, P_KERNELPULT, P_ICESHROOM}, {55, 10, 12, 10, 5, 8}},+};++/* the graves already on the lawn at night: (column, how many) */+const uint8_t grave_columns[N_LEVELS][6][2] = {+ [10] = {{6, 1}, {7, 1}, {8, 2}},+ [11] = {{6, 1}, {7, 1}, {8, 2}},+ [12] = {{6, 1}, {7, 1}, {8, 2}},+ [13] = {{5, 1}, {6, 1}, {7, 2}, {8, 3}},+ [15] = {{5, 1}, {6, 1}, {7, 2}, {8, 3}},+ [16] = {{4, 1}, {5, 2}, {6, 2}, {7, 3}, {8, 3}},+ [17] = {{4, 1}, {5, 2}, {6, 2}, {7, 3}, {8, 3}},+ [18] = {{4, 1}, {5, 2}, {6, 2}, {7, 3}, {8, 3}},+ [19] = {{3, 1}, {4, 2}, {5, 2}, {6, 2}, {7, 3}, {8, 3}},+};diff --git a/games/pvz/src/game.h b/games/pvz/src/game.hnew file mode 100644index 00000000..5362ef5f--- /dev/null+++ b/games/pvz/src/game.h@@ -0,0 +1,318 @@+/* Plants vs. Zombies: the lawn and everything on it.+ *+ * The simulation is the game's own, at its own scale: positions in the pixels of+ * its 800 x 600 screen (the lawn's left at 40, its top at 80, cells 80 wide and+ * 100 high, 85 in the backyard and on the roof), time in ticks of a hundredth of+ * a second, health, damage, speeds and timers as the game counts them. Drawing+ * scales it all by 0.4 to the calculator's screen. */+#ifndef PVZ_GAME_H+#define PVZ_GAME_H+#include <stdbool.h>+#include <stdint.h>++#define COLS 9+#define MAX_ROWS 6+#define BOARD_LEFT 40+#define BOARD_TOP 80+#define CELL_W 80++enum Plant_ {+ P_PEASHOOTER, P_SUNFLOWER, P_CHERRYBOMB, P_WALLNUT, P_POTATOMINE, P_SNOWPEA, P_CHOMPER, P_REPEATER,+ P_PUFFSHROOM, P_SUNSHROOM, P_FUMESHROOM, P_GRAVEBUSTER, P_HYPNOSHROOM, P_SCAREDYSHROOM, P_ICESHROOM, P_DOOMSHROOM,+ P_LILYPAD, P_SQUASH, P_THREEPEATER, P_TANGLEKELP, P_JALAPENO, P_SPIKEWEED, P_TORCHWOOD, P_TALLNUT,+ P_SEASHROOM, P_PLANTERN, P_CACTUS, P_BLOVER, P_SPLITPEA, P_STARFRUIT, P_PUMPKIN, P_MAGNETSHROOM,+ P_CABBAGEPULT, P_FLOWERPOT, P_KERNELPULT, P_COFFEEBEAN, P_GARLIC, P_UMBRELLA, P_MARIGOLD, P_MELONPULT,+ P_EXPLODENUT, /* the red wall-nut of Wall-nut Bowling */+ N_PLANTS,+ N_SEEDS = P_EXPLODENUT+};+enum Zombie_ {+ Z_NORMAL, Z_FLAG, Z_CONE, Z_POLE, Z_BUCKET, Z_NEWSPAPER, Z_DOOR, Z_FOOTBALL, Z_DANCER, Z_BACKUP, Z_DUCKY,+ Z_SNORKEL, Z_ZOMBONI, Z_BOBSLED, Z_DOLPHIN, Z_JACK, Z_BALLOON, Z_DIGGER, Z_POGO, Z_BUNGEE, Z_LADDER, Z_CATAPULT,+ Z_GARGANTUAR, Z_IMP,+ N_ZOMBIES+};+enum { ENV_DAY, ENV_NIGHT, ENV_POOL, ENV_FOG, ENV_ROOF };+enum { MODE_LAWN, MODE_BOWLING, MODE_CONVEYOR, MODE_WHACK, MODE_VASE };+#define N_LEVELS 50++/* ---------------------------------------------------------------- facts (defs.c) */+typedef struct {+ const char *name;+ uint16_t cost;+ uint16_t cooldown; /* ticks */+ int16_t health;+ uint8_t mushroom; /* sleeps in the day */+ uint8_t anim; /* (index into plant_anims) */+} PlantDef;+extern const PlantDef plant_defs[N_PLANTS];+extern const char *const plant_blurbs[N_SEEDS]; /* the Almanac's */+extern const char *const plant_stats[N_SEEDS];++typedef struct {+ const char *name;+ uint8_t value, starting, first_wave;+ uint16_t weight;+ uint64_t allowed; /* bit l: allowed in level l + 1 */+} ZombieDef;+extern const ZombieDef zombie_defs[N_ZOMBIES];+extern const char *const zombie_blurbs[N_ZOMBIES];+extern const char *const zombie_stats[N_ZOMBIES];++typedef struct {+ uint8_t env, mode, rows; /* rows: a bit for each row zombies come in */+ uint16_t sun; /* sun to start with */+ uint8_t waves;+ int8_t reward; /* the plant found at the end, or REWARD_* */+ uint8_t nseeds;+ uint8_t seeds[10]; /* the seed packets of a level without a choice, or the conveyor's plants */+ uint8_t weights[10]; /* the conveyor's */+} LevelDef;+enum { REWARD_NONE = -1, REWARD_SHOVEL = -2, REWARD_ALMANAC = -3, REWARD_KEYS = -4, REWARD_MONEY = -5,+ REWARD_TROPHY = -6 };+extern const LevelDef level_defs[N_LEVELS];+extern const uint8_t grave_columns[N_LEVELS][6][2];++/* ---------------------------------------------------------------- the lawn */+enum {+ PF_AWAKE = 1, /* a mushroom woken by coffee */+ PF_SCARED = 2, /* a scaredy-shroom hiding */+ PF_TALL = 4, /* a cactus stretched up for balloons */+ PF_GROWN = 8, /* a sun-shroom grown up */+};+typedef struct {+ uint16_t id;+ uint8_t kind, row, col, flags;+ uint8_t state; /* chomper: CH_*; squash: jumping; kelp: holding */+ uint8_t pad;+ int16_t health;+ int16_t action; /* ticks to its next action */+ int16_t aux; /* chomper, squash, kelp: ticks left; split pea: its rear pea; potato mine: armed */+ uint16_t target; /* the zombie a squash or kelp is after */+ float tx; /* where a squash lands */+ uint32_t born, shot; /* ticks: planted, last shot */+} Plant;+enum { CH_READY, CH_BITE, CH_DIGEST, CH_RECOVER };++enum {+ ZF_HYPNO = 1, ZF_MINI = 2, ZF_FLYING = 4, ZF_DOLPHIN = 8, ZF_POGO = 16, ZF_UNDERGROUND = 32, ZF_BACKWARDS = 64,+ ZF_METAL_GONE = 128, ZF_POLE = 256, ZF_EATING = 512, ZF_OPENING = 1024, ZF_IN_WATER = 2048, ZF_HEADLESS = 4096,+ ZF_PAPER_GONE = 8192, ZF_SPAWNED = 16384+};+enum { DP_INTRO, DP_POINT, DP_HOLD, DP_DANCE }; /* the dancer */+enum { BP_DOWN, BP_WAIT, BP_UP }; /* the bungee */+enum { CP_WALK, CP_SHOOT, CP_RELOAD }; /* the catapult */+enum { GP_WALK, GP_SMASH, GP_THROW }; /* the gargantuar */+typedef struct {+ uint16_t id;+ uint8_t kind, row;+ uint16_t flags;+ uint8_t wave;+ int8_t bite; /* ticks to its next bite */+ float x, speed;+ float walk; /* pixels walked (its walk's animation) */+ float anim; /* ticks of its other animations */+ int16_t health, armor, shield;+ int16_t chill, frozen, butter, rise;+ float vault, rage; /* ticks left of a pole vault, a newspaper's rage */+ int16_t garlic, ladder_in, emerge, landing, pop, blown, crash;+ uint8_t garlic_row, phase;+ uint32_t hit_at; /* tick of the last hit: a flash */+ union {+ struct { int16_t in; } jack;+ struct { uint16_t leader; uint8_t slot, pad; int16_t dance_in, summon_in; } dance;+ struct { uint8_t column, drop; int16_t left; } bungee;+ struct { uint8_t ammo, pad; int16_t left; } catapult;+ struct { uint8_t thrown, pad; int16_t pad2; float left; } giant;+ struct { int16_t left, duration; float sx, ex; } flight;+ struct { uint16_t sled, leader; } sled;+ } u;+} Zombie;++enum { S_PEA, S_ICE, S_FIRE, S_PUFF, S_SPIKE, S_STAR, S_CABBAGE, S_KERNEL, S_BUTTER, S_MELON, S_BASKETBALL };+enum { SF_HIGH = 1, SF_LONG = 2, SF_DONE = 4, SF_ROOFCHECK = 8 };+typedef struct {+ uint16_t id;+ uint8_t kind, row, flags;+ uint8_t torch; /* the column of the torchwood that lit it, 0xFF none */+ int16_t age;+ float x, y, vx, vy; /* (y only for stars, lobs, and the roof's straight shots: their start's height) */+ /* lobbed: */+ uint16_t target;+ int16_t duration;+ float sx, ex, sy, ey;+} Shot;++typedef struct { float x, y, ty; int16_t left; uint8_t value, flags; } Sun; /* flags: 1 from the sky */+typedef struct { float x, y, ty; int16_t left; uint16_t value; } Coin;+typedef struct { uint16_t id; uint8_t kind, row; float x, y; int8_t dir; uint8_t nhit; uint16_t hit[6]; } Roller;+typedef struct { uint8_t row, col; } Cell;+typedef struct { uint8_t row, col; int16_t left; } Crater;+typedef struct { float x; int16_t left; } Ice;+typedef struct { float x; uint8_t state; } Mower; /* 0 ready, 1 moving, 2 gone */+typedef struct { uint8_t kind; float x; } Packet;+typedef struct { uint8_t row, col, green, zombie, kind; } Vase;+typedef struct { uint8_t kind, row, col, times; int16_t left; } Drop;++/* what is only seen: the dead, explosions, splats */+enum { FX_CORPSE, FX_BOOM, FX_DOOM, FX_FIRE, FX_FREEZE, FX_SPLAT, FX_DIRT, FX_SPLASH, FX_SUNFLY, FX_COINFLY,+ FX_SMOKE, FX_TEXT, FX_HEAD, FX_POW, FX_ZZZ };+typedef struct {+ uint8_t kind, flags; /* flags: GFX_FLIP, 2 mini, 4 burnt */+ uint16_t anim; /* a corpse's animation */+ int16_t tint;+ float x, y;+ int16_t t, life; /* ticks */+ int16_t v; /* a row, a value */+} Fx;++#define MAX_PLANTS 150+#define MAX_ZOMBIES 100+#define MAX_SHOTS 120+#define MAX_SUNS 40+#define MAX_COINS 24+#define MAX_FX 72+#define MAX_ROLLERS 12++enum { PH_INTRO, PH_PLAY, PH_WON, PH_LOST };+typedef struct {+ /* the level */+ uint8_t level, env, mode, nrows, rows; /* rows: lanes zombies use */+ uint8_t phase;+ uint32_t ticks;+ uint32_t rng;+ int32_t sun;+ uint32_t money; /* coins picked up this level */+ uint16_t next_id;+ /* seeds */+ uint8_t nseeds, seeds[10];+ int16_t cooldown[10];+ uint8_t npackets; /* the conveyor */+ Packet packets[10];+ int16_t conveyor_in;+ uint8_t last_conveyor;+ /* waves */+ uint8_t wave, nwaves;+ uint8_t waves[50][24]; /* the zombies of each wave, 0xFF ends */+ int16_t wave_in, flag_warning;+ uint32_t wave_elapsed;+ int32_t wave_threshold;+ int16_t sun_in;+ uint16_t suns_fallen;+ int16_t grave_wave_in;+ uint8_t row_last[MAX_ROWS], row_second[MAX_ROWS];+ int8_t row_mowed[MAX_ROWS];+ uint8_t started;+ uint8_t tutorial; /* TUT_* */+ uint8_t first_coin;+ 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];+ Crater craters[16];+ Cell ladders[24];+ Ice ice[MAX_ROWS];+ Vase vases[45];+ Drop drops[30];+ uint8_t vase_stage;+ /* whack-a-zombie */+ int16_t whack_spawn_in;+ uint8_t whack_final;+ int16_t hammer_t;+ /* stats */+ uint16_t kills, planted;+ /* the last zombie's place: where the reward drops */+ float last_x, last_y;+ uint8_t has_boss;+} Board;++extern Board B;++/* ---------------------------------------------------------------- board.c */+float row_y(int row, float x); /* the ground's height in a row, at x */+float cell_x(int col); /* a cell's middle */+int row_at(float y, float x);+int col_at(float x);+float cell_h(void);+bool water_row(int row);+bool is_night(void);+bool is_pool(void);+uint32_t rnd(void);+float frand(void); /* 0 to 1 */+int irand(int n); /* 0 to n - 1 */+void board_start(int level);+void board_tick(void);+bool board_plant(int seed, int col, int row); /* seed: the packet's index (or the conveyor's) */+int plant_issue(int kind, int col, int row); /* 0 fine, else why not (ISSUE_*) */+enum { ISSUE_NONE, ISSUE_PLACE, ISSUE_OCCUPIED, ISSUE_SUN, ISSUE_RECHARGE, ISSUE_WATER, ISSUE_LILY, ISSUE_POT,+ ISSUE_ROOF, ISSUE_GRAVE, ISSUE_CRATER, ISSUE_COFFEE, ISSUE_BOWLING, ISSUE_ICE };+extern const char *const issue_text[];+bool board_dig(int col, int row);+Plant *dig_target(int col, int row);+int board_collect(float x, float y, float r); /* picks up sun and coins near a point; returns how many */+bool board_whack(float x, float y);+void board_break_vase(int col, int row);+int plant_cost(int kind);+bool sleeping(const Plant *p);+uint16_t new_id(void);+Plant *plant_at(int col, int row, int kind); /* -1: any but lily pads, pots and pumpkins */+Zombie *zombie_by_id(uint16_t id);+void fx_add(int kind, float x, float y, int life, int v);+Fx *fx_corpse(const Zombie *z, int anim, int life, int burnt);+void add_sun(float x, float y, float ty, int value, bool sky);+void add_coin(float x, float y, int value);+bool board_won(void);+int seed_kind(int slot); /* the plant of a packet */+bool has_conveyor(void);+int waves_flag_every(void);+bool is_flag_wave(int wave);+void board_drop_reward(void);++/* ---------------------------------------------------------------- zombies.c */+Zombie *spawn_zombie(int kind, int row, float x, int wave);+void zombies_tick(void);+void damage_zombie(Zombie *z, int amount, bool through_shield);+bool zombie_flying(const Zombie *z);+bool zombie_submerged(const Zombie *z);+bool zombie_headless(const Zombie *z);+float walking_speed(const Zombie *z);+int zombie_total_health(const Zombie *z);+void kill_zombie(Zombie *z, int how);+enum { DIE_NORMAL, DIE_BURN, DIE_GONE, DIE_MOWED, DIE_SQUASH };+void drop_from_sky(int kind, int row, int wave);++/* ---------------------------------------------------------------- plants.c */+void plants_tick(void);+void shots_tick(void);+void plant_new(Plant *p, int kind, int col, int row);++/* ---------------------------------------------------------------- boss.c */+#define BOSS_HEALTH 40000+typedef struct {+ int32_t health;+ uint8_t phase, clip, mode, row, column, ball_kind;+ float elapsed, duration;+ uint8_t fps;+ int32_t age, anim;+ int16_t summon_in, head_in, stomp_in, bungee_in, chill, frozen;+ uint32_t hit_at;+ struct { uint8_t on, kind, row; float x; int16_t age; } ball;+} Boss;+extern Boss boss;+void boss_start(void);+void boss_tick(void);+bool boss_vulnerable(void);+void boss_damage(int amount);+void boss_draw(void);+#endifdiff --git a/games/pvz/src/gfx.c b/games/pvz/src/gfx.cnew file mode 100644index 00000000..f5005b00--- /dev/null+++ b/games/pvz/src/gfx.c@@ -0,0 +1,613 @@+/* Drawing: the draw list, rasterised in bands (gfx.h). */+#include <stdarg.h>+#include <string.h>+#include "../../../launcher/src/inflate.h"+#include "gfx.h"+#include "res.h"++uint8_t gfx_bg[SCREEN_W * SCREEN_H];+uint16_t gfx_bg_pal[256];+bool gfx_bg_on;+int gfx_dropped;++enum { IT_ANIM, IT_RECT, IT_RRECT, IT_ELLIPSE, IT_TEXT, IT_CUSTOM };+typedef struct {+ uint8_t type, flags, alpha, font;+ int16_t x, y, w, h; /* what it covers, for skipping bands */+ int16_t cx0, cy0, cx1, cy1; /* its clip */+ union {+ struct {+ uint16_t frame, base_frame; /* base: 0xFFFF none */+ uint16_t sx, sy; /* scale, 256 = 1 */+ const uint16_t *pal, *base_pal;+ int16_t ax, ay; /* the anchor */+ } a;+ struct { uint16_t color; int16_t r; } r;+ struct { const char *s; uint16_t color; } t;+ struct { gfx_fn fn; void *ctx; } c;+ } u;+} Item;++static Item items[GFX_MAX_ITEMS];+static int nitems;+static uint16_t *band;+static int clip_x0, clip_y0, clip_x1 = SCREEN_W, clip_y1 = SCREEN_H;+static char text_pool[GFX_TEXT_POOL];+static int text_used;++/* palettes changed for a tint, this frame */+#define TINT_SLOTS 24+#define TINT_COLORS 64+static struct { uint16_t pal; uint8_t tint, used; uint16_t col[TINT_COLORS]; } tints[TINT_SLOTS];+static int ntints;++void gfx_set_band_memory(uint16_t *px) { band = px; }++static int imin(int a, int b) { return a < b ? a : b; }+static int imax(int a, int b) { return a > b ? a : b; }++void gfx_clip(int x, int y, int w, int h) {+ clip_x0 = imax(0, x), clip_y0 = imax(0, y), clip_x1 = imin(SCREEN_W, x + w), clip_y1 = imin(SCREEN_H, y + h);+}+void gfx_clip_all(void) { clip_x0 = clip_y0 = 0, clip_x1 = SCREEN_W, clip_y1 = SCREEN_H; }++void gfx_begin(void) {+ nitems = 0, text_used = 0, ntints = 0, gfx_dropped = 0;+ gfx_clip_all();+}++static Item *add(int type, int x, int y, int w, int h) {+ if (nitems >= GFX_MAX_ITEMS) {+ gfx_dropped++;+ return NULL;+ }+ if (x >= clip_x1 || y >= clip_y1 || x + w <= clip_x0 || y + h <= clip_y0 || w <= 0 || h <= 0) return NULL;+ Item *it = &items[nitems++];+ it->type = (uint8_t)type, it->flags = 0, it->alpha = 32;+ it->x = (int16_t)x, it->y = (int16_t)y, it->w = (int16_t)w, it->h = (int16_t)h;+ it->cx0 = (int16_t)clip_x0, it->cy0 = (int16_t)clip_y0, it->cx1 = (int16_t)clip_x1, it->cy1 = (int16_t)clip_y1;+ return it;+}++/* ---------------------------------------------------------------- colours */++static uint16_t tint_color(uint16_t c, int tint) {+ int r = c >> 11, g = (c >> 5) & 63, b = c & 31;+ switch (tint) {+ case TINT_HIT: /* a flash: brighter */+ r = imin(31, r + 6), g = imin(63, g + 12), b = imin(31, b + 6);+ break;+ case TINT_CHILL: { /* the chill of a snow pea: blue */+ r = r * 9 / 16, g = g * 13 / 16 + 6, b = imin(31, b * 3 / 4 + 11);+ break;+ }+ case TINT_FROZEN: {+ int l = (r * 2 + g + b * 2) / 5;+ r = imin(31, l / 2 + 10), g = imin(63, l + 26), b = 31;+ break;+ }+ case TINT_HYPNO: /* charmed by a hypno-shroom: pinkish */+ r = imin(31, (r + 31) / 2), g = g * 2 / 3, b = imin(31, (b + 28) / 2);+ break;+ case TINT_SLEEP: /* a mushroom asleep in the day */+ r = r * 5 / 8, g = g * 5 / 8, b = imin(31, b * 5 / 8 + 3);+ break;+ case TINT_DARK:+ r /= 2, g /= 2, b /= 2;+ break;+ case TINT_WHITE:+ r = 31, g = 63, b = 31;+ break;+ case TINT_BLACK:+ r = g = b = 0;+ break;+ case TINT_RED:+ r = imin(31, r + 10), g = g * 2 / 3, b = b * 2 / 3;+ break;+ case TINT_GRAY: {+ int l = (r * 2 + g + b * 2) / 5;+ r = l / 2, g = l, b = l / 2;+ break;+ }+ }+ return (uint16_t)(r << 11 | g << 5 | b);+}++static const uint16_t *palette(int pal, int tint) {+ int n;+ const uint16_t *c = pal_colors(pal, &n);+ if (tint == TINT_NONE || n > TINT_COLORS) return c;+ for (int i = 0; i < ntints; i++)+ if (tints[i].pal == pal && tints[i].tint == tint) return tints[i].col;+ if (ntints == TINT_SLOTS) return c;+ tints[ntints].pal = (uint16_t)pal, tints[ntints].tint = (uint8_t)tint;+ for (int i = 0; i < n; i++) tints[ntints].col[i] = tint_color(c[i], tint);+ return tints[ntints++].col;+}++/* ---------------------------------------------------------------- the background */++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;+ if (x1 <= x0) x0 = 0, x1 = SCREEN_W;+ 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 tables[3600];+ if (np_inflate_tables_size() > sizeof tables || bk.w * bk.rows > (int)sizeof chunk) 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);+ if (got < bk.w) return false;+ for (int r = 0; r < bk.rows && ry + r < SCREEN_H; r++) {+ int y = ry + r;+ if (y < y0 || y >= y1 || (r + 1) * bk.w > got) continue;+ for (int x = x0; x < x1; x++) {+ int sx = src_x + x;+ gfx_bg[y * SCREEN_W + x] = chunk[r * bk.w + (sx < 0 ? 0 : sx >= bk.w ? bk.w - 1 : sx)];+ }+ }+ }+ gfx_bg_on = true;+ return true;+}+bool gfx_load_back(int b, int src_x) { return gfx_load_back_rows(b, src_x, 0, 0, 0, 0); }++/* ---------------------------------------------------------------- sprites */++void anim_box(int a, int f, int *x, int *y, int *w, int *h) {+ Anim an = anim_info(a);+ Frame fr = frame_info(an.first + (f % an.frames));+ *x = fr.x, *y = fr.y, *w = fr.w, *h = fr.h;+}++int anim_frame_at(int a, uint32_t t) {+ Anim an = anim_info(a);+ if (an.frames <= 1 || !an.cycle) return 0;+ return (int)((t % an.cycle) * an.frames / an.cycle);+}++static void add_anim(int a, int f, int x, int y, int sx, int sy, int flags, int tint, int alpha) {+ Anim an = anim_info(a);+ if (!an.frames) return;+ f = ((f % an.frames) + an.frames) % an.frames;+ Frame fr = frame_info(an.first + f);+ int bx = fr.x, by = fr.y, bw = fr.w, bh = fr.h, base = 0xFFFF;+ const uint16_t *bpal = NULL;+ if (an.base != 0xFFFF) {+ Anim bn = anim_info(an.base);+ base = bn.first + f % bn.frames;+ Frame b = frame_info(base);+ int x1 = imax(bx + bw, b.x + b.w), y1 = imax(by + bh, b.y + b.h);+ bx = imin(bx, b.x), by = imin(by, b.y), bw = x1 - bx, bh = y1 - by;+ bpal = palette(bn.pal, tint);+ }+ int x0, y0, w, h;+ if (flags & GFX_FLIP) bx = -(bx + bw);+ x0 = x + bx * sx / 256, y0 = y + by * sy / 256, w = (bw * sx + 255) / 256 + 1, h = (bh * sy + 255) / 256 + 1;+ Item *it = add(IT_ANIM, x0, y0, w, h);+ if (!it) return;+ it->flags = (uint8_t)flags, it->alpha = (uint8_t)alpha;+ it->u.a.frame = (uint16_t)(an.first + f), it->u.a.base_frame = (uint16_t)base;+ it->u.a.sx = (uint16_t)sx, it->u.a.sy = (uint16_t)sy;+ it->u.a.pal = palette(an.pal, tint), it->u.a.base_pal = bpal;+ it->u.a.ax = (int16_t)x, it->u.a.ay = (int16_t)y;+ it->font = an.bpp;+ if (an.base != 0xFFFF && anim_info(an.base).bpp != an.bpp) it->font |= 0x80; /* (never: overlays share 4 bits) */+}++void gfx_anim(int a, int f, int x, int y, int flags, int tint, int alpha) {+ if (alpha <= 0) return;+ add_anim(a, f, x, y, 256, 256, flags, tint, alpha);+}+void gfx_anim_scaled(int a, int f, int x, int y, int sx, int sy, int flags, int tint, int alpha) {+ if (alpha <= 0 || sx <= 0 || sy <= 0) return;+ add_anim(a, f, x, y, sx, sy, flags, tint, alpha);+}++static inline uint16_t half(uint16_t a, uint16_t b) { return (uint16_t)(((a & 0xF7DE) >> 1) + ((b & 0xF7DE) >> 1)); }++/* one row of a frame into idx / vis (0 none, 1 half, 2 opaque); returns the pointer past it */+static void decode_row(const uint8_t *p, const uint8_t *e, int bpp, uint8_t *idx, uint8_t *vis, int w) {+ int x = 0;+ memset(vis, 0, (size_t)w);+ while (p < e && x < w) {+ int t = *p++;+ if (t < 0x40) {+ x += t + 1;+ } else if (t < 0xC0) {+ int n = (t & 0x3F) + 1, v = t < 0x80 ? 2 : 1;+ if (bpp == 4) {+ for (int i = 0; i < n; i += 2) {+ int b = *p++;+ if (x < w) idx[x] = (uint8_t)(b & 15), vis[x] = (uint8_t)v;+ x++;+ if (i + 1 < n) {+ if (x < w) idx[x] = (uint8_t)(b >> 4), vis[x] = (uint8_t)v;+ x++;+ }+ }+ } else {+ for (int i = 0; i < n; i++, x++)+ if (x < w) idx[x] = p[i], vis[x] = (uint8_t)v;+ p += n;+ }+ } else {+ int n, c;+ if (bpp == 4) n = 2 + ((t >> 4) & 3), c = t & 15;+ else n = t - 0xBE, c = *p++;+ for (int i = 0; i < n; i++, x++)+ if (x < w) idx[x] = (uint8_t)c, vis[x] = 2;+ }+ }+}++/* the start of row r of a frame, and its end */+static const uint8_t *row_at(const Frame *f, int bpp, int r, const uint8_t **end) {+ if (bpp == 4) {+ const uint8_t *p = f->rows + f->h;+ for (int i = 0; i < r; i++) p += f->rows[i];+ *end = p + f->rows[r];+ return p;+ }+ const uint8_t *base = f->rows;+ *end = r + 1 < f->h ? base + rd16(base + 2 * r + 2) : NULL;+ return base + rd16(base + 2 * r);+}++static void blit_frame(const Item *it, int fi, const uint16_t *pal, int bpp, int y0, int y1) {+ Frame f = frame_info(fi);+ int flip = it->flags & GFX_FLIP, alpha = it->alpha;+ int cx0 = it->cx0, cx1 = it->cx1;+ y0 = imax(y0, it->cy0), y1 = imin(y1, it->cy1);+ if (it->u.a.sx != 256 || it->u.a.sy != 256) {+ /* scaled: each screen pixel from the frame's pixel under it */+ int sx = it->u.a.sx, sy = it->u.a.sy;+ int fx = flip ? -(f.x + f.w) : f.x;+ int ox = it->u.a.ax + fx * sx / 256, oy = it->u.a.ay + f.y * sy / 256;+ int dw = f.w * sx / 256, dh = f.h * sy / 256;+ uint8_t idx[320], vis[320];+ int last = -1;+ for (int y = imax(y0, oy); y < imin(y1, oy + dh); y++) {+ int r = (y - oy) * 256 / sy;+ if (r >= f.h) break;+ if (r != last) {+ const uint8_t *e, *p = row_at(&f, bpp, r, &e);+ if (!e) e = p + 4 * f.w + 8;+ decode_row(p, e, bpp, idx, vis, imin(f.w, 320));+ last = r;+ }+ uint16_t *out = band + (y % GFX_BAND) * SCREEN_W;+ for (int x = imax(cx0, ox); x < imin(cx1, ox + dw); x++) {+ int c = (x - ox) * 256 / sx;+ if (c >= f.w) break;+ if (flip) c = f.w - 1 - c;+ int v = vis[c];+ if (!v) continue;+ uint16_t col = pal[idx[c]];+ if (v == 2) out[x] = alpha >= 32 ? col : mix565(col, out[x], alpha);+ else out[x] = alpha >= 32 ? half(col, out[x]) : mix565(col, out[x], alpha / 2);+ }+ }+ return;+ }+ int fx = flip ? -(f.x + f.w) : f.x;+ int ox = it->u.a.ax + fx, oy = it->u.a.ay + f.y;+ int ya = imax(y0, oy), yb = imin(y1, oy + f.h);+ if (ya >= yb) return;+ const uint8_t *e, *p = row_at(&f, bpp, ya - oy, &e);+ for (int y = ya; y < yb; y++) {+ int r = y - oy;+ if (bpp == 4) e = p + f.rows[r];+ else {+ p = f.rows + rd16(f.rows + 2 * r);+ e = r + 1 < f.h ? f.rows + rd16(f.rows + 2 * r + 2) : p + 4 * f.w + 8;+ }+ uint16_t *out = band + (y % GFX_BAND) * SCREEN_W;+ int x = 0, w = f.w;+ const uint8_t *q = p;+ while (q < e && x < w) {+ int t = *q++;+ if (t < 0x40) {+ x += t + 1;+ continue;+ }+ if (t < 0xC0) {+ int n = (t & 0x3F) + 1, opaque = t < 0x80;+ for (int i = 0; i < n; i++, x++) {+ int c = bpp == 4 ? (i & 1 ? q[i >> 1] >> 4 : q[i >> 1] & 15) : q[i];+ int dx = flip ? ox + w - 1 - x : ox + x;+ if (dx < cx0 || dx >= cx1) continue;+ uint16_t col = pal[c];+ if (opaque) out[dx] = alpha >= 32 ? col : mix565(col, out[dx], alpha);+ else out[dx] = alpha >= 32 ? half(col, out[dx]) : mix565(col, out[dx], alpha / 2);+ }+ q += bpp == 4 ? (n + 1) >> 1 : n;+ continue;+ }+ int n, c;+ if (bpp == 4) n = 2 + ((t >> 4) & 3), c = t & 15;+ else n = t - 0xBE, c = *q++;+ uint16_t col = pal[c];+ for (int i = 0; i < n; i++, x++) {+ int dx = flip ? ox + w - 1 - x : ox + x;+ if (dx < cx0 || dx >= cx1) continue;+ out[dx] = alpha >= 32 ? col : mix565(col, out[dx], alpha);+ }+ }+ if (bpp == 4) p = e;+ }+}++/* ---------------------------------------------------------------- shapes */++void gfx_rect(int x, int y, int w, int h, uint16_t color, int alpha) {+ if (alpha <= 0) return;+ Item *it = add(IT_RECT, x, y, w, h);+ if (it) it->alpha = (uint8_t)imin(alpha, 32), it->u.r.color = color, it->u.r.r = 0;+}+void gfx_frame_rect(int x, int y, int w, int h, int t, uint16_t color, int alpha) {+ gfx_rect(x, y, w, t, color, alpha);+ gfx_rect(x, y + h - t, w, t, color, alpha);+ gfx_rect(x, y + t, t, h - 2 * t, color, alpha);+ gfx_rect(x + w - t, y + t, t, h - 2 * t, color, alpha);+}+void gfx_round_rect(int x, int y, int w, int h, int r, uint16_t color, int alpha) {+ if (alpha <= 0) return;+ Item *it = add(IT_RRECT, x, y, w, h);+ if (it) it->alpha = (uint8_t)imin(alpha, 32), it->u.r.color = color, it->u.r.r = (int16_t)imin(r, imin(w, h) / 2);+}+void gfx_ellipse(int cx, int cy, int rx, int ry, uint16_t color, int alpha) {+ if (alpha <= 0 || rx <= 0 || ry <= 0) return;+ Item *it = add(IT_ELLIPSE, cx - rx, cy - ry, 2 * rx + 1, 2 * ry + 1);+ if (it) it->alpha = (uint8_t)imin(alpha, 32), it->u.r.color = color, it->u.r.r = 0;+}+void gfx_custom(gfx_fn fn, void *ctx) {+ Item *it = add(IT_CUSTOM, 0, 0, SCREEN_W, SCREEN_H);+ if (it) it->u.c.fn = fn, it->u.c.ctx = ctx;+}++static int isqrt(int v) {+ int r = 0;+ while ((r + 1) * (r + 1) <= v) r++;+ return r;+}++static void span(uint16_t *out, int a, int b, const Item *it) {+ a = imax(a, it->cx0), b = imin(b, it->cx1);+ uint16_t c = it->u.r.color;+ if (it->alpha >= 32)+ for (int x = a; x < b; x++) out[x] = c;+ else if (it->alpha == 16)+ for (int x = a; x < b; x++) out[x] = half(c, out[x]);+ else+ for (int x = a; x < b; x++) out[x] = mix565(c, out[x], it->alpha);+}++/* ---------------------------------------------------------------- text */++static const uint8_t *glyph(const Font *f, int ch) {+ if (ch < f->first || ch >= f->first + f->count) ch = '?';+ return f->glyphs + 8 * (ch - f->first);+}++int font_line(int font) {+ Font f = font_info(font);+ return f.ascent + f.descent + 1;+}++static int line_width(const Font *f, const char *s) {+ int w = 0;+ for (; *s && *s != '\n'; s++) w += glyph(f, (uint8_t)*s)[4];+ return w;+}++int gfx_text_width(int font, const char *s) {+ Font f = font_info(font);+ int w = 0;+ while (*s) {+ w = imax(w, line_width(&f, s));+ while (*s && *s != '\n') s++;+ if (*s) s++;+ }+ return w;+}++int gfx_text(int font, int x, int y, const char *s, uint16_t color, int flags) {+ Font f = font_info(font);+ int w = gfx_text_width(font, s), lines = 1;+ for (const char *p = s; *p; p++) lines += *p == '\n';+ int lh = font_line(font);+ int x0 = flags & GFX_CENTER ? x - w / 2 : flags & GFX_RIGHT ? x - w : x;+ Item *it = add(IT_TEXT, x0 - 2, y - f.ascent - 2, w + 4, lh * lines + 4);+ if (!it) return w;+ it->flags = (uint8_t)flags, it->font = (uint8_t)font, it->u.t.s = s, it->u.t.color = color;+ return w;+}++static void draw_text(const Item *it, int y0, int y1, int dx, int dy, uint16_t color) {+ Font f = font_info(it->font);+ int lh = font_line(it->font);+ int base = it->y + 2 + f.ascent + dy;+ const char *s = it->u.t.s;+ y0 = imax(y0, it->cy0), y1 = imin(y1, it->cy1);+ while (*s) {+ int w = line_width(&f, s);+ int x = it->flags & GFX_CENTER ? it->x + 2 + (it->w - 4) / 2 - w / 2 : it->flags & GFX_RIGHT ? it->x + it->w - 2 - w+ : it->x + 2;+ x += dx;+ for (; *s && *s != '\n'; s++) {+ const uint8_t *g = glyph(&f, (uint8_t)*s);+ int gw = g[0], gh = g[1], gx = x + (int8_t)g[2], gy = base + (int8_t)g[3];+ const uint8_t *bits = f.data + rd16(g + 6);+ for (int r = imax(0, y0 - gy); r < gh && gy + r < y1; r++) {+ uint16_t *out = band + ((gy + r) % GFX_BAND) * SCREEN_W;+ for (int c = 0; c < gw; c++) {+ int px = gx + c;+ if (px < it->cx0 || px >= it->cx1) continue;+ int i = r * gw + c, v = (bits[i >> 1] >> ((i & 1) * 4)) & 15;+ if (!v) continue;+ out[px] = v == 15 ? color : mix565(color, out[px], (v * 32 + 7) / 15);+ }+ }+ x += g[4];+ }+ if (*s) s++;+ base += lh;+ }+}++int gfx_paragraph(int font, int x, int y, int width, const char *s, uint16_t color, int flags) {+ Font f = font_info(font);+ int lh = font_line(font);+ char line[160];+ while (*s) {+ /* as many words as fit */+ int n = 0, best = 0, w = 0;+ while (s[n] && s[n] != '\n') {+ w += glyph(&f, (uint8_t)s[n])[4];+ if (w > width && best) break;+ n++;+ if (s[n] == ' ' || !s[n] || s[n] == '\n') best = n;+ }+ if (!best) best = n;+ if (best > (int)sizeof line - 1) best = (int)sizeof line - 1;+ memcpy(line, s, (size_t)best);+ line[best] = 0;+ gfx_text(font, x, y, gfx_fmt("%s", line), color, flags | GFX_CENTER);+ s += best;+ while (*s == ' ') s++;+ if (*s == '\n') s++;+ y += lh;+ }+ return y;+}++/* a printf of %d, %u, %s and %c, with a width (%3d, %-3s, %03d) */+const char *gfx_fmt(const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ char *out = text_pool + text_used, *end = text_pool + GFX_TEXT_POOL - 1;+ char *o = out;+ for (const char *p = fmt; *p && o < end; p++) {+ if (*p != '%') {+ *o++ = *p;+ continue;+ }+ p++;+ bool left = false, zero = false;+ int width = 0;+ if (*p == '-') left = true, p++;+ if (*p == '0') zero = true, p++;+ while (*p >= '0' && *p <= '9') width = width * 10 + (*p++ - '0');+ char tmp[16];+ const char *src = tmp;+ int n = 0;+ if (*p == 'd' || *p == 'u') {+ long v = *p == 'd' ? (long)va_arg(ap, int) : (long)va_arg(ap, unsigned);+ bool neg = v < 0;+ unsigned long u = neg ? (unsigned long)-v : (unsigned long)v;+ char rev[16];+ int k = 0;+ do rev[k++] = (char)('0' + u % 10), u /= 10;+ while (u && k < 15);+ if (neg) tmp[n++] = '-';+ while (k) tmp[n++] = rev[--k];+ } else if (*p == 's') {+ src = va_arg(ap, const char *);+ n = (int)strlen(src);+ } else if (*p == 'c') {+ tmp[n++] = (char)va_arg(ap, int);+ } else {+ tmp[n++] = *p;+ }+ int pad = width > n ? width - n : 0;+ if (!left)+ while (pad-- > 0 && o < end) *o++ = zero ? '0' : ' ';+ for (int i = 0; i < n && o < end; i++) *o++ = src[i];+ if (left)+ while (pad-- > 0 && o < end) *o++ = ' ';+ }+ *o++ = 0;+ va_end(ap);+ if (o > end) return "";+ text_used = (int)(o - text_pool);+ return out;+}++/* ---------------------------------------------------------------- a frame */++static void raster(int y0, int y1) {+ /* the background */+ for (int y = y0; y < y1; y++) {+ uint16_t *out = band + (y % GFX_BAND) * SCREEN_W;+ if (!gfx_bg_on) {+ memset(out, 0, SCREEN_W * 2);+ continue;+ }+ const uint8_t *s = gfx_bg + y * SCREEN_W;+ for (int x = 0; x < SCREEN_W; x += 4) {+ out[x] = gfx_bg_pal[s[x]], out[x + 1] = gfx_bg_pal[s[x + 1]];+ out[x + 2] = gfx_bg_pal[s[x + 2]], out[x + 3] = gfx_bg_pal[s[x + 3]];+ }+ }+ for (int i = 0; i < nitems; i++) {+ const Item *it = &items[i];+ if (it->y >= y1 || it->y + it->h <= y0 || it->cy0 >= y1 || it->cy1 <= y0) continue;+ int ya = imax(y0, imax(it->y, it->cy0)), yb = imin(y1, imin(it->y + it->h, it->cy1));+ switch (it->type) {+ case IT_ANIM:+ if (it->u.a.base_frame != 0xFFFF) blit_frame(it, it->u.a.base_frame, it->u.a.base_pal, it->font & 0x7F, y0, y1);+ blit_frame(it, it->u.a.frame, it->u.a.pal, it->font & 0x7F, y0, y1);+ break;+ case IT_RECT:+ for (int y = ya; y < yb; y++) span(band + (y % GFX_BAND) * SCREEN_W, it->x, it->x + it->w, it);+ break;+ case IT_RRECT: {+ int r = it->u.r.r;+ for (int y = ya; y < yb; y++) {+ /* (twice the distance from the corners' centre row, for half-pixel steps) */+ int d2 = y < it->y + r ? 2 * (it->y + r - y) - 1 : y >= it->y + it->h - r ? 2 * (y - (it->y + it->h - r)) + 1 : 0;+ int in = d2 > 0 ? r - isqrt(imax(0, r * r - d2 * d2 / 4)) : 0;+ span(band + (y % GFX_BAND) * SCREEN_W, it->x + in, it->x + it->w - in, it);+ }+ break;+ }+ case IT_ELLIPSE: {+ int rx = (it->w - 1) / 2, ry = (it->h - 1) / 2, cx = it->x + rx, cy = it->y + ry;+ for (int y = ya; y < yb; y++) {+ int dy = y - cy;+ int hw = (int)((long)rx * isqrt(imax(0, ry * ry - dy * dy)) / ry);+ span(band + (y % GFX_BAND) * SCREEN_W, cx - hw, cx + hw + 1, it);+ }+ break;+ }+ case IT_TEXT:+ if (it->flags & (GFX_OUTLINE | GFX_SHADOW)) {+ uint16_t dark = it->flags & GFX_OUTLINE ? 0x0000 : mix565(0, it->u.t.color, 8);+ if (it->flags & GFX_OUTLINE) {+ draw_text(it, y0, y1, -1, 0, dark), draw_text(it, y0, y1, 1, 0, dark);+ draw_text(it, y0, y1, 0, -1, dark), draw_text(it, y0, y1, 0, 1, dark);+ } else {+ draw_text(it, y0, y1, 1, 1, dark);+ }+ }+ draw_text(it, y0, y1, 0, 0, it->u.t.color);+ break;+ case IT_CUSTOM:+ it->u.c.fn(band, y0, y1, it->u.c.ctx);+ break;+ }+ }+}++void gfx_end(void) {+ for (int y = 0; y < SCREEN_H; y += GFX_BAND) {+ raster(y, y + GFX_BAND);+ plat_push(0, y, SCREEN_W, GFX_BAND, band);+ }+}diff --git a/games/pvz/src/gfx.h b/games/pvz/src/gfx.hnew file mode 100644index 00000000..95a39a63--- /dev/null+++ b/games/pvz/src/gfx.h@@ -0,0 +1,77 @@+/* Plants vs. Zombies: drawing.+ *+ * A frame is a draw list, rasterised band by band (the calculator has no frame+ * buffer for its screen) and pushed. Under everything is the background, one+ * byte a pixel in RAM: the lawn or a menu's picture. Commands are in screen+ * pixels and painted in the order given. */+#ifndef PVZ_GFX_H+#define PVZ_GFX_H+#include <stdbool.h>+#include <stdint.h>+#include "plat.h"++static inline uint16_t rgb565(uint32_t rgb) { /* 0xRRGGBB */+ return (uint16_t)(((rgb >> 8) & 0xF800) | ((rgb >> 5) & 0x07E0) | ((rgb >> 3) & 0x001F));+}+#define C_BLACK 0x0000+#define C_WHITE 0xFFFF++/* a colour f over b, a from 0 (all b) to 32 (all f) */+static inline uint16_t mix565(uint16_t f, uint16_t b, int a) {+ uint32_t x = (f | (uint32_t)f << 16) & 0x07E0F81F, y = (b | (uint32_t)b << 16) & 0x07E0F81F;+ y = (y + ((x - y) * (uint32_t)a >> 5)) & 0x07E0F81F;+ return (uint16_t)(y | y >> 16);+}++enum { GFX_FLIP = 1, GFX_OUTLINE = 2, GFX_CENTER = 4, GFX_RIGHT = 8, GFX_SHADOW = 16 };+/* colourings of a sprite (its palette, changed) */+enum { TINT_NONE, TINT_HIT, TINT_CHILL, TINT_FROZEN, TINT_HYPNO, TINT_SLEEP, TINT_DARK, TINT_WHITE, TINT_BLACK,+ TINT_RED, TINT_GRAY, TINT_N };++#define GFX_BAND 20 /* screen rows rasterised at a time */+#define GFX_MAX_ITEMS 360 /* commands in a frame (more are dropped) */+#define GFX_TEXT_POOL 2048 /* bytes of text in a frame */++/* the background: one palette index a pixel, and its colours */+extern uint8_t gfx_bg[SCREEN_W * SCREEN_H];+extern uint16_t gfx_bg_pal[256];+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);++/* the band: SCREEN_W * GFX_BAND pixels, the caller's (main's stack on the calculator) */+void gfx_set_band_memory(uint16_t *px);+void gfx_begin(void);+void gfx_end(void);+/* later commands draw only inside this screen rectangle (gfx_clip_all(): all of it) */+void gfx_clip(int x, int y, int w, int h);+void gfx_clip_all(void);++void gfx_rect(int x, int y, int w, int h, uint16_t color, int alpha); /* alpha 0 (none) to 32 */+void gfx_frame_rect(int x, int y, int w, int h, int t, uint16_t color, int alpha);+void gfx_round_rect(int x, int y, int w, int h, int r, uint16_t color, int alpha);+void gfx_ellipse(int cx, int cy, int rx, int ry, uint16_t color, int alpha);+/* frame f of animation a (A_* or I_*), its anchor at (x, y); alpha 32 opaque */+void gfx_anim(int a, int f, int x, int y, int flags, int tint, int alpha);+/* the same, scaled (256 = 1) from its anchor */+void gfx_anim_scaled(int a, int f, int x, int y, int sx, int sy, int flags, int tint, int alpha);+/* a picture (I_*) */+static inline void gfx_image(int a, int x, int y) { gfx_anim(a, 0, x, y, 0, TINT_NONE, 32); }+/* a sprite's size (its first frame's) and its top-left from its anchor */+void anim_box(int a, int f, int *x, int *y, int *w, int *h);+/* text in a font (F_*), its baseline at y and its left (or centre, GFX_CENTER, or right) at x; returns its+ * width. GFX_OUTLINE draws it with a dark rim; '\n' starts a line */+int gfx_text(int font, int x, int y, const char *s, uint16_t color, int flags);+int gfx_text_width(int font, const char *s);+int font_line(int font); /* the height of a line */+/* text wrapped to width, centred on x (flags as gfx_text); returns the baseline after its last line */+int gfx_paragraph(int font, int x, int y, int width, const char *s, uint16_t color, int flags);+/* copies text into the frame's pool (text kept until gfx_end), printf-like */+const char *gfx_fmt(const char *fmt, ...);+/* a call made for each band, in order with the commands (for what the commands can't draw) */+typedef void (*gfx_fn)(uint16_t *band, int y0, int y1, void *ctx);+void gfx_custom(gfx_fn fn, void *ctx);++extern int gfx_dropped;+#endifdiff --git a/games/pvz/src/plat.h b/games/pvz/src/plat.hnew file mode 100644index 00000000..ecc785ca--- /dev/null+++ b/games/pvz/src/plat.h@@ -0,0 +1,43 @@+/* Plants vs. Zombies: the platform (the calculator, or a computer for tests).+ *+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.+ * plat_host.c: a frame buffer that tests save as images, scripted keys and+ * simulated time (tests/play.c). */+#ifndef PVZ_PLAT_H+#define PVZ_PLAT_H+#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#define SCREEN_W 320+#define SCREEN_H 240++/* keys held now, as bits */+enum {+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,+ K_OK = 1 << 4, /* OK, EXE */+ K_BACK = 1 << 5, /* Back: pause, or back in menus */+ K_SHOVEL = 1 << 6, /* the delete key: the shovel */+ K_HOME = 1 << 7, /* Home, On/Off: save and quit */+ K_ALMANAC = 1 << 8, /* the toolbox key */+ K_D1 = 1 << 9, /* the digits 1 to 9, then 0: K_D1 << (n - 1), 0 is the tenth */+ K_ANY = 1 << 19+};+#define K_DIGIT(n) (K_D1 << ((n) - 1))+#define K_DIGITS (0x3FF * K_D1)+uint32_t plat_keys(void);+uint32_t plat_millis(void);+void plat_sleep(uint32_t ms);+void plat_push(int x, int y, int w, int h, const uint16_t *px);+bool plat_save(const char *name, const void *data, uint32_t len);+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its+ * bytes, plat_reserved says they are written; NULL if there is no room */+uint8_t *plat_reserve(const char *name, uint32_t len);+void plat_reserved(const char *name, uint32_t len);+bool plat_remove(const char *name);+void plat_begin(void);+int plat_end(void);+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */+bool plat_slow(void);+#endifdiff --git a/games/pvz/src/plat_eadk.c b/games/pvz/src/plat_eadk.cnew file mode 100644index 00000000..f81d34fe--- /dev/null+++ b/games/pvz/src/plat_eadk.c@@ -0,0 +1,44 @@+/* The calculator: EADK display, keyboard, time and files. */+#include <eadk.h>+#include "../../common/epsilon_app.h"+#include "../../common/epsilon_files.h"+#include "plat.h"++#define KEY(k) ((uint64_t)1 << (k))++uint32_t plat_keys(void) {+ static const uint8_t digits[10] = {eadk_key_one, eadk_key_two, eadk_key_three, eadk_key_four, eadk_key_five,+ eadk_key_six, eadk_key_seven, eadk_key_eight, eadk_key_nine, eadk_key_zero};+ uint64_t k = eadk_keyboard_scan();+ uint32_t r = 0;+ if (k & KEY(eadk_key_left)) r |= K_LEFT;+ if (k & KEY(eadk_key_right)) r |= K_RIGHT;+ if (k & KEY(eadk_key_up)) r |= K_UP;+ if (k & KEY(eadk_key_down)) r |= K_DOWN;+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) r |= K_OK;+ if (k & KEY(eadk_key_back)) r |= K_BACK;+ if (k & KEY(eadk_key_backspace)) r |= K_SHOVEL;+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;+ if (k & KEY(eadk_key_toolbox)) r |= K_ALMANAC;+ for (int i = 0; i < 10; i++)+ if (k & KEY(digits[i])) r |= K_D1 << i;+ if (k) r |= K_ANY;+ return r;+}++uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);+}+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }+uint8_t *plat_reserve(const char *name, uint32_t len) {+ uint32_t n;+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */+}+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }+bool plat_remove(const char *name) { return ef_remove(name); }+void plat_begin(void) { np_app_begin(); }+int plat_end(void) { return np_app_end(); }+bool plat_slow(void) { return epsilon_slow_model(); }diff --git a/games/pvz/src/plat_host.c b/games/pvz/src/plat_host.cnew file mode 100644index 00000000..f3f5a8c5--- /dev/null+++ b/games/pvz/src/plat_host.c@@ -0,0 +1,71 @@+/* A computer: the screen goes to a frame buffer that tests save as images,+ * keys come from a script, time is simulated. */+#include <stdio.h>+#include <stdlib.h>+#include "plat.h"++uint16_t host_fb[SCREEN_W * SCREEN_H];+uint32_t host_time; /* ms */+uint32_t host_keys;++uint32_t plat_keys(void) { return host_keys; }+uint32_t plat_millis(void) { return host_time; }+void plat_sleep(uint32_t ms) { host_time += ms; }+void plat_push(int x, int y, int w, int h, const uint16_t *px) {+ for (int r = 0; r < h; r++)+ for (int c = 0; c < w; c++)+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];+}++static char save_dir[256] = "build/host-saves";+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }+bool plat_save(const char *name, const void *data, uint32_t len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "wb");+ if (!f) return false;+ bool ok = fwrite(data, 1, len, f) == len;+ fclose(f);+ return ok;+}+/* (each file read gets its own buffer: callers may hold two at once) */+static uint8_t loaded[4][1 << 16];+static int next_load;+const uint8_t *plat_load(const char *name, uint32_t *len) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ FILE *f = fopen(p, "rb");+ if (!f) return NULL;+ uint8_t *b = loaded[next_load++ & 3];+ *len = (uint32_t)fread(b, 1, sizeof loaded[0], f);+ fclose(f);+ return b;+}+static uint8_t reserved[1 << 16];+bool host_storage_full; /* tests: no room for any file */+uint8_t *plat_reserve(const char *name, uint32_t len) {+ (void)name;+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;+}+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }+bool plat_remove(const char *name) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", save_dir, name);+ return remove(p) == 0;+}+void plat_begin(void) {}+int plat_end(void) { return 0; }+bool plat_slow(void) { return false; }++/* writes the screen as a PPM image */+void host_shot(const char *path) {+ FILE *f = fopen(path, "wb");+ if (!f) return;+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {+ uint16_t c = host_fb[i];+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};+ fwrite(rgb, 1, 3, f);+ }+ fclose(f);+}diff --git a/games/pvz/src/res.h b/games/pvz/src/res.hnew file mode 100644index 00000000..5274a43d--- /dev/null+++ b/games/pvz/src/res.h@@ -0,0 +1,65 @@+/* Plants vs. Zombies: data.bin (tools/pack.py), read where it lies in flash.+ *+ * Animations (A_*, and the single pictures I_*) are frames of runs of palette+ * colours; the lawns and menus' backgrounds (BG_*) are DEFLATE chunks of rows,+ * unpacked into RAM when a screen starts; fonts (F_*) are 4-bit glyphs. */+#ifndef PVZ_RES_H+#define PVZ_RES_H+#include <stdbool.h>+#include <stdint.h>+#include "data.h"++extern const uint8_t *pvz_bin;+static inline uint16_t rd16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }+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 };++typedef struct {+ uint16_t first, pal, cycle, base; /* base: the animation an overlay is drawn over, 0xFFFF none */+ uint8_t frames, bpp;+} Anim;+static inline Anim anim_info(int a) {+ const uint8_t *p = table(T_ANIMS) + 12 * a;+ return (Anim){rd16(p), rd16(p + 2), rd16(p + 4), rd16(p + 6), p[8], p[9]};+}+static inline int anim_frames(int a) { return table(T_ANIMS)[12 * a + 8]; }+/* the frame of animation a shown t hundredths of a second into it (looping) */+int anim_frame_at(int a, uint32_t t);++typedef struct {+ int16_t x, y; /* top-left from the anchor */+ uint16_t w, h;+ const uint8_t *rows;+} Frame;+static inline Frame frame_info(int f) {+ const uint8_t *p = table(T_FRAMES) + 12 * f;+ return (Frame){rds16(p), rds16(p + 2), rd16(p + 4), rd16(p + 6), pvz_bin + rd32(p + 8)};+}+/* a palette: its colours (RGB565, aligned) */+static inline const uint16_t *pal_colors(int p, int *n) {+ const uint8_t *q = pvz_bin + rd32(table(T_PALS) + 4 * p);+ if (n) *n = rd16(q);+ return (const uint16_t *)(const void *)(q + 4);+}++typedef struct {+ uint16_t w, h, ncol, rows, pal, nchunks;+ const uint8_t *chunks; /* nchunks + 1 offsets (u32) */+} Back;+static inline Back back_info(int b) {+ const uint8_t *p = table(T_BACKS) + 16 * b;+ return (Back){rd16(p), rd16(p + 2), rd16(p + 4), rd16(p + 6), rd16(p + 8), rd16(p + 10), pvz_bin + rd32(p + 12)};+}++typedef struct {+ uint8_t first, count, ascent, descent;+ const uint8_t *glyphs; /* 8 bytes each */+ const uint8_t *data;+} Font;+static inline Font font_info(int f) {+ const uint8_t *p = pvz_bin + rd32(table(T_FONTS) + 4 * f);+ return (Font){p[0], p[1], p[2], p[3], p + 4, p + 4 + 8 * p[1]};+}+#endifdiff --git a/games/pvz/src/zombies.c b/games/pvz/src/zombies.cnew file mode 100644index 00000000..97ab56c4--- /dev/null+++ b/games/pvz/src/zombies.c@@ -0,0 +1,746 @@+/* The zombies: how each kind walks, eats, jumps, digs, flies and dies (game.h). */+#include <string.h>+#include "game.h"+#include "save.h"++/* ---------------------------------------------------------------- facts */++static int base_health(int kind) {+ switch (kind) {+ case Z_GARGANTUAR: return 3000;+ case Z_CATAPULT: return 850;+ case Z_BUNGEE: return 450;+ case Z_ZOMBONI: return 1350;+ case Z_POLE: case Z_DANCER: case Z_DOLPHIN: case Z_JACK: case Z_LADDER: return 500;+ default: return 270;+ }+}++bool zombie_headless(const Zombie *z) {+ if (z->kind == Z_ZOMBONI || z->kind == Z_CATAPULT || z->kind == Z_GARGANTUAR || z->kind == Z_BUNGEE) return false;+ int full = z->kind == Z_POLE || z->kind == Z_DANCER || z->kind == Z_DOLPHIN || z->kind == Z_JACK || z->kind == Z_LADDER+ ? 500 : 270;+ if (z->flags & ZF_MINI) full /= 4;+ return z->health < full / 3;+}++bool zombie_flying(const Zombie *z) { return z->kind == Z_BALLOON && ((z->flags & ZF_FLYING) || z->pop > 0); }++bool zombie_submerged(const Zombie *z) {+ return 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) ||+ (z->kind == Z_SNORKEL && water_row(z->row) && z->x > 100 && z->x < 770 && !(z->flags & ZF_EATING));+}++int zombie_total_health(const Zombie *z) { return z->health + z->armor + z->shield; }++/* the ground its walk covers in a loop of its animation, and the loop's frames (the .reanim's _ground track) */+static void walk_track(const Zombie *z, float *dist, int *frames) {+ switch (z->kind) {+ case Z_GARGANTUAR: *dist = 124.1f, *frames = 49; return;+ case Z_IMP: *dist = 62.9f, *frames = 33; return;+ case Z_DANCER: case Z_BACKUP: *dist = 28.6f, *frames = 21; return;+ case Z_SNORKEL: *dist = 59.9f, *frames = 37; return;+ case Z_FOOTBALL: *dist = 30, *frames = 30; return;+ case Z_NEWSPAPER: *dist = 57.8f, *frames = 47; return;+ case Z_POLE: *dist = z->flags & ZF_POLE ? 30 : 67.8f, *frames = z->flags & ZF_POLE ? 37 : 45; return;+ default: *dist = 49.8f, *frames = 47;+ }+}++/* Zombie::UpdateAnimSpeed: the speed is its animation's, its feet keep to the ground */+float walking_speed(const Zombie *z) {+ if (z->kind == Z_ZOMBONI || z->kind == Z_CATAPULT || (z->kind == Z_BOBSLED && z->u.sled.sled) || (z->flags & ZF_FLYING))+ return z->speed;+ float d;+ int f;+ walk_track(z, &d, &f);+ return z->speed * 0.47f * f / (f - 1);+}++/* ---------------------------------------------------------------- arriving */++Zombie *spawn_zombie(int kind, int row, float x, int wave) {+ if (B.nzombies >= MAX_ZOMBIES) return NULL;+ /* the rake: the first zombie of its lane steps on it */+ if (B.rake.on == 1 && x >= 780 && kind != Z_BUNGEE && kind != Z_SNORKEL && kind != Z_DOLPHIN && kind != Z_DUCKY &&+ !water_row(B.rake.row)) {+ row = B.rake.row, B.rake.on = 2;+ }+ Zombie *z = &B.zombies[B.nzombies++];+ memset(z, 0, sizeof *z);+ z->id = new_id(), z->kind = (uint8_t)kind, z->row = (uint8_t)row, z->x = x, z->wave = (uint8_t)wave;+ z->armor = (int16_t)(kind == Z_DIGGER ? 100 : kind == Z_FOOTBALL ? 1400 : kind == Z_CONE ? 370 : kind == Z_BUCKET ? 1100 : 0);+ z->shield = (int16_t)(kind == Z_LADDER ? 500 : kind == Z_NEWSPAPER ? 150 : kind == Z_DOOR ? 1100 : 0);+ z->health = (int16_t)base_health(kind);+ switch (kind) {+ case Z_POGO: z->speed = 0.45f; break;+ case Z_LADDER: z->speed = 0.79f + frand() * 0.02f; break;+ case Z_DIGGER: z->speed = 0.66f + frand() * 0.02f; break;+ case Z_DOLPHIN: z->speed = 0.89f + frand() * 0.02f; break;+ case Z_BOBSLED: z->speed = 0.6f; break;+ case Z_POLE: case Z_FOOTBALL: case Z_SNORKEL: case Z_JACK: z->speed = 0.66f + frand() * 0.02f; break;+ case Z_DANCER: case Z_BACKUP: case Z_FLAG: z->speed = 0.45f; break;+ default: z->speed = 0.23f + frand() * 0.14f;+ }+ z->bite = 4;+ z->hit_at = (uint32_t)-1000;+ if (B.level == 25 && B.mode == MODE_CONVEYOR) {+ z->flags |= ZF_MINI;+ z->health /= 4, z->armor /= 4, z->shield /= 4;+ }+ if (kind == Z_POLE) z->flags |= ZF_POLE;+ if (kind == Z_DANCER) z->phase = DP_INTRO, z->u.dance.dance_in = (int16_t)(300 + irand(12));+ if (kind == Z_DIGGER) z->flags |= ZF_UNDERGROUND;+ if (kind == Z_POGO) z->flags |= ZF_POGO;+ if (kind == Z_CATAPULT) z->u.catapult.ammo = 20, z->phase = CP_WALK;+ if (kind == Z_GARGANTUAR) z->phase = GP_WALK;+ if (kind == Z_DOLPHIN) z->flags |= ZF_DOLPHIN;+ if (kind == Z_BALLOON) z->flags |= ZF_FLYING;+ if (kind == Z_BUNGEE) {+ /* a plant no other bungee is after, or anywhere in the back */+ Plant *targets[MAX_PLANTS];+ int n = 0;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->health <= 0) continue;+ bool taken = false;+ for (int k = 0; k < B.nzombies - 1; k++) {+ const Zombie *o = &B.zombies[k];+ taken |= o->kind == Z_BUNGEE && o->u.bungee.column == p->col && o->row == p->row;+ }+ if (!taken) targets[n++] = p;+ }+ int col;+ if (n) {+ Plant *t = targets[irand(n)];+ col = t->col, z->row = t->row;+ } else+ col = 4 + irand(5);+ z->x = cell_x(col), z->phase = BP_DOWN, z->u.bungee.left = 375, z->u.bungee.column = (uint8_t)col;+ z->u.bungee.drop = 0xFF;+ }+ if (kind == Z_JACK) {+ float dist = (450 + irand(300)) / (frand() < 0.05f ? 3.0f : 1.0f);+ z->u.jack.in = (int16_t)(B.mode == MODE_VASE ? 10 : (int)(dist / z->speed) * 2);+ }+ return z;+}++/* a bungee zombie brings a zombie down from the sky (Bungee Blitz, the roof's last wave) */+void drop_from_sky(int kind, int row, int wave) {+ int col = 4 + irand(5);+ Zombie *z = spawn_zombie(Z_BUNGEE, row, cell_x(col), wave);+ if (!z) return;+ z->row = (uint8_t)row, z->x = cell_x(col), z->phase = BP_DOWN, z->u.bungee.left = 375, z->u.bungee.column = (uint8_t)col;+ z->u.bungee.drop = (uint8_t)kind;+}++/* ---------------------------------------------------------------- hurting */++void damage_zombie(Zombie *z, int amount, bool through_shield) {+ if (!through_shield && z->shield > 0) {+ int a = z->shield < amount ? z->shield : amount;+ z->shield = (int16_t)(z->shield - a), amount -= a;+ if (z->kind == Z_LADDER && z->shield == 0) z->ladder_in = 0, z->speed = 0.3f;+ if (z->kind == Z_NEWSPAPER && z->shield == 0) {+ z->rage = 150, z->flags &= (uint16_t)~ZF_EATING, z->flags |= ZF_PAPER_GONE;+ }+ }+ int a = z->armor < amount ? z->armor : amount;+ z->armor = (int16_t)(z->armor - a);+ int hp = z->health - (amount - a);+ z->health = (int16_t)(hp < -30000 ? -30000 : hp);+}++/* gone: a corpse to watch, a coin perhaps, and the place the level's reward drops */+void kill_zombie(Zombie *z, int how) {+ if (z->health > 0) z->health = 0;+ if (z->flags & ZF_SPAWNED) return; /* (already counted) */+ z->flags |= ZF_SPAWNED;+ float y = row_y(z->row, z->x);+ if (!(z->flags & ZF_HYPNO)) B.last_x = z->x, B.last_y = y;+ if (how == DIE_BURN || how == DIE_NORMAL || how == DIE_MOWED) {+ Fx *f = fx_corpse(z, how == DIE_BURN ? 1 : 0, how == DIE_BURN ? 150 : 140, how == DIE_BURN);+ if (f && how == DIE_MOWED) f->flags |= 8;+ }+ /* coins, from the night on (Zombie::DropLoot) */+ if (!(z->flags & ZF_HYPNO) && B.mode != MODE_BOWLING && (B.level >= 11 || progress.finished) && B.mode != MODE_VASE) {+ int hit = B.level == 11 && !B.first_coin && B.wave > 5 && !progress.finished ? 1000 : irand(30000);+ int factor = zombie_defs[z->kind].value;+ if (hit < 2500 * factor) {+ add_coin(z->x, y - 15, hit < 14 * factor && progress.slots > 6 ? 1000 : hit < 250 * factor ? 50 : 10);+ B.first_coin = 1;+ }+ }+}++/* ---------------------------------------------------------------- the kinds' own ways */++static void eat(Zombie *z, Plant *food);++static void update_zomboni(Zombie *z) {+ if (z->health <= 200) {+ kill_zombie(z, DIE_NORMAL);+ return;+ }+ float f = (z->x - 30 - 300) / 400;+ z->speed = 0.05f + 0.2f * (f < 0 ? 0 : f > 1 ? 1 : f);+ z->x -= z->speed, z->flags &= (uint16_t)~ZF_EATING;+ float x = z->x + 88 < 25 ? 25 : z->x + 88;+ if (x < 800) {+ Ice *ice = &B.ice[z->row];+ if (ice->left > 0) ice->x = ice->x < x ? ice->x : x;+ else ice->x = x;+ ice->left = 3000;+ }+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->health <= 0 || p->row != z->row || cell_x(p->col) - z->x >= 55 || z->x - cell_x(p->col) >= 55) continue;+ p->health = 0;+ if (p->kind == P_SPIKEWEED) {+ kill_zombie(z, DIE_NORMAL);+ fx_add(FX_POW, z->x, row_y(z->row, z->x) - 30, 20, 0);+ break;+ }+ }+}++static void crash_sled(uint16_t sled) {+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *o = &B.zombies[i];+ if (o->kind != Z_BOBSLED || o->u.sled.sled != sled) continue;+ o->u.sled.sled = 0, o->u.sled.leader = 0, o->armor = 0, o->crash = 150, o->speed = 0.23f + frand() * 0.14f;+ }+}++static void update_sled(Zombie *z) {+ if (z->crash > 0) {+ z->crash--;+ return;+ }+ Zombie *leader = z->u.sled.leader ? zombie_by_id(z->u.sled.leader) : z;+ Ice *ice = &B.ice[z->row];+ if (!leader || leader->health <= 0 || ice->left <= 0 || leader->x < ice->x || leader->armor == 0) {+ crash_sled(z->u.sled.sled);+ return;+ }+ z->x -= 0.6f;+ if (ice->left < 500) ice->left = 500;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->health <= 0 || p->row != z->row || cell_x(p->col) - z->x >= 45 || z->x - cell_x(p->col) >= 45) continue;+ p->health = 0;+ if (p->kind == P_SPIKEWEED) {+ crash_sled(z->u.sled.sled);+ break;+ }+ }+}++static bool update_jack(Zombie *z) {+ if (--z->u.jack.in > 0) return (z->flags & ZF_OPENING) != 0;+ if (!(z->flags & ZF_OPENING)) {+ z->flags |= ZF_OPENING, z->u.jack.in = 110, z->flags &= (uint16_t)~ZF_EATING, z->anim = 0;+ return true;+ }+ /* the box goes off */+ bool hyp = (z->flags & ZF_HYPNO) != 0;+ for (int i = 0; i < B.nplants && !hyp; i++) {+ Plant *p = &B.plants[i];+ float dx = cell_x(p->col) - z->x, dy = row_y(p->row, cell_x(p->col)) - row_y(z->row, z->x);+ if (dx * dx + dy * dy < 90 * 90) p->health = 0;+ }+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *o = &B.zombies[i];+ if (!(o->flags & ZF_HYPNO) != hyp && o->row - z->row <= 1 && z->row - o->row <= 1 && o->x - z->x < 115 &&+ z->x - o->x < 115) {+ damage_zombie(o, 1800, true);+ if (o->health <= 0) kill_zombie(o, DIE_BURN);+ }+ }+ if (B.mode == MODE_VASE)+ for (int i = 0; i < B.nvases; i++) {+ int dc = B.vases[i].col - col_at(z->x), dr = B.vases[i].row - z->row;+ if (dc >= -1 && dc <= 1 && dr >= -1 && dr <= 1) board_break_vase(B.vases[i].col, B.vases[i].row), i = -1;+ }+ fx_add(FX_BOOM, z->x, row_y(z->row, z->x) - 35, 60, 0);+ kill_zombie(z, DIE_GONE);+ return true;+}++static bool dancer_moving(const Zombie *z) {+ if (z->kind != Z_DANCER && z->kind != Z_BACKUP) return true;+ if (z->kind == Z_DANCER && z->phase == DP_INTRO) return true;+ if ((B.ticks / 20) % 23 > 11) return false;+ const Zombie *leader = z->kind == Z_DANCER ? z : zombie_by_id(z->u.dance.leader);+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *o = &B.zombies[i];+ if (o->health <= 0 || (o->kind != Z_DANCER && o->kind != Z_BACKUP)) continue;+ bool group = o == leader || (leader && o->kind == Z_BACKUP && o->u.dance.leader == leader->id);+ if (group && ((o->flags & ZF_EATING) || o->frozen > 0)) return false;+ }+ return true;+}++/* the dancer calls his four backup dancers around him, again whenever one is missing */+static bool update_dancer(Zombie *z) {+ if (z->flags & ZF_EATING) return false;+ static const int8_t dr[4] = {-1, 1, 0, 0}, dx[4] = {0, 0, -100, 100};+ bool missing[4];+ int nmissing = 0;+ for (int s = 0; s < 4; s++) {+ int row = z->row + dr[s];+ missing[s] = false;+ if (row < 0 || row >= B.nrows || !(B.rows >> row & 1) || water_row(row)) continue;+ bool there = false;+ for (int i = 0; i < B.nzombies; i++) {+ const Zombie *o = &B.zombies[i];+ there |= o->kind == Z_BACKUP && o->u.dance.leader == z->id && o->u.dance.slot == s && o->health > 0;+ }+ if (!there) missing[s] = true, nmissing++;+ }+ if (z->phase == DP_INTRO) {+ if (--z->u.dance.dance_in <= 0) z->phase = DP_POINT, z->u.dance.dance_in = 38, z->anim = 0;+ return false;+ }+ if (z->phase == DP_POINT) {+ if (--z->u.dance.dance_in <= 0) {+ uint16_t id = z->id;+ int row = z->row, wave = z->wave;+ float x = z->x;+ bool hyp = (z->flags & ZF_HYPNO) != 0;+ for (int s = 0; s < 4; s++) {+ if (!missing[s]) continue;+ Zombie *f = spawn_zombie(Z_BACKUP, row + dr[s], x + dx[s], wave);+ if (!f) break;+ f->rise = 150, f->u.dance.leader = id, f->u.dance.slot = (uint8_t)s;+ if (hyp) f->flags |= ZF_HYPNO;+ }+ z = zombie_by_id(id);+ if (!z) return true;+ z->phase = DP_HOLD, z->u.dance.dance_in = 200;+ }+ return true;+ }+ if (z->phase == DP_HOLD) {+ if (--z->u.dance.dance_in <= 0) z->phase = DP_DANCE;+ return true;+ }+ if (nmissing) {+ if (z->u.dance.summon_in == 0) z->u.dance.summon_in = 100;+ else if (z->u.dance.summon_in > 1) z->u.dance.summon_in--;+ else if ((B.ticks / 20) % 23 == 12 && z->x < 730) {+ z->phase = DP_POINT, z->u.dance.dance_in = 38, z->u.dance.summon_in = 0, z->anim = 0;+ return true;+ }+ }+ return false;+}++static Plant *umbrella_near(int col, int row) {+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->kind == P_UMBRELLA && p->health > 0 && p->col - col <= 1 && col - p->col <= 1 && p->row - row <= 1 &&+ row - p->row <= 1)+ return p;+ }+ return NULL;+}++static void update_bungee(Zombie *z) {+ if (--z->u.bungee.left > 0) return;+ if (z->phase == BP_DOWN) {+ Plant *u = umbrella_near(z->u.bungee.column, z->row);+ if (u) {+ u->shot = B.ticks;+ z->phase = BP_UP, z->u.bungee.left = 100;+ return;+ }+ if (z->u.bungee.drop != 0xFF) {+ spawn_zombie(z->u.bungee.drop, z->row, z->x, z->wave);+ z = &B.zombies[0] + (z - B.zombies); /* (the array didn't move: spawning appends) */+ z->phase = BP_UP, z->u.bungee.left = 100;+ } else+ z->phase = BP_WAIT, z->u.bungee.left = 300;+ } else if (z->phase == BP_WAIT) {+ /* it takes the plant, its pot and lily pad last */+ Plant *victim = NULL, *pumpkin = NULL, *base = NULL;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->col != z->u.bungee.column || p->row != z->row || p->health <= 0) continue;+ if (p->kind == P_PUMPKIN) pumpkin = p;+ else if (p->kind == P_FLOWERPOT || p->kind == P_LILYPAD) base = p;+ else victim = p;+ }+ if (!victim) victim = pumpkin ? pumpkin : base;+ if (victim) victim->health = 0, victim->state = 0xEE; /* (taken: no remains) */+ z->phase = BP_UP, z->u.bungee.left = 100;+ } else {+ z->health = 0, z->flags |= ZF_SPAWNED; /* gone up, not killed */+ }+}++/* Zombie::UpdateZombieCatapult: the leftmost plant, 20 balls */+static Plant *catapult_target(const Zombie *z) {+ Plant *best = NULL;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->health <= 0 || p->row != z->row || cell_x(p->col) >= z->x - 100) continue;+ if (!best || p->col < best->col ||+ (p->col == best->col && ((best->kind == P_FLOWERPOT) > (p->kind == P_FLOWERPOT) ||+ (best->kind == P_PUMPKIN) > (p->kind == P_PUMPKIN))))+ best = p;+ }+ return best;+}++static void update_catapult(Zombie *z) {+ if (z->phase == CP_WALK) {+ z->flags &= (uint16_t)~ZF_EATING;+ if (z->x <= 650 && z->u.catapult.ammo > 0 && catapult_target(z)) {+ z->phase = CP_SHOOT, z->u.catapult.left = 300, z->anim = 0;+ } else {+ z->x -= z->speed;+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->row == z->row && cell_x(p->col) - z->x < 40 && z->x - cell_x(p->col) < 40) p->health = 0;+ }+ }+ return;+ }+ z->u.catapult.left--;+ if (z->phase == CP_SHOOT && z->u.catapult.left == 230) {+ Plant *p = catapult_target(z);+ if (p && B.nshots < MAX_SHOTS) {+ Shot *s = &B.shots[B.nshots++];+ memset(s, 0, sizeof *s);+ s->id = new_id(), s->kind = S_BASKETBALL, s->row = z->row, s->torch = 0xFF;+ s->sx = z->x + 65, s->ex = cell_x(p->col), s->sy = row_y(z->row, s->sx) - 110, s->ey = row_y(z->row, s->ex) - 45;+ s->x = s->sx, s->y = s->sy, s->duration = 120, s->target = p->id;+ }+ }+ if (z->phase == CP_SHOOT && z->u.catapult.left == 171) z->u.catapult.ammo--, z->phase = CP_RELOAD;+ if (z->u.catapult.left <= 0) {+ z->phase = z->u.catapult.ammo > 0 && catapult_target(z) ? CP_SHOOT : CP_WALK;+ if (z->phase == CP_SHOOT) z->u.catapult.left = 300;+ z->anim = 0;+ }+}++static Plant *giant_food(const Zombie *z) {+ for (int i = 0; i < B.nplants; i++) {+ Plant *p = &B.plants[i];+ if (p->health > 0 && p->row == z->row && z->x - cell_x(p->col) < 55 && z->x - cell_x(p->col) > -30) return p;+ }+ return NULL;+}++static void update_giant(Zombie *z, float speed_factor) {+ if (z->phase == GP_WALK) {+ z->flags &= (uint16_t)~ZF_EATING;+ if (!z->u.giant.thrown && z->health < 1500 && z->x > 400) z->phase = GP_THROW, z->u.giant.left = 138, z->anim = 0;+ else if (giant_food(z)) z->phase = GP_SMASH, z->u.giant.left = 134, z->anim = 0;+ else {+ float v = walking_speed(z) * speed_factor;+ z->x -= v, z->walk += v;+ }+ return;+ }+ float before = z->u.giant.left;+ z->u.giant.left -= speed_factor;+ if (z->u.giant.left < 0) z->u.giant.left = 0;+ if (z->phase == GP_SMASH && before > 48 && z->u.giant.left <= 48) {+ Plant *p = giant_food(z);+ if (p) {+ int col = p->col, row = p->row;+ for (int i = 0; i < B.nplants; i++)+ if (B.plants[i].col == col && B.plants[i].row == row) B.plants[i].health = 0;+ }+ fx_add(FX_SMOKE, z->x - 40, row_y(z->row, z->x), 30, 0);+ }+ if (z->phase == GP_THROW && before > 36 && z->u.giant.left <= 36) {+ z->u.giant.thrown = 1;+ float dist = z->x - 360 - (B.env == ENV_ROOF ? 180 : 0);+ float lo = B.env == ENV_ROOF ? -140 : 40;+ if (dist < lo) dist = lo;+ if (dist > 140) dist -= frand() * 100;+ uint16_t id = z->id;+ float zx = z->x;+ int row = z->row, wave = z->wave;+ Zombie *imp = spawn_zombie(Z_IMP, row, zx - 133, wave);+ z = zombie_by_id(id);+ if (imp) {+ int dur = (int)((dist < 0 ? -dist : dist) / 3 + 0.5f);+ if (dur < 30) dur = 30;+ imp->u.flight.sx = imp->x, imp->u.flight.ex = imp->x - dist, imp->u.flight.duration = (int16_t)dur;+ imp->u.flight.left = (int16_t)dur;+ }+ if (!z) return;+ }+ if (z->u.giant.left <= 0) z->phase = GP_WALK, z->anim = 0;+}++/* ---------------------------------------------------------------- every tick */++static void eat(Zombie *z, Plant *food) {+ if (food->kind == P_HYPNOSHROOM && !sleeping(food)) {+ food->health = 0;+ z->flags |= ZF_HYPNO, z->speed = 0.17f, z->flags &= (uint16_t)~ZF_EATING;+ if (z->kind == Z_DANCER)+ for (int i = 0; i < B.nzombies; i++) {+ Zombie *f = &B.zombies[i];+ if (f->kind == Z_BACKUP && f->u.dance.leader == z->id) f->flags |= ZF_HYPNO, f->speed = 0.17f;+ }+ fx_add(FX_SMOKE, z->x, row_y(z->row, z->x) - 50, 40, 2);+ } else+ food->health = (int16_t)(food->health - 4);+ food->shot = B.ticks; /* (a bitten plant flashes) */+ if (food->kind == P_GARLIC) {+ int rows[2], n = 0;+ for (int d = -1; d <= 1; d += 2) {+ int r = z->row + d;+ if (r >= 0 && r < B.nrows && (B.rows >> r & 1) && !water_row(r)) rows[n++] = r;+ }+ if (n) z->garlic_row = (uint8_t)rows[irand(n)], z->garlic = 100;+ }+ z->bite = (int8_t)(z->chill > 0 ? 8 : 4);+}++void zombies_tick(void) {+ bool hypnos = false;+ for (int i = 0; i < B.nzombies; i++) hypnos |= (B.zombies[i].flags & ZF_HYPNO) != 0;+ int n = B.nzombies; /* (the ones spawned this tick wait for the next) */+ for (int i = 0; i < n && i < B.nzombies; i++) {+ Zombie *z = &B.zombies[i];+ if (z->health <= 0) continue;+ z->anim += 1;+ if (z->blown > 0) {+ z->x += 6;+ if (--z->blown == 0) kill_zombie(z, DIE_GONE);+ 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) {+ z->flags &= (uint16_t)~ZF_EATING;+ continue;+ }+ if (z->butter > 0) {+ z->butter--;+ continue;+ }+ if (z->chill > 0) z->chill--;+ if (z->frozen > 0) {+ z->frozen--;+ z->anim -= 1;+ continue;+ }+ float sf = z->chill > 0 ? 0.4f : 1;+ z->anim += sf - 1;+ if (z->rise > 0) {+ z->rise--, z->flags &= (uint16_t)~ZF_EATING;+ continue;+ }+ if (z->kind == Z_IMP && z->u.flight.left > 0) {+ z->u.flight.left--;+ float t = 1 - (float)z->u.flight.left / z->u.flight.duration;+ z->x = z->u.flight.sx + (z->u.flight.ex - z->u.flight.sx) * t;+ if (z->u.flight.left == 0) z->landing = 21;+ continue;+ }+ if (z->landing > 0) {+ z->landing--;+ continue;+ }+ if (z->kind == Z_CATAPULT) {+ update_catapult(z);+ continue;+ }+ if (z->kind == Z_GARGANTUAR) {+ update_giant(z, sf);+ continue;+ }+ if (z->kind == Z_BUNGEE) {+ update_bungee(z);+ continue;+ }+ if (z->flags & ZF_UNDERGROUND) {+ z->x -= z->speed * sf;+ if (z->x < 45) z->flags &= (uint16_t)~ZF_UNDERGROUND, z->emerge = 230, z->flags |= ZF_BACKWARDS, z->speed = 0.12f;+ continue;+ }+ if (z->emerge > 0) {+ z->emerge--;+ continue;+ }+ if (z->garlic > 0) {+ if (--z->garlic == 0) z->row = z->garlic_row, z->flags &= (uint16_t)~ZF_EATING;+ continue;+ }+ if (z->ladder_in > 0) {+ if (--z->ladder_in == 0) {+ if (B.nladders < 24) {+ int col = (int)((z->x - 35 - 80) / 80 + 0.5f);+ B.ladders[B.nladders].col = (uint8_t)col, B.ladders[B.nladders++].row = z->row;+ }+ z->shield = 0, z->speed = 0.3f;+ }+ continue;+ }+ if (z->kind == Z_ZOMBONI) {+ update_zomboni(z);+ continue;+ }+ if (z->kind == Z_BOBSLED && (z->u.sled.sled || z->crash)) {+ update_sled(z);+ continue;+ }+ if (z->kind == Z_JACK && !(z->flags & ZF_METAL_GONE) && !zombie_headless(z) && update_jack(z)) continue;+ if (z->health <= 0) continue;+ if (z->pop > 0) {+ if (--z->pop == 0 && water_row(z->row)) kill_zombie(z, DIE_GONE);+ continue;+ }+ if (z->flags & ZF_FLYING) {+ z->flags &= (uint16_t)~ZF_EATING;+ z->x -= z->speed * sf;+ continue;+ }+ if (z->rage > 0 && !zombie_headless(z)) {+ z->rage -= z->rage < sf ? z->rage : sf;+ z->flags &= (uint16_t)~ZF_EATING;+ if (z->rage <= 0) z->speed = 0.89f + frand() * 0.02f;+ continue;+ }+ if (zombie_headless(z)) {+ /* below a third of its health: it can't eat, falls apart as it goes, and can't get in the house */+ z->vault = 0, z->flags &= (uint16_t)~(ZF_POLE | ZF_EATING);+ float v = walking_speed(z) * sf;+ z->x += (z->flags & (ZF_HYPNO | ZF_BACKWARDS) ? 1 : -1) * v, z->walk += v;+ if (frand() < 0.2f) z->health--;+ if (z->flags & (ZF_HYPNO | ZF_BACKWARDS) ? z->x > 900 : z->x < 35) z->health = 0;+ if (z->health <= 0) kill_zombie(z, DIE_NORMAL);+ continue;+ }+ if (z->vault > 0) {+ float step = sf < z->vault ? sf : z->vault;+ z->vault -= step;+ z->x -= (z->kind == Z_DOLPHIN ? 150.0f / 120 : 150.0f / 168) * step;+ if (z->vault <= 0) z->speed = 0.23f + frand() * 0.14f;+ continue;+ }+ if (z->kind == Z_DOLPHIN && (z->flags & ZF_DOLPHIN) && z->x < 780) {+ Plant *barrier = NULL;+ for (int k = 0; k < B.nplants; k++) {+ Plant *p = &B.plants[k];+ if (p->health <= 0 || p->row != z->row || p->kind == P_TANGLEKELP) continue;+ if (z->x - cell_x(p->col) < 95 && z->x > cell_x(p->col) && (!barrier || p->kind == P_TALLNUT)) barrier = p;+ }+ if (barrier) {+ z->flags &= (uint16_t)~(ZF_DOLPHIN | ZF_EATING);+ if (barrier->kind == P_TALLNUT) z->x = cell_x(barrier->col) + 32, z->speed = 0.3f;+ else z->vault = 120, z->anim = 0;+ } else {+ z->x -= 0.9f * sf, z->walk += 0.9f * sf;+ continue;+ }+ }+ if (z->kind == Z_DANCER && update_dancer(z)) continue;+ z = &B.zombies[i];+ if (!(z->flags & ZF_HYPNO) && (z->flags & ZF_POLE)) {+ Plant *barrier = NULL;+ for (int k = 0; k < B.nplants; k++) {+ Plant *p = &B.plants[k];+ if (p->health <= 0 || p->row != z->row || p->kind == P_SPIKEWEED || (p->kind == P_POTATOMINE && p->action > 0)) continue;+ float d = z->x - cell_x(p->col);+ if (d < 95 && d > 0) {+ barrier = p;+ break;+ }+ }+ if (barrier) {+ z->flags &= (uint16_t)~(ZF_POLE | ZF_EATING);+ if (barrier->kind == P_TALLNUT) z->x = cell_x(barrier->col) + 32, z->speed = 0.3f;+ else z->vault = 168, z->anim = 0;+ continue;+ }+ }+ if ((z->flags & ZF_POGO) && !zombie_headless(z)) {+ Plant *tall = NULL;+ for (int k = 0; k < B.nplants; k++) {+ Plant *p = &B.plants[k];+ float d = z->x - cell_x(p->col);+ if (p->kind == P_TALLNUT && p->health > 0 && p->row == z->row && d > 0 && d < 65) tall = p;+ }+ if (tall) z->flags &= (uint16_t)~ZF_POGO, z->speed = 0.3f;+ else {+ z->flags &= (uint16_t)~ZF_EATING;+ z->x -= 0.45f * sf, z->walk += 0.45f * sf;+ continue;+ }+ }+ /* a zombie of the other side to fight */+ bool back = (z->flags & (ZF_HYPNO | ZF_BACKWARDS)) != 0;+ if (hypnos) {+ Zombie *rival = NULL;+ for (int k = 0; k < B.nzombies; k++) {+ Zombie *o = &B.zombies[k];+ if (o == z || !(o->flags & ZF_HYPNO) == !(z->flags & ZF_HYPNO) || o->health <= 0 || zombie_flying(o) ||+ zombie_headless(o) || o->row != z->row || o->rise > 0 || o->vault > 0)+ continue;+ float d = (o->x - z->x) * (back ? 1 : -1);+ if (d >= -30 && d < 40) {+ rival = o;+ break;+ }+ }+ if (rival) {+ z->flags |= ZF_EATING;+ if (--z->bite <= 0) {+ damage_zombie(rival, 4, true);+ rival->hit_at = B.ticks;+ if (rival->health <= 0) kill_zombie(rival, DIE_NORMAL);+ z->bite = (int8_t)(z->chill > 0 ? 8 : 4);+ }+ continue;+ }+ }+ /* a plant to eat: its pumpkin first, then the plant, then what it stands on */+ Plant *food = NULL;+ int prio = 3;+ if (!(z->flags & ZF_HYPNO))+ for (int k = 0; k < B.nplants; k++) {+ Plant *p = &B.plants[k];+ if (p->kind == P_TANGLEKELP || p->kind == P_SPIKEWEED || p->health <= 0 || p->row != z->row) continue;+ float d = (z->x - cell_x(p->col)) * (back ? -1 : 1);+ if (d >= 35 || d <= -30) continue;+ bool laddered = false;+ for (int l = 0; l < B.nladders; l++) laddered |= B.ladders[l].col == p->col && B.ladders[l].row == p->row;+ if (laddered) continue;+ int pr = p->kind == P_PUMPKIN ? 0 : p->kind == P_LILYPAD || p->kind == P_FLOWERPOT ? 2 : 1;+ if (pr < prio) {+ food = p, prio = pr;+ if (!pr) break;+ }+ }+ if (food) {+ if (!(z->flags & ZF_EATING)) z->anim = 0;+ z->flags |= ZF_EATING;+ if (z->kind == Z_LADDER && z->shield > 0 &&+ (food->kind == P_WALLNUT || food->kind == P_TALLNUT || food->kind == P_PUMPKIN)) {+ z->ladder_in = 100, z->x = cell_x(food->col) + 35, z->anim = 0;+ continue;+ }+ if (--z->bite <= 0) eat(z, food);+ } else {+ if (z->flags & ZF_EATING) z->anim = 0;+ z->flags &= (uint16_t)~ZF_EATING;+ if (dancer_moving(z)) {+ float v = walking_speed(z) * sf;+ z->x += (back ? 1 : -1) * v, z->walk += v;+ }+ z->bite = 4;+ }+ }+}diff --git a/games/pvz/tools/fetch.py b/games/pvz/tools/fetch.pynew file mode 100644index 00000000..15961569--- /dev/null+++ b/games/pvz/tools/fetch.py@@ -0,0 +1,88 @@+#!/usr/bin/env python3+"""Gathers the public material the pack is made from, into REF (not committed):++ python3 -I tools/fetch.py REF++- REF/pvz/...: the game's pictures, as the open-source web port pvz-web (github.com/xyxiao001/pvz-web, at the+ commit below) keeps them: every animation of the 40 plants of Adventure and its zombies as frames on 14 sheets+ (public/assets/original: actors-*.png, animations.json), the lawns, the menus and the other pictures, and+ Dr. Zomboss as the game's own parts and their moves (public/assets/runtime/boss)+- REF/fonts/: Nunito and Rammetto One (SIL Open Font License), from Google Fonts++Files already there are kept: run it again to fetch only what is missing."""+import os+import sys+import time+import urllib.request++PVZ = "https://raw.githubusercontent.com/xyxiao001/pvz-web/2d9c64135da3d74ae090c59e1cdfb9b20a09c4cb/"+FONTS = {+ "Nunito.ttf": "https://raw.githubusercontent.com/google/fonts/main/ofl/nunito/Nunito%5Bwght%5D.ttf",+ "RammettoOne.ttf": "https://raw.githubusercontent.com/google/fonts/main/ofl/rammettoone/RammettoOne-Regular.ttf",+}+A = "public/assets/"+FILES = [A + "original/animations.json"] + [A + f"original/actors-{i}.png" for i in range(14)] + [+ A + "lawn.jpg", A + "yard.jpg", A + "original/night.jpg", A + "original/pool.png", A + "original/fog.png",+ A + "original/roof.png", A + "runtime/boss/background.webp", A + "original/award.jpg",+ A + "runtime/effects.json", A + "runtime/pea.webp",+] + [A + "runtime/original/" + n + ".webp" for n in (+ "menu", "logo", "dialog", "seedbank", "shovelbank", "shovel", "crazy-dave", "dave-bubble", "trophy", "button",+ "shop-background", "shop-slots", "shop-roof", "shop-rake", "shop-firstaid", "roof-cleaner", "rake",+ "coin-diamond", "coin-gold", "coin-silver", "meter-empty", "meter-full", "meter-flag", "meter-head",+ "seed-packet", "mower", "pool-cleaner", "grave", "crater", "ice-trail", "ladder", "bungee-target",+ "bungee-cord", "sled", "vases", "hammer", "bowling-stripe", "conveyor", "conveyor-back", "fog-cloud",+ "snow-pea", "puff", "star", "spike", "cabbage", "kernel", "butter", "melon", "basketball", "fire-pea",+ "flowerpot", "trophy")] + [A + "runtime/ui/" + n + ".webp" for n in (+ "seed-chooser", "almanac-card", "stone-panel", "parchment-button", "seed-start", "seed-start-disabled",+ "challenge-background", "seed-silhouette")] + [A + "portraits/almanac/" + n + ".png" for n in (+ "backup", "balloon", "bobsled", "bucket", "bungee", "catapult", "cone", "dancer", "digger", "dolphin", "door",+ "ducky", "flag", "football", "gargantuar", "jack", "ladder", "newspaper", "normal", "pogo", "pole", "snorkel",+ "zomboni")] + [A + "runtime/almanac/imp.webp", A + "runtime/boss/tracks.json"] + [+ A + "runtime/boss/" + n + ".webp" for n in (+ "ZOMBIE_BOSSDRIVER_BODY ZOMBIE_BOSSDRIVER_BRAIN ZOMBIE_BOSSDRIVER_FACE ZOMBIE_BOSSDRIVER_FACE2 "+ "ZOMBIE_BOSSDRIVER_INNERHAND ZOMBIE_BOSSDRIVER_JAW ZOMBIE_BOSSDRIVER_JAW2 ZOMBIE_BOSSDRIVER_LOWERARM "+ "ZOMBIE_BOSSDRIVER_LOWERARM2 ZOMBIE_BOSSDRIVER_OUTERHAND ZOMBIE_BOSSDRIVER_UPPERARM ZOMBIE_BOSS_ANTENNA "+ "ZOMBIE_BOSS_ANTENNA_LIT ZOMBIE_BOSS_ARM_UPPER2 ZOMBIE_BOSS_EYEGLOW ZOMBIE_BOSS_EYEGLOW_BLACK "+ "ZOMBIE_BOSS_EYEGLOW_RED ZOMBIE_BOSS_FIREBALL ZOMBIE_BOSS_FIREBALL_ADDITIVE ZOMBIE_BOSS_FIREBALL_CHUNKS "+ "ZOMBIE_BOSS_FIREBALL_MULTIPLY ZOMBIE_BOSS_FIREBALL_SUPERGLOW ZOMBIE_BOSS_FLAG ZOMBIE_BOSS_FLAGPOLE "+ "ZOMBIE_BOSS_FOOT ZOMBIE_BOSS_HEAD ZOMBIE_BOSS_HEAD2 ZOMBIE_BOSS_ICEBALL ZOMBIE_BOSS_ICEBALL_CRYSTAL1 "+ "ZOMBIE_BOSS_ICEBALL_CRYSTAL2 ZOMBIE_BOSS_ICEBALL_CRYSTAL3 ZOMBIE_BOSS_ICEBALL_HIGHLIGHT "+ "ZOMBIE_BOSS_ICEBALL_MULTIPLY ZOMBIE_BOSS_ICEBALL_OVERLAY ZOMBIE_BOSS_ICEFIRE_SHADOW "+ "ZOMBIE_BOSS_INNERARM_FINGER ZOMBIE_BOSS_INNERARM_FINGERROPE ZOMBIE_BOSS_INNERARM_HAND "+ "ZOMBIE_BOSS_INNERARM_LOWER ZOMBIE_BOSS_INNERARM_THUMB1 ZOMBIE_BOSS_INNERARM_THUMB2 "+ "ZOMBIE_BOSS_INNERARM_UPPER ZOMBIE_BOSS_INNERJAW ZOMBIE_BOSS_INNERLEG_UPPER ZOMBIE_BOSS_JAW "+ "ZOMBIE_BOSS_LEGBITS ZOMBIE_BOSS_LEG_LOWER ZOMBIE_BOSS_LOWERBODY ZOMBIE_BOSS_MOUTHGLOW "+ "ZOMBIE_BOSS_MOUTHGLOW_RED ZOMBIE_BOSS_NECK ZOMBIE_BOSS_OUTERARM_FINGER1 ZOMBIE_BOSS_OUTERARM_FINGER2 "+ "ZOMBIE_BOSS_OUTERARM_HAND ZOMBIE_BOSS_OUTERARM_LOWER ZOMBIE_BOSS_OUTERARM_THUMB1 "+ "ZOMBIE_BOSS_OUTERARM_THUMB2 ZOMBIE_BOSS_OUTERARM_UPPER ZOMBIE_BOSS_OUTERLEG_UPPER ZOMBIE_BOSS_RV "+ "ZOMBIE_BOSS_RVWHEEL ZOMBIE_BOSS_UPPERBODY").split()]+++def get(url, tries=4):+ for t in range(tries):+ try:+ with urllib.request.urlopen(url, timeout=120) as r:+ return r.read()+ except Exception as e:+ if t == tries - 1:+ raise SystemExit(f"fetch: {url}: {e}")+ time.sleep(2 << t)+++def main(ref):+ jobs = [(PVZ + p, os.path.join(ref, "pvz", p[len(A):])) for p in dict.fromkeys(FILES)]+ jobs += [(url, os.path.join(ref, "fonts", name)) for name, url in FONTS.items()]+ for url, dst in jobs:+ if os.path.exists(dst) and os.path.getsize(dst):+ continue+ os.makedirs(os.path.dirname(dst), exist_ok=True)+ data = get(url)+ with open(dst, "wb") as f:+ f.write(data)+ print(f"{len(data):9d} {dst}")+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ main(sys.argv[1])diff --git a/games/pvz/tools/pack.py b/games/pvz/tools/pack.pynew file mode 100644index 00000000..d95db1ee--- /dev/null+++ b/games/pvz/tools/pack.py@@ -0,0 +1,647 @@+#!/usr/bin/env python3+"""Plants vs. Zombies' pictures and fonts -> src/data.bin + src/data.h.++ python3 -I tools/pack.py REF (REF: the folder tools/fetch.py filled)++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),+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 a+ second, the animation it is drawn over (u16 x 4; 0xFFFF none: an overlay holds only what differs from the+ same frame of that one), frames, bits a pixel (u8, u8: 4 or 8), 0 (u16)+- FRAMES: 12 bytes each: x, y of the top-left from the anchor (s16, s16), w, h (u16, u16), offset (u32) of its rows.+ 4 bits a pixel: each row's length in bytes (u8 x h), then the rows; 8 bits: each row's offset (u16 x h, from+ the first), then the rows. A row is runs up to its last visible pixel: 0x00-0x3F n+1 transparent, 0x40-0x7F+ n-63 opaque pixels, 0x80-0xBF n-127 half-transparent ones (their colours follow: 4 bits a pixel, the first+ lowest, padded to a byte, or a byte each), 0xC0-0xFF one opaque colour repeated: with 4 bits 2 + bits 4-5 of+ n times colour n & 15, with 8 bits n-190 times the colour that follows+- PALETTES: the offset (u32) of each: the number of colours (u16), 0 (u16), then the colours (RGB565)+- BACKS: 16 bytes each (BG_*): w, h, colours, rows a chunk, palette, chunks (u16 x 6), the offset of the chunks'+ 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+"""+import json+import os+import struct+import sys+import zlib++import numpy as np+from PIL import Image, ImageDraw, ImageFont++try:+ import zopfli.zlib as zopfli+except ImportError: # (plain zlib then: a few percent bigger)+ zopfli = None++HERE = os.path.dirname(os.path.abspath(__file__))+OUT_BIN = os.path.join(HERE, "..", "src", "data.bin")+OUT_H = os.path.join(HERE, "..", "src", "data.h")+S = 0.4+NONE = 0xFFFF++# The animations of the game's characters, from its sheets: how many frames to keep (evenly spaced, flash is what+# limits it) and, for one that only differs from another by a hat or a tube, the one it is drawn over.+DEFAULT_KEEP = 8+ANIMS = {+ # 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),+ "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),+ "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),+ "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),+ "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),+ # plants+ "peashooter": (12, None), "sunflower": (12, 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),+ "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),+ "lilypad": (1, None), "squash": (8, None), "squash-attack": (6, None), "threepeater": (8, None),+ "tanglekelp": (8, None), "tanglekelp-grab": (1, None), "jalapeno": (8, None), "jalapeno-fire": (6, None),+ "spikeweed": (8, None), "torchwood": (8, None), "tallnut": (8, None), "tallnut-cracked1": (8, "tallnut"),+ "tallnut-cracked2": (8, "tallnut"), "seashroom": (8, None), "plantern": (8, None), "cactus": (8, None),+ "cactus-tall": (8, None), "blover": (8, None), "blover-loop": (6, None), "splitpea": (8, None),+ "starfruit": (8, None), "pumpkin": (8, None), "pumpkin-cracked1": (8, "pumpkin"),+ "pumpkin-cracked2": (8, "pumpkin"), "magnetshroom": (8, None), "magnetshroom-attack": (8, None),+ "cabbagepult": (8, None), "cabbagepult-attack": (8, None), "flowerpot": (6, None), "kernelpult": (8, None),+ "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),+}+# the plants, in the Almanac's order: their seed packets' pictures and their Almanac portraits+PLANTS = ["peashooter", "sunflower", "cherrybomb", "wallnut", "potatomine", "snowpea", "chomper", "repeater",+ "puffshroom", "sunshroom", "fumeshroom", "gravebuster", "hypnoshroom", "scaredyshroom", "iceshroom",+ "doomshroom", "lilypad", "squash", "threepeater", "tanglekelp", "jalapeno", "spikeweed", "torchwood",+ "tallnut", "seashroom", "plantern", "cactus", "blover", "splitpea", "starfruit", "pumpkin", "magnetshroom",+ "cabbagepult", "flowerpot", "kernelpult", "coffeebean", "garlic", "umbrella", "marigold", "melonpult"]+ZOMBIES = ["normal", "flag", "cone", "pole", "bucket", "newspaper", "door", "football", "dancer", "backup", "ducky",+ "snorkel", "zomboni", "bobsled", "dolphin", "jack", "balloon", "digger", "pogo", "bungee", "ladder",+ "catapult", "gargantuar", "imp"]+++def deflate(raw):+ """raw DEFLATE"""+ if zopfli:+ return zopfli.compress(bytes(raw), numiterations=15)[2:-4]+ c = zlib.compressobj(9, zlib.DEFLATED, -15)+ return c.compress(raw) + c.flush()+++def rgb565(c):+ r, g, b = (int(round(min(255, max(0, v)))) for v in c[:3])+ return (r & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3+++def premul_resize(img, size):+ """RGBA image -> float RGBA (straight alpha, 0..1) at size, resampled with premultiplied colours"""+ a = np.asarray(img.convert("RGBA")).astype(np.float32) / 255+ a[..., :3] *= a[..., 3:4]+ chans = [np.asarray(Image.fromarray(a[..., k]).resize(size, Image.LANCZOS)) for k in range(4)]+ out = np.clip(np.stack(chans, -1), 0, 1)+ al = out[..., 3:4]+ out[..., :3] = np.where(al > 1e-3, out[..., :3] / np.maximum(al, 1e-3), 0)+ return np.clip(out, 0, 1)+++def nearest(pts, pal):+ w = np.array([0.30, 0.59, 0.11], np.float32) * 3 # (green counts most)+ d = (((pts[:, None, :] - pal[None, :, :]) ** 2) * w).sum(-1)+ return d.argmin(1)+++def kmeans_palette(pixels, n, iters=6):+ """pixels: (N, 3) 0..255 -> palette (k <= n, 3)"""+ if len(pixels) == 0:+ return np.zeros((1, 3), np.float32)+ uniq = np.unique(pixels.astype(np.uint8), axis=0)+ if len(uniq) <= n:+ return uniq.astype(np.float32)+ q = Image.fromarray(pixels.astype(np.uint8).reshape(-1, 1, 3), "RGB").quantize(n, method=Image.MEDIANCUT,+ dither=Image.NONE)+ pal = np.array(q.getpalette()[:3 * n], np.float32).reshape(-1, 3)+ pts = pixels.astype(np.float32)+ if len(pts) > 60000:+ pts = pts[np.random.default_rng(1).choice(len(pts), 60000, replace=False)]+ for _ in range(iters):+ idx = nearest(pts, pal)+ for k in range(len(pal)):+ m = idx == k+ if m.any():+ pal[k] = pts[m].mean(0)+ return pal+++def index_pixels(rgb, pal):+ flat = rgb.reshape(-1, 3).astype(np.float32)+ out = np.empty(len(flat), np.int32)+ for i in range(0, len(flat), 20000):+ out[i:i + 20000] = nearest(flat[i:i + 20000], pal)+ return out.reshape(rgb.shape[:2])+++def alpha_levels(arr):+ al = arr[..., 3]+ return np.where(al < 0.25, 0, np.where(al < 0.75, 1, 2))+++def encode_rows(idx, alpha, bpp):+ """idx: (h, w) colour indices, alpha: (h, w) 0 transparent, 1 half, 2 opaque -> the frame's rows"""+ h, w = idx.shape+ rows = []+ maxrun = 5 if bpp == 4 else 65++ def lits(vals):+ if bpp == 8:+ return bytes(int(v) for v in vals)+ vals = [int(v) for v in vals] + [0]+ return bytes(vals[i] | vals[i + 1] << 4 for i in range(0, len(vals) - 1, 2))+ for y in range(h):+ out = bytearray()+ a, ix = alpha[y], idx[y]+ last = w+ while last > 0 and a[last - 1] == 0:+ last -= 1+ x = 0+ while x < last:+ if a[x] == 0:+ n = 1+ while x + n < last and a[x + n] == 0 and n < 64:+ n += 1+ out.append(n - 1)+ x += n+ elif a[x] == 2:+ n = 1+ while x + n < last and a[x + n] == 2 and ix[x + n] == ix[x] and n < maxrun:+ n += 1+ if n >= (2 if bpp == 4 else 3):+ if bpp == 4:+ out.append(0xC0 | (n - 2) << 4 | int(ix[x]))+ else:+ out += bytes([0xC0 + n - 2, int(ix[x])])+ x += n+ continue+ n = 1+ k = 2 if bpp == 4 else 3+ while x + n < last and a[x + n] == 2 and n < 64:+ if x + n + k <= last and all(a[x + n + j] == 2 and ix[x + n + j] == ix[x + n] for j in range(k)):+ break+ n += 1+ out.append(0x40 + n - 1)+ out += lits(ix[x:x + n])+ x += n+ else:+ n = 1+ while x + n < last and a[x + n] == 1 and n < 64:+ n += 1+ out.append(0x80 + n - 1)+ out += lits(ix[x:x + n])+ x += n+ rows.append(bytes(out))+ if bpp == 4:+ if max((len(r) for r in rows), default=0) > 255:+ raise SystemExit("a row too long for 4 bits a pixel")+ return bytes(len(r) for r in rows) + b"".join(rows)+ data = bytearray()+ offs = []+ for r in rows:+ offs.append(2 * h + len(data))+ data += r+ if 2 * h + len(data) > 65535:+ raise SystemExit("a frame too big for its row offsets")+ return b"".join(struct.pack("<H", o) for o in offs) + bytes(data)+++def trim(arr, x0, y0):+ """crops a frame to its visible pixels"""+ ys, xs = np.nonzero(arr[..., 3] >= 0.25)+ if len(ys) == 0:+ return np.zeros((1, 1, 4), np.float32), 0, 0+ y1, y2, x1, x2 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1+ return arr[y1:y2, x1:x2], x0 + x1, y0 + y1+++def overlay(arr, x0, y0, base, bx0, by0):+ """what of a frame differs from the base's same frame: drawn over it, gives the frame"""+ h, w = arr.shape[:2]+ bh, bw = base.shape[:2]+ b = np.zeros_like(arr)+ # the base's pixels where the frame's are+ sx, sy = bx0 - x0, by0 - y0+ ya, yb = max(0, sy), min(h, sy + bh)+ xa, xb = max(0, sx), min(w, sx + bw)+ if ya < yb and xa < xb:+ b[ya:yb, xa:xb] = base[ya - sy:yb - sy, xa - sx:xb - sx]+ la, lb = alpha_levels(arr), alpha_levels(b)+ diff = np.abs(arr[..., :3] - b[..., :3]).sum(-1) * 255+ keep = (la > 0) & ((la != lb) | (diff > 36))+ out = arr.copy()+ out[..., 3] = np.where(keep, out[..., 3], 0)+ return out+++class Pack:+ def __init__(self):+ self.anims = [] # (key, first frame, frames, palette, cycle, base, bpp)+ self.frames = [] # (x, y, w, h, data)+ self.pals = [] # lists of RGB565+ self.backs = [] # (key, w, h, colours, rows, palette, chunks)+ self.fonts = [] # (key, bytes)+ self.names = {}+ self.scaled = {} # name -> its frames before trimming (for overlays)++ def palette(self, pal):+ self.pals.append([rgb565(c) for c in pal])+ return len(self.pals) - 1++ def add_anim(self, key, frames, cycle=0, ncolors=16, base=None):+ """frames: (float RGBA array, x0, y0) at the final scale, (x0, y0) its top-left from the anchor"""+ bpp = 4 if ncolors <= 16 else 8+ if base is not None:+ bfr = self.scaled[base]+ frames = [(overlay(a, x, y, *bfr[i]), x, y) for i, (a, x, y) in enumerate(frames)]+ trimmed = [trim(*f) for f in frames]+ px = np.concatenate([t[0][t[0][..., 3] >= 0.25][:, :3] * 255 for t in trimmed])+ pal = kmeans_palette(px, ncolors)+ p = self.palette(pal)+ first = len(self.frames)+ for arr, x0, y0 in trimmed:+ h, w = arr.shape[:2]+ idx = index_pixels(arr[..., :3] * 255, pal)+ self.frames.append((int(x0), int(y0), w, h, encode_rows(idx, alpha_levels(arr), bpp)))+ self.names[key] = len(self.anims)+ self.anims.append((key, first, len(trimmed), p, int(round(cycle)), NONE if base is None else self.names[base], bpp))+ self.scaled[key] = frames if base is None else None+ return self.names[key]++ 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):+ 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)+ idx = index_pixels(np.asarray(img), pal).astype(np.uint8)+ p = self.palette(pal)+ 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)+ self.backs.append((key, w, h, len(pal), rows, p, chunks))++ def add_font(self, name, path, cap, weight=None, spacing=0, first=32, last=126):+ f = load_font(path, cap, weight)+ glyphs, data = [], bytearray()+ asc = desc = 0+ for c in range(first, last + 1):+ g, adv = render_glyph(f, chr(c), spacing)+ if g is None:+ glyphs.append((0, 0, 0, 0, adv, len(data)))+ continue+ q, ox, oy = g+ h, w = q.shape+ asc, desc = max(asc, -oy), max(desc, h + oy)+ flat = q.flatten().tolist()+ if len(flat) % 2:+ flat.append(0)+ off = len(data)+ for i in range(0, len(flat), 2):+ data.append(flat[i] | flat[i + 1] << 4)+ glyphs.append((w, h, ox, oy, adv, off))+ blob = struct.pack("<4B", first, last - first + 1, asc, desc)+ for w, h, ox, oy, adv, off in glyphs:+ blob += struct.pack("<BBbbBBH", w, h, ox, oy, adv, 0, off)+ blob += bytes(data)+ key = "F_" + name.upper()+ self.names[key] = len(self.fonts)+ self.fonts.append((key, blob))+ print(f"font {key}: cap {cap}, ascent {asc}, descent {desc}, {len(blob)} bytes")++ def write(self):+ out = bytearray(b"PVZ1" + bytes(4 * 8))++ def align():+ while len(out) % 4:+ out.append(0)+ tables = [len(out)]+ for key, first, n, p, cycle, base, bpp in self.anims:+ out += struct.pack("<HHHHBBH", first, p, min(cycle, 65535), base, n, bpp, 0)+ align()+ tables.append(len(out))+ frame_at = len(out)+ out += bytes(12 * len(self.frames))+ for i, (x, y, w, h, data) in enumerate(self.frames):+ if len(out) % 2:+ out.append(0)+ struct.pack_into("<hhHHI", out, frame_at + 12 * i, x, y, w, h, len(out))+ out += data+ align()+ tables.append(len(out))+ pal_at = len(out)+ out += bytes(4 * len(self.pals))+ for i, pal in enumerate(self.pals):+ align()+ struct.pack_into("<I", out, pal_at + 4 * i, len(out))+ out += struct.pack("<HH", len(pal), 0) + b"".join(struct.pack("<H", c) for c in pal)+ align()+ tables.append(len(out))+ back_at = len(out)+ out += bytes(16 * len(self.backs))+ for i, (key, w, h, ncol, rows, p, chunks) in enumerate(self.backs):+ align()+ first = len(out)+ out += bytes(4 * (len(chunks) + 1))+ for j, c in enumerate(chunks):+ struct.pack_into("<I", out, first + 4 * j, len(out))+ out += c+ struct.pack_into("<I", out, first + 4 * len(chunks), len(out))+ struct.pack_into("<HHHHHHI", out, back_at + 16 * i, w, h, ncol, rows, p, len(chunks), first)+ align()+ tables.append(len(out))+ font_at = len(out)+ out += bytes(4 * len(self.fonts))+ for i, (key, blob) in enumerate(self.fonts):+ align()+ struct.pack_into("<I", out, font_at + 4 * i, len(out))+ out += blob+ align()+ struct.pack_into("<5I3I", 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",+ ""]+ for key, *_ in self.anims:+ lines.append(f"#define {key} {self.names[key]}")+ lines += [f"#define N_ANIMS {len(self.anims)}", ""]+ for key, *_ in self.backs:+ lines.append(f"#define {key} {self.names[key]}")+ lines.append("")+ for key, _ in self.fonts:+ lines.append(f"#define {key} {self.names[key]}")+ lines += ["", "#endif", ""]+ with open(OUT_H, "w") as f:+ f.write("\n".join(lines))+ return len(out)+++def load_font(path, cap, weight):+ up = 4+ for size in range(4, 200):+ f = ImageFont.truetype(path, size * up)+ if weight:+ f.set_variation_by_axes([weight])+ bb = f.getbbox("H", anchor="ls")+ if -bb[1] >= cap * up - up // 2:+ return f+ raise SystemExit("font size")+++def render_glyph(f, ch, spacing):+ up = 4+ adv = (f.getlength(ch) + spacing * up / 4) / up+ bb = f.getbbox(ch, anchor="ls")+ if bb[2] <= bb[0] or bb[3] <= bb[1]:+ return None, round(adv)+ pad = 2 * up+ x0, y0 = pad - bb[0], pad - bb[1]+ x0 += (-x0) % up+ y0 += (-y0) % up+ w, h = x0 + bb[2] + pad, y0 + bb[3] + pad+ w += (-w) % up+ h += (-h) % up+ im = Image.new("L", (w, h), 0)+ ImageDraw.Draw(im).text((x0, y0), ch, font=f, fill=255, anchor="ls")+ a = np.asarray(im).astype(np.float32) / 255+ a = a.reshape(h // up, up, w // up, up).mean(axis=(1, 3))+ q = np.clip(np.round(a * 15), 0, 15).astype(np.uint8)+ ys, xs = np.nonzero(q)+ if not len(ys):+ return None, round(adv)+ q = q[ys.min():ys.max() + 1, xs.min():xs.max() + 1]+ return (q, xs.min() - x0 // up, ys.min() - y0 // up), round(adv)+++class Atlas:+ """the characters' animations, as the sheets hold them"""+ def __init__(self, ref):+ self.ref = ref+ self.d = json.load(open(os.path.join(ref, "pvz", "original", "animations.json")))["animations"]+ self.pages = {}++ def page(self, i):+ if i not in self.pages:+ self.pages[i] = Image.open(os.path.join(self.ref, "pvz", "original", f"actors-{i}.png")).convert("RGBA")+ return self.pages[i]++ def frames(self, name, keep, scale=S):+ """the kept frames of an animation at scale, each with its top-left from the anchor"""+ a = self.d[name]+ fr = a["frames"]+ n = len(fr)+ k = min(n, keep)+ picks = [int(i * n / k) for i in range(k)]+ ax, ay = a["anchor"]+ step = 1 / scale+ # one canvas for every frame, its corner on the grid of the anchor that the scale keeps whole, so frames don't+ # jitter+ cx0 = ax - np.ceil((ax - min(f[5] for f in fr)) / step) * step+ cy0 = ay - np.ceil((ay - min(f[6] for f in fr)) / step) * step+ W = np.ceil((max(f[5] + f[3] for f in fr) - cx0) / step) * step+ H = np.ceil((max(f[6] + f[4] for f in fr) - cy0) / step) * step+ sw, sh = int(round(W * scale)), int(round(H * scale))+ out = []+ for i in picks:+ p, x, y, w, h, ox, oy = fr[i]+ src = self.page(p).crop((x, y, x + w, y + h))+ canvas = Image.new("RGBA", (int(np.ceil(W)) + 3, int(np.ceil(H)) + 3))+ fx, fy = ox - cx0, oy - cy0+ canvas.paste(src, (int(np.floor(fx)), int(np.floor(fy))))+ dx, dy = fx - np.floor(fx), fy - np.floor(fy)+ if dx or dy:+ canvas = canvas.transform(canvas.size, Image.AFFINE, (1, 0, -dx, 0, 1, -dy), Image.BILINEAR)+ canvas = canvas.crop((0, 0, int(round(W)), int(round(H))))+ out.append((premul_resize(canvas, (sw, sh)), int(round((cx0 - ax) * scale)), int(round((cy0 - ay) * scale))))+ return out, sum(a["durations"])+++def picture(ref, rel, scale=None, size=None, box=None):+ im = Image.open(os.path.join(ref, "pvz", rel)).convert("RGBA")+ if box:+ im = im.crop(box)+ w, h = im.size+ if size is None:+ size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))+ return premul_resize(im, size)+++def opaque(img, size, box=None):+ im = img.convert("RGB")+ if box:+ im = im.crop(box)+ return im.resize(size, Image.LANCZOS)+++def cells(ref, rel, cols, rows, n=None):+ """a sheet's pictures, left to right then down"""+ im = Image.open(os.path.join(ref, "pvz", rel)).convert("RGBA")+ w, h = im.size[0] // cols, im.size[1] // rows+ out = [im.crop((c * w, r * h, c * w + w, r * h + h)) for r in range(rows) for c in range(cols)]+ return out[:n] if n else out+++def centred(img, scale, ax=0.5, ay=0.5):+ """a picture at scale, its anchor at (ax, ay) of it"""+ w, h = img.size+ sw, sh = max(1, int(round(w * scale))), max(1, int(round(h * scale)))+ return premul_resize(img, (sw, sh)), -int(round(sw * ax)), -int(round(sh * ay))+++def main(ref):+ P = Pack()+ at = Atlas(ref)+ pvz = os.path.join(ref, "pvz")+ for name, (keep, base) in ANIMS.items():+ frames, cycle = at.frames(name, keep)+ P.add_anim("A_" + name.upper().replace("-", "_"), frames, cycle,+ base=None if base is None else "A_" + base.upper().replace("-", "_"))+ n_chars = len(P.frames)+ chars = sum(len(f[4]) for f in P.frames)++ # the plants on their seed packets (half their size on the lawn), and in the Almanac+ for name in PLANTS:+ fr, _ = at.frames(name, 1, S * 0.5)+ P.add_image("packet-" + name, *trim(*fr[0]))+ for name in PLANTS:+ fr, _ = at.frames(name, 1, S * 1.6)+ P.add_image("big-" + name, *trim(*fr[0]), ncolors=48)+ for name in ZOMBIES:+ rel = "runtime/almanac/imp.webp" if name == "imp" else f"portraits/almanac/{name}.png"+ im = Image.open(os.path.join(pvz, rel)).convert("RGBA")+ bb = im.getbbox()+ im = im.crop(bb)+ P.add_image("portrait-" + name, *centred(im, 84 / im.size[1], 0.5, 1.0), ncolors=48)++ # the lawn's things, at the game's scale (these pictures are twice the game's size: 0.2)+ R = "runtime/original/"+ things = {+ "pea": ("runtime/pea.webp", 0.2), "snow-pea": (R + "snow-pea.webp", 0.2), "puff": (R + "puff.webp", 0.2),+ "star": (R + "star.webp", 0.2), "spike": (R + "spike.webp", 0.2), "cabbage": (R + "cabbage.webp", 0.2),+ "kernel": (R + "kernel.webp", 0.2), "butter": (R + "butter.webp", 0.2), "melon": (R + "melon.webp", 0.2),+ "basketball": (R + "basketball.webp", 0.2), "coin-silver": (R + "coin-silver.webp", 0.16),+ "coin-gold": (R + "coin-gold.webp", 0.16), "coin-diamond": (R + "coin-diamond.webp", 0.16),+ "bungee-target": (R + "bungee-target.webp", 0.2), "hammer": (R + "hammer.webp", 0.2),+ "meter-flag": (R + "meter-flag.webp", 0.2), "meter-head": (R + "meter-head.webp", 0.2),+ }+ for name, (rel, sc) in things.items():+ P.add_image(name, *centred(Image.open(os.path.join(pvz, rel)).convert("RGBA"), sc))+ # (anchored at the middle of their bottom)+ for name, rel, sc in [("mower", "mower", 0.2), ("pool-cleaner", "pool-cleaner", 0.2),+ ("roof-cleaner", "roof-cleaner", 0.2), ("grave", "grave", 0.2), ("ladder", "ladder", 0.18),+ ("sled", "sled", 0.155)]:+ P.add_image(name, *centred(Image.open(os.path.join(pvz, R + rel + ".webp")).convert("RGBA"), sc, 0.5, 1.0))+ for i, im in enumerate(cells(ref, R + "crater.webp", 2, 1)):+ P.add_image(f"crater{i}", *centred(im, 0.2, 0.5, 0.7))+ for i, im in enumerate(cells(ref, R + "vases.webp", 3, 2)):+ P.add_image(f"vase{i}", *centred(im, 0.2, 0.5, 1.0))+ for i, im in enumerate(cells(ref, R + "fog-cloud.webp", 8, 1)):+ P.add_image(f"fog{i}", *centred(im, 0.2))+ fire = [im.crop(im.getbbox()) for im in cells(ref, R + "fire-pea.webp", 6, 5, 6)]+ P.add_anim("A_FIRE_PEA", [centred(im, 0.16) for im in fire], 24)+ P.add_image("ice-trail", picture(ref, R + "ice-trail.webp", 0.2))+ P.add_image("bungee-cord", picture(ref, R + "bungee-cord.webp", 0.2))+ P.add_image("bowling-stripe", picture(ref, R + "bowling-stripe.webp", 0.2), 0, -100)++ # the screen's frame: the seed bank, the shovel, the progress meter, the conveyor belt+ P.add_image("seedbank", picture(ref, R + "seedbank.webp", 0.2), ncolors=32)+ P.add_image("shovelbank", picture(ref, R + "shovelbank.webp", 0.2))+ P.add_image("shovel", *centred(Image.open(os.path.join(pvz, R + "shovel.webp")).convert("RGBA"), 0.15))+ P.add_image("packet", picture(ref, R + "seed-packet.webp", 0.1), ncolors=32)+ P.add_image("meter-empty", picture(ref, R + "meter-empty.webp", 0.2))+ P.add_image("meter-full", picture(ref, R + "meter-full.webp", 0.2))+ P.add_image("conveyor", picture(ref, R + "conveyor-back.webp", 0.2), ncolors=16)++ # menus+ P.add_image("logo", picture(ref, R + "logo.webp", 0.2), ncolors=64)+ P.add_image("dialog", picture(ref, R + "dialog.webp", 0.2), ncolors=48)+ P.add_image("button", picture(ref, R + "button.webp", size=(100, 32)), ncolors=32)+ P.add_image("dave", picture(ref, R + "crazy-dave.webp", 0.2), ncolors=48)+ P.add_image("trophy", picture(ref, R + "trophy.webp", 0.2, box=(0, 0, 314, 538)), ncolors=48)+ P.add_image("chooser", picture(ref, "runtime/ui/seed-chooser.webp", 0.4), ncolors=32)+ P.add_image("start", picture(ref, "runtime/ui/seed-start.webp", size=(84, 22)), ncolors=16)+ P.add_image("start-off", picture(ref, "runtime/ui/seed-start-disabled.webp", size=(84, 22)), ncolors=16)+ P.add_image("card", picture(ref, "runtime/ui/almanac-card.webp", 0.4), ncolors=32)+ P.add_image("shop-slots", picture(ref, R + "shop-slots.webp", 0.4))+ P.add_image("shop-roof", picture(ref, R + "shop-roof.webp", 0.4))+ P.add_image("shop-rake", picture(ref, R + "shop-rake.webp", 0.4))+ P.add_image("shop-firstaid", picture(ref, R + "shop-firstaid.webp", 0.4))+ images = sum(len(f[4]) for f in P.frames[n_chars:])++ # the lawns, whole (the screen shows 320 pixels of their 560, from 88), and the menus' backgrounds+ lawns = {"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"}+ for name, rel in lawns.items():+ P.add_back(name, Image.open(os.path.join(pvz, rel)).resize((560, 240), Image.LANCZOS))+ 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)++ 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)+ P.add_font("body", os.path.join(fonts, "Nunito.ttf"), 7, 800, 1)+ P.add_font("small", os.path.join(fonts, "Nunito.ttf"), 5, 900, 2)++ for key, first, n, p, cycle, base, bpp in P.anims:+ b = sum(len(P.frames[first + i][4]) for i in range(n))+ if key.startswith("I_") and b > 3000:+ print(f" {key:24s} {b:6d}")+ total = P.write()+ print(f"data.bin: {total} bytes: characters {chars} ({n_chars} frames), other pictures {images}, lawns and "+ f"backgrounds {backs}")+++if __name__ == "__main__":+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ main(sys.argv[1])+