Compare commits
2 commits
02b8bafb1e
...
14263d3c32
| Author | SHA1 | Date | |
|---|---|---|---|
| 14263d3c32 | |||
| 3ccab53b41 |
12 changed files with 462 additions and 105 deletions
|
|
@ -4,7 +4,7 @@ Lightweight Lichess-style chess server and Stockfish analysis web app built with
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **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).
|
- **Simple, sharp, old-device-friendly UI**: Dark & Light themes, 4 board color palettes, inline SVG Staunton pieces, tap-to-move, 25-move premove queue, Web Audio sounds (ES2017 / Safari 12+ compatible).
|
||||||
- **Accounts (no email required)**: Username + password registration (`crypto.scrypt` + `HttpOnly` session cookies).
|
- **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.
|
- **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.
|
- **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,5 +1,11 @@
|
||||||
import { Chess, algToSq, sqToAlg } from '../../shared/chess';
|
import { Chess, algToSq, sqToAlg } from '../../shared/chess';
|
||||||
import { type QueuedPremove, computePremoveTargets, resolveQueuedPremove } from '../../shared/premove';
|
import {
|
||||||
|
MAX_PREMOVES,
|
||||||
|
type QueuedPremove,
|
||||||
|
applyPremoveQueueToBoard,
|
||||||
|
computePremoveTargets,
|
||||||
|
resolveQueuedPremove
|
||||||
|
} from '../../shared/premove';
|
||||||
import type { Color, Piece, PromotionPiece } from '../../shared/types';
|
import type { Color, Piece, PromotionPiece } from '../../shared/types';
|
||||||
import { createPieceNode } from '../pieces';
|
import { createPieceNode } from '../pieces';
|
||||||
import { clearNode, el } from '../dom';
|
import { clearNode, el } from '../dom';
|
||||||
|
|
@ -17,7 +23,11 @@ export interface BoardOptions {
|
||||||
mode?: BoardMode;
|
mode?: BoardMode;
|
||||||
playerColor?: Color;
|
playerColor?: Color;
|
||||||
onMove?: (uci: string) => void;
|
onMove?: (uci: string) => void;
|
||||||
onPremoveChange?: (premoveUci: string | null) => void;
|
onPremoveChange?: (premoveQueueUci: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function premoveToUci(pm: QueuedPremove): string {
|
||||||
|
return sqToAlg(pm.from) + sqToAlg(pm.to) + (pm.promotion || '');
|
||||||
}
|
}
|
||||||
|
|
||||||
export class ChessBoard {
|
export class ChessBoard {
|
||||||
|
|
@ -34,13 +44,13 @@ export class ChessBoard {
|
||||||
private mode: BoardMode = 'readonly';
|
private mode: BoardMode = 'readonly';
|
||||||
private playerColor: Color = 'w';
|
private playerColor: Color = 'w';
|
||||||
private onMoveCallback?: (uci: string) => void;
|
private onMoveCallback?: (uci: string) => void;
|
||||||
private onPremoveChangeCallback?: (premoveUci: string | null) => void;
|
private onPremoveChangeCallback?: (premoveQueueUci: string[]) => void;
|
||||||
|
|
||||||
private selectedSq: number = -1;
|
private selectedSq: number = -1;
|
||||||
private legalTargets = new Map<number, PromotionPiece[]>();
|
private legalTargets = new Map<number, PromotionPiece[]>();
|
||||||
private lastMoveFrom: number = -1;
|
private lastMoveFrom: number = -1;
|
||||||
private lastMoveTo: number = -1;
|
private lastMoveTo: number = -1;
|
||||||
private premove: QueuedPremove | null = null;
|
private premoveQueue: QueuedPremove[] = [];
|
||||||
private arrows: BoardArrow[] = [];
|
private arrows: BoardArrow[] = [];
|
||||||
private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null;
|
private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null;
|
||||||
|
|
||||||
|
|
@ -79,7 +89,13 @@ export class ChessBoard {
|
||||||
|
|
||||||
this.grid.addEventListener('contextmenu', (e) => {
|
this.grid.addEventListener('contextmenu', (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
this.clearSelectionAndPremove();
|
if (this.selectedSq >= 0) {
|
||||||
|
this.selectedSq = -1;
|
||||||
|
this.legalTargets.clear();
|
||||||
|
this.render();
|
||||||
|
} else {
|
||||||
|
this.clearSelectionAndPremove();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.render();
|
this.render();
|
||||||
|
|
@ -89,17 +105,35 @@ export class ChessBoard {
|
||||||
// No global listeners to clean up in tap-tap mode
|
// No global listeners to clean up in tap-tap mode
|
||||||
}
|
}
|
||||||
|
|
||||||
getPremoveUci(): string | null {
|
getPremoveQueueUci(): string[] {
|
||||||
if (!this.premove) return null;
|
return this.premoveQueue.map(premoveToUci);
|
||||||
return sqToAlg(this.premove.from) + sqToAlg(this.premove.to) + (this.premove.promotion || '');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private setPremove(next: QueuedPremove | null): void {
|
private setPremoveQueue(next: QueuedPremove[]): void {
|
||||||
const prevUci = this.getPremoveUci();
|
const prevKey = this.premoveQueue.map(premoveToUci).join(',');
|
||||||
this.premove = next;
|
this.premoveQueue = next.slice(0, MAX_PREMOVES);
|
||||||
const nextUci = this.getPremoveUci();
|
const nextList = this.getPremoveQueueUci();
|
||||||
if (prevUci !== nextUci && this.onPremoveChangeCallback) {
|
if (prevKey !== nextList.join(',') && this.onPremoveChangeCallback) {
|
||||||
this.onPremoveChangeCallback(nextUci);
|
this.onPremoveChangeCallback(nextList);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
popPremove(): void {
|
||||||
|
if (this.premoveQueue.length === 0) return;
|
||||||
|
this.selectedSq = -1;
|
||||||
|
this.legalTargets.clear();
|
||||||
|
this.pendingPromotion = null;
|
||||||
|
this.renderPromotionPicker();
|
||||||
|
this.setPremoveQueue(this.premoveQueue.slice(0, this.premoveQueue.length - 1));
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
clearPremove(): void {
|
||||||
|
if (this.premoveQueue.length > 0) {
|
||||||
|
this.selectedSq = -1;
|
||||||
|
this.legalTargets.clear();
|
||||||
|
this.setPremoveQueue([]);
|
||||||
|
this.render();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -115,7 +149,7 @@ export class ChessBoard {
|
||||||
this.pendingPromotion = null;
|
this.pendingPromotion = null;
|
||||||
this.renderPromotionPicker();
|
this.renderPromotionPicker();
|
||||||
if (mode !== 'play') {
|
if (mode !== 'play') {
|
||||||
this.setPremove(null);
|
this.setPremoveQueue([]);
|
||||||
}
|
}
|
||||||
this.render();
|
this.render();
|
||||||
}
|
}
|
||||||
|
|
@ -140,19 +174,12 @@ export class ChessBoard {
|
||||||
this.renderArrows();
|
this.renderArrows();
|
||||||
}
|
}
|
||||||
|
|
||||||
clearPremove(): void {
|
|
||||||
if (this.premove) {
|
|
||||||
this.setPremove(null);
|
|
||||||
this.render();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private clearSelectionAndPremove(): void {
|
private clearSelectionAndPremove(): void {
|
||||||
this.selectedSq = -1;
|
this.selectedSq = -1;
|
||||||
this.legalTargets.clear();
|
this.legalTargets.clear();
|
||||||
this.pendingPromotion = null;
|
this.pendingPromotion = null;
|
||||||
this.renderPromotionPicker();
|
this.renderPromotionPicker();
|
||||||
this.setPremove(null);
|
this.setPremoveQueue([]);
|
||||||
this.render();
|
this.render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -178,18 +205,28 @@ export class ChessBoard {
|
||||||
this.pendingPromotion = null;
|
this.pendingPromotion = null;
|
||||||
this.renderPromotionPicker();
|
this.renderPromotionPicker();
|
||||||
|
|
||||||
// Auto-execute queued premove if it's now our turn in play mode
|
// Auto-execute first queued premove when our turn arrives in play mode
|
||||||
if (this.mode === 'play' && this.premove && this.chess.turn() === this.playerColor) {
|
if (this.mode === 'play' && this.premoveQueue.length > 0 && this.chess.turn() === this.playerColor) {
|
||||||
const pm = this.premove;
|
const nextPm = this.premoveQueue[0]!;
|
||||||
this.setPremove(null);
|
const remaining = this.premoveQueue.slice(1);
|
||||||
const uci = resolveQueuedPremove(this.chess, pm);
|
const uci = resolveQueuedPremove(this.chess, nextPm);
|
||||||
if (uci) {
|
if (uci) {
|
||||||
|
const applied = this.chess.moveUci(uci);
|
||||||
|
if (applied) {
|
||||||
|
this.currentFen = this.chess.fen();
|
||||||
|
this.lastMoveFrom = applied.from;
|
||||||
|
this.lastMoveTo = applied.to;
|
||||||
|
}
|
||||||
|
this.setPremoveQueue(remaining);
|
||||||
this.render();
|
this.render();
|
||||||
if (this.onMoveCallback) {
|
if (this.onMoveCallback) {
|
||||||
this.onMoveCallback(uci);
|
this.onMoveCallback(uci);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// First premove became illegal -> cancel remaining queue
|
||||||
|
this.setPremoveQueue([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.render();
|
this.render();
|
||||||
|
|
@ -212,6 +249,13 @@ export class ChessBoard {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getDisplayBoard(): Array<Piece | null> {
|
||||||
|
if (this.premoveQueue.length > 0) {
|
||||||
|
return applyPremoveQueueToBoard(this.chess.board(), this.premoveQueue);
|
||||||
|
}
|
||||||
|
return this.chess.board();
|
||||||
|
}
|
||||||
|
|
||||||
private isPieceInteractive(piece: Piece | null): boolean {
|
private isPieceInteractive(piece: Piece | null): boolean {
|
||||||
if (!piece || this.mode === 'readonly') return false;
|
if (!piece || this.mode === 'readonly') return false;
|
||||||
if (this.mode === 'analyze') {
|
if (this.mode === 'analyze') {
|
||||||
|
|
@ -226,9 +270,19 @@ export class ChessBoard {
|
||||||
|
|
||||||
private computeTargetsForSquare(fromSq: number): Map<number, PromotionPiece[]> {
|
private computeTargetsForSquare(fromSq: number): Map<number, PromotionPiece[]> {
|
||||||
const map = new Map<number, PromotionPiece[]>();
|
const map = new Map<number, PromotionPiece[]>();
|
||||||
|
|
||||||
|
if (this.isPremoveTurn()) {
|
||||||
|
if (this.premoveQueue.length >= MAX_PREMOVES) {
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
const projected = this.getDisplayBoard();
|
||||||
|
const piece = projected[fromSq] ?? null;
|
||||||
|
if (!piece || piece.color !== this.playerColor) return map;
|
||||||
|
return computePremoveTargets(this.chess, fromSq, this.premoveQueue);
|
||||||
|
}
|
||||||
|
|
||||||
const piece = this.chess.get(fromSq);
|
const piece = this.chess.get(fromSq);
|
||||||
if (!piece) return map;
|
if (!piece) return map;
|
||||||
|
|
||||||
if (this.mode === 'analyze' || this.chess.turn() === piece.color) {
|
if (this.mode === 'analyze' || this.chess.turn() === piece.color) {
|
||||||
const legal = this.chess.legalMoves(fromSq);
|
const legal = this.chess.legalMoves(fromSq);
|
||||||
for (let i = 0; i < legal.length; i++) {
|
for (let i = 0; i < legal.length; i++) {
|
||||||
|
|
@ -239,34 +293,47 @@ export class ChessBoard {
|
||||||
}
|
}
|
||||||
map.set(m.to, list);
|
map.set(m.to, list);
|
||||||
}
|
}
|
||||||
return map;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.mode === 'play' && piece.color === this.playerColor) {
|
|
||||||
return computePremoveTargets(this.chess, fromSq);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
private selectSquare(sq: number): void {
|
private selectSquare(sq: number): void {
|
||||||
const piece = this.chess.get(sq);
|
const piece = this.getDisplayBoard()[sq] ?? null;
|
||||||
if (!this.isPieceInteractive(piece)) {
|
if (!this.isPieceInteractive(piece)) {
|
||||||
this.selectedSq = -1;
|
this.selectedSq = -1;
|
||||||
this.legalTargets.clear();
|
this.legalTargets.clear();
|
||||||
this.render();
|
this.render();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (this.isPremoveTurn() && this.premoveQueue.length >= MAX_PREMOVES) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.selectedSq = sq;
|
this.selectedSq = sq;
|
||||||
this.legalTargets = this.computeTargetsForSquare(sq);
|
this.legalTargets = this.computeTargetsForSquare(sq);
|
||||||
this.render();
|
this.render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private commitOwnLiveMove(uci: string): void {
|
||||||
|
const applied = this.chess.moveUci(uci);
|
||||||
|
if (applied) {
|
||||||
|
this.currentFen = this.chess.fen();
|
||||||
|
this.lastMoveFrom = applied.from;
|
||||||
|
this.lastMoveTo = applied.to;
|
||||||
|
}
|
||||||
|
this.selectedSq = -1;
|
||||||
|
this.legalTargets.clear();
|
||||||
|
this.render();
|
||||||
|
if (this.onMoveCallback) {
|
||||||
|
this.onMoveCallback(uci);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private tryMoveTo(fromSq: number, toSq: number): boolean {
|
private tryMoveTo(fromSq: number, toSq: number): boolean {
|
||||||
const targets = this.computeTargetsForSquare(fromSq);
|
const targets = this.computeTargetsForSquare(fromSq);
|
||||||
if (!targets.has(toSq)) return false;
|
if (!targets.has(toSq)) return false;
|
||||||
|
|
||||||
const piece = this.chess.get(fromSq);
|
const piece = this.getDisplayBoard()[fromSq] ?? null;
|
||||||
if (!piece) return false;
|
if (!piece) return false;
|
||||||
const isPremove = this.isPremoveTurn();
|
const isPremove = this.isPremoveTurn();
|
||||||
const promos = targets.get(toSq) || [];
|
const promos = targets.get(toSq) || [];
|
||||||
|
|
@ -281,26 +348,25 @@ export class ChessBoard {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isPremove) {
|
if (isPremove) {
|
||||||
|
if (this.premoveQueue.length >= MAX_PREMOVES) return false;
|
||||||
this.selectedSq = -1;
|
this.selectedSq = -1;
|
||||||
this.legalTargets.clear();
|
this.legalTargets.clear();
|
||||||
this.setPremove({ from: fromSq, to: toSq });
|
this.setPremoveQueue(this.premoveQueue.concat([{ from: fromSq, to: toSq }]));
|
||||||
this.render();
|
this.render();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uci = sqToAlg(fromSq) + sqToAlg(toSq);
|
const uci = sqToAlg(fromSq) + sqToAlg(toSq);
|
||||||
this.selectedSq = -1;
|
this.commitOwnLiveMove(uci);
|
||||||
this.legalTargets.clear();
|
|
||||||
this.render();
|
|
||||||
if (this.onMoveCallback) {
|
|
||||||
this.onMoveCallback(uci);
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleSquareTap(sq: number): void {
|
private handleSquareTap(sq: number): void {
|
||||||
if (this.mode === 'readonly' || this.pendingPromotion !== null) return;
|
if (this.mode === 'readonly' || this.pendingPromotion !== null) return;
|
||||||
|
|
||||||
|
const displayBoard = this.getDisplayBoard();
|
||||||
|
const tappedPiece = displayBoard[sq] ?? null;
|
||||||
|
|
||||||
if (this.selectedSq >= 0) {
|
if (this.selectedSq >= 0) {
|
||||||
if (sq === this.selectedSq) {
|
if (sq === this.selectedSq) {
|
||||||
this.selectedSq = -1;
|
this.selectedSq = -1;
|
||||||
|
|
@ -312,19 +378,19 @@ export class ChessBoard {
|
||||||
this.tryMoveTo(this.selectedSq, sq);
|
this.tryMoveTo(this.selectedSq, sq);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.isPieceInteractive(this.chess.get(sq))) {
|
if (this.isPieceInteractive(tappedPiece)) {
|
||||||
this.setPremove(null);
|
|
||||||
this.selectSquare(sq);
|
this.selectSquare(sq);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.clearSelectionAndPremove();
|
this.selectedSq = -1;
|
||||||
|
this.legalTargets.clear();
|
||||||
|
this.render();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.isPieceInteractive(this.chess.get(sq))) {
|
if (this.isPieceInteractive(tappedPiece)) {
|
||||||
this.setPremove(null);
|
|
||||||
this.selectSquare(sq);
|
this.selectSquare(sq);
|
||||||
} else if (this.premove) {
|
} else if (this.premoveQueue.length > 0) {
|
||||||
this.clearPremove();
|
this.clearPremove();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -348,12 +414,15 @@ export class ChessBoard {
|
||||||
this.pendingPromotion = null;
|
this.pendingPromotion = null;
|
||||||
this.promoOverlay.className = 'promo-overlay hidden';
|
this.promoOverlay.className = 'promo-overlay hidden';
|
||||||
if (pending.isPremove) {
|
if (pending.isPremove) {
|
||||||
this.setPremove({ from: pending.from, to: pending.to, promotion: pt });
|
if (this.premoveQueue.length < MAX_PREMOVES) {
|
||||||
|
this.setPremoveQueue(
|
||||||
|
this.premoveQueue.concat([{ from: pending.from, to: pending.to, promotion: pt }])
|
||||||
|
);
|
||||||
|
}
|
||||||
this.render();
|
this.render();
|
||||||
} else {
|
} else {
|
||||||
const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt;
|
const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt;
|
||||||
this.render();
|
this.commitOwnLiveMove(uci);
|
||||||
if (this.onMoveCallback) this.onMoveCallback(uci);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
box.appendChild(btn);
|
box.appendChild(btn);
|
||||||
|
|
@ -376,6 +445,13 @@ export class ChessBoard {
|
||||||
const turnInCheck = this.chess.inCheck();
|
const turnInCheck = this.chess.inCheck();
|
||||||
const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1;
|
const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1;
|
||||||
const premoveTurn = this.isPremoveTurn();
|
const premoveTurn = this.isPremoveTurn();
|
||||||
|
const displayBoard = this.getDisplayBoard();
|
||||||
|
|
||||||
|
const premoveSquares = new Set<number>();
|
||||||
|
for (let i = 0; i < this.premoveQueue.length; i++) {
|
||||||
|
premoveSquares.add(this.premoveQueue[i]!.from);
|
||||||
|
premoveSquares.add(this.premoveQueue[i]!.to);
|
||||||
|
}
|
||||||
|
|
||||||
for (let vi = 0; vi < 64; vi++) {
|
for (let vi = 0; vi < 64; vi++) {
|
||||||
const sq = this.visualIndexToSq(vi);
|
const sq = this.visualIndexToSq(vi);
|
||||||
|
|
@ -384,9 +460,10 @@ export class ChessBoard {
|
||||||
const vr = vi >> 3;
|
const vr = vi >> 3;
|
||||||
const vc = vi & 7;
|
const vc = vi & 7;
|
||||||
|
|
||||||
const piece = this.chess.get(sq);
|
const piece = displayBoard[sq] ?? null;
|
||||||
const isTarget = this.legalTargets.has(sq);
|
const isTarget = this.legalTargets.has(sq);
|
||||||
const isInteractive = this.isPieceInteractive(piece);
|
const isInteractive =
|
||||||
|
this.isPieceInteractive(piece) && (!premoveTurn || this.premoveQueue.length < MAX_PREMOVES);
|
||||||
|
|
||||||
const isLight = ((r + c) & 1) === 0;
|
const isLight = ((r + c) & 1) === 0;
|
||||||
const sqEl = this.squareEls[vi]!;
|
const sqEl = this.squareEls[vi]!;
|
||||||
|
|
@ -397,7 +474,7 @@ export class ChessBoard {
|
||||||
cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected';
|
cls += premoveTurn ? ' sq-premove-selected' : ' sq-selected';
|
||||||
}
|
}
|
||||||
if (sq === checkKingSq) cls += ' sq-check';
|
if (sq === checkKingSq) cls += ' sq-check';
|
||||||
if (this.premove && (sq === this.premove.from || sq === this.premove.to)) cls += ' sq-premove';
|
if (premoveSquares.has(sq)) cls += ' sq-premove';
|
||||||
if (isInteractive) cls += ' sq-interactive';
|
if (isInteractive) cls += ' sq-interactive';
|
||||||
if (isTarget) cls += ' sq-target';
|
if (isTarget) cls += ' sq-target';
|
||||||
|
|
||||||
|
|
@ -439,10 +516,11 @@ export class ChessBoard {
|
||||||
}
|
}
|
||||||
|
|
||||||
const allArrows = this.arrows.slice();
|
const allArrows = this.arrows.slice();
|
||||||
if (this.premove) {
|
for (let i = 0; i < this.premoveQueue.length; i++) {
|
||||||
|
const pm = this.premoveQueue[i]!;
|
||||||
allArrows.push({
|
allArrows.push({
|
||||||
from: sqToAlg(this.premove.from),
|
from: sqToAlg(pm.from),
|
||||||
to: sqToAlg(this.premove.to),
|
to: sqToAlg(pm.to),
|
||||||
color: '#2979ff'
|
color: '#2979ff'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -75,7 +75,14 @@ export class Navbar {
|
||||||
badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined,
|
badge: state.friendBadgeCount > 0 ? state.friendBadgeCount : undefined,
|
||||||
match: (p) => p.indexOf('/friends') === 0
|
match: (p) => p.indexOf('/friends') === 0
|
||||||
},
|
},
|
||||||
{ href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 0 }
|
{ href: '/leaderboard', label: 'Leaderboard', match: (p) => p.indexOf('/leaderboard') === 0 },
|
||||||
|
{
|
||||||
|
href: state.user ? `/u/${encodeURIComponent(state.user.username)}` : '/profile',
|
||||||
|
label: 'Profile',
|
||||||
|
match: (p) =>
|
||||||
|
p === '/profile' ||
|
||||||
|
(state.user !== null && p.toLowerCase() === `/u/${encodeURIComponent(state.user.username)}`.toLowerCase())
|
||||||
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const item of navItems) {
|
for (const item of navItems) {
|
||||||
|
|
@ -129,7 +136,7 @@ export class Navbar {
|
||||||
if (state.user) {
|
if (state.user) {
|
||||||
const profileLink = el(
|
const profileLink = el(
|
||||||
'a',
|
'a',
|
||||||
{ href: `/u/${encodeURIComponent(state.user.username)}`, className: 'nav-user-link' },
|
{ href: `/u/${encodeURIComponent(state.user.username)}`, className: 'btn btn-sm nav-user-link' },
|
||||||
state.user.username
|
state.user.username
|
||||||
);
|
);
|
||||||
profileLink.addEventListener('click', (e) => {
|
profileLink.addEventListener('click', (e) => {
|
||||||
|
|
|
||||||
|
|
@ -150,6 +150,12 @@ class App {
|
||||||
this.activeView = mountFriendsView(this.mainEl, this.ctx);
|
this.activeView = mountFriendsView(this.mainEl, this.ctx);
|
||||||
} else if (pathname === '/leaderboard') {
|
} else if (pathname === '/leaderboard') {
|
||||||
this.activeView = mountLeaderboardView(this.mainEl, this.ctx);
|
this.activeView = mountLeaderboardView(this.mainEl, this.ctx);
|
||||||
|
} else if (pathname === '/profile') {
|
||||||
|
if (this.user) {
|
||||||
|
this.activeView = mountProfileView(this.mainEl, this.ctx, this.user.username);
|
||||||
|
} else {
|
||||||
|
this.navigate('/login?next=/profile', true);
|
||||||
|
}
|
||||||
} else if (pathname === '/analysis') {
|
} else if (pathname === '/analysis') {
|
||||||
this.activeView = mountAnalysisView(this.mainEl, this.ctx);
|
this.activeView = mountAnalysisView(this.mainEl, this.ctx);
|
||||||
} else if (pathname.indexOf('/analysis/') === 0) {
|
} else if (pathname.indexOf('/analysis/') === 0) {
|
||||||
|
|
|
||||||
|
|
@ -222,12 +222,15 @@ a {
|
||||||
|
|
||||||
.nav-user-link {
|
.nav-user-link {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-size: 13px;
|
font-size: 12px;
|
||||||
padding: 4px 6px;
|
max-width: 140px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.nav-user-link:hover {
|
.nav-user-link:hover {
|
||||||
text-decoration: underline;
|
border-color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Main container */
|
/* Main container */
|
||||||
|
|
@ -756,8 +759,16 @@ a {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.profile-id {
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
.profile-title-row {
|
.profile-title-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
margin-bottom: 4px;
|
margin-bottom: 4px;
|
||||||
}
|
}
|
||||||
|
|
@ -765,6 +776,22 @@ a {
|
||||||
.profile-username {
|
.profile-username {
|
||||||
margin: 0 8px 0 0;
|
margin: 0 8px 0 0;
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-scroll-wrap {
|
||||||
|
width: 100%;
|
||||||
|
overflow-x: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-game-meta {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.game-players-text {
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
.h2h-line {
|
.h2h-line {
|
||||||
|
|
@ -1268,6 +1295,12 @@ a {
|
||||||
|
|
||||||
.premove-banner {
|
.premove-banner {
|
||||||
border-left: 3px solid #2979ff;
|
border-left: 3px solid #2979ff;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.premove-text {
|
||||||
|
margin-right: 8px;
|
||||||
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
.game-meta-line {
|
.game-meta-line {
|
||||||
|
|
@ -1650,8 +1683,33 @@ a {
|
||||||
}
|
}
|
||||||
|
|
||||||
.rating-card {
|
.rating-card {
|
||||||
width: 49%;
|
width: 48.5%;
|
||||||
margin-right: 1%;
|
margin-right: 3%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rating-card:nth-child(2n) {
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rating-big {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-bar > .select {
|
||||||
|
flex: 1 1 46%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-bar > .filter-opp {
|
||||||
|
flex: 1 1 140px;
|
||||||
|
width: auto;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.inline-pw-form > .input {
|
||||||
|
width: 100%;
|
||||||
|
flex: 1 1 100%;
|
||||||
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bot-level-card {
|
.bot-level-card {
|
||||||
|
|
@ -1659,3 +1717,31 @@ a {
|
||||||
margin-right: 0;
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.profile-games-table .col-time,
|
||||||
|
.profile-games-table .col-date {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mobile-game-meta {
|
||||||
|
display: block;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-games-table th,
|
||||||
|
.profile-games-table td {
|
||||||
|
padding: 7px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-games-table .col-actions .btn {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
margin-left: 0;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-games-table .col-actions .btn:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,7 @@ export function mountAnalysisView(
|
||||||
gameId?: string
|
gameId?: string
|
||||||
): ViewHandle {
|
): ViewHandle {
|
||||||
let storedGame: StoredGame | null = null;
|
let storedGame: StoredGame | null = null;
|
||||||
|
let unsavedAborted = false;
|
||||||
let report: GameAnalysisReport | null = null;
|
let report: GameAnalysisReport | null = null;
|
||||||
let loadError = '';
|
let loadError = '';
|
||||||
|
|
||||||
|
|
@ -463,6 +464,18 @@ export function mountAnalysisView(
|
||||||
);
|
);
|
||||||
const body = el('div', { className: 'card-body compact' });
|
const body = el('div', { className: 'card-body compact' });
|
||||||
|
|
||||||
|
if (unsavedAborted) {
|
||||||
|
body.appendChild(
|
||||||
|
el(
|
||||||
|
'div',
|
||||||
|
{ className: 'small-text muted' },
|
||||||
|
'Aborted games (< 2 plies) are not saved for post-game reports, but you can explore lines with the Live Engine above.'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
analysisControlEl.appendChild(body);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!report || report.status === 'error') {
|
if (!report || report.status === 'error') {
|
||||||
if (report?.status === 'error') {
|
if (report?.status === 'error') {
|
||||||
body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.'));
|
body.appendChild(el('div', { className: 'alert alert-error' }, 'Previous analysis encountered an error.'));
|
||||||
|
|
@ -749,7 +762,20 @@ export function mountAnalysisView(
|
||||||
.then((resp) => {
|
.then((resp) => {
|
||||||
if (destroyed) return;
|
if (destroyed) return;
|
||||||
if (resp.kind === 'active') {
|
if (resp.kind === 'active') {
|
||||||
loadError = 'This game is still in progress. Watch it live first!';
|
if (!resp.game.finished) {
|
||||||
|
loadError = 'This game is still in progress. Watch it live first!';
|
||||||
|
updateAll();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unsavedAborted = true;
|
||||||
|
initialFen = resp.game.initialFen;
|
||||||
|
mainUci = resp.game.movesUci.slice();
|
||||||
|
mainSan = resp.game.movesSan.slice();
|
||||||
|
mainPly = mainUci.length;
|
||||||
|
rebuildMainFens();
|
||||||
|
renderHeader();
|
||||||
|
renderAnalysisControl();
|
||||||
|
renderPgnPanel();
|
||||||
updateAll();
|
updateAll();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import { Chess } from '../../shared/chess';
|
import { Chess } from '../../shared/chess';
|
||||||
|
import { MAX_PREMOVES } from '../../shared/premove';
|
||||||
import { categoryLabel, formatTimeControl } from '../../shared/timeControl';
|
import { categoryLabel, formatTimeControl } from '../../shared/timeControl';
|
||||||
import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types';
|
import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types';
|
||||||
import { apiRequest, wsClient } from '../api';
|
import { apiRequest, wsClient } from '../api';
|
||||||
|
|
@ -51,8 +52,8 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
||||||
onMove(uci) {
|
onMove(uci) {
|
||||||
wsClient.send({ type: 'game:move', gameId, uci });
|
wsClient.send({ type: 'game:move', gameId, uci });
|
||||||
},
|
},
|
||||||
onPremoveChange(premoveUci) {
|
onPremoveChange(premoveQueueUci) {
|
||||||
renderPremoveBanner(premoveUci);
|
renderPremoveBanner(premoveQueueUci);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -212,20 +213,37 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s
|
||||||
clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited');
|
clock.update(ms, g.clockRunning && isTurn, g.category === 'unlimited');
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderPremoveBanner(premoveUci: string | null): void {
|
function formatPremoveStep(uci: string): string {
|
||||||
|
const from = uci.slice(0, 2);
|
||||||
|
const to = uci.slice(2, 4);
|
||||||
|
const promo = uci.length === 5 ? `=${uci.charAt(4).toUpperCase()}` : '';
|
||||||
|
return `${from}→${to}${promo}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPremoveBanner(queueUci: string[]): void {
|
||||||
clearNode(premoveBannerEl);
|
clearNode(premoveBannerEl);
|
||||||
if (!premoveUci || premoveUci.length < 4) {
|
if (!queueUci || queueUci.length === 0) {
|
||||||
premoveBannerEl.className = 'premove-banner hidden';
|
premoveBannerEl.className = 'premove-banner hidden';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const from = premoveUci.slice(0, 2);
|
const maxPreview = 5;
|
||||||
const to = premoveUci.slice(2, 4);
|
const formatted = queueUci.slice(0, maxPreview).map(formatPremoveStep).join(', ');
|
||||||
const promo = premoveUci.length === 5 ? `=${premoveUci.charAt(4).toUpperCase()}` : '';
|
const suffix = queueUci.length > maxPreview ? `, +${queueUci.length - maxPreview} more` : '';
|
||||||
premoveBannerEl.className = 'premove-banner';
|
premoveBannerEl.className = 'premove-banner';
|
||||||
premoveBannerEl.appendChild(el('span', null, `Premove queued: ${from} → ${to}${promo}`));
|
premoveBannerEl.appendChild(
|
||||||
const cancelBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Cancel');
|
el('span', { className: 'premove-text' }, `Premoves (${queueUci.length}/${MAX_PREMOVES}): ${formatted}${suffix}`)
|
||||||
cancelBtn.addEventListener('click', () => board.clearPremove());
|
);
|
||||||
premoveBannerEl.appendChild(cancelBtn);
|
|
||||||
|
const btns = el('div', { className: 'btn-row' });
|
||||||
|
if (queueUci.length > 1) {
|
||||||
|
const undoBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Undo');
|
||||||
|
undoBtn.addEventListener('click', () => board.popPremove());
|
||||||
|
btns.appendChild(undoBtn);
|
||||||
|
}
|
||||||
|
const clearBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'Clear');
|
||||||
|
clearBtn.addEventListener('click', () => board.clearPremove());
|
||||||
|
btns.appendChild(clearBtn);
|
||||||
|
premoveBannerEl.appendChild(btns);
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateDynamicHeaderBars(g: ActiveGameState): void {
|
function updateDynamicHeaderBars(g: ActiveGameState): void {
|
||||||
|
|
|
||||||
|
|
@ -363,14 +363,15 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
|
||||||
if (games.length === 0) {
|
if (games.length === 0) {
|
||||||
histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.'));
|
histBody.appendChild(el('div', { className: 'empty-state' }, 'No games match the current filters.'));
|
||||||
} else {
|
} else {
|
||||||
const table = el('table', { className: 'data-table' });
|
const tableWrap = el('div', { className: 'table-scroll-wrap' });
|
||||||
|
const table = el('table', { className: 'data-table profile-games-table' });
|
||||||
const thead = el('thead');
|
const thead = el('thead');
|
||||||
const hr = el('tr');
|
const hr = el('tr');
|
||||||
hr.appendChild(el('th', null, 'Players'));
|
hr.appendChild(el('th', null, 'Players'));
|
||||||
hr.appendChild(el('th', null, 'Time'));
|
hr.appendChild(el('th', { className: 'col-time' }, 'Time'));
|
||||||
hr.appendChild(el('th', null, 'Result'));
|
hr.appendChild(el('th', null, 'Result'));
|
||||||
hr.appendChild(el('th', null, 'Date'));
|
hr.appendChild(el('th', { className: 'col-date' }, 'Date'));
|
||||||
hr.appendChild(el('th', { className: 'col-right' }, 'Open'));
|
hr.appendChild(el('th', { className: 'col-right col-actions' }, 'Open'));
|
||||||
thead.appendChild(hr);
|
thead.appendChild(hr);
|
||||||
table.appendChild(thead);
|
table.appendChild(thead);
|
||||||
|
|
||||||
|
|
@ -385,22 +386,31 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
|
||||||
? 'win'
|
? 'win'
|
||||||
: 'loss';
|
: 'loss';
|
||||||
|
|
||||||
const playersTd = el('td');
|
const playersTd = el('td', { className: 'col-players' });
|
||||||
playersTd.appendChild(
|
playersTd.appendChild(
|
||||||
el(
|
el(
|
||||||
'div',
|
'div',
|
||||||
null,
|
{ className: 'game-players-text' },
|
||||||
`${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${
|
`${g.whiteUsername}${g.whiteRatingBefore ? ` (${g.whiteRatingBefore})` : ''} vs ${
|
||||||
g.blackUsername
|
g.blackUsername
|
||||||
}${g.blackRatingBefore ? ` (${g.blackRatingBefore})` : ''}`
|
}${g.blackRatingBefore ? ` (${g.blackRatingBefore})` : ''}`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
playersTd.appendChild(
|
||||||
|
el(
|
||||||
|
'div',
|
||||||
|
{ className: 'mobile-game-meta small-text muted' },
|
||||||
|
`${formatTimeControl(g.initialMs, g.incrementMs)} · ${
|
||||||
|
g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'
|
||||||
|
} · ${formatRelativeDate(g.endedAt)}`
|
||||||
|
)
|
||||||
|
);
|
||||||
tr.appendChild(playersTd);
|
tr.appendChild(playersTd);
|
||||||
|
|
||||||
tr.appendChild(
|
tr.appendChild(
|
||||||
el(
|
el(
|
||||||
'td',
|
'td',
|
||||||
null,
|
{ className: 'col-time' },
|
||||||
`${formatTimeControl(g.initialMs, g.incrementMs)} · ${g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'}`
|
`${formatTimeControl(g.initialMs, g.incrementMs)} · ${g.botLevel ? 'Bot' : g.rated ? 'Rated' : 'Casual'}`
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
@ -416,9 +426,9 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
|
||||||
resTd.appendChild(el('span', { className: 'small-text muted' }, ` ${g.termination}`));
|
resTd.appendChild(el('span', { className: 'small-text muted' }, ` ${g.termination}`));
|
||||||
tr.appendChild(resTd);
|
tr.appendChild(resTd);
|
||||||
|
|
||||||
tr.appendChild(el('td', { className: 'small-text muted' }, formatRelativeDate(g.endedAt)));
|
tr.appendChild(el('td', { className: 'small-text muted col-date' }, formatRelativeDate(g.endedAt)));
|
||||||
|
|
||||||
const actTd = el('td', { className: 'col-right' });
|
const actTd = el('td', { className: 'col-right col-actions' });
|
||||||
const viewBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'View');
|
const viewBtn = el('button', { type: 'button', className: 'btn btn-xs' }, 'View');
|
||||||
const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze');
|
const analyzeBtn = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Analyze');
|
||||||
viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`));
|
viewBtn.addEventListener('click', () => ctx.navigate(`/game/${g.id}`));
|
||||||
|
|
@ -430,7 +440,8 @@ export function mountProfileView(container: HTMLElement, ctx: AppContext, userna
|
||||||
tbody.appendChild(tr);
|
tbody.appendChild(tr);
|
||||||
}
|
}
|
||||||
table.appendChild(tbody);
|
table.appendChild(tbody);
|
||||||
histBody.appendChild(table);
|
tableWrap.appendChild(table);
|
||||||
|
histBody.appendChild(tableWrap);
|
||||||
}
|
}
|
||||||
|
|
||||||
const totalPages = Math.max(1, Math.ceil(totalGames / limit));
|
const totalPages = Math.max(1, Math.ceil(totalGames / limit));
|
||||||
|
|
|
||||||
|
|
@ -578,17 +578,21 @@ export function createHttpHandler(deps: {
|
||||||
|
|
||||||
if (gameId && !segments[2] && method === 'GET') {
|
if (gameId && !segments[2] && method === 'GET') {
|
||||||
const active = gameManager.getGameState(gameId);
|
const active = gameManager.getGameState(gameId);
|
||||||
if (active) {
|
if (active && !active.finished) {
|
||||||
sendJson(res, 200, { kind: 'active', game: active });
|
sendJson(res, 200, { kind: 'active', game: active });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const stored = db.getGameById(gameId);
|
const stored = db.getGameById(gameId);
|
||||||
if (!stored) {
|
if (stored) {
|
||||||
sendJson(res, 404, { error: 'Game not found.' });
|
const analysis = db.getAnalysis(gameId);
|
||||||
|
sendJson(res, 200, { kind: 'stored', game: stored, analysis });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const analysis = db.getAnalysis(gameId);
|
if (active) {
|
||||||
sendJson(res, 200, { kind: 'stored', game: stored, analysis });
|
sendJson(res, 200, { kind: 'active', game: active });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sendJson(res, 404, { error: 'Game not found.' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
import { Chess, sqToAlg } from './chess';
|
import { Chess, sqToAlg } from './chess';
|
||||||
import type { PromotionPiece } from './types';
|
import type { Piece, PromotionPiece } from './types';
|
||||||
|
|
||||||
|
export const MAX_PREMOVES = 25;
|
||||||
|
|
||||||
export interface QueuedPremove {
|
export interface QueuedPremove {
|
||||||
from: number;
|
from: number;
|
||||||
|
|
@ -9,9 +11,59 @@ export interface QueuedPremove {
|
||||||
|
|
||||||
const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n'];
|
const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n'];
|
||||||
|
|
||||||
export function computePremoveTargets(chess: Chess, fromSq: number): Map<number, PromotionPiece[]> {
|
export function applyPremoveQueueToBoard(
|
||||||
|
baseBoard: ReadonlyArray<Piece | null>,
|
||||||
|
queue: ReadonlyArray<QueuedPremove>
|
||||||
|
): Array<Piece | null> {
|
||||||
|
const board: Array<Piece | null> = new Array(64);
|
||||||
|
for (let i = 0; i < 64; i++) {
|
||||||
|
const p = baseBoard[i];
|
||||||
|
board[i] = p ? { color: p.color, type: p.type } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0; i < queue.length; i++) {
|
||||||
|
const pm = queue[i]!;
|
||||||
|
const moving = board[pm.from];
|
||||||
|
if (!moving) break;
|
||||||
|
|
||||||
|
if (moving.type === 'k' && Math.abs((pm.to & 7) - (pm.from & 7)) === 2) {
|
||||||
|
if (pm.from === 60 && pm.to === 62 && board[63]?.color === moving.color && board[63]?.type === 'r') {
|
||||||
|
board[61] = board[63]!;
|
||||||
|
board[63] = null;
|
||||||
|
} else if (pm.from === 60 && pm.to === 58 && board[56]?.color === moving.color && board[56]?.type === 'r') {
|
||||||
|
board[59] = board[56]!;
|
||||||
|
board[56] = null;
|
||||||
|
} else if (pm.from === 4 && pm.to === 6 && board[7]?.color === moving.color && board[7]?.type === 'r') {
|
||||||
|
board[5] = board[7]!;
|
||||||
|
board[7] = null;
|
||||||
|
} else if (pm.from === 4 && pm.to === 2 && board[0]?.color === moving.color && board[0]?.type === 'r') {
|
||||||
|
board[3] = board[0]!;
|
||||||
|
board[0] = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
board[pm.to] = pm.promotion ? { color: moving.color, type: pm.promotion } : moving;
|
||||||
|
board[pm.from] = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return board;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasMovedInQueue(queue: ReadonlyArray<QueuedPremove>, sq: number): boolean {
|
||||||
|
for (let i = 0; i < queue.length; i++) {
|
||||||
|
if (queue[i]!.from === sq || queue[i]!.to === sq) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function computePremoveTargets(
|
||||||
|
chess: Chess,
|
||||||
|
fromSq: number,
|
||||||
|
queue: ReadonlyArray<QueuedPremove> = []
|
||||||
|
): Map<number, PromotionPiece[]> {
|
||||||
const map = new Map<number, PromotionPiece[]>();
|
const map = new Map<number, PromotionPiece[]>();
|
||||||
const piece = chess.get(fromSq);
|
const projected = queue.length > 0 ? applyPremoveQueueToBoard(chess.board(), queue) : chess.board();
|
||||||
|
const piece = projected[fromSq];
|
||||||
if (!piece) return map;
|
if (!piece) return map;
|
||||||
|
|
||||||
const r = fromSq >> 3;
|
const r = fromSq >> 3;
|
||||||
|
|
@ -50,12 +102,12 @@ export function computePremoveTargets(chess: Chess, fromSq: number): Map<number,
|
||||||
if (adr <= 1 && adc <= 1) {
|
if (adr <= 1 && adc <= 1) {
|
||||||
ok = true;
|
ok = true;
|
||||||
} else if (dr === 0 && adc === 2) {
|
} else if (dr === 0 && adc === 2) {
|
||||||
if (piece.color === 'w' && r === 7 && c === 4) {
|
if (piece.color === 'w' && r === 7 && c === 4 && !hasMovedInQueue(queue, 60)) {
|
||||||
if (tc === 6 && castlingField.indexOf('K') >= 0) ok = true;
|
if (tc === 6 && castlingField.indexOf('K') >= 0 && !hasMovedInQueue(queue, 63)) ok = true;
|
||||||
if (tc === 2 && castlingField.indexOf('Q') >= 0) ok = true;
|
if (tc === 2 && castlingField.indexOf('Q') >= 0 && !hasMovedInQueue(queue, 56)) ok = true;
|
||||||
} else if (piece.color === 'b' && r === 0 && c === 4) {
|
} else if (piece.color === 'b' && r === 0 && c === 4 && !hasMovedInQueue(queue, 4)) {
|
||||||
if (tc === 6 && castlingField.indexOf('k') >= 0) ok = true;
|
if (tc === 6 && castlingField.indexOf('k') >= 0 && !hasMovedInQueue(queue, 7)) ok = true;
|
||||||
if (tc === 2 && castlingField.indexOf('q') >= 0) ok = true;
|
if (tc === 2 && castlingField.indexOf('q') >= 0 && !hasMovedInQueue(queue, 0)) ok = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,17 @@
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import { Chess, algToSq } from '../src/shared/chess';
|
import { Chess, algToSq } from '../src/shared/chess';
|
||||||
import { computePremoveTargets, resolveQueuedPremove } from '../src/shared/premove';
|
import {
|
||||||
|
MAX_PREMOVES,
|
||||||
|
type QueuedPremove,
|
||||||
|
applyPremoveQueueToBoard,
|
||||||
|
computePremoveTargets,
|
||||||
|
resolveQueuedPremove
|
||||||
|
} from '../src/shared/premove';
|
||||||
|
|
||||||
|
test('MAX_PREMOVES is 25', () => {
|
||||||
|
assert.equal(MAX_PREMOVES, 25);
|
||||||
|
});
|
||||||
|
|
||||||
test('Pawn premove targets include 1-step, 2-step from start, diagonal captures, and promotions', () => {
|
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 c = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1');
|
||||||
|
|
@ -19,11 +29,30 @@ test('Pawn premove targets include 1-step, 2-step from start, diagonal captures,
|
||||||
assert.deepEqual(c7Targets.get(algToSq('d8')), ['q', 'r', 'b', 'n']);
|
assert.deepEqual(c7Targets.get(algToSq('d8')), ['q', 'r', 'b', 'n']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Chained multi-premove targets project board state across consecutive moves', () => {
|
||||||
|
const c = new Chess('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1');
|
||||||
|
const queue: QueuedPremove[] = [
|
||||||
|
{ from: algToSq('d2'), to: algToSq('d4') },
|
||||||
|
{ from: algToSq('d4'), to: algToSq('d5') }
|
||||||
|
];
|
||||||
|
|
||||||
|
// After queueing d2->d4 and d4->d5, pawn is projected at d5 and d2 is empty
|
||||||
|
const projected = applyPremoveQueueToBoard(c.board(), queue);
|
||||||
|
assert.equal(projected[algToSq('d2')], null);
|
||||||
|
assert.deepEqual(projected[algToSq('d5')], { color: 'w', type: 'p' });
|
||||||
|
|
||||||
|
// From d5, pawn can premove d6 (1-step), c6, e6 — NOT d7 (2-step only from start rank)
|
||||||
|
const d5Targets = computePremoveTargets(c, algToSq('d5'), queue);
|
||||||
|
assert.equal(d5Targets.has(algToSq('d6')), true);
|
||||||
|
assert.equal(d5Targets.has(algToSq('c6')), true);
|
||||||
|
assert.equal(d5Targets.has(algToSq('e6')), true);
|
||||||
|
assert.equal(d5Targets.has(algToSq('d7')), false);
|
||||||
|
});
|
||||||
|
|
||||||
test('Slider premove targets ignore blockers and resolve recapture when turn returns', () => {
|
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
|
// 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 c = new Chess('r2qkbnr/ppp2ppp/2np4/4p3/4P1b1/3P1N2/PPP2PPP/RNBQKB1R b KQkq - 0 4');
|
||||||
const qTargets = computePremoveTargets(c, algToSq('d1'));
|
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('f3')), true);
|
||||||
assert.equal(qTargets.has(algToSq('h5')), true);
|
assert.equal(qTargets.has(algToSq('h5')), true);
|
||||||
|
|
||||||
|
|
@ -39,12 +68,31 @@ test('Slider premove targets ignore blockers and resolve recapture when turn ret
|
||||||
assert.equal(dropped, null);
|
assert.equal(dropped, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('King castling premove targets respect FEN castling rights and check resolution', () => {
|
test('King castling in premove queue moves rook on projected board and disables repeat castling', () => {
|
||||||
const withRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1');
|
const withRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1');
|
||||||
const kTargets = computePremoveTargets(withRights, algToSq('e1'));
|
const kTargets = computePremoveTargets(withRights, algToSq('e1'));
|
||||||
assert.equal(kTargets.has(algToSq('g1')), true);
|
assert.equal(kTargets.has(algToSq('g1')), true);
|
||||||
assert.equal(kTargets.has(algToSq('c1')), true);
|
assert.equal(kTargets.has(algToSq('c1')), true);
|
||||||
|
|
||||||
|
// Queue O-O (e1->g1): projected board places White king on g1 and White rook on f1
|
||||||
|
const queueAfterCastle: QueuedPremove[] = [{ from: algToSq('e1'), to: algToSq('g1') }];
|
||||||
|
const projected = applyPremoveQueueToBoard(withRights.board(), queueAfterCastle);
|
||||||
|
assert.deepEqual(projected[algToSq('g1')], { color: 'w', type: 'k' });
|
||||||
|
assert.deepEqual(projected[algToSq('f1')], { color: 'w', type: 'r' });
|
||||||
|
assert.equal(projected[algToSq('h1')], null);
|
||||||
|
|
||||||
|
// Rook on f1 can now premove along the f-file
|
||||||
|
const f1Targets = computePremoveTargets(withRights, algToSq('f1'), queueAfterCastle);
|
||||||
|
assert.equal(f1Targets.has(algToSq('f8')), true);
|
||||||
|
|
||||||
|
// Once king moves in queue, e1->c1 castling is no longer offered even if projected back
|
||||||
|
const movedBackQueue: QueuedPremove[] = [
|
||||||
|
{ from: algToSq('e1'), to: algToSq('f1') },
|
||||||
|
{ from: algToSq('f1'), to: algToSq('e1') }
|
||||||
|
];
|
||||||
|
const e1AfterMove = computePremoveTargets(withRights, algToSq('e1'), movedBackQueue);
|
||||||
|
assert.equal(e1AfterMove.has(algToSq('g1')), false);
|
||||||
|
|
||||||
const noRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b - - 0 1');
|
const noRights = new Chess('r3k2r/8/8/8/8/8/8/R3K2R b - - 0 1');
|
||||||
const kNoTargets = computePremoveTargets(noRights, algToSq('e1'));
|
const kNoTargets = computePremoveTargets(noRights, algToSq('e1'));
|
||||||
assert.equal(kNoTargets.has(algToSq('g1')), false);
|
assert.equal(kNoTargets.has(algToSq('g1')), false);
|
||||||
|
|
@ -54,3 +102,23 @@ test('King castling premove targets respect FEN castling rights and check resolu
|
||||||
const checkGame = new Chess('4k3/8/8/8/8/8/4P3/4K2r w - - 0 1');
|
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);
|
assert.equal(resolveQueuedPremove(checkGame, { from: algToSq('e2'), to: algToSq('e4') }), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Multi-premove queue can queue 25 moves and executes sequentially until completion or illegality', () => {
|
||||||
|
const c = new Chess('4k3/8/8/8/8/8/R7/4K3 b - - 0 1');
|
||||||
|
const queue: QueuedPremove[] = [];
|
||||||
|
for (let i = 0; i < MAX_PREMOVES; i++) {
|
||||||
|
queue.push(i % 2 === 0 ? { from: algToSq('a2'), to: algToSq('a3') } : { from: algToSq('a3'), to: algToSq('a2') });
|
||||||
|
}
|
||||||
|
assert.equal(queue.length, 25);
|
||||||
|
|
||||||
|
// Black plays Ke7 -> White executes premove 0 (a2->a3) -> Black plays Kd7 -> White executes premove 1 (a3->a2)
|
||||||
|
assert.ok(c.moveSan('Ke7'));
|
||||||
|
const uci0 = resolveQueuedPremove(c, queue[0]!);
|
||||||
|
assert.equal(uci0, 'a2a3');
|
||||||
|
assert.ok(c.moveUci(uci0!));
|
||||||
|
|
||||||
|
assert.ok(c.moveSan('Kd7'));
|
||||||
|
const uci1 = resolveQueuedPremove(c, queue[1]!);
|
||||||
|
assert.equal(uci1, 'a3a2');
|
||||||
|
assert.ok(c.moveUci(uci1!));
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -259,6 +259,7 @@ test('ChessUp full server E2E: auth, lobby, PvP, Glicko-2, Stockfish analysis, b
|
||||||
// Check REST history, PGN, leaderboard
|
// Check REST history, PGN, leaderboard
|
||||||
const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`);
|
const storedRes = await alice.req<{ kind: string; game: { result: string } }>(`/api/games/${pvpGameId}`);
|
||||||
assert.equal(storedRes.status, 200);
|
assert.equal(storedRes.status, 200);
|
||||||
|
assert.equal(storedRes.data.kind, 'stored');
|
||||||
assert.equal(storedRes.data.game.result, '1-0');
|
assert.equal(storedRes.data.game.result, '1-0');
|
||||||
|
|
||||||
const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`);
|
const pgnRes = await alice.req<string>(`/api/games/${pvpGameId}/pgn`);
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue