Files
windroost/tools/mvp_ui_text_validator.py
T
wushenghua e7b55e1c17 feat: align runtime with paper numbers and build the battle HUD carrier
Numbers. The paper runner (tools/mvp_validation_sim.py) and the Godot
runtime adapter were two independent rewrites of the same rules and had
drifted: seed derivation, damage order, the weakness rule and the shield
rebuild semantics all differed, so the runtime never actually reproduced
the paper numbers and P2-BAT-01 could never pass.

- add data/mvp_battle_rules.json as the single source of balance data and
  of the per-run seed derivation, read by both engines
- derive the efficiency factor from SHA-256 (48-bit prefix) so Python and
  GDScript land on the same float64
- port the paper semantics into battle_sim.gd and expose the simulation as
  a stepwise state machine so a live scene can drive it at 1x/2x/3x
- add tools/mvp_parity_gate.py: diffs 300 results field by field, event
  log by event log, and exits non-zero on any difference
- freeze data/mvp_validation_seed_reference.json so unapproved numeric
  drift fails the gate
- note that GDScript's roundf() is half-away-from-zero while Python's
  round() is banker's rounding; the runtime uses String.num instead

UI. The sample had no real UI carrier, no localization and no touch path,
so the NinePatch, dynamic text, safe area and input cases had nothing to
be proven against.

- add the battle HUD, laid out from the contract table rather than container
  stretch ratios, reproducing the 390x844 rectangles exactly and adapting
  360x800 / 430x932 with the stage kept as priority space
- add runtime text tables for zh_CN and en_US and a key validator that
  proves both locales carry the same keys and every content id has a string
- add NinePatch frames with a 6px border band and 6px cut corners
- add the live battle scene, the capture runner and the 1x/2x/3x
  equivalence test

tools/run_p2_checks.sh runs the nine gates in one command; all pass.
2026-11-16 22:22:55 +08:00

189 lines
6.7 KiB
Python
Executable File

