Files
windroost/tools/mvp_ui_text_validator.py
T
wushenghua 5fe1ff57b7 fix: correct first-run onboarding and printf placeholders in UI strings
Running the game window on a clean profile exposed two player-visible defects
that headless assertions never caught.

A brand-new player was told "offline report settled · progress saved" before
they had ever left the game. ProfileStore now tracks seen_intro (schema 4,
migrated from older saves as already-seen), first runs show a welcome banner,
and starting the first node marks the intro seen and persists it.

Upgrade buttons at 0 gold were disabled but looked identical to enabled ones,
and their text showed the literal "需 %d ◆": the string used printf % while
UiText.tf only substitutes {name}. Fixed all such strings (offline reward,
victory, rebuild, archive, growth) to use named placeholders, and added a
validator guard that fails any key passed to UiText.tf whose text still has a
printf % placeholder. Disabled upgrades now read "需 120 ◆" and render dimmed.

Added a first-run evidence test over a real rendered GameRoot. It verifies the
welcome banner, unaffordable button state, and that intro-seen persists.
tools/run_p2_checks.sh now runs 17 gates; all pass. Verified again in a live
Godot window with a clean profile and terminated the process after inspection.
2026-11-17 10:55:27 +08:00

208 lines
7.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*"([^"]+)"')
TF_PATTERN = re.compile(r'UiText\.tf\(\s*"([^"]+)"')
ANY_PATTERN = re.compile(r'UiText\.t_any\(\s*\[([^\]]*)\]')
STRING_ITEM_PATTERN = re.compile(r'"([^"]+)"')
# Placeholder contract: UiText.tf only substitutes {name}; a stray printf-style
# %d/%s in a tf string renders literally (a real bug caught in the live window).
PERCENT_FORMAT_PATTERN = re.compile(r'%[-+ #0-9.*]*[dfsxXeEgu]')
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}")
# Any key passed to UiText.tf must use {name} placeholders, never printf %.
tf_keys: Set[str] = set()
if SCRIPT_DIR.exists():
for path in sorted(SCRIPT_DIR.glob("*.gd")):
text = path.read_text(encoding="utf-8")
for match in TF_PATTERN.finditer(text):
tf_keys.add(match.group(1))
for key in sorted(tf_keys):
for locale in SHIP_LOCALES:
value = str(tables.get(locale, {}).get(key, ""))
if PERCENT_FORMAT_PATTERN.search(value):
failures.append(
f"{key} is used with UiText.tf but its {locale} text has a printf % placeholder: {value!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:]))