From 58360c1fa7a166058c02147eede91795d64d8136 Mon Sep 17 00:00:00 2001 From: markmental Date: Mon, 2 Nov 2026 15:28:46 -0500 Subject: [PATCH] Add a game-agnostic BYOG/edit mode --- .gitignore | 1 + README.md | 32 ++ smackdown_card_maker.py | 944 +++++++++++++++++++++++++++++++---- test_smackdown_card_maker.py | 337 ++++++++++++- 4 files changed, 1213 insertions(+), 101 deletions(-) diff --git a/.gitignore b/.gitignore index 6d6e8d1..1f3e29b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ cards/ seasons/ +edit/ diff --git a/README.md b/README.md index cb7e6f9..8dc013f 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,38 @@ retrieval, Tables require a table break, Battle Royals require a last-survivor win, and Cage matches require escape. Other listed match types use pinfall or submission. Ranking-based non-title matches are not labeled as contender matches. +### BYOG — Bring Your Own Game + +**BYOG / Manage Games** on the main menu lets you run cards and seasons for any +federation, not just the built-in WWF games: + +- **Create a new game and federation** — name the game, pick the federation and + platform (PlayStation 1, PlayStation 2, or other), name the federation's + three shows, list the roster, edit the suggested match types, and add any + championship/ranking divisions (singles, tag team, or women's). A women's + division asks which roster members are eligible. +- **Copy a built-in WWF game to edit** — clones any built-in game into your own + editable profile; the built-in games themselves stay unchanged. +- **Edit a custom game** — reopen any saved profile. + +Show names are WWE branding, so custom federations name their own three shows +during creation (or later via **Show names** in the BYOG editor). The three +slots match the season cycle — the first weekly show, the second weekly show, +and the big event — and default to neutral placeholders ("Weekly Show #1", +"Weekly Show #2", "Big Pay-Per-View") when left untouched. Booked season cards +and random one-off shows use those names, and an event card titled with the +third slot's name counts as a PPV for title weighting and the event rating. + +Profiles are stored under `edit/games/.json` and are validated on +save/launch; invalid files are skipped with a console message so one typo cannot +break the menu. Every custom game is listed alongside the built-ins whenever a +card or season asks for a game, including its federation name. Custom games on +the PlayStation 1 platform get the DuckStation screenshot prompts. Saved cards +and seasons record the game identity and title divisions they were created with, +so old saves keep working (and keep their own divisions) after you edit a +profile. Bases for custom match types default sensibly; enter an explicit base +rating per match type when you want a different number. + When recording a match result, enter its duration in minutes, near-fall count, and finishers executed. Match ratings use fixed match-type bases, +0.1 points per full minute (up to +5), +0.2 per near fall, and +0.5 per finisher. The diff --git a/smackdown_card_maker.py b/smackdown_card_maker.py index 706034e..4eb4873 100644 --- a/smackdown_card_maker.py +++ b/smackdown_card_maker.py @@ -22,10 +22,20 @@ from typing import Any ROOT = Path(__file__).resolve().parent CARD_DIR = ROOT / "cards" SEASON_DIR = ROOT / "seasons" +EDIT_DIR = ROOT / "edit" +CUSTOM_GAME_DIR = EDIT_DIR / "games" DUCKSTATION_SCREENSHOT_DIR = Path.home() / ".local/share/duckstation/screenshots" SESSION_START = datetime.now().astimezone() PS1_GAMES = {"sd1", "sd2"} SEASON_CYCLE = ("Raw", "SmackDown", "PPV") +SHOW_BRANDS = SEASON_CYCLE +# Neutral show-name placeholders for BYOG federations; WWE show names stay +# exclusive to the built-in games. +DEFAULT_CUSTOM_SHOWS = { + "Raw": "Weekly Show #1", + "SmackDown": "Weekly Show #2", + "PPV": "Big Pay-Per-View", +} CHAMPIONSHIPS = ( "Tag Team", "World Wrestling Federation", @@ -124,6 +134,8 @@ MATCH_TYPES: dict[str, list[tuple[str, tuple[int, ...]]]] = { ("Hell in a Cell", (1, 1)), ], } +BUILTIN_GAME_IDS = frozenset(GAMES) +CUSTOM_GAME_CONFIGS: dict[str, dict[str, Any]] = {} # Typical live-event attendance per city; randomization picks a city then an # attendance within its venue range. Unknown cities use the default range. @@ -217,6 +229,8 @@ def ask_choice( def load_roster(game_id: str) -> list[str]: """Load and validate a game's roster from the shared JSON schema.""" + if game_id in CUSTOM_GAME_CONFIGS: + return list(CUSTOM_GAME_CONFIGS[game_id]["roster"]) path = ROOT / GAMES[game_id]["roster"] if not path.is_file(): raise FileNotFoundError(f"Roster file not found: {path}") @@ -241,6 +255,608 @@ def slugify(value: str) -> str: return slug or "smackdown-show" +def game_title(game_id: str) -> str: + return GAMES[game_id]["title"] + + +def federation_name(game_id: str) -> str: + if game_id in CUSTOM_GAME_CONFIGS: + return CUSTOM_GAME_CONFIGS[game_id]["federation_name"] + return "World Wrestling Federation" + + +def game_display_name(game_id: str) -> str: + if game_id in CUSTOM_GAME_CONFIGS: + config = CUSTOM_GAME_CONFIGS[game_id] + return f"{config['federation_name']} — {config['game_title']}" + return GAMES[game_id]["title"] + + +def title_definitions_for_game(game_id: str, + profile: dict[str, Any] | None = None) -> list[dict[str, str]]: + if profile and isinstance(profile.get("championships"), list): + return [dict(title) for title in profile["championships"]] + if game_id in CUSTOM_GAME_CONFIGS: + return [dict(title) for title in CUSTOM_GAME_CONFIGS[game_id]["championships"]] + return [ + {"name": name, "kind": "tag" if name == "Tag Team" else "women" if name == "Women's" else "singles"} + for name in CHAMPIONSHIPS + ] + + +def championship_names_for_game(game_id: str, + profile: dict[str, Any] | None = None) -> list[str]: + return [title["name"] for title in title_definitions_for_game(game_id, profile)] + + +def championship_kind(game_id: str, title_name: str, + profile: dict[str, Any] | None = None) -> str: + for title in title_definitions_for_game(game_id, profile): + if title["name"] == title_name: + return title.get("kind", "singles") + return "singles" + + +def shows_snapshot(config: dict[str, Any] | None) -> dict[str, str]: + """Resolved show names recorded with a season at creation time.""" + shows = (config or {}).get("shows") + return {brand: show_name_for_brand( + brand, shows if isinstance(shows, dict) else None) for brand in SHOW_BRANDS} + + +def season_title_names(season: dict[str, Any]) -> list[str]: + definitions = season.get("title_definitions") + if isinstance(definitions, list): + return [item["name"] for item in definitions] + return list(season.get("champions", {})) or championship_names_for_game(season["game_id"]) + + +def season_championship_kind(season: dict[str, Any], title_name: str) -> str: + for definition in season.get("title_definitions", []): + if definition.get("name") == title_name: + return definition.get("kind", "singles") + return championship_kind(season["game_id"], title_name) + + +def game_profile(game_id: str) -> dict[str, Any]: + if game_id in CUSTOM_GAME_CONFIGS: + return json.loads(json.dumps(CUSTOM_GAME_CONFIGS[game_id])) + return builtin_game_profile(game_id) + + +def season_game_profile(season: dict[str, Any]) -> dict[str, Any]: + profile = season.get("game_config") + return profile if isinstance(profile, dict) else game_profile(season["game_id"]) + + +def match_type_definitions(game_id: str, profile: dict[str, Any] | None = None) -> list[dict[str, Any]]: + if profile and isinstance(profile.get("match_types"), list): + return [dict(item) for item in profile["match_types"]] + if game_id in CUSTOM_GAME_CONFIGS: + return [dict(item) for item in CUSTOM_GAME_CONFIGS[game_id]["match_types"]] + return [ + { + "name": name, + "sides": list(sides), + "base_rating": MATCH_BASE_RATINGS.get(name, 4.5), + "outcomes": list(MATCH_OUTCOME_OPTIONS.get(name, STANDARD_MATCH_OUTCOMES)), + } + for name, sides in MATCH_TYPES[game_id] + ] + + +def match_type_definition(game_id: str, match_type: str, + profile: dict[str, Any] | None = None) -> dict[str, Any]: + for definition in match_type_definitions(game_id, profile): + if definition["name"] == match_type: + return definition + return {"name": match_type, "sides": [1, 1], + "base_rating": MATCH_BASE_RATINGS.get(match_type, 4.5), + "outcomes": list(MATCH_OUTCOME_OPTIONS.get(match_type, STANDARD_MATCH_OUTCOMES))} + + +def refresh_custom_games(directory: Path | None = None) -> list[str]: + """Load user-managed game definitions without changing built-in profiles.""" + global CUSTOM_GAME_CONFIGS + for game_id in list(CUSTOM_GAME_CONFIGS): + GAMES.pop(game_id, None) + MATCH_TYPES.pop(game_id, None) + CUSTOM_GAME_CONFIGS = {} + directory = directory or CUSTOM_GAME_DIR + if not directory.is_dir(): + return [] + loaded: list[str] = [] + for path in sorted(directory.glob("*.json")): + try: + raw = json.loads(path.read_text(encoding="utf-8")) + config = validate_custom_game(raw) + game_id = config["game_id"] + if game_id in BUILTIN_GAME_IDS or game_id in CUSTOM_GAME_CONFIGS: + raise ValueError(f"Game ID is already in use: {game_id}") + CUSTOM_GAME_CONFIGS[game_id] = config + GAMES[game_id] = { + "title": config["game_title"], + "roster": str(path), + "federation": config["federation_name"], + "platform": config["platform"], + } + MATCH_TYPES[game_id] = [ + (entry["name"], tuple(entry["sides"])) for entry in config["match_types"] + ] + loaded.append(game_id) + except (OSError, ValueError, TypeError, json.JSONDecodeError) as exc: + print(f"Skipping custom game {path.name}: {exc}") + return loaded + + +def validate_custom_game(data: Any) -> dict[str, Any]: + if not isinstance(data, dict): + raise ValueError("Game definition must be a JSON object.") + game_id = data.get("game_id") + if not isinstance(game_id, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]*", game_id): + raise ValueError("game_id must use lowercase letters, digits, and hyphens.") + if game_id in BUILTIN_GAME_IDS: + raise ValueError("Custom definitions cannot overwrite built-in games.") + game_title_value = data.get("game_title") + federation = data.get("federation_name") + if not isinstance(game_title_value, str) or not game_title_value.strip(): + raise ValueError("game_title is required.") + if not isinstance(federation, str) or not federation.strip(): + raise ValueError("federation_name is required.") + roster = data.get("roster") + if (not isinstance(roster, list) or len(roster) < 2 + or any(not isinstance(name, str) or not name.strip() for name in roster)): + raise ValueError("roster must contain at least two non-empty wrestler names.") + if len({name.casefold() for name in roster}) != len(roster): + raise ValueError("roster names must be unique, ignoring capitalization.") + platform = str(data.get("platform", "other")).casefold() + if platform not in {"ps1", "ps2", "other"}: + raise ValueError("platform must be ps1, ps2, or other.") + raw_match_types = data.get("match_types") + if not isinstance(raw_match_types, list) or not raw_match_types: + raise ValueError("match_types must contain at least one match type.") + match_types: list[dict[str, Any]] = [] + seen_match_types: set[str] = set() + for item in raw_match_types: + if not isinstance(item, dict): + raise ValueError("Each match type must be a JSON object.") + name = item.get("name") + sides = item.get("sides") + if not isinstance(name, str) or not name.strip() or name.casefold() in seen_match_types: + raise ValueError("Match type names must be non-empty and unique.") + if (not isinstance(sides, list) or len(sides) < 2 + or any(not isinstance(count, int) or isinstance(count, bool) or count < 1 + for count in sides) + or sum(sides) > len(roster)): + raise ValueError(f"Match type '{name}' has invalid side sizes.") + outcomes = item.get("outcomes", list(MATCH_OUTCOME_OPTIONS.get(name, STANDARD_MATCH_OUTCOMES))) + if not isinstance(outcomes, list) or not outcomes or any( + not isinstance(outcome, str) or not outcome.strip() for outcome in outcomes + ): + raise ValueError(f"Match type '{name}' must have at least one valid outcome.") + base_rating = item.get("base_rating", MATCH_BASE_RATINGS.get(name, 4.5)) + if (not isinstance(base_rating, (int, float)) or isinstance(base_rating, bool) + or not math.isfinite(base_rating) or not 0 <= base_rating <= 100): + raise ValueError(f"Match type '{name}' has an invalid base_rating.") + match_types.append({"name": name.strip(), "sides": list(sides), + "outcomes": [outcome.strip() for outcome in outcomes], + "base_rating": float(base_rating)}) + seen_match_types.add(name.casefold()) + raw_titles = data.get("championships", []) + if not isinstance(raw_titles, list): + raise ValueError("championships must be a list.") + championships: list[dict[str, str]] = [] + seen_titles: set[str] = set() + for item in raw_titles: + if not isinstance(item, dict): + raise ValueError("Each championship must be a JSON object with name and kind.") + name, kind = item.get("name"), str(item.get("kind", "singles")).casefold() + if not isinstance(name, str) or not name.strip() or name.casefold() in seen_titles: + raise ValueError("Championship names must be non-empty and unique.") + if kind not in {"singles", "tag", "women"}: + raise ValueError(f"Championship '{name}' kind must be singles, tag, or women.") + championships.append({"name": name.strip(), "kind": kind}) + seen_titles.add(name.casefold()) + women = data.get("women_roster", []) + if not isinstance(women, list) or any(name not in roster for name in women): + raise ValueError("women_roster must be a subset of the roster.") + raw_shows = data.get("shows") + if raw_shows is not None and not isinstance(raw_shows, dict): + raise ValueError("shows must be an object with Raw, SmackDown, and PPV names.") + shows: dict[str, str] = {} + seen_show_names: set[str] = set() + for brand in SHOW_BRANDS: + name = (raw_shows or {}).get(brand, DEFAULT_CUSTOM_SHOWS[brand]) + if not isinstance(name, str) or not name.strip(): + raise ValueError(f"Show name for '{brand}' must be a non-empty string.") + name = name.strip() + if name.casefold() in seen_show_names: + raise ValueError("Show names must be unique, ignoring capitalization.") + seen_show_names.add(name.casefold()) + shows[brand] = name + return { + "schema_version": 1, + "game_id": game_id, + "game_title": game_title_value.strip(), + "federation_name": federation.strip(), + "platform": platform, + "roster": list(roster), + "match_types": match_types, + "championships": championships, + "women_roster": list(dict.fromkeys(women)), + "shows": shows, + } + + +def save_custom_game(data: dict[str, Any], directory: Path | None = None) -> dict[str, Any]: + config = validate_custom_game(data) + directory = directory or CUSTOM_GAME_DIR + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"{config['game_id']}.json" + temporary = path.with_suffix(".json.tmp") + temporary.write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8") + os.replace(temporary, path) + if directory.resolve() == CUSTOM_GAME_DIR.resolve(): + refresh_custom_games(directory) + return config + + +def builtin_game_profile(game_id: str) -> dict[str, Any]: + return { + "game_id": game_id, + "game_title": game_title(game_id), + "federation_name": federation_name(game_id), + "platform": "ps1" if game_id in PS1_GAMES else "ps2", + "roster": load_roster(game_id), + "match_types": match_type_definitions(game_id), + "championships": title_definitions_for_game(game_id), + "women_roster": sorted(WOMEN_ROSTERS.get(game_id, set())), + "shows": {"Raw": "Monday Night Raw", "SmackDown": "Thursday Night SmackDown!", + "PPV": "WWF PPV"}, + } + + +def new_custom_game_id(federation: str, game_title_value: str) -> str: + base = f"custom-{slugify(federation + '-' + game_title_value)}" + candidate = base + suffix = 2 + while candidate in GAMES or (CUSTOM_GAME_DIR / f"{candidate}.json").exists(): + candidate = f"{base}-{suffix}" + suffix += 1 + return candidate + + +def parse_side_sizes(raw: str) -> list[int] | None: + try: + sizes = [int(part.strip()) for part in raw.split(",")] + except ValueError: + return None + if len(sizes) < 2 or any(size < 1 for size in sizes): + return None + return sizes + + +def default_custom_match_types(roster_size: int) -> list[dict[str, Any]]: + defaults = [ + ("Singles", [1, 1]), + ("Tag Team", [2, 2]), + ("Triple Threat", [1, 1, 1]), + ("Fatal 4-Way", [1, 1, 1, 1]), + ("Hardcore", [1, 1]), + ("Ladder", [1, 1]), + ("Cage", [1, 1]), + ] + return [ + {"name": name, "sides": sides, + "base_rating": MATCH_BASE_RATINGS.get(name, 4.5), + "outcomes": list(MATCH_OUTCOME_OPTIONS.get(name, STANDARD_MATCH_OUTCOMES))} + for name, sides in defaults if sum(sides) <= roster_size + ] + + +def edit_custom_roster(config: dict[str, Any]) -> None: + while True: + choices = ["Add wrestler", "Remove wrestler", "Done"] + labels = ["Add a wrestler", "Remove a wrestler", f"Done ({len(config['roster'])} listed)"] + action = ask_choice("Edit roster", choices, labels=labels) + if action == 2: + break + if action == 0: + name = ask("Wrestler name").strip() + if not name: + print("Wrestler name cannot be blank.") + elif any(existing.casefold() == name.casefold() for existing in config["roster"]): + print("That wrestler is already in this roster.") + else: + config["roster"].append(name) + elif not config["roster"]: + print("The roster is empty.") + else: + index = ask_choice("Remove wrestler", config["roster"]) + removed = config["roster"].pop(index) + config["women_roster"] = [name for name in config["women_roster"] + if name.casefold() != removed.casefold()] + + +def edit_custom_match_types(config: dict[str, Any]) -> None: + while True: + existing = config["match_types"] + choices = list(range(len(existing))) + ["add", "remove", "done"] + labels = [f"{item['name']} ({' vs '.join(map(str, item['sides']))}, " + f"base {item['base_rating']:.1f}%)" for item in existing] + labels.extend(["Add a match type", "Remove a match type", "Done"]) + action = ask_choice("Edit match types", choices, labels=labels) + if action == len(existing) + 2: + return + if action == len(existing) + 1: + if not existing: + print("Add at least one match type before removing one.") + continue + remove_index = ask_choice("Remove which match type", list(range(len(existing))), + labels=[item["name"] for item in existing]) + existing.pop(remove_index) + continue + if action == len(existing): + name = ask("New match type name").strip() + if not name: + print("Match type name cannot be blank.") + continue + if any(item["name"].casefold() == name.casefold() for item in existing): + print("That match type already exists.") + continue + side_sizes = parse_side_sizes(ask("Wrestler counts per side, comma-separated (e.g. 1,1)")) + if side_sizes is None: + print("Enter at least two positive side sizes, such as 1,1 or 2,2.") + continue + if sum(side_sizes) > len(config["roster"]): + print("This match type needs more wrestlers than the roster contains.") + continue + base_default = MATCH_BASE_RATINGS.get(name, 4.5) + while True: + try: + base_rating = float(ask("Base rating percentage", str(base_default))) + if math.isfinite(base_rating) and 0 <= base_rating <= 100: + break + except ValueError: + pass + print("Enter a rating from 0 to 100.") + default_outcomes = MATCH_OUTCOME_OPTIONS.get(name, STANDARD_MATCH_OUTCOMES) + raw_outcomes = ask("Legal outcomes, comma-separated", ", ".join(default_outcomes)) + outcomes = [outcome.strip() for outcome in raw_outcomes.split(",") if outcome.strip()] + if not outcomes: + print("At least one legal outcome is required.") + continue + existing.append({"name": name, "sides": side_sizes, + "base_rating": base_rating, "outcomes": outcomes}) + + +def edit_custom_titles(config: dict[str, Any]) -> None: + while True: + existing = config["championships"] + choices = list(range(len(existing))) + ["add", "remove", "done"] + labels = [f"{item['name']} ({item['kind']})" for item in existing] + labels.extend(["Add a championship", "Remove a championship", "Done"]) + action = ask_choice("Edit championship rankings", choices, labels=labels) + if action == len(existing) + 2: + return + if action == len(existing) + 1: + if not existing: + print("There are no championships to remove.") + continue + remove_index = ask_choice("Remove which championship", list(range(len(existing))), + labels=[item["name"] for item in existing]) + existing.pop(remove_index) + continue + if action == len(existing): + name = ask("Championship name").strip() + if not name or any(item["name"].casefold() == name.casefold() for item in existing): + print("Enter a non-empty championship name not already listed.") + continue + kind_options = ["singles", "tag", "women"] + kind_labels = ["Singles / open", "Tag team", "Women's division"] + kind = kind_options[ask_choice("Championship type", kind_options, labels=kind_labels)] + existing.append({"name": name, "kind": kind}) + + +def edit_women_roster(config: dict[str, Any]) -> None: + while True: + choices = ["add", "remove", "done"] + labels = ["Add eligible wrestler", "Remove eligible wrestler", "Done"] + action = ask_choice("Women's division eligibility", choices, labels=labels) + eligible = config["women_roster"] + if action == 2: + return + if action == 0: + available = [name for name in config["roster"] + if name.casefold() not in {item.casefold() for item in eligible}] + if not available: + print("Every roster member is already listed.") + continue + selected = choose_roster_member(available, "Add which wrestler") + eligible.append(selected) + elif not eligible: + print("No eligible wrestlers are listed.") + else: + remove_index = ask_choice("Remove eligible wrestler", eligible) + eligible.pop(remove_index) + + +def edit_custom_shows(config: dict[str, Any]) -> None: + while True: + shows = config["shows"] + labels = [f"{brand}: {shows[brand]}" for brand in SHOW_BRANDS] + ["Done"] + action = ask_choice("Edit show names", list(SHOW_BRANDS) + ["done"], labels=labels) + if action == len(SHOW_BRANDS): + return + brand = SHOW_BRANDS[action] + while True: + name = ask(f"{brand} show name", shows[brand]).strip() + if not name: + print("Show name cannot be blank.") + continue + others = [shows[other] for other in SHOW_BRANDS if other != brand] + if any(other.casefold() == name.casefold() for other in others): + print("Show names must be distinct from each other.") + continue + shows[brand] = name + break + + +def edit_custom_profile(config: dict[str, Any]) -> dict[str, Any]: + while True: + options = ["identity", "shows", "roster", "match_types", "titles", "women", "save"] + labels = ["Game title and federation", + f"Show names (Raw: {config['shows']['Raw']})", + f"Edit roster ({len(config['roster'])} wrestlers)", + f"Edit match types ({len(config['match_types'])})", + f"Edit championships ({len(config['championships'])})", + f"Edit Women's eligibility ({len(config['women_roster'])})", "Validate and save"] + action = ask_choice("BYOG editor", options, labels=labels) + if action == 0: + config["game_title"] = ask("Game title", config["game_title"]).strip() + config["federation_name"] = ask("Federation name", config["federation_name"]).strip() + platform_options = ["ps1", "ps2", "other"] + platform_labels = ["PlayStation 1", "PlayStation 2", "Other / platform agnostic"] + config["platform"] = platform_options[ + ask_choice("Platform", platform_options, labels=platform_labels) + ] + elif action == 1: + edit_custom_shows(config) + elif action == 2: + edit_custom_roster(config) + elif action == 3: + edit_custom_match_types(config) + elif action == 4: + edit_custom_titles(config) + elif action == 5: + edit_women_roster(config) + else: + try: + return save_custom_game(config) + except ValueError as exc: + print(f"Cannot save game profile: {exc}") + + +def builtin_profile_for_copy(game_id: str, custom_id: str) -> dict[str, Any]: + definitions = [ + {"name": name, "sides": list(sides), + "base_rating": MATCH_BASE_RATINGS.get(name, 4.5), + "outcomes": list(MATCH_OUTCOME_OPTIONS.get(name, STANDARD_MATCH_OUTCOMES))} + for name, sides in MATCH_TYPES[game_id] + ] + return validate_custom_game({ + "schema_version": 1, + "game_id": custom_id, + "game_title": game_title(game_id) + " Custom Edition", + "federation_name": federation_name(game_id), + "platform": "ps1" if game_id in PS1_GAMES else "ps2", + "roster": load_roster(game_id), + "match_types": definitions, + "championships": title_definitions_for_game(game_id), + "women_roster": sorted(WOMEN_ROSTERS.get(game_id, set())), + "shows": {"Raw": "Monday Night Raw", "SmackDown": "Thursday Night SmackDown!", + "PPV": "WWF PPV"}, + }) + + +def create_custom_game() -> dict[str, Any]: + title = ask("Game title").strip() + while not title: + title = ask("Game title cannot be blank; enter a game title").strip() + federation = ask("Federation name", "My Wrestling Federation").strip() + if not federation: + federation = "My Wrestling Federation" + platform_options = ["ps1", "ps2", "other"] + platform_labels = ["PlayStation 1", "PlayStation 2", "Other / platform agnostic"] + platform = platform_options[ask_choice("Platform", platform_options, labels=platform_labels)] + shows: dict[str, str] = {} + print("\nName this federation's three shows (weekly #1, weekly #2, and the big event).") + for brand in SHOW_BRANDS: + default = DEFAULT_CUSTOM_SHOWS[brand] + while True: + name = ask(f"{brand} show name", default).strip() or default + if any(other.casefold() == name.casefold() for other in shows.values()): + print("Show names must be distinct from each other.") + continue + shows[brand] = name + break + config: dict[str, Any] = { + "schema_version": 1, + "game_id": new_custom_game_id(federation, title), + "game_title": title, + "federation_name": federation, + "platform": platform, + "roster": [], + "match_types": [], + "championships": [], + "women_roster": [], + "shows": shows, + } + edit_custom_roster(config) + config["match_types"] = default_custom_match_types(len(config["roster"])) + if not config["match_types"]: + config["match_types"] = [{"name": "Singles", "sides": [1, 1], + "base_rating": 4.5, + "outcomes": list(STANDARD_MATCH_OUTCOMES)}] + print("\nAdd this federation's championship divisions (or finish with none).") + edit_custom_titles(config) + if any(title["kind"] == "women" for title in config["championships"]): + edit_women_roster(config) + return edit_custom_profile(config) + + +def choose_builtin_game() -> str: + ids = list(BUILTIN_GAME_IDS) + return ids[ask_choice("Built-in game to copy", ids, + labels=[GAMES[game_id]["title"] for game_id in ids])] + + +def clone_builtin_game() -> dict[str, Any]: + refresh_custom_games() + source_id = choose_builtin_game() + title = ask("Custom game title", game_title(source_id) + " Custom Edition").strip() + federation = ask("Federation name", federation_name(source_id)).strip() + config = builtin_profile_for_copy(source_id, new_custom_game_id(federation, title)) + config["game_title"] = title or config["game_title"] + config["federation_name"] = federation or config["federation_name"] + print(f"Copied {game_title(source_id)} into the editable BYOG directory.") + return edit_custom_profile(config) + + +def edit_existing_custom_game() -> None: + refresh_custom_games() + game_ids = sorted(CUSTOM_GAME_CONFIGS) + if not game_ids: + print("No custom games exist yet. Create or copy one first.") + return + labels = [game_display_name(game_id) for game_id in game_ids] + game_id = game_ids[ask_choice("Choose custom game to edit", game_ids, labels=labels)] + editable = json.loads(json.dumps(CUSTOM_GAME_CONFIGS[game_id])) + edit_custom_profile(editable) + refresh_custom_games() + + +def manage_games() -> None: + while True: + refresh_custom_games() + action = ask_choice( + "BYOG / Manage Games", + ["create", "copy", "edit", "back"], + labels=["Create a new game and federation", "Copy a built-in WWF game to edit", + f"Edit a custom game ({len(CUSTOM_GAME_CONFIGS)} available)", + "Back to main menu"], + ) + if action == 0: + create_custom_game() + elif action == 1: + clone_builtin_game() + elif action == 2: + edit_existing_custom_game() + else: + return + + def default_card_path(show: str, show_date: str) -> Path: CARD_DIR.mkdir(parents=True, exist_ok=True) stem = f"{show_date}-{slugify(show)}" @@ -252,19 +868,36 @@ def default_card_path(show: str, show_date: str) -> Path: return path -def show_name_for_brand(brand: str) -> str: +def show_name_for_brand(brand: str, shows: dict[str, str] | None = None) -> str: + shows = shows or {} if brand == "Raw": - return "Monday Night Raw" + return shows.get("Raw") or "Monday Night Raw" if brand == "SmackDown": - return "Thursday Night SmackDown!" - return "WWF PPV" + return shows.get("SmackDown") or "Thursday Night SmackDown!" + return shows.get("PPV") or "WWF PPV" + + +def game_show_names(game_id: str) -> dict[str, str]: + """Resolved show names for a registered game (WWE names for built-ins).""" + config = CUSTOM_GAME_CONFIGS.get(game_id, {}) + shows = config.get("shows") if isinstance(config, dict) else None + return {brand: show_name_for_brand(brand, shows if isinstance(shows, dict) else None) + for brand in SHOW_BRANDS} def is_ppv_card(card: dict[str, Any]) -> bool: if card.get("season_show") == "PPV": return True - show = str(card.get("show", "")).casefold() - return "ppv" in show or "pay-per-view" in show + show = str(card.get("show", "")) + folded = show.casefold() + if "ppv" in folded or "pay-per-view" in folded: + return True + game_id = str(card.get("game_id", "")) + if game_id: + ppv_name = game_show_names(game_id).get("PPV", "") + if ppv_name and folded == ppv_name.casefold(): + return True + return False def base_match_rating(match_type: str) -> float: @@ -281,7 +914,10 @@ def calculate_match_rating(match: dict[str, Any]) -> float | None: + max(0, int(match.get("near_falls", 0))) * NEAR_FALL_BONUS + max(0, int(match.get("finishers", 0))) * FINISHER_BONUS) action_bonus = min(raw_action, MATCH_ACTION_BONUS_CAP) - earned = base_match_rating(match.get("type", "")) + action_bonus + base_value = match.get("base_rating") + if not isinstance(base_value, (int, float)) or isinstance(base_value, bool): + base_value = base_match_rating(match.get("type", "")) + earned = float(base_value) + action_bonus if match.get("title_defense"): earned *= TITLE_MATCH_MULTIPLIER return round(min(100.0, earned), 1) @@ -311,11 +947,16 @@ def parse_action_count(raw: str) -> int | None: return int(raw) -def allowed_match_outcomes(match_type: str) -> tuple[str, ...]: +def allowed_match_outcomes(match_type: str | dict[str, Any]) -> tuple[str, ...]: + if isinstance(match_type, dict): + outcomes = match_type.get("valid_outcomes") + if isinstance(outcomes, list) and outcomes: + return tuple(outcomes) + match_type = str(match_type.get("type", "")) return MATCH_OUTCOME_OPTIONS.get(match_type, STANDARD_MATCH_OUTCOMES) -def choose_match_outcome(match_type: str) -> str: +def choose_match_outcome(match_type: str | dict[str, Any]) -> str: outcomes = allowed_match_outcomes(match_type) if len(outcomes) == 1: print(f"Match outcome: {outcomes[0]}") @@ -344,6 +985,9 @@ def prompt_action_count(label: str) -> int: def save_card(card: dict[str, Any]) -> None: path = Path(card["path"]) path.parent.mkdir(parents=True, exist_ok=True) + card.setdefault("game_title", game_title(card["game_id"])) + card.setdefault("federation_name", federation_name(card["game_id"])) + card.setdefault("title_definitions", title_definitions_for_game(card["game_id"])) ppv_rating = calculate_ppv_rating(card) card["ppv_rating"] = ppv_rating lines = [ @@ -351,7 +995,9 @@ def save_card(card: dict[str, Any]) -> None: f"- City: {json.dumps(card.get('city', ''), ensure_ascii=False)}", f"- Attendance: {json.dumps(card.get('attendance'))}", f"- Game ID: {json.dumps(card['game_id'])}", - f"- Game: {json.dumps(GAMES[card['game_id']]['title'], ensure_ascii=False)}", + f"- Game: {json.dumps(card['game_title'], ensure_ascii=False)}", + f"- Federation: {json.dumps(card['federation_name'], ensure_ascii=False)}", + f"- Title Definitions: {json.dumps(card['title_definitions'], ensure_ascii=False)}", f"- Date: {json.dumps(card['date'])}", ] if is_ppv_card(card): @@ -380,6 +1026,8 @@ def save_card(card: dict[str, Any]) -> None: lines.append(f"- Near Falls: {json.dumps(match.get('near_falls', 0))}") lines.append(f"- Finishers: {json.dumps(match.get('finishers', 0))}") lines.append(f"- Match Rating: {json.dumps(match.get('rating'))}") + lines.append(f"- Base Rating: {json.dumps(match.get('base_rating'))}") + lines.append(f"- Valid Outcomes: {json.dumps(match.get('valid_outcomes'), ensure_ascii=False)}") lines.append("") path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8") card["path"] = str(path) @@ -400,7 +1048,7 @@ def load_card(path: Path) -> dict[str, Any]: "finish": "", "promo": None, "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, "match_time_minutes": None, "near_falls": 0, "finishers": 0, - "rating": None} + "rating": None, "base_rating": None, "valid_outcomes": None} card["matches"].append(current) continue field = re.match(r"^- ([A-Za-z ]+): (.*)$", line) @@ -411,16 +1059,20 @@ def load_card(path: Path) -> dict[str, Any]: value = json.loads(raw) except json.JSONDecodeError as exc: raise ValueError(f"Invalid Markdown card field '{key}' in {path}") from exc - if key in ("game id", "date", "city", "attendance", "season id", "season show", - "season show number", "ppv rating"): - card[key.replace(" ", "_")] = value + if key in ("game id", "game", "federation", "title definitions", "date", "city", "attendance", + "season id", "season show", "season show number", "ppv rating"): + metadata_key = {"game": "game_title", "game id": "game_id"}.get( + key, key.replace(" ", "_") + ) + card[metadata_key] = value elif current is not None: mapping = {"title": "title", "type": "type", "sides": "sides", "winner side": "winner_side", "finish": "finish", "promo": "promo", "image": "image", "ranking division": "ranking_division", "title defense": "title_defense", "rivalry payoff": "rivalry_payoff", "match time minutes": "match_time_minutes", "near falls": "near_falls", - "finishers": "finishers", "match rating": "rating"} + "finishers": "finishers", "match rating": "rating", + "base rating": "base_rating", "valid outcomes": "valid_outcomes"} if key in mapping: current[mapping[key]] = value if card.get("game_id") not in GAMES: @@ -433,7 +1085,8 @@ def load_card(path: Path) -> dict[str, Any]: "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, "match_time_minutes": None, "near_falls": 0, - "finishers": 0, "rating": None}) + "finishers": 0, "rating": None, "base_rating": None, + "valid_outcomes": None}) if not card.get("show") or not card.get("date"): raise ValueError(f"Card is missing its show name or date: {path}") card.setdefault("city", "") @@ -453,7 +1106,8 @@ def load_card(path: Path) -> dict[str, Any]: if winner is not None and (not isinstance(winner, int) or not 0 <= winner < len(match["sides"])): raise ValueError(f"A match has an invalid winner side: {path}") division = match.get("ranking_division") - if division is not None and division not in CHAMPIONSHIPS: + card_titles = card.get("title_definitions") or title_definitions_for_game(card["game_id"]) + if division is not None and division not in [title["name"] for title in card_titles]: raise ValueError(f"A match has an unknown ranking division: {path}") if match.get("title_defense") and division is None: raise ValueError(f"A title defense must have a ranking division: {path}") @@ -471,6 +1125,21 @@ def load_card(path: Path) -> dict[str, Any]: not isinstance(rating, (int, float)) or not math.isfinite(rating) or not 0 <= rating <= 100 ): raise ValueError(f"A match has an invalid rating: {path}") + base_rating = match.get("base_rating") + if base_rating is not None and ( + not isinstance(base_rating, (int, float)) or not math.isfinite(base_rating) + or not 0 <= base_rating <= 100 + ): + raise ValueError(f"A match has an invalid base rating: {path}") + outcomes = match.get("valid_outcomes") + if outcomes is not None and ( + not isinstance(outcomes, list) or not outcomes + or any(not isinstance(outcome, str) or not outcome.strip() for outcome in outcomes) + ): + raise ValueError(f"A match has invalid outcome options: {path}") + card.setdefault("game_title", game_title(card["game_id"])) + card.setdefault("federation_name", federation_name(card["game_id"])) + card.setdefault("title_definitions", title_definitions_for_game(card["game_id"])) card["ppv_rating"] = calculate_ppv_rating(card) return card @@ -627,20 +1296,25 @@ def attach_match_image(card: dict[str, Any]) -> None: def game_has_screenshots(game_id: str) -> bool: - return game_id in PS1_GAMES + return game_id in PS1_GAMES or ( + game_id in CUSTOM_GAME_CONFIGS and CUSTOM_GAME_CONFIGS[game_id]["platform"] == "ps1" + ) def choose_game() -> str: + refresh_custom_games() ids = list(GAMES) - labels = [GAMES[game_id]["title"] for game_id in ids] + labels = [game_display_name(game_id) for game_id in ids] return ids[ask_choice("Choose a game", ids, labels=labels)] def choose_match_type(game_id: str) -> tuple[str, tuple[int, ...]]: - options = MATCH_TYPES[game_id] - labels = [f"{name} ({' vs '.join(map(str, side_sizes))})" - for name, side_sizes in options] - return options[ask_choice("Choose match type", [item[0] for item in options], labels=labels)] + options = match_type_definitions(game_id) + labels = [f"{item['name']} ({' vs '.join(map(str, item['sides']))})" + for item in options] + selected = ask_choice("Choose match type", [item["name"] for item in options], labels=labels) + definition = options[selected] + return definition["name"], tuple(definition["sides"]) def choose_sides(side_sizes: tuple[int, ...], roster: list[str]) -> list[list[str]]: @@ -701,6 +1375,7 @@ def create_match(number: int, game_id: str, roster: list[str]) -> dict[str, Any] match_name, side_sizes = choose_match_type(game_id) title = ask("Optional match title (leave blank for none)") sides = choose_sides(side_sizes, roster) + definition = match_type_definition(game_id, match_name) image = "" if game_has_screenshots(game_id) and ask("Attach a DuckStation screenshot? (y/N)").lower() == "y": chosen = choose_screenshot() @@ -709,7 +1384,9 @@ def create_match(number: int, game_id: str, roster: list[str]) -> dict[str, Any] return {"title": title, "type": match_name, "sides": sides, "winner_side": None, "finish": "", "promo": None, "image": image, "ranking_division": None, "title_defense": False, "rivalry_payoff": False, - "match_time_minutes": None, "near_falls": 0, "finishers": 0, "rating": None} + "match_time_minutes": None, "near_falls": 0, "finishers": 0, "rating": None, + "base_rating": definition["base_rating"], + "valid_outcomes": list(definition["outcomes"])} def select_card_path() -> Path | None: @@ -733,7 +1410,7 @@ def select_card_path() -> Path | None: def create_card() -> dict[str, Any]: game_id = choose_game() roster = load_roster(game_id) - show = ask("Show name", "Thursday Night SmackDown!") + show = ask("Show name", game_show_names(game_id)["SmackDown"]) while True: show_date = ask("Show date (YYYY-MM-DD)", date.today().isoformat()) try: @@ -743,7 +1420,10 @@ def create_card() -> dict[str, Any]: print("Enter a valid date in YYYY-MM-DD format.") city, attendance = ask_location() card: dict[str, Any] = { - "game_id": game_id, "show": show, "date": show_date, + "game_id": game_id, "game_title": game_title(game_id), + "federation_name": federation_name(game_id), + "title_definitions": title_definitions_for_game(game_id), + "show": show, "date": show_date, "city": city, "attendance": attendance, "matches": [{"title": "", "type": "Singles", "sides": [], "winner_side": None, "finish": "", "promo": None, "image": "", "ranking_division": None, @@ -761,8 +1441,10 @@ def create_card() -> dict[str, Any]: return card -def random_match(game_id: str, roster: list[str], used: set[str]) -> dict[str, Any]: - match_name, side_sizes = random.choice(MATCH_TYPES[game_id]) +def random_match(game_id: str, roster: list[str], used: set[str], + profile: dict[str, Any] | None = None) -> dict[str, Any]: + definition = random.choice(match_type_definitions(game_id, profile)) + match_name, side_sizes = definition["name"], tuple(definition["sides"]) used_folded = {name.casefold() for name in used} available = [name for name in roster if name.casefold() not in used_folded] if len(available) < sum(side_sizes): @@ -780,6 +1462,8 @@ def random_match(game_id: str, roster: list[str], used: set[str]) -> dict[str, A "promo": None, "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, "match_time_minutes": None, "near_falls": 0, "finishers": 0, "rating": None, + "base_rating": definition["base_rating"], + "valid_outcomes": list(definition["outcomes"]), } @@ -787,12 +1471,15 @@ def create_random_card() -> dict[str, Any]: """Create a randomized three-match show after the user selects a game.""" game_id = choose_game() roster = load_roster(game_id) - show = random.choice(("Monday Night Raw", "Thursday Night SmackDown!", "WWF PPV")) + show = random.choice(list(game_show_names(game_id).values())) city, attendance = random_location() show_date = date.today().isoformat() used: set[str] = set() card: dict[str, Any] = { - "game_id": game_id, "show": show, "date": show_date, + "game_id": game_id, "game_title": game_title(game_id), + "federation_name": federation_name(game_id), + "title_definitions": title_definitions_for_game(game_id), + "show": show, "date": show_date, "city": city, "attendance": attendance, "matches": [random_match(game_id, roster, used) for _ in range(3)], "path": str(default_card_path(show, show_date)), @@ -989,7 +1676,7 @@ def header_lines(card: dict[str, Any], width: int) -> list[str]: left_width = 7 row_count = max(len(left), len(center), 2) if width < 62: - title = GAMES[card["game_id"]]["title"] + title = card.get("game_title", game_title(card["game_id"])) return [f"{color('WWF.com', RED)} {color(title, CYAN)}", f"{card['date']} · {show_location_text(card)}", ""] left_x = 1 @@ -1274,7 +1961,7 @@ def season_simulation_weights(season: dict[str, Any] | None, """Higher-ranked division entrants get an edge, but lower ranks can upset.""" sides = match.get("sides", []) division = match.get("ranking_division") - if not season or not division or division not in CHAMPIONSHIPS: + if not season or not division or division not in season_title_names(season): return [1.0] * len(sides) entries = season_ranking_entries(season, division) rank_positions = {side_identity(entry.get("members", [])): position @@ -1349,7 +2036,7 @@ def record_match_result(card: dict[str, Any], index: int, auto_simulate: bool = match["winner_side"] = ask_choice( "Winning side", list(range(len(sides))), labels=side_labels ) - match["finish"] = choose_match_outcome(match["type"]) + match["finish"] = choose_match_outcome(match) match["match_time_minutes"] = prompt_match_minutes() match["near_falls"] = prompt_action_count("Near falls (two-count kickouts)") match["finishers"] = prompt_action_count("Finishers executed") @@ -1397,8 +2084,11 @@ def season_card_exit_label(card: dict[str, Any]) -> str: return "Advance to Next Show" if complete else "Return to Season Menu" -def choose_ranking_division(current: str | None = None, allow_unranked: bool = True) -> str | None: - options: list[str | None] = ([None] if allow_unranked else []) + list(CHAMPIONSHIPS) +def choose_ranking_division(game_id: str, current: str | None = None, + allow_unranked: bool = True, + title_definitions: list[dict[str, str]] | None = None) -> str | None: + titles = title_definitions or title_definitions_for_game(game_id) + options: list[str | None] = ([None] if allow_unranked else []) + [title["name"] for title in titles] labels = ["Unranked / Others pool" if item is None else item for item in options] default = options.index(current) + 1 if current in options else None return options[ask_choice("Assign ranking division", options, @@ -1413,25 +2103,31 @@ def edit_match(card: dict[str, Any]) -> None: index = choose_match_index(card, editable, "Choose a match to edit") match = card["matches"][index] roster = load_roster(card["game_id"]) - options = MATCH_TYPES[card["game_id"]] - names = [item[0] for item in options] + ["Keep current"] - labels = [f"{name} ({' vs '.join(map(str, side_sizes))})" for name, side_sizes in options] + options = match_type_definitions(card["game_id"]) + names = [item["name"] for item in options] + ["Keep current"] + labels = [f"{item['name']} ({' vs '.join(map(str, item['sides']))})" + for item in options] labels.append(f"Keep current: {match['type']}") selected = ask_choice("Choose match type", names, labels=labels) old_sizes = tuple(len(side) for side in match.get("sides", [])) if selected < len(options): - match["type"], side_sizes = options[selected] + match["type"] = options[selected]["name"] + side_sizes = tuple(options[selected]["sides"]) else: - found = next((entry for entry in options if entry[0] == match["type"]), options[0]) - side_sizes = found[1] + found = next((entry for entry in options if entry["name"] == match["type"]), options[0]) + side_sizes = tuple(found["sides"]) needs_participants = old_sizes != side_sizes if needs_participants or ask("Change participants too? (y/N)").lower() == "y": match["sides"] = choose_sides(side_sizes, roster) + profile = match_type_definition(card["game_id"], match["type"]) + match["base_rating"] = profile["base_rating"] + match["valid_outcomes"] = list(profile["outcomes"]) current_title = match.get("title", "") match["title"] = ask(f"Match title (blank removes; current: {current_title or 'none'})") if card.get("season_id"): match["ranking_division"] = choose_ranking_division( - match.get("ranking_division"), allow_unranked=True + card["game_id"], match.get("ranking_division"), allow_unranked=True, + title_definitions=card.get("title_definitions"), ) if match["ranking_division"]: match["title_defense"] = ask_yes_no( @@ -1451,8 +2147,11 @@ def new_season_state(name: str, game_id: str, champions: dict[str, list[str] | None] | None = None, season_id: str | None = None) -> dict[str, Any]: champions = champions or {} + profile = game_profile(game_id) + title_definitions = [dict(item) for item in profile["championships"]] title_state: dict[str, Any] = {} - for division in CHAMPIONSHIPS: + for definition in title_definitions: + division = definition["name"] holder = champions.get(division) title_state[division] = { "holder": list(holder) if holder else None, @@ -1470,11 +2169,16 @@ def new_season_state(name: str, game_id: str, "season_id": season_id, "name": name, "game_id": game_id, + "game_title": profile["game_title"], + "federation_name": profile["federation_name"], + "game_config": profile, + "title_definitions": title_definitions, + "shows": shows_snapshot(profile), "created_at": datetime.now().astimezone().isoformat(timespec="seconds"), "next_show_number": 1, "current_card": "", "champions": title_state, - "rankings": {division: {} for division in CHAMPIONSHIPS}, + "rankings": {definition["name"]: {} for definition in title_definitions}, "rivalries": {}, "processed_results": [], "show_history": [], @@ -1494,14 +2198,24 @@ def load_season(path_or_id: Path | str) -> dict[str, Any]: raise ValueError(f"Invalid season save: {path}") if not payload.get("season_id") or not payload.get("name"): raise ValueError(f"Season save is missing its identity: {path}") + payload.setdefault("game_config", game_profile(payload["game_id"])) + payload.setdefault("game_title", payload["game_config"].get("game_title", game_title(payload["game_id"]))) + payload.setdefault("federation_name", payload["game_config"].get( + "federation_name", federation_name(payload["game_id"]) + )) + payload.setdefault("title_definitions", payload["game_config"].get( + "championships", title_definitions_for_game(payload["game_id"]) + )) + payload.setdefault("shows", shows_snapshot(payload.get("game_config"))) + title_names = season_title_names(payload) payload.setdefault("next_show_number", 1) payload.setdefault("current_card", "") - payload.setdefault("rankings", {division: {} for division in CHAMPIONSHIPS}) + payload.setdefault("rankings", {division: {} for division in title_names}) payload.setdefault("champions", {}) payload.setdefault("rivalries", {}) payload.setdefault("processed_results", []) payload.setdefault("show_history", []) - for division in CHAMPIONSHIPS: + for division in title_names: payload.setdefault("rankings", {}).setdefault(division, {}) payload.setdefault("champions", {}).setdefault( division, {"holder": None, "successful_defenses": 0, "defense_history": {}} @@ -1520,10 +2234,13 @@ def side_display(side: list[str] | None) -> str: def eligible_roster_for_division(game_id: str, division: str, - roster: list[str] | None = None) -> list[str]: - roster = roster or load_roster(game_id) - if division == "Women's": - eligible = {name.casefold() for name in WOMEN_ROSTERS.get(game_id, set())} + roster: list[str] | None = None, + profile: dict[str, Any] | None = None) -> list[str]: + profile = profile or game_profile(game_id) + roster = list(profile.get("roster", [])) if roster is None else roster + if championship_kind(game_id, division, profile) == "women": + eligible_names = profile.get("women_roster", []) + eligible = {name.casefold() for name in eligible_names} return [name for name in roster if name.casefold() in eligible] return list(roster) @@ -1534,8 +2251,11 @@ def choose_roster_member(names: list[str], prompt: str) -> str: return names[ask_choice(prompt, names)] -def choose_initial_champion(division: str, game_id: str, used: set[str]) -> list[str] | None: - roster = eligible_roster_for_division(game_id, division) +def choose_initial_champion(division: str, game_id: str, used: set[str], + profile: dict[str, Any] | None = None) -> list[str] | None: + profile = profile or game_profile(game_id) + roster = eligible_roster_for_division(game_id, division, profile=profile) + is_tag_title = championship_kind(game_id, division, profile) == "tag" print(f"\nInitial {division} champion:") mode = ask_choice("Choose initial champion option", ["choose", "random", "vacant"], labels=["Choose wrestler/team", "Random", "Vacant"]) @@ -1543,9 +2263,9 @@ def choose_initial_champion(division: str, game_id: str, used: set[str]) -> list return None choose_manually = mode == 0 # option 1 is Choose; option 2 is Random. available = [name for name in roster if name.casefold() not in used] - if len(available) < (2 if division == "Tag Team" else 1): + if len(available) < (2 if is_tag_title else 1): available = roster - if division == "Tag Team": + if is_tag_title: if choose_manually: first = choose_roster_member(available, "First tag champion") remaining = [name for name in available if name != first] or available @@ -1559,11 +2279,13 @@ def choose_initial_champion(division: str, game_id: str, used: set[str]) -> list def create_season() -> dict[str, Any]: game_id = choose_game() - name = ask("Season name", f"{GAMES[game_id]['title']} Season") + profile = game_profile(game_id) + name = ask("Season name", f"{game_display_name(game_id)} Season") champions: dict[str, list[str] | None] = {} used: set[str] = set() - for division in CHAMPIONSHIPS: - holder = choose_initial_champion(division, game_id, used) + for definition in profile["championships"]: + division = definition["name"] + holder = choose_initial_champion(division, game_id, used, profile) champions[division] = holder if holder: used.update(name.casefold() for name in holder) @@ -1593,9 +2315,10 @@ def season_ranking_entries(season: dict[str, Any], division: str) -> list[dict[s def season_other_pool(season: dict[str, Any], roster: list[str] | None = None) -> list[str]: """Unassigned wrestlers for non-title booking; this is not a title division.""" - roster = roster or load_roster(season["game_id"]) + profile = season_game_profile(season) + roster = roster or list(profile.get("roster", load_roster(season["game_id"]))) involved: set[str] = set() - for division in CHAMPIONSHIPS: + for division in season_title_names(season): for entry in season.get("rankings", {}).get(division, {}).values(): involved.update(name.casefold() for name in entry.get("members", [])) holder = season.get("champions", {}).get(division, {}).get("holder") @@ -1605,8 +2328,8 @@ def season_other_pool(season: dict[str, Any], roster: list[str] | None = None) - def print_power_rankings(season: dict[str, Any]) -> None: - print(f"\nPOWER RANKINGS — {season['name']} ({GAMES[season['game_id']]['title']})") - for division in CHAMPIONSHIPS: + print(f"\nPOWER RANKINGS — {season['name']} ({game_display_name(season['game_id'])})") + for division in season_title_names(season): championship = season["champions"][division] holder = championship.get("holder") print(f"\n{division} Champion: {side_display(holder)}") @@ -1646,7 +2369,7 @@ def record_season_match(season: dict[str, Any], card: dict[str, Any], match: dict[str, Any], match_index: int) -> None: division = match.get("ranking_division") winner = match.get("winner_side") - if division in CHAMPIONSHIPS and winner is not None: + if division in season_title_names(season) and winner is not None: table = season["rankings"].setdefault(division, {}) for side_index, side in enumerate(match.get("sides", [])): key = side_identity(side) @@ -1657,7 +2380,7 @@ def record_season_match(season: dict[str, Any], card: dict[str, Any], entry.setdefault("recent", []).append(result) entry["recent"] = entry["recent"][-10:] - if match.get("title_defense") and division in CHAMPIONSHIPS and winner is not None: + if match.get("title_defense") and division in season_title_names(season) and winner is not None: championship = season["champions"][division] winner_side = list(match["sides"][winner]) holder = championship.get("holder") @@ -1698,7 +2421,7 @@ def validate_title_defense(season: dict[str, Any], match: dict[str, Any]) -> boo division = match.get("ranking_division") if not match.get("title_defense"): return True - if division not in CHAMPIONSHIPS: + if division not in season_title_names(season): print("A title defense must be assigned to a championship division.") return False holder = season["champions"][division].get("holder") @@ -1752,10 +2475,13 @@ def title_defense_weight(kind: str, brand: str) -> float: def make_season_match(game_id: str, sides: list[list[str]], division: str | None, title: str = "", title_defense: bool = False, - rivalry_payoff: bool = False) -> dict[str, Any]: + rivalry_payoff: bool = False, + profile: dict[str, Any] | None = None) -> dict[str, Any]: sizes = tuple(len(side) for side in sides) - options = [name for name, side_sizes in MATCH_TYPES[game_id] if side_sizes == sizes] - match_type = random.choice(options) if options else "Singles" + options = [item for item in match_type_definitions(game_id, profile) + if tuple(item["sides"]) == sizes] + definition = random.choice(options) if options else match_type_definition(game_id, "Singles", profile) + match_type = definition["name"] return { "title": title, "type": match_type, @@ -1771,29 +2497,37 @@ def make_season_match(game_id: str, sides: list[list[str]], division: str | None "near_falls": 0, "finishers": 0, "rating": None, + "base_rating": definition["base_rating"], + "valid_outcomes": list(definition["outcomes"]), } def division_roster(game_id: str, division: str, roster: list[str], used: set[str], - holder: list[str] | None = None) -> list[str]: - candidates = eligible_roster_for_division(game_id, division, roster) + holder: list[str] | None = None, + profile: dict[str, Any] | None = None) -> list[str]: + profile = profile or game_profile(game_id) + candidates = eligible_roster_for_division(game_id, division, roster, profile) + is_tag = championship_kind(game_id, division, profile) == "tag" excluded = {name.casefold() for name in used} if holder: excluded.update(name.casefold() for name in holder) available = [name for name in candidates if name.casefold() not in excluded] - if len(available) < (4 if division == "Tag Team" else 2): + if len(available) < (4 if is_tag else 2): available = [name for name in candidates if name.casefold() not in {n.casefold() for n in used}] - return available if len(available) >= (4 if division == "Tag Team" else 2) else candidates + return available if len(available) >= (4 if is_tag else 2) else candidates def seed_division_sides(game_id: str, division: str, roster: list[str], used: set[str], - holder: list[str] | None = None) -> list[list[str]] | None: - available = division_roster(game_id, division, roster, used, holder) - needed = 4 if division == "Tag Team" else 2 + holder: list[str] | None = None, + profile: dict[str, Any] | None = None) -> list[list[str]] | None: + profile = profile or game_profile(game_id) + available = division_roster(game_id, division, roster, used, holder, profile) + is_tag = championship_kind(game_id, division, profile) == "tag" + needed = 4 if is_tag else 2 if len(available) < needed: return None picks = random.sample(available, needed) - if division == "Tag Team": + if is_tag: return [picks[:2], picks[2:]] return [[picks[0]], [picks[1]]] @@ -1801,6 +2535,7 @@ def seed_division_sides(game_id: str, division: str, roster: list[str], used: se def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: str, used: set[str]) -> list[dict[str, Any]]: game_id = season["game_id"] + profile = season_game_profile(season) candidates: list[dict[str, Any]] = [] used_folded = {name.casefold() for name in used} @@ -1812,11 +2547,11 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: "match": match}) # A division's top-ranked non-champion is the natural challenger. - for division in CHAMPIONSHIPS: + for division in season_title_names(season): championship = season["champions"][division] holder = championship.get("holder") entries = season_ranking_entries(season, division) - eligible_size = 2 if division == "Tag Team" else 1 + eligible_size = 2 if season_championship_kind(season, division) == "tag" else 1 valid_entries = [entry for entry in entries if len(entry.get("members", [])) == eligible_size] if holder: @@ -1832,7 +2567,8 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: match = make_season_match(game_id, [list(holder), list(challenger)], division, title=(f"{division} Championship — Feud Finale" if payoff else f"{division} Championship"), - title_defense=True, rivalry_payoff=payoff) + title_defense=True, rivalry_payoff=payoff, + profile=profile) add("title", match) elif len(valid_entries) >= 2: challengers = [entry["members"] for entry in valid_entries @@ -1841,6 +2577,7 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: match = make_season_match( game_id, [list(challengers[0]), list(challengers[1])], division, title=f"Vacant {division} Championship", title_defense=True, + profile=profile, ) add("title", match) @@ -1851,17 +2588,17 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: if len(ranked_sides) >= 2: sides = ranked_sides[:2] elif len(ranked_sides) == 1: - available = division_roster(game_id, division, roster, used, holder) + available = division_roster(game_id, division, roster, used, holder, profile) available = [name for name in available if name.casefold() not in {n.casefold() for n in ranked_sides[0]}] - needed = 2 if division == "Tag Team" else 1 + needed = 2 if season_championship_kind(season, division) == "tag" else 1 if len(available) >= needed: new_side = random.sample(available, needed) - sides = [ranked_sides[0], new_side] + sides = [ranked_sides[0], new_side] if sides is None: - sides = seed_division_sides(game_id, division, roster, used, holder) + sides = seed_division_sides(game_id, division, roster, used, holder, profile) if sides: - add("ranked", make_season_match(game_id, sides, division)) + add("ranked", make_season_match(game_id, sides, division, profile=profile)) # Repeated head-to-head meetings become active rivalries; PPVs can resolve them. for rivalry in season.get("rivalries", {}).values(): @@ -1872,7 +2609,7 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: payoff = brand == "PPV" title = "Rivalry Finale" if payoff else "Rivalry Match" add("rivalry", make_season_match(game_id, sides, division, title=title, - rivalry_payoff=payoff)) + rivalry_payoff=payoff, profile=profile)) # The Others pool supplies unranked, non-title bouts. pool = [name for name in season_other_pool(season, roster) @@ -1880,9 +2617,9 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: if len(pool) < 2: pool = [name for name in roster if name.casefold() not in used_folded] if len(pool) >= 2: - available_types = [item for item in MATCH_TYPES[game_id] - if item[1] in ((1, 1), (2, 2), (1, 1, 1))] - _, sizes = random.choice(available_types) + available_types = [item for item in match_type_definitions(game_id, profile) + if tuple(item["sides"]) in ((1, 1), (2, 2), (1, 1, 1))] + sizes = tuple(random.choice(available_types)["sides"]) needed = sum(sizes) choices = pool if len(pool) >= needed else [name for name in roster if name.casefold() not in used_folded] @@ -1894,12 +2631,14 @@ def season_booking_candidates(season: dict[str, Any], roster: list[str], brand: for size in sizes: sides.append(picks[cursor:cursor + size]) cursor += size - add("pool", make_season_match(game_id, sides, None, title="Non-Title Match")) + add("pool", make_season_match(game_id, sides, None, title="Non-Title Match", + profile=profile)) return candidates def build_season_matches(season: dict[str, Any], brand: str) -> list[dict[str, Any]]: - roster = load_roster(season["game_id"]) + profile = season_game_profile(season) + roster = list(profile.get("roster", load_roster(season["game_id"]))) used: set[str] = set() matches: list[dict[str, Any]] = [] title_defenses = 0 @@ -1909,7 +2648,7 @@ def build_season_matches(season: dict[str, Any], brand: str) -> list[dict[str, A if title_defenses >= max_title_defenses: candidates = [candidate for candidate in candidates if candidate["kind"] != "title"] if not candidates: - fallback = random_match(season["game_id"], roster, used) + fallback = random_match(season["game_id"], roster, used, profile=profile) matches.append(fallback) used.update(name.casefold() for side in fallback["sides"] for name in side) continue @@ -1938,7 +2677,7 @@ def book_next_season_show(season: dict[str, Any]) -> dict[str, Any]: season.update(updated) number = int(season.get("next_show_number", 1)) brand = show_for_season_number(number) - show = show_name_for_brand(brand) + show = show_name_for_brand(brand, season.get("shows")) city, attendance = random_location() show_date = date.today().isoformat() card: dict[str, Any] = { @@ -1967,7 +2706,9 @@ def choose_or_create_season() -> dict[str, Any]: try: saved = load_season(path) next_brand = season_show_brand(saved.get("next_show_number", 1)) - labels.append(f"{saved['name']} · {GAMES[saved['game_id']]['title']} · next: {next_brand}") + next_show = show_name_for_brand(next_brand, saved.get("shows")) + labels.append(f"{saved['name']} · {saved.get('federation_name', federation_name(saved['game_id']))}" + f" · {saved.get('game_title', game_title(saved['game_id']))} · next: {next_show}") except (OSError, ValueError, json.JSONDecodeError): labels.append(f"{path.stem} (invalid save)") selected = ask_choice("Season Mode", ["new"] + [path.name for path in paths], labels=labels) @@ -1985,12 +2726,14 @@ def run_season(season: dict[str, Any]) -> None: season["current_card"] = "" save_season(season) current = "" - print(f"\nSeason: {season['name']} · {GAMES[season['game_id']]['title']}") - print(f"Cycle {((number - 1) // 3) + 1} · Next: {brand}") + print(f"\nSeason: {season['name']} · {season.get('federation_name', federation_name(season['game_id']))}" + f" · {season.get('game_title', game_title(season['game_id']))}") + next_name = show_name_for_brand(brand, season.get("shows")) + print(f"Cycle {((number - 1) // 3) + 1} · Next: {next_name} ({brand})") if current: next_action = "Resume current show" else: - next_action = f"Advance to Next Show ({brand})" + next_action = f"Advance to Next Show ({next_name})" choice = ask_choice( "Season action", ["book/resume", "rankings", "back"], labels=[next_action, "Power rankings / title holders", "Back to main menu"], @@ -2218,7 +2961,8 @@ def resume_card(card: dict[str, Any]) -> bool: if card.get("season_id"): sync_season_card_results(card) while True: - print(f"\n{show_location_text(card)} · {GAMES[card['game_id']]['title']} · {card['date']}") + print(f"\n{show_location_text(card)} · {card.get('federation_name', federation_name(card['game_id']))}" + f" · {card.get('game_title', game_title(card['game_id']))} · {card['date']}") if card.get("ppv_rating") is not None: print(f"PPV Rating: {float(card['ppv_rating']):.1f}%") print(f"Card: {card['path']}") @@ -2246,13 +2990,15 @@ def resume_card(card: dict[str, Any]) -> bool: def main() -> int: + refresh_custom_games() print(color("WWF SmackDown! Match Card Maker", CYAN)) while True: try: choice = ask_choice( - "Main menu", ["new", "random", "season", "load", "exit"], + "Main menu", ["new", "random", "season", "load", "byog", "exit"], labels=["Create a new three-match card", "Create a fully randomized show", - "Season Mode", "Load / resume a saved card", "Exit"], + "Season Mode", "Load / resume a saved card", "BYOG / Manage Games", + "Exit"], ) if choice == 0: resume_card(create_card()) @@ -2271,6 +3017,8 @@ def main() -> int: run_season(load_season(str(card["season_id"]))) except (OSError, ValueError, json.JSONDecodeError) as exc: print(f"Could not load card: {exc}") + elif choice == 4: + manage_games() else: return 0 except (KeyboardInterrupt, EOFError): diff --git a/test_smackdown_card_maker.py b/test_smackdown_card_maker.py index 634533f..6f54575 100644 --- a/test_smackdown_card_maker.py +++ b/test_smackdown_card_maker.py @@ -25,6 +25,11 @@ class RosterTests(unittest.TestCase): class MarkdownTests(unittest.TestCase): def make_card(self, path: Path) -> dict: + def profile_fields(match_type: str) -> dict: + definition = app.match_type_definition("sd2", match_type) + return {"base_rating": definition["base_rating"], + "valid_outcomes": list(definition["outcomes"])} + return { "game_id": "sd2", "show": 'The "Big" Show', @@ -34,16 +39,18 @@ class MarkdownTests(unittest.TestCase): {"title": "Opener", "type": "Singles", "sides": [["The Rock"], ["Kane"]], "winner_side": 0, "finish": "pinfall", "promo": None, "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, - "match_time_minutes": None, "near_falls": 0, "finishers": 0, "rating": None}, + "match_time_minutes": None, "near_falls": 0, "finishers": 0, "rating": None, + **profile_fields("Singles")}, {"title": "", "type": "Tag Team", "sides": [["Edge", "Christian"], ["The Hardy Boyz", "Tazz"]], "winner_side": None, "finish": "", "promo": None, "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, "match_time_minutes": None, "near_falls": 0, - "finishers": 0, "rating": None}, + "finishers": 0, "rating": None, **profile_fields("Tag Team")}, {"title": "", "type": "Triple Threat", "sides": [], "winner_side": None, "finish": "", "promo": None, "image": "", "ranking_division": None, "title_defense": False, "rivalry_payoff": False, "match_time_minutes": None, - "near_falls": 0, "finishers": 0, "rating": None}, + "near_falls": 0, "finishers": 0, "rating": None, + **profile_fields("Triple Threat")}, ], } @@ -753,6 +760,330 @@ class SeasonModeTests(unittest.TestCase): self.assertEqual(len(after_second["processed_results"]), 3) +class BYOGTests(unittest.TestCase): + def setUp(self): + self._configs = app.CUSTOM_GAME_CONFIGS + self._games = dict(app.GAMES) + self._match_types = dict(app.MATCH_TYPES) + # Point the BYOG directory at a session-local temp dir so custom + # registrations survive refreshes and never touch the real edit/ folder. + self.game_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.game_dir.cleanup) + patcher = patch.object(app, "CUSTOM_GAME_DIR", Path(self.game_dir.name) / "games") + patcher.start() + self.addCleanup(patcher.stop) + + def tearDown(self): + app.CUSTOM_GAME_CONFIGS = self._configs + app.GAMES.clear() + app.GAMES.update(self._games) + app.MATCH_TYPES.clear() + app.MATCH_TYPES.update(self._match_types) + + def config(self, **overrides) -> dict: + data = { + "game_id": "custom-fantasy-fed-rumble-royale", + "game_title": "Rumble Royale", + "federation_name": "Fantasy Fed", + "platform": "ps1", + "roster": ["Ava Crusher", "Ben Brawler", "Cara Storm", "Dash Vance"], + "match_types": [ + {"name": "Scaffold", "sides": [1, 1], "base_rating": 8.5}, + {"name": "Tag Tornado", "sides": [2, 2], + "outcomes": ["pinfall", "submission"]}, + ], + "championships": [ + {"name": "Rumble Belt", "kind": "singles"}, + {"name": "Fantasy Tag", "kind": "tag"}, + {"name": "Fantasy Women", "kind": "women"}, + ], + "women_roster": ["Cara Storm"], + } + data.update(overrides) + return data + + def register(self, data: dict) -> dict: + saved = app.save_custom_game(data, app.CUSTOM_GAME_DIR) + app.refresh_custom_games() + return saved + + def filler_match(self, match_type: str, base_rating: float | None = None) -> dict: + sized = {} + for item in app.match_type_definitions(self.config()["game_id"]): + if item["name"] == match_type: + sized = item + break + return {"title": "", "type": match_type, "sides": [], "winner_side": None, + "finish": "", "promo": None, "image": "", "ranking_division": None, + "title_defense": False, "rivalry_payoff": False, + "match_time_minutes": None, "near_falls": 0, "finishers": 0, + "rating": None, + "base_rating": base_rating if base_rating is not None + else (sized.get("base_rating") if sized else app.base_match_rating(match_type)), + "valid_outcomes": list(sized["outcomes"]) if sized + else list(app.STANDARD_MATCH_OUTCOMES)} + + def test_validate_custom_game_accepts_and_normalizes_profiles(self): + saved = app.validate_custom_game(self.config()) + self.assertEqual(saved["game_id"], "custom-fantasy-fed-rumble-royale") + self.assertEqual(saved["schema_version"], 1) + self.assertEqual(saved["match_types"][0]["base_rating"], 8.5) + self.assertEqual(saved["match_types"][1]["base_rating"], + app.MATCH_BASE_RATINGS["Tag Team"]) + self.assertEqual(saved["match_types"][0]["outcomes"], + list(app.STANDARD_MATCH_OUTCOMES)) + self.assertEqual(saved["match_types"][1]["outcomes"], ["pinfall", "submission"]) + self.assertEqual(saved["championships"][2]["kind"], "women") + + def test_validate_custom_game_rejects_invalid_definitions(self): + rejects = [ + ({"game_id": "sd1"}, "custom definitions cannot overwrite built-in games"), + ({"game_id": "Bad ID"}, "game_id must use lowercase"), + ({"roster": ["Ava Crusher", "ava crusher"]}, "unique"), + ({"roster": ["Solo"]}, "at least two"), + ({"women_roster": ["Not Listed"]}, "subset of the roster"), + ({"match_types": [{"name": "Tag Tornado", "sides": [3, 3]}]}, + "invalid side sizes"), + ({"match_types": []}, "at least one match type"), + ({"championships": [{"name": "Belt", "kind": "hardcore"}]}, "kind"), + ({"platform": "dreamcast"}, "platform must be ps1"), + ] + for overrides, message in rejects: + with self.subTest(overrides=overrides): + data = self.config(**overrides) + with self.assertRaises(ValueError) as caught: + app.validate_custom_game(data) + self.assertIn(message, str(caught.exception).lower()) + + def test_saved_custom_game_registers_in_catalog(self): + saved = self.register(self.config()) + self.assertTrue((app.CUSTOM_GAME_DIR / f"{saved['game_id']}.json").is_file()) + game_id = saved["game_id"] + self.assertIn(game_id, app.GAMES) + self.assertIn(game_id, app.CUSTOM_GAME_CONFIGS) + self.assertNotIn(game_id, app.BUILTIN_GAME_IDS) + self.assertEqual(app.load_roster(game_id), saved["roster"]) + self.assertEqual(app.game_title(game_id), "Rumble Royale") + self.assertEqual(app.game_display_name(game_id), + "Fantasy Fed — Rumble Royale") + self.assertEqual(app.championship_names_for_game(game_id), + ["Rumble Belt", "Fantasy Tag", "Fantasy Women"]) + self.assertTrue(app.game_has_screenshots(game_id)) + self.assertEqual(app.eligible_roster_for_division(game_id, "Fantasy Women"), + ["Cara Storm"]) + self.assertEqual([item["name"] for item in app.match_type_definitions(game_id)], + ["Scaffold", "Tag Tornado"]) + + def test_custom_game_survives_relaunch_via_refresh(self): + self.register(self.config()) + self.assertEqual(app.refresh_custom_games(), + ["custom-fantasy-fed-rumble-royale"]) + self.assertEqual(app.refresh_custom_games(), + ["custom-fantasy-fed-rumble-royale"]) + + def test_custom_game_card_round_trip_keeps_game_metadata(self): + game_id = self.config()["game_id"] + self.register(self.config()) + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "card.md" + card = { + "game_id": game_id, "show": "Rumble Night", "date": "2026-11-02", + "matches": [self.filler_match("Scaffold", base_rating=8.5), + self.filler_match("Tag Tornado"), + self.filler_match("Tag Tornado")], + "path": str(path), + } + app.save_card(card) + loaded = app.load_card(path) + self.assertEqual(loaded["game_title"], "Rumble Royale") + self.assertEqual(loaded["federation_name"], "Fantasy Fed") + self.assertEqual([item["name"] for item in loaded["title_definitions"]], + ["Rumble Belt", "Fantasy Tag", "Fantasy Women"]) + self.assertEqual(loaded["matches"][0]["type"], "Scaffold") + self.assertEqual(loaded["matches"][0]["base_rating"], 8.5) + self.assertEqual(loaded["matches"][1]["valid_outcomes"], ["pinfall", "submission"]) + + def test_custom_match_base_rating_can_drive_the_match_rating(self): + match = {"type": "Scaffold", "base_rating": 8.5, "match_time_minutes": 12.9, + "near_falls": 2, "finishers": 3, "title_defense": False} + plain = dict(match, base_rating=None) + self.assertEqual(app.calculate_match_rating(match) - app.calculate_match_rating(plain), + 8.5 - app.base_match_rating("Scaffold")) + + def test_custom_game_season_uses_custom_title_divisions(self): + config = self.config() + game_id = config["game_id"] + self.register(config) + season = app.new_season_state("Fantasy Season", game_id, + champions={"Rumble Belt": ["Ava Crusher"], + "Fantasy Tag": ["Ben Brawler", "Dash Vance"]}, + season_id="fantasy-season") + self.assertEqual([item["name"] for item in season["title_definitions"]], + ["Rumble Belt", "Fantasy Tag", "Fantasy Women"]) + self.assertEqual(set(season["rankings"]), + {"Rumble Belt", "Fantasy Tag", "Fantasy Women"}) + self.assertEqual(season["champions"]["Rumble Belt"]["holder"], ["Ava Crusher"]) + with contextlib.redirect_stdout(io.StringIO()): + roster = app.load_roster(game_id) + matches = app.build_season_matches(season, "Raw") + self.assertEqual(len(matches), 3) + for match in matches: + self.assertIn(match["ranking_division"], (None, "Rumble Belt", "Fantasy Tag", + "Fantasy Women")) + # A custom division result updates the custom rankings. + match = {"type": "Scaffold", "sides": [["Ava Crusher"], ["Ben Brawler"]], + "winner_side": 0, "ranking_division": "Rumble Belt", + "title_defense": False} + app.record_season_match(season, {"season_show": "Raw"}, match, 0) + table = season["rankings"]["Rumble Belt"] + self.assertEqual(table[app.side_identity(["Ava Crusher"])]["wins"], 1) + self.assertEqual(table[app.side_identity(["Ben Brawler"])]["losses"], 1) + # A successful defense keeps the custom champion on top. + defense = {"type": "Scaffold", "sides": [["Ava Crusher"], ["Cara Storm"]], + "winner_side": 0, "ranking_division": "Rumble Belt", + "title_defense": True} + app.record_season_match(season, {"season_show": "Raw"}, defense, 0) + self.assertEqual(season["champions"]["Rumble Belt"]["holder"], ["Ava Crusher"]) + self.assertEqual(season["champions"]["Rumble Belt"]["successful_defenses"], 1) + + def test_custom_season_save_round_trip_keeps_title_definitions(self): + self.register(self.config()) + season = app.new_season_state("Fantasy Season", self.config()["game_id"], + champions={"Rumble Belt": ["Ava Crusher"]}, + season_id="fantasy-save") + with tempfile.TemporaryDirectory() as folder: + with patch.object(app, "SEASON_DIR", Path(folder)): + app.save_season(season) + loaded = app.load_season(season["season_id"]) + self.assertEqual(loaded["game_title"], "Rumble Royale") + self.assertEqual(loaded["federation_name"], "Fantasy Fed") + self.assertEqual(loaded["champions"]["Rumble Belt"]["holder"], ["Ava Crusher"]) + self.assertEqual([item["name"] for item in loaded["title_definitions"]], + ["Rumble Belt", "Fantasy Tag", "Fantasy Women"]) + self.assertEqual(loaded["shows"], app.DEFAULT_CUSTOM_SHOWS) + + def test_choose_game_lists_builtin_games_then_custom_games(self): + self.register(self.config()) + with contextlib.redirect_stdout(io.StringIO()), \ + patch.object(app, "ask_choice", return_value=len(app.GAMES) - 1): + self.assertEqual(app.choose_game(), self.config()["game_id"]) + + CUSTOM_SHOWS = {"Raw": "Fantasy Rampage", "SmackDown": "Fantasy Clash", + "PPV": "Fantasy Super Card"} + + def test_shows_validation_accepts_normalizes_and_rejects_bad_values(self): + saved = app.validate_custom_game(self.config(shows=self.CUSTOM_SHOWS)) + self.assertEqual(saved["shows"], self.CUSTOM_SHOWS) + + # Absent shows fall back to neutral placeholders, never WWE names. + self.assertEqual(app.validate_custom_game(self.config())["shows"], + app.DEFAULT_CUSTOM_SHOWS) + + rejects = [ + ({"shows": ["Fantasy Rampage"]}, "shows must be an object"), + ({"shows": {"Raw": " "}}, "non-empty string"), + ({"shows": self.CUSTOM_SHOWS | {"Raw": "fantasy clash"}}, "unique"), + ({"shows": {"Raw": 3}}, "non-empty string"), + ] + for overrides, message in rejects: + with self.subTest(overrides=overrides): + data = self.config(**overrides) + with self.assertRaises(ValueError) as caught: + app.validate_custom_game(data) + self.assertIn(message, str(caught.exception).lower()) + + def test_game_show_names_resolve_wwe_names_only_for_builtins(self): + self.assertEqual(app.game_show_names("sd1")["SmackDown"], + "Thursday Night SmackDown!") + self.register(self.config()) + self.assertEqual(app.game_show_names(self.config()["game_id"]), + app.DEFAULT_CUSTOM_SHOWS) + self.register(self.config(shows=self.CUSTOM_SHOWS)) + game_id = self.config()["game_id"] + self.assertEqual(app.game_show_names(game_id), self.CUSTOM_SHOWS) + + def test_built_in_clone_prefills_wwe_show_names(self): + profile = app.builtin_game_profile("sd2") + self.assertEqual(profile["shows"]["Raw"], "Monday Night Raw") + copied = app.builtin_profile_for_copy("sd2", "custom-clone-test") + self.assertEqual(copied["shows"], {"Raw": "Monday Night Raw", + "SmackDown": "Thursday Night SmackDown!", + "PPV": "WWF PPV"}) + + def test_booked_season_cards_use_custom_show_names(self): + game_id = self.register(self.config(shows=self.CUSTOM_SHOWS))["game_id"] + season = app.new_season_state("Show Name Season", game_id, champions={}, + season_id="showname-season") + self.assertEqual(season["shows"], self.CUSTOM_SHOWS) + with tempfile.TemporaryDirectory() as folder, \ + patch.object(app, "SEASON_DIR", Path(folder) / "seasons"), \ + patch.object(app, "CARD_DIR", Path(folder) / "cards"), \ + contextlib.redirect_stdout(io.StringIO()): + names = [] + for show_number in (1, 2, 3): + season["next_show_number"] = show_number + card = app.book_next_season_show(season) + names.append(card["show"]) + season["current_card"] = "" + card["matches"][0]["winner_side"] = 0 + season_path = app.season_path(season["season_id"]) + # The season save keeps its custom show-name snapshot on disk. + saved = json.loads(season_path.read_text("utf-8")) + self.assertEqual(saved["shows"], self.CUSTOM_SHOWS) + self.assertEqual(names, ["Fantasy Rampage", "Fantasy Clash", "Fantasy Super Card"]) + + def test_is_ppv_card_matches_custom_ppv_show_name_exactly(self): + self.register(self.config(shows=self.CUSTOM_SHOWS)) + game_id = self.config()["game_id"] + event_card = {"game_id": game_id, "show": "Fantasy Super Card"} + weekly_card = {"game_id": game_id, "show": "Fantasy Rampage"} + self.assertTrue(app.is_ppv_card(event_card)) + self.assertFalse(app.is_ppv_card(weekly_card)) + # Case-insensitive exact match still applies. + self.assertTrue(app.is_ppv_card({"game_id": game_id, "show": "fantasy super card"})) + # Unknown card shows stay non-PPV even with a custom game. + self.assertFalse(app.is_ppv_card({"game_id": game_id, "show": "House Party"})) + + def test_one_off_cards_use_game_show_names(self): + game_id = self.register(self.config(shows=self.CUSTOM_SHOWS))["game_id"] + with tempfile.TemporaryDirectory() as folder, \ + patch.object(app, "CARD_DIR", Path(folder) / "cards"), \ + contextlib.redirect_stdout(io.StringIO()): + with patch.object(app, "choose_game", return_value=game_id): + card = app.create_random_card() + self.assertIn(card["show"], set(self.CUSTOM_SHOWS.values())) + # The create-a-card show prompt defaults to the second weekly slot. + captured = {} + + class Stop(Exception): + pass + + def fake_ask(prompt, default=None): + captured["default"] = default + raise Stop() + + with patch.object(app, "choose_game", return_value=game_id), \ + patch.object(app, "ask", fake_ask), \ + self.assertRaises(Stop): + app.create_card() + self.assertEqual(captured["default"], "Fantasy Clash") + + def test_edit_custom_shows_renames_and_rejects_duplicates(self): + config = {"shows": dict(self.CUSTOM_SHOWS)} + with contextlib.redirect_stdout(io.StringIO()), \ + patch.object(app, "ask_choice", side_effect=[0, 3]), \ + patch.object(app, "ask", return_value="Fantasy Festival"): + app.edit_custom_shows(config) + self.assertEqual(config["shows"]["Raw"], "Fantasy Festival") + + config = {"shows": dict(self.CUSTOM_SHOWS)} + with contextlib.redirect_stdout(io.StringIO()), \ + patch.object(app, "ask_choice", side_effect=[1, 3]), \ + patch.object(app, "ask", side_effect=["Fantasy Rampage", "Fantasy Zoom"]): + app.edit_custom_shows(config) + self.assertEqual(config["shows"]["SmackDown"], "Fantasy Zoom") + + class FlashRenderingTests(unittest.TestCase): def test_flash_updates_only_changed_rows_not_static_header(self): card = MarkdownTests().make_card(Path("card.md"))