#!/usr/bin/env python3
"""Validate the runtime UI string tables.
Checks:
* every supported locale file exists and parses;
* zh_CN and en_US expose exactly the same key set;
* no value is empty;
* every key referenced from the GDScript sources exists in the active
locales, so a renamed or missing key cannot reach a build.
Usage:
python3 tools/mvp_ui_text_validator.py
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Dict, List, Set, Tuple
ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
SCRIPT_DIR = ROOT / "p2_godot_sample/scripts"
SUPPORTED_LOCALES = ["zh_CN", "en_US", "es", "pt-BR", "ja", "fr", "de"]
SHIP_LOCALES = ["zh_CN", "en_US"]
# UiText.t("key"), UiText.tf("key", ...), UiText.t_any(["key", ...], ...)
DIRECT_PATTERN = re.compile(r'UiText\.(?:t|tf)\(\s*"([^"]+)"')
ANY_PATTERN = re.compile(r'UiText\.t_any\(\s*\[([^\]]*)\]')
STRING_ITEM_PATTERN = re.compile(r'"([^"]+)"')
def load_locale(locale: str) -> Tuple[Dict[str, str], List[str]]:
path = DATA_DIR / f"ui_text.{locale}.json"
if not path.exists():
return {}, [f"missing locale file {path.name}"]
with path.open("r", encoding="utf-8") as handle:
payload = json.load(handle)
errors: List[str] = []
if payload.get("schema") != 1:
errors.append(f"{path.name}: unsupported schema {payload.get('schema')}")
if payload.get("locale") != locale:
errors.append(f"{path.name}: declares locale {payload.get('locale')!r}")
strings = payload.get("strings", {})
if not isinstance(strings, dict):
return {}, errors + [f"{path.name}: strings is not an object"]
for key, value in strings.items():
if not isinstance(value, str) or not value.strip():
errors.append(f"{path.name}: key {key!r} has an empty value")
return strings, errors
def collect_source_keys() -> Set[str]:
keys: Set[str] = set()
if not SCRIPT_DIR.exists():
return keys
for path in sorted(SCRIPT_DIR.glob("*.gd")):
text = path.read_text(encoding="utf-8")
for match in DIRECT_PATTERN.finditer(text):
keys.add(match.group(1))
for match in ANY_PATTERN.finditer(text):
for item in STRING_ITEM_PATTERN.finditer(match.group(1)):
keys.add(item.group(1))
return keys
def collect_expected_content_keys() -> Set[str]:
"""Every content key the game can actually ask for.
Format templates such as `content.hero.%s` cannot be checked literally, so
the concrete id set is derived from the shared rule table, the content
fixture and the seed pack instead.
"""
keys: Set[str] = set()
rules_path = DATA_DIR / "mvp_battle_rules.json"
if rules_path.exists():
rules = json.loads(rules_path.read_text(encoding="utf-8"))
for hero_id in rules.get("heroes", {}):
keys.add(f"content.hero.{hero_id}")
keys.add(f"content.hero.{hero_id}.short")
for enemy_id, spec in rules.get("enemies", {}).items():
if str(spec.get("kind", "")) == "boss":
keys.add(f"content.boss.{enemy_id}")
else:
keys.add(f"content.enemy.{enemy_id}")
for reward_id in rules.get("reward_ids", {}).values():
keys.add(f"reward.{reward_id}")
for region_id in rules.get("regions", []):
keys.add(f"content.region.{region_id}")
fixture_path = DATA_DIR / "mvp_content_fixture.json"
if fixture_path.exists():
fixture = json.loads(fixture_path.read_text(encoding="utf-8"))
for node in fixture.get("nodes", []):
keys.add(f"content.node.{node.get('id', '')}")
pack_path = DATA_DIR / "mvp_validation_seed_pack.json"
if pack_path.exists():
pack = json.loads(pack_path.read_text(encoding="utf-8"))
for scenario in pack.get("scenarios", []):
keys.add(f"content.node.{scenario.get('node_id', '')}")
for page in ("expedition", "company", "skyport", "archive"):
keys.add(f"hud.nav.{page}")
return keys
def main(argv: List[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--write-results", type=Path, default=DATA_DIR / "mvp_ui_text_validation_results.json")
args = parser.parse_args(argv)
failures: List[str] = []
tables: Dict[str, Dict[str, str]] = {}
for locale in SUPPORTED_LOCALES:
strings, errors = load_locale(locale)
tables[locale] = strings
for error in errors:
if locale in SHIP_LOCALES:
failures.append(error)
else:
print(f"UI_TEXT_NOTE {error}")
reference = tables.get("zh_CN", {})
for locale in SHIP_LOCALES:
if locale == "zh_CN":
continue
other = tables.get(locale, {})
missing = sorted(set(reference) - set(other))
extra = sorted(set(other) - set(reference))
for key in missing:
failures.append(f"{locale} is missing key {key!r}")
for key in extra:
failures.append(f"{locale} has an unknown key {key!r}")
source_keys = collect_source_keys()
literal_source_keys = {key for key in source_keys if "%" not in key}
for key in sorted(literal_source_keys):
for locale in SHIP_LOCALES:
if key not in tables.get(locale, {}):
failures.append(f"source references {key!r} which is absent from {locale}")
expected_content_keys = collect_expected_content_keys()
for key in sorted(expected_content_keys):
for locale in SHIP_LOCALES:
if key not in tables.get(locale, {}):
failures.append(f"content id {key!r} has no {locale} string")
unused = sorted(set(reference) - literal_source_keys - expected_content_keys)
report = {
"schema": 1,
"ship_locales": SHIP_LOCALES,
"supported_locales": SUPPORTED_LOCALES,
"key_count": len(reference),
"source_key_count": len(source_keys),
"unused_keys": unused,
"overall": "PASS" if not failures else "FAIL",
"failures": failures,
}
args.write_results.parent.mkdir(parents=True, exist_ok=True)
args.write_results.write_text(
json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
print(f"ui_text: {len(reference)} keys across {len(SHIP_LOCALES)} ship locales")
print(f"source references {len(source_keys)} distinct keys")
if unused:
print(f"note: {len(unused)} keys are not referenced from scripts yet")
if failures:
print("UI_TEXT_FAIL")
for failure in failures:
print(f" - {failure}")
return 1
print("UI_TEXT_PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))