Switch chessboard to tap-tap interaction and fix/enhance premoving
This commit is contained in:
parent
e2e085b341
commit
02b8bafb1e
6 changed files with 364 additions and 294 deletions
|
|
@ -4,7 +4,7 @@ Lightweight Lichess-style chess server and Stockfish analysis web app built with
|
|||
|
||||
## Features
|
||||
|
||||
- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap + mouse/touch drag, single premove, Web Audio sounds (ES2017 / Safari 12+ compatible).
|
||||
- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap-to-move, single premove, Web Audio sounds (ES2017 / Safari 12+ compatible).
|
||||
- **Accounts (no email required)**: Username + password registration (`crypto.scrypt` + `HttpOnly` session cookies).
|
||||
- **Glicko-2 Ratings**: Separate ratings for Bullet, Blitz, Rapid, and Classical, with rating history charts and leaderboards.
|
||||
- **Multiplayer & Social**: Live Open Lobby seeks, shareable invite links (`/invite/<token>`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Chess, algToSq, sqToAlg } from '../../shared/chess';
|
||||
import { type QueuedPremove, computePremoveTargets, resolveQueuedPremove } from '../../shared/premove';
|
||||
import type { Color, Piece, PromotionPiece } from '../../shared/types';
|
||||
import { createPieceNode } from '../pieces';
|
||||
import { clearNode, el } from '../dom';
|
||||
|
|
@ -16,6 +17,7 @@ export interface BoardOptions {
|
|||
mode?: BoardMode;
|
||||
playerColor?: Color;
|
||||
onMove?: (uci: string) => void;
|
||||
onPremoveChange?: (premoveUci: string | null) => void;
|
||||
}
|
||||
|
||||
export class ChessBoard {
|
||||
|
|
@ -27,37 +29,28 @@ export class ChessBoard {
|
|||
private readonly squareEls: HTMLElement[] = [];
|
||||
|
||||
private chess = new Chess();
|
||||
private currentFen = '';
|
||||
private orientation: Color = 'w';
|
||||
private mode: BoardMode = 'readonly';
|
||||
private playerColor: Color = 'w';
|
||||
private onMoveCallback?: (uci: string) => void;
|
||||
private onPremoveChangeCallback?: (premoveUci: string | null) => void;
|
||||
|
||||
private selectedSq: number = -1;
|
||||
private legalTargets = new Map<number, PromotionPiece[]>();
|
||||
private lastMoveFrom: number = -1;
|
||||
private lastMoveTo: number = -1;
|
||||
private premove: { from: number; to: number; promotion?: PromotionPiece } | null = null;
|
||||
private premove: QueuedPremove | null = null;
|
||||
private arrows: BoardArrow[] = [];
|
||||
private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null;
|
||||
|
||||
// Drag state
|
||||
private pointerDownSq: number = -1;
|
||||
private dragActive = false;
|
||||
private dragStartX = 0;
|
||||
private dragStartY = 0;
|
||||
private dragGhost: HTMLElement | null = null;
|
||||
private dragTouchId: number | null = null;
|
||||
|
||||
private readonly boundMouseMove: (e: MouseEvent) => void;
|
||||
private readonly boundMouseUp: (e: MouseEvent) => void;
|
||||
private readonly boundTouchMove: (e: TouchEvent) => void;
|
||||
private readonly boundTouchEnd: (e: TouchEvent) => void;
|
||||
|
||||
constructor(opts: BoardOptions = {}) {
|
||||
this.orientation = opts.orientation || 'w';
|
||||
this.mode = opts.mode || 'readonly';
|
||||
this.playerColor = opts.playerColor || 'w';
|
||||
this.onMoveCallback = opts.onMove;
|
||||
this.onPremoveChangeCallback = opts.onPremoveChange;
|
||||
this.currentFen = this.chess.fen();
|
||||
|
||||
this.root = el('div', { className: 'board-outer' });
|
||||
this.wrap = el('div', { className: 'board-wrap' });
|
||||
|
|
@ -71,6 +64,10 @@ export class ChessBoard {
|
|||
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const sqEl = el('div', { className: 'sq' });
|
||||
const visualIdx = i;
|
||||
sqEl.addEventListener('click', () => {
|
||||
this.handleSquareTap(this.visualIndexToSq(visualIdx));
|
||||
});
|
||||
this.squareEls.push(sqEl);
|
||||
this.grid.appendChild(sqEl);
|
||||
}
|
||||
|
|
@ -85,43 +82,46 @@ export class ChessBoard {
|
|||
this.clearSelectionAndPremove();
|
||||
});
|
||||
|
||||
this.grid.addEventListener('mousedown', (e) => this.onMouseDown(e));
|
||||
this.grid.addEventListener('touchstart', (e) => this.onTouchStart(e), { passive: false });
|
||||
|
||||
this.boundMouseMove = (e) => this.onMouseMove(e);
|
||||
this.boundMouseUp = (e) => this.onMouseUp(e);
|
||||
this.boundTouchMove = (e) => this.onTouchMove(e);
|
||||
this.boundTouchEnd = (e) => this.onTouchEnd(e);
|
||||
|
||||
window.addEventListener('mousemove', this.boundMouseMove);
|
||||
window.addEventListener('mouseup', this.boundMouseUp);
|
||||
window.addEventListener('touchmove', this.boundTouchMove, { passive: false });
|
||||
window.addEventListener('touchend', this.boundTouchEnd);
|
||||
window.addEventListener('touchcancel', this.boundTouchEnd);
|
||||
|
||||
this.render();
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.endDragGhost();
|
||||
window.removeEventListener('mousemove', this.boundMouseMove);
|
||||
window.removeEventListener('mouseup', this.boundMouseUp);
|
||||
window.removeEventListener('touchmove', this.boundTouchMove);
|
||||
window.removeEventListener('touchend', this.boundTouchEnd);
|
||||
window.removeEventListener('touchcancel', this.boundTouchEnd);
|
||||
// No global listeners to clean up in tap-tap mode
|
||||
}
|
||||
|
||||
getPremoveUci(): string | null {
|
||||
if (!this.premove) return null;
|
||||
return sqToAlg(this.premove.from) + sqToAlg(this.premove.to) + (this.premove.promotion || '');
|
||||
}
|
||||
|
||||
private setPremove(next: QueuedPremove | null): void {
|
||||
const prevUci = this.getPremoveUci();
|
||||
this.premove = next;
|
||||
const nextUci = this.getPremoveUci();
|
||||
if (prevUci !== nextUci && this.onPremoveChangeCallback) {
|
||||
this.onPremoveChangeCallback(nextUci);
|
||||
}
|
||||
}
|
||||
|
||||
setMode(mode: BoardMode, playerColor?: Color): void {
|
||||
const nextColor = playerColor || this.playerColor;
|
||||
if (this.mode === mode && this.playerColor === nextColor) {
|
||||
return;
|
||||
}
|
||||
this.mode = mode;
|
||||
if (playerColor) this.playerColor = playerColor;
|
||||
this.playerColor = nextColor;
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.pendingPromotion = null;
|
||||
if (mode !== 'play') this.premove = null;
|
||||
this.renderPromotionPicker();
|
||||
if (mode !== 'play') {
|
||||
this.setPremove(null);
|
||||
}
|
||||
this.render();
|
||||
}
|
||||
|
||||
setOrientation(color: Color): void {
|
||||
if (this.orientation === color) return;
|
||||
this.orientation = color;
|
||||
this.render();
|
||||
}
|
||||
|
|
@ -142,7 +142,7 @@ export class ChessBoard {
|
|||
|
||||
clearPremove(): void {
|
||||
if (this.premove) {
|
||||
this.premove = null;
|
||||
this.setPremove(null);
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
|
|
@ -150,37 +150,40 @@ export class ChessBoard {
|
|||
private clearSelectionAndPremove(): void {
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.premove = null;
|
||||
this.pendingPromotion = null;
|
||||
this.renderPromotionPicker();
|
||||
this.setPremove(null);
|
||||
this.render();
|
||||
}
|
||||
|
||||
setPosition(fen: string, lastMoveUci?: string | null): void {
|
||||
const nextFrom = lastMoveUci && lastMoveUci.length >= 4 ? algToSq(lastMoveUci.slice(0, 2)) : -1;
|
||||
const nextTo = lastMoveUci && lastMoveUci.length >= 4 ? algToSq(lastMoveUci.slice(2, 4)) : -1;
|
||||
|
||||
if (fen === this.currentFen && nextFrom === this.lastMoveFrom && nextTo === this.lastMoveTo) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
this.chess.loadFen(fen);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (lastMoveUci && lastMoveUci.length >= 4) {
|
||||
this.lastMoveFrom = algToSq(lastMoveUci.slice(0, 2));
|
||||
this.lastMoveTo = algToSq(lastMoveUci.slice(2, 4));
|
||||
} else {
|
||||
this.lastMoveFrom = -1;
|
||||
this.lastMoveTo = -1;
|
||||
}
|
||||
|
||||
this.currentFen = fen;
|
||||
this.lastMoveFrom = nextFrom;
|
||||
this.lastMoveTo = nextTo;
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.pendingPromotion = null;
|
||||
this.renderPromotionPicker();
|
||||
|
||||
// Auto-execute queued premove if it's now our turn in play mode
|
||||
if (this.mode === 'play' && this.premove && this.chess.turn() === this.playerColor) {
|
||||
const pm = this.premove;
|
||||
this.premove = null;
|
||||
const uci = sqToAlg(pm.from) + sqToAlg(pm.to) + (pm.promotion || '');
|
||||
const legal = this.chess.legalMoves(pm.from);
|
||||
if (legal.some((m) => m.uci === uci)) {
|
||||
this.setPremove(null);
|
||||
const uci = resolveQueuedPremove(this.chess, pm);
|
||||
if (uci) {
|
||||
this.render();
|
||||
if (this.onMoveCallback) {
|
||||
this.onMoveCallback(uci);
|
||||
|
|
@ -209,16 +212,6 @@ export class ChessBoard {
|
|||
};
|
||||
}
|
||||
|
||||
private clientPointToSq(clientX: number, clientY: number): number {
|
||||
const rect = this.grid.getBoundingClientRect();
|
||||
if (clientX < rect.left || clientX > rect.right || clientY < rect.top || clientY > rect.bottom) {
|
||||
return -1;
|
||||
}
|
||||
const vc = Math.min(7, Math.max(0, Math.floor(((clientX - rect.left) / rect.width) * 8)));
|
||||
const vr = Math.min(7, Math.max(0, Math.floor(((clientY - rect.top) / rect.height) * 8)));
|
||||
return this.visualIndexToSq((vr << 3) | vc);
|
||||
}
|
||||
|
||||
private isPieceInteractive(piece: Piece | null): boolean {
|
||||
if (!piece || this.mode === 'readonly') return false;
|
||||
if (this.mode === 'analyze') {
|
||||
|
|
@ -227,6 +220,10 @@ export class ChessBoard {
|
|||
return piece.color === this.playerColor;
|
||||
}
|
||||
|
||||
private isPremoveTurn(): boolean {
|
||||
return this.mode === 'play' && this.chess.turn() !== this.playerColor;
|
||||
}
|
||||
|
||||
private computeTargetsForSquare(fromSq: number): Map<number, PromotionPiece[]> {
|
||||
const map = new Map<number, PromotionPiece[]>();
|
||||
const piece = this.chess.get(fromSq);
|
||||
|
|
@ -245,44 +242,8 @@ export class ChessBoard {
|
|||
return map;
|
||||
}
|
||||
|
||||
// Premove geometric targets (only in 'play' mode when waiting for opponent)
|
||||
if (this.mode === 'play' && piece.color === this.playerColor) {
|
||||
const r = fromSq >> 3;
|
||||
const c = fromSq & 7;
|
||||
for (let to = 0; to < 64; to++) {
|
||||
if (to === fromSq) continue;
|
||||
const tr = to >> 3;
|
||||
const tc = to & 7;
|
||||
const dr = tr - r;
|
||||
const dc = tc - c;
|
||||
const adr = Math.abs(dr);
|
||||
const adc = Math.abs(dc);
|
||||
let ok = false;
|
||||
|
||||
if (piece.type === 'p') {
|
||||
const forward = piece.color === 'w' ? -1 : 1;
|
||||
const startRank = piece.color === 'w' ? 6 : 1;
|
||||
if (dr === forward && adc <= 1) ok = true;
|
||||
else if (r === startRank && dr === forward * 2 && dc === 0) ok = true;
|
||||
if (ok) {
|
||||
const promoRank = piece.color === 'w' ? 0 : 7;
|
||||
map.set(to, tr === promoRank ? ['q', 'r', 'b', 'n'] : []);
|
||||
continue;
|
||||
}
|
||||
} else if (piece.type === 'n') {
|
||||
ok = (adr === 2 && adc === 1) || (adr === 1 && adc === 2);
|
||||
} else if (piece.type === 'b') {
|
||||
ok = adr === adc;
|
||||
} else if (piece.type === 'r') {
|
||||
ok = dr === 0 || dc === 0;
|
||||
} else if (piece.type === 'q') {
|
||||
ok = dr === 0 || dc === 0 || adr === adc;
|
||||
} else if (piece.type === 'k') {
|
||||
ok = (adr <= 1 && adc <= 1) || (dr === 0 && adc === 2 && ((piece.color === 'w' && r === 7 && c === 4) || (piece.color === 'b' && r === 0 && c === 4)));
|
||||
}
|
||||
|
||||
if (ok) map.set(to, []);
|
||||
}
|
||||
return computePremoveTargets(this.chess, fromSq);
|
||||
}
|
||||
|
||||
return map;
|
||||
|
|
@ -307,7 +268,7 @@ export class ChessBoard {
|
|||
|
||||
const piece = this.chess.get(fromSq);
|
||||
if (!piece) return false;
|
||||
const isPremove = this.mode === 'play' && this.chess.turn() !== this.playerColor;
|
||||
const isPremove = this.isPremoveTurn();
|
||||
const promos = targets.get(toSq) || [];
|
||||
|
||||
if (promos.length > 0) {
|
||||
|
|
@ -315,13 +276,14 @@ export class ChessBoard {
|
|||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.renderPromotionPicker();
|
||||
this.render();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isPremove) {
|
||||
this.premove = { from: fromSq, to: toSq };
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.setPremove({ from: fromSq, to: toSq });
|
||||
this.render();
|
||||
return true;
|
||||
}
|
||||
|
|
@ -336,6 +298,37 @@ export class ChessBoard {
|
|||
return true;
|
||||
}
|
||||
|
||||
private handleSquareTap(sq: number): void {
|
||||
if (this.mode === 'readonly' || this.pendingPromotion !== null) return;
|
||||
|
||||
if (this.selectedSq >= 0) {
|
||||
if (sq === this.selectedSq) {
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.render();
|
||||
return;
|
||||
}
|
||||
if (this.legalTargets.has(sq)) {
|
||||
this.tryMoveTo(this.selectedSq, sq);
|
||||
return;
|
||||
}
|
||||
if (this.isPieceInteractive(this.chess.get(sq))) {
|
||||
this.setPremove(null);
|
||||
this.selectSquare(sq);
|
||||
return;
|
||||
}
|
||||
this.clearSelectionAndPremove();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isPieceInteractive(this.chess.get(sq))) {
|
||||
this.setPremove(null);
|
||||
this.selectSquare(sq);
|
||||
} else if (this.premove) {
|
||||
this.clearPremove();
|
||||
}
|
||||
}
|
||||
|
||||
private renderPromotionPicker(): void {
|
||||
clearNode(this.promoOverlay);
|
||||
if (!this.pendingPromotion) {
|
||||
|
|
@ -355,7 +348,7 @@ export class ChessBoard {
|
|||
this.pendingPromotion = null;
|
||||
this.promoOverlay.className = 'promo-overlay hidden';
|
||||
if (pending.isPremove) {
|
||||
this.premove = { from: pending.from, to: pending.to, promotion: pt };
|
||||
this.setPremove({ from: pending.from, to: pending.to, promotion: pt });
|
||||
this.render();
|
||||
} else {
|
||||
const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt;
|
||||
|
|
@ -377,156 +370,12 @@ export class ChessBoard {
|
|||
this.promoOverlay.appendChild(box);
|
||||
}
|
||||
|
||||
private onMouseDown(e: MouseEvent): void {
|
||||
if (e.button !== 0 || this.pendingPromotion) return;
|
||||
const sq = this.clientPointToSq(e.clientX, e.clientY);
|
||||
if (sq < 0) return;
|
||||
this.handlePointerDown(sq, e.clientX, e.clientY, null);
|
||||
}
|
||||
|
||||
private onTouchStart(e: TouchEvent): void {
|
||||
if (this.pendingPromotion || e.touches.length !== 1) return;
|
||||
const t = e.touches[0]!;
|
||||
const sq = this.clientPointToSq(t.clientX, t.clientY);
|
||||
if (sq < 0) return;
|
||||
this.handlePointerDown(sq, t.clientX, t.clientY, t.identifier);
|
||||
}
|
||||
|
||||
private handlePointerDown(sq: number, clientX: number, clientY: number, touchId: number | null): void {
|
||||
if (this.mode === 'readonly') return;
|
||||
|
||||
// If user already selected a piece and clicks a valid destination, execute move immediately
|
||||
if (this.selectedSq >= 0 && this.selectedSq !== sq && this.legalTargets.has(sq)) {
|
||||
this.tryMoveTo(this.selectedSq, sq);
|
||||
return;
|
||||
}
|
||||
|
||||
const piece = this.chess.get(sq);
|
||||
if (!this.isPieceInteractive(piece)) {
|
||||
if (this.selectedSq >= 0 || this.premove) {
|
||||
this.clearSelectionAndPremove();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.pointerDownSq = sq;
|
||||
this.dragStartX = clientX;
|
||||
this.dragStartY = clientY;
|
||||
this.dragActive = false;
|
||||
this.dragTouchId = touchId;
|
||||
}
|
||||
|
||||
private onMouseMove(e: MouseEvent): void {
|
||||
if (this.pointerDownSq < 0 || this.dragTouchId !== null) return;
|
||||
this.handlePointerMove(e.clientX, e.clientY);
|
||||
}
|
||||
|
||||
private onTouchMove(e: TouchEvent): void {
|
||||
if (this.pointerDownSq < 0 || this.dragTouchId === null) return;
|
||||
let touch: Touch | null = null;
|
||||
for (let i = 0; i < e.touches.length; i++) {
|
||||
if (e.touches[i]!.identifier === this.dragTouchId) {
|
||||
touch = e.touches[i]!;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!touch) return;
|
||||
e.preventDefault();
|
||||
this.handlePointerMove(touch.clientX, touch.clientY);
|
||||
}
|
||||
|
||||
private handlePointerMove(clientX: number, clientY: number): void {
|
||||
if (!this.dragActive) {
|
||||
const dx = clientX - this.dragStartX;
|
||||
const dy = clientY - this.dragStartY;
|
||||
if (dx * dx + dy * dy < 25) return;
|
||||
|
||||
const piece = this.chess.get(this.pointerDownSq);
|
||||
if (!piece) {
|
||||
this.pointerDownSq = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
this.dragActive = true;
|
||||
this.selectedSq = this.pointerDownSq;
|
||||
this.legalTargets = this.computeTargetsForSquare(this.pointerDownSq);
|
||||
this.render();
|
||||
|
||||
const sqSize = this.grid.getBoundingClientRect().width / 8;
|
||||
const ghost = createPieceNode(piece.color, piece.type);
|
||||
ghost.className = 'piece drag-ghost';
|
||||
ghost.style.width = `${sqSize}px`;
|
||||
ghost.style.height = `${sqSize}px`;
|
||||
document.body.appendChild(ghost);
|
||||
this.dragGhost = ghost;
|
||||
}
|
||||
|
||||
if (this.dragGhost) {
|
||||
this.dragGhost.style.left = `${clientX}px`;
|
||||
this.dragGhost.style.top = `${clientY}px`;
|
||||
}
|
||||
}
|
||||
|
||||
private onMouseUp(e: MouseEvent): void {
|
||||
if (this.pointerDownSq < 0 || this.dragTouchId !== null) return;
|
||||
this.handlePointerUp(e.clientX, e.clientY);
|
||||
}
|
||||
|
||||
private onTouchEnd(e: TouchEvent): void {
|
||||
if (this.pointerDownSq < 0 || this.dragTouchId === null) return;
|
||||
let touch: Touch | null = null;
|
||||
for (let i = 0; i < e.changedTouches.length; i++) {
|
||||
if (e.changedTouches[i]!.identifier === this.dragTouchId) {
|
||||
touch = e.changedTouches[i]!;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!touch) return;
|
||||
this.handlePointerUp(touch.clientX, touch.clientY);
|
||||
}
|
||||
|
||||
private handlePointerUp(clientX: number, clientY: number): void {
|
||||
const startSq = this.pointerDownSq;
|
||||
const wasDragging = this.dragActive;
|
||||
this.pointerDownSq = -1;
|
||||
this.dragActive = false;
|
||||
this.dragTouchId = null;
|
||||
this.endDragGhost();
|
||||
|
||||
const dropSq = this.clientPointToSq(clientX, clientY);
|
||||
|
||||
if (wasDragging) {
|
||||
if (dropSq >= 0 && dropSq !== startSq && this.legalTargets.has(dropSq)) {
|
||||
this.tryMoveTo(startSq, dropSq);
|
||||
} else {
|
||||
this.render();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Tap / Click behavior
|
||||
if (this.selectedSq === startSq) {
|
||||
this.selectedSq = -1;
|
||||
this.legalTargets.clear();
|
||||
this.render();
|
||||
} else {
|
||||
if (this.premove) this.premove = null;
|
||||
this.selectSquare(startSq);
|
||||
}
|
||||
}
|
||||
|
||||
private endDragGhost(): void {
|
||||
if (this.dragGhost && this.dragGhost.parentNode) {
|
||||
this.dragGhost.parentNode.removeChild(this.dragGhost);
|
||||
}
|
||||
this.dragGhost = null;
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
const files = 'abcdefgh';
|
||||
const ranks = '87654321';
|
||||
const turnInCheck = this.chess.inCheck();
|
||||
const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1;
|
||||
const premoveTurn = this.isPremoveTurn();
|
||||
|
||||
for (let vi = 0; vi < 64; vi++) {
|
||||
const sq = this.visualIndexToSq(vi);
|
||||
|
|
@ -535,14 +384,22 @@ export class ChessBoard {
|
|||
const vr = vi >> 3;
|
||||
const vc = vi & 7;
|
||||
|
||||
const piece = this.chess.get(sq);
|
||||
const isTarget = this.legalTargets.has(sq);
|
||||
const isInteractive = this.isPieceInteractive(piece);
|
||||
|
||||
const isLight = ((r + c) & 1) === 0;
|
||||
const sqEl = this.squareEls[vi]!;
|
||||
let cls = 'sq ' + (isLight ? 'sq-light' : 'sq-dark');
|
||||
|
||||
if (sq === this.lastMoveFrom || sq === this.lastMoveTo) cls += ' sq-last';
|
||||
if (sq === this.selectedSq) cls += ' sq-selected';
|
||||
if (sq === this.selectedSq) {
|
||||
cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected';
|
||||
}
|
||||
if (sq === checkKingSq) cls += ' sq-check';
|
||||
if (this.premove && (sq === this.premove.from || sq === this.premove.to)) cls += ' sq-premove';
|
||||
if (isInteractive) cls += ' sq-interactive';
|
||||
if (isTarget) cls += ' sq-target';
|
||||
|
||||
sqEl.className = cls;
|
||||
clearNode(sqEl);
|
||||
|
|
@ -556,18 +413,20 @@ export class ChessBoard {
|
|||
sqEl.appendChild(el('span', { className: 'coord-file' }, files.charAt(c)));
|
||||
}
|
||||
|
||||
const piece = this.chess.get(sq);
|
||||
if (piece) {
|
||||
const pieceNode = createPieceNode(piece.color, piece.type);
|
||||
if (this.dragActive && sq === this.selectedSq) {
|
||||
pieceNode.className += ' piece-dragging-origin';
|
||||
}
|
||||
sqEl.appendChild(pieceNode);
|
||||
sqEl.appendChild(createPieceNode(piece.color, piece.type));
|
||||
}
|
||||
|
||||
if (this.legalTargets.has(sq)) {
|
||||
if (isTarget) {
|
||||
const isCapture = piece !== null;
|
||||
sqEl.appendChild(el('div', { className: isCapture ? 'hint-capture' : 'hint-dot' }));
|
||||
const hintCls = premoveTurn
|
||||
? isCapture
|
||||
? 'hint-premove-capture'
|
||||
: 'hint-premove-dot'
|
||||
: isCapture
|
||||
? 'hint-capture'
|
||||
: 'hint-dot';
|
||||
sqEl.appendChild(el('div', { className: hintCls }));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -578,13 +437,22 @@ export class ChessBoard {
|
|||
while (this.svgArrows.firstChild) {
|
||||
this.svgArrows.removeChild(this.svgArrows.firstChild);
|
||||
}
|
||||
if (this.arrows.length === 0) return;
|
||||
|
||||
const allArrows = this.arrows.slice();
|
||||
if (this.premove) {
|
||||
allArrows.push({
|
||||
from: sqToAlg(this.premove.from),
|
||||
to: sqToAlg(this.premove.to),
|
||||
color: '#2979ff'
|
||||
});
|
||||
}
|
||||
if (allArrows.length === 0) return;
|
||||
|
||||
const svgNs = 'http://www.w3.org/2000/svg';
|
||||
const defs = document.createElementNS(svgNs, 'defs');
|
||||
|
||||
for (let i = 0; i < this.arrows.length; i++) {
|
||||
const arr = this.arrows[i]!;
|
||||
for (let i = 0; i < allArrows.length; i++) {
|
||||
const arr = allArrows[i]!;
|
||||
const fromSq = algToSq(arr.from);
|
||||
const toSq = algToSq(arr.to);
|
||||
if (fromSq < 0 || toSq < 0 || fromSq === toSq) continue;
|
||||
|
|
@ -608,8 +476,8 @@ export class ChessBoard {
|
|||
}
|
||||
this.svgArrows.appendChild(defs);
|
||||
|
||||
for (let i = 0; i < this.arrows.length; i++) {
|
||||
const arr = this.arrows[i]!;
|
||||
for (let i = 0; i < allArrows.length; i++) {
|
||||
const arr = allArrows[i]!;
|
||||
const fromSq = algToSq(arr.from);
|
||||
const toSq = algToSq(arr.to);
|
||||
if (fromSq < 0 || toSq < 0 || fromSq === toSq) continue;
|
||||
|
|
@ -636,7 +504,7 @@ export class ChessBoard {
|
|||
line.setAttribute('stroke', arr.color || '#629924');
|
||||
line.setAttribute('stroke-width', '15');
|
||||
line.setAttribute('stroke-linecap', 'round');
|
||||
line.setAttribute('opacity', '0.82');
|
||||
line.setAttribute('opacity', '0.78');
|
||||
line.setAttribute('marker-end', `url(#arrow-${i})`);
|
||||
this.svgArrows.appendChild(line);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,8 @@
|
|||
--sq-dark: #b58863;
|
||||
--sq-last: rgba(155, 199, 0, 0.42);
|
||||
--sq-selected: rgba(20, 85, 30, 0.52);
|
||||
--sq-premove: rgba(35, 105, 175, 0.5);
|
||||
--sq-premove: rgba(41, 121, 255, 0.45);
|
||||
--sq-premove-selected: rgba(41, 121, 255, 0.52);
|
||||
--coord-light: #9e7350;
|
||||
--coord-dark: #f0d9b5;
|
||||
}
|
||||
|
|
@ -1009,6 +1010,8 @@ a {
|
|||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
-webkit-touch-callout: none;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
.board-wrap {
|
||||
|
|
@ -1036,6 +1039,11 @@ a {
|
|||
height: 12.5%;
|
||||
}
|
||||
|
||||
.sq-interactive,
|
||||
.sq-target {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sq-light {
|
||||
background: var(--sq-light);
|
||||
}
|
||||
|
|
@ -1077,6 +1085,17 @@ a {
|
|||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sq-premove-selected:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
background: var(--sq-premove-selected);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sq-check {
|
||||
background: radial-gradient(ellipse at center, #ff1111 0%, #c92020 55%, rgba(200, 0, 0, 0) 85%);
|
||||
}
|
||||
|
|
@ -1120,7 +1139,7 @@ a {
|
|||
bottom: 3%;
|
||||
left: 3%;
|
||||
z-index: 3;
|
||||
cursor: pointer;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.piece-svg {
|
||||
|
|
@ -1129,17 +1148,6 @@ a {
|
|||
display: block;
|
||||
}
|
||||
|
||||
.piece-dragging-origin {
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
.drag-ghost {
|
||||
position: fixed;
|
||||
z-index: 999;
|
||||
pointer-events: none;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.hint-dot {
|
||||
position: absolute;
|
||||
top: 36%;
|
||||
|
|
@ -1164,6 +1172,30 @@ a {
|
|||
pointer-events: none;
|
||||
}
|
||||
|
||||
.hint-premove-dot {
|
||||
position: absolute;
|
||||
top: 36%;
|
||||
left: 36%;
|
||||
width: 28%;
|
||||
height: 28%;
|
||||
border-radius: 50%;
|
||||
background: rgba(41, 121, 255, 0.58);
|
||||
z-index: 4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.hint-premove-capture {
|
||||
position: absolute;
|
||||
top: 6%;
|
||||
right: 6%;
|
||||
bottom: 6%;
|
||||
left: 6%;
|
||||
border-radius: 50%;
|
||||
border: 4px solid rgba(41, 121, 255, 0.65);
|
||||
z-index: 4;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.board-arrows {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
|
|
@ -1222,6 +1254,7 @@ a {
|
|||
cursor: pointer;
|
||||
}
|
||||
|
||||
.premove-banner,
|
||||
.live-notice {
|
||||
margin-top: 6px;
|
||||
padding: 6px 10px;
|
||||
|
|
@ -1233,6 +1266,10 @@ a {
|
|||
font-size: 12px;
|
||||
}
|
||||
|
||||
.premove-banner {
|
||||
border-left: 3px solid #2979ff;
|
||||
}
|
||||
|
||||
.game-meta-line {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
|
|
|
|||
|
|
@ -50,6 +50,9 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
mode: 'readonly',
|
||||
onMove(uci) {
|
||||
wsClient.send({ type: 'game:move', gameId, uci });
|
||||
},
|
||||
onPremoveChange(premoveUci) {
|
||||
renderPremoveBanner(premoveUci);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -64,13 +67,14 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
const current = board.getOrientation();
|
||||
orientationOverride = current === 'w' ? 'b' : 'w';
|
||||
board.setOrientation(orientationOverride);
|
||||
renderLayout();
|
||||
if (game) updateDynamicHeaderBars(game);
|
||||
}
|
||||
});
|
||||
|
||||
// Dynamic UI refs updated without tearing down Board / Clocks
|
||||
const topPlayerBar = el('div', { className: 'player-bar' });
|
||||
const bottomPlayerBar = el('div', { className: 'player-bar' });
|
||||
const premoveBannerEl = el('div', { className: 'premove-banner hidden' });
|
||||
const liveNoticeEl = el('div', { className: 'live-notice hidden' });
|
||||
const statusBannerEl = el('div', { className: 'game-status-banner hidden' });
|
||||
const actionsEl = el('div', { className: 'game-actions' });
|
||||
|
|
@ -106,6 +110,7 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
boardCol.appendChild(topPlayerBar);
|
||||
boardCol.appendChild(board.root);
|
||||
boardCol.appendChild(bottomPlayerBar);
|
||||
boardCol.appendChild(premoveBannerEl);
|
||||
boardCol.appendChild(liveNoticeEl);
|
||||
layout.appendChild(boardCol);
|
||||
|
||||
|
|
@ -207,25 +212,23 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited');
|
||||
}
|
||||
|
||||
function renderLayout(): void {
|
||||
if (destroyed) return;
|
||||
if (errorMsg) {
|
||||
clearNode(container);
|
||||
const errPage = el('div', { className: 'page-container narrow-page' });
|
||||
const card = el('div', { className: 'card' });
|
||||
const body = el('div', { className: 'card-body' });
|
||||
body.appendChild(el('div', { className: 'alert alert-error' }, errorMsg));
|
||||
const back = el('button', { type: 'button', className: 'btn' }, 'Back to Lobby');
|
||||
back.addEventListener('click', () => ctx.navigate('/'));
|
||||
body.appendChild(back);
|
||||
card.appendChild(body);
|
||||
errPage.appendChild(card);
|
||||
container.appendChild(errPage);
|
||||
function renderPremoveBanner(premoveUci: string | null): void {
|
||||
clearNode(premoveBannerEl);
|
||||
if (!premoveUci || premoveUci.length < 4) {
|
||||
premoveBannerEl.className = 'premove-banner hidden';
|
||||
return;
|
||||
}
|
||||
const from = premoveUci.slice(0, 2);
|
||||
const to = premoveUci.slice(2, 4);
|
||||
const promo = premoveUci.length === 5 ? `=${premoveUci.charAt(4).toUpperCase()}` : '';
|
||||
premoveBannerEl.className = 'premove-banner';
|
||||
premoveBannerEl.appendChild(el('span', null, `Premove queued: ${from} → ${to}${promo}`));
|
||||
const cancelBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel');
|
||||
cancelBtn.addEventListener('click', () => board.clearPremove());
|
||||
premoveBannerEl.appendChild(cancelBtn);
|
||||
}
|
||||
|
||||
if (!game) return;
|
||||
const g = game;
|
||||
function updateDynamicHeaderBars(g: ActiveGameState): void {
|
||||
const orient = effectiveOrientation(g);
|
||||
const topColor: Color = orient === 'w' ? 'b' : 'w';
|
||||
const bottomColor: Color = orient;
|
||||
|
|
@ -260,6 +263,28 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
} else {
|
||||
statusBannerEl.className = 'game-status-banner hidden';
|
||||
}
|
||||
}
|
||||
|
||||
function renderLayout(): void {
|
||||
if (destroyed) return;
|
||||
if (errorMsg) {
|
||||
clearNode(container);
|
||||
const errPage = el('div', { className: 'page-container narrow-page' });
|
||||
const card = el('div', { className: 'card' });
|
||||
const body = el('div', { className: 'card-body' });
|
||||
body.appendChild(el('div', { className: 'alert alert-error' }, errorMsg));
|
||||
const back = el('button', { type: 'button', className: 'btn' }, 'Back to Lobby');
|
||||
back.addEventListener('click', () => ctx.navigate('/'));
|
||||
body.appendChild(back);
|
||||
card.appendChild(body);
|
||||
errPage.appendChild(card);
|
||||
container.appendChild(errPage);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!game) return;
|
||||
const g = game;
|
||||
updateDynamicHeaderBars(g);
|
||||
|
||||
// Action buttons
|
||||
renderActions(g);
|
||||
|
|
@ -481,11 +506,11 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
}
|
||||
}
|
||||
|
||||
// Countdown tick for disconnect / abort banners
|
||||
// Countdown tick for disconnect / abort banners (updates header bars without disturbing board selection/premoves)
|
||||
const countdownTimer = window.setInterval(() => {
|
||||
if (!game || game.finished) return;
|
||||
if (game.white.disconnectDeadlineMs || game.black.disconnectDeadlineMs || (game.abortDeadlineMs && game.movesUci.length < 2)) {
|
||||
renderLayout();
|
||||
updateDynamicHeaderBars(game);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
|
|
@ -538,7 +563,7 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
|||
game.black.connected = msg.blackConnected;
|
||||
game.black.disconnectDeadlineMs = msg.blackDisconnectDeadlineMs;
|
||||
game.spectatorCount = msg.spectatorCount;
|
||||
renderLayout();
|
||||
updateDynamicHeaderBars(game);
|
||||
} else if (msg.type === 'game:chat' && game && msg.gameId === gameId) {
|
||||
game.chat.push(msg.message);
|
||||
renderChat(game);
|
||||
|
|
|
|||
84
src/shared/premove.ts
Normal file
84
src/shared/premove.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { Chess, sqToAlg } from './chess';
|
||||
import type { PromotionPiece } from './types';
|
||||
|
||||
export interface QueuedPremove {
|
||||
from: number;
|
||||
to: number;
|
||||
promotion?: PromotionPiece;
|
||||
}
|
||||
|
||||
const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n'];
|
||||
|
||||
export function computePremoveTargets(chess: Chess, fromSq: number): Map<number, PromotionPiece[]> {
|
||||
const map = new Map<number, PromotionPiece[]>();
|
||||
const piece = chess.get(fromSq);
|
||||
if (!piece) return map;
|
||||
|
||||
const r = fromSq >> 3;
|
||||
const c = fromSq & 7;
|
||||
const castlingField = piece.type === 'k' ? chess.fen().split(' ')[2] || '' : '';
|
||||
|
||||
for (let to = 0; to < 64; to++) {
|
||||
if (to === fromSq) continue;
|
||||
const tr = to >> 3;
|
||||
const tc = to & 7;
|
||||
const dr = tr - r;
|
||||
const dc = tc - c;
|
||||
const adr = Math.abs(dr);
|
||||
const adc = Math.abs(dc);
|
||||
|
||||
if (piece.type === 'p') {
|
||||
const forward = piece.color === 'w' ? -1 : 1;
|
||||
const startRank = piece.color === 'w' ? 6 : 1;
|
||||
const promoRank = piece.color === 'w' ? 0 : 7;
|
||||
if ((dr === forward && adc <= 1) || (r === startRank && dr === forward * 2 && dc === 0)) {
|
||||
map.set(to, tr === promoRank ? PROMO_LIST.slice() : []);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let ok = false;
|
||||
if (piece.type === 'n') {
|
||||
ok = (adr === 2 && adc === 1) || (adr === 1 && adc === 2);
|
||||
} else if (piece.type === 'b') {
|
||||
ok = adr === adc;
|
||||
} else if (piece.type === 'r') {
|
||||
ok = dr === 0 || dc === 0;
|
||||
} else if (piece.type === 'q') {
|
||||
ok = dr === 0 || dc === 0 || adr === adc;
|
||||
} else if (piece.type === 'k') {
|
||||
if (adr <= 1 && adc <= 1) {
|
||||
ok = true;
|
||||
} else if (dr === 0 && adc === 2) {
|
||||
if (piece.color === 'w' && r === 7 && c === 4) {
|
||||
if (tc === 6 && castlingField.indexOf('K') >= 0) ok = true;
|
||||
if (tc === 2 && castlingField.indexOf('Q') >= 0) ok = true;
|
||||
} else if (piece.color === 'b' && r === 0 && c === 4) {
|
||||
if (tc === 6 && castlingField.indexOf('k') >= 0) ok = true;
|
||||
if (tc === 2 && castlingField.indexOf('q') >= 0) ok = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
map.set(to, []);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
export function resolveQueuedPremove(chess: Chess, premove: QueuedPremove): string | null {
|
||||
const piece = chess.get(premove.from);
|
||||
if (!piece || piece.color !== chess.turn()) {
|
||||
return null;
|
||||
}
|
||||
const uci = sqToAlg(premove.from) + sqToAlg(premove.to) + (premove.promotion || '');
|
||||
const legal = chess.legalMoves(premove.from);
|
||||
for (let i = 0; i < legal.length; i++) {
|
||||
if (legal[i]!.uci === uci) {
|
||||
return uci;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
56
tests/premove.test.ts
Normal file
56
tests/premove.test.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { Chess, algToSq } from '../src/shared/chess';
|
||||
import { computePremoveTargets, resolveQueuedPremove } from '../src/shared/premove';
|
||||
|
||||
test('Pawn premove targets include 1-step, 2-step from start, diagonal captures, and promotions', () => {
|
||||
const c = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1');
|
||||
const d2Targets = computePremoveTargets(c, algToSq('d2'));
|
||||
assert.equal(d2Targets.has(algToSq('d3')), true);
|
||||
assert.equal(d2Targets.has(algToSq('d4')), true);
|
||||
assert.equal(d2Targets.has(algToSq('c3')), true);
|
||||
assert.equal(d2Targets.has(algToSq('e3')), true);
|
||||
assert.equal(d2Targets.has(algToSq('d5')), false);
|
||||
|
||||
const promoChess = new Chess('4k3/2P5/8/8/8/8/8/4K3 b - - 0 1');
|
||||
const c7Targets = computePremoveTargets(promoChess, algToSq('c7'));
|
||||
assert.deepEqual(c7Targets.get(algToSq('c8')), ['q', 'r', 'b', 'n']);
|
||||
assert.deepEqual(c7Targets.get(algToSq('b8')), ['q', 'r', 'b', 'n']);
|
||||
assert.deepEqual(c7Targets.get(algToSq('d8')), ['q', 'r', 'b', 'n']);
|
||||
});
|
||||
|
||||
test('Slider premove targets ignore blockers and resolve recapture when turn returns', () => {
|
||||
// Black to move: Black bishop on g4 can take White knight on f3; White queen on d1 premoves Qxf3
|
||||
const c = new Chess('r2qkbnr/ppp2ppp/2np4/4p3/4P1b1/3P1N2/PPP2PPP/RNBQKB1R b KQkq - 0 4');
|
||||
const qTargets = computePremoveTargets(c, algToSq('d1'));
|
||||
// Even though f3 is currently occupied by own knight and e2 is occupied by own pawn, queen can premove d1->f3 and d1->h5
|
||||
assert.equal(qTargets.has(algToSq('f3')), true);
|
||||
assert.equal(qTargets.has(algToSq('h5')), true);
|
||||
|
||||
// If Black plays Bxf3, White's queued premove d1->f3 becomes legal and resolves
|
||||
c.moveUci('g4f3');
|
||||
const resolved = resolveQueuedPremove(c, { from: algToSq('d1'), to: algToSq('f3') });
|
||||
assert.equal(resolved, 'd1f3');
|
||||
|
||||
// If Black instead plays a6, f3 is still occupied by White's own knight -> premove d1->f3 is dropped (null)
|
||||
c.undo();
|
||||
c.moveUci('a7a6');
|
||||
const dropped = resolveQueuedPremove(c, { from: algToSq('d1'), to: algToSq('f3') });
|
||||
assert.equal(dropped, null);
|
||||
});
|
||||
|
||||
test('King castling premove targets respect FEN castling rights and check resolution', () => {
|
||||
const withRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1');
|
||||
const kTargets = computePremoveTargets(withRights, algToSq('e1'));
|
||||
assert.equal(kTargets.has(algToSq('g1')), true);
|
||||
assert.equal(kTargets.has(algToSq('c1')), true);
|
||||
|
||||
const noRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b - - 0 1');
|
||||
const kNoTargets = computePremoveTargets(noRights, algToSq('e1'));
|
||||
assert.equal(kNoTargets.has(algToSq('g1')), false);
|
||||
assert.equal(kNoTargets.has(algToSq('c1')), false);
|
||||
|
||||
// If Black puts White in check and White had premoved a non-evading pawn push, resolveQueuedPremove returns null
|
||||
const checkGame = new Chess('4k3/8/8/8/8/8/4P3/4K2r w - - 0 1');
|
||||
assert.equal(resolveQueuedPremove(checkGame, { from: algToSq('e2'), to: algToSq('e4') }), null);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue