Added time control mechanics to the rules
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "chess-client",
|
"name": "chess-client",
|
||||||
"version": "1.6.0",
|
"version": "1.7.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
+69
-4
@@ -29,12 +29,18 @@ interface GameSnapshot {
|
|||||||
players: PlayerSnapshot[];
|
players: PlayerSnapshot[];
|
||||||
moves_played: number;
|
moves_played: number;
|
||||||
captures: number;
|
captures: number;
|
||||||
|
clocks?: [number, number];
|
||||||
|
turn_start_ms?: number;
|
||||||
|
time_control?: string;
|
||||||
|
increment_ms?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
let S: GameSnapshot | null = null;
|
let S: GameSnapshot | null = null;
|
||||||
let prevS: GameSnapshot | null = null;
|
let prevS: GameSnapshot | null = null;
|
||||||
let init: InitMsg | null = null;
|
let init: InitMsg | null = null;
|
||||||
let vfx: VfxEngine | null = null;
|
let vfx: VfxEngine | null = null;
|
||||||
|
let clockInterval: number | null = null;
|
||||||
|
let snapReceivedAt = Date.now();
|
||||||
|
|
||||||
let selectedSquare = "";
|
let selectedSquare = "";
|
||||||
let legalTargets: { target: string; isCapture: boolean }[] = [];
|
let legalTargets: { target: string; isCapture: boolean }[] = [];
|
||||||
@@ -61,6 +67,11 @@ const host = connectHost({
|
|||||||
}
|
}
|
||||||
prevS = S;
|
prevS = S;
|
||||||
S = env.body as GameSnapshot;
|
S = env.body as GameSnapshot;
|
||||||
|
snapReceivedAt = Date.now();
|
||||||
|
|
||||||
|
if (!clockInterval) {
|
||||||
|
clockInterval = window.setInterval(updateClocks, 200);
|
||||||
|
}
|
||||||
|
|
||||||
if (S.turn !== S.me) {
|
if (S.turn !== S.me) {
|
||||||
selectedSquare = "";
|
selectedSquare = "";
|
||||||
@@ -368,8 +379,43 @@ function updateUI() {
|
|||||||
renderModalContainer();
|
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) {
|
function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isActive: boolean, isMe: boolean) {
|
||||||
const el = document.getElementById(barId);
|
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 🤝") : ""))
|
? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : (S.winner === null ? L("تساوی 🤝", "Draw 🤝") : ""))
|
||||||
: (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : "");
|
: (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
|
||||||
|
? `<div class="chess-clock ${isActive ? "active" : ""} ${isLowTime ? "low-time" : ""}" data-seat="${player.seat}">${formatTime(remainingMs)}</div>`
|
||||||
|
: "";
|
||||||
|
|
||||||
el.innerHTML = `
|
el.innerHTML = `
|
||||||
<div class="player-profile">
|
<div class="player-profile">
|
||||||
<div class="player-badge ${player.color}">
|
<div class="player-badge ${player.color}">
|
||||||
@@ -398,10 +451,13 @@ function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isAc
|
|||||||
<div class="player-status">${statusLabel}</div>
|
<div class="player-status">${statusLabel}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="player-clock-section">
|
||||||
<div class="captured-tray">
|
<div class="captured-tray">
|
||||||
${capturedPieces.map((p) => `<div class="mini-piece">${getPieceSvg(p.type as PieceType, p.color as PieceColor)}</div>`).join("")}
|
${capturedPieces.map((p) => `<div class="mini-piece">${getPieceSvg(p.type as PieceType, p.color as PieceColor)}</div>`).join("")}
|
||||||
${advText}
|
${advText}
|
||||||
</div>
|
</div>
|
||||||
|
${clockHtml}
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -513,6 +569,9 @@ function renderModalContainer() {
|
|||||||
} else if (S.result_reason === "insufficient_material") {
|
} else if (S.result_reason === "insufficient_material") {
|
||||||
title = L("تساوی — عدم کفایت مهرهها", "Draw — Insufficient Material");
|
title = L("تساوی — عدم کفایت مهرهها", "Draw — Insufficient Material");
|
||||||
subtitle = L("مهره کافی برای مات کردن در صفحه وجود ندارد", "Neither side has sufficient pieces to force checkmate");
|
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 {
|
} else {
|
||||||
title = L("بازی مساوی شد", "Draw!");
|
title = L("بازی مساوی شد", "Draw!");
|
||||||
subtitle = L("هیچکدام از طرفین برنده نشد", "No side achieved victory");
|
subtitle = L("هیچکدام از طرفین برنده نشد", "No side achieved victory");
|
||||||
@@ -520,9 +579,15 @@ function renderModalContainer() {
|
|||||||
} else {
|
} else {
|
||||||
const winnerName = S.players[S.winner!]?.name;
|
const winnerName = S.players[S.winner!]?.name;
|
||||||
title = `${winnerName} ${L("برنده شد! 🏆", "Wins! 🏆")}`;
|
title = `${winnerName} ${L("برنده شد! 🏆", "Wins! 🏆")}`;
|
||||||
subtitle = S.result_reason === "checkmate"
|
if (S.result_reason === "checkmate") {
|
||||||
? L("با کیش و مات حریف", "By checkmate")
|
subtitle = L("با کیش و مات حریف", "By checkmate");
|
||||||
: (S.result_reason === "abandoned" ? L("به دلیل ترک حریف", "By abandonment") : "");
|
} else if (S.result_reason === "timeout") {
|
||||||
|
subtitle = L("با اتمام زمان حریف", "On time");
|
||||||
|
} else if (S.result_reason === "abandoned") {
|
||||||
|
subtitle = L("به دلیل ترک حریف", "By abandonment");
|
||||||
|
} else {
|
||||||
|
subtitle = "";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
container.innerHTML = `
|
container.innerHTML = `
|
||||||
|
|||||||
@@ -158,6 +158,51 @@ html, body {
|
|||||||
margin-inline-start: 4px;
|
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
|
Chess Board & Cells
|
||||||
========================================================================== */
|
========================================================================== */
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2
-2
@@ -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-8tGLzrk3.js"></script>
|
<script type="module" crossorigin src="./assets/index-CHF7ocq9.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="./assets/index-CJ1BuKCF.css">
|
<link rel="stylesheet" crossorigin href="./assets/index-C6_IS3s7.css">
|
||||||
</head>
|
</head>
|
||||||
<body><div id="app">…</div></body>
|
<body><div id="app">…</div></body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"bundle_format": 1,
|
"bundle_format": 1,
|
||||||
"kind": "source",
|
"kind": "source",
|
||||||
"game_id": "chess",
|
"game_id": "chess",
|
||||||
"version": "1.6.0",
|
"version": "1.7.0",
|
||||||
"server": { "entry": "server/main.ts" },
|
"server": { "entry": "server/main.ts" },
|
||||||
"client": { "entry": "index.html" },
|
"client": { "entry": "index.html" },
|
||||||
"catalog": {
|
"catalog": {
|
||||||
|
|||||||
+78
-3
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"manifest_version": 1,
|
"manifest_version": 1,
|
||||||
"game_id": "chess",
|
"game_id": "chess",
|
||||||
"version": "1.6.0",
|
"version": "1.7.0",
|
||||||
"protocol": "socketio",
|
"protocol": "socketio",
|
||||||
"protocol_version": 1,
|
"protocol_version": 1,
|
||||||
"title": {
|
"title": {
|
||||||
@@ -41,6 +41,27 @@
|
|||||||
"en": "Classic"
|
"en": "Classic"
|
||||||
},
|
},
|
||||||
"default": true
|
"default": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "blitz",
|
||||||
|
"title": {
|
||||||
|
"fa": "بلیتس (Blitz)",
|
||||||
|
"en": "Blitz"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bullet",
|
||||||
|
"title": {
|
||||||
|
"fa": "بولت (Bullet)",
|
||||||
|
"en": "Bullet"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "rapid",
|
||||||
|
"title": {
|
||||||
|
"fa": "رپید (Rapid)",
|
||||||
|
"en": "Rapid"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"options": [
|
"options": [
|
||||||
@@ -56,6 +77,60 @@
|
|||||||
"en": "Turn time"
|
"en": "Turn time"
|
||||||
},
|
},
|
||||||
"rated_safe": true
|
"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": [],
|
"cosmetic_slots": [],
|
||||||
@@ -81,14 +156,14 @@
|
|||||||
],
|
],
|
||||||
"achievements": [],
|
"achievements": [],
|
||||||
"client": {
|
"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",
|
"integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||||
"aspect": "1:1",
|
"aspect": "1:1",
|
||||||
"min_width_px": 320,
|
"min_width_px": 320,
|
||||||
"supports_portrait": true
|
"supports_portrait": true
|
||||||
},
|
},
|
||||||
"server": {
|
"server": {
|
||||||
"image": "registry.3miz.ir/games/chess:1.6.0",
|
"image": "registry.3miz.ir/games/chess:1.7.0",
|
||||||
"max_tables_per_instance": 500,
|
"max_tables_per_instance": 500,
|
||||||
"checkpoint_every_inputs": 20,
|
"checkpoint_every_inputs": 20,
|
||||||
"snapshot_every_messages": 50,
|
"snapshot_every_messages": 50,
|
||||||
|
|||||||
+67
-23
@@ -22,7 +22,11 @@ export interface State {
|
|||||||
phase: "play" | "over";
|
phase: "play" | "over";
|
||||||
winner: number | null; // winning seat, or null for draw
|
winner: number | null; // winning seat, or null for draw
|
||||||
result_reason: string;
|
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_n: number;
|
||||||
timer_id: string | null;
|
timer_id: string | null;
|
||||||
deadline: number | 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);
|
if (s.timer_id) t.clearTimer?.(s.timer_id);
|
||||||
s.timer_n += 1;
|
s.timer_n += 1;
|
||||||
s.timer_id = `turn-${s.timer_n}`;
|
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);
|
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);
|
if (s.bot_timer) ctx.clearTimer(s.bot_timer);
|
||||||
s.bot_timer = null;
|
s.bot_timer = null;
|
||||||
ctx.finish({
|
ctx.finish({
|
||||||
reason: reason === "abandoned" ? "abandoned" : "completed",
|
reason: reason === "abandoned" ? "abandoned" : (reason === "timeout" ? "timeout" : "completed"),
|
||||||
standings: s.players.map((p) => ({
|
standings: s.players.map((p) => ({
|
||||||
user_id: p.user_id,
|
user_id: p.user_id,
|
||||||
seat: p.seat,
|
seat: p.seat,
|
||||||
@@ -453,13 +459,44 @@ function finish(s: State, ctx: Ctx, winner: number | null, reason: string = "com
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TIME_CONTROLS: Record<string, { initial_ms: number; increment_ms: number }> = {
|
||||||
|
"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<string, unknown>): { 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<State> = {
|
export const chess: GameDef<State> = {
|
||||||
manifest,
|
manifest,
|
||||||
validateModes: (modes) =>
|
validateModes: (modes) => {
|
||||||
modes.every((m) => m === "classic") ? [] : [{ code: "chess.unknown_mode", path: "/modes", message: "unknown mode" }],
|
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 {
|
init(create: CreateTable, ictx: InitCtx): State {
|
||||||
const seats = [...create.participants].sort((a, b) => a.seat - b.seat);
|
const seats = [...create.participants].sort((a, b) => a.seat - b.seat);
|
||||||
const first = firstSeat(create, ictx.rng, 2);
|
const first = firstSeat(create, ictx.rng, 2);
|
||||||
|
const tc = resolveTimeControl(create.modes, create.options);
|
||||||
const s: State = {
|
const s: State = {
|
||||||
players: seats.map((p, i) => ({
|
players: seats.map((p, i) => ({
|
||||||
seat: i,
|
seat: i,
|
||||||
@@ -476,7 +513,11 @@ export const chess: GameDef<State> = {
|
|||||||
phase: "play",
|
phase: "play",
|
||||||
winner: null,
|
winner: null,
|
||||||
result_reason: "",
|
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_n: 0,
|
||||||
timer_id: null,
|
timer_id: null,
|
||||||
deadline: null,
|
deadline: null,
|
||||||
@@ -545,6 +586,11 @@ export const chess: GameDef<State> = {
|
|||||||
promo = payload.promotion;
|
promo = payload.promotion;
|
||||||
}
|
}
|
||||||
if (!isValidMove(s, fromIdx, toIdx, p.seat)) return ctx.reject("chess.invalid_move");
|
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);
|
applyMove(s, fromIdx, toIdx, p.seat, promo);
|
||||||
return postMove(s, ctx, p.seat);
|
return postMove(s, ctx, p.seat);
|
||||||
}
|
}
|
||||||
@@ -566,6 +612,10 @@ export const chess: GameDef<State> = {
|
|||||||
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 })),
|
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,
|
moves_played: s.moves_played,
|
||||||
captures: s.captures,
|
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 seatBefore = s.turn;
|
||||||
const botMove = decideBot(s, s.turn, ctx.rng);
|
const botMove = decideBot(s, s.turn, ctx.rng);
|
||||||
if (botMove !== null && typeof botMove.fromIdx === "number" && typeof botMove.toIdx === "number") {
|
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);
|
applyMove(s, botMove.fromIdx, botMove.toIdx, seatBefore, botMove.promotion);
|
||||||
return postMove(s, ctx, seatBefore);
|
return postMove(s, ctx, seatBefore);
|
||||||
}
|
}
|
||||||
@@ -596,22 +650,12 @@ function handleBotMove(s: State, ctx: Ctx) {
|
|||||||
|
|
||||||
function handleTimeout(s: State, ctx: Ctx) {
|
function handleTimeout(s: State, ctx: Ctx) {
|
||||||
s.timer_id = null;
|
s.timer_id = null;
|
||||||
// On timeout, make a simple default move: first legal move found
|
const timedOutSeat = s.turn;
|
||||||
const seat = s.turn;
|
s.clocks[timedOutSeat] = 0;
|
||||||
for (let from = 0; from < 64; from++) {
|
// If the opponent does not have sufficient material to checkmate, it's a draw by timeout vs insufficient material
|
||||||
const p = s.board[from];
|
const oppSeat = 1 - timedOutSeat;
|
||||||
if (!p || p.color !== s.players[seat].color) continue;
|
if (hasInsufficientMaterial(s)) {
|
||||||
for (let to = 0; to < 64; to++) {
|
return finish(s, ctx, null, "timeout_draw");
|
||||||
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");
|
|
||||||
}
|
}
|
||||||
|
return finish(s, ctx, oppSeat, "timeout");
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@3miz/chess-server",
|
"name": "@3miz/chess-server",
|
||||||
"version": "1.6.0",
|
"version": "1.7.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" },
|
"scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" },
|
||||||
|
|||||||
+83
-1
@@ -328,7 +328,9 @@ test("insufficient material: capturing last pawn triggers draw immediately", ()
|
|||||||
players: [mk(0, "u0", "w"), mk(1, "u1", "b")],
|
players: [mk(0, "u0", "w"), mk(1, "u1", "b")],
|
||||||
board: Array(64).fill(null) as State["board"],
|
board: Array(64).fill(null) as State["board"],
|
||||||
turn: 0, phase: "play", winner: null, result_reason: "",
|
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,
|
moves_played: 50, captures: 29,
|
||||||
rights: { wk: false, wq: false, bk: false, bq: false }, ep: null,
|
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.game as State).result_reason, "insufficient_material");
|
||||||
assert.equal(w.status, "finished");
|
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");
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user