diff --git a/client-src/src/main.ts b/client-src/src/main.ts index eec6f29..cddda73 100644 --- a/client-src/src/main.ts +++ b/client-src/src/main.ts @@ -1,11 +1,47 @@ /** - * Chess client — runs in sandboxed iframe. + * Chess Client — 3miz Game Bundle + * Redesigned with 2D Game Animation & VFX Polish */ + import "./style.css"; import { connectHost, type InitMsg } from "@3miz/game-client/iframe"; +import { getPieceSvg, type PieceType, type PieceColor } from "./pieces"; +import { VfxEngine } from "./vfx"; +import { getLegalMoves, type CellInfo } from "./rules-hint"; -let S: any = null; +interface PlayerSnapshot { + seat: number; + name: string; + color: "w" | "b"; + bot: boolean; + connected: boolean; + left: boolean; +} + +interface GameSnapshot { + me: number | null; + board: CellInfo[]; + turn: number; + phase: "play" | "over"; + winner: number | null; + result_reason: string; + check: boolean; + players: PlayerSnapshot[]; + moves_played: number; + captures: number; +} + +let S: GameSnapshot | null = null; +let prevS: GameSnapshot | null = null; let init: InitMsg | null = null; +let vfx: VfxEngine | null = null; + +let selectedSquare = ""; +let legalTargets: { target: string; isCapture: boolean }[] = []; +let pendingPromo: { from: string; to: string } | null = null; +let lastMove: { from: string; to: string } | null = null; +let confettiTriggered = false; + const L = (fa: string, en: string) => (init?.locale === "en" ? en : fa); const host = connectHost({ @@ -13,146 +49,469 @@ const host = connectHost({ init = m; document.documentElement.lang = m.locale; document.documentElement.dir = m.dir; - render(); + if (!document.getElementById("board-grid")) { + setupDOM(); + } + updateUI(); }, onState(env) { if (env.t === "snap") { - S = env.body; - // Drop any half-finished local selection once the turn moves on (e.g. timeout auto-move). - if (S.turn !== S.me) { selectedSquare = ""; pendingPromo = null; } - render(); + if (!document.getElementById("board-grid")) { + setupDOM(); + } + prevS = S; + S = env.body as GameSnapshot; + + detectMoveEvents(prevS, S); + + if (S.turn !== S.me) { + selectedSquare = ""; + legalTargets = []; + pendingPromo = null; + } + + updateUI(); } }, onAck(a) { - if (a.status === "rejected") host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn"); + if (a.status === "rejected") { + host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn"); + } }, }); -function render() { - const app = document.getElementById("app")!; - if (!S) { - app.innerHTML = `
${L("در حال بارگذاری…", "Loading…")}
`; - return; +/** + * Detect move events between snapshots for animations and VFX + */ +function detectMoveEvents(oldState: GameSnapshot | null, newState: GameSnapshot) { + if (!oldState || !newState || !vfx) return; + + // Find which piece moved + const oldBoard = new Map(oldState.board.map((c) => [c.square, c])); + const newBoard = new Map(newState.board.map((c) => [c.square, c])); + + let movedFrom = ""; + let movedTo = ""; + let capturedPiece: CellInfo | null = null; + + for (const [sq, newCell] of newBoard.entries()) { + const oldCell = oldBoard.get(sq); + if (!oldCell) continue; + + if (oldCell.color && !newCell.color) { + // Piece left this square + movedFrom = sq; + } else if (newCell.color && (!oldCell.color || oldCell.color !== newCell.color || oldCell.type !== newCell.type)) { + // Piece arrived or promoted here + movedTo = sq; + if (oldCell.color && oldCell.color !== newCell.color) { + capturedPiece = oldCell; + } + } } + + if (movedFrom && movedTo) { + lastMove = { from: movedFrom, to: movedTo }; + const targetCellEl = document.querySelector(`[data-square="${movedTo}"]`) as HTMLElement; + + if (targetCellEl) { + const rect = targetCellEl.getBoundingClientRect(); + const canvasRect = document.getElementById("vfx-canvas")?.getBoundingClientRect(); + + if (canvasRect) { + const x = rect.left - canvasRect.left + rect.width / 2; + const y = rect.top - canvasRect.top + rect.height / 2; + + if (capturedPiece) { + vfx.captureImpact(x, y, capturedPiece.color as "w" | "b"); + } else { + vfx.landingPuff(x, y); + } + } + + // Add landing squash animation to arrived piece + const pieceEl = targetCellEl.querySelector(".piece-wrapper"); + if (pieceEl) { + pieceEl.classList.remove("anim-land"); + void (pieceEl as HTMLElement).offsetWidth; + pieceEl.classList.add("anim-land"); + } + } + } + + // Victory celebration + if (newState.phase === "over" && newState.winner !== null && !confettiTriggered) { + confettiTriggered = true; + setTimeout(() => vfx?.victoryConfetti(), 350); + } +} + +/** + * One-time setup of persistent DOM tree + */ +function setupDOM() { + const app = document.getElementById("app")!; + app.innerHTML = ` +
+
+ +
+
+
+ + `; + + const canvas = document.getElementById("vfx-canvas") as HTMLCanvasElement; + vfx = new VfxEngine(canvas); + + // Delegated click listener on board grid + const grid = document.getElementById("board-grid")!; + grid.addEventListener("click", (e) => { + const btn = (e.target as HTMLElement).closest(".cell") as HTMLButtonElement | null; + if (btn && btn.dataset.square && !btn.disabled) { + handleSquareClick(btn.dataset.square); + } + }); + + // Generate 64 permanent square buttons + for (let i = 0; i < 64; i++) { + const btn = document.createElement("button"); + btn.className = "cell"; + btn.dataset.index = String(i); + grid.appendChild(btn); + } +} + +/** + * Update UI on state changes or interaction + */ +function updateUI() { + if (!S) return; + const me = S.me; - const myColor = me !== null && me !== undefined ? S.players[me]?.color : null; - // Orientation: your own back rank is always at the bottom. - // White (and observers) see rank 8 at the top, files a→h; Black sees rank 1 at the top, files h→a. + const isPlaying = me !== null && me !== undefined && S.players[me] !== undefined; + + // Bottom player is ALWAYS ME (if playing) or White (if observer). + // Top player is ALWAYS MY OPPONENT (if playing) or Black (if observer). + let bottomPlayer: PlayerSnapshot | undefined; + let topPlayer: PlayerSnapshot | undefined; + + if (isPlaying) { + bottomPlayer = S.players[me]; + topPlayer = S.players.find((p) => p.seat !== me) || S.players[1 - me]; + } else { + bottomPlayer = S.players.find((p) => p.color === "w") || S.players[0]; + topPlayer = S.players.find((p) => p.color === "b") || S.players[1]; + } + + const myColor = bottomPlayer?.color || "w"; const flipped = myColor === "b"; - const bySquare: Record = {}; - for (const cell of S.board) bySquare[cell.square] = cell; + + const isBottomTurn = bottomPlayer ? S.turn === bottomPlayer.seat && S.phase === "play" : false; + const isTopTurn = topPlayer ? S.turn === topPlayer.seat && S.phase === "play" : false; + + renderPlayerBar("top-bar", topPlayer, isTopTurn, false); + renderPlayerBar("bottom-bar", bottomPlayer, isBottomTurn, isPlaying); + + // Map squares by coordinate + const bySquare = new Map(); + for (const c of S.board) bySquare.set(c.square, c); + const files = flipped ? [7, 6, 5, 4, 3, 2, 1, 0] : [0, 1, 2, 3, 4, 5, 6, 7]; const ranks = flipped ? [0, 1, 2, 3, 4, 5, 6, 7] : [7, 6, 5, 4, 3, 2, 1, 0]; + + const grid = document.getElementById("board-grid"); + if (!grid) return; + const cells = grid.children; + + let idx = 0; const isMyTurn = S.phase === "play" && S.turn === me; - const boardHtml = ranks.map((r) => files.map((f) => { - const sq = String.fromCharCode(97 + f) + (r + 1); - const cell = bySquare[sq] || { square: sq, type: null, color: null }; - const piece = cell.color ? `${pieceChar(cell.type, cell.color)}` : ""; - const selectable = isMyTurn && !!myColor && cell.color === myColor; - const isSelected = selectedSquare === sq; - const enabled = !selectedSquare ? selectable : isMyTurn; - // Standard colouring: a1 is dark; shade = parity of (file + rank). - const shade = (f + r) % 2 === 0 ? "dark" : "light"; - return ``; - }).join("")).join(""); - const selHint = selectedSquare - ? `
${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}
` - : ``; + // King in check location + const kingInCheckSq = (S.check && S.phase === "play") + ? S.board.find((c) => c.type === "k" && c.color === S!.players[S!.turn]?.color)?.square + : null; - const promoPicker = pendingPromo - ? `
${pendingPromo.from} → ${pendingPromo.to}: ${L("ارتقا به", "Promote to")} - ${["q", "r", "b", "n"].map((t) => ``).join("")} -
` - : ``; + for (const r of ranks) { + for (const f of files) { + const sq = String.fromCharCode(97 + f) + (r + 1); + const cell = bySquare.get(sq) || { square: sq, type: null, color: null }; + const btn = cells[idx++] as HTMLButtonElement; - const statusText = S.phase === "over" - ? (S.result_reason === "abandoned" - ? L("بازی رها شد", "Abandoned") - : S.winner === null - ? (S.result_reason === "stalemate" ? L("پات — مساوی!", "Stalemate — draw!") : L("مساوی!", "Draw!")) - : (S.result_reason === "checkmate" - ? `${S.players[S.winner]?.name} ${L("مات کرد! 🏆", "wins by checkmate 🏆")}` - : `${S.players[S.winner]?.name} ${L("برنده شد 🏆", "wins 🏆")}`)) - : ((S.turn === me ? L("نوبت شماست", "Your turn") : `${L("نوبت", "Turn")}: ${S.players[S.turn]?.name}`) + (S.check ? ` · ${L("کیش!", "Check!")}` : "")); + btn.dataset.square = sq; + btn.dataset.color = cell.color || ""; - app.innerHTML = ` -
${statusText}
-
${S.moves_played !== undefined ? `حرکت‌ها: ${S.moves_played}` : ""}
-
${boardHtml}
- ${selHint} - ${promoPicker} -
${L("سفید حرکت می‌کند", "White moves")}
+ // Shading: a1 is dark + const shade = (f + r) % 2 === 0 ? "dark" : "light"; + const isSelected = selectedSquare === sq; + const isLastMove = lastMove && (lastMove.from === sq || lastMove.to === sq); + const isInCheck = kingInCheckSq === sq; + + btn.className = `cell ${shade}` + + (isSelected ? " selected" : "") + + (isLastMove ? " last-move" : "") + + (isInCheck ? " in-check" : ""); + + const isLegalTarget = legalTargets.some((t) => t.target === sq); + const isCaptureTarget = legalTargets.some((t) => t.target === sq && t.isCapture); + + let inner = ""; + + // Coordinates + const showRank = flipped ? f === 7 : f === 0; + const showFile = flipped ? r === 7 : r === 0; + if (showRank) inner += `${r + 1}`; + if (showFile) inner += `${String.fromCharCode(97 + f)}`; + + // Piece SVG + if (cell.type && cell.color) { + const svg = getPieceSvg(cell.type as PieceType, cell.color as PieceColor); + const animClass = (cell.type === "n" && isSelected) ? " anim-knight" : ""; + inner += `
${svg}
`; + } + + // Legal move dot or capture ring + if (isCaptureTarget) { + inner += `
`; + } else if (isLegalTarget) { + inner += `
`; + } + + btn.innerHTML = inner; + + // Enable clicking on own pieces (when my turn), or on any square if selected + const selectable = isMyTurn && !!myColor && cell.color === myColor; + const enabled = !selectedSquare ? selectable : isMyTurn; + btn.disabled = !enabled; + } + } + + renderModalContainer(); +} + +/** + * Render player profile, active turn indicator, captured pieces, and score + */ +function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isActive: boolean, isMe: boolean) { + const el = document.getElementById(barId); + if (!el || !player || !S) return; + + el.className = `player-bar` + (isActive ? " active" : ""); + + // Material captured calculation + const capturedPieces = getCapturedPieces(player.color); + const adv = getMaterialAdvantage(player.color); + const advText = adv > 0 ? `+${adv}` : ""; + + const botBadge = player.bot ? `BOT` : ""; + const youBadge = isMe ? `${L("شما", "YOU")}` : ""; + const statusLabel = S.phase === "over" + ? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : "") + : (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : ""); + + el.innerHTML = ` +
+
+ ${player.color === "w" ? "♔" : "♚"} +
+
+
${player.name} ${botBadge} ${youBadge}
+
${statusLabel}
+
+
+
+ ${capturedPieces.map((p) => `
${getPieceSvg(p.type as PieceType, p.color as PieceColor)}
`).join("")} + ${advText} +
`; } -function pieceChar(type: string | null, color: string | null): string { - if (!type) return ""; - // White uses outline glyphs, black uses filled glyphs. - const white: Record = { k: "♔", q: "♕", r: "♖", b: "♗", n: "♘", p: "♙" }; - const black: Record = { k: "♚", q: "♛", r: "♜", b: "♝", n: "♞", p: "♟" }; - return color === "b" ? (black[type] ?? "") : (white[type] ?? ""); +/** + * Calculate captured pieces for a given player color + */ +function getCapturedPieces(playerColor: "w" | "b"): CellInfo[] { + if (!S) return []; + const opponentColor = playerColor === "w" ? "b" : "w"; + + const initialCount: Record = { p: 8, n: 2, b: 2, r: 2, q: 1 }; + const currentCount: Record = { p: 0, n: 0, b: 0, r: 0, q: 0 }; + + for (const c of S.board) { + if (c.color === opponentColor && c.type && currentCount[c.type] !== undefined) { + currentCount[c.type]++; + } + } + + const captured: CellInfo[] = []; + for (const type of ["q", "r", "b", "n", "p"]) { + const missing = initialCount[type] - (currentCount[type] || 0); + for (let i = 0; i < missing; i++) { + captured.push({ square: "", type, color: opponentColor }); + } + } + return captured; } -let selectedSquare = ""; -let pendingPromo: { from: string; to: string } | null = null; +/** + * Material advantage score + */ +function getMaterialAdvantage(playerColor: "w" | "b"): number { + if (!S) return 0; + const values: Record = { p: 1, n: 3, b: 3, r: 5, q: 9 }; + let myScore = 0; + let oppScore = 0; -document.addEventListener("click", (e) => { - const el = e.target as HTMLElement; - // Promotion choice buttons. - const promoBtn = el.closest("[data-promo]") as HTMLElement | null; - if (promoBtn && pendingPromo) { - host.cmd("move", { from: pendingPromo.from, to: pendingPromo.to, promotion: promoBtn.dataset.promo }); - pendingPromo = null; - selectedSquare = ""; - render(); + for (const c of S.board) { + if (!c.type || !c.color) continue; + const val = values[c.type] || 0; + if (c.color === playerColor) myScore += val; + else oppScore += val; + } + return myScore - oppScore; +} + +/** + * Render promotion modal or game over banner + */ +function renderModalContainer() { + const container = document.getElementById("modal-container"); + if (!container || !S) return; + + if (pendingPromo) { + const myColor = S.me !== null && S.me !== undefined ? S.players[S.me]?.color : "w"; + container.innerHTML = ` + + `; + + container.querySelectorAll("[data-promo]").forEach((btn) => { + btn.addEventListener("click", () => { + const promoType = (btn as HTMLElement).dataset.promo; + if (pendingPromo && promoType) { + host.cmd("move", { from: pendingPromo.from, to: pendingPromo.to, promotion: promoType }); + const targetEl = document.querySelector(`[data-square="${pendingPromo.to}"]`); + if (targetEl) { + const r = targetEl.getBoundingClientRect(); + const cr = document.getElementById("vfx-canvas")?.getBoundingClientRect(); + if (cr) vfx?.promotionBurst(r.left - cr.left + r.width / 2, r.top - cr.top + r.height / 2); + } + pendingPromo = null; + selectedSquare = ""; + legalTargets = []; + updateUI(); + } + }); + }); + + container.querySelector("[data-cancel-promo]")?.addEventListener("click", () => { + pendingPromo = null; + updateUI(); + }); return; } - if (el.closest("[data-cancel-promo]")) { - pendingPromo = null; - render(); + + if (S.phase === "over") { + const isWinner = S.winner !== null && S.winner === S.me; + const isDraw = S.winner === null; + let title = ""; + let subtitle = ""; + + if (isDraw) { + title = S.result_reason === "stalemate" ? L("پات — مساوی!", "Stalemate — Draw!") : L("بازی مساوی شد", "Draw!"); + subtitle = L("هیچ‌کدام از طرفین برنده نشد", "No side achieved victory"); + } else { + const winnerName = S.players[S.winner!]?.name; + title = `${winnerName} ${L("برنده شد! 🏆", "Wins! 🏆")}`; + subtitle = S.result_reason === "checkmate" + ? L("با کیش و مات حریف", "By checkmate") + : (S.result_reason === "abandoned" ? L("به دلیل ترک حریف", "By abandonment") : ""); + } + + container.innerHTML = ` +
+
${title}
+
${subtitle}
+
+ `; return; } - const b = el.closest("[data-from]") as HTMLElement | null; - if (!b) return; - const sq = b.dataset.from!; - if (pendingPromo) return; // choose a promotion piece (or cancel) first + + container.innerHTML = ""; +} + +/** + * Handle square click + */ +function handleSquareClick(sq: string) { + if (!S || S.phase !== "play" || pendingPromo) return; + const me = S.me; + if (me === null || me === undefined || S.turn !== me) return; + + const myColor = S.players[me]?.color; + if (!myColor) return; + + const clickedCell = S.board.find((c) => c.square === sq); + if (selectedSquare) { if (selectedSquare === sq) { + // Deselect selectedSquare = ""; - render(); + legalTargets = []; + updateUI(); return; } - // Clicking another of my own pieces switches the selection instead of sending a bad move. - const clicked = (S?.board || []).find((c: any) => c.square === sq); - const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null; - if (clicked?.color && myColor && clicked.color === myColor) { + + // Switch selection to another own piece + if (clickedCell?.color && clickedCell.color === myColor) { selectedSquare = sq; - render(); + try { + legalTargets = getLegalMoves(sq, S.board, myColor); + } catch (err) { + legalTargets = []; + } + updateUI(); return; } - // Pawn stepping onto the last rank must promote: ask which piece first. - const moving = (S?.board || []).find((c: any) => c.square === selectedSquare); + + // Target clicked: execute move + const moving = S.board.find((c) => c.square === selectedSquare); const lastRank = myColor === "b" ? "1" : "8"; + + // Pawn promotion check if (moving?.type === "p" && sq[1] === lastRank) { pendingPromo = { from: selectedSquare, to: sq }; selectedSquare = ""; - render(); + legalTargets = []; + updateUI(); return; } + + // Send move to host host.cmd("move", { from: selectedSquare, to: sq }); selectedSquare = ""; - render(); + legalTargets = []; + updateUI(); } else { - // Select one of my own pieces when it is my turn. - const cellData = (S?.board || []).find((c: any) => c.square === sq); - const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null; - const isMyColor = !!myColor && cellData?.color === myColor; - if (isMyColor && S?.phase === "play" && S?.turn === S?.me) { + // Select piece + if (clickedCell && clickedCell.color === myColor) { selectedSquare = sq; - render(); + try { + legalTargets = getLegalMoves(sq, S.board, myColor); + } catch (err) { + legalTargets = []; + } + updateUI(); } } -}); - -render(); +} diff --git a/client-src/src/pieces.ts b/client-src/src/pieces.ts new file mode 100644 index 0000000..4d1044a --- /dev/null +++ b/client-src/src/pieces.ts @@ -0,0 +1,119 @@ +/** + * High-quality vector SVGs for standard Chess pieces (Staunton design). + * Provides clean, crisp rendering at all DPRs and sizes. + */ + +export type PieceType = "k" | "q" | "r" | "b" | "n" | "p"; +export type PieceColor = "w" | "b"; + +const PIECE_SVGS: Record = { + k: { + w: ` + + + + + + + `, + b: ` + + + + + + + `, + }, + q: { + w: ` + + + + + + + + `, + b: ` + + + + + + + + `, + }, + r: { + w: ` + + + + + + + `, + b: ` + + + + + + + `, + }, + b: { + w: ` + + + + + + + + + `, + b: ` + + + + + + + + + `, + }, + n: { + w: ` + + + + + + + `, + b: ` + + + + + + + `, + }, + p: { + w: ` + + `, + b: ` + + `, + }, +}; + +export function getPieceSvg(type: PieceType | null, color: PieceColor | null): string { + if (!type || !color) return ""; + return PIECE_SVGS[type]?.[color] ?? ""; +} diff --git a/client-src/src/rules-hint.ts b/client-src/src/rules-hint.ts new file mode 100644 index 0000000..7fd24f4 --- /dev/null +++ b/client-src/src/rules-hint.ts @@ -0,0 +1,286 @@ +/** + * Client-side move hint evaluator. + * Computes legal move destinations for any selected piece so the UI can render: + * - Movement dots on empty squares + * - Attack rings on capturable enemy pieces + */ + +export interface CellInfo { + square: string; + type: string | null; + color: string | null; +} + +function parseSq(sq: string): { f: number; r: number } { + return { + f: sq.charCodeAt(0) - 97, + r: parseInt(sq[1], 10) - 1, + }; +} + +function formatSquare(f: number, r: number): string { + return String.fromCharCode(97 + f) + (r + 1); +} + +export function getLegalMoves( + fromSquare: string, + board: CellInfo[], + myColor: string +): { target: string; isCapture: boolean }[] { + const boardMap = new Map(); + for (const c of board) boardMap.set(c.square, c); + + const piece = boardMap.get(fromSquare); + if (!piece || !piece.type || piece.color !== myColor) return []; + + const { f, r } = parseSq(fromSquare); + const candidates: { target: string; isCapture: boolean }[] = []; + + const addIfValid = (tf: number, tr: number) => { + if (tf < 0 || tf > 7 || tr < 0 || tr > 7) return false; + const destSq = formatSquare(tf, tr); + const dest = boardMap.get(destSq); + if (!dest || !dest.color) { + candidates.push({ target: destSq, isCapture: false }); + return true; // continue ray + } + if (dest.color !== myColor) { + candidates.push({ target: destSq, isCapture: true }); + } + return false; // hit piece, stop ray + }; + + switch (piece.type) { + case "p": { + const dir = myColor === "w" ? 1 : -1; + const startRank = myColor === "w" ? 1 : 6; + // 1-step forward + const oneFwd = formatSquare(f, r + dir); + const c1 = boardMap.get(oneFwd); + if (c1 && !c1.color) { + candidates.push({ target: oneFwd, isCapture: false }); + // 2-step forward + if (r === startRank) { + const twoFwd = formatSquare(f, r + dir * 2); + const c2 = boardMap.get(twoFwd); + if (c2 && !c2.color) { + candidates.push({ target: twoFwd, isCapture: false }); + } + } + } + // Diagonal captures + for (const df of [-1, 1]) { + if (f + df >= 0 && f + df <= 7) { + const diagSq = formatSquare(f + df, r + dir); + const dest = boardMap.get(diagSq); + if (dest && dest.color && dest.color !== myColor) { + candidates.push({ target: diagSq, isCapture: true }); + } + } + } + break; + } + + case "n": { + const knightOffsets = [ + [-2, -1], [-2, 1], [-1, -2], [-1, 2], + [1, -2], [1, 2], [2, -1], [2, 1], + ]; + for (const [df, dr] of knightOffsets) { + const tf = f + df; + const tr = r + dr; + if (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const destSq = formatSquare(tf, tr); + const dest = boardMap.get(destSq); + if (!dest || !dest.color) { + candidates.push({ target: destSq, isCapture: false }); + } else if (dest.color !== myColor) { + candidates.push({ target: destSq, isCapture: true }); + } + } + } + break; + } + + case "b": { + const dirs = [[-1, -1], [-1, 1], [1, -1], [1, 1]]; + for (const [df, dr] of dirs) { + let tf = f + df; + let tr = r + dr; + while (addIfValid(tf, tr)) { + tf += df; + tr += dr; + } + } + break; + } + + case "r": { + const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + for (const [df, dr] of dirs) { + let tf = f + df; + let tr = r + dr; + while (addIfValid(tf, tr)) { + tf += df; + tr += dr; + } + } + break; + } + + case "q": { + const dirs = [ + [-1, -1], [-1, 1], [1, -1], [1, 1], + [-1, 0], [1, 0], [0, -1], [0, 1], + ]; + for (const [df, dr] of dirs) { + let tf = f + df; + let tr = r + dr; + while (addIfValid(tf, tr)) { + tf += df; + tr += dr; + } + } + break; + } + + case "k": { + for (let df = -1; df <= 1; df++) { + for (let dr = -1; dr <= 1; dr++) { + if (df === 0 && dr === 0) continue; + const tf = f + df; + const tr = r + dr; + if (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const destSq = formatSquare(tf, tr); + const dest = boardMap.get(destSq); + if (!dest || !dest.color) { + candidates.push({ target: destSq, isCapture: false }); + } else if (dest.color !== myColor) { + candidates.push({ target: destSq, isCapture: true }); + } + } + } + } + // Castling candidates (if path clear) + const rankK = myColor === "w" ? 0 : 7; + if (r === rankK && f === 4) { + // Kingside + const f1 = boardMap.get(formatSquare(5, rankK)); + const g1 = boardMap.get(formatSquare(6, rankK)); + const h1 = boardMap.get(formatSquare(7, rankK)); + if (f1 && !f1.color && g1 && !g1.color && h1?.type === "r" && h1.color === myColor) { + candidates.push({ target: formatSquare(6, rankK), isCapture: false }); + } + // Queenside + const d1 = boardMap.get(formatSquare(3, rankK)); + const c1 = boardMap.get(formatSquare(2, rankK)); + const b1 = boardMap.get(formatSquare(1, rankK)); + const a1 = boardMap.get(formatSquare(0, rankK)); + if (d1 && !d1.color && c1 && !c1.color && b1 && !b1.color && a1?.type === "r" && a1.color === myColor) { + candidates.push({ target: formatSquare(2, rankK), isCapture: false }); + } + } + break; + } + } + + // Filter candidates to ensure they do not leave King in check + return candidates.filter((cand) => !simLeavesInCheck(fromSquare, cand.target, board, myColor)); +} + +function simLeavesInCheck( + fromSquare: string, + targetSquare: string, + board: CellInfo[], + myColor: string +): boolean { + // Simulate board after move + const sim = board.map((c) => { + if (c.square === fromSquare) return { square: fromSquare, type: null, color: null }; + if (c.square === targetSquare) { + const moving = board.find((b) => b.square === fromSquare); + return { square: targetSquare, type: moving?.type ?? null, color: myColor }; + } + return { ...c }; + }); + + // Find my king + const kingCell = sim.find((c) => c.type === "k" && c.color === myColor); + if (!kingCell) return false; + const { f: kf, r: kr } = parseSq(kingCell.square); + + const oppColor = myColor === "w" ? "b" : "w"; + const simMap = new Map(); + for (const c of sim) simMap.set(c.square, c); + + // Check attacks from enemy pieces on (kf, kr) + // 1. Knights + const knightOffsets = [ + [-2, -1], [-2, 1], [-1, -2], [-1, 2], + [1, -2], [1, 2], [2, -1], [2, 1], + ]; + for (const [df, dr] of knightOffsets) { + const tf = kf + df; + const tr = kr + dr; + if (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const p = simMap.get(formatSquare(tf, tr)); + if (p && p.color === oppColor && p.type === "n") return true; + } + } + + // 2. Pawns + const pawnDir = oppColor === "w" ? 1 : -1; + for (const df of [-1, 1]) { + const pf = kf - df; + const pr = kr - pawnDir; + if (pf >= 0 && pf <= 7 && pr >= 0 && pr <= 7) { + const p = simMap.get(formatSquare(pf, pr)); + if (p && p.color === oppColor && p.type === "p") return true; + } + } + + // 3. Sliding orthogonals (Rook, Queen) + for (const [df, dr] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) { + let tf = kf + df; + let tr = kr + dr; + while (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const p = simMap.get(formatSquare(tf, tr)); + if (p && p.color) { + if (p.color === oppColor && (p.type === "r" || p.type === "q")) return true; + break; + } + tf += df; + tr += dr; + } + } + + // 4. Sliding diagonals (Bishop, Queen) + for (const [df, dr] of [[-1, -1], [-1, 1], [1, -1], [1, 1]]) { + let tf = kf + df; + let tr = kr + dr; + while (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const p = simMap.get(formatSquare(tf, tr)); + if (p && p.color) { + if (p.color === oppColor && (p.type === "b" || p.type === "q")) return true; + break; + } + tf += df; + tr += dr; + } + } + + // 5. Enemy king adjacent + for (let df = -1; df <= 1; df++) { + for (let dr = -1; dr <= 1; dr++) { + if (df === 0 && dr === 0) continue; + const tf = kf + df; + const tr = kr + dr; + if (tf >= 0 && tf <= 7 && tr >= 0 && tr <= 7) { + const p = simMap.get(formatSquare(tf, tr)); + if (p && p.color === oppColor && p.type === "k") return true; + } + } + } + + return false; +} diff --git a/client-src/src/style.css b/client-src/src/style.css index 63bcf0c..4549b49 100644 --- a/client-src/src/style.css +++ b/client-src/src/style.css @@ -1,18 +1,491 @@ -html, body { margin: 0; height: 100%; background: #1a1a2e; color: #f1f3f5; font-family: system-ui, sans-serif; } -#app { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 16px; } -.status { font-size: 22px; font-weight: 700; } -.info { font-size: 14px; opacity: 0.8; } -.board { display: grid; grid-template-columns: repeat(8, min(10vmin, 60px)); grid-template-rows: repeat(8, min(10vmin, 60px)); gap: 1px; border: 3px solid #c5a065; border-radius: 4px; overflow: hidden; } -.cell { aspect-ratio: 1; font-size: min(6vmin, 36px); font-weight: 800; border: 0; border-radius: 0; color: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; } -/* Square colours are assigned per square in JS (a1 is dark), so orientation flips keep them correct. */ -.cell.light { background: #d18b47; } -.cell.dark { background: #8b5e3c; } -.cell:disabled { cursor: default; opacity: 0.85; } -.cell.selected { outline: 3px solid #ffd43b; outline-offset: -3px; } -.hint { font-size: 14px; font-weight: 600; color: #ffd43b; } -.promo { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; background: #2b2b45; border-radius: 10px; padding: 8px 12px; } -.promo-btn { font-size: 30px; line-height: 1; border: 0; border-radius: 8px; background: #d18b47; color: #1a1a2e; cursor: pointer; padding: 4px 10px; } -.promo-cancel { font-size: 13px; border: 0; border-radius: 8px; background: transparent; color: #f1f3f5; cursor: pointer; padding: 6px 8px; } -.cell[data-color="w"] { color: #f0f0f0; text-shadow: 1px 1px 2px #333; } -.cell[data-color="b"] { color: #222; text-shadow: 1px 1px 2px #ddd; } -.legend { font-size: 12px; opacity: 0.7; } +/* ========================================================================== + Modern 2D Chess Styling with Responsive Animation & VFX Support + ========================================================================== */ + +:root { + --bg-primary: #14151b; + --bg-card: #1e2029; + --bg-card-hover: #282a36; + --text-main: #f3f4f6; + --text-muted: #9ca3af; + --gold-accent: #f59e0b; + --gold-light: #fbbf24; + --danger: #ef4444; + --board-light: #f0d9b5; + --board-dark: #b58863; + --board-border: #3b2818; + --coord-light: #b58863; + --coord-dark: #f0d9b5; +} + +*, *::before, *::after { + box-sizing: border-box; +} + +html, body { + margin: 0; + padding: 0; + width: 100%; + height: 100%; + background: radial-gradient(circle at center, #1b1c26 0%, #101117 100%); + color: var(--text-main); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Vazirmatn", sans-serif; + overflow: hidden; + user-select: none; + -webkit-user-select: none; +} + +#app { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 8px 12px; + gap: 8px; +} + +/* ========================================================================== + Player Cards & Header / Footer + ========================================================================== */ + +.player-bar { + width: min(88vmin, 540px); + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 12px; + background: rgba(30, 32, 41, 0.85); + backdrop-filter: blur(8px); + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + transition: border-color 0.25s ease, box-shadow 0.25s ease; +} + +.player-bar.active { + border-color: var(--gold-accent); + box-shadow: 0 0 14px rgba(245, 158, 11, 0.35); +} + +.player-profile { + display: flex; + align-items: center; + gap: 10px; +} + +.player-badge { + width: 28px; + height: 28px; + border-radius: 6px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); +} + +.player-badge.w { + background: #f8fafc; + color: #1e293b; + border: 1px solid #cbd5e1; +} + +.player-badge.b { + background: #1e2029; + color: #f8fafc; + border: 1px solid #475569; +} + +.player-meta { + display: flex; + flex-direction: column; + gap: 2px; +} + +.player-name { + font-size: 14px; + font-weight: 700; + display: flex; + align-items: center; + gap: 6px; +} + +.bot-tag { + font-size: 10px; + font-weight: 800; + padding: 1px 5px; + background: #334155; + color: #94a3b8; + border-radius: 4px; + letter-spacing: 0.5px; +} + +.bot-tag.you-tag { + background: #1e3a8a; + color: #60a5fa; + border: 1px solid rgba(96, 165, 250, 0.4); +} + +.player-status { + font-size: 11px; + color: var(--text-muted); +} + +.captured-tray { + display: flex; + align-items: center; + gap: 2px; + min-height: 22px; + flex-wrap: wrap; +} + +.captured-tray .mini-piece { + width: 18px; + height: 18px; + opacity: 0.85; +} + +.advantage-score { + font-size: 11px; + font-weight: 800; + color: var(--gold-accent); + margin-inline-start: 4px; +} + +/* ========================================================================== + Chess Board & Cells + ========================================================================== */ + +.board-container { + position: relative; + width: min(88vmin, 540px); + aspect-ratio: 1; + border-radius: 8px; + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.6), 0 2px 6px rgba(0, 0, 0, 0.4); + padding: 4px; + background: var(--board-border); + direction: ltr !important; +} + +.board-grid { + display: grid; + grid-template-columns: repeat(8, 1fr); + grid-template-rows: repeat(8, 1fr); + width: 100%; + height: 100%; + border-radius: 6px; + overflow: hidden; + direction: ltr !important; +} + +.cell { + position: relative; + aspect-ratio: 1; + padding: 0; + margin: 0; + border: 0; + background: transparent; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + outline: none; + transition: background-color 0.15s ease; +} + +.cell.light { + background-color: var(--board-light); +} + +.cell.dark { + background-color: var(--board-dark); +} + +.cell.selected { + background-color: #baca44 !important; +} + +.cell.last-move { + background-color: rgba(245, 158, 11, 0.42) !important; +} + +.cell.in-check { + background: radial-gradient(circle at center, rgba(239, 68, 68, 0.95) 0%, rgba(220, 38, 38, 0.4) 60%, transparent 75%) !important; + animation: king-check-pulse 1.2s ease-in-out infinite; +} + +@keyframes king-check-pulse { + 0%, 100% { filter: drop-shadow(0 0 4px rgba(239, 68, 68, 0.8)); } + 50% { filter: drop-shadow(0 0 14px rgba(239, 68, 68, 1)); } +} + +/* Board coordinate notation labels */ +.coord-rank, .coord-file { + position: absolute; + font-size: 10px; + font-weight: 800; + pointer-events: none; + opacity: 0.75; + line-height: 1; +} + +.coord-rank { + top: 3px; + left: 4px; +} + +.coord-file { + bottom: 3px; + right: 4px; +} + +.cell.light .coord-rank, .cell.light .coord-file { + color: var(--coord-light); +} + +.cell.dark .coord-rank, .cell.dark .coord-file { + color: var(--coord-dark); +} + +/* ========================================================================== + Pieces & SVGs + ========================================================================== */ + +.piece-wrapper { + width: 90%; + height: 90%; + display: flex; + align-items: center; + justify-content: center; + pointer-events: none; + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1), filter 0.2s ease; +} + +.piece-svg { + width: 100%; + height: 100%; + filter: drop-shadow(0 2px 3px rgba(0, 0, 0, 0.28)); + display: block; +} + +.cell:not(:disabled):hover .piece-wrapper { + transform: translateY(-3px) scale(1.06); + filter: drop-shadow(0 6px 8px rgba(0, 0, 0, 0.35)); +} + +.cell.selected .piece-wrapper { + transform: translateY(-5px) scale(1.14); + filter: drop-shadow(0 8px 14px rgba(0, 0, 0, 0.45)); + animation: piece-hover-breath 1.8s ease-in-out infinite alternate; +} + +@keyframes piece-hover-breath { + 0% { transform: translateY(-5px) scale(1.14); } + 100% { transform: translateY(-7px) scale(1.18); } +} + +/* Physical animation classes */ +.piece-wrapper.anim-land { + animation: piece-land-squash 0.22s ease-out; +} + +@keyframes piece-land-squash { + 0% { transform: scale(1.12, 0.88); } + 50% { transform: scale(0.96, 1.04); } + 100% { transform: scale(1, 1); } +} + +.piece-wrapper.anim-knight { + animation: knight-arc-leap 0.28s cubic-bezier(0.25, 0.46, 0.45, 0.94); +} + +@keyframes knight-arc-leap { + 0% { transform: translateY(0) scale(1); } + 50% { transform: translateY(-16px) scale(1.22); } + 85% { transform: translateY(0) scale(1.08, 0.92); } + 100% { transform: translateY(0) scale(1); } +} + +/* ========================================================================== + Move Indicators: Dots & Capture Reticles + ========================================================================== */ + +.move-dot { + position: absolute; + width: 32%; + height: 32%; + border-radius: 50%; + background: rgba(0, 0, 0, 0.24); + pointer-events: none; + animation: dot-spawn 0.18s cubic-bezier(0.34, 1.56, 0.64, 1); + transition: transform 0.15s ease, background-color 0.15s ease; +} + +.cell:hover .move-dot { + transform: scale(1.3); + background: rgba(0, 0, 0, 0.36); +} + +@keyframes dot-spawn { + 0% { transform: scale(0); opacity: 0; } + 100% { transform: scale(1); opacity: 1; } +} + +.capture-ring { + position: absolute; + inset: 0; + border: 4px solid rgba(239, 68, 68, 0.72); + border-radius: 50%; + pointer-events: none; + animation: ring-spawn 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +@keyframes ring-spawn { + 0% { transform: scale(0.5); opacity: 0; } + 100% { transform: scale(1); opacity: 1; } +} + +/* ========================================================================== + VFX Canvas Overlay + ========================================================================== */ + +#vfx-canvas { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; + z-index: 10; +} + +/* ========================================================================== + Promotion Picker Modal + ========================================================================== */ + +.modal-backdrop { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(4px); + display: flex; + align-items: center; + justify-content: center; + z-index: 50; + animation: fade-in 0.2s ease; +} + +.promo-card { + background: var(--bg-card); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 12px; + padding: 16px 20px; + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + box-shadow: 0 16px 36px rgba(0, 0, 0, 0.7); + animation: modal-spring 0.26s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.promo-title { + font-size: 15px; + font-weight: 700; + color: var(--text-main); +} + +.promo-options { + display: flex; + gap: 10px; +} + +.promo-piece-btn { + width: 58px; + height: 58px; + background: #2a2c38; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 10px; + cursor: pointer; + padding: 6px; + display: flex; + align-items: center; + justify-content: center; + transition: transform 0.18s cubic-bezier(0.34, 1.56, 0.64, 1), background-color 0.15s ease, box-shadow 0.18s ease; +} + +.promo-piece-btn:hover { + transform: translateY(-4px) scale(1.12); + background: #373a4a; + box-shadow: 0 8px 18px rgba(0, 0, 0, 0.4); +} + +.promo-cancel-btn { + background: transparent; + border: 0; + color: var(--text-muted); + font-size: 13px; + font-weight: 600; + cursor: pointer; + padding: 4px 12px; + transition: color 0.15s ease; +} + +.promo-cancel-btn:hover { + color: var(--text-main); +} + +@keyframes modal-spring { + 0% { transform: scale(0.6); opacity: 0; } + 100% { transform: scale(1); opacity: 1; } +} + +@keyframes fade-in { + 0% { opacity: 0; } + 100% { opacity: 1; } +} + +/* ========================================================================== + Game Over Banner + ========================================================================== */ + +.game-over-banner { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: rgba(24, 25, 34, 0.94); + backdrop-filter: blur(8px); + border: 2px solid var(--gold-accent); + border-radius: 14px; + padding: 16px 28px; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + box-shadow: 0 16px 40px rgba(0, 0, 0, 0.8), 0 0 24px rgba(245, 158, 11, 0.4); + z-index: 40; + animation: banner-spring 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); + text-align: center; +} + +.game-over-title { + font-size: 22px; + font-weight: 800; + color: var(--gold-light); + display: flex; + align-items: center; + gap: 8px; +} + +.game-over-subtitle { + font-size: 14px; + color: var(--text-muted); + font-weight: 600; +} + +@keyframes banner-spring { + 0% { transform: translate(-50%, -50%) scale(0.4); opacity: 0; } + 100% { transform: translate(-50%, -50%) scale(1); opacity: 1; } +} diff --git a/client-src/src/vfx.ts b/client-src/src/vfx.ts new file mode 100644 index 0000000..0dacbab --- /dev/null +++ b/client-src/src/vfx.ts @@ -0,0 +1,300 @@ +/** + * 2D Game VFX Engine for Chess (canvas-based). + * Implements particles, bursts, shockwaves, rings, and celebrations + * according to the 2D Game VFX skill. + */ + +interface Particle { + x: number; + y: number; + vx: number; + vy: number; + radius: number; + color: string; + alpha: number; + decay: number; + gravity: number; + drag: number; + rotation?: number; + vRot?: number; + shape?: "circle" | "spark" | "rect" | "star"; + size?: number; +} + +interface Shockwave { + x: number; + y: number; + radius: number; + maxRadius: number; + color: string; + alpha: number; + decay: number; + lineWidth: number; +} + +export class VfxEngine { + private canvas: HTMLCanvasElement; + private ctx: CanvasRenderingContext2D; + private particles: Particle[] = []; + private shockwaves: Shockwave[] = []; + private animId: number | null = null; + private lastTime = 0; + + constructor(canvas: HTMLCanvasElement) { + this.canvas = canvas; + this.ctx = canvas.getContext("2d")!; + this.resize(); + window.addEventListener("resize", () => this.resize()); + this.startLoop(); + } + + public resize() { + const rect = this.canvas.parentElement?.getBoundingClientRect(); + if (!rect) return; + const dpr = window.devicePixelRatio || 1; + this.canvas.width = Math.round(rect.width * dpr); + this.canvas.height = Math.round(rect.height * dpr); + this.canvas.style.width = `${rect.width}px`; + this.canvas.style.height = `${rect.height}px`; + this.ctx.resetTransform?.(); + this.ctx.scale(dpr, dpr); + } + + private startLoop() { + if (this.animId) return; + const loop = (time: number) => { + const dt = this.lastTime ? Math.min((time - this.lastTime) / 1000, 0.1) : 0.016; + this.lastTime = time; + this.update(dt); + this.render(); + this.animId = requestAnimationFrame(loop); + }; + this.animId = requestAnimationFrame(loop); + } + + private update(dt: number) { + // Update shockwaves + for (let i = this.shockwaves.length - 1; i >= 0; i--) { + const sw = this.shockwaves[i]; + sw.radius += (sw.maxRadius - sw.radius) * 12 * dt; + sw.alpha -= sw.decay * dt; + if (sw.alpha <= 0 || sw.radius >= sw.maxRadius * 0.98) { + this.shockwaves.splice(i, 1); + } + } + + // Update particles + for (let i = this.particles.length - 1; i >= 0; i--) { + const p = this.particles[i]; + p.x += p.vx * dt; + p.y += p.vy * dt; + p.vx *= Math.pow(p.drag, dt * 60); + p.vy *= Math.pow(p.drag, dt * 60); + p.vy += p.gravity * dt; + if (p.vRot && p.rotation !== undefined) { + p.rotation += p.vRot * dt; + } + p.alpha -= p.decay * dt; + if (p.alpha <= 0) { + this.particles.splice(i, 1); + } + } + } + + private render() { + const width = this.canvas.width / (window.devicePixelRatio || 1); + const height = this.canvas.height / (window.devicePixelRatio || 1); + this.ctx.clearRect(0, 0, width, height); + + // Render shockwaves + for (const sw of this.shockwaves) { + this.ctx.save(); + this.ctx.beginPath(); + this.ctx.arc(sw.x, sw.y, Math.max(1, sw.radius), 0, Math.PI * 2); + this.ctx.strokeStyle = sw.color; + this.ctx.globalAlpha = Math.max(0, sw.alpha); + this.ctx.lineWidth = sw.lineWidth; + this.ctx.stroke(); + this.ctx.restore(); + } + + // Render particles + for (const p of this.particles) { + this.ctx.save(); + this.ctx.globalAlpha = Math.max(0, p.alpha); + this.ctx.fillStyle = p.color; + + if (p.shape === "rect" || p.shape === "spark") { + this.ctx.translate(p.x, p.y); + if (p.rotation !== undefined) this.ctx.rotate(p.rotation); + const sz = p.size || p.radius * 2; + if (p.shape === "spark") { + this.ctx.fillRect(-sz, -sz * 0.25, sz * 2, sz * 0.5); + } else { + this.ctx.fillRect(-sz * 0.5, -sz * 0.5, sz, sz); + } + } else { + this.ctx.beginPath(); + this.ctx.arc(p.x, p.y, Math.max(0.5, p.radius), 0, Math.PI * 2); + this.ctx.fill(); + } + this.ctx.restore(); + } + } + + /** + * Impact burst when a piece captures another: + * Spark hit sparks + shockwave ring + debris + */ + public captureImpact(x: number, y: number, capturedColor: "w" | "b" = "w") { + // 1. Expanding shockwave ring + this.shockwaves.push({ + x, + y, + radius: 4, + maxRadius: 48, + color: capturedColor === "w" ? "rgba(255, 235, 180, 0.9)" : "rgba(120, 140, 180, 0.9)", + alpha: 0.9, + decay: 2.8, + lineWidth: 3, + }); + + // 2. High-speed hit sparks + const sparkColors = capturedColor === "w" + ? ["#ffffff", "#fef08a", "#f59e0b", "#fbbf24"] + : ["#94a3b8", "#cbd5e1", "#64748b", "#38bdf8"]; + + const count = 18; + for (let i = 0; i < count; i++) { + const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5) * 0.5; + const speed = 120 + Math.random() * 220; + this.particles.push({ + x, + y, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed, + radius: 2 + Math.random() * 2.5, + color: sparkColors[Math.floor(Math.random() * sparkColors.length)], + alpha: 1.0, + decay: 1.8 + Math.random() * 1.4, + gravity: 80, + drag: 0.92, + shape: "spark", + size: 3 + Math.random() * 3, + rotation: angle, + }); + } + + // 3. Smoke / dust puffs + for (let i = 0; i < 6; i++) { + const angle = Math.random() * Math.PI * 2; + const speed = 25 + Math.random() * 45; + this.particles.push({ + x: x + (Math.random() - 0.5) * 12, + y: y + (Math.random() - 0.5) * 12, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed, + radius: 4 + Math.random() * 6, + color: "rgba(200, 200, 210, 0.4)", + alpha: 0.6, + decay: 1.2, + gravity: -10, + drag: 0.88, + shape: "circle", + }); + } + } + + /** + * Landing feedback on move completion: subtle dust puff + */ + public landingPuff(x: number, y: number) { + for (let i = 0; i < 8; i++) { + const angle = Math.PI * 0.15 + (Math.random() * Math.PI * 0.7); + const speed = 20 + Math.random() * 40; + this.particles.push({ + x: x + (Math.random() - 0.5) * 10, + y: y + 10, + vx: (Math.random() - 0.5) * speed, + vy: -Math.random() * 20, + radius: 2.5 + Math.random() * 3, + color: "rgba(220, 220, 230, 0.35)", + alpha: 0.5, + decay: 2.0, + gravity: 15, + drag: 0.85, + shape: "circle", + }); + } + } + + /** + * Magical ascension / burst on Pawn Promotion + */ + public promotionBurst(x: number, y: number) { + this.shockwaves.push({ + x, + y, + radius: 6, + maxRadius: 60, + color: "rgba(251, 191, 36, 0.95)", + alpha: 1.0, + decay: 2.0, + lineWidth: 4, + }); + + const colors = ["#fbbf24", "#fef08a", "#60a5fa", "#a78bfa", "#ffffff"]; + for (let i = 0; i < 28; i++) { + const angle = Math.random() * Math.PI * 2; + const speed = 60 + Math.random() * 180; + this.particles.push({ + x, + y, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed - 50, + radius: 2 + Math.random() * 3, + color: colors[Math.floor(Math.random() * colors.length)], + alpha: 1.0, + decay: 1.2 + Math.random() * 1.0, + gravity: -30, + drag: 0.94, + shape: "rect", + size: 3 + Math.random() * 4, + rotation: Math.random() * Math.PI * 2, + vRot: (Math.random() - 0.5) * 10, + }); + } + } + + /** + * Victory celebration: confetti burst and golden stars + */ + public victoryConfetti() { + const width = this.canvas.width / (window.devicePixelRatio || 1); + const height = this.canvas.height / (window.devicePixelRatio || 1); + const colors = ["#ef4444", "#3b82f6", "#10b981", "#f59e0b", "#8b5cf6", "#ec4899", "#ffffff", "#fbbf24"]; + + for (let i = 0; i < 90; i++) { + const x = width * 0.5 + (Math.random() - 0.5) * 100; + const y = height * 0.45 + (Math.random() - 0.5) * 50; + const angle = -Math.PI * 0.5 + (Math.random() - 0.5) * Math.PI * 0.85; + const speed = 180 + Math.random() * 360; + this.particles.push({ + x, + y, + vx: Math.cos(angle) * speed, + vy: Math.sin(angle) * speed, + radius: 3 + Math.random() * 3, + color: colors[Math.floor(Math.random() * colors.length)], + alpha: 1.0, + decay: 0.4 + Math.random() * 0.3, + gravity: 160, + drag: 0.97, + shape: "rect", + size: 5 + Math.random() * 5, + rotation: Math.random() * Math.PI * 2, + vRot: (Math.random() - 0.5) * 12, + }); + } + } +}