#!/usr/bin/env python3 """Simulate a full first-chapter run against the frozen P3a content. This answers the question that matters for playability: with the profile the game actually starts with, can a player reach the boss and win it? The script uses the paper runner's deterministic battle logic, so the numbers are the same ones the Godot runtime would produce. It models the minimum-effort player: never clicks, never uses the storm or ultimate, and only spends gold on the cheapest visible hero upgrade when it can afford one. Any node this profile can clear is therefore comfortably clearable by an engaged player. Usage: python3 tools/simulate_chapter.py """ from __future__ import annotations import argparse import json from pathlib import Path from typing import Any, Dict, List from mvp_validation_sim import Rules, run_scenario ROOT = Path(__file__).resolve().parent.parent RULES_PATH = ROOT / "data/mvp_battle_rules.json" CONTENT_PATH = ROOT / "data/mvp_launch_content.json" SEED = 10001 def read_json(path: Path) -> Dict[str, Any]: with path.open("r", encoding="utf-8") as handle: return json.load(handle) def hero_names(content: Dict[str, Any]) -> Dict[str, str]: return {str(row["id"]): str(row.get("name", row["id"])) for row in content["heroes"]} def active_inputs(timeout: float) -> List[Dict[str, Any]]: """A player who taps continuously and uses storm/ultimate on cooldown.""" events: List[Dict[str, Any]] = [] time = 0.2 while time < timeout: events.append({"time": round(time, 2), "type": "click_enemy"}) time += 0.2 for storm_time in (3.0, 13.0, 23.0): if storm_time < timeout: events.append({"time": storm_time, "type": "offboard_burst"}) for ultimate_time in (5.0, 15.0, 25.0): if ultimate_time < timeout: events.append({"time": ultimate_time, "type": "cast_ultimate", "hero_id": "H01"}) return events def simulate(content: Dict[str, Any], rules: Rules, seed: int, active: bool = False) -> Dict[str, Any]: heroes = {str(row["id"]): row for row in content["heroes"]} enemies = {str(row["id"]): row for row in content["enemies"]} boss = content["boss"] unlocked: List[str] = ["H01", "H02", "H03"] levels: Dict[str, int] = {hero_id: 1 for hero_id in unlocked} gold = 0 crystal = 0 completed: List[str] = [] results: List[Dict[str, Any]] = [] def roster_dps() -> float: total = 0.0 for hero_id in unlocked: total += float(heroes[hero_id]["base_dps"]) * (1.0 + 0.25 * (levels[hero_id] - 1)) return total def upgrade() -> bool: # Cheapest unlocked hero first; this is what a player would do. candidates = sorted(unlocked, key=lambda h: heroes[h]["base_dps"]) for hero_id in candidates: cost = int(round(120.0 * pow(1.15, levels[hero_id] - 1))) if gold >= cost: # Return the cost so the caller can spend it. return True return False def cheapest_upgrade() -> tuple: candidates = sorted(unlocked, key=lambda h: heroes[h]["base_dps"]) best = None for hero_id in candidates: cost = int(round(120.0 * pow(1.15, levels[hero_id] - 1))) if best is None or cost < best[1]: best = (hero_id, cost) return best if best else ("", -1) for node in content["nodes"]: node_id = str(node["id"]) waves: List[List[str]] = node.get("waves", []) if node.get("type") == "event": # Event nodes grant their gold without a battle in the current # shell; record that honestly rather than inventing a fight. gold += int(node.get("gold", 0)) completed.append(node_id) results.append({ "node": node_id, "type": "event", "result": "resolved", "dps": round(roster_dps(), 1), "gold": gold, }) continue node_won = bool(waves) node_time = 0.0 for wave_index, wave in enumerate(waves): enemy_specs: Dict[str, Any] = {} enemy_ids: List[str] = [] for index, enemy_id in enumerate(wave): enemy_id = str(enemy_id) enemy_ids.append(enemy_id) spec = enemies.get(enemy_id, boss if enemy_id.startswith("B-") else {}) enemy_specs[enemy_id] = { "hp": float(spec.get("hp", spec.get("base_hp", 0.0))), "armor": float(spec.get("armor", 1.0)), "shield": float(spec.get("shield_max", 0.0)), "weak_tag": str(spec.get("weak_tag", "")), "rebuild_at": list(spec.get("rebuild_at", [])), "rebuild_amount": float(spec.get("rebuild_amount", 0.0)), } scenario = { "id": node_id, "mode": "auto", "enemy_ids": enemy_ids, "enemy_specs": enemy_specs, "visible_hero_ids": list(unlocked), "roster_hero_ids": list(unlocked), "input_events": active_inputs(float(node["timeout_sec"])) if active else [], "timeout_seconds": float(node.get("timeout_sec", 45.0)), "hp_scale": float(node.get("hp_scale", 1.0)), } outcome = run_scenario(rules, scenario, seed + wave_index, float(node["timeout_sec"])) node_time += float(outcome["duration_seconds"]) if outcome["result"] != "win": node_won = False break if node_won: gold += int(node.get("gold", 0)) crystal += int(node.get("crystal", 0)) completed.append(node_id) for unlock in node.get("unlocks", []): if unlock not in unlocked: unlocked.append(str(unlock)) levels[str(unlock)] = 1 # Spend down to the next upgrade, as a player would between nodes. while upgrade(): hero_id, cost = cheapest_upgrade() levels[hero_id] += 1 gold -= cost results.append({ "node": node_id, "type": node.get("type", ""), "result": "win" if node_won else "loss", "duration": round(node_time, 1), "dps": round(roster_dps(), 1), "gold": gold, "heroes": len(unlocked), }) return { "seed": seed, "results": results, "final": { "gold": gold, "crystal": crystal, "heroes": unlocked, "levels": levels, "completed": completed, }, } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--out", type=Path, default=ROOT / "data/chapter_simulation_results.json") parser.add_argument("--seed", type=int, default=SEED) parser.add_argument("--active", action="store_true", help="model continuous taps and manual cooldowns") args = parser.parse_args() rules = Rules(read_json(RULES_PATH)) content = read_json(CONTENT_PATH) report = simulate(content, rules, args.seed, active=args.active) names = hero_names(content) print(f"{'node':<14} {'type':<8} {'result':<8} {'time':>7} {'dps':>7} {'gold':>6} {'heroes':>7}") for row in report["results"]: print( f"{row['node']:<14} {row['type']:<8} {row['result']:<8} " f"{row.get('duration', 0):>7} {row['dps']:>7} {row['gold']:>6} {row.get('heroes', 0):>7}" ) final = report["final"] print(f"\ncleared {len(final['completed'])}/10 nodes, gold={final['gold']}, crystal={final['crystal']}") print("heroes: " + ", ".join(f"{names[h]} Lv.{final['levels'][h]}" for h in final["heroes"])) args.out.write_text( json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) losses = [row for row in report["results"] if row["result"] == "loss"] return 1 if losses else 0 if __name__ == "__main__": raise SystemExit(main())