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