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