/**
* 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";
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({
onInit(m) {
init = m;
document.documentElement.lang = m.locale;
document.documentElement.dir = m.dir;
if (!document.getElementById("board-grid")) {
setupDOM();
}
updateUI();
},
onState(env) {
if (env.t === "snap") {
if (!document.getElementById("board-grid")) {
setupDOM();
}
prevS = S;
S = env.body as GameSnapshot;
if (S.turn !== S.me) {
selectedSquare = "";
legalTargets = [];
pendingPromo = null;
}
// Pre-compute lastMove so cell highlight renders immediately in updateUI
if (prevS && S) {
const oldBoard = new Map(prevS.board.map((c) => [c.square, c]));
const newBoard = new Map(S.board.map((c) => [c.square, c]));
let f = "";
let t = "";
for (const [sq, newCell] of newBoard.entries()) {
const oldCell = oldBoard.get(sq);
if (!oldCell) continue;
if (oldCell.color && !newCell.color) f = sq;
else if (newCell.color && (!oldCell.color || oldCell.color !== newCell.color || oldCell.type !== newCell.type)) t = sq;
}
if (f && t) {
lastMove = { from: f, to: t };
}
}
updateUI();
detectMoveEvents(prevS, S);
}
},
onAck(a) {
if (a.status === "rejected") {
host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn");
}
},
});
/**
* 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;
let capturedSquare = "";
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;
capturedSquare = sq;
}
}
}
// Handle en-passant where captured pawn square is different from movedTo
if (!capturedPiece && movedFrom && movedTo) {
for (const [sq, newCell] of newBoard.entries()) {
const oldCell = oldBoard.get(sq);
if (!oldCell) continue;
if (oldCell.color && !newCell.color && sq !== movedFrom) {
capturedPiece = oldCell;
capturedSquare = sq;
break;
}
}
}
if (movedFrom && movedTo) {
lastMove = { from: movedFrom, to: movedTo };
const targetCellEl = document.querySelector(`[data-square="${movedTo}"]`) as HTMLElement | null;
const fromCellEl = document.querySelector(`[data-square="${movedFrom}"]`) as HTMLElement | null;
const boardGridEl = document.getElementById("board-grid");
const ghostLayerEl = document.getElementById("ghost-layer");
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");
setTimeout(() => {
vfx?.dissolvePuff(x, y, capturedPiece!.color as "w" | "b");
}, 440);
} else {
vfx.landingPuff(x, y);
}
}
// Add strike / land animation to arrived piece
const pieceEl = targetCellEl.querySelector(".piece-wrapper") as HTMLElement | null;
if (pieceEl) {
pieceEl.classList.remove("anim-land", "anim-strike");
void pieceEl.offsetWidth;
if (capturedPiece) {
pieceEl.classList.add("anim-strike");
targetCellEl.classList.remove("anim-shudder");
void targetCellEl.offsetWidth;
targetCellEl.classList.add("anim-shudder");
} else {
pieceEl.classList.add("anim-land");
}
}
}
// Dramatic Topple & Dissolve animation for captured piece
if (capturedPiece && boardGridEl && ghostLayerEl) {
const toppleOnSq = capturedSquare || movedTo;
const capturedCellEl = document.querySelector(`[data-square="${toppleOnSq}"]`) as HTMLElement | null;
if (capturedCellEl) {
const boardRect = boardGridEl.getBoundingClientRect();
const cellRect = capturedCellEl.getBoundingClientRect();
// Determine knock-over direction (attacker kinetic force direction)
let toppleDir: "right" | "left" = "right";
if (fromCellEl) {
const fromRect = fromCellEl.getBoundingClientRect();
if (cellRect.left < fromRect.left - 4) {
toppleDir = "left";
}
}
const ghost = document.createElement("div");
ghost.className = `captured-ghost topple-${toppleDir}`;
ghost.style.left = `${cellRect.left - boardRect.left}px`;
ghost.style.top = `${cellRect.top - boardRect.top}px`;
ghost.style.width = `${cellRect.width}px`;
ghost.style.height = `${cellRect.height}px`;
const pieceSvg = getPieceSvg(capturedPiece.type as PieceType, capturedPiece.color as PieceColor);
ghost.innerHTML = `
${pieceSvg}
`;
ghostLayerEl.appendChild(ghost);
setTimeout(() => {
ghost.remove();
}, 800);
}
}
}
// 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 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 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;
// 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;
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;
btn.dataset.square = sq;
btn.dataset.color = cell.color || "";
// 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 🏆") : (S.winner === null ? L("تساوی 🤝", "Draw 🤝") : ""))
: (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : "");
el.innerHTML = `
${player.color === "w" ? "♔" : "♚"}
${capturedPieces.map((p) => `
${getPieceSvg(p.type as PieceType, p.color as PieceColor)}
`).join("")}
${advText}
`;
}
/**
* 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;
}
/**
* 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;
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 (S.phase === "over") {
const isWinner = S.winner !== null && S.winner === S.me;
const isDraw = S.winner === null;
let title = "";
let subtitle = "";
if (isDraw) {
if (S.result_reason === "stalemate") {
title = L("پات — مساوی!", "Stalemate — Draw!");
subtitle = L("شاه راه حرکتی ندارد", "King has no legal moves");
} else if (S.result_reason === "insufficient_material") {
title = L("تساوی — عدم کفایت مهرهها", "Draw — Insufficient Material");
subtitle = L("مهره کافی برای مات کردن در صفحه وجود ندارد", "Neither side has sufficient pieces to force checkmate");
} else {
title = 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 = `
`;
return;
}
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 = "";
legalTargets = [];
updateUI();
return;
}
// Switch selection to another own piece
if (clickedCell?.color && clickedCell.color === myColor) {
selectedSquare = sq;
try {
legalTargets = getLegalMoves(sq, S.board, myColor);
} catch (err) {
legalTargets = [];
}
updateUI();
return;
}
// 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 = "";
legalTargets = [];
updateUI();
return;
}
// Send move to host
host.cmd("move", { from: selectedSquare, to: sq });
selectedSquare = "";
legalTargets = [];
updateUI();
} else {
// Select piece
if (clickedCell && clickedCell.color === myColor) {
selectedSquare = sq;
try {
legalTargets = getLegalMoves(sq, S.board, myColor);
} catch (err) {
legalTargets = [];
}
updateUI();
}
}
}