Skip to content

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.

Kingdom Rush: the battlefield, waves, towers, soldiers and spells

Mason3637462d1ce2b9a
diff --git a/games/kingdomrush/.gitignore b/games/kingdomrush/.gitignore
new file mode 100644
index 00000000..643bd909
--- /dev/null
+++ b/games/kingdomrush/.gitignore
@@ -0,0 +1,3 @@
+output/
+build/
+__pycache__/
diff --git a/games/kingdomrush/Makefile b/games/kingdomrush/Makefile
new file mode 100644
index 00000000..531cfbcd
--- /dev/null
+++ b/games/kingdomrush/Makefile
@@ -0,0 +1,78 @@
+# Kingdom Rush on the NumWorks calculator.
+# make output/kingdomrush.nwa
+# make check link it like the calculator does (output/kingdomrush.bin)
+# make host build/rules: the game on a computer, for tests and screenshots
+# make test the rules against the game's numbers, a won stage, random keys (tests/rules.c, sanitizers)
+# make data src/data.bin, data.h, stats.c, settings.h, strings.c from the game's Flash file, taken apart
+# (KR=that folder: see tools/pack.py; Python + Pillow + NumPy)
+
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+KR ?=
+
+# the drawing runs every frame at -O2; the rest is small at -Os
+HOT = src/pic.c src/gfx.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DEPSILON_XL=1 -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test data
+build: $(BUILD_DIR)/kingdomrush.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/kingdomrush.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/kingdomrush.bin
+ @echo "BIN $(BUILD_DIR)/kingdomrush.bin: $$(wc -c < $(BUILD_DIR)/kingdomrush.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/kingdomrush.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+# on a computer: tests/rules.c checks the rules against the game's numbers, wins stage 1, plays random keys
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c src/main.c,$(wildcard src/*.c))
+host: build/rules
+build/rules: $(HOST_SRC) tests/rules.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/rules.c src/data.S -lm -o $@
+
+test: host
+ ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 build/rules
+
+data:
+ python3 -I tools/pack.py $(KR)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/kingdomrush/src/anim.h b/games/kingdomrush/src/anim.h
new file mode 100644
index 00000000..5ca191c3
--- /dev/null
+++ b/games/kingdomrush/src/anim.h
@@ -0,0 +1,28 @@
+/* Kingdom Rush: which animation (AN_*, data.h) each enemy plays. */
+#ifndef KR_ANIM_H
+#define KR_ANIM_H
+#include <stdint.h>
+#include "data.h"
+
+enum { A_WALK, A_UP, A_DOWN, A_IDLE, A_FIGHT, A_DEAD };
+extern const int16_t enemy_anim[EN_COUNT][6]; /* stats.c; -1: none */
+static inline int ANIM(int type, int a) {
+ int an = enemy_anim[type][a];
+ if (an < 0 && a != A_WALK) an = enemy_anim[type][a == A_DEAD || a == A_FIGHT || a == A_IDLE ? A_WALK : A_WALK];
+ return an;
+}
+
+/* enemy2.c */
+#include <stdbool.h>
+struct Enemy;
+extern int enemy_health_pct; /* the difficulty: 80, 100 or 120 */
+bool enemy_area_attack(const struct Enemy *e);
+void egg_lay(struct Enemy *e);
+void eggs_step(void);
+int skeletons(void);
+void summon_skeleton(struct Enemy *e, int k);
+void demon_explode(struct Enemy *e);
+bool boss_power(struct Enemy *e);
+bool veznan_power(struct Enemy *e);
+void enemy_armor_down(struct Enemy *e, int v);
+#endif
diff --git a/games/kingdomrush/src/bullet.c b/games/kingdomrush/src/bullet.c
new file mode 100644
index 00000000..c01835cc
--- /dev/null
+++ b/games/kingdomrush/src/bullet.c
@@ -0,0 +1,224 @@
+/* What flies: arrows (Arrow.as), bolts (Bolt.as), bombs (Bomb.as), the enemies' arrows, axes and bolts, the
+ * missiles, the fireballs (Fireball.as); and what stays a while (fx: blasts, blood, smoke, gold). */
+#include <math.h>
+#include <string.h>
+#include "kr.h"
+#include "settings.h"
+#include "special.h"
+#include "gfx.h"
+
+Bullet *bullet_new(int kind) {
+ for (int i = 0; i < MAX_BULLETS; i++)
+ if (!B.bu[i].alive) {
+ Bullet *b = &B.bu[i];
+ memset(b, 0, sizeof *b);
+ b->alive = 1, b->kind = (uint8_t)kind, b->active = 1, b->target = -1;
+ return b;
+ }
+ return 0;
+}
+
+void fx_add(int anim, float x, float y, bool flip, bool decal) {
+ if (anim < 0) return;
+ int life = anim_ticks(anim);
+ if (decal) life = 120; /* blood and craters stay 4 s */
+ for (int i = 0; i < MAX_FX; i++)
+ if (!B.fx[i].alive) {
+ B.fx[i] = (Fx){1, flip, decal, (uint16_t)anim, 0, (uint16_t)life, x, y, 0};
+ return;
+ }
+}
+
+void fx_value(float x, float y, int value) {
+ for (int i = 0; i < MAX_FX; i++)
+ if (!B.fx[i].alive) {
+ B.fx[i] = (Fx){1, 0, 0, 0xFFFF, 0, 40, x, y, (int16_t)value};
+ return;
+ }
+}
+
+void fx_step(void) {
+ for (int i = 0; i < MAX_FX; i++)
+ if (B.fx[i].alive && ++B.fx[i].t >= B.fx[i].life) B.fx[i].alive = 0;
+}
+
+/* hitTestObject: the arrow's box and the enemy's (its picture and life bar) */
+static bool hits(const Bullet *b, const Enemy *e) {
+ const EnemyStat *s = &enemy_stats[e->type];
+ return b->x + 6 > e->x - s->hit_w && b->x - 6 < e->x + s->hit_w && b->y + 4 > e->y - s->hit_h && b->y - 4 < e->y + 4;
+}
+
+static bool soldier_hit(const Bullet *b, const Soldier *so) {
+ return b->x + 6 > so->x - 10 && b->x - 6 < so->x + 10 && b->y + 4 > so->y - 24 && b->y - 4 < so->y + 4;
+}
+
+/* Arrow.moveArrow: a thrown arc of t1 frames */
+static void arc(Bullet *b) {
+ float t = b->t0;
+ b->x = b->x0 + t * b->xs;
+ b->y = b->y0 + t * b->ys + b->g * t * t / 2;
+ float nx = b->x0 + (t + 1) * b->xs, ny = b->y0 + (t + 1) * b->ys + b->g * (t + 1) * (t + 1) / 2;
+ b->rot = atan2f(ny - b->y, nx - b->x);
+}
+
+static void fade(Bullet *b) {
+ if (b->fade_t == b->fade) b->alive = 0;
+ b->fade_t++;
+}
+
+/* Bomb.getDamage: falls from the most at the middle to the least at the edge (the ellipse's point that way) */
+static int bomb_damage(const Bullet *b, const Enemy *e) {
+ if (up_on(UP_ENGINEERS, 5)) return b->max_dmg; /* Efficiency */
+ float w = b->area * 1.5f, h = (float)b->area;
+ float deg = atan2f(e->x - b->tx, e->y - b->ty) * 180.0f / (float)M_PI;
+ float rad = (deg - 90.0f) * (float)M_PI / 180.0f;
+ float px = b->tx + cosf(rad) * w / 2, py = b->ty + sinf(rad) * h / 2;
+ float edge = sqrtf((px - b->tx) * (px - b->tx) + (py - b->ty) * (py - b->ty));
+ float d = sqrtf((e->x - b->tx) * (e->x - b->tx) + (e->y - b->y) * (e->y - b->y));
+ float span = (float)(b->max_dmg - b->min_dmg);
+ if (edge <= 0) return b->max_dmg;
+ return (int)(span - d * span / edge + b->min_dmg);
+}
+
+void bomb_blast(Bullet *b) {
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive || !e->active) continue;
+ if (!ellipse_contains(b->tx, b->ty, b->area * 1.5f, (float)b->area, e->x, e->y)) continue;
+ /* bombHit: a kill blows it up */
+ int dmg = bomb_damage(b, e);
+ int left = e->health - (int)((float)dmg - (float)e->armor / 2.0f * dmg / 100.0f);
+ if (left <= 0 && e->sp_state != 9) enemy_kill(e, 1);
+ else enemy_damage(e, dmg, ARM_E, 0);
+ }
+ fx_add(AN_B_BOMBDECAL, b->x, b->y, false, true);
+}
+
+void bullet_step(Bullet *b) {
+ b->anim_t++;
+ if (!b->active) {
+ fade(b);
+ return;
+ }
+ switch (b->kind) {
+ case BU_ARROW: {
+ arc(b);
+ Enemy *e = EN(b->target);
+ if (e && e->active && b->t0 + 2 >= b->t1 && hits(b, e)) {
+ b->x = e->x + enemy_stats[e->type].x_adj, b->y = e->y + enemy_stats[e->type].y_adj;
+ const TowerStat st = tower_stat(b->level == 4 ? TW_RANGER : TW_ARCHER, b->level == 4 ? 4 : b->level);
+ int dmg = rnd_dmg(b->min_dmg ? b->min_dmg : st.min_dmg, b->max_dmg ? b->max_dmg : st.max_dmg);
+ if (b->crit) dmg *= 2;
+ enemy_damage(e, dmg, ARM_P, b->pierce);
+ if (b->bombs && !e->dead) special_poison(e, b->bombs); /* the ranger's poison */
+ b->alive = 0;
+ return;
+ }
+ if (b->t0 == b->t1) {
+ fx_add(AN_B_ARROWDECAL, b->x, b->y, b->xs < 0, true);
+ b->alive = 0;
+ return;
+ }
+ b->t0++;
+ return;
+ }
+ case BU_ARROW_ENEMY: case BU_AXE_ENEMY: {
+ arc(b);
+ Soldier *so = SO(b->target);
+ if (so && so->active && b->t0 + 2 >= b->t1 && soldier_hit(b, so)) {
+ soldier_damage(so, rnd_dmg(b->min_dmg, b->max_dmg), false);
+ b->active = 0, b->fade = 11;
+ return;
+ }
+ if (b->t0 == b->t1) {
+ fx_add(AN_B_ARROWDECAL, b->x, b->y, b->xs < 0, true);
+ b->alive = 0;
+ return;
+ }
+ b->t0++;
+ return;
+ }
+ case BU_BOLT: case BU_BOLT_SORCERER: case BU_BOLT_NECRO: case BU_MISSILE_ENEMY: {
+ /* Bolt.moveMe: homes in, speeding up */
+ bool at_soldier = b->kind == BU_BOLT_NECRO || b->kind == BU_MISSILE_ENEMY;
+ float tx = b->tx, ty = b->ty;
+ if (!at_soldier) {
+ Enemy *e = EN(b->target);
+ if (e && !e->active) b->target = -1, e = 0;
+ if (e) tx = b->tx = e->x + enemy_stats[e->type].x_adj, ty = b->ty = e->y + enemy_stats[e->type].y_adj;
+ } else {
+ Soldier *so = SO(b->target);
+ if (so && !so->active) b->target = -1, so = 0;
+ if (so) tx = b->tx = so->x, ty = b->ty = so->y - 7;
+ }
+ float a = atan2f(ty - b->y, tx - b->x);
+ if (b->acc < b->acc_max) {
+ b->acc += ceilf(b->acc * 0.05f);
+ if (b->acc >= b->acc_max) b->acc = b->acc_max;
+ }
+ b->xs = cosf(a) * b->acc, b->ys = sinf(a) * b->acc;
+ b->rot = a;
+ if (b->first && ty <= b->y) b->y -= 11;
+ b->first = 0;
+ b->x += b->xs, b->y += b->ys;
+ float dx = tx - b->x, dy = ty - b->y;
+ if (sqrtf(dx * dx + dy * dy) < b->acc) {
+ if (at_soldier) {
+ Soldier *so = SO(b->target);
+ if (b->kind == BU_MISSILE_ENEMY) { /* the Juggernaut's missile: a blast on the soldiers there */
+ for (int i = 0; i < MAX_SOLDIERS; i++) {
+ Soldier *o = &B.so[i];
+ if (o->alive && o->active && ellipse_contains(tx, ty, 90, 63, o->x, o->y)) soldier_damage(o, rnd_dmg(b->min_dmg, b->max_dmg), false);
+ }
+ fx_add(AN_FX_EXPLODEBIG, tx, ty, false, false);
+ } else if (so)
+ soldier_damage(so, rnd_dmg(b->min_dmg, b->max_dmg), false);
+ } else {
+ Enemy *e = EN(b->target);
+ if (e) special_bolt_hit(b, e);
+ }
+ b->x = tx, b->y = ty, b->acc = 0;
+ b->active = 0, b->fade = 10, b->anim_t = 0;
+ }
+ return;
+ }
+ case BU_BOMB:
+ b->x = b->x0 + b->t0 * b->xs;
+ b->y = b->y0 + b->t0 * b->ys + b->g * b->t0 * b->t0 / 2;
+ b->rot += 20;
+ if (b->t0 >= b->t1) {
+ b->x = b->tx, b->y = b->ty;
+ special_bomb_hit(b);
+ b->active = 0, b->fade = 21, b->anim_t = 0;
+ return;
+ }
+ b->t0++;
+ return;
+ case BU_FIREBALL: {
+ /* Fireball.get: falls on its spot, speeding up; burns everything in 100 x 70 there */
+ float a = atan2f(b->ty - b->y, b->tx - b->x);
+ if (b->acc < b->acc_max) {
+ b->acc += ceilf(b->acc * 0.05f);
+ if (b->acc >= b->acc_max) b->acc = b->acc_max;
+ }
+ b->xs = cosf(a) * b->acc, b->ys = sinf(a) * b->acc;
+ b->x += b->xs, b->y += b->ys;
+ float dx = b->tx - b->x, dy = b->ty - b->y;
+ if (sqrtf(dx * dx + dy * dy) < b->acc) {
+ int r = b->area;
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *e = &B.en[i];
+ if (e->alive && e->active &&
+ ellipse_contains(b->tx, b->ty, (float)r, r * RANGE_RATIO, e->x + enemy_stats[e->type].x_adj, e->y + enemy_stats[e->type].y_adj))
+ enemy_damage(e, b->min_dmg, ARM_I, 0);
+ }
+ fx_add(AN_B_BOMBDECAL, b->tx, b->ty, false, true);
+ if (b->pierce) special_scorched_earth(b->tx, b->ty);
+ b->active = 0, b->fade = 30, b->anim_t = 0;
+ }
+ return;
+ }
+ default:
+ special_bullet(b);
+ }
+}
diff --git a/games/kingdomrush/src/data.S b/games/kingdomrush/src/data.S
new file mode 100644
index 00000000..84c8fa26
--- /dev/null
+++ b/games/kingdomrush/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 _kr_data
+_kr_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.kr_data,"a"
+ .balign 4
+ .global kr_data
+kr_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/kingdomrush/src/data.bin b/games/kingdomrush/src/data.bin
new file mode 100644
index 00000000..d1d8a87c
Binary files /dev/null and b/games/kingdomrush/src/data.bin differ
diff --git a/games/kingdomrush/src/data.h b/games/kingdomrush/src/data.h
new file mode 100644
index 00000000..56154adb
--- /dev/null
+++ b/games/kingdomrush/src/data.h
@@ -0,0 +1,647 @@
+/* Made by tools/pack.py: what is in data.bin. */
+#ifndef KR_DATA_H
+#define KR_DATA_H
+
+#define SEC_HUFF 0
+#define SEC_QUANT 1
+#define SEC_PICS 2
+#define SEC_TABLE 3
+#define SEC_BANK 4
+#define SEC_BGPAL 5
+#define SEC_SPAL 6
+#define SEC_FRAMES 7
+#define SEC_ANIMS 8
+#define SEC_FONTS 9
+#define SEC_LEVELS 10
+#define FONT_HUD 0
+#define FONT_BIG 1
+#define FONT_SMALL 2
+#define FONT_TEXT 3
+#define PIC_LEVEL1 0
+#define PIC_LEVEL2 1
+#define PIC_LEVEL3 2
+#define PIC_LEVEL4 3
+#define PIC_LEVEL5 4
+#define PIC_LEVEL6 5
+#define PIC_LEVEL7 6
+#define PIC_LEVEL8 7
+#define PIC_LEVEL9 8
+#define PIC_LEVEL10 9
+#define PIC_LEVEL11 10
+#define PIC_LEVEL12 11
+#define PIC_TITLE 12
+#define PIC_MAP 13
+#define MAP_Y0 17
+#define PIC_UPGRADES 14
+#define UPG_X 52
+#define AN_E_GOBLIN_WALKING 0
+#define AN_E_GOBLIN_WALKINGUP 1
+#define AN_E_GOBLIN_WALKINGDOWN 2
+#define AN_E_GOBLIN_IDLE 3
+#define AN_E_GOBLIN_FIGHTING 4
+#define AN_E_GOBLIN_DEAD 5
+#define AN_E_FATORC_WALKING 6
+#define AN_E_FATORC_WALKINGUP 7
+#define AN_E_FATORC_WALKINGDOWN 8
+#define AN_E_FATORC_IDLE 9
+#define AN_E_FATORC_FIGHTING 10
+#define AN_E_FATORC_DEAD 11
+#define AN_E_WOLFSMALL_WALKING 12
+#define AN_E_WOLFSMALL_WALKINGUP 13
+#define AN_E_WOLFSMALL_WALKINGDOWN 14
+#define AN_E_WOLFSMALL_IDLE 15
+#define AN_E_WOLFSMALL_FIGHTING 16
+#define AN_E_WOLFSMALL_DEAD 17
+#define AN_E_SHAMAN_WALKING 18
+#define AN_E_SHAMAN_WALKINGUP 19
+#define AN_E_SHAMAN_WALKINGDOWN 20
+#define AN_E_SHAMAN_IDLE 21
+#define AN_E_SHAMAN_FIGHTING 22
+#define AN_E_SHAMAN_HEALING 23
+#define AN_E_SHAMAN_DEAD 24
+#define AN_E_OGRE_WALKING 25
+#define AN_E_OGRE_WALKINGUP 26
+#define AN_E_OGRE_WALKINGDOWN 27
+#define AN_E_OGRE_IDLE 28
+#define AN_E_OGRE_FIGHTING 29
+#define AN_E_OGRE_DEAD 30
+#define AN_E_BANDIT_WALKING 31
+#define AN_E_BANDIT_WALKINGUP 32
+#define AN_E_BANDIT_WALKINGDOWN 33
+#define AN_E_BANDIT_IDLE 34
+#define AN_E_BANDIT_FIGHTING 35
+#define AN_E_BANDIT_DEAD 36
+#define AN_E_BRIGAND_WALKING 37
+#define AN_E_BRIGAND_WALKINGUP 38
+#define AN_E_BRIGAND_WALKINGDOWN 39
+#define AN_E_BRIGAND_IDLE 40
+#define AN_E_BRIGAND_FIGHTING 41
+#define AN_E_BRIGAND_DEAD 42
+#define AN_E_MARAUDER_WALKING 43
+#define AN_E_MARAUDER_WALKINGUP 44
+#define AN_E_MARAUDER_WALKINGDOWN 45
+#define AN_E_MARAUDER_IDLE 46
+#define AN_E_MARAUDER_FIGHTING 47
+#define AN_E_MARAUDER_DEAD 48
+#define AN_E_WOLF_WALKING 49
+#define AN_E_WOLF_WALKINGUP 50
+#define AN_E_WOLF_WALKINGDOWN 51
+#define AN_E_WOLF_IDLE 52
+#define AN_E_WOLF_FIGHTING 53
+#define AN_E_WOLF_DEAD 54
+#define AN_E_SPIDER_WALKING 55
+#define AN_E_SPIDER_WALKINGUP 56
+#define AN_E_SPIDER_WALKINGDOWN 57
+#define AN_E_SPIDER_IDLE 58
+#define AN_E_SPIDER_FIGHTING 59
+#define AN_E_SPIDER_DEAD 60
+#define AN_E_SPIDERSMALL_WALKING 61
+#define AN_E_SPIDERSMALL_WALKINGUP 62
+#define AN_E_SPIDERSMALL_WALKINGDOWN 63
+#define AN_E_SPIDERSMALL_IDLE 64
+#define AN_E_SPIDERSMALL_FIGHTING 65
+#define AN_E_SPIDERSMALL_DEAD 66
+#define AN_E_SPIDERTINY_WALKING 67
+#define AN_E_SPIDERTINY_WALKINGUP 68
+#define AN_E_SPIDERTINY_WALKINGDOWN 69
+#define AN_E_SPIDERTINY_IDLE 70
+#define AN_E_SPIDERTINY_FIGHTING 71
+#define AN_E_SPIDERTINY_DEAD 72
+#define AN_E_SHADOWARCHER_WALKING 73
+#define AN_E_SHADOWARCHER_WALKINGUP 74
+#define AN_E_SHADOWARCHER_WALKINGDOWN 75
+#define AN_E_SHADOWARCHER_IDLE 76
+#define AN_E_SHADOWARCHER_FIGHTING 77
+#define AN_E_SHADOWARCHER_ARROW 78
+#define AN_E_SHADOWARCHER_DEAD 79
+#define AN_E_DARKKNIGHT_WALKING 80
+#define AN_E_DARKKNIGHT_WALKINGUP 81
+#define AN_E_DARKKNIGHT_WALKINGDOWN 82
+#define AN_E_DARKKNIGHT_IDLE 83
+#define AN_E_DARKKNIGHT_FIGHTING 84
+#define AN_E_DARKKNIGHT_DEAD 85
+#define AN_E_GARGOYLE_WALKING 86
+#define AN_E_GARGOYLE_WALKINGUP 87
+#define AN_E_GARGOYLE_WALKINGDOWN 88
+#define AN_E_GARGOYLE_DEAD 89
+#define AN_E_JUGGERNAUT_WALKING 90
+#define AN_E_JUGGERNAUT_WALKINGUP 91
+#define AN_E_JUGGERNAUT_IDLE 92
+#define AN_E_JUGGERNAUT_FIGHTING 93
+#define AN_E_JUGGERNAUT_MISSILE 94
+#define AN_E_JUGGERNAUT_DEAD 95
+#define AN_E_GOLEMHEAD_WALKING 96
+#define AN_E_GOLEMHEAD_WALKINGUP 97
+#define AN_E_GOLEMHEAD_IDLE 98
+#define AN_E_GOLEMHEAD_FIGHTING 99
+#define AN_E_GOLEMHEAD_DEAD 100
+#define AN_E_WHITEWOLF_WALKING 101
+#define AN_E_WHITEWOLF_WALKINGUP 102
+#define AN_E_WHITEWOLF_WALKINGDOWN 103
+#define AN_E_WHITEWOLF_IDLE 104
+#define AN_E_WHITEWOLF_FIGHTING 105
+#define AN_E_WHITEWOLF_DEAD 106
+#define AN_E_TROLL_WALKING 107
+#define AN_E_TROLL_WALKINGUP 108
+#define AN_E_TROLL_WALKINGDOWN 109
+#define AN_E_TROLL_IDLE 110
+#define AN_E_TROLL_FIGHTING 111
+#define AN_E_TROLL_DEAD 112
+#define AN_E_TROLLCHIEFTAIN_WALKING 113
+#define AN_E_TROLLCHIEFTAIN_WALKINGUP 114
+#define AN_E_TROLLCHIEFTAIN_WALKINGDOWN 115
+#define AN_E_TROLLCHIEFTAIN_IDLE 116
+#define AN_E_TROLLCHIEFTAIN_FIGHTING 117
+#define AN_E_TROLLCHIEFTAIN_RAGE 118
+#define AN_E_TROLLCHIEFTAIN_DEAD 119
+#define AN_E_TROLLAXETHROWER_WALKING 120
+#define AN_E_TROLLAXETHROWER_WALKINGUP 121
+#define AN_E_TROLLAXETHROWER_WALKINGDOWN 122
+#define AN_E_TROLLAXETHROWER_IDLE 123
+#define AN_E_TROLLAXETHROWER_AXE 124
+#define AN_E_TROLLAXETHROWER_FIGHTING 125
+#define AN_E_TROLLAXETHROWER_DEAD 126
+#define AN_E_YETI_WALKING 127
+#define AN_E_YETI_WALKINGUP 128
+#define AN_E_YETI_WALKINGDOWN 129
+#define AN_E_YETI_IDLE 130
+#define AN_E_YETI_FIGHTING 131
+#define AN_E_YETI_DEAD 132
+#define AN_E_YETIBOSS_WALKING 133
+#define AN_E_YETIBOSS_WALKINGDOWN 134
+#define AN_E_YETIBOSS_IDLE 135
+#define AN_E_YETIBOSS_FIGHTING 136
+#define AN_E_YETIBOSS_FROZE 137
+#define AN_E_YETIBOSS_BREATH 138
+#define AN_E_YETIBOSS_PREDEAD 139
+#define AN_E_YETIBOSS_DEAD 140
+#define AN_E_SLAYER_WALKING 141
+#define AN_E_SLAYER_WALKINGUP 142
+#define AN_E_SLAYER_WALKINGDOWN 143
+#define AN_E_SLAYER_IDLE 144
+#define AN_E_SLAYER_FIGHTING 145
+#define AN_E_SLAYER_DEAD 146
+#define AN_E_ROCKETEER_WALKING 147
+#define AN_E_ROCKETEER_WALKINGFAST 148
+#define AN_E_ROCKETEER_WALKINGUP 149
+#define AN_E_ROCKETEER_WALKINGUPFAST 150
+#define AN_E_ROCKETEER_WALKINGDOWN 151
+#define AN_E_ROCKETEER_WALKINGDOWNFAST 152
+#define AN_E_ROCKETEER_DEAD 153
+#define AN_E_SKELETON_WALKING 154
+#define AN_E_SKELETON_WALKINGUP 155
+#define AN_E_SKELETON_WALKINGDOWN 156
+#define AN_E_SKELETON_IDLE 157
+#define AN_E_SKELETON_FIGHTING 158
+#define AN_E_SKELETON_RESPAWNING 159
+#define AN_E_SKELETON_DEAD 160
+#define AN_E_SKELETONBIG_WALKING 161
+#define AN_E_SKELETONBIG_WALKINGUP 162
+#define AN_E_SKELETONBIG_WALKINGDOWN 163
+#define AN_E_SKELETONBIG_IDLE 164
+#define AN_E_SKELETONBIG_FIGHTING 165
+#define AN_E_SKELETONBIG_RESPAWNING 166
+#define AN_E_SKELETONBIG_DEAD 167
+#define AN_E_DEMONWOLF_WALKING 168
+#define AN_E_DEMONWOLF_WALKINGUP 169
+#define AN_E_DEMONWOLF_WALKINGDOWN 170
+#define AN_E_DEMONWOLF_IDLE 171
+#define AN_E_DEMONWOLF_FIGHTING 172
+#define AN_E_DEMONWOLF_DEAD 173
+#define AN_E_DEMON_WALKING 174
+#define AN_E_DEMON_WALKINGUP 175
+#define AN_E_DEMON_WALKINGDOWN 176
+#define AN_E_DEMON_IDLE 177
+#define AN_E_DEMON_FIGHTING 178
+#define AN_E_DEMON_DEAD 179
+#define AN_E_DEMONMAGE_WALKING 180
+#define AN_E_DEMONMAGE_WALKINGUP 181
+#define AN_E_DEMONMAGE_WALKINGDOWN 182
+#define AN_E_DEMONMAGE_IDLE 183
+#define AN_E_DEMONMAGE_FIGHTING 184
+#define AN_E_DEMONMAGE_SHIELD 185
+#define AN_E_DEMONMAGE_DEAD 186
+#define AN_E_NECROMANCER_WALKING 187
+#define AN_E_NECROMANCER_WALKINGUP 188
+#define AN_E_NECROMANCER_WALKINGDOWN 189
+#define AN_E_NECROMANCER_IDLE 190
+#define AN_E_NECROMANCER_FIGHTING 191
+#define AN_E_NECROMANCER_SPELL 192
+#define AN_E_NECROMANCER_SUMMON 193
+#define AN_E_NECROMANCER_DEAD 194
+#define AN_E_DEMONIMP_WALKING 195
+#define AN_E_DEMONIMP_WALKINGUP 196
+#define AN_E_DEMONIMP_WALKINGDOWN 197
+#define AN_E_DEMONIMP_DEAD 198
+#define AN_E_LAVAELEMENTAL_WALKING 199
+#define AN_E_LAVAELEMENTAL_WALKINGUP 200
+#define AN_E_LAVAELEMENTAL_WALKINGDOWN 201
+#define AN_E_LAVAELEMENTAL_IDLE 202
+#define AN_E_LAVAELEMENTAL_FIGHTING 203
+#define AN_E_LAVAELEMENTAL_RESPAWNING 204
+#define AN_E_LAVAELEMENTAL_DEAD 205
+#define AN_E_VEZNAN_WALKING 206
+#define AN_E_VEZNAN_WALKINGDOWN 207
+#define AN_E_VEZNAN_WALKINGUP 208
+#define AN_E_VEZNAN_IDLE 209
+#define AN_E_VEZNAN_IDLEDOWN 210
+#define AN_E_VEZNAN_FIGHTING 211
+#define AN_E_VEZNAN_SPELL 212
+#define AN_E_VEZNAN_SPELLDOWN 213
+#define AN_E_VEZNAN_RANGEDATTACK 214
+#define AN_E_VEZNAN_RANGEDLOOP 215
+#define AN_E_VEZNAN_RANGEDRELEASE 216
+#define AN_E_VEZNAN_TODEMON 217
+#define AN_E_VEZNAN_WALKINGDEMON 218
+#define AN_E_VEZNAN_WALKINGDOWNDEMON 219
+#define AN_E_VEZNAN_IDLEDEMON 220
+#define AN_E_VEZNAN_FIGHTINGDEMON 221
+#define AN_E_VEZNAN_FADE 222
+#define AN_E_VEZNAN_LAUGH 223
+#define AN_E_VEZNAN_DEAD 224
+#define AN_E_SHEEPGROUND_IDLE 225
+#define AN_E_SHEEPGROUND_WALKING 226
+#define AN_E_SHEEPGROUND_WALKINGUP 227
+#define AN_E_SHEEPGROUND_WALKINGDOWN 228
+#define AN_E_SHEEPGROUND_DEAD 229
+#define AN_E_SHEEPFLYING_IDLE 230
+#define AN_E_SHEEPFLYING_WALKING 231
+#define AN_E_SHEEPFLYING_WALKINGUP 232
+#define AN_E_SHEEPFLYING_WALKINGDOWN 233
+#define AN_E_SHEEPFLYING_DEAD 234
+#define AN_FX_TELEPORT 235
+#define AN_FX_EXPLODENORMAL 236
+#define AN_FX_EXPLODEBIG 237
+#define AN_FX_EXPLODEAIR 238
+#define AN_FX_DESINTEGRATENORMAL 239
+#define AN_FX_DESINTEGRATEBIG 240
+#define AN_FX_DESINTEGRATEAIR 241
+#define AN_FX_POLYMORPHNORMAL 242
+#define AN_FX_POLYMORPHBIG 243
+#define AN_FX_POLYMORPHAIR 244
+#define AN_T_ARCHER1_ALL 245
+#define AN_T_ARCHER2_ALL 246
+#define AN_T_ARCHER3_ALL 247
+#define AN_T_RANGER_ALL 248
+#define AN_T_MUSKETEER_ALL 249
+#define AN_T_MAGE1_IDLE 250
+#define AN_T_MAGE1_SHOOT 251
+#define AN_T_MAGE2_IDLE 252
+#define AN_T_MAGE2_SHOOT 253
+#define AN_T_MAGE3_IDLE 254
+#define AN_T_MAGE3_SHOOT 255
+#define AN_T_ARCANE_IDLE 256
+#define AN_T_ARCANE_SHOOT 257
+#define AN_T_ARCANE_TELEPORT 258
+#define AN_T_SORCERER_IDLE 259
+#define AN_T_SORCERER_SHOOT 260
+#define AN_T_ENG1_IDLE 261
+#define AN_T_ENG1_SHOOT 262
+#define AN_T_ENG2_IDLE 263
+#define AN_T_ENG2_SHOOT 264
+#define AN_T_ENG3_IDLE 265
+#define AN_T_ENG3_SHOOT 266
+#define AN_T_BFG_IDLE 267
+#define AN_T_BFG_SHOOT 268
+#define AN_T_BFG_SHOOT_MISSILE 269
+#define AN_T_TESLA_IDLE 270
+#define AN_T_TESLA_SHOOTING 271
+#define AN_T_BAR1_IDLE 272
+#define AN_T_BAR1_DOOR_OPEN 273
+#define AN_T_BAR1_DOOR_CLOSED 274
+#define AN_T_BAR2_IDLE 275
+#define AN_T_BAR2_OPEN_DOOR 276
+#define AN_T_BAR2_DOOR_CLOSED 277
+#define AN_T_BAR3_IDLE 278
+#define AN_T_BAR3_OPEN_DOOR 279
+#define AN_T_BAR3_DOOR_CLOSED 280
+#define AN_T_PALADIN_IDLE 281
+#define AN_T_PALADIN_OPEN_DOOR 282
+#define AN_T_PALADIN_DOOR_CLOSED 283
+#define AN_T_BARBARIAN_IDLE 284
+#define AN_T_BARBARIAN_OPEN_DOOR 285
+#define AN_T_BARBARIAN_DOOR_CLOSED 286
+#define AN_T_HOLDER_FOREST 287
+#define AN_T_HOLDER_SNOW 288
+#define AN_T_HOLDER_WASTELAND 289
+#define AN_T_BASE_ARCHER_FOREST 290
+#define AN_T_BASE_ARCHER_SNOW 291
+#define AN_T_BASE_ARCHER_WASTELAND 292
+#define AN_T_BASE_MAGE_FOREST 293
+#define AN_T_BASE_MAGE_SNOW 294
+#define AN_T_BASE_MAGE_WASTELAND 295
+#define AN_T_BASE_BAR_FOREST 296
+#define AN_T_BASE_BAR_SNOW 297
+#define AN_T_BASE_BAR_WASTELAND 298
+#define AN_T_BUILD_ARCHER 299
+#define AN_T_BUILD_MAGE 300
+#define AN_T_BUILD_BAR 301
+#define AN_T_FLAG 302
+#define AN_T_RALLY 303
+#define AN_T_CLOUD 304
+#define AN_T_SELL 305
+#define AN_S_ARCHER1_IDLEDOWN 306
+#define AN_S_ARCHER1_IDLEUP 307
+#define AN_S_ARCHER1_SHOOTDOWN 308
+#define AN_S_ARCHER1_SHOOTUP 309
+#define AN_S_ARCHER2_IDLEDOWN 310
+#define AN_S_ARCHER2_IDLEUP 311
+#define AN_S_ARCHER2_SHOOTDOWN 312
+#define AN_S_ARCHER2_SHOOTUP 313
+#define AN_S_ARCHER3_IDLEDOWN 314
+#define AN_S_ARCHER3_IDLEUP 315
+#define AN_S_ARCHER3_SHOOTDOWN 316
+#define AN_S_ARCHER3_SHOOTUP 317
+#define AN_S_RANGER_IDLEDOWN 318
+#define AN_S_RANGER_IDLEUP 319
+#define AN_S_RANGER_SHOOTDOWN 320
+#define AN_S_RANGER_SHOOTUP 321
+#define AN_S_MUSKETEER_IDLEDOWN 322
+#define AN_S_MUSKETEER_IDLEUP 323
+#define AN_S_MUSKETEER_SHOOTDOWN 324
+#define AN_S_MUSKETEER_SHOOTUP 325
+#define AN_S_MUSKETEER_SNIPERAIMDOWN 326
+#define AN_S_MUSKETEER_SNIPERSHOOTDOWN 327
+#define AN_S_MUSKETEER_SNIPERAIMUP 328
+#define AN_S_MUSKETEER_SNIPERSHOOTUP 329
+#define AN_S_MUSKETEER_SNIPERSEEKDOWN 330
+#define AN_S_MUSKETEER_SNIPERSEEKUP 331
+#define AN_S_MUSKETEER_SNIPERSEEKHIDEDOWN 332
+#define AN_S_MUSKETEER_SNIPERSEEKHIDEUP 333
+#define AN_S_MUSKETEER_CANONFUSEDOWN 334
+#define AN_S_MUSKETEER_CANONFUSEUP 335
+#define AN_S_MUSKETEER_CANONSHOOTERDOWN 336
+#define AN_S_MUSKETEER_CANONSHOOTERUP 337
+#define AN_S_MAGE_IDLEDOWN 338
+#define AN_S_MAGE_IDLEUP 339
+#define AN_S_MAGE_SHOOT_DOWN 340
+#define AN_S_MAGE_SHOOT_UP 341
+#define AN_S_ARCANE_IDLEDOWN 342
+#define AN_S_ARCANE_IDLEUP 343
+#define AN_S_ARCANE_SHOOT_DOWN 344
+#define AN_S_ARCANE_SHOOT_UP 345
+#define AN_S_ARCANE_TELEPORT_DOWN 346
+#define AN_S_ARCANE_TELEPORT_UP 347
+#define AN_S_SORCERER_IDLEDOWN 348
+#define AN_S_SORCERER_IDLEUP 349
+#define AN_S_SORCERER_SHOOT_DOWN 350
+#define AN_S_SORCERER_SHOOT_UP 351
+#define AN_S_SORCERER_POLYMORPH_DOWN 352
+#define AN_S_SORCERER_POLYMORPH_UP 353
+#define AN_SO_STANDAR_IDLE 354
+#define AN_SO_STANDAR_RUNNING 355
+#define AN_SO_STANDAR_FIGHTING 356
+#define AN_SO_STANDAR_DEAD 357
+#define AN_SO_STANDARLEVEL2_IDLE 358
+#define AN_SO_STANDARLEVEL2_RUNNING 359
+#define AN_SO_STANDARLEVEL2_FIGHTING 360
+#define AN_SO_STANDARLEVEL2_DEAD 361
+#define AN_SO_STANDARLEVEL3_IDLE 362
+#define AN_SO_STANDARLEVEL3_RUNNING 363
+#define AN_SO_STANDARLEVEL3_FIGHTING 364
+#define AN_SO_STANDARLEVEL3_DEAD 365
+#define AN_SO_PALADIN_IDLE 366
+#define AN_SO_PALADIN_RUNNING 367
+#define AN_SO_PALADIN_ATTACK1 368
+#define AN_SO_PALADIN_ATTACK2 369
+#define AN_SO_PALADIN_HOLYSTRIKE 370
+#define AN_SO_PALADIN_HEAL 371
+#define AN_SO_PALADIN_DEAD 372
+#define AN_SO_BARBARIAN_IDLE 373
+#define AN_SO_BARBARIAN_IDLE2 374
+#define AN_SO_BARBARIAN_RUNNING 375
+#define AN_SO_BARBARIAN_RUNNING2 376
+#define AN_SO_BARBARIAN_ATTACK 377
+#define AN_SO_BARBARIAN_ATTACK2 378
+#define AN_SO_BARBARIAN_HUNTING_NETS2 379
+#define AN_SO_BARBARIAN_HUNTING_NETS 380
+#define AN_SO_BARBARIAN_THROWING_AXE2 381
+#define AN_SO_BARBARIAN_THROWING_AXE 382
+#define AN_SO_BARBARIAN_DEAD 383
+#define AN_SO_ELEMENTAL_IDLE 384
+#define AN_SO_ELEMENTAL_RUNNING 385
+#define AN_SO_ELEMENTAL_FIGHTING 386
+#define AN_SO_ELEMENTAL_DEAD 387
+#define AN_SO_ELEMENTAL_RESPAWNING 388
+#define AN_SO_FARMERJOHN_IDLE 389
+#define AN_SO_FARMERJOHN_RUNNING 390
+#define AN_SO_FARMERJOHN_FIGHTING 391
+#define AN_SO_FARMERJOHN_RESPAWNING 392
+#define AN_SO_FARMERJOHN_DEAD 393
+#define AN_SO_FARMERPAUL_IDLE 394
+#define AN_SO_FARMERPAUL_RUNNING 395
+#define AN_SO_FARMERPAUL_FIGHTING 396
+#define AN_SO_FARMERPAUL_RESPAWNING 397
+#define AN_SO_FARMERPAUL_DEAD 398
+#define AN_SO_FARMERRINGO_IDLE 399
+#define AN_SO_FARMERRINGO_RUNNING 400
+#define AN_SO_FARMERRINGO_FIGHTING 401
+#define AN_SO_FARMERRINGO_RESPAWNING 402
+#define AN_SO_FARMERRINGO_DEAD 403
+#define AN_SO_REINFORCEMENTLEVEL2A_IDLE 404
+#define AN_SO_REINFORCEMENTLEVEL2A_RUNNING 405
+#define AN_SO_REINFORCEMENTLEVEL2A_FIGHTING 406
+#define AN_SO_REINFORCEMENTLEVEL2A_RESPAWNING 407
+#define AN_SO_REINFORCEMENTLEVEL2A_DEAD 408
+#define AN_SO_REINFORCEMENTLEVEL2B_IDLE 409
+#define AN_SO_REINFORCEMENTLEVEL2B_RUNNING 410
+#define AN_SO_REINFORCEMENTLEVEL2B_FIGHTING 411
+#define AN_SO_REINFORCEMENTLEVEL2B_RESPAWNING 412
+#define AN_SO_REINFORCEMENTLEVEL2B_DEAD 413
+#define AN_SO_REINFORCEMENTLEVEL3A_IDLE 414
+#define AN_SO_REINFORCEMENTLEVEL3A_RUNNING 415
+#define AN_SO_REINFORCEMENTLEVEL3A_FIGHTING 416
+#define AN_SO_REINFORCEMENTLEVEL3A_RESPAWNING 417
+#define AN_SO_REINFORCEMENTLEVEL3A_DEAD 418
+#define AN_SO_REINFORCEMENTLEVEL3B_IDLE 419
+#define AN_SO_REINFORCEMENTLEVEL3B_RUNNING 420
+#define AN_SO_REINFORCEMENTLEVEL3B_FIGHTING 421
+#define AN_SO_REINFORCEMENTLEVEL3B_RESPAWNING 422
+#define AN_SO_REINFORCEMENTLEVEL3B_DEAD 423
+#define AN_SO_REINFORCEMENTLEVEL4A_IDLE 424
+#define AN_SO_REINFORCEMENTLEVEL4A_RUNNING 425
+#define AN_SO_REINFORCEMENTLEVEL4A_FIGHTING 426
+#define AN_SO_REINFORCEMENTLEVEL4A_RESPAWNING 427
+#define AN_SO_REINFORCEMENTLEVEL4A_SPEAR 428
+#define AN_SO_REINFORCEMENTLEVEL4A_DEAD 429
+#define AN_SO_REINFORCEMENTLEVEL4B_IDLE 430
+#define AN_SO_REINFORCEMENTLEVEL4B_RUNNING 431
+#define AN_SO_REINFORCEMENTLEVEL4B_FIGHTING 432
+#define AN_SO_REINFORCEMENTLEVEL4B_RESPAWNING 433
+#define AN_SO_REINFORCEMENTLEVEL4B_SPEAR 434
+#define AN_SO_REINFORCEMENTLEVEL4B_DEAD 435
+#define AN_B_ARROW_IDLE 436
+#define AN_B_ARROWENEMY_IDLE 437
+#define AN_B_ARROWENEMY_HIT 438
+#define AN_B_BOLTNECROMANCER_TRAVEL 439
+#define AN_B_BOLTNECROMANCER_HIT 440
+#define AN_B_BOLTSORCERER_TRAVEL 441
+#define AN_B_BOLTSORCERER_HIT 442
+#define AN_B_BOMBBFG_IDLE 443
+#define AN_B_BOMBBFG_HIT 444
+#define AN_B_BOMBBLACK_IDLE 445
+#define AN_B_BOMBBLACK_HIT 446
+#define AN_B_BOMBCOMMON_IDLE 447
+#define AN_B_BOMBCOMMON_HIT 448
+#define AN_B_BOMBDYNAMITE_IDLE 449
+#define AN_B_BOMBDYNAMITE_HIT 450
+#define AN_B_BOMBFRAGMENT_IDLE 451
+#define AN_B_BOMBFRAGMENT_HIT 452
+#define AN_B_BOMBSHRAPNEL_IDLE 453
+#define AN_B_BOMBSHRAPNEL_HIT 454
+#define AN_B_FIREBALL_TRAVEL 455
+#define AN_B_FIREBALL_HIT 456
+#define AN_B_MISSILE_START 457
+#define AN_B_MISSILE_HIT 458
+#define AN_B_MISSILE_AIRHIT 459
+#define AN_B_MISSILEENEMY_START 460
+#define AN_B_MISSILEENEMY_HIT 461
+#define AN_B_MISSILEENEMY_AIRHIT 462
+#define AN_B_RAYARCANECOMMON 463
+#define AN_B_RAYARCANEDESINTEGRATE 464
+#define AN_B_RAYPOLYMORPH 465
+#define AN_B_RAYTESLA 466
+#define AN_B_AXE_IDLE 467
+#define AN_B_AXEENEMY_IDLE 468
+#define AN_B_AXEENEMY_HIT 469
+#define AN_B_ICEBLOCK_START 470
+#define AN_B_ICEBLOCK_IDLE 471
+#define AN_B_ICEBLOCK_END 472
+#define AN_B_VEZNANBLOCK_START 473
+#define AN_B_VEZNANBLOCK_IDLE 474
+#define AN_B_VEZNANBLOCK_HOLD 475
+#define AN_B_VEZNANBLOCK_RELEASE 476
+#define AN_B_SPIDEREGG 477
+#define AN_B_TELEPORTPORTAL 478
+#define AN_B_DEMONFIRE 479
+#define AN_B_JUGGERNAUTEGG_START 480
+#define AN_B_JUGGERNAUTEGG_END 481
+#define AN_B_BLOODDECAL 482
+#define AN_B_BOMBDECAL 483
+#define AN_B_ARROWDECAL 484
+#define AN_B_BLOOD 485
+#define AN_B_BLOODGREEN 486
+#define AN_B_DEFENSEINDICATOR 487
+#define AN_B_WAVEFLAGREWARD 488
+#define AN_B_BOLT_TRAVEL 489
+#define AN_B_BOLT_HIT 490
+#define AN_UI_WAVEFLAG 491
+#define AN_UI_WAVEICO_GROUND 492
+#define AN_UI_WAVEICO_AIR 493
+#define AN_UI_ICONS 494
+#define AN_UI_PFIRE_IDLE 495
+#define AN_UI_PFIRE_SEL 496
+#define AN_UI_PFIRE_OPEN 497
+#define AN_UI_PFIRE_READY 498
+#define AN_UI_PREINF_IDLE 499
+#define AN_UI_PREINF_SEL 500
+#define AN_UI_PREINF_OPEN 501
+#define AN_UI_PREINF_READY 502
+#define AN_UI_HEART 503
+#define AN_UI_COIN 504
+#define AN_UI_SKULL 505
+#define AN_UI_FLAGNEW 506
+#define AN_UI_FLAGDONE 507
+#define AN_UI_FLAGSEL 508
+#define AN_UI_FLAGSTAR 509
+#define AN_UI_FLAGHEROIC 510
+#define AN_UI_UPICONS 511
+#define AN_UI_UPITEM 512
+#define AN_T_BASE_ENG_FOREST 513
+#define AN_T_BASE_ENG_SNOW 514
+#define AN_T_BASE_ENG_WASTELAND 515
+#define AN_T_BASE_BFG_FOREST 516
+#define AN_T_BASE_BFG_SNOW 517
+#define AN_T_BASE_BFG_WASTELAND 518
+#define AN_T_BASE_TESLA_FOREST 519
+#define AN_T_BASE_TESLA_SNOW 520
+#define AN_T_BASE_TESLA_WASTELAND 521
+#define AN_T_BASE_RANGER_FOREST 522
+#define AN_T_BASE_RANGER_SNOW 523
+#define AN_T_BASE_RANGER_WASTELAND 524
+#define AN_T_BASE_MUSKETEER_FOREST 525
+#define AN_T_BASE_MUSKETEER_SNOW 526
+#define AN_T_BASE_MUSKETEER_WASTELAND 527
+#define EN_GOBLIN 0
+#define EN_FATORC 1
+#define EN_WOLFSMALL 2
+#define EN_SHAMAN 3
+#define EN_OGRE 4
+#define EN_BANDIT 5
+#define EN_BRIGAND 6
+#define EN_MARAUDER 7
+#define EN_WOLF 8
+#define EN_SPIDER 9
+#define EN_SPIDERSMALL 10
+#define EN_SPIDERTINY 11
+#define EN_SHADOWARCHER 12
+#define EN_DARKKNIGHT 13
+#define EN_GARGOYLE 14
+#define EN_JUGGERNAUT 15
+#define EN_GOLEMHEAD 16
+#define EN_WHITEWOLF 17
+#define EN_TROLL 18
+#define EN_TROLLCHIEFTAIN 19
+#define EN_TROLLAXETHROWER 20
+#define EN_YETI 21
+#define EN_YETIBOSS 22
+#define EN_SLAYER 23
+#define EN_ROCKETEER 24
+#define EN_SKELETON 25
+#define EN_SKELETONBIG 26
+#define EN_DEMONWOLF 27
+#define EN_DEMON 28
+#define EN_DEMONMAGE 29
+#define EN_NECROMANCER 30
+#define EN_DEMONIMP 31
+#define EN_LAVAELEMENTAL 32
+#define EN_VEZNAN 33
+#define EN_SHEEPGROUND 34
+#define EN_SHEEPFLYING 35
+#define EN_COUNT 36
+#define NLEVELS 12
+
+#define NOTE_NONE 0
+#define NOTE_POWERREINFORCEMENT 1
+#define NOTE_POWERFIREBALL 2
+#define NOTE_ENEMYGOBLIN 3
+#define NOTE_ENEMYFATORC 4
+#define NOTE_TIPARMOR 5
+#define NOTE_TIPRALLYPOINT 6
+#define NOTE_TOWERLEVEL2 7
+#define NOTE_TIPSTRATEGYSOLDIER 8
+#define NOTE_ENEMYWOLFSMALL 9
+#define NOTE_ENEMYSHAMAN 10
+#define NOTE_TIPARMORMAGIC 11
+#define NOTE_ENEMYOGRE 12
+#define NOTE_TOWERLEVEL3 13
+#define NOTE_ENEMYBANDIT 14
+#define NOTE_ENEMYBRIGAND 15
+#define NOTE_ENEMYSPIDERSMALL 16
+#define NOTE_TOWERARCHERRANGER 17
+#define NOTE_ENEMYWOLF 18
+#define NOTE_ENEMYSPIDER 19
+#define NOTE_ENEMYMARAUDER 20
+#define NOTE_TOWERMAGEARCANE 21
+#define NOTE_TIPSTRATEGYHEAVYARMOR 22
+#define NOTE_ENEMYDARKKNIGHT 23
+#define NOTE_ENEMYGARGOYLE 24
+#define NOTE_ENEMYSHADOWARCHER 25
+#define NOTE_TOWERARCHERMUSKETEER 26
+#define NOTE_ENEMYTROLL 27
+#define NOTE_ENEMYWHITEWOLF 28
+#define NOTE_TOWERSOLDIERBARBARIAN 29
+#define NOTE_ENEMYTROLLAXETHROWER 30
+#define NOTE_ENEMYYETI 31
+#define NOTE_ENEMYTROLLCHIEFTAIN 32
+#define NOTE_TOWERMAGESORCERER 33
+#define NOTE_ENEMYSLAYER 34
+#define NOTE_ENEMYROCKETEER 35
+#define NOTE_TOWERENGINEERTESLA 36
+#define NOTE_ENEMYDEMON 37
+#define NOTE_ENEMYDEMONMAGE 38
+#define NOTE_ENEMYDEMONWOLF 39
+#define NOTE_ENEMYDEMONIMP 40
+#define NOTE_ENEMYNECROMANCER 41
+
+#endif
diff --git a/games/kingdomrush/src/enemy.c b/games/kingdomrush/src/enemy.c
new file mode 100644
index 00000000..e8380cd9
--- /dev/null
+++ b/games/kingdomrush/src/enemy.c
@@ -0,0 +1,618 @@
+/* The enemies (Enemy.as, EnemyCommon.as and each Enemy*.as). */
+#include <math.h>
+#include <string.h>
+#include "anim.h"
+#include "kr.h"
+#include "settings.h"
+
+#define ST(e) (&enemy_stats[(e)->type])
+
+float ellipse_contains(float cx, float cy, float w, float h, float px, float py) {
+ /* casalib's Ellipse.containsPoint, the ellipse given by its centre and size */
+ float rx = w / 2, ry = h / 2;
+ if (rx <= 0 || ry <= 0) return 0;
+ float dx = (px - cx) / rx, dy = (py - cy) / ry;
+ return dx * dx + dy * dy <= 1.0f;
+}
+
+Pt enemy_road(const Enemy *e, int ahead) {
+ int n = e->node + ahead, len = path_len(e->path, e->lane);
+ if (n >= len) n = len - 1;
+ if (n < 0) n = 0;
+ return path_node(e->path, e->lane, n);
+}
+
+int enemy_nodes_speed(const Enemy *e) {
+ if (e->blocked || e->held) return 0;
+ int k = (int)ceilf(5.5f * e->speed), len = path_len(e->path, e->lane);
+ if (e->node + k >= len) return len - e->node - 1;
+ return k;
+}
+
+/* ------------------------------------------------------------------ animations */
+static void play(Enemy *e, int an) {
+ if (an < 0) return;
+ e->anim = (uint16_t)an, e->anim_t = 0;
+}
+
+/* getFacing: the walk for the road's direction */
+static void facing(Enemy *e) {
+ if (e->fighting) {
+ e->charge_t = 0;
+ play(e, ANIM(e->type, A_IDLE));
+ return;
+ }
+ Pt a = enemy_road(e, 0), b = enemy_road(e, 1);
+ int ang = (int)lroundf(atan2f(-(b.y - a.y), b.x - a.x) * 180.0f / (float)M_PI);
+ if (ang < 0) ang += 360;
+ int d;
+ if (ang > 55 && ang < 135) d = 3;
+ else if (ang >= 135 && ang <= 240) d = 2;
+ else if (ang > 240 && ang < 315) d = 4;
+ else d = 1;
+ if (d == e->dir) return;
+ e->dir = (uint8_t)d;
+ if (d == 1 || d == 2) e->left = d == 2;
+ int an = ANIM(e->type, d == 3 ? A_UP : d == 4 ? A_DOWN : A_WALK);
+ if (an < 0) an = ANIM(e->type, A_WALK);
+ play(e, an);
+}
+
+/* ------------------------------------------------------------------ spawn */
+int enemy_spawn(int type, int path, int lane, int node) {
+ int i = 0;
+ while (i < MAX_ENEMIES && B.en[i].alive) i++;
+ if (i == MAX_ENEMIES) return -1;
+ Enemy *e = &B.en[i];
+ memset(e, 0, sizeof *e);
+ const EnemyStat *s = &enemy_stats[type];
+ e->alive = 1, e->type = (uint8_t)type, e->path = (uint8_t)path, e->lane = (uint8_t)lane;
+ e->node = (int16_t)node;
+ Pt p = path_node(path, lane, node);
+ e->x = p.x, e->y = p.y;
+ e->health = e->init_health = (s->health * enemy_health_pct + 50) / 100;
+ if (s->health == 0) e->health = e->init_health = 1;
+ e->armor = s->armor, e->magic_armor = s->magic_armor, e->dodge = s->dodge;
+ e->gold = s->gold, e->cost = s->cost, e->min_dmg = s->min_dmg, e->max_dmg = s->max_dmg;
+ e->speed = e->base_speed = s->speed;
+ e->margin = s->speed + 0.1f;
+ e->flying = (uint8_t)s->flying, e->boss = (uint8_t)s->boss;
+ e->charge = s->charge;
+ e->reload = (int16_t)(s->reload - s->charge);
+ e->dead_time = s->dead_time;
+ e->soldier = -1;
+ /* the specials' first timers */
+ if (type == EN_SPIDER) e->sp_t2 = (int16_t)rnd_round(S_enemies_spider_eggsCooldownTimeMin, S_enemies_spider_eggsCooldownTimeMax);
+ if (type == EN_SHADOWARCHER || type == EN_TROLLAXETHROWER)
+ e->sp_n = (int16_t)((type == EN_SHADOWARCHER ? S_enemies_shadowArcher_arrowRange : S_enemies_trollAxeThrower_axeRange) +
+ rnd_round(-70, 30));
+ facing(e);
+ return i;
+}
+
+/* ------------------------------------------------------------------ damage */
+/* getArmorDamage (the game subtracts this Number from an int: the result is cut to an int) */
+static float armor_loss(const Enemy *e, int type, int dmg, int pierce) {
+ int a = e->armor;
+ if (pierce) {
+ a -= pierce;
+ if (a < 0) a = 0;
+ }
+ float d = (float)dmg;
+ switch (type) {
+ case ARM_P: return d - (float)a * d / 100.0f;
+ case ARM_M: return d - (float)e->magic_armor * d / 100.0f;
+ case ARM_E: return d - (float)a / 2.0f * d / 100.0f;
+ default: return d;
+ }
+}
+
+static void dead_status(Enemy *e) {
+ e->active = 0, e->dead = 1;
+ battle_cash(e->gold);
+ B.kills++;
+ if (e->soldier >= 0) enemy_unblock(e);
+}
+
+void enemy_kill(Enemy *e, int how) {
+ if (e->dead) return;
+ dead_status(e);
+ if (how == 1) { /* blown up (EnemyExplode*) */
+ fx_add(e->flying ? AN_FX_EXPLODEAIR : ST(e)->size == SZ_BIG ? AN_FX_EXPLODEBIG : AN_FX_EXPLODENORMAL, e->x, e->y, false, false);
+ e->alive = 0;
+ } else if (how == 2) { /* desintegrated by the arcane death ray */
+ fx_add(e->flying ? AN_FX_DESINTEGRATEAIR : ST(e)->size == SZ_BIG ? AN_FX_DESINTEGRATEBIG : AN_FX_DESINTEGRATENORMAL,
+ e->x, e->y, false, false);
+ e->alive = 0;
+ } else {
+ fx_add(ST(e)->blood == 1 ? AN_B_BLOODGREEN : ST(e)->blood == 2 ? -1 : AN_B_BLOOD, e->x, e->y + 1, false, true);
+ }
+}
+
+void enemy_damage(Enemy *e, int dmg, int type, int pierce) {
+ if (e->dead) return;
+ if (e->sp_state == 9 && type != 99) { /* a demon lord's shield takes the hit */
+ if (--e->sp_n <= 0) e->sp_state = 0;
+ return;
+ }
+ float loss = type == ARM_I ? (float)dmg : armor_loss(e, type, dmg, pierce);
+ e->health = (int32_t)((float)e->health - loss);
+ if (e->type == EN_ROCKETEER && !e->sp_state && e->health > 0) { /* DebuffRocketeer: a rush at its first hit */
+ e->sp_state = 1;
+ if (!e->net_t && !e->slow_t) {
+ e->sp_t = S_enemies_rocketeer_fastSpeedDuration;
+ e->speed = S_enemies_rocketeer_fastSpeed, e->margin = e->speed + 0.1f;
+ e->dir = 0;
+ facing(e);
+ }
+ }
+ if (e->health <= 0) {
+ e->health = 0;
+ enemy_kill(e, 0);
+ }
+}
+
+void enemy_armor_down(Enemy *e, int v) {
+ if (e->armor == 0) return;
+ e->armor = (int16_t)(e->armor - v);
+ if (e->armor < 0) e->armor = 0;
+}
+
+bool enemy_dodge(Enemy *e) { return e->dodge && rnd() * 100.0f <= (float)e->dodge; }
+
+/* ------------------------------------------------------------------ soldiers */
+void enemy_block(Enemy *e, int soldier) {
+ e->soldier = (int8_t)soldier, e->blocked = 1;
+ play(e, ANIM(e->type, A_IDLE));
+}
+
+void enemy_unblock(Enemy *e) { /* §_-Ef§ */
+ e->blocked = 0, e->fighting = 0, e->charging = 0, e->soldier = -1;
+ e->dir = 0;
+ if (!e->dead) facing(e);
+}
+
+void enemy_start_fighting(Enemy *e) {
+ e->fighting = 1, e->dir = 0;
+ e->y += 0.1f;
+ play(e, ANIM(e->type, A_FIGHT));
+ e->charging = 1;
+}
+
+int enemy_fighter_position(Enemy *e) {
+ if (e->fpos[0] == 0) return e->fpos[0]++, 0;
+ if (e->fpos[1] == 0) return e->fpos[1]++, 1;
+ if (rnd() >= 0.5f) return e->fpos[0]++, 0;
+ return e->fpos[1]++, 1;
+}
+void enemy_free_position(Enemy *e, int pos) {
+ if (pos >= 0 && pos < 2 && e->fpos[pos]) e->fpos[pos]--;
+}
+
+static void attack(Enemy *e) {
+ Soldier *so = SO(e->soldier);
+ if (!so) return;
+ int dmg = rnd_dmg(e->min_dmg, e->max_dmg);
+ if (enemy_area_attack(e)) { /* the big ones hit everyone around (yetis, lava) */
+ int n = 0;
+ for (int i = 0; i < MAX_SOLDIERS && n < 10; i++) {
+ Soldier *o = &B.so[i];
+ if (o->alive && o->active && ellipse_contains(e->x, e->y, 70, 49, o->x, o->y)) soldier_damage(o, dmg, false), n++;
+ }
+ return;
+ }
+ soldier_damage(so, dmg, false);
+}
+
+/* ------------------------------------------------------------------ the road */
+static bool reached_node(Enemy *e) { /* §_-M9§: true when it left the battlefield */
+ int len = path_len(e->path, e->lane);
+ if (e->node == 10) {
+ e->active = 1;
+ return false;
+ }
+ if (e->node + 11 == len) {
+ e->active = 0;
+ return false;
+ }
+ if (e->node + 7 < len) return false;
+ e->active = 0;
+ battle_lose_lives(e->cost);
+ battle_cash(e->gold);
+ e->alive = 0;
+ if (e->soldier >= 0) {
+ Soldier *so = SO(e->soldier);
+ if (so) so->enemy = -1;
+ }
+ return true;
+}
+
+static void move(Enemy *e) {
+ if (e->blocked) {
+ e->xs = e->ys = 0;
+ return;
+ }
+ Pt n = enemy_road(e, 1);
+ float a = atan2f(n.y - e->y, n.x - e->x);
+ e->ys = sinf(a) * e->speed, e->xs = cosf(a) * e->speed;
+ e->x += e->xs, e->y += e->ys;
+ n = enemy_road(e, 1);
+ float dx = n.x - e->x, dy = n.y - e->y;
+ if (sqrtf(dx * dx + dy * dy) < e->margin) {
+ e->node++;
+ if (reached_node(e)) return;
+ facing(e);
+ }
+}
+
+/* ------------------------------------------------------------------ debuffs (DebuffPoison, Curse, Slow, Net) */
+static void debuffs(Enemy *e) {
+ /* DebuffPoison: its damage each second (true damage) while it lasts */
+ if (e->poison_t > 0) {
+ e->poison_t--;
+ if (e->poison_tick < FPS) e->poison_tick++;
+ else {
+ enemy_damage(e, S_archers_ranger_poisonDamage * e->poison_lvl, ARM_I, 0);
+ e->poison_tick = 0;
+ if (e->dead) return;
+ }
+ }
+ /* DebuffCurse: half its armour, 10 a second */
+ if (e->curse_t > 0) {
+ if (e->curse_tick < FPS) e->curse_tick++;
+ else {
+ enemy_damage(e, S_mages_sorcerer_curseDamage, ARM_I, 0);
+ e->curse_tick = 0;
+ if (e->dead) return;
+ }
+ if (--e->curse_t == 0) e->armor = (int16_t)(e->armor + e->curse_amt), e->curse_amt = 0;
+ }
+ if (e->slow_t > 0 && --e->slow_t == 0) e->speed = e->slow_speed, e->margin = e->speed + 0.1f;
+ if (e->net_t > 0 && --e->net_t == 0) e->speed = e->slow_speed, e->margin = e->speed + 0.1f;
+ if (e->type == EN_ROCKETEER && e->sp_t > 0 && --e->sp_t == 0) {
+ e->speed = e->base_speed, e->margin = e->speed + 0.1f;
+ e->dir = 0;
+ facing(e);
+ }
+}
+
+/* ------------------------------------------------------------------ the specials */
+static int count_alive(int type) {
+ int n = 0;
+ for (int i = 0; i < MAX_ENEMIES; i++)
+ if (B.en[i].alive && !B.en[i].dead && B.en[i].type == type) n++;
+ return n;
+}
+
+/* a soldier for a ranged attack: in range, not too close (§_-F9§, §_-9s§) */
+static int ranged_target(Enemy *e, int range, int min_range) {
+ for (int i = 0; i < MAX_SOLDIERS; i++) {
+ Soldier *so = &B.so[i];
+ if (!so->alive || !so->active) continue;
+ if (!ellipse_contains(e->x, e->y, (float)range, range * RANGE_RATIO, so->x, so->y)) continue;
+ float dx = so->x - e->x, dy = so->y - e->y;
+ if (sqrtf(dx * dx + dy * dy) > (float)min_range) return i;
+ }
+ return -1;
+}
+
+/* the shadow archer's arrows, the axe thrower's axes, the necromancer's bolts: stop, aim, throw */
+static bool ranged(Enemy *e, int cooldown, int min_range, int charge_len, int fire_at, int kind, int an) {
+ if (e->sp_state != 2) {
+ if (e->blocked) {
+ e->held = 0;
+ return false;
+ }
+ if (e->sp_t < cooldown) {
+ e->sp_t++;
+ return e->held;
+ }
+ int t = ranged_target(e, e->sp_n, min_range);
+ if (t < 0) {
+ if (e->held) {
+ e->held = 0, e->dir = 0;
+ facing(e);
+ }
+ return false;
+ }
+ e->left = B.so[t].x < e->x;
+ e->sp_state = 2, e->held = 1, e->sp_t2 = 0;
+ e->sp_n2 = (int16_t)t;
+ play(e, an);
+ return true;
+ }
+ if (e->sp_t2 < charge_len) {
+ e->sp_t2++;
+ if (e->sp_t2 == fire_at) {
+ Soldier *so = SO(e->sp_n2);
+ if (!so || !so->active) {
+ int t = ranged_target(e, e->sp_n, min_range);
+ so = t >= 0 ? &B.so[t] : 0;
+ }
+ Bullet *b = bullet_new(kind);
+ if (b) {
+ b->x = b->x0 = e->x + (e->left ? -4 : 4), b->y = b->y0 = e->y - 12.5f;
+ b->target = so ? (int8_t)(so - B.so) : -1;
+ b->tx = so ? so->x : e->x, b->ty = so ? so->y - 7 : e->y;
+ b->t1 = 17;
+ b->xs = (b->tx - b->x0) / b->t1;
+ b->ys = (b->ty - b->y0 - 1.0f * b->t1 * (b->t1 / 2.0f)) / b->t1;
+ b->g = 1;
+ if (kind == BU_ARROW_ENEMY) b->min_dmg = S_enemies_shadowArcher_arrowMinDamage, b->max_dmg = S_enemies_shadowArcher_arrowMaxDamage;
+ else if (kind == BU_AXE_ENEMY) b->min_dmg = S_enemies_trollAxeThrower_axeMinDamage, b->max_dmg = S_enemies_trollAxeThrower_axeMaxDamage;
+ else b->min_dmg = S_enemies_necromancer_spellMinDamage, b->max_dmg = S_enemies_necromancer_spellMaxDamage;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0;
+ return true;
+}
+
+static void heal(Enemy *e, int v) {
+ e->health += v;
+ if (e->health > e->init_health) e->health = e->init_health;
+}
+
+static bool special_power(Enemy *e) {
+ switch (e->type) {
+ case EN_SHAMAN: /* heals 3 wounded around it every 8 s */
+ if (e->sp_state != 1) {
+ if (e->sp_t < S_enemies_shaman_healCoolDown) {
+ e->sp_t++;
+ return false;
+ }
+ bool any = false;
+ for (int i = 0; i < MAX_ENEMIES && !any; i++) {
+ Enemy *o = &B.en[i];
+ any = o->alive && o->active && o->health < o->init_health &&
+ ellipse_contains(e->x, e->y, S_enemies_shaman_healRange, S_enemies_shaman_healRange * RANGE_RATIO, o->x, o->y);
+ }
+ if (!any) return false;
+ e->sp_state = 1, e->sp_t2 = 0;
+ play(e, AN_E_SHAMAN_HEALING);
+ return true;
+ }
+ if (e->sp_t2 < 28) {
+ if (++e->sp_t2 == 14) {
+ int n = 0;
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *o = &B.en[i];
+ if (o->alive && o->active && o->health < o->init_health &&
+ ellipse_contains(e->x, e->y, S_enemies_shaman_healRange, S_enemies_shaman_healRange * RANGE_RATIO, o->x, o->y)) {
+ heal(o, S_enemies_shaman_healPoints);
+ if (++n == S_enemies_shaman_healMaxEnemies) break;
+ }
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->dir = 0;
+ if (!e->blocked) facing(e);
+ return false;
+ case EN_SPIDER: /* lays up to 3 eggs, each hatching 3 spiderlings */
+ if (e->sp_n >= S_enemies_spider_eggsMax) return false;
+ if (e->sp_t < e->sp_t2) {
+ e->sp_t++;
+ return false;
+ }
+ if (e->blocked) return false;
+ egg_lay(e);
+ e->sp_t = 0, e->sp_n++;
+ return false;
+ case EN_SHADOWARCHER:
+ return ranged(e, S_enemies_shadowArcher_arrowCoolDown, S_enemies_shadowArcher_arrowMinRange, 12, 7, BU_ARROW_ENEMY,
+ AN_E_SHADOWARCHER_ARROW);
+ case EN_TROLLAXETHROWER:
+ return ranged(e, S_enemies_trollAxeThrower_axeCoolDown, S_enemies_trollAxeThrower_axeMinRange, 15, 8, BU_AXE_ENEMY,
+ AN_E_TROLLAXETHROWER_AXE);
+ case EN_TROLLCHIEFTAIN: /* rage: 3 trolls around it healed, stronger, faster, armoured for 6 s */
+ if (e->sp_state != 1) {
+ if (e->sp_t < S_enemies_trollChieftain_rageCoolDown) {
+ e->sp_t++;
+ return false;
+ }
+ e->sp_state = 1, e->sp_t2 = 0;
+ play(e, AN_E_TROLLCHIEFTAIN_RAGE);
+ return true;
+ }
+ if (e->sp_t2 < 49) {
+ if (++e->sp_t2 == 25) {
+ int n = 0;
+ for (int i = 0; i < MAX_ENEMIES && n < S_enemies_trollChieftain_rageMaxEnemies; i++) {
+ Enemy *o = &B.en[i];
+ if (!o->alive || !o->active || o == e || o->rage_t) continue;
+ if (o->type != EN_TROLL && o->type != EN_TROLLAXETHROWER && o->type != EN_TROLLCHIEFTAIN) continue;
+ if (!ellipse_contains(e->x, e->y, S_enemies_trollChieftain_rageRange, S_enemies_trollChieftain_rageRange * RANGE_RATIO, o->x, o->y)) continue;
+ heal(o, S_enemies_trollChieftain_rageHealPoints);
+ o->rage_t = S_enemies_trollChieftain_rageDurationTime;
+ o->min_dmg = (int16_t)(o->min_dmg + S_enemies_trollChieftain_rageAddedMinDamage);
+ o->max_dmg = (int16_t)(o->max_dmg + S_enemies_trollChieftain_rageAddedMaxDamage);
+ o->speed += S_enemies_trollChieftain_rageAddedSpeed, o->margin = o->speed + 0.1f;
+ o->base_speed += S_enemies_trollChieftain_rageAddedSpeed;
+ o->armor = (int16_t)(o->armor + S_enemies_trollChieftain_rageAddedArmor);
+ n++;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->dir = 0;
+ if (!e->blocked) facing(e);
+ return false;
+ case EN_DEMONMAGE: /* shields 4 demons around it: they shrug off 4 hits */
+ if (e->sp_state != 1) {
+ if (e->sp_t < S_enemies_demonMage_shieldCoolDown) {
+ e->sp_t++;
+ return false;
+ }
+ bool any = false;
+ for (int i = 0; i < MAX_ENEMIES && !any; i++) {
+ Enemy *o = &B.en[i];
+ any = o->alive && o->active && (o->type == EN_DEMON || o->type == EN_DEMONWOLF) && o->sp_state != 9 &&
+ ellipse_contains(e->x, e->y, S_enemies_demonMage_shieldRange, S_enemies_demonMage_shieldRange * RANGE_RATIO, o->x, o->y);
+ }
+ if (!any) return false;
+ e->sp_state = 1, e->sp_t2 = 0;
+ play(e, AN_E_DEMONMAGE_SHIELD);
+ return true;
+ }
+ if (e->sp_t2 < 24) {
+ if (++e->sp_t2 == 15) {
+ int n = 0;
+ for (int i = 0; i < MAX_ENEMIES && n < S_enemies_demonMage_shieldMaxEnemies; i++) {
+ Enemy *o = &B.en[i];
+ if (o->alive && o->active && (o->type == EN_DEMON || o->type == EN_DEMONWOLF) && o->sp_state != 9 &&
+ ellipse_contains(e->x, e->y, S_enemies_demonMage_shieldRange, S_enemies_demonMage_shieldRange * RANGE_RATIO, o->x, o->y))
+ o->sp_state = 9, o->sp_n = S_enemies_demonMage_shieldIgnoreHits, n++;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->charge_t = 0, e->dir = 0;
+ if (!e->blocked) facing(e);
+ return false;
+ case EN_NECROMANCER: { /* raises skeletons, and throws bolts at soldiers */
+ e->sp_t++, e->rage_t++;
+ if (e->sp_state != 2) {
+ if (e->blocked) e->sp_t = 0;
+ else if (e->sp_state == 3 || (e->sp_t >= S_enemies_necromancer_summonCoolDown && skeletons() < S_enemies_necromancer_summonMaxSkeletons)) {
+ if (e->sp_state != 3) {
+ e->sp_state = 3, e->sp_t2 = 0, e->sp_n2 = 0, e->thorn_tick = 0;
+ play(e, AN_E_NECROMANCER_SUMMON);
+ return true;
+ }
+ if (e->sp_t2 < 47) {
+ e->sp_t2++;
+ if (e->sp_t2 > 12 && e->sp_n2 <= S_enemies_necromancer_summonMaxEnemies) {
+ if (e->thorn_tick < 4) e->thorn_tick++;
+ else if (skeletons() < S_enemies_necromancer_summonMaxSkeletons) {
+ summon_skeleton(e, e->sp_n2);
+ e->sp_n2++, e->thorn_tick = 0;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->dir = 0;
+ if (!e->blocked) facing(e);
+ return false;
+ }
+ }
+ /* the bolt: as the archers, on its own cooldown */
+ int16_t keep = e->sp_t;
+ e->sp_t = e->rage_t;
+ bool r = ranged(e, S_enemies_necromancer_spellCoolDown, S_enemies_necromancer_spellMinRange, 23, 13, BU_BOLT_NECRO,
+ AN_E_NECROMANCER_SPELL);
+ e->rage_t = e->sp_t, e->sp_t = keep;
+ return r;
+ }
+ default:
+ return boss_power(e);
+ }
+}
+
+/* EnemyCommon.specialMove: respawning, arcane teleports, the rangers' thorns, regeneration */
+static bool special_move(Enemy *e) {
+ if (e->respawn_t > 0) { /* rising (skeletons) */
+ if (--e->respawn_t == 0) {
+ e->active = 1, e->dir = 0;
+ facing(e);
+ }
+ return true;
+ }
+ if (e->teleporting) {
+ if (++e->teleport_t >= 9) {
+ if (e->teleporting == 1) {
+ Pt p = enemy_road(e, 0);
+ e->x = p.x, e->y = p.y;
+ e->teleporting = 2, e->teleport_t = 0;
+ fx_add(AN_FX_TELEPORT, e->x, e->y, false, false);
+ return true;
+ }
+ e->teleporting = 0, e->active = 1, e->fighting = 0, e->blocked = 0, e->thorned = 0, e->held = 0, e->dir = 0;
+ facing(e);
+ }
+ return true;
+ }
+ if (e->thorned) {
+ if (e->thorned == 1) {
+ if (e->thorn_t < 18) {
+ e->thorn_t++;
+ return true;
+ }
+ e->thorned = 2, e->thorn_t = 0, e->thorn_tick = 0;
+ }
+ if (e->thorn_t < e->thorn_len) {
+ e->thorn_t++;
+ if (++e->thorn_tick == e->thorn_every) {
+ enemy_damage(e, e->thorn_dmg, ARM_P, 0);
+ e->thorn_tick = 0;
+ }
+ return true;
+ }
+ e->thorned = 0, e->held = 0;
+ if (!e->dead) {
+ e->dir = 0;
+ facing(e);
+ }
+ return false;
+ }
+ int heal_pts = 0, heal_time = 0;
+ switch (e->type) {
+ case EN_TROLL: heal_pts = S_enemies_troll_regenerateHealPoints, heal_time = S_enemies_troll_regenerateTime; break;
+ case EN_TROLLCHIEFTAIN: heal_pts = S_enemies_trollChieftain_regenerateHealPoints, heal_time = S_enemies_trollChieftain_regenerateTime; break;
+ case EN_TROLLAXETHROWER: heal_pts = S_enemies_trollAxeThrower_regenerateHealPoints, heal_time = S_enemies_trollAxeThrower_regenerateTime; break;
+ }
+ if (heal_pts) {
+ if (e->regen_t < heal_time) e->regen_t++;
+ else heal(e, heal_pts), e->regen_t = 0;
+ }
+ return false;
+}
+
+/* ------------------------------------------------------------------ a frame */
+void enemy_step(Enemy *e) {
+ e->anim_t++;
+ if (e->dead) {
+ if (e->dead_t == 0) play(e, ANIM(e->type, A_DEAD));
+ e->dead_t++;
+ if ((e->type == EN_DEMON || e->type == EN_DEMONWOLF || e->type == EN_DEMONMAGE) && e->dead_t == 5) demon_explode(e);
+ if (e->dead_t >= e->dead_time) e->alive = 0;
+ return;
+ }
+ if (special_move(e)) return;
+ if (e->dead) return;
+ debuffs(e);
+ if (e->dead || !e->alive) return;
+ if (e->rage_t > 0 && e->type != EN_NECROMANCER && --e->rage_t == 0) { /* the chieftain's rage ends */
+ e->min_dmg = (int16_t)(e->min_dmg - S_enemies_trollChieftain_rageAddedMinDamage);
+ e->max_dmg = (int16_t)(e->max_dmg - S_enemies_trollChieftain_rageAddedMaxDamage);
+ e->speed -= S_enemies_trollChieftain_rageAddedSpeed, e->base_speed -= S_enemies_trollChieftain_rageAddedSpeed;
+ e->margin = e->speed + 0.1f;
+ e->armor = (int16_t)(e->armor - S_enemies_trollChieftain_rageAddedArmor);
+ if (e->armor < 0) e->armor = 0;
+ }
+ if (e->active && !e->charging && special_power(e)) return;
+ if (!e->alive || e->dead) return;
+ if (e->blocked) {
+ Soldier *so = SO(e->soldier);
+ if (!so || !so->active || !so->fighting) enemy_unblock(e);
+ }
+ if (e->fighting) {
+ Soldier *so = SO(e->soldier);
+ if (!so || !so->active) enemy_unblock(e);
+ else if (e->charging) {
+ if (++e->charge_t != e->charge) return;
+ e->charge_t = 0;
+ e->charging = 0;
+ attack(e);
+ play(e, ANIM(e->type, A_IDLE));
+ so = SO(e->soldier);
+ if (!so || so->dead) enemy_unblock(e);
+ } else if (++e->reload_t == e->reload) {
+ play(e, ANIM(e->type, A_FIGHT));
+ e->charging = 1;
+ e->reload_t = 0;
+ }
+ } else if (!e->held)
+ move(e);
+}
diff --git a/games/kingdomrush/src/enemy2.c b/games/kingdomrush/src/enemy2.c
new file mode 100644
index 00000000..21915a10
--- /dev/null
+++ b/games/kingdomrush/src/enemy2.c
@@ -0,0 +1,173 @@
+/* The enemies' helpers: eggs, skeletons, demons' last blast, the big ones' blows, the bosses. */
+#include <math.h>
+#include <string.h>
+#include "anim.h"
+#include "kr.h"
+#include "settings.h"
+
+int enemy_health_pct = 100;
+
+bool enemy_area_attack(const Enemy *e) {
+ return e->type == EN_YETI || e->type == EN_LAVAELEMENTAL || e->type == EN_JUGGERNAUT || e->type == EN_YETIBOSS ||
+ (e->type == EN_VEZNAN && e->froze);
+}
+
+/* ------------------------------------------------------------------ spider eggs */
+void egg_lay(Enemy *e) {
+ for (int i = 0; i < (int)(sizeof B.egg / sizeof B.egg[0]); i++)
+ if (!B.egg[i].on) {
+ B.egg[i].on = 1, B.egg[i].path = e->path, B.egg[i].node = e->node, B.egg[i].t = 0, B.egg[i].n = 0;
+ B.egg[i].x = e->x, B.egg[i].y = e->y;
+ return;
+ }
+}
+
+void eggs_step(void) {
+ for (int i = 0; i < (int)(sizeof B.egg / sizeof B.egg[0]); i++) {
+ if (!B.egg[i].on) continue;
+ B.egg[i].t++;
+ /* 85 frames, then a spiderling every 6, then the shell stays a while; the Juggernaut's: golem heads */
+ bool golem = B.egg[i].on == 2;
+ int wait = golem ? 20 : 85, count = golem ? S_enemies_juggernaut_golemHeads : S_enemies_spider_eggsSpiders;
+ if (B.egg[i].t > wait && B.egg[i].n < count && (B.egg[i].t - wait) % 6 == 0) {
+ int lane = B.egg[i].n % B.nlanes[B.egg[i].path];
+ int len = path_len(B.egg[i].path, lane), node = B.egg[i].node + 2;
+ if (node > len - 12) node = len - 12;
+ int j = enemy_spawn(golem ? EN_GOLEMHEAD : EN_SPIDERTINY, B.egg[i].path, lane, node);
+ if (j >= 0) {
+ B.en[j].x = B.egg[i].x, B.en[j].y = B.egg[i].y;
+ B.en[j].active = 1;
+ }
+ B.egg[i].n++;
+ }
+ if (B.egg[i].t > 85 + 120) B.egg[i].on = 0;
+ }
+}
+
+/* ------------------------------------------------------------------ skeletons */
+int skeletons(void) { return B.skeletons; }
+
+void summon_skeleton(Enemy *e, int k) {
+ static const int8_t lanes[8] = {1, 2, 0, 1, 2, 0, 1, 2};
+ int node = e->node;
+ if (k >= 2 && k <= 4) node += rnd_round(3, 7);
+ if (k >= 5) node -= rnd_round(3, 7);
+ int lane = lanes[k & 7] % B.nlanes[e->path];
+ int len = path_len(e->path, lane);
+ if (node < 11) node = 11;
+ if (node > len - 12) node = len - 12;
+ int j = enemy_spawn(EN_SKELETON, e->path, lane, node);
+ if (j < 0) return;
+ Enemy *s = &B.en[j];
+ s->respawn_t = 33, s->active = 0;
+ s->anim = AN_E_SKELETON_RESPAWNING, s->anim_t = 0;
+ B.skeletons++;
+}
+
+/* ------------------------------------------------------------------ demons: their last blast */
+void demon_explode(Enemy *e) {
+ int lo, hi, r;
+ if (e->type == EN_DEMONWOLF) lo = S_enemies_demonWolf_exploteMinDamage, hi = S_enemies_demonWolf_exploteMaxDamage, r = S_enemies_demonWolf_exploteRange;
+ else if (e->type == EN_DEMONMAGE) lo = S_enemies_demonMage_exploteMinDamage, hi = S_enemies_demonMage_exploteMaxDamage, r = S_enemies_demonMage_exploteRange;
+ else lo = S_enemies_demon_exploteMinDamage, hi = S_enemies_demon_exploteMaxDamage, r = S_enemies_demon_exploteRange;
+ fx_add(AN_B_DEMONFIRE, e->x, e->y, false, false);
+ for (int i = 0; i < MAX_SOLDIERS; i++) {
+ Soldier *so = &B.so[i];
+ if (so->alive && so->active && ellipse_contains(e->x, e->y, (float)r, r * RANGE_RATIO, so->x, so->y))
+ soldier_damage(so, rnd_dmg(lo, hi), false);
+ }
+}
+
+/* ------------------------------------------------------------------ the bosses */
+static void boss_anim(Enemy *e, int an) { e->anim = (uint16_t)an, e->anim_t = 0; }
+
+/* the Juggernaut: golem heads in an egg every 4 s, a missile at the soldiers every 9 s */
+static bool juggernaut(Enemy *e) {
+ e->sp_t++, e->sp_t2++;
+ if (e->sp_state == 1) { /* launching */
+ if (e->sp_n < 49) {
+ if (++e->sp_n == 24) {
+ /* the egg lands a little down the road and hatches golem heads */
+ Pt p = enemy_road(e, 40 + rnd_round(0, 30));
+ for (int k = 0; k < (int)(sizeof B.egg / sizeof B.egg[0]); k++)
+ if (!B.egg[k].on) {
+ B.egg[k].on = 2, B.egg[k].path = e->path, B.egg[k].node = (int16_t)(e->node + 40), B.egg[k].t = 0, B.egg[k].n = 0;
+ B.egg[k].x = p.x, B.egg[k].y = p.y;
+ break;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->dir = 0;
+ return false;
+ }
+ if (e->sp_t >= 120 && !e->blocked) {
+ e->sp_state = 1, e->sp_n = 0;
+ boss_anim(e, AN_E_JUGGERNAUT_MISSILE);
+ return true;
+ }
+ if (e->sp_t2 >= S_enemies_juggernaut_missileCoolDown) {
+ /* a missile at a soldier out of reach */
+ for (int i = 0; i < MAX_SOLDIERS; i++) {
+ Soldier *so = &B.so[i];
+ if (!so->alive || !so->active) continue;
+ float dx = so->x - e->x, dy = so->y - e->y;
+ if (sqrtf(dx * dx + dy * dy) < S_enemies_juggernaut_missileMinRange) continue;
+ Bullet *b = bullet_new(BU_MISSILE_ENEMY);
+ if (b) {
+ b->x = b->x0 = e->x, b->y = b->y0 = e->y - 60, b->target = (int8_t)i, b->tx = so->x, b->ty = so->y;
+ b->acc = 2, b->acc_max = 12;
+ b->min_dmg = S_enemies_juggernaut_missileMinDamage, b->max_dmg = S_enemies_juggernaut_missileMaxDamage;
+ }
+ e->sp_t2 = 0;
+ break;
+ }
+ }
+ return false;
+}
+
+/* J.T., the yeti king: freezes up to 4 towers around it every 10 s, calls winter wolves */
+static bool yeti_boss(Enemy *e) {
+ e->sp_t++, e->sp_t2++;
+ if (e->sp_state == 1) { /* the breath */
+ if (e->sp_n < 30) {
+ if (++e->sp_n == 15) {
+ int n = 0;
+ for (int s = 0; s < B.nspots && n < S_enemies_yetiBoss_frozeMaxTowers; s++) {
+ Spot *t = &B.spot[s];
+ if (t->kind == TW_NONE || t->kind == 0xFF || t->disabled || t->building) continue;
+ if (!ellipse_contains(e->x, e->y, S_enemies_yetiBoss_frozeRangeWidth, S_enemies_yetiBoss_frozeRangeWidth * RANGE_RATIO, t->x, t->y)) continue;
+ t->disabled = 1, t->ice = 1, t->ice_t = 0, t->ice_hits = 0; /* IceBlock: three hits break it */
+ n++;
+ }
+ }
+ return true;
+ }
+ e->sp_state = 0, e->sp_t = 0, e->dir = 0;
+ return false;
+ }
+ if (e->sp_t >= S_enemies_yetiBoss_frozeReloadTime && !e->blocked) {
+ e->sp_state = 1, e->sp_n = 0;
+ boss_anim(e, AN_E_YETIBOSS_BREATH);
+ return true;
+ }
+ if (e->sp_t2 >= S_enemies_yetiBoss_wolfSpawnCooldownTime) {
+ for (int k = 0; k < S_enemies_yetiBoss_maxWolf; k++) {
+ int j = enemy_spawn(EN_WHITEWOLF, e->path, k % B.nlanes[e->path], 0);
+ (void)j;
+ }
+ e->sp_t2 = 0;
+ }
+ return false;
+}
+
+bool veznan_power(Enemy *e) { (void)e; return false; }
+
+bool boss_power(Enemy *e) {
+ switch (e->type) {
+ case EN_JUGGERNAUT: return juggernaut(e);
+ case EN_YETIBOSS: return yeti_boss(e);
+ case EN_VEZNAN: return veznan_power(e);
+ default: return false;
+ }
+}
diff --git a/games/kingdomrush/src/game.c b/games/kingdomrush/src/game.c
new file mode 100644
index 00000000..90d22060
--- /dev/null
+++ b/games/kingdomrush/src/game.c
@@ -0,0 +1,58 @@
+/* The screens: what each key does, a step at 30 a second (the game's frame rate). */
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "kr.h"
+
+Game g;
+static uint32_t last_keys, repeat_key;
+static int repeat_t;
+
+void game_init(void) {
+ memset(&g, 0, sizeof g);
+ g.running = true;
+ load_progress();
+ g.screen = SCR_TITLE;
+}
+
+void game_quit(void) {
+ save_progress();
+ g.running = false;
+}
+
+/* a key pressed this step; the arrows repeat while held (after 8 steps, then every 3) */
+bool play_key(uint32_t k) {
+ if (g.pressed & k) return true;
+ return (k & (K_LEFT | K_RIGHT | K_UP | K_DOWN)) && repeat_key == k && repeat_t >= 8 && (repeat_t - 8) % 3 == 0;
+}
+
+void game_step(uint32_t keys) {
+ g.ticks++;
+ g.keys = keys;
+ g.pressed = keys & ~last_keys;
+ last_keys = keys;
+ uint32_t arrows = keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN);
+ if (arrows && arrows == repeat_key) repeat_t++;
+ else repeat_key = arrows, repeat_t = 0;
+ if (g.pressed & K_HOME) {
+ game_quit();
+ return;
+ }
+ switch (g.screen) {
+ case SCR_TITLE: title_step(); break;
+ case SCR_MAP: map_step(); break;
+ case SCR_UPGRADES: upgrades_step(); break;
+ case SCR_BATTLE: play_step(); break;
+ case SCR_HELP: help_step(); break;
+ }
+}
+
+void game_draw(void) {
+ switch (g.screen) {
+ case SCR_TITLE: title_draw(); break;
+ case SCR_MAP: map_draw(); break;
+ case SCR_UPGRADES: upgrades_draw(); break;
+ case SCR_BATTLE: play_draw(); break;
+ case SCR_HELP: help_draw(); break;
+ }
+}
diff --git a/games/kingdomrush/src/game.h b/games/kingdomrush/src/game.h
new file mode 100644
index 00000000..a0cbf97a
--- /dev/null
+++ b/games/kingdomrush/src/game.h
@@ -0,0 +1,57 @@
+/* Kingdom Rush: the screens and the save. */
+#ifndef KR_GAME_H
+#define KR_GAME_H
+#include <stdbool.h>
+#include <stdint.h>
+
+enum { SCR_TITLE, SCR_MAP, SCR_UPGRADES, SCR_BATTLE, SCR_HELP };
+
+typedef struct {
+ uint8_t camp[12]; /* the campaign's stars (0: not won) */
+ uint8_t heroic[12], iron[12];
+ uint8_t ups[6]; /* the upgrades bought (each line 0 to 5) */
+ uint8_t difficulty; /* 0 casual, 1 normal, 2 veteran */
+ uint8_t guide_seen;
+ uint8_t seen_note[8]; /* notifications already shown, a bit each */
+} Progress;
+
+typedef struct {
+ bool running;
+ uint8_t screen;
+ uint32_t keys, pressed; /* held now; pressed this step */
+ uint32_t ticks;
+ Progress p;
+ uint8_t map_sel; /* the map's selected stage */
+} Game;
+extern Game g;
+
+void game_init(void);
+void game_step(uint32_t keys);
+void game_draw(void);
+void game_quit(void);
+
+/* stars: won, and free to spend on upgrades */
+int stars_won(void);
+int stars_free(void);
+int stars_max(void);
+
+/* save.c */
+void save_progress(void);
+void load_progress(void);
+
+/* play.c: the battle screen */
+void play_start(int level, int mode);
+void play_step(void);
+void play_draw(void);
+bool play_key(uint32_t k); /* a key pressed now (with repeats for the arrows) */
+
+/* menus.c: the title, the map, the upgrades, the help */
+void title_step(void);
+void title_draw(void);
+void map_step(void);
+void map_draw(void);
+void upgrades_step(void);
+void upgrades_draw(void);
+void help_step(void);
+void help_draw(void);
+#endif
diff --git a/games/kingdomrush/src/gfx.c b/games/kingdomrush/src/gfx.c
new file mode 100644
index 00000000..2e72870c
--- /dev/null
+++ b/games/kingdomrush/src/gfx.c
@@ -0,0 +1,265 @@
+/* Drawing (gfx.h): a band of 16 rows at a time, then pushed to the screen. */
+#include "gfx.h"
+#include "res.h"
+
+uint16_t *gfx_band;
+int gfx_y0;
+
+void gfx_set_band_memory(uint16_t *m) { gfx_band = m; }
+
+void gfx_frame(void (*draw)(void)) {
+ for (gfx_y0 = 0; gfx_y0 < SCREEN_H; gfx_y0 += BAND_H) {
+ draw();
+ plat_push(0, gfx_y0, SCREEN_W, BAND_H, gfx_band);
+ }
+ gfx_y0 = 0;
+}
+
+uint16_t gfx_mix(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);
+}
+
+/* the rectangle's part in this band: rows r0 to r1 of the band, columns x0 to x1 */
+static bool clip(int x, int y, int w, int h, int *x0, int *x1, int *r0, int *r1) {
+ *x0 = x > 0 ? x : 0, *x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ *r0 = y0 - gfx_y0, *r1 = y1 - gfx_y0;
+ return *x0 < *x1 && *r0 < *r1;
+}
+
+void gfx_fill(int x, int y, int w, int h, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++) *p = c;
+}
+
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ for (int r = r0; r < r1; r++)
+ for (uint16_t *p = gfx_band + r * SCREEN_W + x0, *e = gfx_band + r * SCREEN_W + x1; p < e; p++)
+ *p = gfx_mix(c, *p, a);
+}
+
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c) {
+ gfx_fill(x, y, w, 1, c);
+ gfx_fill(x, y + h - 1, w, 1, c);
+ gfx_fill(x, y, 1, h, c);
+ gfx_fill(x + w - 1, y, 1, h, c);
+}
+
+static inline void plot(int x, int y, uint16_t c, int a) {
+ if ((unsigned)x >= SCREEN_W || y < gfx_y0 || y >= gfx_y0 + BAND_H) return;
+ uint16_t *p = gfx_band + (y - gfx_y0) * SCREEN_W + x;
+ *p = a >= 32 ? c : gfx_mix(c, *p, a);
+}
+
+void gfx_ellipse(int cx, int cy, int rx, int ry, uint16_t c, int a) {
+ if (rx <= 0 || ry <= 0 || !gfx_rows(cy - ry, 2 * ry + 1)) return;
+ /* for each row the outline's two ends, joined to the next row's so it has no gaps */
+ int prev = -1;
+ for (int dy = -ry; dy <= ry; dy++) {
+ int y = cy + dy;
+ int64_t t = (int64_t)rx * rx * ((int64_t)ry * ry - (int64_t)dy * dy);
+ int dx = 0;
+ if (t > 0) {
+ int64_t s = (int64_t)ry * ry;
+ while ((int64_t)(dx + 1) * (dx + 1) * s <= t) dx++;
+ }
+ int from = prev < 0 ? dx : (prev < dx ? prev + 1 : dx);
+ int to = prev < 0 ? dx : (prev > dx ? prev - 1 : dx);
+ if (from > to) { int k = from; from = to; to = k; }
+ if (y >= gfx_y0 && y < gfx_y0 + BAND_H)
+ for (int k = from; k <= to; k++) {
+ plot(cx - k, y, c, a);
+ if (k) plot(cx + k, y, c, a);
+ }
+ prev = dx;
+ }
+}
+
+void gfx_ellipse_fill(int cx, int cy, int rx, int ry, uint16_t c, int a) {
+ if (rx <= 0 || ry <= 0 || !gfx_rows(cy - ry, 2 * ry + 1)) return;
+ for (int y = cy - ry; y <= cy + ry; y++) {
+ if (y < gfx_y0 || y >= gfx_y0 + BAND_H) continue;
+ int dy = y - cy;
+ int64_t t = (int64_t)rx * rx * ((int64_t)ry * ry - (int64_t)dy * dy), s = (int64_t)ry * ry;
+ int dx = 0;
+ while ((int64_t)(dx + 1) * (dx + 1) * s <= t) dx++;
+ if (a >= 32) gfx_fill(cx - dx, y, 2 * dx + 1, 1, c);
+ else gfx_blend(cx - dx, y, 2 * dx + 1, 1, c, a);
+ }
+}
+
+void gfx_line(int x0, int y0, int x1, int y1, uint16_t c) {
+ int dx = x1 > x0 ? x1 - x0 : x0 - x1, dy = y1 > y0 ? y0 - y1 : y1 - y0;
+ int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, e = dx + dy;
+ for (int n = 0; n < 2000; n++) {
+ plot(x0, y0, c, 32);
+ if (x0 == x1 && y0 == y1) break;
+ int e2 = 2 * e;
+ if (e2 >= dy) e += dy, x0 += sx;
+ if (e2 <= dx) e += dx, y0 += sy;
+ }
+}
+
+void gfx_panel(int x, int y, int w, int h, uint16_t fill, uint16_t border) {
+ gfx_fill(x + 1, y + 1, w - 2, h - 2, fill);
+ gfx_fill(x + 2, y, w - 4, 1, border);
+ gfx_fill(x + 2, y + h - 1, w - 4, 1, border);
+ gfx_fill(x, y + 2, 1, h - 4, border);
+ gfx_fill(x + w - 1, y + 2, 1, h - 4, border);
+ gfx_fill(x + 1, y + 1, 1, 1, border);
+ gfx_fill(x + w - 2, y + 1, 1, 1, border);
+ gfx_fill(x + 1, y + h - 2, 1, 1, border);
+ gfx_fill(x + w - 2, y + h - 2, 1, 1, border);
+}
+
+/* ------------------------------------------------------------------ text */
+static const uint8_t *font_at(int font) {
+ const uint8_t *s = section(SEC_FONTS);
+ return s + rd32(s + 4 + 4 * font);
+}
+
+int gfx_line_h(int font) { return font_at(font)[0]; }
+
+/* 4-bit alpha rows (the first pixel in the low half of a byte) in colour c */
+static void alpha_rows(const uint8_t *rows, int w, int h, int x, int y, uint16_t c) {
+ int x0, x1, r0, r1;
+ if (!clip(x, y, w, h, &x0, &x1, &r0, &r1)) return;
+ int stride = (w + 1) >> 1;
+ for (int r = r0; r < r1; r++) {
+ const uint8_t *src = rows + (gfx_y0 + r - y) * stride;
+ uint16_t *d = gfx_band + r * SCREEN_W;
+ for (int px = x0; px < x1; px++) {
+ int i = px - x, a = src[i >> 1] >> ((i & 1) * 4) & 15;
+ if (a) d[px] = a == 15 ? c : gfx_mix(c, d[px], a * 2 + (a >> 3));
+ }
+ }
+}
+
+int gfx_text(int font, int x, int y, const char *s, uint16_t c) {
+ const uint8_t *f = font_at(font);
+ int x0 = x;
+ bool here = y < gfx_y0 + BAND_H && y + f[0] > gfx_y0;
+ for (; *s; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ const uint8_t *g = f + 4 + 12 * (ch - 32);
+ if (here && g[1]) alpha_rows(f + rd32(g + 8), g[1], g[2], x + (int8_t)g[3], y + (int8_t)g[4], c);
+ x += g[0];
+ }
+ return x - x0;
+}
+
+int gfx_text_w(int font, const char *s) {
+ const uint8_t *f = font_at(font);
+ int w = 0;
+ for (; *s; s++) {
+ int ch = (uint8_t)*s;
+ if (ch < 32 || ch > 126) ch = '?';
+ w += f[4 + 12 * (ch - 32)];
+ }
+ return w;
+}
+
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c) { gfx_text(font, cx - gfx_text_w(font, s) / 2, y, s, c); }
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c) { gfx_text(font, rx - gfx_text_w(font, s), y, s, c); }
+void gfx_text_o(int font, int x, int y, const char *s, uint16_t c) {
+ if (!gfx_rows(y - 1, gfx_line_h(font) + 2)) return;
+ static const int8_t d[8][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}};
+ for (int k = 0; k < 8; k++) gfx_text(font, x + d[k][0], y + d[k][1], s, RGB(0x2A1A0C));
+ gfx_text(font, x, y, s, c);
+}
+void gfx_text_oc(int font, int cx, int y, const char *s, uint16_t c) { gfx_text_o(font, cx - gfx_text_w(font, s) / 2, y, s, c); }
+
+int gfx_text_box(int font, int x, int y, int w, const char *s, uint16_t c) {
+ int lh = gfx_line_h(font), yy = y;
+ char line[96];
+ while (*s) {
+ /* as many words as fit */
+ int n = 0, best = 0;
+ for (;;) {
+ int k = n;
+ while (s[k] && s[k] != ' ' && s[k] != '\n') k++;
+ if (k >= (int)sizeof line - 1) break;
+ for (int i = 0; i < k; i++) line[i] = s[i];
+ line[k] = 0;
+ if (gfx_text_w(font, line) > w && best) break;
+ best = k;
+ if (!s[k] || s[k] == '\n') break;
+ n = k + 1;
+ }
+ if (!best) best = 1;
+ for (int i = 0; i < best; i++) line[i] = s[i];
+ line[best] = 0;
+ gfx_text(font, x, yy, line, c);
+ yy += lh;
+ s += best;
+ if (*s == ' ' || *s == '\n') s++;
+ }
+ return yy - y;
+}
+
+/* ------------------------------------------------------------------ sprites */
+static const uint16_t *spal;
+
+static inline const uint8_t *frame_at(int slot) {
+ const uint8_t *f = section(SEC_FRAMES);
+ return f + rd32(f + 4 + 4 * slot);
+}
+
+void spr_box(int slot, int *w, int *h, int *ox, int *oy) {
+ const uint8_t *p = frame_at(slot);
+ *w = p[0], *h = p[1], *ox = rds16(p + 2), *oy = rds16(p + 4);
+}
+
+static void frame_draw(int slot, int x, int y, bool flip, bool tint, uint16_t tc, int ta) {
+ if (!spal) spal = (const uint16_t *)(const void *)section(SEC_SPAL);
+ const uint8_t *p = frame_at(slot);
+ int w = p[0], h = p[1];
+ int left = x - (flip ? w - 1 - rds16(p + 2) : rds16(p + 2)), top = y - rds16(p + 4);
+ if (top >= gfx_y0 + BAND_H || top + h <= gfx_y0 || left >= SCREEN_W || left + w <= 0) return;
+ p += 6;
+ for (int r = 0; r < h; r++) {
+ int n = *p++, sy = top + r;
+ if (sy < gfx_y0) { /* above the band: skip the row */
+ for (int k = 0; k < n; k++) p += 2 + (p[1] & 0x7F);
+ continue;
+ }
+ if (sy >= gfx_y0 + BAND_H) break;
+ uint16_t *d = gfx_band + (sy - gfx_y0) * SCREEN_W;
+ int cx = 0;
+ for (int k = 0; k < n; k++) {
+ cx += p[0];
+ int len = p[1] & 0x7F;
+ bool half = p[1] & 0x80;
+ const uint8_t *c = p + 2;
+ for (int i = 0; i < len; i++) {
+ int px = flip ? left + w - 1 - (cx + i) : left + cx + i;
+ if ((unsigned)px >= SCREEN_W) continue;
+ uint16_t col = spal[c[i]];
+ if (tint) col = gfx_mix(tc, col, ta);
+ d[px] = half ? (uint16_t)((((d[px] ^ col) & 0xF7DEu) >> 1) + (d[px] & col)) : col;
+ }
+ cx += len;
+ p += 2 + len;
+ }
+ }
+}
+
+void spr_frame(int slot, int x, int y, bool flip) { frame_draw(slot, x, y, flip, false, 0, 0); }
+void spr_frame_tint(int slot, int x, int y, bool flip, uint16_t c, int a) { frame_draw(slot, x, y, flip, true, c, a); }
+
+static inline const uint8_t *anim_at(int an) { return section(SEC_ANIMS) + 4 * an; }
+int anim_frames(int an) { return anim_at(an)[2]; }
+int anim_ticks(int an) { const uint8_t *a = anim_at(an); return a[2] * a[3]; }
+int anim_slot(int an, int t, bool loop) {
+ const uint8_t *a = anim_at(an);
+ int n = a[2], k = t < 0 ? 0 : t / a[3];
+ k = loop ? k % n : (k >= n ? n - 1 : k);
+ return (int)rd16(a) + k;
+}
diff --git a/games/kingdomrush/src/gfx.h b/games/kingdomrush/src/gfx.h
new file mode 100644
index 00000000..ac003d3d
--- /dev/null
+++ b/games/kingdomrush/src/gfx.h
@@ -0,0 +1,70 @@
+/* Kingdom Rush: drawing, a band of 16 rows at a time.
+ *
+ * The screen is drawn in 15 bands of 320 x 16 pixels: for each band the scene's whole drawing function runs,
+ * everything clipped to the band, then the band is pushed. So the game needs no frame buffer (it would not fit
+ * in the RAM apps get): the battlefield's terrain waits in RAM at a byte a pixel (bg_*), the sprites are read
+ * from flash as they are drawn. */
+#ifndef KR_GFX_H
+#define KR_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "plat.h"
+
+#define BAND_H 16
+#define RGB(c) (uint16_t)((((c) >> 8) & 0xF800) | (((c) >> 5) & 0x07E0) | (((c) >> 3) & 0x1F))
+#define WHITE 0xFFFF
+#define BLACK 0x0000
+
+extern uint16_t *gfx_band; /* SCREEN_W x BAND_H */
+extern int gfx_y0; /* the band's top row */
+void gfx_set_band_memory(uint16_t *m);
+/* draws the frame: draw() once for each band */
+void gfx_frame(void (*draw)(void));
+/* is any of rows y to y + h - 1 in this band? */
+static inline bool gfx_rows(int y, int h) { return y < gfx_y0 + BAND_H && y + h > gfx_y0; }
+
+uint16_t gfx_mix(uint16_t f, uint16_t b, int a); /* f over b, a from 0 (b) to 32 (f) */
+void gfx_fill(int x, int y, int w, int h, uint16_t c);
+void gfx_blend(int x, int y, int w, int h, uint16_t c, int a);
+void gfx_frame_rect(int x, int y, int w, int h, uint16_t c);
+/* an ellipse's outline (centre, half axes), a of 32 opaque */
+void gfx_ellipse(int cx, int cy, int rx, int ry, uint16_t c, int a);
+/* a filled ellipse, a of 32 */
+void gfx_ellipse_fill(int cx, int cy, int rx, int ry, uint16_t c, int a);
+void gfx_line(int x0, int y0, int x1, int y1, uint16_t c);
+/* a rounded panel: a fill and a 1-pixel border */
+void gfx_panel(int x, int y, int w, int h, uint16_t fill, uint16_t border);
+
+/* text in data.bin's fonts (FONT_*); returns the width */
+int gfx_text(int font, int x, int y, const char *s, uint16_t c);
+int gfx_text_w(int font, const char *s);
+int gfx_line_h(int font);
+void gfx_text_c(int font, int cx, int y, const char *s, uint16_t c); /* centred on cx */
+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c); /* ending at rx */
+/* with a 1-pixel dark outline, for words over pictures */
+void gfx_text_o(int font, int x, int y, const char *s, uint16_t c);
+void gfx_text_oc(int font, int cx, int y, const char *s, uint16_t c);
+/* text wrapped to width w from (x, y); returns the height */
+int gfx_text_box(int font, int x, int y, int w, const char *s, uint16_t c);
+
+/* sprites (data.bin's FRAMES and ANIMS): an animation's frame with its origin at (x, y), mirrored or not */
+void spr_frame(int slot, int x, int y, bool flip);
+/* the frame shown t ticks into an animation (held at its end, or looping) */
+int anim_slot(int an, int t, bool loop);
+int anim_ticks(int an); /* how long it plays */
+int anim_frames(int an);
+static inline void spr_anim(int an, int t, bool loop, int x, int y, bool flip) { spr_frame(anim_slot(an, t, loop), x, y, flip); }
+/* a frame's box around its origin (w, h; ox, oy: the origin from the top left) */
+void spr_box(int slot, int *w, int *h, int *ox, int *oy);
+/* tinted: the frame's shape in colour c, a of 32 */
+void spr_frame_tint(int slot, int x, int y, bool flip, uint16_t c, int a);
+
+/* pictures (pic.c) */
+void pic_draw(int id, int x, int y); /* straight from flash, decoded as the band needs */
+int pic_w(int id);
+int pic_h(int id);
+/* the terrain: the picture decoded once into RAM (w x h bytes at mem), drawn at (x, y) */
+void bg_load(int id, uint8_t *mem);
+void bg_draw(int x, int y);
+void bg_dim(bool dim); /* the terrain darkened (behind a menu) */
+#endif
diff --git a/games/kingdomrush/src/icon.png b/games/kingdomrush/src/icon.png
new file mode 100644
index 00000000..57968f8b
Binary files /dev/null and b/games/kingdomrush/src/icon.png differ
diff --git a/games/kingdomrush/src/kr.h b/games/kingdomrush/src/kr.h
new file mode 100644
index 00000000..d3461e03
--- /dev/null
+++ b/games/kingdomrush/src/kr.h
@@ -0,0 +1,300 @@
+/* Kingdom Rush: the battle's state and rules, as the Flash game (2011) runs them.
+ *
+ * Everything is in the game's own units: its 700 x 600 battlefield, a step a frame at 30 frames a second, its
+ * numbers (stats.c, from its GameSettings). Each part follows the game's class of the same name: level.c
+ * (Level, Wave, WaveSpawn), enemy.c (Enemy, EnemyCommon and each enemy), tower.c (Tower and each tower),
+ * soldier.c (Soldier and each soldier), bullet.c (Arrow, Bolt, Bomb, the rays...), power.c (the spells). */
+#ifndef KR_KR_H
+#define KR_KR_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "data.h"
+
+#define FPS 30
+#define RANGE_RATIO 0.7f
+#define MAX_ENEMIES 160
+#define MAX_SOLDIERS 80
+#define MAX_BULLETS 96
+#define MAX_FX 96
+#define MAX_SPOTS 20
+#define MAX_PATHS 6
+#define MAX_LANES 3
+#define MAX_ACTIVE_WAVES 8
+
+/* ------------------------------------------------------------------ randomness: Math.random() */
+float rnd(void); /* [0, 1) */
+void rnd_seed(uint32_t s);
+static inline int rnd_dmg(int lo, int hi) { int d = hi - lo; return lo + (d > 0 ? (int)__builtin_ceilf(rnd() * (float)d) : 0); }
+int rnd_round(int lo, int hi); /* Math.round(Math.random() * (hi - lo)) + lo */
+
+/* ------------------------------------------------------------------ the numbers (stats.c) */
+typedef struct {
+ int16_t health, armor, magic_armor, dodge, gold, cost, min_dmg, max_dmg, reload;
+ float speed;
+ int8_t size, flying, boss, blockable, charge, x_soldier, x_adj, y_adj, bar_y, bar_w; /* bar_w: 0 small 1 medium 2 big */
+ int16_t hit_w, hit_h; /* the hit box: x +-hit_w, y - hit_h to y + 4 */
+ int16_t dead_time;
+ uint8_t blood; /* 0 red, 1 green, 2 grey */
+} EnemyStat;
+extern const EnemyStat enemy_stats[EN_COUNT];
+const char *enemy_name(int type);
+
+enum { SZ_SMALL, SZ_MEDIUM, SZ_BIG };
+enum { ARM_P, ARM_M, ARM_E, ARM_I }; /* physical, magic, explosive, true damage */
+
+/* ------------------------------------------------------------------ towers */
+enum {
+ TW_NONE, TW_ARCHER, TW_BARRACKS, TW_MAGE, TW_ENGINEER,
+ TW_RANGER, TW_MUSKETEER, TW_PALADIN, TW_BARBARIAN, TW_ARCANE, TW_SORCERER, TW_BFG, TW_TESLA
+};
+typedef struct {
+ int16_t cost, range, min_dmg, max_dmg, reload, area;
+} TowerStat;
+/* [kind][level 1..3] for the four basic towers; the specials at level 4 */
+TowerStat tower_stat(int kind, int level);
+typedef struct {
+ int16_t cost, range, rally, health, armor, min_dmg, max_dmg, reload, respawn, regen, regen_reload;
+} BarrackStat;
+BarrackStat barrack_stat(int kind, int level);
+
+/* ------------------------------------------------------------------ entities */
+typedef struct {
+ float x, y;
+} Pt;
+
+typedef struct Enemy {
+ uint8_t alive, type, path, lane;
+ uint8_t active, dead, blocked, fighting, charging, flying, boss, left; /* left: facing left (scaleX -1) */
+ uint8_t held; /* §_-9R§: can't move (thorns, frozen...) */
+ uint8_t fpos[2]; /* fighterPosition: soldiers around it */
+ int8_t soldier; /* who blocks it */
+ int16_t node; /* currentNode */
+ float x, y, xs, ys, speed, margin;
+ int32_t health, init_health;
+ int16_t armor, magic_armor, dodge, gold, cost, min_dmg, max_dmg;
+ int16_t reload, reload_t, charge, charge_t;
+ int16_t dead_t, dead_time;
+ uint16_t anim, anim_t;
+ uint8_t dir; /* 0 none, 1 right, 2 left, 3 up, 4 down (§_-LW§) */
+ /* debuffs */
+ int16_t poison_t, poison_lvl, poison_tick;
+ int16_t curse_t, curse_tick, curse_amt, slow_t, net_t;
+ float slow_speed; /* the speed before a slow or a net */
+ float base_speed;
+ /* the specials: timers and counts, by enemy */
+ int16_t sp_t, sp_t2, sp_n, sp_n2, sp_state;
+ int16_t regen_t, rage_t, respawn_t;
+ int16_t teleport_t, teleports, thorn_t, thorn_tick, thorns, thorn_dmg, thorn_len, thorn_every;
+ uint8_t teleporting, thorned;
+ uint8_t no_teleport, no_thorn, no_poly;
+ uint8_t froze; /* bosses: a phase */
+} Enemy;
+
+typedef struct Soldier {
+ uint8_t alive, kind, active, dead, respawning, walking, fighting, blocking, idle, charging, door_queued, left;
+ uint8_t hidden; /* in its barracks, not drawn */
+ uint8_t look; /* the reinforcements' three faces (A, B, C) */
+ int8_t spot; /* its barracks' spot, -1: reinforcements or a sorcerer's elemental */
+ int8_t enemy;
+ uint8_t fpos;
+ uint8_t level; /* reinforcements: their level; elemental: its upgrade */
+ float x, y, rx, ry, dx, dy; /* where it is, its rally point, where it goes */
+ float speed;
+ int16_t health, init_health, armor, min_dmg, max_dmg, range_w, range_h;
+ int16_t reload, reload_t, charge, charge_dmg, charge_t;
+ int16_t idle_time, idle_t, targeted_t, regen, regen_reload, regen_t;
+ int16_t dead_time, dead_t, door_wait, door_t;
+ int16_t life_time, life_t, lifes;
+ uint16_t anim, anim_t;
+ int16_t sp_t, sp_t2; /* specials' cooldowns */
+ uint8_t sp_state;
+ float home_x, home_y; /* reinforcements: where they were called (§_-Fm§) */
+} Soldier;
+
+typedef struct Spot {
+ int16_t x, y; /* the tower's place (the build spot is drawn 36 higher) */
+ Pt rally; /* the soldiers' rally point */
+ uint8_t kind, level; /* TW_*, 1 to 3 (4: a special) */
+ uint8_t building; /* building: the frames left */
+ uint8_t charging, ready;
+ int16_t reload_t, reload, charge_t, charge_len, shoot_at;
+ int16_t spent; /* §_-1Y§: what it cost, for selling */
+ int16_t shots;
+ int8_t target;
+ uint8_t shooter_flip[2], shooter_up[2], arrows;
+ uint16_t anim_t, shooter_t[2];
+ int16_t idle_t;
+ Pt dest; /* a bomb's or an arrow's aim */
+ /* barracks */
+ int8_t soldiers[3];
+ uint8_t door; /* 0 closed, 1 opening, 2 open, 3 closing */
+ int16_t door_t;
+ /* specials: each ability's level and cooldown */
+ uint8_t sp_lvl[3];
+ int16_t sp_t[3];
+ uint8_t sp_flag;
+ int8_t elemental;
+ uint8_t premade; /* built by the level (iron mode), not bought */
+ uint8_t disabled; /* frozen, or held by Vez'nan */
+ uint8_t ice, ice_hits; /* J.T.'s ice: 1 forming, 2 holding (3 hits break it), 3 melting; 4 to 6: Vez'nan's hold */
+ int16_t ice_t;
+} Spot;
+
+enum {
+ BU_ARROW, BU_BOLT, BU_BOMB, BU_FIREBALL, BU_ARROW_ENEMY, BU_AXE, BU_AXE_ENEMY, BU_MISSILE, BU_MISSILE_ENEMY,
+ BU_RAY_ARCANE, BU_RAY_DEATH, BU_RAY_POLY, BU_RAY_TESLA, BU_BOLT_SORCERER, BU_BOLT_NECRO, BU_SPEAR, BU_SHOT
+};
+typedef struct Bullet {
+ uint8_t alive, kind, level, active, crit, first;
+ int8_t target; /* an enemy (or a soldier for the enemies' bullets) */
+ int16_t t0, t1, fade_t, fade;
+ float x, y, x0, y0, tx, ty, xs, ys, acc, acc_max, g, rot;
+ int16_t min_dmg, max_dmg, area, pierce, bombs;
+ uint16_t anim, anim_t;
+} Bullet;
+
+typedef struct Fx {
+ uint8_t alive, flip, decal;
+ uint16_t anim, t, life;
+ float x, y;
+ int16_t value; /* gold from selling, from calling a wave */
+} Fx;
+
+/* ------------------------------------------------------------------ the battle */
+enum { LS_STARTING, LS_NORMAL, LS_PAUSED, LS_PRE_WIN, LS_WIN, LS_OVER };
+enum { MODE_CAMPAIGN, MODE_HEROIC, MODE_IRON };
+
+typedef struct {
+ int16_t wave; /* index in the level's waves */
+ int16_t spawn; /* indexSpawn */
+ uint8_t between; /* §_-4l§: waiting after a spawn finished */
+ int16_t between_t;
+ int16_t ival_t, index_cant, index_swap;
+ uint8_t cur_creep;
+} ActiveWave;
+
+typedef struct {
+ uint8_t index, mode, state;
+ int16_t lives, init_lives, cash, max_upgrade;
+ uint8_t unlock[4], unlock_lvl[4]; /* archers, barracks, engineers, mages (as the level gives them) */
+ uint8_t power_fire, power_reinf; /* unlocked at the first call */
+ uint8_t npaths, nlanes[MAX_PATHS];
+ const uint8_t *lane[MAX_PATHS][MAX_LANES];
+ uint16_t lane_n[MAX_PATHS][MAX_LANES];
+ const uint8_t *waves; /* this mode's waves */
+ uint8_t nwaves, max_waves, current_wave, index_waves;
+ int16_t interval_t;
+ uint8_t waiting_first; /* §switch§: the first wave waits for its call */
+ uint8_t flags_up; /* the next wave's flags show */
+ uint8_t nactive;
+ ActiveWave active[MAX_ACTIVE_WAVES];
+ uint8_t nflags;
+ Pt flag[MAX_PATHS], flag_dir[MAX_PATHS];
+ uint8_t flag_path[MAX_PATHS]; /* paths whose flags show */
+ int16_t start_t, prewin_t, ready_win_t;
+ uint8_t ready_win;
+ uint8_t fearless;
+ Pt defend[2];
+ uint8_t ndefend;
+ /* spells */
+ int16_t fire_cd, fire_reload, reinf_cd, reinf_reload;
+ uint8_t fire_on, reinf_on; /* unlocked */
+ int16_t fire_open_t, reinf_open_t;
+ uint8_t pending_note; /* a notification to show (NOTE_*) */
+ /* the field */
+ uint8_t nspots;
+ Spot spot[MAX_SPOTS];
+ Enemy en[MAX_ENEMIES];
+ Soldier so[MAX_SOLDIERS];
+ Bullet bu[MAX_BULLETS];
+ Fx fx[MAX_FX];
+ /* fireballs falling: the rain of fire's controllers */
+ struct { uint8_t on; int16_t t, dur; Pt at; } rain[2];
+ /* spider eggs (SpiderEgg): where, on which road, when they hatch */
+ struct { uint8_t on, path, n; int16_t node, t; float x, y; } egg[12];
+ int16_t skeletons; /* currentSkeletons */
+ uint32_t frame;
+ int32_t gold_won;
+ uint16_t kills;
+} Battle;
+extern Battle B;
+
+/* the upgrades bought with stars (as the game's GameUpgrades: each line's level, 0 to 5) */
+enum { UP_ARCHERS, UP_BARRACKS, UP_MAGES, UP_ENGINEERS, UP_RAIN, UP_REINF };
+extern uint8_t upgrades[6];
+/* is upgrade n (1 to 5) of a line on in this battle (heroic and iron cap them)? */
+bool up_on(int line, int n);
+
+/* level.c */
+extern uint32_t battle_seed; /* mixed into each battle's randomness */
+void battle_start(int level, int mode);
+void battle_step(void); /* a frame (1/30 s) */
+bool battle_call_wave(void); /* the next wave now (true if there was one to call) */
+int battle_stars(void);
+Pt path_node(int path, int lane, int node);
+int path_len(int path, int lane);
+int battle_wave_seconds_left(void); /* until the next wave comes by itself, -1 if none waits */
+bool tower_locked(int kind, int level); /* isTowerLocked */
+void battle_cash(int v);
+void battle_lose_lives(int n);
+
+/* enemy.c */
+int enemy_spawn(int type, int path, int lane, int node);
+void enemy_step(Enemy *e);
+void enemy_damage(Enemy *e, int dmg, int armor_type, int armor_pierce);
+void enemy_kill(Enemy *e, int how); /* how: 0 normal, 1 explode, 2 desintegrate */
+void enemy_block(Enemy *e, int soldier);
+void enemy_unblock(Enemy *e);
+void enemy_start_fighting(Enemy *e);
+int enemy_fighter_position(Enemy *e);
+void enemy_free_position(Enemy *e, int pos);
+bool enemy_dodge(Enemy *e);
+Pt enemy_road(const Enemy *e, int ahead); /* road[currentNode + ahead], kept on the road */
+int enemy_nodes_speed(const Enemy *e);
+static inline Enemy *EN(int i) { return i >= 0 && i < MAX_ENEMIES && B.en[i].alive ? &B.en[i] : 0; }
+float ellipse_contains(float cx, float cy, float w, float h, float px, float py);
+
+/* tower.c */
+void spot_build(int s, int kind);
+void spot_make(int s, int kind, int level); /* a tower the level built (iron mode), free */
+void spot_upgrade(int s, int choice); /* 0 next level, 1 / 2 the specials */
+void spot_sell(int s);
+int spot_sell_value(int s);
+int spot_cost(int s, int choice); /* -1 if it can't */
+void tower_step(int s);
+void spot_rally(int s, Pt p);
+bool spot_rally_ok(int s, Pt p);
+int tower_range(int kind, int level);
+int spot_ability_cost(int s, int k); /* -1 at its top */
+void spot_buy_ability(int s, int k);
+
+/* soldier.c */
+int soldier_new(int kind, int spot, Pt at, Pt rally);
+void soldier_step(Soldier *so);
+void soldier_damage(Soldier *so, int dmg, bool true_dmg);
+void soldier_set_rally(Soldier *so, Pt p);
+void soldier_free(Soldier *so);
+static inline Soldier *SO(int i) { return i >= 0 && i < MAX_SOLDIERS && B.so[i].alive ? &B.so[i] : 0; }
+enum {
+ SK_L1, SK_L2, SK_L3, SK_PALADIN, SK_BARBARIAN, SK_FARMER, SK_REINF2, SK_REINF3, SK_REINF4, SK_ELEMENTAL
+};
+
+/* bullet.c */
+Bullet *bullet_new(int kind);
+void bullet_step(Bullet *b);
+void fx_add(int anim, float x, float y, bool flip, bool decal);
+void fx_value(float x, float y, int value); /* "+15" floating up */
+void fx_step(void);
+
+/* power.c */
+void power_init(void);
+void power_step(void);
+bool power_fire(Pt at);
+bool power_reinforce(Pt at);
+bool power_reinforce_ok(Pt at);
+int power_fire_cooldown(void);
+int power_reinf_cooldown(void);
+void power_unlock_fire(void);
+void power_unlock_reinf(void);
+void power_shorten(int frames);
+#endif
diff --git a/games/kingdomrush/src/level.c b/games/kingdomrush/src/level.c
new file mode 100644
index 00000000..de1c9693
--- /dev/null
+++ b/games/kingdomrush/src/level.c
@@ -0,0 +1,329 @@
+/* The battle (Level.as), its waves (Wave.as, WaveSpawn.as).
+ *
+ * A level's data (tools/pack.py): its paths, flags and each mode's build spots, lives, gold, unlocks and waves.
+ * A wave: its interval (u16, the frames from the last wave's end), its path, its two notifications, whether its
+ * flag shows a flier, how many spawns; a spawn: the enemy, the one it alternates with (0xFF none) every max_same,
+ * how many, the frames between them, the frames before the next spawn, a fixed lane or a random one. */
+#include <string.h>
+#include "kr.h"
+#include "res.h"
+
+Battle B;
+uint8_t upgrades[6];
+uint32_t battle_seed;
+
+static uint32_t rs = 0x9E3779B9u;
+void rnd_seed(uint32_t s) { rs = s ? s : 0x9E3779B9u; }
+float rnd(void) {
+ rs ^= rs << 13, rs ^= rs >> 17, rs ^= rs << 5;
+ return (float)(rs >> 8) * (1.0f / 16777216.0f);
+}
+int rnd_round(int lo, int hi) { return (int)__builtin_roundf(rnd() * (float)(hi - lo)) + lo; }
+
+bool up_on(int line, int n) {
+ if (upgrades[line] < n) return false;
+ /* heroic and iron allow the upgrades up to a level: maxUpgradeLevel (0: all) */
+ return B.max_upgrade == 0 || B.max_upgrade >= n;
+}
+
+/* ------------------------------------------------------------------ the level's data */
+static const uint8_t *level_data(int i) {
+ const uint8_t *s = section(SEC_LEVELS);
+ return s + rd32(s + 4 + 4 * i);
+}
+static const uint8_t *level_part(int i, int part) {
+ const uint8_t *l = level_data(i);
+ return l + rd32(l + 4 * part);
+}
+
+Pt path_node(int path, int lane, int node) {
+ const uint8_t *p = B.lane[path][lane] + 4 * node;
+ return (Pt){(float)rds16(p) / 16.0f, (float)rds16(p + 2) / 16.0f};
+}
+int path_len(int path, int lane) { return B.lane_n[path][lane]; }
+
+#define WAVE_HDR 7
+#define SPAWN_SZ 11
+static const uint8_t *wave_at(int w) {
+ const uint8_t *p = B.waves;
+ for (int i = 0; i < w; i++) p += WAVE_HDR + SPAWN_SZ * p[6];
+ return p;
+}
+static int wave_interval(int w) { return (int)rd16(wave_at(w)); }
+
+/* ------------------------------------------------------------------ start */
+static void count_waves(void) {
+ /* waves with an interval of 0 come with the one before: they count as one */
+ int n = 0;
+ for (int i = 0; i < B.nwaves; i++) {
+ n++;
+ while (i + 1 < B.nwaves && wave_interval(i + 1) == 0) i++;
+ }
+ B.max_waves = (uint8_t)n;
+}
+
+void battle_start(int level, int mode) {
+ memset(&B, 0, sizeof B);
+ B.index = (uint8_t)level, B.mode = (uint8_t)mode;
+ const uint8_t *p = level_part(level, 0);
+ B.npaths = *p++;
+ for (int i = 0; i < B.npaths && i < MAX_PATHS; i++) {
+ B.nlanes[i] = *p++;
+ for (int l = 0; l < B.nlanes[i]; l++) {
+ B.lane_n[i][l] = (uint16_t)rd16(p);
+ B.lane[i][l] = p + 2;
+ p += 2 + 4 * B.lane_n[i][l];
+ }
+ }
+ p = level_part(level, 1);
+ B.nflags = *p++;
+ for (int i = 0; i < B.nflags && i < MAX_PATHS; i++, p += 8) {
+ B.flag[i] = (Pt){(float)rds16(p), (float)rds16(p + 2)};
+ B.flag_dir[i] = (Pt){(float)rds16(p + 4), (float)rds16(p + 6)};
+ }
+ B.ndefend = *p++;
+ for (int i = 0; i < B.ndefend; i++, p += 4)
+ if (i < 2) B.defend[i] = (Pt){(float)rds16(p), (float)rds16(p + 2)};
+ if (B.ndefend > 2) B.ndefend = 2;
+ B.unlock_lvl[0] = p[0], B.unlock_lvl[1] = p[1], B.unlock_lvl[2] = p[2], B.unlock_lvl[3] = p[3];
+ p = level_part(level, 2 + mode);
+ B.nspots = *p++;
+ int premade[MAX_SPOTS][2], npre = 0;
+ for (int i = 0; i < B.nspots; i++, p += 10) {
+ Spot *s = &B.spot[i < MAX_SPOTS ? i : MAX_SPOTS - 1];
+ s->x = (int16_t)rds16(p + 2), s->y = (int16_t)rds16(p + 4);
+ s->rally = (Pt){(float)rds16(p + 6), (float)rds16(p + 8)};
+ s->target = -1, s->elemental = -1;
+ for (int k = 0; k < 3; k++) s->soldiers[k] = -1;
+ if (p[0] == 0xFF) s->kind = 0xFF; /* (a level's special building: not here) */
+ else if (p[0] >= 1 && p[0] <= 4 && npre < MAX_SPOTS) premade[npre][0] = i, premade[npre][1] = p[0] << 4 | p[1], npre++;
+ }
+ B.lives = B.init_lives = (int16_t)rd16(p);
+ B.cash = (int16_t)rd16(p + 2);
+ B.unlock[0] = p[4], B.unlock[1] = p[5], B.unlock[2] = p[6], B.unlock[3] = p[7];
+ B.max_upgrade = p[8];
+ bool power1 = p[9], power2 = p[10];
+ B.nwaves = p[11];
+ B.waves = p + 12;
+ count_waves();
+ /* power1: the reinforcements, power2: the rain of fire, unlocked at the first wave's call (Level.§_-H6§) */
+ B.power_reinf = power1, B.power_fire = power2;
+ B.fearless = 1;
+ B.state = LS_STARTING;
+ power_init();
+ rnd_seed(0x5EED0000u ^ (uint32_t)(level * 977 + mode * 131) ^ battle_seed);
+ for (int k = 0; k < npre; k++) {
+ static const uint8_t kinds[5] = {0, TW_ARCHER, TW_BARRACKS, TW_MAGE, TW_ENGINEER};
+ spot_make(premade[k][0], kinds[premade[k][1] >> 4], premade[k][1] & 15);
+ }
+}
+
+/* ------------------------------------------------------------------ cash, lives */
+void battle_cash(int v) {
+ if (v > 0) B.gold_won += v;
+ B.cash = (int16_t)(B.cash + v);
+}
+
+void battle_lose_lives(int n) {
+ B.lives = (int16_t)(B.lives - n);
+ if (B.lives <= 0) {
+ B.lives = 0;
+ B.state = LS_OVER;
+ }
+}
+
+int battle_stars(void) {
+ if (B.mode != MODE_CAMPAIGN) return 3;
+ if (B.lives >= 18) return 3;
+ if (B.lives > 5) return 2;
+ return 1;
+}
+
+bool tower_locked(int kind, int level) {
+ /* kind: 0 archers, 1 barracks, 2 engineers, 3 mages; level 1 to 5 (4, 5: the specials) */
+ int u = B.unlock[kind], ul = B.unlock_lvl[kind];
+ if (u >= level || (u == 0 && level != 1 && ul >= level)) return false;
+ return true;
+}
+
+/* ------------------------------------------------------------------ waves */
+static bool spawn_step(ActiveWave *a) {
+ const uint8_t *w = wave_at(a->wave), *s = w + WAVE_HDR + SPAWN_SZ * a->spawn;
+ int creep = s[0], aux = s[1], max_same = s[2], cant = (int)rd16(s + 3), ival = (int)rd16(s + 5);
+ if (a->index_cant > cant) return false;
+ if (ival - 1 > a->ival_t) {
+ a->ival_t++;
+ return true;
+ }
+ if (aux != 0xFF) {
+ if (a->index_swap == max_same) {
+ a->cur_creep = (uint8_t)(a->cur_creep == aux ? creep : aux);
+ a->index_swap = 0;
+ }
+ } else
+ a->cur_creep = (uint8_t)creep;
+ int path = w[2], lane;
+ if (path >= B.npaths) path = B.npaths - 1;
+ if (!s[9]) lane = (int)__builtin_ceilf(rnd() * (float)B.nlanes[path]) - 1;
+ else lane = s[10];
+ if (lane < 0) lane = 0;
+ if (lane >= B.nlanes[path]) lane = B.nlanes[path] - 1;
+ enemy_spawn(a->cur_creep, path, lane, 0);
+ a->index_swap++, a->index_cant++, a->ival_t = 0;
+ return true;
+}
+
+/* Wave.spawnEnemies: false when it is done */
+static bool wave_step(ActiveWave *a) {
+ const uint8_t *w = wave_at(a->wave);
+ int n = w[6];
+ if (a->spawn < n) {
+ const uint8_t *s = w + WAVE_HDR + SPAWN_SZ * a->spawn;
+ if (a->between) {
+ if (a->between_t < (int)rd16(s + 7)) {
+ a->between_t++;
+ return true;
+ }
+ a->spawn++, a->between = 0;
+ a->ival_t = 0, a->index_cant = 1, a->index_swap = 0, a->cur_creep = 0xFF;
+ if (a->spawn < n) a->cur_creep = w[WAVE_HDR + SPAWN_SZ * a->spawn];
+ return true;
+ }
+ if (!spawn_step(a)) {
+ a->between = 1, a->between_t = 0;
+ if (a->spawn + 1 == n) {
+ a->spawn++;
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+}
+
+static void activate(int wi) {
+ if (B.nactive >= MAX_ACTIVE_WAVES) return;
+ ActiveWave *a = &B.active[B.nactive++];
+ memset(a, 0, sizeof *a);
+ a->wave = (int16_t)wi, a->index_cant = 1;
+ a->cur_creep = wave_at(wi)[WAVE_HDR];
+}
+
+static void show_flags(int wi) {
+ memset(B.flag_path, 0, sizeof B.flag_path);
+ for (int k = wi; k < B.nwaves; k++) {
+ if (k > wi && wave_interval(k) != 0) break;
+ int p = wave_at(k)[2];
+ if (p < MAX_PATHS) B.flag_path[p] = 1 + wave_at(k)[5]; /* 2: a flier comes */
+ }
+ B.flags_up = 1;
+}
+
+static void notify(int note) {
+ if (note == NOTE_POWERREINFORCEMENT) power_unlock_reinf();
+ if (note == NOTE_POWERFIREBALL) power_unlock_fire();
+ if (note != NOTE_NONE) B.pending_note = (uint8_t)note;
+}
+
+static bool has_enemies(void) {
+ if (B.ready_win) {
+ if (B.ready_win_t < 30) {
+ B.ready_win_t++;
+ if (B.ready_win_t % 10 == 0)
+ for (int i = 0; i < MAX_ENEMIES; i++)
+ if (B.en[i].alive && (!B.en[i].boss || !B.en[i].dead)) B.ready_win = 0;
+ return true;
+ }
+ return false;
+ }
+ for (int i = 0; i < MAX_ENEMIES; i++)
+ if (B.en[i].alive && (!B.en[i].boss || !B.en[i].dead)) return true;
+ B.ready_win = 1, B.ready_win_t = 0;
+ return true;
+}
+
+/* Level.§_-6x§: the waves, a frame */
+static void waves_step(void) {
+ if (B.current_wave == 0 && B.waiting_first) return;
+ if (B.nactive == 0) {
+ if (B.index_waves < B.nwaves) {
+ const uint8_t *w = wave_at(B.index_waves);
+ if ((int)rd16(w) == B.interval_t) {
+ if (B.index_waves != 0) notify(w[3]);
+ B.current_wave++;
+ activate(B.index_waves);
+ B.interval_t = 0;
+ B.index_waves++;
+ while (B.index_waves < B.nwaves && wave_interval(B.index_waves) == 0) activate(B.index_waves++);
+ B.flags_up = 0;
+ } else {
+ if (B.index_waves == 0 && w[3] && !B.waiting_first) notify(w[3]);
+ if ((B.interval_t == 50 && rd16(w) != 0) || B.index_waves == 0) show_flags(B.index_waves);
+ if (B.index_waves == 0) B.waiting_first = 1;
+ else B.interval_t++;
+ }
+ } else if (!has_enemies()) {
+ B.state = LS_PRE_WIN;
+ B.prewin_t = 0;
+ }
+ }
+ for (int i = 0; i < B.nactive;) {
+ if (!wave_step(&B.active[i])) {
+ B.active[i] = B.active[--B.nactive];
+ continue;
+ }
+ i++;
+ }
+}
+
+int battle_wave_seconds_left(void) {
+ if (!B.flags_up || B.index_waves >= B.nwaves) return -1;
+ if (B.waiting_first) return 0;
+ return (wave_interval(B.index_waves) - B.interval_t + FPS - 1) / FPS;
+}
+
+/* Level.§_-H6§: a wave flag clicked */
+bool battle_call_wave(void) {
+ if (!B.flags_up || B.index_waves >= B.nwaves || B.state != LS_NORMAL) return false;
+ if (B.waiting_first) {
+ if (B.power_fire) power_unlock_fire();
+ if (B.power_reinf) power_unlock_reinf();
+ B.waiting_first = 0;
+ }
+ if (B.index_waves != 0) {
+ int left = wave_interval(B.index_waves) - B.interval_t;
+ power_shorten(left);
+ int secs = (int)__builtin_roundf((float)left / FPS);
+ if (secs >= 1) {
+ battle_cash(secs);
+ int p = 0;
+ while (p < MAX_PATHS - 1 && !B.flag_path[p]) p++;
+ fx_value(B.flag[p].x, B.flag[p].y, secs);
+ }
+ B.fearless = 0;
+ }
+ B.interval_t = (int16_t)wave_interval(B.index_waves);
+ B.flags_up = 0;
+ return true;
+}
+
+/* ------------------------------------------------------------------ a frame */
+void battle_step(void) {
+ B.frame++;
+ if (B.state == LS_STARTING) {
+ if (++B.start_t >= 30) B.state = LS_NORMAL;
+ return;
+ }
+ if (B.state != LS_NORMAL && B.state != LS_PRE_WIN) return;
+ if (B.state == LS_NORMAL) waves_step();
+ for (int s = 0; s < B.nspots; s++) tower_step(s);
+ for (int i = 0; i < MAX_ENEMIES; i++)
+ if (B.en[i].alive) enemy_step(&B.en[i]);
+ for (int i = 0; i < MAX_SOLDIERS; i++)
+ if (B.so[i].alive) soldier_step(&B.so[i]);
+ for (int i = 0; i < MAX_BULLETS; i++)
+ if (B.bu[i].alive) bullet_step(&B.bu[i]);
+ fx_step();
+ power_step();
+ if (B.state == LS_PRE_WIN && ++B.prewin_t > 30) B.state = LS_WIN;
+}
diff --git a/games/kingdomrush/src/main.c b/games/kingdomrush/src/main.c
new file mode 100644
index 00000000..c8ed0da3
--- /dev/null
+++ b/games/kingdomrush/src/main.c
@@ -0,0 +1,46 @@
+/* Kingdom Rush for the NumWorks calculator.
+ *
+ * Inspired by Kingdom Rush by Ironhide Game Studio, not affiliated with them.
+ * Made by Mason Chen as part of NumPlay. */
+#include "game.h"
+#include "gfx.h"
+#include "plat.h"
+#include "res.h"
+
+#ifndef HOST
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Kingdom Rush";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+extern const uint8_t kr_data[];
+const uint8_t *kr_bin;
+
+uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */
+uint32_t perf_updates __attribute__((used));
+
+int main(void) {
+ uint16_t band[SCREEN_W * BAND_H]; /* (on the stack, out of the RAM apps get) */
+ gfx_set_band_memory(band);
+ plat_begin();
+ kr_bin = kr_data;
+ game_init();
+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 100 a step, 30 steps a second */
+ while (g.running) {
+ /* the game's steps: drawn when caught up (at most 3 steps for a drawing) */
+ int n = 0;
+ uint32_t now = plat_millis() * 3;
+ while ((int32_t)(now - next) >= 0 && n < 3 && g.running) {
+ game_step(plat_keys());
+ perf_updates++;
+ next += 100;
+ n++;
+ }
+ if (!g.running) break;
+ if ((int32_t)(now - next) > 600) next = now; /* far behind: do not rush */
+ if (n) {
+ game_draw();
+ perf_frames++;
+ } else
+ plat_sleep(1);
+ }
+ return plat_end();
+}
+#endif
diff --git a/games/kingdomrush/src/menus.c b/games/kingdomrush/src/menus.c
new file mode 100644
index 00000000..f0179bf3
--- /dev/null
+++ b/games/kingdomrush/src/menus.c
@@ -0,0 +1,271 @@
+/* The title, the world map and its stage window (Map.as, LevelSelect.as), the upgrades (MenuUpgrades.as), the
+ * help page. */
+#include <stdio.h>
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "kr.h"
+#include "strings.h"
+
+#define C_TEXT RGB(0xF4E6C8)
+#define C_GOLD RGB(0xFFD32A)
+#define C_DIM RGB(0x9A8A70)
+
+/* Map.§_-2§: the stages' flags on the map (at full size) */
+static const int16_t flags[12][2] = {{104, 482}, {87, 422}, {144, 398}, {206, 373}, {152, 290}, {141, 186},
+ {278, 123}, {359, 118}, {437, 151}, {530, 206}, {526, 301}, {557, 393}};
+static int fx(int i) { return flags[i][0] * 32 / 70; }
+static int fy(int i) { return flags[i][1] * 32 / 70 - MAP_Y0; }
+
+static bool unlocked(int i) { return i == 0 || g.p.camp[i - 1] > 0; }
+
+static void panel(int x, int y, int w, int h) {
+ gfx_panel(x, y, w, h, RGB(0x3A2614), RGB(0xC09A5A));
+ gfx_frame_rect(x + 2, y + 2, w - 4, h - 4, RGB(0x6A4A26));
+}
+
+static void key_line(const char *s) {
+ if (!gfx_rows(228, 12)) return;
+ gfx_blend(0, 228, 320, 12, BLACK, 22);
+ gfx_text_c(FONT_SMALL, 160, 229, s, C_TEXT);
+}
+
+/* ------------------------------------------------------------------ title */
+static uint8_t title_sel;
+
+void title_step(void) {
+ if (g.pressed & (K_OK | K_EXE)) {
+ g.screen = SCR_MAP;
+ /* the first stage not yet won */
+ g.map_sel = 0;
+ for (int i = 0; i < NLEVELS; i++)
+ if (unlocked(i)) g.map_sel = (uint8_t)i;
+ }
+ if (g.pressed & K_BACK) game_quit();
+ (void)title_sel;
+}
+
+static void title_band(void) {
+ pic_draw(PIC_TITLE, 0, 0);
+ key_line("OK start Back quit");
+}
+void title_draw(void) { gfx_frame(title_band); }
+
+/* ------------------------------------------------------------------ the map */
+static uint8_t win_open, win_mode;
+
+static bool mode_open(int i, int m) { return m == 0 || g.p.camp[i] >= 3; }
+
+void map_step(void) {
+ uint32_t pr = g.pressed;
+ if (win_open) {
+ if (pr & K_BACK) win_open = 0;
+ if (play_key(K_LEFT)) win_mode = (uint8_t)((win_mode + 2) % 3);
+ if (play_key(K_RIGHT)) win_mode = (uint8_t)((win_mode + 1) % 3);
+ if (pr & (K_OK | K_EXE)) {
+ if (!mode_open(g.map_sel, win_mode)) return;
+ win_open = 0;
+ play_start(g.map_sel, win_mode);
+ }
+ return;
+ }
+ if (pr & K_BACK) {
+ g.screen = SCR_TITLE;
+ return;
+ }
+ if (pr & (K_OK | K_EXE)) {
+ win_open = 1, win_mode = 0;
+ return;
+ }
+ if (pr & K_DIGIT(0) || pr & K_DEL) {
+ g.screen = SCR_UPGRADES;
+ return;
+ }
+ int dx = 0, dy = 0;
+ if (play_key(K_LEFT)) dx = -1;
+ else if (play_key(K_RIGHT)) dx = 1;
+ else if (play_key(K_UP)) dy = -1;
+ else if (play_key(K_DOWN)) dy = 1;
+ if (dx || dy) {
+ /* the unlocked stage nearest that way */
+ int cur = g.map_sel, best = -1;
+ int bs = 1 << 30;
+ for (int i = 0; i < NLEVELS; i++) {
+ if (i == cur || !unlocked(i)) continue;
+ int vx = fx(i) - fx(cur), vy = fy(i) - fy(cur);
+ int along = vx * dx + vy * dy, across = vx * dy - vy * dx;
+ if (across < 0) across = -across;
+ if (along <= 0) continue;
+ int sc = along + 2 * across;
+ if (sc < bs) bs = sc, best = i;
+ }
+ if (best >= 0) g.map_sel = (uint8_t)best;
+ }
+}
+
+static void map_band(void) {
+ pic_draw(PIC_MAP, 0, 0);
+ for (int i = 0; i < NLEVELS; i++) {
+ if (!unlocked(i)) continue;
+ int x = fx(i), y = fy(i);
+ if (i == g.map_sel) {
+ gfx_ellipse(x, y + 1, 12, 5, RGB(0xFFE14D), 32);
+ gfx_ellipse(x, y + 1, 13, 6, RGB(0x6A4A00), 32);
+ }
+ if (g.p.camp[i]) {
+ spr_anim(AN_UI_FLAGDONE, 0, false, x, y, false);
+ for (int k = 0; k < 3; k++) spr_anim(AN_UI_FLAGSTAR, k < g.p.camp[i] ? 1 : 0, false, x - 13 + 7 * k, y + 3, false);
+ if (g.p.heroic[i]) spr_anim(AN_UI_FLAGHEROIC, 0, false, x, y, false);
+ } else
+ spr_anim(AN_UI_FLAGNEW, 0, false, x, y, false);
+ }
+ /* the stars: won, and free to spend */
+ if (gfx_rows(2, 18)) {
+ gfx_panel(2, 2, 74, 17, RGB(0x2A1A0C), RGB(0xC09A5A));
+ char s[24];
+ snprintf(s, sizeof s, "%d/%d", stars_won(), stars_max());
+ spr_anim(AN_UI_FLAGSTAR, 1, false, 5, 4, false);
+ gfx_text(FONT_HUD, 22, 3, s, C_GOLD);
+ }
+ if (!win_open) {
+ char s[64];
+ snprintf(s, sizeof s, "Arrows choose OK play %s 0 upgrades (%d stars)", level_title(g.map_sel), stars_free());
+ key_line(s);
+ return;
+ }
+ /* LevelSelect: the stage's title, its story, its three modes */
+ int i = g.map_sel;
+ if (!gfx_rows(30, 180)) return;
+ panel(30, 30, 260, 176);
+ gfx_text_oc(FONT_BIG, 160, 36, level_title(i), C_GOLD);
+ char story[200];
+ snprintf(story, sizeof story, "%s", level_story(i));
+ if (strlen(story) > 180) strcpy(story + 176, "...");
+ gfx_text_box(FONT_TEXT, 42, 64, 236, story, C_TEXT);
+ static const char *const names[3] = {"Campaign", "Heroic", "Iron"};
+ for (int m = 0; m < 3; m++) {
+ int x = 75 + 85 * m, y = 150;
+ bool open = mode_open(i, m), sel = m == win_mode;
+ gfx_panel(x - 36, y, 72, 20, sel ? RGB(0xE0A020) : RGB(0x5A3E20), sel ? WHITE : RGB(0xC09A5A));
+ gfx_text_c(FONT_HUD, x, y + 3, names[m], !open ? C_DIM : sel ? RGB(0x2A1A0C) : C_TEXT);
+ bool done = m == 0 ? g.p.camp[i] > 0 : m == 1 ? g.p.heroic[i] : g.p.iron[i];
+ if (done) spr_anim(AN_UI_FLAGSTAR, 1, false, x + 26, y - 6, false);
+ }
+ const char *rule = win_mode == 0 ? "Defend the realm. Lose a life for each enemy that gets through."
+ : !mode_open(i, win_mode) ? "Win this stage with 3 stars to open it."
+ : win_mode == 1 ? "6 elite waves, 1 life, upgrades capped."
+ : "1 big wave, 1 life, some towers barred.";
+ gfx_text_c(FONT_SMALL, 160, 176, rule, C_DIM);
+ gfx_text_c(FONT_SMALL, 160, 190, "Left Right mode OK fight Back close", C_TEXT);
+}
+void map_draw(void) { gfx_frame(map_band); }
+
+/* ------------------------------------------------------------------ upgrades (MenuUpgrades) */
+/* the costs in stars, by line and level (MenuUpgrades.§_-C9§) */
+static const uint8_t up_cost[6][5] = {{1, 1, 2, 2, 3}, {1, 1, 2, 2, 3}, {1, 1, 2, 2, 3},
+ {1, 1, 3, 3, 3}, {1, 1, 2, 2, 3}, {2, 3, 3, 3, 4}};
+/* the panel's columns in the game's order (archers, barracks, mages, artillery, rain, reinforcements) */
+static const uint8_t col_x[6] = {21, 53, 84, 115, 146, 177};
+static const uint8_t row_y[5] = {165, 144, 124, 102, 82};
+static uint8_t up_col, up_row;
+
+int stars_max(void) { return 3 * NLEVELS + 2 * NLEVELS; } /* 3 a campaign, 1 a heroic, 1 an iron challenge */
+int stars_won(void) {
+ int n = 0;
+ for (int i = 0; i < NLEVELS; i++) n += g.p.camp[i] + g.p.heroic[i] + g.p.iron[i];
+ return n;
+}
+int stars_free(void) {
+ int spent = 0;
+ for (int l = 0; l < 6; l++)
+ for (int k = 0; k < g.p.ups[l]; k++) spent += up_cost[l][k];
+ return stars_won() - spent;
+}
+
+void upgrades_step(void) {
+ uint32_t pr = g.pressed;
+ if (pr & (K_BACK | K_DIGIT(0))) {
+ save_progress();
+ g.screen = SCR_MAP;
+ return;
+ }
+ if (play_key(K_LEFT)) up_col = (uint8_t)((up_col + 5) % 6);
+ if (play_key(K_RIGHT)) up_col = (uint8_t)((up_col + 1) % 6);
+ if (play_key(K_UP) && up_row < 4) up_row++;
+ if (play_key(K_DOWN) && up_row > 0) up_row--;
+ if (pr & (K_OK | K_EXE)) {
+ int have = g.p.ups[up_col];
+ if (up_row == have && have < 5 && stars_free() >= up_cost[up_col][up_row]) {
+ g.p.ups[up_col]++;
+ save_progress();
+ }
+ }
+ if (pr & K_DEL) { /* reset: every star back */
+ memset(g.p.ups, 0, sizeof g.p.ups);
+ save_progress();
+ }
+}
+
+static void upgrades_band(void) {
+ pic_draw(PIC_UPGRADES, 0, 0);
+ /* the game's icon order: barracks first, then archers */
+ static const uint8_t icon_line[6] = {1, 0, 2, 3, 4, 5};
+ for (int c = 0; c < 6; c++)
+ for (int r = 0; r < 5; r++) {
+ int x = UPG_X + col_x[c], y = row_y[r];
+ int have = g.p.ups[c];
+ int state = r < have ? 2 : r == have ? 0 : 1;
+ spr_anim(AN_UI_UPITEM, state, false, x, y, false);
+ int icon = icon_line[c] * 5 + r;
+ if (state == 1) spr_frame_tint(anim_slot(AN_UI_UPICONS, icon, false), x, y, false, RGB(0x202020), 20);
+ else spr_anim(AN_UI_UPICONS, icon, false, x, y, false);
+ if (state == 0) {
+ char s[4];
+ snprintf(s, sizeof s, "%d", up_cost[c][r]);
+ gfx_text_oc(FONT_SMALL, x + 6, y + 6, s, stars_free() >= up_cost[c][r] ? C_GOLD : RGB(0xFF6040));
+ }
+ if (c == up_col && r == up_row) {
+ gfx_frame_rect(x - 10, y - 10, 21, 21, RGB(0xFFE14D));
+ gfx_frame_rect(x - 11, y - 11, 23, 23, RGB(0x6A4A00));
+ }
+ }
+ /* stars to spend, and what the chosen one does */
+ char s[48];
+ snprintf(s, sizeof s, "%d", stars_free());
+ spr_anim(AN_UI_FLAGSTAR, 1, false, UPG_X + 8, 214, false);
+ gfx_text_o(FONT_HUD, UPG_X + 25, 213, s, C_GOLD);
+ if (gfx_rows(0, 240)) {
+ const char *nm = upgrade_name(up_col, up_row), *ds = upgrade_desc(up_col, up_row);
+ gfx_fill(0, 0, UPG_X - 2, 240, RGB(0x1E140B));
+ gfx_fill(UPG_X + 217, 0, 320 - UPG_X - 217, 240, RGB(0x1E140B));
+ gfx_text_box(FONT_SMALL, UPG_X + 220, 40, 48, nm, C_GOLD);
+ gfx_text_box(FONT_SMALL, UPG_X + 220, 80, 48, ds, C_TEXT);
+ gfx_text_box(FONT_SMALL, 2, 40, 48, "OK buy", C_TEXT);
+ gfx_text_box(FONT_SMALL, 2, 64, 48, "Clear: all stars back", C_DIM);
+ gfx_text_box(FONT_SMALL, 2, 110, 48, "Back map", C_TEXT);
+ }
+}
+void upgrades_draw(void) { gfx_frame(upgrades_band); }
+
+/* ------------------------------------------------------------------ how to play */
+void help_step(void) {
+ if (g.pressed & (K_BACK | K_OK | K_EXE)) g.screen = SCR_BATTLE;
+}
+
+static void help_band(void) {
+ gfx_fill(0, gfx_y0, 320, BAND_H, RGB(0x2A1C10));
+ gfx_text_oc(FONT_BIG, 160, 6, "How to play", C_GOLD);
+ static const char *const lines[] = {
+ "Enemies walk the roads. Each one that gets through costs lives.",
+ "Arrows: hop between build spots, wave flags and enemies.",
+ "OK on a spot: the tower menu. Arrows pick, OK buys.",
+ "Archers and mages shoot. Bombards blast ground enemies.",
+ "Barracks send soldiers to block the road (rally point).",
+ "1: rain of fire. 2: reinforcements. Aim with the arrows.",
+ "Clear key (or the flag): the next wave now, for gold.",
+ "Back: pause. Home: save and quit.",
+ };
+ for (int i = 0; i < (int)(sizeof lines / sizeof lines[0]); i++) gfx_text(FONT_TEXT, 12, 40 + 22 * i, lines[i], C_TEXT);
+ gfx_text_c(FONT_SMALL, 160, 226, "OK back", C_DIM);
+}
+void help_draw(void) { gfx_frame(help_band); }
diff --git a/games/kingdomrush/src/pic.c b/games/kingdomrush/src/pic.c
new file mode 100644
index 00000000..80d1fc8f
--- /dev/null
+++ b/games/kingdomrush/src/pic.c
@@ -0,0 +1,322 @@
+/* The pictures (tools/codec.py, as Five Nights at Freddy's 4's): 16 x 16 squares coded as JPEG codes them.
+ *
+ * A square: four 8 x 8 blocks of Y, one of Cb and one of Cr (at half resolution), each a Huffman-coded
+ * list of quantized cosine coefficients. The inverse transform is libjpeg's "ifast" one (the AAN algorithm,
+ * its scales folded into the quantization tables by tools/pack.py), with a shortcut for blocks of one flat
+ * colour. Colours are dithered on the way to 16 bits.
+ *
+ * Screens are decoded as the bands are drawn (pic_draw). A battlefield's terrain is decoded once, when the
+ * level starts, into a byte a pixel: its own 256 colours (BGPAL), each pixel the nearest of them (bg_load). */
+#include "gfx.h"
+#include "res.h"
+
+typedef struct {
+ const uint16_t *lut; /* 9 bits ahead: length << 8 | symbol, 0 when the code is longer */
+ const int32_t *maxcode; /* JPEG's, by length (1 to 17) */
+ const int32_t *valoff;
+ const uint8_t *vals;
+} Huff;
+
+static const uint8_t zigzag[64 + 16] = {
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 /* (a corrupt run lands here) */
+};
+
+static Huff huff_tab(int k) {
+ const uint8_t *p = section(SEC_HUFF) + 1424 * k;
+ return (Huff){(const uint16_t *)(const void *)p, (const int32_t *)(const void *)(p + 1024),
+ (const int32_t *)(const void *)(p + 1096), p + 1168};
+}
+
+/* ------------------------------------------------------------------ bits */
+typedef struct {
+ const uint8_t *p;
+ uint32_t buf; /* the next bits, from the top */
+ int n;
+} Bits;
+
+static inline void fill(Bits *b) {
+ while (b->n <= 24) {
+ b->buf |= (uint32_t)*b->p++ << (24 - b->n);
+ b->n += 8;
+ }
+}
+static inline uint32_t take(Bits *b, int k) {
+ uint32_t v = b->buf >> (32 - k);
+ b->buf <<= k;
+ b->n -= k;
+ return v;
+}
+static inline int decode(Bits *b, const Huff *h) {
+ fill(b);
+ uint32_t e = h->lut[b->buf >> 23];
+ if (e) {
+ b->buf <<= e >> 8;
+ b->n -= (int)(e >> 8);
+ return (int)(e & 0xFF);
+ }
+ for (int l = 10; l <= 16; l++) {
+ int32_t code = (int32_t)(b->buf >> (32 - l));
+ if (code <= h->maxcode[l]) {
+ b->buf <<= l;
+ b->n -= l;
+ return h->vals[(code + h->valoff[l]) & 0xFF];
+ }
+ }
+ b->buf <<= 16; /* (corrupt: give up on this block) */
+ b->n -= 16;
+ return 0;
+}
+/* JPEG's extension of s bits to a signed value */
+static inline int value(Bits *b, int s) {
+ if (!s) return 0;
+ fill(b);
+ int v = (int)take(b, s);
+ return v < 1 << (s - 1) ? v - (1 << s) + 1 : v;
+}
+
+/* ------------------------------------------------------------------ one block */
+#define CONST_BITS 8
+#define MUL(v, c) (((v) * (c)) >> CONST_BITS)
+#define FIX_1_082392200 277
+#define FIX_1_414213562 362
+#define FIX_1_847759065 473
+#define FIX_2_613125930 669
+
+static inline uint8_t clamp8(int v) { return (uint8_t)(v < 0 ? 0 : v > 255 ? 255 : v); }
+
+/* decodes a block into out (8 x 8 bytes, stride 8); *pred: the DC before it */
+static void block(Bits *b, const Huff *dc, const Huff *ac, int *pred, const uint16_t *q, uint8_t *out) {
+ int32_t c[64];
+ uint64_t cols = 0; /* which coefficients are not 0, a bit each */
+ int s = decode(b, dc);
+ *pred += value(b, s);
+ int dcv = *pred * q[0];
+ for (int k = 1; k < 64;) {
+ int rs = decode(b, ac), r = rs >> 4;
+ s = rs & 15;
+ if (!s) {
+ if (r != 15) break;
+ k += 16;
+ continue;
+ }
+ k += r;
+ if (k > 63) break;
+ int z = zigzag[k++];
+ cols |= (uint64_t)1 << z;
+ c[z] = value(b, s) * q[z];
+ }
+ if (!cols) { /* one colour */
+ uint8_t v = clamp8(((dcv + 16) >> 5) + 128);
+ uint32_t w = v * 0x01010101u;
+ for (int i = 0; i < 16; i++) ((uint32_t *)(void *)out)[i] = w;
+ return;
+ }
+ c[0] = dcv;
+ int32_t ws[64];
+ for (int x = 0; x < 8; x++) { /* columns */
+ int32_t *in = c + x, *o = ws + x;
+#define IN(k) ((cols >> (x + 8 * (k)) & 1) ? in[8 * (k)] : 0)
+ if (!(cols >> 8 & (0x01010101010101ull << x))) {
+ int32_t d = x ? IN(0) : dcv;
+ for (int k = 0; k < 8; k++) o[8 * k] = d;
+ continue;
+ }
+ int32_t t0 = x ? IN(0) : dcv, t1 = IN(2), t2 = IN(4), t3 = IN(6);
+ int32_t t10 = t0 + t2, t11 = t0 - t2, t13 = t1 + t3, t12 = MUL(t1 - t3, FIX_1_414213562) - t13;
+ t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t t4 = IN(1), t5 = IN(3), t6 = IN(5), t7 = IN(7);
+#undef IN
+ int32_t z13 = t6 + t5, z10 = t6 - t5, z11 = t4 + t7, z12 = t4 - t7;
+ t7 = z11 + z13;
+ t11 = MUL(z11 - z13, FIX_1_414213562);
+ int32_t z5 = MUL(z10 + z12, FIX_1_847759065);
+ t10 = MUL(z12, FIX_1_082392200) - z5;
+ t12 = MUL(z10, -FIX_2_613125930) + z5;
+ t6 = t12 - t7, t5 = t11 - t6, t4 = t10 + t5;
+ o[0] = t0 + t7, o[56] = t0 - t7, o[8] = t1 + t6, o[48] = t1 - t6;
+ o[16] = t2 + t5, o[40] = t2 - t5, o[32] = t3 + t4, o[24] = t3 - t4;
+ }
+ for (int y = 0; y < 8; y++) { /* rows: +128 and rounding folded into the first */
+ int32_t *w = ws + 8 * y;
+ uint8_t *o = out + 8 * y;
+ int32_t w0 = w[0] + (128 << 5) + 16;
+ int32_t t10 = w0 + w[4], t11 = w0 - w[4], t13 = w[2] + w[6], t12 = MUL(w[2] - w[6], FIX_1_414213562) - t13;
+ int32_t t0 = t10 + t13, t3 = t10 - t13, t1 = t11 + t12, t2 = t11 - t12;
+ int32_t z13 = w[5] + w[3], z10 = w[5] - w[3], z11 = w[1] + w[7], z12 = w[1] - w[7];
+ int32_t t7 = z11 + z13, t11b = MUL(z11 - z13, FIX_1_414213562), z5 = MUL(z10 + z12, FIX_1_847759065);
+ int32_t t10b = MUL(z12, FIX_1_082392200) - z5, t12b = MUL(z10, -FIX_2_613125930) + z5;
+ int32_t t6 = t12b - t7, t5 = t11b - t6, t4 = t10b + t5;
+ o[0] = clamp8((t0 + t7) >> 5), o[7] = clamp8((t0 - t7) >> 5);
+ o[1] = clamp8((t1 + t6) >> 5), o[6] = clamp8((t1 - t6) >> 5);
+ o[2] = clamp8((t2 + t5) >> 5), o[5] = clamp8((t2 - t5) >> 5);
+ o[4] = clamp8((t3 + t4) >> 5), o[3] = clamp8((t3 - t4) >> 5);
+ }
+}
+
+/* ------------------------------------------------------------------ one square */
+#if defined(__ARM_FEATURE_SAT)
+#include <arm_acle.h>
+#define SAT8(v) __usat(v, 8)
+#else
+#define SAT8(v) ((v) < 0 ? 0 : (v) > 255 ? 255 : (v))
+#endif
+/* a 4 x 4 ordered dither: what is added to red and blue (0 to 7) and green (0 to 3) before they lose bits */
+static const uint8_t dither_rb[4][4] = {{0, 4, 1, 5}, {6, 2, 7, 3}, {1, 5, 0, 4}, {7, 3, 6, 2}};
+static const uint8_t dither_g[4][4] = {{0, 2, 0, 2}, {3, 1, 3, 1}, {0, 2, 0, 2}, {3, 1, 3, 1}};
+
+/* decodes the square at data into dst (16 x 16, rows stride apart) */
+static void square(const uint8_t *data, int qset, uint16_t *dst, int stride) {
+ static Huff h[4];
+ static const uint8_t *loaded;
+ if (loaded != kr_bin) {
+ for (int k = 0; k < 4; k++) h[k] = huff_tab(k);
+ loaded = kr_bin;
+ }
+ const uint16_t *qy = (const uint16_t *)(const void *)(section(SEC_QUANT) + 256 * qset), *qc = qy + 64;
+ uint8_t y[4][64] __attribute__((aligned(4))), cb[64] __attribute__((aligned(4))), cr[64] __attribute__((aligned(4)));
+ Bits b = {data, 0, 0};
+ int pred = 0;
+ for (int k = 0; k < 4; k++) block(&b, &h[0], &h[1], &pred, qy, y[k]);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cb);
+ pred = 0;
+ block(&b, &h[2], &h[3], &pred, qc, cr);
+ for (int rp = 0; rp < 8; rp++) { /* two rows at a time, sharing their colours */
+ int dr[8], dg[8], db[8];
+ for (int c = 0; c < 8; c++) {
+ int u = cb[rp * 8 + c] - 128, v = cr[rp * 8 + c] - 128;
+ dr[c] = (91881 * v + 32768) >> 16;
+ dg[c] = (-22554 * u - 46802 * v + 32768) >> 16;
+ db[c] = (116130 * u + 32768) >> 16;
+ }
+ for (int r = 2 * rp; r < 2 * rp + 2; r++) {
+ const uint8_t *yl = y[(r >> 3) * 2] + (r & 7) * 8, *drb = dither_rb[r & 3], *dgg = dither_g[r & 3];
+ uint16_t *o = dst + r * stride;
+ for (int c = 0; c < 16; c++) {
+ if (c == 8) yl = y[(r >> 3) * 2 + 1] + (r & 7) * 8;
+ int l = yl[c & 7], k = c >> 1;
+ int R = SAT8(l + dr[k] + drb[c & 3]), G = SAT8(l + dg[k] + dgg[c & 3]), B = SAT8(l + db[k] + drb[(c + 2) & 3]);
+ o[c] = (uint16_t)((R & 0xF8) << 8 | (G & 0xFC) << 3 | B >> 3);
+ }
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ pictures */
+typedef struct {
+ int mw, mh, q;
+ const uint8_t *table, *base_table; /* base_table: the picture whose squares it shares, or NULL */
+ int count; /* its own squares then */
+} Info;
+
+static Info info(int id) {
+ const uint8_t *p = section(SEC_PICS) + 12 * id, *t = section(SEC_TABLE);
+ Info i = {p[0], p[1], p[2], t + rd32(p + 8), NULL, (int)rd16(p + 6)};
+ uint32_t base = rd16(p + 4);
+ if (base != 0xFFFF) i.base_table = t + rd32(section(SEC_PICS) + 12 * base + 8);
+ return i;
+}
+
+static uint32_t square_at(const Info *i, int k) {
+ if (!i->base_table) return rd24(i->table + 3 * k);
+ int lo = 0, hi = i->count - 1;
+ while (lo <= hi) {
+ int mid = (lo + hi) >> 1, mk = (int)rd16(i->table + 5 * mid);
+ if (mk == k) return rd24(i->table + 5 * mid + 2);
+ if (mk < k) lo = mid + 1;
+ else hi = mid - 1;
+ }
+ return rd24(i->base_table + 3 * k);
+}
+
+int pic_w(int id) { return 16 * section(SEC_PICS)[12 * id]; }
+int pic_h(int id) { return 16 * section(SEC_PICS)[12 * id + 1]; }
+
+void pic_part(int id, int x, int y, int sx, int sy, int w, int h) {
+ Info in = info(id);
+ /* clip to the screen, the band and the picture */
+ int x0 = x > 0 ? x : 0, x1 = x + w < SCREEN_W ? x + w : SCREEN_W;
+ int y0 = y > gfx_y0 ? y : gfx_y0, y1 = y + h < gfx_y0 + BAND_H ? y + h : gfx_y0 + BAND_H;
+ if (x0 >= x1 || y0 >= y1) return;
+ const uint8_t *bank = section(SEC_BANK);
+ uint16_t px[256];
+ /* in the picture: rows y0 - y + sy to y1 - y + sy, columns likewise */
+ int pr0 = y0 - y + sy, pr1 = y1 - y + sy, pc0 = x0 - x + sx, pc1 = x1 - x + sx;
+ for (int my = pr0 >> 4; my <= (pr1 - 1) >> 4 && my < in.mh; my++)
+ for (int mx = pc0 >> 4; mx <= (pc1 - 1) >> 4 && mx < in.mw; mx++) {
+ const uint8_t *data = bank + square_at(&in, my * in.mw + mx);
+ int r0 = my * 16 > pr0 ? my * 16 : pr0, r1 = my * 16 + 16 < pr1 ? my * 16 + 16 : pr1;
+ int c0 = mx * 16 > pc0 ? mx * 16 : pc0, c1 = mx * 16 + 16 < pc1 ? mx * 16 + 16 : pc1;
+ if (r1 - r0 == 16 && c1 - c0 == 16) { /* all of it shows: straight into the band */
+ square(data, in.q, gfx_band + (r0 - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x), SCREEN_W);
+ continue;
+ }
+ square(data, in.q, px, 16);
+ for (int r = r0; r < r1; r++) {
+ uint16_t *d = gfx_band + (r - sy + y - gfx_y0) * SCREEN_W + (c0 - sx + x);
+ const uint16_t *s = px + (r - my * 16) * 16 + (c0 - mx * 16);
+ for (int c = c0; c < c1; c++) *d++ = *s++;
+ }
+ }
+}
+
+void pic_draw(int id, int x, int y) { pic_part(id, x, y, 0, 0, pic_w(id), pic_h(id)); }
+
+/* ------------------------------------------------------------------ the terrain, a byte a pixel */
+static uint8_t *bg_mem;
+static int bg_w, bg_h;
+static uint16_t bg_pal[256], bg_pal_dim[256];
+static bool bg_dark;
+
+void bg_load(int id, uint8_t *mem) {
+ Info in = info(id);
+ bg_mem = mem, bg_w = in.mw * 16, bg_h = in.mh * 16;
+ const uint8_t *pal = section(SEC_BGPAL) + 512 * id;
+ for (int i = 0; i < 256; i++) {
+ bg_pal[i] = (uint16_t)rd16(pal + 2 * i);
+ bg_pal_dim[i] = gfx_mix(BLACK, bg_pal[i], 14);
+ }
+ /* the nearest of the 256 colours for each colour of 12 bits */
+ static uint8_t near[4096];
+ int16_t pr[256], pg[256], pb[256];
+ for (int i = 0; i < 256; i++)
+ pr[i] = (int16_t)((bg_pal[i] >> 11) * 255 / 31), pg[i] = (int16_t)((bg_pal[i] >> 5 & 63) * 255 / 63),
+ pb[i] = (int16_t)((bg_pal[i] & 31) * 255 / 31);
+ for (int c = 0; c < 4096; c++) {
+ int r = (c >> 8) * 17, g = (c >> 4 & 15) * 17, b = (c & 15) * 17, best = 0, bd = 1 << 30;
+ for (int i = 0; i < 256; i++) {
+ int d = 2 * (r - pr[i]) * (r - pr[i]) + 4 * (g - pg[i]) * (g - pg[i]) + 3 * (b - pb[i]) * (b - pb[i]);
+ if (d < bd) bd = d, best = i;
+ }
+ near[c] = (uint8_t)best;
+ }
+ const uint8_t *bank = section(SEC_BANK);
+ uint16_t px[256];
+ for (int my = 0; my < in.mh; my++)
+ for (int mx = 0; mx < in.mw; mx++) {
+ square(bank + square_at(&in, my * in.mw + mx), in.q, px, 16);
+ for (int r = 0; r < 16; r++) {
+ uint8_t *d = mem + (my * 16 + r) * bg_w + mx * 16;
+ for (int c = 0; c < 16; c++) {
+ uint16_t v = px[r * 16 + c];
+ d[c] = near[(v >> 12) << 8 | (v >> 7 & 15) << 4 | (v >> 1 & 15)];
+ }
+ }
+ }
+}
+
+void bg_dim(bool dim) { bg_dark = dim; }
+
+void bg_draw(int x, int y) {
+ int y0 = gfx_y0 > y ? gfx_y0 : y, y1 = gfx_y0 + BAND_H < y + bg_h ? gfx_y0 + BAND_H : y + bg_h;
+ int x0 = x > 0 ? x : 0, x1 = x + bg_w < SCREEN_W ? x + bg_w : SCREEN_W;
+ const uint16_t *pal = bg_dark ? bg_pal_dim : bg_pal;
+ for (int sy = y0; sy < y1; sy++) {
+ const uint8_t *s = bg_mem + (sy - y) * bg_w + (x0 - x);
+ uint16_t *d = gfx_band + (sy - gfx_y0) * SCREEN_W + x0;
+ for (int k = x1 - x0; k > 0; k--) *d++ = pal[*s++];
+ }
+}
diff --git a/games/kingdomrush/src/plat.h b/games/kingdomrush/src/plat.h
new file mode 100644
index 00000000..f0a3cf95
--- /dev/null
+++ b/games/kingdomrush/src/plat.h
@@ -0,0 +1,42 @@
+/* Kingdom Rush: 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/rules.c). */
+#ifndef KR_PLAT_H
+#define KR_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 */
+ K_BACK = 1 << 5, /* Back: pause, or close a menu */
+ K_HOME = 1 << 6, /* Home, On/Off: save and quit */
+ K_DEL = 1 << 7, /* backspace (clear): call the next wave */
+ K_0 = 1 << 8, /* the digits: K_0 << n */
+ K_EXE = 1 << 18, /* EXE: as OK */
+ K_ANY = 1 << 19
+};
+#define K_DIGIT(n) (K_0 << (n))
+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);
+#endif
diff --git a/games/kingdomrush/src/plat_eadk.c b/games/kingdomrush/src/plat_eadk.c
new file mode 100644
index 00000000..52991778
--- /dev/null
+++ b/games/kingdomrush/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_zero, 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};
+ 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)) r |= K_OK;
+ if (k & KEY(eadk_key_exe)) r |= K_EXE;
+ if (k & KEY(eadk_key_back)) r |= K_BACK;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k & KEY(eadk_key_backspace)) r |= K_DEL;
+ for (int i = 0; i < 10; i++)
+ if (k & KEY(digits[i])) r |= K_DIGIT(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/kingdomrush/src/plat_host.c b/games/kingdomrush/src/plat_host.c
new file mode 100644
index 00000000..f3f5a8c5
--- /dev/null
+++ b/games/kingdomrush/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/kingdomrush/src/play.c b/games/kingdomrush/src/play.c
new file mode 100644
index 00000000..fa978afe
--- /dev/null
+++ b/games/kingdomrush/src/play.c
@@ -0,0 +1,578 @@
+/* The battle screen: the battlefield at 0.4 of the game's size on the right, the counts and spells on the left.
+ *
+ * Keys: the arrows hop between build spots, the wave flags and the enemies; OK opens the tower menu around a
+ * spot (its items hop with the arrows, OK buys); 1 and 2 aim the rain of fire and the reinforcements (a cross
+ * the arrows move, OK drops it); backspace calls the next wave early; Back pauses. */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "kr.h"
+#include "settings.h"
+#include "special.h"
+#include "ui.h"
+#include "anim.h"
+#include "strings.h"
+
+#define MAP_X 40
+#define SX(x) (MAP_X + (int)lroundf((x) * 0.4f))
+#define SY(y) ((int)lroundf((y) * 0.4f))
+
+static uint8_t bg_mem[288 * 240];
+
+enum { M_SELECT, M_RING, M_AIM, M_PAUSE, M_NOTE, M_RESULT, M_QUIT };
+enum { AIM_FIRE, AIM_REINF, AIM_RALLY };
+enum { SEL_SPOT, SEL_FLAG, SEL_ENEMY };
+
+static struct {
+ uint8_t mode, aim, sel_kind, ring_sel, nring, pause_sel, result_sel;
+ int16_t sel; /* the spot, flag or enemy */
+ float cx, cy; /* the cursor (the game's coordinates) */
+ RingItem ring[6];
+ int16_t aim_spot;
+ int16_t msg_t;
+ char msg[48];
+ uint8_t note;
+ int16_t result_t;
+ uint8_t level, bmode;
+ uint8_t saved;
+} P;
+
+/* ------------------------------------------------------------------ start */
+void play_start(int level, int mode) {
+ memset(&P, 0, sizeof P);
+ P.level = (uint8_t)level, P.bmode = (uint8_t)mode;
+ memcpy(upgrades, g.p.ups, sizeof upgrades);
+ enemy_health_pct = g.p.difficulty == 0 ? 80 : g.p.difficulty == 2 ? 120 : 100;
+ battle_seed = g.ticks * 2654435761u;
+ battle_start(level, mode);
+ bg_load(PIC_LEVEL1 + level, bg_mem);
+ bg_dim(false);
+ P.mode = M_SELECT, P.sel_kind = SEL_SPOT, P.sel = 0;
+ /* start at the spot nearest the middle */
+ float best = 1e9f;
+ for (int s = 0; s < B.nspots; s++) {
+ float dx = B.spot[s].x - 350, dy = B.spot[s].y - 300, d = dx * dx + dy * dy;
+ if (B.spot[s].kind != 0xFF && d < best) best = d, P.sel = (int16_t)s;
+ }
+ g.screen = SCR_BATTLE;
+}
+
+/* ------------------------------------------------------------------ the selection */
+static Pt sel_pos(void) {
+ if (P.sel_kind == SEL_SPOT) return (Pt){B.spot[P.sel].x, B.spot[P.sel].y - 20};
+ if (P.sel_kind == SEL_FLAG) return B.flag[P.sel];
+ Enemy *e = EN(P.sel);
+ if (e) return (Pt){e->x, e->y + enemy_stats[e->type].y_adj};
+ return (Pt){350, 300};
+}
+
+static void fix_selection(void) {
+ if (P.sel_kind == SEL_ENEMY && (!EN(P.sel) || B.en[P.sel].dead || !B.en[P.sel].active)) {
+ /* the enemy is gone: the nearest spot */
+ Pt at = {P.cx, P.cy};
+ float best = 1e9f;
+ P.sel_kind = SEL_SPOT;
+ for (int s = 0; s < B.nspots; s++) {
+ float dx = B.spot[s].x - at.x, dy = B.spot[s].y - 20 - at.y, d = dx * dx + dy * dy;
+ if (B.spot[s].kind != 0xFF && d < best) best = d, P.sel = (int16_t)s;
+ }
+ }
+ if (P.sel_kind == SEL_FLAG && (!B.flags_up || !B.flag_path[P.sel])) P.sel_kind = SEL_SPOT, P.sel = 0;
+ Pt p = sel_pos();
+ P.cx = p.x, P.cy = p.y;
+}
+
+/* the candidate nearest in a direction: along it counts once, across it twice */
+static void hop(int dx, int dy) {
+ Pt at = sel_pos();
+ float best = 1e9f;
+ int bk = -1, bi = -1;
+ for (int kind = 0; kind < 3; kind++) {
+ int n = kind == SEL_SPOT ? B.nspots : kind == SEL_FLAG ? B.nflags : MAX_ENEMIES;
+ for (int i = 0; i < n; i++) {
+ Pt p;
+ if (kind == SEL_SPOT) {
+ if (B.spot[i].kind == 0xFF) continue;
+ p = (Pt){B.spot[i].x, B.spot[i].y - 20};
+ } else if (kind == SEL_FLAG) {
+ if (!B.flags_up || i >= MAX_PATHS || !B.flag_path[i]) continue;
+ p = B.flag[i];
+ } else {
+ Enemy *e = &B.en[i];
+ if (!e->alive || e->dead || !e->active) continue;
+ p = (Pt){e->x, e->y + enemy_stats[e->type].y_adj};
+ }
+ if (kind == P.sel_kind && i == P.sel) continue;
+ float vx = p.x - at.x, vy = p.y - at.y;
+ float along = vx * dx + vy * dy, across = fabsf(vx * dy - vy * dx);
+ if (along <= 4) continue;
+ float score = along + 2 * across;
+ if (kind == SEL_ENEMY) score += 25; /* (the spots come first when close) */
+ if (score < best) best = score, bk = kind, bi = i;
+ }
+ }
+ if (bk >= 0) P.sel_kind = (uint8_t)bk, P.sel = (int16_t)bi;
+}
+
+/* ------------------------------------------------------------------ messages */
+static void say(const char *s) {
+ snprintf(P.msg, sizeof P.msg, "%s", s);
+ P.msg_t = 75;
+}
+
+/* ------------------------------------------------------------------ the ring */
+static void open_ring(void) {
+ P.nring = (uint8_t)ring_items(P.sel, P.ring);
+ if (!P.nring) return;
+ P.mode = M_RING;
+ /* the first one you can afford, or the first */
+ P.ring_sel = 0;
+ for (int i = 0; i < P.nring; i++)
+ if (P.ring[i].cost >= 0 && P.ring[i].cost <= B.cash && !P.ring[i].locked) {
+ P.ring_sel = (uint8_t)i;
+ break;
+ }
+}
+
+static void ring_hop(int dx, int dy) {
+ RingItem *c = &P.ring[P.ring_sel];
+ float best = 1e9f;
+ int bi = -1;
+ for (int i = 0; i < P.nring; i++) {
+ if (i == P.ring_sel) continue;
+ float vx = (float)(P.ring[i].x - c->x), vy = (float)(P.ring[i].y - c->y);
+ float along = vx * dx + vy * dy, across = fabsf(vx * dy - vy * dx);
+ if (along <= 0) continue;
+ float score = along + 2 * across;
+ if (score < best) best = score, bi = i;
+ }
+ if (bi >= 0) P.ring_sel = (uint8_t)bi;
+}
+
+static void ring_do(void) {
+ RingItem *it = &P.ring[P.ring_sel];
+ int s = P.sel;
+ if (it->locked) {
+ say("Not yet: it comes in a later stage");
+ return;
+ }
+ if (it->action == RA_RALLY) {
+ P.mode = M_AIM, P.aim = AIM_RALLY, P.aim_spot = (int16_t)s;
+ Spot *t = &B.spot[s];
+ if (t->kind == TW_SORCERER) {
+ Soldier *el = SO(t->elemental);
+ P.cx = el ? el->rx : t->rally.x, P.cy = el ? el->ry : t->rally.y;
+ } else
+ P.cx = t->rally.x, P.cy = t->rally.y;
+ return;
+ }
+ if (it->action == RA_SELL) {
+ spot_sell(s);
+ P.mode = M_SELECT;
+ return;
+ }
+ if (it->cost > B.cash) {
+ say("Not enough gold");
+ return;
+ }
+ if (it->action >= RA_ARCHER && it->action <= RA_ENGINEER) spot_build(s, (int[]){TW_ARCHER, TW_BARRACKS, TW_MAGE, TW_ENGINEER}[it->action - RA_ARCHER]);
+ else if (it->action == RA_UPGRADE) spot_upgrade(s, 0);
+ else if (it->action == RA_SPECIAL1) spot_upgrade(s, 1);
+ else if (it->action == RA_SPECIAL2) spot_upgrade(s, 2);
+ else if (it->action >= RA_ABILITY0) spot_buy_ability(s, it->action - RA_ABILITY0);
+ /* abilities keep the menu open, as the game's (closeOnExcec false) */
+ if (it->action >= RA_ABILITY0) {
+ P.nring = (uint8_t)ring_items(s, P.ring);
+ return;
+ }
+ P.mode = M_SELECT;
+}
+
+/* ------------------------------------------------------------------ the end */
+static void finish(bool won) {
+ P.mode = M_RESULT, P.result_t = 0, P.result_sel = 0;
+ if (won && !P.saved) {
+ int l = P.level;
+ if (P.bmode == MODE_CAMPAIGN) {
+ int st = battle_stars();
+ if (st > g.p.camp[l]) g.p.camp[l] = (uint8_t)st;
+ } else if (P.bmode == MODE_HEROIC)
+ g.p.heroic[l] = 1;
+ else
+ g.p.iron[l] = 1;
+ save_progress();
+ P.saved = 1;
+ }
+}
+
+/* ------------------------------------------------------------------ a step */
+static void aim_move(int dx, int dy) {
+ P.cx += dx * 15.0f, P.cy += dy * 15.0f;
+ if (P.cx < 0) P.cx = 0;
+ if (P.cx > 699) P.cx = 699;
+ if (P.cy < 0) P.cy = 0;
+ if (P.cy > 599) P.cy = 599;
+}
+
+static void start_aim(int which) {
+ if (which == AIM_FIRE ? power_fire_cooldown() != 0 : power_reinf_cooldown() != 0) {
+ int cd = which == AIM_FIRE ? power_fire_cooldown() : power_reinf_cooldown();
+ say(cd < 0 ? "Not yet: it comes with the first wave" : "Still recharging");
+ return;
+ }
+ P.mode = M_AIM, P.aim = (uint8_t)which;
+ Pt p = sel_pos();
+ /* aim at the enemy furthest along, or where the selection is */
+ int best = -1;
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive || !e->active || e->dead) continue;
+ if (best < 0 || path_len(e->path, e->lane) - e->node < path_len(B.en[best].path, B.en[best].lane) - B.en[best].node) best = i;
+ }
+ if (best >= 0) p = (Pt){B.en[best].x, B.en[best].y};
+ P.cx = p.x, P.cy = p.y;
+}
+
+static int dir_key(int *dx, int *dy) {
+ *dx = *dy = 0;
+ if (play_key(K_LEFT)) *dx = -1;
+ else if (play_key(K_RIGHT)) *dx = 1;
+ else if (play_key(K_UP)) *dy = -1;
+ else if (play_key(K_DOWN)) *dy = 1;
+ return *dx || *dy;
+}
+
+void play_step(void) {
+ uint32_t pr = g.pressed;
+ bool ok = pr & (K_OK | K_EXE);
+ int dx, dy;
+ if (P.msg_t) P.msg_t--;
+ switch (P.mode) {
+ case M_SELECT:
+ case M_RING:
+ case M_AIM:
+ if (pr & K_BACK) {
+ if (P.mode == M_SELECT) P.mode = M_PAUSE, P.pause_sel = 0;
+ else P.mode = M_SELECT;
+ return;
+ }
+ if (pr & K_DIGIT(1)) start_aim(AIM_FIRE);
+ else if (pr & K_DIGIT(2)) start_aim(AIM_REINF);
+ else if (pr & (K_DEL | K_DIGIT(3))) {
+ if (battle_call_wave()) P.mode = P.mode == M_RING ? M_SELECT : P.mode;
+ else if (B.state == LS_NORMAL) say("The next wave isn't ready");
+ }
+ if (P.mode == M_SELECT) {
+ if (dir_key(&dx, &dy)) hop(dx, dy);
+ fix_selection();
+ if (ok) {
+ if (P.sel_kind == SEL_SPOT) {
+ Spot *t = &B.spot[P.sel];
+ if (t->ice == 2) { /* J.T.'s ice: three hits */
+ if (++t->ice_hits >= 3) t->ice = 3, t->ice_t = 0;
+ } else if (!t->disabled && !t->building)
+ open_ring();
+ } else if (P.sel_kind == SEL_FLAG)
+ battle_call_wave();
+ }
+ } else if (P.mode == M_RING) {
+ if (dir_key(&dx, &dy)) ring_hop(dx, dy);
+ if (ok) ring_do();
+ if (B.spot[P.sel].kind == 0xFF || B.spot[P.sel].disabled) P.mode = M_SELECT;
+ } else if (P.mode == M_AIM) {
+ if (dir_key(&dx, &dy)) aim_move(dx, dy);
+ if (ok) {
+ Pt at = {P.cx, P.cy};
+ if (P.aim == AIM_FIRE) {
+ power_fire(at);
+ P.mode = M_SELECT;
+ } else if (P.aim == AIM_REINF) {
+ if (power_reinforce(at)) P.mode = M_SELECT;
+ else say("Put them on a road");
+ } else {
+ if (spot_rally_ok(P.aim_spot, at)) {
+ spot_rally(P.aim_spot, at);
+ P.mode = M_SELECT;
+ } else
+ say("On a road, near the tower");
+ }
+ }
+ }
+ break;
+ case M_PAUSE:
+ if (pr & K_BACK) P.mode = M_SELECT;
+ if (play_key(K_UP)) P.pause_sel = (uint8_t)((P.pause_sel + 3) % 4);
+ if (play_key(K_DOWN)) P.pause_sel = (uint8_t)((P.pause_sel + 1) % 4);
+ if (ok) {
+ if (P.pause_sel == 0) P.mode = M_SELECT;
+ else if (P.pause_sel == 1) play_start(P.level, P.bmode);
+ else if (P.pause_sel == 2) g.screen = SCR_HELP;
+ else P.mode = M_QUIT, P.pause_sel = 1;
+ }
+ return;
+ case M_QUIT:
+ if (play_key(K_LEFT) || play_key(K_RIGHT)) P.pause_sel ^= 1;
+ if (pr & K_BACK) P.mode = M_PAUSE, P.pause_sel = 3;
+ if (ok) {
+ if (P.pause_sel == 0) g.screen = SCR_MAP;
+ else P.mode = M_PAUSE, P.pause_sel = 3;
+ }
+ return;
+ case M_NOTE:
+ if (ok || (pr & K_BACK)) P.mode = M_SELECT;
+ return;
+ case M_RESULT:
+ P.result_t++;
+ if (play_key(K_LEFT) || play_key(K_RIGHT)) P.result_sel ^= 1;
+ if (ok && P.result_t > 20) {
+ if (P.result_sel == 0 && B.state == LS_WIN) g.screen = SCR_MAP;
+ else if (P.result_sel == 0) play_start(P.level, P.bmode);
+ else if (B.state == LS_WIN) play_start(P.level, P.bmode);
+ else g.screen = SCR_MAP;
+ }
+ return;
+ }
+ if (P.mode == M_PAUSE || P.mode == M_QUIT) return;
+ battle_step();
+ eggs_step();
+ if (B.pending_note) {
+ int n = B.pending_note;
+ B.pending_note = 0;
+ if (!(g.p.seen_note[n >> 3] & (1 << (n & 7))) && note_text(n)) {
+ g.p.seen_note[n >> 3] = (uint8_t)(g.p.seen_note[n >> 3] | 1 << (n & 7));
+ P.note = (uint8_t)n, P.mode = M_NOTE;
+ }
+ }
+ if (B.state == LS_WIN) finish(true);
+ else if (B.state == LS_OVER) finish(false);
+}
+
+/* ------------------------------------------------------------------ drawing */
+static uint8_t terrain(void) { return P.level >= 9 ? 2 : P.level >= 6 ? 1 : 0; }
+
+typedef struct {
+ int16_t y;
+ uint8_t kind;
+ uint8_t i;
+} Item;
+enum { IT_SPOT, IT_ENEMY, IT_SOLDIER, IT_FX };
+static Item items[MAX_SPOTS + MAX_ENEMIES + MAX_SOLDIERS + MAX_FX];
+static int nitems;
+
+static void collect(void) {
+ nitems = 0;
+ for (int s = 0; s < B.nspots; s++)
+ if (B.spot[s].kind != 0xFF) items[nitems++] = (Item){B.spot[s].y, IT_SPOT, (uint8_t)s};
+ for (int i = 0; i < MAX_ENEMIES; i++)
+ if (B.en[i].alive) items[nitems++] = (Item){(int16_t)B.en[i].y, IT_ENEMY, (uint8_t)i};
+ for (int i = 0; i < MAX_SOLDIERS; i++)
+ if (B.so[i].alive && !B.so[i].hidden) items[nitems++] = (Item){(int16_t)B.so[i].y, IT_SOLDIER, (uint8_t)i};
+ for (int i = 0; i < MAX_FX; i++)
+ if (B.fx[i].alive && !B.fx[i].decal && B.fx[i].anim != 0xFFFF) items[nitems++] = (Item){(int16_t)B.fx[i].y, IT_FX, (uint8_t)i};
+ for (int i = 1; i < nitems; i++) { /* by y, as the game sorts its entities */
+ Item k = items[i];
+ int j = i - 1;
+ while (j >= 0 && items[j].y > k.y) items[j + 1] = items[j], j--;
+ items[j + 1] = k;
+ }
+}
+
+static void draw_bar(int x, int y, int w, int v, int max) {
+ if (max <= 0) return;
+ int f = v * w / max;
+ if (f < 0) f = 0;
+ if (v > 0 && f == 0) f = 1;
+ gfx_fill(x - 1, y - 1, w + 2, 4, RGB(0x1A0F08));
+ gfx_fill(x, y, w, 2, RGB(0xC62020));
+ gfx_fill(x, y, f, 2, RGB(0x46D23C));
+}
+
+static void draw_enemy(Enemy *e) {
+ int x = SX(e->x), y = SY(e->y);
+ if (e->teleporting) {
+ spr_anim(AN_FX_TELEPORT, e->teleport_t, false, x, y, false);
+ return;
+ }
+ spr_anim(e->anim, e->anim_t, !e->dead, x, y, e->left);
+ if (e->sp_state == 9) gfx_ellipse(x, y - 5, 6, 7, RGB(0xF0A030), 20); /* a demon lord's shield */
+ if (e->thorned) gfx_ellipse(x, y, 5, 2, RGB(0x6EB43C), 32);
+ if (e->dead || !e->active) return;
+ const EnemyStat *s = &enemy_stats[e->type];
+ if (e->health < e->init_health) {
+ int w = s->bar_w == 2 ? 24 : s->bar_w == 1 ? 14 : 9;
+ draw_bar(x - w / 2, SY(e->y + s->bar_y), w, e->health, e->init_health);
+ }
+}
+
+static void draw_soldier(Soldier *so) {
+ int x = SX(so->x), y = SY(so->y);
+ spr_anim(so->anim, so->anim_t, so->walking || so->idle, x, y, so->left);
+ if (so->active && so->health < so->init_health) draw_bar(x - 4, y - 9, 9, so->health, so->init_health);
+}
+
+static void draw_spot(int s) {
+ Spot *t = &B.spot[s];
+ int x = SX(t->x), y = SY(t->y);
+ if (t->kind == TW_NONE) {
+ spr_anim(AN_T_HOLDER_FOREST + terrain(), 0, false, x, SY(t->y - 36), false);
+ return;
+ }
+ draw_tower(t, x, y);
+ if (t->building) draw_bar(x - 7, SY(t->y - 45), 14, 30 - t->building, 30);
+ if (t->ice) {
+ int an = t->ice == 1 ? AN_B_ICEBLOCK_START : t->ice == 2 ? AN_B_ICEBLOCK_IDLE : AN_B_ICEBLOCK_END;
+ spr_anim(an, t->ice == 2 ? 0 : t->ice_t, false, x, y, false);
+ }
+}
+
+static void draw_bullets(void) {
+ for (int i = 0; i < MAX_BULLETS; i++) {
+ Bullet *b = &B.bu[i];
+ if (!b->alive) continue;
+ draw_bullet(b, SX(b->x), SY(b->y));
+ }
+}
+
+static void draw_fx(Fx *f) {
+ int x = SX(f->x), y = SY(f->y);
+ if (f->anim == 0xFFFF) { /* gold: "+15" rising */
+ char s[12];
+ snprintf(s, sizeof s, "+%d", f->value);
+ gfx_text_oc(FONT_SMALL, x, y - f->t / 3 - 8, s, RGB(0xFFD32A));
+ return;
+ }
+ spr_anim(f->anim, f->t, false, x, y, f->flip);
+}
+
+static void draw_range(Pt c, int w, uint16_t col) {
+ gfx_ellipse(SX(c.x), SY(c.y), (int)lroundf(w * 0.2f), (int)lroundf(w * RANGE_RATIO * 0.2f), col, 24);
+}
+
+static void draw_field(void) {
+ bg_draw(MAP_X, 0);
+ /* the decals: tower bases, blood, craters, arrows in the ground, eggs */
+ for (int s = 0; s < B.nspots; s++) draw_base(&B.spot[s], SX(B.spot[s].x), SY(B.spot[s].y), terrain());
+ for (int i = 0; i < MAX_FX; i++)
+ if (B.fx[i].alive && B.fx[i].decal) draw_fx(&B.fx[i]);
+ for (int i = 0; i < (int)(sizeof B.egg / sizeof B.egg[0]); i++)
+ if (B.egg[i].on)
+ spr_anim(B.egg[i].on == 2 ? AN_B_JUGGERNAUTEGG_START : AN_B_SPIDEREGG, B.egg[i].t, false, SX(B.egg[i].x), SY(B.egg[i].y), false);
+ /* the selected spot's range */
+ if ((P.mode == M_SELECT || P.mode == M_RING) && P.sel_kind == SEL_SPOT) {
+ Spot *t = &B.spot[P.sel];
+ if (t->kind != TW_NONE && t->kind != 0xFF && !t->building)
+ draw_range((Pt){t->x, t->y - 10}, tower_range(t->kind, t->level), RGB(0xFFFFFF));
+ }
+ if (P.mode == M_RING && P.ring[P.ring_sel].range)
+ draw_range((Pt){B.spot[P.sel].x, B.spot[P.sel].y - 10}, P.ring[P.ring_sel].range, RGB(0x9CF080));
+ for (int k = 0; k < nitems; k++) {
+ Item *it = &items[k];
+ if (SY(it->y) < gfx_y0 - 60 || SY(it->y) > gfx_y0 + BAND_H + 60) continue;
+ switch (it->kind) {
+ case IT_SPOT: draw_spot(it->i); break;
+ case IT_ENEMY: draw_enemy(&B.en[it->i]); break;
+ case IT_SOLDIER: draw_soldier(&B.so[it->i]); break;
+ default: draw_fx(&B.fx[it->i]);
+ }
+ }
+ draw_bullets();
+ for (int i = 0; i < MAX_FX; i++)
+ if (B.fx[i].alive && B.fx[i].anim == 0xFFFF) draw_fx(&B.fx[i]);
+ /* the wave flags at the roads' starts */
+ if (B.flags_up && B.state == LS_NORMAL)
+ for (int p = 0; p < B.nflags && p < MAX_PATHS; p++) {
+ if (!B.flag_path[p]) continue;
+ int x = SX(B.flag[p].x), y = SY(B.flag[p].y);
+ draw_wave_flag(x, y, B.flag_path[p] == 2, B.frame, P.sel_kind == SEL_FLAG && P.sel == p && P.mode == M_SELECT);
+ }
+}
+
+static void draw_selection(void) {
+ if (P.mode == M_SELECT) {
+ Pt p = sel_pos();
+ int x = SX(p.x), y = SY(p.y);
+ if (P.sel_kind == SEL_SPOT) {
+ Spot *t = &B.spot[P.sel];
+ int ty = SY(t->y - (t->kind == TW_NONE ? 36 : 18));
+ int w = t->kind == TW_NONE ? 14 : 15, h = t->kind == TW_NONE ? 7 : 14;
+ gfx_ellipse(SX(t->x), ty, w, h, RGB(0xFFE14D), 32);
+ gfx_ellipse(SX(t->x), ty, w + 1, h + 1, RGB(0x6A4A00), 32);
+ } else if (P.sel_kind == SEL_ENEMY) {
+ Enemy *e = EN(P.sel);
+ if (e) {
+ gfx_ellipse(x, SY(e->y), 7, 3, RGB(0xFF4A3A), 32);
+ gfx_ellipse(x, SY(e->y), 8, 4, RGB(0x500000), 32);
+ }
+ }
+ } else if (P.mode == M_RING)
+ draw_ring(P.ring, P.nring, P.ring_sel, SX(B.spot[P.sel].x), SY(B.spot[P.sel].y - 25), B.cash);
+ else if (P.mode == M_AIM) {
+ int x = SX(P.cx), y = SY(P.cy);
+ Pt at = {P.cx, P.cy};
+ bool good = P.aim == AIM_FIRE || (P.aim == AIM_REINF ? power_reinforce_ok(at) : spot_rally_ok(P.aim_spot, at));
+ if (P.aim == AIM_FIRE) {
+ int lo, hi, r = S_powers_fireball_range;
+ (void)lo, (void)hi;
+ if (up_on(UP_RAIN, 3)) r += r / 4;
+ draw_range(at, r, RGB(0xFF7A2A));
+ }
+ if (P.aim == AIM_RALLY) {
+ Spot *t = &B.spot[P.aim_spot];
+ int r = t->kind == TW_SORCERER ? S_mages_sorcerer_elementalRallyRange : barrack_stat(TW_BARRACKS, 1).rally;
+ draw_range((Pt){t->x, t->y - 10}, r, RGB(0xFFFFFF));
+ }
+ uint16_t c = good ? RGB(0xFFE14D) : RGB(0xFF3030);
+ gfx_fill(x - 6, y, 13, 1, c);
+ gfx_fill(x, y - 6, 1, 13, c);
+ gfx_ellipse(x, y, 4, 4, c, 32);
+ }
+}
+
+static void draw_side(void) {
+ draw_sidebar(P.mode == M_AIM ? (P.aim == AIM_FIRE ? 1 : P.aim == AIM_REINF ? 2 : 0) : 0);
+ /* what is selected: an enemy's life and armour, a tower's numbers */
+ if (P.mode == M_SELECT && P.sel_kind == SEL_ENEMY && EN(P.sel)) draw_enemy_info(EN(P.sel));
+ else if (P.mode == M_SELECT && P.sel_kind == SEL_SPOT) draw_spot_info(&B.spot[P.sel]);
+}
+
+static void draw_keys(void) {
+ const char *k;
+ switch (P.mode) {
+ case M_RING: k = P.ring[P.ring_sel].name; break;
+ case M_AIM: k = P.aim == AIM_RALLY ? "Arrows move OK set rally point Back cancel" : "Arrows aim OK cast Back cancel"; break;
+ default:
+ if (P.sel_kind == SEL_FLAG) k = "OK call the wave now (gold for it)";
+ else if (P.sel_kind == SEL_SPOT && B.spot[P.sel].ice == 2) k = "OK break the ice (3 hits)";
+ else if (P.sel_kind == SEL_SPOT && B.spot[P.sel].kind == TW_NONE) k = "OK build 1 fire 2 soldiers Back pause";
+ else k = "OK tower menu 1 fire 2 soldiers Back pause";
+ }
+ draw_key_line(MAP_X, k, P.mode == M_RING ? &P.ring[P.ring_sel] : 0, B.cash);
+ if (P.msg_t) {
+ int w = gfx_text_w(FONT_SMALL, P.msg) + 10;
+ int x = MAP_X + 140 - w / 2;
+ gfx_panel(x, 98, w, 15, RGB(0x2A1A0C), RGB(0xE0B040));
+ gfx_text_c(FONT_SMALL, MAP_X + 140, 100, P.msg, WHITE);
+ }
+}
+
+static void draw_band(void) {
+ draw_field();
+ draw_selection();
+ draw_side();
+ if (P.mode == M_SELECT || P.mode == M_RING || P.mode == M_AIM) draw_keys();
+ if (B.state == LS_STARTING) gfx_blend(MAP_X, 0, 280, 240, BLACK, 16 - B.start_t / 2);
+ switch (P.mode) {
+ case M_PAUSE: draw_pause(P.pause_sel); break;
+ case M_QUIT: draw_quit(P.pause_sel); break;
+ case M_NOTE: draw_note(P.note); break;
+ case M_RESULT: draw_result(B.state == LS_WIN, battle_stars(), P.bmode, P.result_sel, P.result_t); break;
+ }
+}
+
+void play_draw(void) {
+ collect();
+ bg_dim(P.mode == M_PAUSE || P.mode == M_QUIT || P.mode == M_NOTE || (P.mode == M_RESULT && P.result_t > 10));
+ gfx_frame(draw_band);
+}
diff --git a/games/kingdomrush/src/power.c b/games/kingdomrush/src/power.c
new file mode 100644
index 00000000..c7487dd1
--- /dev/null
+++ b/games/kingdomrush/src/power.c
@@ -0,0 +1,131 @@
+/* The spells (PowerFireball, PowerReinforcement, FireballControler, the reinforcements' pointers). */
+#include <math.h>
+#include "kr.h"
+#include "settings.h"
+
+/* the rain of fire's numbers, with the upgrades (GameSettings.§_-Gm§) */
+static int fire_reload(void) {
+ int cd = S_powers_fireball_coolDown;
+ if (up_on(UP_RAIN, 3)) cd -= 10 * FPS;
+ if (up_on(UP_RAIN, 4)) cd -= 10 * FPS;
+ return cd;
+}
+static void fire_damage(int *lo, int *hi, int *range) {
+ *lo = S_powers_fireball_minDamage, *hi = S_powers_fireball_maxDamage, *range = S_powers_fireball_range;
+ if (upgrades[UP_RAIN] >= 1) *lo += 20, *hi += 20;
+ if (up_on(UP_RAIN, 3)) *range += *range / 4, *lo += 40, *hi += 40;
+ if (up_on(UP_RAIN, 5)) *lo += 60, *hi += 60;
+}
+
+static int reinf_level(void) {
+ int l = upgrades[UP_REINF];
+ if (B.max_upgrade != 0 && B.max_upgrade < l) l = B.max_upgrade;
+ return l;
+}
+
+void power_init(void) {
+ B.fire_reload = (int16_t)fire_reload();
+ B.reinf_reload = 10 * FPS;
+}
+
+/* unlocked: after 15 + 17 frames it is ready (§_-Ff§: opening, then refresh) */
+void power_unlock_fire(void) {
+ if (!B.fire_on) B.fire_on = 1, B.fire_open_t = 32, B.fire_cd = 0;
+}
+void power_unlock_reinf(void) {
+ if (!B.reinf_on) B.reinf_on = 1, B.reinf_open_t = 32, B.reinf_cd = 0;
+}
+
+int power_fire_cooldown(void) { return !B.fire_on ? -1 : B.fire_open_t ? B.fire_open_t : B.fire_cd; }
+int power_reinf_cooldown(void) { return !B.reinf_on ? -1 : B.reinf_open_t ? B.reinf_open_t : B.reinf_cd; }
+
+void power_shorten(int frames) { /* §_-Hv§: calling a wave early takes the time off the cooldowns */
+ if (B.fire_on && !B.fire_open_t && B.fire_cd > 0) {
+ B.fire_cd = (int16_t)(B.fire_cd - frames);
+ if (B.fire_cd <= 0) B.fire_cd = 1;
+ }
+ if (B.reinf_on && !B.reinf_open_t && B.reinf_cd > 0) {
+ B.reinf_cd = (int16_t)(B.reinf_cd - frames);
+ if (B.reinf_cd <= 0) B.reinf_cd = 1;
+ }
+}
+
+/* ------------------------------------------------------------------ rain of fire */
+bool power_fire(Pt at) {
+ if (power_fire_cooldown() != 0) return false;
+ for (int k = 0; k < 2; k++)
+ if (!B.rain[k].on) {
+ B.rain[k].on = 1, B.rain[k].t = 0, B.rain[k].at = (Pt){at.x, at.y + 20};
+ /* three fireballs (five with Blazing Skies), and Cataclysm's five more over the roads */
+ B.rain[k].dur = (int16_t)(31 + (upgrades[UP_RAIN] >= 1 ? 20 : 0));
+ break;
+ }
+ B.fire_cd = (int16_t)fire_reload();
+ return true;
+}
+
+static void fireball(Pt from, Pt to) {
+ Bullet *b = bullet_new(BU_FIREBALL);
+ if (!b) return;
+ int lo, hi, range;
+ fire_damage(&lo, &hi, &range);
+ b->x = from.x, b->y = from.y, b->tx = to.x, b->ty = to.y;
+ b->acc = 10, b->acc_max = 15;
+ b->min_dmg = (int16_t)rnd_dmg(lo, hi), b->area = (int16_t)range;
+ b->pierce = up_on(UP_RAIN, 2); /* (Scorched Earth) */
+}
+
+static void rain_step(int k) {
+ int dev = 15 + (up_on(UP_RAIN, 3) ? 10 : 0);
+ bool cataclysm = up_on(UP_RAIN, 5);
+ int t = ++B.rain[k].t;
+ if (t < B.rain[k].dur && t % 10 == 0) {
+ float sx = rnd() >= 0.5f ? 1 : -1, sy = rnd() >= 0.5f ? 1 : -1;
+ Pt at = B.rain[k].at;
+ float x0 = at.x + sx * (float)rnd_round(0, dev);
+ Pt to = {at.x + sx * (float)rnd_round(0, dev), at.y + sy * (float)rnd_round(0, dev)};
+ fireball((Pt){x0, 0}, to);
+ }
+ if (cataclysm && t < 51 && t % 10 == 0) {
+ int p = (int)floorf((float)rnd_round(0, B.npaths - 1));
+ int n = (int)floorf((float)rnd_round(0, path_len(p, 0) - 1));
+ Pt to = path_node(p, 0, n);
+ fireball((Pt){to.x, 0}, to);
+ }
+ if ((!cataclysm && t >= B.rain[k].dur) || (cataclysm && t >= 51 && t >= B.rain[k].dur)) B.rain[k].on = 0;
+}
+
+/* ------------------------------------------------------------------ reinforcements */
+bool power_reinforce_ok(Pt at) {
+ for (int p = 0; p < B.npaths; p++) {
+ int n = path_len(p, 0);
+ for (int k = 0; k < n; k++) {
+ Pt q = path_node(p, 0, k);
+ float dx = q.x - at.x, dy = q.y - at.y;
+ if (sqrtf(dx * dx + dy * dy) < 30) return true;
+ }
+ }
+ return false;
+}
+
+bool power_reinforce(Pt at) {
+ if (power_reinf_cooldown() != 0 || !power_reinforce_ok(at)) return false;
+ int l = reinf_level(), kind = l <= 1 ? SK_FARMER : l == 2 ? SK_REINF2 : l == 3 ? SK_REINF3 : SK_REINF4;
+ for (int k = 0; k < 2; k++) {
+ float d = k ? -7.0f : 7.0f;
+ int i = soldier_new(kind, -1, (Pt){at.x + d, at.y + d}, (Pt){at.x + d, at.y + d});
+ if (i >= 0) B.so[i].home_x = at.x, B.so[i].home_y = at.y, B.so[i].look = (uint8_t)(rnd() * 3);
+ }
+ B.reinf_cd = B.reinf_reload;
+ return true;
+}
+
+/* ------------------------------------------------------------------ a frame */
+void power_step(void) {
+ if (B.fire_open_t) B.fire_open_t--;
+ else if (B.fire_on && B.fire_cd > 0) B.fire_cd--;
+ if (B.reinf_open_t) B.reinf_open_t--;
+ else if (B.reinf_on && B.reinf_cd > 0) B.reinf_cd--;
+ for (int k = 0; k < 2; k++)
+ if (B.rain[k].on) rain_step(k);
+}
diff --git a/games/kingdomrush/src/res.h b/games/kingdomrush/src/res.h
new file mode 100644
index 00000000..b30c58dd
--- /dev/null
+++ b/games/kingdomrush/src/res.h
@@ -0,0 +1,15 @@
+/* Kingdom Rush: data.bin (tools/pack.py), read where it lies in flash. */
+#ifndef KR_RES_H
+#define KR_RES_H
+#include <stdint.h>
+#include "data.h"
+
+extern const uint8_t *kr_bin;
+
+/* (byte by byte: the data is not always aligned) */
+static inline uint32_t rd16(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8); }
+static inline int32_t rds16(const uint8_t *p) { return (int16_t)(p[0] | p[1] << 8); }
+static inline uint32_t rd24(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16); }
+static inline uint32_t rd32(const uint8_t *p) { return (uint32_t)(p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24); }
+static inline const uint8_t *section(int s) { return kr_bin + rd32(kr_bin + 8 + 4 * s); }
+#endif
diff --git a/games/kingdomrush/src/save.c b/games/kingdomrush/src/save.c
new file mode 100644
index 00000000..9a4814e7
--- /dev/null
+++ b/games/kingdomrush/src/save.c
@@ -0,0 +1,40 @@
+/* The save: kingdomrush.sav, "KRS", a version, then the progress (game.h's Progress), and a check byte. */
+#include <string.h>
+#include "game.h"
+#include "plat.h"
+
+#define SAVE_NAME "kingdomrush.sav"
+#define SAVE_VERSION 1
+
+static uint8_t sum(const uint8_t *p, uint32_t n) {
+ uint8_t s = 0x5A;
+ for (uint32_t i = 0; i < n; i++) s = (uint8_t)(s * 31 + p[i]);
+ return s;
+}
+
+void save_progress(void) {
+ uint8_t buf[4 + sizeof(Progress) + 1];
+ memcpy(buf, "KRS", 3);
+ buf[3] = SAVE_VERSION;
+ memcpy(buf + 4, &g.p, sizeof g.p);
+ buf[sizeof buf - 1] = sum(buf, sizeof buf - 1);
+ plat_save(SAVE_NAME, buf, sizeof buf);
+}
+
+void load_progress(void) {
+ memset(&g.p, 0, sizeof g.p);
+ g.p.difficulty = 1;
+ uint32_t n = 0;
+ const uint8_t *d = plat_load(SAVE_NAME, &n);
+ if (!d || n != 4 + sizeof(Progress) + 1 || memcmp(d, "KRS", 3) || d[3] != SAVE_VERSION || sum(d, n - 1) != d[n - 1])
+ return;
+ Progress p;
+ memcpy(&p, d + 4, sizeof p);
+ /* anything out of range: a fresh start rather than a broken one */
+ for (int i = 0; i < 12; i++)
+ if (p.camp[i] > 3 || p.heroic[i] > 1 || p.iron[i] > 1) return;
+ for (int i = 0; i < 6; i++)
+ if (p.ups[i] > 5) return;
+ if (p.difficulty > 2) p.difficulty = 1;
+ g.p = p;
+}
diff --git a/games/kingdomrush/src/settings.h b/games/kingdomrush/src/settings.h
new file mode 100644
index 00000000..ca6e7b3c
--- /dev/null
+++ b/games/kingdomrush/src/settings.h
@@ -0,0 +1,1180 @@
+/* Made by tools/pack.py: the game's GameSettings, by name (S_<group>_<object>_<field>). */
+#ifndef KR_SETTINGS_H
+#define KR_SETTINGS_H
+#define S_archers_level1_cost 70
+#define S_archers_level1_maxDamage 6
+#define S_archers_level1_minDamage 4
+#define S_archers_level1_range 220
+#define S_archers_level1_reload 24
+#define S_archers_level2_cost 110
+#define S_archers_level2_maxDamage 11
+#define S_archers_level2_minDamage 7
+#define S_archers_level2_range 250
+#define S_archers_level2_reload 18
+#define S_archers_level3_cost 160
+#define S_archers_level3_maxDamage 16
+#define S_archers_level3_minDamage 10
+#define S_archers_level3_range 280
+#define S_archers_level3_reload 15
+#define S_archers_musketeer_cost 230
+#define S_archers_musketeer_maxDamage 65
+#define S_archers_musketeer_minDamage 35
+#define S_archers_musketeer_range 370
+#define S_archers_musketeer_reload 45
+#define S_archers_musketeer_shrapnelArea 50
+#define S_archers_musketeer_shrapnelCoolDown 270
+#define S_archers_musketeer_shrapnelCost 300
+#define S_archers_musketeer_shrapnelCostLevel 300
+#define S_archers_musketeer_shrapnelLevels 3
+#define S_archers_musketeer_shrapnelMaxDamage 40
+#define S_archers_musketeer_shrapnelMinDamage 10
+#define S_archers_musketeer_shrapnelRange 0.5f
+#define S_archers_musketeer_sniperCoolDown 420
+#define S_archers_musketeer_sniperCost 250
+#define S_archers_musketeer_sniperCostLevel 250
+#define S_archers_musketeer_sniperDamagePercent 20
+#define S_archers_musketeer_sniperLevels 3
+#define S_archers_musketeer_sniperRange 1.5f
+#define S_archers_ranger_cost 230
+#define S_archers_ranger_maxDamage 19
+#define S_archers_ranger_minDamage 13
+#define S_archers_ranger_poisonCoolDown 12
+#define S_archers_ranger_poisonCost 250
+#define S_archers_ranger_poisonCostLevel 250
+#define S_archers_ranger_poisonDamage 5
+#define S_archers_ranger_poisonDuration 90
+#define S_archers_ranger_poisonLevels 3
+#define S_archers_ranger_range 310
+#define S_archers_ranger_reload 12
+#define S_archers_ranger_thornCoolDown 240
+#define S_archers_ranger_thornCost 300
+#define S_archers_ranger_thornCostLevel 150
+#define S_archers_ranger_thornDamage 40
+#define S_archers_ranger_thornDamageTime 30
+#define S_archers_ranger_thornDuration 30
+#define S_archers_ranger_thornLevels 3
+#define S_archers_ranger_thornMaxEnemies 2
+#define S_archers_ranger_thornMaxTimes 3
+#define S_archers_ranger_thornMinEnemies 2
+#define S_enemies_bandit_armor 0
+#define S_enemies_bandit_attackReloadTime 30
+#define S_enemies_bandit_cost 1
+#define S_enemies_bandit_dodge 50
+#define S_enemies_bandit_gold 8
+#define S_enemies_bandit_health 70
+#define S_enemies_bandit_magicArmor 0
+#define S_enemies_bandit_maxDamage 30
+#define S_enemies_bandit_minDamage 20
+#define S_enemies_bandit_size 0
+#define S_enemies_bandit_speed 1.2f
+#define S_enemies_bandit_xAdjust 0
+#define S_enemies_bandit_xSoldierAdjust 15
+#define S_enemies_bandit_yAdjust -8
+#define S_enemies_brigand_armor 50
+#define S_enemies_brigand_attackReloadTime 30
+#define S_enemies_brigand_cost 1
+#define S_enemies_brigand_dodge 0
+#define S_enemies_brigand_gold 15
+#define S_enemies_brigand_health 160
+#define S_enemies_brigand_magicArmor 0
+#define S_enemies_brigand_maxDamage 10
+#define S_enemies_brigand_minDamage 6
+#define S_enemies_brigand_size 0
+#define S_enemies_brigand_speed 0.8f
+#define S_enemies_brigand_xAdjust 0
+#define S_enemies_brigand_xSoldierAdjust 15
+#define S_enemies_brigand_yAdjust -8
+#define S_enemies_darkKnight_armor 80
+#define S_enemies_darkKnight_attackReloadTime 30
+#define S_enemies_darkKnight_cost 1
+#define S_enemies_darkKnight_dodge 0
+#define S_enemies_darkKnight_gold 25
+#define S_enemies_darkKnight_health 300
+#define S_enemies_darkKnight_magicArmor 0
+#define S_enemies_darkKnight_maxDamage 25
+#define S_enemies_darkKnight_minDamage 15
+#define S_enemies_darkKnight_size 0
+#define S_enemies_darkKnight_speed 0.7f
+#define S_enemies_darkKnight_xAdjust 0
+#define S_enemies_darkKnight_xSoldierAdjust 20
+#define S_enemies_darkKnight_yAdjust -10
+#define S_enemies_demonImp_armor 0
+#define S_enemies_demonImp_attackReloadTime 30
+#define S_enemies_demonImp_cost 1
+#define S_enemies_demonImp_dodge 0
+#define S_enemies_demonImp_gold 25
+#define S_enemies_demonImp_health 350
+#define S_enemies_demonImp_magicArmor 0
+#define S_enemies_demonImp_maxDamage 2
+#define S_enemies_demonImp_minDamage 1
+#define S_enemies_demonImp_size 0
+#define S_enemies_demonImp_speed 1
+#define S_enemies_demonImp_xAdjust 3
+#define S_enemies_demonImp_xSoldierAdjust 15
+#define S_enemies_demonImp_yAdjust -45
+#define S_enemies_demonMage_armor 0
+#define S_enemies_demonMage_attackReloadTime 30
+#define S_enemies_demonMage_cost 5
+#define S_enemies_demonMage_dodge 0
+#define S_enemies_demonMage_exploteMaxDamage 400
+#define S_enemies_demonMage_exploteMinDamage 200
+#define S_enemies_demonMage_exploteRange 100
+#define S_enemies_demonMage_gold 60
+#define S_enemies_demonMage_health 1000
+#define S_enemies_demonMage_magicArmor 60
+#define S_enemies_demonMage_maxDamage 75
+#define S_enemies_demonMage_minDamage 15
+#define S_enemies_demonMage_shieldCoolDown 180
+#define S_enemies_demonMage_shieldIgnoreHits 4
+#define S_enemies_demonMage_shieldMaxEnemies 4
+#define S_enemies_demonMage_shieldRange 280
+#define S_enemies_demonMage_size 2
+#define S_enemies_demonMage_speed 0.6f
+#define S_enemies_demonMage_xAdjust 0
+#define S_enemies_demonMage_xSoldierAdjust 23
+#define S_enemies_demonMage_yAdjust -18
+#define S_enemies_demonWolf_armor 0
+#define S_enemies_demonWolf_attackReloadTime 30
+#define S_enemies_demonWolf_cost 1
+#define S_enemies_demonWolf_dodge 50
+#define S_enemies_demonWolf_exploteMaxDamage 140
+#define S_enemies_demonWolf_exploteMinDamage 70
+#define S_enemies_demonWolf_exploteRange 100
+#define S_enemies_demonWolf_gold 25
+#define S_enemies_demonWolf_health 350
+#define S_enemies_demonWolf_magicArmor 60
+#define S_enemies_demonWolf_maxDamage 40
+#define S_enemies_demonWolf_minDamage 20
+#define S_enemies_demonWolf_size 0
+#define S_enemies_demonWolf_speed 1.5f
+#define S_enemies_demonWolf_xAdjust 0
+#define S_enemies_demonWolf_xSoldierAdjust 20
+#define S_enemies_demonWolf_yAdjust -8
+#define S_enemies_demon_armor 0
+#define S_enemies_demon_attackReloadTime 30
+#define S_enemies_demon_cost 1
+#define S_enemies_demon_dodge 0
+#define S_enemies_demon_exploteMaxDamage 100
+#define S_enemies_demon_exploteMinDamage 50
+#define S_enemies_demon_exploteRange 100
+#define S_enemies_demon_gold 20
+#define S_enemies_demon_health 250
+#define S_enemies_demon_magicArmor 60
+#define S_enemies_demon_maxDamage 30
+#define S_enemies_demon_minDamage 10
+#define S_enemies_demon_size 0
+#define S_enemies_demon_speed 0.8f
+#define S_enemies_demon_xAdjust 0
+#define S_enemies_demon_xSoldierAdjust 15
+#define S_enemies_demon_yAdjust -8
+#define S_enemies_fatOrc_armor 30
+#define S_enemies_fatOrc_attackReloadTime 30
+#define S_enemies_fatOrc_cost 1
+#define S_enemies_fatOrc_dodge 0
+#define S_enemies_fatOrc_gold 9
+#define S_enemies_fatOrc_health 80
+#define S_enemies_fatOrc_magicArmor 0
+#define S_enemies_fatOrc_maxDamage 8
+#define S_enemies_fatOrc_minDamage 4
+#define S_enemies_fatOrc_size 1
+#define S_enemies_fatOrc_speed 0.8f
+#define S_enemies_fatOrc_xAdjust 0
+#define S_enemies_fatOrc_xSoldierAdjust 15
+#define S_enemies_fatOrc_yAdjust -8
+#define S_enemies_forestTroll_areaAttackMaxEnemies 10
+#define S_enemies_forestTroll_areaAttackRangeWidth 70
+#define S_enemies_forestTroll_armor 0
+#define S_enemies_forestTroll_attackReloadTime 75
+#define S_enemies_forestTroll_cost 5
+#define S_enemies_forestTroll_dodge 0
+#define S_enemies_forestTroll_gold 200
+#define S_enemies_forestTroll_health 4000
+#define S_enemies_forestTroll_magicArmor 0
+#define S_enemies_forestTroll_maxDamage 150
+#define S_enemies_forestTroll_minDamage 50
+#define S_enemies_forestTroll_regenerateHealPoints 2
+#define S_enemies_forestTroll_regenerateTime 1
+#define S_enemies_forestTroll_size 2
+#define S_enemies_forestTroll_speed 0.6f
+#define S_enemies_forestTroll_xAdjust 0
+#define S_enemies_forestTroll_xSoldierAdjust 27
+#define S_enemies_forestTroll_yAdjust -18
+#define S_enemies_gargoyle_armor 0
+#define S_enemies_gargoyle_attackReloadTime 30
+#define S_enemies_gargoyle_cost 1
+#define S_enemies_gargoyle_dodge 0
+#define S_enemies_gargoyle_gold 12
+#define S_enemies_gargoyle_health 90
+#define S_enemies_gargoyle_magicArmor 0
+#define S_enemies_gargoyle_maxDamage 2
+#define S_enemies_gargoyle_minDamage 1
+#define S_enemies_gargoyle_size 0
+#define S_enemies_gargoyle_speed 1.2f
+#define S_enemies_gargoyle_xAdjust 3
+#define S_enemies_gargoyle_xSoldierAdjust 15
+#define S_enemies_gargoyle_yAdjust -45
+#define S_enemies_goblinChieftain_armor 0
+#define S_enemies_goblinChieftain_attackReloadTime 30
+#define S_enemies_goblinChieftain_cost 20
+#define S_enemies_goblinChieftain_dodge 0
+#define S_enemies_goblinChieftain_gold 0
+#define S_enemies_goblinChieftain_healCoolDown 240
+#define S_enemies_goblinChieftain_healMaxEnemies 20
+#define S_enemies_goblinChieftain_healPoints 200
+#define S_enemies_goblinChieftain_healRange 500
+#define S_enemies_goblinChieftain_health 12000
+#define S_enemies_goblinChieftain_magicArmor 0
+#define S_enemies_goblinChieftain_maxDamage 600
+#define S_enemies_goblinChieftain_minDamage 200
+#define S_enemies_goblinChieftain_size 2
+#define S_enemies_goblinChieftain_speed 0.4f
+#define S_enemies_goblinChieftain_xAdjust 0
+#define S_enemies_goblinChieftain_xSoldierAdjust 42
+#define S_enemies_goblinChieftain_yAdjust -15
+#define S_enemies_goblinZapper_armor 0
+#define S_enemies_goblinZapper_attackReloadTime 30
+#define S_enemies_goblinZapper_bombCoolDown 30
+#define S_enemies_goblinZapper_bombMaxDamage 60
+#define S_enemies_goblinZapper_bombMinDamage 30
+#define S_enemies_goblinZapper_bombMinRange 40
+#define S_enemies_goblinZapper_bombRange 260
+#define S_enemies_goblinZapper_cost 1
+#define S_enemies_goblinZapper_dodge 0
+#define S_enemies_goblinZapper_exploteMaxDamage 150
+#define S_enemies_goblinZapper_exploteMinDamage 50
+#define S_enemies_goblinZapper_exploteRange 120
+#define S_enemies_goblinZapper_gold 10
+#define S_enemies_goblinZapper_health 140
+#define S_enemies_goblinZapper_magicArmor 0
+#define S_enemies_goblinZapper_maxDamage 20
+#define S_enemies_goblinZapper_minDamage 10
+#define S_enemies_goblinZapper_size 0
+#define S_enemies_goblinZapper_speed 1.2f
+#define S_enemies_goblinZapper_xAdjust 1
+#define S_enemies_goblinZapper_xSoldierAdjust 15
+#define S_enemies_goblinZapper_yAdjust -8
+#define S_enemies_goblin_armor 0
+#define S_enemies_goblin_attackReloadTime 30
+#define S_enemies_goblin_cost 1
+#define S_enemies_goblin_dodge 0
+#define S_enemies_goblin_gold 3
+#define S_enemies_goblin_health 20
+#define S_enemies_goblin_magicArmor 0
+#define S_enemies_goblin_maxDamage 4
+#define S_enemies_goblin_minDamage 1
+#define S_enemies_goblin_size 0
+#define S_enemies_goblin_speed 1.2f
+#define S_enemies_goblin_xAdjust 0
+#define S_enemies_goblin_xSoldierAdjust 15
+#define S_enemies_goblin_yAdjust -8
+#define S_enemies_golemHead_armor 0
+#define S_enemies_golemHead_attackReloadTime 30
+#define S_enemies_golemHead_cost 1
+#define S_enemies_golemHead_dodge 0
+#define S_enemies_golemHead_gold 10
+#define S_enemies_golemHead_health 125
+#define S_enemies_golemHead_magicArmor 0
+#define S_enemies_golemHead_maxDamage 20
+#define S_enemies_golemHead_minDamage 10
+#define S_enemies_golemHead_size 0
+#define S_enemies_golemHead_speed 0.7f
+#define S_enemies_golemHead_xAdjust 1
+#define S_enemies_golemHead_xSoldierAdjust 14
+#define S_enemies_golemHead_yAdjust -8
+#define S_enemies_juggernaut_areaAttackMaxEnemies 10
+#define S_enemies_juggernaut_areaAttackRangeWidth 90
+#define S_enemies_juggernaut_armor 0
+#define S_enemies_juggernaut_attackReloadTime 60
+#define S_enemies_juggernaut_cost 20
+#define S_enemies_juggernaut_dodge 0
+#define S_enemies_juggernaut_gold 0
+#define S_enemies_juggernaut_golemHeads 7
+#define S_enemies_juggernaut_health 10000
+#define S_enemies_juggernaut_magicArmor 0
+#define S_enemies_juggernaut_maxDamage 250
+#define S_enemies_juggernaut_minDamage 150
+#define S_enemies_juggernaut_missileCoolDown 270
+#define S_enemies_juggernaut_missileMaxDamage 250
+#define S_enemies_juggernaut_missileMinDamage 150
+#define S_enemies_juggernaut_missileMinRange 100
+#define S_enemies_juggernaut_size 2
+#define S_enemies_juggernaut_spawnCooldownTime 180
+#define S_enemies_juggernaut_speed 0.4f
+#define S_enemies_juggernaut_xAdjust 0
+#define S_enemies_juggernaut_xSoldierAdjust 35
+#define S_enemies_juggernaut_yAdjust -30
+#define S_enemies_lavaElemental_areaAttackMaxEnemies 10
+#define S_enemies_lavaElemental_areaAttackRangeWidth 70
+#define S_enemies_lavaElemental_armor 0
+#define S_enemies_lavaElemental_attackReloadTime 75
+#define S_enemies_lavaElemental_cost 5
+#define S_enemies_lavaElemental_dodge 0
+#define S_enemies_lavaElemental_gold 100
+#define S_enemies_lavaElemental_health 2500
+#define S_enemies_lavaElemental_magicArmor 0
+#define S_enemies_lavaElemental_maxDamage 150
+#define S_enemies_lavaElemental_minDamage 50
+#define S_enemies_lavaElemental_size 2
+#define S_enemies_lavaElemental_speed 0.5f
+#define S_enemies_lavaElemental_xAdjust 0
+#define S_enemies_lavaElemental_xSoldierAdjust 27
+#define S_enemies_lavaElemental_yAdjust -18
+#define S_enemies_marauder_armor 60
+#define S_enemies_marauder_attackReloadTime 30
+#define S_enemies_marauder_cost 3
+#define S_enemies_marauder_dodge 0
+#define S_enemies_marauder_gold 40
+#define S_enemies_marauder_health 600
+#define S_enemies_marauder_magicArmor 0
+#define S_enemies_marauder_maxDamage 24
+#define S_enemies_marauder_minDamage 16
+#define S_enemies_marauder_size 2
+#define S_enemies_marauder_speed 0.8f
+#define S_enemies_marauder_xAdjust 0
+#define S_enemies_marauder_xSoldierAdjust 20
+#define S_enemies_marauder_yAdjust -18
+#define S_enemies_necromancer_armor 0
+#define S_enemies_necromancer_attackReloadTime 30
+#define S_enemies_necromancer_cost 3
+#define S_enemies_necromancer_dodge 0
+#define S_enemies_necromancer_gold 50
+#define S_enemies_necromancer_health 700
+#define S_enemies_necromancer_magicArmor 0
+#define S_enemies_necromancer_maxDamage 40
+#define S_enemies_necromancer_minDamage 20
+#define S_enemies_necromancer_size 0
+#define S_enemies_necromancer_speed 0.6f
+#define S_enemies_necromancer_spellCoolDown 30
+#define S_enemies_necromancer_spellMaxDamage 40
+#define S_enemies_necromancer_spellMinDamage 20
+#define S_enemies_necromancer_spellMinRange 40
+#define S_enemies_necromancer_spellRange 230
+#define S_enemies_necromancer_summonCoolDown 240
+#define S_enemies_necromancer_summonMaxEnemies 4
+#define S_enemies_necromancer_summonMaxSkeletons 35
+#define S_enemies_necromancer_xAdjust 0
+#define S_enemies_necromancer_xSoldierAdjust 15
+#define S_enemies_necromancer_yAdjust -9
+#define S_enemies_ogre_armor 0
+#define S_enemies_ogre_attackReloadTime 30
+#define S_enemies_ogre_cost 3
+#define S_enemies_ogre_dodge 0
+#define S_enemies_ogre_gold 50
+#define S_enemies_ogre_health 800
+#define S_enemies_ogre_magicArmor 0
+#define S_enemies_ogre_maxDamage 60
+#define S_enemies_ogre_minDamage 40
+#define S_enemies_ogre_size 2
+#define S_enemies_ogre_speed 0.7f
+#define S_enemies_ogre_xAdjust 3
+#define S_enemies_ogre_xSoldierAdjust 25
+#define S_enemies_ogre_yAdjust -18
+#define S_enemies_orcArmored_armor 80
+#define S_enemies_orcArmored_attackReloadTime 30
+#define S_enemies_orcArmored_cost 1
+#define S_enemies_orcArmored_dodge 0
+#define S_enemies_orcArmored_gold 30
+#define S_enemies_orcArmored_health 400
+#define S_enemies_orcArmored_magicArmor 0
+#define S_enemies_orcArmored_maxDamage 40
+#define S_enemies_orcArmored_minDamage 20
+#define S_enemies_orcArmored_size 1
+#define S_enemies_orcArmored_speed 0.8f
+#define S_enemies_orcArmored_xAdjust 0
+#define S_enemies_orcArmored_xSoldierAdjust 18
+#define S_enemies_orcArmored_yAdjust -12
+#define S_enemies_orcWolfRider_armor 0
+#define S_enemies_orcWolfRider_attackReloadTime 30
+#define S_enemies_orcWolfRider_cost 2
+#define S_enemies_orcWolfRider_dodge 0
+#define S_enemies_orcWolfRider_gold 25
+#define S_enemies_orcWolfRider_health 400
+#define S_enemies_orcWolfRider_magicArmor 80
+#define S_enemies_orcWolfRider_maxDamage 40
+#define S_enemies_orcWolfRider_minDamage 20
+#define S_enemies_orcWolfRider_size 1
+#define S_enemies_orcWolfRider_speed 1.4f
+#define S_enemies_orcWolfRider_xAdjust 0
+#define S_enemies_orcWolfRider_xSoldierAdjust 22
+#define S_enemies_orcWolfRider_yAdjust -13
+#define S_enemies_rocketeer_armor 0
+#define S_enemies_rocketeer_attackReloadTime 30
+#define S_enemies_rocketeer_cost 1
+#define S_enemies_rocketeer_dodge 0
+#define S_enemies_rocketeer_fastSpeed 4
+#define S_enemies_rocketeer_fastSpeedDuration 60
+#define S_enemies_rocketeer_gold 30
+#define S_enemies_rocketeer_health 340
+#define S_enemies_rocketeer_magicArmor 0
+#define S_enemies_rocketeer_maxDamage 2
+#define S_enemies_rocketeer_minDamage 1
+#define S_enemies_rocketeer_size 0
+#define S_enemies_rocketeer_speed 1.2f
+#define S_enemies_rocketeer_xAdjust 0
+#define S_enemies_rocketeer_xSoldierAdjust 15
+#define S_enemies_rocketeer_yAdjust -50
+#define S_enemies_rottenBoss_areaAttackMaxEnemies 10
+#define S_enemies_rottenBoss_areaAttackRangeWidth 90
+#define S_enemies_rottenBoss_armor 0
+#define S_enemies_rottenBoss_attackReloadTime 60
+#define S_enemies_rottenBoss_bombCooldownTime 180
+#define S_enemies_rottenBoss_bombMaxBalls 7
+#define S_enemies_rottenBoss_bombMaxDamage 160
+#define S_enemies_rottenBoss_bombMinDamage 80
+#define S_enemies_rottenBoss_cost 20
+#define S_enemies_rottenBoss_dodge 0
+#define S_enemies_rottenBoss_gold 0
+#define S_enemies_rottenBoss_health 10000
+#define S_enemies_rottenBoss_magicArmor 0
+#define S_enemies_rottenBoss_maxDamage 250
+#define S_enemies_rottenBoss_minDamage 150
+#define S_enemies_rottenBoss_size 2
+#define S_enemies_rottenBoss_speed 0.3f
+#define S_enemies_rottenBoss_xAdjust 0
+#define S_enemies_rottenBoss_xSoldierAdjust 35
+#define S_enemies_rottenBoss_yAdjust -30
+#define S_enemies_rottenSpider_armor 0
+#define S_enemies_rottenSpider_attackReloadTime 30
+#define S_enemies_rottenSpider_cost 3
+#define S_enemies_rottenSpider_dodge 0
+#define S_enemies_rottenSpider_eggsCooldownTimeMax 300
+#define S_enemies_rottenSpider_eggsCooldownTimeMin 150
+#define S_enemies_rottenSpider_eggsMax 6
+#define S_enemies_rottenSpider_eggsSpiders 3
+#define S_enemies_rottenSpider_gold 40
+#define S_enemies_rottenSpider_health 1000
+#define S_enemies_rottenSpider_magicArmor 60
+#define S_enemies_rottenSpider_maxDamage 40
+#define S_enemies_rottenSpider_minDamage 20
+#define S_enemies_rottenSpider_size 0
+#define S_enemies_rottenSpider_speed 0.6f
+#define S_enemies_rottenSpider_xAdjust 1
+#define S_enemies_rottenSpider_xSoldierAdjust 24
+#define S_enemies_rottenSpider_yAdjust -8
+#define S_enemies_rottenTree_armor 80
+#define S_enemies_rottenTree_attackReloadTime 30
+#define S_enemies_rottenTree_cost 1
+#define S_enemies_rottenTree_dodge 0
+#define S_enemies_rottenTree_gold 60
+#define S_enemies_rottenTree_health 1000
+#define S_enemies_rottenTree_magicArmor 0
+#define S_enemies_rottenTree_maxDamage 40
+#define S_enemies_rottenTree_minDamage 20
+#define S_enemies_rottenTree_size 0
+#define S_enemies_rottenTree_speed 0.6f
+#define S_enemies_rottenTree_xAdjust 0
+#define S_enemies_rottenTree_xSoldierAdjust 15
+#define S_enemies_rottenTree_yAdjust -8
+#define S_enemies_sarelgazSmall_armor 70
+#define S_enemies_sarelgazSmall_attackReloadTime 30
+#define S_enemies_sarelgazSmall_cost 1
+#define S_enemies_sarelgazSmall_dodge 0
+#define S_enemies_sarelgazSmall_gold 80
+#define S_enemies_sarelgazSmall_health 1250
+#define S_enemies_sarelgazSmall_magicArmor 70
+#define S_enemies_sarelgazSmall_maxDamage 100
+#define S_enemies_sarelgazSmall_minDamage 50
+#define S_enemies_sarelgazSmall_size 0
+#define S_enemies_sarelgazSmall_speed 0.8f
+#define S_enemies_sarelgazSmall_xAdjust 1
+#define S_enemies_sarelgazSmall_xSoldierAdjust 32
+#define S_enemies_sarelgazSmall_yAdjust -21
+#define S_enemies_sarelgaz_armor 0
+#define S_enemies_sarelgaz_attackReloadTime 30
+#define S_enemies_sarelgaz_cost 20
+#define S_enemies_sarelgaz_dodge 0
+#define S_enemies_sarelgaz_gold 0
+#define S_enemies_sarelgaz_health 18000
+#define S_enemies_sarelgaz_magicArmor 0
+#define S_enemies_sarelgaz_maxDamage 500
+#define S_enemies_sarelgaz_minDamage 300
+#define S_enemies_sarelgaz_size 0
+#define S_enemies_sarelgaz_speed 0.4f
+#define S_enemies_sarelgaz_xAdjust 1
+#define S_enemies_sarelgaz_xSoldierAdjust 75
+#define S_enemies_sarelgaz_yAdjust -40
+#define S_enemies_shadowArcher_armor 0
+#define S_enemies_shadowArcher_arrowCoolDown 30
+#define S_enemies_shadowArcher_arrowMaxDamage 30
+#define S_enemies_shadowArcher_arrowMinDamage 20
+#define S_enemies_shadowArcher_arrowMinRange 40
+#define S_enemies_shadowArcher_arrowRange 230
+#define S_enemies_shadowArcher_attackReloadTime 30
+#define S_enemies_shadowArcher_cost 1
+#define S_enemies_shadowArcher_dodge 0
+#define S_enemies_shadowArcher_gold 16
+#define S_enemies_shadowArcher_health 180
+#define S_enemies_shadowArcher_magicArmor 30
+#define S_enemies_shadowArcher_maxDamage 20
+#define S_enemies_shadowArcher_minDamage 10
+#define S_enemies_shadowArcher_size 0
+#define S_enemies_shadowArcher_speed 1.2f
+#define S_enemies_shadowArcher_xAdjust 1
+#define S_enemies_shadowArcher_xSoldierAdjust 15
+#define S_enemies_shadowArcher_yAdjust -8
+#define S_enemies_shaman_armor 0
+#define S_enemies_shaman_attackReloadTime 30
+#define S_enemies_shaman_cost 1
+#define S_enemies_shaman_dodge 0
+#define S_enemies_shaman_gold 10
+#define S_enemies_shaman_healCoolDown 240
+#define S_enemies_shaman_healMaxEnemies 3
+#define S_enemies_shaman_healPoints 50
+#define S_enemies_shaman_healRange 150
+#define S_enemies_shaman_health 100
+#define S_enemies_shaman_magicArmor 85
+#define S_enemies_shaman_maxDamage 5
+#define S_enemies_shaman_minDamage 3
+#define S_enemies_shaman_size 0
+#define S_enemies_shaman_speed 1
+#define S_enemies_shaman_xAdjust 0
+#define S_enemies_shaman_xSoldierAdjust 15
+#define S_enemies_shaman_yAdjust -8
+#define S_enemies_skeletonBig_armor 30
+#define S_enemies_skeletonBig_attackReloadTime 30
+#define S_enemies_skeletonBig_cost 1
+#define S_enemies_skeletonBig_dodge 0
+#define S_enemies_skeletonBig_gold 10
+#define S_enemies_skeletonBig_health 400
+#define S_enemies_skeletonBig_magicArmor 0
+#define S_enemies_skeletonBig_maxDamage 40
+#define S_enemies_skeletonBig_minDamage 20
+#define S_enemies_skeletonBig_size 2
+#define S_enemies_skeletonBig_speed 0.6f
+#define S_enemies_skeletonBig_xAdjust 0
+#define S_enemies_skeletonBig_xSoldierAdjust 18
+#define S_enemies_skeletonBig_yAdjust -11
+#define S_enemies_skeleton_armor 0
+#define S_enemies_skeleton_attackReloadTime 30
+#define S_enemies_skeleton_cost 1
+#define S_enemies_skeleton_dodge 0
+#define S_enemies_skeleton_gold 2
+#define S_enemies_skeleton_health 120
+#define S_enemies_skeleton_magicArmor 0
+#define S_enemies_skeleton_maxDamage 20
+#define S_enemies_skeleton_minDamage 10
+#define S_enemies_skeleton_size 0
+#define S_enemies_skeleton_speed 0.6f
+#define S_enemies_skeleton_xAdjust 0
+#define S_enemies_skeleton_xSoldierAdjust 15
+#define S_enemies_skeleton_yAdjust -8
+#define S_enemies_slayer_armor 95
+#define S_enemies_slayer_attackReloadTime 30
+#define S_enemies_slayer_cost 3
+#define S_enemies_slayer_dodge 0
+#define S_enemies_slayer_gold 100
+#define S_enemies_slayer_health 1200
+#define S_enemies_slayer_magicArmor 0
+#define S_enemies_slayer_maxDamage 76
+#define S_enemies_slayer_minDamage 24
+#define S_enemies_slayer_size 2
+#define S_enemies_slayer_speed 0.7f
+#define S_enemies_slayer_xAdjust 0
+#define S_enemies_slayer_xSoldierAdjust 20
+#define S_enemies_slayer_yAdjust -18
+#define S_enemies_spiderSmall_armor 0
+#define S_enemies_spiderSmall_attackReloadTime 30
+#define S_enemies_spiderSmall_cost 1
+#define S_enemies_spiderSmall_dodge 0
+#define S_enemies_spiderSmall_gold 6
+#define S_enemies_spiderSmall_health 60
+#define S_enemies_spiderSmall_magicArmor 65
+#define S_enemies_spiderSmall_maxDamage 18
+#define S_enemies_spiderSmall_minDamage 10
+#define S_enemies_spiderSmall_size 0
+#define S_enemies_spiderSmall_speed 1.5f
+#define S_enemies_spiderSmall_xAdjust 1
+#define S_enemies_spiderSmall_xSoldierAdjust 18
+#define S_enemies_spiderSmall_yAdjust -8
+#define S_enemies_spiderTinyRotten_armor 0
+#define S_enemies_spiderTinyRotten_attackReloadTime 30
+#define S_enemies_spiderTinyRotten_cost 1
+#define S_enemies_spiderTinyRotten_dodge 0
+#define S_enemies_spiderTinyRotten_gold 0
+#define S_enemies_spiderTinyRotten_health 80
+#define S_enemies_spiderTinyRotten_magicArmor 30
+#define S_enemies_spiderTinyRotten_maxDamage 20
+#define S_enemies_spiderTinyRotten_minDamage 10
+#define S_enemies_spiderTinyRotten_size 0
+#define S_enemies_spiderTinyRotten_speed 1.2f
+#define S_enemies_spiderTinyRotten_xAdjust 1
+#define S_enemies_spiderTinyRotten_xSoldierAdjust 14
+#define S_enemies_spiderTinyRotten_yAdjust -4
+#define S_enemies_spiderTiny_armor 0
+#define S_enemies_spiderTiny_attackReloadTime 30
+#define S_enemies_spiderTiny_cost 1
+#define S_enemies_spiderTiny_dodge 0
+#define S_enemies_spiderTiny_gold 0
+#define S_enemies_spiderTiny_health 10
+#define S_enemies_spiderTiny_magicArmor 50
+#define S_enemies_spiderTiny_maxDamage 5
+#define S_enemies_spiderTiny_minDamage 1
+#define S_enemies_spiderTiny_size 0
+#define S_enemies_spiderTiny_speed 2
+#define S_enemies_spiderTiny_xAdjust 1
+#define S_enemies_spiderTiny_xSoldierAdjust 14
+#define S_enemies_spiderTiny_yAdjust -4
+#define S_enemies_spider_armor 0
+#define S_enemies_spider_attackReloadTime 30
+#define S_enemies_spider_cost 2
+#define S_enemies_spider_dodge 0
+#define S_enemies_spider_eggsCooldownTimeMax 240
+#define S_enemies_spider_eggsCooldownTimeMin 120
+#define S_enemies_spider_eggsMax 3
+#define S_enemies_spider_eggsSpiders 3
+#define S_enemies_spider_gold 20
+#define S_enemies_spider_health 250
+#define S_enemies_spider_magicArmor 80
+#define S_enemies_spider_maxDamage 25
+#define S_enemies_spider_minDamage 15
+#define S_enemies_spider_size 0
+#define S_enemies_spider_speed 1
+#define S_enemies_spider_xAdjust 1
+#define S_enemies_spider_xSoldierAdjust 24
+#define S_enemies_spider_yAdjust -8
+#define S_enemies_theThing_areaAttackMaxEnemies 10
+#define S_enemies_theThing_areaAttackRangeWidth 70
+#define S_enemies_theThing_armor 0
+#define S_enemies_theThing_attackReloadTime 75
+#define S_enemies_theThing_bombCoolDown 30
+#define S_enemies_theThing_bombMaxDamage 100
+#define S_enemies_theThing_bombMinDamage 40
+#define S_enemies_theThing_bombMinRange 70
+#define S_enemies_theThing_bombRange 260
+#define S_enemies_theThing_cost 5
+#define S_enemies_theThing_dodge 0
+#define S_enemies_theThing_gold 200
+#define S_enemies_theThing_health 3000
+#define S_enemies_theThing_magicArmor 0
+#define S_enemies_theThing_maxDamage 100
+#define S_enemies_theThing_minDamage 40
+#define S_enemies_theThing_regenerateHealPoints 1
+#define S_enemies_theThing_regenerateTime 1
+#define S_enemies_theThing_size 2
+#define S_enemies_theThing_speed 0.6f
+#define S_enemies_theThing_xAdjust 0
+#define S_enemies_theThing_xSoldierAdjust 27
+#define S_enemies_theThing_yAdjust -18
+#define S_enemies_trollAxeThrower_armor 0
+#define S_enemies_trollAxeThrower_attackReloadTime 30
+#define S_enemies_trollAxeThrower_axeCoolDown 30
+#define S_enemies_trollAxeThrower_axeMaxDamage 80
+#define S_enemies_trollAxeThrower_axeMinDamage 40
+#define S_enemies_trollAxeThrower_axeMinRange 40
+#define S_enemies_trollAxeThrower_axeRange 230
+#define S_enemies_trollAxeThrower_cost 3
+#define S_enemies_trollAxeThrower_dodge 0
+#define S_enemies_trollAxeThrower_gold 50
+#define S_enemies_trollAxeThrower_health 600
+#define S_enemies_trollAxeThrower_magicArmor 0
+#define S_enemies_trollAxeThrower_maxDamage 50
+#define S_enemies_trollAxeThrower_minDamage 30
+#define S_enemies_trollAxeThrower_regenerateHealPoints 2
+#define S_enemies_trollAxeThrower_regenerateTime 5
+#define S_enemies_trollAxeThrower_size 2
+#define S_enemies_trollAxeThrower_speed 0.8f
+#define S_enemies_trollAxeThrower_xAdjust 1
+#define S_enemies_trollAxeThrower_xSoldierAdjust 15
+#define S_enemies_trollAxeThrower_yAdjust -8
+#define S_enemies_trollChieftain_armor 0
+#define S_enemies_trollChieftain_attackReloadTime 30
+#define S_enemies_trollChieftain_cost 6
+#define S_enemies_trollChieftain_dodge 0
+#define S_enemies_trollChieftain_gold 70
+#define S_enemies_trollChieftain_health 1200
+#define S_enemies_trollChieftain_magicArmor 0
+#define S_enemies_trollChieftain_maxDamage 30
+#define S_enemies_trollChieftain_minDamage 10
+#define S_enemies_trollChieftain_rageAddedArmor 50
+#define S_enemies_trollChieftain_rageAddedMaxDamage 30
+#define S_enemies_trollChieftain_rageAddedMinDamage 15
+#define S_enemies_trollChieftain_rageAddedSpeed 0.8f
+#define S_enemies_trollChieftain_rageCoolDown 180
+#define S_enemies_trollChieftain_rageDurationTime 180
+#define S_enemies_trollChieftain_rageHealPoints 50
+#define S_enemies_trollChieftain_rageMaxEnemies 3
+#define S_enemies_trollChieftain_rageRange 280
+#define S_enemies_trollChieftain_regenerateHealPoints 4
+#define S_enemies_trollChieftain_regenerateTime 5
+#define S_enemies_trollChieftain_size 2
+#define S_enemies_trollChieftain_speed 0.6f
+#define S_enemies_trollChieftain_xAdjust 0
+#define S_enemies_trollChieftain_xSoldierAdjust 25
+#define S_enemies_trollChieftain_yAdjust -18
+#define S_enemies_troll_armor 0
+#define S_enemies_troll_attackReloadTime 30
+#define S_enemies_troll_cost 1
+#define S_enemies_troll_dodge 0
+#define S_enemies_troll_gold 25
+#define S_enemies_troll_health 280
+#define S_enemies_troll_magicArmor 0
+#define S_enemies_troll_maxDamage 40
+#define S_enemies_troll_minDamage 20
+#define S_enemies_troll_regenerateHealPoints 1
+#define S_enemies_troll_regenerateTime 5
+#define S_enemies_troll_size 0
+#define S_enemies_troll_speed 0.9f
+#define S_enemies_troll_xAdjust 0
+#define S_enemies_troll_xSoldierAdjust 15
+#define S_enemies_troll_yAdjust -8
+#define S_enemies_veznan_areaAttackMaxEnemies 8
+#define S_enemies_veznan_areaAttackRangeWidth 120
+#define S_enemies_veznan_armor 0
+#define S_enemies_veznan_attackReloadTime 60
+#define S_enemies_veznan_cost 20
+#define S_enemies_veznan_demonAttackReloadTime 75
+#define S_enemies_veznan_demonHealth 6666
+#define S_enemies_veznan_demonSpeed 0.6f
+#define S_enemies_veznan_demonXAdjust 0
+#define S_enemies_veznan_demonXSoldierAdjust 35
+#define S_enemies_veznan_demonYAdjust -45
+#define S_enemies_veznan_dodge 0
+#define S_enemies_veznan_gold 0
+#define S_enemies_veznan_health 6666
+#define S_enemies_veznan_magicArmor 0
+#define S_enemies_veznan_maxDamage 999
+#define S_enemies_veznan_minDamage 666
+#define S_enemies_veznan_size 2
+#define S_enemies_veznan_speed 0.4f
+#define S_enemies_veznan_towerHoldBlockTime 180
+#define S_enemies_veznan_towerHoldFreeTime 120
+#define S_enemies_veznan_tsungMaxEnemies 5
+#define S_enemies_veznan_tsungMinRange 50
+#define S_enemies_veznan_tsungRangeWidth 230
+#define S_enemies_veznan_tsungReloadTime 150
+#define S_enemies_veznan_xAdjust 0
+#define S_enemies_veznan_xSoldierAdjust 20
+#define S_enemies_veznan_yAdjust -18
+#define S_enemies_whiteWolf_armor 0
+#define S_enemies_whiteWolf_attackReloadTime 30
+#define S_enemies_whiteWolf_cost 1
+#define S_enemies_whiteWolf_dodge 50
+#define S_enemies_whiteWolf_gold 35
+#define S_enemies_whiteWolf_health 350
+#define S_enemies_whiteWolf_magicArmor 50
+#define S_enemies_whiteWolf_maxDamage 40
+#define S_enemies_whiteWolf_minDamage 20
+#define S_enemies_whiteWolf_regenerateHealPoints 0
+#define S_enemies_whiteWolf_regenerateTime 30
+#define S_enemies_whiteWolf_size 0
+#define S_enemies_whiteWolf_speed 2
+#define S_enemies_whiteWolf_xAdjust 0
+#define S_enemies_whiteWolf_xSoldierAdjust 15
+#define S_enemies_whiteWolf_yAdjust -8
+#define S_enemies_wolfSmall_armor 0
+#define S_enemies_wolfSmall_attackReloadTime 30
+#define S_enemies_wolfSmall_cost 1
+#define S_enemies_wolfSmall_dodge 30
+#define S_enemies_wolfSmall_gold 5
+#define S_enemies_wolfSmall_health 35
+#define S_enemies_wolfSmall_magicArmor 0
+#define S_enemies_wolfSmall_maxDamage 3
+#define S_enemies_wolfSmall_minDamage 1
+#define S_enemies_wolfSmall_size 0
+#define S_enemies_wolfSmall_speed 2.5f
+#define S_enemies_wolfSmall_xAdjust 0
+#define S_enemies_wolfSmall_xSoldierAdjust 15
+#define S_enemies_wolfSmall_yAdjust -8
+#define S_enemies_wolf_armor 0
+#define S_enemies_wolf_attackReloadTime 30
+#define S_enemies_wolf_cost 1
+#define S_enemies_wolf_dodge 50
+#define S_enemies_wolf_gold 12
+#define S_enemies_wolf_health 120
+#define S_enemies_wolf_magicArmor 50
+#define S_enemies_wolf_maxDamage 18
+#define S_enemies_wolf_minDamage 12
+#define S_enemies_wolf_size 1
+#define S_enemies_wolf_speed 2
+#define S_enemies_wolf_xAdjust 0
+#define S_enemies_wolf_xSoldierAdjust 20
+#define S_enemies_wolf_yAdjust -8
+#define S_enemies_yetiBoss_areaAttackMaxEnemies 5
+#define S_enemies_yetiBoss_areaAttackRangeWidth 70
+#define S_enemies_yetiBoss_areaDamageAttackMaxEnemies 10
+#define S_enemies_yetiBoss_areaDamageAttackRangeWidth 70
+#define S_enemies_yetiBoss_armor 0
+#define S_enemies_yetiBoss_attackReloadTime 60
+#define S_enemies_yetiBoss_breathDuration 120
+#define S_enemies_yetiBoss_cost 20
+#define S_enemies_yetiBoss_dodge 0
+#define S_enemies_yetiBoss_frozeMaxTowers 4
+#define S_enemies_yetiBoss_frozeRangeWidth 300
+#define S_enemies_yetiBoss_frozeReloadTime 300
+#define S_enemies_yetiBoss_gold 0
+#define S_enemies_yetiBoss_health 11000
+#define S_enemies_yetiBoss_magicArmor 0
+#define S_enemies_yetiBoss_maxDamage 200
+#define S_enemies_yetiBoss_maxWolf 2
+#define S_enemies_yetiBoss_maxYetis 1
+#define S_enemies_yetiBoss_minDamage 150
+#define S_enemies_yetiBoss_size 2
+#define S_enemies_yetiBoss_speed 0.4f
+#define S_enemies_yetiBoss_wolfSpawnCooldownTime 240
+#define S_enemies_yetiBoss_wolfSpawnInterval 20
+#define S_enemies_yetiBoss_xAdjust 0
+#define S_enemies_yetiBoss_xSoldierAdjust 35
+#define S_enemies_yetiBoss_yAdjust -50
+#define S_enemies_yetiBoss_yetisSpawnCooldownTime 570
+#define S_enemies_yetiBoss_yetisSpawnInterval 200
+#define S_enemies_yeti_areaAttackMaxEnemies 10
+#define S_enemies_yeti_areaAttackRangeWidth 70
+#define S_enemies_yeti_armor 0
+#define S_enemies_yeti_attackReloadTime 75
+#define S_enemies_yeti_cost 5
+#define S_enemies_yeti_dodge 0
+#define S_enemies_yeti_gold 120
+#define S_enemies_yeti_health 2000
+#define S_enemies_yeti_magicArmor 0
+#define S_enemies_yeti_maxDamage 150
+#define S_enemies_yeti_minDamage 50
+#define S_enemies_yeti_size 2
+#define S_enemies_yeti_speed 0.7f
+#define S_enemies_yeti_xAdjust 0
+#define S_enemies_yeti_xSoldierAdjust 27
+#define S_enemies_yeti_yAdjust -18
+#define S_enemies_zombie_armor 40
+#define S_enemies_zombie_attackReloadTime 30
+#define S_enemies_zombie_cost 1
+#define S_enemies_zombie_dodge 0
+#define S_enemies_zombie_gold 10
+#define S_enemies_zombie_health 250
+#define S_enemies_zombie_magicArmor 0
+#define S_enemies_zombie_maxDamage 15
+#define S_enemies_zombie_minDamage 5
+#define S_enemies_zombie_size 0
+#define S_enemies_zombie_speed 0.5f
+#define S_enemies_zombie_xAdjust 0
+#define S_enemies_zombie_xSoldierAdjust 15
+#define S_enemies_zombie_yAdjust -8
+#define S_engineers_bfg_area 80
+#define S_engineers_bfg_clusterArea 70
+#define S_engineers_bfg_clusterCoolDown 510
+#define S_engineers_bfg_clusterCost 250
+#define S_engineers_bfg_clusterCostLevel 150
+#define S_engineers_bfg_clusterIncrementBombs 2
+#define S_engineers_bfg_clusterLevels 3
+#define S_engineers_bfg_clusterMaxDamage 80
+#define S_engineers_bfg_clusterMinBombs 1
+#define S_engineers_bfg_clusterMinDamage 60
+#define S_engineers_bfg_cost 400
+#define S_engineers_bfg_maxDamage 120
+#define S_engineers_bfg_minDamage 60
+#define S_engineers_bfg_missileArea 50
+#define S_engineers_bfg_missileCoolDown 330
+#define S_engineers_bfg_missileCost 250
+#define S_engineers_bfg_missileCostLevel 100
+#define S_engineers_bfg_missileIncrementDamage 40
+#define S_engineers_bfg_missileLevels 3
+#define S_engineers_bfg_missileMaxDamage 140
+#define S_engineers_bfg_missileMinDamage 100
+#define S_engineers_bfg_missileRangeIncrement 0.2f
+#define S_engineers_bfg_range 280
+#define S_engineers_bfg_reload 105
+#define S_engineers_level1_area 70
+#define S_engineers_level1_cost 125
+#define S_engineers_level1_maxDamage 14
+#define S_engineers_level1_minDamage 7
+#define S_engineers_level1_range 250
+#define S_engineers_level1_reload 90
+#define S_engineers_level2_area 70
+#define S_engineers_level2_cost 220
+#define S_engineers_level2_maxDamage 39
+#define S_engineers_level2_minDamage 20
+#define S_engineers_level2_range 250
+#define S_engineers_level2_reload 90
+#define S_engineers_level3_area 75
+#define S_engineers_level3_cost 320
+#define S_engineers_level3_maxDamage 66
+#define S_engineers_level3_minDamage 33
+#define S_engineers_level3_range 280
+#define S_engineers_level3_reload 90
+#define S_engineers_tesla_chargedBoltCoolDown 180
+#define S_engineers_tesla_chargedBoltCost 300
+#define S_engineers_tesla_chargedBoltCostLevel 300
+#define S_engineers_tesla_chargedBoltEnemies 3
+#define S_engineers_tesla_chargedBoltIncrementEnemies 1
+#define S_engineers_tesla_chargedBoltLevels 2
+#define S_engineers_tesla_chargedBoltRange 80
+#define S_engineers_tesla_cost 375
+#define S_engineers_tesla_maxDamage 105
+#define S_engineers_tesla_minDamage 55
+#define S_engineers_tesla_overchargeArea 230
+#define S_engineers_tesla_overchargeCoolDown 180
+#define S_engineers_tesla_overchargeCost 250
+#define S_engineers_tesla_overchargeCostLevel 125
+#define S_engineers_tesla_overchargeDamageIncrement 5
+#define S_engineers_tesla_overchargeDisplayRatio 0.7f
+#define S_engineers_tesla_overchargeLevels 3
+#define S_engineers_tesla_overchargeMaxDamage 10
+#define S_engineers_tesla_overchargeMinDamage 0
+#define S_engineers_tesla_range 260
+#define S_engineers_tesla_reload 66
+#define S_mages_arcane_cost 300
+#define S_mages_arcane_deathRayCoolDown 660
+#define S_mages_arcane_deathRayCost 350
+#define S_mages_arcane_deathRayCostLevel 200
+#define S_mages_arcane_deathRayLessCoolDown 60
+#define S_mages_arcane_deathRayLevels 3
+#define S_mages_arcane_maxDamage 140
+#define S_mages_arcane_minDamage 76
+#define S_mages_arcane_range 310
+#define S_mages_arcane_reload 60
+#define S_mages_arcane_teleportCoolDown 300
+#define S_mages_arcane_teleportCost 300
+#define S_mages_arcane_teleportCostLevel 100
+#define S_mages_arcane_teleportExtraEnemies 1
+#define S_mages_arcane_teleportExtraNodes 5
+#define S_mages_arcane_teleportLevels 3
+#define S_mages_arcane_teleportMaxEnemies 3
+#define S_mages_arcane_teleportMaxTimes 3
+#define S_mages_arcane_teleportNodes 20
+#define S_mages_arcane_teleportRange 50
+#define S_mages_level1_cost 100
+#define S_mages_level1_maxDamage 17
+#define S_mages_level1_minDamage 9
+#define S_mages_level1_range 220
+#define S_mages_level1_reload 45
+#define S_mages_level2_cost 160
+#define S_mages_level2_maxDamage 43
+#define S_mages_level2_minDamage 23
+#define S_mages_level2_range 250
+#define S_mages_level2_reload 45
+#define S_mages_level3_cost 240
+#define S_mages_level3_maxDamage 74
+#define S_mages_level3_minDamage 40
+#define S_mages_level3_range 280
+#define S_mages_level3_reload 45
+#define S_mages_sorcerer_cost 300
+#define S_mages_sorcerer_curseArmorReduce 50
+#define S_mages_sorcerer_curseDamage 10
+#define S_mages_sorcerer_curseDuration 150
+#define S_mages_sorcerer_elementalAreaAttackMaxEnemies 4
+#define S_mages_sorcerer_elementalAreaAttackRangeWidth 70
+#define S_mages_sorcerer_elementalArmor 30
+#define S_mages_sorcerer_elementalArmorExtra 10
+#define S_mages_sorcerer_elementalCost 350
+#define S_mages_sorcerer_elementalCostLevel 150
+#define S_mages_sorcerer_elementalDamageExtra 10
+#define S_mages_sorcerer_elementalExtraHealth 100
+#define S_mages_sorcerer_elementalHealth 500
+#define S_mages_sorcerer_elementalLevels 3
+#define S_mages_sorcerer_elementalMaxDamage 80
+#define S_mages_sorcerer_elementalMaxLevel 10
+#define S_mages_sorcerer_elementalMaxSize 2
+#define S_mages_sorcerer_elementalMinDamage 40
+#define S_mages_sorcerer_elementalRallyRange 280
+#define S_mages_sorcerer_elementalRange 120
+#define S_mages_sorcerer_elementalRegen 20
+#define S_mages_sorcerer_elementalRegenReload 30
+#define S_mages_sorcerer_elementalReload 60
+#define S_mages_sorcerer_elementalRespawnTime 240
+#define S_mages_sorcerer_maxDamage 78
+#define S_mages_sorcerer_minDamage 42
+#define S_mages_sorcerer_polymorphCoolDown 660
+#define S_mages_sorcerer_polymorphCost 300
+#define S_mages_sorcerer_polymorphCostLevel 150
+#define S_mages_sorcerer_polymorphDamage 50
+#define S_mages_sorcerer_polymorphLessCoolDown 60
+#define S_mages_sorcerer_polymorphLevels 3
+#define S_mages_sorcerer_polymorphSpeedMultiplier 1.5f
+#define S_mages_sorcerer_range 310
+#define S_mages_sorcerer_reload 45
+#define S_powers_farmers_armor 0
+#define S_powers_farmers_coolDown 300
+#define S_powers_farmers_health 30
+#define S_powers_farmers_lifeTime 600
+#define S_powers_farmers_maxDamage 2
+#define S_powers_farmers_maxLevel 5
+#define S_powers_farmers_maxSize 2
+#define S_powers_farmers_minDamage 1
+#define S_powers_farmers_range 100
+#define S_powers_farmers_regen 3
+#define S_powers_farmers_regenReload 30
+#define S_powers_farmers_reload 30
+#define S_powers_fireball_blazingEarthDamageTime 30
+#define S_powers_fireball_blazingEarthDuration 300
+#define S_powers_fireball_blazingEarthMaxDamage 30
+#define S_powers_fireball_blazingEarthMinDamage 20
+#define S_powers_fireball_blazingEarthRange 100
+#define S_powers_fireball_coolDown 2400
+#define S_powers_fireball_maxDamage 60
+#define S_powers_fireball_minDamage 30
+#define S_powers_fireball_range 100
+#define S_powers_fireball_scorchedEarthDamageTime 30
+#define S_powers_fireball_scorchedEarthDuration 150
+#define S_powers_fireball_scorchedEarthMaxDamage 20
+#define S_powers_fireball_scorchedEarthMinDamage 10
+#define S_powers_fireball_scorchedEarthRange 100
+#define S_powers_knights_armor 0
+#define S_powers_knights_coolDown 300
+#define S_powers_knights_health 200
+#define S_powers_knights_lifeTime 600
+#define S_powers_knights_maxDamage 35
+#define S_powers_knights_maxLevel 5
+#define S_powers_knights_maxSize 2
+#define S_powers_knights_minDamage 25
+#define S_powers_knights_range 100
+#define S_powers_knights_regen 10
+#define S_powers_knights_regenReload 30
+#define S_powers_knights_reload 30
+#define S_powers_lightning_coolDown 750
+#define S_powers_lightning_maxDamage 500
+#define S_powers_lightning_minDamage 1
+#define S_powers_reinforcementLevel1_armor 0
+#define S_powers_reinforcementLevel1_health 50
+#define S_powers_reinforcementLevel1_lifeTime 600
+#define S_powers_reinforcementLevel1_maxDamage 3
+#define S_powers_reinforcementLevel1_minDamage 1
+#define S_powers_reinforcementLevel1_range 100
+#define S_powers_reinforcementLevel1_regen 6
+#define S_powers_reinforcementLevel1_regenReload 30
+#define S_powers_reinforcementLevel1_reload 30
+#define S_powers_reinforcementLevel2_armor 10
+#define S_powers_reinforcementLevel2_coolDown 300
+#define S_powers_reinforcementLevel2_health 70
+#define S_powers_reinforcementLevel2_lifeTime 600
+#define S_powers_reinforcementLevel2_maxDamage 4
+#define S_powers_reinforcementLevel2_maxLevel 5
+#define S_powers_reinforcementLevel2_maxSize 2
+#define S_powers_reinforcementLevel2_minDamage 2
+#define S_powers_reinforcementLevel2_range 100
+#define S_powers_reinforcementLevel2_regen 9
+#define S_powers_reinforcementLevel2_regenReload 30
+#define S_powers_reinforcementLevel2_reload 30
+#define S_powers_reinforcementLevel3_armor 20
+#define S_powers_reinforcementLevel3_coolDown 300
+#define S_powers_reinforcementLevel3_health 90
+#define S_powers_reinforcementLevel3_lifeTime 600
+#define S_powers_reinforcementLevel3_maxDamage 6
+#define S_powers_reinforcementLevel3_maxLevel 5
+#define S_powers_reinforcementLevel3_maxSize 2
+#define S_powers_reinforcementLevel3_minDamage 3
+#define S_powers_reinforcementLevel3_range 100
+#define S_powers_reinforcementLevel3_regen 12
+#define S_powers_reinforcementLevel3_regenReload 30
+#define S_powers_reinforcementLevel3_reload 30
+#define S_powers_reinforcementLevel4_armor 30
+#define S_powers_reinforcementLevel4_coolDown 300
+#define S_powers_reinforcementLevel4_health 110
+#define S_powers_reinforcementLevel4_lifeTime 600
+#define S_powers_reinforcementLevel4_maxDamage 10
+#define S_powers_reinforcementLevel4_maxLevel 5
+#define S_powers_reinforcementLevel4_maxSize 2
+#define S_powers_reinforcementLevel4_minDamage 6
+#define S_powers_reinforcementLevel4_range 100
+#define S_powers_reinforcementLevel4_regen 15
+#define S_powers_reinforcementLevel4_regenReload 30
+#define S_powers_reinforcementLevel4_reload 30
+#define S_powers_reinforcementLevel4_spearCoolDown 30
+#define S_powers_reinforcementLevel4_spearMaxDamage 40
+#define S_powers_reinforcementLevel4_spearMinDamage 24
+#define S_powers_reinforcementLevel4_spearMinRange 40
+#define S_powers_reinforcementLevel4_spearRange 260
+#define S_soldiers_barbarian_armor 0
+#define S_soldiers_barbarian_cost 230
+#define S_soldiers_barbarian_dualWeaponsCost 300
+#define S_soldiers_barbarian_dualWeaponsCostLevel 100
+#define S_soldiers_barbarian_dualWeaponsIncrementDamage 10
+#define S_soldiers_barbarian_dualWeaponsLevels 3
+#define S_soldiers_barbarian_health 200
+#define S_soldiers_barbarian_huntingNetsCoolDown 90
+#define S_soldiers_barbarian_huntingNetsCost 150
+#define S_soldiers_barbarian_huntingNetsCostLevel 75
+#define S_soldiers_barbarian_huntingNetsDuration 90
+#define S_soldiers_barbarian_huntingNetsLevels 3
+#define S_soldiers_barbarian_huntingNetsNewSpeed 30
+#define S_soldiers_barbarian_huntingNetsNewSpeedIncrement 15
+#define S_soldiers_barbarian_huntingNetsRange 150
+#define S_soldiers_barbarian_maxDamage 24
+#define S_soldiers_barbarian_maxLevel 5
+#define S_soldiers_barbarian_maxSize 1
+#define S_soldiers_barbarian_minDamage 16
+#define S_soldiers_barbarian_range 100
+#define S_soldiers_barbarian_rangeRally 230
+#define S_soldiers_barbarian_regen 20
+#define S_soldiers_barbarian_regenReload 30
+#define S_soldiers_barbarian_reload 30
+#define S_soldiers_barbarian_respawn 300
+#define S_soldiers_barbarian_throwingCoolDown 90
+#define S_soldiers_barbarian_throwingCost 200
+#define S_soldiers_barbarian_throwingCostLevel 100
+#define S_soldiers_barbarian_throwingIncrementDamage 10
+#define S_soldiers_barbarian_throwingIncrementRange 20
+#define S_soldiers_barbarian_throwingLevels 3
+#define S_soldiers_barbarian_throwingMaxDamage 32
+#define S_soldiers_barbarian_throwingMinDamage 24
+#define S_soldiers_barbarian_throwingMinRange 40
+#define S_soldiers_barbarian_throwingRange 240
+#define S_soldiers_level1_armor 0
+#define S_soldiers_level1_cost 70
+#define S_soldiers_level1_health 50
+#define S_soldiers_level1_maxDamage 3
+#define S_soldiers_level1_maxLevel 5
+#define S_soldiers_level1_maxSize 1
+#define S_soldiers_level1_minDamage 1
+#define S_soldiers_level1_range 100
+#define S_soldiers_level1_rangeRally 230
+#define S_soldiers_level1_regen 5
+#define S_soldiers_level1_regenReload 30
+#define S_soldiers_level1_reload 30
+#define S_soldiers_level1_respawn 300
+#define S_soldiers_level2_armor 15
+#define S_soldiers_level2_cost 110
+#define S_soldiers_level2_health 100
+#define S_soldiers_level2_maxDamage 4
+#define S_soldiers_level2_maxLevel 5
+#define S_soldiers_level2_maxSize 1
+#define S_soldiers_level2_minDamage 3
+#define S_soldiers_level2_range 100
+#define S_soldiers_level2_rangeRally 230
+#define S_soldiers_level2_regen 7
+#define S_soldiers_level2_regenReload 30
+#define S_soldiers_level2_reload 30
+#define S_soldiers_level2_respawn 300
+#define S_soldiers_level3_armor 30
+#define S_soldiers_level3_cost 160
+#define S_soldiers_level3_health 150
+#define S_soldiers_level3_maxDamage 10
+#define S_soldiers_level3_maxLevel 5
+#define S_soldiers_level3_maxSize 1
+#define S_soldiers_level3_minDamage 6
+#define S_soldiers_level3_range 100
+#define S_soldiers_level3_rangeRally 230
+#define S_soldiers_level3_regen 10
+#define S_soldiers_level3_regenReload 30
+#define S_soldiers_level3_reload 30
+#define S_soldiers_level3_respawn 300
+#define S_soldiers_paladin_armor 50
+#define S_soldiers_paladin_cost 230
+#define S_soldiers_paladin_healingCoolDown 300
+#define S_soldiers_paladin_healingCost 150
+#define S_soldiers_paladin_healingCostLevel 150
+#define S_soldiers_paladin_healingLevels 3
+#define S_soldiers_paladin_healingMax 60
+#define S_soldiers_paladin_healingMin 40
+#define S_soldiers_paladin_health 200
+#define S_soldiers_paladin_holyStrikeChance 10
+#define S_soldiers_paladin_holyStrikeCost 220
+#define S_soldiers_paladin_holyStrikeCostLevel 150
+#define S_soldiers_paladin_holyStrikeLevels 3
+#define S_soldiers_paladin_holyStrikeMaxDamage 45
+#define S_soldiers_paladin_holyStrikeMinDamage 25
+#define S_soldiers_paladin_holyStrikeMinEnemies 1
+#define S_soldiers_paladin_holyStrikeRange 80
+#define S_soldiers_paladin_maxDamage 18
+#define S_soldiers_paladin_maxLevel 5
+#define S_soldiers_paladin_maxSize 1
+#define S_soldiers_paladin_minDamage 12
+#define S_soldiers_paladin_range 100
+#define S_soldiers_paladin_rangeRally 230
+#define S_soldiers_paladin_regen 25
+#define S_soldiers_paladin_regenReload 30
+#define S_soldiers_paladin_reload 30
+#define S_soldiers_paladin_respawn 420
+#define S_soldiers_paladin_shieldArmor 15
+#define S_soldiers_paladin_shieldCost 250
+#define S_soldiers_paladin_shieldCostLevel 100
+#define S_soldiers_paladin_shieldLevels 1
+#define S_soldiers_paladin_shieldMaxSize 2
+#endif
diff --git a/games/kingdomrush/src/soldier.c b/games/kingdomrush/src/soldier.c
new file mode 100644
index 00000000..b5a542c3
--- /dev/null
+++ b/games/kingdomrush/src/soldier.c
@@ -0,0 +1,380 @@
+/* The soldiers (Soldier.as and its kinds: SoldierStandar*, the reinforcements, the paladins', barbarians' and the
+ * sorcerer's elemental, whose specials are in special.c). */
+#include <math.h>
+#include <string.h>
+#include "kr.h"
+#include "settings.h"
+#include "special.h"
+
+typedef struct {
+ int16_t charge, charge_dmg, speed10, respawn_wait, x_adj;
+ int16_t an_idle, an_run, an_fight, an_dead, an_spawn;
+} SoldierKind;
+
+static SoldierKind kind_of(int k) {
+ switch (k) {
+ case SK_L1: return (SoldierKind){11, 5, 20, 1, 0, AN_SO_STANDAR_IDLE, AN_SO_STANDAR_RUNNING, AN_SO_STANDAR_FIGHTING, AN_SO_STANDAR_DEAD, -1};
+ case SK_L2: return (SoldierKind){20, 5, 20, 1, 0, AN_SO_STANDARLEVEL2_IDLE, AN_SO_STANDARLEVEL2_RUNNING, AN_SO_STANDARLEVEL2_FIGHTING, AN_SO_STANDARLEVEL2_DEAD, -1};
+ case SK_L3: return (SoldierKind){20, 5, 20, 1, 0, AN_SO_STANDARLEVEL3_IDLE, AN_SO_STANDARLEVEL3_RUNNING, AN_SO_STANDARLEVEL3_FIGHTING, AN_SO_STANDARLEVEL3_DEAD, -1};
+ case SK_PALADIN: return (SoldierKind){20, 5, 20, 1, 0, AN_SO_PALADIN_IDLE, AN_SO_PALADIN_RUNNING, AN_SO_PALADIN_ATTACK1, AN_SO_PALADIN_DEAD, -1};
+ case SK_BARBARIAN: return (SoldierKind){20, 5, 20, 1, 0, AN_SO_BARBARIAN_IDLE, AN_SO_BARBARIAN_RUNNING, AN_SO_BARBARIAN_ATTACK, AN_SO_BARBARIAN_DEAD, -1};
+ case SK_FARMER: return (SoldierKind){11, 5, 20, 6, 5, AN_SO_FARMERJOHN_IDLE, AN_SO_FARMERJOHN_RUNNING, AN_SO_FARMERJOHN_FIGHTING, AN_SO_FARMERJOHN_DEAD, AN_SO_FARMERJOHN_RESPAWNING};
+ case SK_REINF2: return (SoldierKind){11, 5, 20, 6, 5, AN_SO_REINFORCEMENTLEVEL2A_IDLE, AN_SO_REINFORCEMENTLEVEL2A_RUNNING, AN_SO_REINFORCEMENTLEVEL2A_FIGHTING, AN_SO_REINFORCEMENTLEVEL2A_DEAD, AN_SO_REINFORCEMENTLEVEL2A_RESPAWNING};
+ case SK_REINF3: return (SoldierKind){11, 5, 20, 6, 5, AN_SO_REINFORCEMENTLEVEL3A_IDLE, AN_SO_REINFORCEMENTLEVEL3A_RUNNING, AN_SO_REINFORCEMENTLEVEL3A_FIGHTING, AN_SO_REINFORCEMENTLEVEL3A_DEAD, AN_SO_REINFORCEMENTLEVEL3A_RESPAWNING};
+ case SK_REINF4: return (SoldierKind){11, 5, 20, 6, 5, AN_SO_REINFORCEMENTLEVEL4A_IDLE, AN_SO_REINFORCEMENTLEVEL4A_RUNNING, AN_SO_REINFORCEMENTLEVEL4A_FIGHTING, AN_SO_REINFORCEMENTLEVEL4A_DEAD, AN_SO_REINFORCEMENTLEVEL4A_RESPAWNING};
+ default: return (SoldierKind){30, 13, 13, 27, 0, AN_SO_ELEMENTAL_IDLE, AN_SO_ELEMENTAL_RUNNING, AN_SO_ELEMENTAL_FIGHTING, AN_SO_ELEMENTAL_DEAD, AN_SO_ELEMENTAL_RESPAWNING};
+ }
+}
+
+static void play(Soldier *so, int an) {
+ if (an < 0) return;
+ so->anim = (uint16_t)an, so->anim_t = 0;
+}
+
+static bool reinforcement(const Soldier *so) { return so->kind >= SK_FARMER && so->kind <= SK_REINF4; }
+
+int soldier_new(int kind, int spot, Pt at, Pt rally) {
+ int i = 0;
+ while (i < MAX_SOLDIERS && B.so[i].alive) i++;
+ if (i == MAX_SOLDIERS) return -1;
+ Soldier *so = &B.so[i];
+ memset(so, 0, sizeof *so);
+ SoldierKind k = kind_of(kind);
+ so->alive = 1, so->kind = (uint8_t)kind, so->spot = (int8_t)spot, so->enemy = -1;
+ so->x = at.x, so->y = at.y, so->rx = rally.x, so->ry = rally.y, so->dx = rally.x, so->dy = rally.y;
+ so->charge = k.charge, so->charge_dmg = k.charge_dmg, so->speed = k.speed10 / 10.0f;
+ so->door_wait = k.respawn_wait, so->idle_time = 30;
+ so->hidden = 1, so->respawning = 1;
+ if (spot >= 0 && kind <= SK_BARBARIAN) {
+ int tk = B.spot[spot].kind;
+ BarrackStat b = barrack_stat(tk, B.spot[spot].level);
+ so->health = so->init_health = b.health, so->armor = b.armor;
+ so->min_dmg = b.min_dmg, so->max_dmg = b.max_dmg;
+ so->reload = (int16_t)(kind == SK_L1 ? b.reload - so->charge : b.reload);
+ so->dead_time = b.respawn, so->regen = b.regen, so->regen_reload = b.regen_reload;
+ so->range_w = b.range, so->range_h = (int16_t)(b.range * RANGE_RATIO);
+ } else if (reinforcement(so)) {
+ int lvl = kind == SK_FARMER ? (upgrades[UP_REINF] >= 1 ? 1 : 0) : kind - SK_REINF2 + 2;
+ static const int16_t hp[5] = {S_powers_farmers_health, S_powers_reinforcementLevel1_health, S_powers_reinforcementLevel2_health,
+ S_powers_reinforcementLevel3_health, S_powers_reinforcementLevel4_health};
+ static const int16_t ar[5] = {S_powers_farmers_armor, S_powers_reinforcementLevel1_armor, S_powers_reinforcementLevel2_armor,
+ S_powers_reinforcementLevel3_armor, S_powers_reinforcementLevel4_armor};
+ static const int16_t lo[5] = {S_powers_farmers_minDamage, S_powers_reinforcementLevel1_minDamage, S_powers_reinforcementLevel2_minDamage,
+ S_powers_reinforcementLevel3_minDamage, S_powers_reinforcementLevel4_minDamage};
+ static const int16_t hi[5] = {S_powers_farmers_maxDamage, S_powers_reinforcementLevel1_maxDamage, S_powers_reinforcementLevel2_maxDamage,
+ S_powers_reinforcementLevel3_maxDamage, S_powers_reinforcementLevel4_maxDamage};
+ static const int16_t rg[5] = {S_powers_farmers_regen, S_powers_reinforcementLevel1_regen, S_powers_reinforcementLevel2_regen,
+ S_powers_reinforcementLevel3_regen, S_powers_reinforcementLevel4_regen};
+ so->level = (uint8_t)lvl;
+ so->health = so->init_health = hp[lvl], so->armor = ar[lvl], so->min_dmg = lo[lvl], so->max_dmg = hi[lvl];
+ so->regen = rg[lvl], so->regen_reload = FPS;
+ so->reload = (int16_t)(FPS - so->charge);
+ so->range_w = 100, so->range_h = 70;
+ so->life_time = 20 * FPS;
+ /* they start dead, appear (respawning) at once, live 20 s and are gone when they fall */
+ so->respawning = 0, so->dead = 1, so->lifes = 1, so->dead_time = 10, so->dead_t = 9;
+ so->home_x = at.x, so->home_y = at.y;
+ } else { /* the sorcerer's elemental */
+ special_elemental_stats(so, spot);
+ }
+ play(so, k.an_idle);
+ return i;
+}
+
+void soldier_free(Soldier *so) {
+ Enemy *e = EN(so->enemy);
+ if (e) {
+ if (so->blocking) {
+ if (e->soldier == so - B.so) enemy_unblock(e);
+ } else if (so->fighting)
+ enemy_free_position(e, so->fpos);
+ }
+ so->alive = 0;
+}
+
+/* §_-02§: stops fighting */
+static void stop_fight(Soldier *so) {
+ Enemy *e = EN(so->enemy);
+ so->blocking = 0, so->fighting = 0, so->charging = 0, so->charge_t = 0;
+ if (e) enemy_free_position(e, so->fpos);
+ so->enemy = -1;
+}
+
+/* §_-LT§: back to the rally point */
+static void go_home(Soldier *so) {
+ if (!so->walking) {
+ so->idle = 0, so->walking = 1;
+ play(so, kind_of(so->kind).an_run);
+ }
+ so->enemy = -1, so->fighting = 0, so->blocking = 0, so->charging = 0;
+ so->dx = so->rx, so->dy = so->ry;
+}
+
+void soldier_set_rally(Soldier *so, Pt p) { /* changeRallyPoint */
+ so->rx = p.x, so->ry = p.y;
+ if (so->dead || so->respawning) return;
+ so->active = 0;
+ stop_fight(so);
+ go_home(so);
+ special_soldier_stop(so);
+}
+
+void soldier_damage(Soldier *so, int dmg, bool true_dmg) {
+ if (!so->active && !so->walking) return;
+ so->targeted_t = 0;
+ int loss = true_dmg ? dmg : (int)((float)dmg - (float)so->armor * dmg / 100.0f);
+ /* (the shield of the paladins and the elemental's armour are in its armour) */
+ so->health = (int16_t)(so->health - loss);
+ if (so->health <= 0) {
+ so->health = 0;
+ so->active = 0, so->dead = 1, so->charging = 0, so->charge_t = 0;
+ play(so, kind_of(so->kind).an_dead);
+ if (so->blocking) stop_fight(so);
+ else if (so->fighting) stop_fight(so);
+ so->dead_t = 0;
+ return;
+ }
+ /* Barbed Armor: the attacker takes a tenth back */
+ if (up_on(UP_BARRACKS, 5) && so->spot >= 0 && so->kind <= SK_BARBARIAN) {
+ Enemy *e = EN(so->enemy);
+ if (e && e->active) {
+ enemy_damage(e, (int)ceilf(dmg * 0.1f), ARM_I, 0);
+ if (!e->active) stop_fight(so);
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ fights */
+static bool in_range(const Soldier *so, const Enemy *e) {
+ float cx, cy;
+ if (reinforcement(so)) cx = so->home_x, cy = so->home_y;
+ else if (so->spot >= 0 && so->kind == SK_ELEMENTAL) cx = so->rx, cy = so->ry;
+ else if (so->spot >= 0) cx = B.spot[so->spot].rally.x, cy = B.spot[so->spot].rally.y + 10;
+ else cx = so->rx, cy = so->ry;
+ return ellipse_contains(cx, cy, so->range_w, so->range_h, e->x, e->y);
+}
+
+static void fight_position(Soldier *so) { /* setFightingPosition */
+ Enemy *e = EN(so->enemy);
+ if (!e) return;
+ float dy = 0, dx = 0;
+ if (so->fpos == 0) dy = 6, dx = 3;
+ else if (so->fpos == 1) dy = -6, dx = 3;
+ int xadj = kind_of(so->kind).x_adj, xs = enemy_stats[e->type].x_soldier;
+ so->dy = roundf(e->y) + dy;
+ if (!e->left) so->dx = roundf(e->x) + xadj + xs - dx;
+ else so->dx = roundf(e->x) - xadj - xs + dx;
+ play(so, kind_of(so->kind).an_run);
+}
+
+static void engage(Soldier *so, int i, bool block) {
+ Enemy *e = &B.en[i];
+ if (block) { /* §_-Df§: it stops the enemy */
+ if (so->fighting) {
+ Enemy *o = EN(so->enemy);
+ if (o) enemy_free_position(o, so->fpos);
+ }
+ so->fighting = 1, so->blocking = 1, so->walking = 1, so->idle = 0;
+ so->enemy = (int8_t)i;
+ enemy_block(e, (int)(so - B.so));
+ so->fpos = 2;
+ } else { /* §_-Fc§: it joins a fight *
+ */
+ so->walking = 1, so->blocking = 0, so->fighting = 1, so->idle = 0;
+ so->enemy = (int8_t)i;
+ so->fpos = (uint8_t)enemy_fighter_position(e);
+ }
+ so->reload_t = (int16_t)(so->reload - 1);
+ fight_position(so);
+}
+
+/* findEnemy: an unblocked enemy first (the nearest the start), else one already held */
+static bool find_enemy(Soldier *so) {
+ if (so->blocking) return false;
+ int free_e = -1, held_e = -1;
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive || !e->active || !enemy_stats[e->type].blockable || e->flying || !in_range(so, e)) continue;
+ if (!e->blocked) {
+ if (free_e < 0 || B.en[free_e].node > e->node) free_e = i;
+ } else if (!so->fighting && (held_e < 0 || B.en[held_e].node > e->node))
+ held_e = i;
+ }
+ if (free_e >= 0) {
+ engage(so, free_e, true);
+ return true;
+ }
+ if (held_e >= 0) {
+ engage(so, held_e, false);
+ return true;
+ }
+ return false;
+}
+
+static void face_enemy(Soldier *so) { /* §_-7g§ */
+ Enemy *e = EN(so->enemy);
+ if (!e) return;
+ if (!e->left) so->left = 1;
+ else so->left = 0, e->left = 1;
+}
+
+static void hit(Soldier *so) {
+ Enemy *e = EN(so->enemy);
+ if (!e || !e->active) {
+ stop_fight(so);
+ go_home(so);
+ return;
+ }
+ if (!enemy_dodge(e)) {
+ enemy_damage(e, special_soldier_damage(so, rnd_dmg(so->min_dmg, so->max_dmg)), ARM_P, 0);
+ if (!e->active) stop_fight(so);
+ }
+}
+
+/* §_-Ha§: walking to where it goes; false while on the way */
+static bool walk(Soldier *so) {
+ if (so->active) {
+ if (so->fighting) {
+ Enemy *e = EN(so->enemy);
+ if (!e || !e->active || !e->blocked) {
+ stop_fight(so);
+ if (!find_enemy(so)) go_home(so);
+ } else if (!so->blocking)
+ find_enemy(so);
+ } else
+ find_enemy(so);
+ }
+ float dx = so->dx - so->x, dy = so->dy - so->y;
+ if (sqrtf(dx * dx + dy * dy) <= so->speed) { /* §_-Eo§: arrived */
+ so->walking = 0, so->active = 1;
+ so->x = roundf(so->dx), so->y = roundf(so->dy);
+ if (so->fighting) {
+ face_enemy(so);
+ Enemy *e = EN(so->enemy);
+ if (so->blocking && e && e->active) enemy_start_fighting(e);
+ } else
+ so->idle = 1;
+ play(so, kind_of(so->kind).an_idle);
+ return true;
+ }
+ float a = atan2f(dy, dx);
+ so->left = so->dx < so->x;
+ so->x += cosf(a) * so->speed, so->y += sinf(a) * so->speed;
+ return false;
+}
+
+static void respawn(Soldier *so) {
+ so->active = 1, so->dead = 0, so->respawning = 0, so->walking = 1;
+ so->charging = 0, so->blocking = 0, so->fighting = 0, so->idle = 0, so->hidden = 0;
+ if (so->spot >= 0 && !reinforcement(so) && so->kind != SK_ELEMENTAL) {
+ so->x = B.spot[so->spot].x, so->y = B.spot[so->spot].y - 1;
+ }
+ so->dx = so->rx, so->dy = so->ry;
+ so->health = so->init_health;
+ so->dead_t = 0, so->door_t = 0;
+ play(so, kind_of(so->kind).an_run);
+}
+
+static void idle(Soldier *so) { /* playIdle: turns now and then; heals after 2 s untouched */
+ so->targeted_t++;
+ if (++so->idle_t >= so->idle_time) {
+ if (roundf(rnd() * 10) < 4) so->left = !so->left;
+ so->idle_t = 0;
+ }
+ if (so->targeted_t < 60) return;
+ so->targeted_t = 60;
+ if (++so->regen_t >= so->regen_reload) {
+ if (so->health < so->init_health) {
+ so->health = (int16_t)(so->health + so->regen);
+ if (so->health > so->init_health) so->health = so->init_health;
+ }
+ so->regen_t = 0;
+ }
+}
+
+/* ------------------------------------------------------------------ a frame */
+void soldier_step(Soldier *so) {
+ so->anim_t++;
+ if (so->dead) { /* readyToRespawn */
+ if (++so->dead_t < so->dead_time) return;
+ if (reinforcement(so)) {
+ if (so->lifes != 1) {
+ so->alive = 0;
+ return;
+ }
+ so->lifes = 2, so->dead = 0, so->respawning = 1, so->door_t = 0, so->hidden = 0;
+ play(so, kind_of(so->kind).an_spawn);
+ return;
+ }
+ if (so->kind == SK_ELEMENTAL) {
+ so->dead = 0, so->respawning = 1, so->door_t = 0, so->hidden = 0;
+ so->x = so->rx, so->y = so->ry;
+ play(so, kind_of(so->kind).an_spawn);
+ return;
+ }
+ so->dead = 0, so->door_queued = 0, so->respawning = 1, so->hidden = 1;
+ return;
+ }
+ if (so->respawning) { /* readyToLive */
+ if (reinforcement(so) || so->kind == SK_ELEMENTAL) {
+ if (++so->door_t >= so->door_wait) respawn(so);
+ return;
+ }
+ if (so->spot < 0 || B.spot[so->spot].disabled) return;
+ so->hidden = 1;
+ if (!so->door_queued) {
+ int s = so->spot;
+ if (barracks_door_closed(s)) {
+ barracks_open(s);
+ so->door_wait = 12, so->door_queued = 1;
+ } else if (barracks_door_opening(s)) {
+ so->door_wait = (int16_t)(12 - barracks_door_t(s)), so->door_queued = 1;
+ } else
+ return;
+ }
+ if (++so->door_t >= so->door_wait) respawn(so);
+ return;
+ }
+ if (reinforcement(so) && ++so->life_t >= so->life_time) { /* readyToHide */
+ so->active = 0, so->dead = 1, so->dead_t = 0, so->lifes = 2;
+ play(so, kind_of(so->kind).an_dead);
+ if (so->blocking || so->fighting) stop_fight(so);
+ return;
+ }
+ if (special_soldier(so)) return;
+ if (so->active && !so->fighting && !so->blocking && so->charge_t != 0) { /* a blow finishing */
+ if (so->charge_t < so->charge) {
+ so->charge_t++;
+ return;
+ }
+ so->charge_t = 0;
+ go_home(so);
+ }
+ if (so->walking && !walk(so)) return;
+ if (!so->active) return;
+ if (so->idle) {
+ if (!find_enemy(so)) idle(so);
+ } else if (so->fighting) {
+ Enemy *e = EN(so->enemy);
+ if (!e || !e->active) stop_fight(so);
+ e = EN(so->enemy);
+ if (so->fighting && !so->blocking && (!e || !e->blocked)) stop_fight(so);
+ if (!so->blocking && find_enemy(so)) return;
+ if (!so->fighting) {
+ go_home(so);
+ return;
+ }
+ if (so->charging) { /* §_-Jy§ */
+ if (++so->charge_t < so->charge) {
+ if (so->charge_t == so->charge_dmg) hit(so);
+ return;
+ }
+ so->charge_t = 0, so->charging = 0;
+ } else if (++so->reload_t == so->reload) {
+ play(so, kind_of(so->kind).an_fight);
+ special_soldier_attack_anim(so);
+ so->charging = 1, so->reload_t = 0;
+ }
+ } else
+ go_home(so);
+}
diff --git a/games/kingdomrush/src/special.c b/games/kingdomrush/src/special.c
new file mode 100644
index 00000000..548c5700
--- /dev/null
+++ b/games/kingdomrush/src/special.c
@@ -0,0 +1,57 @@
+/* The special towers (TowerArcherRanger, TowerArcherMusketeer, TowerMageArcane, TowerMageSorcerer,
+ * TowerEngineerBfg, TowerEngineerTesla, TowerSoldierPaladin, TowerSoldierBarbarian), their abilities and
+ * soldiers; and the hits every mage bolt and bomb share. */
+#include <math.h>
+#include <string.h>
+#include "special.h"
+#include "settings.h"
+#include "anim.h"
+
+int special_kind(int kind, int choice) {
+ switch (kind) {
+ case TW_ARCHER: return choice == 1 ? TW_MUSKETEER : TW_RANGER;
+ case TW_MAGE: return choice == 1 ? TW_ARCANE : TW_SORCERER;
+ case TW_ENGINEER: return choice == 1 ? TW_TESLA : TW_BFG;
+ case TW_BARRACKS: return choice == 1 ? TW_PALADIN : TW_BARBARIAN;
+ default: return kind;
+ }
+}
+
+int special_abilities(int s, Ability *a) { (void)s, (void)a; return 0; }
+void spot_buy_ability(int s, int k) { (void)s, (void)k; }
+int spot_ability_cost(int s, int k) { (void)s, (void)k; return -1; }
+void special_draw_bullet(const Bullet *b, int x, int y) { (void)b, (void)x, (void)y; }
+void special_init(int s) { (void)s; }
+void special_sold(int s) { (void)s; }
+void special_timers(int s) { (void)s; }
+bool special_run(int s) { (void)s; return false; }
+bool special_shoot(int s) { (void)s; return false; }
+void special_arrow(int s, Bullet *b) { (void)s, (void)b; }
+void special_bolt(int s, Bullet *b) { (void)s, (void)b; }
+void special_bomb(int s, Bullet *b) { (void)s, (void)b; }
+void special_bullet(Bullet *b) { b->alive = 0; }
+void special_scorched_earth(float x, float y) { (void)x, (void)y; }
+void special_rally(int s, Pt p) { (void)s, (void)p; }
+void special_elemental_stats(Soldier *so, int spot) { (void)so, (void)spot; }
+bool special_soldier(Soldier *so) { (void)so; return false; }
+void special_soldier_stop(Soldier *so) { (void)so; }
+int special_soldier_damage(Soldier *so, int dmg) { (void)so; return dmg; }
+void special_soldier_attack_anim(Soldier *so) { (void)so; }
+
+void special_poison(Enemy *e, int level) {
+ if (e->poison_t && e->poison_lvl > level) return;
+ e->poison_lvl = (int16_t)level, e->poison_t = S_archers_ranger_poisonDuration, e->poison_tick = 0;
+}
+
+/* Bolt.hitOnTarget: magic damage; Slow Curse halves its speed half a second, Arcane Shatter takes 3 armour */
+void special_bolt_hit(Bullet *b, Enemy *e) {
+ bool slow = up_on(UP_MAGES, 5) && !e->rage_t && !e->slow_t && !e->net_t;
+ enemy_damage(e, rnd_dmg(b->min_dmg, b->max_dmg), ARM_M, 0);
+ if (slow && !e->dead) {
+ e->slow_speed = e->speed, e->speed /= 2, e->margin = e->speed + 0.1f;
+ e->slow_t = 15;
+ }
+ if (up_on(UP_MAGES, 2) && e->active) enemy_armor_down(e, 3);
+}
+
+void special_bomb_hit(Bullet *b) { bomb_blast(b); }
diff --git a/games/kingdomrush/src/special.h b/games/kingdomrush/src/special.h
new file mode 100644
index 00000000..9749890c
--- /dev/null
+++ b/games/kingdomrush/src/special.h
@@ -0,0 +1,45 @@
+/* Kingdom Rush: the special towers' abilities and their soldiers (special.c), and what tower.c shares. */
+#ifndef KR_SPECIAL_H
+#define KR_SPECIAL_H
+#include "kr.h"
+
+/* tower.c */
+bool tower_in_range(const Spot *t, float x, float y);
+int tower_find_target(Spot *t, bool fliers, bool predicted);
+void barracks_step(int s);
+bool barracks_door_closed(int s);
+bool barracks_door_opening(int s);
+int barracks_door_t(int s);
+void barracks_open(int s);
+
+/* special.c */
+typedef struct {
+ uint8_t icon, pos, level, max; /* its menu icon and place (TowerMenu's), its level and top */
+ int16_t cost; /* the next level's price */
+ const char *key; /* its name (strings.c) */
+} Ability;
+int special_abilities(int s, Ability *a); /* up to 3 */
+int special_kind(int kind, int choice); /* the tower a level 3 becomes: choice 1 or 2 */
+void special_init(int s); /* a tower finished, upgraded or turned special */
+void special_sold(int s);
+void special_timers(int s); /* runSpecialTimers */
+bool special_run(int s); /* runSpecial: an ability used instead of a shot */
+bool special_shoot(int s); /* the special towers' own shots */
+void special_arrow(int s, Bullet *b);
+void special_bolt(int s, Bullet *b);
+void special_bomb(int s, Bullet *b);
+void special_bolt_hit(Bullet *b, Enemy *e);
+void special_bomb_hit(Bullet *b);
+void special_bullet(Bullet *b);
+void special_poison(Enemy *e, int level);
+void special_scorched_earth(float x, float y);
+void special_rally(int s, Pt p);
+/* soldiers */
+void special_elemental_stats(Soldier *so, int spot);
+bool special_soldier(Soldier *so); /* runSpecial */
+void special_soldier_stop(Soldier *so);
+int special_soldier_damage(Soldier *so, int dmg);
+void special_soldier_attack_anim(Soldier *so);
+void bomb_blast(Bullet *b);
+void special_draw_bullet(const Bullet *b, int x, int y);
+#endif
diff --git a/games/kingdomrush/src/stats.c b/games/kingdomrush/src/stats.c
new file mode 100644
index 00000000..52c00508
--- /dev/null
+++ b/games/kingdomrush/src/stats.c
@@ -0,0 +1,123 @@
+/* Made by tools/pack.py from the game's GameSettings and its enemies' classes. */
+#include "anim.h"
+#include "kr.h"
+
+const EnemyStat enemy_stats[EN_COUNT] = {
+ {20, 0, 0, 0, 3, 1, 1, 4, 30, 1.2f,0, 0, 0, 1, 14, 15, 0, -8, -20, 0, 18, 24, 50, 0}, /* Goblin */
+ {80, 30, 0, 0, 9, 1, 4, 8, 30, 0.8f,1, 0, 0, 1, 10, 15, 0, -8, -23, 0, 21, 24, 50, 0}, /* FatOrc */
+ {35, 0, 0, 30, 5, 1, 1, 3, 30, 2.5f,0, 0, 0, 1, 8, 15, 0, -8, -20, 0, 23, 26, 15, 0}, /* WolfSmall */
+ {100, 0, 85, 0, 10, 1, 3, 5, 30, 1.0f,0, 0, 0, 1, 17, 15, 0, -8, -25, 0, 26, 41, 50, 0}, /* Shaman */
+ {800, 0, 0, 0, 50, 3, 40, 60, 30, 0.7f,2, 0, 0, 1, 27, 25, 3, -18, -39, 1, 30, 51, 50, 0}, /* Ogre */
+ {70, 0, 0, 50, 8, 1, 20, 30, 30, 1.2f,0, 0, 0, 1, 8, 15, 0, -8, -23, 0, 11, 20, 50, 0}, /* Bandit */
+ {160, 50, 0, 0, 15, 1, 6, 10, 30, 0.8f,0, 0, 0, 1, 13, 15, 0, -8, -25, 0, 12, 24, 50, 0}, /* Brigand */
+ {600, 60, 0, 0, 40, 3, 16, 24, 30, 0.8f,2, 0, 0, 1, 13, 20, 0, -18, -39, 1, 22, 35, 50, 0}, /* Marauder */
+ {120, 0, 50, 50, 12, 1, 12, 18, 30, 2.0f,1, 0, 0, 1, 8, 20, 0, -8, -24, 0, 14, 18, 15, 0}, /* Wolf */
+ {250, 0, 80, 0, 20, 2, 15, 25, 30, 1.0f,0, 0, 0, 1, 17, 24, 1, -8, -25, 0, 20, 25, 50, 1}, /* Spider */
+ {60, 0, 65, 0, 6, 1, 10, 18, 30, 1.5f,0, 0, 0, 1, 17, 18, 1, -8, -18, 0, 12, 17, 50, 1}, /* SpiderSmall */
+ {10, 0, 50, 0, 0, 1, 1, 5, 30, 2.0f,0, 0, 0, 1, 17, 14, 1, -4, -13, 0, 10, 18, 50, 1}, /* SpiderTiny */
+ {180, 0, 30, 0, 16, 1, 10, 20, 30, 1.2f,0, 0, 0, 1, 7, 15, 1, -8, -25, 0, 22, 22, 50, 0}, /* ShadowArcher */
+ {300, 80, 0, 0, 25, 1, 15, 25, 30, 0.7f,0, 0, 0, 1, 10, 20, 0, -10, -28, 0, 22, 31, 50, 0}, /* DarkKnight */
+ {90, 0, 0, 0, 12, 1, 1, 2, 30, 1.2f,0, 1, 0, 0, 8, 15, 3, -45, -60, 0, 23, 73, 50, 0}, /* Gargoyle */
+ {10000, 0, 0, 0, 0, 20, 150, 250, 60, 0.4f,2, 0, 1, 1, 28, 35, 0, -30, -90, 2, 58, 92, 200, 2}, /* Juggernaut */
+ {125, 0, 0, 0, 10, 1, 10, 20, 30, 0.7f,0, 0, 0, 1, 17, 14, 1, -8, -17, 0, 14, 20, 50, 2}, /* GolemHead */
+ {350, 0, 50, 50, 35, 1, 20, 40, 30, 2.0f,0, 0, 0, 1, 8, 15, 0, -8, -24, 0, 23, 26, 15, 0}, /* WhiteWolf */
+ {280, 0, 0, 0, 25, 1, 20, 40, 30, 0.9f,0, 0, 0, 1, 12, 15, 0, -8, -26, 0, 15, 26, 50, 0}, /* Troll */
+ {1200, 0, 0, 0, 70, 6, 10, 30, 30, 0.6f,2, 0, 0, 1, 26, 25, 0, -18, -39, 1, 25, 36, 50, 0}, /* TrollChieftain */
+ {600, 0, 0, 0, 50, 3, 30, 50, 30, 0.8f,2, 0, 0, 1, 15, 15, 1, -8, -35, 0, 24, 31, 50, 0}, /* TrollAxeThrower */
+ {2000, 0, 0, 0, 120, 5, 50, 150, 75, 0.7f,2, 0, 0, 1, 30, 27, 0, -18, -45, 1, 33, 51, 50, 0}, /* Yeti */
+ {11000, 0, 0, 0, 0, 20, 150, 200, 60, 0.4f,2, 0, 1, 1, 40, 35, 0, -50, -110, 2, 72, 115, 90, 0}, /* YetiBoss */
+ {1200, 95, 0, 0, 100, 3, 24, 76, 30, 0.7f,2, 0, 0, 1, 13, 20, 0, -18, -39, 1, 23, 41, 50, 0}, /* Slayer */
+ {340, 0, 0, 0, 30, 1, 1, 2, 30, 1.2f,0, 1, 0, 0, 8, 15, 0, -50, -68, 0, 24, 59, 50, 0}, /* Rocketeer */
+ {120, 0, 0, 0, 2, 1, 10, 20, 30, 0.6f,0, 0, 0, 1, 20, 15, 0, -8, -24, 0, 20, 24, 50, 2}, /* Skeleton */
+ {400, 30, 0, 0, 10, 1, 20, 40, 30, 0.6f,2, 0, 0, 1, 20, 18, 0, -11, -32, 1, 23, 29, 50, 2}, /* SkeletonBig */
+ {350, 0, 60, 50, 25, 1, 20, 40, 30, 1.5f,0, 0, 0, 1, 13, 20, 0, -8, -23, 0, 23, 25, 50, 0}, /* DemonWolf */
+ {250, 0, 60, 0, 20, 1, 10, 30, 30, 0.8f,0, 0, 0, 1, 9, 15, 0, -8, -23, 0, 10, 25, 50, 0}, /* Demon */
+ {1000, 0, 60, 0, 60, 5, 15, 75, 30, 0.6f,2, 0, 0, 1, 18, 23, 0, -18, -39, 1, 20, 37, 50, 0}, /* DemonMage */
+ {700, 0, 0, 0, 50, 3, 20, 40, 30, 0.6f,0, 0, 0, 1, 19, 15, 0, -9, -25, 0, 16, 24, 50, 0}, /* Necromancer */
+ {350, 0, 0, 0, 25, 1, 1, 2, 30, 1.0f,0, 1, 0, 0, 8, 15, 3, -45, -60, 0, 23, 78, 50, 0}, /* DemonImp */
+ {2500, 0, 0, 0, 100, 5, 50, 150, 75, 0.5f,2, 0, 0, 1, 20, 27, 0, -18, -45, 1, 37, 51, 50, 2}, /* LavaElemental */
+ {6666, 0, 0, 0, 0, 20, 666, 999, 60, 0.4f,2, 0, 1, 1, 37, 20, 0, -18, -37, 1, 24, 38, 340, 0}, /* Veznan */
+ {0, 0, 0, 0, 0, 1, 1, 4, 30, 1.2f,0, 0, 0, 1, 8, 15, 0, -8, -20, 0, 10, 18, 50, 0}, /* SheepGround */
+ {0, 0, 0, 0, 0, 1, 1, 2, 30, 1.2f,0, 1, 0, 0, 8, 15, 3, -45, -60, 0, 20, 60, 50, 0}, /* SheepFlying */
+};
+
+const int16_t enemy_anim[EN_COUNT][6] = {
+ {AN_E_GOBLIN_WALKING, AN_E_GOBLIN_WALKINGUP, AN_E_GOBLIN_WALKINGDOWN, AN_E_GOBLIN_IDLE, AN_E_GOBLIN_FIGHTING, AN_E_GOBLIN_DEAD},
+ {AN_E_FATORC_WALKING, AN_E_FATORC_WALKINGUP, AN_E_FATORC_WALKINGDOWN, AN_E_FATORC_IDLE, AN_E_FATORC_FIGHTING, AN_E_FATORC_DEAD},
+ {AN_E_WOLFSMALL_WALKING, AN_E_WOLFSMALL_WALKINGUP, AN_E_WOLFSMALL_WALKINGDOWN, AN_E_WOLFSMALL_IDLE, AN_E_WOLFSMALL_FIGHTING, AN_E_WOLFSMALL_DEAD},
+ {AN_E_SHAMAN_WALKING, AN_E_SHAMAN_WALKINGUP, AN_E_SHAMAN_WALKINGDOWN, AN_E_SHAMAN_IDLE, AN_E_SHAMAN_FIGHTING, AN_E_SHAMAN_DEAD},
+ {AN_E_OGRE_WALKING, AN_E_OGRE_WALKINGUP, AN_E_OGRE_WALKINGDOWN, AN_E_OGRE_IDLE, AN_E_OGRE_FIGHTING, AN_E_OGRE_DEAD},
+ {AN_E_BANDIT_WALKING, AN_E_BANDIT_WALKINGUP, AN_E_BANDIT_WALKINGDOWN, AN_E_BANDIT_IDLE, AN_E_BANDIT_FIGHTING, AN_E_BANDIT_DEAD},
+ {AN_E_BRIGAND_WALKING, AN_E_BRIGAND_WALKINGUP, AN_E_BRIGAND_WALKINGDOWN, AN_E_BRIGAND_IDLE, AN_E_BRIGAND_FIGHTING, AN_E_BRIGAND_DEAD},
+ {AN_E_MARAUDER_WALKING, AN_E_MARAUDER_WALKINGUP, AN_E_MARAUDER_WALKINGDOWN, AN_E_MARAUDER_IDLE, AN_E_MARAUDER_FIGHTING, AN_E_MARAUDER_DEAD},
+ {AN_E_WOLF_WALKING, AN_E_WOLF_WALKINGUP, AN_E_WOLF_WALKINGDOWN, AN_E_WOLF_IDLE, AN_E_WOLF_FIGHTING, AN_E_WOLF_DEAD},
+ {AN_E_SPIDER_WALKING, AN_E_SPIDER_WALKINGUP, AN_E_SPIDER_WALKINGDOWN, AN_E_SPIDER_IDLE, AN_E_SPIDER_FIGHTING, AN_E_SPIDER_DEAD},
+ {AN_E_SPIDERSMALL_WALKING, AN_E_SPIDERSMALL_WALKINGUP, AN_E_SPIDERSMALL_WALKINGDOWN, AN_E_SPIDERSMALL_IDLE, AN_E_SPIDERSMALL_FIGHTING, AN_E_SPIDERSMALL_DEAD},
+ {AN_E_SPIDERTINY_WALKING, AN_E_SPIDERTINY_WALKINGUP, AN_E_SPIDERTINY_WALKINGDOWN, AN_E_SPIDERTINY_IDLE, AN_E_SPIDERTINY_FIGHTING, AN_E_SPIDERTINY_DEAD},
+ {AN_E_SHADOWARCHER_WALKING, AN_E_SHADOWARCHER_WALKINGUP, AN_E_SHADOWARCHER_WALKINGDOWN, AN_E_SHADOWARCHER_IDLE, AN_E_SHADOWARCHER_FIGHTING, AN_E_SHADOWARCHER_DEAD},
+ {AN_E_DARKKNIGHT_WALKING, AN_E_DARKKNIGHT_WALKINGUP, AN_E_DARKKNIGHT_WALKINGDOWN, AN_E_DARKKNIGHT_IDLE, AN_E_DARKKNIGHT_FIGHTING, AN_E_DARKKNIGHT_DEAD},
+ {AN_E_GARGOYLE_WALKING, AN_E_GARGOYLE_WALKINGUP, AN_E_GARGOYLE_WALKINGDOWN, -1, -1, AN_E_GARGOYLE_DEAD},
+ {AN_E_JUGGERNAUT_WALKING, AN_E_JUGGERNAUT_WALKINGUP, -1, AN_E_JUGGERNAUT_IDLE, AN_E_JUGGERNAUT_FIGHTING, AN_E_JUGGERNAUT_DEAD},
+ {AN_E_GOLEMHEAD_WALKING, AN_E_GOLEMHEAD_WALKINGUP, -1, AN_E_GOLEMHEAD_IDLE, AN_E_GOLEMHEAD_FIGHTING, AN_E_GOLEMHEAD_DEAD},
+ {AN_E_WHITEWOLF_WALKING, AN_E_WHITEWOLF_WALKINGUP, AN_E_WHITEWOLF_WALKINGDOWN, AN_E_WHITEWOLF_IDLE, AN_E_WHITEWOLF_FIGHTING, AN_E_WHITEWOLF_DEAD},
+ {AN_E_TROLL_WALKING, AN_E_TROLL_WALKINGUP, AN_E_TROLL_WALKINGDOWN, AN_E_TROLL_IDLE, AN_E_TROLL_FIGHTING, AN_E_TROLL_DEAD},
+ {AN_E_TROLLCHIEFTAIN_WALKING, AN_E_TROLLCHIEFTAIN_WALKINGUP, AN_E_TROLLCHIEFTAIN_WALKINGDOWN, AN_E_TROLLCHIEFTAIN_IDLE, AN_E_TROLLCHIEFTAIN_FIGHTING, AN_E_TROLLCHIEFTAIN_DEAD},
+ {AN_E_TROLLAXETHROWER_WALKING, AN_E_TROLLAXETHROWER_WALKINGUP, AN_E_TROLLAXETHROWER_WALKINGDOWN, AN_E_TROLLAXETHROWER_IDLE, AN_E_TROLLAXETHROWER_FIGHTING, AN_E_TROLLAXETHROWER_DEAD},
+ {AN_E_YETI_WALKING, AN_E_YETI_WALKINGUP, AN_E_YETI_WALKINGDOWN, AN_E_YETI_IDLE, AN_E_YETI_FIGHTING, AN_E_YETI_DEAD},
+ {AN_E_YETIBOSS_WALKING, -1, AN_E_YETIBOSS_WALKINGDOWN, AN_E_YETIBOSS_IDLE, AN_E_YETIBOSS_FIGHTING, AN_E_YETIBOSS_DEAD},
+ {AN_E_SLAYER_WALKING, AN_E_SLAYER_WALKINGUP, AN_E_SLAYER_WALKINGDOWN, AN_E_SLAYER_IDLE, AN_E_SLAYER_FIGHTING, AN_E_SLAYER_DEAD},
+ {AN_E_ROCKETEER_WALKING, AN_E_ROCKETEER_WALKINGUP, AN_E_ROCKETEER_WALKINGDOWN, -1, -1, AN_E_ROCKETEER_DEAD},
+ {AN_E_SKELETON_WALKING, AN_E_SKELETON_WALKINGUP, AN_E_SKELETON_WALKINGDOWN, AN_E_SKELETON_IDLE, AN_E_SKELETON_FIGHTING, AN_E_SKELETON_DEAD},
+ {AN_E_SKELETONBIG_WALKING, AN_E_SKELETONBIG_WALKINGUP, AN_E_SKELETONBIG_WALKINGDOWN, AN_E_SKELETONBIG_IDLE, AN_E_SKELETONBIG_FIGHTING, AN_E_SKELETONBIG_DEAD},
+ {AN_E_DEMONWOLF_WALKING, AN_E_DEMONWOLF_WALKINGUP, AN_E_DEMONWOLF_WALKINGDOWN, AN_E_DEMONWOLF_IDLE, AN_E_DEMONWOLF_FIGHTING, AN_E_DEMONWOLF_DEAD},
+ {AN_E_DEMON_WALKING, AN_E_DEMON_WALKINGUP, AN_E_DEMON_WALKINGDOWN, AN_E_DEMON_IDLE, AN_E_DEMON_FIGHTING, AN_E_DEMON_DEAD},
+ {AN_E_DEMONMAGE_WALKING, AN_E_DEMONMAGE_WALKINGUP, AN_E_DEMONMAGE_WALKINGDOWN, AN_E_DEMONMAGE_IDLE, AN_E_DEMONMAGE_FIGHTING, AN_E_DEMONMAGE_DEAD},
+ {AN_E_NECROMANCER_WALKING, AN_E_NECROMANCER_WALKINGUP, AN_E_NECROMANCER_WALKINGDOWN, AN_E_NECROMANCER_IDLE, AN_E_NECROMANCER_FIGHTING, AN_E_NECROMANCER_DEAD},
+ {AN_E_DEMONIMP_WALKING, AN_E_DEMONIMP_WALKINGUP, AN_E_DEMONIMP_WALKINGDOWN, -1, -1, AN_E_DEMONIMP_DEAD},
+ {AN_E_LAVAELEMENTAL_WALKING, AN_E_LAVAELEMENTAL_WALKINGUP, AN_E_LAVAELEMENTAL_WALKINGDOWN, AN_E_LAVAELEMENTAL_IDLE, AN_E_LAVAELEMENTAL_FIGHTING, AN_E_LAVAELEMENTAL_DEAD},
+ {AN_E_VEZNAN_WALKING, AN_E_VEZNAN_WALKINGUP, AN_E_VEZNAN_WALKINGDOWN, AN_E_VEZNAN_IDLE, AN_E_VEZNAN_FIGHTING, AN_E_VEZNAN_DEAD},
+ {AN_E_SHEEPGROUND_WALKING, AN_E_SHEEPGROUND_WALKINGUP, AN_E_SHEEPGROUND_WALKINGDOWN, AN_E_SHEEPGROUND_IDLE, -1, AN_E_SHEEPGROUND_DEAD},
+ {AN_E_SHEEPFLYING_WALKING, AN_E_SHEEPFLYING_WALKINGUP, AN_E_SHEEPFLYING_WALKINGDOWN, AN_E_SHEEPFLYING_IDLE, -1, AN_E_SHEEPFLYING_DEAD},
+};
+
+const char *enemy_name(int type) {
+ static const char *const n[EN_COUNT] = {
+ "Goblin",
+ "Orc",
+ "Wulf",
+ "Shaman",
+ "Ogre",
+ "Bandit",
+ "Brigand",
+ "Marauder",
+ "Worg",
+ "Giant Spider",
+ "Spider",
+ "Spiderling",
+ "Shadow Archer",
+ "Dark Knight",
+ "Gargoyle",
+ "Juggernaut",
+ "Golem Head",
+ "Winter Wolf",
+ "Troll",
+ "Troll Chieftain",
+ "Troll Axe Thrower",
+ "Yeti",
+ "J.T.",
+ "Dark Slayer",
+ "Goblin Rocketeer",
+ "Skeleton",
+ "Skeleton Knight",
+ "Demon Hound",
+ "Demon Spawn",
+ "Demon Lord",
+ "Necromancer",
+ "Flareon",
+ "Lava Elemental",
+ "Vez'nan",
+ "Sheep",
+ "Flying Sheep",
+ };
+ return type >= 0 && type < EN_COUNT ? n[type] : "";
+}
diff --git a/games/kingdomrush/src/strings.c b/games/kingdomrush/src/strings.c
new file mode 100644
index 00000000..6b4cb9ac
--- /dev/null
+++ b/games/kingdomrush/src/strings.c
@@ -0,0 +1,295 @@
+/* Made by tools/pack.py: the game's own English words (its Locale strings). */
+#include "kr.h"
+#include "strings.h"
+
+static const char *const notes[][2] = {
+ {"", ""},
+ {"New spell: Call Reinforcements", "Summon reinforcements to block and fight enemies. Press 2 to aim it, OK to cast."},
+ {"New spell: Rain of Fire", "Rains fire and brimstone from the skies. Press 1 to aim it, OK to cast."},
+ {"New enemy: Goblin", "Small evil humanoids with no outstanding abilities."},
+ {"New enemy: Orc", "Tough savages with light armor."},
+ {"Tip", "Enemies and Soldiers with armor receive less physical damage."},
+ {"Tip", "Adjust the rally point of soldiers to create better strategies."},
+ {"Level 2 towers", "Your towers can now be upgraded to level 2."},
+ {"Tip", "Support barracks with ranged towers to maximize enemy exposure."},
+ {"New enemy: Wulf", "Very fast vicious creatures that can dodge melee attacks. Can dodge melee attacks."},
+ {"New enemy: Shaman", "Tribal healers resistant to magic attacks. Can heal allies."},
+ {"Tip", "Enemies with magic resistance receive less damage from magic attacks."},
+ {"New enemy: Ogre", "Big, ugly and tough humanoids, they'll obliterate everything in their path."},
+ {"Level 3 towers", "Your towers can now be upgraded to level 3."},
+ {"New enemy: Bandit", "Swift & agile, they can dispatch their enemies very quickly. Can dodge melee attacks."},
+ {"New enemy: Brigand", "Armored outlaws that can withstand a lot of punishment."},
+ {"New enemy: Giant Spiders", "Quick, vicious enemies resistant to magic."},
+ {"New tower: Rangers Hideout", "Legendary masters of the bow, they can unleash a hail of arrows faster and further than any other force in the realm."},
+ {"New enemy: Worg", "Cunning fast beasts that can dodge melee attacks and resist magic attacks. Can dodge melee attacks."},
+ {"New enemy: Spider Matriarch", "Tough magic resistant beast that can spawn several spiderlings. Spawns spiderlings."},
+ {"New enemy: Marauder", "Hulking, well-trained armored outlaws, often seen leading brigands and bandits."},
+ {"New tower: Arcane Wizard", "Arcane wizards focus on altering reality; as well as shooting the deadliest magical ray known to man."},
+ {"Tip", "Magic damage is the best way to deal with armored enemies."},
+ {"New enemy: Dark Knight", "Full plated corrupted knights, almost impervious to damage."},
+ {"New enemy: Gargoyle", "Vile winged creatures that can fly past barracks and artillery. Flying."},
+ {"New enemy: Shadow Archer", "Deadly accurate archers that will shoot at nearby soldiers in their path. Shoots arrows."},
+ {"New tower: Musketeer Garrison", "Patient, careful, and deadly accurate long-range deadeye shooters, with advanced weaponry."},
+ {"New enemy: Troll", "Very tough warriors that can regenerate their wounds quickly. Regen."},
+ {"New enemy: Winter Wolf", "Cunning & deadly, these beasts can defeat all but the best warriors. Can dodge melee attacks."},
+ {"New tower: Barbarian Hall", "Barbarians are savage warriors that will quickly clear a battlefield, usually at the cost of their own lives."},
+ {"New enemy: Troll Champion", "Elite tribal warriors equipped with vicious throwing axes Regen, Throws armor piercing axes."},
+ {"New enemy: Yeti", "Large ape-man like creature that can obliterate scores of soldiers with one strike. Area attack."},
+ {"New enemy: Troll Chieftain", "The chieftain can enrage his brethren, improving their attack damage, armor rating, speed and health. Regen, Can enrage allies."},
+ {"New tower: Sorcerer Mage", "Sorcerers handle forces that are close to darkness, weaving spells that temporarily lower enemy armor and deal damage."},
+ {"New enemy: Dark Slayer", "Claimed by darkness; slayers are the bane of anyone standing in their way."},
+ {"New enemy: Rocket Rider", "Half man, half machine; the rocket riders follow their dark lord's will wherever they go. Flying, Turbo."},
+ {"New tower: Tesla x104", "Dwarven engineering at its finest, harnessing the power of a thousand thunderstorms. Who shall we aim it at?"},
+ {"New enemy: Demon Spawn", "Terrible infernal creatures that explode when they die, damaging nearby soldiers. Infernal combustion."},
+ {"New enemy: Demon Lord", "Demon lords lead fiendish armies into battle, protecting their minions with infernal shields. Shields other demons, Infernal combustion."},
+ {"New enemy: Demon Hound", "Vicious terrible creatures, they serve as hunting dogs for the demon lords. Infernal combustion."},
+ {"New enemy: Demon Imp", "Flying mischievious infernal creatures that are often seen in the company of gargoyles.. Flying."},
+ {"New enemy: Necromancer", "Master of the dark arts, the Necromancer summons undead minions to do their bidding. Summons undead, Ranged attack."},
+};
+const char *note_title(int n) { return n > 0 && n < (int)(sizeof notes / sizeof notes[0]) ? notes[n][0] : 0; }
+const char *note_text(int n) { return n > 0 && n < (int)(sizeof notes / sizeof notes[0]) && notes[n][1][0] ? notes[n][1] : 0; }
+
+static const char *const enemy_desc_s[EN_COUNT] = {
+ "Small evil humanoids with no outstanding abilities.",
+ "Tough savages with light armor.",
+ "Very fast vicious creatures that can dodge melee attacks.",
+ "Tribal healers resistant to magic attacks.",
+ "Big, ugly and tough humanoids, they'll obliterate everything in their path.",
+ "Swift & agile, they can dispatch their enemies very quickly.",
+ "Armored outlaws that can withstand a lot of punishment.",
+ "Hulking, well-trained armored outlaws, often seen leading brigands and bandits.",
+ "Cunning fast beasts that can dodge melee attacks and resist magic attacks.",
+ "Tough magic resistant beast that can spawn several spiderlings.",
+ "Quick, vicious enemies resistant to magic.",
+ "Very weak spider hatchlings.",
+ "Deadly accurate archers that will shoot at nearby soldiers in their path.",
+ "Full plated corrupted knights, almost impervious to damage.",
+ "Vile winged creatures that can fly past barracks and artillery.",
+ "A mindless unstoppable machine of destruction. The Juggernaut obliterates any army that tries to stop him.",
+ "Mechanical dark magical construct.",
+ "Cunning & deadly, these beasts can defeat all but the best warriors.",
+ "Very tough warriors that can regenerate their wounds quickly.",
+ "The chieftain can enrage his brethren, improving their attack damage, armor rating, speed and health.",
+ "Elite tribal warriors equipped with vicious throwing axes",
+ "Large ape-man like creature that can obliterate scores of soldiers with one strike.",
+ "An abominable legendary creature from the coldest reaches of Stormspike.",
+ "Claimed by darkness; slayers are the bane of anyone standing in their way.",
+ "Half man, half machine; the rocket riders follow their dark lord's will wherever they go.",
+ "Mindless automatons that obey the orders of their evil masters.",
+ "Skeleton Knights are the reanimated bones of once great warriors.",
+ "Vicious terrible creatures, they serve as hunting dogs for the demon lords.",
+ "Terrible infernal creatures that explode when they die, damaging nearby soldiers.",
+ "Demon lords lead fiendish armies into battle, protecting their minions with infernal shields.",
+ "Master of the dark arts, the Necromancer summons undead minions to do their bidding.",
+ "Flying mischievious infernal creatures that are often seen in the company of gargoyles..",
+ "Made of rock and fire, magma elementals are beings of death and destruction.",
+ "The most evil being you will encounter. Watch out for his evil bad jokes!",
+ "",
+ "",
+};
+const char *enemy_desc(int t) { return t >= 0 && t < EN_COUNT ? enemy_desc_s[t] : ""; }
+
+static const char *const titles[NLEVELS] = {"Southport", "The Outskirts", "Pagras", "Twin River Pass", "Silveroak Forest", "The Citadel", "Coldstep Mines", "Icewind Pass", "Stormcloud Temple", "The Wastes", "Forsaken Valley", "The Dark Tower"};
+const char *level_title(int i) { return i >= 0 && i < NLEVELS ? titles[i] : ""; }
+static const char *const stories[NLEVELS] = {
+ "Greetings, noble and heroic warrior! As a General of His Majesty's forces, King Denas requires your services. The inhabitants of the city of Southport have reported attacks by highwaymen and other roaming outlaws. You must take a battalion to Southport to bolster the city's defenses. Good luck, General!",
+ "Good job! Your diligent investigations have revealed that it was not mere brigands terrorizing Southport, but organized bands of goblins and orcs! Now, their forward troops are creeping towards the defenseless rural communities North of Southport. We must establish an efficient and swift defense!",
+ "While your men celebrate your victory over the goblinoid and orcish troops, a messenger bears bad news. The township of Pagras is under siege by an overwhelmingly superior force. This is clearly an attack on the Kingdom: war is upon us!",
+ "Enemy troops are marching from the East through the Stonecliff Mountains. This can only mean that Hammerhold has fallen, and our Kingdom's capital is in peril. Our scouts conclude that the best place to stop our enemy's advance is at the Twin Rivers pass.",
+ "With Twin Rivers Pass blocked, and after days of marching, we've finally reached the Silveroak Forest outpost... only to find its troop compliment decimated! The garrison's men have endured several attacks recently, and their scouts report an even greater enemy force approaching. Good thing elite ranger units are on the way to help us...",
+ "After several days of travel, we have arrived at our capital city of Linirea. The time has come to make a stand, and defend Linirea's southern walls. In addition to your highly experienced units, the King adds two units to your batallions. The arcane wizards will provide superior firepower, and the pious paladins will inspire the troops with their bravery.",
+ "Our capital is safe, thanks to you, General! Now, our good King has entrusted you with the mission of creating a safe passage through the mountains so that we may strike at Valardul, and defeat Vez'nan and his armies. The first step in your journey will be the Coldstep Mines, which were abandoned years ago, and are now home to the Ha'kraj troll tribes. To aid you in your mission, you will be joined by a brigade of His Majesty's Royal Musketeers.",
+ "There is no place colder in these mountains than Icewind Pass, but we must advance. Our men have been besieged by Ha'kraj trolls for days, and our scouts report enemy troop movements around us... and something else, something wilder. If we are to make a stand here, this is a good place to install some of our new Artillery emplacements, and to construct a Barbarian Mead Hall so we may entertain our more... colorful troops.",
+ "Arriving at the Stormcloud temple has been the best thing to happen to us in days! The Stormcloud Sorcerers will now be at your command, General, and they can open a portal straight to Valardul. However, we must provide them with a defense while they complete their spell. Something... abominable is aproaching, and the men are extremely nervous...",
+ "We have arrived at the dreadful realm of Valardul. This is a barren and forsaken land, where the wretched souls of the departed find no solace. Pray to the gods that this place does not take its toll on your men's spirits...",
+ "Threading through the Forsaken Valley will not be an easy task! We are near the end of our journey, and although our men are tired, they are filled with honorable purpose. But beware... this is a land riddled with Rock and Fire Titans... best not to upset them!",
+ "Our troops gather around the dread wizard Vez'nan's tower. It is time for a reckoning... time for the final fray. This is the ultimate battle for our kingdom's safety. Every step has brought us to this moment; and there is no turning back. Now it's time to show our mettle!",
+};
+const char *level_story(int i) { return i >= 0 && i < NLEVELS ? stories[i] : ""; }
+
+static const char *const ups[30][2] = {
+ {"Salvage", "Marksmen towers return 90% of value when sold."},
+ {"Eagle Eye", "Increases Marksmen attack range."},
+ {"Piercing Shots", "Piercing shots ignore a portion of the enemy's physical armor."},
+ {"Far Shots", "Increases Marksmen attack range."},
+ {"Precision", "Marksmen attacks have a chance of dealing double damage."},
+ {"Toughness Training", "Barracks train soldiers with more health."},
+ {"Better Armor", "Barracks train soldiers with improved armor."},
+ {"Improved Deployment", "Increases rally point range and reduces soldier training time."},
+ {"Endurance Training", "Barracks train soldiers with even more health."},
+ {"Spiked Armor", "When attacked, soldier's spiked armor return a % of the damage received to the attacker (This upgrade also affects reinforcements)."},
+ {"Spell Reach", "Increases Wizard's attack range."},
+ {"Arcane Shatter", "Magic attacks destroy a portion of enemy physical armor on every hit."},
+ {"Hermetic Study", "Mage towers construction and upgrading costs are reduced by 10%."},
+ {"Empowered Magic", "Increases Wizard's attack damage."},
+ {"Slow Curse", "Magic attacks slow enemies by half their speed for a moment."},
+ {"Concentrated Fire", "Increases Artillery attack damage."},
+ {"Range Finder", "Increases Artillery attack range."},
+ {"Field Logistic", "Artillery construction and upgrading costs are reduced by 10%."},
+ {"Industrialization", "Artillery special abilities costs are reduced by 25%."},
+ {"Smart Targeting", "Artillery suffers no reduction of splash and chain lightning damage."},
+ {"Blazing Skies", "Adds 2 additional meteors and increases meteor damage."},
+ {"Scorched Earth", "Meteors set the ground on fire burning enemies over it for 5 seconds."},
+ {"The Fast & Furious", "Increases meteor damage, explosion radius by 25% and reduces cooldown by 10 seconds."},
+ {"Blazing Earth", "Doubles damage and duration of scorched earth, and reduces cooldown by 10 seconds."},
+ {"Cataclysm", "Increases meteor damage and rains additional meteors at random locations all over the battlefield."},
+ {"Well Fed", "Well fed farmers have additional health and deal a little more damage."},
+ {"Conscripts", "Conscripts have more health and are better equipped."},
+ {"Warriors", "Warriors have even more health and are excellently equipped."},
+ {"Legionnaires", "Legionnaires have the most health and wear the best equipment."},
+ {"Spear Throw", "Gives Legionnaires a spear throw attack that can target ground and flying enemies."},
+};
+const char *upgrade_name(int line, int n) { return ups[line * 5 + n][0]; }
+const char *upgrade_desc(int line, int n) { return ups[line * 5 + n][1]; }
+
+static const char *const tw[][2] = {
+ {"TOWER_LOCKED_NAME", "Locked!"},
+ {"TOWER_LOCKED_DESCRIPTION", "This item is locked."},
+ {"TOWER_BARRACKS_RALLY_POINT", "Rally Point"},
+ {"TOWER_BARRACKS_RALLY_POINT_DESCRIPTION", "Change the rally point where soldiers defend."},
+ {"TOWER_BARRACKS_NAME", "Barracks"},
+ {"TOWER_BARRACKS_DESCRIPTION", "Trains militia, tough soldiers that block and damage your enemies."},
+ {"TOWER_BARRACKS_UPGRADE_LEVEL2_NAME", "Footmen Barracks"},
+ {"TOWER_BARRACKS_UPGRADE_LEVEL2_DESCRIPTION", "Footmen are better trained and equipped than basic militia. They can become the backbone of a good army."},
+ {"TOWER_BARRACKS_UPGRADE_LEVEL3_NAME", "Knights Barracks"},
+ {"TOWER_BARRACKS_UPGRADE_LEVEL3_DESCRIPTION", "Knights are professional soldiers with heavy armor. Dedicated to his majesty, they will stop your enemies' advance."},
+ {"TOWER_BARBARIANS_NAME", "Barbarian Hall"},
+ {"TOWER_BARBARIANS_DESCRIPTION", "Barbarians are savage warriors that will quickly clear a battlefield, usually at the cost of their own lives."},
+ {"TOWER_BARBARIANS_SPECIAL", "Throwing Axes, More Axes, Hunting Nets"},
+ {"TOWER_BARBARIANS_BLOODLUST_NAME", "Bloodrage"},
+ {"TOWER_BARBARIANS_BLOODLUST_DESCRIPTION", "When injured, Barbarians enter bloodrage making them deal extra damage with every attack."},
+ {"TOWER_BARBARIANS_BLOODLUST_NOTE", "Don't make me angry. You wouldn't like me when I'm angry."},
+ {"TOWER_BARBARIANS_THROWING_AXES_NAME", "Throwing axes"},
+ {"TOWER_BARBARIANS_THROWING_AXES_DESCRIPTION", "Barbarians can throw great axes at ground and flying enemies in range."},
+ {"TOWER_BARBARIANS_THROWING_AXES_NOTE", "May our axes split our enemies in two!"},
+ {"TOWER_BARBARIANS_DOUBLE_AXE_NAME", "More Axes"},
+ {"TOWER_BARBARIANS_DOUBLE_AXE_DESCRIPTION", "Barbarians equip an additional axe to deliver additional damage."},
+ {"TOWER_BARBARIANS_DOUBLE_AXE_NOTE", "Double the Axes Double the fun!"},
+ {"TOWER_BARBARIANS_HUNTER_NETS_NAME", "Hunting Nets"},
+ {"TOWER_BARBARIANS_HUNTER_NETS_DESCRIPTION", "Hunters by nature, Barbarians can throw nets to slow flying enemies for a while."},
+ {"TOWER_BARBARIANS_HUNTER_NETS_NOTE", "Stay Put!"},
+ {"TOWER_PALADINS_NAME", "Holy Order"},
+ {"TOWER_PALADINS_DESCRIPTION", "Trains paladins, an order of holy warriors. They are paragons of divine protection and heavenly defense."},
+ {"TOWER_PALADINS_SPECIAL", "Healing Light, Holy Strike, Shield of Valor"},
+ {"TOWER_PALADINS_HEALING_NAME", "Healing Light"},
+ {"TOWER_PALADINS_HEALING_DESCRIPTION", "Paladins can heal their wounds with Holy Light whenever they are injured."},
+ {"TOWER_PALADINS_HEALING_NOTE", "There shall be light!"},
+ {"TOWER_PALADINS_HOLY_STRIKE_NAME", "Holy Strike"},
+ {"TOWER_PALADINS_HOLY_STRIKE_DESCRIPTION", "Every attack has a chance of becoming a Holy Strike, dealing holy area damage."},
+ {"TOWER_PALADINS_HOLY_STRIKE_NOTE", "By Holy fire be Purged!"},
+ {"TOWER_PALADINS_SHIELD_NAME", "Shield of Valor"},
+ {"TOWER_PALADINS_SHIELD_DESCRIPTION", "Enhances paladins protection, making them more resilient."},
+ {"TOWER_PALADINS_SHIELD_NOTE", "No retreat, No surrender!"},
+ {"TOWER_ARCHERS_NAME", "Archer Tower"},
+ {"TOWER_ARCHERS_DESCRIPTION", "Archers ready to strike at your enemies from a distance."},
+ {"TOWER_ARCHERS_UPGRADE_LEVEL2_NAME", "Marksmen Tower"},
+ {"TOWER_ARCHERS_UPGRADE_LEVEL2_DESCRIPTION", "Marksmen shoot broadhead arrows, dealing more damage. Their longbows have longer attack range."},
+ {"TOWER_ARCHERS_UPGRADE_LEVEL3_NAME", "Sharpshooter Tower"},
+ {"TOWER_ARCHERS_UPGRADE_LEVEL3_DESCRIPTION", "Once archers reach the sharpshooter level, their attack range and damage potential increases above any other archer's."},
+ {"TOWER_RANGERS_NAME", "Rangers Hideout"},
+ {"TOWER_RANGERS_DESCRIPTION", "Legendary masters of the bow, they can unleash a hail of arrows faster and further than any other force in the realm."},
+ {"TOWER_RANGERS_SPECIAL", "Poison Arrows, Wrath of the Forest"},
+ {"TOWER_RANGERS_POISON_NAME", "Poison Arrows"},
+ {"TOWER_RANGERS_POISON_DESCRIPTION", "Poisons enemies dealing damage over time."},
+ {"TOWER_RANGERS_POISON_NOTE", "It won't hurt... for long."},
+ {"TOWER_RANGERS_THORNS_NAME", "Wrath of the Forest"},
+ {"TOWER_RANGERS_THORNS_DESCRIPTION", "Summons thorns and vines that trap, hold, and incapacitate ground-based enemies within its range."},
+ {"TOWER_RANGERS_THORNS_NOTE", "It's a trap!"},
+ {"TOWER_MUSKETEERS_NAME", "Musketeer Garrison"},
+ {"TOWER_MUSKETEERS_DESCRIPTION", "Patient, careful, and deadly accurate long-range deadeye shooters, with advanced weaponry."},
+ {"TOWER_MUSKETEERS_SPECIAL", "Sniper Shot, Shrapnel Shot"},
+ {"TOWER_MUSKETEERS_SNIPER_NAME", "Sniper Shot"},
+ {"TOWER_MUSKETEERS_SNIPER_DESCRIPTION", "Long range shot with increasing chance of instantly killing an enemy or deal massive damage."},
+ {"TOWER_MUSKETEERS_SNIPER_NOTE", "One shot... One kill..."},
+ {"TOWER_MUSKETEERS_SHRAPNEL_NAME", "Shrapnel Shot"},
+ {"TOWER_MUSKETEERS_SHRAPNEL_DESCRIPTION", "Special explosive ammunition, that blasts an area with shrapnel, dealing damage to all ground-based enemies within range."},
+ {"TOWER_MUSKETEERS_SHRAPNEL_NOTE", "Eat grapeshot!"},
+ {"TOWER_ENGINEERS_NAME", "Dwarven Bombard"},
+ {"TOWER_ENGINEERS_DESCRIPTION", "Bombards ground enemies dealing area damage."},
+ {"TOWER_ENGINEERS_UPGRADE_LEVEL2_NAME", "Dwarven Artillery"},
+ {"TOWER_ENGINEERS_UPGRADE_LEVEL2_DESCRIPTION", "Enhanced dwarven ordnance, this artillery will blast an even larger area."},
+ {"TOWER_ENGINEERS_UPGRADE_LEVEL3_NAME", "Dwarven Howitzer"},
+ {"TOWER_ENGINEERS_UPGRADE_LEVEL3_DESCRIPTION", "They build them bigger and bigger, don't they? Your enemies stand no chance!"},
+ {"TOWER_BFG_NAME", "500mm Big Bertha"},
+ {"TOWER_BFG_DESCRIPTION", "The 500mm siege gun aka"},
+ {"TOWER_BFG_SPECIAL", "Dragonbreath Launcher, Cluster Launcher"},
+ {"TOWER_BFG_MISSILE_NAME", "Dragonbreath Launcher"},
+ {"TOWER_BFG_MISSILE_DESCRIPTION", "Launches seeking missiles with extended range that never miss. They even find another target if they lose the current one."},
+ {"TOWER_BFG_MISSILE_NOTE", "Guaranteed mayhem. Use with discretion."},
+ {"TOWER_BFG_CLUSTER_NAME", "Cluster Launcher Xtreme"},
+ {"TOWER_BFG_CLUSTER_DESCRIPTION", "Fires a special bomb that will explode in mid air dropping additional bomblets into a wide area."},
+ {"TOWER_BFG_CLUSTER_NOTE", "I love the smell of napalm in the morning..."},
+ {"TOWER_TESLA_NAME", "Tesla x104"},
+ {"TOWER_TESLA_DESCRIPTION", "Dwarven engineering at its finest, harnessing the power of a thousand thunderstorms. Who shall we aim it at?"},
+ {"TOWER_TESLA_SPECIAL", "Supercharged Bolt, Overcharge"},
+ {"TOWER_TESLA_CHARGED_BOLT_NAME", "Supercharged Bolt"},
+ {"TOWER_TESLA_CHARGED_BOLT_DESCRIPTION", "Supercharged Bolts will arc to additional targets."},
+ {"TOWER_TESLA_CHARGED_BOLT_NOTE", "You've been - thunderstruck!"},
+ {"TOWER_TESLA_OVERCHARGE_NAME", "Overcharge"},
+ {"TOWER_TESLA_OVERCHARGE_DESCRIPTION", "Overcharges the tower creating a static field that damages all enemies in proximity."},
+ {"TOWER_TESLA_OVERCHARGE_NOTE", "Ride the Lightning!"},
+ {"TOWER_MAGES_NAME", "Mages"},
+ {"TOWER_MAGES_DESCRIPTION", "Mages cast armor piercing bolts at your enemies, ignoring any physical protection."},
+ {"TOWER_MAGES_UPGRADE_LEVEL2_NAME", "Adept Tower"},
+ {"TOWER_MAGES_UPGRADE_LEVEL2_DESCRIPTION", "Adepts cast enhanced bolts, which can tear through armor, flesh and bone."},
+ {"TOWER_MAGES_UPGRADE_LEVEL3_NAME", "Wizard Tower"},
+ {"TOWER_MAGES_UPGRADE_LEVEL3_DESCRIPTION", "Wizards cast high-energy bolts, which rip apart the very essence of enemy troops."},
+ {"TOWER_ARCANE_NAME", "Arcane Wizard"},
+ {"TOWER_ARCANE_DESCRIPTION", "Arcane wizards focus on altering reality; as well as shooting the deadliest magical ray known to man."},
+ {"TOWER_ARCANE_SPECIAL", "Death Ray, Teleport"},
+ {"TOWER_ARCANE_TELEPORT_NAME", "Teleport"},
+ {"TOWER_ARCANE_TELEPORT_DESCRIPTION", "Teleports a group of enemies a random distance back down the path."},
+ {"TOWER_ARCANE_TELEPORT_NOTE", "Space is merely a perception, a concern for mortal men."},
+ {"TOWER_ARCANE_DESINTEGRATE_NAME", "Death Ray"},
+ {"TOWER_ARCANE_DESINTEGRATE_DESCRIPTION", "Enemy troops are disintegrated into fine dust. Complete effectivity guaranteed!"},
+ {"TOWER_ARCANE_DESINTEGRATE_NOTE", "Avada Kedavra!"},
+ {"TOWER_SORCERER_NAME", "Sorcerer Mage"},
+ {"TOWER_SORCERER_DESCRIPTION", "Sorcerers handle forces that are close to darkness, weaving spells that temporarily lower enemy armor and deal damage."},
+ {"TOWER_SORCERER_SPECIAL", "Summon Elemental, Polymorph"},
+ {"TOWER_SORCERER_POLIMORPH_NAME", "Polymorph"},
+ {"TOWER_SORCERER_POLIMORPH_DESCRIPTION", "Polymorphs enemies into harmless sheep. Sheep have no armor, no abilities and cannot be blocked."},
+ {"TOWER_SORCERER_POLIMORPH_NOTE", "Meeeeh!"},
+ {"TOWER_SORCERER_ELEMENTAL_NAME", "Summon Elemental"},
+ {"TOWER_SORCERER_ELEMENTAL_DESCRIPTION", "Summons a rock elemental, stout avatar of the land's power. It will fight those who approach his master."},
+ {"TOWER_SORCERER_ELEMENTAL_NOTE", "Rock is eternal."},
+ {"TOWER_SELL", "Sell Tower"},
+ {"TOWER_SELL_DESCRIPTION", "Sell this tower and get a"},
+ {"POWER_FIREBALL_NAME", "Rain of Fire"},
+ {"POWER_FIREBALL_DESCRIPTION", "Rains fire and brimstone from the skies."},
+ {"POWER_REINFORCEMENTS_NAME", "Call Reinforcements"},
+ {"POWER_REINFORCEMENTS_DESCRIPTION", "Summon reinforcements to block and fight enemies."},
+ {"POWER_LIGHTNING_NAME", "Lightning Bolt"},
+ {"POWER_LIGHTNING_DESCRIPTION", "Casts a bolt of lightning at one enemy."},
+};
+const char *tower_text(const char *key) {
+ for (unsigned i = 0; i < sizeof tw / sizeof tw[0]; i++) {
+ const char *a = tw[i][0], *b = key;
+ while (*a && *a == *b) a++, b++;
+ if (!*a && !*b) return tw[i][1];
+ }
+ return "";
+}
+
+static const char *const tips[20] = {
+ "Enemies and Soldiers with armor receive less physical damage.",
+ "Support barracks with ranged towers to maximize enemy exposure.",
+ "Reinforcements are a great way to split enemy forces.",
+ "Artillery works best against high concentration of enemies.",
+ "Artillery damage is highest in the center of the explosion.",
+ "Use reinforcements constantly to slow and damage the enemy.",
+ "Always aim rain of fire a little ahead of your target.",
+ "With the Salvage upgrade you can sell archer towers with only a 10% of loss.",
+ "Magic damage is the best way to deal with armored enemies.",
+ "Flying enemies cannot be blocked by barracks, and won't be targeted by most artillery.",
+ "Enemies with magic resistance receive less damage from magic attacks.",
+ "Adjust the rally point of soldiers to create better strategies.",
+ "Sometimes it is better to build more towers instead of upgrading a few.",
+ "Poison damage ignores armor.",
+ "Upgrading a barracks instantly trains new soldiers.",
+ "Calling an early wave gives bonus cash and reduces spell cooldowns a bit.",
+ "Artillery explosions can damage flying enemies although they cannot target them directly.",
+ "Use barracks or reinforcements to isolate troublesome enemies.",
+ "Barbarians with the right upgrades are capable of dealing with flying enemies.",
+ "Earth elementals are very tough and deal area damage every time they strike.",
+};
+const char *tip(int i) { return tips[i % 20]; }
diff --git a/games/kingdomrush/src/strings.h b/games/kingdomrush/src/strings.h
new file mode 100644
index 00000000..e2ba4194
--- /dev/null
+++ b/games/kingdomrush/src/strings.h
@@ -0,0 +1,13 @@
+/* Kingdom Rush: the game's own words (strings.c, made by tools/pack.py). */
+#ifndef KR_STRINGS_H
+#define KR_STRINGS_H
+const char *note_title(int n);
+const char *note_text(int n); /* 0 when there is nothing to show */
+const char *enemy_desc(int type);
+const char *level_title(int i);
+const char *level_story(int i);
+const char *upgrade_name(int line, int n); /* n: 0 to 4 */
+const char *upgrade_desc(int line, int n);
+const char *tower_text(const char *key); /* TOWER_*, POWER_* */
+const char *tip(int i);
+#endif
diff --git a/games/kingdomrush/src/tower.c b/games/kingdomrush/src/tower.c
new file mode 100644
index 00000000..43c7fd0e
--- /dev/null
+++ b/games/kingdomrush/src/tower.c
@@ -0,0 +1,472 @@
+/* The towers (Tower.as, TowerHolder.as, TowerArcher.as, TowerMage.as, TowerEngineer.as, TowerSoldier.as; the
+ * specials in special.c). A spot holds the build spot or its tower. */
+#include <math.h>
+#include <string.h>
+#include "kr.h"
+#include "settings.h"
+#include "special.h"
+
+#define BUILD_TIME 30
+
+TowerStat tower_stat(int kind, int level) {
+ TowerStat t = {0};
+#define T(c, r, lo, hi, rl, ar) t = (TowerStat){c, r, lo, hi, rl, ar}
+ switch (kind) {
+ case TW_ARCHER:
+ if (level == 1) T(S_archers_level1_cost, S_archers_level1_range, S_archers_level1_minDamage, S_archers_level1_maxDamage, S_archers_level1_reload, 0);
+ if (level == 2) T(S_archers_level2_cost, S_archers_level2_range, S_archers_level2_minDamage, S_archers_level2_maxDamage, S_archers_level2_reload, 0);
+ if (level == 3) T(S_archers_level3_cost, S_archers_level3_range, S_archers_level3_minDamage, S_archers_level3_maxDamage, S_archers_level3_reload, 0);
+ break;
+ case TW_RANGER: T(S_archers_ranger_cost, S_archers_ranger_range, S_archers_ranger_minDamage, S_archers_ranger_maxDamage, S_archers_ranger_reload, 0); break;
+ case TW_MUSKETEER: T(S_archers_musketeer_cost, S_archers_musketeer_range, S_archers_musketeer_minDamage, S_archers_musketeer_maxDamage, S_archers_musketeer_reload, 0); break;
+ case TW_MAGE:
+ if (level == 1) T(S_mages_level1_cost, S_mages_level1_range, S_mages_level1_minDamage, S_mages_level1_maxDamage, S_mages_level1_reload, 0);
+ if (level == 2) T(S_mages_level2_cost, S_mages_level2_range, S_mages_level2_minDamage, S_mages_level2_maxDamage, S_mages_level2_reload, 0);
+ if (level == 3) T(S_mages_level3_cost, S_mages_level3_range, S_mages_level3_minDamage, S_mages_level3_maxDamage, S_mages_level3_reload, 0);
+ break;
+ case TW_ARCANE: T(S_mages_arcane_cost, S_mages_arcane_range, S_mages_arcane_minDamage, S_mages_arcane_maxDamage, S_mages_arcane_reload, 0); break;
+ case TW_SORCERER: T(S_mages_sorcerer_cost, S_mages_sorcerer_range, S_mages_sorcerer_minDamage, S_mages_sorcerer_maxDamage, S_mages_sorcerer_reload, 0); break;
+ case TW_ENGINEER:
+ if (level == 1) T(S_engineers_level1_cost, S_engineers_level1_range, S_engineers_level1_minDamage, S_engineers_level1_maxDamage, S_engineers_level1_reload, S_engineers_level1_area);
+ if (level == 2) T(S_engineers_level2_cost, S_engineers_level2_range, S_engineers_level2_minDamage, S_engineers_level2_maxDamage, S_engineers_level2_reload, S_engineers_level2_area);
+ if (level == 3) T(S_engineers_level3_cost, S_engineers_level3_range, S_engineers_level3_minDamage, S_engineers_level3_maxDamage, S_engineers_level3_reload, S_engineers_level3_area);
+ break;
+ case TW_BFG: T(S_engineers_bfg_cost, S_engineers_bfg_range, S_engineers_bfg_minDamage, S_engineers_bfg_maxDamage, S_engineers_bfg_reload, S_engineers_bfg_area); break;
+ case TW_TESLA: T(S_engineers_tesla_cost, S_engineers_tesla_range, S_engineers_tesla_minDamage, S_engineers_tesla_maxDamage, S_engineers_tesla_reload, 0); break;
+ }
+#undef T
+ /* GameSettings.§_-Gm§: the upgrades bought with stars */
+ bool archer = kind == TW_ARCHER || kind == TW_RANGER || kind == TW_MUSKETEER;
+ bool mage = kind == TW_MAGE || kind == TW_ARCANE || kind == TW_SORCERER;
+ bool eng = kind == TW_ENGINEER || kind == TW_BFG || kind == TW_TESLA;
+ if (archer && up_on(UP_ARCHERS, 2)) t.range = (int16_t)(t.range + (int)ceilf(t.range * 0.1f));
+ if (archer && up_on(UP_ARCHERS, 4)) t.range = (int16_t)(t.range + (int)ceilf(t.range * 0.1f));
+ if (mage && upgrades[UP_MAGES] >= 1) t.range = (int16_t)(t.range + (int)ceilf(t.range * 0.1f));
+ if (mage && up_on(UP_MAGES, 4))
+ t.min_dmg = (int16_t)(t.min_dmg + (int)ceilf(t.min_dmg * 0.15f)), t.max_dmg = (int16_t)(t.max_dmg + (int)ceilf(t.max_dmg * 0.15f));
+ if (eng && upgrades[UP_ENGINEERS] >= 1)
+ t.min_dmg = (int16_t)(t.min_dmg + (int)ceilf(t.min_dmg * 0.1f)), t.max_dmg = (int16_t)(t.max_dmg + (int)ceilf(t.max_dmg * 0.1f));
+ if (eng && up_on(UP_ENGINEERS, 2)) t.range = (int16_t)(t.range + (int)ceilf(t.range * 0.1f));
+ /* the mages' and engineers' price cut (Hermetic Study, Field Logistics) */
+ if ((mage && up_on(UP_MAGES, 3)) || (eng && up_on(UP_ENGINEERS, 3))) t.cost = (int16_t)ceilf(t.cost - t.cost * 0.1f);
+ return t;
+}
+
+BarrackStat barrack_stat(int kind, int level) {
+ BarrackStat b = {0};
+#define BS(g) b = (BarrackStat){S_soldiers_##g##_cost, S_soldiers_##g##_range, S_soldiers_##g##_rangeRally, S_soldiers_##g##_health, \
+ S_soldiers_##g##_armor, S_soldiers_##g##_minDamage, S_soldiers_##g##_maxDamage, S_soldiers_##g##_reload, \
+ S_soldiers_##g##_respawn, S_soldiers_##g##_regen, S_soldiers_##g##_regenReload}
+ if (kind == TW_PALADIN) BS(paladin);
+ else if (kind == TW_BARBARIAN) BS(barbarian);
+ else if (level == 1) BS(level1);
+ else if (level == 2) BS(level2);
+ else BS(level3);
+#undef BS
+ if (upgrades[UP_BARRACKS] >= 1) {
+ float f = up_on(UP_BARRACKS, 4) ? 0.2f : 0.1f;
+ b.health = (int16_t)(b.health + (int)ceilf(b.health * f));
+ }
+ if (up_on(UP_BARRACKS, 2)) b.armor = (int16_t)(b.armor + 10);
+ if (up_on(UP_BARRACKS, 3)) {
+ b.respawn = (int16_t)(b.respawn - (int)ceilf(b.respawn * 0.2f));
+ b.rally = (int16_t)(b.rally + (int)ceilf(b.rally * 0.2f));
+ }
+ return b;
+}
+
+int tower_range(int kind, int level) {
+ if (kind == TW_BARRACKS || kind == TW_PALADIN || kind == TW_BARBARIAN) return barrack_stat(kind, level).rally;
+ return tower_stat(kind, level).range;
+}
+
+static bool is_barracks(int k) { return k == TW_BARRACKS || k == TW_PALADIN || k == TW_BARBARIAN; }
+static int base_kind(int k) {
+ switch (k) {
+ case TW_RANGER: case TW_MUSKETEER: return TW_ARCHER;
+ case TW_ARCANE: case TW_SORCERER: return TW_MAGE;
+ case TW_BFG: case TW_TESLA: return TW_ENGINEER;
+ case TW_PALADIN: case TW_BARBARIAN: return TW_BARRACKS;
+ default: return k;
+ }
+}
+static int lock_kind(int k) { /* isTowerLocked's numbering: archers, barracks, engineers, mages (as packed) */
+ switch (base_kind(k)) {
+ case TW_ARCHER: return 0;
+ case TW_BARRACKS: return 1;
+ case TW_ENGINEER: return 2;
+ default: return 3;
+ }
+}
+
+/* ------------------------------------------------------------------ the shooting cycle */
+static void set_level(Spot *t) {
+ /* reloadTime: the reload less the charge; the charge plays, then the shot */
+ t->target = -1, t->ready = 0, t->reload_t = 0, t->charging = 0, t->charge_t = 0;
+ switch (t->kind) {
+ case TW_ARCHER: case TW_RANGER: t->charge_len = 8, t->shoot_at = 7; break;
+ case TW_MUSKETEER: t->charge_len = 24, t->shoot_at = 7; break;
+ case TW_MAGE: t->charge_len = 15, t->shoot_at = 10; break;
+ case TW_ARCANE: t->charge_len = 38, t->shoot_at = 18; break;
+ case TW_SORCERER: t->charge_len = 25, t->shoot_at = 14; break;
+ case TW_ENGINEER: t->charge_len = 34, t->shoot_at = 10; break;
+ case TW_BFG: t->charge_len = 48, t->shoot_at = 22; break;
+ case TW_TESLA: t->charge_len = 63, t->shoot_at = 48; break;
+ default: t->charge_len = 0;
+ }
+ if (!is_barracks(t->kind)) t->reload = (int16_t)(tower_stat(t->kind, t->level).reload - t->charge_len);
+ /* the shooters stand at the tower's top (§_-5E§ right, §_-0C§ left) */
+}
+
+static void barracks_soldiers(int s, int kind) {
+ Spot *t = &B.spot[s];
+ for (int k = 0; k < 3; k++) {
+ Soldier *old = SO(t->soldiers[k]);
+ float ox = old ? old->x : t->x, oy = old ? old->y : t->y - 0.01f;
+ bool was_dead = old ? old->dead || old->respawning : true;
+ if (old) soldier_free(old);
+ /* their places: around the rally point, on an ellipse 40 x 28, from 180 degrees in thirds */
+ float ang = (180.0f + 120.0f * (float)k - 90.0f) * (float)M_PI / 180.0f;
+ Pt r = {t->rally.x + cosf(ang) * 20.0f, t->rally.y + 10.0f + sinf(ang) * 14.0f};
+ int i = soldier_new(kind, s, (Pt){ox, oy}, r);
+ t->soldiers[k] = (int8_t)i;
+ if (i >= 0 && old && !was_dead) {
+ Soldier *so = &B.so[i];
+ so->respawning = 0, so->active = 1, so->walking = 1, so->hidden = 0;
+ so->dx = r.x, so->dy = r.y;
+ }
+ }
+}
+
+static int soldier_kind(int kind, int level) {
+ if (kind == TW_PALADIN) return SK_PALADIN;
+ if (kind == TW_BARBARIAN) return SK_BARBARIAN;
+ return level == 1 ? SK_L1 : level == 2 ? SK_L2 : SK_L3;
+}
+
+static void finish(int s) {
+ Spot *t = &B.spot[s];
+ t->building = 0;
+ set_level(t);
+ if (is_barracks(t->kind)) barracks_soldiers(s, soldier_kind(t->kind, t->level));
+ special_init(s);
+}
+
+void spot_build(int s, int kind) {
+ Spot *t = &B.spot[s];
+ int cost = kind == TW_BARRACKS ? barrack_stat(TW_BARRACKS, 1).cost : tower_stat(kind, 1).cost;
+ memset(&t->charging, 0, (size_t)((uint8_t *)&t->premade - &t->charging));
+ t->kind = (uint8_t)kind, t->level = 1;
+ t->spent = (int16_t)cost;
+ battle_cash(-cost);
+ t->building = BUILD_TIME;
+ t->target = -1, t->elemental = -1;
+ for (int k = 0; k < 3; k++) t->soldiers[k] = -1;
+}
+
+void spot_make(int s, int kind, int level) {
+ Spot *t = &B.spot[s];
+ t->kind = (uint8_t)kind, t->level = (uint8_t)level, t->premade = 1, t->spent = 0;
+ t->target = -1, t->elemental = -1;
+ for (int k = 0; k < 3; k++) t->soldiers[k] = -1;
+ finish(s);
+}
+
+/* what the next step costs: choice 0 the next level, 1 and 2 the specials; -1 if there is none, -2 locked */
+int spot_cost(int s, int choice) {
+ Spot *t = &B.spot[s];
+ if (t->kind == TW_NONE) { /* the build menu: choice 1 archers, 2 barracks, 3 mages, 4 engineers */
+ static const uint8_t kinds[5] = {0, TW_ARCHER, TW_BARRACKS, TW_MAGE, TW_ENGINEER};
+ int k = kinds[choice < 0 || choice > 4 ? 0 : choice];
+ if (!k) return -1;
+ if (tower_locked(lock_kind(k), 1)) return -2;
+ return k == TW_BARRACKS ? barrack_stat(k, 1).cost : tower_stat(k, 1).cost;
+ }
+ if (t->level >= 4 || t->building) return -1;
+ if (choice == 0) {
+ if (t->level == 3) return -1;
+ if (tower_locked(lock_kind(t->kind), t->level + 1)) return -2;
+ return is_barracks(t->kind) ? barrack_stat(t->kind, t->level + 1).cost : tower_stat(t->kind, t->level + 1).cost;
+ }
+ if (t->level != 3) return -1;
+ int k = special_kind(t->kind, choice);
+ /* the first special (ranger, arcane, BFG, paladin) needs unlock 4, the second 5 */
+ bool second = k == TW_MUSKETEER || k == TW_SORCERER || k == TW_TESLA || k == TW_BARBARIAN;
+ if (tower_locked(lock_kind(t->kind), second ? 5 : 4)) return -2;
+ return is_barracks(k) ? barrack_stat(k, 4).cost : tower_stat(k, 4).cost;
+}
+
+void spot_upgrade(int s, int choice) {
+ Spot *t = &B.spot[s];
+ int cost = spot_cost(s, choice);
+ if (cost < 0) return;
+ battle_cash(-cost);
+ t->spent = (int16_t)(t->spent + cost);
+ fx_add(AN_T_CLOUD, t->x, t->y, false, false);
+ if (choice == 0) {
+ t->level++;
+ set_level(t);
+ if (is_barracks(t->kind)) barracks_soldiers(s, soldier_kind(t->kind, t->level));
+ return;
+ }
+ t->kind = (uint8_t)special_kind(t->kind, choice);
+ t->level = 4;
+ set_level(t);
+ if (is_barracks(t->kind)) barracks_soldiers(s, soldier_kind(t->kind, t->level));
+ special_init(s);
+}
+
+int spot_sell_value(int s) {
+ Spot *t = &B.spot[s];
+ if (base_kind(t->kind) == TW_ARCHER && upgrades[UP_ARCHERS] >= 1) return (int)((float)t->spent * 0.9f);
+ return (int)((float)t->spent * 0.6f);
+}
+
+void spot_sell(int s) {
+ Spot *t = &B.spot[s];
+ int v = spot_sell_value(s);
+ battle_cash(v);
+ for (int k = 0; k < 3; k++) {
+ Soldier *so = SO(t->soldiers[k]);
+ if (so) soldier_free(so);
+ t->soldiers[k] = -1;
+ }
+ special_sold(s);
+ fx_add(AN_T_SELL, t->x, t->y, false, false);
+ fx_value(t->x, t->y - 30, v);
+ Pt rally = t->rally;
+ int16_t x = t->x, y = t->y;
+ memset(t, 0, sizeof *t);
+ t->x = x, t->y = y, t->rally = rally, t->target = -1, t->elemental = -1;
+ for (int k = 0; k < 3; k++) t->soldiers[k] = -1;
+}
+
+/* ------------------------------------------------------------------ targets */
+bool tower_in_range(const Spot *t, float x, float y) {
+ int r = tower_stat(t->kind, t->level).range;
+ return ellipse_contains(t->x, t->y - 10, (float)r, r * RANGE_RATIO, x, y);
+}
+
+/* findNewTarget: the active enemy in range furthest along its road */
+int tower_find_target(Spot *t, bool fliers, bool predicted) {
+ int best = -1;
+ for (int i = 0; i < MAX_ENEMIES; i++) {
+ Enemy *e = &B.en[i];
+ if (!e->alive || !e->active || (!fliers && e->flying)) continue;
+ float x = e->x, y = e->y;
+ if (predicted) { /* the engineers aim where it will be */
+ Pt p = enemy_road(e, enemy_nodes_speed(e));
+ x = p.x, y = p.y;
+ }
+ if (!tower_in_range(t, x, y)) continue;
+ if (best < 0) {
+ best = i;
+ continue;
+ }
+ Enemy *b = &B.en[best];
+ if (path_len(b->path, b->lane) - b->node > path_len(e->path, e->lane) - e->node) best = i;
+ }
+ t->target = (int8_t)best;
+ return best;
+}
+
+/* ------------------------------------------------------------------ shots */
+static void shoot_arrow(int s) {
+ Spot *t = &B.spot[s];
+ Enemy *e = EN(t->target);
+ bool have = e && e->active;
+ if (!have) {
+ int k = tower_find_target(t, true, false);
+ e = EN(k);
+ have = e != 0;
+ }
+ Bullet *b = bullet_new(BU_ARROW);
+ if (!b) return;
+ t->arrows++;
+ bool right = t->arrows & 1;
+ float lift = t->level >= 3 ? (t->kind == TW_ARCHER ? 50 : 53) : 45;
+ if (t->kind == TW_RANGER || t->kind == TW_MUSKETEER) lift = 53;
+ b->x = b->x0 = t->x + (right ? (t->level >= 3 && t->kind == TW_ARCHER ? 8 : 5) : (t->level >= 3 && t->kind == TW_ARCHER ? -7 : -9));
+ b->y = b->y0 = t->y - lift;
+ b->level = t->kind == TW_RANGER ? 4 : t->level;
+ b->t1 = 17;
+ b->target = have ? (int8_t)(e - B.en) : -1;
+ if (!have) b->tx = t->dest.x, b->ty = t->dest.y;
+ else if (e->held) b->tx = e->x + enemy_stats[e->type].x_adj, b->ty = e->y + enemy_stats[e->type].y_adj;
+ else {
+ b->tx = e->x + enemy_stats[e->type].x_adj + e->xs * b->t1 + rnd() * 10;
+ b->ty = e->y + enemy_stats[e->type].y_adj + e->ys * b->t1 + rnd() * 10 - 10;
+ }
+ b->g = 1;
+ b->xs = (b->tx - b->x0) / b->t1;
+ b->ys = (b->ty - b->y0 - b->g * b->t1 * (b->t1 / 2.0f)) / b->t1;
+ if (up_on(UP_ARCHERS, 5) && rnd() <= 0.1f) b->crit = 1; /* Precision: double damage */
+ if (up_on(UP_ARCHERS, 3)) b->pierce = 10; /* Piercing Shots */
+ special_arrow(s, b);
+ t->shots++;
+}
+
+static void shoot_bolt(int s) {
+ Spot *t = &B.spot[s];
+ Enemy *e = EN(t->target);
+ if (!e || !e->active) {
+ e = EN(tower_find_target(t, true, false));
+ if (!e) return;
+ }
+ bool down = e->y >= t->y;
+ Bullet *b = bullet_new(BU_BOLT);
+ if (!b) return;
+ float up_y = t->level >= 3 ? 51 : 48, down_y = t->level >= 3 ? 53 : 48;
+ b->x = t->x + (down ? (t->level >= 3 ? -7 : -6) : 6), b->y = t->y - (down ? down_y : up_y);
+ b->target = (int8_t)(e - B.en), b->level = t->level;
+ b->acc = 1, b->acc_max = 10;
+ b->first = 1;
+ b->tx = e->x + enemy_stats[e->type].x_adj, b->ty = e->y + enemy_stats[e->type].y_adj;
+ TowerStat st = tower_stat(t->kind, t->level);
+ b->min_dmg = st.min_dmg, b->max_dmg = st.max_dmg;
+ special_bolt(s, b);
+ t->shots++;
+}
+
+static void shoot_bomb(int s) {
+ Spot *t = &B.spot[s];
+ Enemy *e = EN(t->target);
+ if (!e || !e->active) {
+ e = EN(tower_find_target(t, false, true));
+ if (e) {
+ Pt p = enemy_road(e, enemy_nodes_speed(e));
+ t->dest = p;
+ }
+ } else if (e->blocked)
+ t->dest = (Pt){e->x, e->y};
+ Bullet *b = bullet_new(BU_BOMB);
+ if (!b) return;
+ b->x = b->x0 = t->x, b->y = b->y0 = t->y - 45;
+ b->tx = t->dest.x, b->ty = t->dest.y;
+ b->t1 = 27, b->g = 1;
+ b->xs = (b->tx - b->x0) / b->t1;
+ b->ys = (b->ty - b->y0 - b->g * b->t1 * b->t1 / 2) / b->t1;
+ TowerStat st = tower_stat(t->kind, t->level);
+ b->min_dmg = st.min_dmg, b->max_dmg = st.max_dmg, b->area = st.area, b->level = t->level;
+ b->rot = rnd() * 100;
+ special_bomb(s, b);
+ t->shots++;
+}
+
+/* §_-06§: the shot starts (the shooter turns, the tower plays its shot) */
+static void start_shot(int s) {
+ Spot *t = &B.spot[s];
+ Enemy *e = EN(t->target);
+ t->ready = 0, t->charging = 1, t->charge_t = 0, t->idle_t = 0;
+ if (!e) return;
+ int k = (t->arrows + 1) & 1;
+ t->shooter_flip[k] = e->x < t->x;
+ t->shooter_up[k] = e->y < t->y;
+ t->shooter_t[k] = 0;
+ t->anim_t = 0;
+ t->dest = (Pt){e->x, e->y};
+ if (base_kind(t->kind) == TW_ENGINEER) t->dest = enemy_road(e, enemy_nodes_speed(e));
+}
+
+/* ------------------------------------------------------------------ a frame */
+static void ice_step(Spot *t) {
+ /* IceBlock: 23 frames forming, then held until it takes 3 hits, then 44 melting (free at 25) */
+ if (t->ice == 1 && ++t->ice_t >= 23) t->ice = 2, t->ice_t = 0;
+ else if (t->ice == 3) {
+ if (++t->ice_t == 25) t->disabled = 0;
+ if (t->ice_t >= 44) t->ice = 0;
+ }
+}
+
+void tower_step(int s) {
+ Spot *t = &B.spot[s];
+ if (t->kind == TW_NONE || t->kind == 0xFF) return;
+ t->anim_t++, t->shooter_t[0]++, t->shooter_t[1]++;
+ if (t->ice) ice_step(t);
+ if (t->disabled) return;
+ if (t->building) {
+ if (--t->building == 0) finish(s);
+ return;
+ }
+ if (is_barracks(t->kind)) {
+ barracks_step(s);
+ return;
+ }
+ special_timers(s);
+ if (t->charging) {
+ t->charge_t++;
+ bool at = t->charge_t == t->shoot_at;
+ if (t->charge_t == t->charge_len) t->charge_t = 0, t->charging = 0;
+ if (at) {
+ switch (base_kind(t->kind)) {
+ case TW_ARCHER: if (!special_shoot(s)) shoot_arrow(s); break;
+ case TW_MAGE: if (!special_shoot(s)) shoot_bolt(s); break;
+ case TW_ENGINEER: if (!special_shoot(s)) shoot_bomb(s); break;
+ }
+ }
+ return;
+ }
+ bool mage_like = base_kind(t->kind) != TW_ARCHER;
+ if (mage_like && special_run(s)) return;
+ if (!t->ready && ++t->reload_t >= t->reload) t->ready = 1, t->reload_t = 0;
+ if (t->ready) {
+ if (!mage_like && special_run(s)) return;
+ bool fliers = base_kind(t->kind) != TW_ENGINEER || t->kind == TW_TESLA;
+ if (tower_find_target(t, fliers, base_kind(t->kind) == TW_ENGINEER && t->kind != TW_TESLA) >= 0) start_shot(s);
+ else if (++t->idle_t == 90) t->shooter_up[0] = t->shooter_up[1] = 0;
+ }
+}
+
+/* ------------------------------------------------------------------ barracks */
+void barracks_step(int s) {
+ Spot *t = &B.spot[s];
+ /* the door: opens over 12 frames (soldiers come out), stays, closes from 22 to 25 */
+ if (t->door) {
+ if (t->door_t < 25) {
+ if (t->door_t == 12) t->door = 2;
+ else if (t->door_t > 22) t->door = 3;
+ t->door_t++;
+ } else
+ t->door = 0;
+ }
+ special_timers(s);
+}
+
+bool barracks_door_closed(int s) { return B.spot[s].door == 0; }
+bool barracks_door_opening(int s) { return B.spot[s].door == 1; }
+int barracks_door_t(int s) { return B.spot[s].door_t; }
+void barracks_open(int s) {
+ Spot *t = &B.spot[s];
+ if (t->door == 0) t->door = 1, t->door_t = 0, t->anim_t = 0;
+}
+
+bool spot_rally_ok(int s, Pt p) {
+ Spot *t = &B.spot[s];
+ int r = t->kind == TW_SORCERER ? S_mages_sorcerer_elementalRallyRange : barrack_stat(TW_BARRACKS, 1).rally;
+ if (!ellipse_contains(t->x, t->y - 10, (float)r, r * RANGE_RATIO, p.x, p.y)) return false;
+ for (int pa = 0; pa < B.npaths; pa++) {
+ int n = path_len(pa, 0);
+ for (int k = 0; k < n; k++) {
+ Pt q = path_node(pa, 0, k);
+ float dx = q.x - p.x, dy = q.y - p.y;
+ if (dx * dx + dy * dy < 900) return true;
+ }
+ }
+ return false;
+}
+
+void spot_rally(int s, Pt p) {
+ Spot *t = &B.spot[s];
+ if (t->kind == TW_SORCERER) {
+ special_rally(s, p);
+ return;
+ }
+ t->rally = p;
+ for (int k = 0; k < 3; k++) {
+ Soldier *so = SO(t->soldiers[k]);
+ if (!so) continue;
+ float ang = (180.0f + 120.0f * (float)k - 90.0f) * (float)M_PI / 180.0f;
+ soldier_set_rally(so, (Pt){p.x + cosf(ang) * 20.0f, p.y + 10.0f + sinf(ang) * 14.0f});
+ }
+ fx_add(AN_T_FLAG, p.x, p.y, false, false);
+}
diff --git a/games/kingdomrush/src/ui.c b/games/kingdomrush/src/ui.c
new file mode 100644
index 00000000..2176586a
--- /dev/null
+++ b/games/kingdomrush/src/ui.c
@@ -0,0 +1,430 @@
+/* The battle's pictures: towers, what flies, the tower menu (TowerMenu.as), the counts and spells (Hud,
+ * MenuBottom), the pause, notification and end screens. */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+#include "gfx.h"
+#include "settings.h"
+#include "special.h"
+#include "strings.h"
+#include "ui.h"
+
+#define C_PANEL RGB(0x2A1C10)
+#define C_EDGE RGB(0x8A6A3A)
+#define C_GOLD RGB(0xFFD32A)
+#define C_TEXT RGB(0xF4E6C8)
+#define C_DIM RGB(0x9A8A70)
+
+/* TowerMenuItem's icons (its frames, from 1) */
+enum {
+ IC_SELL = 2, IC_RALLY = 4, IC_ARCHER, IC_SOLDIER, IC_MAGE, IC_ENGINEER, IC_UP, IC_ARCANE, IC_SORCERER, IC_PALADIN,
+ IC_BARBARIAN, IC_RIFLEMEN, IC_SHARPSHOOTER, IC_BFG, IC_TESLA, IC_LOCKED
+};
+
+/* TowerMenu.§_-NM§: the places around a spot (positions 1 to 11), at 0.4 */
+static const int8_t place[12][2] = {{0, 23}, {-16, -13}, {16, -13}, {-16, 17}, {16, 17}, {-20, -2}, {20, -2},
+ {0, -18}, {0, 24}, {16, 16}, {-18, -8}, {18, -8}};
+
+const char *tower_name(int kind, int level) {
+ switch (kind) {
+ case TW_ARCHER: return level == 1 ? "Archer Tower" : level == 2 ? "Marksmen Tower" : "Sharpshooter Tower";
+ case TW_BARRACKS: return level == 1 ? "Militia Barracks" : level == 2 ? "Footmen Barracks" : "Knights Barracks";
+ case TW_MAGE: return level == 1 ? "Mage Tower" : level == 2 ? "Adept Tower" : "Wizard Tower";
+ case TW_ENGINEER: return level == 1 ? "Dwarven Bombard" : level == 2 ? "Dwarven Artillery" : "Dwarven Howitzer";
+ case TW_RANGER: return tower_text("TOWER_RANGERS_NAME");
+ case TW_MUSKETEER: return tower_text("TOWER_MUSKETEERS_NAME");
+ case TW_PALADIN: return tower_text("TOWER_PALADINS_NAME");
+ case TW_BARBARIAN: return tower_text("TOWER_BARBARIANS_NAME");
+ case TW_ARCANE: return tower_text("TOWER_ARCANE_NAME");
+ case TW_SORCERER: return tower_text("TOWER_SORCERER_NAME");
+ case TW_BFG: return tower_text("TOWER_BFG_NAME");
+ case TW_TESLA: return tower_text("TOWER_TESLA_NAME");
+ }
+ return "";
+}
+
+static bool barracks(int k) { return k == TW_BARRACKS || k == TW_PALADIN || k == TW_BARBARIAN; }
+
+/* ------------------------------------------------------------------ the menu */
+static void item(RingItem *it, int action, int icon, int pos, int cost, bool locked, const char *name, int range) {
+ memset(it, 0, sizeof *it);
+ it->action = (uint8_t)action, it->icon = (uint8_t)icon, it->cost = (int16_t)cost, it->locked = locked;
+ it->x = place[pos][0], it->y = place[pos][1], it->range = (int16_t)range;
+ snprintf(it->name, sizeof it->name, "%s", name);
+}
+
+int ring_items(int s, RingItem *out) {
+ Spot *t = &B.spot[s];
+ int n = 0;
+ if (t->kind == TW_NONE) {
+ static const uint8_t acts[4] = {RA_ARCHER, RA_BARRACKS, RA_MAGE, RA_ENGINEER};
+ static const uint8_t icons[4] = {IC_ARCHER, IC_SOLDIER, IC_MAGE, IC_ENGINEER};
+ static const uint8_t kinds[4] = {TW_ARCHER, TW_BARRACKS, TW_MAGE, TW_ENGINEER};
+ for (int k = 0; k < 4; k++) {
+ int c = spot_cost(s, k + 1);
+ item(&out[n++], acts[k], c == -2 ? IC_LOCKED : icons[k], k + 1, c < 0 ? 0 : c, c == -2, tower_name(kinds[k], 1),
+ c == -2 ? 0 : tower_range(kinds[k], 1));
+ }
+ return n;
+ }
+ if (t->level < 3) {
+ int c = spot_cost(s, 0);
+ item(&out[n++], RA_UPGRADE, c == -2 ? IC_LOCKED : IC_UP, 7, c < 0 ? 0 : c, c == -2, tower_name(t->kind, t->level + 1),
+ c == -2 ? 0 : tower_range(t->kind, t->level + 1));
+ } else if (t->level == 3) {
+ static const uint8_t ic[5][2] = {{0, 0}, {IC_RIFLEMEN, IC_SHARPSHOOTER}, {IC_PALADIN, IC_BARBARIAN},
+ {IC_ARCANE, IC_SORCERER}, {IC_TESLA, IC_BFG}};
+ for (int k = 1; k <= 2; k++) {
+ int c = spot_cost(s, k), sk = special_kind(t->kind, k);
+ item(&out[n++], k == 1 ? RA_SPECIAL1 : RA_SPECIAL2, c == -2 ? IC_LOCKED : ic[t->kind][k - 1], k, c < 0 ? 0 : c, c == -2,
+ tower_name(sk, 4), c == -2 ? 0 : tower_range(sk, 4));
+ }
+ } else {
+ Ability a[3];
+ int na = special_abilities(s, a);
+ for (int k = 0; k < na; k++) {
+ char nm[40];
+ if (a[k].level >= a[k].max) snprintf(nm, sizeof nm, "%s (top)", tower_text(a[k].key));
+ else snprintf(nm, sizeof nm, "%s %d/%d", tower_text(a[k].key), a[k].level + 1, a[k].max);
+ item(&out[n], RA_ABILITY0 + k, a[k].icon, a[k].pos, a[k].level >= a[k].max ? 0 : a[k].cost, false, nm, 0);
+ out[n].level = a[k].level, out[n].max = a[k].max;
+ n++;
+ }
+ }
+ if (barracks(t->kind) || t->kind == TW_SORCERER)
+ item(&out[n++], RA_RALLY, IC_RALLY, 9, 0, false, "Rally point", 0);
+ if (!t->premade || 1) {
+ char nm[40];
+ snprintf(nm, sizeof nm, "Sell for %d", spot_sell_value(s));
+ item(&out[n++], RA_SELL, IC_SELL, 0, 0, false, nm, 0);
+ }
+ return n;
+}
+
+void draw_ring(const RingItem *it, int n, int sel, int cx, int cy, int cash) {
+ if (!gfx_rows(cy - 40, 80)) return;
+ gfx_ellipse(cx, cy + 2, 25, 23, RGB(0x6A5030), 20);
+ for (int i = 0; i < n; i++) {
+ int x = cx + it[i].x, y = cy + it[i].y;
+ int slot = anim_slot(AN_UI_ICONS, it[i].icon - 1, false);
+ bool afford = it[i].action == RA_SELL || it[i].action == RA_RALLY || it[i].cost <= cash;
+ bool done = it[i].max && it[i].level >= it[i].max;
+ if (i == sel) {
+ gfx_ellipse_fill(x, y, 11, 11, RGB(0xFFE14D), 32);
+ gfx_ellipse(x, y, 12, 12, RGB(0x6A4A00), 32);
+ }
+ if (it[i].locked || !afford || done) spr_frame_tint(slot, x - 10, y - 10, false, RGB(0x302820), 18);
+ else spr_frame(slot, x - 10, y - 10, false);
+ if (it[i].cost && !it[i].locked && !done) {
+ char s[8];
+ snprintf(s, sizeof s, "%d", it[i].cost);
+ gfx_text_oc(FONT_SMALL, x, y + 7, s, afford ? C_GOLD : RGB(0xB0A090));
+ }
+ }
+}
+
+/* ------------------------------------------------------------------ towers */
+typedef struct {
+ int idle, shoot;
+ int shooter; /* the archers' set (AN_S_*_IDLEDOWN), or the mage's */
+ int8_t sx[2], sy[2]; /* the shooters' places (at full size) */
+} TowerLook;
+
+static TowerLook look(const Spot *t) {
+ switch (t->kind) {
+ case TW_ARCHER:
+ if (t->level == 1) return (TowerLook){AN_T_ARCHER1_ALL, -1, AN_S_ARCHER1_IDLEDOWN, {-7, 7}, {-50, -50}};
+ if (t->level == 2) return (TowerLook){AN_T_ARCHER2_ALL, -1, AN_S_ARCHER2_IDLEDOWN, {-7, 6}, {-52, -52}};
+ return (TowerLook){AN_T_ARCHER3_ALL, -1, AN_S_ARCHER3_IDLEDOWN, {-8, 6}, {-54, -54}};
+ case TW_RANGER: return (TowerLook){AN_T_RANGER_ALL, -1, AN_S_RANGER_IDLEDOWN, {-6, 6}, {-59, -59}};
+ case TW_MUSKETEER: return (TowerLook){AN_T_MUSKETEER_ALL, -1, AN_S_MUSKETEER_IDLEDOWN, {-10, 6}, {-54, -54}};
+ case TW_MAGE:
+ if (t->level == 1) return (TowerLook){AN_T_MAGE1_IDLE, AN_T_MAGE1_SHOOT, AN_S_MAGE_IDLEDOWN, {-8, 0}, {-49, 0}};
+ if (t->level == 2) return (TowerLook){AN_T_MAGE2_IDLE, AN_T_MAGE2_SHOOT, AN_S_MAGE_IDLEDOWN, {-8, 0}, {-48, 0}};
+ return (TowerLook){AN_T_MAGE3_IDLE, AN_T_MAGE3_SHOOT, AN_S_MAGE_IDLEDOWN, {-8, 0}, {-53, 0}};
+ case TW_ARCANE: return (TowerLook){AN_T_ARCANE_IDLE, AN_T_ARCANE_SHOOT, AN_S_ARCANE_IDLEDOWN, {-4, 0}, {-51, 0}};
+ case TW_SORCERER: return (TowerLook){AN_T_SORCERER_IDLE, AN_T_SORCERER_SHOOT, AN_S_SORCERER_IDLEDOWN, {-6, 0}, {-50, 0}};
+ case TW_ENGINEER:
+ if (t->level == 1) return (TowerLook){AN_T_ENG1_IDLE, AN_T_ENG1_SHOOT, -1, {0}, {0}};
+ if (t->level == 2) return (TowerLook){AN_T_ENG2_IDLE, AN_T_ENG2_SHOOT, -1, {0}, {0}};
+ return (TowerLook){AN_T_ENG3_IDLE, AN_T_ENG3_SHOOT, -1, {0}, {0}};
+ case TW_BFG: return (TowerLook){AN_T_BFG_IDLE, AN_T_BFG_SHOOT, -1, {0}, {0}};
+ case TW_TESLA: return (TowerLook){AN_T_TESLA_IDLE, AN_T_TESLA_SHOOTING, -1, {0}, {0}};
+ case TW_BARRACKS:
+ if (t->level == 1) return (TowerLook){AN_T_BAR1_IDLE, AN_T_BAR1_DOOR_OPEN, -1, {0}, {0}};
+ if (t->level == 2) return (TowerLook){AN_T_BAR2_IDLE, AN_T_BAR2_OPEN_DOOR, -1, {0}, {0}};
+ return (TowerLook){AN_T_BAR3_IDLE, AN_T_BAR3_OPEN_DOOR, -1, {0}, {0}};
+ case TW_PALADIN: return (TowerLook){AN_T_PALADIN_IDLE, AN_T_PALADIN_OPEN_DOOR, -1, {0}, {0}};
+ case TW_BARBARIAN: return (TowerLook){AN_T_BARBARIAN_IDLE, AN_T_BARBARIAN_OPEN_DOOR, -1, {0}, {0}};
+ }
+ return (TowerLook){-1, -1, -1, {0}, {0}};
+}
+
+static int base_of(int k) {
+ switch (k) {
+ case TW_ARCHER: case TW_RANGER: case TW_MUSKETEER: return TW_ARCHER;
+ case TW_MAGE: case TW_ARCANE: case TW_SORCERER: return TW_MAGE;
+ case TW_ENGINEER: case TW_BFG: case TW_TESLA: return TW_ENGINEER;
+ default: return TW_BARRACKS;
+ }
+}
+
+void draw_base(const Spot *t, int x, int y, int terrain) {
+ if (t->kind == TW_NONE || t->kind == 0xFF || t->building) return;
+ int b = base_of(t->kind);
+ int an = b == TW_ARCHER ? AN_T_BASE_ARCHER_FOREST : b == TW_MAGE ? AN_T_BASE_MAGE_FOREST : AN_T_BASE_BAR_FOREST;
+ spr_anim(an + terrain, 0, false, x, y, false);
+}
+
+void draw_tower(const Spot *t, int x, int y) {
+ if (t->building) {
+ int b = base_of(t->kind);
+ spr_anim(b == TW_ARCHER ? AN_T_BUILD_ARCHER : b == TW_MAGE ? AN_T_BUILD_MAGE : AN_T_BUILD_BAR, 0, false, x, y, false);
+ return;
+ }
+ TowerLook L = look(t);
+ int b = base_of(t->kind);
+ if (b == TW_BARRACKS) {
+ if (t->door) spr_anim(L.shoot, t->door_t, false, x, y, false);
+ else spr_anim(L.idle, 0, false, x, y, false);
+ return;
+ }
+ bool shooting = L.shoot >= 0 && t->anim_t < anim_ticks(L.shoot) && (t->charging || t->anim_t < anim_ticks(L.shoot));
+ if (L.shoot >= 0 && (t->charging || shooting) && t->shots) spr_anim(L.shoot, t->anim_t, false, x, y, false);
+ else spr_anim(L.idle, 0, false, x, y, false);
+ if (L.shooter < 0) return;
+ /* the shooters: [idle down, idle up, shoot down, shoot up] in that order in data.bin */
+ int nsh = b == TW_ARCHER ? 2 : 1;
+ for (int k = 0; k < nsh; k++) {
+ int sx = x + (int)lroundf(L.sx[k] * 0.4f), sy = y + (int)lroundf(L.sy[k] * 0.4f);
+ int up = t->shooter_up[k], an = L.shooter + up;
+ int shoot_an = L.shooter + 2 + up;
+ int tt = t->shooter_t[k];
+ if (t->shots && tt < anim_ticks(shoot_an) && (b != TW_ARCHER || ((t->arrows + (t->charging ? 1 : 0)) & 1) == k))
+ spr_anim(shoot_an, tt, false, sx, sy, t->shooter_flip[k]);
+ else
+ spr_anim(an, 0, false, sx, sy, t->shooter_flip[k]);
+ }
+}
+
+/* ------------------------------------------------------------------ what flies */
+static void line_dir(int x, int y, float rot, int len, uint16_t shaft, uint16_t tip) {
+ float c = cosf(rot), s = sinf(rot);
+ int x0 = x - (int)lroundf(c * len / 2), y0 = y - (int)lroundf(s * len / 2);
+ int x1 = x + (int)lroundf(c * len / 2), y1 = y + (int)lroundf(s * len / 2);
+ gfx_line(x0, y0, x1, y1, shaft);
+ gfx_fill(x1, y1, 1, 1, tip);
+}
+
+void draw_bullet(const Bullet *b, int x, int y) {
+ switch (b->kind) {
+ case BU_ARROW: case BU_ARROW_ENEMY:
+ if (b->active) line_dir(x, y, b->rot, 7, b->kind == BU_ARROW ? RGB(0x8A5A2A) : RGB(0x3A2A4A), RGB(0xE0E0E0));
+ break;
+ case BU_AXE_ENEMY:
+ spr_anim(b->active ? AN_B_AXEENEMY_IDLE : AN_B_AXEENEMY_HIT, b->anim_t, b->active, x, y, b->xs < 0);
+ break;
+ case BU_BOLT:
+ spr_anim(b->active ? AN_B_BOLT_TRAVEL : AN_B_BOLT_HIT, b->anim_t, b->active, x, y, false);
+ break;
+ case BU_BOLT_SORCERER:
+ spr_anim(b->active ? AN_B_BOLTSORCERER_TRAVEL : AN_B_BOLTSORCERER_HIT, b->anim_t, b->active, x, y, false);
+ break;
+ case BU_BOLT_NECRO:
+ spr_anim(b->active ? AN_B_BOLTNECROMANCER_TRAVEL : AN_B_BOLTNECROMANCER_HIT, b->anim_t, b->active, x, y, false);
+ break;
+ case BU_BOMB: {
+ static const int16_t idle[4] = {AN_B_BOMBCOMMON_IDLE, AN_B_BOMBCOMMON_IDLE, AN_B_BOMBDYNAMITE_IDLE, AN_B_BOMBBLACK_IDLE};
+ static const int16_t hit[4] = {AN_B_BOMBCOMMON_HIT, AN_B_BOMBCOMMON_HIT, AN_B_BOMBDYNAMITE_HIT, AN_B_BOMBBLACK_HIT};
+ int l = b->level > 3 ? 3 : b->level;
+ int ia = b->bombs == 9 ? AN_B_BOMBBFG_IDLE : idle[l], ha = b->bombs == 9 ? AN_B_BOMBBFG_HIT : hit[l];
+ if (b->active) spr_anim(ia, 0, false, x, y, false);
+ else spr_anim(ha, b->anim_t, false, x, y, false);
+ break;
+ }
+ case BU_FIREBALL:
+ spr_anim(b->active ? AN_B_FIREBALL_TRAVEL : AN_B_FIREBALL_HIT, b->anim_t, b->active, x, y, false);
+ break;
+ case BU_MISSILE_ENEMY:
+ if (b->active) spr_anim(AN_B_MISSILEENEMY_START, b->anim_t, true, x, y, b->xs < 0);
+ break;
+ default:
+ special_draw_bullet(b, x, y);
+ }
+}
+
+void draw_wave_flag(int x, int y, bool air, uint32_t frame, bool selected) {
+ if (!gfx_rows(y - 14, 28)) return;
+ int left = battle_wave_seconds_left();
+ /* the countdown: a pie filling (WaveFlag's orange arc) */
+ if (selected) gfx_ellipse_fill(x, y, 11, 11, RGB(0xFFE14D), 32);
+ spr_anim(AN_UI_WAVEFLAG, 0, false, x, y, false);
+ spr_anim(air ? AN_UI_WAVEICO_AIR : AN_UI_WAVEICO_GROUND, 0, false, x, y, false);
+ int pulse = (frame / 4) % 2;
+ gfx_ellipse(x, y, 9 + pulse, 9 + pulse, selected ? RGB(0x6A4A00) : RGB(0xFF7A1A), 28);
+ (void)left;
+}
+
+/* ------------------------------------------------------------------ the left side: lives, gold, wave, spells */
+static void counter(int an, int y, const char *s) {
+ spr_anim(an, 0, false, 4, y, false);
+ gfx_text_o(FONT_HUD, 21, y - 1, s, C_TEXT);
+}
+
+static void spell(int y, int an_idle, int an_open, int cd, int reload, char key, bool aiming) {
+ int x = 8;
+ if (cd < 0) { /* locked: the stone doors */
+ spr_anim(an_open, 0, false, x + 11, y + 13, false);
+ } else if (cd > 0 && cd <= 32 && reload == 0) {
+ spr_anim(an_open, 32 - cd, false, x + 11, y + 13, false);
+ } else {
+ spr_anim(an_idle, 0, false, x + 11, y + 13, false);
+ if (cd > 0) { /* recharging: dark from the top, the seconds left */
+ int h = 26 * cd / (reload ? reload : 1);
+ if (h > 26) h = 26;
+ gfx_blend(x, y, 22, h, BLACK, 20);
+ char s[8];
+ snprintf(s, sizeof s, "%d", (cd + 29) / 30);
+ gfx_text_oc(FONT_SMALL, x + 11, y + 7, s, WHITE);
+ }
+ }
+ if (aiming) gfx_frame_rect(x - 2, y - 2, 26, 30, RGB(0xFFE14D));
+ char k[2] = {key, 0};
+ gfx_panel(x + 17, y + 18, 9, 10, RGB(0x1A0F08), C_EDGE);
+ gfx_text(FONT_SMALL, x + 19, y + 18, k, C_TEXT);
+}
+
+void draw_sidebar(int aiming) {
+ if (gfx_y0 >= 240) return;
+ gfx_fill(0, gfx_y0, 40, BAND_H, C_PANEL);
+ gfx_fill(39, gfx_y0, 1, BAND_H, C_EDGE);
+ char s[16];
+ snprintf(s, sizeof s, "%d", B.lives);
+ counter(AN_UI_HEART, 4, s);
+ snprintf(s, sizeof s, "%d", B.cash);
+ counter(AN_UI_COIN, 22, s);
+ snprintf(s, sizeof s, "%d/%d", B.current_wave, B.max_waves);
+ spr_anim(AN_UI_SKULL, 0, false, 5, 41, false);
+ gfx_text_o(FONT_SMALL, 21, 41, s, C_TEXT);
+ int fc = power_fire_cooldown(), rc = power_reinf_cooldown();
+ spell(60, AN_UI_PFIRE_IDLE, AN_UI_PFIRE_OPEN, fc, B.fire_open_t ? 0 : B.fire_reload, '1', aiming == 1);
+ spell(94, AN_UI_PREINF_IDLE, AN_UI_PREINF_OPEN, rc, B.reinf_open_t ? 0 : B.reinf_reload, '2', aiming == 2);
+ /* the next wave: ready to call, and how soon it comes */
+ int left = battle_wave_seconds_left();
+ if (left >= 0 && B.state == LS_NORMAL) {
+ int y = 130;
+ spr_anim(AN_UI_WAVEFLAG, 0, false, 20, y + 10, false);
+ gfx_panel(3, y + 20, 34, 11, RGB(0x1A0F08), C_EDGE);
+ gfx_text_c(FONT_SMALL, 20, y + 20, B.waiting_first ? "start" : "call", C_GOLD);
+ }
+}
+
+static void info_box(const char *title, int y) {
+ gfx_fill(1, y, 38, 240 - y, RGB(0x1E140B));
+ gfx_fill(1, y, 38, 1, C_EDGE);
+ gfx_text_box(FONT_SMALL, 3, y + 2, 35, title, C_TEXT);
+}
+
+static const char *armor_word(int a) {
+ if (a == 0) return "none";
+ if (a <= 30) return "low";
+ if (a <= 60) return "med";
+ if (a < 90) return "high";
+ return "great";
+}
+
+void draw_enemy_info(const Enemy *e) {
+ if (gfx_y0 + BAND_H < 166) return;
+ info_box(enemy_name(e->type), 166);
+ char s[24];
+ snprintf(s, sizeof s, "%d", (int)e->health);
+ int y = 166 + 2 + gfx_line_h(FONT_SMALL) * (gfx_text_w(FONT_SMALL, enemy_name(e->type)) > 35 ? 2 : 1);
+ spr_anim(AN_UI_HEART, 0, false, 3, y + 1, false);
+ gfx_text(FONT_SMALL, 18, y, s, C_TEXT);
+ snprintf(s, sizeof s, "A %s", armor_word(e->armor));
+ gfx_text(FONT_SMALL, 3, y + 14, s, C_DIM);
+ snprintf(s, sizeof s, "M %s", armor_word(e->magic_armor));
+ gfx_text(FONT_SMALL, 3, y + 25, s, C_DIM);
+}
+
+void draw_spot_info(const Spot *t) {
+ if (t->kind == TW_NONE || t->kind == 0xFF || gfx_y0 + BAND_H < 166) return;
+ info_box(tower_name(t->kind, t->level), 166);
+}
+
+void draw_key_line(int x0, const char *text, const RingItem *it, int cash) {
+ int y = 228;
+ if (!gfx_rows(y, 12)) return;
+ gfx_blend(x0, y, 320 - x0, 12, BLACK, 22);
+ if (it) {
+ char s[64];
+ int x = x0 + 4;
+ x += gfx_text(FONT_SMALL, x, y + 1, it->name, it->locked ? C_DIM : WHITE) + 6;
+ if (it->cost && !(it->max && it->level >= it->max)) {
+ spr_anim(AN_UI_COIN, 0, false, x, y + 1, false);
+ snprintf(s, sizeof s, "%d", it->cost);
+ x += 18;
+ x += gfx_text(FONT_SMALL, x, y + 1, s, it->cost <= cash ? C_GOLD : RGB(0xFF6040)) + 6;
+ }
+ gfx_text_r(FONT_SMALL, 316, y + 1, "OK buy Back close", C_DIM);
+ return;
+ }
+ gfx_text(FONT_SMALL, x0 + 4, y + 1, text, C_TEXT);
+}
+
+/* ------------------------------------------------------------------ pause, quit, notes, the end */
+static void window(int x, int y, int w, int h) {
+ gfx_panel(x, y, w, h, RGB(0x3A2614), RGB(0xC09A5A));
+ gfx_frame_rect(x + 2, y + 2, w - 4, h - 4, RGB(0x6A4A26));
+}
+
+static void button(int cx, int y, const char *s, bool sel) {
+ int w = gfx_text_w(FONT_HUD, s) + 16;
+ gfx_panel(cx - w / 2, y, w, 18, sel ? RGB(0xE0A020) : RGB(0x5A3E20), sel ? WHITE : RGB(0xC09A5A));
+ gfx_text_c(FONT_HUD, cx, y + 2, s, sel ? RGB(0x2A1A0C) : C_TEXT);
+}
+
+void draw_pause(int sel) {
+ if (!gfx_rows(50, 140)) return;
+ window(90, 50, 180, 140);
+ gfx_text_oc(FONT_BIG, 180, 56, "Paused", C_GOLD);
+ static const char *const it[4] = {"Resume", "Restart", "How to play", "Quit to map"};
+ for (int i = 0; i < 4; i++) button(180, 88 + 24 * i, it[i], sel == i);
+}
+
+void draw_quit(int sel) {
+ if (!gfx_rows(80, 80)) return;
+ window(70, 80, 220, 76);
+ gfx_text_c(FONT_TEXT, 180, 90, "Leave this battle?", C_TEXT);
+ button(140, 120, "Quit", sel == 0);
+ button(220, 120, "Stay", sel == 1);
+}
+
+void draw_note(int n) {
+ if (!gfx_rows(40, 160)) return;
+ window(60, 40, 240, 160);
+ gfx_text_oc(FONT_HUD, 180, 48, note_title(n), C_GOLD);
+ gfx_text_box(FONT_TEXT, 72, 72, 216, note_text(n), C_TEXT);
+ gfx_text_c(FONT_SMALL, 180, 184, "OK continue", C_DIM);
+}
+
+void draw_result(bool won, int stars, int mode, int sel, int t) {
+ if (t < 10 || !gfx_rows(40, 160)) return;
+ window(70, 40, 220, 160);
+ gfx_text_oc(FONT_BIG, 180, 48, won ? "Victory!" : "Defeat", won ? C_GOLD : RGB(0xFF6040));
+ if (won) {
+ if (mode == MODE_CAMPAIGN) {
+ for (int k = 0; k < 3; k++) {
+ int x = 150 + 30 * k, y = 100;
+ bool on = k < stars && t > 20 + 10 * k;
+ spr_anim(AN_UI_FLAGSTAR, on ? 1 : 0, false, x - 7, y - 8, false);
+ if (on) gfx_ellipse(x, y, 9, 9, C_GOLD, 12);
+ }
+ gfx_text_c(FONT_TEXT, 180, 120, stars == 3 ? "Flawless!" : stars == 2 ? "Well defended" : "The kingdom holds", C_TEXT);
+ } else
+ gfx_text_c(FONT_TEXT, 180, 100, mode == MODE_HEROIC ? "Heroic Challenge won: 1 star" : "Iron Challenge won: 1 star", C_TEXT);
+ } else
+ gfx_text_box(FONT_TEXT, 84, 88, 192, tip((int)(B.frame / 7)), C_TEXT);
+ button(140, 166, won ? "Continue" : "Restart", sel == 0);
+ button(225, 166, won ? "Restart" : "Map", sel == 1);
+}
diff --git a/games/kingdomrush/src/ui.h b/games/kingdomrush/src/ui.h
new file mode 100644
index 00000000..c0a58d67
--- /dev/null
+++ b/games/kingdomrush/src/ui.h
@@ -0,0 +1,31 @@
+/* Kingdom Rush: the battle's pictures and menus (ui.c). */
+#ifndef KR_UI_H
+#define KR_UI_H
+#include "kr.h"
+
+enum {
+ RA_NONE, RA_ARCHER, RA_BARRACKS, RA_MAGE, RA_ENGINEER, RA_UPGRADE, RA_SPECIAL1, RA_SPECIAL2, RA_SELL, RA_RALLY,
+ RA_ABILITY0, RA_ABILITY1, RA_ABILITY2
+};
+typedef struct {
+ uint8_t action, icon, locked, level, max;
+ int16_t cost, x, y, range; /* x, y: from the menu's middle, on screen */
+ char name[40];
+} RingItem;
+int ring_items(int s, RingItem *out);
+void draw_ring(const RingItem *it, int n, int sel, int cx, int cy, int cash);
+
+void draw_tower(const Spot *t, int x, int y);
+void draw_base(const Spot *t, int x, int y, int terrain);
+void draw_bullet(const Bullet *b, int x, int y);
+void draw_wave_flag(int x, int y, bool air, uint32_t frame, bool selected);
+void draw_sidebar(int aiming);
+void draw_enemy_info(const Enemy *e);
+void draw_spot_info(const Spot *t);
+void draw_key_line(int x0, const char *text, const RingItem *item, int cash);
+void draw_pause(int sel);
+void draw_quit(int sel);
+void draw_note(int note);
+void draw_result(bool won, int stars, int mode, int sel, int t);
+const char *tower_name(int kind, int level);
+#endif
diff --git a/games/kingdomrush/tests/rules.c b/games/kingdomrush/tests/rules.c
new file mode 100644
index 00000000..960cb6d5
--- /dev/null
+++ b/games/kingdomrush/tests/rules.c
@@ -0,0 +1,97 @@
+/* Kingdom Rush on a computer: the rules against the game's numbers, a won stage, random keys.
+ *
+ * build/rules all the tests
+ * build/rules shots DIR the screens as PPM pictures in DIR */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "game.h"
+#include "gfx.h"
+#include "kr.h"
+#include "plat.h"
+#include "settings.h"
+#include "special.h"
+
+extern const uint8_t kr_data[];
+const uint8_t *kr_bin;
+extern uint32_t host_keys, host_time;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+static uint16_t band[SCREEN_W * BAND_H];
+
+static int fails;
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ fails++; \
+ fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \
+ fprintf(stderr, __VA_ARGS__); \
+ fprintf(stderr, "\n"); \
+ } \
+ } while (0)
+
+static void step(uint32_t keys) {
+ game_step(keys);
+ host_time += 33;
+}
+static void press(uint32_t k) {
+ step(k);
+ step(0);
+}
+
+int main(int argc, char **argv) {
+ kr_bin = kr_data;
+ gfx_set_band_memory(band);
+ system("mkdir -p build/host-saves");
+ host_save_dir("build/host-saves");
+ remove("build/host-saves/kingdomrush.sav");
+ game_init();
+ if (argc > 1 && !strcmp(argv[1], "sizes")) {
+ printf("Battle %zu: Enemy %zu x %d, Soldier %zu x %d, Bullet %zu x %d, Fx %zu x %d, Spot %zu\n", sizeof B, sizeof(Enemy),
+ MAX_ENEMIES, sizeof(Soldier), MAX_SOLDIERS, sizeof(Bullet), MAX_BULLETS, sizeof(Fx), MAX_FX, sizeof(Spot));
+ return 0;
+ }
+ if (argc > 2 && !strcmp(argv[1], "fight")) {
+ /* level 1 by the rules alone: archers on every spot, waves called, a picture now and then */
+ char p[512];
+ memset(g.p.seen_note, 0xFF, sizeof g.p.seen_note);
+ play_start(0, MODE_CAMPAIGN);
+ for (int i = 0; i < 40; i++) step(0);
+ for (int s = 0; s < B.nspots && s < 3; s++) spot_build(s, s == 1 ? TW_BARRACKS : TW_ARCHER);
+ battle_call_wave();
+ for (int t = 0; t < 30 * 300 && B.state != LS_WIN && B.state != LS_OVER; t++) {
+ step(0);
+ if (B.flags_up) battle_call_wave();
+ for (int s = 0; s < B.nspots; s++)
+ if (B.spot[s].kind == TW_NONE && B.cash >= 100) spot_build(s, s % 3 == 1 ? TW_MAGE : TW_ARCHER);
+ else if (B.spot[s].kind != TW_NONE && B.spot[s].level < 3 && spot_cost(s, 0) > 0 && spot_cost(s, 0) <= B.cash - 50) spot_upgrade(s, 0);
+ if (t % 600 == 300) {
+ game_draw();
+ snprintf(p, sizeof p, "%s/fight%d.ppm", argv[2], t / 600);
+ host_shot(p);
+ }
+ }
+ printf("state %d lives %d cash %d wave %d/%d kills %d\n", B.state, B.lives, B.cash, B.current_wave, B.max_waves, B.kills);
+ for (int s = 0; s < B.nspots; s++) printf("spot %d kind %d level %d shots %d\n", s, B.spot[s].kind, B.spot[s].level, B.spot[s].shots);
+ return 0;
+ }
+ if (argc > 2 && !strcmp(argv[1], "shots")) {
+ char p[512];
+ game_draw();
+ snprintf(p, sizeof p, "%s/title.ppm", argv[2]);
+ host_shot(p);
+ press(K_OK);
+ game_draw();
+ snprintf(p, sizeof p, "%s/map.ppm", argv[2]);
+ host_shot(p);
+ press(K_OK);
+ press(K_OK);
+ for (int i = 0; i < 40; i++) step(0);
+ game_draw();
+ snprintf(p, sizeof p, "%s/battle.ppm", argv[2]);
+ host_shot(p);
+ return 0;
+ }
+ printf("%s\n", fails ? "FAILED" : "ok");
+ return fails != 0;
+}
diff --git a/games/kingdomrush/tools/codec.py b/games/kingdomrush/tools/codec.py
new file mode 100644
index 00000000..cd60b260
--- /dev/null
+++ b/games/kingdomrush/tools/codec.py
@@ -0,0 +1,249 @@
+"""Five Nights at Freddy's: the pictures' codec (src/pic.c decodes it).
+
+The game's pictures are dark, grainy renders: what keeps them small is what JPEG does, so this is JPEG's
+baseline coding without its file format. A picture is a grid of 16 x 16 squares (MCUs): YCbCr, the colours at
+half resolution (4:2:0), each 8 x 8 block cosine-transformed, quantized and Huffman-coded (JPEG's run/size
+symbols and tables, one set for the whole game). Every square stands alone, starting on a byte, with no DC
+prediction from the one before it (only between the four Y blocks of a square), so the game decodes only the
+squares on screen, and pictures share squares: a camera with Bonnie in it is the empty camera's squares but
+where he stands, the frames of a jumpscare share what doesn't move, and squares that come out the same anywhere
+are stored once."""
+import heapq
+
+import numpy as np
+
+ZIGZAG = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
+ 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63]
+STD_LUMA = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56,
+ 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92,
+ 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99]
+STD_CHROMA = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99,
+ 47, 66, 99, 99, 99, 99, 99, 99] + [99] * 32
+# libjpeg's "ifast" IDCT folds these scales into the quantization table (src/pic.c)
+AANSCALES = [16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299,
+ 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137,
+ 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873,
+ 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520,
+ 3552, 2446, 1247]
+LUT_BITS = 9
+
+
+def qtable(base, quality):
+ s = 5000 / quality if quality < 50 else 200 - 2 * quality
+ return np.array([min(255, max(1, int((b * s + 50) // 100))) for b in base], dtype=np.float64)
+
+
+def dct_matrix():
+ c = np.zeros((8, 8))
+ for k in range(8):
+ for n in range(8):
+ c[k, n] = (np.sqrt(1 / 8) if k == 0 else np.sqrt(2 / 8)) * np.cos((2 * n + 1) * k * np.pi / 16)
+ return c
+
+
+DCT = dct_matrix()
+
+
+def ycbcr(rgb):
+ """an H x W x 3 picture (0-255) -> Y (H x W), Cb and Cr (H/2 x W/2), all level-shifted (-128)"""
+ r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
+ y = 0.299 * r + 0.587 * g + 0.114 * b - 128
+ cb = -0.168736 * r - 0.331264 * g + 0.5 * b
+ cr = 0.5 * r - 0.418688 * g - 0.081312 * b
+ h, w = y.shape
+ cb = cb.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ cr = cr.reshape(h // 2, 2, w // 2, 2).mean(axis=(1, 3))
+ return y, cb, cr
+
+
+def blocks_of(plane):
+ """an H x W plane -> (H/8, W/8, 8, 8) of its DCT coefficients"""
+ h, w = plane.shape
+ b = plane.reshape(h // 8, 8, w // 8, 8).transpose(0, 2, 1, 3)
+ return np.einsum("ij,abjk,lk->abil", DCT, b, DCT)
+
+
+def quantize(coef, q, deadzone):
+ """coefficients (..., 8, 8) / a natural-order table, rounded toward 0 a little (deadzone) on the AC ones"""
+ x = coef / q.reshape(8, 8)
+ r = np.sign(x) * np.floor(np.abs(x) + 0.5 - deadzone)
+ r[..., 0, 0] = np.round(x[..., 0, 0])
+ return np.maximum(r, 0 * r - 2047).clip(-2047, 2047).astype(np.int32)
+
+
+def size_of(v):
+ v = abs(int(v))
+ n = 0
+ while v:
+ n += 1
+ v >>= 1
+ return n
+
+
+def bits_of(v, n):
+ return v if v >= 0 else v + (1 << n) - 1
+
+
+def block_symbols(zz, pred):
+ """one block's coefficients in zigzag order -> [(table: 0 DC 1 AC, symbol, extra bits value, extra bits count)]"""
+ out = []
+ d = int(zz[0]) - pred
+ s = size_of(d)
+ out.append((0, s, bits_of(d, s), s))
+ run = 0
+ last = 63
+ while last > 0 and zz[last] == 0:
+ last -= 1
+ for k in range(1, last + 1):
+ v = int(zz[k])
+ if v == 0:
+ run += 1
+ continue
+ while run > 15:
+ out.append((1, 0xF0, 0, 0))
+ run -= 16
+ s = size_of(v)
+ out.append((1, run << 4 | s, bits_of(v, s), s))
+ run = 0
+ if last < 63:
+ out.append((1, 0x00, 0, 0))
+ return out
+
+
+def mcu_symbols(yq, cbq, crq):
+ """the quantized blocks of one square: 4 Y (8 x 8 each, natural order), Cb, Cr -> [(component class, ...)]"""
+ syms = []
+ pred = 0
+ for b in yq:
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(0,) + s for s in block_symbols(zz, pred)]
+ pred = int(zz[0])
+ for b in (cbq, crq):
+ zz = b.reshape(64)[ZIGZAG]
+ syms += [(1,) + s for s in block_symbols(zz, 0)]
+ return syms
+
+
+def huffman_lengths(freq):
+ """symbol -> frequency, to code lengths of at most 16 bits (JPEG's Annex K.2 and K.3)"""
+ # a symbol of its own takes the all-ones code, which JPEG never uses (the padding is ones)
+ f = {s: float(c) for s, c in freq.items() if c > 0}
+ f[256] = 0.5
+ syms = list(f)
+ heap = [(f[s], i, [s]) for i, s in enumerate(syms)]
+ heapq.heapify(heap)
+ length = {s: 0 for s in syms}
+ n = len(syms)
+ while len(heap) > 1:
+ f1, _, a = heapq.heappop(heap)
+ f2, _, b = heapq.heappop(heap)
+ for s in a + b:
+ length[s] += 1
+ n += 1
+ heapq.heappush(heap, (f1 + f2, n, a + b))
+ bits = [0] * 64
+ for s in syms:
+ bits[length[s]] += 1
+ i = 63
+ while i > 16:
+ while bits[i] > 0:
+ j = i - 2
+ while bits[j] == 0:
+ j -= 1
+ bits[i] -= 2
+ bits[i - 1] += 1
+ bits[j + 1] += 2
+ bits[j] -= 1
+ i -= 1
+ while bits[i] == 0:
+ i -= 1
+ bits[i] -= 1 # (the reserved code goes)
+ order = sorted(syms, key=lambda s: (length[s], s == 256, s))[:-1]
+ out = {}
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ out[order[k]] = ln
+ k += 1
+ return out
+
+
+def canonical(lengths):
+ """symbol -> length to (symbol -> (code, length), BITS[1..16], HUFFVAL)"""
+ order = sorted(lengths, key=lambda s: (lengths[s], s))
+ bits = [0] * 17
+ for s in order:
+ bits[lengths[s]] += 1
+ codes = {}
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ for _ in range(bits[ln]):
+ codes[order[k]] = (code, ln)
+ code += 1
+ k += 1
+ code <<= 1
+ return codes, bits[1:], order
+
+
+def decode_tables(bits, vals):
+ """BITS and HUFFVAL -> the decoder's tables: a LUT_BITS lookup (length << 8 | symbol, 0 when longer), then
+ for the slow way JPEG's maxcode (17 int32, -1 when none) and valoffset (17 int32), then HUFFVAL (256 bytes)"""
+ lut = [0] * (1 << LUT_BITS)
+ maxcode = [-1] * 18
+ valoff = [0] * 18
+ code = 0
+ k = 0
+ for ln in range(1, 17):
+ n = bits[ln - 1]
+ if n:
+ valoff[ln] = k - code
+ for _ in range(n):
+ if ln <= LUT_BITS:
+ base = code << (LUT_BITS - ln)
+ for j in range(1 << (LUT_BITS - ln)):
+ lut[base + j] = ln << 8 | vals[k]
+ code += 1
+ k += 1
+ maxcode[ln] = code - 1
+ code <<= 1
+ maxcode[17] = 0x7FFFFFFF
+ out = b"".join(v.to_bytes(2, "little") for v in lut)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in maxcode)
+ out += b"".join(v.to_bytes(4, "little", signed=True) for v in valoff)
+ out += bytes(vals) + bytes(256 - len(vals))
+ return out
+
+
+class BitWriter:
+ def __init__(self):
+ self.out = bytearray()
+ self.acc = 0
+ self.n = 0
+
+ def put(self, v, n):
+ if n == 0:
+ return
+ self.acc = self.acc << n | (v & ((1 << n) - 1))
+ self.n += n
+ while self.n >= 8:
+ self.n -= 8
+ self.out.append(self.acc >> self.n & 0xFF)
+ self.acc &= (1 << self.n) - 1
+
+ def flush(self):
+ """pads with ones (like JPEG) to a byte"""
+ if self.n:
+ self.put((1 << (8 - self.n)) - 1, 8 - self.n)
+ return bytes(self.out)
+
+
+def encode_mcu(syms, tables):
+ """a square's symbols -> its bytes; tables[component class][0 DC, 1 AC][symbol] = (code, length)"""
+ w = BitWriter()
+ for comp, tab, sym, val, n in syms:
+ code, ln = tables[comp][tab][sym]
+ w.put(code, ln)
+ w.put(val, n)
+ return w.flush()
diff --git a/games/kingdomrush/tools/pack.py b/games/kingdomrush/tools/pack.py
new file mode 100644
index 00000000..bf424562
--- /dev/null
+++ b/games/kingdomrush/tools/pack.py
@@ -0,0 +1,765 @@
+#!/usr/bin/env python3
+"""Kingdom Rush: its pictures, levels and fonts -> src/data.bin, src/data.h and src/stats.c.
+
+ python3 -I tools/pack.py [KR] KR: the folder made from the game's Flash file (default
+ ~/Documents/Assets/gamesrc/kingdomrush), holding:
+ swf/full/*GLevelN/1.png each level's terrain, 700 x 600 (JPEXS, sprite export)
+ render/r/<set>/N.png the game's sprites, frame by frame, at 0.4 scale, the origin in the middle of
+ the picture (tools/java/Render.java in that folder)
+ render/d/d_<id>/1.png the levels' decorations at full size, likewise
+ swf/sprites.json the sprites' frame labels (tools/swfinfo.py)
+ spec/data/*.json levels.json, settings.json, decor.json (tools/extract.py, tools/decor.py)
+
+Everything is the game's own, at 0.4 of its size: the 700 x 600 battlefield is 280 x 240.
+
+data.bin: "KRSH", the number of sections, their offsets, then the sections (SEC_* in data.h):
+- HUFF, QUANT, PICS, TABLE, BANK: the terrains and screens, coded as JPEG codes them (tools/codec.py, src/pic.c)
+- BGPAL: for each picture, 256 colours (RGB565) the game reduces it to when it loads it (8 bits a pixel in RAM)
+- SPAL: the sprites' 256 colours (RGB565)
+- FRAMES: u32 count, u32 offsets, then each frame: w, h (u8), ox, oy (s16: the origin from the top left), then
+ its rows: a run count, and for each run its offset from the last (u8), its length (u8, bit 7: half see-through)
+ and its colours
+- ANIMS: 4 bytes an animation (AN_*): first frame (u16), frames (u8), ticks a frame (u8)
+- FONTS: as Five Nights at Freddy's 4's (FONT_*)
+- LEVELS: for each level, u32 offsets of: its build spots, paths, flags, then each mode's waves (see level.c)"""
+import json
+import os
+import struct
+import sys
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+import codec as C # noqa: E402
+
+SRC = os.path.join(HERE, "..", "src")
+KR = os.path.expanduser(sys.argv[1] if len(sys.argv) > 1 else "~/Documents/Assets/gamesrc/kingdomrush")
+SECTIONS = ["HUFF", "QUANT", "PICS", "TABLE", "BANK", "BGPAL", "SPAL", "FRAMES", "ANIMS", "FONTS", "LEVELS"]
+QUALITY = {"terrain": 86}
+SCALE = 0.4
+FONT_DIRS = [os.environ.get("FONTS", ""), os.path.expanduser("~/Documents/Assets/gamesrc/fonts"),
+ os.path.expanduser("~/Documents/Assets/gamesrc/fonts/dejavu"), "/Library/Fonts"]
+NLEVELS = 12
+MAP_Y0 = 17 # the map's rows shown: from 17 (of 274)
+UPG_X = 52 # where the upgrades' panel (215 x 240) sits
+TERRAIN_IDS = [1541, 1540, 1537, 1505, 1498, 1495, 1492, 1489, 1486, 1483, 1480, 1477]
+
+DEFINES = []
+
+
+def define(name, value):
+ DEFINES.append((name, value))
+
+
+def rgb565(r, g, b):
+ return (int(r) >> 3) << 11 | (int(g) >> 2) << 5 | int(b) >> 3
+
+
+# ------------------------------------------------------------------ pictures (JPEG-coded)
+class Pic:
+ def __init__(self, name, a, quality):
+ self.name, self.q = name, quality
+ self.h, self.w = a.shape[:2]
+ H, W = -(-self.h // 16) * 16, -(-self.w // 16) * 16
+ self.a = np.pad(a, ((0, H - self.h), (0, W - self.w), (0, 0)), mode="edge")
+ self.mw, self.mh = W // 16, H // 16
+
+
+PICS = []
+
+
+def pic(name, im, quality="terrain"):
+ a = np.asarray(im.convert("RGB")).astype(np.float64)
+ define(f"PIC_{name}", len(PICS))
+ PICS.append(Pic(name, a, quality))
+
+
+def encode_pics():
+ qt = {k: (C.qtable(C.STD_LUMA, v), C.qtable(C.STD_CHROMA, v)) for k, v in QUALITY.items()}
+ qnames = list(QUALITY)
+ for p in PICS:
+ y, cb, cr = C.ycbcr(p.a)
+ ql, qc = qt[p.q]
+ yq = C.quantize(C.blocks_of(y), ql, 0.18)
+ cbq = C.quantize(C.blocks_of(cb), qc, 0.22)
+ crq = C.quantize(C.blocks_of(cr), qc, 0.22)
+ p.sq = [tuple(C.mcu_symbols([yq[2 * my + i, 2 * mx + j] for i in (0, 1) for j in (0, 1)], cbq[my, mx], crq[my, mx]))
+ for my in range(p.mh) for mx in range(p.mw)]
+ freq = [[{}, {}], [{}, {}]]
+ for p in PICS:
+ for s in p.sq:
+ for comp, tab, sym, _, _ in s:
+ f = freq[comp][tab]
+ f[sym] = f.get(sym, 0) + 1
+ tables, huff = [[None, None], [None, None]], b""
+ for comp in (0, 1):
+ for tab in (0, 1):
+ codes, bits, vals = C.canonical(C.huffman_lengths(freq[comp][tab]))
+ tables[comp][tab] = codes
+ huff += C.decode_tables(bits, vals)
+ bank, where = bytearray(), {}
+ for p in PICS:
+ p.off = []
+ for s in p.sq:
+ data = C.encode_mcu(s, tables)
+ if data not in where:
+ where[data] = len(bank)
+ bank += data
+ p.off.append(where[data])
+ bank += bytes(8)
+ quant = b""
+ for k in qnames:
+ for t in qt[k]:
+ quant += b"".join(struct.pack("<H", (int(t[i]) * C.AANSCALES[i] + 2048) >> 12) for i in range(64))
+ pics, table = b"", bytearray()
+ for p in PICS:
+ pics += struct.pack("<BBBBHHI", p.mw, p.mh, qnames.index(p.q), 0, 0xFFFF, 0, len(table))
+ for o in p.off:
+ table += o.to_bytes(3, "little")
+ # the colours each picture is reduced to: its own 256, from the picture as the calculator decodes it
+ bgpal = b""
+ for p in PICS:
+ im = Image.fromarray(np.clip(p.a[:p.h, :p.w], 0, 255).astype(np.uint8))
+ q = im.quantize(256, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
+ pal = (q.getpalette() + [0] * 768)[:768]
+ bgpal += b"".join(struct.pack("<H", rgb565(*pal[3 * i:3 * i + 3])) for i in range(256))
+ print(f"pictures: {len(PICS)}, squares {len(bank)} bytes")
+ return huff, quant, pics, bytes(table), bytes(bank), bgpal
+
+
+def terrain(n, decor):
+ im = Image.open(f"{KR}/swf/full/DefineSprite_{TERRAIN_IDS[n - 1]}_GLevel{n}/1.png").convert("RGBA")
+ base = Image.new("RGBA", (700, 600), (0, 0, 0, 255))
+ base.alpha_composite(im.crop((0, 0, 700, 600)) if im.width >= 700 else im)
+ for d in decor.get(str(n), []):
+ p = f"{KR}/render/d/d_{d['id']}/1.png"
+ if not os.path.exists(p):
+ continue
+ s = Image.open(p).convert("RGBA")
+ if d["flip"]:
+ s = s.transpose(Image.FLIP_LEFT_RIGHT)
+ x, y = round(d["x"] - s.width / 2), round(d["y"] - s.height / 2)
+ layer = Image.new("RGBA", (700, 600))
+ layer.paste(s, (x, y))
+ base.alpha_composite(layer)
+ return base.convert("RGB").resize((280, 240), Image.LANCZOS)
+
+
+# ------------------------------------------------------------------ sprites
+SPR = json.load(open(f"{KR}/swf/sprites.json"))
+CLASS_ID = {v: k for k, v in SPR["classes"].items()}
+
+
+def segments(set_id):
+ """a sprite's labelled parts: label -> (first, last) frames (from 1), loops stop before their End frame"""
+ frames = SPR["sprites"][str(set_id)]["frames"]
+ marks = [(i + 1, l) for i, f in enumerate(frames) for l in f["labels"]]
+ out = {}
+ starts = [(f, l) for f, l in marks if not l.endswith("End")]
+ if starts and starts[0][0] > 1: # frames before the first label
+ out["start"] = (1, starts[0][0] - 1)
+ for k, (f, l) in enumerate(starts):
+ end = next((g for g, m in marks if m in (l + "End", l.replace("thorn", "thor") + "End") and g >= f), None)
+ nxt = starts[k + 1][0] - 1 if k + 1 < len(starts) else len(frames)
+ last = end if end is not None else nxt
+ if l.startswith("walking") or l.startswith("running") or l in ("travel",):
+ last = (end - 1) if end is not None and end > f else nxt
+ out[l] = (f, max(f, min(last, len(frames))))
+ if not out:
+ out["all"] = (1, len(frames))
+ return out
+
+
+FRAMES, FRAME_KEY, ANIMS = [], {}, []
+ALPHA_LO, ALPHA_HI = 48, 176
+
+
+def load_frame(path):
+ im = Image.open(path).convert("RGBA")
+ a = np.asarray(im).astype(np.int32)
+ return a, im.width // 2, im.height // 2
+
+
+SPRITE_PIXELS = []
+
+
+def add_frame(a, ox, oy):
+ """a frame (RGBA, origin at ox, oy) -> its index in FRAMES (shared when equal)"""
+ al = a[..., 3]
+ ys, xs = np.nonzero(al >= ALPHA_LO)
+ if len(ys) == 0:
+ a, x0, y0 = np.zeros((1, 1, 4), np.int32), ox, oy
+ else:
+ x0, x1, y0, y1 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1
+ a = a[y0:y1, x0:x1]
+ key = (a.tobytes(), a.shape, int(ox - x0), int(oy - y0))
+ if key in FRAME_KEY:
+ return FRAME_KEY[key]
+ FRAME_KEY[key] = len(FRAMES)
+ FRAMES.append((a, int(ox - x0), int(oy - y0)))
+ SPRITE_PIXELS.append(a[a[..., 3] >= ALPHA_LO][:, :3])
+ return len(FRAMES) - 1
+
+
+def anim(name, frames, ticks):
+ define(f"AN_{name}", len(ANIMS))
+ ANIMS.append((frames, ticks))
+
+
+def sprite_set(prefix, folder, set_id, keep=None, step=2, rename=None):
+ """every labelled part of a rendered sprite as an animation AN_<prefix>_<LABEL>"""
+ segs = segments(set_id)
+ for label, (f0, f1) in segs.items():
+ if keep is not None and label not in keep:
+ continue
+ n = f1 - f0 + 1
+ st = step if n >= 6 else 1
+ idx = [add_frame(*load_frame(f"{KR}/render/r/{folder}/{f}.png")) for f in range(f0, f1 + 1, st)]
+ nm = (rename or {}).get(label, label)
+ anim(f"{prefix}_{nm.upper()}" if nm else prefix, idx, st)
+
+
+def single(prefix, folder, frame=1):
+ anim(prefix, [add_frame(*load_frame(f"{KR}/render/r/{folder}/{frame}.png"))], 1)
+
+
+ENEMIES = ['Goblin', 'FatOrc', 'WolfSmall', 'Shaman', 'Ogre', 'Bandit', 'Brigand', 'Marauder', 'Wolf', 'Spider',
+ 'SpiderSmall', 'SpiderTiny', 'ShadowArcher', 'DarkKnight', 'Gargoyle', 'Juggernaut', 'GolemHead', 'WhiteWolf',
+ 'Troll', 'TrollChieftain', 'TrollAxeThrower', 'Yeti', 'YetiBoss', 'Slayer', 'Rocketeer', 'Skeleton',
+ 'SkeletonBig', 'DemonWolf', 'Demon', 'DemonMage', 'Necromancer', 'DemonImp', 'LavaElemental', 'Veznan',
+ 'SheepGround', 'SheepFlying']
+ENEMY_DROP = {"thorn", "thornFree", "teleport", "deathloop"}
+
+
+def sprites():
+ for e in ENEMIES:
+ cid = CLASS_ID["Enemy" + e]
+ keep = [l for l in segments(cid) if l not in ENEMY_DROP]
+ sprite_set("E_" + e.upper(), "e_" + e, cid, keep, 3 if e in ("YetiBoss", "Veznan", "Juggernaut") else 2)
+ # the generic arcane teleport and the thorns' hold: the goblin's, for every enemy
+ sprite_set("FX_TELEPORT", "e_Goblin", CLASS_ID["EnemyGoblin"], ["teleport"], 1, {"teleport": ""})
+ for c in ['ExplodeNormal', 'ExplodeBig', 'ExplodeAir', 'DesintegrateNormal', 'DesintegrateBig', 'DesintegrateAir',
+ 'PolymorphNormal', 'PolymorphBig', 'PolymorphAir']:
+ sprite_set("FX_" + c.upper(), "fx_" + c, CLASS_ID["Enemy" + c], None, 1, {"explotion": "", "desintegrate": "",
+ "polymorph": ""})
+ towers = {'archer1': 1038, 'archer2': 1036, 'archer3': 1012, 'ranger': 1062, 'musketeer': 1196,
+ 'mage1': 493, 'mage2': 481, 'mage3': 468, 'arcane': 702, 'sorcerer': 602,
+ 'eng1': 906, 'eng2': 863, 'eng3': 817, 'bfg': 988, 'tesla': 769,
+ 'bar1': 411, 'bar2': 403, 'bar3': 394, 'paladin': 340, 'barbarian': 349}
+ for n, cid in towers.items():
+ sprite_set("T_" + n.upper(), "t_" + n, cid, None, 2)
+ for n, cid in {'holder': 382, 'base_archer': 1264, 'base_mage': 1240, 'base_bar': 1236}.items():
+ sprite_set("T_" + n.upper(), "t_" + n, cid, None, 1)
+ for n in ('build_archer', 'build_mage', 'build_bar', 'flag', 'rally'):
+ single("T_" + n.upper(), "t_" + n)
+ sprite_set("T_CLOUD", "t_cloud", 385, None, 1, {"all": "", "cloudEnd": "end"})
+ sprite_set("T_SELL", "t_sell", 377, None, 1, {"all": ""})
+ shooters = {'archer1': 252, 'archer2': 1035, 'archer3': 1011, 'ranger': 1061, 'musketeer': 1195,
+ 'mage': 457, 'arcane': 617, 'sorcerer': 585}
+ for n, cid in shooters.items():
+ sprite_set("S_" + n.upper(), "s_" + n, cid, None, 1)
+ for c in ['SoldierStandar', 'SoldierStandarLevel2', 'SoldierStandarLevel3', 'SoldierPaladin', 'SoldierBarbarian',
+ 'SoldierElemental', 'SoldierFarmerJohn', 'SoldierFarmerPaul', 'SoldierFarmerRingo',
+ 'SoldierReinforcementLevel2A', 'SoldierReinforcementLevel2B', 'SoldierReinforcementLevel3A',
+ 'SoldierReinforcementLevel3B', 'SoldierReinforcementLevel4A', 'SoldierReinforcementLevel4B']:
+ sprite_set("SO_" + c[7:].upper(), "so_" + c[7:], CLASS_ID[c], None, 1)
+ for c in ['Arrow', 'ArrowEnemy', 'BoltNecromancer', 'BoltSorcerer', 'BombBfg', 'BombBlack', 'BombCommon',
+ 'BombDynamite', 'BombFragment', 'BombShrapnel', 'Fireball', 'Missile', 'MissileEnemy',
+ 'RayArcaneCommon', 'RayArcaneDesintegrate', 'RayPolymorph', 'RayTesla', 'Axe', 'AxeEnemy',
+ 'IceBlock', 'VeznanBlock', 'SpiderEgg', 'TeleportPortal', 'DemonFire', 'JuggernautEgg',
+ 'BloodDecal', 'BombDecal', 'ArrowDecal', 'Blood', 'BloodGreen', 'DefenseIndicator', 'WaveFlagReward']:
+ sprite_set("B_" + c.upper(), "b_" + c, CLASS_ID[c], None, 1, {"all": ""})
+ sprite_set("B_BOLT", "b_Bolt", 4729, None, 1)
+ single("UI_WAVEFLAG", "ui_WaveFlag")
+ sprite_set("UI_WAVEICO", "ui_WaveFlag_ico_175", CLASS_ID["_KingdomRush_RC_1_fla.WaveFlag_ico_175"], None, 1)
+ ui_sprites()
+
+
+def ui_frames(folder, frames):
+ return [add_frame(*load_frame(f"{KR}/render/u/{folder}/{f}.png")) for f in frames]
+
+
+def crop_icon(name, path, box):
+ """a part of a picture, as a one-frame animation with its origin at its top left"""
+ a = np.asarray(Image.open(path).convert("RGBA").crop(box)).astype(np.int32)
+ anim(name, [add_frame(a, 0, 0)], 1)
+
+
+def ui_sprites():
+ # the tower menu's 40 icons (TowerMenuItem's frames: empty, sell, ..., see ICON_* in ui.c)
+ anim("UI_ICONS", ui_frames("icons", range(1, 41)), 1)
+ for nm, folder in (("UI_PFIRE", "pfire"), ("UI_PREINF", "preinf")):
+ anim(nm + "_IDLE", ui_frames(folder, [1]), 1)
+ anim(nm + "_SEL", ui_frames(folder, [20]), 1)
+ anim(nm + "_OPEN", ui_frames(folder, range(21, 37)), 2)
+ anim(nm + "_READY", ui_frames(folder, range(2, 19)), 1)
+ hud = f"{KR}/render/u/hud8/1.png"
+ crop_icon("UI_HEART", hud, (177, 165, 193, 181))
+ crop_icon("UI_COIN", hud, (217, 167, 236, 181))
+ crop_icon("UI_SKULL", hud, (185, 185, 200, 197))
+ # the map's flags: a stage to play, one played (its stars), the heroic shield
+ anim("UI_FLAGNEW", ui_frames("flagnew", [1]), 1)
+ anim("UI_FLAGDONE", ui_frames("flagdone", [1]), 1)
+ anim("UI_FLAGSEL", ui_frames("flagdone", [3]), 1)
+ anim("UI_FLAGSTAR", ui_frames("flagstar", [1, 2]), 1)
+ anim("UI_FLAGHEROIC", ui_frames("flagheroic", [60]), 1)
+ # the upgrades' icons (in the game's order: barracks, archers, mages, artillery, rain, reinforcements) and their
+ # frames: available, locked, bought
+ anim("UI_UPICONS", ui_frames("upicons", range(1, 31)), 1)
+ anim("UI_UPITEM", ui_frames("upitem", [1, 4, 5]), 1)
+ for n in ("eng", "bfg", "tesla", "ranger", "musketeer"):
+ sprite_set("T_BASE_" + n.upper(), "t_base_" + n, {"eng": 1248, "bfg": 1252, "tesla": 1244, "ranger": 1256,
+ "musketeer": 1260}[n], None, 1)
+
+
+def pack_sprites():
+ px = np.concatenate(SPRITE_PIXELS).astype(np.uint8)
+ strip = Image.fromarray(px.reshape(1, -1, 3))
+ q = strip.quantize(255, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)
+ pal = np.array((q.getpalette() + [0] * 768)[:765]).reshape(255, 3)
+ spal = struct.pack("<H", 0) + b"".join(struct.pack("<H", rgb565(*c)) for c in pal)
+ # nearest of the 255 colours (1 to 255) for every RGB555 colour
+ cells = np.stack(np.meshgrid(np.arange(32), np.arange(32), np.arange(32), indexing="ij"), -1).reshape(-1, 3) * 8 + 4
+ inv = np.empty(len(cells), np.uint8)
+ for i in range(0, len(cells), 4096):
+ d = ((cells[i:i + 4096, None, :] - pal[None]) ** 2).sum(-1)
+ inv[i:i + 4096] = d.argmin(1) + 1
+ blobs = []
+ for a, ox, oy in FRAMES:
+ h, w = a.shape[:2]
+ rgb = a[..., :3] >> 3
+ idx = inv[(rgb[..., 0] * 32 + rgb[..., 1]) * 32 + rgb[..., 2]]
+ al = a[..., 3]
+ b = bytearray(struct.pack("<BBhh", w, h, ox, oy))
+ for r in range(h):
+ runs, c = [], 0
+ while c < w:
+ if al[r, c] < ALPHA_LO:
+ c += 1
+ continue
+ half = al[r, c] < ALPHA_HI
+ s = c
+ while c < w and al[r, c] >= ALPHA_LO and (al[r, c] < ALPHA_HI) == half and c - s < 127:
+ c += 1
+ runs.append((s, half, idx[r, s:c]))
+ b.append(len(runs))
+ last = 0
+ for s, half, cols in runs:
+ while s - last > 255: # (never at this size)
+ raise SystemExit("pack: a run too far")
+ b += bytes([s - last, len(cols) | (0x80 if half else 0)]) + bytes(cols)
+ last = s + len(cols)
+ blobs.append(bytes(b))
+ # the frame table: an entry for each animation's frame in turn (equal frames share their bytes)
+ slots, anims = [], b""
+ for fr, t in ANIMS:
+ anims += struct.pack("<HBB", len(slots), len(fr), t)
+ slots += fr
+ base = 4 + 4 * len(slots)
+ starts, p = [], base
+ for bl in blobs:
+ starts.append(p)
+ p += len(bl)
+ frames = struct.pack("<I", len(slots)) + b"".join(struct.pack("<I", starts[i]) for i in slots) + b"".join(blobs)
+ return spal, frames, anims
+
+
+# ------------------------------------------------------------------ fonts (as Five Nights at Freddy's 4's)
+def find_font(name):
+ for d in FONT_DIRS:
+ p = os.path.join(d, name) if d else ""
+ if p and os.path.exists(p):
+ return p
+ raise SystemExit(f"pack: {name} not found (FONTS=<its folder>)")
+
+
+def nibbles(alpha):
+ h, w = alpha.shape
+ out = bytearray()
+ for r in range(h):
+ row = list(alpha[r]) + [0]
+ for c in range(0, w, 2):
+ out.append(int(row[c]) | int(row[c + 1]) << 4)
+ return bytes(out)
+
+
+def ttf_font(f):
+ asc, desc = f.getmetrics()
+ line = asc + desc
+ glyphs = []
+ for c in range(32, 127):
+ ch = chr(c)
+ adv = int(round(f.getlength(ch)))
+ box = f.getbbox(ch)
+ if box[2] <= box[0] or ch == " ":
+ glyphs.append((adv, 0, 0, 0, 0, b""))
+ continue
+ im = Image.new("L", (box[2] - box[0], box[3] - box[1]))
+ ImageDraw.Draw(im).text((-box[0], -box[1]), ch, font=f, fill=255)
+ a = np.clip(np.round(np.asarray(im, dtype=np.float64) / 255 * 15), 0, 15).astype(np.uint8)
+ glyphs.append((adv, im.width, im.height, box[0], box[1], nibbles(a)))
+ return line, asc, glyphs
+
+
+def pack_fonts(fonts):
+ blobs = []
+ for line, asc, glyphs in fonts:
+ b = struct.pack("<BBBB", line, asc, 32, 95)
+ rows, offs = b"", []
+ for adv, w, h, x, y, r in glyphs:
+ offs.append(len(rows))
+ rows += r
+ g0 = len(b) + 12 * 95
+ for (adv, w, h, x, y, r), o in zip(glyphs, offs):
+ b += struct.pack("<BBBbbBHI", adv, w, h, x, y, 0, 0, g0 + o)
+ blobs.append(b + rows)
+ out = struct.pack("<I", len(fonts))
+ p = 4 + 4 * len(fonts)
+ for b in blobs:
+ out += struct.pack("<I", p)
+ p += len(b)
+ return out + b"".join(blobs)
+
+
+# ------------------------------------------------------------------ levels
+LEVELS = json.load(open(f"{KR}/spec/data/levels.json"))[:NLEVELS]
+ENEMY_IDS = {"Enemy" + e: i for i, e in enumerate(ENEMIES)}
+NOTES = ["", "NotificationPowerReinforcement", "NotificationPowerFireball"]
+MODES = ("campaign", "heroic", "iron")
+TOWER_KIND = {"TowerHolder": 0, "TowerArcher": 1, "TowerSoldier": 2, "TowerMage": 3, "TowerEngineer": 4}
+PREMADE = {"": 0, "level_1": 1, "level_2": 2, "level_3": 3}
+
+
+def note(s):
+ if s not in NOTES:
+ NOTES.append(s)
+ return NOTES.index(s)
+
+
+def fx(v):
+ return int(round(v * 16))
+
+
+def pack_level(lv):
+ out = {}
+ # paths: the number of paths, then for each its lanes (u8), and for each lane its nodes (u16), each x and y
+ # (s16, 1/16 px)
+ b = bytearray(struct.pack("<B", len(lv["paths"])))
+ for path in lv["paths"]:
+ b.append(len(path))
+ for lane in path:
+ b += struct.pack("<H", len(lane))
+ for x, y in lane:
+ b += struct.pack("<hh", fx(x), fx(y))
+ out["paths"] = bytes(b)
+ b = bytearray(struct.pack("<B", len(lv["flags"])))
+ for (x0, y0), (x1, y1) in lv["flags"]:
+ b += struct.pack("<hhhh", round(x0), round(y0), round(x1), round(y1))
+ b += struct.pack("<B", len(lv["defend"]))
+ for x, y in lv["defend"]:
+ b += struct.pack("<hh", round(x), round(y))
+ for k in ("unlockMaxArchersLevel", "unlockMaxBarracksLevel", "unlockMaxEngineersLevel", "unlockMaxMagesLevel"):
+ b.append(lv.get(k, 0))
+ out["flags"] = bytes(b)
+ for mode in MODES:
+ hs = lv["holders"][mode]
+ b = bytearray(struct.pack("<B", len(hs)))
+ for h in hs:
+ if h["cls"] == "ref": # the level's special building (elf hall, frozen sasquatch, temple): later
+ b += struct.pack("<BBhhhh", 0xFF, 0, 0, 0, 0, 0)
+ continue
+ kind = TOWER_KIND.get(h["cls"], 0xFE)
+ pre = PREMADE.get(h["args"][0] if h["args"] else "", 0)
+ rx, ry = h["rally"] if h["rally"] else (h["x"], h["y"])
+ b += struct.pack("<BBhhhh", kind, pre, round(h["x"]), round(h["y"]), round(rx), round(ry))
+ d = lv[mode]
+ b += struct.pack("<HHBBBBBBB", d["initLives"], d["cash"], d.get("unlockMaxArchers", 0),
+ d.get("unlockMaxBarracks", 0), d.get("unlockMaxEngineers", 0), d.get("unlockMaxMages", 0),
+ d.get("maxUpgradeLevel", 0), int(bool(d.get("power1", True))), int(bool(d.get("power2", True))))
+ b += struct.pack("<B", len(d["waves"]))
+ for w in d["waves"]:
+ b += struct.pack("<HBBBBB", w["interval"], w["path"], note(w["notification"]), note(w["notification2"]),
+ int(w["flying_flag"]), len(w["spawns"]))
+ for s in w["spawns"]:
+ b += struct.pack("<BBBHHHBB", ENEMY_IDS[s["creep"]], ENEMY_IDS[s["aux"]] if s["aux"] else 0xFF,
+ s["max_same"], s["count"], s["interval"], s["next"], int(s["fixed_sub_path"]),
+ s["sub_path"])
+ out[mode] = bytes(b)
+ return out
+
+
+def pack_levels():
+ blobs = []
+ for lv in LEVELS:
+ parts = pack_level(lv)
+ order = ["paths", "flags"] + list(MODES)
+ hdr = len(order) * 4
+ b, offs = b"", []
+ for k in order:
+ offs.append(hdr + len(b))
+ b += parts[k]
+ blobs.append(b"".join(struct.pack("<I", o) for o in offs) + b)
+ out = struct.pack("<I", len(blobs))
+ p = 4 + 4 * len(blobs)
+ for bl in blobs:
+ out += struct.pack("<I", p)
+ p += len(bl)
+ return out + b"".join(blobs)
+
+
+# ------------------------------------------------------------------ the numbers: src/stats.c
+# what each enemy's class sets on its own (Enemy*.as init): attack charge, life bar (y, size), hit box, dead time
+CLASS = {
+ 'Goblin': (14, -20, 0, 18, 24), 'FatOrc': (10, -23, 0, 21, 24), 'WolfSmall': (8, -20, 0, 23, 26, 15),
+ 'Shaman': (17, -25, 0, 26, 41), 'Ogre': (27, -39, 1, 30, 51), 'Bandit': (8, -23, 0, 11, 20),
+ 'Brigand': (13, -25, 0, 12, 24), 'Marauder': (13, -39, 1, 22, 35), 'Wolf': (8, -24, 0, 14, 18, 15),
+ 'Spider': (17, -25, 0, 20, 25), 'SpiderSmall': (17, -18, 0, 12, 17), 'SpiderTiny': (17, -13, 0, 10, 18),
+ 'ShadowArcher': (7, -25, 0, 22, 22), 'DarkKnight': (10, -28, 0, 22, 31), 'Gargoyle': (8, -60, 0, 23, 73),
+ 'Juggernaut': (28, -90, 2, 58, 92, 200), 'GolemHead': (17, -17, 0, 14, 20), 'WhiteWolf': (8, -24, 0, 23, 26, 15),
+ 'Troll': (12, -26, 0, 15, 26), 'TrollChieftain': (26, -39, 1, 25, 36), 'TrollAxeThrower': (15, -35, 0, 24, 31),
+ 'Yeti': (30, -45, 1, 33, 51), 'YetiBoss': (40, -110, 2, 72, 115, 90), 'Slayer': (13, -39, 1, 23, 41),
+ 'Rocketeer': (8, -68, 0, 24, 59), 'Skeleton': (20, -24, 0, 20, 24), 'SkeletonBig': (20, -32, 1, 23, 29),
+ 'DemonWolf': (13, -23, 0, 23, 25), 'Demon': (9, -23, 0, 10, 25), 'DemonMage': (18, -39, 1, 20, 37),
+ 'Necromancer': (19, -25, 0, 16, 24), 'DemonImp': (8, -60, 0, 23, 78), 'LavaElemental': (20, -45, 1, 37, 51),
+ 'Veznan': (37, -37, 1, 24, 38, 340), 'SheepGround': (8, -20, 0, 10, 18), 'SheepFlying': (8, -60, 0, 20, 60),
+}
+BLOOD = {'Spider': 1, 'SpiderSmall': 1, 'SpiderTiny': 1, 'Juggernaut': 2, 'GolemHead': 2, 'Skeleton': 2,
+ 'SkeletonBig': 2, 'LavaElemental': 2}
+SETTING_KEY = {'Goblin': 'goblin', 'FatOrc': 'fatOrc', 'WolfSmall': 'wolfSmall', 'Shaman': 'shaman', 'Ogre': 'ogre',
+ 'Bandit': 'bandit', 'Brigand': 'brigand', 'Marauder': 'marauder', 'Wolf': 'wolf', 'Spider': 'spider',
+ 'SpiderSmall': 'spiderSmall', 'SpiderTiny': 'spiderTiny', 'ShadowArcher': 'shadowArcher',
+ 'DarkKnight': 'darkKnight', 'Gargoyle': 'gargoyle', 'Juggernaut': 'juggernaut', 'GolemHead': 'golemHead',
+ 'WhiteWolf': 'whiteWolf', 'Troll': 'troll', 'TrollChieftain': 'trollChieftain',
+ 'TrollAxeThrower': 'trollAxeThrower', 'Yeti': 'yeti', 'YetiBoss': 'yetiBoss', 'Slayer': 'slayer',
+ 'Rocketeer': 'rocketeer', 'Skeleton': 'skeleton', 'SkeletonBig': 'skeletonBig', 'DemonWolf': 'demonWolf',
+ 'Demon': 'demon', 'DemonMage': 'demonMage', 'Necromancer': 'necromancer', 'DemonImp': 'demonImp',
+ 'LavaElemental': 'lavaElemental', 'Veznan': 'veznan', 'SheepGround': 'goblin', 'SheepFlying': 'gargoyle'}
+NAMES = {'Goblin': 'Goblin', 'FatOrc': 'Orc', 'WolfSmall': 'Wulf', 'Shaman': 'Shaman', 'Ogre': 'Ogre',
+ 'Bandit': 'Bandit', 'Brigand': 'Brigand', 'Marauder': 'Marauder', 'Wolf': 'Worg', 'Spider': 'Giant Spider',
+ 'SpiderSmall': 'Spider', 'SpiderTiny': 'Spiderling', 'ShadowArcher': 'Shadow Archer',
+ 'DarkKnight': 'Dark Knight', 'Gargoyle': 'Gargoyle', 'Juggernaut': 'Juggernaut', 'GolemHead': 'Golem Head',
+ 'WhiteWolf': 'Winter Wolf', 'Troll': 'Troll', 'TrollChieftain': 'Troll Chieftain',
+ 'TrollAxeThrower': 'Troll Axe Thrower', 'Yeti': 'Yeti', 'YetiBoss': "J.T.", 'Slayer': 'Dark Slayer',
+ 'Rocketeer': 'Goblin Rocketeer', 'Skeleton': 'Skeleton', 'SkeletonBig': 'Skeleton Knight',
+ 'DemonWolf': 'Demon Hound', 'Demon': 'Demon Spawn', 'DemonMage': 'Demon Lord', 'Necromancer': 'Necromancer',
+ 'DemonImp': 'Flareon', 'LavaElemental': 'Lava Elemental', 'Veznan': "Vez'nan", 'SheepGround': 'Sheep',
+ 'SheepFlying': 'Flying Sheep'}
+
+
+def write_stats():
+ s = json.load(open(f"{KR}/spec/data/settings.json"))
+ out = ['/* Made by tools/pack.py from the game\'s GameSettings and its enemies\' classes. */',
+ '#include "anim.h"', '#include "kr.h"', '', 'const EnemyStat enemy_stats[EN_COUNT] = {']
+ for e in ENEMIES:
+ st = s['enemies'][SETTING_KEY[e]]
+ c = CLASS[e]
+ sheep = e.startswith('Sheep')
+ boss = 1 if e in ('Juggernaut', 'YetiBoss', 'Veznan') else 0
+ dead = c[5] if len(c) > 5 else 50
+ vals = [0 if sheep else st['health'], 0 if sheep else st['armor'], 0 if sheep else st['magicArmor'],
+ 0 if sheep else st.get('dodge', 0), 0 if sheep else st['gold'], st['cost'], st['minDamage'],
+ st['maxDamage'], st['attackReloadTime']]
+ flying = 1 if (st['isFlying'] and e != 'SheepGround') or e == 'SheepFlying' else 0
+ blockable = 0 if flying else 1 # (each enemy's init: canBeBlocked = false when it flies)
+ out.append(f" {{{', '.join(str(v) for v in vals)}, {float(st['speed'])}f,{st['size']}, {flying}, {boss}, {blockable}, "
+ f"{c[0]}, {st['xSoldierAdjust']}, {st['xAdjust']}, {st['yAdjust']}, {c[1]}, {c[2]}, {c[3]}, {c[4]}, "
+ f"{dead}, {BLOOD.get(e, 0)}}}, /* {e} */")
+ out += ['};', '']
+ # each enemy's walk (sideways, up, down), idle, fight and death (anim.h's A_*): -1 when it has none
+ have = {n for n, _ in DEFINES}
+ out += ['const int16_t enemy_anim[EN_COUNT][6] = {']
+ for e in ENEMIES:
+ row = []
+ for lab in ('WALKING', 'WALKINGUP', 'WALKINGDOWN', 'IDLE', 'FIGHTING', 'DEAD'):
+ n = f"AN_E_{e.upper()}_{lab}"
+ row.append(n if n in have else '-1')
+ out.append(f" {{{', '.join(row)}}},")
+ out += ['};', '', 'const char *enemy_name(int type) {', ' static const char *const n[EN_COUNT] = {']
+ out += [f' "{NAMES[e]}",' for e in ENEMIES]
+ out += [' };', ' return type >= 0 && type < EN_COUNT ? n[type] : "";', '}', '']
+ # a few settings the rules read by name
+ flat = {}
+ for grp in ('archers', 'mages', 'engineers', 'soldiers', 'powers', 'enemies'):
+ for k, v in s[grp].items():
+ for kk, vv in v.items():
+ if isinstance(vv, (int, float)) and not isinstance(vv, bool):
+ flat[f"{grp}_{k}_{kk}"] = vv
+ hdr = ['/* Made by tools/pack.py: the game\'s GameSettings, by name (S_<group>_<object>_<field>). */',
+ '#ifndef KR_SETTINGS_H', '#define KR_SETTINGS_H']
+ for k, v in sorted(flat.items()):
+ hdr.append(f"#define S_{k} {repr(float(v)) + 'f' if isinstance(v, float) and not float(v).is_integer() else int(v)}")
+ hdr += ['#endif', '']
+ open(os.path.join(SRC, "stats.c"), "w").write("\n".join(out))
+ open(os.path.join(SRC, "settings.h"), "w").write("\n".join(hdr))
+
+
+# ------------------------------------------------------------------ the game's own words: src/strings.c
+def load_strings():
+ out = {}
+ for line in open(f"{KR}/spec/strings_en.txt", encoding="utf-8", errors="replace"):
+ if " = " not in line:
+ continue
+ k, v = line.rstrip("\n").split(" = ", 1)
+ v = v.replace("\\'", "'").replace("\\n", " ").replace("’", "'").replace("‘", "'").replace("\\", "")
+ v = " ".join(v.split())
+ out[k] = v
+ return out
+
+
+def c_str(s):
+ s = s.encode("ascii", "replace").decode().replace("?", "'") if any(ord(ch) > 126 for ch in s) else s
+ return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
+
+
+ENEMY_KEY = {'Goblin': 'GOBLIN', 'FatOrc': 'FAT_ORC', 'WolfSmall': 'WULF', 'Shaman': 'SHAMAN', 'Ogre': 'OGRE',
+ 'Bandit': 'BANDIT', 'Brigand': 'BRIGAND', 'Marauder': 'MARAUDER', 'Wolf': 'WORG', 'Spider': 'SPIDER',
+ 'SpiderSmall': 'SPIDERSMALL', 'SpiderTiny': 'SPIDERTINY', 'ShadowArcher': 'SHADOW_ARCHER',
+ 'DarkKnight': 'DARK_NIGHT', 'Gargoyle': 'GARGOYLE', 'Juggernaut': 'JUGGERNAUT', 'GolemHead': 'GOLEM_HEAD',
+ 'WhiteWolf': 'WHITE_WOLF', 'Troll': 'TROLL', 'TrollChieftain': 'TROLL_CHIEFTAIN',
+ 'TrollAxeThrower': 'TROLL_AXE_THROWER', 'Yeti': 'YETI', 'YetiBoss': 'YETI_BOSS', 'Slayer': 'SLAYER',
+ 'Rocketeer': 'ROCKETEER', 'Skeleton': 'SKELETON', 'SkeletonBig': 'SKELETON_BIG', 'DemonWolf': 'DEMON_WOLF',
+ 'Demon': 'DEMON', 'DemonMage': 'DEMON_MAGE', 'Necromancer': 'NECROMANCER', 'DemonImp': 'DEMON_IMP',
+ 'LavaElemental': 'LAVA_ELEMENTAL', 'Veznan': 'VEZNAN', 'SheepGround': 'SHEEP', 'SheepFlying': 'SHEEP'}
+TIP_OF = {"NotificationTipArmor": 1, "NotificationTipRallyPoint": 12, "NotificationTipStrategySoldier": 2,
+ "NotificationTipArmorMagic": 11, "NotificationTipStrategyHeavyArmor": 9}
+TOWER_OF = {"NotificationTowerLevel2": ("Level 2 towers", "Your towers can now be upgraded to level 2."),
+ "NotificationTowerLevel3": ("Level 3 towers", "Your towers can now be upgraded to level 3."),
+ "NotificationTowerArcherRanger": "RANGERS", "NotificationTowerMageArcane": "ARCANE",
+ "NotificationTowerArcherMusketeer": "MUSKETEERS", "NotificationTowerSoldierBarbarian": "BARBARIANS",
+ "NotificationTowerMageSorcerer": "SORCERER", "NotificationTowerEngineerTesla": "TESLA",
+ "NotificationTowerSoldierPaladin": "PALADINS", "NotificationTowerEngineerBfg": "BFG"}
+
+
+def write_strings():
+ S = load_strings()
+ out = ['/* Made by tools/pack.py: the game\'s own English words (its Locale strings). */', '#include "kr.h"',
+ '#include "strings.h"', '']
+ # notifications: a title and a text
+ rows = []
+ for n in NOTES:
+ if not n:
+ rows.append(("", ""))
+ elif n.startswith("NotificationEnemy"):
+ e = n[len("NotificationEnemy"):]
+ k = ENEMY_KEY.get(e, e.upper())
+ txt = S.get(f"ENEMY_{k}_DESCRIPTION", "")
+ sp = S.get(f"ENEMY_{k}_SPECIAL", "").lstrip("*")
+ rows.append(("New enemy: " + S.get(f"ENEMY_{k}_NAME", e), txt + (" " + sp + "." if sp and not sp.endswith(".") else (" " + sp if sp else ""))))
+ elif n.startswith("NotificationPower"):
+ k = "FIREBALL" if "Fireball" in n else "REINFORCEMENTS"
+ key = "1" if k == "FIREBALL" else "2"
+ rows.append(("New spell: " + S[f"POWER_{k}_NAME"], S[f"POWER_{k}_DESCRIPTION"] + f" Press {key} to aim it, OK to cast."))
+ elif n.startswith("NotificationTip"):
+ rows.append(("Tip", S.get(f"TIP_{TIP_OF.get(n, 1)}", "")))
+ else:
+ t = TOWER_OF.get(n)
+ if isinstance(t, tuple):
+ rows.append(t)
+ elif t:
+ rows.append(("New tower: " + S[f"TOWER_{t}_NAME"], S[f"TOWER_{t}_DESCRIPTION"]))
+ else:
+ rows.append(("", ""))
+ out.append("static const char *const notes[][2] = {")
+ out += [f" {{{c_str(a)}, {c_str(b)}}}," for a, b in rows]
+ out += ["};", "const char *note_title(int n) { return n > 0 && n < (int)(sizeof notes / sizeof notes[0]) ? notes[n][0] : 0; }",
+ "const char *note_text(int n) { return n > 0 && n < (int)(sizeof notes / sizeof notes[0]) && notes[n][1][0] ? notes[n][1] : 0; }", ""]
+ out.append("static const char *const enemy_desc_s[EN_COUNT] = {")
+ out += [f" {c_str(S.get('ENEMY_' + ENEMY_KEY[e] + '_DESCRIPTION', ''))}," for e in ENEMIES]
+ out += ["};", "const char *enemy_desc(int t) { return t >= 0 && t < EN_COUNT ? enemy_desc_s[t] : \"\"; }", ""]
+ titles = [S[f"LEVEL_{i}_TITLE"] for i in range(1, NLEVELS + 1)]
+ out.append("static const char *const titles[NLEVELS] = {" + ", ".join(c_str(t) for t in titles) + "};")
+ out.append("const char *level_title(int i) { return i >= 0 && i < NLEVELS ? titles[i] : \"\"; }")
+ hist = [S[f"LEVEL_{i}_HISTORY"] for i in range(1, NLEVELS + 1)]
+ out.append("static const char *const stories[NLEVELS] = {")
+ out += [f" {c_str(h)}," for h in hist]
+ out += ["};", "const char *level_story(int i) { return i >= 0 && i < NLEVELS ? stories[i] : \"\"; }", ""]
+ ups = ["archersUpSalvage", "archersUpEagleEye", "archersUpPiercing", "archersUpFarShots", "archersUpPrecision",
+ "barracksUpSurvival", "barracksUpBetterArmor", "barracksUpImprovedDeployment", "barracksUpSurvival2",
+ "barracksUpBarbedArmor", "magesUpSpellReach", "magesUpArcaneShatter", "magesUpHermeticStudy",
+ "magesUpEmpoweredMagic", "magesUpSlowCurse", "engineersUpConcentratedFire", "engineersUpRangeFinder",
+ "engineersUpFieldLogistics", "engineersUpIndustrialization", "engineersUpEfficiency", "rainUpBlazingSkies",
+ "rainUpScorchedEarth", "rainsUpBiggerAndMeaner", "rainUpBlazingEarth", "rainUpCataclysm"]
+ out.append("static const char *const ups[30][2] = {")
+ for u in ups:
+ k = u.upper()
+ out.append(f" {{{c_str(S.get('UPGRADE_' + k + '_NAME', u))}, {c_str(S.get('UPGRADE_' + k + '_DESCRIPTION', ''))}}},")
+ for i in range(1, 6):
+ out.append(f" {{{c_str(S.get(f'UPGRADE_REINFORCEMENTLEVEL{i}_NAME', f'Reinforcements {i}'))}, "
+ f"{c_str(S.get(f'UPGRADE_REINFORCEMENTLEVEL{i}_DESCRIPTION', ''))}}},")
+ out += ["};", "const char *upgrade_name(int line, int n) { return ups[line * 5 + n][0]; }",
+ "const char *upgrade_desc(int line, int n) { return ups[line * 5 + n][1]; }", ""]
+ # towers and their abilities: names and descriptions by key
+ keys = [k for k in S if k.startswith("TOWER_") or k.startswith("POWER_")]
+ out.append("static const char *const tw[][2] = {")
+ for k in keys:
+ out.append(f" {{{c_str(k)}, {c_str(S[k])}}},")
+ out += ["};", "const char *tower_text(const char *key) {",
+ " for (unsigned i = 0; i < sizeof tw / sizeof tw[0]; i++) {",
+ " const char *a = tw[i][0], *b = key;", " while (*a && *a == *b) a++, b++;",
+ " if (!*a && !*b) return tw[i][1];", " }", " return \"\";", "}", ""]
+ tips = [S[f"TIP_{i}"] for i in range(1, 21)]
+ out.append("static const char *const tips[20] = {")
+ out += [f" {c_str(t)}," for t in tips]
+ out += ["};", "const char *tip(int i) { return tips[i % 20]; }", ""]
+ open(os.path.join(SRC, "strings.c"), "w").write("\n".join(out))
+
+
+# ------------------------------------------------------------------ main
+def main():
+ decor = json.load(open(f"{KR}/spec/data/decor.json"))
+ for n in range(1, NLEVELS + 1):
+ pic(f"LEVEL{n}", terrain(n, decor))
+ # the title (MainMenu, its buttons but START left out) and the world map (Map's terrain and its road), at
+ # 320 / 700 of their size: 320 x 274, the calculator's 240 rows of them
+ t = Image.open(f"{KR}/render/u/title/47.png").convert("RGBA").crop((366, 366, 686, 606))
+ a = np.asarray(t).copy()
+ a[127:139, 282:320] = a[115:127, 282:320] # (the version number at the right edge)
+ pic("TITLE", Image.fromarray(a).convert("RGB"))
+ m = Image.open(f"{KR}/render/u/map/1.png").convert("RGBA")
+ road = Image.open(f"{KR}/render/u/road/250.png").convert("RGBA")
+ m.alpha_composite(road)
+ mp = m.crop((366, 366 + MAP_Y0, 686, 606 + MAP_Y0))
+ pic("MAP", mp.convert("RGB"))
+ define("MAP_Y0", MAP_Y0)
+ # the upgrades (MenuUpgrades at 0.33, its buttons and bars left out) over the darkened map
+ up = Image.open(f"{KR}/render/u/upgr/1.png").convert("RGBA").crop((155, 216, 370, 456))
+ dark = Image.blend(mp.convert("RGB"), Image.new("RGB", mp.size, (0, 0, 0)), 0.55).convert("RGBA")
+ dark.alpha_composite(up, (UPG_X, 0))
+ pic("UPGRADES", dark.convert("RGB"))
+ define("UPG_X", UPG_X)
+ huff, quant, pics, table, bank, bgpal = encode_pics()
+ sprites()
+ write_stats()
+ spal, frames, anims = pack_sprites()
+ print(f"sprites: {len(FRAMES)} frames, {len(frames)} bytes, {len(ANIMS)} animations")
+ fonts = [ttf_font(ImageFont.truetype(find_font("LilitaOne-Regular.ttf"), 13)), # FONT_HUD
+ ttf_font(ImageFont.truetype(find_font("LilitaOne-Regular.ttf"), 22)), # FONT_BIG
+ ttf_font(ImageFont.truetype(find_font("DejaVuSans-Bold.ttf"), 10)), # FONT_SMALL
+ ttf_font(ImageFont.truetype(find_font("DejaVuSans.ttf"), 11))] # FONT_TEXT
+ levels = pack_levels()
+ write_strings()
+ sections = [huff, quant, pics, table, bank, bgpal, spal, frames, anims, pack_fonts(fonts), levels]
+ head = b"KRSH" + struct.pack("<I", len(sections))
+ off = len(head) + 4 * len(sections)
+ body = b""
+ for s in sections:
+ head += struct.pack("<I", off + len(body))
+ body += s + bytes(-len(s) % 4)
+ data = head + body
+ open(os.path.join(SRC, "data.bin"), "wb").write(data)
+ h = ["/* Made by tools/pack.py: what is in data.bin. */", "#ifndef KR_DATA_H", "#define KR_DATA_H", ""]
+ h += [f"#define SEC_{n} {i}" for i, n in enumerate(SECTIONS)]
+ h += [f"#define FONT_{n} {i}" for i, n in enumerate(["HUD", "BIG", "SMALL", "TEXT"])]
+ h += [f"#define {n} {v}" for n, v in DEFINES]
+ h += [f"#define EN_{e.upper()} {i}" for i, e in enumerate(ENEMIES)]
+ h += [f"#define EN_COUNT {len(ENEMIES)}", f"#define NLEVELS {NLEVELS}", ""]
+ h += [f"#define NOTE_{n.replace('Notification', '').upper() or 'NONE'} {i}" for i, n in enumerate(NOTES)]
+ h += ["", "#endif", ""]
+ open(os.path.join(SRC, "data.h"), "w").write("\n".join(h))
+ print(f"data.bin: {len(data)} bytes ({', '.join(f'{n} {len(s)}' for n, s in zip(SECTIONS, sections))})")
+
+
+if __name__ == "__main__":
+ main()