67 lines
2.4 KiB
JavaScript
67 lines
2.4 KiB
JavaScript
import { Chess } from "/static/vendor/chess.min.js";
|
|
import { Chessground } from "/static/vendor/chessground.min.js";
|
|
|
|
const $ = (id) => document.getElementById(id);
|
|
const tbody = document.querySelector("#games-table tbody");
|
|
|
|
let cg = null, chess = null, history = [], ply = 0;
|
|
|
|
function renderReplay() {
|
|
chess = new Chess();
|
|
for (let i = 0; i < ply; i++) chess.move(history[i].san);
|
|
cg.set({ fen: chess.fen() });
|
|
$("ply").textContent = `ply ${ply}/${history.length}`;
|
|
const ol = $("replay-history");
|
|
ol.innerHTML = "";
|
|
history.forEach((h, i) => {
|
|
const li = document.createElement("li");
|
|
li.textContent = h.san + (h.comment ? " «" + h.comment + "»" : "");
|
|
if (i === ply - 1) li.style.background = "#444";
|
|
ol.appendChild(li);
|
|
});
|
|
}
|
|
|
|
async function openReplay(id) {
|
|
const data = await (await fetch(`/api/games/${id}`)).json();
|
|
const meta = data.meta;
|
|
const w = meta.agents?.white || {};
|
|
const b = meta.agents?.black || {};
|
|
$("replay-title").textContent =
|
|
`${id} — ${w.agent || "?"}/${w.model || "?"} vs ${b.agent || "?"}/${b.model || "?"} → ${meta.result || "*"}`;
|
|
chess = new Chess();
|
|
chess.load_pgn(data.pgn);
|
|
// chess.js 0.13.4: history({verbose:true}) returns [{san, ...}, ...]
|
|
history = chess.history({ verbose: true }).map(m => ({ san: m.san, comment: null }));
|
|
ply = 0;
|
|
if (!cg) cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
|
|
$("replay-wrap").style.display = "block";
|
|
renderReplay();
|
|
}
|
|
|
|
async function main() {
|
|
const games = await (await fetch("/api/games")).json();
|
|
for (const g of games) {
|
|
const w = g.agents?.white || {};
|
|
const b = g.agents?.black || {};
|
|
const tr = document.createElement("tr");
|
|
tr.innerHTML = `
|
|
<td><a href="#" data-id="${g.id}">${(g.id || "?").slice(0, 10)}…</a></td>
|
|
<td>${w.agent || "?"}/${w.model || "?"}</td>
|
|
<td>${b.agent || "?"}/${b.model || "?"}</td>
|
|
<td>${g.result || "*"}</td>
|
|
<td>${g.termination || ""}</td>
|
|
<td>${g.moves_count ?? 0}</td>
|
|
<td><a href="/api/games/${g.id}/pgn">pgn</a></td>
|
|
`;
|
|
tr.querySelector("a[data-id]").addEventListener("click", (e) => {
|
|
e.preventDefault();
|
|
openReplay(g.id);
|
|
});
|
|
tbody.appendChild(tr);
|
|
}
|
|
}
|
|
main();
|
|
|
|
$("prev").addEventListener("click", () => { if (ply > 0) { ply--; renderReplay(); } });
|
|
$("next").addEventListener("click", () => { if (ply < history.length) { ply++; renderReplay(); } });
|