Files
windroost/tools/mvp_validation_sim.py
T
wushenghua 970cadb129 feat: add offline progress, rebuild and a full-chapter balance simulation
P3b. ProfileStore is now schema 3 with an 8-hour-capped offline report derived
from roster DPS, a claim-once guard, clock-rollback handling, and a rebuild
transaction that clears run state while keeping recruited heroes and granting
wind essence. The skyport shows the claimable report and a rebuild entry.

Balance. simulate_chapter.py plays the whole chapter with two profiles. The
minimum-effort profile clears 9/10 nodes (N08 needs taps); the active profile
clears 10/10 including the boss. This is the evidence that the chapter is
actually completable and that manual input changes the outcome. The boss's
1500 HP was being wrongly multiplied by the node scale; the content generator
now keeps it fixed as the data pack requires.

Paper parity. mvp_validation_sim.py now understands P3a enemy specs, node HP
scale and the recruited-roster filter, so the runtime and paper models stay
aligned beyond the P2 fixture. The 300-result parity gate still passes.

tools/run_p2_checks.sh now runs 15 gates; all pass. Recorded balance note:
an active player kills the boss in ~4s, so the 30s timer and phases are not
yet meaningful. That is a tuning item against the frozen data pack, not a
local fix to smuggle in.
2026-11-17 01:25:30 +08:00

570 lines
20 KiB
Python

