Support up to 25 queued premoves with projected board state

This commit is contained in:
tyuXX 2026-11-22 20:14:40 +03:00
parent 3ccab53b41
commit 14263d3c32
6 changed files with 304 additions and 82 deletions

View file

@ -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.

View file

@ -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();
if (this.selectedSq >= 0) {
this.selectedSq = -1;
this.legalTargets.clear();
this.render();
} else {
this.clearSelectionAndPremove(); 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'
}); });
} }

View file

@ -1295,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 {

View file

@ -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 {

View file

@ -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;
} }
} }
} }

View file

@ -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!));
});