Compare commits

..
3 Commits
Author SHA1 Message Date
Xoerex 79eda0da45 vfx and animations vite build 2026-10-15 11:17:29 +03:30
Xoerex ccd9da4866 added vfx and animations to the board 2026-10-15 11:17:12 +03:30
Xoerex ee5deb6d5f bundle files must be ignored 2026-10-15 11:16:23 +03:30
11 changed files with 1778 additions and 127 deletions
+2
View File
@@ -1,2 +1,4 @@
client-src/node_modules/* client-src/node_modules/*
client-src/dist/* client-src/dist/*
# build files
*.zip
+455 -96
View File
@@ -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 "./style.css";
import { connectHost, type InitMsg } from "@3miz/game-client/iframe"; 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 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 L = (fa: string, en: string) => (init?.locale === "en" ? en : fa);
const host = connectHost({ const host = connectHost({
@@ -13,146 +49,469 @@ const host = connectHost({
init = m; init = m;
document.documentElement.lang = m.locale; document.documentElement.lang = m.locale;
document.documentElement.dir = m.dir; document.documentElement.dir = m.dir;
render(); if (!document.getElementById("board-grid")) {
setupDOM();
}
updateUI();
}, },
onState(env) { onState(env) {
if (env.t === "snap") { if (env.t === "snap") {
S = env.body; if (!document.getElementById("board-grid")) {
// Drop any half-finished local selection once the turn moves on (e.g. timeout auto-move). setupDOM();
if (S.turn !== S.me) { selectedSquare = ""; pendingPromo = null; } }
render(); prevS = S;
S = env.body as GameSnapshot;
detectMoveEvents(prevS, S);
if (S.turn !== S.me) {
selectedSquare = "";
legalTargets = [];
pendingPromo = null;
}
updateUI();
} }
}, },
onAck(a) { 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")!; * Detect move events between snapshots for animations and VFX
if (!S) { */
app.innerHTML = `<div class="status">${L("در حال بارگذاری…", "Loading…")}</div>`; function detectMoveEvents(oldState: GameSnapshot | null, newState: GameSnapshot) {
return; 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 = `
<div id="top-bar" class="player-bar"></div>
<div class="board-container">
<canvas id="vfx-canvas"></canvas>
<div id="board-grid" class="board-grid"></div>
</div>
<div id="bottom-bar" class="player-bar"></div>
<div id="modal-container"></div>
`;
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 me = S.me;
const myColor = me !== null && me !== undefined ? S.players[me]?.color : null; const isPlaying = me !== null && me !== undefined && S.players[me] !== undefined;
// 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. // 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 flipped = myColor === "b";
const bySquare: Record<string, any> = {};
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<string, CellInfo>();
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 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 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 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 ? `<span class="piece ${cell.color}">${pieceChar(cell.type, cell.color)}</span>` : "";
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 `<button class="cell ${shade}${isSelected ? " selected" : ""}" data-from="${sq}" data-color="${cell.color || "null"}" title="${sq}" ${enabled ? "" : "disabled"}>${piece}</button>`;
}).join("")).join("");
const selHint = selectedSquare // King in check location
? `<div class="hint">${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}</div>` 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 for (const r of ranks) {
? `<div class="promo"><span>${pendingPromo.from} → ${pendingPromo.to}: ${L("ارتقا به", "Promote to")}</span> for (const f of files) {
${["q", "r", "b", "n"].map((t) => `<button class="promo-btn" data-promo="${t}" title="${t}">${pieceChar(t, myColor)}</button>`).join("")} const sq = String.fromCharCode(97 + f) + (r + 1);
<button class="promo-cancel" data-cancel-promo="1">${L("لغو", "Cancel")}</button></div>` const cell = bySquare.get(sq) || { square: sq, type: null, color: null };
: ``; const btn = cells[idx++] as HTMLButtonElement;
const statusText = S.phase === "over" btn.dataset.square = sq;
? (S.result_reason === "abandoned" btn.dataset.color = cell.color || "";
? 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!")}` : ""));
app.innerHTML = ` // Shading: a1 is dark
<div class="status">${statusText}</div> const shade = (f + r) % 2 === 0 ? "dark" : "light";
<div class="info">${S.moves_played !== undefined ? `حرکت‌ها: ${S.moves_played}` : ""}</div> const isSelected = selectedSquare === sq;
<div class="board">${boardHtml}</div> const isLastMove = lastMove && (lastMove.from === sq || lastMove.to === sq);
${selHint} const isInCheck = kingInCheckSq === sq;
${promoPicker}
<div class="legend">${L("سفید حرکت می‌کند", "White moves")}</div> 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 += `<span class="coord-rank">${r + 1}</span>`;
if (showFile) inner += `<span class="coord-file">${String.fromCharCode(97 + f)}</span>`;
// 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 += `<div class="piece-wrapper${animClass}">${svg}</div>`;
}
// Legal move dot or capture ring
if (isCaptureTarget) {
inner += `<div class="capture-ring"></div>`;
} else if (isLegalTarget) {
inner += `<div class="move-dot"></div>`;
}
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 ? `<span class="advantage-score">+${adv}</span>` : "";
const botBadge = player.bot ? `<span class="bot-tag">BOT</span>` : "";
const youBadge = isMe ? `<span class="bot-tag you-tag">${L("شما", "YOU")}</span>` : "";
const statusLabel = S.phase === "over"
? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : "")
: (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : "");
el.innerHTML = `
<div class="player-profile">
<div class="player-badge ${player.color}">
${player.color === "w" ? "♔" : "♚"}
</div>
<div class="player-meta">
<div class="player-name">${player.name} ${botBadge} ${youBadge}</div>
<div class="player-status">${statusLabel}</div>
</div>
</div>
<div class="captured-tray">
${capturedPieces.map((p) => `<div class="mini-piece">${getPieceSvg(p.type as PieceType, p.color as PieceColor)}</div>`).join("")}
${advText}
</div>
`; `;
} }
function pieceChar(type: string | null, color: string | null): string { /**
if (!type) return ""; * Calculate captured pieces for a given player color
// White uses outline glyphs, black uses filled glyphs. */
const white: Record<string, string> = { k: "♔", q: "♕", r: "♖", b: "♗", n: "♘", p: "♙" }; function getCapturedPieces(playerColor: "w" | "b"): CellInfo[] {
const black: Record<string, string> = { k: "♚", q: "♛", r: "♜", b: "♝", n: "♞", p: "♟" }; if (!S) return [];
return color === "b" ? (black[type] ?? "") : (white[type] ?? ""); const opponentColor = playerColor === "w" ? "b" : "w";
const initialCount: Record<string, number> = { p: 8, n: 2, b: 2, r: 2, q: 1 };
const currentCount: Record<string, number> = { 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<string, number> = { p: 1, n: 3, b: 3, r: 5, q: 9 };
let myScore = 0;
let oppScore = 0;
document.addEventListener("click", (e) => { for (const c of S.board) {
const el = e.target as HTMLElement; if (!c.type || !c.color) continue;
// Promotion choice buttons. const val = values[c.type] || 0;
const promoBtn = el.closest("[data-promo]") as HTMLElement | null; if (c.color === playerColor) myScore += val;
if (promoBtn && pendingPromo) { else oppScore += val;
host.cmd("move", { from: pendingPromo.from, to: pendingPromo.to, promotion: promoBtn.dataset.promo }); }
pendingPromo = null; return myScore - oppScore;
selectedSquare = ""; }
render();
/**
* 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 = `
<div class="modal-backdrop">
<div class="promo-card">
<div class="promo-title">${L("ارتقای پیاده به:", "Promote pawn to:")}</div>
<div class="promo-options">
${(["q", "r", "b", "n"] as PieceType[]).map((t) => `
<button class="promo-piece-btn" data-promo="${t}" title="${t}">
${getPieceSvg(t, myColor as PieceColor)}
</button>
`).join("")}
</div>
<button class="promo-cancel-btn" data-cancel-promo="1">${L("لغو", "Cancel")}</button>
</div>
</div>
`;
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; return;
} }
if (el.closest("[data-cancel-promo]")) {
pendingPromo = null; if (S.phase === "over") {
render(); 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 = `
<div class="game-over-banner">
<div class="game-over-title">${title}</div>
<div class="game-over-subtitle">${subtitle}</div>
</div>
`;
return; return;
} }
const b = el.closest("[data-from]") as HTMLElement | null;
if (!b) return; container.innerHTML = "";
const sq = b.dataset.from!; }
if (pendingPromo) return; // choose a promotion piece (or cancel) first
/**
* 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) {
if (selectedSquare === sq) { if (selectedSquare === sq) {
// Deselect
selectedSquare = ""; selectedSquare = "";
render(); legalTargets = [];
updateUI();
return; 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); // Switch selection to another own piece
const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null; if (clickedCell?.color && clickedCell.color === myColor) {
if (clicked?.color && myColor && clicked.color === myColor) {
selectedSquare = sq; selectedSquare = sq;
render(); try {
legalTargets = getLegalMoves(sq, S.board, myColor);
} catch (err) {
legalTargets = [];
}
updateUI();
return; 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"; const lastRank = myColor === "b" ? "1" : "8";
// Pawn promotion check
if (moving?.type === "p" && sq[1] === lastRank) { if (moving?.type === "p" && sq[1] === lastRank) {
pendingPromo = { from: selectedSquare, to: sq }; pendingPromo = { from: selectedSquare, to: sq };
selectedSquare = ""; selectedSquare = "";
render(); legalTargets = [];
updateUI();
return; return;
} }
// Send move to host
host.cmd("move", { from: selectedSquare, to: sq }); host.cmd("move", { from: selectedSquare, to: sq });
selectedSquare = ""; selectedSquare = "";
render(); legalTargets = [];
updateUI();
} else { } else {
// Select one of my own pieces when it is my turn. // Select piece
const cellData = (S?.board || []).find((c: any) => c.square === sq); if (clickedCell && clickedCell.color === myColor) {
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) {
selectedSquare = sq; selectedSquare = sq;
render(); try {
legalTargets = getLegalMoves(sq, S.board, myColor);
} catch (err) {
legalTargets = [];
}
updateUI();
} }
} }
}); }
render();
+119
View File
@@ -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<PieceType, { w: string; b: string }> = {
k: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M22.5 11.63V6M20 8h5" stroke-linejoin="miter"/>
<path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#fff" stroke-linecap="butt" stroke-linejoin="miter"/>
<path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V23.5c-2.5-7.5-12-10.5-16-4-3 6 6 10.5 6 10.5v7z" fill="#fff"/>
<path d="M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0"/>
</g>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M22.5 11.63V6M20 8h5" stroke="#fff" stroke-linejoin="miter"/>
<path d="M22.5 25s4.5-7.5 3-10.5c0 0-1-2.5-3-2.5s-3 2.5-3 2.5c-1.5 3 3 10.5 3 10.5" fill="#2d3038" stroke-linecap="butt" stroke-linejoin="miter"/>
<path d="M11.5 37c5.5 3.5 15.5 3.5 21 0v-7s9-4.5 6-10.5c-4-6.5-13.5-3.5-16 4V23.5c-2.5-7.5-12-10.5-16-4-3 6 6 10.5 6 10.5v7z" fill="#2d3038"/>
<path d="M11.5 30c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0m-21 3.5c5.5-3 15.5-3 21 0" stroke="#fff"/>
</g>
</svg>`,
},
q: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<g fill="#fff" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zm16.5-4.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM41 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM16 8.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zm17 0a2 2 0 1 1-4 0 2 2 0 1 1 4 0z"/>
<path d="M9 26c8.5-1.5 21-1.5 27 0l2-12-7 11V11l-5.5 13.5-3-15-3 15-5.5-13.5V25L7 14l2 12z" stroke-linecap="butt"/>
<path d="M9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 2-1 .5-2.5 0 0 0-1.5-1.5-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/>
<path d="M11 38.5a35 35 1 0 0 23 0" fill="none" stroke-linecap="butt"/>
<path d="M11 29a35 35 1 0 1 23 0M12.5 31.5h20M11.5 34.5a35 35 1 0 0 22 0M10.5 37.5a35 35 1 0 0 24 0" fill="none"/>
</g>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<g fill="#2d3038" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zm16.5-4.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM41 12a2 2 0 1 1-4 0 2 2 0 1 1 4 0zM16 8.5a2 2 0 1 1-4 0 2 2 0 1 1 4 0zm17 0a2 2 0 1 1-4 0 2 2 0 1 1 4 0z"/>
<path d="M9 26c8.5-1.5 21-1.5 27 0l2-12-7 11V11l-5.5 13.5-3-15-3 15-5.5-13.5V25L7 14l2 12z" stroke-linecap="butt"/>
<path d="M9 26c0 2 1.5 2 2.5 4 1 1.5 1 1 .5 3.5-1.5 1-1.5 2.5-1.5 2.5-1.5 1.5.5 2.5.5 2.5 6.5 1 16.5 1 23 0 0 0 2-1 .5-2.5 0 0 0-1.5-1.5-2.5-.5-2.5-.5-2 .5-3.5 1-2 2.5-2 2.5-4-8.5-1.5-18.5-1.5-27 0z" stroke-linecap="butt"/>
<path d="M11 38.5a35 35 1 0 0 23 0" fill="none" stroke="#fff" stroke-linecap="butt"/>
<path d="M11 29a35 35 1 0 1 23 0M12.5 31.5h20M11.5 34.5a35 35 1 0 0 22 0M10.5 37.5a35 35 1 0 0 24 0" fill="none" stroke="#fff"/>
</g>
</svg>`,
},
r: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<g fill="#fff" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 39h27v-3H9v3zm3-3v-4.5h21V36H12zm2-4.5v-11h17v11H14z" stroke-linecap="butt"/>
<path d="M14 20.5h17M11 14h23l-2.5 6.5h-18L11 14z"/>
<path d="M12 10.5h4v3.5h-4zm7 0h7v3.5h-7zm10 0h4v3.5h-4z" stroke-linecap="butt"/>
<path d="M14 29.5v-1h17v1H14zm-1 3.5v-1h19v1H13z" fill="none"/>
</g>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<g fill="#2d3038" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M9 39h27v-3H9v3zm3-3v-4.5h21V36H12zm2-4.5v-11h17v11H14z" stroke-linecap="butt"/>
<path d="M14 20.5h17M11 14h23l-2.5 6.5h-18L11 14z"/>
<path d="M12 10.5h4v3.5h-4zm7 0h7v3.5h-7zm10 0h4v3.5h-4z" stroke-linecap="butt"/>
<path d="M14 29.5v-1h17v1H14zm-1 3.5v-1h19v1H13z" fill="none" stroke="#fff"/>
</g>
</svg>`,
},
b: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<g fill="#fff">
<path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.35.49-2.32.47-3-.5 1.35-1.94 3-2 3-2z"/>
<path d="M15 32c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2z"/>
<path d="M25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z"/>
</g>
<path d="M17.5 26h10M15 30h15M22.5 15.5v5M20 18h5" stroke-linejoin="miter"/>
</g>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<g fill="#2d3038">
<path d="M9 36c3.39-.97 10.11.43 13.5-2 3.39 2.43 10.11 1.03 13.5 2 0 0 1.65.54 3 2-.68.97-1.65.99-3 .5-3.39-.97-10.11.46-13.5-1-3.39 1.46-10.11.03-13.5 1-1.35.49-2.32.47-3-.5 1.35-1.94 3-2 3-2z"/>
<path d="M15 32c2.5 2.5 12.5 2.5 15 0 .5-1.5 0-2 0-2 0-2.5-2.5-4-2.5-4 5.5-1.5 6-11.5-5-15.5-11 4-10.5 14-5 15.5 0 0-2.5 1.5-2.5 4 0 0-.5.5 0 2z"/>
<path d="M25 8a2.5 2.5 0 1 1-5 0 2.5 2.5 0 1 1 5 0z"/>
</g>
<path d="M17.5 26h10M15 30h15M22.5 15.5v5M20 18h5" stroke="#fff" stroke-linejoin="miter"/>
</g>
</svg>`,
},
n: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18" fill="#fff"/>
<path d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,7.4 17.03,5.16 20,6 C 22,6.5 21.84,7.85 22,10 z" fill="#fff"/>
<path d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z" fill="#222" stroke="#222"/>
<path d="M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z" transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)" fill="#222" stroke="#222"/>
</g>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<g fill="none" fill-rule="evenodd" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M 22,10 C 32.5,11 38.5,18 38,39 L 15,39 C 15,30 25,32.5 23,18" fill="#2d3038"/>
<path d="M 24,18 C 24.38,20.91 18.45,25.37 16,27 C 13,29 13.18,31.34 11,31 C 9.958,30.06 12.41,27.96 11,28 C 10,28 11.19,29.23 10,30 C 9,30 5.997,31 6,26 C 6,24 12,14 12,14 C 12,14 13.89,12.1 14,10.5 C 13.27,7.4 17.03,5.16 20,6 C 22,6.5 21.84,7.85 22,10 z" fill="#2d3038"/>
<path d="M 9.5 25.5 A 0.5 0.5 0 1 1 8.5,25.5 A 0.5 0.5 0 1 1 9.5 25.5 z" fill="#fff" stroke="#fff"/>
<path d="M 15 15.5 A 0.5 1.5 0 1 1 14,15.5 A 0.5 1.5 0 1 1 15 15.5 z" transform="matrix(0.866,0.5,-0.5,0.866,9.693,-5.173)" fill="#fff" stroke="#fff"/>
</g>
</svg>`,
},
p: {
w: `<svg viewBox="0 0 45 45" class="piece-svg piece-w" xmlns="http://www.w3.org/2000/svg">
<path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" fill="#fff" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`,
b: `<svg viewBox="0 0 45 45" class="piece-svg piece-b" xmlns="http://www.w3.org/2000/svg">
<path d="M22.5 9c-2.21 0-4 1.79-4 4 0 .89.29 1.71.78 2.38C17.33 16.5 16 18.59 16 21c0 2.03.94 3.84 2.41 5.03-3 1.06-7.41 5.55-7.41 13.47h23c0-7.92-4.41-12.41-7.41-13.47 1.47-1.19 2.41-3 2.41-5.03 0-2.41-1.33-4.5-3.28-5.62.49-.67.78-1.49.78-2.38 0-2.21-1.79-4-4-4z" fill="#2d3038" stroke="#222" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`,
},
};
export function getPieceSvg(type: PieceType | null, color: PieceColor | null): string {
if (!type || !color) return "";
return PIECE_SVGS[type]?.[color] ?? "";
}
+286
View File
@@ -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<string, CellInfo>();
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<string, CellInfo>();
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;
}
+491 -18
View File
@@ -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; } Modern 2D Chess Styling with Responsive Animation & VFX Support
.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; } :root {
.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; } --bg-primary: #14151b;
/* Square colours are assigned per square in JS (a1 is dark), so orientation flips keep them correct. */ --bg-card: #1e2029;
.cell.light { background: #d18b47; } --bg-card-hover: #282a36;
.cell.dark { background: #8b5e3c; } --text-main: #f3f4f6;
.cell:disabled { cursor: default; opacity: 0.85; } --text-muted: #9ca3af;
.cell.selected { outline: 3px solid #ffd43b; outline-offset: -3px; } --gold-accent: #f59e0b;
.hint { font-size: 14px; font-weight: 600; color: #ffd43b; } --gold-light: #fbbf24;
.promo { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; background: #2b2b45; border-radius: 10px; padding: 8px 12px; } --danger: #ef4444;
.promo-btn { font-size: 30px; line-height: 1; border: 0; border-radius: 8px; background: #d18b47; color: #1a1a2e; cursor: pointer; padding: 4px 10px; } --board-light: #f0d9b5;
.promo-cancel { font-size: 13px; border: 0; border-radius: 8px; background: transparent; color: #f1f3f5; cursor: pointer; padding: 6px 8px; } --board-dark: #b58863;
.cell[data-color="w"] { color: #f0f0f0; text-shadow: 1px 1px 2px #333; } --board-border: #3b2818;
.cell[data-color="b"] { color: #222; text-shadow: 1px 1px 2px #ddd; } --coord-light: #b58863;
.legend { font-size: 12px; opacity: 0.7; } --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; }
}
+300
View File
@@ -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,
});
}
}
}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
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:.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}.cell.light{background:#d18b47}.cell.dark{background:#8b5e3c}.cell:disabled{cursor:default;opacity:.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:.7}
File diff suppressed because one or more lines are too long
-10
View File
@@ -1,10 +0,0 @@
(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const t of document.querySelectorAll('link[rel="modulepreload"]'))d(t);new MutationObserver(t=>{for(const n of t)if(n.type==="childList")for(const s of n.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&d(s)}).observe(document,{childList:!0,subtree:!0});function a(t){const n={};return t.integrity&&(n.integrity=t.integrity),t.referrerPolicy&&(n.referrerPolicy=t.referrerPolicy),t.crossOrigin==="use-credentials"?n.credentials="include":t.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function d(t){if(t.ep)return;t.ep=!0;const n=a(t);fetch(t.href,n)}})();function I(o){const r=new URLSearchParams(location.search).get("host")??"*",a=t=>window.parent.postMessage({m3:1,...t},r);let d=0;return window.addEventListener("message",t=>{var s,l,u;if(t.source!==window.parent||r!=="*"&&t.origin!==r)return;const n=t.data;if(!(!n||n.m3!==1))switch(n.type){case"init":o.onInit(n),a({type:"ready"});break;case"state":o.onState(n.env);break;case"ack":(s=o.onAck)==null||s.call(o,n);break;case"view_changed":(l=o.onViewChanged)==null||l.call(o,n.view);break;case"cmd_failed":(u=o.onCmdFailed)==null||u.call(o,n.req_id,n.code);break}}),a({type:"loaded"}),{cmd(t,n={}){const s=++d;return a({type:"cmd",cmd_type:t,payload:n,req_id:s}),s},toast(t,n,s="info"){a({type:"toast",text_fa:t,text_en:n,kind:s})}}}let e=null,w=null;const i=(o,r)=>(w==null?void 0:w.locale)==="en"?r:o,k=I({onInit(o){w=o,document.documentElement.lang=o.locale,document.documentElement.dir=o.dir,p()},onState(o){o.t==="snap"&&(e=o.body,e.turn!==e.me&&(c="",m=null),p())},onAck(o){o.status==="rejected"&&k.toast("حرکت پذیرفته نشد","Move not accepted","warn")}});function p(){var q,h,C,L;const o=document.getElementById("app");if(!e){o.innerHTML=`<div class="status">${i("در حال بارگذاری…","Loading…")}</div>`;return}const r=e.me,a=r!=null?(q=e.players[r])==null?void 0:q.color:null,d=a==="b",t={};for(const f of e.board)t[f.square]=f;const n=d?[7,6,5,4,3,2,1,0]:[0,1,2,3,4,5,6,7],s=d?[0,1,2,3,4,5,6,7]:[7,6,5,4,3,2,1,0],l=e.phase==="play"&&e.turn===r,u=s.map(f=>n.map(_=>{const g=String.fromCharCode(97+_)+(f+1),y=t[g]||{type:null,color:null},P=y.color?`<span class="piece ${y.color}">${M(y.type,y.color)}</span>`:"",O=l&&!!a&&y.color===a,E=c===g,H=c?l:O;return`<button class="cell ${(_+f)%2===0?"dark":"light"}${E?" selected":""}" data-from="${g}" data-color="${y.color||"null"}" title="${g}" ${H?"":"disabled"}>${P}</button>`}).join("")).join(""),b=c?`<div class="hint">${i("مبدا","From")}: ${c} — ${i("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)","click a target square (click it again to cancel)")}</div>`:"",$=m?`<div class="promo"><span>${m.from} → ${m.to}: ${i("ارتقا به","Promote to")}</span>
${["q","r","b","n"].map(f=>`<button class="promo-btn" data-promo="${f}" title="${f}">${M(f,a)}</button>`).join("")}
<button class="promo-cancel" data-cancel-promo="1">${i("لغو","Cancel")}</button></div>`:"",v=e.phase==="over"?e.result_reason==="abandoned"?i("بازی رها شد","Abandoned"):e.winner===null?e.result_reason==="stalemate"?i("پات — مساوی!","Stalemate — draw!"):i("مساوی!","Draw!"):e.result_reason==="checkmate"?`${(h=e.players[e.winner])==null?void 0:h.name} ${i("مات کرد! 🏆","wins by checkmate 🏆")}`:`${(C=e.players[e.winner])==null?void 0:C.name} ${i("برنده شد 🏆","wins 🏆")}`:(e.turn===r?i("نوبت شماست","Your turn"):`${i("نوبت","Turn")}: ${(L=e.players[e.turn])==null?void 0:L.name}`)+(e.check?` · ${i("کیش!","Check!")}`:"");o.innerHTML=`
<div class="status">${v}</div>
<div class="info">${e.moves_played!==void 0?`حرکت‌ها: ${e.moves_played}`:""}</div>
<div class="board">${u}</div>
${b}
${$}
<div class="legend">${i("سفید حرکت می‌کند","White moves")}</div>
`}function M(o,r){return o?r==="b"?{k:"♚",q:"♛",r:"♜",b:"♝",n:"♞",p:"♟"}[o]??"":{k:"♔",q:"♕",r:"♖",b:"♗",n:"♘",p:"♙"}[o]??"":""}let c="",m=null;document.addEventListener("click",o=>{var n,s;const r=o.target,a=r.closest("[data-promo]");if(a&&m){k.cmd("move",{from:m.from,to:m.to,promotion:a.dataset.promo}),m=null,c="",p();return}if(r.closest("[data-cancel-promo]")){m=null,p();return}const d=r.closest("[data-from]");if(!d)return;const t=d.dataset.from;if(!m)if(c){if(c===t){c="",p();return}const l=((e==null?void 0:e.board)||[]).find(v=>v.square===t),u=(e==null?void 0:e.me)!==null&&(e==null?void 0:e.me)!==void 0?(n=e==null?void 0:e.players[e.me])==null?void 0:n.color:null;if(l!=null&&l.color&&u&&l.color===u){c=t,p();return}const b=((e==null?void 0:e.board)||[]).find(v=>v.square===c),$=u==="b"?"1":"8";if((b==null?void 0:b.type)==="p"&&t[1]===$){m={from:c,to:t},c="",p();return}k.cmd("move",{from:c,to:t}),c="",p()}else{const l=((e==null?void 0:e.board)||[]).find($=>$.square===t),u=(e==null?void 0:e.me)!==null&&(e==null?void 0:e.me)!==void 0?(s=e==null?void 0:e.players[e.me])==null?void 0:s.color:null;!!u&&(l==null?void 0:l.color)===u&&(e==null?void 0:e.phase)==="play"&&(e==null?void 0:e.turn)===(e==null?void 0:e.me)&&(c=t,p())}});p();
+2 -2
View File
@@ -4,8 +4,8 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chess — 3miz</title> <title>Chess — 3miz</title>
<script type="module" crossorigin src="./assets/index-D5ThqQkE.js"></script> <script type="module" crossorigin src="./assets/index-Cj8AUTlf.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-BquRMbQ0.css"> <link rel="stylesheet" crossorigin href="./assets/index-BJNpcCwx.css">
</head> </head>
<body><div id="app">…</div></body> <body><div id="app">…</div></body>
</html> </html>