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