From bc5783145b26edfa531620c8317e3b6018d9a459 Mon Sep 17 00:00:00 2001 From: ar_rezaei Date: Fri, 9 Oct 2026 16:46:29 +0330 Subject: [PATCH] Initial Commit --- .gitignore | 2 + README.md | 136 ++++ client-src/index.html | 9 + client-src/package-lock.json | 1005 ++++++++++++++++++++++++++++++ client-src/package.json | 13 + client-src/sdk-src/host.ts | 136 ++++ client-src/sdk-src/iframe.ts | 40 ++ client-src/sdk-src/index.ts | 2 + client-src/src/main.ts | 158 +++++ client-src/src/style.css | 18 + client-src/vite.config.ts | 11 + client/assets/index-BquRMbQ0.css | 1 + client/assets/index-D5ThqQkE.js | 10 + client/index.html | 11 + docs/TIPS.md | 8 + game.json | 20 + manifest.json | 105 ++++ server/bot.ts | 24 + server/game.ts | 543 ++++++++++++++++ server/main.ts | 5 + server/package.json | 8 + server/tsconfig.json | 1 + tests/game.test.ts | 246 ++++++++ 23 files changed, 2512 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 client-src/index.html create mode 100644 client-src/package-lock.json create mode 100644 client-src/package.json create mode 100644 client-src/sdk-src/host.ts create mode 100644 client-src/sdk-src/iframe.ts create mode 100644 client-src/sdk-src/index.ts create mode 100644 client-src/src/main.ts create mode 100644 client-src/src/style.css create mode 100644 client-src/vite.config.ts create mode 100644 client/assets/index-BquRMbQ0.css create mode 100644 client/assets/index-D5ThqQkE.js create mode 100644 client/index.html create mode 100644 docs/TIPS.md create mode 100644 game.json create mode 100644 manifest.json create mode 100644 server/bot.ts create mode 100644 server/game.ts create mode 100644 server/main.ts create mode 100644 server/package.json create mode 100644 server/tsconfig.json create mode 100644 tests/game.test.ts diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..691ce92 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +client-src/node_modules/* +client-src/dist/* diff --git a/README.md b/README.md new file mode 100644 index 0000000..cea4f8f --- /dev/null +++ b/README.md @@ -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= \ + --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. diff --git a/client-src/index.html b/client-src/index.html new file mode 100644 index 0000000..a368cbd --- /dev/null +++ b/client-src/index.html @@ -0,0 +1,9 @@ + + + + + + Chess — 3miz + +
…
+ diff --git a/client-src/package-lock.json b/client-src/package-lock.json new file mode 100644 index 0000000..ddaad90 --- /dev/null +++ b/client-src/package-lock.json @@ -0,0 +1,1005 @@ +{ + "name": "chess-client", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "chess-client", + "version": "1.0.0", + "devDependencies": { + "vite": "^5.0.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.2.tgz", + "integrity": "sha512-gjNDUwMswogkw3fNqV00u54uZlgmInuw5EU/1TeqQ6K0bEagoGvqjPdKzy112lKyhe7PkGudZ/kSQHsc9qroIg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.2.tgz", + "integrity": "sha512-YkAW8q7p5SCLSaGWaUkmsRnBEb3MGA1pB5nI/8k0lAK5fZsQKRBqkdR1h4UU9p8u3c7ZGdUF2Zcx7mK+E/pUKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.2.tgz", + "integrity": "sha512-hNmuIHv+LnrP/+q/44vsmIMWfoh7X2YXOp5FLtjGuvqN52VdtFpOpnshTc1k28tWv1wE/0D5gLjsozBUowEGbQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.2.tgz", + "integrity": "sha512-B0t5CoxgF2KL7R5FHAsyN8yVEQCSIkh4XVs8MCDjuBLNjEa8l3zd5tVKaFMv53LfUtHs9p2rnqeavPTOunV+Ww==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.2.tgz", + "integrity": "sha512-QQdYnfwrPmc1DoPlddjFvQPzUHFbStKXsHrG6EBYsWHhBVUCjsCRdcfGGXGAvhDpDtTzKK4vy1UrGFJ45rQaiw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.2.tgz", + "integrity": "sha512-1xRxtGWif6BB58VSfMavi0Yfs2M4x6CtRp4o7ScY4W7AGlgvf6GSPKdDNdw7TX3tMiQwZY5W/mvyrOJTq/7AKA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.2.tgz", + "integrity": "sha512-CXFLEt384BUwwOLR9DURWNHl1bQOVLd1ibOee+yKBJm/fZtvrSAOZ0JbxjAxszVMIovYMwFMS+oP+Q1aPcx8Eg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.2.tgz", + "integrity": "sha512-T1dorY0WHm5mMNpMHFl5rYRZ02gLSZcr6J45r66tYb3S3R3DyIRGiGWVdLtF+zOQjratNJaObl9jYumueRiL1A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.2.tgz", + "integrity": "sha512-ia6bfaCIc0ldp6bvs9oEkFrJVJKNUMoiDF0+LBZsQAZg+vE0znXnzGqH+ew/FYswE30cruAWPTO3dPw7keaVkQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.2.tgz", + "integrity": "sha512-mB/gwfBfXtT0EBpbSssqKCqMFuX8b21Zy2TGoIhehSJEssZ5ksybxymwp1BkEM5Nczh/AAxpmh5q+MkhtundGg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.2.tgz", + "integrity": "sha512-VPd0a+XlHoNRI9jIPRHww2UKhDkD6XjbtcKYXZijAnhJS1jLLbiNtVl6a5LyEfNN+eyiyWcJOZXPzBo69oTsew==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.2.tgz", + "integrity": "sha512-10N1I6oBpERqzGtHKcCLrEpHlbXSBbMK9TURHvqgWbIFZuU3oJROxJ0H2nHfq96TVI0XJHQ9qzolJMFd2tz0LA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.2.tgz", + "integrity": "sha512-dhJrLVZ3wNNhwCmy9/VTg6Pq6J8a8eZ0n15dVRlbSWcDb+8V/1mDfbnvis+vt8W6Pbxzv6gUbTEl4piOT3bbUQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.2.tgz", + "integrity": "sha512-tPd2QuwxkTxgju5eARyb3RdgBWWi/O9dn/NFH0VkvGbLzoQeXrH6qMABtW8IODb5lUeBzB3sy2U7qmI4MtQ72g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.2.tgz", + "integrity": "sha512-njtDdPvSQWI9CDhIPPxsiEMeHayCfu7wwcbSQ7c2kYPhGVviL+WGVhq6Jfj/b+VuhSTkFuQ0z4ZFbFjkWwBFmg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.2.tgz", + "integrity": "sha512-EbOBo3dqCj9ecEV9Z7zvulB6AieMP2ztnKQYGVOSN0pzIyOu+3JH2YJZnLmbPeVvfn6yP6Qi7NbBM27EzGbj2w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.2.tgz", + "integrity": "sha512-8wLt2Q5n4qmfiE2Gk8V6KNLSf+oJuBX7Kdw5joFDtnZIZvirS0hLzBc79OiJjV71oYDmBUZLNy6pDgvylo4qiQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.2.tgz", + "integrity": "sha512-aIChbkhC4d33bxkVP0LSi2/2lUSGRXE6k4Qa0G7tgpgTOK7kxHTixmx5qC3SKUJ6yUMznHBtQoWaG4QMqLUnhw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.2.tgz", + "integrity": "sha512-gQ+TkVZRfjZVcl/UOAxxfWw+sHjzIXoieNwxEyJlD3tRBmBhR8ZDq11w+QEgQDcpslEB+fhN/OEpaTsDoIIHhQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.2.tgz", + "integrity": "sha512-sUaJpMKS2JBCvUk8fYimG7aMq2jHVT4kw/uVHxPolKLrMmkKy0KXirmZyZehdNpL7PffqAlPAWUELQcTiD8ChA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.2.tgz", + "integrity": "sha512-j1RdJWb0CrlSuwt12OPjLucPlwfLtA/KMOKVvh5rXSJEtl/WDoIGR3CSykK/jLGTo9RqNfW5Ub6kY5Z5ccYl9w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.2.tgz", + "integrity": "sha512-i3r04aHCIY3eggTBLUp/4IxiBjDpAgQaK89Ue2nMJ2MKuIXX5JfoeZjHw+kPjGGNVDlhi8FT8xzuGMJZe3aehg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.2.tgz", + "integrity": "sha512-kCQ15h/uwNMGdN8gjXBZGf+aGE+ODzHfbi90/cAm4+Q89WoMiLODNoj8HoGZmYx87HPxfu5CBNPsZ+ZG4uIAoA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.2.tgz", + "integrity": "sha512-yYAuySSs+0X2gSMJPw/Q4jHsHZHyMq1dpAE+XnN790Jg1WuReUAD/+j+e4vuDvS4PXJ4PA4NCzTR4OYtDf18/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.2.tgz", + "integrity": "sha512-JY1rQdWOJrKutORqKO1uzrHXV86jFiQzfLFKx2s8S1CjLXL9fC5LOIvk0q7Z7PXJvsByt+sdoE1Q2a9gBr4gLQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.64.2", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.2.tgz", + "integrity": "sha512-RxXm0XVVV1hFI3dYe12ruaOgsYQ725lUcUWeMSQqkF9tTxVErY+fy2Ets6vWhItL9MZMSNZGbvZFc7rH/VHp2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.2", + "@rollup/rollup-android-arm64": "4.64.2", + "@rollup/rollup-darwin-arm64": "4.64.2", + "@rollup/rollup-darwin-x64": "4.64.2", + "@rollup/rollup-freebsd-arm64": "4.64.2", + "@rollup/rollup-freebsd-x64": "4.64.2", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.2", + "@rollup/rollup-linux-arm-musleabihf": "4.64.2", + "@rollup/rollup-linux-arm64-gnu": "4.64.2", + "@rollup/rollup-linux-arm64-musl": "4.64.2", + "@rollup/rollup-linux-loong64-gnu": "4.64.2", + "@rollup/rollup-linux-loong64-musl": "4.64.2", + "@rollup/rollup-linux-ppc64-gnu": "4.64.2", + "@rollup/rollup-linux-ppc64-musl": "4.64.2", + "@rollup/rollup-linux-riscv64-gnu": "4.64.2", + "@rollup/rollup-linux-riscv64-musl": "4.64.2", + "@rollup/rollup-linux-s390x-gnu": "4.64.2", + "@rollup/rollup-linux-x64-gnu": "4.64.2", + "@rollup/rollup-linux-x64-musl": "4.64.2", + "@rollup/rollup-openbsd-x64": "4.64.2", + "@rollup/rollup-openharmony-arm64": "4.64.2", + "@rollup/rollup-win32-arm64-msvc": "4.64.2", + "@rollup/rollup-win32-ia32-msvc": "4.64.2", + "@rollup/rollup-win32-x64-gnu": "4.64.2", + "@rollup/rollup-win32-x64-msvc": "4.64.2", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/vite": { + "version": "5.4.21", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", + "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + } + } +} diff --git a/client-src/package.json b/client-src/package.json new file mode 100644 index 0000000..0c0fd93 --- /dev/null +++ b/client-src/package.json @@ -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" + } +} diff --git a/client-src/sdk-src/host.ts b/client-src/sdk-src/host.ts new file mode 100644 index 0000000..dec157f --- /dev/null +++ b/client-src/sdk-src/host.ts @@ -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(); + private resyncAt = 0; + private pending = new Map(); + private closed = false; + + constructor(private tid: string, private origin: string, private getTicket: (ci: string) => Promise, 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(); + } +} diff --git a/client-src/sdk-src/iframe.ts b/client-src/sdk-src/iframe.ts new file mode 100644 index 0000000..9165161 --- /dev/null +++ b/client-src/sdk-src/iframe.ts @@ -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=` 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; locale: "fa" | "en"; dir: "rtl" | "ltr"; theme: Record; 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 }); }, + }; +} diff --git a/client-src/sdk-src/index.ts b/client-src/sdk-src/index.ts new file mode 100644 index 0000000..40184e3 --- /dev/null +++ b/client-src/sdk-src/index.ts @@ -0,0 +1,2 @@ +export * from "./host.ts"; +export * from "./iframe.ts"; diff --git a/client-src/src/main.ts b/client-src/src/main.ts new file mode 100644 index 0000000..eec6f29 --- /dev/null +++ b/client-src/src/main.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 = `
${L("در حال بارگذاری…", "Loading…")}
`; + 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 = {}; + 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 ? `${pieceChar(cell.type, cell.color)}` : ""; + 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 ``; + }).join("")).join(""); + + const selHint = selectedSquare + ? `
${L("مبدا", "From")}: ${selectedSquare} — ${L("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)", "click a target square (click it again to cancel)")}
` + : ``; + + const promoPicker = pendingPromo + ? `
${pendingPromo.from} → ${pendingPromo.to}: ${L("ارتقا به", "Promote to")} + ${["q", "r", "b", "n"].map((t) => ``).join("")} +
` + : ``; + + 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 = ` +
${statusText}
+
${S.moves_played !== undefined ? `حرکت‌ها: ${S.moves_played}` : ""}
+
${boardHtml}
+ ${selHint} + ${promoPicker} +
${L("سفید حرکت می‌کند", "White moves")}
+ `; +} + +function pieceChar(type: string | null, color: string | null): string { + if (!type) return ""; + // White uses outline glyphs, black uses filled glyphs. + const white: Record = { k: "♔", q: "♕", r: "♖", b: "♗", n: "♘", p: "♙" }; + const black: Record = { 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(); diff --git a/client-src/src/style.css b/client-src/src/style.css new file mode 100644 index 0000000..63bcf0c --- /dev/null +++ b/client-src/src/style.css @@ -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; } diff --git a/client-src/vite.config.ts b/client-src/vite.config.ts new file mode 100644 index 0000000..a9c0da0 --- /dev/null +++ b/client-src/vite.config.ts @@ -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 }, +}); diff --git a/client/assets/index-BquRMbQ0.css b/client/assets/index-BquRMbQ0.css new file mode 100644 index 0000000..91cd1eb --- /dev/null +++ b/client/assets/index-BquRMbQ0.css @@ -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} diff --git a/client/assets/index-D5ThqQkE.js b/client/assets/index-D5ThqQkE.js new file mode 100644 index 0000000..c8a998f --- /dev/null +++ b/client/assets/index-D5ThqQkE.js @@ -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=`
${i("در حال بارگذاری…","Loading…")}
`;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?`${M(y.type,y.color)}`:"",O=l&&!!a&&y.color===a,E=c===g,H=c?l:O;return``}).join("")).join(""),b=c?`
${i("مبدا","From")}: ${c} — ${i("یک خانه مقصد را بزنید (برای لغو، دوباره همان خانه)","click a target square (click it again to cancel)")}
`:"",$=m?`
${m.from} → ${m.to}: ${i("ارتقا به","Promote to")} + ${["q","r","b","n"].map(f=>``).join("")} +
`:"",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=` +
${v}
+
${e.moves_played!==void 0?`حرکت‌ها: ${e.moves_played}`:""}
+
${u}
+ ${b} + ${$} +
${i("سفید حرکت می‌کند","White moves")}
+ `}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(); diff --git a/client/index.html b/client/index.html new file mode 100644 index 0000000..3942e47 --- /dev/null +++ b/client/index.html @@ -0,0 +1,11 @@ + + + + + + Chess — 3miz + + + +
…
+ diff --git a/docs/TIPS.md b/docs/TIPS.md new file mode 100644 index 0000000..5e9e1d2 --- /dev/null +++ b/docs/TIPS.md @@ -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. diff --git a/game.json b/game.json new file mode 100644 index 0000000..afc0bc5 --- /dev/null +++ b/game.json @@ -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." } +} diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..820b737 --- /dev/null +++ b/manifest.json @@ -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": [] +} diff --git a/server/bot.ts b/server/bot.ts new file mode 100644 index 0000000..5aa4075 --- /dev/null +++ b/server/bot.ts @@ -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 }; +} diff --git a/server/game.ts b/server/game.ts new file mode 100644 index 0000000..4ffd6ff --- /dev/null +++ b/server/game.ts @@ -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 = { + 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"); + } +} diff --git a/server/main.ts b/server/main.ts new file mode 100644 index 0000000..17d5679 --- /dev/null +++ b/server/main.ts @@ -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); diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..4ba56ee --- /dev/null +++ b/server/package.json @@ -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": "*" } +} diff --git a/server/tsconfig.json b/server/tsconfig.json new file mode 100644 index 0000000..77934bc --- /dev/null +++ b/server/tsconfig.json @@ -0,0 +1 @@ +{ "extends": "../../../tsconfig.base.json", "include": [".", "../tests"] } diff --git a/tests/game.test.ts b/tests/game.test.ts new file mode 100644 index 0000000..4762c2c --- /dev/null +++ b/tests/game.test.ts @@ -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); +});