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