Files
ai-chess/public/app.js
T
ai-chess 3a9ba2ea49 feat(ui): eval bar as two opposing bars (black on top, white on bottom)
The dark container now visually represents the black share; the
bottom-anchored white fill grows/shrinks with the eval. cp range ±800
maps to full bar. Mate is pinned at 100%/0% with #M text. The score
label flips to the top when black is ahead so it stays inside the
darker half.
2026-05-14 23:55:33 +03:00

276 lines
8.9 KiB
JavaScript

import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js";
const wsUrl = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`;
const $ = (id) => document.getElementById(id);
const STATE = {
game: null,
settings: null,
bindings: null, // {white: {agent, model, ...}, black: {...}}
viewPly: null, // null = live; otherwise integer ply (1-based)
};
window._STATE = STATE; // for debugging
const cg = Chessground($("board"), {
viewOnly: true,
fen: "start",
orientation: "white",
movable: { free: false },
drawable: { enabled: true, visible: true },
});
// ---------- agent labels ----------
function agentOfSide(side) {
return STATE.bindings?.[side]?.agent || "?";
}
function agentDisplay(side) {
const b = STATE.bindings?.[side];
if (!b) return side;
return `${b.agent} (${side})`;
}
// ---------- rendering ----------
function renderBoard() {
if (!STATE.game) return;
let fen = STATE.game.fen;
let lastMove = undefined;
const moves = (STATE.game.history || []).filter(h => h.san);
if (STATE.viewPly !== null && STATE.viewPly >= 0) {
const c = new Chess();
for (let i = 0; i < STATE.viewPly; i++) c.move(moves[i].san);
fen = c.fen();
if (STATE.viewPly > 0) {
const m = moves[STATE.viewPly - 1];
const uci = m.uci || "";
if (uci.length >= 4) lastMove = [uci.slice(0, 2), uci.slice(2, 4)];
}
} else if (moves.length) {
const m = moves[moves.length - 1];
const uci = m.uci || "";
if (uci.length >= 4) lastMove = [uci.slice(0, 2), uci.slice(2, 4)];
}
cg.set({ fen, lastMove });
$("live-btn").hidden = STATE.viewPly === null;
}
function renderChat() {
const list = $("chat-list");
list.innerHTML = "";
const moves = (STATE.game?.history || []).filter(h => h.san);
const counter = $("chat-counter");
counter.textContent = moves.length ? `${moves.length} moves` : "";
moves.forEach((h, i) => {
const ply = i + 1;
const side = h.side; // "white" | "black"
const div = document.createElement("div");
div.className = `bubble bubble-${side}`;
if (STATE.viewPly === ply) div.classList.add("active");
const moveNum = Math.floor(i / 2) + 1;
const moveLabel = side === "white" ? `${moveNum}.` : `${moveNum}...`;
const meta = document.createElement("div");
meta.className = "bubble-meta";
const left = document.createElement("span");
left.textContent = agentDisplay(side);
const right = document.createElement("span");
right.className = "bubble-san";
right.textContent = `${moveLabel} ${h.san}`;
meta.append(left, right);
const body = document.createElement("div");
body.className = "bubble-body";
if (h.comment) body.textContent = h.comment;
else { body.classList.add("bubble-empty"); body.textContent = "(без реплики)"; }
div.append(meta, body);
div.addEventListener("click", () => setView(ply));
list.appendChild(div);
});
// auto-scroll to bottom if at live
if (STATE.viewPly === null) list.scrollTop = list.scrollHeight;
}
function renderHistory() {
const list = $("history-list");
list.innerHTML = "";
const moves = (STATE.game?.history || []).filter(h => h.san);
let row = 0;
for (let i = 0; i < moves.length; i += 2) {
row++;
const num = document.createElement("li");
num.className = "ply-num";
num.textContent = `${row}.`;
list.appendChild(num);
const w = document.createElement("li");
w.textContent = moves[i]?.san || "";
if (STATE.viewPly === i + 1) w.classList.add("active");
w.addEventListener("click", () => setView(i + 1));
list.appendChild(w);
const b = document.createElement("li");
b.textContent = moves[i + 1]?.san || "";
if (moves[i + 1]) {
if (STATE.viewPly === i + 2) b.classList.add("active");
b.addEventListener("click", () => setView(i + 2));
}
list.appendChild(b);
}
}
function renderStatus() {
const g = STATE.game;
if (!g) { $("status-line").textContent = "no game"; return; }
const r = g.status?.result;
if (r) {
$("status-line").textContent = `game over: ${r} (${g.status.termination})`;
} else {
$("status-line").textContent = `${agentDisplay(g.side_to_move)} to move`;
}
}
function applyEval(e) {
const cp = e.cp, mate = e.mate;
const col = $("eval-col"), bar = $("eval-fill"), txt = $("eval-text");
// pct = % of the bar occupied by WHITE (bottom-anchored).
// 50 = even; >50 = white ahead; <50 = black ahead.
let pct = 50;
if (mate != null) {
pct = mate > 0 ? 100 : 0;
txt.textContent = (mate > 0 ? "+M" : "-M") + Math.abs(mate);
} else if (cp != null) {
// map cp to percentage: ±800cp = full bar. Capped.
pct = Math.max(2, Math.min(98, 50 + cp / 16));
const v = (cp / 100);
txt.textContent = (v > 0 ? "+" : "") + v.toFixed(2);
} else {
txt.textContent = "—";
}
bar.style.height = `${pct}%`;
col.classList.toggle("advantage-black", pct < 50);
if (e.best_uci && e.best_uci.length >= 4) {
const from = e.best_uci.slice(0, 2), to = e.best_uci.slice(2, 4);
cg.setShapes([{ orig: from, dest: to, brush: "green" }]);
}
if (e.pv && e.pv.length) {
$("sf-pv").textContent = "pv: " + e.pv.slice(0, 6).join(" ");
}
}
function setView(ply) {
STATE.viewPly = ply;
renderBoard(); renderChat(); renderHistory();
}
function goLive() {
STATE.viewPly = null;
renderBoard(); renderChat(); renderHistory();
}
function log(line) {
const t = $("log-text");
t.textContent += line + "\n";
// trim to last 200 lines
const lines = t.textContent.split("\n");
if (lines.length > 200) t.textContent = lines.slice(-200).join("\n");
t.scrollTop = t.scrollHeight;
}
function applySnapshot(s) {
STATE.game = s.game;
STATE.settings = s.settings;
STATE.bindings = s.bindings;
STATE.viewPly = null;
renderBoard(); renderChat(); renderHistory(); renderStatus();
}
function connect() {
const ws = new WebSocket(wsUrl);
ws.addEventListener("message", (m) => {
const ev = JSON.parse(m.data);
if (ev.type === "snapshot") return applySnapshot(ev);
if (ev.type === "new_game") {
STATE.game = ev.game;
STATE.viewPly = null;
renderBoard(); renderChat(); renderHistory(); renderStatus();
log(`new game: ${ev.game?.id || "?"}`);
return;
}
if (ev.type === "move") {
if (!STATE.game) return;
STATE.game.history = ev.history;
STATE.game.fen = ev.fen;
STATE.game.status = ev.status;
if (!ev.status?.result) {
STATE.game.side_to_move = ev.side === "white" ? "black" : "white";
}
// stay live unless user clicked back
renderBoard(); renderChat(); renderHistory(); renderStatus();
log(`${ev.side} ${ev.san} «${ev.comment || ""}»`);
return;
}
if (ev.type === "eval") return applyEval(ev);
if (ev.type === "game_over") {
if (STATE.game?.status) {
STATE.game.status.result = ev.result;
STATE.game.status.termination = ev.termination;
}
renderStatus();
log(`game over: ${ev.result} (${ev.termination})`);
return;
}
if (ev.type === "settings") { STATE.settings = ev.settings; return; }
// term_chunk + others — ignore
});
ws.addEventListener("close", () => setTimeout(connect, 1000));
ws.addEventListener("error", () => {});
}
connect();
// ---------- controls ----------
$("live-btn").addEventListener("click", goLive);
$("new-game").addEventListener("click", async () => {
await fetch("/api/new-game", { method: "POST" });
});
const dialog = $("settings-dialog");
$("settings-btn").addEventListener("click", async () => {
const s = STATE.settings || (await (await fetch("/api/settings")).json());
dialog.querySelector('[name="allow_draw_resign"]').checked = s.allow_draw_resign;
dialog.querySelector('[name="allow_illegal_moves"]').checked = s.allow_illegal_moves;
dialog.querySelector('[name="stockfish_depth"]').value = s.stockfish_depth;
dialog.showModal();
});
$("settings-save").addEventListener("click", async (e) => {
e.preventDefault();
const form = $("settings-form");
const patch = {
allow_draw_resign: form.allow_draw_resign.checked,
allow_illegal_moves: form.allow_illegal_moves.checked,
stockfish_depth: parseInt(form.stockfish_depth.value, 10),
};
await fetch("/api/settings", {
method: "POST",
headers: {"content-type": "application/json"},
body: JSON.stringify(patch),
});
dialog.close();
});
// Keyboard nav: ← prev ply, → next ply, Space = live
window.addEventListener("keydown", (e) => {
const moves = (STATE.game?.history || []).filter(h => h.san);
if (e.key === "ArrowLeft") {
const cur = STATE.viewPly === null ? moves.length : STATE.viewPly;
if (cur > 0) setView(cur - 1);
} else if (e.key === "ArrowRight") {
const cur = STATE.viewPly === null ? moves.length : STATE.viewPly;
if (cur < moves.length) {
if (cur + 1 === moves.length) goLive();
else setView(cur + 1);
}
} else if (e.key === " ") {
e.preventDefault(); goLive();
}
});