From 14263d3c32d9f8d0c5c245e55ab7877ed4b8b04f Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 22 Nov 2026 20:14:40 +0300 Subject: [PATCH] Support up to 25 queued premoves with projected board state --- README.md | 2 +- src/client/components/board.ts | 194 +++++++++++++++++++++++---------- src/client/styles.css | 6 + src/client/views/gameView.ts | 40 +++++-- src/shared/premove.ts | 70 ++++++++++-- tests/premove.test.ts | 74 ++++++++++++- 6 files changed, 304 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index 1d4eed7..986663a 100644 --- a/README.md +++ b/README.md @@ -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-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). - **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/`), mutual friends, live online/in-game status, direct challenges, head-to-head records, live spectating, and in-game chat. diff --git a/src/client/components/board.ts b/src/client/components/board.ts index 4330a95..9b21361 100644 --- a/src/client/components/board.ts +++ b/src/client/components/board.ts @@ -1,5 +1,11 @@ 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 { createPieceNode } from '../pieces'; import { clearNode, el } from '../dom'; @@ -17,7 +23,11 @@ export interface BoardOptions { mode?: BoardMode; playerColor?: Color; 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 { @@ -34,13 +44,13 @@ export class ChessBoard { private mode: BoardMode = 'readonly'; private playerColor: Color = 'w'; private onMoveCallback?: (uci: string) => void; - private onPremoveChangeCallback?: (premoveUci: string | null) => void; + private onPremoveChangeCallback?: (premoveQueueUci: string[]) => void; private selectedSq: number = -1; private legalTargets = new Map(); private lastMoveFrom: number = -1; private lastMoveTo: number = -1; - private premove: QueuedPremove | null = null; + private premoveQueue: QueuedPremove[] = []; private arrows: BoardArrow[] = []; private pendingPromotion: { from: number; to: number; isPremove: boolean; color: Color } | null = null; @@ -79,7 +89,13 @@ export class ChessBoard { this.grid.addEventListener('contextmenu', (e) => { e.preventDefault(); - this.clearSelectionAndPremove(); + if (this.selectedSq >= 0) { + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); + } else { + this.clearSelectionAndPremove(); + } }); this.render(); @@ -89,17 +105,35 @@ export class ChessBoard { // 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 || ''); + getPremoveQueueUci(): string[] { + return this.premoveQueue.map(premoveToUci); } - 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); + private setPremoveQueue(next: QueuedPremove[]): void { + const prevKey = this.premoveQueue.map(premoveToUci).join(','); + this.premoveQueue = next.slice(0, MAX_PREMOVES); + const nextList = this.getPremoveQueueUci(); + if (prevKey !== nextList.join(',') && this.onPremoveChangeCallback) { + 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.renderPromotionPicker(); if (mode !== 'play') { - this.setPremove(null); + this.setPremoveQueue([]); } this.render(); } @@ -140,19 +174,12 @@ export class ChessBoard { this.renderArrows(); } - clearPremove(): void { - if (this.premove) { - this.setPremove(null); - this.render(); - } - } - private clearSelectionAndPremove(): void { this.selectedSq = -1; this.legalTargets.clear(); this.pendingPromotion = null; this.renderPromotionPicker(); - this.setPremove(null); + this.setPremoveQueue([]); this.render(); } @@ -178,18 +205,28 @@ export class ChessBoard { 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.setPremove(null); - const uci = resolveQueuedPremove(this.chess, pm); + // Auto-execute first queued premove when our turn arrives in play mode + if (this.mode === 'play' && this.premoveQueue.length > 0 && this.chess.turn() === this.playerColor) { + const nextPm = this.premoveQueue[0]!; + const remaining = this.premoveQueue.slice(1); + const uci = resolveQueuedPremove(this.chess, nextPm); 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(); if (this.onMoveCallback) { this.onMoveCallback(uci); } return; } + + // First premove became illegal -> cancel remaining queue + this.setPremoveQueue([]); } this.render(); @@ -212,6 +249,13 @@ export class ChessBoard { }; } + private getDisplayBoard(): Array { + if (this.premoveQueue.length > 0) { + return applyPremoveQueueToBoard(this.chess.board(), this.premoveQueue); + } + return this.chess.board(); + } + private isPieceInteractive(piece: Piece | null): boolean { if (!piece || this.mode === 'readonly') return false; if (this.mode === 'analyze') { @@ -226,9 +270,19 @@ export class ChessBoard { private computeTargetsForSquare(fromSq: number): Map { const map = new Map(); + + 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); if (!piece) return map; - if (this.mode === 'analyze' || this.chess.turn() === piece.color) { const legal = this.chess.legalMoves(fromSq); for (let i = 0; i < legal.length; i++) { @@ -239,34 +293,47 @@ export class ChessBoard { } map.set(m.to, list); } - return map; - } - - if (this.mode === 'play' && piece.color === this.playerColor) { - return computePremoveTargets(this.chess, fromSq); } return map; } private selectSquare(sq: number): void { - const piece = this.chess.get(sq); + const piece = this.getDisplayBoard()[sq] ?? null; if (!this.isPieceInteractive(piece)) { this.selectedSq = -1; this.legalTargets.clear(); this.render(); return; } + if (this.isPremoveTurn() && this.premoveQueue.length >= MAX_PREMOVES) { + return; + } this.selectedSq = sq; this.legalTargets = this.computeTargetsForSquare(sq); 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 { const targets = this.computeTargetsForSquare(fromSq); if (!targets.has(toSq)) return false; - const piece = this.chess.get(fromSq); + const piece = this.getDisplayBoard()[fromSq] ?? null; if (!piece) return false; const isPremove = this.isPremoveTurn(); const promos = targets.get(toSq) || []; @@ -281,26 +348,25 @@ export class ChessBoard { } if (isPremove) { + if (this.premoveQueue.length >= MAX_PREMOVES) return false; this.selectedSq = -1; this.legalTargets.clear(); - this.setPremove({ from: fromSq, to: toSq }); + this.setPremoveQueue(this.premoveQueue.concat([{ from: fromSq, to: toSq }])); this.render(); return true; } const uci = sqToAlg(fromSq) + sqToAlg(toSq); - this.selectedSq = -1; - this.legalTargets.clear(); - this.render(); - if (this.onMoveCallback) { - this.onMoveCallback(uci); - } + this.commitOwnLiveMove(uci); return true; } private handleSquareTap(sq: number): void { if (this.mode === 'readonly' || this.pendingPromotion !== null) return; + const displayBoard = this.getDisplayBoard(); + const tappedPiece = displayBoard[sq] ?? null; + if (this.selectedSq >= 0) { if (sq === this.selectedSq) { this.selectedSq = -1; @@ -312,19 +378,19 @@ export class ChessBoard { this.tryMoveTo(this.selectedSq, sq); return; } - if (this.isPieceInteractive(this.chess.get(sq))) { - this.setPremove(null); + if (this.isPieceInteractive(tappedPiece)) { this.selectSquare(sq); return; } - this.clearSelectionAndPremove(); + this.selectedSq = -1; + this.legalTargets.clear(); + this.render(); return; } - if (this.isPieceInteractive(this.chess.get(sq))) { - this.setPremove(null); + if (this.isPieceInteractive(tappedPiece)) { this.selectSquare(sq); - } else if (this.premove) { + } else if (this.premoveQueue.length > 0) { this.clearPremove(); } } @@ -348,12 +414,15 @@ export class ChessBoard { this.pendingPromotion = null; this.promoOverlay.className = 'promo-overlay hidden'; 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(); } else { const uci = sqToAlg(pending.from) + sqToAlg(pending.to) + pt; - this.render(); - if (this.onMoveCallback) this.onMoveCallback(uci); + this.commitOwnLiveMove(uci); } }); box.appendChild(btn); @@ -376,6 +445,13 @@ export class ChessBoard { const turnInCheck = this.chess.inCheck(); const checkKingSq = turnInCheck ? this.chess.kingSquare(this.chess.turn()) : -1; const premoveTurn = this.isPremoveTurn(); + const displayBoard = this.getDisplayBoard(); + + const premoveSquares = new Set(); + 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++) { const sq = this.visualIndexToSq(vi); @@ -384,9 +460,10 @@ export class ChessBoard { const vr = vi >> 3; const vc = vi & 7; - const piece = this.chess.get(sq); + const piece = displayBoard[sq] ?? null; 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 sqEl = this.squareEls[vi]!; @@ -397,7 +474,7 @@ export class ChessBoard { 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 (premoveSquares.has(sq)) cls += ' sq-premove'; if (isInteractive) cls += ' sq-interactive'; if (isTarget) cls += ' sq-target'; @@ -439,10 +516,11 @@ export class ChessBoard { } const allArrows = this.arrows.slice(); - if (this.premove) { + for (let i = 0; i < this.premoveQueue.length; i++) { + const pm = this.premoveQueue[i]!; allArrows.push({ - from: sqToAlg(this.premove.from), - to: sqToAlg(this.premove.to), + from: sqToAlg(pm.from), + to: sqToAlg(pm.to), color: '#2979ff' }); } diff --git a/src/client/styles.css b/src/client/styles.css index 128213b..dc642ca 100644 --- a/src/client/styles.css +++ b/src/client/styles.css @@ -1295,6 +1295,12 @@ a { .premove-banner { border-left: 3px solid #2979ff; + flex-wrap: wrap; +} + +.premove-text { + margin-right: 8px; + word-break: break-word; } .game-meta-line { diff --git a/src/client/views/gameView.ts b/src/client/views/gameView.ts index c236e1e..5aeaa6c 100644 --- a/src/client/views/gameView.ts +++ b/src/client/views/gameView.ts @@ -1,4 +1,5 @@ import { Chess } from '../../shared/chess'; +import { MAX_PREMOVES } from '../../shared/premove'; import { categoryLabel, formatTimeControl } from '../../shared/timeControl'; import type { ActiveGameState, Color, ServerWsMessage } from '../../shared/types'; import { apiRequest, wsClient } from '../api'; @@ -51,8 +52,8 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s onMove(uci) { wsClient.send({ type: 'game:move', gameId, uci }); }, - onPremoveChange(premoveUci) { - renderPremoveBanner(premoveUci); + onPremoveChange(premoveQueueUci) { + renderPremoveBanner(premoveQueueUci); } }); @@ -212,20 +213,37 @@ export function mountGameView(container: HTMLElement, ctx: AppContext, gameId: s 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); - if (!premoveUci || premoveUci.length < 4) { + if (!queueUci || queueUci.length === 0) { 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()}` : ''; + const maxPreview = 5; + const formatted = queueUci.slice(0, maxPreview).map(formatPremoveStep).join(', '); + const suffix = queueUci.length > maxPreview ? `, +${queueUci.length - maxPreview} more` : ''; 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); + premoveBannerEl.appendChild( + el('span', { className: 'premove-text' }, `Premoves (${queueUci.length}/${MAX_PREMOVES}): ${formatted}${suffix}`) + ); + + 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 { diff --git a/src/shared/premove.ts b/src/shared/premove.ts index 836cbd5..88cb37c 100644 --- a/src/shared/premove.ts +++ b/src/shared/premove.ts @@ -1,5 +1,7 @@ import { Chess, sqToAlg } from './chess'; -import type { PromotionPiece } from './types'; +import type { Piece, PromotionPiece } from './types'; + +export const MAX_PREMOVES = 25; export interface QueuedPremove { from: number; @@ -9,9 +11,59 @@ export interface QueuedPremove { const PROMO_LIST: PromotionPiece[] = ['q', 'r', 'b', 'n']; -export function computePremoveTargets(chess: Chess, fromSq: number): Map { +export function applyPremoveQueueToBoard( + baseBoard: ReadonlyArray, + queue: ReadonlyArray +): Array { + const board: Array = 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, 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 = [] +): Map { const map = new Map(); - const piece = chess.get(fromSq); + const projected = queue.length > 0 ? applyPremoveQueueToBoard(chess.board(), queue) : chess.board(); + const piece = projected[fromSq]; if (!piece) return map; const r = fromSq >> 3; @@ -50,12 +102,12 @@ export function computePremoveTargets(chess: Chess, fromSq: number): Map= 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 (piece.color === 'w' && r === 7 && c === 4 && !hasMovedInQueue(queue, 60)) { + if (tc === 6 && castlingField.indexOf('K') >= 0 && !hasMovedInQueue(queue, 63)) ok = true; + if (tc === 2 && castlingField.indexOf('Q') >= 0 && !hasMovedInQueue(queue, 56)) ok = true; + } else if (piece.color === 'b' && r === 0 && c === 4 && !hasMovedInQueue(queue, 4)) { + if (tc === 6 && castlingField.indexOf('k') >= 0 && !hasMovedInQueue(queue, 7)) ok = true; + if (tc === 2 && castlingField.indexOf('q') >= 0 && !hasMovedInQueue(queue, 0)) ok = true; } } } diff --git a/tests/premove.test.ts b/tests/premove.test.ts index 00b2187..3292b8d 100644 --- a/tests/premove.test.ts +++ b/tests/premove.test.ts @@ -1,7 +1,17 @@ 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'; +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', () => { 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']); }); +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', () => { // 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); @@ -39,12 +68,31 @@ test('Slider premove targets ignore blockers and resolve recapture when turn ret 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 kTargets = computePremoveTargets(withRights, algToSq('e1')); assert.equal(kTargets.has(algToSq('g1')), 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 kNoTargets = computePremoveTargets(noRights, algToSq('e1')); 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'); 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!)); +});