comparison tools/build.py @ 1:5492efd60e2c

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