#!/usr/bin/env python3 """Build one maximally-strong "typical" deck per sub-archetype. Rarity budget (from trophy data: ~0.6 mythic / ~1.9 rare / ~8.8 uncommon per deck): at most 1 mythic + 1 rare + 9 uncommons, rest commons -> 23 spells + lands. Cards are chosen by quality-in-archetype (affinity); creature/spell split follows the archetype's creature ratio; basic lands only in colours the deck uses. Outputs: value//reference_decks/.json + .txt """ from __future__ import annotations import argparse import json import re from collections import Counter, defaultdict from pathlib import Path ALL_COLORS = "WUBRG" BASIC_COLOR = {"Plains": "W", "Island": "U", "Swamp": "B", "Mountain": "R", "Forest": "G"} RARITY_CAP = {"mythic": 1, "rare": 1, "uncommon": 9, "common": 99} def required_colors(mana_cost): req = set() for sym in re.findall(r"\{([^}]+)\}", mana_cost or ""): if "/" in sym: continue for ch in sym: if ch in ALL_COLORS: req.add(ch) return req def score(c): return c["affinity"] if c.get("affinity") is not None else (c.get("importance") or 0) def build_deck(t, cap): allowed = set((t.get("colors") or t["archetype"]).upper()) spells = [c for c in t["cards"] if c["roles"] != ["land"]] cand = [c for c in spells if set(required_colors(c.get("mana_cost", ""))) <= allowed] cre = sorted((c for c in cand if "creature" in (c.get("roles") or [])), key=score, reverse=True) non = sorted((c for c in cand if "creature" not in (c.get("roles") or [])), key=score, reverse=True) cr = t["deck_params"].get("creature_ratio") or 0.55 n_cre = min(17, max(10, round(23 * cr))) used = defaultdict(int) counts = Counter() total = 0 def add(c): nonlocal total rar = (c.get("rarity") or "common").lower() if rar not in cap: rar = "common" cop = min(3, max(1, round(c.get("copies_when_played") or 1))) for _ in range(cop): if total >= 23 or used[rar] >= cap[rar]: break used[rar] += 1 counts[c["name"]] += 1 total += 1 for c in cre: if total >= n_cre: break add(c) for c in non: if total >= 23: break add(c) for c in cre + non: # fill if creature pass capped early if total >= 23: break add(c) info = {c["name"]: c for c in cand} deck = [{"name": n, "count": k, "rarity": info[n].get("rarity"), "cmc": info[n].get("cmc"), "roles": info[n].get("roles"), "mechanic_tags": info[n].get("mechanic_tags")} for n, k in sorted(counts.items(), key=lambda kv: (0 if "creature" in (info[kv[0]].get("roles") or []) else 1, info[kv[0]].get("cmc") or 0))] n_creatures = sum(d["count"] for d in deck if "creature" in (d["roles"] or [])) dp = t["deck_params"] nl = round(dp["land_count"]) bases = {k: v for k, v in dp["basic_lands"].items() if v > 0.3 and BASIC_COLOR.get(k, "?") in allowed} if not bases: bases = {k: 1.0 for k in BASIC_COLOR if BASIC_COLOR[k] in allowed} or {"Plains": 1.0} s = sum(bases.values()) or 1 lands = {k: max(1, round(v / s * nl)) for k, v in bases.items()} while sum(lands.values()) > nl: lands[max(lands, key=lands.get)] -= 1 while sum(lands.values()) < nl: lands[max(bases, key=bases.get)] += 1 return deck, lands, used, n_creatures def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", required=True) ap.add_argument("--uncommon", type=int, default=9) a = ap.parse_args() out = Path(a.out) cap = dict(RARITY_CAP) cap["uncommon"] = a.uncommon tdir = out / "templates" ddir = out / "reference_decks" ddir.mkdir(parents=True, exist_ok=True) for f in sorted(tdir.glob("*.PremierDraft.*.json")): t = json.loads(f.read_text(encoding="utf-8")) if t.get("reference_deck"): # actual medoid deck of the cluster (the real 40 cards closest to all others) rd = t["reference_deck"] deck, lands = rd["spells"], rd["lands"] used = Counter() for d in deck: used[d.get("rarity") or "common"] += d["count"] n_creatures = sum(d["count"] for d in deck if "creature" in (d.get("roles") or [])) src = rd.get("source", "actual medoid deck") src += f" · 战绩 {rd['record']}" if rd.get("record") else "" else: deck, lands, used, n_creatures = build_deck(t, cap) src = "constructed (max-quality under rarity budget)" rec = {"archetype": t["archetype"], "archetype_slug": t["archetype_slug"], "archetype_name": t["archetype_name"], "colors": t.get("colors"), "source": src, "rarity_budget": cap, "rarity_used": dict(used), "n_creatures": n_creatures, "spells": deck, "lands": lands, "total_spells": sum(d["count"] for d in deck), "total_lands": sum(lands.values())} (ddir / f"{t['archetype_slug']}.json").write_text( json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8") txt = [f"# {t['archetype_name']} ({t.get('colors')}) {src}", f"# used={dict(used)} creatures={n_creatures}"] txt += [f"{d['count']}x {d['name']} [{d['rarity']}]" for d in deck] txt.append("-- lands --") txt += [f"{v}x {k}" for k, v in sorted(lands.items(), key=lambda kv: -kv[1])] (ddir / f"{t['archetype_slug']}.txt").write_text("\n".join(txt), encoding="utf-8") # MTGA-importable decklist mtga = ["Deck"] mtga += [f"{d['count']} {d['name']}" for d in deck] mtga += [f"{v} {k}" for k, v in sorted(lands.items(), key=lambda kv: -kv[1])] (ddir / f"{t['archetype_slug']}.mtga.txt").write_text("\n".join(mtga) + "\n", encoding="utf-8") print(f"{t['archetype_name']:44} spells={rec['total_spells']} lands={rec['total_lands']} " f"creatures={n_creatures} {dict(used)}") print(f"\nwrote {len(list(ddir.glob('*.json')))} reference decks -> {ddir}") if __name__ == "__main__": main()