src/board/board.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 |
import type { Move, Square, Color } from "../game/state";
import { type PieceSet, type PieceType } from "./pieces";
export interface BoardOptions {
orientation: Color;
set: PieceSet;
coords: boolean;
legalTargets: (from: Square) => Move[];
canMove: () => boolean;
onMove: (from: Square, to: Square, promotion?: PromoPiece) => void;
}
type PromoPiece = "q" | "r" | "b" | "n";
const FILES = "abcdefgh";
export class Board {
private root: HTMLElement;
private cells = new Map<Square, HTMLElement>();
private pieces = new Map<Square, HTMLElement>();
private selected: Square | null = null;
private lastMove: [Square, Square] | null = null;
private drag: { from: Square; el: HTMLElement; moved: boolean } | null = null;
private arrowSvg!: SVGSVGElement;
constructor(root: HTMLElement, private opts: BoardOptions) {
this.root = root;
this.root.classList.add("board");
this.buildGrid();
this.root.addEventListener("pointerdown", this.onPointerDown);
window.addEventListener("pointermove", this.onPointerMove);
window.addEventListener("pointerup", this.onPointerUp);
}
private buildGrid() {
this.root.replaceChildren();
this.cells.clear();
for (let rank = 8; rank >= 1; rank--) {
for (let f = 0; f < 8; f++) {
const file = this.opts.orientation === "w" ? f : 7 - f;
const r = this.opts.orientation === "w" ? rank : 9 - rank;
const square = (FILES[file] + r) as Square;
const cell = document.createElement("div");
cell.className = "sq " + ((file + r) % 2 === 0 ? "light" : "dark");
cell.dataset.square = square;
if (this.opts.coords) this.addCoords(cell, file, r);
this.cells.set(square, cell);
this.root.appendChild(cell);
}
}
// The arrow layer sits above the squares and pieces, redrawn on every rebuild.
this.arrowSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
this.arrowSvg.setAttribute("viewBox", "0 0 8 8");
this.arrowSvg.classList.add("arrows");
this.root.appendChild(this.arrowSvg);
}
private addCoords(cell: HTMLElement, file: number, rank: number) {
const bottomRank = this.opts.orientation === "w" ? 1 : 8;
const edgeFile = this.opts.orientation === "w" ? 0 : 7;
if (rank === bottomRank) {
const c = document.createElement("span");
c.className = "coord file";
c.textContent = FILES[file];
cell.appendChild(c);
}
if (file === edgeFile) {
const c = document.createElement("span");
c.className = "coord rank";
c.textContent = String(rank);
cell.appendChild(c);
}
}
setPosition(board: ReturnType<import("../game/state").Game["board"]>) {
for (const el of this.pieces.values()) el.remove();
this.pieces.clear();
for (const row of board) {
for (const cell of row) {
if (!cell) continue;
const el = this.makePiece(cell.type, cell.color, cell.square as Square);
this.pieces.set(cell.square as Square, el);
this.root.appendChild(el);
}
}
this.clearHints();
}
private makePiece(type: PieceType, color: Color, square: Square): HTMLElement {
const el = document.createElement("div");
el.className = "piece " + color + (this.opts.set.traditional ? " traditional" : "");
const glyph = document.createElement("span");
glyph.className = "glyph";
glyph.textContent = this.opts.set.glyphs[type];
el.appendChild(glyph);
el.dataset.type = type;
this.place(el, square);
return el;
}
private place(el: HTMLElement, square: Square) {
const { x, y } = this.xy(square);
el.style.transform = `translate(${x * 100}%, ${y * 100}%)`;
}
private xy(square: Square): { x: number; y: number } {
const file = FILES.indexOf(square[0]);
const rank = Number(square[1]);
if (this.opts.orientation === "w") return { x: file, y: 8 - rank };
return { x: 7 - file, y: rank - 1 };
}
// Animate a single applied move, including the special cases chess.js flags for us.
applyMove(move: Move) {
const from = move.from as Square;
const to = move.to as Square;
const moving = this.pieces.get(from);
if (!moving) return this.reconcile(move);
if (move.flags.includes("e")) {
const capSquare = (to[0] + from[1]) as Square;
this.capture(capSquare);
} else if (move.captured) {
this.capture(to);
}
this.pieces.delete(from);
this.pieces.set(to, moving);
this.animateFor(moving, move.piece);
this.place(moving, to);
if (move.flags.includes("p") && move.promotion) {
const glyph = moving.querySelector(".glyph");
if (glyph) glyph.textContent = this.opts.set.glyphs[move.promotion as PieceType];
moving.dataset.type = move.promotion;
}
if (move.flags.includes("k")) this.moveRook(move.color, "h", "f");
if (move.flags.includes("q")) this.moveRook(move.color, "a", "d");
this.setLastMove(from, to);
this.clearHints();
}
private reconcile(move: Move) {
this.setLastMove(move.from as Square, move.to as Square);
}
private moveRook(color: Color, fromFile: string, toFile: string) {
const rank = color === "w" ? "1" : "8";
const from = (fromFile + rank) as Square;
const to = (toFile + rank) as Square;
const rook = this.pieces.get(from);
if (!rook) return;
this.pieces.delete(from);
this.pieces.set(to, rook);
this.place(rook, to);
}
private capture(square: Square) {
const el = this.pieces.get(square);
if (!el) return;
this.pieces.delete(square);
el.classList.add("captured");
setTimeout(() => el.remove(), 220);
this.puff(square);
}
// Each piece carries a little of its own character: pawns hop, the king trudges.
private animateFor(el: HTMLElement, type: string) {
const ms: Record<string, number> = { p: 220, n: 340, b: 300, r: 340, q: 240, k: 400 };
el.style.transitionDuration = (ms[type] ?? 280) + "ms";
if (type === "n") {
el.classList.add("hop");
setTimeout(() => el.classList.remove("hop"), ms.n);
}
}
private puff(square: Square) {
const p = document.createElement("div");
p.className = "puff";
p.textContent = "💨";
this.place(p, square);
this.root.appendChild(p);
setTimeout(() => p.remove(), 480);
}
setThreats(squares: Square[]) {
for (const el of this.pieces.values()) el.classList.remove("threat");
for (const sq of squares) this.pieces.get(sq)?.classList.add("threat");
}
react(square: Square, text: string, stay = false) {
const b = document.createElement("div");
b.className = "reaction" + (stay ? " stay" : "");
b.textContent = text;
this.place(b, square);
this.root.appendChild(b);
if (stay) return;
requestAnimationFrame(() => b.classList.add("rise"));
setTimeout(() => b.remove(), 900);
}
// An arrow from the engine's last move, so the eye catches what just happened.
setArrow(from: Square, to: Square) {
this.clearArrow();
const a = this.xy(from);
const b = this.xy(to);
const x1 = a.x + 0.5;
const y1 = a.y + 0.5;
const x2 = b.x + 0.5;
const y2 = b.y + 0.5;
const len = Math.hypot(x2 - x1, y2 - y1);
if (len === 0) return;
const ux = (x2 - x1) / len;
const uy = (y2 - y1) / len;
const px = -uy;
const py = ux;
const ex = x2 - ux * 0.36; // arrowhead tip, short of the piece's center
const ey = y2 - uy * 0.36;
const ns = "http://www.w3.org/2000/svg";
const line = document.createElementNS(ns, "line");
line.setAttribute("x1", String(x1 + ux * 0.18));
line.setAttribute("y1", String(y1 + uy * 0.18));
line.setAttribute("x2", String(ex - ux * 0.24));
line.setAttribute("y2", String(ey - uy * 0.24));
line.setAttribute("class", "arrow");
const head = document.createElementNS(ns, "polygon");
head.setAttribute(
"points",
`${ex},${ey} ${ex - ux * 0.3 + px * 0.17},${ey - uy * 0.3 + py * 0.17} ${ex - ux * 0.3 - px * 0.17},${ey - uy * 0.3 - py * 0.17}`
);
head.setAttribute("class", "arrow");
this.arrowSvg.append(line, head);
}
clearArrow() {
this.arrowSvg?.replaceChildren();
}
// The beaten king keels over; the board flinches with him.
defeat(square: Square) {
this.pieces.get(square)?.classList.add("defeated");
this.root.classList.add("shake");
setTimeout(() => this.root.classList.remove("shake"), 600);
}
clearDefeat() {
for (const el of this.pieces.values()) el.classList.remove("defeated");
this.root.querySelectorAll(".reaction.stay").forEach((r) => r.remove());
}
setLastMove(from: Square, to: Square) {
if (this.lastMove) {
for (const sq of this.lastMove) this.cells.get(sq)?.classList.remove("last");
}
this.lastMove = [from, to];
this.cells.get(from)?.classList.add("last");
this.cells.get(to)?.classList.add("last");
}
setCheck(square: Square | null) {
for (const cell of this.cells.values()) cell.classList.remove("check");
if (square) this.cells.get(square)?.classList.add("check");
}
private select(square: Square) {
this.clearHints();
this.selected = square;
this.cells.get(square)?.classList.add("sel");
for (const move of this.opts.legalTargets(square)) {
const cell = this.cells.get(move.to as Square);
if (!cell) continue;
const dot = document.createElement("div");
dot.className = "dot" + (move.captured || move.flags.includes("e") ? " capture" : "");
cell.appendChild(dot);
}
}
private clearHints() {
if (this.selected) this.cells.get(this.selected)?.classList.remove("sel");
this.selected = null;
for (const cell of this.cells.values()) {
cell.querySelectorAll(".dot").forEach((d) => d.remove());
}
}
private tryMove(from: Square, to: Square) {
const legal = this.opts.legalTargets(from).find((m) => m.to === to);
if (!legal) return false;
if (legal.flags.includes("p")) {
this.askPromotion(legal.color, to, (choice) => this.opts.onMove(from, to, choice));
} else {
this.opts.onMove(from, to);
}
return true;
}
private squareAt(clientX: number, clientY: number): Square | null {
const rect = this.root.getBoundingClientRect();
const col = Math.floor(((clientX - rect.left) / rect.width) * 8);
const row = Math.floor(((clientY - rect.top) / rect.height) * 8);
if (col < 0 || col > 7 || row < 0 || row > 7) return null;
const file = this.opts.orientation === "w" ? col : 7 - col;
const rank = this.opts.orientation === "w" ? 8 - row : row + 1;
return (FILES[file] + rank) as Square;
}
private onPointerDown = (e: PointerEvent) => {
if (!this.opts.canMove()) return;
const square = this.squareAt(e.clientX, e.clientY);
if (!square) return;
if (this.selected && this.selected !== square) {
if (this.tryMove(this.selected, square)) return;
}
const el = this.pieces.get(square);
if (el) {
this.select(square);
this.drag = { from: square, el, moved: false };
el.classList.add("dragging");
this.dragTo(el, e.clientX, e.clientY);
} else {
this.clearHints();
}
};
private onPointerMove = (e: PointerEvent) => {
if (!this.drag) return;
this.drag.moved = true;
this.dragTo(this.drag.el, e.clientX, e.clientY);
};
private onPointerUp = (e: PointerEvent) => {
if (!this.drag) return;
const { from, el, moved } = this.drag;
this.drag = null;
el.classList.remove("dragging");
this.place(el, from);
if (!moved) return;
const to = this.squareAt(e.clientX, e.clientY);
if (to && to !== from) this.tryMove(from, to);
};
private dragTo(el: HTMLElement, clientX: number, clientY: number) {
const rect = this.root.getBoundingClientRect();
const size = rect.width / 8;
const x = clientX - rect.left - size / 2;
const y = clientY - rect.top - size / 2;
el.style.transform = `translate(${x}px, ${y}px)`;
}
private askPromotion(color: Color, at: Square, done: (choice: PromoPiece) => void) {
const menu = document.createElement("div");
menu.className = "promo";
const { x, y } = this.xy(at);
menu.style.left = `${x * 12.5}%`;
menu.style.top = `${Math.min(y, 4) * 12.5}%`;
const order: PromoPiece[] = ["q", "r", "b", "n"];
for (const type of order) {
const b = document.createElement("button");
b.textContent = this.opts.set.traditional
? this.opts.set.glyphs[type]
: this.opts.set.glyphs[type];
b.className = "piece-choice " + color;
b.onclick = () => {
menu.remove();
done(type);
};
menu.appendChild(b);
}
this.root.appendChild(menu);
}
setOrientation(o: Color) {
this.opts.orientation = o;
this.buildGrid();
}
// The board listens on window for drags; drop those listeners when a game ends,
// or every rematch would pile another dead board onto the window.
destroy() {
window.removeEventListener("pointermove", this.onPointerMove);
window.removeEventListener("pointerup", this.onPointerUp);
}
setSet(set: PieceSet) {
this.opts.set = set;
}
setCoords(on: boolean) {
this.opts.coords = on;
this.buildGrid();
}
}
|