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