Spaces:
Running
Running
Download app.js from vynly/cael-chess: direct link, hf CLI and curl.
- Browser
- Download file 22.2 kB
-
https://huggingface.co/spaces/vynly/cael-chess/resolve/main/app.js
- Command line
-
hf download hf://spaces/vynly/cael-chess/app.js
-
curl -L -o app.js https://huggingface.co/spaces/vynly/cael-chess/resolve/main/app.js
22.2 kB
| // CAEL Chess static page: rules, SAN, opening books, local game records. | |
| // The engine itself runs in a Web Worker (engine.js). | |
| ; | |
| // pieces drawn as vector shapes (Unicode chess symbols render as emoji on some devices) | |
| const BASE = "M24 88h52a5 5 0 0 0 5-5v-1a5 5 0 0 0-5-5H24a5 5 0 0 0-5 5v1a5 5 0 0 0 5 5z"; | |
| const SHAPE = { | |
| P: "M50 17a11 11 0 0 0-7 19.5c-4 2-6.5 5-6.5 7.5h27c0-2.5-2.5-5.5-6.5-7.5A11 11 0 0 0 50 17zM40 48c0 10-5 19-12 29h44c-7-10-12-19-12-29z", | |
| R: "M27 16h10v8h7v-8h12v8h7v-8h10v19l-7 5v24l6 13H28l6-13V40l-7-5z", | |
| N: "M31 77c1-14 8-21 16-27-7 1-12 4-16 8-4 2-8 0-8-4 0-3 3-6 6-9 5-5 7-12 13-17l3-9 5 7c14 2 25 14 26 33 1 7 0 13-1 18z", | |
| B: "M50 11a4.5 4.5 0 1 0 0 9a4.5 4.5 0 1 0 0-9zM50 21c-12 9-16 19-13 27 2 4 6 6 13 6s11-2 13-6c3-8-1-18-13-27zM41 58c-1 7-6 13-11 19h40c-5-6-10-12-11-19z", | |
| Q: "M19 27a5 5 0 1 0 0.1 0zM35 18a5 5 0 1 0 0.1 0zM50 14a5 5 0 1 0 0.1 0zM65 18a5 5 0 1 0 0.1 0zM81 27a5 5 0 1 0 0.1 0zM21 33l9 30h40l9-30-14 17-5-27-10 25-10-25-5 27zM30 67l-3 10h46l-3-10z", | |
| K: "M47 8h6v7h7v6h-7v8h-6v-8h-7v-6h7zM50 31c-6 0-10 4-10 9 0 3 1 6 3 8-9-6-24-3-24 9 0 8 7 12 13 16h36c6-4 13-8 13-16 0-12-15-15-24-9 2-2 3-5 3-8 0-5-4-9-10-9zM30 74l-2 3h44l-2-3z", | |
| }; | |
| const DETAIL = { // inner lines that make the shapes read as pieces | |
| R: "M34 40h32M34 64h32", N: "M58 33a2.6 2.6 0 1 0 0.1 0z", B: "M50 31v13M44 37h12M38 58h24", | |
| Q: "M30 63h40", K: "M33 66h34M50 48v18", P: "M38 48h24", | |
| }; | |
| function pieceSVG(letter, white) { | |
| const fill = white ? "url(#gw)" : "url(#gb)", line = white ? "#3b342a" : "#0d0c0a", det = white ? "#3b342a" : "#c9bfae"; | |
| return `<svg viewBox="0 0 100 100" aria-hidden="true"><defs> | |
| <linearGradient id="gw" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#e2dccf"/></linearGradient> | |
| <linearGradient id="gb" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#4a443b"/><stop offset="1" stop-color="#16140f"/></linearGradient></defs> | |
| <g fill="${fill}" stroke="${line}" stroke-width="3" stroke-linejoin="round"><path d="${SHAPE[letter]}"/><path d="${BASE}"/></g> | |
| <path d="${DETAIL[letter]}" fill="${letter === "N" ? det : "none"}" stroke="${det}" stroke-width="2.4" stroke-linecap="round"/></svg>`; | |
| } | |
| const START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; | |
| const $ = id => document.getElementById(id); | |
| const RULES = new Engine(new Array(806).fill(0), 10); | |
| const MAX_MS = 29500; // no CAEL turn may take longer than 30 seconds | |
| const worker = new Worker("engine.js?v=9"); | |
| // Lazy SMP: extra workers search the same position and share one hash table (needs a cross-origin | |
| // isolated page for SharedArrayBuffer; otherwise CAEL uses one worker) | |
| const SMP = typeof SharedArrayBuffer !== "undefined" && self.crossOriginIsolated === true; | |
| const NWORK = SMP ? Math.max(1, Math.min(8, (navigator.hardwareConcurrency || 2) - 1)) : 1; | |
| const helpers = []; | |
| let stopFlag = null; | |
| if (NWORK > 1) { | |
| const n = 1 << 20, sab = (bytes) => new SharedArrayBuffer(bytes); | |
| const shared = { ttk: sab(4 * n), ttc: sab(4 * n), ttm: sab(4 * n), ttd: sab(n), ttf: sab(n), tts: sab(2 * n), stop: sab(4) }; | |
| stopFlag = new Int32Array(shared.stop); | |
| worker.postMessage({ cmd: "shared", shared }); | |
| for (let i = 1; i < NWORK; i++) { const h = new Worker("engine.js?v=9"); h.postMessage({ cmd: "shared", shared }); helpers.push(h); } | |
| } | |
| let S = { moves: [], human: "w", flip: false, sel: null, st: null, busy: false, saved: false, started: null }; | |
| let PARAMS = {}, BOOKS = {}, POLY = null, STYLES = [], reqId = 0; | |
| // ------------------------------------------------------------ loading | |
| async function getJSON(path) { const r = await fetch(path); if (!r.ok) throw new Error(path); return r.json(); } | |
| async function params(style) { | |
| const key = style || "default"; | |
| if (!PARAMS[key]) { | |
| try { PARAMS[key] = (await getJSON(style ? `data/params_${style}.json` : "data/params.json")).params; } | |
| catch (e) { PARAMS[key] = await params(""); } | |
| } | |
| return PARAMS[key]; | |
| } | |
| async function book(name) { | |
| if (!(name in BOOKS)) { try { BOOKS[name] = await getJSON(`data/${name}.json`); } catch (e) { BOOKS[name] = null; } } | |
| return BOOKS[name]; | |
| } | |
| // ------------------------------------------------------------ rules | |
| function setup(moves) { RULES.setFen(START); for (const u of moves) RULES.pushUci(u); } | |
| const SQN = s => { const x = (Math.floor(s / 10) - 2) * 8 + (s % 10 - 1); return "abcdefgh"[x & 7] + ((x >> 3) + 1); }; | |
| function sanOf(m) { // RULES must be at the position before m | |
| const b = RULES.b, fr = m & 127, to = (m >> 7) & 127, pr = (m >> 14) & 7, fl = (m >> 17) & 3, p = Math.abs(b[fr]); | |
| let s; | |
| if (fl === 3) s = (to % 10 === 7) ? "O-O" : "O-O-O"; | |
| else { | |
| const cap = b[to] !== 0 || fl === 2; | |
| if (p === 1) s = (cap ? SQN(fr)[0] + "x" : "") + SQN(to) + (pr ? "=" + "NBRQ"[pr - 2] : ""); | |
| else { | |
| const others = RULES.legal().filter(o => o !== m && ((o >> 7) & 127) === to && Math.abs(b[o & 127]) === p); | |
| let dis = ""; | |
| if (others.length) { | |
| const f = SQN(fr)[0], r = SQN(fr)[1]; | |
| if (!others.some(o => SQN(o & 127)[0] === f)) dis = f; | |
| else if (!others.some(o => SQN(o & 127)[1] === r)) dis = r; | |
| else dis = f + r; | |
| } | |
| s = " PNBRQK"[p] + dis + (cap ? "x" : "") + SQN(to); | |
| } | |
| } | |
| RULES.make(m); | |
| const side = RULES.st[0], chk = RULES.attacked(RULES.kingSq(side), -side); | |
| if (chk) s += RULES.legal().length ? "+" : "#"; | |
| RULES.unmake(); | |
| return s; | |
| } | |
| function state(moves) { | |
| RULES.setFen(START); | |
| const san = []; | |
| for (const u of moves) { const m = RULES.legal().find(x => Engine.uci(x) === u); san.push(sanOf(m)); RULES.make(m); } | |
| const st = RULES.st, side = st[0], legal = RULES.legal(), chk = RULES.attacked(RULES.kingSq(side), -side); | |
| let status = "ongoing", result = null; | |
| if (!legal.length) { status = chk ? "checkmate" : "stalemate"; result = chk ? (side === 1 ? "0-1" : "1-0") : "1/2-1/2"; } | |
| else if (st[3] >= 100) { status = "fifty moves"; result = "1/2-1/2"; } | |
| else { | |
| const i = st[6]; let reps = 0; | |
| for (let k = i; k >= Math.max(0, i - st[3]); k -= 2) if (RULES.hl[k] === RULES.hl[i] && RULES.hh_[k] === RULES.hh_[i]) reps++; | |
| if (reps >= 3) { status = "threefold repetition"; result = "1/2-1/2"; } | |
| else { | |
| let pawnsOrMajors = false, wmin = 0, bmin = 0; | |
| for (let s = 21; s < 99; s++) { const p = RULES.b[s]; if (p === 99 || p === 0) continue; const t = Math.abs(p); | |
| if (t === 1 || t === 4 || t === 5) pawnsOrMajors = true; else if (t === 2 || t === 3) { if (p > 0) wmin++; else bmin++; } } | |
| if (!pawnsOrMajors && wmin <= 1 && bmin <= 1) { status = "insufficient material"; result = "1/2-1/2"; } | |
| } | |
| } | |
| const board = {}; | |
| for (let s = 21; s < 99; s++) { const p = RULES.b[s]; if (p !== 0 && p !== 99) board[SQN(s)] = p > 0 ? " PNBRQK"[p] : " pnbrqk"[-p]; } | |
| return { board, turn: side === 1 ? "w" : "b", legal: legal.map(Engine.uci), san, status, result, | |
| check: chk ? SQN(RULES.kingSq(side)) : null, last: moves.length ? moves[moves.length - 1] : null, hash: polyHash() }; | |
| } | |
| // ------------------------------------------------------------ polyglot book hash | |
| function polyHash() { | |
| if (!POLY) return null; | |
| const b = RULES.b, st = RULES.st; let h = 0n; | |
| for (let s = 21; s < 99; s++) { | |
| const p = b[s]; if (p === 0 || p === 99) continue; | |
| const x = (Math.floor(s / 10) - 2) * 8 + (s % 10 - 1), kind = (Math.abs(p) - 1) * 2 + (p > 0 ? 1 : 0); | |
| h ^= POLY[64 * kind + 8 * (x >> 3) + (x & 7)]; | |
| } | |
| if (st[1] & 1) h ^= POLY[768]; if (st[1] & 2) h ^= POLY[769]; if (st[1] & 4) h ^= POLY[770]; if (st[1] & 8) h ^= POLY[771]; | |
| if (st[2]) { const t = st[2], can = st[0] === 1 ? (b[t - 9] === 1 || b[t - 11] === 1) : (b[t + 9] === -1 || b[t + 11] === -1); | |
| if (can) h ^= POLY[772 + (t % 10 - 1)]; } | |
| if (st[0] === 1) h ^= POLY[780]; | |
| return h.toString(); | |
| } | |
| function pickBook(entry, legal) { | |
| const best = Math.max(...entry.map(e => e[1])); | |
| const good = entry.filter(e => e[1] >= Math.max(3, best * 0.15) && e[2] >= 0.40 && legal.includes(e[0])); | |
| if (!good.length) return null; | |
| const w = good.map(e => e[1] * (0.5 + e[2])), tot = w.reduce((a, c) => a + c, 0); | |
| let x = Math.random() * tot; | |
| for (let i = 0; i < good.length; i++) { x -= w[i]; if (x <= 0) return good[i][0]; } | |
| return good[good.length - 1][0]; | |
| } | |
| async function bookMove(st) { | |
| if (!$("book").checked || S.moves.length >= 40) return null; | |
| const style = $("style").value; | |
| for (const name of [style ? "book_" + style : null, "book"]) { | |
| if (!name) continue; | |
| const bk = await book(name); | |
| if (bk && bk[st.hash]) { const mv = pickBook(bk[st.hash], st.legal); if (mv) return mv; } | |
| } | |
| return null; | |
| } | |
| // ------------------------------------------------------------ engine calls | |
| async function think(play) { | |
| const st = state(S.moves); | |
| if (st.status !== "ongoing") return null; | |
| if (play || true) { | |
| const bm = await bookMove(st); | |
| if (bm) return { move: bm, source: "book", score: null, pv: [bm] }; | |
| } | |
| const style = $("style").value, P = await params(style), id = ++reqId; | |
| const movetime = Math.min(+$("think").value, MAX_MS), ply = S.moves.length; | |
| const msg = { fen: START, moves: S.moves, movetime, params: P, paramsKey: style || "default" }; | |
| if (helpers.length && st.legal.length > 1) { | |
| Atomics.store(stopFlag, 0, 0); | |
| helpers.forEach((h, k) => h.postMessage({ cmd: "helper", id, k, ...msg })); | |
| } | |
| return new Promise(resolve => { | |
| worker.onmessage = ev => { | |
| const m = ev.data; if (m.id !== id) return; | |
| if (m.type === "info") showInfo({ ...m.info, workers: NWORK }, ply); | |
| else { if (stopFlag) Atomics.store(stopFlag, 0, 1); resolve(m.result && { ...m.result, workers: NWORK }); } // stop the helpers | |
| }; | |
| worker.postMessage({ cmd: "go", id, ...msg }); | |
| }); | |
| } | |
| // ------------------------------------------------------------ rendering | |
| function render() { | |
| const st = S.st, el = $("board"); el.innerHTML = ""; | |
| const targets = S.sel ? st.legal.filter(m => m.startsWith(S.sel)).map(m => m.slice(2, 4)) : []; | |
| for (let i = 0; i < 64; i++) { | |
| const r = S.flip ? i >> 3 : 7 - (i >> 3), f = S.flip ? 7 - (i & 7) : i & 7, sq = "abcdefgh"[f] + (r + 1); | |
| const d = document.createElement("div"); | |
| d.className = "sq " + ((r + f) % 2 ? "l" : "d"); | |
| if (st.last && (st.last.slice(0, 2) === sq || st.last.slice(2, 4) === sq)) d.classList.add("last"); | |
| if (S.sel === sq) d.classList.add("sel"); | |
| if (st.check === sq) d.classList.add("chk"); | |
| const p = st.board[sq]; | |
| if (p) { const s = document.createElement("span"); s.className = "pc " + (p === p.toUpperCase() ? "w" : "b"); s.innerHTML = pieceSVG(p.toUpperCase(), p === p.toUpperCase()); d.appendChild(s); } | |
| if (targets.includes(sq)) { const m = document.createElement("i"); m.className = p ? "ring" : "dot"; d.appendChild(m); } | |
| if (S.flip ? r === 7 : r === 0) { const c = document.createElement("span"); c.className = "coord f"; c.textContent = "abcdefgh"[f]; d.appendChild(c); } | |
| if (S.flip ? f === 7 : f === 0) { const c = document.createElement("span"); c.className = "coord r"; c.textContent = r + 1; d.appendChild(c); } | |
| d.onclick = () => clickSq(sq); | |
| el.appendChild(d); | |
| } | |
| const mv = $("moves"); mv.innerHTML = ""; | |
| st.san.forEach((s, i) => { if (i % 2 === 0) { const n = document.createElement("span"); n.className = "n"; n.textContent = (i / 2 + 1) + "."; mv.appendChild(n); } | |
| const x = document.createElement("span"); x.textContent = s; mv.appendChild(x); }); | |
| if (st.san.length % 2 === 1) mv.appendChild(document.createElement("span")); | |
| mv.scrollTop = mv.scrollHeight; | |
| if (st.status !== "ongoing") $("status").textContent = "Game over: " + st.status + (st.result ? " (" + st.result + ")" : ""); | |
| else if (S.busy) $("status").textContent = "CAEL is thinking…"; | |
| else if (S.saved) $("status").textContent = "Game ended. Start a new game when you like."; | |
| else $("status").textContent = st.turn === S.human ? (st.check ? "Check! " : "") + "Your move." : "CAEL to move."; | |
| } | |
| function clickSq(sq) { | |
| if (S.busy || S.saved || S.st.status !== "ongoing" || S.st.turn !== S.human) return; | |
| const p = S.st.board[sq], mine = p && ((p === p.toUpperCase()) === (S.human === "w")); | |
| if (S.sel) { | |
| const c = S.st.legal.filter(m => m.startsWith(S.sel + sq)); | |
| if (c.length === 1) { play(c[0]); return; } | |
| if (c.length > 1) { askPromo(S.sel + sq); return; } | |
| } | |
| S.sel = mine ? sq : null; render(); | |
| } | |
| function askPromo(base) { | |
| const box = $("promo"), inner = box.firstElementChild; inner.innerHTML = ""; | |
| for (const [k, g] of [["q", "Q"], ["r", "R"], ["b", "B"], ["n", "N"]]) { | |
| const b = document.createElement("button"); b.innerHTML = pieceSVG(g, S.human === "w"); b.className = "promo-pc"; b.title = { Q: "Queen", R: "Rook", B: "Bishop", N: "Knight" }[g]; | |
| b.onclick = () => { box.style.display = "none"; play(base + k); }; inner.appendChild(b); | |
| } | |
| box.style.display = "flex"; | |
| } | |
| function showInfo(e, plyCount) { | |
| if (!e || !e.source) { for (const id of ["src", "ev", "dp", "nd", "nps"]) $(id).textContent = "-"; $("pv").textContent = ""; $("evalfill").style.height = "50%"; return; } | |
| const style = $("style").value; | |
| $("src").textContent = e.source === "book" ? (style ? "opening book (" + $("style").selectedOptions[0].textContent + ", then masters)" : "opening book (master games)") : "search"; | |
| const whiteToMove = plyCount % 2 === 0; | |
| let txt = "-", frac = .5; | |
| if (e.mate !== undefined) { const m = whiteToMove ? e.mate : -e.mate; txt = (m > 0 ? "White" : "Black") + " mates in " + Math.abs(e.mate); frac = m > 0 ? 1 : 0; } | |
| else if (e.score !== null && e.score !== undefined) { const w = whiteToMove ? e.score : -e.score; txt = (w / 100).toFixed(2) + " (White's view)"; frac = 1 / (1 + Math.exp(-w / 250)); } | |
| $("ev").textContent = txt; $("evalfill").style.height = (frac * 100) + "%"; | |
| $("dp").textContent = e.depth ? e.depth + (e.seldepth ? " / " + e.seldepth : "") : "-"; | |
| $("nd").textContent = e.nodes ? e.nodes.toLocaleString() : "-"; | |
| $("nps").textContent = e.nps ? Math.round(e.nps / 1000).toLocaleString() + "k nodes/s" + (e.workers > 1 ? " (main thread; " + e.workers + " cores searching)" : "") : "-"; | |
| if (e.pv && e.pv.length) { | |
| setup(S.moves.slice(0, plyCount)); const sans = []; | |
| for (const u of e.pv) { const m = RULES.legal().find(x => Engine.uci(x) === u); if (!m) break; sans.push(sanOf(m)); RULES.make(m); } | |
| $("pv").textContent = "Line: " + sans.join(" "); | |
| } else $("pv").textContent = ""; | |
| } | |
| // ------------------------------------------------------------ game flow | |
| async function play(u) { | |
| S.sel = null; S.moves.push(u); S.st = state(S.moves); render(); | |
| if (S.st.status === "ongoing") engineMove(); else finish(false); | |
| } | |
| async function engineMove() { | |
| S.busy = true; render(); | |
| const ply = S.moves.length, r = await think(true); | |
| S.busy = false; | |
| if (r && r.move) { S.moves.push(r.move); showInfo(r, ply); } | |
| S.st = state(S.moves); render(); | |
| if (S.st.status !== "ongoing") finish(false); | |
| } | |
| async function analyse(label) { | |
| if (S.busy || S.saved || S.st.status !== "ongoing") return; | |
| S.busy = true; render(); | |
| const ply = S.moves.length, r = await think(false); | |
| S.busy = false; render(); | |
| if (r && r.move) { showInfo(r, ply); S.sel = r.move.slice(0, 2); render(); setup(S.moves); | |
| const m = RULES.legal().find(x => Engine.uci(x) === r.move); $("status").textContent = label + sanOf(m); } | |
| } | |
| // ------------------------------------------------------------ rank all legal moves | |
| async function rankAll() { | |
| if (S.busy || S.st.status !== "ongoing") return; | |
| S.busy = true; render(); | |
| const style = $("style").value, P = await params(style), id = ++reqId, ply = S.moves.length; | |
| setup(S.moves); | |
| const sanMap = {}; | |
| for (const m of RULES.legal()) sanMap[Engine.uci(m)] = sanOf(m); | |
| const whiteToMove = ply % 2 === 0; | |
| const show = info => { | |
| $("rankCard").style.display = ""; | |
| $("rankHead").textContent = `${info.legal} legal moves · every move searched to depth ${info.depth} · scores in pawns, ${whiteToMove ? "White" : "Black"} to move`; | |
| $("rankList").innerHTML = info.ranked.map(([u, sc], i) => { | |
| const txt = Math.abs(sc) > 30000 - 200 ? (sc > 0 ? "mates" : "gets mated") : (sc / 100).toFixed(2); | |
| return `<span style="color:var(--muted)">${i + 1}.</span><span${i === 0 ? ' style="font-weight:600"' : ""}>${esc(sanMap[u] || u)}</span><span>${txt}</span>`; | |
| }).join(""); | |
| }; | |
| const r = await new Promise(resolve => { | |
| worker.onmessage = ev => { const m = ev.data; if (m.id !== id) return; if (m.type === "rankinfo") show(m.info); else if (m.type === "rankdone") resolve(m.result); }; | |
| worker.postMessage({ cmd: "rank", id, fen: START, moves: S.moves, movetime: Math.min(Math.max(2000, +$("think").value * 2), MAX_MS), params: P, paramsKey: style || "default" }); | |
| }); | |
| S.busy = false; render(); | |
| if (r && r.ranked.length) { show(r); S.sel = r.ranked[0][0].slice(0, 2); render(); $("status").textContent = `Best of ${r.legal}: ${sanMap[r.ranked[0][0]]}`; } | |
| } | |
| // ------------------------------------------------------------ local records | |
| function loadGames() { try { return JSON.parse(localStorage.getItem("cael_games") || "[]"); } catch (e) { return []; } } | |
| function saveGames(g) { try { localStorage.setItem("cael_games", JSON.stringify(g)); } catch (e) { } } | |
| function finish(resigned) { | |
| if (S.saved || S.moves.length < 2) return; | |
| const st = state(S.moves); | |
| let result = st.result, term = st.status; | |
| if (!result) { if (resigned) { result = S.human === "w" ? "0-1" : "1-0"; term = "resigned"; } else { result = "*"; term = "unfinished"; } } | |
| const games = loadGames(); | |
| games.push({ date: new Date().toISOString(), name: $("nick").value.trim() || "You", human: S.human, | |
| style: $("style").value, styleName: $("style").selectedOptions[0].textContent, think: +$("think").value, | |
| moves: S.moves.slice(), san: st.san, result, termination: term }); | |
| saveGames(games); | |
| S.saved = true; render(); loadStats(); | |
| } | |
| function pgnOf(g) { | |
| const cael = "CAEL (" + (g.styleName || "master games") + ")", d = g.date.slice(0, 10).replace(/-/g, "."); | |
| let s = `[Event "CAEL chess"]\n[Site "Hugging Face Space"]\n[Date "${d}"]\n[White "${g.human === "w" ? g.name : cael}"]\n[Black "${g.human === "w" ? cael : g.name}"]\n[Result "${g.result}"]\n[Termination "${g.termination}"]\n\n`; | |
| g.san.forEach((m, i) => { s += (i % 2 === 0 ? (i / 2 + 1) + ". " : "") + m + " "; }); | |
| return s + g.result + "\n"; | |
| } | |
| function loadStats() { | |
| const games = loadGames(), done = games.filter(g => g.result !== "*"); | |
| let w = 0, d = 0, l = 0; | |
| for (const g of done) { const youWin = (g.result === "1-0") === (g.human === "w"); if (g.result === "1/2-1/2") d++; else if (youWin) w++; else l++; } | |
| $("stTotal").textContent = games.length; | |
| $("stScore").textContent = done.length ? `you ${w} W / ${d} D / ${l} L` : "-"; | |
| const by = {}; | |
| for (const g of done) { const k = g.styleName || "CAEL"; by[k] = by[k] || [0, 0, 0]; | |
| const youWin = (g.result === "1-0") === (g.human === "w"); by[k][g.result === "1/2-1/2" ? 1 : youWin ? 0 : 2]++; } | |
| $("stStyles").innerHTML = Object.entries(by).map(([k, v]) => `<div>vs ${esc(k)}: ${v[0]} W / ${v[1]} D / ${v[2]} L</div>`).join(""); | |
| $("stRecent").innerHTML = games.slice(-8).reverse().map(g => `<div>${esc(g.date.slice(0, 16).replace("T", " "))} · ${g.human === "w" ? "White" : "Black"} vs ${esc(g.styleName)} · ${esc(g.result)} · ${g.moves.length} plies</div>`).join("") || "<div>No games yet.</div>"; | |
| } | |
| function esc(s) { return String(s).replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } | |
| function download(name, text) { | |
| const a = document.createElement("a"); a.href = URL.createObjectURL(new Blob([text], { type: "application/x-chess-pgn" })); | |
| a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); | |
| } | |
| async function newGame(side) { | |
| if (S.st && !S.saved && S.moves.length >= 2) finish(false); | |
| worker.postMessage({ cmd: "newgame" }); | |
| for (const h of helpers) h.postMessage({ cmd: "newgame" }); | |
| S = { moves: [], human: side, flip: side === "b", sel: null, st: state([]), busy: false, saved: false }; | |
| render(); showInfo(null, 0); | |
| if (side === "b") engineMove(); | |
| } | |
| async function main() { | |
| try { POLY = (await getJSON("data/polyglot.json")).map(x => BigInt("0x" + x)); } catch (e) { POLY = null; } | |
| try { STYLES = await getJSON("data/styles.json"); } catch (e) { STYLES = []; } | |
| const sel = $("style"); | |
| for (const s of STYLES) { const o = document.createElement("option"); o.value = s.key; o.textContent = s.name; sel.appendChild(o); } | |
| $("newW").onclick = () => newGame("w"); | |
| $("newB").onclick = () => newGame("b"); | |
| $("flip").onclick = () => { S.flip = !S.flip; render(); }; | |
| $("hint").onclick = () => analyse("Hint: "); | |
| $("analyse").onclick = () => analyse("Best: "); | |
| $("rankAll").onclick = () => rankAll(); | |
| $("resign").onclick = () => { if (!S.busy && !S.saved && S.st.status === "ongoing" && S.moves.length >= 2) finish(true); }; | |
| $("undo").onclick = () => { | |
| if (S.busy || S.saved) return; | |
| const n = S.st.turn === S.human ? 2 : 1; S.moves = S.moves.slice(0, Math.max(0, S.moves.length - n)); | |
| S.st = state(S.moves); S.sel = null; render(); | |
| if (S.st.turn !== S.human && S.st.status === "ongoing") engineMove(); | |
| }; | |
| $("pgnThis").onclick = () => { const st = state(S.moves); | |
| download("cael-game.pgn", pgnOf({ date: new Date().toISOString(), name: $("nick").value.trim() || "You", human: S.human, | |
| styleName: $("style").selectedOptions[0].textContent, san: st.san, moves: S.moves, result: st.result || "*", termination: st.status })); }; | |
| $("pgnAll").onclick = () => download("cael-games.pgn", loadGames().map(pgnOf).join("\n")); | |
| $("clearAll").onclick = () => { if (confirm("Delete all games saved in this browser?")) { saveGames([]); loadStats(); } }; | |
| try { $("nick").value = localStorage.getItem("cael_nick") || ""; } catch (e) { } | |
| $("nick").onchange = () => { try { localStorage.setItem("cael_nick", $("nick").value); } catch (e) { } }; | |
| window.addEventListener("pagehide", () => { if (S.st && !S.saved && S.moves.length >= 2) finish(false); }); | |
| loadStats(); | |
| newGame("w"); | |
| } | |
| main(); | |