Files
mtga/scripts/render_matchups_html.py
fukunee 58446ec562 Add TRK set preview and refresh draft analysis
Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
2026-11-15 11:37:16 +08:00

140 lines
5.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Render the matchup matrix as an interactive HTML heatmap.
Output: value/<SNAPSHOT>/reports/matchups.html
* color-pair 10x10
* the 21 template clusters vs opponent pairs (click a column header to sort)
"""
from __future__ import annotations
import argparse
import sys
import html
import json
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _layout # noqa: E402
PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
AVG = 0.84
def esc(s):
return html.escape(str(s))
def color(wr, lo=0.70, hi=0.95):
if wr is None:
return "#1b1e27"
t = max(0.0, min(1.0, (wr - lo) / (hi - lo)))
hue = 8 + t * 130 # red -> green
return f"hsl({hue:.0f},58%,{28 + t * 16:.0f}%)"
def build(out_dir: Path, report_dir: Path) -> None:
_layout.SET = _layout.set_of(out_dir)
_mx = sorted((out_dir / "matchups").glob("*.PremierDraft.matrix.json"))
if not _mx:
raise SystemExit(f"no matchups/*.PremierDraft.matrix.json under {out_dir}")
m = json.loads(_mx[0].read_text(encoding="utf-8"))
index = json.loads((out_dir / "templates/_index.json").read_text(encoding="utf-8"))
def cell_table(title, keys, row_label, matrix, cols):
head = "".join(f'<th class="sortcol" data-i="{i}">{c}</th>' for i, c in enumerate(cols))
rows = ""
for k in keys:
row = matrix.get(k, {})
tds = ""
for i, opp in enumerate(cols):
c = row.get(opp)
if c and c.get("n"):
wr = c["winrate"]
tds += (f'<td class="cell" data-i="{i}" data-v="{wr}" '
f'style="background:{color(wr)}" title="n={c["n"]} CI={c.get("ci")}">'
f'{wr*100:.0f}%<span class="n">{c["n"]}</span></td>')
else:
tds += f'<td class="cell empty" data-i="{i}" data-v=""></td>'
rows += f'<tr><td class="name">{row_label(k)}</td>{tds}</tr>'
return f"""<h2>{title}</h2>
<table class="mx"><thead><tr><th>我方 \\ 对手</th>{head}</tr></thead><tbody>{rows}</tbody></table>"""
pair_tbl = cell_table("双色对 × 双色对", PAIRS, lambda k: k, m["color_pair_matrix"], PAIRS)
tpl_tbl = cell_table("子流派模板 × 对手双色(点列头排序)",
[s for s in index if not s.endswith("-Other")],
lambda s: f'<a href="templates/{esc(s)}.html">{esc(index[s]["name"])}</a>',
m["matrix"], PAIRS)
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{_layout.SET} 克制矩阵</title><style>{CSS}{_layout.CSS}</style></head><body>
{_layout.banner("matchups.html")}
<main class="wrap">
<h1>{_layout.SET} PremierDraft · 克制矩阵</h1>
<p class="note">数字 = 我方胜率(格子右下小字为样本 n,鼠标悬停看置信区间)。我方均为 7 胜奖杯牌表,
绝对胜率偏高,请看<b>相对差异</b>;绿=占优,红=吃亏。点表头/列头可排序。</p>
{pair_tbl}
{tpl_tbl}
<p class="note">来源:<code>matchups/{_layout.SET}.PremierDraft.matrix.json</code>,由 {m['games']} 局(data/17lands 的 event_details)统计。</p>
</main>
{_layout.footbanner("数字 = 我方胜率;格子右下小字为样本 n。我方均为 7 胜奖杯牌表,绝对胜率偏高,请看相对差异;绿 = 占优,红 = 吃亏。")}
<script>{JS}</script>
</body></html>"""
report_dir.mkdir(parents=True, exist_ok=True)
_layout.ensure_assets(report_dir)
(report_dir / "matchups.html").write_text(doc, encoding="utf-8")
print(f"wrote {report_dir / 'matchups.html'}")
CSS = """
*{box-sizing:border-box} body{font-family:system-ui,'Segoe UI',sans-serif;margin:0;padding:20px;background:#12141a;color:#e8e8ea}
a{color:#7cc4ff;text-decoration:none} h1{margin:.3em 0} h2{margin-top:1.2em}
.topbar{font-size:14px}.note{color:#9aa2b1;font-size:13px;max-width:1000px}
table.mx{border-collapse:separate;border-spacing:3px;font-size:12px;margin-top:8px}
table.mx th{background:#1b1e27;color:#c7cfdd;padding:5px 7px;border-radius:6px;font-weight:600;cursor:pointer;user-select:none}
table.mx th.sortcol::after{content:' ⇅';opacity:.35}
table.mx th.sortcol[data-dir=asc]::after{content:' ▲';opacity:1}
table.mx th.sortcol[data-dir=desc]::after{content:' ▼';opacity:1}
table.mx td{text-align:center;border-radius:6px;padding:5px 7px;min-width:52px;color:#fff}
table.mx td.name{background:#1b1e27;text-align:left;font-weight:600;white-space:nowrap;min-width:230px}
table.mx td.empty{background:#15181f}
td.cell .n{display:block;font-size:9px;opacity:.7}
"""
JS = """
document.querySelectorAll('table.mx th.sortcol').forEach(th => {
th.addEventListener('click', () => {
const tbl = th.closest('table');
const tb = tbl.tBodies[0];
const i = +th.dataset.i;
const dir = th.dataset.dir === 'asc' ? 'desc' : 'asc';
th.dataset.dir = dir;
tbl.querySelectorAll('th.sortcol').forEach(o => { if (o !== th) o.removeAttribute('data-dir'); });
const rows = [...tb.rows];
rows.sort((a, b) => {
const an = a.cells[i + 1].dataset.v, bn = b.cells[i + 1].dataset.v;
if (an === '' && bn === '') return 0;
if (an === '') return 1;
if (bn === '') return -1;
return dir === 'asc' ? parseFloat(an) - parseFloat(bn) : parseFloat(bn) - parseFloat(an);
});
rows.forEach(r => tb.appendChild(r));
});
});
"""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", required=True)
ap.add_argument("--report-dir", default=None)
a = ap.parse_args()
out = Path(a.out)
rd = Path(a.report_dir) if a.report_dir else out / "reports"
build(out, rd)
if __name__ == "__main__":
main()