#!/usr/bin/env python3
"""Deterministic P1 validation runner for the Windroost MVP seed pack.
This is the **paper** simulator: it defines the agreed numeric contract for
the P3a vertical slice. It is deliberately engine-free so the numbers can be
reviewed and re-derived without launching Godot.
The Godot runtime adapter (`p2_godot_sample/scripts/battle_sim.gd`) implements
the same algorithm and MUST reproduce this runner's output byte for byte.
`tools/mvp_parity_gate.py` enforces that.
All balance data comes from `data/mvp_battle_rules.json`; this file owns no
numbers of its own. Every run is deterministic for (scenario_id, seed, input).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import random
import sys
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
DEFAULT_RULES_PATH = Path("data/mvp_battle_rules.json")
DEFAULT_PACK_PATH = Path("data/mvp_validation_seed_pack.json")
DEFAULT_OUT_PATH = Path("data/mvp_validation_seed_results.json")
TIME_EPSILON = 1e-9
RESULT_KEYS = (
"seed",
"scenario_id",
"mode",
"result",
"duration_seconds",
"roster_dps",
"visible_signature_damage",
"click_damage",
"burst_damage",
"ultimate_casts",
"shield_broken",
"weakness_hits",
"reward_id",
"event_log",
)
class Rules:
"""Shared combat rules loaded from data/mvp_battle_rules.json."""
def __init__(self, payload: Dict[str, Any]) -> None:
self.raw = payload
self.tick_seconds = float(payload["tick_seconds"])
seed = payload["seed_derivation"]
self.seed_algorithm = str(seed["algorithm"])
self.seed_input_format = str(seed["input_format"])
self.seed_prefix_bytes = int(seed["prefix_bytes"])
self.seed_divisor = int(seed["divisor"])
self.constants = payload["constants"]
self.heroes: Dict[str, Dict[str, Any]] = payload["heroes"]
self.enemies: Dict[str, Dict[str, Any]] = payload["enemies"]
self.reward_ids: Dict[str, str] = payload["reward_ids"]
@property
def armor_base(self) -> float:
return float(self.constants["armor_base"])
@property
def weak_multiplier(self) -> float:
return float(self.constants["weak_multiplier"])
@property
def efficiency_min(self) -> float:
return float(self.constants["efficiency_min"])
@property
def efficiency_range(self) -> float:
return float(self.constants["efficiency_range"])
def read_json(path: Path) -> Dict[str, Any]:
with path.open("r", encoding="utf-8") as handle:
value = json.load(handle)
if not isinstance(value, dict):
raise ValueError(f"expected JSON object in {path}")
return value
def unit_from_hash(rules: Rules, scenario_id: str, seed: int) -> float:
"""Derive a stable [0,1) value from SHA-256.
The prefix is 6 bytes = 48 bits, which every engine can hold exactly in a
float64, so Python and GDScript derive an identical double. Do not widen
the prefix without re-verifying both engines.
"""
material = rules.seed_input_format.format(scenario_id=scenario_id, seed=seed)
digest = hashlib.sha256(material.encode("utf-8")).digest()
value = int.from_bytes(digest[: rules.seed_prefix_bytes], "big")
return value / rules.seed_divisor
def round_metric(value: float) -> float:
return round(value + 0.0, 3)
def event_key(event: Dict[str, Any]) -> Tuple[float, str]:
return (float(event.get("time", 0.0)), str(event.get("type", "")))
def validate_pack(pack: Dict[str, Any], rules: Rules) -> None:
if pack.get("schema") != 1:
raise ValueError("unsupported seed pack schema")
if pack.get("tick_seconds") != rules.tick_seconds:
raise ValueError(f"seed pack tick_seconds must be {rules.tick_seconds}")
scenarios = pack.get("scenarios")
if not isinstance(scenarios, list) or not scenarios:
raise ValueError("seed pack has no scenarios")
required = set(pack.get("result_schema", {}).get("required", []))
missing = [key for key in RESULT_KEYS if key not in required]
if missing:
raise ValueError(f"result schema is missing: {', '.join(missing)}")
for scenario in scenarios:
for key in ("id", "mode", "enemy_ids", "visible_hero_ids", "input_events"):
if key not in scenario:
raise ValueError(f"scenario missing {key}: {scenario!r}")
unknown_heroes = set(scenario["visible_hero_ids"]) - set(rules.heroes)
if unknown_heroes:
raise ValueError(f"unknown visible hero ids: {sorted(unknown_heroes)}")
unknown_enemies = set(scenario["enemy_ids"]) - set(rules.enemies)
if unknown_enemies:
raise ValueError(f"unknown enemy ids: {sorted(unknown_enemies)}")
def armor_factor(rules: Rules, armor: float) -> float:
return rules.armor_base / (rules.armor_base + armor)
def apply_damage(
rules: Rules,
enemy: Dict[str, Any],
gross: float,
*,
label: str,
timestamp: float,
event_log: List[Dict[str, Any]],
weak: bool = False,
) -> Tuple[float, float, bool]:
"""Apply damage and return (hp_damage, shield_damage, broke_shield)."""
if enemy["dead"] or gross <= 0.0:
return (0.0, 0.0, False)
if weak:
gross *= rules.weak_multiplier
mitigated = gross * armor_factor(rules, enemy["armor"])
shield_damage = min(enemy["shield"], mitigated)
enemy["shield"] -= shield_damage
hp_damage = max(0.0, mitigated - shield_damage)
enemy["hp"] = max(0.0, enemy["hp"] - hp_damage)
broke = (
enemy["shield"] <= TIME_EPSILON
and enemy["shield_before"] > 0.0
and not enemy["shield_broken"]
)
if broke:
enemy["shield_broken"] = True
event_log.append(
{
"time": round_metric(timestamp),
"type": "shield_break",
"target_id": enemy["id"],
"source": label,
}
)
if enemy["hp"] <= TIME_EPSILON:
enemy["dead"] = True
event_log.append(
{
"time": round_metric(timestamp),
"type": "enemy_defeated",
"target_id": enemy["id"],
"source": label,
}
)
return (hp_damage, shield_damage, broke)
def build_enemy(
rules: Rules,
enemy_id: str,
index: int,
spec_override: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
# P2 scenarios take their stats from the shared rules file. P3a scenarios
# carry their own specs from the launch content file.
spec = spec_override or rules.enemies[enemy_id]
return {
"id": f"{enemy_id}#{index + 1}",
"content_id": enemy_id,
"hp": float(spec["hp"]),
"max_hp": float(spec["hp"]),
"armor": float(spec["armor"]),
"shield": float(spec["shield"]),
"shield_before": float(spec["shield"]),
"weak_tag": str(spec["weak_tag"]),
"rebuild_at": list(spec.get("rebuild_at", [])),
"rebuild_amount": float(spec.get("rebuild_amount", 0.0)),
"shield_broken": False,
"dead": False,
}
def choose_target(
enemies: List[Dict[str, Any]], target_id: Optional[str] = None
) -> Optional[Dict[str, Any]]:
if target_id:
for enemy in enemies:
if enemy["content_id"] == target_id or enemy["id"] == target_id:
if not enemy["dead"]:
return enemy
for enemy in enemies:
if not enemy["dead"]:
return enemy
return None
def has_weakness(
rules: Rules, visible_hero_ids: List[str], weak_tag: str
) -> bool:
"""True when any visible signature hero counters this enemy weakness."""
for hero_id in visible_hero_ids:
counters = rules.heroes[hero_id].get("counters", [])
if weak_tag in counters:
return True
return False
def run_scenario(
rules: Rules, scenario: Dict[str, Any], seed: int, timeout: float
) -> Dict[str, Any]:
scenario_id = str(scenario["id"])
mode = str(scenario["mode"])
visible_hero_ids = list(scenario["visible_hero_ids"])
efficiency = rules.efficiency_min + unit_from_hash(rules, scenario_id, seed) * rules.efficiency_range
roster_hero_ids = scenario.get("roster_hero_ids", [])
if roster_hero_ids:
roster_dps = sum(
float(rules.heroes[str(hero_id)]["base_dps"]) for hero_id in roster_hero_ids
)
else:
roster_dps = sum(float(hero["base_dps"]) for hero in rules.heroes.values())
roster_dps += float(scenario.get("roster_bonus", 0.0))
signature_dps = sum(
float(rules.heroes[hero_id]["signature_dps"]) for hero_id in visible_hero_ids
)
enemy_specs: Dict[str, Any] = scenario.get("enemy_specs", {})
enemies = [
build_enemy(rules, enemy_id, idx, enemy_specs.get(enemy_id))
for idx, enemy_id in enumerate(scenario["enemy_ids"])
]
hp_scale = float(scenario.get("hp_scale", 1.0))
if hp_scale > 0.0 and abs(hp_scale - 1.0) > 1e-12:
for enemy in enemies:
enemy["hp"] *= hp_scale
enemy["max_hp"] *= hp_scale
event_log: List[Dict[str, Any]] = []
input_events = sorted(scenario.get("input_events", []), key=event_key)
input_index = 0
click_damage = 0.0
burst_damage = 0.0
ultimate_casts = 0
visible_signature_damage = 0.0
weakness_hits = 0
shield_broken = 0
time = 0.0
result = "timeout"
max_ticks = int(math.ceil(timeout / rules.tick_seconds))
for tick in range(max_ticks + 1):
time = round(tick * rules.tick_seconds, 10)
while (
input_index < len(input_events)
and float(input_events[input_index].get("time", 0.0)) <= time + TIME_EPSILON
):
action = input_events[input_index]
action_type = action.get("type")
target = choose_target(enemies, action.get("target_id"))
if action_type == "click_enemy" and target:
raw = (
float(rules.constants["click_base"])
+ roster_dps * float(rules.constants["click_roster_multiplier"])
) * efficiency
hp_damage, _, broke = apply_damage(
rules,
target,
raw,
label="click",
timestamp=time,
event_log=event_log,
weak=target["weak_tag"] == "click",
)
click_damage += raw
if broke:
shield_broken += 1
event_log.append(
{
"time": round_metric(time),
"type": "click_enemy",
"target_id": target["content_id"],
"damage": round_metric(hp_damage),
}
)
elif action_type == "offboard_burst" and target:
raw = (
float(rules.constants["burst_base"])
+ roster_dps * float(rules.constants["burst_roster_multiplier"])
) * efficiency
hp_damage, _, broke = apply_damage(
rules,
target,
raw,
label="offboard_burst",
timestamp=time,
event_log=event_log,
weak=target["weak_tag"] in {"aoe", "break"},
)
burst_damage += raw
if broke:
shield_broken += 1
event_log.append(
{
"time": round_metric(time),
"type": "offboard_burst",
"target_id": target["content_id"],
"damage": round_metric(hp_damage),
}
)
elif action_type == "cast_ultimate" and target:
hero_id = str(action.get("hero_id", ""))
hero = rules.heroes.get(hero_id)
if hero:
raw = (
float(hero["base_atk"])
* float(rules.constants["ultimate_atk_multiplier"])
* efficiency
)
hp_damage, _, broke = apply_damage(
rules,
target,
raw,
label=f"ultimate:{hero_id}",
timestamp=time,
event_log=event_log,
weak=target["weak_tag"] == "break"
or target["content_id"] == "B-R1-01",
)
ultimate_casts += 1
if broke:
shield_broken += 1
event_log.append(
{
"time": round_metric(time),
"type": "cast_ultimate",
"hero_id": hero_id,
"target_id": target["content_id"],
"damage": round_metric(hp_damage),
}
)
input_index += 1
# Rebuild timers are deterministic and fire before automatic output.
for enemy in enemies:
if enemy["dead"]:
continue
for rebuild_time in enemy["rebuild_at"][:]:
if abs(float(rebuild_time) - time) <= TIME_EPSILON:
enemy["shield"] += enemy["rebuild_amount"]
enemy["shield_before"] = enemy["shield"]
enemy["shield_broken"] = False
enemy["rebuild_at"].remove(rebuild_time)
event_log.append(
{
"time": round_metric(time),
"type": "shield_rebuild",
"target_id": enemy["content_id"],
"shield": round_metric(enemy["shield"]),
}
)
target = choose_target(enemies)
if target:
# Signature damage is the visible tactical layer and lands before
# the always-on roster output.
raw_signature = signature_dps * rules.tick_seconds * efficiency
weakness = has_weakness(rules, visible_hero_ids, target["weak_tag"])
if weakness:
weakness_hits += 1
hp_damage, _, broke = apply_damage(
rules,
target,
raw_signature,
label="visible_signature",
timestamp=time,
event_log=event_log,
weak=weakness,
)
visible_signature_damage += raw_signature
if broke:
shield_broken += 1
# Roster DPS is always active and is intentionally independent of
# which heroes are in visible slots.
raw_roster = roster_dps * rules.tick_seconds * efficiency
_, _, broke = apply_damage(
rules,
target,
raw_roster,
label="roster_dps",
timestamp=time,
event_log=event_log,
)
if broke:
shield_broken += 1
if all(enemy["dead"] for enemy in enemies):
result = "win"
break
if time >= timeout - TIME_EPSILON:
break
duration = min(time, timeout)
reward_id = rules.reward_ids.get(scenario_id, "REWARD-R1-C01-N01")
if scenario_id == "P3A-N10-MANUAL":
reward_id = (
rules.reward_ids["P3A-N10-MANUAL_WIN"]
if result == "win"
else rules.reward_ids["P3A-N10-MANUAL_LOSS"]
)
event_log.append(
{
"time": round_metric(duration),
"type": "battle_result",
"result": result,
}
)
return {
"seed": seed,
"scenario_id": scenario_id,
"mode": mode,
"result": result,
"duration_seconds": round_metric(duration),
"roster_dps": round_metric(roster_dps),
"visible_signature_damage": round_metric(visible_signature_damage),
"click_damage": round_metric(click_damage),
"burst_damage": round_metric(burst_damage),
"ultimate_casts": ultimate_casts,
"shield_broken": shield_broken,
"weakness_hits": weakness_hits,
"reward_id": reward_id,
"event_log": event_log,
}
def seed_values(pack: Dict[str, Any]) -> Iterable[int]:
seed_range = pack["seed_range"]
start = int(seed_range["start"])
count = int(seed_range["count"])
step = int(seed_range.get("step", 1))
return (start + idx * step for idx in range(count))
def summarize(
scenario: Dict[str, Any], results: List[Dict[str, Any]]
) -> Dict[str, Any]:
wins = sum(result["result"] == "win" for result in results)
durations = [result["duration_seconds"] for result in results]
target_duration = scenario.get("target_duration_seconds", [0.0, float("inf")])
target_win_rate = scenario.get("target_win_rate", [0.0, 1.0])
win_rate = wins / len(results) if results else 0.0
average_duration = sum(durations) / len(durations) if durations else 0.0
return {
"scenario_id": scenario["id"],
"mode": scenario["mode"],
"runs": len(results),
"wins": wins,
"losses": len(results) - wins,
"win_rate": round_metric(win_rate),
"average_duration_seconds": round_metric(average_duration),
"min_duration_seconds": min(durations) if durations else None,
"max_duration_seconds": max(durations) if durations else None,
"target_duration_seconds": target_duration,
"target_win_rate": target_win_rate,
"duration_target_pass": bool(
durations
and min(durations) >= float(target_duration[0])
and max(durations) <= float(target_duration[1])
),
"win_rate_target_pass": bool(
float(target_win_rate[0]) <= win_rate <= float(target_win_rate[1])
),
}
def run(rules: Rules, pack: Dict[str, Any]) -> Dict[str, Any]:
validate_pack(pack, rules)
results: List[Dict[str, Any]] = []
summaries: List[Dict[str, Any]] = []
for scenario in pack["scenarios"]:
timeout = float(scenario.get("timeout_seconds", 60.0))
scenario_results = [
run_scenario(rules, scenario, seed, timeout) for seed in seed_values(pack)
]
results.extend(scenario_results)
summaries.append(summarize(scenario, scenario_results))
return {
"schema": 1,
"source_pack": str(pack.get("source_pack", "data/mvp_validation_seed_pack.json")),
"rules_source": "data/mvp_battle_rules.json",
"tick_seconds": rules.tick_seconds,
"determinism_rule": pack["result_schema"]["determinism_rule"],
"summaries": summaries,
"results": results,
}
def main(argv: List[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--pack", type=Path, default=DEFAULT_PACK_PATH)
parser.add_argument("--rules", type=Path, default=DEFAULT_RULES_PATH)
parser.add_argument("--out", type=Path, default=DEFAULT_OUT_PATH)
parser.add_argument("--check-determinism", action="store_true")
args = parser.parse_args(argv)
rules = Rules(read_json(args.rules))
pack = read_json(args.pack)
output = run(rules, pack)
serialized = json.dumps(
output, ensure_ascii=False, sort_keys=True, separators=(",", ":")
) + "\n"
if args.check_determinism:
second = run(rules, pack)
second_serialized = json.dumps(
second, ensure_ascii=False, sort_keys=True, separators=(",", ":")
) + "\n"
if serialized != second_serialized:
raise RuntimeError("determinism check failed: repeated run differs")
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(serialized, encoding="utf-8")
for summary in output["summaries"]:
print(
f"{summary['scenario_id']}: "
f"win_rate={summary['win_rate']:.3f} "
f"duration={summary['average_duration_seconds']:.3f}s "
f"range={summary['min_duration_seconds']:.3f}-{summary['max_duration_seconds']:.3f}s "
f"duration_pass={summary['duration_target_pass']} "
f"win_rate_pass={summary['win_rate_target_pass']}"
)
print(f"wrote {args.out}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))