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