comparison tools/build.py @ 23:2f555a54c332

layout fixes and balancing
author ark
date 2026-10-20 12:04 +0200
parents ad1b478fc4dc
children 3f2811aebb3d
comparison
equal deleted inserted replaced
22:ad1b478fc4dc 23:2f555a54c332
164 return changed 164 return changed
165 165
166 166
167 # 4. masks 167 # 4. masks
168 168
169 def apply_corrections(m, routes, fix):
170 """
171 apply routes.toml corrections for map m to a list of route dicts.
172 each route dict has points, and gets a fixed weight or None.
173 """
174 for r in routes:
175 r["weight"] = None
176 for spec in fix.get("route", []):
177 pts = [tuple(p) for p in spec["points"]]
178 if "replace" in spec:
179 routes[spec["replace"]]["points"] = pts
180 routes[spec["replace"]]["manual"] = True
181 else:
182 routes.append({"points": pts, "weight": None, "manual": True})
183 for k, v in fix.get("weights", {}).items():
184 routes[int(k)]["weight"] = float(v)
185 drop = set(fix.get("drop", []))
186 for i, r in enumerate(routes):
187 r["number"] = i
188 return [r for i, r in enumerate(routes) if i not in drop]
189
190
191 def route_values(routes): 169 def route_values(routes):
192 """ 170 """
193 fill in length, turning and value of each route (balance.md, route 171 fill in length, turning and value of each route (balance.md, route
194 preference): the average of length relative to the longest route and 172 preference): the average of length relative to the longest route and
195 straightness relative to the straightest, that is the least turning. 173 straightness relative to the straightest, that is the least turning.
206 184
207 def step_masks(cfg, force): 185 def step_masks(cfg, force):
208 placement = cfg["placement"] 186 placement = cfg["placement"]
209 settings = {"placement": placement, 187 settings = {"placement": placement,
210 "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]} 188 "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]}
211 routes_toml = CONFIG / "routes.toml" 189 inputs = [ART / f"map{m}mask.png" for m in range(MAPS)]
212 inputs = [ART / f"map{m}mask.png" for m in range(MAPS)] + [routes_toml]
213 outputs = [DATA / "maps.js", MAPS_CACHE] 190 outputs = [DATA / "maps.js", MAPS_CACHE]
214 cached = None 191 cached = None
215 if MAPS_CACHE.exists(): 192 if MAPS_CACHE.exists():
216 cached = json.loads(MAPS_CACHE.read_text()) 193 cached = json.loads(MAPS_CACHE.read_text())
217 # the placement settings are part of the input, compared by value 194 # the placement settings are part of the input, compared by value
218 if not stale(inputs, outputs, force) and cached and cached.get("settings") == settings: 195 if not stale(inputs, outputs, force) and cached and cached.get("settings") == settings:
219 print("masks: up to date") 196 print("masks: up to date")
220 return cached["maps"], False 197 return cached["maps"], False
221 198
222 fixes = tomllib.loads(routes_toml.read_text()).get("map", {})
223 out = [] 199 out = []
224 for m in range(MAPS): 200 for m in range(MAPS):
225 t0 = time.time() 201 t0 = time.time()
226 mc = settings["maps"][m] 202 mc = settings["maps"][m]
227 mask = masks.Mask(ART / f"map{m}mask.png") 203 mask = masks.Mask(ART / f"map{m}mask.png")
228 found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE) 204 found = masks.extract_routes(mask, ROUTE_SMOOTH, ROUTE_TOLERANCE)
229 spaces = [(found["spawns"], mc["spawn_distance"]), 205 spaces = [(found["spawns"], mc["spawn_distance"]),
230 (found["exit_points"], mc["exit_distance"])] 206 (found["exit_points"], mc["exit_distance"])]
231 cols, rows, grid = masks.placement_grid(mask, placement, found["centre"], 207 cols, rows, grid = masks.placement_grid(mask, placement, found["centre"],
232 mc["path_half_width"], spaces) 208 mc["path_half_width"], spaces)
233 routes = [{"points": pts, "manual": False} for pts in found["routes"]] 209 routes = [{"points": pts} for pts in found["routes"]]
234 routes = apply_corrections(m, routes, fixes.get(str(m), {}))
235 route_values(routes) 210 route_values(routes)
236 g = found["graph"] 211 g = found["graph"]
237 out.append({ 212 out.append({
238 "name": f"map{m}", 213 "name": f"map{m}",
239 "width": mask.w, 214 "width": mask.w,
279 "routes": [{ 254 "routes": [{
280 "points": [rnd(v) for p in r["points"] for v in p], 255 "points": [rnd(v) for p in r["points"] for v in p],
281 "length": rnd(r["length"]), 256 "length": rnd(r["length"]),
282 "turning": rnd(r["turning"]), 257 "turning": rnd(r["turning"]),
283 "value": round(r["value"], 3), 258 "value": round(r["value"], 3),
284 "weight": r["weight"],
285 } for r in mp["routes"]], 259 } for r in mp["routes"]],
286 }) 260 })
287 body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js) 261 body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js)
288 write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png and config/routes.toml") 262 write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png")
289 + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n") 263 + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n")
290 264
291 265
292 # 5. sounds 266 # 5. sounds
293 267
335 309
336 310
337 def check_config(cfg): 311 def check_config(cfg):
338 """raise ConfigError on missing or malformed settings.""" 312 """raise ConfigError on missing or malformed settings."""
339 for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower", 313 for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower",
340 "placement", "economy", "waves", "hearts", "coins", "controls", "art", "debug", 314 "placement", "waves", "hearts", "coins", "controls", "art", "debug",
341 "sound", "map"): 315 "sound", "map"):
342 if sec not in cfg: 316 if sec not in cfg:
343 raise ConfigError(f"section [{sec}] missing") 317 raise ConfigError(f"section [{sec}] missing")
344 for mid, mon in cfg["monster"].items(): 318 for mid, mon in cfg["monster"].items():
345 for k in ("hp", "coins", "speed"): 319 for k in ("hp", "coins", "speed"):
378 if mp is None: 352 if mp is None:
379 raise ConfigError(f"[map.{m}] missing") 353 raise ConfigError(f"[map.{m}] missing")
380 where = f"map.{m}" 354 where = f"map.{m}"
381 for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS: 355 for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS:
382 need(mp, k, float, where) 356 need(mp, k, float, where)
383 need(mp, "monster_share", list, where) 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}")
384 if "spawn_interval" in mp: 361 if "spawn_interval" in mp:
385 need(mp, "spawn_interval", float, where) 362 need(mp, "spawn_interval", float, where)
386 for w, wave in enumerate(mp.get("wave", []), start=1): 363 for w, wave in enumerate(mp.get("wave", []), start=1):
387 ww = f"{where} wave {w}" 364 ww = f"{where} wave {w}"
388 for mon in need(wave, "monsters", dict, ww): 365 for mon in need(wave, "monsters", dict, ww):
463 f" road half width {c['path_half_width']}, {mp['grid'].count('1')} placement cells") 440 f" road half width {c['path_half_width']}, {mp['grid'].count('1')} placement cells")
464 if len(mp["entrances"]) == 0 or len(mp["exits"]) == 0: 441 if len(mp["entrances"]) == 0 or len(mp["exits"]) == 0:
465 warn(f"map{m}: no entrance or no exit found") 442 warn(f"map{m}: no entrance or no exit found")
466 if not mp["routes"]: 443 if not mp["routes"]:
467 warn(f"map{m}: no routes") 444 warn(f"map{m}: no routes")
468 for r in mp["routes"]: 445 for k, r in enumerate(mp["routes"]):
469 times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds) 446 times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds)
470 fixed = f", weight {r['weight']}" if r["weight"] is not None else "" 447 print(f" route {k}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
471 manual = ", manual" if r.get("manual") else "" 448 f" value {r['value']:.2f}; walk time {times} s"
472 print(f" route {r['number']}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
473 f" value {r['value']:.2f}{fixed}{manual}; walk time {times} s"
474 f" at speed {', '.join(str(s) for s in speeds)}") 449 f" at speed {', '.join(str(s) for s in speeds)}")
475 450
476 waves = c.get("wave", []) 451 waves = c.get("wave", [])
477 if len(waves) != c["wave_count"]: 452 if len(waves) != c["wave_count"]:
478 warn(f"map{m}: {len(waves)} waves, wave_count says {c['wave_count']}") 453 warn(f"map{m}: {len(waves)} waves, wave_count says {c['wave_count']}")
479 if not waves: 454 if not waves:
480 continue 455 continue
481 counts, reg, boss, hp = wave_totals(cfg, waves) 456 counts, reg, boss, hp = wave_totals(cfg, waves)
482 target = c["starting_coins"] * cfg["economy"]["coin_total_factor"] 457 n_reg = sum(counts.get(k, 0) for k in regular)
483 total = reg + boss
484 print(" monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts)) 458 print(" monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts))
485 + f", {sum(counts.values())} in all") 459 + f", {sum(counts.values())} in all")
486 share = [100 * counts.get(k, 0) * mons[k]["coins"] / reg if reg else 0 for k in regular] 460 share = [100 * counts.get(k, 0) / n_reg if n_reg else 0 for k in regular]
487 print(" coin share %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t 461 print(" share by count %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t
488 in zip(regular, share, c["monster_share"]))) 462 in zip(regular, share, c["monster_share"])))
489 print(f" coins: regular {reg}, boss {boss}, total {total}, target {target:.0f};" 463 print(f" coins: regular {reg}, boss {boss}, total {reg + boss},"
490 f" regular hp {hp}") 464 f" {reg + boss + c['starting_coins']} with the starting coins;"
491 if abs(total - target) > cfg["economy"]["coin_tolerance"] * target: 465 f" regular hp {hp}, {reg / hp if hp else 0:.2f} coins per hp")
492 warn(f"map{m}: coins {total} are more than"
493 f" {cfg['economy']['coin_tolerance'] * 100:.0f} % off the target {target:.0f}")
494 per_wave = [] 466 per_wave = []
495 for w, wave in enumerate(waves, start=1): 467 for w, wave in enumerate(waves, start=1):
496 _, r, b, _ = wave_totals(cfg, [wave]) 468 _, r, b, _ = wave_totals(cfg, [wave])
497 per_wave.append(r + b) 469 per_wave.append(r + b)
498 print(" coins per wave: " + ", ".join(str(v) for v in per_wave)) 470 print(" coins per wave: " + ", ".join(str(v) for v in per_wave))