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