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