#!/usr/bin/env python """Parse 17lands GRE replays into real "cast / played" counts per card. For each replay we replay the GameStateMessages and detect: * cast - a GameObjectType_Card entering the Stack zone (zoneId 27), controlled by our seat (activated abilities, which are GameObjectType_Ability, excluded) * play - a land card entering the Battlefield zone (zoneId 28) Counts are aggregated per card name together with the number of replay-games in which the card was in that draft's 40-card maindeck, giving: cast_rate = casts / games-in-deck (spells, casts per game) cast_game_pct = games-with-cast / games-in-deck play_rate = land plays / games-in-deck Output: value//cast_stats.json """ from __future__ import annotations import argparse import gzip import json from collections import Counter, defaultdict from pathlib import Path STACK_ZONE = 27 BATTLEFIELD_ZONE = 28 def load_jsonl(p: Path): with p.open(encoding="utf-8") as f: for line in f: line = line.strip() if line: yield json.loads(line) def build_id2name(snapshot: Path) -> dict[int, str]: id2name: dict[int, str] = {} for c in json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]: id2name[c["mtga_id"]] = c["name"] for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"): for cid, m in (rec.get("cards") or {}).items(): id2name.setdefault(int(cid), m.get("name")) return id2name def build_decks(snapshot: Path, id2name: dict[int, str]) -> dict[str, tuple[set, set]]: """draft_id -> (nonland names in maindeck, land names in maindeck).""" land_names = set(_BASICS) for c in json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]: if any("Land" in t for t in (c.get("types") or [])): land_names.add(c["name"]) decks: dict[str, tuple[set, set]] = {} for deck in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"): aid = deck.get("aggregate_id") if not aid: continue nl, ld = set(), set() for e in deck.get("maindeck") or []: nm = id2name.get(e.get("mtga_id")) if not nm: continue (ld if nm in land_names else nl).add(nm) decks[aid] = (nl, ld) return decks _BASICS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"} def parse_replay(path: Path, me: int, id2name: dict[int, str]): """Return (casts Counter[name], land_plays Counter[name]).""" data = json.loads(gzip.open(path, "rb").read()) events = data.get("events") or [] me = data.get("seat_id") or me casts: Counter = Counter() land_plays: Counter = Counter() objs: dict[int, dict] = {} prev_stack: set[int] = set() seen_bf: set[int] = set() for e in events: gsm = e.get("gameStateMessage") or {} for o in gsm.get("gameObjects") or []: objs[o["instanceId"]] = o zones = {z["zoneId"]: z for z in gsm.get("zones") or []} st = zones.get(STACK_ZONE) if st is not None: now = set(st.get("objectInstanceIds") or []) for iid in now - prev_stack: o = objs.get(iid) or {} if o.get("controllerSeatId") != me or o.get("type") != "GameObjectType_Card": continue nm = id2name.get(o.get("grpId")) if nm: casts[nm] += 1 prev_stack = now bf = zones.get(BATTLEFIELD_ZONE) if bf is not None: for iid in bf.get("objectInstanceIds") or []: if iid in seen_bf: continue seen_bf.add(iid) o = objs.get(iid) or {} if o.get("controllerSeatId") == me and "CardType_Land" in (o.get("cardTypes") or []): nm = id2name.get(o.get("grpId")) if nm: land_plays[nm] += 1 return casts, land_plays def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--snapshot", required=True) ap.add_argument("--out", required=True) ap.add_argument("--force", action="store_true") args = ap.parse_args() snapshot = Path(args.snapshot) out = Path(args.out) dest = out / "cast_stats.json" if dest.exists() and not args.force: print(f"exists, skip: {dest} (use --force)") return 0 id2name = build_id2name(snapshot) decks = build_decks(snapshot, id2name) print(f"id2name={len(id2name)} decks={len(decks)}") rows = list(load_jsonl(snapshot / "replays/replay_index.jsonl")) stat = defaultdict(lambda: {"cast": 0, "cast_games": 0, "play": 0, "play_games": 0, "games": 0}) by_draft = defaultdict(lambda: {"games": 0, "cast": defaultdict(int), "cg": defaultdict(int), "play": defaultdict(int), "pg": defaultdict(int)}) done = skipped = 0 for i, r in enumerate(rows, 1): draft_id = r["draft_id"] deck = decks.get(draft_id) if not deck: skipped += 1 continue path = snapshot / "replays" / f"{r['history_path']}.json.gz" if not path.exists(): skipped += 1 continue try: casts, plays = parse_replay(path, 0, id2name) except Exception as e: # noqa: BLE001 print(f" !! {path.name}: {e}") skipped += 1 continue nl, ld = deck bd = by_draft[draft_id] bd["games"] += 1 for nm, n in casts.items(): bd["cast"][nm] += n bd["cg"][nm] += 1 for nm, n in plays.items(): bd["play"][nm] += n bd["pg"][nm] += 1 for nm in nl | ld: stat[nm]["games"] += 1 for nm, n in casts.items(): stat[nm]["cast"] += n stat[nm]["cast_games"] += 1 for nm, n in plays.items(): stat[nm]["play"] += n stat[nm]["play_games"] += 1 done += 1 if i % 200 == 0: print(f" {i}/{len(rows)} (parsed {done}, skipped {skipped})") out.mkdir(parents=True, exist_ok=True) dest.write_text(json.dumps(stat, ensure_ascii=False), encoding="utf-8") bd_dest = out / "cast_by_draft.json" bd_dest.write_text(json.dumps( {k: {"games": v["games"], "cast": dict(v["cast"]), "cg": dict(v["cg"]), "play": dict(v["play"]), "pg": dict(v["pg"])} for k, v in by_draft.items()}, ensure_ascii=False), encoding="utf-8") print(f"wrote {bd_dest} ({len(by_draft)} drafts)") print(f"wrote {len(stat)} cards from {done} replays (skipped {skipped}) -> {dest}") return 0 if __name__ == "__main__": raise SystemExit(main())