diff --git a/client-src/package.json b/client-src/package.json index 27b9a7a..5555c87 100644 --- a/client-src/package.json +++ b/client-src/package.json @@ -1,6 +1,6 @@ { "name": "chess-client", - "version": "1.6.0", + "version": "1.7.0", "private": true, "type": "module", "scripts": { diff --git a/client-src/src/main.ts b/client-src/src/main.ts index c78f129..f592017 100644 --- a/client-src/src/main.ts +++ b/client-src/src/main.ts @@ -29,12 +29,18 @@ interface GameSnapshot { players: PlayerSnapshot[]; moves_played: number; captures: number; + clocks?: [number, number]; + turn_start_ms?: number; + time_control?: string; + increment_ms?: number; } let S: GameSnapshot | null = null; let prevS: GameSnapshot | null = null; let init: InitMsg | null = null; let vfx: VfxEngine | null = null; +let clockInterval: number | null = null; +let snapReceivedAt = Date.now(); let selectedSquare = ""; let legalTargets: { target: string; isCapture: boolean }[] = []; @@ -61,6 +67,11 @@ const host = connectHost({ } prevS = S; S = env.body as GameSnapshot; + snapReceivedAt = Date.now(); + + if (!clockInterval) { + clockInterval = window.setInterval(updateClocks, 200); + } if (S.turn !== S.me) { selectedSquare = ""; @@ -368,8 +379,43 @@ function updateUI() { renderModalContainer(); } +function formatTime(ms: number): string { + const totalSeconds = Math.max(0, Math.floor(ms / 1000)); + const m = Math.floor(totalSeconds / 60); + const s = totalSeconds % 60; + return `${m}:${s < 10 ? "0" : ""}${s}`; +} + +function getRemainingTime(seat: number): number { + if (!S || !S.clocks) return 0; + const base = S.clocks[seat] ?? 0; + if (S.phase === "play" && S.turn === seat) { + const elapsed = Date.now() - snapReceivedAt; + return Math.max(0, base - elapsed); + } + return base; +} + +function updateClocks() { + if (!S || !S.clocks || S.phase !== "play") return; + for (const barId of ["top-bar", "bottom-bar"]) { + const barEl = document.getElementById(barId); + if (!barEl) continue; + const clockEl = barEl.querySelector(".chess-clock") as HTMLElement | null; + if (!clockEl || !clockEl.dataset.seat) continue; + const seat = Number(clockEl.dataset.seat); + const ms = getRemainingTime(seat); + clockEl.textContent = formatTime(ms); + if (ms <= 30000 && ms > 0) { + clockEl.classList.add("low-time"); + } else { + clockEl.classList.remove("low-time"); + } + } +} + /** - * Render player profile, active turn indicator, captured pieces, and score + * Render player profile, active turn indicator, captured pieces, clock, and score */ function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isActive: boolean, isMe: boolean) { const el = document.getElementById(barId); @@ -388,6 +434,13 @@ function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isAc ? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : (S.winner === null ? L("تساوی 🤝", "Draw 🤝") : "")) : (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : ""); + // Chess clock + const remainingMs = getRemainingTime(player.seat); + const isLowTime = remainingMs <= 30000 && remainingMs > 0 && S.phase === "play"; + const clockHtml = S.clocks + ? `
${formatTime(remainingMs)}
` + : ""; + el.innerHTML = `
@@ -398,9 +451,12 @@ function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isAc
${statusLabel}
-
- ${capturedPieces.map((p) => `
${getPieceSvg(p.type as PieceType, p.color as PieceColor)}
`).join("")} - ${advText} +
+
+ ${capturedPieces.map((p) => `
${getPieceSvg(p.type as PieceType, p.color as PieceColor)}
`).join("")} + ${advText} +
+ ${clockHtml}
`; } @@ -513,6 +569,9 @@ function renderModalContainer() { } else if (S.result_reason === "insufficient_material") { title = L("تساوی — عدم کفایت مهره‌ها", "Draw — Insufficient Material"); subtitle = L("مهره کافی برای مات کردن در صفحه وجود ندارد", "Neither side has sufficient pieces to force checkmate"); + } else if (S.result_reason === "timeout_draw") { + title = L("تساوی — پایان زمان و عدم کفایت مهره", "Draw — Timeout vs Insufficient Material"); + subtitle = L("زمان حریف تمام شد اما مهره کافی برای مات کردن ندارید", "Opponent flagged but you lack mating material"); } else { title = L("بازی مساوی شد", "Draw!"); subtitle = L("هیچ‌کدام از طرفین برنده نشد", "No side achieved victory"); @@ -520,9 +579,15 @@ function renderModalContainer() { } 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") : ""); + if (S.result_reason === "checkmate") { + subtitle = L("با کیش و مات حریف", "By checkmate"); + } else if (S.result_reason === "timeout") { + subtitle = L("با اتمام زمان حریف", "On time"); + } else if (S.result_reason === "abandoned") { + subtitle = L("به دلیل ترک حریف", "By abandonment"); + } else { + subtitle = ""; + } } container.innerHTML = ` diff --git a/client-src/src/style.css b/client-src/src/style.css index ae56e94..bcec3d3 100644 --- a/client-src/src/style.css +++ b/client-src/src/style.css @@ -158,6 +158,51 @@ html, body { margin-inline-start: 4px; } +/* ========================================================================== + Chess Clock + ========================================================================== */ + +.player-clock-section { + display: flex; + align-items: center; + gap: 8px; +} + +.chess-clock { + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace; + font-size: 14px; + font-weight: 800; + padding: 4px 10px; + border-radius: 6px; + background: rgba(15, 16, 22, 0.85); + color: #94a3b8; + border: 1px solid rgba(255, 255, 255, 0.1); + letter-spacing: 0.5px; + box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5); + transition: all 0.2s ease; + min-width: 58px; + text-align: center; +} + +.chess-clock.active { + background: rgba(30, 41, 59, 0.95); + color: #f8fafc; + border-color: rgba(245, 158, 11, 0.6); + box-shadow: 0 0 10px rgba(245, 158, 11, 0.25), inset 0 1px 2px rgba(0, 0, 0, 0.3); +} + +.chess-clock.low-time { + background: rgba(127, 29, 29, 0.85); + color: #fca5a5; + border-color: rgba(239, 68, 68, 0.8); + animation: clock-pulse 1s infinite alternate; +} + +@keyframes clock-pulse { + 0% { transform: scale(1); box-shadow: 0 0 4px rgba(239, 68, 68, 0.4); } + 100% { transform: scale(1.04); box-shadow: 0 0 12px rgba(239, 68, 68, 0.8); } +} + /* ========================================================================== Chess Board & Cells ========================================================================== */ diff --git a/client/assets/index-C6_IS3s7.css b/client/assets/index-C6_IS3s7.css new file mode 100644 index 0000000..8cf14cb --- /dev/null +++ b/client/assets/index-C6_IS3s7.css @@ -0,0 +1 @@ +: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,#101117);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-bar{width:min(88vmin,540px);display:flex;align-items:center;justify-content:space-between;padding:6px 12px;background:#1e2029d9;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);border-radius:8px;border:1px solid rgba(255,255,255,.08);box-shadow:0 4px 12px #0000004d;transition:border-color .25s ease,box-shadow .25s ease}.player-bar.active{border-color:var(--gold-accent);box-shadow:0 0 14px #f59e0b59}.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 #0003}.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:.5px}.bot-tag.you-tag{background:#1e3a8a;color:#60a5fa;border:1px solid rgba(96,165,250,.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:21px;height:21px;opacity:.95;filter:drop-shadow(0 2px 3px rgba(0,0,0,.45));display:flex;align-items:center;justify-content:center}.advantage-score{font-size:11px;font-weight:800;color:var(--gold-accent);margin-inline-start:4px}.player-clock-section{display:flex;align-items:center;gap:8px}.chess-clock{font-family:ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace;font-size:14px;font-weight:800;padding:4px 10px;border-radius:6px;background:#0f1016d9;color:#94a3b8;border:1px solid rgba(255,255,255,.1);letter-spacing:.5px;box-shadow:inset 0 1px 3px #00000080;transition:all .2s ease;min-width:58px;text-align:center}.chess-clock.active{background:#1e293bf2;color:#f8fafc;border-color:#f59e0b99;box-shadow:0 0 10px #f59e0b40,inset 0 1px 2px #0000004d}.chess-clock.low-time{background:#7f1d1dd9;color:#fca5a5;border-color:#ef4444cc;animation:clock-pulse 1s infinite alternate}@keyframes clock-pulse{0%{transform:scale(1);box-shadow:0 0 4px #ef444466}to{transform:scale(1.04);box-shadow:0 0 12px #ef4444cc}}.board-container{position:relative;width:min(88vmin,540px);aspect-ratio:1;border-radius:8px;box-shadow:0 12px 32px #0009,0 2px 6px #0006;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 .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:#f59e0b6b!important}.cell.in-check{background:radial-gradient(circle at center,rgba(239,68,68,.95) 0%,rgba(220,38,38,.4) 60%,transparent 75%)!important;animation:king-check-pulse 1.2s ease-in-out infinite}@keyframes king-check-pulse{0%,to{filter:drop-shadow(0 0 4px rgba(239,68,68,.8))}50%{filter:drop-shadow(0 0 14px rgba(239,68,68,1))}}.coord-rank,.coord-file{position:absolute;font-size:10px;font-weight:800;pointer-events:none;opacity:.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)}.piece-wrapper{width:92%;height:92%;display:flex;align-items:center;justify-content:center;pointer-events:none;transition:transform .22s cubic-bezier(.34,1.56,.64,1),filter .22s ease}.piece-svg{width:100%;height:100%;display:block;filter:drop-shadow(0 3px 5px rgba(0,0,0,.38));transition:filter .25s ease}.piece-svg.piece-w{filter:drop-shadow(0 4px 6px rgba(0,0,0,.35)) drop-shadow(0 1px 2px rgba(254,240,138,.2))}.piece-svg.piece-b{filter:drop-shadow(0 4px 6px rgba(0,0,0,.52)) drop-shadow(0 1px 2px rgba(129,140,248,.25))}.cell:not(:disabled):hover .piece-wrapper{transform:translateY(-4px) scale(1.09)}.cell:not(:disabled):hover .piece-svg.piece-w{filter:drop-shadow(0 8px 12px rgba(0,0,0,.45)) drop-shadow(0 0 10px rgba(245,158,11,.65))}.cell:not(:disabled):hover .piece-svg.piece-b{filter:drop-shadow(0 8px 12px rgba(0,0,0,.6)) drop-shadow(0 0 10px rgba(168,85,247,.7))}.cell.selected .piece-wrapper{transform:translateY(-6px) scale(1.15);animation:piece-hover-breath 1.8s ease-in-out infinite alternate}.cell.selected .piece-svg.piece-w{filter:drop-shadow(0 10px 18px rgba(0,0,0,.5)) drop-shadow(0 0 16px rgba(251,191,36,.9))}.cell.selected .piece-svg.piece-b{filter:drop-shadow(0 10px 18px rgba(0,0,0,.7)) drop-shadow(0 0 16px rgba(192,132,252,.9))}@keyframes piece-hover-breath{0%{transform:translateY(-5px) scale(1.14)}to{transform:translateY(-8px) scale(1.18)}}.piece-wrapper.anim-land{animation:piece-land-squash .22s ease-out}@keyframes piece-land-squash{0%{transform:scale(1.12,.88)}50%{transform:scale(.96,1.04)}to{transform:scale(1)}}.piece-wrapper.anim-knight{animation:knight-arc-leap .28s cubic-bezier(.25,.46,.45,.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,.92)}to{transform:translateY(0) scale(1)}}.piece-wrapper.anim-strike{animation:piece-strike-lunge .38s cubic-bezier(.34,1.56,.64,1);z-index:10}@keyframes piece-strike-lunge{0%{transform:scale(.88) translateY(-6px);filter:brightness(1.25)}30%{transform:scale(1.22) translateY(2px);filter:brightness(1.35) drop-shadow(0 8px 16px rgba(0,0,0,.6))}60%{transform:scale(.94,1.06) translateY(-2px)}80%{transform:scale(1.03,.97) translateY(0)}to{transform:scale(1) translateY(0);filter:none}}.cell.anim-shudder{animation:cell-shudder .22s ease-out}@keyframes cell-shudder{0%{transform:translate(0)}25%{transform:translate(2px,1px)}50%{transform:translate(-2px,-1px)}75%{transform:translate(1px,-1px)}to{transform:translate(0)}}.ghost-layer{position:absolute;top:4px;right:4px;bottom:4px;left:4px;pointer-events:none;z-index:15;overflow:visible}.captured-ghost{position:absolute;pointer-events:none;display:flex;align-items:center;justify-content:center;z-index:20}.captured-ghost .piece-wrapper{width:92%;height:92%}.captured-ghost.topple-right{transform-origin:45% 90%;animation:piece-topple-right .78s cubic-bezier(.25,.46,.45,.94) forwards}.captured-ghost.topple-left{transform-origin:55% 90%;animation:piece-topple-left .78s cubic-bezier(.25,.46,.45,.94) forwards}@keyframes piece-topple-right{0%{transform:translate(0) rotate(0) scale(1);opacity:1;filter:drop-shadow(0 4px 6px rgba(0,0,0,.45))}14%{transform:translate(6px,-12px) rotate(22deg) scale(1.05);opacity:1;filter:drop-shadow(0 10px 14px rgba(0,0,0,.4)) brightness(1.2)}38%{transform:translate(16px,-2px) rotate(60deg) scale(1);opacity:.96}58%{transform:translate(24px,12px) rotate(92deg) scale(.96,.9);opacity:.92;filter:drop-shadow(0 2px 4px rgba(0,0,0,.6))}70%{transform:translate(26px,8px) rotate(84deg) scale(.97,.94);opacity:.88}80%{transform:translate(27px,12px) rotate(90deg) scale(.95);opacity:.8;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4))}to{transform:translate(30px,16px) rotate(90deg) scale(.68) scaleY(.4);opacity:0;filter:blur(5px) brightness(1.8) drop-shadow(0 0 12px rgba(255,255,255,.9))}}@keyframes piece-topple-left{0%{transform:translate(0) rotate(0) scale(1);opacity:1;filter:drop-shadow(0 4px 6px rgba(0,0,0,.45))}14%{transform:translate(-6px,-12px) rotate(-22deg) scale(1.05);opacity:1;filter:drop-shadow(0 10px 14px rgba(0,0,0,.4)) brightness(1.2)}38%{transform:translate(-16px,-2px) rotate(-60deg) scale(1);opacity:.96}58%{transform:translate(-24px,12px) rotate(-92deg) scale(.96,.9);opacity:.92;filter:drop-shadow(0 2px 4px rgba(0,0,0,.6))}70%{transform:translate(-26px,8px) rotate(-84deg) scale(.97,.94);opacity:.88}80%{transform:translate(-27px,12px) rotate(-90deg) scale(.95);opacity:.8;filter:drop-shadow(0 2px 4px rgba(0,0,0,.4))}to{transform:translate(-30px,16px) rotate(-90deg) scale(.68) scaleY(.4);opacity:0;filter:blur(5px) brightness(1.8) drop-shadow(0 0 12px rgba(255,255,255,.9))}}.move-dot{position:absolute;width:32%;height:32%;border-radius:50%;background:#0000003d;pointer-events:none;animation:dot-spawn .18s cubic-bezier(.34,1.56,.64,1);transition:transform .15s ease,background-color .15s ease}.cell:hover .move-dot{transform:scale(1.3);background:#0000005c}@keyframes dot-spawn{0%{transform:scale(0);opacity:0}to{transform:scale(1);opacity:1}}.capture-ring{position:absolute;top:0;right:0;bottom:0;left:0;border:4px solid rgba(239,68,68,.72);border-radius:50%;pointer-events:none;animation:ring-spawn .2s cubic-bezier(.34,1.56,.64,1)}@keyframes ring-spawn{0%{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}#vfx-canvas{position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:10}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;background:#000000a6;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;z-index:50;animation:fade-in .2s ease}.promo-card{background:var(--bg-card);border:1px solid rgba(255,255,255,.12);border-radius:12px;padding:16px 20px;display:flex;flex-direction:column;align-items:center;gap:14px;box-shadow:0 16px 36px #000000b3;animation:modal-spring .26s cubic-bezier(.34,1.56,.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,.1);border-radius:10px;cursor:pointer;padding:6px;display:flex;align-items:center;justify-content:center;transition:transform .18s cubic-bezier(.34,1.56,.64,1),background-color .15s ease,box-shadow .18s ease}.promo-piece-btn:hover{transform:translateY(-4px) scale(1.12);background:#373a4a;box-shadow:0 8px 18px #0006}.promo-cancel-btn{background:transparent;border:0;color:var(--text-muted);font-size:13px;font-weight:600;cursor:pointer;padding:4px 12px;transition:color .15s ease}.promo-cancel-btn:hover{color:var(--text-main)}@keyframes modal-spring{0%{transform:scale(.6);opacity:0}to{transform:scale(1);opacity:1}}@keyframes fade-in{0%{opacity:0}to{opacity:1}}.game-over-banner{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:#181922f0;-webkit-backdrop-filter:blur(8px);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 #000c,0 0 24px #f59e0b66;z-index:40;animation:banner-spring .35s cubic-bezier(.34,1.56,.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(.4);opacity:0}to{transform:translate(-50%,-50%) scale(1);opacity:1}} diff --git a/client/assets/index-CHF7ocq9.js b/client/assets/index-CHF7ocq9.js new file mode 100644 index 0000000..3143a25 --- /dev/null +++ b/client/assets/index-CHF7ocq9.js @@ -0,0 +1,209 @@ +(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))t(s);new MutationObserver(s=>{for(const e of s)if(e.type==="childList")for(const c of e.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&t(c)}).observe(document,{childList:!0,subtree:!0});function r(s){const e={};return s.integrity&&(e.integrity=s.integrity),s.referrerPolicy&&(e.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?e.credentials="include":s.crossOrigin==="anonymous"?e.credentials="omit":e.credentials="same-origin",e}function t(s){if(s.ep)return;s.ep=!0;const e=r(s);fetch(s.href,e)}})();function ct(o){const a=new URLSearchParams(location.search).get("host")??"*",r=s=>window.parent.postMessage({m3:1,...s},a);let t=0;return window.addEventListener("message",s=>{var c,i,y;if(s.source!==window.parent||a!=="*"&&s.origin!==a)return;const e=s.data;if(!(!e||e.m3!==1))switch(e.type){case"init":o.onInit(e),r({type:"ready"});break;case"state":o.onState(e.env);break;case"ack":(c=o.onAck)==null||c.call(o,e);break;case"view_changed":(i=o.onViewChanged)==null||i.call(o,e.view);break;case"cmd_failed":(y=o.onCmdFailed)==null||y.call(o,e.req_id,e.code);break}}),r({type:"loaded"}),{cmd(s,e={}){const c=++t;return r({type:"cmd",cmd_type:s,payload:e,req_id:c}),c},toast(s,e,c="info"){r({type:"toast",text_fa:s,text_en:e,kind:c})}}}const S=` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`,G=` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`;function nt(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)";return` + ${a} + + + + + + + + + + + + + `}function lt(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)",c=o?"url(#cp-ruby)":"url(#cp-sapphire)";return` + ${a} + + + + + + + + + + + + + + + + `}function it(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)";return` + ${a} + + + + + + + + + + + + + + `}function dt(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)";return` + ${a} + + + + + + + + + + + + + + + + + `}function ft(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)",c=o?"url(#cp-ruby)":"url(#cp-sapphire)",i=o?"url(#cp-pearl)":"url(#cp-amethyst)";return` + ${a} + + + + + + + + + + + + + + + + + + `}function pt(o){const a=o?S:G,r=o?"#0f172a":"#020617",t=o?"url(#cp-w-body)":"url(#cp-b-body)",s=o?"url(#cp-w-spec)":"url(#cp-b-spec)",e=o?"url(#cp-w-gold)":"url(#cp-b-gold)";return` + ${a} + + + + + + + + + + + + + + + `}const ut={p:nt,n:lt,b:it,r:dt,q:ft,k:pt},D={};function _(o,a){if(!o||!a)return"";const r=`${o}-${a}`;if(!D[r]){const t=ut[o];t&&(D[r]=t(a==="w"))}return D[r]??""}class ht{constructor(a){this.particles=[],this.shockwaves=[],this.animId=null,this.lastTime=0,this.canvas=a,this.ctx=a.getContext("2d"),this.resize(),window.addEventListener("resize",()=>this.resize()),this.startLoop()}resize(){var t,s,e;const a=(t=this.canvas.parentElement)==null?void 0:t.getBoundingClientRect();if(!a)return;const r=window.devicePixelRatio||1;this.canvas.width=Math.round(a.width*r),this.canvas.height=Math.round(a.height*r),this.canvas.style.width=`${a.width}px`,this.canvas.style.height=`${a.height}px`,(e=(s=this.ctx).resetTransform)==null||e.call(s),this.ctx.scale(r,r)}startLoop(){if(this.animId)return;const a=r=>{const t=this.lastTime?Math.min((r-this.lastTime)/1e3,.1):.016;this.lastTime=r,this.update(t),this.render(),this.animId=requestAnimationFrame(a)};this.animId=requestAnimationFrame(a)}update(a){for(let r=this.shockwaves.length-1;r>=0;r--){const t=this.shockwaves[r];t.radius+=(t.maxRadius-t.radius)*12*a,t.alpha-=t.decay*a,(t.alpha<=0||t.radius>=t.maxRadius*.98)&&this.shockwaves.splice(r,1)}for(let r=this.particles.length-1;r>=0;r--){const t=this.particles[r];t.x+=t.vx*a,t.y+=t.vy*a,t.vx*=Math.pow(t.drag,a*60),t.vy*=Math.pow(t.drag,a*60),t.vy+=t.gravity*a,t.vRot&&t.rotation!==void 0&&(t.rotation+=t.vRot*a),t.alpha-=t.decay*a,t.alpha<=0&&this.particles.splice(r,1)}}render(){const a=this.canvas.width/(window.devicePixelRatio||1),r=this.canvas.height/(window.devicePixelRatio||1);this.ctx.clearRect(0,0,a,r);for(const t of this.shockwaves)this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(t.x,t.y,Math.max(1,t.radius),0,Math.PI*2),this.ctx.strokeStyle=t.color,this.ctx.globalAlpha=Math.max(0,t.alpha),this.ctx.lineWidth=t.lineWidth,this.ctx.stroke(),this.ctx.restore();for(const t of this.particles){if(this.ctx.save(),this.ctx.globalAlpha=Math.max(0,t.alpha),this.ctx.fillStyle=t.color,t.shape==="rect"||t.shape==="spark"){this.ctx.translate(t.x,t.y),t.rotation!==void 0&&this.ctx.rotate(t.rotation);const s=t.size||t.radius*2;t.shape==="spark"?this.ctx.fillRect(-s,-s*.25,s*2,s*.5):this.ctx.fillRect(-s*.5,-s*.5,s,s)}else this.ctx.beginPath(),this.ctx.arc(t.x,t.y,Math.max(.5,t.radius),0,Math.PI*2),this.ctx.fill();this.ctx.restore()}}captureImpact(a,r,t="w"){this.shockwaves.push({x:a,y:r,radius:4,maxRadius:48,color:t==="w"?"rgba(255, 235, 180, 0.9)":"rgba(120, 140, 180, 0.9)",alpha:.9,decay:2.8,lineWidth:3});const s=t==="w"?["#ffffff","#fef08a","#f59e0b","#fbbf24"]:["#94a3b8","#cbd5e1","#64748b","#38bdf8"],e=18;for(let c=0;c{if(l<0||l>7||g<0||g>7)return!1;const u=b(l,g),d=t.get(u);return!d||!d.color?(i.push({target:u,isCapture:!1}),!0):(d.color!==r&&i.push({target:u,isCapture:!0}),!1)};switch(s.type){case"p":{const l=r==="w"?1:-1,g=r==="w"?1:6,u=b(e,c+l),d=t.get(u);if(d&&!d.color&&(i.push({target:u,isCapture:!1}),c===g)){const f=b(e,c+l*2),p=t.get(f);p&&!p.color&&i.push({target:f,isCapture:!1})}for(const f of[-1,1])if(e+f>=0&&e+f<=7){const p=b(e+f,c+l),h=t.get(p);h&&h.color&&h.color!==r&&i.push({target:p,isCapture:!0})}break}case"n":{const l=[[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];for(const[g,u]of l){const d=e+g,f=c+u;if(d>=0&&d<=7&&f>=0&&f<=7){const p=b(d,f),h=t.get(p);!h||!h.color?i.push({target:p,isCapture:!1}):h.color!==r&&i.push({target:p,isCapture:!0})}}break}case"b":{const l=[[-1,-1],[-1,1],[1,-1],[1,1]];for(const[g,u]of l){let d=e+g,f=c+u;for(;y(d,f);)d+=g,f+=u}break}case"r":{const l=[[-1,0],[1,0],[0,-1],[0,1]];for(const[g,u]of l){let d=e+g,f=c+u;for(;y(d,f);)d+=g,f+=u}break}case"q":{const l=[[-1,-1],[-1,1],[1,-1],[1,1],[-1,0],[1,0],[0,-1],[0,1]];for(const[g,u]of l){let d=e+g,f=c+u;for(;y(d,f);)d+=g,f+=u}break}case"k":{for(let g=-1;g<=1;g++)for(let u=-1;u<=1;u++){if(g===0&&u===0)continue;const d=e+g,f=c+u;if(d>=0&&d<=7&&f>=0&&f<=7){const p=b(d,f),h=t.get(p);!h||!h.color?i.push({target:p,isCapture:!1}):h.color!==r&&i.push({target:p,isCapture:!0})}}const l=r==="w"?0:7;if(c===l&&e===4){const g=t.get(b(5,l)),u=t.get(b(6,l)),d=t.get(b(7,l));g&&!g.color&&u&&!u.color&&(d==null?void 0:d.type)==="r"&&d.color===r&&i.push({target:b(6,l),isCapture:!1});const f=t.get(b(3,l)),p=t.get(b(2,l)),h=t.get(b(1,l)),m=t.get(b(0,l));f&&!f.color&&p&&!p.color&&h&&!h.color&&(m==null?void 0:m.type)==="r"&&m.color===r&&i.push({target:b(2,l),isCapture:!1})}break}}return i.filter(l=>!gt(o,l.target,a,r))}function gt(o,a,r,t){const s=r.map(d=>{if(d.square===o)return{square:o,type:null,color:null};if(d.square===a){const f=r.find(p=>p.square===o);return{square:a,type:(f==null?void 0:f.type)??null,color:t}}return{...d}}),e=s.find(d=>d.type==="k"&&d.color===t);if(!e)return!1;const{f:c,r:i}=K(e.square),y=t==="w"?"b":"w",l=new Map;for(const d of s)l.set(d.square,d);const g=[[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];for(const[d,f]of g){const p=c+d,h=i+f;if(p>=0&&p<=7&&h>=0&&h<=7){const m=l.get(b(p,h));if(m&&m.color===y&&m.type==="n")return!0}}const u=y==="w"?1:-1;for(const d of[-1,1]){const f=c-d,p=i-u;if(f>=0&&f<=7&&p>=0&&p<=7){const h=l.get(b(f,p));if(h&&h.color===y&&h.type==="p")return!0}}for(const[d,f]of[[-1,0],[1,0],[0,-1],[0,1]]){let p=c+d,h=i+f;for(;p>=0&&p<=7&&h>=0&&h<=7;){const m=l.get(b(p,h));if(m&&m.color){if(m.color===y&&(m.type==="r"||m.type==="q"))return!0;break}p+=d,h+=f}}for(const[d,f]of[[-1,-1],[-1,1],[1,-1],[1,1]]){let p=c+d,h=i+f;for(;p>=0&&p<=7&&h>=0&&h<=7;){const m=l.get(b(p,h));if(m&&m.color){if(m.color===y&&(m.type==="b"||m.type==="q"))return!0;break}p+=d,h+=f}}for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){if(d===0&&f===0)continue;const p=c+d,h=i+f;if(p>=0&&p<=7&&h>=0&&h<=7){const m=l.get(b(p,h));if(m&&m.color===y&&m.type==="k")return!0}}return!1}let n=null,Z=null,T=null,$=null,H=null,U=Date.now(),C="",x=[],L=null,R=null,F=!1;const w=(o,a)=>(T==null?void 0:T.locale)==="en"?a:o,O=ct({onInit(o){T=o,document.documentElement.lang=o.locale,document.documentElement.dir=o.dir,document.getElementById("board-grid")||j(),I()},onState(o){if(o.t==="snap"){if(document.getElementById("board-grid")||j(),Z=n,n=o.body,U=Date.now(),H||(H=window.setInterval(yt,200)),n.turn!==n.me&&(C="",x=[],L=null),Z&&n){const a=new Map(Z.board.map(e=>[e.square,e])),r=new Map(n.board.map(e=>[e.square,e]));let t="",s="";for(const[e,c]of r.entries()){const i=a.get(e);i&&(i.color&&!c.color?t=e:c.color&&(!i.color||i.color!==c.color||i.type!==c.type)&&(s=e))}t&&s&&(R={from:t,to:s})}I(),mt(Z,n)}},onAck(o){o.status==="rejected"&&O.toast("حرکت پذیرفته نشد","Move not accepted","warn")}});function mt(o,a){var y;if(!o||!a||!$)return;const r=new Map(o.board.map(l=>[l.square,l])),t=new Map(a.board.map(l=>[l.square,l]));let s="",e="",c=null,i="";for(const[l,g]of t.entries()){const u=r.get(l);u&&(u.color&&!g.color?s=l:g.color&&(!u.color||u.color!==g.color||u.type!==g.type)&&(e=l,u.color&&u.color!==g.color&&(c=u,i=l)))}if(!c&&s&&e)for(const[l,g]of t.entries()){const u=r.get(l);if(u&&u.color&&!g.color&&l!==s){c=u,i=l;break}}if(s&&e){R={from:s,to:e};const l=document.querySelector(`[data-square="${e}"]`),g=document.querySelector(`[data-square="${s}"]`),u=document.getElementById("board-grid"),d=document.getElementById("ghost-layer");if(l){const f=l.getBoundingClientRect(),p=(y=document.getElementById("vfx-canvas"))==null?void 0:y.getBoundingClientRect();if(p){const m=f.left-p.left+f.width/2,v=f.top-p.top+f.height/2;c?($.captureImpact(m,v,c.color),setTimeout(()=>{$==null||$.dissolvePuff(m,v,c.color)},440)):$.landingPuff(m,v)}const h=l.querySelector(".piece-wrapper");h&&(h.classList.remove("anim-land","anim-strike"),h.offsetWidth,c?(h.classList.add("anim-strike"),l.classList.remove("anim-shudder"),l.offsetWidth,l.classList.add("anim-shudder")):h.classList.add("anim-land"))}if(c&&u&&d){const f=i||e,p=document.querySelector(`[data-square="${f}"]`);if(p){const h=u.getBoundingClientRect(),m=p.getBoundingClientRect();let v="right";if(g){const q=g.getBoundingClientRect();m.left${k}
`,d.appendChild(M),setTimeout(()=>{M.remove()},800)}}}a.phase==="over"&&a.winner!==null&&!F&&(F=!0,setTimeout(()=>$==null?void 0:$.victoryConfetti(),350))}function j(){const o=document.getElementById("app");o.innerHTML=` +
+
+ +
+
+
+
+ + `;const a=document.getElementById("vfx-canvas");$=new ht(a);const r=document.getElementById("board-grid");r.addEventListener("click",t=>{const s=t.target.closest(".cell");s&&s.dataset.square&&!s.disabled&&Mt(s.dataset.square)});for(let t=0;t<64;t++){const s=document.createElement("button");s.className="cell",s.dataset.index=String(t),r.appendChild(s)}}function I(){var m;if(!n)return;const o=n.me,a=o!=null&&n.players[o]!==void 0;let r,t;a?(r=n.players[o],t=n.players.find(v=>v.seat!==o)||n.players[1-o]):(r=n.players.find(v=>v.color==="w")||n.players[0],t=n.players.find(v=>v.color==="b")||n.players[1]);const s=(r==null?void 0:r.color)||"w",e=s==="b",c=r?n.turn===r.seat&&n.phase==="play":!1,i=t?n.turn===t.seat&&n.phase==="play":!1;z("top-bar",t,i,!1),z("bottom-bar",r,c,a);const y=new Map;for(const v of n.board)y.set(v.square,v);const l=e?[7,6,5,4,3,2,1,0]:[0,1,2,3,4,5,6,7],g=e?[0,1,2,3,4,5,6,7]:[7,6,5,4,3,2,1,0],u=document.getElementById("board-grid");if(!u)return;const d=u.children;let f=0;const p=n.phase==="play"&&n.turn===o,h=n.check&&n.phase==="play"?(m=n.board.find(v=>{var M;return v.type==="k"&&v.color===((M=n.players[n.turn])==null?void 0:M.color)}))==null?void 0:m.square:null;for(const v of g)for(const M of l){const k=String.fromCharCode(97+M)+(v+1),q=y.get(k)||{type:null,color:null},P=d[f++];P.dataset.square=k,P.dataset.color=q.color||"";const Q=(M+v)%2===0?"dark":"light",N=C===k,J=R&&(R.from===k||R.to===k),X=h===k;P.className=`cell ${Q}`+(N?" selected":"")+(J?" last-move":"")+(X?" in-check":"");const W=x.some(B=>B.target===k),tt=x.some(B=>B.target===k&&B.isCapture);let E="";const et=e?M===7:M===0,ot=e?v===7:v===0;if(et&&(E+=`${v+1}`),ot&&(E+=`${String.fromCharCode(97+M)}`),q.type&&q.color){const B=_(q.type,q.color),at=q.type==="n"&&N?" anim-knight":"";E+=`
${B}
`}tt?E+='
':W&&(E+='
'),P.innerHTML=E;const rt=p&&!0&&q.color===s,st=C?p:rt;P.disabled=!st}wt()}function V(o){const a=Math.max(0,Math.floor(o/1e3)),r=Math.floor(a/60),t=a%60;return`${r}:${t<10?"0":""}${t}`}function Y(o){if(!n||!n.clocks)return 0;const a=n.clocks[o]??0;if(n.phase==="play"&&n.turn===o){const r=Date.now()-U;return Math.max(0,a-r)}return a}function yt(){if(!(!n||!n.clocks||n.phase!=="play"))for(const o of["top-bar","bottom-bar"]){const a=document.getElementById(o);if(!a)continue;const r=a.querySelector(".chess-clock");if(!r||!r.dataset.seat)continue;const t=Number(r.dataset.seat),s=Y(t);r.textContent=V(s),s<=3e4&&s>0?r.classList.add("low-time"):r.classList.remove("low-time")}}function z(o,a,r,t){const s=document.getElementById(o);if(!s||!a||!n)return;s.className="player-bar"+(r?" active":"");const e=vt(a.color),c=bt(a.color),i=c>0?`+${c}`:"",y=a.bot?'BOT':"",l=t?`${w("شما","YOU")}`:"",g=n.phase==="over"?n.winner===a.seat?w("برنده 🏆","Winner 🏆"):n.winner===null?w("تساوی 🤝","Draw 🤝"):"":r?t?w("نوبت شماست","Your turn"):w("در حال تفکر…","Thinking…"):"",u=Y(a.seat),d=u<=3e4&&u>0&&n.phase==="play",f=n.clocks?`
${V(u)}
`:"";s.innerHTML=` +
+
+ ${a.color==="w"?"♔":"♚"} +
+
+
${a.name} ${y} ${l}
+
${g}
+
+
+
+
+ ${e.map(p=>`
${_(p.type,p.color)}
`).join("")} + ${i} +
+ ${f} +
+ `}function vt(o){if(!n)return[];const a=o==="w"?"b":"w",r={p:8,n:2,b:2,r:2,q:1},t={p:0,n:0,b:0,r:0,q:0};for(const e of n.board)e.color===a&&e.type&&t[e.type]!==void 0&&t[e.type]++;const s=[];for(const e of["q","r","b","n","p"]){const c=r[e]-(t[e]||0);for(let i=0;i +
+
${w("ارتقای پیاده به:","Promote pawn to:")}
+
+ ${["q","r","b","n"].map(e=>` + + `).join("")} +
+ +
+ + `,o.querySelectorAll("[data-promo]").forEach(e=>{e.addEventListener("click",()=>{var i;const c=e.dataset.promo;if(L&&c){O.cmd("move",{from:L.from,to:L.to,promotion:c});const y=document.querySelector(`[data-square="${L.to}"]`);if(y){const l=y.getBoundingClientRect(),g=(i=document.getElementById("vfx-canvas"))==null?void 0:i.getBoundingClientRect();g&&($==null||$.promotionBurst(l.left-g.left+l.width/2,l.top-g.top+l.height/2))}L=null,C="",x=[],I()}})}),(r=o.querySelector("[data-cancel-promo]"))==null||r.addEventListener("click",()=>{L=null,I()});return}if(n.phase==="over"){n.winner!==null&&(n.winner,n.me);const s=n.winner===null;let e="",c="";s?n.result_reason==="stalemate"?(e=w("پات — مساوی!","Stalemate — Draw!"),c=w("شاه راه حرکتی ندارد","King has no legal moves")):n.result_reason==="insufficient_material"?(e=w("تساوی — عدم کفایت مهره‌ها","Draw — Insufficient Material"),c=w("مهره کافی برای مات کردن در صفحه وجود ندارد","Neither side has sufficient pieces to force checkmate")):n.result_reason==="timeout_draw"?(e=w("تساوی — پایان زمان و عدم کفایت مهره","Draw — Timeout vs Insufficient Material"),c=w("زمان حریف تمام شد اما مهره کافی برای مات کردن ندارید","Opponent flagged but you lack mating material")):(e=w("بازی مساوی شد","Draw!"),c=w("هیچ‌کدام از طرفین برنده نشد","No side achieved victory")):(e=`${(t=n.players[n.winner])==null?void 0:t.name} ${w("برنده شد! 🏆","Wins! 🏆")}`,n.result_reason==="checkmate"?c=w("با کیش و مات حریف","By checkmate"):n.result_reason==="timeout"?c=w("با اتمام زمان حریف","On time"):n.result_reason==="abandoned"?c=w("به دلیل ترک حریف","By abandonment"):c=""),o.innerHTML=` +
+
${e}
+
${c}
+
+ `;return}o.innerHTML=""}}function Mt(o){var s;if(!n||n.phase!=="play"||L)return;const a=n.me;if(a==null||n.turn!==a)return;const r=(s=n.players[a])==null?void 0:s.color;if(!r)return;const t=n.board.find(e=>e.square===o);if(C){if(C===o){C="",x=[],I();return}if(t!=null&&t.color&&t.color===r){C=o;try{x=A(o,n.board,r)}catch{x=[]}I();return}const e=n.board.find(i=>i.square===C),c=r==="b"?"1":"8";if((e==null?void 0:e.type)==="p"&&o[1]===c){L={from:C,to:o},C="",x=[],I();return}O.cmd("move",{from:C,to:o}),C="",x=[],I()}else if(t&&t.color===r){C=o;try{x=A(o,n.board,r)}catch{x=[]}I()}} diff --git a/client/index.html b/client/index.html index 681820a..6067f11 100644 --- a/client/index.html +++ b/client/index.html @@ -4,8 +4,8 @@ Chess — 3miz - - + +
…
diff --git a/game.json b/game.json index c167c7a..5874f4f 100644 --- a/game.json +++ b/game.json @@ -2,7 +2,7 @@ "bundle_format": 1, "kind": "source", "game_id": "chess", - "version": "1.6.0", + "version": "1.7.0", "server": { "entry": "server/main.ts" }, "client": { "entry": "index.html" }, "catalog": { diff --git a/manifest.json b/manifest.json index 291d9a9..47ba341 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 1, "game_id": "chess", - "version": "1.6.0", + "version": "1.7.0", "protocol": "socketio", "protocol_version": 1, "title": { @@ -41,6 +41,27 @@ "en": "Classic" }, "default": true + }, + { + "id": "blitz", + "title": { + "fa": "بلیتس (Blitz)", + "en": "Blitz" + } + }, + { + "id": "bullet", + "title": { + "fa": "بولت (Bullet)", + "en": "Bullet" + } + }, + { + "id": "rapid", + "title": { + "fa": "رپید (Rapid)", + "en": "Rapid" + } } ], "options": [ @@ -56,6 +77,60 @@ "en": "Turn time" }, "rated_safe": true + }, + { + "id": "time_control", + "type": "enum", + "title": { + "fa": "کنترل زمان", + "en": "Time Control" + }, + "values": [ + { + "id": "1m", + "title": { + "fa": "۱ دقیقه (Bullet)", + "en": "1 min (Bullet)" + } + }, + { + "id": "1m_1s", + "title": { + "fa": "۱ دقیقه + ۱ ثانیه پاداش (Bullet)", + "en": "1 min + 1s (Bullet)" + } + }, + { + "id": "3m", + "title": { + "fa": "۳ دقیقه (Blitz)", + "en": "3 min (Blitz)" + } + }, + { + "id": "3m_2s", + "title": { + "fa": "۳ دقیقه + ۲ ثانیه پاداش (Blitz)", + "en": "3 min + 2s (Blitz)" + } + }, + { + "id": "10m", + "title": { + "fa": "۱۰ دقیقه (Rapid)", + "en": "10 min (Rapid)" + } + }, + { + "id": "15m_10s", + "title": { + "fa": "۱۵ دقیقه + ۱۰ ثانیه پاداش (Rapid)", + "en": "15 min + 10s (Rapid)" + } + } + ], + "default": "3m", + "rated_safe": true } ], "cosmetic_slots": [], @@ -81,14 +156,14 @@ ], "achievements": [], "client": { - "entry": "https://g.3miz.ir/chess/1.6.0/index.html", + "entry": "https://g.3miz.ir/chess/1.7.0/index.html", "integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "aspect": "1:1", "min_width_px": 320, "supports_portrait": true }, "server": { - "image": "registry.3miz.ir/games/chess:1.6.0", + "image": "registry.3miz.ir/games/chess:1.7.0", "max_tables_per_instance": 500, "checkpoint_every_inputs": 20, "snapshot_every_messages": 50, diff --git a/server/game.ts b/server/game.ts index 58f4e89..8d265cc 100644 --- a/server/game.ts +++ b/server/game.ts @@ -22,7 +22,11 @@ export interface State { phase: "play" | "over"; winner: number | null; // winning seat, or null for draw result_reason: string; - turn_ms: number; + time_control: string; + initial_time_ms: number; + increment_ms: number; + clocks: [number, number]; // remaining time in ms for seat 0 and seat 1 + turn_start_ms: number; // timestamp when current turn started timer_n: number; timer_id: string | null; deadline: number | null; @@ -353,7 +357,9 @@ function setDeadline(s: State, t: { now: number; setTimer(id: string, due: numbe if (s.timer_id) t.clearTimer?.(s.timer_id); s.timer_n += 1; s.timer_id = `turn-${s.timer_n}`; - s.deadline = t.now + s.turn_ms; + const remaining = s.clocks[s.turn]; + s.turn_start_ms = t.now; + s.deadline = t.now + remaining; t.setTimer(s.timer_id, s.deadline); } @@ -437,7 +443,7 @@ function finish(s: State, ctx: Ctx, winner: number | null, reason: string = "com if (s.bot_timer) ctx.clearTimer(s.bot_timer); s.bot_timer = null; ctx.finish({ - reason: reason === "abandoned" ? "abandoned" : "completed", + reason: reason === "abandoned" ? "abandoned" : (reason === "timeout" ? "timeout" : "completed"), standings: s.players.map((p) => ({ user_id: p.user_id, seat: p.seat, @@ -453,13 +459,44 @@ function finish(s: State, ctx: Ctx, winner: number | null, reason: string = "com }); } +const TIME_CONTROLS: Record = { + "1m": { initial_ms: 60_000, increment_ms: 0 }, + "1m_1s": { initial_ms: 60_000, increment_ms: 1_000 }, + "3m": { initial_ms: 180_000, increment_ms: 0 }, + "3m_2s": { initial_ms: 180_000, increment_ms: 2_000 }, + "10m": { initial_ms: 600_000, increment_ms: 0 }, + "15m_10s": { initial_ms: 900_000, increment_ms: 10_000 }, +}; + +function resolveTimeControl(modes: string[], options: Record): { tcId: string; initial_ms: number; increment_ms: number } { + // If explicitly specified in options + if (typeof options.time_control === "string" && TIME_CONTROLS[options.time_control]) { + const tcId = options.time_control; + return { tcId, ...TIME_CONTROLS[tcId] }; + } + // Otherwise deduce from mode + if (modes.includes("bullet")) { + return { tcId: "1m", ...TIME_CONTROLS["1m"] }; + } + if (modes.includes("rapid")) { + return { tcId: "10m", ...TIME_CONTROLS["10m"] }; + } + // Default is blitz 3m + return { tcId: "3m", ...TIME_CONTROLS["3m"] }; +} + export const chess: GameDef = { manifest, - validateModes: (modes) => - modes.every((m) => m === "classic") ? [] : [{ code: "chess.unknown_mode", path: "/modes", message: "unknown mode" }], + validateModes: (modes) => { + const valid = ["blitz", "bullet", "rapid", "classic"]; + return modes.every((m) => valid.includes(m)) + ? [] + : [{ code: "chess.unknown_mode", path: "/modes", message: "unknown mode" }]; + }, init(create: CreateTable, ictx: InitCtx): State { const seats = [...create.participants].sort((a, b) => a.seat - b.seat); const first = firstSeat(create, ictx.rng, 2); + const tc = resolveTimeControl(create.modes, create.options); const s: State = { players: seats.map((p, i) => ({ seat: i, @@ -476,7 +513,11 @@ export const chess: GameDef = { phase: "play", winner: null, result_reason: "", - turn_ms: typeof create.options.turn_ms === "number" ? (create.options.turn_ms as number) : 60000, + time_control: tc.tcId, + initial_time_ms: tc.initial_ms, + increment_ms: tc.increment_ms, + clocks: [tc.initial_ms, tc.initial_ms], + turn_start_ms: ictx.now, timer_n: 0, timer_id: null, deadline: null, @@ -545,6 +586,11 @@ export const chess: GameDef = { promo = payload.promotion; } if (!isValidMove(s, fromIdx, toIdx, p.seat)) return ctx.reject("chess.invalid_move"); + + // Deduct elapsed time and add increment + const elapsed = Math.max(0, ctx.now - s.turn_start_ms); + s.clocks[p.seat] = Math.max(0, s.clocks[p.seat] - elapsed) + s.increment_ms; + applyMove(s, fromIdx, toIdx, p.seat, promo); return postMove(s, ctx, p.seat); } @@ -566,6 +612,10 @@ export const chess: GameDef = { players: s.players.map((p) => ({ seat: p.seat, name: p.name, color: p.color, bot: p.bot, connected: p.conns.length > 0, left: p.left })), moves_played: s.moves_played, captures: s.captures, + clocks: s.clocks, + turn_start_ms: s.turn_start_ms, + time_control: s.time_control, + increment_ms: s.increment_ms, }; }, }; @@ -584,6 +634,10 @@ function handleBotMove(s: State, ctx: Ctx) { const seatBefore = s.turn; const botMove = decideBot(s, s.turn, ctx.rng); if (botMove !== null && typeof botMove.fromIdx === "number" && typeof botMove.toIdx === "number") { + // Deduct elapsed time and add increment for bot + const elapsed = Math.max(0, ctx.now - s.turn_start_ms); + s.clocks[seatBefore] = Math.max(0, s.clocks[seatBefore] - elapsed) + s.increment_ms; + applyMove(s, botMove.fromIdx, botMove.toIdx, seatBefore, botMove.promotion); return postMove(s, ctx, seatBefore); } @@ -596,22 +650,12 @@ function handleBotMove(s: State, ctx: Ctx) { function handleTimeout(s: State, ctx: Ctx) { s.timer_id = null; - // On timeout, make a simple default move: first legal move found - const seat = s.turn; - for (let from = 0; from < 64; from++) { - const p = s.board[from]; - if (!p || p.color !== s.players[seat].color) continue; - for (let to = 0; to < 64; to++) { - if (isValidMove(s, from, to, seat)) { - applyMove(s, from, to, seat); - return postMove(s, ctx, seat); - } - } - } - // No legal moves — checkmate loss if in check, else stalemate draw. - if (isKingInCheck(s, s.players[seat].color)) { - finish(s, ctx, 1 - seat, "checkmate"); - } else { - finish(s, ctx, null, "stalemate"); + const timedOutSeat = s.turn; + s.clocks[timedOutSeat] = 0; + // If the opponent does not have sufficient material to checkmate, it's a draw by timeout vs insufficient material + const oppSeat = 1 - timedOutSeat; + if (hasInsufficientMaterial(s)) { + return finish(s, ctx, null, "timeout_draw"); } + return finish(s, ctx, oppSeat, "timeout"); } diff --git a/server/package.json b/server/package.json index 0368c2a..1b20656 100644 --- a/server/package.json +++ b/server/package.json @@ -1,6 +1,6 @@ { "name": "@3miz/chess-server", - "version": "1.6.0", + "version": "1.7.0", "private": true, "type": "module", "scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" }, diff --git a/tests/game.test.ts b/tests/game.test.ts index 16e3818..9331429 100644 --- a/tests/game.test.ts +++ b/tests/game.test.ts @@ -328,7 +328,9 @@ test("insufficient material: capturing last pawn triggers draw immediately", () players: [mk(0, "u0", "w"), mk(1, "u1", "b")], board: Array(64).fill(null) as State["board"], turn: 0, phase: "play", winner: null, result_reason: "", - turn_ms: 60000, timer_n: 0, timer_id: null, deadline: null, bot_timer: null, bot_n: 0, + time_control: "3m", initial_time_ms: 180000, increment_ms: 0, + clocks: [180000, 180000], turn_start_ms: 1700000000000, + timer_n: 0, timer_id: null, deadline: null, bot_timer: null, bot_n: 0, moves_played: 50, captures: 29, rights: { wk: false, wq: false, bk: false, bq: false }, ep: null, }; @@ -364,3 +366,83 @@ test("insufficient material: capturing last pawn triggers draw immediately", () assert.equal((w.game as State).result_reason, "insufficient_material"); assert.equal(w.status, "finished"); }); + +test("time controls: bullet 1m, bullet 1m+1s, blitz 3m, blitz 3m+2s, rapid 10m, rapid 15m+10s", () => { + const base = create(false); + + // Bullet mode default + const { w: wBullet } = initTable(chess, { ...base, modes: ["bullet"], options: {} }, 1); + const sBullet = wBullet.game as State; + assert.equal(sBullet.initial_time_ms, 60_000); + assert.equal(sBullet.increment_ms, 0); + + // Bullet mode with 1m_1s option + const { w: wBulletInc } = initTable(chess, { ...base, modes: ["bullet"], options: { time_control: "1m_1s" } }, 1); + const sBulletInc = wBulletInc.game as State; + assert.equal(sBulletInc.initial_time_ms, 60_000); + assert.equal(sBulletInc.increment_ms, 1_000); + + // Blitz mode default 3m + const { w: wBlitz } = initTable(chess, { ...base, modes: ["blitz"], options: {} }, 1); + const sBlitz = wBlitz.game as State; + assert.equal(sBlitz.initial_time_ms, 180_000); + assert.equal(sBlitz.increment_ms, 0); + + // Blitz mode with 3m_2s option + const { w: wBlitzInc } = initTable(chess, { ...base, modes: ["blitz"], options: { time_control: "3m_2s" } }, 1); + const sBlitzInc = wBlitzInc.game as State; + assert.equal(sBlitzInc.initial_time_ms, 180_000); + assert.equal(sBlitzInc.increment_ms, 2_000); + + // Rapid mode default 10m + const { w: wRapid } = initTable(chess, { ...base, modes: ["rapid"], options: {} }, 1); + const sRapid = wRapid.game as State; + assert.equal(sRapid.initial_time_ms, 600_000); + assert.equal(sRapid.increment_ms, 0); + + // Rapid mode with 15m_10s option + const { w: wRapidInc } = initTable(chess, { ...base, modes: ["rapid"], options: { time_control: "15m_10s" } }, 1); + const sRapidInc = wRapidInc.game as State; + assert.equal(sRapidInc.initial_time_ms, 900_000); + assert.equal(sRapidInc.increment_ms, 10_000); +}); + +test("time controls: clocks deduct elapsed time and add increment on move", () => { + const base = create(false); + const { w } = initTable(chess, { ...base, modes: ["blitz"], options: { time_control: "3m_2s" } }, 1); + const s0 = w.game as State; + const seat = whiteSeatOf(s0); + assert.deepEqual(s0.clocks, [180_000, 180_000]); + + // Player thinks for 5 seconds (5000 ms), then moves e2 -> e4 + // New clock should be: 180,000 - 5,000 + 2,000 = 177,000 + const tMove = base.created_at_ms + 5_000; + const result = applyInput(chess, w, { + v: 1, type: "move", payload: { from: "e2", to: "e4" }, + uid: userOf(s0, seat), ci: "c0", cid: 1, role: "player", seat, ts_ms: tMove, + } as Input, 1); + assert.equal(result.status, "accepted"); + const s1 = w.game as State; + assert.equal(s1.clocks[seat], 177_000); + assert.equal(s1.clocks[1 - seat], 180_000); // opponent clock hasn't started yet +}); + +test("time controls: timeout leads to game over", () => { + const base = create(false); + const { w } = initTable(chess, { ...base, modes: ["bullet"], options: { time_control: "1m" } }, 1); + const s0 = w.game as State; + const seat = whiteSeatOf(s0); + const timerId = s0.timer_id!; + assert.ok(timerId); + + // Time runs out and $timer fires + applyInput(chess, w, { + v: 1, type: "$timer", payload: { timer_id: timerId, due_ms: base.created_at_ms + 60_000 }, + ts_ms: base.created_at_ms + 60_000, + } as Input, 1); + + const sEnd = w.game as State; + assert.equal(sEnd.phase, "over"); + assert.equal(sEnd.winner, 1 - seat); // opponent wins on time + assert.equal(sEnd.result_reason, "timeout"); +});