Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Clash Royale: battles against a bot, from the 2016 game's own files
Mason363d9f6624fa607
diff --git a/Makefile b/Makefileindex f59a887b..e094f8f2 100644--- a/Makefile+++ b/Makefile@@ -18,7 +18,7 @@ PY ?= python3CARGO ?= cargoB = build/data# Conventional games honor a configurable output directory; special layouts are kept local.-GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnaf4 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno uttt+GAMES_REDIRECT = angrybirds badtime balatro blockblast breakout buckshot celeste championisland chess clashroyale connectfour cookieclicker coreball dinorun donkeykong doodlejump doom dune famidash finalearth2 flappybird flappydunk fnaf fnaf2 fnaf3 fnaf4 fnf g2048 hillclimb hollowknight invaders isaac jetpackjoyride leveldevil mahjong meowdoku minesweeper monkeymart numblocks numpowder numvisuals pacman paperclips polytrack portal pvz rider snake snowrider sokoban solitaire sonic stickmanhook subway sudoku suika templerun tombofthemask towerblock turborush twoplayer undertale uno utttGAMES_OUT = dinorunGAME_REDIRECT_ARG = $(if $(filter $(1),$(GAMES_OUT)),OUT=../../$(B)/games/$(1),BUILD_DIR=../../$(B)/games/$(1))# the RAM the oldest calculator software that runs apps gives them (23.2: 148928 bytes; 25.2 gives 153676).@@ -29,7 +29,7 @@ RAM_LIMIT = 148928# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)CUSTOM_RAM = 133652-BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 FiveNightsAtFreddys4 Famidash UniversalPaperclips-French+BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune MonkeyMart TombOfTheMask UNO FridayNightFunkin TurboRush AngryBirds PolyTrack UniversalPaperclips BadTimeSimulator Mahjong Rider SnowRider3D TempleRun FiveNightsAtFreddys2 FiveNightsAtFreddys3 FiveNightsAtFreddys4 Famidash ClashRoyale UniversalPaperclips-French# the calculator's space for installed apps: from the end of its software (64 KiB aligned) to 64 KiB before the# end of its 4 MiB slot of flash, 0x903F0000. The software's size sets the start: 0x90200000 is the latest a# NumPlay counts on (1.94 MB, APP_SPACE); Epsilon 26.4 on an N0120 ends at 0x90180000 (2.44 MB, the@@ -337,6 +337,7 @@ APP_fnaf2 = $(B)/games/fnaf2/fnaf2.nwa:FiveNightsAtFreddys2.nwaAPP_fnaf3 = $(B)/games/fnaf3/fnaf3.nwa:FiveNightsAtFreddys3.nwaAPP_fnaf4 = $(B)/games/fnaf4/fnaf4.nwa:FiveNightsAtFreddys4.nwaAPP_famidash = $(B)/games/famidash/famidash.nwa:Famidash.nwa+APP_clashroyale = $(B)/games/clashroyale/clashroyale.nwa:ClashRoyale.nwa# the big games' modules are made from these (the kit)$(foreach g,$(XL_GAMES),$(eval MOD_$(g) = $$(word 1,$$(subst :, ,$$(APP_$(g))))))@@ -385,6 +386,7 @@ apps: | $(B)$(MAKE) -C games/fnaf3 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf3$(MAKE) -C games/fnaf4 build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/fnaf4$(MAKE) -C games/famidash build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/famidash+ $(MAKE) -C games/clashroyale build NWLINK="$(NWLINK)" BUILD_DIR=../../$(B)/games/clashroyalecd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quietcp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))@@ -432,6 +434,7 @@ apps: | $(B)cp $(word 1,$(subst :, ,$(APP_fnaf3))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf3)))cp $(word 1,$(subst :, ,$(APP_fnaf4))) $(B)/apps/$(word 2,$(subst :, ,$(APP_fnaf4)))cp $(word 1,$(subst :, ,$(APP_famidash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_famidash)))+ cp $(word 1,$(subst :, ,$(APP_clashroyale))) $(B)/apps/$(word 2,$(subst :, ,$(APP_clashroyale)))arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwaSTD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))@@ -519,5 +522,6 @@ clean:-$(MAKE) -C games/fnaf3 clean-$(MAKE) -C games/fnaf4 clean-$(MAKE) -C games/famidash clean+ -$(MAKE) -C games/clashroyale clean-cd games/tetris/tetris && $(CARGO) clean-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)diff --git a/docs/play.md b/docs/play.mdindex 5a02d196..2a8628e4 100644--- a/docs/play.md+++ b/docs/play.md@@ -807,6 +807,23 @@ Your icon moves on by itself: jump over the spikes and reach the end. Hold the b<br clear="right">+## Clash Royale++<img src="../games/clashroyale/docs/shot.png" width="320" align="right" alt="Clash Royale: troops at the bridge, the bot's towers on the right">++| Key | What it does |+| --- | --- |+| **1** to **4** | Pick a card of your hand |+| **Left / Right**, **OK** | Pick a card, then take it to the field |+| **Arrows** | Move the card on the field |+| **OK** | Drop it there |+| **Back** | Put the card back; in the hand, pause |+| **Home** | Keep the battle and quit |++Knock down the bot's towers before it knocks down yours: a Princess tower is a crown, the King tower is three and ends the battle. Elixir fills up by itself and pays for your cards; a played card goes to the back of your deck and the next takes its place. Troops and buildings go on your side of the river, spells anywhere. The last minute gives double elixir; even crowns at the end bring overtime, where the next crown wins. Wins give trophies, and trophies open the next arena. Build your deck of eight from the 41 cards in Deck.++<br clear="right">+## Portal Returns<img src="media/portal.gif" width="320" align="right" alt="Portal Returns: falling through a portal and flying across a test chamber">diff --git a/games/clashroyale/.gitignore b/games/clashroyale/.gitignorenew file mode 100644index 00000000..643bd909--- /dev/null+++ b/games/clashroyale/.gitignore@@ -0,0 +1,3 @@+output/+build/+__pycache__/diff --git a/games/clashroyale/Makefile b/games/clashroyale/Makefilenew file mode 100644index 00000000..96f877eb--- /dev/null+++ b/games/clashroyale/Makefile@@ -0,0 +1,79 @@+# Clash Royale on the NumWorks calculator.+# make output/clashroyale.nwa+# make check link it like the calculator does (output/clashroyale.bin)+# make host build/rules and build/shots: the game on a computer, for tests and screenshots+# make test the game played on a computer (tests/rules.c, with the sanitizers)+# make data src/data.bin, src/data.h, src/ids.h and src/tables.c from the game's Android package+# (APK=its path; Python + Pillow + NumPy + SciPy)++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+APK ?=++# drawing and the battle run every frame at -O2; the rest is small at -Os+HOT = src/gfx.c src/view.c src/sim.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 ../common/np_lz.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)/clashroyale.nwa++# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)+check: $(BUILD_DIR)/clashroyale.nwa+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/clashroyale.bin+ @echo "BIN $(BUILD_DIR)/clashroyale.bin: $$(wc -c < $(BUILD_DIR)/clashroyale.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)/clashroyale.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 units against the spec's numbers, plays bot against bot and 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 $(APK)++clean:+ $(Q) rm -rf $(BUILD_DIR) build/rules build/host-saves build/shotsdiff --git a/games/clashroyale/README.md b/games/clashroyale/README.mdnew file mode 100644index 00000000..efff67c2--- /dev/null+++ b/games/clashroyale/README.md@@ -0,0 +1,77 @@+<p align="center">+ <img src="src/icon.png" width="84" alt="Clash Royale icon">+</p>++<h1 align="center">Clash Royale</h1>++<p align="center">+ <b>Knock down the towers, on the NumWorks calculator.</b><br>+ One against a bot: the 2016 game's cards, arenas, elixir and crowns.+</p>++<p align="center">+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/ClashRoyale.nwa"><b>Download ClashRoyale.nwa</b></a>+ · <a href="#controls">Controls</a>+</p>++<p align="center">+ <img src="../../docs/media/gallery/clashroyale.gif" width="480" alt="A battle: troops cross the bridges and fight at the towers">+</p>++## Highlights++* **41 cards of the 2016 game,** every one but Mirror: troops, buildings and spells, with the game's own hitpoints, damage, hit speed, range, speed, splash, spawns and death damage, read out of its Android package, at tournament standard (Common 8, Rare 6, Epic 3).+* **The game's rules:** 3 minutes, an elixir every 2.8 s, double elixir in the last minute, a minute of sudden death, a crown for each Princess tower and three for the King's. The King tower wakes when hit or when a Princess tower falls.+* **The game's pictures:** its arenas, towers, troops in eight directions, card art and font.+* **Seven arenas,** from Goblin Stadium to the Legendary Arena, opened by trophies. The bot gets quicker in each.+* **A deck of your own** from all the cards, and the bot plays the training camp's decks.++<table>+ <tr>+ <td align="center"><img src="docs/shot.png" width="390" alt="Troops at the bridge"><br><sub>A battle</sub></td>+ <td align="center"><img src="docs/deck.png" width="390" alt="The deck and the card collection"><br><sub>The deck</sub></td>+ </tr>+ <tr>+ <td align="center"><img src="docs/title.png" width="390" alt="The title"><br><sub>The title</sub></td>+ <td align="center"><img src="docs/place.png" width="390" alt="A card on the field, the enemy side in red"><br><sub>Placing a card</sub></td>+ </tr>+</table>++## How to play++Knock down the bot's towers before it knocks down yours. A Princess tower is a crown, the King tower is three and ends the battle at once. After 3 minutes the one with more crowns wins; even crowns bring a minute of overtime, where the next crown wins.++Elixir fills up by itself, up to 10, and each card costs some. You hold four cards: play one and it goes to the back of your deck, and the next card takes its place. Troops and buildings go on your side of the river (and on the enemy's side of a lane once its Princess tower is down), spells anywhere. Troops walk to the nearest building and fight what they meet on the way; some only go for buildings.++## Controls++| Key | What it does |+| --- | --- |+| 1 to 4 | Pick a card |+| ← → and OK | Pick a card, then take it to the field |+| Arrows | Move it on the field |+| OK | Drop it |+| Back | Put the card back; in the hand, pause |+| Home | Keep the battle and quit |++## Good to know++* **Too big to install next to NumPlay.** Your trophies and deck are kept.+* **The arena is turned** to fit the wide screen: your side on the left.+* **The bot is NumPlay's own,** not Supercell's.+* **Left out:** Mirror, chests, gold and card upgrades, clans and online play. No sound: the calculator has no speaker.+* Leaving a battle counts as a loss, as in the game.++## Credits++Inspired by Clash Royale by Supercell, not affiliated with Supercell. Clash Royale is a trademark of Supercell.++* The numbers, pictures, card names and fonts (Supercell-Magic, CCBackBeat) come from the game's 2016 Android package: `tools/sc.py` reads its pictures, and `tools/pack.py` makes them and its card tables into `src/data.bin` and `src/tables.c`.++Made by Mason Chen as part of NumPlay.++## License++The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The game's pictures, names and fonts keep their own terms (see Credits).++Build: `make` (needs `arm-none-eabi-gcc` and Node.js for nwlink), `make test` on a computer.diff --git a/games/clashroyale/src/bot.c b/games/clashroyale/src/bot.cnew file mode 100644index 00000000..6096faea--- /dev/null+++ b/games/clashroyale/src/bot.c@@ -0,0 +1,283 @@+/* The bot: NumPlay's own, not Supercell's. It plays team 1 by the same rules as you, with one of the training camp's+ * decks: it defends what crosses toward its towers with a card that can hit it, pulls building-chasers with its+ * buildings, spells clumps, and pushes a lane with a win condition when it has the elixir. Higher arenas think+ * faster and wait for bigger pushes. */+#include <stddef.h>+#include "sim.h"++bool bot_plays_both; /* tests: a bot for you too */++static int32_t brand(Bot *bt, int32_t n) { return n > 0 ? (int32_t)(sim_rand(&bt->rng) % (uint32_t)n) : 0; }++typedef struct {+ int n, air, small, tank, chasers;+ int32_t x, y, hp;+} Threat;++/* the enemy troops heading for team's side, in a lane (-1: both) */+static void threats(const Battle *b, int team, int lane, Threat *t) {+ *t = (Threat){0};+ int64_t sx = 0, sy = 0;+ for (int i = 0; i < MAXE; i++) {+ const Ent *e = &b->e[i];+ if (!ent_alive(b, i) || e->team == team) continue;+ const UnitDef *d = &UNITS[e->type];+ if (d->flags & (U_BUILDING | U_BOMB)) continue;+ bool near = team ? e->x > 11500 : e->x < ARENA_X - 11500;+ if (!near) continue;+ if (lane >= 0 && (e->y < ARENA_Y / 2) != (lane == 0)) continue;+ t->n++;+ t->hp += e->hp;+ if (d->flags & U_FLY) t->air++;+ if (e->maxhp < 400) t->small++;+ if (e->maxhp >= 1500) t->tank++;+ if (d->flags & U_BUILDINGS) t->chasers++;+ /* the front one counts most */+ int w = team ? e->x : ARENA_X - e->x;+ sx += (int64_t)e->x * w, sy += (int64_t)e->y * w;+ t->x += w;+ }+ if (t->n) {+ int32_t w = t->x;+ t->x = (int32_t)(sx / w), t->y = (int32_t)(sy / w);+ }+}++static bool can_hit_air(int card) {+ const CardDef *c = &CARDS[card];+ if (c->kind == K_SPELL) return c->proj != NONE ? (PROJS[c->proj].flags & P_AOE_AIR) != 0 : c->area != NONE;+ return c->unit != NONE && (UNITS[c->unit].flags & U_AIR);+}++static bool splashes(int card) {+ const CardDef *c = &CARDS[card];+ if (c->unit == NONE) return false;+ const UnitDef *u = &UNITS[c->unit];+ return u->area || (u->proj != NONE && PROJS[u->proj].radius);+}++static int32_t dps(int card) {+ const CardDef *c = &CARDS[card];+ if (c->unit == NONE) return 0;+ const UnitDef *u = &UNITS[c->unit];+ int32_t dmg = u->proj != NONE ? PROJS[u->proj].dmg : u->dmg;+ if (u->dmg2) dmg = u->dmg2;+ return u->hit_ms ? lv(dmg, card_lvl_index(card)) * 1000 / u->hit_ms * c->count : 0;+}++/* the spell damage of a card at its level, and what it would hit around (x, y) */+static int32_t spell_value(const Battle *b, int team, int card, int32_t x, int32_t y, int32_t *hit_hp) {+ const CardDef *c = &CARDS[card];+ int32_t dmg = 0, r = c->radius;+ if (c->proj != NONE) dmg = lv(PROJS[c->proj].dmg, card_lvl_index(card));+ else if (c->area != NONE) {+ const AreaDef *a = &AREAS[c->area];+ dmg = a->dmg ? lv(a->dmg, card_lvl_index(card)) : a->proj != NONE ? lv(PROJS[a->proj].dmg, card_lvl_index(card)) : 0;+ }+ int32_t v = 0, hhp = 0;+ for (int i = 0; i < MAXE; i++) {+ const Ent *e = &b->e[i];+ if (!ent_alive(b, i) || e->team == team || (UNITS[e->type].flags & U_BOMB)) continue;+ if (dist(x, y, e->x, e->y) > r + UNITS[e->type].radius) continue;+ int32_t d = dmg;+ if (UNITS[e->type].flags & U_TOWER) d = d * GL(REDUCED_TOWER_DAMAGE_PERCENT) / 100;+ v += d < e->hp ? d : e->hp * 3 / 2; /* a kill is worth more */+ hhp += e->hp;+ }+ if (hit_hp) *hit_hp = hhp;+ return v;+}++static bool play(Battle *b, int team, int slot, int32_t x, int32_t y) {+ /* there, or the nearest tile it may use */+ static const int8_t off[9][2] = {{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};+ int card = b->side[team].hand[slot];+ for (int k = 0; k < 9; k++) {+ int32_t px = x + off[k][0] * 1000, py = y + off[k][1] * 1000;+ if (battle_can_place(b, team, card, px, py) && battle_play(b, team, slot, px, py)) return true;+ }+ return false;+}++static int32_t own_x(int team, int32_t from_king) { return team ? ARENA_X - from_king : from_king; }++static bool defend(Battle *b, int team) {+ const Side *s = &b->side[team];+ Threat t;+ for (int lane = 0; lane < 2; lane++) {+ threats(b, team, lane, &t);+ if (!t.n) continue;+ /* how close: the front one past the river is urgent */+ bool crossed = team ? t.x > RIVER_X1 - 1500 : t.x < RIVER_X0 + 1500;+ if (!crossed && t.hp < 600) continue;+ int best = -1;+ int32_t bs = 0, bx = 0, by = 0;+ for (int k = 0; k < 4; k++) {+ int card = s->hand[k];+ if (card == NONE || CARDS[card].cost > s->elixir) continue;+ const CardDef *c = &CARDS[card];+ int32_t score = 0, x = 0, y = t.y;+ if (c->kind == K_SPELL) {+ if (c->proj == NONE && c->area == NONE) continue;+ if (c->area != NONE && !AREAS[c->area].dmg && AREAS[c->area].proj == NONE) continue; /* Rage, Freeze */+ if (c->proj != NONE && PROJS[c->proj].spawn_unit != NONE) continue; /* Goblin Barrel */+ int32_t lead = team ? 800 : -800;+ int32_t v = spell_value(b, team, card, t.x + lead, t.y, NULL);+ score = v * 10 / (c->cost * 120) - 6;+ x = t.x + lead;+ } else if (c->kind == K_BUILDING) {+ if (c->unit == NONE || !(UNITS[c->unit].range && (UNITS[c->unit].dmg || UNITS[c->unit].proj != NONE)) ||+ UNITS[c->unit].range > 9000)+ continue;+ if (t.air && !(UNITS[c->unit].flags & U_AIR)) continue;+ score = t.chasers ? 9 : 3;+ x = own_x(team, 8500), y = ARENA_Y / 2;+ } else {+ if (t.air && !can_hit_air(card)) continue;+ const UnitDef *u = &UNITS[c->unit];+ if (u->flags & U_BUILDINGS) continue;+ score = 4 + (int32_t)(dps(card) / 60);+ if (t.small >= 3 && splashes(card)) score += 5;+ if (t.tank && dps(card) > 250) score += 4;+ if (t.air && (u->flags & U_AIR)) score += 3;+ score -= c->cost;+ bool ranged = u->range > 3000;+ if (ranged) x = own_x(team, 5500), y = t.y < ARENA_Y / 2 ? 3500 : 14500;+ else x = team ? (t.x + 2500 > RIVER_X1 + 500 ? t.x + 2500 : RIVER_X1 + 500) : (t.x - 2500 < RIVER_X0 - 500 ? t.x - 2500 : RIVER_X0 - 500);+ }+ if (score > bs) bs = score, best = k, bx = x, by = y;+ }+ if (best >= 0 && bs > 0) {+ if (bx < 500) bx = 500;+ if (bx > ARENA_X - 500) bx = ARENA_X - 500;+ return play(b, team, best, bx / 1000 * 1000 + 500, by / 1000 * 1000 + 500);+ }+ }+ return false;+}++static bool is_win_condition(int card) {+ const CardDef *c = &CARDS[card];+ if (c->proj != NONE && PROJS[c->proj].spawn_unit != NONE) return true; /* Goblin Barrel */+ if (c->unit == NONE) return false;+ const UnitDef *u = &UNITS[c->unit];+ return (u->flags & U_BUILDINGS) || u->hp * LEVEL_MULT[card_lvl_index(card)] / 100 >= 1500 || card == CA_XBOW ||+ card == CA_MORTAR || card == CA_BARBARIANS;+}++static bool attack(Battle *b, int team) {+ Bot *bt = &b->bot[team];+ const Side *s = &b->side[team], *o = &b->side[1 - team];+ int32_t need = 9 - bt->level / 3;+ if (bt->push_ms > 0) need = 3; /* support the push */+ if (s->elixir < need) return false;+ int lane = bt->push_lane;+ if (lane < 0) {+ /* the weaker enemy tower */+ int32_t h0 = ent_alive(b, o->princess[0]) ? b->e[o->princess[0]].hp : 0;+ int32_t h1 = ent_alive(b, o->princess[1]) ? b->e[o->princess[1]].hp : 0;+ lane = h0 && h1 ? (h0 == h1 ? brand(bt, 2) : h0 < h1 ? 0 : 1) : (h0 ? 1 : 0);+ if (!h0 && !h1) lane = brand(bt, 2);+ }+ int32_t ly = lane ? 14500 : 3500;+ int best = -1, bs = -100;+ for (int k = 0; k < 4; k++) {+ int card = s->hand[k];+ if (card == NONE || CARDS[card].cost > s->elixir) continue;+ const CardDef *c = &CARDS[card];+ int32_t score = 0;+ if (bt->push_ms <= 0) {+ if (!is_win_condition(card)) continue;+ score = 10 + c->cost;+ } else {+ if (c->kind != K_TROOP || is_win_condition(card)) continue;+ score = 5 + (int32_t)(dps(card) / 80);+ }+ if (score > bs) bs = score, best = k;+ }+ if (best < 0) return false;+ int card = s->hand[best];+ const CardDef *c = &CARDS[card];+ int32_t x, y = ly;+ if (c->proj != NONE) { /* the barrel, at the tower */+ int pt = o->princess[lane];+ if (!ent_alive(b, pt)) pt = o->king;+ if (!ent_alive(b, pt)) return false;+ x = b->e[pt].x, y = b->e[pt].y;+ } else if (bt->push_ms > 0) {+ /* behind the tank */+ x = own_x(team, 11000);+ for (int i = 0; i < MAXE; i++) {+ const Ent *e = &b->e[i];+ if (ent_alive(b, i) && e->team == team && (UNITS[e->type].flags & U_BUILDINGS) && (e->y < ARENA_Y / 2) == !lane) {+ x = team ? e->x + 2500 : e->x - 2500;+ y = e->y;+ break;+ }+ }+ if (team ? x < RIVER_X1 : x >= RIVER_X0) x = team ? RIVER_X1 + 500 : RIVER_X0 - 500;+ } else if (c->kind == K_BUILDING) {+ x = card == CA_XBOW || card == CA_MORTAR ? own_x(team, 13000) : own_x(team, 4500);+ } else {+ const UnitDef *u = &UNITS[c->unit];+ bool slow = u->speed <= 45;+ x = slow ? own_x(team, 2500) : own_x(team, 14500);+ }+ if (!play(b, team, best, x / 1000 * 1000 + 500, y / 1000 * 1000 + 500)) return false;+ if (bt->push_ms <= 0) bt->push_ms = 9000, bt->push_lane = lane;+ return true;+}++static bool finish_tower(Battle *b, int team) {+ const Side *s = &b->side[team], *o = &b->side[1 - team];+ for (int k = 0; k < 4; k++) {+ int card = s->hand[k];+ if (card == NONE || CARDS[card].cost > s->elixir || CARDS[card].kind != K_SPELL) continue;+ const CardDef *c = &CARDS[card];+ int32_t dmg = c->proj != NONE ? lv(PROJS[c->proj].dmg, card_lvl_index(card))+ : c->area != NONE && AREAS[c->area].dmg ? lv(AREAS[c->area].dmg, card_lvl_index(card)) : 0;+ if (!dmg || (c->proj != NONE && PROJS[c->proj].spawn_unit != NONE)) continue;+ dmg = dmg * GL(REDUCED_TOWER_DAMAGE_PERCENT) / 100;+ int towers[3] = {o->princess[0], o->princess[1], o->king};+ for (int i = 0; i < 3; i++)+ if (ent_alive(b, towers[i]) && b->e[towers[i]].hp <= dmg)+ return battle_play(b, team, k, b->e[towers[i]].x, b->e[towers[i]].y);+ }+ return false;+}++static bool leak(Battle *b, int team) {+ const Side *s = &b->side[team];+ if (s->elixir < GL(MAX_MANA)) return false;+ int best = -1, bc = 99;+ for (int k = 0; k < 4; k++) {+ int card = s->hand[k];+ if (card == NONE || CARDS[card].kind == K_SPELL) continue;+ if (CARDS[card].cost < bc) bc = CARDS[card].cost, best = k;+ }+ if (best < 0) return false;+ int32_t y = brand(&b->bot[team], 2) ? 3500 : 14500;+ return play(b, team, best, own_x(team, 2500) / 1000 * 1000 + 500, y);+}++static void think(Battle *b, int team) {+ Bot *bt = &b->bot[team];+ if (bt->push_ms > 0) bt->push_ms -= 600;+ if (bt->push_ms <= 0) bt->push_lane = -1;+ /* now and then it misses its chance (less in higher arenas) */+ if (brand(bt, 100) < 18 - 2 * bt->level) return;+ if (finish_tower(b, team)) return;+ if (defend(b, team)) return;+ if (attack(b, team)) return;+ leak(b, team);+}++void bot_step(Battle *b) {+ for (int team = bot_plays_both ? 0 : 1; team < 2; team++) {+ Bot *bt = &b->bot[team];+ bt->think -= TICK;+ if (bt->think > 0) continue;+ bt->think = 1000 - 90 * bt->level + brand(bt, 400);+ think(b, team);+ }+}diff --git a/games/clashroyale/src/data.S b/games/clashroyale/src/data.Snew file mode 100644index 00000000..938a8736--- /dev/null+++ b/games/clashroyale/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 _cr_data+_cr_data:+ .incbin DATA_BIN+ .p2align 2+#else+ .section .rodata.cr_data,"a"+ .balign 4+ .global cr_data+cr_data:+ .incbin DATA_BIN+ .balign 4+#endif+#ifdef __ELF__+ .section .note.GNU-stack,"",%progbits+#endifdiff --git a/games/clashroyale/src/data.bin b/games/clashroyale/src/data.binnew file mode 100644index 00000000..371125abBinary files /dev/null and b/games/clashroyale/src/data.bin differdiff --git a/games/clashroyale/src/data.h b/games/clashroyale/src/data.hnew file mode 100644index 00000000..a8177407--- /dev/null+++ b/games/clashroyale/src/data.h@@ -0,0 +1,27 @@+/* made by tools/pack.py */+#ifndef CR_DATA_H+#define CR_DATA_H++#define SEC_IMGS 0+#define SEC_PALS 1+#define SEC_FONTS 2+#define SEC_ARENAS 3++#define IMG_RUBBLE 1469+#define IMG_EXPLOSION 1481+#define IMG_PUFF 1487+#define IMG_ZAP 1491+#define IMG_LIGHTNING 1494+#define IMG_CROWN 1497+#define IMG_CARDFRAME 1498+#define IMG_DROP 1499+#define IMG_DROP_BIG 1500+#define IMG_CARD_HIDDEN 1583+#define IMG_TITLE 1584+#define FONT_SMALL 0+#define FONT_MID 1+#define FONT_BIG 2+#define FONT_NUM 3+#define NARENAS 7++#endifdiff --git a/games/clashroyale/src/game.c b/games/clashroyale/src/game.cnew file mode 100644index 00000000..03b00ac1--- /dev/null+++ b/games/clashroyale/src/game.c@@ -0,0 +1,440 @@+/* The screens: the title, the deck, how to play, the battle with its pause and result. */+#include <stdio.h>+#include <string.h>+#include "game.h"+#include "gfx.h"+#include "res.h"++Game g;+Battle bt;++#define GOLD RGB(0xFFD23C)+#define BLUE RGB(0x3C8CF0)+#define RED RGB(0xE8403C)+#define PINK RGB(0xD83CE0)+#define PANEL RGB(0x1C2A4A)++/* arenas.csv: Arena1 to Arena7 from these trophies; TID_INFO_ARENA1 to 7 */+static const int32_t ARENA_TROPHIES[NARENAS] = {0, 400, 800, 1100, 1400, 1700, 3000};+static const char *const ARENA_NAMES[NARENAS] = {"Goblin Stadium", "Bone Pit", "Barbarian Bowl", "P.E.K.K.A's Playhouse",+ "Spell Valley", "Royal Arena", "Legendary Arena"};+int arena_of(int32_t trophies) {+ int a = 0;+ for (int i = 0; i < NARENAS; i++)+ if (trophies >= ARENA_TROPHIES[i]) a = i;+ return a;+}+const char *arena_name(int a) { return ARENA_NAMES[a < 0 ? 0 : a >= NARENAS ? NARENAS - 1 : a]; }++/* the training camp's BasicDeck16: Knight, Archers, Skeleton Army, Goblins, Fireball, Giant, Valkyrie, Mini P.E.K.K.A. */+static const uint8_t DEFAULT_DECK[8] = {CA_KNIGHT, CA_ARCHER, CA_SKELETONARMY, CA_GOBLINS, CA_FIREBALL, CA_GIANT, CA_VALKYRIE, CA_MINIPEKKA};++static void go(int screen) {+ g.screen = screen;+ g.ms = 0;+ g.sel = 0;+ g.confirm = false;+}++void game_init(void) {+ memset(&g, 0, sizeof g);+ g.running = true;+ memcpy(g.prof.deck, DEFAULT_DECK, 8);+ save_load();+ g.hold = -1;+ g.cx = 11, g.cy = 3;+ go(SC_TITLE);+ if (resume_load()) {+ view_load_arena(bt.arena);+ go(SC_PAUSE);+ }+}++static void start_battle(void) {+ uint32_t seed = plat_millis() * 2654435761u ^ (uint32_t)g.prof.wins * 7919u ^ (uint32_t)g.prof.losses * 104729u;+ if (!seed) seed = 1;+ int arena = arena_of(g.prof.trophies);+ uint32_t r = seed;+ int deck = (int)(sim_rand(&r) % NBOTDECKS);+ battle_init(&bt, g.prof.deck, BOT_DECKS[deck], arena, seed);+ view_load_arena(arena);+ g.field = false;+ g.slot = 0;+ g.cx = 11, g.cy = 3;+ g.msg = NULL;+ g.steps = 0;+ go(SC_BATTLE);+}++static void finish_battle(void) {+ /* trophies: K_FACTOR 60 against an even opponent, half of it */+ g.old_arena = arena_of(g.prof.trophies);+ g.dtroph = bt.winner == 0 ? 30 : bt.winner == 1 ? -30 : 0;+ if (g.prof.trophies + g.dtroph < 0) g.dtroph = -g.prof.trophies;+ g.prof.trophies += g.dtroph;+ if (g.prof.trophies > g.prof.best) g.prof.best = g.prof.trophies;+ if (bt.winner == 0) g.prof.wins++;+ else if (bt.winner == 1) g.prof.losses++;+ else g.prof.draws++;+ if (bt.winner == 0 && bt.side[0].crowns == 3) g.prof.three++;+ save_write();+ resume_clear();+ go(SC_RESULT);+}++/* ------------------------------------------------------------------ keys */+static uint32_t pressed(void) { return g.keys & ~g.prev; }++/* arrows: once, then again every 90 ms after 300 ms held */+static uint32_t arrows(void) {+ uint32_t a = g.keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN);+ if (!a) return 0;+ if (a & ~g.prev) return a & ~g.prev;+ if (g.held_ms >= 300 && (g.held_ms - 300) % 90 < 17) return a;+ return 0;+}+static bool ok(void) { return pressed() & (K_OK | K_EXE); }++static void say(const char *m) {+ g.msg = m;+ g.msg_t = 90;+}++/* ------------------------------------------------------------------ the battle's keys */+static void battle_keys(void) {+ uint32_t p = pressed(), a = arrows();+ for (int k = 0; k < 4; k++)+ if (p & K_DIGIT(k + 1)) {+ g.slot = k;+ g.field = true;+ return;+ }+ if (!g.field) {+ if (a & K_LEFT) g.slot = (g.slot + 3) & 3;+ if (a & K_RIGHT) g.slot = (g.slot + 1) & 3;+ if (ok() || (p & K_UP)) g.field = true;+ else if (p & K_BACK) go(SC_PAUSE);+ return;+ }+ if (a & K_LEFT && g.cx > 0) g.cx--;+ if (a & K_RIGHT && g.cx < 31) g.cx++;+ if (a & K_UP && g.cy > 0) g.cy--;+ if (a & K_DOWN && g.cy < 17) g.cy++;+ if (p & K_BACK) g.field = false;+ if (ok()) {+ int32_t x = g.cx * 1000 + 500, y = g.cy * 1000 + 500;+ const char *why = battle_check(&bt, 0, g.slot, x, y);+ if (why) say(why);+ else if (battle_play(&bt, 0, g.slot, x, y)) g.field = false;+ }+}++/* ------------------------------------------------------------------ the deck's keys */+#define DCOLS 8+#define DROWS_SHOWN 3+static int deck_has(int card) {+ for (int k = 0; k < 8; k++)+ if (g.prof.deck[k] == card) return k;+ return -1;+}+static int deck_cursor_card(void) {+ if (g.drow == 0) return g.prof.deck[g.dcol];+ int i = (g.drow - 1) * DCOLS + g.dcol;+ return i < NCARDS ? i : -1;+}++static void deck_keys(void) {+ uint32_t a = arrows(), p = pressed();+ int rows = 1 + (NCARDS + DCOLS - 1) / DCOLS;+ if (a & K_LEFT && g.dcol > 0) g.dcol--;+ if (a & K_RIGHT && g.dcol < DCOLS - 1) g.dcol++;+ if (a & K_UP && g.drow > 0) g.drow--;+ if (a & K_DOWN && g.drow < rows - 1) g.drow++;+ while (g.drow > 0 && (g.drow - 1) * DCOLS + g.dcol >= NCARDS) g.dcol--;+ if (g.drow > 0) {+ if (g.drow - 1 < g.dscroll) g.dscroll = g.drow - 1;+ if (g.drow - 1 >= g.dscroll + DROWS_SHOWN) g.dscroll = g.drow - DROWS_SHOWN;+ }+ if (p & K_BACK) {+ if (g.hold >= 0) g.hold = -1;+ else {+ save_write();+ go(SC_TITLE);+ g.sel = 1;+ }+ return;+ }+ if (!ok()) return;+ int card = deck_cursor_card();+ if (card < 0) return;+ if (g.hold < 0) {+ /* pick one: from the deck, or a card not in it */+ if (g.drow == 0) g.hold = 100 + g.dcol;+ else if (deck_has(card) < 0) g.hold = card, g.drow = 0;+ else g.drow = 0, g.dcol = deck_has(card);+ return;+ }+ if (g.hold >= 100) {+ int slot = g.hold - 100;+ if (g.drow == 0) { /* two deck cards: swapped */+ uint8_t v = g.prof.deck[slot];+ g.prof.deck[slot] = g.prof.deck[g.dcol], g.prof.deck[g.dcol] = v;+ } else if (deck_has(card) < 0) {+ g.prof.deck[slot] = (uint8_t)card;+ }+ } else if (g.drow == 0) {+ g.prof.deck[g.dcol] = (uint8_t)g.hold;+ }+ g.hold = -1;+ save_write();+}++/* ------------------------------------------------------------------ the step */+void game_step(uint32_t keys) {+ g.prev = g.keys;+ g.keys = keys;+ g.held_ms = (keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN)) && (keys & (K_LEFT | K_RIGHT | K_UP | K_DOWN)) == (g.prev & (K_LEFT | K_RIGHT | K_UP | K_DOWN))+ ? g.held_ms + 17 : 0;+ g.ms += 17;+ if (g.msg_t > 0) g.msg_t--;+ if (keys & K_HOME) {+ if (g.screen == SC_BATTLE || g.screen == SC_PAUSE) resume_write();+ save_write();+ g.running = false;+ return;+ }+ uint32_t p = pressed(), a = arrows();+ switch (g.screen) {+ case SC_TITLE:+ if (a & K_UP) g.sel = (g.sel + 2) % 3;+ if (a & K_DOWN) g.sel = (g.sel + 1) % 3;+ if (ok()) {+ if (g.sel == 0) {+ if (!g.prof.guide) {+ g.prof.guide = 1;+ save_write();+ go(SC_HELP);+ g.back_to = SC_BATTLE;+ } else {+ start_battle();+ }+ } else if (g.sel == 1) {+ go(SC_DECK);+ g.drow = 0, g.dcol = 0, g.dscroll = 0, g.hold = -1;+ } else {+ go(SC_HELP);+ g.back_to = SC_TITLE;+ }+ }+ break;+ case SC_DECK:+ deck_keys();+ break;+ case SC_HELP:+ if (ok() || (p & K_BACK)) {+ if (g.back_to == SC_BATTLE) start_battle();+ else if (g.back_to == SC_PAUSE) go(SC_PAUSE);+ else go(SC_TITLE), g.sel = 2;+ }+ break;+ case SC_BATTLE:+ battle_keys();+ if (g.screen != SC_BATTLE) break;+ if (++g.steps % 3 == 0) {+ int32_t before = bt.time_ms;+ bool ot = bt.overtime;+ battle_step(&bt);+ if (!ot && bt.overtime) say("Sudden death!");+ else if (!bt.overtime && before > 60000 && bt.time_ms <= 60000) say("60 seconds left");+ if (bt.over) finish_battle();+ }+ break;+ case SC_PAUSE:+ if (g.confirm) {+ if (ok()) {+ /* leaving counts as a loss, as in the game */+ bt.over = 1, bt.winner = 1;+ finish_battle();+ } else if (p & K_BACK) {+ g.confirm = false;+ }+ break;+ }+ if (a & K_UP) g.sel = (g.sel + 2) % 3;+ if (a & K_DOWN) g.sel = (g.sel + 1) % 3;+ if (p & K_BACK) go(SC_BATTLE);+ else if (ok()) {+ if (g.sel == 0) go(SC_BATTLE);+ else if (g.sel == 1) go(SC_HELP), g.back_to = SC_PAUSE;+ else g.confirm = true;+ }+ break;+ case SC_RESULT:+ if (g.ms > 600 && (ok() || (p & K_BACK))) go(SC_TITLE);+ break;+ }+}++/* ------------------------------------------------------------------ drawing */+static void button(int x, int y, int w, int h, const char *s, bool sel) {+ gfx_round_rect(x, y, w, h, 4, sel ? RGB(0xA06A10) : RGB(0x0E1626));+ gfx_round_rect(x + 1, y + 1, w - 2, h - 3, 3, sel ? GOLD : RGB(0x34507E));+ gfx_text_oc(FONT_MID, x + w / 2, y + (h - gfx_line_h(FONT_MID)) / 2, s, WHITE);+}++static void draw_title(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, RGB(0x0A1830));+ gfx_img(IMG_TITLE, 0, 0, 0, false);+ int x = 186, w = 128;+ char t[40];+ int a = arena_of(g.prof.trophies);+ gfx_text_oc(FONT_SMALL, x + w / 2, 12, arena_name(a), RGB(0xC8D8F0));+ snprintf(t, sizeof t, "%ld trophies", (long)g.prof.trophies);+ gfx_text_oc(FONT_MID, x + w / 2, 26, t, GOLD);+ static const char *const items[3] = {"Battle", "Deck", "How to play"};+ for (int i = 0; i < 3; i++) button(x, 62 + i * 40, w, 32, items[i], g.sel == i);+ snprintf(t, sizeof t, "Won %ld Lost %ld", (long)g.prof.wins, (long)g.prof.losses);+ gfx_text_c(FONT_SMALL, x + w / 2, 192, t, RGB(0xA8B8D0));+ gfx_text_c(FONT_SMALL, x + w / 2, 222, "OK choose Home quit", RGB(0x8090B0));+}++static void card_icon(int card, int x, int y, bool sel, bool dim) {+ if (sel) gfx_round_rect(x - 3, y - 3, 42, 51, 4, GOLD);+ else gfx_round_rect(x - 1, y - 1, 38, 47, 3, RGB(0x0E1626));+ gfx_img_dim(CARDS[card].icon, x + 18, y + 22, 0, false, dim ? 20 : 0);+ gfx_img(IMG_DROP_BIG, x + 6, y + 38, 0, false);+ char t[4];+ snprintf(t, sizeof t, "%ld", (long)CARDS[card].cost);+ gfx_text_oc(FONT_NUM, x + 6, y + 34, t, WHITE);+}++static void card_stats(int card, int x, int y) {+ const CardDef *c = &CARDS[card];+ static const char *const rar[4] = {"Common", "Rare", "Epic", "Legendary"};+ char t[96];+ int lvl = card_level(card), idx = card_lvl_index(card);+ snprintf(t, sizeof t, "%s Level %d %ld elixir", rar[c->rarity], lvl, (long)c->cost);+ gfx_text(FONT_SMALL, x, y, t, RGB(0xC8D8F0));+ t[0] = 0;+ if (c->unit != NONE) {+ const UnitDef *u = &UNITS[c->unit];+ int32_t d = u->proj != NONE ? PROJS[u->proj].dmg : u->dmg;+ if (u->flags & U_BOMB) d = u->death_dmg;+ snprintf(t, sizeof t, "HP %ld Damage %ld Hit %ld.%lds%s", (long)lv(u->hp, idx), (long)lv(d, idx), (long)(u->hit_ms / 1000),+ (long)(u->hit_ms % 1000 / 100), c->count > 1 ? "" : "");+ if (c->count > 1) snprintf(t + strlen(t), sizeof t - strlen(t), " x%ld", (long)c->count);+ if (!u->dmg && u->proj == NONE) snprintf(t, sizeof t, "HP %ld Lifetime %lds", (long)lv(u->hp, idx), (long)(u->life_ms / 1000));+ } else if (c->proj != NONE) {+ snprintf(t, sizeof t, "Damage %ld Radius %ld.%ld", (long)lv(PROJS[c->proj].dmg, idx), (long)(c->radius / 1000),+ (long)(c->radius % 1000 / 100));+ } else if (c->area != NONE) {+ const AreaDef *ar = &AREAS[c->area];+ if (ar->dmg) snprintf(t, sizeof t, "Damage %ld Radius %ld.%ld", (long)lv(ar->dmg, idx), (long)(c->radius / 1000), (long)(c->radius % 1000 / 100));+ else if (ar->proj != NONE) snprintf(t, sizeof t, "Damage %ld 3 targets", (long)lv(PROJS[ar->proj].dmg, idx));+ else snprintf(t, sizeof t, "Duration %ld.%lds Radius %ld", (long)((ar->life_ms + ar->life_per_level * idx) / 1000),+ (long)((ar->life_ms + ar->life_per_level * idx) % 1000 / 100), (long)(c->radius / 1000));+ }+ gfx_text(FONT_SMALL, x, y + 11, t, WHITE);+}++static void draw_deck(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, RGB(0x14223E));+ gfx_text_o(FONT_SMALL, 6, 2, "Battle Deck", WHITE);+ int sum = 0;+ for (int k = 0; k < 8; k++) sum += CARDS[g.prof.deck[k]].cost;+ char t[48];+ snprintf(t, sizeof t, "Average Elixir cost: %d.%d", sum / 8, sum * 10 / 8 % 10);+ gfx_text_r(FONT_SMALL, 314, 2, t, PINK);+ for (int k = 0; k < 8; k++)+ if (!(g.drow == 0 && g.dcol == k)) card_icon(g.prof.deck[k], 6 + k * 39, 15, false, false);+ if (g.drow == 0) card_icon(g.prof.deck[g.dcol], 6 + g.dcol * 39, 15, true, false);+ if (g.hold >= 100) gfx_frame_rect(4 + (g.hold - 100) * 39, 13, 40, 49, WHITE);+ int card = deck_cursor_card();+ gfx_fill(0, 63, SCREEN_W, 30, RGB(0x0E1830));+ if (card >= 0) {+ gfx_text_o(FONT_MID, 6, 65, CARDS[card].name, WHITE);+ card_stats(card, 120, 66);+ }+ for (int pass = 0; pass < 2; pass++)+ for (int r = 0; r < DROWS_SHOWN; r++) {+ int row = g.dscroll + r;+ for (int c = 0; c < DCOLS; c++) {+ int i = row * DCOLS + c;+ if (i >= NCARDS) break;+ bool sel = g.drow == row + 1 && g.dcol == c;+ if (sel != (pass == 1)) continue; /* (the chosen one last, its frame on top) */+ card_icon(i, 6 + c * 39, 96 + r * 43, sel, deck_has(i) >= 0);+ if (g.hold == i) gfx_frame_rect(4 + c * 39, 94 + r * 43, 40, 49, WHITE);+ }+ }+ const char *hint = g.hold < 0 ? "OK pick a card arrows move Back done" : "OK put it here Back cancel";+ gfx_fill(0, 228, SCREEN_W, 12, RGB(0x0E1830));+ gfx_text_c(FONT_SMALL, 160, 229, hint, RGB(0xC8D8F0));+}++static void draw_help(void) {+ gfx_fill(0, 0, SCREEN_W, SCREEN_H, RGB(0x14223E));+ gfx_text_oc(FONT_MID, 160, 4, "How to play", GOLD);+ static const char *const lines[] = {+ "Knock down the enemy's towers. A Princess tower is a crown, the King tower is three and wins at once.",+ "Elixir fills up by itself. Each card costs some. You hold four cards; one played, the Next one takes its place.",+ ("1 to 4 (or left, right and OK) picks a card. Arrows move it on the field, OK drops it. Troops and buildings go on "+ "your side, spells anywhere."),+ "3 minutes. In the last minute elixir comes twice as fast. Even crowns at the end: overtime, the first crown wins.",+ "Back pauses. Home keeps the battle and quits."};+ int y = 24;+ for (unsigned i = 0; i < sizeof lines / sizeof lines[0]; i++) y += gfx_wrap(FONT_SMALL, 10, y, 300, lines[i], WHITE) + 6;+ gfx_text_c(FONT_SMALL, 160, 226, "OK continue", RGB(0xC8D8F0));+}++static void draw_pause(void) {+ if (!gfx_rows(40, 140)) return;+ gfx_blend(0, 0, SCREEN_W, 180, BLACK, 14);+ gfx_round_rect(90, 40, 140, 136, 6, PANEL);+ gfx_text_oc(FONT_MID, 160, 46, g.confirm ? "Quit battle?" : "Paused", WHITE);+ if (g.confirm) {+ gfx_wrap(FONT_SMALL, 100, 72, 120, "It counts as a loss. OK quit, Back stay.", WHITE);+ return;+ }+ static const char *const items[3] = {"Resume", "How to play", "Quit battle"};+ for (int i = 0; i < 3; i++) button(100, 70 + i * 34, 120, 28, items[i], g.sel == i);+}++static void draw_result(void) {+ if (!gfx_rows(30, 150)) return;+ gfx_blend(0, 0, SCREEN_W, 180, BLACK, 16);+ const char *t = bt.winner == 0 ? "You win!" : bt.winner == 1 ? "You lose" : "Draw";+ gfx_text_oc(FONT_BIG, 160, 34, t, bt.winner == 0 ? GOLD : bt.winner == 1 ? RED : WHITE);+ for (int i = 0; i < 3; i++) {+ int x = 130 + i * 30;+ if (i < bt.side[0].crowns) gfx_img(IMG_CROWN, x, 92, 0, false);+ else gfx_img_dim(IMG_CROWN, x, 92, 0, false, 24);+ }+ char s[48];+ snprintf(s, sizeof s, "%s%d trophies", g.dtroph > 0 ? "+" : "", g.dtroph);+ gfx_text_oc(FONT_MID, 160, 104, s, g.dtroph > 0 ? GOLD : WHITE);+ int a = arena_of(g.prof.trophies);+ if (a != g.old_arena) {+ snprintf(s, sizeof s, "%s %s", a > g.old_arena ? "Up to" : "Down to", arena_name(a));+ gfx_text_oc(FONT_SMALL, 160, 126, s, RGB(0xC8D8F0));+ }+ if (g.ms > 600) gfx_text_oc(FONT_SMALL, 160, 150, "OK continue", WHITE);+}++static void draw(void) {+ switch (g.screen) {+ case SC_TITLE: draw_title(); break;+ case SC_DECK: draw_deck(); break;+ case SC_HELP: draw_help(); break;+ default:+ view_battle();+ view_hud();+ if (g.screen == SC_PAUSE) draw_pause();+ if (g.screen == SC_RESULT) draw_result();+ }+}++void game_draw(void) {+ if (g.screen == SC_BATTLE || g.screen == SC_PAUSE || g.screen == SC_RESULT) view_prepare();+ gfx_frame(draw);+}diff --git a/games/clashroyale/src/game.h b/games/clashroyale/src/game.hnew file mode 100644index 00000000..c0816510--- /dev/null+++ b/games/clashroyale/src/game.h@@ -0,0 +1,58 @@+/* Clash Royale: the screens around the battle, and what is kept. */+#ifndef CR_GAME_H+#define CR_GAME_H+#include <stdbool.h>+#include <stdint.h>+#include "sim.h"++typedef struct {+ uint8_t deck[8];+ int32_t trophies, best, wins, losses, draws, three;+ uint8_t guide; /* how to play seen */+ uint8_t pad[3];+} Profile;++enum { SC_TITLE, SC_DECK, SC_HELP, SC_BATTLE, SC_PAUSE, SC_RESULT };++typedef struct {+ bool running;+ int screen, back_to; /* back_to: where How to play returns */+ Profile prof;+ uint32_t keys, prev, held_ms; /* keys now, last step's; how long the arrows have been held */+ uint32_t ms; /* time on this screen */+ int sel; /* the menu's choice */+ /* deck */+ int drow, dcol, dscroll, hold; /* hold: a card picked (-1 none), held from the deck (slot + 100) or collection */+ /* battle */+ bool field; /* the cursor on the field (else the hand) */+ int slot, cx, cy; /* the card chosen, the cursor's tile */+ int msg_t;+ const char *msg;+ int steps; /* game steps (60 a second): a battle step each 3 */+ bool confirm; /* pause: quit asked */+ int dtroph; /* the result's trophies */+ int old_arena;+} Game;++extern Game g;+extern Battle bt;++void game_init(void);+void game_step(uint32_t keys); /* 60 a second */+void game_draw(void);+int arena_of(int32_t trophies);+const char *arena_name(int a);++/* view.c: the battle on screen */+void view_load_arena(int a);+void view_prepare(void); /* once a frame, before drawing */+void view_battle(void);+void view_hud(void);++/* save.c */+void save_load(void);+void save_write(void);+bool resume_load(void); /* a battle kept by Home: true when it is back */+void resume_write(void);+void resume_clear(void);+#endifdiff --git a/games/clashroyale/src/gfx.c b/games/clashroyale/src/gfx.cnew file mode 100644index 00000000..1805ccfa--- /dev/null+++ b/games/clashroyale/src/gfx.c@@ -0,0 +1,270 @@+/* 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);+}++void gfx_round_rect(int x, int y, int w, int h, int r, uint16_t c) {+ gfx_fill(x + r, y, w - 2 * r, h, c);+ for (int i = 0; i < r; i++) {+ int dy = r - i, dx = 0;+ while ((dx + 1) * (dx + 1) + dy * dy <= r * r + r) dx++;+ int inset = r - dx;+ gfx_fill(x + inset, y + i, r - inset, 1, c);+ gfx_fill(x + w - r, y + i, r - inset, 1, c);+ gfx_fill(x + inset, y + h - 1 - i, r - inset, 1, c);+ gfx_fill(x + w - r, y + h - 1 - i, r - inset, 1, c);+ }+ gfx_fill(x, y + r, r, h - 2 * r, c);+ gfx_fill(x + w - r, y + r, r, h - 2 * r, c);+}++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;+ int y0 = cy - ry > gfx_y0 ? cy - ry : gfx_y0, y1 = cy + ry < gfx_y0 + BAND_H - 1 ? cy + ry : gfx_y0 + BAND_H - 1;+ for (int y = y0; y <= y1; y++) {+ int dy = y - cy;+ /* half width at this row: rx * sqrt(1 - dy^2/ry^2) */+ int32_t q = (int32_t)rx * rx * (ry * ry - dy * dy) / (ry * ry);+ int hw = 0;+ while ((hw + 1) * (hw + 1) <= q) hw++;+ if (a >= 32)+ gfx_fill(cx - hw, y, 2 * hw + 1, 1, c);+ else+ gfx_blend(cx - hw, y, 2 * hw + 1, 1, c, a);+ }+}++void gfx_ring(int cx, int cy, int rx, int ry, int t, uint16_t c, int a) {+ if (rx <= 0 || ry <= 0 || !gfx_rows(cy - ry, 2 * ry + 1)) return;+ int y0 = cy - ry > gfx_y0 ? cy - ry : gfx_y0, y1 = cy + ry < gfx_y0 + BAND_H - 1 ? cy + ry : gfx_y0 + BAND_H - 1;+ int irx = rx - t, iry = ry - t;+ for (int y = y0; y <= y1; y++) {+ int dy = y - cy;+ int32_t q = (int32_t)rx * rx * (ry * ry - dy * dy) / (ry * ry);+ int hw = 0, iw = -1;+ while ((hw + 1) * (hw + 1) <= q) hw++;+ if (irx > 0 && iry > 0 && dy * dy < iry * iry) {+ int32_t qi = (int32_t)irx * irx * (iry * iry - dy * dy) / (iry * iry);+ iw = 0;+ while ((iw + 1) * (iw + 1) <= qi) iw++;+ }+ if (iw < 0) {+ gfx_blend(cx - hw, y, 2 * hw + 1, 1, c, a);+ } else {+ gfx_blend(cx - hw, y, hw - iw, 1, c, a);+ gfx_blend(cx + iw + 1, y, hw - iw, 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 ? y1 - y0 : y0 - y1;+ int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, err = dx - dy;+ for (int n = 0; n < 400; n++) {+ if (y0 >= gfx_y0 && y0 < gfx_y0 + BAND_H && (unsigned)x0 < SCREEN_W) gfx_band[(y0 - gfx_y0) * SCREEN_W + x0] = c;+ if (x0 == x1 && y0 == y1) break;+ int e2 = 2 * err;+ if (e2 > -dy) err -= dy, x0 += sx;+ if (e2 < dx) err += dx, y0 += sy;+ }+}++/* ------------------------------------------------------------------ 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 = gfx_rows(y, f[0] + 2);+ 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) + 4)) 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 i = 0; i < 8; i++) gfx_text(font, x + d[i][0], y + d[i][1], s, RGB(0x1A1420));+ gfx_text(font, x, y + 2, s, RGB(0x1A1420));+ 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_wrap(int font, int x, int y, int w, const char *s, uint16_t c) {+ int lh = gfx_line_h(font), y0 = y;+ char line[96];+ while (*s) {+ int n = 0, last_space = -1;+ while (s[n] && s[n] != '\n') {+ if (s[n] == ' ') last_space = n;+ if (n < (int)sizeof line - 1) line[n] = s[n];+ line[n + 1 < (int)sizeof line ? n + 1 : (int)sizeof line - 1] = 0;+ if (gfx_text_w(font, line) > w && last_space > 0) {+ n = last_space;+ break;+ }+ n++;+ }+ int m = n < (int)sizeof line - 1 ? n : (int)sizeof line - 1;+ for (int i = 0; i < m; i++) line[i] = s[i];+ line[m] = 0;+ gfx_text(font, x, y, line, c);+ y += lh;+ s += n;+ while (*s == ' ' || *s == '\n') s++;+ }+ return y - y0;+}++/* ------------------------------------------------------------------ pictures */+static const uint8_t *img_at(int id) {+ const uint8_t *s = section(SEC_IMGS);+ return s + rd32(s + 4 + 4 * id);+}+int gfx_img_w(int id) { return (int)rd16(img_at(id)); }+int gfx_img_h(int id) { return (int)rd16(img_at(id) + 2); }++void gfx_img_box(int id, bool mirror, int *x0, int *y0, int *w, int *h) {+ const uint8_t *p = img_at(id);+ *w = (int)rd16(p), *h = (int)rd16(p + 2);+ int ax = rds16(p + 4), ay = rds16(p + 6);+ *x0 = mirror ? ax - *w + 1 : -ax;+ *y0 = -ay;+}++/* mode 0: opaque colours; mode 1: 6-bit colours with 2 bits of alpha (a quarter to all) */+static void img_draw(int id, int x, int y, int team, bool mirror, int dim, uint16_t tint, int ta) {+ const uint8_t *p = img_at(id);+ int h = (int)rd16(p + 2), ax = rds16(p + 4), ay = rds16(p + 6), mode = p[8];+ int top = y - ay;+ if (!gfx_rows(top, h)) return;+ const uint8_t *pal = cr_bin + rd32(p + (team ? 16 : 12)) + 2;+ int r0 = gfx_y0 > top ? gfx_y0 - top : 0, r1 = top + h < gfx_y0 + BAND_H ? h : gfx_y0 + BAND_H - top;+ int left = mirror ? x + ax : x - ax; /* mirrored: column c lands at left - c */+ for (int r = r0; r < r1; r++) {+ const uint8_t *q = p + rd16(p + 20 + 2 * r);+ uint16_t *d = gfx_band + (top + r - gfx_y0) * SCREEN_W;+ int runs = *q++;+ while (runs--) {+ int cx = q[0], n = q[1];+ q += 2;+ for (int i = 0; i < n; i++) {+ int v = q[i];+ int sx = mirror ? left - (cx + i) : left + cx + i;+ if ((unsigned)sx >= SCREEN_W) continue;+ uint16_t c;+ int a = 32;+ if (mode) {+ c = (uint16_t)rd16(pal + 2 * (v & 63));+ a = ((v >> 6) + 1) * 8;+ } else {+ c = (uint16_t)rd16(pal + 2 * v);+ }+ if (dim) c = gfx_mix(BLACK, c, dim);+ if (ta) c = gfx_mix(tint, c, ta);+ d[sx] = a >= 32 ? c : gfx_mix(c, d[sx], a);+ }+ q += n;+ }+ }+}++void gfx_img(int id, int x, int y, int team, bool mirror) { img_draw(id, x, y, team, mirror, 0, 0, 0); }+void gfx_img_dim(int id, int x, int y, int team, bool mirror, int dim) { img_draw(id, x, y, team, mirror, dim, 0, 0); }+void gfx_img_tint(int id, int x, int y, int team, bool mirror, uint16_t c, int a) { img_draw(id, x, y, team, mirror, 0, c, a); }++void gfx_arena(const uint8_t *idx, const uint8_t *pal, int y0, int rows) {+ int a = gfx_y0 > y0 ? gfx_y0 : y0, b = gfx_y0 + BAND_H < y0 + rows ? gfx_y0 + BAND_H : y0 + rows;+ for (int y = a; y < b; y++) {+ const uint8_t *s = idx + (y - y0) * SCREEN_W;+ uint16_t *d = gfx_band + (y - gfx_y0) * SCREEN_W;+ for (int x = 0; x < SCREEN_W; x++) d[x] = (uint16_t)(pal[2 * s[x]] | pal[2 * s[x] + 1] << 8);+ }+}diff --git a/games/clashroyale/src/gfx.h b/games/clashroyale/src/gfx.hnew file mode 100644index 00000000..7486b918--- /dev/null+++ b/games/clashroyale/src/gfx.h@@ -0,0 +1,53 @@+/* Clash Royale: drawing, a band of 16 rows at a time (no frame buffer fits in the RAM apps get).+ *+ * For each band the screen's whole drawing function runs, everything clipped to the band, then the band is+ * pushed to the screen. */+#ifndef CR_GFX_H+#define CR_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);+void gfx_frame(void (*draw)(void));+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);+void gfx_round_rect(int x, int y, int w, int h, int r, uint16_t c);+/* an ellipse (rx, ry) blended a / 32; filled, or its ring of width t */+void gfx_ellipse(int cx, int cy, int rx, int ry, uint16_t c, int a);+void gfx_ring(int cx, int cy, int rx, int ry, int t, uint16_t c, int a);+void gfx_line(int x0, int y0, int x1, int y1, uint16_t c);++/* text in data.bin's fonts (FONT_*), with a dark outline when shadow */+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);+void gfx_text_r(int font, int rx, int y, const char *s, uint16_t c);+void gfx_text_o(int font, int x, int y, const char *s, uint16_t c); /* outlined */+void gfx_text_oc(int font, int cx, int y, const char *s, uint16_t c);+/* plain words wrapped in w pixels; returns the height used */+int gfx_wrap(int font, int x, int y, int w, const char *s, uint16_t c);++/* data.bin's pictures (IMG_*): drawn with their anchor at (x, y), red palette for team 1, mirrored */+void gfx_img(int id, int x, int y, int team, bool mirror);+void gfx_img_dim(int id, int x, int y, int team, bool mirror, int dim); /* dim: 0 none to 32 black */+void gfx_img_tint(int id, int x, int y, int team, bool mirror, uint16_t c, int a);+int gfx_img_w(int id);+int gfx_img_h(int id);+void gfx_img_box(int id, bool mirror, int *x0, int *y0, int *w, int *h); /* relative to the anchor */++/* the arena: 320 x 180 colour indices (unpacked in RAM) and its 256 colours */+void gfx_arena(const uint8_t *idx, const uint8_t *pal, int y0, int rows);+#endifdiff --git a/games/clashroyale/src/icon.png b/games/clashroyale/src/icon.pngnew file mode 100644index 00000000..6c2ddcbdBinary files /dev/null and b/games/clashroyale/src/icon.png differdiff --git a/games/clashroyale/src/ids.h b/games/clashroyale/src/ids.hnew file mode 100644index 00000000..5ada5d33--- /dev/null+++ b/games/clashroyale/src/ids.h@@ -0,0 +1,176 @@+/* made by tools/pack.py */+#ifndef CR_IDS_H+#define CR_IDS_H+#define NSETS 39+#define NUNITS 37+#define NPROJS 19+#define NAREAS 4+#define NCARDS 41+#define NGLOBALS 25+#define NBOTDECKS 14+#define UN_KINGTOWER 0+#define UN_PRINCESSTOWER 1+#define UN_KNIGHT 2+#define UN_ARCHER 3+#define UN_GOBLIN 4+#define UN_GIANT 5+#define UN_PEKKA 6+#define UN_MINION 7+#define UN_BALLOON 8+#define UN_WITCH 9+#define UN_BARBARIAN 10+#define UN_GOLEM 11+#define UN_SKELETON 12+#define UN_VALKYRIE 13+#define UN_BOMBER 14+#define UN_MUSKETEER 15+#define UN_BABYDRAGON 16+#define UN_PRINCE 17+#define UN_WIZARD 18+#define UN_MINIPEKKA 19+#define UN_SPEARGOBLIN 20+#define UN_GIANTSKELETON 21+#define UN_HOGRIDER 22+#define UN_CANNON 23+#define UN_GOBLINHUT 24+#define UN_MORTAR 25+#define UN_INFERNOTOWER 26+#define UN_BOMBTOWER 27+#define UN_BARBARIANHUT 28+#define UN_TESLA 29+#define UN_ELIXIRCOLLECTOR 30+#define UN_XBOW 31+#define UN_TOMBSTONE 32+#define UN_PRINCESSB 33+#define UN_BALLOONBOMB 34+#define UN_GOLEMITE 35+#define UN_GIANTSKELETONBOMB 36+#define PR_KINGPROJECTILE 0+#define PR_PRINCESSPROJECTILE 1+#define PR_ARCHERARROW 2+#define PR_MINIONSPIT 3+#define PR_WITCHPROJECTILE 4+#define PR_BOMBSKELETONPROJECTILE 5+#define PR_MUSKETEERPROJECTILE 6+#define PR_BABYDRAGONPROJECTILE 7+#define PR_CHR_WIZARDPROJECTILE 8+#define PR_SPEARGOBLINPROJECTILE 9+#define PR_TOWERCANNONBALL 10+#define PR_MORTARPROJECTILE 11+#define PR_BOMBTOWERPROJECTILE 12+#define PR_XBOW_PROJECTILE 13+#define PR_FIREBALLSPELL 14+#define PR_ARROWSSPELLDECO 15+#define PR_ROCKETSPELL 16+#define PR_GOBLINBARRELSPELL 17+#define PR_LIGHNINGSPELL 18+#define AR_RAGE 0+#define AR_FREEZE 1+#define AR_LIGHTNING 2+#define AR_ZAP 3+#define CA_KNIGHT 0+#define CA_ARCHER 1+#define CA_GOBLINS 2+#define CA_GIANT 3+#define CA_PEKKA 4+#define CA_MINIONS 5+#define CA_BALLOON 6+#define CA_WITCH 7+#define CA_BARBARIANS 8+#define CA_GOLEM 9+#define CA_SKELETONS 10+#define CA_VALKYRIE 11+#define CA_SKELETONARMY 12+#define CA_BOMBER 13+#define CA_MUSKETEER 14+#define CA_BABYDRAGON 15+#define CA_PRINCE 16+#define CA_WIZARD 17+#define CA_MINIPEKKA 18+#define CA_SPEARGOBLINS 19+#define CA_GIANTSKELETON 20+#define CA_HOGRIDER 21+#define CA_MINIONHORDE 22+#define CA_CANNON 23+#define CA_GOBLINHUT 24+#define CA_MORTAR 25+#define CA_INFERNOTOWER 26+#define CA_BOMBTOWER 27+#define CA_BARBARIANHUT 28+#define CA_TESLA 29+#define CA_ELIXIR_COLLECTOR 30+#define CA_XBOW 31+#define CA_TOMBSTONE 32+#define CA_FIREBALL 33+#define CA_ARROWS 34+#define CA_RAGE 35+#define CA_ROCKET 36+#define CA_GOBLINBARREL 37+#define CA_FREEZE 38+#define CA_LIGHTNING 39+#define CA_ZAP 40+#define SET_KNIGHT 0+#define SET_ARCHER 1+#define SET_GOBLIN 2+#define SET_GIANT 3+#define SET_PEKKA 4+#define SET_MINION 5+#define SET_BALLOON 6+#define SET_WITCH 7+#define SET_BARBARIAN 8+#define SET_GOLEM 9+#define SET_SKELETON 10+#define SET_VALKYRIE 11+#define SET_BOMBER 12+#define SET_MUSKETEER 13+#define SET_BABYDRAGON 14+#define SET_PRINCE 15+#define SET_WIZARD 16+#define SET_MINIPEKKA 17+#define SET_SPEARGOBLIN 18+#define SET_GIANTSKELETON 19+#define SET_HOGRIDER 20+#define SET_PRINCESSB 21+#define SET_GOLEMITE 22+#define SET_KINGTOWER 23+#define SET_PRINCESSTOWER 24+#define SET_PRINCESSTOWERTOP 25+#define SET_CANNON 26+#define SET_GOBLINHUT 27+#define SET_MORTAR 28+#define SET_INFERNOTOWER 29+#define SET_BOMBTOWER 30+#define SET_BOMBTOWERTOP 31+#define SET_BARBARIANHUT 32+#define SET_TESLA 33+#define SET_ELIXIRCOLLECTOR 34+#define SET_XBOW 35+#define SET_TOMBSTONE 36+#define SET_BALLOONBOMB 37+#define SET_GIANTSKELETONBOMB 38+#define G_MAX_MANA 0+#define G_MANA_REGEN_MS 1+#define G_MANA_REGEN_MS_END 2+#define G_MANA_REGEN_MS_OVERTIME 3+#define G_MANA_SPEED_UP_WHEN_REMAINING_SECONDS 4+#define G_START_MANA 5+#define G_NEXT_SPELL_COOLDOWN_MILLISECONDS 6+#define G_NEXT_SPELL_COOLDOWN_MILLISECONDS_BOOST 7+#define G_NEXT_SPELL_COOLDOWN_MILLISECONDS_OVERTIME 8+#define G_DAMAGE_INCREASE_PERCENT_PER_SPELL_LEVEL 9+#define G_HITPOINT_INCREASE_PERCENT_PER_SPELL_LEVEL 10+#define G_DAMAGE_INCREASE_PERCENT_PER_KING_LEVEL 11+#define G_HITPOINT_INCREASE_PERCENT_PER_KING_LEVEL 12+#define G_DAMAGE_INCREASE_PERCENT_PER_TOWER_LEVEL 13+#define G_HITPOINT_INCREASE_PERCENT_PER_TOWER_LEVEL 14+#define G_MELEE_RANGE_LIMIT 15+#define G_REDUCED_TOWER_DAMAGE_PERCENT 16+#define G_KING_ACTIVATE_TIME_MS 17+#define G_TOURNAMENT_MAX_EXP_LEVEL 18+#define G_TOURNAMENT_MAX_COMMON_LEVEL 19+#define G_TOURNAMENT_MAX_RARE_LEVEL 20+#define G_TOURNAMENT_MAX_EPIC_LEVEL 21+#define G_TOURNAMENT_MATCH_LENGTH_SECONDS 22+#define G_MATCH_LENGTH 23+#define G_OVERTIME_SECONDS 24+#endifdiff --git a/games/clashroyale/src/main.c b/games/clashroyale/src/main.cnew file mode 100644index 00000000..b2c3e136--- /dev/null+++ b/games/clashroyale/src/main.c@@ -0,0 +1,53 @@+/* Clash Royale for the NumWorks calculator.+ *+ * Inspired by Clash Royale by Supercell, not affiliated with Supercell.+ * 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"))) = "Clash Royale";+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;+extern const uint8_t cr_data[];+const uint8_t *cr_bin;++uint32_t perf_frames __attribute__((used)); /* read by tools/emu.py */+uint32_t perf_updates __attribute__((used));++#ifdef CR_DEMO+extern bool bot_plays_both; /* (make EXTRA=-DCR_DEMO: a bot plays your side too, for timing many units) */+#endif++int main(void) {+ uint16_t band[SCREEN_W * BAND_H]; /* (here: on the stack, out of the RAM apps get) */+#ifdef CR_DEMO+ bot_plays_both = true;+#endif+ gfx_set_band_memory(band);+ plat_begin();+ cr_bin = cr_data;+ game_init();+ uint32_t next = plat_millis() * 3; /* in thirds of a millisecond: 50 a step, 60 steps a second */+ while (g.running) {+ /* the game's steps: drawn when caught up (at most 6 steps, two battle steps, for a drawing) */+ int n = 0;+ uint32_t now = plat_millis() * 3;+ while ((int32_t)(now - next) >= 0 && n < 6 && g.running) {+ game_step(plat_keys());+ perf_updates++;+ next += 50;+ 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();+}+#endifdiff --git a/games/clashroyale/src/plat.h b/games/clashroyale/src/plat.hnew file mode 100644index 00000000..4fc74e86--- /dev/null+++ b/games/clashroyale/src/plat.h@@ -0,0 +1,42 @@+/* Clash Royale: 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 CR_PLAT_H+#define CR_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 */+ K_HOME = 1 << 6, /* Home, On/Off: keep the battle and quit */+ K_DEL = 1 << 7, /* backspace */+ 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);+#endifdiff --git a/games/clashroyale/src/plat_eadk.c b/games/clashroyale/src/plat_eadk.cnew file mode 100644index 00000000..52991778--- /dev/null+++ b/games/clashroyale/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/clashroyale/src/plat_host.c b/games/clashroyale/src/plat_host.cnew file mode 100644index 00000000..f3f5a8c5--- /dev/null+++ b/games/clashroyale/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/clashroyale/src/res.h b/games/clashroyale/src/res.hnew file mode 100644index 00000000..2cde095c--- /dev/null+++ b/games/clashroyale/src/res.h@@ -0,0 +1,14 @@+/* Clash Royale: data.bin (tools/pack.py), read where it lies in flash. */+#ifndef CR_RES_H+#define CR_RES_H+#include <stdint.h>+#include "data.h"++extern const uint8_t *cr_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 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 cr_bin + rd32(cr_bin + 8 + 4 * s); }+#endifdiff --git a/games/clashroyale/src/save.c b/games/clashroyale/src/save.cnew file mode 100644index 00000000..604ec5a8--- /dev/null+++ b/games/clashroyale/src/save.c@@ -0,0 +1,221 @@+/* Saves: the profile (clashroyale.sav: the deck, trophies and tallies), the battle as it was when Home quit+ * (crresume.sav, packed, read once on the next start), and a copy of the profile in a Python script: installing+ * apps from the NumWorks website keeps only Python scripts, so the profile comes back from it when the file itself+ * is gone. The copy is a comment line "#>name:base64" (the way NumPlay and its big games keep theirs). */+#include <stddef.h>+#include <string.h>+#ifdef DEBUG_RESUME+#include <stdio.h>+#endif+#include "../../common/np_lz.h"+#include "data.h"+#include "game.h"+#include "plat.h"++#define SAVE_NAME "clashroyale.sav"+#define RESUME_NAME "crresume.sav"+#define COPY_NAME "clashroyale_saves.py"+#define MAGIC 0x31595243u /* "CRY1" */+#define VERSION 1++typedef struct {+ uint32_t magic;+ uint16_t version, size;+ Profile p;+ uint32_t sum; /* FNV-1a of what is before it */+} SaveFile;++static uint32_t fnv(const void *d, uint32_t n) {+ const uint8_t *p = d;+ uint32_t h = 2166136261u;+ for (uint32_t i = 0; i < n; i++) h = (h ^ p[i]) * 16777619u;+ return h;+}++static const char copy_head[] = "# Clash Royale's saves: keep this file\n";+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";++static void copy_write(void) {+ uint32_t len;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ plat_remove(COPY_NAME);+ if (!d || !len) return;+ uint32_t nl = (uint32_t)strlen(SAVE_NAME);+ uint32_t total = 1 + (sizeof copy_head - 1) + 2 + nl + 1 + (len + 2) / 3 * 4 + 1 + 1;+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;+ if (!o) return;+ d = plat_load(SAVE_NAME, &len); /* (the storage may have moved) */+ if (!d) {+ plat_remove(COPY_NAME);+ return;+ }+ *p++ = 0; /* (the script's status byte: not imported) */+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;+ *p++ = '#', *p++ = '>';+ memcpy(p, SAVE_NAME, nl), p += nl;+ *p++ = ':';+ for (uint32_t i = 0; i < len; i += 3, p += 4) {+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's+ * launcher/src/storage.c) */+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);+ p[0] = (uint8_t)b64[v >> 18 & 63];+ p[1] = (uint8_t)b64[v >> 12 & 63];+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';+ }+ *p++ = '\n';+ *p++ = 0;+ plat_reserved(COPY_NAME, (uint32_t)(p - o));+}++static int b64_value(uint8_t c) {+ for (int i = 0; i < 64; i++)+ if ((uint8_t)b64[i] == c) return i;+ return -1;+}++/* the profile from the copy, into out (sizeof SaveFile); false if there is none */+static bool copy_read(uint8_t *out) {+ uint32_t n, nl = (uint32_t)strlen(SAVE_NAME);+ const uint8_t *c = plat_load(COPY_NAME, &n);+ if (!c) return false;+ for (uint32_t i = 0; i + nl + 3 <= n; i++) {+ if (c[i] != '#' || c[i + 1] != '>' || memcmp(c + i + 2, SAVE_NAME, nl) || c[i + 2 + nl] != ':') continue;+ const uint8_t *l = c + i + 3 + nl;+ uint32_t m = 0;+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;+ if (m % 4 || m / 4 * 3 - (l[m - 1] == '=') - (l[m - 2] == '=') != sizeof(SaveFile)) return false;+ uint32_t o = 0;+ for (uint32_t k = 0; k < m; k += 4) {+ int v[4];+ for (int j = 0; j < 4; j++) {+ v[j] = l[k + j] == '=' ? 0 : b64_value(l[k + j]);+ if (v[j] < 0) return false;+ }+ uint32_t w = (uint32_t)(v[0] << 18 | v[1] << 12 | v[2] << 6 | v[3]);+ if (o < sizeof(SaveFile)) out[o++] = (uint8_t)(w >> 16);+ if (o < sizeof(SaveFile)) out[o++] = (uint8_t)(w >> 8);+ if (o < sizeof(SaveFile)) out[o++] = (uint8_t)w;+ }+ return true;+ }+ return false;+}++static bool profile_ok(const SaveFile *s) {+ if (s->magic != MAGIC || s->version != VERSION || s->size != sizeof(SaveFile)) return false;+ if (s->sum != fnv(s, offsetof(SaveFile, sum))) return false;+ for (int k = 0; k < 8; k++) {+ if (s->p.deck[k] >= NCARDS) return false;+ for (int j = 0; j < k; j++)+ if (s->p.deck[j] == s->p.deck[k]) return false;+ }+ return s->p.trophies >= 0 && s->p.trophies < 100000;+}++void save_load(void) {+ uint32_t len;+ SaveFile s;+ const uint8_t *d = plat_load(SAVE_NAME, &len);+ bool ok = false;+ if (d && len == sizeof s) {+ memcpy(&s, d, sizeof s);+ ok = profile_ok(&s);+ }+ if (!ok) {+ /* the copy, after the app was installed again */+ uint8_t buf[sizeof(SaveFile)];+ if (copy_read(buf)) {+ memcpy(&s, buf, sizeof s);+ ok = profile_ok(&s);+ if (ok) plat_save(SAVE_NAME, &s, sizeof s);+ }+ }+ if (ok) g.prof = s.p;+}++void save_write(void) {+ SaveFile s;+ memset(&s, 0, sizeof s);+ s.magic = MAGIC, s.version = VERSION, s.size = sizeof s;+ s.p = g.prof;+ s.sum = fnv(&s, offsetof(SaveFile, sum));+ uint32_t len;+ const uint8_t *old = plat_load(SAVE_NAME, &len);+ if (old && len == sizeof s && !memcmp(old, &s, sizeof s)) return;+ if (plat_save(SAVE_NAME, &s, sizeof s)) copy_write();+}++/* ------------------------------------------------------------------ the battle Home kept */+void resume_write(void) {+ uint16_t table[NP_LZ_HASH]; /* (8 KB of stack: Home comes from the main loop, little is on it) */+ bt.magic = 0x31424352u, bt.size = sizeof bt;+ uint32_t n = np_lz_pack((const uint8_t *)&bt, sizeof bt, NULL, table);+#ifdef DEBUG_RESUME+ printf("resume_write: %u packed to %u\n", (unsigned)sizeof bt, n);+#endif+ plat_remove(RESUME_NAME);+ uint8_t *o = plat_reserve(RESUME_NAME, n + 8);+ if (!o) return;+ uint32_t head[2] = {fnv(&bt, sizeof bt), (uint32_t)sizeof bt};+ memcpy(o, head, 8);+ np_lz_pack((const uint8_t *)&bt, sizeof bt, o + 8, table);+ plat_reserved(RESUME_NAME, n + 8);+}++void resume_clear(void) { plat_remove(RESUME_NAME); }++/* a kept battle that can be played on: every index and number in its range */+static bool battle_valid(const Battle *b) {+ if (b->magic != 0x31424352u || b->size != sizeof *b || b->over || b->arena >= NARENAS) return false;+ if (b->time_ms < 0 || b->time_ms > 600000) return false;+ for (int t = 0; t < 2; t++) {+ const Side *s = &b->side[t];+ if (s->nqueue > 8 || s->elixir < 0 || s->elixir > 10 || s->crowns > 3) return false;+ for (int k = 0; k < 8; k++)+ if (s->deck[k] >= NCARDS || (k < s->nqueue && s->queue[k] >= NCARDS)) return false;+ for (int k = 0; k < 4; k++)+ if (s->hand[k] != NONE && s->hand[k] >= NCARDS) return false;+ int16_t tw[3] = {s->king, s->princess[0], s->princess[1]};+ for (int k = 0; k < 3; k++)+ if (tw[k] >= MAXE) return false;+ if (s->king < 0) return false;+ }+ for (int i = 0; i < MAXE; i++) {+ const Ent *e = &b->e[i];+ if (e->used > 1 || (e->used && (e->type >= NUNITS || e->team > 1 || e->lvl > 15 || e->face > 7 || e->anim > 2))) return false;+ if (e->used && (e->x < -2000 || e->x > ARENA_X + 2000 || e->y < -2000 || e->y > ARENA_Y + 2000)) return false;+ if (e->target >= MAXE) return false;+ }+ for (int i = 0; i < MAXP; i++) {+ const Proj *p = &b->p[i];+ if (p->used > 1 || (p->used && (p->type >= NPROJS || p->team > 1 || p->lvl > 15 || p->target >= MAXE))) return false;+ }+ for (int i = 0; i < MAXA; i++) {+ const Area *a = &b->a[i];+ if (a->used > 1 || (a->used && (a->type >= NAREAS || a->team > 1 || a->lvl > 15 || a->hits > 4))) return false;+ }+ for (int i = 0; i < MAXFX; i++)+ if (b->fx[i].used > 1 || (b->fx[i].used && (b->fx[i].kind > FX_TEXT || b->fx[i].len <= 0))) return false;+ return true;+}++bool resume_load(void) {+ uint32_t len;+ const uint8_t *d = plat_load(RESUME_NAME, &len);+ if (!d) return false;+ bool ok = false;+ if (len > 8) {+ uint32_t head[2];+ memcpy(head, d, 8);+ /* (straight into the battle: nothing else uses it yet) */+ int32_t un = head[1] == sizeof bt ? np_lz_unpack(d + 8, len - 8, (uint8_t *)&bt, sizeof bt) : -2;+ ok = un == (int32_t)sizeof bt && fnv(&bt, sizeof bt) == head[0] && battle_valid(&bt);+#ifdef DEBUG_RESUME+ printf("resume: size %u/%u unpacked %d fnv %d valid %d\n", head[1], (unsigned)sizeof bt, un, fnv(&bt, sizeof bt) == head[0], battle_valid(&bt));+#endif+ if (!ok) memset(&bt, 0, sizeof bt);+ }+ plat_remove(RESUME_NAME);+ return ok;+}diff --git a/games/clashroyale/src/sim.c b/games/clashroyale/src/sim.cnew file mode 100644index 00000000..62e6daca--- /dev/null+++ b/games/clashroyale/src/sim.c@@ -0,0 +1,902 @@+/* The battle (sim.h): towers, elixir, the cards, and every unit's step, at the game's numbers (tables.c). */+#include <string.h>+#include "sim.h"++/* DAMAGE/HITPOINT_INCREASE_PERCENT_PER_SPELL_LEVEL = 10: each level the last * 110 / 100, rounded down */+const int32_t LEVEL_MULT[16] = {100, 110, 121, 133, 146, 160, 176, 193, 212, 233, 256, 281, 309, 339, 372, 409};++static int32_t compound(int pct, int levels) {+ int32_t m = 100;+ for (int i = 1; i < levels; i++) m = m * (100 + pct) / 100;+ return m;+}+int32_t king_mult(void) { return compound(GL(HITPOINT_INCREASE_PERCENT_PER_KING_LEVEL), GL(TOURNAMENT_MAX_EXP_LEVEL)); }+int32_t tower_mult(void) { return compound(GL(HITPOINT_INCREASE_PERCENT_PER_TOWER_LEVEL), GL(TOURNAMENT_MAX_EXP_LEVEL)); }++int card_level(int card) {+ switch (CARDS[card].rarity) {+ case R_COMMON: return GL(TOURNAMENT_MAX_COMMON_LEVEL);+ case R_RARE: return GL(TOURNAMENT_MAX_RARE_LEVEL);+ case R_EPIC: return GL(TOURNAMENT_MAX_EPIC_LEVEL);+ default: return 1;+ }+}+int card_lvl_index(int card) { return card_level(card) - 1; }+int32_t lv(int32_t v, int idx) { return v * LEVEL_MULT[idx < 0 ? 0 : idx > 15 ? 15 : idx] / 100; }++uint32_t sim_rand(uint32_t *s) {+ uint32_t x = *s ? *s : 0x9E3779B9u;+ x ^= x << 13, x ^= x >> 17, x ^= x << 5;+ return *s = x;+}+static int32_t rnd(Battle *b, int32_t n) { return n > 0 ? (int32_t)(sim_rand(&b->rng) % (uint32_t)n) : 0; }++int32_t isqrt64(int64_t v) {+ if (v <= 0) return 0;+ uint64_t r = 0, bit = (uint64_t)1 << 62, n = (uint64_t)v;+ while (bit > n) bit >>= 2;+ while (bit) {+ if (n >= r + bit) n -= r + bit, r = (r >> 1) + bit;+ else r >>= 1;+ bit >>= 2;+ }+ return (int32_t)r;+}+int32_t dist(int32_t ax, int32_t ay, int32_t bx, int32_t by) {+ int64_t dx = ax - bx, dy = ay - by;+ return isqrt64(dx * dx + dy * dy);+}++bool ent_alive(const Battle *b, int i) { return i >= 0 && i < MAXE && b->e[i].used && b->e[i].hp > 0; }+bool ent_flying(const Ent *e) { return (UNITS[e->type].flags & U_FLY) != 0; }+static const UnitDef *def(const Ent *e) { return &UNITS[e->type]; }+static bool is_building(const Ent *e) { return (def(e)->flags & U_BUILDING) != 0; }++/* ------------------------------------------------------------------ the arena's ground (locations' Map) */+static bool on_bridge(int32_t y) { return (y >= 2500 && y < 4500) || (y >= 13500 && y < 15500); }+static bool water(int32_t x, int32_t y) { return x >= RIVER_X0 && x < RIVER_X1 && !on_bridge(y); }+static bool blocked(int32_t x, int32_t y) {+ if (x < 0 || x >= ARENA_X || y < 0 || y >= ARENA_Y) return true;+ if ((x < 1000 || x >= 31000) && (y < 6000 || y >= 12000)) return true; /* behind the King towers */+ if (((x >= 14000 && x < 15000) || (x >= 17000 && x < 18000)) && (y < 1000 || y >= 17000)) return true;+ return false;+}+static int32_t bridge_y(int32_t y) { return y < ARENA_Y / 2 ? 3500 : 14500; }+static int side_of(int32_t x) { return x < (RIVER_X0 + RIVER_X1) / 2 ? 0 : 1; }++/* ------------------------------------------------------------------ entities */+static void fx_add(Battle *b, int kind, int team, int32_t x, int32_t y, int size, int len) {+ for (int i = 0; i < MAXFX; i++)+ if (!b->fx[i].used) {+ b->fx[i] = (Fx){1, (uint8_t)kind, (uint8_t)team, (uint8_t)size, (int16_t)(x / 100), (int16_t)(y / 100), 0, (int16_t)len};+ return;+ }+}++int battle_spawn(Battle *b, int type, int team, int lvl, int32_t x, int32_t y, int32_t deploy) {+ if (type < 0 || type >= NUNITS) return -1;+ for (int i = 0; i < MAXE; i++) {+ if (b->e[i].used) continue;+ const UnitDef *d = &UNITS[type];+ Ent *e = &b->e[i];+ memset(e, 0, sizeof *e);+ e->used = 1, e->type = (uint8_t)type, e->team = (uint8_t)team, e->lvl = (uint8_t)lvl;+ e->x = x, e->y = y;+ e->maxhp = e->hp = d->flags & U_BOMB ? 1 : lv(d->hp, lvl);+ e->dmg = d->proj != NONE ? lv(PROJS[d->proj].dmg, lvl) : lv(d->dmg, lvl);+ e->deploy = deploy;+ e->target = -1;+ e->gen = ++b->gen;+ e->face = team ? 4 : 0;+ e->anim = 2;+ e->spawn_t = d->spawn_start;+ e->hidden = (d->flags & U_HIDES) ? 1 : 0;+ return i;+ }+ return -1;+}++static bool hittable(const Battle *b, const Ent *a, int ti) {+ if (!ent_alive(b, ti)) return false;+ const Ent *t = &b->e[ti];+ if (t->team == a->team) return false;+ const UnitDef *td = def(t), *ad = def(a);+ if (td->flags & U_BOMB) return false;+ if (t->hidden) return false;+ if ((ad->flags & U_BUILDINGS) && !(td->flags & U_BUILDING)) return false;+ bool fly = (td->flags & U_FLY) != 0;+ return fly ? (ad->flags & U_AIR) != 0 : (ad->flags & U_GROUND) != 0;+}++static int32_t edge(const Ent *a, const Ent *t) { return dist(a->x, a->y, t->x, t->y) - def(t)->radius; }++/* how far a ground unit walks to (tx, ty): over a bridge when the river is between */+static int32_t path_len(const Ent *a, int32_t tx, int32_t ty) {+ const UnitDef *d = def(a);+ if ((d->flags & (U_FLY | U_JUMP)) || (a->x >= RIVER_X0 && a->x < RIVER_X1) || side_of(a->x) == side_of(tx))+ return dist(a->x, a->y, tx, ty);+ int32_t best = 0x7FFFFFFF;+ for (int k = 0; k < 2; k++) {+ int32_t by = k ? 14500 : 3500, ex = side_of(a->x) ? RIVER_X1 : RIVER_X0, ox = side_of(a->x) ? RIVER_X0 : RIVER_X1;+ int32_t l = dist(a->x, a->y, ex, by) + 2000 + dist(ox, by, tx, ty);+ if (l < best) best = l;+ }+ return best;+}++/* the next point to walk to on the way to (tx, ty) */+static void waypoint(const Ent *a, int32_t tx, int32_t ty, int32_t *wx, int32_t *wy) {+ const UnitDef *d = def(a);+ *wx = tx, *wy = ty;+ if (d->flags & (U_FLY | U_JUMP)) return;+ if (a->x >= RIVER_X0 - 300 && a->x < RIVER_X1 + 300 && on_bridge(a->y)) {+ if (side_of(tx) != side_of(a->x) || (a->x >= RIVER_X0 && a->x < RIVER_X1)) {+ /* on a bridge: straight across */+ *wx = tx >= (RIVER_X0 + RIVER_X1) / 2 ? RIVER_X1 + 600 : RIVER_X0 - 600;+ *wy = bridge_y(a->y);+ if ((tx >= (RIVER_X0 + RIVER_X1) / 2) == (a->x >= RIVER_X1)) *wx = tx, *wy = ty;+ return;+ }+ }+ if (side_of(a->x) == side_of(tx)) return;+ /* the bridge that makes the shorter walk */+ int32_t best = 0x7FFFFFFF, by = 3500;+ for (int k = 0; k < 2; k++) {+ int32_t y = k ? 14500 : 3500, ex = side_of(a->x) ? RIVER_X1 : RIVER_X0, ox = side_of(a->x) ? RIVER_X0 : RIVER_X1;+ int32_t l = dist(a->x, a->y, ex, y) + dist(ox, y, tx, ty);+ if (l < best) best = l, by = y;+ }+ *wx = side_of(a->x) ? RIVER_X1 + 200 : RIVER_X0 - 200;+ *wy = by;+ if (dist(a->x, a->y, *wx, *wy) < 500 || (a->x >= RIVER_X0 - 700 && a->x < RIVER_X1 + 700 && on_bridge(a->y)))+ *wx = side_of(a->x) ? RIVER_X0 - 600 : RIVER_X1 + 600;+}++static void wake_king(Battle *b, int team) {+ int k = b->side[team].king;+ if (ent_alive(b, k) && !(b->e[k].flags & E_AWAKE) && !b->e[k].wake) b->e[k].wake = GL(KING_ACTIVATE_TIME_MS);+}++static void kill(Battle *b, int i);++static void hurt(Battle *b, int i, int32_t dmg, bool reduced) {+ if (!ent_alive(b, i) || dmg <= 0) return;+ Ent *e = &b->e[i];+ if ((def(e)->flags & U_TOWER) && reduced) dmg = dmg * GL(REDUCED_TOWER_DAMAGE_PERCENT) / 100;+ e->hp -= dmg;+ e->flash = 120;+ if (def(e)->flags & U_KING) wake_king(b, e->team);+ if (e->hp <= 0) kill(b, i);+}++static void push(Ent *e, int32_t cx, int32_t cy, int32_t amount) {+ if ((def(e)->flags & U_NOPUSH) || amount <= 0) return;+ int32_t d = dist(e->x, e->y, cx, cy);+ int32_t dx = d ? (e->x - cx) * 1000 / d : 1000, dy = d ? (e->y - cy) * 1000 / d : 0;+ e->push_t = 5;+ e->push_x = dx * amount / 1000 / 5, e->push_y = dy * amount / 1000 / 5;+}++/* damage around (x, y): enemies of team, ground and/or air, buildings too; pushed back */+static void splash(Battle *b, int team, int32_t x, int32_t y, int32_t r, int32_t dmg, bool ground, bool air, bool reduced,+ int32_t pushback, bool spell) {+ for (int j = 0; j < MAXE; j++) {+ if (!ent_alive(b, j)) continue;+ Ent *t = &b->e[j];+ if (t->team == team || (def(t)->flags & U_BOMB) || (t->hidden && !spell)) continue;+ bool fly = ent_flying(t);+ if ((fly && !air) || (!fly && !ground)) continue;+ if (dist(x, y, t->x, t->y) > r + def(t)->radius) continue;+ if (pushback) push(t, x, y, pushback);+ hurt(b, j, dmg, reduced);+ }+}++static void place_near(int32_t *x, int32_t *y, bool fly) {+ if (*x < 500) *x = 500;+ if (*x > ARENA_X - 500) *x = ARENA_X - 500;+ if (*y < 500) *y = 500;+ if (*y > ARENA_Y - 500) *y = ARENA_Y - 500;+ if (!fly && water(*x, *y)) *x = *x < (RIVER_X0 + RIVER_X1) / 2 ? RIVER_X0 - 300 : RIVER_X1 + 300;+}++static void spawn_around(Battle *b, int type, int team, int lvl, int32_t x, int32_t y, int n, int32_t r, int32_t deploy) {+ static const int8_t ring[8][2] = {{10, 0}, {0, -10}, {0, 10}, {-10, 0}, {7, -7}, {7, 7}, {-7, -7}, {-7, 7}};+ for (int k = 0; k < n; k++) {+ int32_t px = x, py = y;+ if (n > 1) {+ int fx = team ? -ring[k & 7][0] : ring[k & 7][0];+ px += fx * r / 10, py += ring[k & 7][1] * r / 10;+ }+ place_near(&px, &py, (UNITS[type].flags & U_FLY) != 0);+ battle_spawn(b, type, team, lvl, px, py, deploy);+ }+}++static void end_battle(Battle *b) {+ b->over = 1;+ int c0 = b->side[0].crowns, c1 = b->side[1].crowns;+ b->winner = c0 > c1 ? 0 : c1 > c0 ? 1 : 2;+}++static void kill(Battle *b, int i) {+ Ent *e = &b->e[i];+ if (!e->used) return;+ const UnitDef *d = def(e);+ int team = e->team, lvl = e->lvl;+ int32_t x = e->x, y = e->y;+ e->used = 0, e->hp = 0;+ if (d->flags & U_TOWER)+ fx_add(b, FX_EXPLOSION, team, x, y, 3, 600);+ else if (!(d->flags & U_BOMB))+ fx_add(b, FX_PUFF, team, x, y - (d->flags & U_FLY ? d->fly_height * 6 / 10 : 0), d->radius >= 700 ? 2 : 1, 350);+ if (d->death_dmg) {+ fx_add(b, FX_EXPLOSION, team, x, y, d->death_radius >= 3000 ? 3 : 2, 500);+ splash(b, team, x, y, d->death_radius, lv(d->death_dmg, lvl), (d->flags & U_GROUND) != 0, (d->flags & U_AIR) != 0,+ false, d->death_push, false);+ }+ if (d->death_unit != NONE && d->death_count > 0)+ spawn_around(b, d->death_unit, team, lvl + d->spawn_level, x, y, d->death_count, 700,+ UNITS[d->death_unit].flags & U_BOMB ? UNITS[d->death_unit].deploy_ms : 0);+ if (d->flags & U_TOWER) {+ Side *s = &b->side[team], *o = &b->side[1 - team];+ if (d->flags & U_KING) {+ s->king = -1;+ o->crowns = 3;+ end_battle(b);+ } else {+ for (int k = 0; k < 2; k++)+ if (s->princess[k] == i) s->princess[k] = -1;+ if (o->crowns < 3) o->crowns++;+ wake_king(b, team);+ if (b->overtime) end_battle(b);+ }+ }+}++/* ------------------------------------------------------------------ the start */+void battle_init(Battle *b, const uint8_t deck0[8], const uint8_t deck1[8], int arena, uint32_t seed) {+ memset(b, 0, sizeof *b);+ b->magic = 0x31424352u; /* "RCB1" */+ b->size = sizeof *b;+ b->rng = seed ? seed : 1;+ b->arena = (uint8_t)arena;+ b->time_ms = GL(MATCH_LENGTH) * 1000;+ for (int t = 0; t < 2; t++) {+ Side *s = &b->side[t];+ const uint8_t *deck = t ? deck1 : deck0;+ memcpy(s->deck, deck, 8);+ uint8_t order[8];+ memcpy(order, deck, 8);+ for (int i = 7; i > 0; i--) {+ int j = rnd(b, i + 1);+ uint8_t v = order[i];+ order[i] = order[j], order[j] = v;+ }+ memcpy(s->hand, order, 4);+ memcpy(s->queue, order + 4, 4);+ s->nqueue = 4;+ s->elixir = GL(START_MANA);+ s->last_card = NONE;+ int32_t kx = t ? ARENA_X - 3000 : 3000, px = t ? ARENA_X - 6500 : 6500;+ s->king = (int16_t)battle_spawn(b, UN_KINGTOWER, t, 0, kx, 9000, 0);+ s->princess[0] = (int16_t)battle_spawn(b, UN_PRINCESSTOWER, t, 0, px, 3500, 0);+ s->princess[1] = (int16_t)battle_spawn(b, UN_PRINCESSTOWER, t, 0, px, 14500, 0);+ Ent *k = &b->e[s->king];+ k->maxhp = k->hp = UNITS[UN_KINGTOWER].hp * king_mult() / 100;+ k->dmg = PROJS[UNITS[UN_KINGTOWER].proj].dmg * compound(GL(DAMAGE_INCREASE_PERCENT_PER_KING_LEVEL), GL(TOURNAMENT_MAX_EXP_LEVEL)) / 100;+ for (int p = 0; p < 2; p++) {+ Ent *e = &b->e[s->princess[p]];+ e->maxhp = e->hp = UNITS[UN_PRINCESSTOWER].hp * tower_mult() / 100;+ e->dmg = PROJS[UNITS[UN_PRINCESSTOWER].proj].dmg *+ compound(GL(DAMAGE_INCREASE_PERCENT_PER_TOWER_LEVEL), GL(TOURNAMENT_MAX_EXP_LEVEL)) / 100;+ e->flags |= E_AWAKE;+ }+ }+ for (int t = 0; t < 2; t++) {+ b->bot[t].rng = seed * 2654435761u + 7 + (uint32_t)t * 977;+ b->bot[t].level = arena;+ b->bot[t].push_lane = -1;+ b->bot[t].think = 2000 + t * 300;+ }+}++/* ------------------------------------------------------------------ elixir and cards */+bool battle_double(const Battle *b) {+ return b->overtime || b->time_ms <= GL(MANA_SPEED_UP_WHEN_REMAINING_SECONDS) * 1000;+}+int32_t battle_regen_ms(const Battle *b) {+ int32_t m = b->overtime ? GL(MANA_REGEN_MS_OVERTIME) : battle_double(b) ? GL(MANA_REGEN_MS_END) : GL(MANA_REGEN_MS);+ return m / GL(MAX_MANA);+}+static int32_t draw_delay(const Battle *b) {+ return b->overtime ? GL(NEXT_SPELL_COOLDOWN_MILLISECONDS_OVERTIME)+ : battle_double(b) ? GL(NEXT_SPELL_COOLDOWN_MILLISECONDS_BOOST)+ : GL(NEXT_SPELL_COOLDOWN_MILLISECONDS);+}++bool battle_can_place(const Battle *b, int team, int card, int32_t x, int32_t y) {+ if (x < 0 || x >= ARENA_X || y < 0 || y >= ARENA_Y) return false;+ const CardDef *c = &CARDS[card];+ if (c->kind == K_SPELL) return true;+ bool own = team ? x >= RIVER_X1 : x < RIVER_X0;+ if (!own) {+ /* an enemy Princess tower down opens its side of the field, 4 tiles past the river */+ int lane = y < ARENA_Y / 2 ? 0 : 1;+ if (b->side[1 - team].princess[lane] >= 0) return false;+ if (team == 0 && !(x >= RIVER_X1 && x < RIVER_X1 + 4000)) return false;+ if (team == 1 && !(x < RIVER_X0 && x >= RIVER_X0 - 4000)) return false;+ }+ if (blocked(x, y) || water(x, y)) return false;+ int32_t r = c->kind == K_BUILDING && c->unit != NONE ? UNITS[c->unit].radius : 0;+ for (int j = 0; j < MAXE; j++) {+ const Ent *t = &b->e[j];+ if (!t->used || !(def(t)->flags & U_BUILDING) || (def(t)->flags & U_BOMB)) continue;+ int32_t tr = def(t)->radius;+ if (def(t)->flags & U_TOWER) tr += 400; /* (their footprints are squares) */+ if (dist(x, y, t->x, t->y) < tr + r) return false;+ }+ return true;+}++const char *battle_check(const Battle *b, int team, int slot, int32_t x, int32_t y) {+ const Side *s = &b->side[team];+ if (b->over) return "The battle is over";+ if (slot < 0 || slot > 3 || s->hand[slot] == NONE) return "The next card is coming";+ if (s->elixir < CARDS[s->hand[slot]].cost) return "Not enough elixir";+ if (!battle_can_place(b, team, s->hand[slot], x, y)) return "Not here: on your side only";+ return NULL;+}++/* the formation of a card's units, facing the enemy (game units) */+static void formation(int n, int k, int32_t *dx, int32_t *dy) {+ *dx = *dy = 0;+ if (n == 2) *dy = k ? 600 : -600;+ else if (n == 3) {+ static const int16_t f[3][2] = {{500, 0}, {-300, -600}, {-300, 600}};+ *dx = f[k][0], *dy = f[k][1];+ } else if (n == 4) {+ *dx = k & 1 ? 500 : -500, *dy = k & 2 ? 500 : -500;+ } else if (n > 4) {+ static const int16_t ring[13][2] = {{1000, 0}, {500, 866}, {-500, 866}, {-1000, 0}, {-500, -866}, {500, -866},+ {1000, 0}, {809, 588}, {309, 951}, {-309, 951}, {-809, 588}, {-1000, 0}, {-809, -588}};+ if (n <= 7) {+ if (k < 6) *dx = ring[k][0] * 9 / 10, *dy = ring[k][1] * 9 / 10;+ } else if (k > 0) {+ int r = k <= 6 ? 700 : 1450;+ int i = k <= 6 ? k - 1 : k - 7;+ int m = k <= 6 ? 6 : n - 7;+ /* evenly round a circle: the angle 360 * i / m, from a small table of cosines */+ static const int16_t cs[16][2] = {{1000, 0}, {924, 383}, {707, 707}, {383, 924}, {0, 1000}, {-383, 924},+ {-707, 707}, {-924, 383}, {-1000, 0}, {-924, -383}, {-707, -707}, {-383, -924},+ {0, -1000}, {383, -924}, {707, -707}, {924, -383}};+ int a = (i * 16 + m / 2) / m & 15;+ *dx = cs[a][0] * r / 1000, *dy = cs[a][1] * r / 1000;+ }+ }+}++static void cast(Battle *b, int team, int card, int32_t x, int32_t y, int lvl) {+ const CardDef *c = &CARDS[card];+ Side *s = &b->side[team];+ if (c->unit != NONE) {+ const UnitDef *u = &UNITS[c->unit];+ for (int k = 0; k < c->count; k++) {+ int32_t dx, dy, px, py;+ formation(c->count, k, &dx, &dy);+ px = x + (team ? -dx : dx), py = y + dy;+ place_near(&px, &py, (u->flags & U_FLY) != 0);+ if (!(u->flags & U_FLY) && (blocked(px, py) || water(px, py))) px = x, py = y;+ int32_t extra = c->count > 1 && u->random_deploy ? rnd(b, u->random_deploy) : 0;+ battle_spawn(b, c->unit, team, lvl, px, py, u->deploy_ms + extra);+ }+ }+ if (c->proj != NONE) {+ /* thrown from the King tower (or where it stood) */+ int32_t kx = team ? ARENA_X - 3000 : 3000, ky = 9000;+ int n = 1 + (c->arrows > 0 ? 3 : 0);+ for (int k = 0; k < n && k < 4; k++)+ for (int i = 0; i < MAXP; i++) {+ if (b->p[i].used) continue;+ Proj *p = &b->p[i];+ memset(p, 0, sizeof *p);+ p->used = 1, p->type = (uint8_t)c->proj, p->team = (uint8_t)team, p->lvl = (uint8_t)lvl, p->spell = 1;+ p->deco = k > 0;+ p->sx = p->x = kx, p->sy = p->y = ky + (k ? (k - 2) * 900 : 0);+ p->tx = x + (k ? (k - 2) * 500 : 0), p->ty = y + (k ? (k & 1 ? 700 : -700) : 0);+ p->target = -1;+ p->z0 = 3000;+ p->dmg = lv(PROJS[c->proj].dmg, lvl);+ int32_t sp = PROJS[c->proj].speed * TICK * 1000 / 60000;+ p->total = sp ? dist(kx, ky, x, y) / sp * TICK : 0;+ break;+ }+ }+ if (c->area != NONE) {+ const AreaDef *a = &AREAS[c->area];+ for (int i = 0; i < MAXA; i++) {+ if (b->a[i].used) continue;+ Area *ar = &b->a[i];+ memset(ar, 0, sizeof *ar);+ ar->used = 1, ar->type = (uint8_t)c->area, ar->team = (uint8_t)team, ar->lvl = (uint8_t)lvl;+ ar->x = x, ar->y = y;+ ar->total = ar->life = a->life_ms + a->life_per_level * lvl;+ for (int k = 0; k < 4; k++) ar->hit_ids[k] = -1;+ if (a->dmg) {+ /* Zap: at once, and it stops what it hits for a moment */+ splash(b, team, x, y, a->radius, lv(a->dmg, lvl), (a->flags & A_GROUND) != 0, (a->flags & A_AIR) != 0,+ (a->flags & A_REDUCED) != 0, 0, true);+ for (int j = 0; j < MAXE; j++) {+ Ent *t = &b->e[j];+ if (!ent_alive(b, j) || t->team == team || dist(x, y, t->x, t->y) > a->radius + def(t)->radius) continue;+ t->stun = 500, t->t = 0, t->lock = 0, t->walked = 0, t->flags &= (uint8_t)~E_CHARGING;+ }+ fx_add(b, FX_ZAP, team, x, y, 1, 300);+ }+ break;+ }+ }+ (void)s;+}++bool battle_play(Battle *b, int team, int slot, int32_t x, int32_t y) {+ if (battle_check(b, team, slot, x, y)) return false;+ Side *s = &b->side[team];+ int card = s->hand[slot];+ s->elixir -= CARDS[card].cost;+ s->spent += CARDS[card].cost;+ s->played++;+ s->last_card = (uint8_t)card;+ cast(b, team, card, x, y, card_lvl_index(card));+ s->queue[s->nqueue++] = (uint8_t)card;+ s->hand[slot] = NONE;+ s->draw_t[slot] = (int16_t)draw_delay(b);+ return true;+}++static void side_step(Battle *b, int team) {+ Side *s = &b->side[team];+ int32_t max = GL(MAX_MANA), regen = battle_regen_ms(b);+ if (s->elixir < max) {+ s->elixir_t += TICK;+ while (s->elixir_t >= regen && s->elixir < max) s->elixir++, s->elixir_t -= regen;+ if (s->elixir >= max) s->elixir_t = 0;+ } else {+ s->leaked += TICK;+ }+ for (int k = 0; k < 4; k++)+ if (s->hand[k] == NONE) {+ s->draw_t[k] = (int16_t)(s->draw_t[k] - TICK);+ if (s->draw_t[k] <= 0 && s->nqueue) {+ s->hand[k] = s->queue[0];+ memmove(s->queue, s->queue + 1, --s->nqueue);+ }+ }+}++/* ------------------------------------------------------------------ a unit's step */+static int rate(const Ent *e, int base) { /* Rage: 135%, as a percent */+ return e->rage > 0 ? base * 135 / 100 : base;+}++static void face_to(Ent *e, int32_t dx, int32_t dy) {+ if (!dx && !dy) return;+ /* octants: 0 right, 1 down-right, 2 down ... 7 up-right; 22.5 degrees is a slope of 0.414 */+ int32_t ax = dx < 0 ? -dx : dx, ay = dy < 0 ? -dy : dy;+ int o;+ if (ay * 1000 < ax * 414) o = dx > 0 ? 0 : 4;+ else if (ax * 1000 < ay * 414) o = dy > 0 ? 2 : 6;+ else o = dx > 0 ? (dy > 0 ? 1 : 7) : (dy > 0 ? 3 : 5);+ e->face = (uint8_t)o;+}++static int find_target(Battle *b, int i) {+ Ent *a = &b->e[i];+ const UnitDef *d = def(a);+ int best = -1;+ int32_t bd = 0x7FFFFFFF;+ if (is_building(a)) {+ for (int j = 0; j < MAXE; j++) {+ if (!hittable(b, a, j)) continue;+ int32_t e = edge(a, &b->e[j]);+ if (e > d->range || (d->min_range && dist(a->x, a->y, b->e[j].x, b->e[j].y) < d->min_range)) continue;+ if (e < bd) bd = e, best = j;+ }+ return best;+ }+ for (int j = 0; j < MAXE; j++) {+ if (!hittable(b, a, j)) continue;+ int32_t e = edge(a, &b->e[j]);+ if (e <= d->sight && e < bd) bd = e, best = j;+ }+ if (best >= 0 && !(d->flags & U_BUILDINGS)) return best;+ /* nothing in sight: the nearest building on the way */+ best = -1, bd = 0x7FFFFFFF;+ for (int j = 0; j < MAXE; j++) {+ if (!hittable(b, a, j) || !is_building(&b->e[j])) continue;+ int32_t l = path_len(a, b->e[j].x, b->e[j].y);+ if (l < bd) bd = l, best = j;+ }+ return best;+}++static void fire(Battle *b, int i, int ti) {+ Ent *a = &b->e[i], *t = &b->e[ti];+ const UnitDef *d = def(a);+ int32_t dmg = a->dmg;+ if (d->charge_range && (a->flags & E_CHARGING)) dmg = lv(d->dmg_special, a->lvl);+ if (d->dmg2) { /* Inferno Tower: more the longer it burns one target */+ if (a->lock >= d->t1 + d->t2) dmg = lv(d->dmg3, a->lvl);+ else if (a->lock >= d->t1) dmg = lv(d->dmg2, a->lvl);+ }+ a->flags &= (uint8_t)~E_CHARGING;+ a->walked = 0;+ a->post = 0;+ if (d->proj != NONE) {+ for (int k = 0; k < MAXP; k++) {+ if (b->p[k].used) continue;+ Proj *p = &b->p[k];+ memset(p, 0, sizeof *p);+ p->used = 1, p->type = (uint8_t)d->proj, p->team = a->team, p->lvl = a->lvl;+ p->sx = p->x = a->x, p->sy = p->y = a->y;+ p->tx = t->x, p->ty = t->y;+ p->target = (int16_t)ti, p->tgen = t->gen;+ p->dmg = dmg;+ p->z0 = d->flags & U_FLY ? d->fly_height : d->attached_h ? d->attached_h : 600;+ if (d->flags & U_TOWER) p->z0 = 2400;+ int32_t sp = PROJS[d->proj].speed * TICK * 1000 / 60000;+ p->total = sp ? dist(a->x, a->y, t->x, t->y) / sp * TICK + TICK : TICK;+ return;+ }+ return;+ }+ if (d->area && (d->flags & U_SELFAOE)) {+ /* Valkyrie: all round her */+ splash(b, a->team, a->x, a->y, d->area, dmg, true, false, false, 0, false);+ return;+ }+ hurt(b, ti, dmg, false);+}++static void move_unit(Battle *b, Ent *e, int32_t tx, int32_t ty, int32_t step) {+ int32_t wx, wy;+ waypoint(e, tx, ty, &wx, &wy);+ int32_t d = dist(e->x, e->y, wx, wy);+ if (!d) return;+ if (step > d) step = d;+ int64_t ddx = (int64_t)(wx - e->x) * step, ddy = (int64_t)(wy - e->y) * step;+ int32_t nx = e->x + (int32_t)((ddx + (ddx < 0 ? -d / 2 : d / 2)) / d), ny = e->y + (int32_t)((ddy + (ddy < 0 ? -d / 2 : d / 2)) / d);+ bool ground = !(def(e)->flags & (U_FLY | U_JUMP));+ if (!(def(e)->flags & U_FLY)) {+ /* a building in the way (not the one it goes for): round it */+ for (int j = 0; j < MAXE; j++) {+ const Ent *o = &b->e[j];+ if (!o->used || j == e->target || !is_building(o) || (def(o)->flags & U_BOMB) || o == e) continue;+ int32_t r = def(o)->radius + def(e)->radius + 100;+ if (dist(nx, ny, o->x, o->y) >= r || dist(e->x, e->y, o->x, o->y) > r + step + 400) continue;+ int32_t vx = e->x - o->x, vy = e->y - o->y, vd = dist(0, 0, vx, vy);+ if (!vd) vx = 1, vd = 1;+ int32_t tx1 = -vy, ty1 = vx;+ if ((int64_t)tx1 * (wx - e->x) + (int64_t)ty1 * (wy - e->y) < 0) tx1 = -tx1, ty1 = -ty1;+ /* along the tangent, and a little outward if inside */+ int32_t out = vd < r ? (r - vd < step ? r - vd : step) : 0;+ nx = e->x + (int32_t)((int64_t)tx1 * step / vd) + (int32_t)((int64_t)vx * out / vd);+ ny = e->y + (int32_t)((int64_t)ty1 * step / vd) + (int32_t)((int64_t)vy * out / vd);+ wx = nx, wy = ny;+ break;+ }+ }+ face_to(e, wx - e->x, wy - e->y);+ if (ground && (water(nx, ny) || blocked(nx, ny))) {+ if (!water(nx, e->y) && !blocked(nx, e->y)) ny = e->y;+ else if (!water(e->x, ny) && !blocked(e->x, ny)) nx = e->x;+ else return;+ }+ if (!ground && blocked(nx, ny) && (nx < 0 || nx >= ARENA_X || ny < 0 || ny >= ARENA_Y)) return;+ e->walked += dist(e->x, e->y, nx, ny);+ e->x = nx, e->y = ny;+ (void)b;+}++static void unit_step(Battle *b, int i) {+ Ent *e = &b->e[i];+ const UnitDef *d = def(e);+ if (e->flash > 0) e->flash -= TICK;+ if (e->rage > 0) e->rage -= TICK;+ if (e->push_t > 0) {+ int32_t nx = e->x + e->push_x, ny = e->y + e->push_y;+ if (!blocked(nx, ny) && (ent_flying(e) || !water(nx, ny))) e->x = nx, e->y = ny;+ e->push_t--;+ }+ if (e->deploy > 0) {+ e->deploy -= TICK;+ e->anim = 2;+ if (e->deploy <= 0 && (d->flags & U_BOMB)) {+ kill(b, i);+ return;+ }+ if (e->deploy > 0) return;+ e->deploy = 0;+ }+ if (e->freeze > 0 || e->stun > 0) {+ if (e->freeze > 0) e->freeze -= TICK;+ if (e->stun > 0) e->stun -= TICK;+ e->anim = 2;+ return;+ }+ e->anim_ms += rate(e, TICK);+ e->post += TICK;+ /* buildings: their hitpoints drain over their lifetime */+ if (d->life_ms) {+ int64_t acc = (int64_t)e->maxhp * TICK + e->decay;+ int32_t loss = (int32_t)(acc / d->life_ms);+ e->decay = (int32_t)(acc % d->life_ms);+ e->hp -= loss;+ if (e->hp <= 0) {+ kill(b, i);+ return;+ }+ }+ if (d->mana_ms) {+ e->mana_t += TICK;+ if (e->mana_t >= d->mana_ms) {+ e->mana_t -= d->mana_ms;+ Side *s = &b->side[e->team];+ if (s->elixir < GL(MAX_MANA)) s->elixir += d->mana_amount;+ fx_add(b, FX_TEXT, e->team, e->x, e->y - 1500, 1, 900);+ }+ }+ if (d->spawn_unit != NONE && d->spawn_number) {+ int dt = rate(e, TICK);+ if (e->spawn_left > 0) {+ e->spawn_gap -= dt;+ if (e->spawn_gap <= 0) {+ int32_t fx = e->team ? -1 : 1, sx = e->x, sy = e->y;+ if (is_building(e)) sx += fx * (d->radius + 500), sy += (e->spawn_left & 1 ? 1 : -1) * 400;+ else sx += fx * 800, sy += (e->spawn_left - 2) * 700;+ place_near(&sx, &sy, false);+ battle_spawn(b, d->spawn_unit, e->team, e->lvl + d->spawn_level, sx, sy, 0);+ e->spawn_left--;+ e->spawn_gap = d->spawn_interval;+ }+ } else {+ e->spawn_t -= dt;+ if (e->spawn_t <= 0) {+ e->spawn_left = d->spawn_number;+ e->spawn_gap = 0;+ e->spawn_t += d->spawn_pause + d->spawn_interval * (d->spawn_number - 1);+ }+ }+ }+ /* the King tower sleeps until hit or a Princess tower falls */+ if (d->flags & U_KING) {+ if (!(e->flags & E_AWAKE)) {+ if (e->wake > 0) {+ e->wake -= TICK;+ if (e->wake <= 0) e->flags |= E_AWAKE;+ }+ if (!(e->flags & E_AWAKE)) return;+ }+ }+ bool attacks = d->range > 0 && (d->dmg || d->proj != NONE);+ if (!attacks && is_building(e)) {+ e->anim = 2;+ return;+ }+ /* the target: kept while it can be hit and is near; a unit walking to a building looks again */+ int tg = e->target;+ if (tg >= 0 && (!hittable(b, e, tg) || b->e[tg].gen != e->tgen)) tg = -1;+ if (tg >= 0) {+ int32_t ed = edge(e, &b->e[tg]);+ if (is_building(e)) {+ if (ed > d->range) tg = -1;+ } else if (!(e->flags & E_ATTACKING) && is_building(&b->e[tg]) && !(d->flags & U_BUILDINGS)) {+ tg = -1;+ } else if (!(e->flags & E_ATTACKING) && ed > d->sight + 2000 && !is_building(&b->e[tg])) {+ tg = -1;+ }+ }+ if (tg < 0) tg = find_target(b, i);+ if (tg != e->target || (tg >= 0 && b->e[tg].gen != e->tgen)) {+ e->lock = 0;+ if (e->flags & E_ATTACKING) e->t = 0;+ e->flags &= (uint8_t)~E_ATTACKING;+ }+ e->target = (int16_t)tg;+ e->tgen = tg >= 0 ? b->e[tg].gen : 0;+ /* Tesla: up while something is in range, under the ground otherwise */+ if (d->flags & U_HIDES) {+ if (tg >= 0) {+ if (e->hidden) {+ e->hide_t += TICK;+ if (e->hide_t >= d->up_ms) e->hidden = 0, e->hide_t = 0;+ return;+ }+ } else if (!e->hidden) {+ e->hide_t += TICK;+ if (e->hide_t >= d->hide_ms) e->hidden = 1, e->hide_t = 0;+ } else {+ e->hide_t = 0;+ }+ }+ int load = d->load_ms, hit = d->hit_ms;+ if (tg < 0) {+ e->flags &= (uint8_t)~E_ATTACKING;+ if (e->t < load) e->t = e->t + rate(e, TICK) < load ? e->t + rate(e, TICK) : load;+ e->anim = 2;+ return;+ }+ Ent *t = &b->e[tg];+ int32_t ed = edge(e, t);+ bool in_range = ed <= d->range && (!d->min_range || dist(e->x, e->y, t->x, t->y) >= d->min_range);+ if (in_range) {+ e->flags |= E_ATTACKING;+ e->anim = 1;+ face_to(e, t->x - e->x, t->y - e->y);+ e->lock += TICK;+ e->t += rate(e, TICK);+ if (e->t >= hit) {+ e->t = 0;+ fire(b, i, tg);+ }+ return;+ }+ e->flags &= (uint8_t)~E_ATTACKING;+ if (e->t < load) e->t = e->t + rate(e, TICK) < load ? e->t + rate(e, TICK) : load;+ if (is_building(e) || !d->speed) {+ e->anim = 2;+ return;+ }+ /* walk (the Prince charges after ChargeRange of walking) */+ int32_t step = rate(e, d->speed * TICK * 1000 / 60000);+ if (d->charge_range) {+ if (e->walked >= d->charge_range * 10) e->flags |= E_CHARGING;+ if (e->flags & E_CHARGING) step = step * d->charge_mul / 100;+ }+ /* stop where the target comes in range */+ int32_t room = ed - d->range;+ if (room + 20 < step) step = room + 20;+ move_unit(b, e, t->x, t->y, step);+ e->anim = 0;+}++/* units do not stand inside each other or the buildings */+static void collide(Battle *b) {+ for (int i = 0; i < MAXE; i++) {+ Ent *a = &b->e[i];+ if (!a->used || (def(a)->flags & U_BOMB)) continue;+ bool afly = ent_flying(a), ab = is_building(a);+ for (int j = i + 1; j < MAXE; j++) {+ Ent *c = &b->e[j];+ if (!c->used || (def(c)->flags & U_BOMB) || ent_flying(c) != afly) continue;+ bool cb = is_building(c);+ if (ab && cb) continue;+ int32_t r = def(a)->radius + def(c)->radius;+ int32_t dx = c->x - a->x, dy = c->y - a->y;+ if (dx >= r || -dx >= r || dy >= r || -dy >= r) continue;+ int32_t d = isqrt64((int64_t)dx * dx + (int64_t)dy * dy);+ if (d >= r) continue;+ if (!d) dx = (i & 1) ? 1 : -1, dy = (j & 1) ? 1 : -1, d = 1;+ int32_t over = r - d;+ int32_t ma = ab ? 0 : def(a)->mass ? def(a)->mass : 1, mc = cb ? 0 : def(c)->mass ? def(c)->mass : 1;+ /* the lighter gives way; a building not at all */+ int32_t sa = ab ? 0 : cb ? over : over * mc / (ma + mc), sc = cb ? 0 : ab ? over : over - sa;+ Ent *m[2] = {a, c};+ int32_t s[2] = {-sa, sc};+ for (int k = 0; k < 2; k++) {+ if (!s[k]) continue;+ int32_t nx = m[k]->x + (int32_t)((int64_t)dx * s[k] / d), ny = m[k]->y + (int32_t)((int64_t)dy * s[k] / d);+ if (!blocked(nx, ny) && (afly || !water(nx, ny) || (def(m[k])->flags & U_JUMP))) m[k]->x = nx, m[k]->y = ny;+ }+ }+ }+}++/* ------------------------------------------------------------------ projectiles and spells */+static void proj_step(Battle *b, int i) {+ Proj *p = &b->p[i];+ const ProjDef *d = &PROJS[p->type];+ p->t += TICK;+ if ((d->flags & P_HOMING) && !p->spell && p->target >= 0) {+ if (ent_alive(b, p->target) && b->e[p->target].gen == p->tgen) p->tx = b->e[p->target].x, p->ty = b->e[p->target].y;+ else p->target = -1;+ }+ int32_t step = d->speed * TICK * 1000 / 60000;+ int32_t dd = dist(p->x, p->y, p->tx, p->ty);+ if (dd > step) {+ p->x += (int32_t)((int64_t)(p->tx - p->x) * step / dd);+ p->y += (int32_t)((int64_t)(p->ty - p->y) * step / dd);+ return;+ }+ p->x = p->tx, p->y = p->ty;+ p->used = 0;+ if (p->deco) return;+ bool reduced = (d->flags & P_REDUCED) != 0;+ if (d->radius) {+ bool ground = (d->flags & P_AOE_GROUND) != 0, air = (d->flags & P_AOE_AIR) != 0;+ splash(b, p->team, p->x, p->y, d->radius, p->dmg, ground, air, reduced, d->push, p->spell);+ int sz = d->radius >= 2500 ? 3 : d->radius >= 1500 ? 2 : 1;+ fx_add(b, d->radius >= 1500 || p->spell ? FX_EXPLOSION : FX_SPLASH, p->team, p->x, p->y, sz, 450);+ } else if (p->target >= 0 && ent_alive(b, p->target)) {+ hurt(b, p->target, p->dmg, reduced);+ }+ if (d->spawn_unit != NONE && d->spawn_count)+ spawn_around(b, d->spawn_unit, p->team, p->lvl + d->spawn_level, p->x, p->y, d->spawn_count, 600, d->spawn_deploy);+}++static void area_step(Battle *b, int i) {+ Area *ar = &b->a[i];+ const AreaDef *a = &AREAS[ar->type];+ ar->life -= TICK;+ ar->hit_t += TICK;+ int32_t since = ar->total - ar->life;+ if (a->speed_mul || a->hit_mul) {+ bool freeze = a->speed_mul < 0;+ for (int j = 0; j < MAXE; j++) {+ Ent *t = &b->e[j];+ if (!ent_alive(b, j) || (def(t)->flags & U_BOMB)) continue;+ bool own = t->team == ar->team;+ if ((a->flags & A_OWN) && !own) continue;+ if ((a->flags & A_ENEMIES) && own) continue;+ bool fly = ent_flying(t);+ if ((fly && !(a->flags & A_AIR)) || (!fly && !(a->flags & A_GROUND))) continue;+ if (dist(ar->x, ar->y, t->x, t->y) > a->radius + def(t)->radius) continue;+ if (freeze) {+ if (since <= TICK) t->freeze = ar->life + TICK; /* the ones in it when it falls, for its time */+ } else {+ t->rage = a->buff_ms;+ }+ }+ }+ if (a->proj != NONE && a->hit_ms && ar->hit_t >= a->hit_ms && ar->hits < 3) {+ /* Lightning: the biggest (most hitpoints) not hit yet */+ ar->hit_t -= a->hit_ms;+ int best = -1;+ int32_t bh = -1;+ for (int j = 0; j < MAXE; j++) {+ Ent *t = &b->e[j];+ if (!ent_alive(b, j) || t->team == ar->team || (def(t)->flags & U_BOMB)) continue;+ if (dist(ar->x, ar->y, t->x, t->y) > a->radius + def(t)->radius) continue;+ bool done = false;+ for (int k = 0; k < ar->hits; k++) done |= ar->hit_ids[k] == j;+ if (!done && t->hp > bh) bh = t->hp, best = j;+ }+ if (best >= 0) {+ Ent *t = &b->e[best];+ ar->hit_ids[ar->hits] = (int16_t)best;+ fx_add(b, FX_LIGHTNING, ar->team, t->x, t->y, 1, 400);+ t->t = 0, t->lock = 0, t->walked = 0, t->flags &= (uint8_t)~E_CHARGING;+ hurt(b, best, lv(PROJS[a->proj].dmg, ar->lvl), (PROJS[a->proj].flags & P_REDUCED) != 0);+ }+ ar->hits++;+ }+ if (ar->life <= 0) ar->used = 0;+}++void battle_step(Battle *b) {+ if (b->over) return;+ b->tick++;+ b->time_ms -= TICK;+ if (b->time_ms <= 0) {+ if (!b->overtime && b->side[0].crowns == b->side[1].crowns) {+ b->overtime = 1;+ b->time_ms = GL(OVERTIME_SECONDS) * 1000;+ } else {+ b->time_ms = 0;+ end_battle(b);+ return;+ }+ }+ side_step(b, 0);+ side_step(b, 1);+ bot_step(b);+ for (int i = 0; i < MAXE; i++)+ if (b->e[i].used) unit_step(b, i);+ collide(b);+ for (int i = 0; i < MAXP; i++)+ if (b->p[i].used) proj_step(b, i);+ for (int i = 0; i < MAXA; i++)+ if (b->a[i].used) area_step(b, i);+ for (int i = 0; i < MAXFX; i++)+ if (b->fx[i].used && (b->fx[i].t = (int16_t)(b->fx[i].t + TICK)) >= b->fx[i].len) b->fx[i].used = 0;+}diff --git a/games/clashroyale/src/sim.h b/games/clashroyale/src/sim.hnew file mode 100644index 00000000..8a7f7d67--- /dev/null+++ b/games/clashroyale/src/sim.h@@ -0,0 +1,134 @@+/* Clash Royale: the battle, as the game plays it (see gamesrc/clashroyale/spec/spec.md).+ *+ * The arena is the game's 18 x 32 tiles turned a quarter: x along it (0 to 32000, 1000 a tile, your King tower+ * at 3000), y across (0 to 18000; the top lane's bridge at 3500). Team 0 is you, on the left; team 1 the bot.+ * One step is 50 ms, 20 a second. Everything is integers, so a battle plays the same from the same start. */+#ifndef CR_SIM_H+#define CR_SIM_H+#include <stdbool.h>+#include <stdint.h>+#include "tables.h"++#define TICK 50+#define ARENA_X 32000+#define ARENA_Y 18000+#define RIVER_X0 15000+#define RIVER_X1 17000+#define MAXE 120+#define MAXP 72+#define MAXA 6+#define MAXFX 40+#define NONE 255++enum { E_ATTACKING = 1, E_CHARGING = 2, E_AWAKE = 4, E_WALKED = 8 };++typedef struct {+ uint8_t used, type, team, lvl; /* UNITS[type]; lvl: the level index of its stats (m[lvl]) */+ uint8_t flags, face, anim, hidden; /* face: 0 right, 1 down-right ... 7 up-right; anim: 0 run 1 attack 2 idle */+ int16_t target; /* an entity, -1 none */+ uint16_t tgen, gen; /* the target's generation, this one's */+ int32_t x, y;+ int32_t hp, maxhp, dmg;+ int32_t deploy; /* ms left deploying */+ int32_t t; /* attack charge, ms */+ int32_t post; /* ms since the last hit (for the picture) */+ int32_t decay; /* buildings: the lifetime's remainder */+ int32_t spawn_t, spawn_gap; /* ms to the next group, to the next of the group */+ int32_t spawn_left;+ int32_t walked; /* Prince: units walked since his last hit */+ int32_t lock; /* Inferno Tower: ms on this target */+ int32_t rage, freeze, stun; /* ms left of each */+ int32_t push_x, push_y, push_t; /* pushed back: units a step, steps left */+ int32_t anim_ms;+ int32_t hide_t; /* Tesla: ms into coming up or going down */+ int32_t mana_t; /* Elixir Collector */+ int32_t flash; /* ms of the hit flash */+ int32_t wake; /* King tower: ms until it shoots */+} Ent;++typedef struct {+ uint8_t used, type, team, lvl;+ uint8_t spell, deco, pad1, pad2;+ int16_t target;+ uint16_t tgen;+ int32_t x, y, sx, sy, tx, ty; /* where it is, where it started, where it goes */+ int32_t z0; /* the height it started at (units) */+ int32_t dmg;+ int32_t t, total; /* ms flown, of about total */+} Proj;++typedef struct {+ uint8_t used, type, team, lvl;+ int32_t x, y;+ int32_t life, total, hit_t, hits;+ int16_t hit_ids[4];+} Area;++enum { FX_EXPLOSION, FX_PUFF, FX_ZAP, FX_LIGHTNING, FX_SPLASH, FX_TEXT };+typedef struct {+ uint8_t used, kind, team, size;+ int16_t x, y; /* pixels */+ int16_t t, len; /* ms */+} Fx;++typedef struct {+ uint8_t deck[8];+ uint8_t hand[4]; /* card ids, NONE while the next one comes */+ int16_t draw_t[4];+ uint8_t queue[8];+ uint8_t nqueue;+ uint8_t crowns;+ int16_t king, princess[2]; /* entities */+ int32_t elixir, elixir_t; /* whole elixir, ms toward the next */+ int32_t played, spent, leaked; /* cards played, elixir spent, elixir lost at 10 */+ uint8_t last_card, pad[3];+} Side;++typedef struct {+ int32_t think; /* ms to the next look */+ int32_t level; /* 0 to 6: the arena */+ int32_t push_lane; /* -1 none */+ int32_t push_ms;+ uint32_t rng;+} Bot;++typedef struct {+ uint32_t magic, size;+ uint32_t tick;+ int32_t time_ms; /* left in the match, or in overtime */+ uint8_t overtime, over, winner, arena; /* winner: 0 you, 1 the bot, 2 draw */+ uint32_t rng;+ uint16_t gen;+ uint16_t pad;+ Side side[2];+ Bot bot[2]; /* team 1's; team 0's only in tests */+ Ent e[MAXE];+ Proj p[MAXP];+ Area a[MAXA];+ Fx fx[MAXFX];+} Battle;++extern const int32_t LEVEL_MULT[16];+int card_level(int card); /* the tournament standard's level of a card (1...) */+int card_lvl_index(int card); /* its stats' index in LEVEL_MULT */+int32_t lv(int32_t v, int idx); /* a stat at a level index */+int32_t king_mult(void), tower_mult(void); /* the towers' (percent) */++void battle_init(Battle *b, const uint8_t deck0[8], const uint8_t deck1[8], int arena, uint32_t seed);+void battle_step(Battle *b);+/* a card in the hand's slot at (x, y): NULL when it can be, else why not */+const char *battle_check(const Battle *b, int team, int slot, int32_t x, int32_t y);+bool battle_play(Battle *b, int team, int slot, int32_t x, int32_t y);+bool battle_can_place(const Battle *b, int team, int card, int32_t x, int32_t y);+int32_t battle_regen_ms(const Battle *b); /* ms an elixir takes now */+bool battle_double(const Battle *b);+int battle_spawn(Battle *b, int type, int team, int lvl, int32_t x, int32_t y, int32_t deploy); /* tests */+int32_t isqrt64(int64_t v);+int32_t dist(int32_t ax, int32_t ay, int32_t bx, int32_t by);+bool ent_alive(const Battle *b, int i);+bool ent_flying(const Ent *e);+uint32_t sim_rand(uint32_t *s);++/* the bot (bot.c): plays team 1 */+void bot_step(Battle *b);+#endifdiff --git a/games/clashroyale/src/tables.c b/games/clashroyale/src/tables.cnew file mode 100644index 00000000..374471a1--- /dev/null+++ b/games/clashroyale/src/tables.c@@ -0,0 +1,239 @@+/* made by tools/pack.py from Clash Royale's assets/csv_logic: see tables.h */+#include "tables.h"++const SetDef SETS[NSETS] = {+ {{0, 6, 5, 255, 26}, {30, 6, 5, 4, 35}, {60, 1, 5, 255, 1}}, /* Knight */+ {{65, 6, 5, 255, 16}, {95, 6, 5, 3, 24}, {125, 1, 5, 255, 1}}, /* Archer */+ {{130, 6, 5, 255, 18}, {160, 6, 5, 4, 19}, {190, 1, 5, 255, 1}}, /* Goblin */+ {{195, 6, 5, 255, 30}, {225, 6, 5, 3, 28}, {255, 1, 5, 255, 1}}, /* Giant */+ {{260, 6, 5, 255, 30}, {290, 6, 5, 3, 21}, {320, 1, 5, 255, 2}}, /* Pekka */+ {{325, 6, 5, 255, 16}, {355, 6, 5, 4, 14}, {385, 1, 5, 255, 16}}, /* Minion */+ {{390, 6, 1, 255, 60}, {396, 6, 1, 5, 39}, {402, 1, 1, 255, 1}}, /* Balloon */+ {{403, 6, 5, 255, 24}, {433, 6, 5, 3, 17}, {463, 1, 5, 255, 1}}, /* Witch */+ {{468, 6, 5, 255, 16}, {498, 6, 5, 3, 22}, {528, 1, 5, 255, 2}}, /* Barbarian */+ {{533, 6, 5, 255, 36}, {563, 6, 5, 3, 18}, {593, 1, 5, 255, 2}}, /* Golem */+ {{598, 6, 5, 255, 16}, {628, 6, 5, 2, 14}, {658, 1, 5, 255, 2}}, /* Skeleton */+ {{663, 6, 5, 255, 16}, {693, 6, 5, 2, 27}, {723, 1, 5, 255, 1}}, /* Valkyrie */+ {{728, 6, 5, 255, 20}, {758, 6, 5, 3, 33}, {788, 1, 5, 255, 35}}, /* Bomber */+ {{793, 6, 5, 255, 28}, {823, 6, 5, 3, 30}, {853, 1, 5, 255, 1}}, /* Musketeer */+ {{858, 6, 5, 255, 18}, {888, 6, 5, 4, 22}, {918, 1, 5, 255, 18}}, /* BabyDragon */+ {{923, 6, 5, 255, 20}, {953, 6, 5, 3, 27}, {983, 1, 5, 255, 1}}, /* Prince */+ {{988, 6, 5, 255, 16}, {1018, 6, 5, 3, 30}, {1048, 1, 2, 255, 1}}, /* Wizard */+ {{1050, 6, 5, 255, 16}, {1080, 6, 5, 3, 23}, {1110, 1, 5, 255, 1}}, /* MiniPekka */+ {{1115, 6, 5, 255, 22}, {1145, 6, 5, 4, 23}, {1175, 1, 5, 255, 1}}, /* SpearGoblin */+ {{1180, 6, 5, 255, 30}, {1210, 6, 5, 3, 22}, {1240, 1, 5, 255, 1}}, /* GiantSkeleton */+ {{1245, 6, 5, 255, 17}, {1275, 6, 5, 4, 20}, {1305, 1, 5, 255, 1}}, /* HogRider */+ {{1310, 1, 5, 255, 1}, {1315, 6, 5, 3, 24}, {1345, 1, 5, 255, 1}}, /* PrincessB */+ {{1350, 6, 5, 255, 36}, {1380, 6, 5, 3, 18}, {1410, 1, 5, 255, 2}}, /* Golemite */+ {{1415, 1, 1, 255, 1}, {1415, 1, 1, 255, 1}, {1415, 1, 1, 255, 1}}, /* KingTower */+ {{1416, 1, 1, 255, 1}, {1416, 1, 1, 255, 1}, {1416, 1, 1, 255, 1}}, /* PrincessTower */+ {{1417, 1, 1, 255, 1}, {1417, 1, 1, 255, 1}, {1417, 1, 1, 255, 1}}, /* PrincessTowerTop */+ {{1418, 1, 5, 255, 1}, {1418, 1, 5, 255, 1}, {1418, 1, 5, 255, 1}}, /* Cannon */+ {{1423, 1, 1, 255, 1}, {1423, 1, 1, 255, 1}, {1423, 1, 1, 255, 1}}, /* GoblinHut */+ {{1424, 1, 5, 0, 3}, {1429, 3, 5, 1, 3}, {1444, 1, 5, 255, 3}}, /* Mortar */+ {{1449, 1, 1, 255, 1}, {1449, 1, 1, 255, 1}, {1449, 1, 1, 255, 1}}, /* InfernoTower */+ {{1450, 1, 1, 255, 1}, {1450, 1, 1, 255, 1}, {1450, 1, 1, 255, 1}}, /* BombTower */+ {{1451, 1, 1, 255, 1}, {1451, 1, 1, 255, 1}, {1451, 1, 1, 255, 1}}, /* BombTowerTop */+ {{1452, 1, 1, 255, 1}, {1452, 1, 1, 255, 1}, {1452, 1, 1, 255, 1}}, /* BarbarianHut */+ {{1453, 3, 1, 255, 3}, {1453, 3, 1, 255, 3}, {1453, 3, 1, 255, 3}}, /* Tesla */+ {{1456, 1, 1, 255, 1}, {1456, 1, 1, 255, 1}, {1456, 1, 1, 255, 1}}, /* ElixirCollector */+ {{1457, 1, 5, 255, 1}, {1457, 1, 5, 255, 1}, {1457, 1, 5, 255, 1}}, /* Xbow */+ {{1462, 1, 1, 255, 1}, {1462, 1, 1, 255, 1}, {1462, 1, 1, 255, 1}}, /* Tombstone */+ {{1463, 3, 1, 255, 3}, {1463, 3, 1, 255, 3}, {1463, 3, 1, 255, 3}}, /* BalloonBomb */+ {{1466, 3, 1, 255, 3}, {1466, 3, 1, 255, 3}, {1466, 3, 1, 255, 3}}, /* GiantSkeletonBomb */+};++const UnitDef UNITS[NUNITS] = {+ {"Wizard", 2400, 0, 1000, 500, 8000, 0, 8000, 0, 0, 1400, 0, 0, 0, 0, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING | U_TOWER | U_KING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 102, 60, -6, 2, 255, 2400, -1}, /* KingTower */+ {"Archer Tower", 1400, 0, 800, 0, 8500, 0, 8500, 0, 0, 1000, 0, 1, 0, 0, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING | U_TOWER,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 102, 70, -5, 5, 33, 2200, 25}, /* PrincessTower */+ {"Knight", 600, 75, 1100, 700, 1500, 0, 6000, 60, 1000, 500, 6, 255, 0, 0, U_GROUND,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 85, 85, 0, -10, 255, 0, -1}, /* Knight */+ {"Archer", 125, 0, 1200, 1000, 5500, 0, 6000, 60, 1000, 500, 3, 2, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 1, 75, 75, 0, -15, 255, 0, -1}, /* Archer */+ {"Goblin", 80, 50, 1100, 900, 1000, 0, 6000, 120, 1000, 500, 2, 255, 0, 0, U_GROUND,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 2, 50, 50, -5, 5, 255, 0, -1}, /* Goblin */+ {"Giant", 2000, 120, 1500, 1000, 2000, 0, 8000, 45, 1000, 750, 18, 255, 0, 0, U_GROUND | U_BUILDINGS | U_NOPUSH,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 85, 80, 0, 0, 255, 0, -1}, /* Giant */+ {"P.E.K.K.A.", 2600, 450, 1800, 1200, 1500, 0, 6000, 45, 3000, 750, 18, 255, 0, 0, U_GROUND | U_NOPUSH,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 80, 80, 0, 0, 255, 0, -1}, /* Pekka */+ {"Minion", 90, 0, 1000, 500, 2500, 0, 6000, 90, 1000, 500, 2, 3, 0, 0, U_GROUND | U_AIR | U_FLY,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 1500, 0, 0, 5, 85, -60, 0, 20, 255, 0, -1}, /* Minion */+ {"Balloon", 1000, 600, 3000, 2800, 400, 0, 8000, 60, 1000, 300, 6, 255, 0, 0, U_GROUND | U_BUILDINGS | U_FLY | U_NOPUSH,+ 0, 0, 0, 34, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3000, 0, 0, 6, 85, 50, 0, -10, 255, 0, -1}, /* Balloon */+ {"Witch", 500, 0, 700, 200, 5500, 0, 6000, 60, 1000, 500, 4, 4, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 12, 3, 5, 300, 6900, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 80, 80, 0, 0, 255, 0, -1}, /* Witch */+ {"Barbarian", 300, 75, 1500, 1000, 1200, 0, 6000, 60, 1000, 500, 4, 255, 0, 0, U_GROUND,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 8, 85, 85, 0, -10, 255, 0, -1}, /* Barbarian */+ {"Golem", 3150, 186, 2500, 1500, 1500, 0, 8000, 45, 3000, 750, 20, 255, 0, 0, U_GROUND | U_BUILDINGS | U_NOPUSH,+ 186, 2000, 1800, 35, 2, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, -85, 80, 0, 0, 255, 0, -1}, /* Golem */+ {"Skeleton", 27, 27, 1000, 500, 750, 0, 6000, 90, 1000, 500, 1, 255, 0, 0, U_GROUND,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 10, 50, 50, -5, 5, 255, 0, -1}, /* Skeleton */+ {"Valkyrie", 800, 110, 1500, 1300, 1500, 0, 6000, 60, 1000, 500, 5, 255, 2000, 0, U_GROUND | U_NOPUSH | U_SELFAOE,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, -85, 80, 0, 0, 255, 0, -1}, /* Valkyrie */+ {"Bomber", 150, 0, 1900, 1700, 5000, 0, 6000, 60, 1000, 500, 4, 5, 0, 0, U_GROUND,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 50, 50, -5, 5, 255, 0, -1}, /* Bomber */+ {"Musketeer", 340, 0, 1100, 600, 6500, 0, 6500, 60, 1000, 750, 5, 6, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 80, 80, 0, -10, 255, 0, -1}, /* Musketeer */+ {"Baby Dragon", 800, 0, 1800, 1300, 3500, 0, 6000, 90, 1000, 500, 5, 7, 0, 0, U_GROUND | U_AIR | U_FLY | U_NOPUSH,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3500, 0, 0, 14, 85, -60, 0, 20, 255, 0, -1}, /* BabyDragon */+ {"Prince", 1100, 220, 1500, 1000, 2500, 0, 6000, 60, 1000, 650, 6, 255, 0, 0, U_GROUND | U_NOPUSH,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 250, 440, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 80, 80, 0, 0, 255, 0, -1}, /* Prince */+ {"Wizard", 340, 0, 1700, 1500, 5500, 0, 6000, 60, 1000, 700, 5, 8, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 80, 80, 0, 0, 255, 0, -1}, /* Wizard */+ {"Mini P.E.K.K.A.", 600, 325, 1800, 1300, 1500, 0, 6000, 90, 1000, 450, 4, 255, 0, 0, U_GROUND | U_NOPUSH,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 80, 80, 0, 0, 255, 0, -1}, /* MiniPekka */+ {"Spear Goblin", 52, 0, 1300, 1100, 5500, 0, 6000, 120, 1000, 500, 1, 9, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 18, 75, 75, 0, -15, 255, 0, -1}, /* SpearGoblin */+ {"Giant Skeleton", 1800, 100, 1500, 1000, 2000, 0, 6000, 60, 1000, 1200, 15, 255, 0, 0, U_GROUND | U_NOPUSH,+ 0, 0, 0, 36, 1, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 50, 50, -5, 5, 255, 0, -1}, /* GiantSkeleton */+ {"Hog Rider", 800, 160, 1500, 1000, 1400, 0, 10000, 120, 1000, 600, 4, 255, 0, 0, U_GROUND | U_BUILDINGS | U_JUMP,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 20, 85, 85, 0, -10, 255, 0, -1}, /* HogRider */+ {"Cannon", 450, 0, 800, 0, 6000, 0, 6000, 0, 1000, 600, 0, 10, 0, 40000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 90, -90, -7, 10, 255, 0, -1}, /* Cannon */+ {"Goblin Hut", 700, 0, 10000, 0, 0, 0, 0, 0, 1000, 1000, 0, 255, 0, 60000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 20, 1, 2, 0, 4950, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 90, 60, -8, 0, 255, 0, -1}, /* GoblinHut */+ {"Mortar", 600, 0, 5000, 4000, 12000, 5000, 12000, 0, 3000, 600, 0, 11, 0, 30000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 80, 80, 0, 0, 255, 0, -1}, /* Mortar */+ {"Inferno Tower", 850, 20, 400, 1600, 6500, 0, 6500, 0, 1000, 600, 0, 255, 0, 45000, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 75, 2000, 400, 2000, 0, 0, 0, 0, 0, 0, 29, 90, 70, -5, 15, 255, 0, -1}, /* InfernoTower */+ {"Bomb Tower", 900, 0, 1600, 1100, 6500, 0, 6500, 0, 1000, 600, 0, 12, 0, 60000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 100, 85, -8, 0, 14, 3200, 31}, /* BombTower */+ {"Barbarian Hut", 1100, 0, 10000, 0, 0, 0, 0, 0, 1000, 1000, 0, 255, 0, 60000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 10, 2, 2, 500, 13500, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 90, 60, -8, 0, 255, 0, -1}, /* BarbarianHut */+ {"Tesla", 420, 64, 700, 0, 6000, 0, 6000, 0, 1000, 500, 0, 255, 0, 60000, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING | U_HIDES,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 800, 800, 33, 80, 80, 0, 0, 255, 0, -1}, /* Tesla */+ {"Elixir Collector", 800, 0, 0, 0, 0, 0, 0, 0, 1000, 1000, 0, 255, 0, 70000, U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9800, 1, 0, 0, 0, 0, 34, 55, 50, -15, 0, 255, 0, -1}, /* ElixirCollector */+ {"X-Bow", 850, 0, 300, 0, 13000, 0, 13000, 0, 5000, 600, 0, 13, 0, 40000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 80, 80, 0, 0, 255, 0, -1}, /* Xbow */+ {"Tombstone", 200, 0, 10000, 0, 0, 0, 0, 0, 1000, 1000, 0, 255, 0, 60000, U_GROUND | U_NOPUSH | U_BUILDING,+ 0, 0, 0, 12, 4, 12, 1, 2, 0, 2950, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 90, 60, -8, 0, 255, 0, -1}, /* Tombstone */+ {"Archer", 125, 0, 1200, 1000, 5500, 0, 6000, 60, 1000, 500, 3, 1, 0, 0, U_GROUND | U_AIR,+ 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 400, 0, 0, 0, 21, 75, 75, 0, -15, 255, 0, -1}, /* PrincessB */+ {"Bomb", 0, 0, 0, 0, 0, 0, 0, 0, 1000, 450, 0, 255, 0, 0, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING | U_BOMB,+ 100, 2000, 0, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0, 0, 0, 255, 0, -1}, /* BalloonBomb */+ {"Golemite", 630, 37, 2500, 1500, 750, 0, 8000, 45, 1000, 500, 6, 255, 0, 0, U_GROUND | U_BUILDINGS,+ 37, 2000, 1800, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 50, 50, -5, 5, 255, 0, -1}, /* Golemite */+ {"Bomb", 0, 0, 0, 0, 0, 0, 0, 0, 1000, 450, 0, 255, 0, 0, U_GROUND | U_AIR | U_NOPUSH | U_BUILDING | U_BOMB,+ 720, 3000, 1800, 255, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 255, 0, -1}, /* GiantSkeletonBomb */+};++const ProjDef PROJS[NPROJS] = {+ {850, 50, 0, 0, P_HOMING, 255, 0, 0, 0, 0, 1471}, /* KingProjectile */+ {400, 50, 0, 0, P_HOMING | P_ARROW, 255, 0, 0, 0, 60, -1}, /* PrincessProjectile */+ {400, 40, 0, 0, P_HOMING | P_ARROW, 255, 0, 0, 0, 60, -1}, /* ArcherArrow */+ {1000, 40, 0, 0, P_HOMING, 255, 0, 0, 0, 0, 1471}, /* MinionSpit */+ {600, 35, 1000, 0, P_HOMING | P_AOE_GROUND | P_AOE_AIR, 255, 0, 0, 0, 0, 1472}, /* WitchProjectile */+ {300, 100, 1500, 0, P_AOE_GROUND, 255, 0, 0, 0, 200, 1473}, /* BombSkeletonProjectile */+ {1000, 90, 0, 0, P_HOMING, 255, 0, 0, 0, 0, 1471}, /* MusketeerProjectile */+ {500, 100, 1200, 0, P_HOMING | P_AOE_GROUND | P_AOE_AIR, 255, 0, 0, 0, 250, 1474}, /* BabyDragonProjectile */+ {600, 130, 1200, 0, P_HOMING | P_AOE_GROUND | P_AOE_AIR, 255, 0, 0, 0, 0, 1475}, /* chr_wizardProjectile */+ {350, 24, 0, 0, P_HOMING | P_SPEAR, 255, 0, 0, 0, 150, -1}, /* SpearGoblinProjectile */+ {1000, 60, 0, 0, P_HOMING, 255, 0, 0, 0, 0, 1476}, /* TowerCannonball */+ {300, 120, 1800, 0, P_AOE_GROUND, 255, 0, 0, 0, 60, 1477}, /* MortarProjectile */+ {300, 100, 1500, 0, P_AOE_GROUND, 255, 0, 0, 0, 200, 1473}, /* BombTowerProjectile */+ {1400, 20, 0, 0, P_HOMING | P_ARROW, 255, 0, 0, 0, 0, -1}, /* xbow_projectile */+ {600, 325, 2500, 1800, P_AOE_GROUND | P_AOE_AIR | P_REDUCED, 255, 0, 0, 0, 50, 1478}, /* FireballSpell */+ {600, 0, 0, 0, P_HOMING | P_AOE_GROUND | P_AOE_AIR | P_ARROW, 255, 0, 0, 0, 50, -1}, /* ArrowsSpellDeco */+ {350, 700, 2000, 1800, P_AOE_GROUND | P_AOE_AIR | P_REDUCED, 255, 0, 0, 0, 50, 1479}, /* RocketSpell */+ {400, 50, 1500, 0, P_AOE_GROUND | P_REDUCED, 4, 3, 5, 1200, 40, 1480}, /* GoblinBarrelSpell */+ {500, 650, 0, 0, P_REDUCED, 255, 0, 0, 0, 0, -1}, /* LighningSpell */+};++const AreaDef AREAS[NAREAS] = {+ {5000, 10000, 600, 300, 0, A_OWN | A_GROUND | A_AIR, 500, 0, 255, 135, 135, 135}, /* Rage */+ {3000, 5000, 300, 0, 0, A_ENEMIES | A_GROUND | A_AIR, 5000, 300, 255, -100, -100, -100}, /* Freeze */+ {3500, 1500, 0, 460, 0, A_ENEMIES | A_BIGGEST | A_GROUND | A_AIR, 0, 0, 18, 0, 0, 0}, /* Lightning */+ {2500, 1, 0, 0, 85, A_ENEMIES | A_REDUCED | A_GROUND | A_AIR, 0, 0, 255, 0, 0, 0}, /* Zap */+};++const CardDef CARDS[NCARDS] = {+ {"Knight", "A tough melee fighter. The Barbarian´s handsome, cultured cousin. Rumor has it that he was knighted based on the sheer awesomeness of his mustache alone.", 0, 3, 0, 1, 2, 255, 255, 0, 0, 1501}, /* Knight */+ {"Archers", "A pair of unarmored ranged attackers. They´ll help you with ground and air unit attacks, but you´re on your own with coloring your hair.", 0, 3, 0, 2, 3, 255, 255, 0, 0, 1503}, /* Archer */+ {"Goblins", "Three fast, unarmored melee attackers. Small, fast, green and mean!", 0, 2, 0, 3, 4, 255, 255, 0, 0, 1505}, /* Goblins */+ {"Giant", "Slow but durable, only attacks buildings. A real one-man wrecking crew!", 1, 5, 0, 1, 5, 255, 255, 0, 0, 1507}, /* Giant */+ {"P.E.K.K.A.", "A heavily armored, slow melee fighter. Swings from the hip but packs a huge punch.", 2, 7, 0, 1, 6, 255, 255, 0, 0, 1509}, /* Pekka */+ {"Minions", "Three fast, unarmored flying attackers. Roses are red, minions are blue, they can fly, and will crush you!", 0, 3, 0, 3, 7, 255, 255, 0, 0, 1511}, /* Minions */+ {"Balloon", "As pretty as they are, you won´t want a parade of THESE balloons showing up on the horizon. Drops powerful bombs and when shot down, crashes dealing area damage.", 2, 5, 0, 1, 8, 255, 255, 0, 0, 1513}, /* Balloon */+ {"Witch", "Summons skeletons, shoots destructo beams, has glowing pink eyes that unfortunately don´t shoot lasers.", 2, 5, 0, 1, 9, 255, 255, 0, 0, 1515}, /* Witch */+ {"Barbarians", "A horde of melee attackers with mean mustaches and even meaner tempers.", 0, 5, 0, 4, 10, 255, 255, 0, 0, 1517}, /* Barbarians */+ {"Golem", "Slow but durable, only attacks buildings. When destroyed, explosively splits into two Golemites and deals area damage!", 2, 8, 0, 1, 11, 255, 255, 0, 0, 1519}, /* Golem */+ {"Skeletons", "Four fast, very weak melee fighters. Swarm your enemies with this pile of bones!", 0, 1, 0, 4, 12, 255, 255, 0, 0, 1521}, /* Skeletons */+ {"Valkyrie", "Tough melee fighter, deals area damage around her. Swarm or horde, no problem! She can take them all out with a few spins.", 1, 4, 0, 1, 13, 255, 255, 0, 0, 1523}, /* Valkyrie */+ {"Skeleton Army", "Summons an army of skeletons. Meet Larry and his friends Harry, Gerry, Terry, Mary, etc.", 2, 4, 0, 20, 12, 255, 255, 0, 0, 1525}, /* SkeletonArmy */+ {"Bomber", "Small, lightly protected skeleton that throws bombs. Deals area damage that can wipe out a swarm of enemies.", 0, 3, 0, 1, 14, 255, 255, 0, 0, 1527}, /* Bomber */+ {"Musketeer", "Don´t be fooled by her delicately coiffed hair, the Musketeer is a mean shot with her trusty boomstick.", 1, 4, 0, 1, 15, 255, 255, 0, 0, 1529}, /* Musketeer */+ {"Baby Dragon", "Flying troop that deals area damage. Baby dragons hatch cute, hungry and ready for a barbeque.", 2, 4, 0, 1, 16, 255, 255, 0, 0, 1531}, /* BabyDragon */+ {"Prince", "Don´t let the little pony fool you. Once the Prince gets a running start, you WILL be trampled. Does 2x damage once he gets charging.", 2, 5, 0, 1, 17, 255, 255, 0, 0, 1533}, /* Prince */+ {"Wizard", "The most awesome man to ever set foot in the arena, the Wizard will blow you away with his handsomeness... and/or fireballs.", 1, 5, 0, 1, 18, 255, 255, 0, 0, 1535}, /* Wizard */+ {"Mini P.E.K.K.A.", "The arena is a certified butterfly-free zone. No distractions for P.E.K.K.A, only destruction.", 1, 4, 0, 1, 19, 255, 255, 0, 0, 1537}, /* MiniPekka */+ {"Spear Goblins", "Three unarmored ranged attackers. Who the heck taught these guys to throw spears!?! Who thought that was a good idea?!", 0, 2, 0, 3, 20, 255, 255, 0, 0, 1539}, /* SpearGoblins */+ {"Giant Skeleton", "The bigger the skeleton, the bigger the bomb. Carries a bomb that blows up when the Giant Skeleton dies.", 2, 6, 0, 1, 21, 255, 255, 0, 0, 1541}, /* GiantSkeleton */+ {"Hog Rider", "Fast melee troop that targets buildings and can jump over the river. He followed the echoing call of 'Hog Riderrrrr' all the way through the arena doors.", 1, 4, 0, 1, 22, 255, 255, 0, 0, 1543}, /* HogRider */+ {"Minion Horde", "Six fast, unarmored flying attackers. Three's a crowd, six is a horde!", 0, 5, 0, 6, 7, 255, 255, 0, 0, 1545}, /* MinionHorde */+ {"Cannon", "Defensive building. Shoots cannonballs with deadly effect, but cannot target flying troops.", 0, 3, 1, 1, 23, 255, 255, 0, 0, 1547}, /* Cannon */+ {"Goblin Hut", "Building that spawns Spear Goblins. But don´t look inside. You don´t want to see how they are made.", 1, 5, 1, 1, 24, 255, 255, 0, 0, 1549}, /* GoblinHut */+ {"Mortar", "Defensive building with a long range. Shoots exploding shells that deal area damage. Cannot shoot at targets that get very close!", 0, 4, 1, 1, 25, 255, 255, 0, 0, 1551}, /* Mortar */+ {"Inferno Tower", "Defensive building, roasts targets for damage that increases over time. Burns through even the biggest and toughest enemies!", 1, 5, 1, 1, 26, 255, 255, 0, 0, 1553}, /* InfernoTower */+ {"Bomb Tower", "Defensive building that houses a Bomber. Deals area damage to anything dumb enough to stand near it.", 1, 5, 1, 1, 27, 255, 255, 0, 0, 1555}, /* BombTower */+ {"Barbarian Hut", "Troop building that periodically deploys Barbarians to fight the enemy. Time to make the Barbarians.", 1, 7, 1, 1, 28, 255, 255, 0, 0, 1557}, /* BarbarianHut */+ {"Tesla", "Defensive building. Whenever it's not zapping the enemy, the power of Electrickery is best kept grounded.", 0, 4, 1, 1, 29, 255, 255, 0, 0, 1559}, /* Tesla */+ {"Elixir Collector", "You gotta spend Elixir to make Elixir.", 1, 5, 1, 1, 30, 255, 255, 0, 0, 1561}, /* Elixir Collector */+ {"X-Bow", "Nice tower you got there. Would be a shame if this X-Bow whittled it down from this side of the arena...", 2, 6, 1, 1, 31, 255, 255, 0, 0, 1563}, /* Xbow */+ {"Tombstone", "Troop building that periodically deploys Skeletons to fight the enemy. When destroyed, spawns 4 Skeletons. Creepy!", 1, 3, 1, 1, 32, 255, 255, 0, 0, 1565}, /* Tombstone */+ {"Fireball", "Annnnnd... Fireball. Incinerates a small area, dealing high damage. Reduced damage to Crown Towers.", 1, 4, 2, 1, 255, 14, 255, 2500, 0, 1567}, /* Fireball */+ {"Arrows", "Arrows pepper a large area, damaging everyone hit. Reduced damage to Crown Towers.", 0, 3, 2, 1, 255, 15, 255, 4000, 15, 1569}, /* Arrows */+ {"Rage", "Increases troop movement and attack speed by 35%. Troop buildings and summoners deploy troops faster. Chaaaarge!", 2, 3, 2, 1, 255, 255, 0, 5000, 0, 1571}, /* Rage */+ {"Rocket", "Deals high damage to a small area. Looks really awesome doing it. Reduced damage to Crown Towers.", 1, 6, 2, 1, 255, 16, 255, 2000, 0, 1573}, /* Rocket */+ {"Goblin Barrel", "Spawns three Goblins anywhere on the Arena. It's going to be a thrilling ride, boys!", 2, 4, 2, 1, 255, 17, 255, 1500, 0, 1575}, /* GoblinBarrel */+ {"Freeze", "Freezes troops and buildings, making them unable to move or attack. Everybody chill.", 2, 4, 2, 1, 255, 255, 1, 3000, 0, 1577}, /* Freeze */+ {"Lightning", "Bolts of lightning hit up to 3 enemy troops or buildings with the most hitpoints in the target area. Reduced damage to Crown Towers.", 2, 6, 2, 1, 255, 255, 2, 3500, 0, 1579}, /* Lightning */+ {"Zap", "Lightning zaps enemies, dealing damage inside a small radius. Reduced damage to Crown Towers.", 0, 2, 2, 1, 255, 255, 3, 2500, 0, 1581}, /* Zap */+};++const uint8_t BOT_DECKS[NBOTDECKS][8] = {+ {CA_KNIGHT, CA_GOBLINS, CA_SKELETONS, CA_ARCHER, CA_BOMBER, CA_ARROWS, CA_FIREBALL, CA_GIANT}, /* BasicDeck7 */+ {CA_KNIGHT, CA_ARCHER, CA_GOBLINS, CA_SPEARGOBLINS, CA_GIANT, CA_GOBLINHUT, CA_FIREBALL, CA_BABYDRAGON}, /* BasicDeck8 */+ {CA_KNIGHT, CA_ARCHER, CA_GOBLINS, CA_SPEARGOBLINS, CA_GIANT, CA_GOBLINHUT, CA_ARROWS, CA_SKELETONARMY}, /* BasicDeck9 */+ {CA_KNIGHT, CA_ARCHER, CA_GOBLINS, CA_SKELETONS, CA_PRINCE, CA_SPEARGOBLINS, CA_ARROWS, CA_FIREBALL}, /* BasicDeck10 */+ {CA_VALKYRIE, CA_ARCHER, CA_WITCH, CA_SKELETONS, CA_TOMBSTONE, CA_GIANTSKELETON, CA_KNIGHT, CA_FIREBALL}, /* BasicDeck11 */+ {CA_KNIGHT, CA_ARCHER, CA_GOBLINS, CA_SKELETONS, CA_BOMBTOWER, CA_MINIONS, CA_TOMBSTONE, CA_BALLOON}, /* BasicDeck12 */+ {CA_BARBARIANS, CA_BARBARIANHUT, CA_SKELETONARMY, CA_SKELETONS, CA_WITCH, CA_FIREBALL, CA_CANNON, CA_ARROWS}, /* BasicDeck13 */+ {CA_MUSKETEER, CA_BOMBER, CA_BARBARIANHUT, CA_GOBLINS, CA_GIANT, CA_BALLOON, CA_ARCHER, CA_FIREBALL}, /* BasicDeck14 */+ {CA_MUSKETEER, CA_BOMBER, CA_MINIPEKKA, CA_GOBLINS, CA_PRINCE, CA_BALLOON, CA_ARCHER, CA_FIREBALL}, /* BasicDeck15 */+ {CA_KNIGHT, CA_ARCHER, CA_SKELETONARMY, CA_GOBLINS, CA_FIREBALL, CA_GIANT, CA_VALKYRIE, CA_MINIPEKKA}, /* BasicDeck16 */+ {CA_HOGRIDER, CA_INFERNOTOWER, CA_CANNON, CA_KNIGHT, CA_SPEARGOBLINS, CA_PRINCE, CA_ARCHER, CA_FIREBALL}, /* BasicDeck17 */+ {CA_WITCH, CA_PEKKA, CA_GOBLINS, CA_SPEARGOBLINS, CA_ZAP, CA_WIZARD, CA_ARCHER, CA_ARROWS}, /* BasicDeck18 */+ {CA_MUSKETEER, CA_MINIONHORDE, CA_ROCKET, CA_GOBLINS, CA_GIANT, CA_WIZARD, CA_ARCHER, CA_ARROWS}, /* BasicDeck19 */+ {CA_BARBARIANHUT, CA_TOMBSTONE, CA_BOMBTOWER, CA_GOBLINS, CA_GIANT, CA_SPEARGOBLINS, CA_PRINCE, CA_FIREBALL}, /* BasicDeck20 */+};++const int32_t GLOBALS[NGLOBALS] = {+ 10, /* MAX_MANA */+ 28000, /* MANA_REGEN_MS */+ 14000, /* MANA_REGEN_MS_END */+ 14000, /* MANA_REGEN_MS_OVERTIME */+ 60, /* MANA_SPEED_UP_WHEN_REMAINING_SECONDS */+ 5, /* START_MANA */+ 2000, /* NEXT_SPELL_COOLDOWN_MILLISECONDS */+ 1000, /* NEXT_SPELL_COOLDOWN_MILLISECONDS_BOOST */+ 1000, /* NEXT_SPELL_COOLDOWN_MILLISECONDS_OVERTIME */+ 10, /* DAMAGE_INCREASE_PERCENT_PER_SPELL_LEVEL */+ 10, /* HITPOINT_INCREASE_PERCENT_PER_SPELL_LEVEL */+ 7, /* DAMAGE_INCREASE_PERCENT_PER_KING_LEVEL */+ 7, /* HITPOINT_INCREASE_PERCENT_PER_KING_LEVEL */+ 8, /* DAMAGE_INCREASE_PERCENT_PER_TOWER_LEVEL */+ 8, /* HITPOINT_INCREASE_PERCENT_PER_TOWER_LEVEL */+ 2000, /* MELEE_RANGE_LIMIT */+ 50, /* REDUCED_TOWER_DAMAGE_PERCENT */+ 3300, /* KING_ACTIVATE_TIME_MS */+ 8, /* TOURNAMENT_MAX_EXP_LEVEL */+ 8, /* TOURNAMENT_MAX_COMMON_LEVEL */+ 6, /* TOURNAMENT_MAX_RARE_LEVEL */+ 3, /* TOURNAMENT_MAX_EPIC_LEVEL */+ 180, /* TOURNAMENT_MATCH_LENGTH_SECONDS */+ 180, /* MATCH_LENGTH */+ 60, /* OVERTIME_SECONDS */+};diff --git a/games/clashroyale/src/tables.h b/games/clashroyale/src/tables.hnew file mode 100644index 00000000..93bdb547--- /dev/null+++ b/games/clashroyale/src/tables.h@@ -0,0 +1,77 @@+/* Clash Royale: the game's numbers, as tools/pack.py reads them from its assets/csv_logic (tables.c).+ * Stats are at level 1 of the card's rarity; times in ms, distances in the game's units (1000 a tile),+ * speeds in tiles a minute (60: one tile a second). */+#ifndef CR_TABLES_H+#define CR_TABLES_H+#include <stdint.h>+#include "ids.h"++/* an animation: pictures img + dir * nf + frame; act: the frame that hits (255 none); len: the game's frames */+typedef struct {+ int16_t img;+ uint8_t nf, ndir, act, len;+} AnimDef;+typedef struct {+ AnimDef run, attack, idle;+} SetDef;++enum {+ U_GROUND = 1 << 0, /* AttacksGround */+ U_AIR = 1 << 1, /* AttacksAir */+ U_BUILDINGS = 1 << 2, /* TargetOnlyBuildings */+ U_FLY = 1 << 3, /* FlyingHeight */+ U_NOPUSH = 1 << 4, /* IgnorePushback (and buildings) */+ U_SELFAOE = 1 << 5, /* SelfAsAoeCenter: splash around itself (Valkyrie) */+ U_JUMP = 1 << 6, /* JumpEnabled: over the river (Hog Rider) */+ U_BUILDING = 1 << 7,+ U_HIDES = 1 << 8, /* HidesWhenNotAttacking (Tesla) */+ U_TOWER = 1 << 9, /* a crown tower */+ U_KING = 1 << 10,+ U_BOMB = 1 << 11 /* no hitpoints: explodes when deployed */+};++typedef struct {+ const char *name;+ int32_t hp, dmg, hit_ms, load_ms, range, min_range, sight, speed, deploy_ms, radius, mass, proj, area, life_ms;+ uint32_t flags;+ int32_t death_dmg, death_radius, death_push, death_unit, death_count;+ int32_t spawn_unit, spawn_number, spawn_level, spawn_interval, spawn_pause, spawn_start;+ int32_t charge_range, dmg_special, charge_mul;+ int32_t dmg2, t1, dmg3, t2; /* Inferno Tower: VariableDamage2, its time, VariableDamage3 */+ int32_t mana_ms, mana_amount; /* Elixir Collector */+ int32_t random_deploy, fly_height, hide_ms, up_ms;+ int32_t set; /* SETS[] */+ int32_t shadow_sx, shadow_sy, shadow_x, shadow_y;+ int32_t attached, attached_h, top_set; /* the Princess on her tower, the Bomber on his; the tower's top */+} UnitDef;++enum { P_HOMING = 1, P_AOE_GROUND = 2, P_AOE_AIR = 4, P_REDUCED = 8, P_ARROW = 16, P_SPEAR = 32 };+typedef struct {+ int32_t speed, dmg, radius, push;+ uint32_t flags;+ int32_t spawn_unit, spawn_count, spawn_level, spawn_deploy, gravity, img;+} ProjDef;++enum { A_ENEMIES = 1, A_OWN = 2, A_BIGGEST = 4, A_REDUCED = 8, A_GROUND = 16, A_AIR = 32 };+typedef struct {+ int32_t radius, life_ms, life_per_level, hit_ms, dmg;+ uint32_t flags;+ int32_t buff_ms, buff_per_level, proj, speed_mul, hit_mul, spawn_mul;+} AreaDef;++enum { K_TROOP, K_BUILDING, K_SPELL };+enum { R_COMMON, R_RARE, R_EPIC, R_LEGENDARY };+typedef struct {+ const char *name, *info;+ int32_t rarity, cost, kind, count, unit, proj, area, radius, arrows, icon;+} CardDef;++extern const SetDef SETS[NSETS];+extern const UnitDef UNITS[NUNITS];+extern const ProjDef PROJS[NPROJS];+extern const AreaDef AREAS[NAREAS];+extern const CardDef CARDS[NCARDS];+extern const int32_t GLOBALS[NGLOBALS];+extern const uint8_t BOT_DECKS[NBOTDECKS][8]; /* the training camp's eight-card decks (predefined_decks.csv) */+#define GL(name) (GLOBALS[G_##name])+#endifdiff --git a/games/clashroyale/src/view.c b/games/clashroyale/src/view.cnew file mode 100644index 00000000..dd9abfea--- /dev/null+++ b/games/clashroyale/src/view.c@@ -0,0 +1,403 @@+/* The battle on screen: the arena, the units in depth order, the towers' hitpoints, the cursor, and the hand. */+#include <stdio.h>+#include <string.h>+#include "../../common/np_lz.h"+#include "game.h"+#include "gfx.h"+#include "res.h"++#define FIELD_H 180+#define HUD_Y 180+#define BLUE RGB(0x3C8CF0)+#define RED RGB(0xE8403C)+#define PINK RGB(0xD83CE0)+#define GOLD RGB(0xFFD23C)++static uint8_t arena_idx[SCREEN_W * FIELD_H];+static uint8_t arena_pal[512];+static int arena_loaded = -1;++void view_load_arena(int a) {+ if (a == arena_loaded) return;+ const uint8_t *s = section(SEC_ARENAS);+ if (a < 0 || a >= (int)rd32(s)) a = 0;+ const uint8_t *p = s + rd32(s + 4 + 4 * a);+ memcpy(arena_pal, p, 512);+ uint32_t n = rd32(p + 512);+ if (np_lz_unpack(p + 516, n, arena_idx, sizeof arena_idx) != (int32_t)sizeof arena_idx) memset(arena_idx, 0, sizeof arena_idx);+ arena_loaded = a;+}++/* ------------------------------------------------------------------ units */+static const uint8_t DSLOT[8] = {2, 3, 4, 3, 2, 1, 0, 1}; /* the face's picture: the game's 1, 3, 5, 7, 9 */+static const uint8_t DMIR[8] = {0, 0, 0, 1, 1, 1, 0, 0};++static int height_px(int32_t h) { return h * 6 / 1000; } /* (heights drawn a little lower than the game's) */++static int anim_frame(const Ent *e, const AnimDef *a, const UnitDef *d) {+ if (a->nf <= 1) return 0;+ if (e->anim == 0) {+ int f = (int)((e->anim_ms * 30 / 1000) % (a->len ? a->len : 1));+ return f * a->nf / (a->len ? a->len : 1);+ }+ if (e->anim == 1) {+ int fms = a->len * 1000 / 30 / a->nf;+ int act = a->act == 255 ? a->nf - 1 : a->act;+ if (fms && e->post / fms + act < a->nf && e->post < d->hit_ms) return act + e->post / fms;+ return d->hit_ms ? act * e->t / d->hit_ms : 0;+ }+ return 0;+}++static int unit_img(const Ent *e, bool *mirror) {+ const UnitDef *d = &UNITS[e->type];+ const SetDef *s = &SETS[d->set];+ const AnimDef *a = e->anim == 0 ? &s->run : e->anim == 1 ? &s->attack : &s->idle;+ if (d->flags & U_HIDES) { /* Tesla: up, half, down */+ a = &s->idle;+ *mirror = false;+ return a->img + (e->hidden ? 2 : e->hide_t > 0 ? 1 : 0);+ }+ int dir = 0;+ *mirror = false;+ if (a->ndir >= 5) dir = DSLOT[e->face], *mirror = DMIR[e->face];+ else if (a->ndir == 1 && !(d->flags & U_BUILDING)) *mirror = e->face >= 3 && e->face <= 5;+ int f = anim_frame(e, a, d);+ if (f >= a->nf) f = a->nf - 1;+ return a->img + dir * a->nf + f;+}++static void hp_bar(int x, int y, int w, int32_t hp, int32_t max, int team, bool number) {+ if (max <= 0) return;+ int fw = (int)((int64_t)(w - 2) * (hp > 0 ? hp : 0) / max);+ gfx_fill(x, y, w, 4, RGB(0x202020));+ gfx_fill(x + 1, y + 1, fw, 2, team ? RED : BLUE);+ if (number) {+ char t[12];+ snprintf(t, sizeof t, "%ld", (long)(hp > 0 ? hp : 0));+ gfx_text_oc(FONT_NUM, x + w / 2, y - 10, t, WHITE);+ }+}++static void draw_tower(const Ent *e) {+ const UnitDef *d = &UNITS[e->type];+ int px = e->x / 100, py = e->y / 100;+ bool mirror;+ gfx_ellipse(px, py + 2, d->radius / 100 + 3, d->radius / 160 + 2, BLACK, 7);+ if (d->flags & U_KING) {+ gfx_img_tint(SETS[d->set].idle.img, px, py, e->team, false, WHITE, e->flash > 0 ? 12 : 0);+ hp_bar(px - 16, py - 44, 32, e->hp, e->maxhp, e->team, true);+ return;+ }+ gfx_img_tint(SETS[d->set].idle.img, px, py, e->team, false, WHITE, e->flash > 0 ? 12 : 0);+ /* the tower's back wall, then the Princess (or the Bomber) standing in it, aiming */+ int top = py - d->attached_h * 77 / 10000;+ if (d->top_set >= 0) gfx_img(SETS[d->top_set].idle.img, px, top, e->team, false);+ if (d->attached != NONE) {+ Ent a = *e;+ a.type = (uint8_t)d->attached;+ int img = unit_img(&a, &mirror);+ gfx_img(img, px, top, e->team, mirror);+ }+ if (d->flags & U_TOWER) hp_bar(px - 14, py - 38, 28, e->hp, e->maxhp, e->team, true);+}++static void draw_unit(const Ent *e) {+ const UnitDef *d = &UNITS[e->type];+ if (d->flags & U_TOWER || d->attached != NONE) {+ draw_tower(e);+ if (d->flags & U_TOWER) return;+ }+ int px = e->x / 100, py = e->y / 100;+ int h = d->flags & U_FLY ? height_px(d->fly_height) : 0;+ if (d->flags & U_JUMP && e->x >= RIVER_X0 - 500 && e->x < RIVER_X1 + 500) {+ int32_t m = (RIVER_X0 + RIVER_X1) / 2, k = 1500 - (e->x > m ? e->x - m : m - e->x);+ if (k > 0) h = k * 12 / 1500;+ }+ bool mirror;+ int img = unit_img(e, &mirror);+ if (d->attached == NONE) {+ /* the shadow, a little of the side's colour in it: whose a Skeleton is, at a glance */+ gfx_ellipse(px, py, d->radius / 110 + 2, d->radius / 180 + 1, e->team ? RGB(0x500808) : RGB(0x081850), h ? 9 : 12);+ if (e->freeze > 0)+ gfx_img_tint(img, px, py - h, e->team, mirror, RGB(0xA0E0FF), 16);+ else if (e->deploy > 0)+ gfx_img_tint(img, px, py - h, e->team, mirror, WHITE, 14);+ else+ gfx_img_tint(img, px, py - h, e->team, mirror, WHITE, e->flash > 0 ? 12 : 0);+ }+ int bx, by, bw, bh;+ gfx_img_box(img, mirror, &bx, &by, &bw, &bh);+ if (e->deploy > 0 && d->deploy_ms) {+ /* the deploy clock */+ int w = 12, f = w * (d->deploy_ms - e->deploy) / d->deploy_ms;+ gfx_fill(px - w / 2, py + 3, w, 2, RGB(0x202020));+ gfx_fill(px - w / 2, py + 3, f, 2, WHITE);+ }+ if (e->hp < e->maxhp && !(d->flags & U_BOMB)) {+ int w = d->radius >= 700 ? 18 : 12;+ hp_bar(px - w / 2, py - h + by - 5, w, e->hp, e->maxhp, e->team, false);+ }+ if (d->dmg2 && (e->flags & E_ATTACKING) && ent_alive(&bt, e->target)) {+ /* the Inferno Tower's beam */+ const Ent *t = &bt.e[e->target];+ int th = UNITS[t->type].flags & U_FLY ? height_px(UNITS[t->type].fly_height) : 4;+ uint16_t c = e->lock >= d->t1 + d->t2 ? RGB(0xFFF080) : e->lock >= d->t1 ? RGB(0xFF9030) : RGB(0xE03020);+ gfx_line(px, py - 18, t->x / 100, t->y / 100 - th, c);+ gfx_line(px + 1, py - 18, t->x / 100 + 1, t->y / 100 - th, c);+ }+ if ((d->flags & U_HIDES) && !e->hidden && (e->flags & E_ATTACKING) && e->post < 150 && ent_alive(&bt, e->target)) {+ const Ent *t = &bt.e[e->target];+ gfx_line(px, py - 12, t->x / 100, t->y / 100 - 6, RGB(0xB0F0FF));+ }+}++/* ------------------------------------------------------------------ projectiles and effects */+static void draw_proj(const Proj *p) {+ const ProjDef *d = &PROJS[p->type];+ int px = p->x / 100, py = p->y / 100;+ int32_t total = p->total > 0 ? p->total : 1, t = p->t < total ? p->t : total;+ int z0 = height_px(p->z0);+ int arc = p->spell ? 34 : d->gravity >= 150 ? 18 : d->gravity ? 8 : 0;+ int h = z0 * (total - t) / total + arc * 4 * t / total * (total - t) / total;+ if (d->flags & (P_ARROW | P_SPEAR)) {+ int32_t dx = p->tx - p->x, dy = p->ty - p->y, dd = dist(0, 0, dx, dy);+ int lx = dd ? (int)(dx * 4 / dd) : 4, ly = dd ? (int)(dy * 4 / dd) : 0;+ uint16_t c = d->flags & P_SPEAR ? RGB(0xC0A070) : RGB(0xF0E8D0);+ gfx_line(px - lx, py - h - ly, px + lx / 2, py - h + ly / 2, c);+ if (!p->spell) gfx_line(px - lx, py - h - ly + 1, px, py - h + 1, RGB(0x604020));+ return;+ }+ if (d->img >= 0) {+ gfx_ellipse(px, py, 2, 1, BLACK, 8);+ gfx_img(d->img, px, py - h, 0, p->tx < p->sx);+ }+}++static void draw_fx(const Fx *f) {+ int t = f->t, len = f->len ? f->len : 1;+ switch (f->kind) {+ case FX_EXPLOSION:+ gfx_img(f->size >= 2 ? IMG_EXPLOSION + 6 * t / len : IMG_PUFF + 4 * t / len, f->x, f->y, 0, false);+ break;+ case FX_PUFF:+ case FX_SPLASH:+ gfx_img(IMG_PUFF + 4 * t / len, f->x, f->y - 4, 0, false);+ break;+ case FX_ZAP:+ gfx_img(IMG_ZAP + 3 * t / len, f->x, f->y, 0, false);+ gfx_ring(f->x, f->y, 25 * (len - t / 2) / len, 25 * (len - t / 2) / len, 2, RGB(0xC0F0FF), 20);+ break;+ case FX_LIGHTNING:+ gfx_img(IMG_LIGHTNING + 3 * t / len, f->x, f->y, 0, false);+ break;+ case FX_TEXT:+ gfx_text_oc(FONT_NUM, f->x, f->y - t / 60, "+1", PINK);+ break;+ }+}++/* ------------------------------------------------------------------ the field */+typedef struct {+ int16_t y;+ uint8_t kind, i;+} Item;+static Item items[MAXE + MAXP + MAXFX + 8];+static int nitems;++static int cmp_y(const Item *a, const Item *b) { return a->y - b->y; }++static void sort_items(void) {+ for (int i = 1; i < nitems; i++) { /* (insertion: nearly sorted from frame to frame) */+ Item v = items[i];+ int j = i - 1;+ while (j >= 0 && cmp_y(&items[j], &v) > 0) items[j + 1] = items[j], j--;+ items[j + 1] = v;+ }+}++static void collect(void) {+ nitems = 0;+ for (int i = 0; i < MAXE; i++)+ if (bt.e[i].used) {+ const UnitDef *d = &UNITS[bt.e[i].type];+ items[nitems++] = (Item){(int16_t)(bt.e[i].y / 100 + (d->flags & U_FLY ? 400 : 0)), 0, (uint8_t)i};+ }+ for (int i = 0; i < MAXP; i++)+ if (bt.p[i].used) items[nitems++] = (Item){(int16_t)(bt.p[i].y / 100 + 800), 1, (uint8_t)i};+ for (int i = 0; i < MAXFX; i++)+ if (bt.fx[i].used) items[nitems++] = (Item){(int16_t)(bt.fx[i].y + 600), 2, (uint8_t)i};+ sort_items();+}++static void draw_rubble(void) {+ for (int t = 0; t < 2; t++) {+ const Side *s = &bt.side[t];+ int32_t px = t ? ARENA_X - 6500 : 6500;+ for (int k = 0; k < 2; k++)+ if (s->princess[k] < 0) gfx_img(IMG_RUBBLE, px / 100, (k ? 14500 : 3500) / 100, 0, t);+ if (s->king < 0) gfx_img(IMG_RUBBLE + 1, (t ? ARENA_X - 3000 : 3000) / 100, 90, 0, t);+ }+}++static void draw_areas(void) {+ for (int i = 0; i < MAXA; i++) {+ const Area *a = &bt.a[i];+ if (!a->used) continue;+ const AreaDef *d = &AREAS[a->type];+ int r = d->radius / 100;+ if (d->speed_mul < 0) {+ gfx_ellipse(a->x / 100, a->y / 100, r, r, RGB(0xA8E8FF), 9);+ gfx_ring(a->x / 100, a->y / 100, r, r, 2, WHITE, 18);+ } else if (d->speed_mul > 0) {+ gfx_ellipse(a->x / 100, a->y / 100, r, r, RGB(0xC040E0), 8);+ gfx_ring(a->x / 100, a->y / 100, r, r, 2, RGB(0xE070FF), 18);+ } else if (d->proj != NONE) {+ gfx_ring(a->x / 100, a->y / 100, r, r, 1, RGB(0xE0F0FF), 10);+ }+ }+}++static void draw_zone(void) {+ /* where the card may go: the rest tinted red, as the game does while a card is held */+ int card = bt.side[0].hand[g.slot];+ if (card == NONE || CARDS[card].kind == K_SPELL) return;+ bool top = bt.side[1].princess[0] < 0, bot = bt.side[1].princess[1] < 0;+ int x0 = RIVER_X0 / 100, x1 = (RIVER_X1 + 4000) / 100;+ gfx_blend(x0, 0, SCREEN_W - x0, FIELD_H, RED, 7);+ /* (the open pockets: undo the tint by drawing them again from the arena) */+ if (top || bot) {+ for (int y = gfx_y0; y < gfx_y0 + BAND_H && y < FIELD_H; y++) {+ bool open = y < FIELD_H / 2 ? top : bot;+ if (!open) continue;+ const uint8_t *s = arena_idx + y * SCREEN_W;+ uint16_t *d = gfx_band + (y - gfx_y0) * SCREEN_W;+ for (int x = RIVER_X1 / 100; x < x1; x++) d[x] = (uint16_t)(arena_pal[2 * s[x]] | arena_pal[2 * s[x] + 1] << 8);+ }+ }+}++static void draw_cursor(void) {+ int card = bt.side[0].hand[g.slot];+ int x = g.cx * 10, y = g.cy * 10;+ int32_t ux = g.cx * 1000 + 500, uy = g.cy * 1000 + 500;+ bool ok = card != NONE && battle_can_place(&bt, 0, card, ux, uy);+ uint16_t c = ok ? WHITE : RED;+ if (card != NONE) {+ const CardDef *cd = &CARDS[card];+ if (cd->kind == K_SPELL) {+ int r = cd->radius / 100;+ gfx_ellipse(x + 5, y + 5, r, r, WHITE, 6);+ gfx_ring(x + 5, y + 5, r, r, 1, c, 26);+ } else if (cd->unit != NONE) {+ const UnitDef *u = &UNITS[cd->unit];+ int img = SETS[u->set].idle.img + (SETS[u->set].idle.ndir >= 5 ? 2 : 0) * SETS[u->set].idle.nf;+ int h = u->flags & U_FLY ? height_px(u->fly_height) : 0;+ gfx_img_tint(img, x + 5, y + 5 - h, 0, false, ok ? WHITE : RED, 16);+ if (cd->kind == K_BUILDING && u->range > 0 && u->range < 14000) {+ int r = u->range / 100;+ gfx_ring(x + 5, y + 5, r, r, 1, WHITE, 8);+ }+ }+ }+ gfx_frame_rect(x, y, 10, 10, c);+}++void view_battle(void) {+ if (!gfx_rows(0, FIELD_H)) return;+ gfx_arena(arena_idx, arena_pal, 0, FIELD_H);+ if (g.field && g.screen == SC_BATTLE) draw_zone();+ draw_rubble();+ draw_areas();+ for (int k = 0; k < nitems; k++) {+ const Item *it = &items[k];+ if (it->kind == 0) {+ const Ent *e = &bt.e[it->i];+ if (e->used) draw_unit(e);+ } else if (it->kind == 1) {+ if (bt.p[it->i].used) draw_proj(&bt.p[it->i]);+ } else if (bt.fx[it->i].used) {+ draw_fx(&bt.fx[it->i]);+ }+ }+ if (g.field && g.screen == SC_BATTLE) draw_cursor();+ /* the time left, top right */+ char t[16];+ int32_t s = (bt.time_ms + 999) / 1000;+ snprintf(t, sizeof t, "%ld:%02ld", (long)(s / 60), (long)(s % 60));+ gfx_blend(250, 0, 70, 30, BLACK, 14);+ gfx_text_c(FONT_SMALL, 285, 1, bt.overtime ? "Overtime" : "Time left", bt.overtime ? RGB(0xFF8060) : RGB(0xE0E0E0));+ gfx_text_oc(FONT_MID, 285, 14, t, bt.overtime || bt.time_ms <= 60000 ? RGB(0xFFB040) : WHITE);+ if (battle_double(&bt)) gfx_text_oc(FONT_NUM, 285, 33, "Elixir x2", PINK);+ if (g.msg && g.msg_t > 0) {+ int w = gfx_text_w(FONT_MID, g.msg) + 16;+ gfx_blend(160 - w / 2, 76, w, 24, BLACK, 18);+ gfx_text_oc(FONT_MID, 160, 81, g.msg, WHITE);+ }+}++/* ------------------------------------------------------------------ the hand */+static void card_at(int card, int x, int y, bool big, bool dim) {+ if (card == NONE) {+ gfx_round_rect(x, y, 36, 45, 3, RGB(0x6A4A2A));+ return;+ }+ const CardDef *c = &CARDS[card];+ gfx_img_dim(c->icon, x + 18, y + 22, 0, false, dim ? 18 : 0);+ if (big) {+ gfx_img(IMG_DROP_BIG, x + 6, y + 38, 0, false);+ char t[4];+ snprintf(t, sizeof t, "%ld", (long)c->cost);+ gfx_text_oc(FONT_NUM, x + 6, y + 34, t, WHITE);+ }+}++void view_hud(void) {+ if (!gfx_rows(HUD_Y, SCREEN_H - HUD_Y)) return;+ const Side *s = &bt.side[0];+ gfx_fill(0, HUD_Y, SCREEN_W, SCREEN_H - HUD_Y, RGB(0xC48B52));+ gfx_fill(0, HUD_Y, SCREEN_W, 2, RGB(0x6E4423));+ /* next */+ gfx_text_c(FONT_SMALL, 20, HUD_Y + 4, "Next", RGB(0x3A2210));+ if (s->nqueue) {+ const CardDef *c = &CARDS[s->queue[0]];+ gfx_img(c->icon + 1, 20, HUD_Y + 34, 0, false);+ }+ /* the four cards */+ for (int k = 0; k < 4; k++) {+ int x = 42 + k * 44, y = HUD_Y + 5;+ int card = s->hand[k];+ bool sel = k == g.slot && (g.field || g.screen == SC_BATTLE);+ if (sel) y -= 3;+ gfx_round_rect(x - 2, y - 2, 40, 49, 3, sel ? (g.field ? WHITE : GOLD) : RGB(0x8A5A30));+ bool afford = card != NONE && CARDS[card].cost <= s->elixir;+ card_at(card, x, y, true, !afford);+ char n[2] = {(char)('1' + k), 0};+ gfx_text_o(FONT_NUM, x + 28, y + 1, n, sel ? GOLD : WHITE);+ }+ /* elixir */+ int ex = 42, ey = SCREEN_H - 9, ew = 176;+ gfx_fill(ex, ey, ew, 7, RGB(0x3A2416));+ int32_t regen = battle_regen_ms(&bt);+ int32_t fill = s->elixir * 1000 + (s->elixir < GL(MAX_MANA) ? s->elixir_t * 1000 / regen : 0);+ int fw = (int)((ew - 2) * fill / (GL(MAX_MANA) * 1000));+ gfx_fill(ex + 1, ey + 1, fw, 5, PINK);+ for (int k = 1; k < 10; k++) gfx_fill(ex + 1 + (ew - 2) * k / 10, ey + 1, 1, 5, RGB(0x3A2416));+ gfx_img(IMG_DROP_BIG, 22, SCREEN_H - 12, 0, false);+ char t[4];+ snprintf(t, sizeof t, "%ld", (long)s->elixir);+ gfx_text_oc(FONT_MID, 22, SCREEN_H - 22, t, WHITE);+ /* crowns and keys */+ gfx_img(IMG_CROWN, 234, HUD_Y + 12, 0, false);+ snprintf(t, sizeof t, "%d", bt.side[0].crowns);+ gfx_text_o(FONT_MID, 246, HUD_Y + 4, t, BLUE);+ gfx_text_o(FONT_MID, 260, HUD_Y + 4, "-", WHITE);+ snprintf(t, sizeof t, "%d", bt.side[1].crowns);+ gfx_text_o(FONT_MID, 271, HUD_Y + 4, t, RED);+ uint16_t k = RGB(0x3A2210);+ static const char *const hand[3] = {"1-4: a card", "OK: place it", "Back: pause"};+ static const char *const field[3] = {"arrows: move", "OK: drop it", "Back: cancel"};+ for (int i = 0; i < 3; i++) gfx_text(FONT_SMALL, 224, HUD_Y + 21 + 13 * i, (g.field ? field : hand)[i], k);+}++void view_prepare(void) { collect(); }diff --git a/games/clashroyale/tests/rules.c b/games/clashroyale/tests/rules.cnew file mode 100644index 00000000..b4dfc61e--- /dev/null+++ b/games/clashroyale/tests/rules.c@@ -0,0 +1,385 @@+/* Clash Royale on a computer: the units against the spec's numbers (gamesrc/clashroyale/spec), whole battles bot+ * against bot, random keys, saves, and screenshots (build/shots, as PPM). */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include "game.h"+#include "gfx.h"+#include "plat.h"+#include "res.h"++extern const uint8_t cr_data[];+const uint8_t *cr_bin;+extern uint16_t host_fb[SCREEN_W * SCREEN_H];+extern uint32_t host_time, host_keys;+extern bool host_storage_full;+extern bool bot_plays_both;+void host_shot(const char *path);+void host_save_dir(const char *d);++static int fails, checks;+#define CHECK(c, ...) \+ do { \+ checks++; \+ if (!(c)) { \+ fails++; \+ printf("FAIL %s:%d: ", __FILE__, __LINE__); \+ printf(__VA_ARGS__); \+ printf("\n"); \+ } \+ } while (0)++static const uint8_t DECK[8] = {CA_KNIGHT, CA_ARCHER, CA_SKELETONARMY, CA_GOBLINS, CA_FIREBALL, CA_GIANT, CA_VALKYRIE, CA_MINIPEKKA};++/* an empty field: the towers only, no bot */+static void bare(Battle *b) {+ battle_init(b, DECK, DECK, 0, 1);+ b->bot[1].think = 1 << 30;+ b->bot[0].think = 1 << 30;+}++static void test_numbers(void) {+ Battle *b = malloc(sizeof *b);+ bare(b);+ /* towers at King level 8 */+ CHECK(b->e[b->side[0].king].maxhp == 3768, "King tower %ld HP", (long)b->e[b->side[0].king].maxhp);+ CHECK(b->e[b->side[0].king].dmg == 78, "King tower %ld damage", (long)b->e[b->side[0].king].dmg);+ CHECK(b->e[b->side[0].princess[0]].maxhp == 2352, "Princess tower %ld HP", (long)b->e[b->side[0].princess[0]].maxhp);+ CHECK(b->e[b->side[0].princess[0]].dmg == 84, "Princess tower %ld damage", (long)b->e[b->side[0].princess[0]].dmg);+ /* cards at tournament standard (spec/cards.md) */+ struct { int card; int32_t hp, dmg; } want[] = {+ {CA_KNIGHT, 1158, 144}, {CA_ARCHER, 241, 77}, {CA_GIANT, 3200, 192}, {CA_PEKKA, 3146, 544},+ {CA_MUSKETEER, 544, 144}, {CA_MINIPEKKA, 960, 520}, {CA_HOGRIDER, 1280, 256}, {CA_BABYDRAGON, 968, 121},+ {CA_CANNON, 868, 115}, {CA_GOLEM, 3811, 225}};+ for (unsigned i = 0; i < sizeof want / sizeof want[0]; i++) {+ const CardDef *c = &CARDS[want[i].card];+ int idx = card_lvl_index(want[i].card);+ const UnitDef *u = &UNITS[c->unit];+ int32_t d = u->proj != NONE ? PROJS[u->proj].dmg : u->dmg;+ CHECK(lv(u->hp, idx) == want[i].hp, "%s: %ld HP, want %ld", c->name, (long)lv(u->hp, idx), (long)want[i].hp);+ CHECK(lv(d, idx) == want[i].dmg, "%s: %ld damage, want %ld", c->name, (long)lv(d, idx), (long)want[i].dmg);+ }+ CHECK(CARDS[CA_KNIGHT].cost == 3 && CARDS[CA_GOLEM].cost == 8 && CARDS[CA_SKELETONS].cost == 1, "costs");+ CHECK(CARDS[CA_SKELETONARMY].count == 20 && CARDS[CA_MINIONHORDE].count == 6, "counts");+ CHECK(lv(PROJS[CARDS[CA_FIREBALL].proj].dmg, card_lvl_index(CA_FIREBALL)) == 520, "Fireball 520");+ CHECK(lv(AREAS[CARDS[CA_ZAP].area].dmg, card_lvl_index(CA_ZAP)) == 164, "Zap 164");+ CHECK(lv(PROJS[CARDS[CA_ARROWS].proj].dmg, card_lvl_index(CA_ARROWS)) == 221 && CARDS[CA_ARROWS].radius == 4000,+ "Arrows 221 in 4 tiles");+ CHECK(GL(MATCH_LENGTH) == 180 && GL(OVERTIME_SECONDS) == 60, "3 minutes and a minute of overtime");+ free(b);+}++static void test_elixir(void) {+ Battle *b = malloc(sizeof *b);+ bare(b);+ CHECK(b->side[0].elixir == 5, "start with 5 elixir");+ for (int i = 0; i < 56; i++) battle_step(b); /* 2.8 s */+ CHECK(b->side[0].elixir == 6, "an elixir every 2.8 s: %ld", (long)b->side[0].elixir);+ b->time_ms = 60000;+ b->side[0].elixir = 0, b->side[0].elixir_t = 0;+ for (int i = 0; i < 28; i++) battle_step(b); /* 1.4 s */+ CHECK(b->side[0].elixir == 1, "double elixir: one every 1.4 s: %ld", (long)b->side[0].elixir);+ /* the cycle: a played card goes to the back, the next comes after 2 s */+ bare(b);+ b->side[0].elixir = 10;+ uint8_t first = b->side[0].hand[0], next = b->side[0].queue[0];+ CHECK(battle_play(b, 0, 0, 5500, 9500), "play a card");+ CHECK(b->side[0].hand[0] == NONE && b->side[0].queue[b->side[0].nqueue - 1] == first, "to the back of the queue");+ for (int i = 0; i < 40; i++) battle_step(b);+ CHECK(b->side[0].hand[0] == next, "the next card after 2 s");+ /* where cards go */+ CHECK(!battle_can_place(b, 0, CA_KNIGHT, 20500, 3500), "no troops on the enemy side");+ CHECK(battle_can_place(b, 0, CA_FIREBALL, 25500, 3500), "spells anywhere");+ CHECK(!battle_can_place(b, 0, CA_KNIGHT, 15500, 9500), "not in the river");+ CHECK(!battle_can_place(b, 0, CA_KNIGHT, 6500, 3500), "not on a tower");+ free(b);+}++/* a Knight against a Knight, in the middle of the field away from the towers */+static void test_duel(void) {+ Battle *b = malloc(sizeof *b);+ bare(b);+ int lv8 = card_lvl_index(CA_KNIGHT);+ int a = battle_spawn(b, UN_KNIGHT, 0, lv8, 12500, 9000, 0);+ int c = battle_spawn(b, UN_KNIGHT, 1, lv8, 19500, 9000, 0);+ int steps = 0;+ while (ent_alive(b, a) && ent_alive(b, c) && steps < 2000) battle_step(b), steps++;+ bool one = ent_alive(b, a) != ent_alive(b, c);+ CHECK(one, "one Knight left");+ int w = ent_alive(b, a) ? a : c;+ /* nine hits of 144 kill 1158; the one that hits first takes eight */+ CHECK(b->e[w].hp == 1158 - 8 * 144, "the winner has %ld HP, want %d", (long)b->e[w].hp, 1158 - 8 * 144);+ /* they met near the middle */+ CHECK(b->e[w].x > 13000 && b->e[w].x < 19000, "met at x %ld", (long)b->e[w].x);+ free(b);+}++static void test_spells(void) {+ Battle *b = malloc(sizeof *b);+ bare(b);+ int k = battle_spawn(b, UN_KNIGHT, 1, card_lvl_index(CA_KNIGHT), 22500, 9500, 1 << 20);+ /* a Fireball from the hand */+ b->side[0].hand[0] = CA_FIREBALL;+ b->side[0].elixir = 10;+ CHECK(battle_play(b, 0, 0, 22500, 9500), "Fireball cast");+ for (int i = 0; i < 80 && b->e[k].hp == b->e[k].maxhp; i++) battle_step(b);+ CHECK(b->e[k].hp == 1158 - 520, "Fireball does 520: %ld left", (long)b->e[k].hp);+ /* half to a crown tower */+ int pt = b->side[1].princess[0];+ b->side[0].hand[1] = CA_FIREBALL;+ b->side[0].elixir = 10;+ CHECK(battle_play(b, 0, 1, b->e[pt].x, b->e[pt].y), "Fireball on a tower");+ for (int i = 0; i < 80 && b->e[pt].hp == b->e[pt].maxhp; i++) battle_step(b);+ CHECK(b->e[pt].maxhp - b->e[pt].hp == 260, "Fireball does 260 to a tower: %ld", (long)(b->e[pt].maxhp - b->e[pt].hp));+ /* Arrows */+ int k2 = battle_spawn(b, UN_KNIGHT, 1, card_lvl_index(CA_KNIGHT), 24500, 14000, 1 << 20);+ b->side[0].hand[3] = CA_ARROWS;+ b->side[0].elixir = 10;+ CHECK(battle_play(b, 0, 3, 24500, 14000), "Arrows cast");+ for (int i = 0; i < 80 && b->e[k2].hp == b->e[k2].maxhp; i++) battle_step(b);+ CHECK(b->e[k2].hp == 1158 - 221, "Arrows do 221: %ld left", (long)b->e[k2].hp);+ /* Zap at once */+ int g1 = battle_spawn(b, UN_GOBLIN, 1, card_lvl_index(CA_GOBLINS), 20500, 14500, 1 << 20);+ b->side[0].hand[2] = CA_ZAP;+ b->side[0].elixir = 10;+ battle_play(b, 0, 2, 20500, 14500);+ CHECK(!ent_alive(b, g1) || b->e[g1].hp == b->e[g1].maxhp - 164, "Zap 164");+ free(b);+}++static void test_rules(void) {+ Battle *b = malloc(sizeof *b);+ /* a Giant walks to the tower over the bridge and hits only buildings */+ bare(b);+ int gi = battle_spawn(b, UN_GIANT, 0, card_lvl_index(CA_GIANT), 9500, 3500, 0);+ int sk = battle_spawn(b, UN_SKELETON, 1, card_lvl_index(CA_SKELETONS), 18500, 3500, 0);+ b->e[sk].x = 18500;+ bool crossed_bridge = false, hit_tower = false;+ int pt = b->side[1].princess[0];+ for (int i = 0; i < 1200 && ent_alive(b, gi); i++) {+ battle_step(b);+ if (ent_alive(b, gi) && b->e[gi].x >= 15000 && b->e[gi].x < 17000) crossed_bridge |= b->e[gi].y >= 2500 && b->e[gi].y < 4500;+ if (b->e[pt].hp < b->e[pt].maxhp && ent_alive(b, gi) && b->e[gi].target == pt) hit_tower = true;+ }+ CHECK(crossed_bridge, "the Giant crossed on the bridge");+ CHECK(hit_tower, "the Giant hit the tower");+ /* the King wakes when a Princess tower falls */+ bare(b);+ int kt = b->side[1].king;+ CHECK(!(b->e[kt].flags & E_AWAKE), "the King sleeps");+ b->e[b->side[1].princess[1]].hp = 1;+ int ar = battle_spawn(b, UN_ARCHER, 0, 7, 12500, 14500, 0);+ for (int i = 0; i < 600 && ent_alive(b, b->side[1].princess[1] >= 0 ? b->side[1].princess[1] : -1); i++) battle_step(b);+ CHECK(b->side[1].princess[1] < 0 && b->side[0].crowns == 1, "a crown for the tower");+ for (int i = 0; i < 80; i++) battle_step(b);+ CHECK(b->e[kt].flags & E_AWAKE, "the King woke");+ (void)ar;+ /* overtime and the first crown */+ bare(b);+ b->time_ms = 100;+ for (int i = 0; i < 4; i++) battle_step(b);+ CHECK(b->overtime && !b->over && b->time_ms > 59000, "overtime");+ b->e[b->side[1].princess[0]].hp = 1;+ battle_spawn(b, UN_ARCHER, 0, 7, 12500, 3500, 0);+ for (int i = 0; i < 600 && !b->over; i++) battle_step(b);+ CHECK(b->over && b->winner == 0, "sudden death: the first crown wins");+ free(b);+}++/* bot against bot, whole battles */+static void test_battles(void) {+ Battle *b = malloc(sizeof *b);+ bot_plays_both = true;+ int wins[3] = {0}, longest = 0, maxe = 0, crowns = 0;+ for (int s = 0; s < 24; s++) {+ battle_init(b, BOT_DECKS[s % NBOTDECKS], BOT_DECKS[(s * 7 + 3) % NBOTDECKS], s % NARENAS, 1000 + (uint32_t)s);+ int steps = 0;+ while (!b->over && steps < 20 * 60 * 6) {+ battle_step(b);+ steps++;+ int n = 0;+ for (int i = 0; i < MAXE; i++) n += b->e[i].used;+ if (n > maxe) maxe = n;+ }+ CHECK(b->over, "battle %d ended", s);+ if (steps > longest) longest = steps;+ wins[b->winner]++;+ crowns += b->side[0].crowns + b->side[1].crowns;+ if (s < 2) printf("battle %d: crowns %d-%d, %ld and %ld cards played, %ld s\n", s, b->side[0].crowns, b->side[1].crowns,+ (long)b->side[0].played, (long)b->side[1].played, (long)(steps / 20));+ CHECK(b->side[0].played > 10 && b->side[1].played > 10, "both play cards: %ld %ld", (long)b->side[0].played, (long)b->side[1].played);+ }+ printf("bot battles: %d, %d, %d draws; longest %d s; at most %d units\n", wins[0], wins[1], wins[2], longest / 20, maxe);+ CHECK(crowns >= 6, "towers fall: %d crowns in 24 battles", crowns);+ /* and against no one, the bot takes all three crowns */+ bot_plays_both = false;+ for (int k = 0; k < NBOTDECKS; k++) {+ battle_init(b, DECK, BOT_DECKS[k], k % NARENAS, 50 + (uint32_t)k);+ for (int s = 0; s < 20 * 240 && !b->over; s++) battle_step(b);+ CHECK(b->over && b->winner == 1 && b->side[1].crowns == 3, "deck %d against no one: %d crowns", k, b->side[1].crowns);+ }+ bot_plays_both = true;+ /* a deterministic replay */+ battle_init(b, BOT_DECKS[0], BOT_DECKS[1], 3, 77);+ for (int i = 0; i < 2000 && !b->over; i++) battle_step(b);+ uint32_t h = 0;+ for (unsigned i = 0; i < sizeof *b; i++) h = h * 31 + ((uint8_t *)b)[i];+ Battle *c = malloc(sizeof *c);+ battle_init(c, BOT_DECKS[0], BOT_DECKS[1], 3, 77);+ for (int i = 0; i < 2000 && !c->over; i++) battle_step(c);+ uint32_t h2 = 0;+ for (unsigned i = 0; i < sizeof *c; i++) h2 = h2 * 31 + ((uint8_t *)c)[i];+ CHECK(h == h2, "the same start plays the same");+ bot_plays_both = false;+ free(b);+ free(c);+}++/* the game through its keys */+static void run(uint32_t keys, int steps) {+ for (int i = 0; i < steps && g.running; i++) {+ host_keys = keys;+ game_step(keys);+ host_time += 17;+ }+}+static void tap(uint32_t k) {+ run(k, 2);+ run(0, 3);+}+static void shot(const char *name) {+ char p[128];+ game_draw();+ snprintf(p, sizeof p, "build/shots/%s.ppm", name);+ host_shot(p);+}++static void test_play(void) {+ mkdir("build/shots", 0755);+ mkdir("build/host-saves", 0755);+ host_save_dir("build/host-saves");+ remove("build/host-saves/clashroyale.sav");+ remove("build/host-saves/crresume.sav");+ remove("build/host-saves/clashroyale_saves.py");+ game_init();+ shot("title");+ CHECK(g.screen == SC_TITLE, "the title");+ tap(K_OK); /* Battle: how to play first */+ CHECK(g.screen == SC_HELP, "how to play the first time");+ shot("help");+ tap(K_OK);+ CHECK(g.screen == SC_BATTLE, "the battle");+ run(0, 60 * 4);+ /* a card to the bridge */+ tap(K_DIGIT(1));+ CHECK(g.field, "the cursor on the field");+ for (int i = 0; i < 2; i++) tap(K_RIGHT);+ shot("place");+ tap(K_OK);+ run(0, 60 * 12);+ tap(K_DIGIT(2));+ tap(K_OK);+ run(0, 60 * 8);+ shot("battle");+ /* Home keeps the battle */+ run(K_HOME, 1);+ CHECK(!g.running, "Home quits");+ game_init();+ CHECK(g.screen == SC_PAUSE, "the battle back, paused");+ tap(K_BACK);+ CHECK(g.screen == SC_BATTLE, "and on");+ bot_plays_both = true;+ for (int i = 0; i < 60 * 60 * 5 && g.screen == SC_BATTLE; i++) run(0, 1);+ bot_plays_both = false;+ CHECK(g.screen == SC_RESULT, "the battle ended");+ shot("result");+ run(0, 60);+ tap(K_OK);+ CHECK(g.screen == SC_TITLE, "back to the title");+ CHECK(g.prof.wins + g.prof.losses + g.prof.draws == 1, "one battle counted");+ int32_t troph = g.prof.trophies;+ /* the deck: swap a card in */+ tap(K_DOWN);+ tap(K_OK);+ CHECK(g.screen == SC_DECK, "the deck");+ tap(K_DOWN), tap(K_DOWN), tap(K_DOWN);+ shot("deck");+ int card = (g.drow - 1) * 8 + g.dcol;+ bool in = false;+ for (int k = 0; k < 8; k++) in |= g.prof.deck[k] == card;+ tap(K_OK);+ if (!in) {+ tap(K_OK);+ CHECK(g.prof.deck[g.dcol] == card, "the card went into the deck");+ }+ tap(K_BACK);+ tap(K_BACK);+ CHECK(g.screen == SC_TITLE, "back from the deck");+ run(K_HOME, 1);+ /* the profile comes back, and from the copy alone */+ game_init();+ CHECK(g.prof.trophies == troph && g.prof.guide, "the profile kept");+ remove("build/host-saves/clashroyale.sav");+ game_init();+ CHECK(g.prof.trophies == troph && g.prof.wins + g.prof.losses + g.prof.draws == 1, "the profile from the copy");+}++/* a battle bot against bot as you would see it: build/shots/demo_*.ppm every 5 s */+static void test_demo(void) {+ bot_plays_both = true;+ memset(&g, 0, sizeof g);+ g.running = true;+ battle_init(&bt, BOT_DECKS[6], BOT_DECKS[2], 2, 4242);+ view_load_arena(2);+ g.screen = SC_BATTLE;+ for (int s = 0; s < 20 * 150 && !bt.over; s++) {+ battle_step(&bt);+ if (s % 100 == 99) {+ char n[32];+ snprintf(n, sizeof n, "demo_%03d", s / 20 + 1);+ shot(n);+ }+ }+ bot_plays_both = false;+}++static void test_fuzz(void) {+ static const uint32_t keys[] = {K_LEFT, K_RIGHT, K_UP, K_DOWN, K_OK, K_BACK, K_EXE, K_DIGIT(1), K_DIGIT(2), K_DIGIT(3),+ K_DIGIT(4), 0, 0, 0};+ srand(5);+ for (int s = 0; s < 300; s++) {+ game_init();+ for (int i = 0; i < 1500 && g.running; i++) {+ uint32_t k = keys[rand() % (sizeof keys / sizeof keys[0])];+ if (rand() % 400 == 0) k = K_HOME;+ run(k, 1 + rand() % 4);+ if (i % 200 == 0) game_draw();+ }+ if (g.running) run(K_HOME, 1);+ }+ CHECK(1, "fuzz");+ /* a damaged resume file is dropped */+ FILE *f = fopen("build/host-saves/crresume.sav", "wb");+ for (int i = 0; i < 300; i++) fputc(i * 37, f);+ fclose(f);+ game_init();+ CHECK(g.screen == SC_TITLE, "a damaged battle is not loaded");+}++int main(void) {+ cr_bin = cr_data;+ static uint16_t band[SCREEN_W * BAND_H];+ gfx_set_band_memory(band);+ test_numbers();+ test_elixir();+ test_duel();+ test_spells();+ test_rules();+ test_battles();+ test_play();+ test_demo();+ test_fuzz();+ printf("%d checks, %d failed\n", checks, fails);+ return fails != 0;+}diff --git a/games/clashroyale/tools/pack.py b/games/clashroyale/tools/pack.pynew file mode 100644index 00000000..92eaa417--- /dev/null+++ b/games/clashroyale/tools/pack.py@@ -0,0 +1,866 @@+#!/usr/bin/env python3+"""Clash Royale: the game's own numbers and pictures -> src/data.bin, src/data.h and src/tables.c.++ python3 -I tools/pack.py [APK] APK: Clash Royale's 2016 Android package (archive.org item clash-royale-2016,+ CLASHROYALE2016.apk); by default ~/Documents/Assets/gamesrc/clashroyale/dl/cr2016.apk++Everything comes from the package: the cards, characters, buildings, projectiles and spells from assets/csv_logic+(tables.c), the pictures from assets/sc (tools/sc.py draws them), the names from assets/csv_client/texts.csv, the+font from assets/font.++The arena is turned a quarter for the calculator's wide screen: your side on the left. One tile is 10 pixels, the+field 320 x 180. The game draws a tile 29.68 units wide and 24.12 high (its camera looks down at an angle), so the+pictures are drawn at 10 / 29.68 of their size; the ground is resampled to square tiles.++data.bin: "CRD1", the number of sections, their offsets (SEC_* in data.h), then:+- IMGS: the number of pictures, their offsets; a picture: width, height, x and y of its anchor (u16, u16, s16,+ s16), its mode (0: opaque, 1: 6-bit colour and 2-bit alpha), 0, 0, 0, the offsets of its blue and red palettes+ (u32, from the file's start), then for each row the offset of the row (u16, from the picture's start); a row: the+ number of runs (u8), each run its x, its length (u8) and its colours (u8 each)+- PALS: palettes: the number of colours (u16), then RGB565 each+- FONTS: for each font (FONT_*): line height, baseline, 0, 0, then 95 glyphs (32 to 126): advance, width, height,+ x and y (s8), 0, 0, 0, the offset of its 4-bit alpha rows (u32, from the section)+- ARENAS: the number of arenas, their offsets; an arena: 256 colours (RGB565), the packed size (u32), then the+ 320 x 180 picture as colour indices, packed (np_lz.h's LZSS)+"""+import csv+import io+import os+import struct+import sys+import zipfile++import numpy as np+from PIL import Image, ImageDraw, ImageFont+from scipy.cluster.vq import kmeans2++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import sc as SCF # noqa: E402++APK = os.path.expanduser('~/Documents/Assets/gamesrc/clashroyale/dl/cr2016.apk')+OUT = os.path.join(HERE, '..', 'src')+TILE = 10+SX, SY = 29.68, 24.115 # the game's units for a tile across and down+S = TILE / SX # pictures' scale+SECTIONS = ['IMGS', 'PALS', 'FONTS', 'ARENAS']+DIRS = (1, 3, 5, 7, 9) # the game's nine directions, up to down on the right; five of them kept++# ------------------------------------------------------------------ the package+++class Apk:+ def __init__(self, path):+ self.z = zipfile.ZipFile(path)+ self.cache = {}++ def read(self, name):+ return self.z.read('assets/' + name)++ def sc(self, name):+ if name not in self.cache:+ tex = name[:-3] + '_tex.sc'+ try:+ td = self.read(tex)+ except KeyError:+ td = None+ self.cache[name] = SCF.SC(self.read(name), td)+ self.cache[name].path = name+ return self.cache[name]++ def csv(self, name):+ rows = list(csv.reader(io.StringIO(self.read(name).decode('utf-8'))))+ h = rows[0]+ out, last = {}, None+ for row in rows[2:]:+ if row and row[0]:+ last = row[0]+ out[last] = {h[i]: v for i, v in enumerate(row) if i < len(h) and v != ''}+ return out+++# ------------------------------------------------------------------ pictures+++class Pics:+ def __init__(self):+ self.imgs = [] # bytes of each picture (palette offsets patched later)+ self.pals = [] # bytes of each palette+ self.names = {}++ def pal(self, colors):+ c = np.clip(np.round(np.asarray(colors, float) * 255), 0, 255).astype(int)+ b = struct.pack('<H', len(c)) + b''.join(struct.pack('<H', (r >> 3) << 11 | (g >> 2) << 5 | bl >> 3) for r, g, bl in c)+ if b in self.pals:+ return self.pals.index(b)+ self.pals.append(b)+ return len(self.pals) - 1++ def add(self, idx, mask, ax, ay, pb, pr, mode=0, name=None):+ """idx: colour indices (h x w), mask: which are drawn, (ax, ay) the anchor"""+ h, w = idx.shape+ ys, xs = np.nonzero(mask)+ if len(ys) == 0:+ ys, xs = np.array([0]), np.array([0])+ mask = np.zeros_like(mask)+ y0, y1, x0, x1 = ys.min(), ys.max() + 1, xs.min(), xs.max() + 1+ idx, mask = idx[y0:y1, x0:x1], mask[y0:y1, x0:x1]+ h, w = idx.shape+ assert w < 256, w+ rows = []+ for y in range(h):+ runs, x = [], 0+ while x < w:+ if not mask[y, x]:+ x += 1+ continue+ s = x+ while x < w and mask[y, x] and x - s < 255:+ x += 1+ runs.append(bytes([s, x - s]) + bytes(int(v) for v in idx[y, s:x]))+ rows.append(bytes([len(runs)]) + b''.join(runs))+ head = 20 + 2 * h+ offs, o = [], head+ for r in rows:+ offs.append(o)+ o += len(r)+ assert o < 65536+ b = struct.pack('<HHhhBBBB', w, h, int(ax - x0), int(ay - y0), mode, 0, 0, 0)+ b += struct.pack('<II', pb, pr) + b''.join(struct.pack('<H', v) for v in offs) + b''.join(rows)+ self.imgs.append(b)+ i = len(self.imgs) - 1+ if name:+ self.names[name] = i+ return i+++P = Pics()+++RCACHE = {}+RCACHE_FILE = os.path.join(HERE, '..', 'build', 'render-cache.pkl')+++def render(scf, name, frame, scale, size=(160, 160), anchor=(80, 120), hide=()):+ """(kept in build/render-cache.pkl between runs: drawing is the slow part)"""+ key = (getattr(scf, 'path', ''), name, frame, round(scale, 6), tuple(size), tuple(anchor), tuple(hide))+ if key in RCACHE:+ return RCACHE[key].astype(np.float32) / 255+ cv = SCF.Canvas(size[0], size[1], anchor[0], anchor[1], scale)+ cv.draw(scf, scf.pieces(name, frame, hide=hide))+ out = cv.rgba()+ RCACHE[key] = np.round(out * 255).astype(np.uint8)+ return RCACHE[key].astype(np.float32) / 255+++def quantize(pairs, k):+ """pairs: (n, 6) blue and red colours of the same pixels -> labels, blue palette, red palette"""+ uniq, inv = np.unique(np.round(pairs * 63).astype(np.int32), axis=0, return_inverse=True)+ inv = inv.reshape(-1)+ if len(uniq) <= k:+ cent = uniq / 63.0+ return inv, cent[:, :3], cent[:, 3:]+ rng = np.random.default_rng(1)+ sample = pairs if len(pairs) < 40000 else pairs[rng.choice(len(pairs), 40000, replace=False)]+ np.random.seed(1)+ cent, _ = kmeans2(sample.astype(np.float64), k, minit='++', iter=12, seed=1)+ d = ((pairs[:, None, :] - cent[None]) ** 2).sum(-1) if len(pairs) * k < 3e7 else None+ if d is None:+ lab = np.concatenate([((pairs[i:i + 20000, None, :] - cent[None]) ** 2).sum(-1).argmin(1)+ for i in range(0, len(pairs), 20000)])+ else:+ lab = d.argmin(1)+ return lab, cent[:, :3], cent[:, 3:]+++def add_group(frames, name=None, k=255, mode=0, thr=0.45):+ """frames: list of (blue rgba, red rgba or None, anchor x, anchor y); one palette pair for all -> picture ids"""+ pix, masks = [], []+ for fb, fr, ax, ay in frames:+ m = fb[..., 3] > thr+ if mode == 1:+ m = fb[..., 3] > 0.12+ masks.append(m)+ b = fb[..., :3][m]+ r = (fr if fr is not None else fb)[..., :3][m]+ pix.append(np.concatenate([b, r], 1))+ allp = np.concatenate(pix) if pix else np.zeros((1, 6))+ if len(allp) == 0:+ allp = np.zeros((1, 6))+ kk = 63 if mode == 1 else k+ lab, pb, pr = quantize(allp, kk)+ ib, ir = P.pal(pb), P.pal(pr)+ ids, o = [], 0+ for (fb, fr, ax, ay), m in zip(frames, masks):+ n = int(m.sum())+ idx = np.zeros(m.shape, np.int32)+ idx[m] = lab[o:o + n]+ o += n+ if mode == 1:+ a = np.clip(np.round(fb[..., 3] * 4 - 0.5), 0, 3).astype(np.int32)+ idx = idx | a << 6+ ids.append(P.add(idx, m, ax, ay, ib, ir, mode))+ if name:+ P.names[name] = ids[0]+ return ids+++# ------------------------------------------------------------------ characters and buildings: sprite sets++SETS = [] # (name, {anim: (first picture, frames, dirs, action frame, the game's frame count)})+++def sample(n, k, act=None):+ """k frames of n, evenly, the action frame among them"""+ if n <= k:+ return list(range(n))+ fr = sorted(set(int(i * n / k) for i in range(k)))+ if act is not None and act not in fr:+ j = min(range(len(fr)), key=lambda i: abs(fr[i] - act))+ fr[j] = act+ return sorted(set(fr))+++def char_set(apk, setname, file, blue, red, scale, nrun=6, natt=6, size=(96, 112), anchor=(48, 92), dirs=DIRS):+ scf = apk.sc(file)+ anims = {}+ frames, meta = [], []+ for an, k in (('run', nrun), ('attack', natt), ('idle', 1)):+ src = an+ ds = [d for d in dirs if '%s_%s1_%d' % (blue, an, d) in scf.exports]+ for alt in ('idle', 'run', 'attack'):+ if ds:+ break+ src = alt+ ds = [d for d in dirs if '%s_%s1_%d' % (blue, alt, d) in scf.exports]+ nd = len(ds)+ n0 = scf.frames('%s_%s1_%d' % (blue, src, ds[0]))+ labels = scf.labels('%s_%s1_%d' % (blue, src, ds[0]))+ act = labels.get('action_frame')+ fr = sample(n0, k, act) if an != 'idle' else [0]+ a = fr.index(act) if act in fr else 255+ first = len(frames)+ for d in ds:+ bn, rn = '%s_%s1_%d' % (blue, src, d), '%s_%s1_%d' % (red, src, d)+ if rn not in scf.exports:+ rn = bn+ for f in fr:+ fb = render(scf, bn, f, scale * S, size, anchor)+ frr = render(scf, rn, f, scale * S, size, anchor) if rn != bn else None+ frames.append((fb, frr, anchor[0], anchor[1]))+ meta.append((an, first, len(fr), nd, a, n0))+ ids = add_group(frames)+ for an, first, nf, nd, a, n0 in meta:+ anims[an] = (ids[first], nf, nd, a, n0)+ SETS.append((setname, anims))+ return len(SETS) - 1+++def still_set(apk, setname, file, blue, red, scale, frames_of=None, size=(110, 120), anchor=(55, 90), hide=()):+ """a building: one picture (or a few: frames_of = [frame numbers]) for each side; 'dirs' of one"""+ scf = apk.sc(file)+ if blue not in scf.exports and blue + '_idle1_1' in scf.exports:+ blue, red = blue + '_idle1_1', red + '_idle1_1'+ fl = frames_of or [0]+ frames = []+ for f in fl:+ fb = render(scf, blue, f, scale * S, size, anchor, hide)+ fr = render(scf, red, f, scale * S, size, anchor, hide) if red and red != blue else None+ frames.append((fb, fr, anchor[0], anchor[1]))+ ids = add_group(frames)+ a = {'idle': (ids[0], len(fl), 1, 255, len(fl))}+ SETS.append((setname, a))+ return len(SETS) - 1+++def turret_set(apk, setname, file, blue, red, scale, n=19, size=(110, 120), anchor=(55, 90)):+ """cannon and X-Bow: 19 frames from up to down on the right; 5 kept"""+ scf = apk.sc(file)+ fl = [0, 4, 9, 14, 18] if n == 19 else [int(i * (n - 1) / 4) for i in range(5)]+ frames = []+ for f in fl:+ frames.append((render(scf, blue, f, scale * S, size, anchor), render(scf, red, f, scale * S, size, anchor), *anchor))+ ids = add_group(frames)+ SETS.append((setname, {'idle': (ids[0], 1, 5, 255, 1)}))+ return len(SETS) - 1+++def effect(apk, file, name, scale, frames, size=(120, 120), anchor=(60, 60), mode=1, pname=None):+ scf = apk.sc(file)+ fl = [render(scf, name, f, scale * S, size, anchor) for f in frames]+ ids = add_group([(f, None, anchor[0], anchor[1]) for f in fl], mode=mode)+ if pname:+ P.names[pname] = ids[0]+ return ids+++# ------------------------------------------------------------------ the tables+++MULT = [100]+for _ in range(14):+ MULT.append(MULT[-1] * 110 // 100)+++def num(d, k, default=0):+ return int(d.get(k, default))+++def build(apk):+ chars = apk.csv('csv_logic/characters.csv')+ blds = apk.csv('csv_logic/buildings.csv')+ projs = apk.csv('csv_logic/projectiles.csv')+ aeos = apk.csv('csv_logic/area_effect_objects.csv')+ buffs = apk.csv('csv_logic/character_buffs.csv')+ glob = apk.csv('csv_logic/globals.csv')+ texts = {r[0]: r[1] for r in csv.reader(io.StringIO(apk.read('csv_client/texts.csv').decode('utf-8'))) if r}+ cards = []+ for kind, f in ((0, 'spells_characters'), (1, 'spells_buildings'), (2, 'spells_other')):+ for n, c in apk.csv('csv_logic/%s.csv' % f).items():+ if c.get('NotInUse') or n == 'Mirror':+ continue+ cards.append((kind, n, c))++ # units: everything a card summons, spawns, or leaves when it dies, and the towers+ unit_names = ['KingTower', 'PrincessTower']+ for kind, n, c in cards:+ if c.get('SummonCharacter'):+ unit_names.append(c['SummonCharacter'])+ p = c.get('Projectile')+ if p and projs[p].get('SpawnCharacter'):+ unit_names.append(projs[p]['SpawnCharacter'])+ i = 0+ while i < len(unit_names):+ u = chars.get(unit_names[i]) or blds[unit_names[i]]+ for k in ('SpawnCharacter', 'DeathSpawnCharacter', 'AttachedCharacter'):+ if u.get(k) and u[k] not in unit_names:+ unit_names.append(u[k])+ i += 1+ unit_names = list(dict.fromkeys(unit_names))+ proj_names = []+ for n in unit_names:+ u = chars.get(n) or blds[n]+ if u.get('Projectile'):+ proj_names.append(u['Projectile'])+ for kind, n, c in cards:+ # (Arrows: the first projectile, ArrowsSpell, does the damage; the rest of the volley is for show)+ if c.get('CustomFirstProjectile') or c.get('Projectile'):+ proj_names.append(c.get('CustomFirstProjectile') or c['Projectile'])+ a = c.get('AreaEffectObject')+ if a and aeos[a].get('Projectile'):+ proj_names.append(aeos[a]['Projectile'])+ proj_names = list(dict.fromkeys(proj_names))+ area_names = list(dict.fromkeys(c['AreaEffectObject'] for k, n, c in cards if c.get('AreaEffectObject')))+ return chars, blds, projs, aeos, buffs, glob, texts, cards, unit_names, proj_names, area_names+++def cname(s):+ return ''.join(ch if ch.isalnum() else '_' for ch in s).upper()+++APKREF, BOTN = [None], [0]+++def main():+ apk = Apk(sys.argv[1] if len(sys.argv) > 1 else APK)+ APKREF[0] = apk+ import pickle+ if os.path.exists(RCACHE_FILE):+ RCACHE.update(pickle.load(open(RCACHE_FILE, 'rb')))+ try:+ run(apk)+ finally:+ if os.path.isdir(os.path.dirname(RCACHE_FILE)):+ pickle.dump(RCACHE, open(RCACHE_FILE, 'wb'))+++def run(apk):+ chars, blds, projs, aeos, buffs, glob, texts, cards, unit_names, proj_names, area_names = build(apk)+ G = {k: v.get('NumberValue') for k, v in glob.items()}+ pvp = apk.csv('csv_logic/locations.csv')['PvP_goblin']+ G['MATCH_LENGTH'], G['OVERTIME_SECONDS'] = pvp['MatchLength'], pvp['OvertimeSeconds']++ # --- sprite sets for the units+ unit_set = {}+ for n in unit_names:+ u = chars.get(n)+ if u:+ sc_scale = num(u, 'Scale', 100) / 100+ if n == 'Golemite':+ sc_scale = 0.75+ big = num(u, 'CollisionRadius') >= 750 or n in ('Balloon', 'BabyDragon', 'Golem')+ size, anchor = ((140, 150), (70, 115)) if big else ((80, 96), (40, 76))+ unit_set[n] = char_set(apk, n, u['FileName'], u['BlueExportName'], u['RedExportName'], sc_scale,+ size=size, anchor=anchor, dirs=(1,) if n == 'Balloon' else DIRS)+ print('set', n, flush=True)+ for n in unit_names:+ b = blds.get(n)+ if not b or n in unit_set:+ continue+ f, be, re_ = b['FileName'], b['BlueExportName'], b['RedExportName']+ sc_scale = num(b, 'Scale', 100) / 100+ if n in ('Cannon', 'Xbow'):+ unit_set[n] = turret_set(apk, n, f, be, re_, sc_scale)+ elif n == 'Mortar':+ unit_set[n] = char_set(apk, n, f, be, re_, sc_scale, nrun=1, natt=3, size=(110, 120), anchor=(55, 90),+ dirs=(1, 2, 3, 4, 5))+ elif n == 'Tesla':+ scf = apk.sc(f)+ lab = scf.labels(be)+ unit_set[n] = still_set(apk, n, f, be, re_, sc_scale, [lab['idle'], lab['hide_start'] + 8, lab['hide_end']])+ elif n == 'KingTower':+ unit_set[n] = still_set(apk, n, f, be, re_, 1.0, [0], size=(130, 140), anchor=(65, 95))+ elif n == 'PrincessTower':+ unit_set[n] = still_set(apk, n, f, be, re_, 1.0, [0], size=(110, 120), anchor=(55, 90))+ unit_set['PrincessTowerTop'] = still_set(apk, 'PrincessTowerTop', f, b['BlueTopExportName'],+ b['RedTopExportName'], 1.0, [0], size=(110, 80), anchor=(55, 60))+ elif n == 'BombTower':+ unit_set[n] = still_set(apk, n, f, be, re_, sc_scale)+ unit_set['BombTowerTop'] = still_set(apk, 'BombTowerTop', f, b['BlueTopExportName'], b['RedTopExportName'],+ sc_scale, [0], size=(110, 80), anchor=(55, 60))+ elif n in ('GiantSkeletonBomb', 'BalloonBomb'):+ unit_set[n] = still_set(apk, n, f, be, re_, sc_scale, [0, 15, 28], size=(80, 80), anchor=(40, 60))+ else:+ unit_set[n] = still_set(apk, n, f, be, re_, sc_scale)+ print('set', n, flush=True)+ scf = apk.sc('sc/building_tower.sc')+ rub = render(scf, 'Tower_destroyed_ground1', 0, S, (110, 100), (55, 60))+ rub2 = render(scf, 'Tower_destroyed_ground2', 0, S, (110, 100), (55, 60))+ add_group([(rub, None, 55, 60), (rub2, None, 55, 60)], name='IMG_RUBBLE')++ # --- projectiles and effects: one picture each (mode 1: with alpha)+ proj_img = {}+ for n in proj_names:+ p = projs[n]+ if not p.get('ExportName'):+ continue+ e = p['ExportName']+ if e in ('projectile_arrow_basic_enemy', 'projectile_arrow_basic', 'projectile_spear_360'):+ continue # drawn as lines+ if e not in proj_img:+ scf = apk.sc(p['FileName'])+ proj_img[e] = add_group([(render(scf, e, 0, S * 0.9, (60, 60), (30, 30)), None, 30, 30)], mode=1)[0]+ fx = {}+ fx['explosion'] = effect(apk, 'sc/effects.sc', 'RoundExplosion', 1.0, [0, 3, 6, 9, 12, 15], pname='IMG_EXPLOSION')+ fx['puff'] = effect(apk, 'sc/effects.sc', 'RoundExplosion', 0.45, [0, 4, 8, 12], (60, 60), (30, 30), pname='IMG_PUFF')+ fx['zap'] = effect(apk, 'sc/effects.sc', 'zap_bolt1', 0.9, [0, 3, 6], (80, 140), (40, 120), pname='IMG_ZAP')+ fx['lightning'] = effect(apk, 'sc/effects.sc', 'lightning_bolt', 0.9, [0, 3, 6], (80, 220), (40, 200), pname='IMG_LIGHTNING')+ scf = apk.sc('sc/effects.sc')+ add_group([(render(scf, 'crown_rotate_anim', 0, 0.45, (40, 40), (20, 24)), None, 20, 24)], name='IMG_CROWN')+ scf = apk.sc('sc/ui.sc')+ add_group([(render(scf, 'spell_card_ingame', 0, 0.16, (24, 24), (12, 12), hide=()), None, 12, 12)], name='IMG_CARDFRAME')+ # the elixir drop: the bottom-right of the in-game card+ big = render(scf, 'spell_card_ingame', 0, 1.0, (140, 170), (70, 85))+ drop = big[125:165, 95:135]+ dimg = Image.fromarray((drop * 255).astype(np.uint8), 'RGBA').resize((10, 10), Image.LANCZOS)+ add_group([(np.asarray(dimg, np.float32) / 255, None, 5, 5)], name='IMG_DROP')+ dimg = Image.fromarray((drop * 255).astype(np.uint8), 'RGBA').resize((16, 16), Image.LANCZOS)+ add_group([(np.asarray(dimg, np.float32) / 255, None, 8, 8)], name='IMG_DROP_BIG')++ # --- card pictures: 36 x 45+ scf = apk.sc('sc/ui_spells.sc')+ card_icon = {}+ for kind, n, c in cards:+ ic = c['IconFile']+ rgba = render(scf, ic, 0, 0.153, (38, 48), (19, 24))+ small = render(scf, ic, 0, 0.1, (26, 32), (13, 16))+ card_icon[n] = add_group([(rgba, None, 19, 24), (small, None, 13, 16)], k=255)[0] # (the small one next)+ hidden = add_group([(render(scf, 'hidden', 0, 0.153, (38, 48), (19, 24)), None, 19, 24)])[0]+ P.names['IMG_CARD_HIDDEN'] = hidden++ # --- the title picture: the loading screen, 180 x 240+ scf = apk.sc('sc/loading.sc')+ lo, hi = scf.bounds('loading_screen')+ title = render(scf, 'loading_screen', 0, 248 / 1024, (180, 248), (90, 0))[:240] # (without its loading bar)+ add_group([(title, None, 0, 0)], name='IMG_TITLE')++ # --- arenas+ arenas = []+ for loc in ('goblin_arena', 'bone_arena', 'barbarian_arena', 'dark_arena', 'spell_arena', 'royal_arena', 'legendary_arena'):+ arenas.append(arena(apk, loc))+ print('arena', loc, flush=True)++ # --- fonts+ fonts = font_section(apk)++ write(apk, chars, blds, projs, aeos, buffs, G, texts, cards, unit_names, proj_names, area_names, unit_set,+ proj_img, card_icon, fonts, arenas)+++# ------------------------------------------------------------------ arenas+++def arena(apk, loc):+ rows = list(csv.reader(io.StringIO(apk.read('locations/%s.csv' % loc).decode('utf-8'))))+ file, export = rows[3][1], rows[3][2]+ scf = apk.sc(file)+ # the field in the game's units: x -9 to 9 tiles, y 0 to 32 tiles; drawn 3 times the calculator's size+ k = 3+ W, H = 18 * TILE * k, 32 * TILE * k+ cv = SCF.Canvas(W, H, 0, 0, 1.0, ss=1)+ # a matrix from the game's picture to this canvas: x * (TILE*k/SX) + W/2, (y + 1.25) * (TILE*k/SY)+ m = (TILE * k / SX, 0, 0, TILE * k / SY, W / 2, 1.25 * TILE * k / SY)+ cv.draw(scf, scf.pieces(export, 0, m))+ ground = cv.rgba()+ img = Image.fromarray((ground[..., :3] * 255).astype(np.uint8)).resize((18 * TILE, 32 * TILE), Image.LANCZOS)+ img = img.transpose(Image.ROTATE_270) # the game's top (the enemy) to the right, its left lane to the top+ base = np.asarray(img, np.float32) / 255+ # (the decorations at the river's ends would stand in the field once it is turned: left out)+ rgb = Image.fromarray((base * 255).astype(np.uint8))+ q = rgb.quantize(256, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE)+ pal = np.array(q.getpalette()[:768], float).reshape(-1, 3) / 255+ pal = np.vstack([pal, np.zeros((256 - len(pal), 3))])+ idx = np.asarray(q, np.uint8).tobytes()+ packed = lz_pack(idx)+ c = np.clip(np.round(pal * 255), 0, 255).astype(int)+ b = b''.join(struct.pack('<H', (r >> 3) << 11 | (g >> 2) << 5 | bl >> 3) for r, g, bl in c)+ rgb.save(os.path.join(HERE, '..', 'build', 'arena_%s.png' % loc)) if os.path.isdir(os.path.join(HERE, '..', 'build')) else None+ return b + struct.pack('<I', len(packed)) + packed+++def lz_pack(data):+ """np_lz.h's stream: a flag byte for 8 items (set: a literal), a match: distance - 1 (12 bits), length - 3 (4)"""+ n = len(data)+ out = bytearray()+ i = 0+ heads = {}+ while i < n:+ flag_at = len(out)+ out.append(0)+ for b in range(8):+ if i >= n:+ break+ best, bd = 0, 0+ key = data[i:i + 3]+ if len(key) == 3:+ for c in reversed(heads.get(key, [])[-48:]):+ if i - c > 4096:+ break+ ln = 0+ while ln < 18 and i + ln < n and data[c + ln] == data[i + ln]:+ ln += 1+ if ln > best:+ best, bd = ln, i - c+ if ln == 18:+ break+ if best >= 3:+ out += bytes([(bd - 1) & 255, (bd - 1) >> 8 | (best - 3) << 4])+ for j in range(i, i + best):+ heads.setdefault(data[j:j + 3], []).append(j)+ i += best+ else:+ out[flag_at] |= 1 << b+ out.append(data[i])+ heads.setdefault(data[i:i + 3], []).append(i)+ i += 1+ return bytes(out)+++# ------------------------------------------------------------------ fonts+++def font_section(apk):+ blobs = []+ # FONT_SMALL: the game's body font (CCBackBeat); FONT_MID, FONT_BIG, FONT_NUM: its titles' (Supercell-Magic)+ for file, size in (('sc_ccbackbeatregular.ttf', 11), ('supercell-magic_0.ttf', 13), ('supercell-magic_0.ttf', 20),+ ('supercell-magic_0.ttf', 9)):+ f = ImageFont.truetype(io.BytesIO(apk.read('font/' + file)), size)+ asc, desc = f.getmetrics()+ glyphs, data = [], b''+ for ch in range(32, 127):+ s = chr(ch)+ adv = int(round(f.getlength(s)))+ bb = f.getbbox(s)+ if bb[2] <= bb[0]:+ glyphs.append((adv, 0, 0, 0, 0, 0))+ continue+ im = Image.new('L', (bb[2] - bb[0], bb[3] - bb[1]))+ ImageDraw.Draw(im).text((-bb[0], -bb[1]), s, font=f, fill=255)+ a = np.asarray(im)+ w, h = a.shape[1], a.shape[0]+ q = (a.astype(int) * 15 + 127) // 255+ rows = b''+ for y in range(h):+ row = list(q[y]) + ([0] if w & 1 else [])+ rows += bytes(row[i] | row[i + 1] << 4 for i in range(0, len(row), 2))+ glyphs.append((adv, w, h, bb[0], bb[1], len(data)))+ data += rows+ blobs.append((asc + desc, asc, glyphs, data))+ # FONTS: count, offsets; each: line, base, 0, 0, glyphs (12 bytes), data+ out = struct.pack('<I', len(blobs))+ heads = []+ body = b''+ for line, base, glyphs, data in blobs:+ g0 = 4 + 95 * 12+ b = struct.pack('<BBBB', line, base, 0, 0)+ for adv, w, h, x, y, off in glyphs:+ b += struct.pack('<BBBbbBBBI', adv, w, h, x, y, 0, 0, 0, off + g0)+ b += data+ heads.append(body)+ body += b+ offs = []+ o = 4 + 4 * len(blobs)+ for i, (line, base, glyphs, data) in enumerate(blobs):+ offs.append(o)+ o += 4 + 95 * 12 + len(data)+ return out + b''.join(struct.pack('<I', v) for v in offs) + body+++# ------------------------------------------------------------------ writing+++def write(apk, chars, blds, projs, aeos, buffs, G, texts, cards, unit_names, proj_names, area_names, unit_set,+ proj_img, card_icon, fonts, arenas):+ # data.bin+ imgs_head = 4 + 4 * len(P.imgs)+ pal_base = None+ sec = {}+ body = b''+ sec_imgs = struct.pack('<I', len(P.imgs))+ o = imgs_head+ offs = []+ for b in P.imgs:+ offs.append(o)+ o += len(b)+ head_len = 8 + 4 * len(SECTIONS)+ # the palettes' absolute offsets: after IMGS (padded to 4 bytes)+ imgs_len = (o + 3) & ~3+ pals_start = head_len + imgs_len+ pal_off, po = [], pals_start+ for p in P.pals:+ pal_off.append(po)+ po += len(p)+ fixed = []+ for b in P.imgs:+ pb, pr = struct.unpack_from('<II', b, 12)+ fixed.append(b[:12] + struct.pack('<II', pal_off[pb], pal_off[pr]) + b[20:])+ sec['IMGS'] = sec_imgs + b''.join(struct.pack('<I', v) for v in offs) + b''.join(fixed)+ sec['PALS'] = b''.join(P.pals)+ sec['FONTS'] = fonts+ ar = struct.pack('<I', len(arenas))+ ao = 4 + 4 * len(arenas)+ for a in arenas:+ ar += struct.pack('<I', ao)+ ao += len(a)+ sec['ARENAS'] = ar + b''.join(arenas)+ out = b'CRD1' + struct.pack('<I', len(SECTIONS))+ o = head_len+ for s in SECTIONS:+ out += struct.pack('<I', o)+ o += len(sec[s])+ while o % 4:+ o += 1+ sec[s] += b'\0'+ for s in SECTIONS:+ out += sec[s]+ assert out[head_len:head_len + 4] == sec['IMGS'][:4]+ open(os.path.join(OUT, 'data.bin'), 'wb').write(out)+ print('data.bin', len(out), 'bytes;', len(P.imgs), 'pictures,', len(P.pals), 'palettes;',+ 'IMGS', len(sec['IMGS']), 'ARENAS', len(sec['ARENAS']), 'FONTS', len(sec['FONTS']))++ # data.h+ h = ['/* made by tools/pack.py */', '#ifndef CR_DATA_H', '#define CR_DATA_H', '']+ for i, s in enumerate(SECTIONS):+ h.append('#define SEC_%s %d' % (s, i))+ h.append('')+ for n, i in sorted(P.names.items(), key=lambda t: t[1]):+ h.append('#define %s %d' % (n, i))+ h += ['#define FONT_SMALL 0', '#define FONT_MID 1', '#define FONT_BIG 2', '#define FONT_NUM 3', '#define NARENAS %d' % len(arenas),+ '', '#endif', '']+ open(os.path.join(OUT, 'data.h'), 'w').write('\n'.join(h))++ tables(chars, blds, projs, aeos, buffs, G, texts, cards, unit_names, proj_names, area_names, unit_set, proj_img,+ card_icon)+++def tables(chars, blds, projs, aeos, buffs, G, texts, cards, unit_names, proj_names, area_names, unit_set, proj_img,+ card_icon):+ L = ['/* made by tools/pack.py from Clash Royale\'s assets/csv_logic: see tables.h */', '#include "tables.h"', '']+ uidx = {n: i for i, n in enumerate(unit_names)}+ pidx = {n: i for i, n in enumerate(proj_names)}+ aidx = {n: i for i, n in enumerate(area_names)}+ # sprite sets+ L.append('const SetDef SETS[NSETS] = {')+ for name, anims in SETS:+ parts = []+ for an in ('run', 'attack', 'idle'):+ a = anims.get(an) or anims['idle']+ parts.append('{%d, %d, %d, %d, %d}' % a)+ L.append(' {%s}, /* %s */' % (', '.join(parts), name))+ L += ['};', '']+ # units+ L.append('const UnitDef UNITS[NUNITS] = {')+ for n in unit_names:+ u = chars.get(n) or blds[n]+ isb = n in blds+ fl = []+ if u.get('AttacksGround') == 'true':+ fl.append('U_GROUND')+ if u.get('AttacksAir') == 'true':+ fl.append('U_AIR')+ if u.get('TargetOnlyBuildings') == 'true':+ fl.append('U_BUILDINGS')+ if u.get('FlyingHeight'):+ fl.append('U_FLY')+ if u.get('IgnorePushback') == 'true' or isb:+ fl.append('U_NOPUSH')+ if u.get('SelfAsAoeCenter') == 'true':+ fl.append('U_SELFAOE')+ if u.get('JumpEnabled') == 'true':+ fl.append('U_JUMP')+ if isb:+ fl.append('U_BUILDING')+ if u.get('HidesWhenNotAttacking') == 'true':+ fl.append('U_HIDES')+ if n in ('KingTower', 'PrincessTower'):+ fl.append('U_TOWER')+ if n == 'KingTower':+ fl.append('U_KING')+ if n in ('GiantSkeletonBomb', 'BalloonBomb'):+ fl.append('U_BOMB')+ p = u.get('Projectile')+ dmg = num(u, 'Damage')+ title = texts.get(u.get('TID', ''), n)+ sl = num(u, 'SpawnCharacterLevelIndex')+ top = -1+ if n == 'PrincessTower':+ top = unit_set['PrincessTowerTop']+ if n == 'BombTower':+ top = unit_set['BombTowerTop']+ L.append(' {"%s", %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %s,' % (+ title, num(u, 'Hitpoints'), dmg, num(u, 'HitSpeed'), num(u, 'LoadTime'), num(u, 'Range'),+ num(u, 'MinimumRange'), num(u, 'SightRange'), num(u, 'Speed'), num(u, 'DeployTime'),+ num(u, 'CollisionRadius'), num(u, 'Mass'), pidx.get(p, 255) if p else 255, num(u, 'AreaDamageRadius'),+ num(u, 'LifeTime'), ' | '.join(fl) or '0'))+ L.append(' %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d,'+ ' %d, %d, %d, %d, %d}, /* %s */' % (+ num(u, 'DeathDamage'), num(u, 'DeathDamageRadius'), num(u, 'DeathPushBack'),+ uidx.get(u.get('DeathSpawnCharacter'), 255), num(u, 'DeathSpawnCount'),+ uidx.get(u.get('SpawnCharacter'), 255), num(u, 'SpawnNumber'), sl,+ num(u, 'SpawnInterval'), num(u, 'SpawnPauseTime'), num(u, 'SpawnStartTime'),+ num(u, 'ChargeRange'), num(u, 'DamageSpecial'), num(u, 'ChargeSpeedMultiplier'),+ num(u, 'VariableDamage2'), num(u, 'VariableDamageTime1'), num(u, 'VariableDamage3'),+ num(u, 'VariableDamageTime2'), num(u, 'ManaGenerateTimeMs'), num(u, 'ManaCollectAmount'),+ num(u, 'RandomDeployDelay'), num(u, 'FlyingHeight'), num(u, 'HideTimeMs'), num(u, 'UpTimeMs'),+ unit_set.get(n, 0), num(u, 'ShadowScaleX'), num(u, 'ShadowScaleY'), num(u, 'ShadowX'),+ num(u, 'ShadowY'), uidx.get(u.get('AttachedCharacter'), 255), num(u, 'AttachedCharacterHeight'),+ top, n))+ L += ['};', '']+ # projectiles+ L.append('const ProjDef PROJS[NPROJS] = {')+ for n in proj_names:+ p = projs[n]+ fl = []+ if p.get('Homing') == 'true':+ fl.append('P_HOMING')+ if p.get('AoeToGround') == 'true':+ fl.append('P_AOE_GROUND')+ if p.get('AoeToAir') == 'true':+ fl.append('P_AOE_AIR')+ if p.get('ReducedTowerDamage', '').upper() == 'TRUE':+ fl.append('P_REDUCED')+ e = p.get('ExportName', '')+ if e in ('projectile_arrow_basic_enemy', 'projectile_arrow_basic'):+ fl.append('P_ARROW')+ if e == 'projectile_spear_360':+ fl.append('P_SPEAR')+ L.append(' {%d, %d, %d, %d, %s, %d, %d, %d, %d, %d, %d}, /* %s */' % (+ num(p, 'Speed'), num(p, 'Damage'), num(p, 'Radius'), num(p, 'Pushback'), ' | '.join(fl) or '0',+ uidx.get(p.get('SpawnCharacter'), 255), num(p, 'SpawnCharacterCount'), num(p, 'SpawnCharacterLevelIndex'),+ num(p, 'SpawnCharacterDeployTime'), num(p, 'Gravity'), proj_img.get(e, -1), n))+ L += ['};', '']+ # area effects+ L.append('const AreaDef AREAS[NAREAS] = {')+ for n in area_names:+ a = aeos[n]+ fl = []+ if a.get('OnlyEnemies', '').upper() == 'TRUE':+ fl.append('A_ENEMIES')+ if a.get('OnlyOwnTroops', '').upper() == 'TRUE':+ fl.append('A_OWN')+ if a.get('HitBiggestTargets', '').upper() == 'TRUE':+ fl.append('A_BIGGEST')+ if a.get('ReducedTowerDamage', '').upper() == 'TRUE':+ fl.append('A_REDUCED')+ if a.get('HitsGround', '').upper() == 'TRUE':+ fl.append('A_GROUND')+ if a.get('HitsAir', '').upper() == 'TRUE':+ fl.append('A_AIR')+ b = buffs.get(a.get('Buff', ''), {})+ L.append(' {%d, %d, %d, %d, %d, %s, %d, %d, %d, %d, %d, %d}, /* %s */' % (+ num(a, 'Radius'), num(a, 'LifeDuration'), num(a, 'LifeDurationIncreasePerLevel'), num(a, 'HitSpeed'),+ num(a, 'Damage'), ' | '.join(fl) or '0', num(a, 'BuffTime'), num(a, 'BuffTimeIncreasePerLevel'),+ pidx.get(a.get('Projectile'), 255), num(b, 'SpeedMultiplier'), num(b, 'HitSpeedMultiplier'),+ num(b, 'SpawnSpeedMultiplier'), n))+ L += ['};', '']+ # cards+ rar = {'Common': 0, 'Rare': 1, 'Epic': 2, 'Legendary': 3}+ L.append('const CardDef CARDS[NCARDS] = {')+ for kind, n, c in cards:+ title = texts.get(c.get('TID', ''), n)+ info = texts.get(c.get('TID_INFO', ''), '').replace('\\q', "'").replace('\\n', ' ').replace('"', "'")+ radius = num(c, 'Radius')+ if not radius and c.get('Projectile'):+ radius = num(projs[c.get('CustomFirstProjectile') or c['Projectile']], 'Radius')+ if not radius and c.get('AreaEffectObject'):+ radius = num(aeos[c['AreaEffectObject']], 'Radius')+ L.append(' {"%s", "%s", %d, %d, %d, %d, %d, %d, %d, %d, %d, %d}, /* %s */' % (+ title, info, rar[c['Rarity']], num(c, 'ManaCost'), kind, num(c, 'SummonNumber', 1) or 1,+ uidx.get(c.get('SummonCharacter'), 255), pidx.get(c.get('CustomFirstProjectile') or c.get('Projectile'), 255),+ aidx.get(c.get('AreaEffectObject'), 255), radius, num(c, 'MultipleProjectiles'), card_icon[n], n))+ L += ['};', '']+ # the training camp's decks (predefined_decks.csv) of eight cards: the bot's+ cidx = {n: i for i, (kind, n, c) in enumerate(cards)}+ rows = list(csv.reader(io.StringIO(APKREF[0].read('csv_logic/predefined_decks.csv').decode('utf-8'))))+ decks, cur = [], None+ for r in rows[2:]:+ if r and r[0]:+ cur = [r[0], []]+ decks.append(cur)+ if r and len(r) > 1 and r[1] and cur:+ cur[1].append(r[1])+ bot = [(n, d) for n, d in decks if len(d) == 8 and all(c in cidx for c in d)]+ L.append('const uint8_t BOT_DECKS[NBOTDECKS][8] = {')+ for n, d in bot:+ L.append(' {%s}, /* %s */' % (', '.join('CA_%s' % cname(c) for c in d), n))+ L += ['};', '']+ BOTN[0] = len(bot)+ # globals+ L.append('const int32_t GLOBALS[NGLOBALS] = {')+ for k in GLOBAL_NAMES:+ L.append(' %s, /* %s */' % (G.get(k) or 0, k))+ L += ['};', '']+ open(os.path.join(OUT, 'tables.c'), 'w').write('\n'.join(L))+ # counts and ids+ H = ['/* made by tools/pack.py */', '#ifndef CR_IDS_H', '#define CR_IDS_H',+ '#define NSETS %d' % len(SETS), '#define NUNITS %d' % len(unit_names), '#define NPROJS %d' % len(proj_names),+ '#define NAREAS %d' % len(area_names), '#define NCARDS %d' % len(cards), '#define NGLOBALS %d' % len(GLOBAL_NAMES),+ '#define NBOTDECKS %d' % BOTN[0]]+ for i, n in enumerate(unit_names):+ H.append('#define UN_%s %d' % (cname(n), i))+ for i, n in enumerate(proj_names):+ H.append('#define PR_%s %d' % (cname(n), i))+ for i, n in enumerate(area_names):+ H.append('#define AR_%s %d' % (cname(n), i))+ for i, (kind, n, c) in enumerate(cards):+ H.append('#define CA_%s %d' % (cname(n), i))+ for i, (name, a) in enumerate(SETS):+ H.append('#define SET_%s %d' % (cname(name), i))+ for i, k in enumerate(GLOBAL_NAMES):+ H.append('#define G_%s %d' % (k, i))+ H += ['#endif', '']+ open(os.path.join(OUT, 'ids.h'), 'w').write('\n'.join(H))+++GLOBAL_NAMES = ['MAX_MANA', 'MANA_REGEN_MS', 'MANA_REGEN_MS_END', 'MANA_REGEN_MS_OVERTIME',+ 'MANA_SPEED_UP_WHEN_REMAINING_SECONDS', 'START_MANA', 'NEXT_SPELL_COOLDOWN_MILLISECONDS',+ 'NEXT_SPELL_COOLDOWN_MILLISECONDS_BOOST', 'NEXT_SPELL_COOLDOWN_MILLISECONDS_OVERTIME',+ 'DAMAGE_INCREASE_PERCENT_PER_SPELL_LEVEL', 'HITPOINT_INCREASE_PERCENT_PER_SPELL_LEVEL',+ 'DAMAGE_INCREASE_PERCENT_PER_KING_LEVEL', 'HITPOINT_INCREASE_PERCENT_PER_KING_LEVEL',+ 'DAMAGE_INCREASE_PERCENT_PER_TOWER_LEVEL', 'HITPOINT_INCREASE_PERCENT_PER_TOWER_LEVEL',+ 'MELEE_RANGE_LIMIT', 'REDUCED_TOWER_DAMAGE_PERCENT', 'KING_ACTIVATE_TIME_MS',+ 'TOURNAMENT_MAX_EXP_LEVEL', 'TOURNAMENT_MAX_COMMON_LEVEL', 'TOURNAMENT_MAX_RARE_LEVEL',+ 'TOURNAMENT_MAX_EPIC_LEVEL', 'TOURNAMENT_MATCH_LENGTH_SECONDS', 'MATCH_LENGTH', 'OVERTIME_SECONDS']++if __name__ == '__main__':+ main()diff --git a/games/clashroyale/tools/sc.py b/games/clashroyale/tools/sc.pynew file mode 100644index 00000000..697d1499--- /dev/null+++ b/games/clashroyale/tools/sc.py@@ -0,0 +1,293 @@+"""Supercell's .sc files as Clash Royale's 2016 Android build has them: read and drawn.++An .sc file is "SC", a version and an MD5, then LZMA (5 bytes of properties, a 4-byte size). foo.sc holds the+shapes (pieces of a texture placed in the picture), movie clips (frames of shapes and clips with matrices and+colour transforms) and the names they are exported under; foo_tex.sc holds the textures.+"""+import lzma+import struct++import numpy as np+from PIL import Image, ImageDraw+++def decompress(data):+ if data[:2] == b'SC':+ _, hl = struct.unpack('>II', data[2:10])+ data = data[10 + hl:]+ raw = data[:5] + data[5:9] + b'\0\0\0\0' + data[9:]+ return lzma.LZMADecompressor(format=lzma.FORMAT_ALONE).decompress(raw)+++class Reader:+ def __init__(self, b):+ self.b, self.p = b, 0++ def u8(self):+ self.p += 1+ return self.b[self.p - 1]++ def u16(self):+ self.p += 2+ return struct.unpack_from('<H', self.b, self.p - 2)[0]++ def u32(self):+ self.p += 4+ return struct.unpack_from('<I', self.b, self.p - 4)[0]++ def i32(self):+ self.p += 4+ return struct.unpack_from('<i', self.b, self.p - 4)[0]++ def s(self):+ n = self.u8()+ if n == 255:+ return None+ self.p += n+ return self.b[self.p - n:self.p].decode('latin1')+++def pixels(r, fmt, w, h):+ n = w * h+ if fmt in (0, 1):+ a = np.frombuffer(r.b, np.uint8, n * 4, r.p).reshape(h, w, 4).copy()+ r.p += n * 4+ return a+ v = None+ if fmt in (2, 3, 4):+ v = np.frombuffer(r.b, '<u2', n, r.p).reshape(h, w).astype(np.uint32)+ r.p += n * 2+ if fmt == 2:+ return (np.stack([v >> 12 & 15, v >> 8 & 15, v >> 4 & 15, v & 15], -1) * 17).astype(np.uint8)+ if fmt == 3:+ return np.stack([(v >> 11 & 31) * 255 // 31, (v >> 6 & 31) * 255 // 31, (v >> 1 & 31) * 255 // 31,+ (v & 1) * 255], -1).astype(np.uint8)+ if fmt == 4:+ return np.stack([(v >> 11 & 31) * 255 // 31, (v >> 5 & 63) * 255 // 63, (v & 31) * 255 // 31,+ np.full_like(v, 255)], -1).astype(np.uint8)+ if fmt == 6:+ a = np.frombuffer(r.b, np.uint8, n * 2, r.p).reshape(h, w, 2)+ r.p += n * 2+ return np.stack([a[..., 1], a[..., 1], a[..., 1], a[..., 0]], -1).copy()+ if fmt == 10:+ a = np.frombuffer(r.b, np.uint8, n, r.p).reshape(h, w)+ r.p += n+ return np.stack([a, a, a, np.full_like(a, 255)], -1).copy()+ raise ValueError('pixel format %d' % fmt)+++def untile(img, w, h):+ """textures stored in 32 x 32 blocks"""+ flat = img.reshape(-1, img.shape[-1])+ out = np.zeros_like(img)+ i = 0+ for by in range(0, h, 32):+ for bx in range(0, w, 32):+ bh, bw = min(32, h - by), min(32, w - bx)+ for y in range(bh):+ out[by + y, bx:bx + bw] = flat[i:i + bw]+ i += bw+ return out+++def textures(data):+ b = decompress(data)+ r = Reader(b)+ out = []+ while r.p < len(b):+ tag, ln = r.u8(), r.u32()+ if tag == 0:+ break+ end = r.p + ln+ if tag in (1, 16, 19, 24, 27, 28, 29, 34):+ fmt, w, h = r.u8(), r.u16(), r.u16()+ img = pixels(r, fmt, w, h)+ out.append(untile(img, w, h) if tag in (27, 28, 29) else img)+ r.p = end+ # premultiplied, as floats, for drawing+ pm = []+ for t in out:+ f = t.astype(np.float32) / 255+ f[..., :3] *= f[..., 3:4]+ pm.append(f)+ return pm+++class SC:+ def __init__(self, data, tex_data=None):+ self.tex = textures(tex_data) if tex_data else []+ b = decompress(data)+ r = Reader(b)+ r.p = 12 + 5+ n = r.u16()+ ids = [r.u16() for _ in range(n)]+ names = [r.s() for _ in range(n)]+ self.exports = {}+ for i, nm in zip(ids, names):+ self.exports.setdefault(nm, i)+ self.shapes, self.clips, self.matrices, self.colors = {}, {}, [], []+ while r.p < len(b):+ tag, ln = r.u8(), r.u32()+ end = r.p + ln+ if tag == 0:+ break+ if tag in (2, 18):+ self.shape(r, tag)+ elif tag in (10, 12, 35):+ self.clip(r, tag)+ elif tag == 8:+ a, bb, c, d, tx, ty = [r.i32() for _ in range(6)]+ self.matrices.append((a / 1024, bb / 1024, c / 1024, d / 1024, tx / 20, ty / 20))+ elif tag == 9:+ ra, ga, ba, am, rm, gm, bm = [r.u8() for _ in range(7)]+ self.colors.append((np.array([rm, gm, bm, am], np.float32) / 255, np.array([ra, ga, ba], np.float32) / 255))+ r.p = end++ def shape(self, r, tag):+ sid = r.u16()+ r.u16()+ if tag == 18:+ r.u16()+ regions = []+ while True:+ st, ln = r.u8(), r.u32()+ end = r.p + ln+ if st == 0:+ break+ if st in (4, 17, 22):+ t = r.u8()+ n = 4 if st == 4 else r.u8()+ xy = np.array([(r.i32() / 20, r.i32() / 20) for _ in range(n)])+ uv = np.array([(r.u16(), r.u16()) for _ in range(n)], float)+ if st == 22:+ th, tw = self.tex[t].shape[:2]+ uv = uv / 65535 * np.array([tw, th])+ regions.append((t, xy, uv))+ r.p = end+ self.shapes[sid] = regions++ def clip(self, r, tag):+ cid = r.u16()+ r.u8()+ r.u16()+ cnt = r.u32()+ elems = [(r.u16(), r.u16(), r.u16()) for _ in range(cnt)]+ nb = r.u16()+ binds = [r.u16() for _ in range(nb)]+ if tag in (12, 35):+ r.p += nb+ names = [r.s() for _ in range(nb)]+ frames = []+ ei = 0+ while True:+ st, ln = r.u8(), r.u32()+ end = r.p + ln+ if st == 0:+ break+ if st == 11:+ n = r.u16()+ frames.append((r.s(), elems[ei:ei + n]))+ ei += n+ r.p = end+ self.clips[cid] = (list(zip(binds, names)), frames)++ def frames(self, name):+ return len(self.clips[self.exports[name]][1])++ def labels(self, name):+ return {lab: i for i, (lab, _) in enumerate(self.clips[self.exports[name]][1]) if lab}++ def walk(self, cid, frame, m, col, out, hide=()):+ if cid in self.shapes:+ for t, xy, uv in self.shapes[cid]:+ out.append((t, xy, uv, m, col))+ return+ if cid not in self.clips:+ return+ binds, frames = self.clips[cid]+ if not frames:+ return+ for ci, mi, coi in frames[frame % len(frames)][1]:+ child, name = binds[ci]+ if name in hide:+ continue+ cm = m if mi == 0xFFFF else mul(m, self.matrices[mi])+ cc = col+ if coi != 0xFFFF:+ k, add = self.colors[coi]+ cc = (k, add) if col is None else (col[0] * k, col[1] + add)+ self.walk(child, frame, cm, cc, out, hide)++ def pieces(self, name, frame=0, m=(1, 0, 0, 1, 0, 0), hide=()):+ out = []+ self.walk(self.exports[name], frame, m, None, out, hide)+ return out++ def bounds(self, name, frame=0, m=(1, 0, 0, 1, 0, 0)):+ pts = []+ for t, xy, uv, mm, col in self.pieces(name, frame, m):+ a, b, c, d, tx, ty = mm+ pts += [(a * x + c * y + tx, b * x + d * y + ty) for x, y in xy]+ p = np.array(pts)+ return p.min(0), p.max(0)+++def mul(m, n):+ a, b, c, d, tx, ty = m+ a2, b2, c2, d2, tx2, ty2 = n+ return (a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * tx2 + c * ty2 + tx, b * tx2 + d * ty2 + ty)+++class Canvas:+ """premultiplied RGBA floats; (ox, oy) is where the picture's (0, 0) lands; drawn ss times larger, then reduced"""++ def __init__(self, w, h, ox, oy, scale=1.0, ss=4):+ self.ss = ss+ self.w, self.h = w * ss, h * ss+ self.ox, self.oy, self.scale = ox * ss, oy * ss, scale * ss+ self.img = np.zeros((self.h, self.w, 4), np.float32)++ def draw(self, sc, pieces):+ for t, xy, uv, m, col in pieces:+ self.region(sc.tex[t], xy, uv, m, col)++ def region(self, tex, xy, uv, m, col):+ a, b, c, d, tx, ty = m+ pts = np.array([(a * x + c * y + tx, b * x + d * y + ty) for x, y in xy]) * self.scale + (self.ox, self.oy)+ x0, y0 = np.floor(pts.min(0)).astype(int)+ x1, y1 = np.ceil(pts.max(0)).astype(int)+ x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, self.w), min(y1, self.h)+ if x0 >= x1 or y0 >= y1:+ return+ A, _, rank, _ = np.linalg.lstsq(np.c_[pts, np.ones(len(pts))], uv, rcond=None)+ if rank < 3:+ return+ mask = Image.new('L', (x1 - x0, y1 - y0), 0)+ ImageDraw.Draw(mask).polygon([(px - x0, py - y0) for px, py in pts], fill=255)+ mk = np.asarray(mask, np.float32)[..., None] / 255+ ys, xs = np.mgrid[y0:y1, x0:x1] + 0.5+ th, tw = tex.shape[:2]+ u = np.clip(A[0, 0] * xs + A[1, 0] * ys + A[2, 0] - 0.5, 0, tw - 1)+ v = np.clip(A[0, 1] * xs + A[1, 1] * ys + A[2, 1] - 0.5, 0, th - 1)+ ui, vi = u.astype(int), v.astype(int)+ uf, vf = (u - ui)[..., None], (v - vi)[..., None]+ u1, v1 = np.minimum(ui + 1, tw - 1), np.minimum(vi + 1, th - 1)+ s = (tex[vi, ui] * (1 - uf) * (1 - vf) + tex[vi, u1] * uf * (1 - vf) + tex[v1, ui] * (1 - uf) * vf+ + tex[v1, u1] * uf * vf)+ if col is not None:+ k, add = col+ s = s * np.array([k[0] * k[3], k[1] * k[3], k[2] * k[3], k[3]], np.float32)+ s[..., :3] = np.minimum(s[..., :3] + add * s[..., 3:4], s[..., 3:4])+ s = s * mk+ dst = self.img[y0:y1, x0:x1]+ self.img[y0:y1, x0:x1] = s + dst * (1 - s[..., 3:4])++ def rgba(self):+ """straight RGBA floats at the final size"""+ im = self.img+ if self.ss > 1:+ h, w = self.h // self.ss, self.w // self.ss+ im = im.reshape(h, self.ss, w, self.ss, 4).mean((1, 3))+ a = im[..., 3:4]+ rgb = np.where(a > 1e-4, im[..., :3] / np.maximum(a, 1e-4), 0)+ return np.concatenate([np.clip(rgb, 0, 1), np.clip(a, 0, 1)], -1)diff --git a/games/games.json b/games/games.jsonindex b7116273..ddd85fb6 100644--- a/games/games.json+++ b/games/games.json@@ -1449,5 +1449,27 @@"repo": "https://github.com/Mason363/NumPlay/tree/main/games/famidash","default": false,"xl": true+ },+ {+ "id": "clashroyale",+ "rank": 37,+ "title": "Clash Royale",+ "tagline": "Knock down the towers",+ "credit": "Based on the game by Supercell",+ "top": "0x2E5CB8",+ "bottom": "0x0C1A3C",+ "accent": "0xFFC832",+ "colors": 16,+ "records": [+ "clashroyale.sav",+ "crresume.sav",+ "clashroyale_saves.py"+ ],+ "shots": [+ "docs/shot.png"+ ],+ "repo": "https://github.com/Mason363/NumPlay/tree/main/games/clashroyale",+ "default": false,+ "xl": true}]diff --git a/tests/test_games.py b/tests/test_games.pyindex 749ec92d..9d7d643f 100644--- a/tests/test_games.py+++ b/tests/test_games.py@@ -320,6 +320,11 @@ GAMES = {"portal": ("PortalReturns.nwa", "portal.sav",presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,presses((1500, "ok")), 4000),+ # Battle: how to play (the first time), then the battle: a card dropped at the bridge; Home keeps the battle and the+ # profile. Next time, from the copy, Battle goes straight in, quit with On/Off+ "clashroyale": ("ClashRoyale.nwa", "clashroyale.sav",+ presses((1500, "ok"), (2200, "ok"), (4000, "1"), (4400, "ok"), (6500, "2"), (6900, "ok")), 9000,+ presses((1500, "ok")), 5000),}@@ -386,7 +391,8 @@ COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.p"angrybirds": "angrybirds_saves.py", "polytrack": "polytrack_saves.py", "paperclips": "paperclips_saves.py","badtime": "badtime_saves.py", "mahjong": "mahjong_saves.py","rider": "rider_saves.py", "snowrider": "snowrider_saves.py", "templerun": "templerun_saves.py",- "fnaf2": "fnaf2_saves.py", "fnaf3": "fnaf3_saves.py", "fnaf4": "fnaf4_saves.py", "famidash": "famidash_saves.py"}+ "fnaf2": "fnaf2_saves.py", "fnaf3": "fnaf3_saves.py", "fnaf4": "fnaf4_saves.py", "famidash": "famidash_saves.py",+ "clashroyale": "clashroyale_saves.py"}def paperclips_ok(v):@@ -419,6 +425,16 @@ def famidash_ok(v):return struct.unpack_from("<I", v, len(v) - 4)[0] == h+def clashroyale_ok(v):+ """Clash Royale's profile: "CRY1", version 1, 48 bytes, an FNV-1a sum of the rest at the end"""+ if len(v) != 48 or v[:4] != b"CRY1" or struct.unpack_from("<HH", v, 4) != (1, 48):+ return False+ h = 2166136261+ for x in v[:-4]:+ h = (h ^ x) * 16777619 & 0xFFFFFFFF+ return struct.unpack_from("<I", v, 44)[0] == h++def badtime_ok(v):"""Bad Time Simulator's save: "BTS1", version 1, 24 bytes, an FNV-1a sum of the rest at the end"""if len(v) != 24 or v[:4] != b"BTS1" or struct.unpack_from("<HH", v, 4) != (1, 24):@@ -653,6 +669,8 @@ CHECKS = {# "FMD1", version 1: how to play read (flags at 5), time played (564); after the reinstall, from the copy, more"famidash": (lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 7000,lambda v: famidash_ok(v) and v[5] & 1 and struct.unpack_from("<I", v, 2100)[0] >= 12000),+ # "CRY1", version 1, its size (48): how to play read (guide at 40); after the reinstall, from the copy+ "clashroyale": (lambda v: clashroyale_ok(v) and v[40] == 1,) * 2,"breakout": (lambda v: len(v) == 12 and v[:2] == b"B\2" and v[4] == 1 and struct.unpack_from("<I", v, 8)[0] >= 10,lambda v: v[4] == 0 and struct.unpack_from("<I", v, 8)[0] >= 1), # best kept, shake off# Air Hockey and the easy computer chosen; then the normal computer and Tanks, the tallies of the six games keptdiff --git a/tools/release.py b/tools/release.pyindex c930fa8d..78565114 100644--- a/tools/release.py+++ b/tools/release.py@@ -64,6 +64,7 @@ ALONE = {"fnaf3": ("Five Nights at Freddy's 3", "Fazbear's Fright's six nights with Springtrap and the phantoms: the lure, the vents, the maintenance panel"),"fnaf4": ("Five Nights at Freddy's 4", "the bedroom's nights with the Nightmares: listen at the doors, the closet, the bed, Fun with Plushtrap"),"famidash": ("Famidash", "TFDSoft's Geometry Dash for the NES, made for the calculator: the 173 levels of Famidash HUGE, every mode, practice mode"),+ "clashroyale": ("Clash Royale", "battles against a bot: the 2016 game's 41 cards, its seven arenas, elixir, crowns and trophies"),}VARIANTS = [("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),