TR2X/tools/update_gameflow

77 lines
2.1 KiB
Plaintext
Raw Permalink Normal View History

#!/usr/bin/env python3
import json
import re
2024-09-17 22:23:38 +00:00
from pathlib import Path
2024-09-17 22:23:38 +00:00
from tr2x.paths import LIBTRX_INCLUDE_DIR, TR2X_DATA_DIR, TR2X_SRC_DIR
SHIP_DIR = TR2X_DATA_DIR / "ship"
2024-09-17 22:23:38 +00:00
GAME_STRING_DEF_PATHS = [
TR2X_SRC_DIR / "game/game_string.def",
LIBTRX_INCLUDE_DIR / "game/game_string.def",
]
OBJECT_STRINGS_DEF_PATH = LIBTRX_INCLUDE_DIR / "game/objects/names_tr2.def"
2024-09-17 22:23:38 +00:00
def get_strings_map(paths: list[Path]) -> dict[str, str]:
result: dict[str, str] = {}
2024-09-17 22:23:38 +00:00
for path in paths:
for line in path.read_text().splitlines():
if match := re.match(
r'^\w+DEFINE\((\w+),\s*"([^"]+)"\)$', line.strip()
):
result[match.group(1)] = match.group(2)
return result
2024-09-17 22:23:38 +00:00
def postprocess_gameflow(
gameflow: str,
object_strings_map: dict[str, str],
game_strings_map: dict[str, str],
) -> str:
gameflow = re.sub(
r'^( "object_strings": {)[^}]*(})',
' "object_strings": {\n'
+ "\n".join(
f" {json.dumps(key)}: {json.dumps(value)},"
for key, value in object_strings_map.items()
)
+ "\n }",
gameflow,
flags=re.M | re.DOTALL,
)
gameflow = re.sub(
r'^( "game_strings": {)[^}]*(})',
' "game_strings": {\n'
+ "\n".join(
f" {json.dumps(key)}: {json.dumps(value)},"
2024-09-17 22:23:38 +00:00
for key, value in sorted(
game_strings_map.items(), key=lambda kv: kv[0]
)
)
+ "\n }",
gameflow,
flags=re.M | re.DOTALL,
)
return gameflow
def main() -> None:
2024-09-17 22:23:38 +00:00
object_strings_map = get_strings_map([OBJECT_STRINGS_DEF_PATH])
game_strings_map = get_strings_map(GAME_STRING_DEF_PATHS)
assert object_strings_map
assert game_strings_map
for gameflow_path in SHIP_DIR.rglob("*gameflow*.json*"):
old_gameflow = gameflow_path.read_text()
2024-09-17 22:23:38 +00:00
new_gameflow = postprocess_gameflow(
old_gameflow, object_strings_map, game_strings_map
)
if new_gameflow != old_gameflow:
gameflow_path.write_text(new_gameflow)
if __name__ == "__main__":
main()