wobblyhead hg > minor_monsters
annotate tools/build.py @ 35:0d40f346059c
Added tag 0.10.1 for changeset 83e8b0e0f010
| author | ark |
|---|---|
| date | 2026-10-20 19:54 +0200 |
| parents | 85d23328a215 |
| children | a464bd43b76c |
| rev | line source |
|---|---|
| 1 | 1 #!/usr/bin/env python3 |
| 2 """ | |
| 17 | 3 build the runnable game into www/: the game data from art/ and config/ into |
| 4 www/assets/ and www/data/, and a copy of the hand-written files in game/. | |
| 1 | 5 |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
6 usage: python3 tools/build.py [--force] [--watch] [--release] |
| 1 | 7 |
| 17 | 8 steps: sprites, tower levels, maps, masks, sounds, config, checks, previews, |
| 9 game files. a step is skipped when all its outputs are newer than its inputs | |
| 10 and the build scripts; --force runs every step. --watch reruns the build | |
| 11 whenever a file in art/, art/sounds/, art/digits/, config/ or game/ changes. | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
12 --release leaves the debug code and switches out: www/js/debug.js is |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
13 written empty and config.js has no [debug] section. |
| 1 | 14 |
| 15 requires python 3.11 or later and pillow. | |
| 16 """ | |
| 17 | |
| 4 | 18 import base64 |
| 1 | 19 import json |
| 20 import math | |
| 4 | 21 import re |
| 17 | 22 import shutil |
| 1 | 23 import sys |
| 24 import time | |
| 25 import tomllib | |
| 26 from pathlib import Path | |
| 27 | |
| 28 from PIL import Image | |
| 29 | |
| 30 # keep tools/ free of __pycache__ | |
| 31 sys.dont_write_bytecode = True | |
| 32 | |
| 33 import images | |
| 34 import masks | |
| 35 import preview | |
| 36 | |
| 37 ROOT = Path(__file__).resolve().parent.parent | |
| 38 ART = ROOT / "art" | |
| 4 | 39 SOUNDS = ART / "sounds" |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
40 DIGITS = ART / "digits" |
| 1 | 41 CONFIG = ROOT / "config" |
| 17 | 42 GAME = ROOT / "game" |
| 43 WWW = ROOT / "www" | |
| 44 ASSETS = WWW / "assets" | |
| 45 DATA = WWW / "data" | |
| 1 | 46 TEMP = ROOT / "temp" |
| 47 PREVIEW = TEMP / "preview" | |
| 48 # route data of the last mask step, read when the step is skipped | |
| 49 MAPS_CACHE = TEMP / "build" / "maps.json" | |
| 50 | |
| 22 | 51 # build scripts; tools/balance.py only reads the build's output |
| 52 TOOLS = sorted(p for p in (ROOT / "tools").glob("*.py") if p.name != "balance.py") | |
| 1 | 53 HEADER = "// generated by tools/build.py from {src}, do not edit\n" |
| 54 | |
| 55 SPRITES = (["m%d" % i for i in range(5)] + ["b%d" % i for i in range(4)] | |
| 56 + ["t%d" % i for i in range(4)] + ["p%d" % i for i in range(4)] | |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
57 + ["c%d" % i for i in range(4)] + ["hpm", "hpb"] |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
58 # icons, buttons and screens (art.md) |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
59 + ["coin_icon", "heart", "monster_icon", "play_button", "pause_button", |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
60 "speed_x1", "speed_x2", "speed_x4", "sound_on", "sound_off", "next_wave", |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
61 "shop_bubble", "shop_bubble_dark", "shop_bubble_dark2", "tower_popup", |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
62 "upgrade_button", "sell_button", "monster_death", "boss_death", |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
63 "splash", "splash_play", "map_won", "map_won_button", |
| 24 | 64 "game_lost", "game_lost_button", "game_won", "game_won_button", |
| 65 "wobbly_logo", "help_splash", "help_button", "help_info", "freeze"]) | |
| 6 | 66 # hp bar variants (art.md): the empty part is a darkened copy, the bar of a |
| 67 # slowed monster has its colour set to this hue in degrees | |
| 1 | 68 BAR_DARKEN = 0.35 |
| 6 | 69 BAR_SLOW_HUE = 220 |
| 70 BARS = ["hpm", "hpb"] | |
| 71 BAR_VARIANTS = [f"{n}{v}" for n in BARS for v in ("_empty", "_slow", "_slow_empty")] | |
| 1 | 72 MAPS = 4 |
| 73 MAP_QUALITY = 88 | |
| 74 # centre line smoothing: moving average half window, simplify tolerance | |
| 75 ROUTE_SMOOTH = 8 | |
| 76 ROUTE_TOLERANCE = 0.8 | |
| 77 # number of decimals of route points in maps.js | |
| 78 ROUTE_DECIMALS = 1 | |
| 9 | 79 # per map settings used by the mask step |
| 80 MASK_SETTINGS = ("path_half_width", "spawn_distance", "exit_distance") | |
| 15 | 81 # tower levels, and the tower settings given as [level 1, last level] |
| 82 TOWER_LEVELS = 5 | |
| 83 TOWER_BY_LEVEL = ("damage", "range", "cost", "slow") | |
| 84 # number of decimals of tower values filled in between non-whole ends | |
| 85 TOWER_DECIMALS = 3 | |
| 1 | 86 |
| 87 warnings = [] | |
| 88 | |
| 89 | |
| 90 def warn(msg): | |
| 91 warnings.append(msg) | |
| 92 print(" warning:", msg) | |
| 93 | |
| 94 | |
| 95 def stale(inputs, outputs, force): | |
| 96 """true when an output is missing or older than an input or a build script.""" | |
| 97 if force: | |
| 98 return True | |
| 99 try: | |
| 100 oldest = min(p.stat().st_mtime for p in outputs) | |
| 101 except FileNotFoundError: | |
| 102 return True | |
| 103 newest = max(p.stat().st_mtime for p in list(inputs) + TOOLS) | |
| 104 return newest > oldest | |
| 105 | |
| 106 | |
| 107 def write_text(path, text): | |
| 108 path.parent.mkdir(parents=True, exist_ok=True) | |
| 109 path.write_text(text) | |
| 110 | |
| 111 | |
| 112 # 1. sprites | |
| 113 | |
| 114 def step_sprites(force): | |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
115 # digits cut by tools/cut_digits.py, written as digit_NAME_N |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
116 digits = sorted(DIGITS.glob("*.png")) |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
117 inputs = [ART / f"{n}.png" for n in SPRITES] + digits + [DIGITS] |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
118 outputs = ([ASSETS / f"{n}.png" for n in SPRITES + BAR_VARIANTS] |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
119 + [ASSETS / f"digit_{p.name}" for p in digits]) |
| 1 | 120 if not stale(inputs, outputs, force): |
| 121 print("sprites: up to date") | |
| 122 return False | |
| 123 ASSETS.mkdir(parents=True, exist_ok=True) | |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
124 for p in ASSETS.glob("digit_*.png"): |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
125 p.unlink() |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
126 for p in digits: |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
127 images.trim(Image.open(p).convert("RGBA")).save(ASSETS / f"digit_{p.name}", optimize=True) |
| 1 | 128 for n in SPRITES: |
| 129 im = images.trim(Image.open(ART / f"{n}.png").convert("RGBA")) | |
| 130 im.save(ASSETS / f"{n}.png", optimize=True) | |
| 6 | 131 if n in BARS: |
| 132 slow = images.recolour(im, BAR_SLOW_HUE) | |
| 1 | 133 images.darken(im, BAR_DARKEN).save(ASSETS / f"{n}_empty.png", optimize=True) |
| 6 | 134 slow.save(ASSETS / f"{n}_slow.png", optimize=True) |
| 135 images.darken(slow, BAR_DARKEN).save(ASSETS / f"{n}_slow_empty.png", optimize=True) | |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
136 print(f"sprites: wrote {len(SPRITES)} sprites, {len(BAR_VARIANTS)} bar variants" |
|
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
137 f" and {len(digits)} digits") |
| 1 | 138 return True |
| 139 | |
| 140 | |
| 141 # 2. tower levels | |
| 142 | |
| 143 def step_towers(force): | |
| 144 changed = False | |
| 145 for t in range(4): | |
| 146 src = ART / f"t{t}p.png" | |
| 147 outputs = [ASSETS / f"t{t}_{lv}.png" for lv in range(2, 6)] | |
| 148 if not stale([src], outputs, force): | |
| 149 continue | |
| 150 for lv, im in enumerate(images.tower_levels(src), start=2): | |
| 151 im.save(ASSETS / f"t{t}_{lv}.png", optimize=True) | |
| 152 changed = True | |
| 153 print("towers:", "wrote levels 2-5" if changed else "up to date") | |
| 154 return changed | |
| 155 | |
| 156 | |
| 157 # 3. maps | |
| 158 | |
| 159 def step_maps(force): | |
| 160 changed = False | |
| 161 for m in range(MAPS): | |
| 162 src, dst = ART / f"map{m}.png", ASSETS / f"map{m}.jpg" | |
| 163 if stale([src], [dst], force): | |
| 164 images.map_copy(src, dst, MAP_QUALITY) | |
| 165 changed = True | |
| 166 print("maps:", "wrote jpeg copies" if changed else "up to date") | |
| 167 return changed | |
| 168 | |
| 169 | |
| 170 # 4. masks | |
| 171 | |
| 172 def route_values(routes): | |
| 173 """ | |
| 174 fill in length, turning and value of each route (balance.md, route | |
| 175 preference): the average of length relative to the longest route and | |
| 176 straightness relative to the straightest, that is the least turning. | |
| 177 """ | |
| 178 for r in routes: | |
| 179 r["length"] = masks.polyline_length(r["points"]) | |
| 180 r["turning"] = masks.turning(r["points"]) | |
| 181 longest = max(r["length"] for r in routes) | |
| 182 least = min(r["turning"] for r in routes) | |
| 183 for r in routes: | |
| 184 straight = least / r["turning"] if r["turning"] else 1.0 | |
| 185 r["value"] = (r["length"] / longest + straight) / 2 | |
| 186 | |
| 187 | |
| 188 def step_masks(cfg, force): | |
| 189 placement = cfg["placement"] | |
| 9 | 190 settings = {"placement": placement, |
| 191 "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]} | |
| 23 | 192 inputs = [ART / f"map{m}mask.png" for m in range(MAPS)] |
| 1 | 193 outputs = [DATA / "maps.js", MAPS_CACHE] |
| 194 cached = None | |
| 195 if MAPS_CACHE.exists(): | |
| 196 cached = json.loads(MAPS_CACHE.read_text()) | |
| 197 # the placement settings are part of the input, compared by value | |
| 9 | 198 if not stale(inputs, outputs, force) and cached and cached.get("settings") == settings: |
| 1 | 199 print("masks: up to date") |
| 200 return cached["maps"], False | |
| 201 | |
| 202 out = [] | |
| 203 for m in range(MAPS): | |
| 204 t0 = time.time() | |
| 9 | 205 mc = settings["maps"][m] |
| 1 | 206 mask = masks.Mask(ART / f"map{m}mask.png") |
| 207 found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE) | |
| 9 | 208 spaces = [(found["spawns"], mc["spawn_distance"]), |
| 209 (found["exit_points"], mc["exit_distance"])] | |
| 210 cols, rows, grid = masks.placement_grid(mask, placement, found["centre"], | |
| 211 mc["path_half_width"], spaces) | |
| 23 | 212 routes = [{"points": pts} for pts in found["routes"]] |
| 1 | 213 route_values(routes) |
| 214 g = found["graph"] | |
| 215 out.append({ | |
| 216 "name": f"map{m}", | |
| 217 "width": mask.w, | |
| 218 "height": mask.h, | |
| 219 "cell": placement["grid_cell"], | |
| 220 "cols": cols, | |
| 221 "rows": rows, | |
| 222 "grid": grid, | |
| 9 | 223 "line_width": found["width"], |
| 1 | 224 "entrances": [b[:3] for b in found["entrances"]], |
| 225 "exits": [b[:3] for b in found["exits"]], | |
| 226 "routes": routes, | |
| 227 "graph": { | |
| 228 "nodes": [list(p) for p in g.nodes.values()], | |
| 229 "edges": [e[2] for e in g.edges.values()], | |
| 230 }, | |
| 231 }) | |
| 232 print(f"masks: map{m} {len(routes)} route(s), {time.time() - t0:.1f} s") | |
| 233 | |
| 234 write_maps_js(out) | |
| 235 MAPS_CACHE.parent.mkdir(parents=True, exist_ok=True) | |
| 9 | 236 MAPS_CACHE.write_text(json.dumps({"settings": settings, "maps": out})) |
| 1 | 237 return out, True |
| 238 | |
| 239 | |
| 240 def write_maps_js(maps): | |
| 241 def rnd(v): | |
| 242 return round(v, ROUTE_DECIMALS) | |
| 243 | |
| 244 js = [] | |
| 245 for mp in maps: | |
| 246 js.append({ | |
| 247 "name": mp["name"], | |
| 248 "image": f"assets/{mp['name']}.jpg", | |
| 249 "width": mp["width"], | |
| 250 "height": mp["height"], | |
| 251 "cell": mp["cell"], | |
| 252 "cols": mp["cols"], | |
| 253 "rows": mp["rows"], | |
| 254 "grid": mp["grid"], | |
| 255 "entrances": [[rnd(v) for v in b] for b in mp["entrances"]], | |
| 256 "exits": [[rnd(v) for v in b] for b in mp["exits"]], | |
| 257 "routes": [{ | |
| 258 "points": [rnd(v) for p in r["points"] for v in p], | |
| 259 "length": rnd(r["length"]), | |
| 260 "turning": rnd(r["turning"]), | |
| 261 "value": round(r["value"], 3), | |
| 262 } for r in mp["routes"]], | |
| 263 }) | |
| 264 body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js) | |
| 23 | 265 write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png") |
| 1 | 266 + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n") |
| 267 | |
| 268 | |
| 4 | 269 # 5. sounds |
| 270 | |
| 271 def step_sounds(cfg, force): | |
| 272 """ | |
| 17 | 273 embed art/sounds/*.mp3 as base64 in www/data/sounds.js, grouped by |
| 4 | 274 event: NAME.mp3 or the variants NAME_1.mp3, NAME_2.mp3 and so on. |
| 275 """ | |
| 276 inputs = sorted(SOUNDS.glob("*.mp3")) | |
| 277 dst = DATA / "sounds.js" | |
| 278 if not stale(inputs, [dst], force): | |
| 279 print("sounds: up to date") | |
| 280 return | |
| 281 events = {} | |
| 282 for p in inputs: | |
| 283 name = re.sub(r"_\d+$", "", p.stem) | |
| 284 events.setdefault(name, []).append(base64.b64encode(p.read_bytes()).decode("ascii")) | |
| 285 for name in events: | |
| 286 if name not in cfg["sound"]["event"]: | |
| 287 warn(f"sounds: {name} has no entry in [sound.event]") | |
| 288 body = ",\n".join(f" {json.dumps(k)}: {json.dumps(v)}" for k, v in events.items()) | |
| 289 write_text(dst, HEADER.format(src="art/sounds/") | |
| 290 + "window.MM = window.MM || {};\nMM.sounds = {\n" + body + "\n};\n") | |
| 291 size = dst.stat().st_size / 1024 | |
| 292 print(f"sounds: wrote {len(inputs)} sounds for {len(events)} events, {size:.0f} KB") | |
| 293 | |
| 294 | |
| 295 # 6. config | |
| 1 | 296 |
| 297 class ConfigError(Exception): | |
| 298 pass | |
| 299 | |
| 300 | |
| 301 def need(table, key, kind, where): | |
| 302 if key not in table: | |
| 303 raise ConfigError(f"{where}: {key} missing") | |
| 304 v = table[key] | |
| 305 if kind is float: | |
| 306 ok = isinstance(v, (int, float)) and not isinstance(v, bool) | |
| 307 else: | |
| 308 ok = isinstance(v, kind) | |
| 309 if not ok: | |
| 310 raise ConfigError(f"{where}: {key} should be {kind.__name__}, is {v!r}") | |
| 311 return v | |
| 312 | |
| 313 | |
| 314 def check_config(cfg): | |
| 315 """raise ConfigError on missing or malformed settings.""" | |
| 10 | 316 for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower", |
| 23 | 317 "placement", "waves", "hearts", "coins", "controls", "art", "debug", |
| 24 | 318 "sound", "links", "map"): |
| 1 | 319 if sec not in cfg: |
| 320 raise ConfigError(f"section [{sec}] missing") | |
| 321 for mid, mon in cfg["monster"].items(): | |
| 322 for k in ("hp", "coins", "speed"): | |
| 323 need(mon, k, float, f"monster.{mid}") | |
| 324 for tid, tw in cfg["tower"].items(): | |
| 15 | 325 for k in TOWER_BY_LEVEL: |
| 24 | 326 if k in ("slow", "damage") and k not in tw: |
| 15 | 327 continue |
| 1 | 328 v = need(tw, k, list, f"tower.{tid}") |
| 15 | 329 if len(v) != 2 or not all(isinstance(x, (int, float)) and not isinstance(x, bool) |
| 330 for x in v): | |
| 331 raise ConfigError(f"tower.{tid}: {k} should be [level 1, level " | |
| 332 f"{TOWER_LEVELS}], is {v!r}") | |
| 333 for k in ("attack_time", "projectile_speed"): | |
| 1 | 334 need(tw, k, float, f"tower.{tid}") |
| 335 need(tw, "projectile", str, f"tower.{tid}") | |
| 24 | 336 if "splash_radius" in tw: |
| 337 need(tw, "splash_radius", float, f"tower.{tid}") | |
| 338 for k in ("logo_url", "email", "email_subject"): | |
| 339 need(cfg["links"], k, str, "links") | |
| 10 | 340 for k in ("speed_variation", "offset", "lean", "wander_step", "fade_in"): |
| 341 need(cfg["movement"], k, float, "movement") | |
| 1 | 342 for k in ("footprint_radius", "max_gap", "min_tower_distance", "edge_distance", |
| 343 "snap_radius", "grid_cell"): | |
| 344 need(cfg["placement"], k, float, "placement") | |
| 4 | 345 snd = cfg["sound"] |
| 346 need(snd, "enabled", bool, "sound") | |
| 347 need(snd, "volume", float, "sound") | |
| 348 need(snd, "beep_wave", str, "sound") | |
|
32
85d23328a215
added intro music, logic for browser audio triggering on splash screen
ark
parents:
27
diff
changeset
|
349 need(snd, "music_fade", float, "sound") |
| 4 | 350 for name, ev in need(snd, "event", dict, "sound").items(): |
| 351 where = f"sound.event.{name}" | |
| 352 need(ev, "volume", float, where) | |
| 353 if "min_interval" in ev: | |
| 354 need(ev, "min_interval", float, where) | |
| 355 for note in ev.get("beep", []): | |
| 356 if not (isinstance(note, list) and len(note) == 2): | |
| 357 raise ConfigError(f"{where}: beep notes should be [frequency, seconds]") | |
| 1 | 358 for m in range(MAPS): |
| 359 mp = cfg["map"].get(str(m)) | |
| 360 if mp is None: | |
| 361 raise ConfigError(f"[map.{m}] missing") | |
| 362 where = f"map.{m}" | |
| 9 | 363 for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS: |
| 1 | 364 need(mp, k, float, where) |
| 23 | 365 for k, n in (("monster_share", 5), ("wave_size", 2), ("first_wave", 5)): |
| 366 v = need(mp, k, list, where) | |
| 367 if len(v) != n or not all(isinstance(x, int) and not isinstance(x, bool) for x in v): | |
| 368 raise ConfigError(f"{where}: {k} should be {n} whole numbers, is {v!r}") | |
| 14 | 369 if "spawn_interval" in mp: |
| 370 need(mp, "spawn_interval", float, where) | |
| 1 | 371 for w, wave in enumerate(mp.get("wave", []), start=1): |
| 14 | 372 ww = f"{where} wave {w}" |
| 373 for mon in need(wave, "monsters", dict, ww): | |
| 1 | 374 if mon not in cfg["monster"]: |
| 14 | 375 raise ConfigError(f"{ww}: unknown monster {mon}") |
| 376 need(wave["monsters"], mon, int, ww) | |
| 1 | 377 |
| 378 | |
| 15 | 379 def tower_levels(ends): |
| 380 """ | |
| 381 the values for all tower levels from [level 1, last level], in equal | |
| 382 steps. whole numbers when both ends are whole (halves round up), | |
| 383 otherwise rounded to TOWER_DECIMALS. | |
| 384 """ | |
| 385 first, last = ends | |
| 386 whole = isinstance(first, int) and isinstance(last, int) | |
| 387 out = [] | |
| 388 for i in range(TOWER_LEVELS): | |
| 389 v = first + (last - first) * i / (TOWER_LEVELS - 1) | |
| 390 out.append(math.floor(v + 0.5) if whole else round(v, TOWER_DECIMALS)) | |
| 391 return out | |
| 392 | |
| 393 | |
| 1 | 394 def sprite_table(): |
| 17 | 395 """name -> [width, height] of every image in www/assets/ except maps.""" |
| 1 | 396 out = {} |
| 397 for p in sorted(ASSETS.glob("*.png")): | |
| 398 with Image.open(p) as im: | |
| 399 out[p.stem] = list(im.size) | |
| 400 return out | |
| 401 | |
| 402 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
403 def step_config(cfg, force, assets_changed, release): |
| 1 | 404 src = CONFIG / "game.toml" |
| 405 dst = DATA / "config.js" | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
406 # a switch between release and debug builds rewrites the file |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
407 was_release = dst.exists() and '"debug":' not in dst.read_text() |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
408 if not stale([src], [dst], force) and not assets_changed and was_release == release: |
| 1 | 409 print("config: up to date") |
| 410 return | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
411 out = {k: v for k, v in cfg.items() if k != "map" and not (release and k == "debug")} |
| 15 | 412 out["tower"] = {tid: {k: tower_levels(v) if k in TOWER_BY_LEVEL else v |
| 413 for k, v in tw.items()} | |
| 414 for tid, tw in cfg["tower"].items()} | |
| 1 | 415 out["maps"] = [] |
| 416 for m in range(MAPS): | |
| 417 mp = dict(cfg["map"][str(m)]) | |
| 418 mp["waves"] = mp.pop("wave", []) | |
| 419 out["maps"].append(mp) | |
| 420 out["sprites"] = sprite_table() | |
| 421 write_text(dst, HEADER.format(src="config/game.toml") | |
| 422 + "window.MM = window.MM || {};\nMM.config = " | |
| 423 + json.dumps(out, indent=1) + ";\n") | |
| 17 | 424 print("config: wrote www/data/config.js") |
| 1 | 425 |
| 426 | |
| 4 | 427 # 7. checks |
| 1 | 428 |
| 429 def wave_totals(cfg, waves): | |
| 430 """return per monster counts, regular coins, boss coins, regular hp.""" | |
| 431 counts = {} | |
| 432 for wave in waves: | |
| 14 | 433 for mon, n in wave["monsters"].items(): |
| 434 counts[mon] = counts.get(mon, 0) + n | |
| 1 | 435 mons = cfg["monster"] |
| 436 reg = sum(n * mons[k]["coins"] for k, n in counts.items() if not mons[k].get("boss")) | |
| 437 boss = sum(n * mons[k]["coins"] for k, n in counts.items() if mons[k].get("boss")) | |
| 438 hp = sum(n * mons[k]["hp"] for k, n in counts.items() if not mons[k].get("boss")) | |
| 439 return counts, reg, boss, hp | |
| 440 | |
| 441 | |
| 442 def step_checks(cfg, maps): | |
| 443 print("\nchecks") | |
| 444 mons = cfg["monster"] | |
| 445 regular = sorted(k for k, v in mons.items() if not v.get("boss")) | |
| 446 speeds = sorted({v["speed"] for v in mons.values()}) | |
| 447 for m, mp in enumerate(maps): | |
| 448 c = cfg["map"][str(m)] | |
| 9 | 449 print(f"\nmap{m}: {mp['width']}x{mp['height']}, line width {mp['line_width']:.0f}," |
| 450 f" road half width {c['path_half_width']}, {mp['grid'].count('1')} placement cells") | |
| 1 | 451 if len(mp["entrances"]) == 0 or len(mp["exits"]) == 0: |
| 452 warn(f"map{m}: no entrance or no exit found") | |
| 453 if not mp["routes"]: | |
| 454 warn(f"map{m}: no routes") | |
| 23 | 455 for k, r in enumerate(mp["routes"]): |
| 1 | 456 times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds) |
| 23 | 457 print(f" route {k}: length {r['length']:.0f}, turning {r['turning']:.0f} deg," |
| 458 f" value {r['value']:.2f}; walk time {times} s" | |
| 1 | 459 f" at speed {', '.join(str(s) for s in speeds)}") |
| 460 | |
| 461 waves = c.get("wave", []) | |
| 462 if len(waves) != c["wave_count"]: | |
| 463 warn(f"map{m}: {len(waves)} waves, wave_count says {c['wave_count']}") | |
| 464 if not waves: | |
| 465 continue | |
| 466 counts, reg, boss, hp = wave_totals(cfg, waves) | |
| 23 | 467 n_reg = sum(counts.get(k, 0) for k in regular) |
| 1 | 468 print(" monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts)) |
| 469 + f", {sum(counts.values())} in all") | |
| 23 | 470 share = [100 * counts.get(k, 0) / n_reg if n_reg else 0 for k in regular] |
| 471 print(" share by count %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t | |
| 472 in zip(regular, share, c["monster_share"]))) | |
| 473 print(f" coins: regular {reg}, boss {boss}, total {reg + boss}," | |
| 474 f" {reg + boss + c['starting_coins']} with the starting coins;" | |
| 475 f" regular hp {hp}, {reg / hp if hp else 0:.2f} coins per hp") | |
| 1 | 476 per_wave = [] |
| 477 for w, wave in enumerate(waves, start=1): | |
| 478 _, r, b, _ = wave_totals(cfg, [wave]) | |
| 479 per_wave.append(r + b) | |
| 480 print(" coins per wave: " + ", ".join(str(v) for v in per_wave)) | |
| 481 | |
| 14 | 482 bosses = [(k, n) for w in waves for k, n in w["monsters"].items() |
| 483 if n and mons[k].get("boss")] | |
| 484 if bosses != [(f"b{m}", 1)] or not waves[-1]["monsters"].get(f"b{m}"): | |
| 485 warn(f"map{m}: expected one b{m} in the last wave") | |
| 1 | 486 bonus = c["early_bonus"] * (cfg["waves"]["first_break"] |
| 487 + cfg["waves"]["break"] * (len(waves) - 1)) | |
| 488 print(f" early start bonus if every break is skipped: {math.floor(bonus)}") | |
| 489 | |
| 490 | |
| 4 | 491 # 8. previews |
| 1 | 492 |
| 2 | 493 def step_previews(cfg, maps, force, changed): |
| 1 | 494 outputs = [PREVIEW / f"map{m}.png" for m in range(MAPS)] + [PREVIEW / "towers.png"] |
|
19
3a831478eda4
adjusted tower pivot and angle definitions to better match scribbled assets
ark
parents:
17
diff
changeset
|
495 # the tower sheet shows the angles, pivots, footprint and sprite scale from game.toml |
| 2 | 496 if not changed and not stale([CONFIG / "game.toml"], outputs, force): |
| 1 | 497 print("previews: up to date") |
| 498 return | |
| 499 PREVIEW.mkdir(parents=True, exist_ok=True) | |
| 500 for m, mp in enumerate(maps): | |
| 501 preview.map_preview(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}.png") | |
| 502 if len(mp["routes"]) > 1: | |
| 503 preview.route_sheet(ART / f"map{m}.png", mp).save(PREVIEW / f"map{m}_routes.png") | |
|
19
3a831478eda4
adjusted tower pivot and angle definitions to better match scribbled assets
ark
parents:
17
diff
changeset
|
504 preview.tower_sheet(ASSETS, cfg["art"]["angle"], cfg["art"]["pivot"], |
|
3a831478eda4
adjusted tower pivot and angle definitions to better match scribbled assets
ark
parents:
17
diff
changeset
|
505 cfg["placement"]["footprint_radius"], |
| 16 | 506 cfg["scale"]["sprite"]).save(PREVIEW / "towers.png") |
| 1 | 507 print(f"previews: wrote {PREVIEW.relative_to(ROOT)}/") |
| 508 | |
| 509 | |
| 17 | 510 # 9. game files |
| 511 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
512 # debug switches and drawing, left out of a release build |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
513 DEBUG_JS = Path("js") / "debug.js" |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
514 |
| 17 | 515 def game_files(): |
| 516 """the hand-written files in game/, as paths relative to it.""" | |
| 517 return sorted(p.relative_to(GAME) for p in GAME.rglob("*") | |
| 518 if p.is_file() and p.name != ".DS_Store") | |
| 519 | |
| 520 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
521 def step_game(force, release): |
| 17 | 522 """ |
| 523 copy the files in game/ to www/ when they differ in time or size, and | |
| 524 remove files from www/ that are no longer in game/. www/assets/ and | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
525 www/data/ are left alone, as the other steps write them. a release |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
526 build writes js/debug.js empty. |
| 17 | 527 """ |
| 528 files = game_files() | |
| 529 copied = 0 | |
| 530 for rel in files: | |
| 531 src, dst = GAME / rel, WWW / rel | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
532 if release and rel == DEBUG_JS: |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
533 if force or not dst.exists() or dst.stat().st_size: |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
534 write_text(dst, "") |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
535 copied += 1 |
|
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
536 continue |
| 17 | 537 a = src.stat() |
| 538 if not force and dst.exists(): | |
| 539 b = dst.stat() | |
| 540 if b.st_mtime == a.st_mtime and b.st_size == a.st_size: | |
| 541 continue | |
| 542 dst.parent.mkdir(parents=True, exist_ok=True) | |
| 543 shutil.copy2(src, dst) | |
| 544 copied += 1 | |
| 545 keep = set(files) | |
| 546 removed = 0 | |
| 547 for p in sorted(WWW.rglob("*"), reverse=True): | |
| 548 rel = p.relative_to(WWW) | |
| 549 if rel.parts[0] in (ASSETS.name, DATA.name) or rel in keep: | |
| 550 continue | |
| 551 if p.is_file(): | |
| 552 p.unlink() | |
| 553 removed += 1 | |
| 554 elif not any(p.iterdir()): | |
| 555 p.rmdir() | |
| 556 if copied or removed: | |
| 557 print(f"game files: copied {copied}, removed {removed}") | |
| 558 else: | |
| 559 print("game files: up to date") | |
| 560 | |
| 561 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
562 def build(force, release): |
| 1 | 563 warnings.clear() |
| 564 try: | |
| 565 cfg = tomllib.loads((CONFIG / "game.toml").read_text()) | |
| 566 check_config(cfg) | |
| 567 except (tomllib.TOMLDecodeError, ConfigError) as e: | |
| 568 print("config error:", e) | |
| 569 return False | |
| 570 changed = step_sprites(force) | |
| 571 changed |= step_towers(force) | |
| 572 step_maps(force) | |
| 573 maps, masks_changed = step_masks(cfg, force) | |
| 4 | 574 step_sounds(cfg, force) |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
575 step_config(cfg, force, changed, release) |
| 1 | 576 step_checks(cfg, maps) |
| 2 | 577 step_previews(cfg, maps, force, changed or masks_changed) |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
578 step_game(force, release) |
| 1 | 579 print(f"\n{len(warnings)} warning(s)") |
| 580 return True | |
| 581 | |
| 582 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
583 def watch(release): |
| 1 | 584 def snapshot(): |
|
8
2c4fed8baed9
art update, persistent sound setting, tower selling as double action
ark
parents:
6
diff
changeset
|
585 files = (list(ART.iterdir()) + list(SOUNDS.glob("*.mp3")) + list(DIGITS.glob("*.png")) |
| 17 | 586 + list(CONFIG.iterdir()) + [GAME / p for p in game_files()] + TOOLS) |
| 1 | 587 return {p: p.stat().st_mtime for p in files if p.is_file()} |
| 588 | |
| 589 seen = None | |
| 590 while True: | |
| 591 now = snapshot() | |
| 592 if now != seen: | |
| 593 seen = now | |
| 594 print(time.strftime("\n== build %H:%M:%S")) | |
| 595 try: | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
596 build(False, release) |
| 1 | 597 except Exception as e: # keep watching after a failed build |
| 598 print("build failed:", e) | |
| 599 time.sleep(1) | |
| 600 | |
| 601 | |
| 602 def main(): | |
| 603 args = sys.argv[1:] | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
604 release = "--release" in args |
| 1 | 605 if "--watch" in args: |
| 606 # show each line at once, also when the output goes to a file | |
| 607 sys.stdout.reconfigure(line_buffering=True) | |
| 608 try: | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
609 watch(release) |
| 1 | 610 except KeyboardInterrupt: |
| 611 pass | |
| 612 return 0 | |
|
27
75deda08db90
game debug functions separated into own file; release build option, distribution script
ark
parents:
24
diff
changeset
|
613 return 0 if build("--force" in args, release) else 1 |
| 1 | 614 |
| 615 | |
| 616 if __name__ == "__main__": | |
| 617 sys.exit(main()) |
