src/play.ts (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
import { Game, type Color, type Square, type Move } from "./game/state";
import { Board } from "./board/board";
import { Engine } from "./game/engine";
import type { Personality } from "./game/personalities";
import { getSet, type PieceType } from "./board/pieces";
import { Clock, formatTime, type TimeControl } from "./game/clock";
import { threats, PIECE_NAME } from "./game/analysis";
import { explainPosition, explainMistake, blunderCheck } from "./game/coach";
import { sound } from "./util/sound";
import { loadPrefs, savePrefs, saveGame, clearGame } from "./util/storage";
import { goto } from "./util/url";
type Promo = "q" | "r" | "b" | "n";
const app = document.querySelector<HTMLDivElement>("#app")!;
let prefs = loadPrefs();
let engine: Engine | null = null;
let liveBoard: Board | null = null;
const PIECE_VALUE: Record<string, number> = { p: 1, n: 3, b: 3, r: 5, q: 9 };
const START_COUNT: Record<string, number> = { p: 8, n: 2, b: 2, r: 2, q: 1 };
const GRAVEYARD_ORDER: PieceType[] = ["q", "r", "b", "n", "p"];
// Entry point for the game screen. Loaded on demand so the home page stays tiny.
export async function startGame(
human: Color,
personality: Personality,
tc: TimeControl,
text: string
): Promise<string | null> {
prefs = loadPrefs();
const initial = parseInitial(text);
if (initial === "invalid") return "That is not a valid FEN or PGN.";
liveBoard?.destroy();
liveBoard = null;
await new PlayController(human, personality, tc, initial).mount();
return null;
}
function parseInitial(text: string): { fen?: string; pgn?: string } | null | "invalid" {
const t = text.trim();
if (!t) return null;
const probe = new Game();
if (probe.load(t)) return { fen: t };
if (probe.loadPgn(t)) return { pgn: t };
return "invalid";
}
class PlayController {
private game: Game;
private board!: Board;
private clock: Clock;
private thinking = false;
private view: Color;
private timeLoss: Color | null = null;
private over = false;
private threatsOn = prefs.threats;
private blunderOn = prefs.blunder;
private beforeHuman: Game | null = null;
private afterHuman: Game | null = null;
private humanMove: Move | null = null;
private pendingBlunder: { from: Square; to: Square; promo?: Promo } | null = null;
// Evaluations are queued so they never interleave with a search on the wire.
private evalQueue: Promise<unknown> = Promise.resolve();
private evalToken = 0;
private lastTickSec = -1;
constructor(
private human: Color,
private personality: Personality,
private tc: TimeControl,
initial: { fen?: string; pgn?: string } | null
) {
this.game = new Game(initial?.fen);
if (initial?.pgn) this.game.loadPgn(initial.pgn);
this.view = human;
this.clock = new Clock(tc, this.onTick, this.onFlag);
if (!engine) engine = new Engine();
}
async mount() {
const opp = this.human === "w" ? "b" : "w";
const glyphs = getSet(prefs.pieceSet).glyphs;
const clockHtml = (c: Color) =>
this.clock.enabled
? `<span class="clock" data-c="${c}"><span class="bar" id="bar-${c}"></span><span class="time" id="clk-${c}">--</span></span>`
: "";
app.innerHTML = `
<div class="topbar">
<h2>${this.personality.face} ${this.personality.name}</h2>
<button class="back" data-back>← menu</button>
</div>
<div class="play">
<div class="arena">
<div class="hud opp">
<span class="face">${this.personality.face}</span>
<span class="who">${this.personality.name}</span>
<span class="captured" id="cap-${opp}"></span>
<span class="mat" id="mat-${opp}"></span>
${clockHtml(opp)}
</div>
<div class="board-row">
<div class="evalwrap">
<div class="evalbar"><div class="evalfill" id="evalfill"></div></div>
<span class="evalnum" id="evalnum"></span>
</div>
<div class="board-wrap"><div id="board"></div></div>
</div>
<div class="hud you">
<span class="face">${glyphs.k}</span>
<span class="who">you · ${this.human === "w" ? "white" : "black"}</span>
<span class="captured" id="cap-${this.human}"></span>
<span class="mat" id="mat-${this.human}"></span>
${clockHtml(this.human)}
</div>
</div>
<aside class="panel">
<div class="status" id="status"></div>
<div class="assist" id="assist">
<button id="t-threats" aria-pressed="${this.threatsOn}">threats</button>
<button id="t-blunder" aria-pressed="${this.blunderOn}">blunder</button>
<button id="explain">explain</button>
<button id="why">why?</button>
</div>
<div class="coach" id="coach"></div>
<div class="moves"><ol id="movelist"></ol></div>
<div class="controls">
<button id="undo">undo</button>
<button id="flip">flip</button>
<button id="pgn">copy pgn</button>
<button id="new">new game</button>
</div>
</aside>
</div>
<div class="gameover hidden" id="gameover"></div>`;
app.querySelector<HTMLButtonElement>("[data-back]")!.onclick = () => {
this.clock.stop();
clearGame();
goto("home");
};
this.board = new Board(app.querySelector<HTMLElement>("#board")!, {
orientation: this.view,
set: getSet(prefs.pieceSet),
coords: prefs.coords,
legalTargets: (sq) => (this.canMove() ? this.game.legalTargets(sq) : []),
canMove: () => this.canMove(),
onMove: (from, to, promo) => this.onHumanMove(from, to, promo as Promo),
});
liveBoard = this.board;
this.board.setPosition(this.game.board());
this.wireControls();
this.refreshCheck();
this.update();
if (engine) await engine.configure(this.personality);
if (prefs.sound) sound.start();
if (this.clock.enabled) this.clock.start(this.game.turn);
if (this.game.outcome().over) this.showGameOver();
else if (this.game.turn !== this.human) void this.aiMove().finally(() => this.refreshEval());
else void this.refreshEval();
}
private wireControls() {
app.querySelector<HTMLButtonElement>("#undo")!.onclick = () => this.undo();
app.querySelector<HTMLButtonElement>("#flip")!.onclick = () => {
this.view = this.view === "w" ? "b" : "w";
this.board.setOrientation(this.view);
this.board.setPosition(this.game.board());
this.refreshCheck();
this.refreshThreats();
};
app.querySelector<HTMLButtonElement>("#pgn")!.onclick = (e) => {
navigator.clipboard?.writeText(this.game.pgn());
flash(e.target as HTMLButtonElement, "copied", "copy pgn");
};
app.querySelector<HTMLButtonElement>("#new")!.onclick = () => {
this.clock.stop();
clearGame();
goto("play");
};
const threatsBtn = app.querySelector<HTMLButtonElement>("#t-threats")!;
threatsBtn.onclick = () => {
this.threatsOn = !this.threatsOn;
prefs = { ...prefs, threats: this.threatsOn };
savePrefs(prefs);
threatsBtn.setAttribute("aria-pressed", String(this.threatsOn));
this.refreshThreats();
};
const blunderBtn = app.querySelector<HTMLButtonElement>("#t-blunder")!;
blunderBtn.onclick = () => {
this.blunderOn = !this.blunderOn;
prefs = { ...prefs, blunder: this.blunderOn };
savePrefs(prefs);
blunderBtn.setAttribute("aria-pressed", String(this.blunderOn));
};
app.querySelector<HTMLButtonElement>("#explain")!.onclick = () => this.explain();
app.querySelector<HTMLButtonElement>("#why")!.onclick = () => this.why();
if (this.clock.enabled) app.querySelector<HTMLButtonElement>("#undo")!.disabled = true;
}
private canMove(): boolean {
return (
!this.thinking &&
!this.pendingBlunder &&
!this.timeLoss &&
this.game.turn === this.human &&
!this.game.outcome().over
);
}
private onHumanMove(from: Square, to: Square, promo?: Promo) {
if (this.blunderOn) {
const risk = blunderCheck(this.game, from, to, promo, this.human);
if (risk) {
this.pendingBlunder = { from, to, promo };
this.askBlunder(PIECE_NAME[risk.type], risk.square);
return;
}
}
this.commitHuman(from, to, promo);
}
private commitHuman(from: Square, to: Square, promo?: Promo) {
this.beforeHuman = this.game.clone();
const move = this.game.play(from, to, promo);
if (!move) return;
this.humanMove = move;
this.afterHuman = this.game.clone();
this.setCoach("");
this.board.clearArrow();
this.afterMove(move);
if (!this.game.outcome().over && !this.timeLoss) {
void this.aiMove().finally(() => this.refreshEval());
}
}
private async aiMove() {
if (!engine || this.game.outcome().over || this.timeLoss) return;
this.thinking = true;
this.showThinking();
const uci = await engine.chooseMove(this.game.fen, this.personality, this.game.legalUci());
this.thinking = false;
app.querySelector(".hud.opp")?.classList.remove("thinking");
if (!uci || this.timeLoss) return this.update();
const move = this.game.playUci(uci);
if (move) {
this.board.setArrow(move.from as Square, move.to as Square);
this.afterMove(move);
} else this.update();
}
private afterMove(move: Move) {
this.board.applyMove(move);
if (this.clock.enabled) this.clock.press(move.color);
this.playSound(move);
this.showReactions(move);
this.refreshCheck();
this.refreshThreats();
this.update();
this.persist();
if (this.game.outcome().over) {
this.clock.stop();
if (prefs.sound) sound.end();
this.showGameOver();
}
}
private undo() {
if (this.thinking || this.clock.enabled) return;
this.hideGameOver();
this.board.clearDefeat();
this.board.clearArrow();
this.game.undo();
if (this.game.turn !== this.human) this.game.undo();
this.pendingBlunder = null;
this.setCoach("");
this.board.setPosition(this.game.board());
this.refreshCheck();
this.refreshThreats();
this.update();
this.persist();
void this.refreshEval();
}
private playSound(move: Move) {
if (!prefs.sound) return;
if (move.flags.includes("p")) sound.promote();
else if (move.flags.includes("k") || move.flags.includes("q")) sound.castle();
else if (move.captured) sound.capture();
else sound.move();
if (this.game.inCheck()) sound.check();
}
private showReactions(move: Move) {
if (!prefs.reactions) return;
if (move.flags.includes("p")) this.board.react(move.to as Square, "✨");
if (this.game.inCheck()) {
const king = this.game.kingSquare(this.game.turn);
if (king) this.board.react(king, "❗");
}
}
private refreshCheck() {
this.board.setCheck(this.game.inCheck() ? this.game.kingSquare(this.game.turn) : null);
}
private refreshThreats() {
if (this.threatsOn) this.board.setThreats(threats(this.game, this.human).map((t) => t.square));
else this.board.setThreats([]);
}
private runEngineEval(fen: string, movetime = 400): Promise<{ cp: number | null; mate: number | null }> {
const p = this.evalQueue.then(() =>
engine ? engine.evaluate(fen, movetime) : { cp: null, mate: null }
);
this.evalQueue = p.catch(() => {});
return p;
}
// The eval bar reads from White's point of view, no matter who sits where.
private async refreshEval() {
if (!engine || this.game.outcome().over || this.timeLoss) return;
const token = ++this.evalToken;
const fen = this.game.fen;
const stm = this.game.turn;
const { cp, mate } = await this.runEngineEval(fen);
if (token !== this.evalToken) return;
if (mate !== null) {
const m = stm === "w" ? mate : -mate; // from White's side of the board
this.renderEval(m > 0 ? 1 : -1, (m > 0 ? "#" : "-#") + Math.abs(m));
} else if (cp !== null) {
const cpW = stm === "w" ? cp : -cp;
const score = (2 / Math.PI) * Math.atan(cpW / 350);
this.renderEval(score, (cpW >= 0 ? "+" : "") + (cpW / 100).toFixed(1));
}
}
private renderEval(score: number, label: string) {
const fill = app.querySelector<HTMLElement>("#evalfill");
const num = app.querySelector<HTMLElement>("#evalnum");
if (!fill || !num) return;
fill.style.height = Math.round(((score + 1) / 2) * 100) + "%";
num.textContent = label;
}
private async explain() {
if (!engine) return;
if (this.thinking) {
this.setCoach("One moment — the engine is busy with its move.");
return;
}
this.setCoach("thinking…");
const { cp, mate } = await this.runEngineEval(this.game.fen, 500);
const forHuman = this.game.turn === this.human ? 1 : -1;
const cpH = cp === null ? null : cp * forHuman;
const mateH = mate === null ? null : mate * forHuman;
this.setCoach(explainPosition(this.game, this.human, cpH, mateH));
}
private why() {
if (!this.beforeHuman || !this.afterHuman || !this.humanMove) {
this.setCoach("Make a move first, then ask.");
return;
}
const reason = explainMistake(this.beforeHuman, this.afterHuman, this.humanMove, this.human);
this.setCoach(reason ?? "That move was fine — nothing was hanging.");
}
private askBlunder(name: string, square: Square) {
this.setCoach("");
const coach = app.querySelector<HTMLElement>("#coach")!;
coach.innerHTML = `This move leaves your ${name} on ${square} for the taking.
<div class="assist" style="margin-top:6px">
<button id="playanyway">play it anyway</button>
<button id="takeback">take it back</button>
</div>`;
coach.querySelector<HTMLButtonElement>("#playanyway")!.onclick = () => {
const p = this.pendingBlunder!;
this.pendingBlunder = null;
coach.textContent = "";
this.commitHuman(p.from, p.to, p.promo);
};
coach.querySelector<HTMLButtonElement>("#takeback")!.onclick = () => {
this.pendingBlunder = null;
coach.textContent = "";
};
}
private setCoach(text: string) {
const coach = app.querySelector<HTMLElement>("#coach");
if (coach) coach.textContent = text;
}
private onTick = (w: number, b: number) => {
this.setClock("w", w);
this.setClock("b", b);
const ms = this.human === "w" ? w : b;
if (prefs.sound && this.canRun() && this.game.turn === this.human && ms > 0 && ms <= 10000) {
const sec = Math.ceil(ms / 1000);
if (sec !== this.lastTickSec) {
this.lastTickSec = sec;
sound.tick();
}
} else {
this.lastTickSec = -1;
}
};
private setClock(c: Color, ms: number) {
const el = document.getElementById("clk-" + c);
if (!el) return;
el.textContent = formatTime(ms);
const box = el.parentElement!;
box.classList.toggle("running", this.game.turn === c && this.canRun());
box.classList.toggle("low", ms < 10000 && ms > 0);
box.classList.toggle("flag", this.timeLoss === c);
const bar = document.getElementById("bar-" + c);
if (bar) {
const pct = Math.max(0, Math.min(100, (ms / this.clock.baseMs) * 100));
bar.style.width = pct + "%";
}
}
private canRun(): boolean {
return !this.timeLoss && !this.game.outcome().over;
}
private onFlag = (side: Color) => {
this.timeLoss = side;
this.clock.stop();
if (prefs.sound) sound.end();
this.update();
this.showGameOver();
};
private showThinking() {
const status = app.querySelector<HTMLElement>("#status");
if (status) status.innerHTML = `<span class="thinking">${this.personality.face} is thinking…</span>`;
app.querySelector(".hud.opp")?.classList.add("thinking");
}
private update() {
this.renderStatus();
this.renderMoves();
this.renderMaterial();
const undo = app.querySelector<HTMLButtonElement>("#undo");
if (undo && !this.clock.enabled) undo.disabled = this.game.history().length === 0;
}
private renderStatus() {
const status = app.querySelector<HTMLElement>("#status");
if (!status) return;
if (this.timeLoss) {
status.textContent =
this.timeLoss === this.human ? "You lost on time." : "Your opponent lost on time. You win.";
return;
}
const outcome = this.game.outcome();
if (outcome.over) {
status.textContent = describeOutcome(outcome, this.human);
return;
}
const dot = `<span class="turn-dot ${this.game.turn}"></span>`;
status.innerHTML = dot + (this.game.turn === this.human ? "Your move" : "Waiting…");
}
// Fallen pieces line up next to the side that lost them; the leader gets a +N chip.
private renderMaterial() {
const set = getSet(prefs.pieceSet);
const count: Record<Color, Record<string, number>> = {
w: { p: 0, n: 0, b: 0, r: 0, q: 0 },
b: { p: 0, n: 0, b: 0, r: 0, q: 0 },
};
for (const row of this.game.board()) {
for (const cell of row) {
if (cell && cell.type !== "k") count[cell.color][cell.type]++;
}
}
let valW = 0;
let valB = 0;
for (const t of GRAVEYARD_ORDER) {
valW += count.w[t] * PIECE_VALUE[t];
valB += count.b[t] * PIECE_VALUE[t];
}
for (const c of ["w", "b"] as Color[]) {
const el = app.querySelector<HTMLElement>("#cap-" + c);
if (el) {
let html = "";
for (const t of GRAVEYARD_ORDER) {
const lost = START_COUNT[t] - count[c][t];
const cls = set.traditional ? ` class="cap trad ${c}"` : ` class="cap"`;
for (let i = 0; i < lost; i++) html += `<span${cls}>${set.glyphs[t]}</span>`;
}
el.innerHTML = html;
}
const mat = app.querySelector<HTMLElement>("#mat-" + c);
if (mat) {
const diff = c === "w" ? valW - valB : valB - valW;
mat.textContent = diff > 0 ? "+" + diff : "";
}
}
}
private renderMoves() {
const list = app.querySelector<HTMLOListElement>("#movelist");
if (!list) return;
const history = this.game.history();
let html = "";
for (let i = 0; i < history.length; i += 2) {
const no = i / 2 + 1;
const white = history[i]?.san ?? "";
const black = history[i + 1]?.san ?? "";
const wHere = i === history.length - 1 ? " here" : "";
const bHere = i + 1 === history.length - 1 ? " here" : "";
html += `<li><span class="no">${no}.</span><span class="san${wHere}">${white}</span><span class="san${bHere}">${black}</span></li>`;
}
list.innerHTML = html;
list.parentElement!.scrollTop = list.parentElement!.scrollHeight;
}
private showGameOver() {
if (this.over) return;
this.over = true;
let banner = "DRAW";
let detail: string;
const outcome = this.game.outcome();
if (this.timeLoss) {
banner = "FLAG FALL";
detail = this.timeLoss === this.human ? "You lost on time." : "You win on time.";
} else if (outcome.over && outcome.reason === "checkmate") {
banner = "CHECKMATE";
detail = outcome.winner === this.human ? "You win." : "You lose.";
const king = this.game.kingSquare(this.game.turn);
if (king) {
this.board.defeat(king);
this.board.react(king, "💀", true);
}
this.renderEval(outcome.winner === "w" ? 1 : -1, outcome.winner === "w" ? "1-0" : "0-1");
} else {
if (outcome.over && outcome.reason === "stalemate") banner = "STALEMATE";
detail = outcome.over ? describeOutcome(outcome, this.human) : "The game is over.";
}
const moves = Math.ceil(this.game.history().length / 2);
const box = app.querySelector<HTMLElement>("#gameover")!;
box.innerHTML = `
<div class="go-box">
<pre class="go-banner">${banner}</pre>
<p class="go-detail">${detail}</p>
<p class="go-meta">${moves} moves · ${this.personality.face} ${this.personality.name}</p>
<div class="go-actions">
<button class="btn" id="rematch">rematch</button>
<button class="btn" id="gonew">new opponent</button>
<button class="btn ghost" id="gomenu">menu</button>
</div>
<button class="go-pgn" id="gopgn">[ copy pgn ]</button>
</div>`;
box.querySelector<HTMLButtonElement>("#rematch")!.onclick = () => {
this.clock.stop();
clearGame();
const next: Color = this.human === "w" ? "b" : "w";
void startGame(next, this.personality, this.tc, "");
};
box.querySelector<HTMLButtonElement>("#gonew")!.onclick = () => {
this.clock.stop();
clearGame();
goto("play");
};
box.querySelector<HTMLButtonElement>("#gomenu")!.onclick = () => {
this.clock.stop();
clearGame();
goto("home");
};
box.querySelector<HTMLButtonElement>("#gopgn")!.onclick = (e) => {
navigator.clipboard?.writeText(this.game.pgn());
flash(e.target as HTMLButtonElement, "[ copied ]", "[ copy pgn ]");
};
// Let the final position land — the falling king, the skull — before the curtain.
setTimeout(() => box.classList.remove("hidden"), 700);
}
private hideGameOver() {
this.over = false;
const box = app.querySelector<HTMLElement>("#gameover");
if (box) {
box.classList.add("hidden");
box.innerHTML = "";
}
}
private persist() {
if (this.game.outcome().over || this.timeLoss) {
clearGame();
return;
}
saveGame({
pgn: this.game.pgn(),
side: this.human,
personality: this.personality.id,
savedAt: Date.now(),
});
}
}
function flash(btn: HTMLButtonElement, on: string, off: string) {
btn.textContent = on;
setTimeout(() => (btn.textContent = off), 1200);
}
function describeOutcome(
outcome: Extract<ReturnType<Game["outcome"]>, { over: true }>,
human: Color
): string {
if (outcome.reason === "checkmate") {
return outcome.winner === human ? "Checkmate. You win." : "Checkmate. You lose.";
}
const draws: Record<string, string> = {
stalemate: "Stalemate. It's a draw.",
insufficient: "Draw — not enough material to mate.",
repetition: "Draw by repetition.",
fifty: "Draw by the fifty-move rule.",
draw: "The game is a draw.",
};
return draws[outcome.reason] ?? "The game is over.";
}
|