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