Initial Commit
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
client-src/node_modules/*
|
||||
client-src/dist/*
|
||||
@@ -0,0 +1,136 @@
|
||||
# Chess — 3miz game bundle
|
||||
|
||||
Standard 8×8 chess for two players, packaged as a 3miz game bundle (contract 36).
|
||||
Built from `templates/game-bundle` (the Tic-Tac-Toe sample) and adapted to this
|
||||
monorepo: deterministic TypeScript game server on the `@3miz/game-server-sdk`
|
||||
(contract 40) plus a sandboxed iframe client (contract 43).
|
||||
|
||||
- `game_id`: `chess`, version `1.0.0`
|
||||
- Lafayette orientation: the board is shown from your own side (white sees `a8`
|
||||
top-left, black sees `h1` top-left); `a1` is always dark.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
games/chess/
|
||||
game.json bundle descriptor (kind "source", server/client entries, catalog block)
|
||||
manifest.json game manifest, contract 30 (players, modes, options, bots, client/server …)
|
||||
README.md this file (also packed into the ZIP by tools/gamezip/zip.mjs)
|
||||
server/
|
||||
main.ts entry point: runGameServer(chess)
|
||||
game.ts rules: state, init, apply, views/snapshot, timers, results
|
||||
bot.ts bot move choice (random legal move, queen on promotion)
|
||||
package.json @3miz/chess-server (deps: @3miz/game-server-sdk, @3miz/common)
|
||||
tsconfig.json extends the repo tsconfig.base.json
|
||||
client-src/ Vite + TypeScript browser client (source of truth for the UI)
|
||||
index.html iframe entry
|
||||
src/main.ts rendering, select→target picking, promotion picker, host bridge
|
||||
src/style.css board theme (square colours are assigned per square in JS)
|
||||
vite.config.ts relative base + alias for @3miz/game-client/iframe (see below)
|
||||
sdk-src/ iframe bridge copied from sdk/game-client.zip (build-time only)
|
||||
node_modules/ build-time only, never packed into the ZIP
|
||||
dist/ throwaway Vite output, synced into ../client/ before zipping
|
||||
client/ generated: the last good Vite build (what goes into the ZIP)
|
||||
tests/
|
||||
game.test.ts rule tests, run against the real engine (see Testing)
|
||||
docs/
|
||||
TIPS.md reviewer/developer notes
|
||||
```
|
||||
|
||||
## Rules implemented
|
||||
|
||||
- All six pieces with standard movement, captures, alternating turns (white first).
|
||||
- **Check**: any move leaving your own king attacked is rejected
|
||||
(`chess.invalid_move`), so check is answered by king flight, capture, or block.
|
||||
- **Checkmate** (no legal reply) wins; **stalemate** (no legal move while safe)
|
||||
draws. No threefold-repetition, fifty-move, or insufficient-material draws.
|
||||
- **Castling**: rights start `wk/wq/bk/bq = true` and decay on king/rook moves
|
||||
and corner-rook captures. No castling out of, through, or into check.
|
||||
- **En passant**: a one-move window (`ep`) opens behind a double-stepping pawn.
|
||||
- **Promotion**: `promotion: q|r|b|n` in the move command (default queen; bots
|
||||
and timeout auto-moves always queen). Anything else → `chess.invalid_promotion`.
|
||||
- Timers: every turn has a `turn_ms` deadline (table option, default 60 s);
|
||||
timeout plays the first legal move. `$leave` abandons, `$bot_replace` subs a bot.
|
||||
- Determinism (GS-610): time only via `ctx.now`, randomness only via `ctx.rng`,
|
||||
no module-level mutable state — replays and failover stay exact.
|
||||
|
||||
## Wire protocol (client ⇄ server)
|
||||
|
||||
One player command:
|
||||
|
||||
```jsonc
|
||||
{ "type": "move", "payload": { "from": "e2", "to": "e4", "promotion": "q" } }
|
||||
// promotion: only "q" | "r" | "b" | "n", only when a pawn reaches the last rank
|
||||
```
|
||||
|
||||
Snapshots (per view) carry `me`, `board: [{ square, type, color } × 64]` in
|
||||
`a1…h8` index order (the client re-orients for display), `turn`, `phase`,
|
||||
`winner`, `result_reason` (`"" | "checkmate" | "stalemate" | "abandoned"`),
|
||||
`check` (side to move is in check), `players`, `moves_played`, `captures`.
|
||||
No hidden information: all views see the same board. Error codes are
|
||||
`chess.not_a_player | chess.invalid_move | chess.invalid_square |
|
||||
chess.invalid_promotion | chess.unknown_type | chess.unknown_mode`.
|
||||
|
||||
## Build & ZIP
|
||||
|
||||
Prerequisites: Node.js. All commands run from the repo root
|
||||
(`3miz-platform/`); PowerShell users should run `npm`/`npx` via `cmd /c`
|
||||
(execution policy blocks `npm.ps1`).
|
||||
|
||||
```powershell
|
||||
# 1. Build the client (resolves the game-client bridge via client-src/sdk-src)
|
||||
cmd /c "cd /d games\chess\client-src && npm install" # first time only
|
||||
cmd /c "cd /d games\chess\client-src && node_modules\.bin\vite.cmd build --base ./ --outDir dist --emptyOutDir"
|
||||
|
||||
# 2. Sync the build output into client/
|
||||
Remove-Item -Recurse -Force games\chess\client
|
||||
Copy-Item -Recurse -Force games\chess\client-src\dist games\chess\client
|
||||
|
||||
# 3. ZIP it. zip.mjs prefers client-src/ and shells out to `npx` (absent on some
|
||||
# machines), so hide client-src/ while zipping and restore it afterwards:
|
||||
Move-Item games\chess\client-src C:\Temp\chess-client-src
|
||||
node tools/gamezip/zip.mjs games/chess chess-1.0.0.zip
|
||||
Move-Item C:\Temp\chess-client-src games\chess\client-src
|
||||
```
|
||||
|
||||
Why `sdk-src/`? The client imports `@3miz/game-client/iframe`, which is not a
|
||||
published npm package — it lives in `sdk/game-client.zip`. `sdk-src/` is that
|
||||
zip's `src/` extracted, wired up by the `resolve.alias` in
|
||||
`client-src/vite.config.ts`, so a standalone `npm install` + `vite build`
|
||||
works. It is build tooling only: the ZIP packs `server/`, `client/`,
|
||||
`tests/`, `docs/`, `game.json`, `manifest.json`, `README.md` — never
|
||||
`client-src/`, `node_modules/`, or `dist/`.
|
||||
|
||||
Upload: admin panel → *Games & deployments* → **Upload ZIP**, then raise the
|
||||
version's instances (suggested: 2). Play as admin; publish when ready.
|
||||
|
||||
## Testing
|
||||
|
||||
Canonical (inside a full repo checkout with dev dependencies):
|
||||
|
||||
```
|
||||
node --test --import tsx games/chess/tests/game.test.ts
|
||||
```
|
||||
|
||||
The suite covers init layout, pawn direction both colours, knight jumps, bad
|
||||
squares, kingside castling + rights decay, en passant (window open/close),
|
||||
promotion to queen/knight (+ invalid piece rejected), fool's mate ending the
|
||||
game, answering `Qxf7+` (sideline rejected, `Kxf7` accepted), and a stalemate
|
||||
position. If `tsx` is unavailable, the same file can be run by bundling it
|
||||
with esbuild and aliasing the two workspace packages (this is how it was
|
||||
verified here):
|
||||
|
||||
```
|
||||
esbuild --bundle --platform=node --format=esm --loader:.ts=ts \
|
||||
--alias:@3miz/game-server-sdk=<shim re-exporting sdk/game-server-ts/src/{engine,seating,rng}.ts> \
|
||||
--alias:@3miz/common=packages/ts/common/src/jcs.ts \
|
||||
games/chess/tests/game.test.ts --outfile=/tmp/chess-test.bundle.mjs
|
||||
node --test /tmp/chess-test.bundle.mjs
|
||||
```
|
||||
|
||||
## New versions
|
||||
|
||||
Bump `version` in **both** `game.json` and `manifest.json` for every upload
|
||||
(versions are immutable). Keep PATCH/MINOR backward compatible per contract 35
|
||||
(no removed modes/options, no narrowed bounds); breaking changes need a new
|
||||
MAJOR. `client.entry` / `server.image` URLs must match the new version.
|
||||
@@ -0,0 +1,9 @@
|
||||
<!doctype html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Chess — 3miz</title>
|
||||
</head>
|
||||
<body><div id="app">…</div><script type="module" src="./src/main.ts"></script></body>
|
||||
</html>
|
||||
Generated
+1005
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "chess-client",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Host-side table connection (contract 41 client rules TP-4xx/5xx), used by the table page (M19).
|
||||
* Owns both sockets and all credentials (CS-12); the game iframe only sees ordered `state` messages.
|
||||
*/
|
||||
import { io, type Socket } from "socket.io-client";
|
||||
|
||||
export interface HostCallbacks {
|
||||
onState(env: any): void;
|
||||
onViewChanged(view: string | null): void;
|
||||
onAck(ack: { cid: number; status: string; code?: string }): void;
|
||||
onStatus(status: string): void;
|
||||
onConnection(state: "connecting" | "online" | "offline"): void;
|
||||
onHello?(h: { server_time_ms: number; view: string | null; ep: number }): void;
|
||||
}
|
||||
|
||||
const rand = () => Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
function ss(): Storage | null { try { return window.sessionStorage; } catch { return null; } }
|
||||
|
||||
export class TableConnection {
|
||||
readonly ci: string;
|
||||
private cid: number;
|
||||
private ing!: Socket;
|
||||
private egr!: Socket;
|
||||
private view: string | null = null;
|
||||
private vseq = 0;
|
||||
private ep = 0;
|
||||
private buffer = new Map<number, any>();
|
||||
private resyncAt = 0;
|
||||
private pending = new Map<number, { type: string; payload: unknown; known?: unknown }>();
|
||||
private closed = false;
|
||||
|
||||
constructor(private tid: string, private origin: string, private getTicket: (ci: string) => Promise<string>, private cb: HostCallbacks) {
|
||||
const s = ss();
|
||||
const key = `m3.ci.${tid}`;
|
||||
this.ci = s?.getItem(key) ?? rand(); // TP-004: fresh ci per tab per table
|
||||
s?.setItem(key, this.ci);
|
||||
this.cid = Number(s?.getItem(`m3.cid.${tid}.${this.ci}`) ?? 0);
|
||||
}
|
||||
|
||||
connect() {
|
||||
const auth = (extra: () => object) => (cb: (d: object) => void) => {
|
||||
this.getTicket(this.ci).then((ticket) => cb({ ticket, ...extra() })).catch(() => cb({ ticket: "" }));
|
||||
};
|
||||
const common = { transports: ["websocket"], reconnectionDelay: 500, reconnectionDelayMax: 4000 };
|
||||
this.cb.onConnection("connecting");
|
||||
this.ing = io(this.origin, { ...common, path: "/t/in", auth: auth(() => ({})) });
|
||||
this.egr = io(this.origin, { ...common, path: "/t/out", auth: auth(() => (this.view ? { resume: { view: this.view, after_vseq: this.vseq } } : {})) });
|
||||
|
||||
this.ing.on("connect", () => {
|
||||
// TP-501: re-send pending commands with their original cid
|
||||
for (const [cid, p] of [...this.pending.entries()].sort((a, b) => a[0] - b[0])) this.emitCmd(cid, p.type, p.payload, p.known);
|
||||
this.updateConn();
|
||||
});
|
||||
this.ing.on("disconnect", () => this.updateConn());
|
||||
this.egr.on("connect", () => this.updateConn());
|
||||
this.egr.on("disconnect", () => this.updateConn());
|
||||
this.egr.on("hello", (h: any) => {
|
||||
if (h.view !== this.view) this.setView(h.view);
|
||||
this.cb.onHello?.(h);
|
||||
});
|
||||
this.egr.on("sys", (s: any) => {
|
||||
if (s.kind === "view_changed") this.setView(s.view);
|
||||
if (s.kind === "status") this.cb.onStatus(s.status);
|
||||
});
|
||||
this.egr.on("m", (env: any) => this.onMessage(env));
|
||||
this.egr.on("ack", (a: any) => {
|
||||
if (!this.pending.has(a.cid)) return; // TP-504
|
||||
this.pending.delete(a.cid);
|
||||
this.cb.onAck(a);
|
||||
});
|
||||
}
|
||||
|
||||
private updateConn() {
|
||||
if (this.closed) return;
|
||||
this.cb.onConnection(this.ing?.connected && this.egr?.connected ? "online" : "offline");
|
||||
}
|
||||
|
||||
private setView(view: string | null) { // TP-405
|
||||
this.view = view; this.vseq = 0; this.buffer.clear();
|
||||
this.cb.onViewChanged(view);
|
||||
}
|
||||
|
||||
private onMessage(env: any) {
|
||||
if (env.view !== this.view) return; // TP-401
|
||||
if (env.vseq <= this.vseq) return; // TP-402
|
||||
this.ep = Math.max(this.ep, env.ep);
|
||||
if (env.t === "snap") { // TP-403
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
this.drain();
|
||||
return;
|
||||
}
|
||||
if (this.vseq > 0 && env.vseq === this.vseq + 1) { // TP-404
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
this.drain();
|
||||
return;
|
||||
}
|
||||
this.buffer.set(env.vseq, env);
|
||||
if (this.buffer.size > 256) this.buffer.clear();
|
||||
const now = Date.now();
|
||||
if (now - this.resyncAt > 3000) { this.resyncAt = now; this.egr.emit("resync", { view: this.view, after_vseq: this.vseq }); }
|
||||
}
|
||||
|
||||
private drain() {
|
||||
for (const k of [...this.buffer.keys()]) if (k <= this.vseq) this.buffer.delete(k);
|
||||
while (this.buffer.has(this.vseq + 1)) {
|
||||
const env = this.buffer.get(this.vseq + 1);
|
||||
this.buffer.delete(this.vseq + 1);
|
||||
this.vseq = env.vseq;
|
||||
this.cb.onState(env);
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns the assigned cid; result arrives via onAck. */
|
||||
send(type: string, payload: unknown): number {
|
||||
const cid = ++this.cid;
|
||||
ss()?.setItem(`m3.cid.${this.tid}.${this.ci}`, String(cid));
|
||||
const known = this.view ? { ep: this.ep, view: this.view, vseq: this.vseq } : undefined;
|
||||
this.pending.set(cid, { type, payload, known });
|
||||
if (this.ing.connected) this.emitCmd(cid, type, payload, known);
|
||||
return cid;
|
||||
}
|
||||
|
||||
private emitCmd(cid: number, type: string, payload: unknown, known?: unknown) {
|
||||
this.ing.emit("cmd", { tid: this.tid, cid, type, payload, known }, (r: any) => {
|
||||
if (r && !r.ok) { this.pending.delete(cid); this.cb.onAck({ cid, status: "failed", code: r.code }); }
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.closed = true;
|
||||
this.ing?.close();
|
||||
this.egr?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Game-bundle side of the postMessage protocol (contract 43 §2). Messages are `{ m3: 1, type, ... }`.
|
||||
* The host origin is passed as `?host=<origin>` in the iframe URL and checked on every message (CS-20).
|
||||
*/
|
||||
export interface InitMsg {
|
||||
table_id: string; game_version: string; replay: boolean;
|
||||
me: { user_id: string; seat?: number; role: string; view: string | null };
|
||||
participants: { user_id: string; seat?: number; display: string; is_bot: boolean }[];
|
||||
options: Record<string, unknown>; locale: "fa" | "en"; dir: "rtl" | "ltr"; theme: Record<string, string>; server_offset_ms?: number;
|
||||
}
|
||||
export interface GameHandlers {
|
||||
onInit(init: InitMsg): void;
|
||||
onState(env: any): void;
|
||||
onAck?(a: { cid: number; status: string; code?: string; req_id?: number }): void;
|
||||
onViewChanged?(view: string | null): void;
|
||||
onCmdFailed?(reqId: number, code: string): void;
|
||||
}
|
||||
|
||||
export function connectHost(h: GameHandlers) {
|
||||
const hostOrigin = new URLSearchParams(location.search).get("host") ?? "*";
|
||||
const post = (msg: object) => window.parent.postMessage({ m3: 1, ...msg }, hostOrigin);
|
||||
let reqId = 0;
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.source !== window.parent || (hostOrigin !== "*" && e.origin !== hostOrigin)) return;
|
||||
const m = e.data;
|
||||
if (!m || m.m3 !== 1) return;
|
||||
switch (m.type) {
|
||||
case "init": h.onInit(m); post({ type: "ready" }); break;
|
||||
case "state": h.onState(m.env); break;
|
||||
case "ack": h.onAck?.(m); break;
|
||||
case "view_changed": h.onViewChanged?.(m.view); break;
|
||||
case "cmd_failed": h.onCmdFailed?.(m.req_id, m.code); break;
|
||||
}
|
||||
});
|
||||
post({ type: "loaded" });
|
||||
return {
|
||||
cmd(type: string, payload: unknown = {}) { const id = ++reqId; post({ type: "cmd", cmd_type: type, payload, req_id: id }); return id; },
|
||||
toast(text_fa: string, text_en: string, kind: "info" | "warn" | "error" = "info") { post({ type: "toast", text_fa, text_en, kind }); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./host.ts";
|
||||
export * from "./iframe.ts";
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Chess client — runs in sandboxed iframe.
|
||||
*/
|
||||
import "./style.css";
|
||||
import { connectHost, type InitMsg } from "@3miz/game-client/iframe";
|
||||
|
||||
let S: any = null;
|
||||
let init: InitMsg | null = null;
|
||||
const L = (fa: string, en: string) => (init?.locale === "en" ? en : fa);
|
||||
|
||||
const host = connectHost({
|
||||
onInit(m) {
|
||||
init = m;
|
||||
document.documentElement.lang = m.locale;
|
||||
document.documentElement.dir = m.dir;
|
||||
render();
|
||||
},
|
||||
onState(env) {
|
||||
if (env.t === "snap") {
|
||||
S = env.body;
|
||||
// Drop any half-finished local selection once the turn moves on (e.g. timeout auto-move).
|
||||
if (S.turn !== S.me) { selectedSquare = ""; pendingPromo = null; }
|
||||
render();
|
||||
}
|
||||
},
|
||||
onAck(a) {
|
||||
if (a.status === "rejected") host.toast("حرکت پذیرفته نشد", "Move not accepted", "warn");
|
||||
},
|
||||
});
|
||||
|
||||
function render() {
|
||||
const app = document.getElementById("app")!;
|
||||
if (!S) {
|
||||
app.innerHTML = `<div class="status">${L("در حال بارگذاری…", "Loading…")}</div>`;
|
||||
return;
|
||||
}
|
||||
const me = S.me;
|
||||
const myColor = me !== null && me !== undefined ? S.players[me]?.color : null;
|
||||
// Orientation: your own back rank is always at the bottom.
|
||||
// White (and observers) see rank 8 at the top, files a→h; Black sees rank 1 at the top, files h→a.
|
||||
const flipped = myColor === "b";
|
||||
const bySquare: Record<string, any> = {};
|
||||
for (const cell of S.board) bySquare[cell.square] = cell;
|
||||
const files = flipped ? [7, 6, 5, 4, 3, 2, 1, 0] : [0, 1, 2, 3, 4, 5, 6, 7];
|
||||
const ranks = flipped ? [0, 1, 2, 3, 4, 5, 6, 7] : [7, 6, 5, 4, 3, 2, 1, 0];
|
||||
const isMyTurn = S.phase === "play" && S.turn === me;
|
||||
const boardHtml = ranks.map((r) => files.map((f) => {
|
||||
const sq = String.fromCharCode(97 + f) + (r + 1);
|
||||
const cell = bySquare[sq] || { square: sq, type: null, color: null };
|
||||
const piece = cell.color ? `<span class="piece ${cell.color}">${pieceChar(cell.type, cell.color)}</span>` : "";
|
||||
const selectable = isMyTurn && !!myColor && cell.color === myColor;
|
||||
const isSelected = selectedSquare === sq;
|
||||
const enabled = !selectedSquare ? selectable : isMyTurn;
|
||||
// Standard colouring: a1 is dark; shade = parity of (file + rank).
|
||||
const shade = (f + r) % 2 === 0 ? "dark" : "light";
|
||||
return `<button class="cell ${shade}${isSelected ? " selected" : ""}" data-from="${sq}" data-color="${cell.color || "null"}" title="${sq}" ${enabled ? "" : "disabled"}>${piece}</button>`;
|
||||
}).join("")).join("");
|
||||
|
||||
const selHint = selectedSquare
|
||||
? `<div class="hint">${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}</div>`
|
||||
: ``;
|
||||
|
||||
const promoPicker = pendingPromo
|
||||
? `<div class="promo"><span>${pendingPromo.from} → ${pendingPromo.to}: ${L("ارتقا به", "Promote to")}</span>
|
||||
${["q", "r", "b", "n"].map((t) => `<button class="promo-btn" data-promo="${t}" title="${t}">${pieceChar(t, myColor)}</button>`).join("")}
|
||||
<button class="promo-cancel" data-cancel-promo="1">${L("لغو", "Cancel")}</button></div>`
|
||||
: ``;
|
||||
|
||||
const statusText = S.phase === "over"
|
||||
? (S.result_reason === "abandoned"
|
||||
? L("بازی رها شد", "Abandoned")
|
||||
: S.winner === null
|
||||
? (S.result_reason === "stalemate" ? L("پات — مساوی!", "Stalemate — draw!") : L("مساوی!", "Draw!"))
|
||||
: (S.result_reason === "checkmate"
|
||||
? `${S.players[S.winner]?.name} ${L("مات کرد! 🏆", "wins by checkmate 🏆")}`
|
||||
: `${S.players[S.winner]?.name} ${L("برنده شد 🏆", "wins 🏆")}`))
|
||||
: ((S.turn === me ? L("نوبت شماست", "Your turn") : `${L("نوبت", "Turn")}: ${S.players[S.turn]?.name}`) + (S.check ? ` · ${L("کیش!", "Check!")}` : ""));
|
||||
|
||||
app.innerHTML = `
|
||||
<div class="status">${statusText}</div>
|
||||
<div class="info">${S.moves_played !== undefined ? `حرکتها: ${S.moves_played}` : ""}</div>
|
||||
<div class="board">${boardHtml}</div>
|
||||
${selHint}
|
||||
${promoPicker}
|
||||
<div class="legend">${L("سفید حرکت میکند", "White moves")}</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function pieceChar(type: string | null, color: string | null): string {
|
||||
if (!type) return "";
|
||||
// White uses outline glyphs, black uses filled glyphs.
|
||||
const white: Record<string, string> = { k: "♔", q: "♕", r: "♖", b: "♗", n: "♘", p: "♙" };
|
||||
const black: Record<string, string> = { k: "♚", q: "♛", r: "♜", b: "♝", n: "♞", p: "♟" };
|
||||
return color === "b" ? (black[type] ?? "") : (white[type] ?? "");
|
||||
}
|
||||
|
||||
let selectedSquare = "";
|
||||
let pendingPromo: { from: string; to: string } | null = null;
|
||||
|
||||
document.addEventListener("click", (e) => {
|
||||
const el = e.target as HTMLElement;
|
||||
// Promotion choice buttons.
|
||||
const promoBtn = el.closest("[data-promo]") as HTMLElement | null;
|
||||
if (promoBtn && pendingPromo) {
|
||||
host.cmd("move", { from: pendingPromo.from, to: pendingPromo.to, promotion: promoBtn.dataset.promo });
|
||||
pendingPromo = null;
|
||||
selectedSquare = "";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
if (el.closest("[data-cancel-promo]")) {
|
||||
pendingPromo = null;
|
||||
render();
|
||||
return;
|
||||
}
|
||||
const b = el.closest("[data-from]") as HTMLElement | null;
|
||||
if (!b) return;
|
||||
const sq = b.dataset.from!;
|
||||
if (pendingPromo) return; // choose a promotion piece (or cancel) first
|
||||
if (selectedSquare) {
|
||||
if (selectedSquare === sq) {
|
||||
selectedSquare = "";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
// Clicking another of my own pieces switches the selection instead of sending a bad move.
|
||||
const clicked = (S?.board || []).find((c: any) => c.square === sq);
|
||||
const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null;
|
||||
if (clicked?.color && myColor && clicked.color === myColor) {
|
||||
selectedSquare = sq;
|
||||
render();
|
||||
return;
|
||||
}
|
||||
// Pawn stepping onto the last rank must promote: ask which piece first.
|
||||
const moving = (S?.board || []).find((c: any) => c.square === selectedSquare);
|
||||
const lastRank = myColor === "b" ? "1" : "8";
|
||||
if (moving?.type === "p" && sq[1] === lastRank) {
|
||||
pendingPromo = { from: selectedSquare, to: sq };
|
||||
selectedSquare = "";
|
||||
render();
|
||||
return;
|
||||
}
|
||||
host.cmd("move", { from: selectedSquare, to: sq });
|
||||
selectedSquare = "";
|
||||
render();
|
||||
} else {
|
||||
// Select one of my own pieces when it is my turn.
|
||||
const cellData = (S?.board || []).find((c: any) => c.square === sq);
|
||||
const myColor = S?.me !== null && S?.me !== undefined ? S?.players[S.me]?.color : null;
|
||||
const isMyColor = !!myColor && cellData?.color === myColor;
|
||||
if (isMyColor && S?.phase === "play" && S?.turn === S?.me) {
|
||||
selectedSquare = sq;
|
||||
render();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
render();
|
||||
@@ -0,0 +1,18 @@
|
||||
html, body { margin: 0; height: 100%; background: #1a1a2e; color: #f1f3f5; font-family: system-ui, sans-serif; }
|
||||
#app { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; padding: 16px; }
|
||||
.status { font-size: 22px; font-weight: 700; }
|
||||
.info { font-size: 14px; opacity: 0.8; }
|
||||
.board { display: grid; grid-template-columns: repeat(8, min(10vmin, 60px)); grid-template-rows: repeat(8, min(10vmin, 60px)); gap: 1px; border: 3px solid #c5a065; border-radius: 4px; overflow: hidden; }
|
||||
.cell { aspect-ratio: 1; font-size: min(6vmin, 36px); font-weight: 800; border: 0; border-radius: 0; color: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center; }
|
||||
/* Square colours are assigned per square in JS (a1 is dark), so orientation flips keep them correct. */
|
||||
.cell.light { background: #d18b47; }
|
||||
.cell.dark { background: #8b5e3c; }
|
||||
.cell:disabled { cursor: default; opacity: 0.85; }
|
||||
.cell.selected { outline: 3px solid #ffd43b; outline-offset: -3px; }
|
||||
.hint { font-size: 14px; font-weight: 600; color: #ffd43b; }
|
||||
.promo { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; background: #2b2b45; border-radius: 10px; padding: 8px 12px; }
|
||||
.promo-btn { font-size: 30px; line-height: 1; border: 0; border-radius: 8px; background: #d18b47; color: #1a1a2e; cursor: pointer; padding: 4px 10px; }
|
||||
.promo-cancel { font-size: 13px; border: 0; border-radius: 8px; background: transparent; color: #f1f3f5; cursor: pointer; padding: 6px 8px; }
|
||||
.cell[data-color="w"] { color: #f0f0f0; text-shadow: 1px 1px 2px #333; }
|
||||
.cell[data-color="b"] { color: #222; text-shadow: 1px 1px 2px #ddd; }
|
||||
.legend { font-size: 12px; opacity: 0.7; }
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from "vite";
|
||||
import { resolve } from "path";
|
||||
export default defineConfig({
|
||||
base: "./",
|
||||
resolve: {
|
||||
alias: {
|
||||
"@3miz/game-client/iframe": resolve(__dirname, "sdk-src/iframe.ts"),
|
||||
},
|
||||
},
|
||||
build: { outDir: "dist", assetsInlineLimit: 0 },
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
html,body{margin:0;height:100%;background:#1a1a2e;color:#f1f3f5;font-family:system-ui,sans-serif}#app{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:16px}.status{font-size:22px;font-weight:700}.info{font-size:14px;opacity:.8}.board{display:grid;grid-template-columns:repeat(8,min(10vmin,60px));grid-template-rows:repeat(8,min(10vmin,60px));gap:1px;border:3px solid #c5a065;border-radius:4px;overflow:hidden}.cell{aspect-ratio:1;font-size:min(6vmin,36px);font-weight:800;border:0;border-radius:0;color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center}.cell.light{background:#d18b47}.cell.dark{background:#8b5e3c}.cell:disabled{cursor:default;opacity:.85}.cell.selected{outline:3px solid #ffd43b;outline-offset:-3px}.hint{font-size:14px;font-weight:600;color:#ffd43b}.promo{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:700;background:#2b2b45;border-radius:10px;padding:8px 12px}.promo-btn{font-size:30px;line-height:1;border:0;border-radius:8px;background:#d18b47;color:#1a1a2e;cursor:pointer;padding:4px 10px}.promo-cancel{font-size:13px;border:0;border-radius:8px;background:transparent;color:#f1f3f5;cursor:pointer;padding:6px 8px}.cell[data-color=w]{color:#f0f0f0;text-shadow:1px 1px 2px #333}.cell[data-color=b]{color:#222;text-shadow:1px 1px 2px #ddd}.legend{font-size:12px;opacity:.7}
|
||||
@@ -0,0 +1,10 @@
|
||||
(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const t of document.querySelectorAll('link[rel="modulepreload"]'))d(t);new MutationObserver(t=>{for(const n of t)if(n.type==="childList")for(const s of n.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&d(s)}).observe(document,{childList:!0,subtree:!0});function a(t){const n={};return t.integrity&&(n.integrity=t.integrity),t.referrerPolicy&&(n.referrerPolicy=t.referrerPolicy),t.crossOrigin==="use-credentials"?n.credentials="include":t.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function d(t){if(t.ep)return;t.ep=!0;const n=a(t);fetch(t.href,n)}})();function I(o){const r=new URLSearchParams(location.search).get("host")??"*",a=t=>window.parent.postMessage({m3:1,...t},r);let d=0;return window.addEventListener("message",t=>{var s,l,u;if(t.source!==window.parent||r!=="*"&&t.origin!==r)return;const n=t.data;if(!(!n||n.m3!==1))switch(n.type){case"init":o.onInit(n),a({type:"ready"});break;case"state":o.onState(n.env);break;case"ack":(s=o.onAck)==null||s.call(o,n);break;case"view_changed":(l=o.onViewChanged)==null||l.call(o,n.view);break;case"cmd_failed":(u=o.onCmdFailed)==null||u.call(o,n.req_id,n.code);break}}),a({type:"loaded"}),{cmd(t,n={}){const s=++d;return a({type:"cmd",cmd_type:t,payload:n,req_id:s}),s},toast(t,n,s="info"){a({type:"toast",text_fa:t,text_en:n,kind:s})}}}let e=null,w=null;const i=(o,r)=>(w==null?void 0:w.locale)==="en"?r:o,k=I({onInit(o){w=o,document.documentElement.lang=o.locale,document.documentElement.dir=o.dir,p()},onState(o){o.t==="snap"&&(e=o.body,e.turn!==e.me&&(c="",m=null),p())},onAck(o){o.status==="rejected"&&k.toast("حرکت پذیرفته نشد","Move not accepted","warn")}});function p(){var q,h,C,L;const o=document.getElementById("app");if(!e){o.innerHTML=`<div class="status">${i("در حال بارگذاری…","Loading…")}</div>`;return}const r=e.me,a=r!=null?(q=e.players[r])==null?void 0:q.color:null,d=a==="b",t={};for(const f of e.board)t[f.square]=f;const n=d?[7,6,5,4,3,2,1,0]:[0,1,2,3,4,5,6,7],s=d?[0,1,2,3,4,5,6,7]:[7,6,5,4,3,2,1,0],l=e.phase==="play"&&e.turn===r,u=s.map(f=>n.map(_=>{const g=String.fromCharCode(97+_)+(f+1),y=t[g]||{type:null,color:null},P=y.color?`<span class="piece ${y.color}">${M(y.type,y.color)}</span>`:"",O=l&&!!a&&y.color===a,E=c===g,H=c?l:O;return`<button class="cell ${(_+f)%2===0?"dark":"light"}${E?" selected":""}" data-from="${g}" data-color="${y.color||"null"}" title="${g}" ${H?"":"disabled"}>${P}</button>`}).join("")).join(""),b=c?`<div class="hint">${i("مبدا","From")}: ${c} — ${i("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)","click a target square (click it again to cancel)")}</div>`:"",$=m?`<div class="promo"><span>${m.from} → ${m.to}: ${i("ارتقا به","Promote to")}</span>
|
||||
${["q","r","b","n"].map(f=>`<button class="promo-btn" data-promo="${f}" title="${f}">${M(f,a)}</button>`).join("")}
|
||||
<button class="promo-cancel" data-cancel-promo="1">${i("لغو","Cancel")}</button></div>`:"",v=e.phase==="over"?e.result_reason==="abandoned"?i("بازی رها شد","Abandoned"):e.winner===null?e.result_reason==="stalemate"?i("پات — مساوی!","Stalemate — draw!"):i("مساوی!","Draw!"):e.result_reason==="checkmate"?`${(h=e.players[e.winner])==null?void 0:h.name} ${i("مات کرد! 🏆","wins by checkmate 🏆")}`:`${(C=e.players[e.winner])==null?void 0:C.name} ${i("برنده شد 🏆","wins 🏆")}`:(e.turn===r?i("نوبت شماست","Your turn"):`${i("نوبت","Turn")}: ${(L=e.players[e.turn])==null?void 0:L.name}`)+(e.check?` · ${i("کیش!","Check!")}`:"");o.innerHTML=`
|
||||
<div class="status">${v}</div>
|
||||
<div class="info">${e.moves_played!==void 0?`حرکتها: ${e.moves_played}`:""}</div>
|
||||
<div class="board">${u}</div>
|
||||
${b}
|
||||
${$}
|
||||
<div class="legend">${i("سفید حرکت میکند","White moves")}</div>
|
||||
`}function M(o,r){return o?r==="b"?{k:"♚",q:"♛",r:"♜",b:"♝",n:"♞",p:"♟"}[o]??"":{k:"♔",q:"♕",r:"♖",b:"♗",n:"♘",p:"♙"}[o]??"":""}let c="",m=null;document.addEventListener("click",o=>{var n,s;const r=o.target,a=r.closest("[data-promo]");if(a&&m){k.cmd("move",{from:m.from,to:m.to,promotion:a.dataset.promo}),m=null,c="",p();return}if(r.closest("[data-cancel-promo]")){m=null,p();return}const d=r.closest("[data-from]");if(!d)return;const t=d.dataset.from;if(!m)if(c){if(c===t){c="",p();return}const l=((e==null?void 0:e.board)||[]).find(v=>v.square===t),u=(e==null?void 0:e.me)!==null&&(e==null?void 0:e.me)!==void 0?(n=e==null?void 0:e.players[e.me])==null?void 0:n.color:null;if(l!=null&&l.color&&u&&l.color===u){c=t,p();return}const b=((e==null?void 0:e.board)||[]).find(v=>v.square===c),$=u==="b"?"1":"8";if((b==null?void 0:b.type)==="p"&&t[1]===$){m={from:c,to:t},c="",p();return}k.cmd("move",{from:c,to:t}),c="",p()}else{const l=((e==null?void 0:e.board)||[]).find($=>$.square===t),u=(e==null?void 0:e.me)!==null&&(e==null?void 0:e.me)!==void 0?(s=e==null?void 0:e.players[e.me])==null?void 0:s.color:null;!!u&&(l==null?void 0:l.color)===u&&(e==null?void 0:e.phase)==="play"&&(e==null?void 0:e.turn)===(e==null?void 0:e.me)&&(c=t,p())}});p();
|
||||
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html lang="fa" dir="rtl">
|
||||
<head>
|
||||
<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-D5ThqQkE.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-BquRMbQ0.css">
|
||||
</head>
|
||||
<body><div id="app">…</div></body>
|
||||
</html>
|
||||
@@ -0,0 +1,8 @@
|
||||
# Chess — tips for reviewers and developers
|
||||
|
||||
- Check: moves leaving your own king in check are rejected (answer by moving the king, capturing, or blocking);
|
||||
checkmate (no legal reply) wins, stalemate (no legal move while safe) draws. No pin filtering beyond this.
|
||||
- Special moves: castling (rights decay on king/rook moves and corner-rook captures, no castling through check),
|
||||
en passant (one-move window after a double step), promotion (choice q/r/b/n in the move command, queen default for bots/timeouts).
|
||||
- Client orients the board around your colour (white: a8 top-left; black: h1 top-left); a1 is always dark.
|
||||
- Server is deterministic (time only via ctx.now, randomness via ctx.rng); bots pick random legal moves.
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"bundle_format": 1,
|
||||
"kind": "source",
|
||||
"game_id": "chess",
|
||||
"version": "1.0.0",
|
||||
"server": { "entry": "server/main.ts" },
|
||||
"client": { "entry": "index.html" },
|
||||
"catalog": {
|
||||
"slug": "chess",
|
||||
"title": { "fa": "شطرنج", "en": "Chess" },
|
||||
"tagline": { "fa": "بازی استراتژیک دو نفره با مهرههای کلاسیک.", "en": "Classic two-player strategy game with traditional pieces." },
|
||||
"description": { "fa": "شطرنج استاندارد برای دو بازیکن. مهرهها را طبق قوانین حرکت دهید و شاه حریف را مات کنید.", "en": "Standard chess for two players. Move pieces according to rules and checkmate the opponent's king." },
|
||||
"icon": "♟",
|
||||
"color": "#2d1b0e",
|
||||
"aliases": ["chess", "shatranj", "شطرنج"]
|
||||
},
|
||||
"instances": { "suggested": 2 },
|
||||
"authors": ["3miz team"],
|
||||
"notes": { "fa": "نسخه اولیه شطرنج برای پلتفرم سهمیز.", "en": "Initial chess release for the 3miz platform." }
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"manifest_version": 1,
|
||||
"game_id": "chess",
|
||||
"version": "1.0.0",
|
||||
"protocol": "socketio",
|
||||
"protocol_version": 1,
|
||||
"title": {
|
||||
"fa": "شطرنج",
|
||||
"en": "Chess"
|
||||
},
|
||||
"description": {
|
||||
"fa": "بازی استراتژیک دو نفره با مهرههای کلاسیک. شاه حریف را مات کنید.",
|
||||
"en": "A strategic two-player game with classic pieces. Checkmate the opponent's king."
|
||||
},
|
||||
"aliases": ["chess", "shatranj", "شطرنج"],
|
||||
"players": {
|
||||
"min": 2,
|
||||
"max": 2
|
||||
},
|
||||
"observers": {
|
||||
"allowed": true,
|
||||
"max": 50,
|
||||
"commands": [],
|
||||
"omniscient_broadcast_delay_ms": null
|
||||
},
|
||||
"estimated_duration_min": 15,
|
||||
"turn_based": true,
|
||||
"rated": false,
|
||||
"bots": {
|
||||
"supported": true,
|
||||
"levels": ["easy", "basic", "hard"]
|
||||
},
|
||||
"fog_of_war": false,
|
||||
"deterministic": true,
|
||||
"encoding": "json",
|
||||
"modes": [
|
||||
{
|
||||
"id": "classic",
|
||||
"title": {
|
||||
"fa": "کلاسیک",
|
||||
"en": "Classic"
|
||||
},
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"options": [
|
||||
{
|
||||
"id": "turn_ms",
|
||||
"type": "int",
|
||||
"min": 10000,
|
||||
"max": 300000,
|
||||
"step": 5000,
|
||||
"default": 60000,
|
||||
"title": {
|
||||
"fa": "زمان هر نوبت",
|
||||
"en": "Turn time"
|
||||
},
|
||||
"rated_safe": true
|
||||
}
|
||||
],
|
||||
"cosmetic_slots": [],
|
||||
"stats": [
|
||||
{
|
||||
"key": "moves_played",
|
||||
"kind": "counter",
|
||||
"public": true,
|
||||
"title": {
|
||||
"fa": "حرکتهای انجام شده",
|
||||
"en": "Moves played"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "captures",
|
||||
"kind": "counter",
|
||||
"public": true,
|
||||
"title": {
|
||||
"fa": "مهرههای گرفته شده",
|
||||
"en": "Captures"
|
||||
}
|
||||
}
|
||||
],
|
||||
"achievements": [],
|
||||
"client": {
|
||||
"entry": "https://g.3miz.ir/chess/1.0.0/index.html",
|
||||
"integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
|
||||
"aspect": "1:1",
|
||||
"min_width_px": 320,
|
||||
"supports_portrait": true
|
||||
},
|
||||
"server": {
|
||||
"image": "registry.3miz.ir/games/chess:1.0.0",
|
||||
"max_tables_per_instance": 500,
|
||||
"checkpoint_every_inputs": 20,
|
||||
"snapshot_every_messages": 50,
|
||||
"resources": {
|
||||
"cpu_millicores": 150,
|
||||
"memory_mib": 128
|
||||
}
|
||||
},
|
||||
"seating": {
|
||||
"turn_order": true
|
||||
},
|
||||
"auto_activate_minor": false,
|
||||
"communication_commands": []
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Chess bot — basic random / tactical bot.
|
||||
*/
|
||||
import type { Rng } from "@3miz/game-server-sdk";
|
||||
import { isValidMove, type State } from "./game.ts";
|
||||
|
||||
export function decideBot(s: State, seat: number, rng: Rng): { fromIdx: number; toIdx: number } | null {
|
||||
const player = s.players[seat];
|
||||
if (!player) return null;
|
||||
const color = player.color;
|
||||
const moves: { from: number; to: number }[] = [];
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const piece = s.board[i];
|
||||
if (!piece || piece.color !== color) continue;
|
||||
for (let to = 0; to < 64; to++) {
|
||||
if (isValidMove(s, i, to, seat)) {
|
||||
moves.push({ from: i, to });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (moves.length === 0) return null;
|
||||
const pick = moves[rng.int(moves.length)];
|
||||
return { fromIdx: pick.from, toIdx: pick.to };
|
||||
}
|
||||
+543
@@ -0,0 +1,543 @@
|
||||
/**
|
||||
* Chess — standard 2-player strategy game.
|
||||
* Simplified rules: all standard pieces, basic moves, captures, checkmate detection.
|
||||
*/
|
||||
import type { CreateTable, Ctx, GameDef, Input, InitCtx } from "@3miz/game-server-sdk";
|
||||
import { firstSeat } from "@3miz/game-server-sdk";
|
||||
import manifest from "../manifest.json" with { type: "json" };
|
||||
import { decideBot } from "./bot.ts";
|
||||
|
||||
type Color = "w" | "b";
|
||||
type PieceType = "p" | "r" | "n" | "b" | "q" | "k";
|
||||
|
||||
export interface Piece {
|
||||
type: PieceType;
|
||||
color: Color;
|
||||
}
|
||||
|
||||
export interface State {
|
||||
players: { seat: number; user_id: string; name: string; color: Color; bot: boolean; level: string; conns: string[]; left: boolean }[];
|
||||
board: (Piece | null)[]; // 64 squares: index 0 = a1, 7 = h1, 8 = a2 ... (file = (i%8)+1, rank = Math.floor(i/8)+1)
|
||||
turn: number; // seat index of player whose turn it is (0 or 1)
|
||||
phase: "play" | "over";
|
||||
winner: number | null; // winning seat, or null for draw
|
||||
result_reason: string;
|
||||
turn_ms: number;
|
||||
timer_n: number;
|
||||
timer_id: string | null;
|
||||
deadline: number | null;
|
||||
bot_timer: string | null;
|
||||
moves_played: number;
|
||||
captures: number;
|
||||
// Castling rights decay as kings/rooks move or corner rooks are captured.
|
||||
rights: { wk: boolean; wq: boolean; bk: boolean; bq: boolean };
|
||||
// En-passant window: index of the skipped square after a pawn double step, else null.
|
||||
// Valid only on the immediately following move.
|
||||
ep: number | null;
|
||||
}
|
||||
|
||||
function file(i: number) { return String.fromCharCode(97 + (i % 8)); } // a-h
|
||||
function rank(i: number) { return Math.floor(i / 8) + 1; } // 1-8
|
||||
function squareName(i: number) { return file(i) + rank(i); }
|
||||
function squareIndex(name: string): number {
|
||||
const f = name.charCodeAt(0) - 97;
|
||||
const r = parseInt(name[1], 10) - 1;
|
||||
return r * 8 + f;
|
||||
}
|
||||
|
||||
const STARTING_FEN = [
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",
|
||||
];
|
||||
|
||||
function parseFEN(boardStr: string): (Piece | null)[] {
|
||||
const b: (Piece | null)[] = Array(64).fill(null);
|
||||
const rows = boardStr.split("/");
|
||||
for (let r = 0; r < 8; r++) {
|
||||
const rowChars = rows[7 - r].split("");
|
||||
let col = 0;
|
||||
for (const ch of rowChars) {
|
||||
if (ch >= "1" && ch <= "8") {
|
||||
col += parseInt(ch, 10);
|
||||
} else {
|
||||
const color = ch === ch.toUpperCase() ? "w" : "b";
|
||||
const type: PieceType = ch.toLowerCase() as PieceType;
|
||||
b[r * 8 + col] = { type, color };
|
||||
col++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
function initialBoard(): (Piece | null)[] {
|
||||
return parseFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
|
||||
}
|
||||
|
||||
function isWhitePiece(p: Piece | null): boolean {
|
||||
return p !== null && p.color === "w";
|
||||
}
|
||||
function isBlackPiece(p: Piece | null): boolean {
|
||||
return p !== null && p.color === "b";
|
||||
}
|
||||
|
||||
// Pure movement geometry: can a piece of `moverColor` on `from` move to `to`?
|
||||
// No turn/phase/seat checks here, so check detection can reuse it for either side.
|
||||
// `allowCastling` is false when probing attacks (a king's two-square stride is a move, not an attack).
|
||||
export function pieceCanMove(s: State, from: number, to: number, moverColor: Color, allowCastling = true): boolean {
|
||||
const board = s.board;
|
||||
const p = board[from];
|
||||
if (!p || p.color !== moverColor) return false;
|
||||
if (from === to) return false;
|
||||
|
||||
const target = board[to];
|
||||
if (target && target.color === p.color) return false; // can't capture own piece
|
||||
|
||||
const dx = (to % 8) - (from % 8);
|
||||
const dy = Math.floor(to / 8) - Math.floor(from / 8);
|
||||
|
||||
switch (p.type) {
|
||||
case "p": { // pawn: white advances toward rank 8 (dy +1), black toward rank 1 (dy -1)
|
||||
const direction = p.color === "w" ? 1 : -1;
|
||||
const startRow = p.color === "w" ? 1 : 6;
|
||||
const fromRow = Math.floor(from / 8);
|
||||
// Forward (also the promotion push; the promotion piece rides in the command)
|
||||
if (dx === 0 && dy === direction && !target) return true;
|
||||
// Double step from start (opens the en-passant window behind the pawn)
|
||||
if (dx === 0 && dy === direction * 2 && fromRow === startRow && !target && !board[from + direction * 8]) return true;
|
||||
// Capture diagonally
|
||||
if (Math.abs(dx) === 1 && dy === direction && target && target.color !== p.color) return true;
|
||||
// En passant: diagonal stride onto the marked empty square
|
||||
if (Math.abs(dx) === 1 && dy === direction && !target && to === s.ep) return true;
|
||||
return false;
|
||||
}
|
||||
case "r": { // rook
|
||||
if (from === to) return false;
|
||||
if (from % 8 === to % 8 || Math.floor(from / 8) === Math.floor(to / 8)) {
|
||||
const stepX = Math.sign(to % 8 - from % 8);
|
||||
const stepY = Math.sign(Math.floor(to / 8) - Math.floor(from / 8));
|
||||
let cx = from % 8 + stepX;
|
||||
let cy = Math.floor(from / 8) + stepY;
|
||||
while (cx !== to % 8 || cy !== Math.floor(to / 8)) {
|
||||
const idx = cy * 8 + cx;
|
||||
if (board[idx]) return false;
|
||||
cx += stepX;
|
||||
cy += stepY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case "n": { // knight
|
||||
const x = Math.abs(dx);
|
||||
const y = Math.abs(dy);
|
||||
return (x === 2 && y === 1) || (x === 1 && y === 2);
|
||||
}
|
||||
case "b": { // bishop
|
||||
if (Math.abs(dx) !== Math.abs(dy) || from === to) return false;
|
||||
const stepX = Math.sign(dx);
|
||||
const stepY = Math.sign(dy);
|
||||
let cx = from % 8 + stepX;
|
||||
let cy = Math.floor(from / 8) + stepY;
|
||||
while (cx !== to % 8 || cy !== Math.floor(to / 8)) {
|
||||
const idx = cy * 8 + cx;
|
||||
if (board[idx]) return false;
|
||||
cx += stepX;
|
||||
cy += stepY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "q": { // queen (rook + bishop)
|
||||
if (from === to) return false;
|
||||
// Rook-like
|
||||
if (from % 8 === to % 8 || Math.floor(from / 8) === Math.floor(to / 8)) {
|
||||
const stepX = Math.sign(to % 8 - from % 8);
|
||||
const stepY = Math.sign(Math.floor(to / 8) - Math.floor(from / 8));
|
||||
let cx = from % 8 + stepX;
|
||||
let cy = Math.floor(from / 8) + stepY;
|
||||
while (cx !== to % 8 || cy !== Math.floor(to / 8)) {
|
||||
const idx = cy * 8 + cx;
|
||||
if (board[idx]) return false;
|
||||
cx += stepX;
|
||||
cy += stepY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Bishop-like
|
||||
if (Math.abs(dx) === Math.abs(dy)) {
|
||||
const stepX = Math.sign(dx);
|
||||
const stepY = Math.sign(dy);
|
||||
let cx = from % 8 + stepX;
|
||||
let cy = Math.floor(from / 8) + stepY;
|
||||
while (cx !== to % 8 || cy !== Math.floor(to / 8)) {
|
||||
const idx = cy * 8 + cx;
|
||||
if (board[idx]) return false;
|
||||
cx += stepX;
|
||||
cy += stepY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case "k": { // king: one square any way, or the two-square castling stride
|
||||
if (Math.abs(dx) <= 1 && Math.abs(dy) <= 1 && !(dx === 0 && dy === 0)) return true;
|
||||
// Castling: the king strides two squares sideways from its home square;
|
||||
// the corner rook is dragged along in applyMove. Destination must be empty.
|
||||
if (allowCastling && dy === 0 && Math.abs(dx) === 2 && !target) {
|
||||
return canCastle(s, from, to, p.color);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Castling legality: rights intact, king and rook home, path clear,
|
||||
// king neither in check nor crossing an attacked square.
|
||||
function canCastle(s: State, from: number, to: number, color: Color): boolean {
|
||||
const home = color === "w" ? 4 : 60; // e1 / e8
|
||||
if (from !== home) return false;
|
||||
const kingside = to > from;
|
||||
const r = s.rights;
|
||||
if (color === "w" ? (kingside ? !r.wk : !r.wq) : (kingside ? !r.bk : !r.bq)) return false;
|
||||
const wantTo = color === "w" ? (kingside ? 6 : 2) : (kingside ? 62 : 58);
|
||||
if (to !== wantTo) return false;
|
||||
const rookFrom = color === "w" ? (kingside ? 7 : 0) : (kingside ? 63 : 56);
|
||||
const rook = s.board[rookFrom];
|
||||
if (!rook || rook.type !== "r" || rook.color !== color) return false;
|
||||
// Squares between king and rook (destination already known empty): kingside one, queenside two.
|
||||
const between = kingside ? [from + 1] : [from - 1, from - 3];
|
||||
for (const q of between) if (s.board[q]) return false;
|
||||
const enemy: Color = color === "w" ? "b" : "w";
|
||||
const transit = kingside ? [from, from + 1, to] : [from, from - 1, to];
|
||||
for (const q of transit) if (isSquareAttacked(s, q, enemy)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function isSquareAttacked(s: State, square: number, attacker: Color): boolean {
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const pc = s.board[i];
|
||||
if (!pc || pc.color !== attacker) continue;
|
||||
if (pieceCanMove(s, i, square, attacker, false)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// A seat's move is valid when it is their turn, the geometry allows it, and the
|
||||
// king is safe afterwards (simplified: no pin / discovered-check filtering beyond this rule).
|
||||
export function isValidMove(state: State, from: number, to: number, seat: number): boolean {
|
||||
const player = state.players[seat];
|
||||
if (!player) return false;
|
||||
if (state.phase !== "play") return false;
|
||||
if (state.turn !== seat) return false;
|
||||
return isMoveLegalFor(state, from, to, player.color);
|
||||
}
|
||||
|
||||
// Geometry + king safety, without any turn/phase/seat checks.
|
||||
function isMoveLegalFor(s: State, from: number, to: number, moverColor: Color): boolean {
|
||||
if (!pieceCanMove(s, from, to, moverColor)) return false;
|
||||
return !wouldLeaveInCheck(s, from, to, moverColor);
|
||||
}
|
||||
|
||||
// Would `moverColor`'s king be under attack after this move? Simulates the move
|
||||
// (including castling rook drag, en-passant victim, promotion blocking) on a board copy.
|
||||
export function wouldLeaveInCheck(s: State, from: number, to: number, moverColor: Color): boolean {
|
||||
const b = s.board.slice();
|
||||
const moving = b[from];
|
||||
if (!moving) return false;
|
||||
if (moving.type === "p" && to === s.ep && !b[to]) {
|
||||
b[to + (moving.color === "w" ? -8 : 8)] = null;
|
||||
}
|
||||
b[from] = null;
|
||||
b[to] = moving; // promotion changes the piece kind, never its blocking footprint
|
||||
if (moving.type === "k" && Math.abs((to % 8) - (from % 8)) === 2) {
|
||||
const rookFrom = to > from ? to + 1 : to - 2;
|
||||
const rookTo = to > from ? to - 1 : to + 1;
|
||||
b[rookTo] = b[rookFrom];
|
||||
b[rookFrom] = null;
|
||||
}
|
||||
const kingSquare = b.findIndex((pc) => pc && pc.type === "k" && pc.color === moverColor);
|
||||
if (kingSquare === -1) return false;
|
||||
const probe: State = { ...s, board: b };
|
||||
return isSquareAttacked(probe, kingSquare, moverColor === "w" ? "b" : "w");
|
||||
}
|
||||
|
||||
function hasAnyLegalMove(s: State, color: Color): boolean {
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const pc = s.board[i];
|
||||
if (!pc || pc.color !== color) continue;
|
||||
for (let to = 0; to < 64; to++) {
|
||||
if (isMoveLegalFor(s, i, to, color)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isKingInCheck(state: State, color: Color): boolean {
|
||||
const kingSquare = state.board.findIndex((p) => p && p.type === "k" && p.color === color);
|
||||
if (kingSquare === -1) return false;
|
||||
return isSquareAttacked(state, kingSquare, color === "w" ? "b" : "w");
|
||||
}
|
||||
|
||||
export function isCheckmate(state: State, color: Color): boolean {
|
||||
// In check with no legal reply (no king flight, capture, or block): mate.
|
||||
return isKingInCheck(state, color) && !hasAnyLegalMove(state, color);
|
||||
}
|
||||
|
||||
export function isStalemate(state: State, color: Color): boolean {
|
||||
// Not in check but no legal move at all: draw.
|
||||
return state.phase === "play" && !isKingInCheck(state, color) && !hasAnyLegalMove(state, color);
|
||||
}
|
||||
|
||||
function setDeadline(s: State, t: { now: number; setTimer(id: string, due: number): void; clearTimer?(id: string): void }) {
|
||||
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;
|
||||
t.setTimer(s.timer_id, s.deadline);
|
||||
}
|
||||
|
||||
function scheduleBot(s: State, t: { now: number; setTimer(id: string, due: number): void; clearTimer?(id: string): void }) {
|
||||
const p = s.players[s.turn];
|
||||
if (s.phase !== "play" || !p.bot || s.bot_timer) return;
|
||||
s.bot_timer = `bot-${s.timer_n}`;
|
||||
t.setTimer(s.bot_timer, t.now + 600);
|
||||
}
|
||||
|
||||
export const PROMOTIONS: PieceType[] = ["q", "r", "b", "n"];
|
||||
|
||||
function applyMove(state: State, from: number, to: number, seat: number, promotion?: PieceType) {
|
||||
const moving = state.board[from];
|
||||
const captured = state.board[to];
|
||||
// En passant: the landing square is empty but the window is open — lift the bypassed pawn.
|
||||
if (moving && moving.type === "p" && to === state.ep && !captured) {
|
||||
const victim = to + (moving.color === "w" ? -8 : 8);
|
||||
state.board[victim] = null;
|
||||
state.captures++;
|
||||
}
|
||||
state.board[from] = null;
|
||||
let placed = moving;
|
||||
if (moving && moving.type === "p") {
|
||||
const lastRow = moving.color === "w" ? 7 : 0;
|
||||
if (Math.floor(to / 8) === lastRow) placed = { type: promotion ?? "q", color: moving.color };
|
||||
}
|
||||
// Castling: the king's two-square stride drags the corner rook over it.
|
||||
if (moving && moving.type === "k" && Math.abs((to % 8) - (from % 8)) === 2) {
|
||||
const rookFrom = to > from ? to + 1 : to - 2;
|
||||
const rookTo = to > from ? to - 1 : to + 1;
|
||||
state.board[rookTo] = state.board[rookFrom];
|
||||
state.board[rookFrom] = null;
|
||||
}
|
||||
state.board[to] = placed;
|
||||
if (captured) state.captures++;
|
||||
state.moves_played++;
|
||||
// Castling rights decay when kings/rooks move or corner rooks are taken.
|
||||
if (moving) {
|
||||
if (moving.type === "k") {
|
||||
if (moving.color === "w") { state.rights.wk = false; state.rights.wq = false; }
|
||||
else { state.rights.bk = false; state.rights.bq = false; }
|
||||
}
|
||||
if (moving.type === "r") {
|
||||
if (from === 0) state.rights.wq = false;
|
||||
if (from === 7) state.rights.wk = false;
|
||||
if (from === 56) state.rights.bq = false;
|
||||
if (from === 63) state.rights.bk = false;
|
||||
}
|
||||
}
|
||||
if (captured && captured.type === "r") {
|
||||
if (to === 0) state.rights.wq = false;
|
||||
if (to === 7) state.rights.wk = false;
|
||||
if (to === 56) state.rights.bq = false;
|
||||
if (to === 63) state.rights.bk = false;
|
||||
}
|
||||
// The en-passant window only survives the move immediately after a double step.
|
||||
state.ep = null;
|
||||
if (moving && moving.type === "p" && Math.abs(to - from) === 16) {
|
||||
state.ep = from + (moving.color === "w" ? 8 : -8);
|
||||
}
|
||||
state.turn = 1 - seat; // switch to other seat
|
||||
}
|
||||
|
||||
function finish(s: State, ctx: Ctx, winner: number | null, reason: string = "completed") {
|
||||
s.phase = "over";
|
||||
s.winner = winner;
|
||||
s.result_reason = reason;
|
||||
s.deadline = null;
|
||||
if (s.timer_id) ctx.clearTimer(s.timer_id);
|
||||
s.timer_id = null;
|
||||
ctx.finish({
|
||||
reason: reason === "abandoned" ? "abandoned" : "completed",
|
||||
standings: s.players.map((p) => ({
|
||||
user_id: p.user_id,
|
||||
seat: p.seat,
|
||||
rank: winner === null || p.seat === winner ? 1 : 2,
|
||||
score: p.seat === winner ? 1 : 0,
|
||||
...(p.bot ? { is_bot: true } : {}),
|
||||
...(p.left ? { abandoned: true } : {}),
|
||||
})),
|
||||
stats: {
|
||||
[s.players[0].user_id]: { moves_played: s.moves_played, captures: s.captures },
|
||||
[s.players[1].user_id]: { moves_played: s.moves_played, captures: s.captures },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const chess: GameDef<State> = {
|
||||
manifest,
|
||||
validateModes: (modes) =>
|
||||
modes.every((m) => m === "classic") ? [] : [{ 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 s: State = {
|
||||
players: seats.map((p, i) => ({
|
||||
seat: i,
|
||||
user_id: p.user_id,
|
||||
name: p.display.name,
|
||||
color: i === first ? "w" : "b",
|
||||
bot: p.kind === "bot",
|
||||
level: p.bot_level ?? "basic",
|
||||
conns: [],
|
||||
left: false,
|
||||
})),
|
||||
board: initialBoard(),
|
||||
turn: first,
|
||||
phase: "play",
|
||||
winner: null,
|
||||
result_reason: "",
|
||||
turn_ms: typeof create.options.turn_ms === "number" ? (create.options.turn_ms as number) : 60000,
|
||||
timer_n: 0,
|
||||
timer_id: null,
|
||||
deadline: null,
|
||||
bot_timer: null,
|
||||
moves_played: 0,
|
||||
captures: 0,
|
||||
rights: { wk: true, wq: true, bk: true, bq: true },
|
||||
ep: null,
|
||||
};
|
||||
setDeadline(s, ictx);
|
||||
scheduleBot(s, ictx);
|
||||
return s;
|
||||
},
|
||||
apply(s: State, input: Input, ctx: Ctx) {
|
||||
const p = s.players.find((x) => x.user_id === (input.uid ?? input.payload?.user_id));
|
||||
switch (input.type) {
|
||||
case "$connect":
|
||||
if (p && !p.conns.includes(input.payload.conn_id)) p.conns.push(input.payload.conn_id);
|
||||
return;
|
||||
case "$disconnect":
|
||||
if (p) p.conns = p.conns.filter((c) => c !== input.payload.conn_id);
|
||||
return;
|
||||
case "$leave":
|
||||
if (p && s.phase === "play") {
|
||||
p.left = true;
|
||||
return finish(s, ctx, 1 - p.seat, "abandoned");
|
||||
}
|
||||
return;
|
||||
case "$bot_replace":
|
||||
if (p) {
|
||||
p.user_id = String(input.payload.bot_user_id);
|
||||
p.name = String(input.payload.display?.name ?? "🤖");
|
||||
p.bot = true;
|
||||
scheduleBot(s, ctx);
|
||||
}
|
||||
return;
|
||||
case "$timer": {
|
||||
const id = input.payload.timer_id;
|
||||
if (id === s.bot_timer) {
|
||||
s.bot_timer = null;
|
||||
return handleBotMove(s, ctx);
|
||||
}
|
||||
if (id === s.timer_id && s.phase === "play") {
|
||||
s.timer_id = null;
|
||||
return handleTimeout(s, ctx);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (input.role !== "player" || !p || p.seat !== input.seat) return ctx.reject("chess.not_a_player");
|
||||
if (input.type === "move") {
|
||||
const payload = input.payload as { from?: string; to?: string; promotion?: string } | undefined;
|
||||
if (!payload || typeof payload.from !== "string" || typeof payload.to !== "string") {
|
||||
return ctx.reject("chess.invalid_move");
|
||||
}
|
||||
const fromIdx = squareIndex(payload.from);
|
||||
const toIdx = squareIndex(payload.to);
|
||||
if (fromIdx < 0 || fromIdx > 63 || toIdx < 0 || toIdx > 63) return ctx.reject("chess.invalid_square");
|
||||
let promo: PieceType | undefined;
|
||||
if (payload.promotion !== undefined) {
|
||||
if (payload.promotion !== "q" && payload.promotion !== "r" && payload.promotion !== "b" && payload.promotion !== "n") {
|
||||
return ctx.reject("chess.invalid_promotion");
|
||||
}
|
||||
promo = payload.promotion;
|
||||
}
|
||||
if (!isValidMove(s, fromIdx, toIdx, p.seat)) return ctx.reject("chess.invalid_move");
|
||||
applyMove(s, fromIdx, toIdx, p.seat, promo);
|
||||
return postMove(s, ctx, p.seat);
|
||||
}
|
||||
return ctx.reject("chess.unknown_type");
|
||||
},
|
||||
views: (s) => [...s.players.map((p) => `seat-${p.seat}`), "obs", "__full"],
|
||||
grants: (s) => Object.fromEntries(s.players.map((p) => [p.user_id, `seat-${p.seat}`])),
|
||||
observerView: () => "obs",
|
||||
snapshot(s, view) {
|
||||
const me = view.startsWith("seat-") ? Number(view.slice(5)) : null;
|
||||
return {
|
||||
me,
|
||||
board: s.board.map((piece, idx) => (piece ? { square: squareName(idx), type: piece.type, color: piece.color } : { square: squareName(idx), type: null, color: null })),
|
||||
turn: s.turn,
|
||||
phase: s.phase,
|
||||
winner: s.winner,
|
||||
result_reason: s.result_reason,
|
||||
check: s.phase === "play" && isKingInCheck(s, s.players[s.turn].color),
|
||||
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,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function postMove(s: State, ctx: Ctx, mover: number) {
|
||||
// After applyMove, s.turn is the opponent: mated if checkmated, drawn if stalemated.
|
||||
const oppColor = s.players[1 - mover].color;
|
||||
if (isCheckmate(s, oppColor)) return finish(s, ctx, mover, "checkmate");
|
||||
if (isStalemate(s, oppColor)) return finish(s, ctx, null, "stalemate");
|
||||
setDeadline(s, ctx);
|
||||
scheduleBot(s, ctx);
|
||||
}
|
||||
|
||||
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") {
|
||||
applyMove(s, botMove.fromIdx, botMove.toIdx, seatBefore);
|
||||
return postMove(s, ctx, seatBefore);
|
||||
}
|
||||
// Bot has no legal move: mated if in check, otherwise stalemate draw.
|
||||
if (isKingInCheck(s, s.players[seatBefore].color)) {
|
||||
return finish(s, ctx, 1 - seatBefore, "checkmate");
|
||||
}
|
||||
return finish(s, ctx, null, "stalemate");
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// Entry point of the chess game server.
|
||||
import { runGameServer } from "@3miz/game-server-sdk";
|
||||
import { chess } from "./game.ts";
|
||||
|
||||
await runGameServer(chess);
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "@3miz/chess-server",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" },
|
||||
"dependencies": { "@3miz/game-server-sdk": "*", "@3miz/common": "*" }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "extends": "../../../tsconfig.base.json", "include": [".", "../tests"] }
|
||||
@@ -0,0 +1,246 @@
|
||||
// Run inside the 3miz repository: node --test --import tsx games/chess/tests/game.test.ts
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { applyInput, initTable, type CreateTable, type Input } from "@3miz/game-server-sdk";
|
||||
import { chess, isCheckmate, isKingInCheck, isStalemate, type State } from "../server/game.ts";
|
||||
|
||||
export const squareIndex = (name: string): number => {
|
||||
const f = name.charCodeAt(0) - 97;
|
||||
const r = parseInt(name[1], 10) - 1;
|
||||
return r * 8 + f;
|
||||
};
|
||||
|
||||
const create = (bots: boolean): CreateTable => ({
|
||||
v: 1, table_id: "0192f0c1-1111-7aaa-8bbb-000000000099", game_id: "chess", game_version: "1.0.0", modes: ["classic"], options: {},
|
||||
customization: { schema_version: 1, values: {} }, packs: [], seed: Buffer.alloc(32, 7).toString("base64"), created_at_ms: 1_700_000_000_000,
|
||||
observers_allowed: true, context: { rated: false, source: "manual" },
|
||||
participants: [
|
||||
{ user_id: "u0", kind: "user", seat: 0, display: { name: "A" } },
|
||||
bots ? { user_id: "b1", kind: "bot", seat: 1, display: { name: "Bot" }, bot_level: "hard" } : { user_id: "u1", kind: "user", seat: 1, display: { name: "B" } },
|
||||
],
|
||||
});
|
||||
|
||||
const whiteSeatOf = (s: State) => s.players.find((p) => p.color === "w")!.seat;
|
||||
const blackSeatOf = (s: State) => s.players.find((p) => p.color === "b")!.seat;
|
||||
const userOf = (s: State, seat: number) => s.players.find((p) => p.seat === seat)!.user_id;
|
||||
|
||||
test("chess init: white back rank on rank 1, black on rank 8, white to move", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s = w.game as State;
|
||||
assert.equal(s.phase, "play");
|
||||
assert.equal(s.board.length, 64);
|
||||
// White home rank (a1..h1) and black home rank (a8..h8)
|
||||
assert.deepEqual(s.board[squareIndex("a1")], { type: "r", color: "w" });
|
||||
assert.deepEqual(s.board[squareIndex("h1")], { type: "r", color: "w" });
|
||||
assert.deepEqual(s.board[squareIndex("e1")], { type: "k", color: "w" });
|
||||
assert.deepEqual(s.board[squareIndex("a8")], { type: "r", color: "b" });
|
||||
assert.deepEqual(s.board[squareIndex("h8")], { type: "r", color: "b" });
|
||||
assert.deepEqual(s.board[squareIndex("e8")], { type: "k", color: "b" });
|
||||
// White moves first, whoever holds the white seat
|
||||
assert.equal(s.players[s.turn].color, "w");
|
||||
});
|
||||
|
||||
test("white pawn advances toward rank 8 (e2 -> e4)", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const seat = whiteSeatOf(s0);
|
||||
assert.equal(s0.turn, seat);
|
||||
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: 1_700_000_001_000,
|
||||
} as Input, 1);
|
||||
assert.equal(result.status, "accepted");
|
||||
const s = w.game as State;
|
||||
assert.equal(s.board[squareIndex("e2")], null);
|
||||
assert.deepEqual(s.board[squareIndex("e4")], { type: "p", color: "w" });
|
||||
assert.equal(s.turn, 1 - seat);
|
||||
});
|
||||
|
||||
test("white pawn cannot move backwards (e2 -> e1)", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const seat = whiteSeatOf(s0);
|
||||
const result = applyInput(chess, w, {
|
||||
v: 1, type: "move", payload: { from: "e2", to: "e1" }, uid: userOf(s0, seat), ci: "c0", cid: 1, role: "player", seat, ts_ms: 1_700_000_001_000,
|
||||
} as Input, 1);
|
||||
assert.equal(result.status, "rejected");
|
||||
});
|
||||
|
||||
test("black pawn advances toward rank 1 after white moves", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
let ts = 1_700_000_001_000, cid = 0;
|
||||
const move = (seat: number, from: string, to: string) => applyInput(chess, w, {
|
||||
v: 1, type: "move", payload: { from, to }, uid: userOf(w.game as State, seat), ci: `c${seat}`, cid: ++cid, role: "player", seat, ts_ms: (ts += 100),
|
||||
} as Input, 1);
|
||||
assert.equal(move(ws, "e2", "e4").status, "accepted");
|
||||
assert.equal(move(bs, "e7", "e5").status, "accepted");
|
||||
const s = w.game as State;
|
||||
assert.deepEqual(s.board[squareIndex("e5")], { type: "p", color: "b" });
|
||||
// Black pawn cannot drift backwards either
|
||||
assert.equal(move(ws, "d2", "d4").status, "accepted");
|
||||
assert.equal(move(bs, "e5", "e6").status, "rejected");
|
||||
});
|
||||
|
||||
test("knight jumps (white Ng1 -> f3)", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const seat = whiteSeatOf(s0);
|
||||
const result = applyInput(chess, w, {
|
||||
v: 1, type: "move", payload: { from: "g1", to: "f3" }, uid: userOf(s0, seat), ci: "c0", cid: 1, role: "player", seat, ts_ms: 1_700_000_001_000,
|
||||
} as Input, 1);
|
||||
assert.equal(result.status, "accepted");
|
||||
assert.deepEqual((w.game as State).board[squareIndex("f3")], { type: "n", color: "w" });
|
||||
});
|
||||
|
||||
test("chess rejects invalid square", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const seat = whiteSeatOf(s0);
|
||||
const result = applyInput(chess, w, {
|
||||
v: 1, type: "move", payload: { from: "z9", to: "e2" }, uid: userOf(s0, seat), ci: "c0", cid: 1, role: "player", seat, ts_ms: 1_700_000_001_000,
|
||||
} as Input, 1);
|
||||
assert.equal(result.status, "rejected");
|
||||
});
|
||||
|
||||
function driver(w: { game: unknown }) {
|
||||
let cid = 0, ts = 1_700_000_001_000;
|
||||
return (seat: number, from: string, to: string, promotion?: string) => applyInput(chess, w as never, {
|
||||
v: 1, type: "move", payload: promotion ? { from, to, promotion } : { from, to },
|
||||
uid: userOf(w.game as State, seat), ci: `c${seat}`, cid: ++cid, role: "player", seat, ts_ms: (ts += 100),
|
||||
} as Input, 1);
|
||||
}
|
||||
|
||||
test("white castles kingside once the path is clear", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
assert.equal(send(ws, "g1", "f3").status, "accepted");
|
||||
assert.equal(send(bs, "g8", "f6").status, "accepted");
|
||||
assert.equal(send(ws, "e2", "e3").status, "accepted");
|
||||
assert.equal(send(bs, "e7", "e6").status, "accepted");
|
||||
assert.equal(send(ws, "f1", "e2").status, "accepted");
|
||||
assert.equal(send(bs, "b7", "b6").status, "accepted");
|
||||
assert.equal(send(ws, "e1", "g1").status, "accepted"); // O-O
|
||||
const s = w.game as State;
|
||||
assert.deepEqual(s.board[squareIndex("g1")], { type: "k", color: "w" });
|
||||
assert.deepEqual(s.board[squareIndex("f1")], { type: "r", color: "w" });
|
||||
assert.equal(s.board[squareIndex("e1")], null);
|
||||
assert.equal(s.board[squareIndex("h1")], null);
|
||||
// Rights are spent and stay spent.
|
||||
assert.equal(s.rights.wk, false);
|
||||
assert.equal(s.rights.wq, false);
|
||||
assert.equal(s.rights.bk, true);
|
||||
});
|
||||
|
||||
test("en passant capture works only on the next move", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
assert.equal(send(ws, "e2", "e4").status, "accepted");
|
||||
assert.equal(send(bs, "a7", "a6").status, "accepted");
|
||||
assert.equal(send(ws, "e4", "e5").status, "accepted");
|
||||
assert.equal(send(bs, "d7", "d5").status, "accepted");
|
||||
assert.equal((w.game as State).ep, squareIndex("d6")); // window opens behind the double-stepper
|
||||
assert.equal(send(ws, "e5", "d6").status, "accepted"); // exd6 e.p.
|
||||
const s = w.game as State;
|
||||
assert.deepEqual(s.board[squareIndex("d6")], { type: "p", color: "w" });
|
||||
assert.equal(s.board[squareIndex("d5")], null); // bypassed pawn is lifted
|
||||
assert.equal(s.board[squareIndex("e5")], null);
|
||||
assert.equal(s.captures, 1);
|
||||
assert.equal(s.ep, null); // window closes after use
|
||||
});
|
||||
|
||||
test("promotion: pawn on the last rank becomes the chosen piece", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
const line: [number, string, string][] = [
|
||||
[ws, "a2", "a4"], [bs, "g8", "f6"],
|
||||
[ws, "a4", "a5"], [bs, "f6", "h5"],
|
||||
[ws, "a5", "a6"], [bs, "e7", "e6"],
|
||||
[ws, "a6", "b7"], [bs, "d7", "d6"],
|
||||
];
|
||||
for (const [seat, from, to] of line) assert.equal(send(seat, from, to).status, "accepted", `${from}->${to}`);
|
||||
assert.equal(send(ws, "b7", "a8", "q").status, "accepted");
|
||||
const s = w.game as State;
|
||||
assert.deepEqual(s.board[squareIndex("a8")], { type: "q", color: "w" });
|
||||
assert.equal(s.moves_played, 9);
|
||||
});
|
||||
|
||||
test("promotion: invalid piece is rejected, knight is accepted", () => {
|
||||
const setup = () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
const line: [number, string, string][] = [
|
||||
[ws, "a2", "a4"], [bs, "g8", "f6"],
|
||||
[ws, "a4", "a5"], [bs, "f6", "h5"],
|
||||
[ws, "a5", "a6"], [bs, "e7", "e6"],
|
||||
[ws, "a6", "b7"], [bs, "d7", "d6"],
|
||||
];
|
||||
for (const [seat, from, to] of line) assert.equal(send(seat, from, to).status, "accepted");
|
||||
return { w, ws, send };
|
||||
};
|
||||
{ const { ws, send } = setup(); assert.equal(send(ws, "b7", "a8", "k").status, "rejected"); }
|
||||
{ const { w, ws, send } = setup(); assert.equal(send(ws, "b7", "a8", "n").status, "accepted");
|
||||
assert.deepEqual((w.game as State).board[squareIndex("a8")], { type: "n", color: "w" }); }
|
||||
});
|
||||
|
||||
test("fool's mate is detected and ends the game", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
assert.equal(send(ws, "f2", "f3").status, "accepted");
|
||||
assert.equal(send(bs, "e7", "e5").status, "accepted");
|
||||
assert.equal(send(ws, "g2", "g4").status, "accepted");
|
||||
assert.equal(send(bs, "d8", "h4").status, "accepted"); // Qh4#
|
||||
assert.equal(w.status, "finished");
|
||||
const s = w.game as State;
|
||||
assert.equal(s.phase, "over");
|
||||
assert.equal(s.winner, bs);
|
||||
assert.equal(s.result_reason, "checkmate");
|
||||
assert.equal(w.result!.standings.find((r) => r.seat === bs)!.rank, 1);
|
||||
});
|
||||
|
||||
test("check must be answered: sidelines rejected, capture accepted", () => {
|
||||
const { w } = initTable(chess, create(false), 1);
|
||||
const s0 = w.game as State;
|
||||
const ws = whiteSeatOf(s0), bs = blackSeatOf(s0);
|
||||
const send = driver(w);
|
||||
assert.equal(send(ws, "e2", "e4").status, "accepted");
|
||||
assert.equal(send(bs, "e7", "e5").status, "accepted");
|
||||
assert.equal(send(ws, "d1", "h5").status, "accepted");
|
||||
assert.equal(send(bs, "b8", "c6").status, "accepted");
|
||||
assert.equal(send(ws, "h5", "f7").status, "accepted"); // Qxf7+
|
||||
assert.equal((w.game as State).phase, "play"); // check, not mate
|
||||
assert.equal(isKingInCheck(w.game as State, "b"), true);
|
||||
assert.equal(isCheckmate(w.game as State, "b"), false);
|
||||
assert.equal(send(bs, "a7", "a6").status, "rejected"); // ignores the check
|
||||
assert.equal(send(bs, "e8", "f7").status, "accepted"); // king takes the checker
|
||||
assert.deepEqual((w.game as State).board[squareIndex("f7")], { type: "k", color: "b" });
|
||||
});
|
||||
|
||||
test("stalemate: lone king with no flight squares is a draw", () => {
|
||||
const mk = (seat: number, user_id: string, color: "w" | "b"): State["players"][number] =>
|
||||
({ seat, user_id, name: user_id, color, bot: false, level: "basic", conns: [], left: false });
|
||||
const s: State = {
|
||||
players: [mk(0, "u0", "w"), mk(1, "u1", "b")],
|
||||
board: Array(64).fill(null) as State["board"],
|
||||
turn: 1, phase: "play", winner: null, result_reason: "",
|
||||
turn_ms: 60000, timer_n: 0, timer_id: null, deadline: null, bot_timer: null,
|
||||
moves_played: 30, captures: 10,
|
||||
rights: { wk: false, wq: false, bk: false, bq: false }, ep: null,
|
||||
};
|
||||
s.board[squareIndex("h8")] = { type: "k", color: "b" };
|
||||
s.board[squareIndex("f7")] = { type: "k", color: "w" };
|
||||
s.board[squareIndex("g6")] = { type: "q", color: "w" };
|
||||
assert.equal(isKingInCheck(s, "b"), false);
|
||||
assert.equal(isCheckmate(s, "b"), false);
|
||||
assert.equal(isStalemate(s, "b"), true);
|
||||
});
|
||||
Reference in New Issue
Block a user