Added time control mechanics to the rules

This commit is contained in:
2026-11-06 22:29:07 +03:30
parent 48c0ad1265
commit 9921e64598
11 changed files with 560 additions and 39 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "chess-client",
"version": "1.6.0",
"version": "1.7.0",
"private": true,
"type": "module",
"scripts": {
+69 -4
View File
@@ -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
? `<div class="chess-clock ${isActive ? "active" : ""} ${isLowTime ? "low-time" : ""}" data-seat="${player.seat}">${formatTime(remainingMs)}</div>`
: "";
el.innerHTML = `
<div class="player-profile">
<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>
</div>
<div class="player-clock-section">
<div class="captured-tray">
${capturedPieces.map((p) => `<div class="mini-piece">${getPieceSvg(p.type as PieceType, p.color as PieceColor)}</div>`).join("")}
${advText}
</div>
${clockHtml}
</div>
`;
}
@@ -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 = `
+45
View File
@@ -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
========================================================================== */
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -4,8 +4,8 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chess — 3miz</title>
<script type="module" crossorigin src="./assets/index-8tGLzrk3.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-CJ1BuKCF.css">
<script type="module" crossorigin src="./assets/index-CHF7ocq9.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-C6_IS3s7.css">
</head>
<body><div id="app">…</div></body>
</html>
+1 -1
View File
@@ -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": {
+78 -3
View File
@@ -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,
+67 -23
View File
@@ -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<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> = {
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<State> = {
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<State> = {
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<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 })),
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");
}
+1 -1
View File
@@ -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" },
+83 -1
View File
@@ -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");
});