662 lines
25 KiB
TypeScript
662 lines
25 KiB
TypeScript
/**
|
|
* 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;
|
|
time_control: string;
|
|
initial_time_ms: number;
|
|
increment_ms: number;
|
|
clocks: [number, number]; // remaining time in ms for seat 0 and seat 1
|
|
turn_start_ms: number; // timestamp when current turn started
|
|
timer_n: number;
|
|
timer_id: string | null;
|
|
deadline: number | null;
|
|
bot_timer: string | null;
|
|
bot_n: number;
|
|
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.
|
|
export 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);
|
|
}
|
|
|
|
/**
|
|
* Check if neither side has sufficient material to force checkmate:
|
|
* - King vs King
|
|
* - King + Bishop vs King
|
|
* - King + Knight vs King
|
|
* - King + Minor vs King + Minor (KB vs KB, KN vs KN, KB vs KN)
|
|
* - King + two Knights vs King (KNN vs K cannot force checkmate)
|
|
*/
|
|
export function hasInsufficientMaterial(state: State): boolean {
|
|
if (state.phase !== "play") return false;
|
|
|
|
let whiteKnights = 0;
|
|
let whiteBishops: number[] = [];
|
|
let blackKnights = 0;
|
|
let blackBishops: number[] = [];
|
|
|
|
for (let sq = 0; sq < 64; sq++) {
|
|
const p = state.board[sq];
|
|
if (!p) continue;
|
|
// Any pawn, rook, or queen means checkmate can be forced (or pawn can promote)
|
|
if (p.type === "p" || p.type === "r" || p.type === "q") {
|
|
return false;
|
|
}
|
|
if (p.type === "n") {
|
|
if (p.color === "w") whiteKnights++;
|
|
else blackKnights++;
|
|
} else if (p.type === "b") {
|
|
if (p.color === "w") whiteBishops.push(sq);
|
|
else blackBishops.push(sq);
|
|
}
|
|
}
|
|
|
|
const whiteMinors = whiteKnights + whiteBishops.length;
|
|
const blackMinors = blackKnights + blackBishops.length;
|
|
|
|
// 1. King vs King
|
|
if (whiteMinors === 0 && blackMinors === 0) {
|
|
return true;
|
|
}
|
|
|
|
// 2. King + Minor vs King (KB vs K or KN vs K)
|
|
if ((whiteMinors === 1 && blackMinors === 0) || (whiteMinors === 0 && blackMinors === 1)) {
|
|
return true;
|
|
}
|
|
|
|
// 3. King + Minor vs King + Minor (KB vs KB, KN vs KN, KB vs KN)
|
|
if (whiteMinors === 1 && blackMinors === 1) {
|
|
return true;
|
|
}
|
|
|
|
// 4. King + two Knights vs King (KNN vs K cannot force checkmate)
|
|
if ((whiteKnights === 2 && whiteMinors === 2 && blackMinors === 0) ||
|
|
(blackKnights === 2 && blackMinors === 2 && whiteMinors === 0)) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
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}`;
|
|
const remaining = s.clocks[s.turn];
|
|
s.turn_start_ms = t.now;
|
|
s.deadline = t.now + remaining;
|
|
t.setTimer(s.timer_id, s.deadline);
|
|
}
|
|
|
|
const pendingBot = (s: State) => s.phase === "play" && !!s.players[s.turn]?.bot && !s.players[s.turn].left;
|
|
|
|
function scheduleBot(s: State, t: { now: number; setTimer(id: string, due: number): void; clearTimer?(id: string): void }) {
|
|
if (!pendingBot(s)) {
|
|
if (s.bot_timer) {
|
|
t.clearTimer?.(s.bot_timer);
|
|
s.bot_timer = null;
|
|
}
|
|
return;
|
|
}
|
|
if (s.bot_timer) return;
|
|
s.bot_n += 1;
|
|
s.bot_timer = `bot-${s.bot_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;
|
|
if (s.bot_timer) ctx.clearTimer(s.bot_timer);
|
|
s.bot_timer = null;
|
|
ctx.finish({
|
|
reason: reason === "abandoned" ? "abandoned" : (reason === "timeout" ? "timeout" : "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 },
|
|
},
|
|
});
|
|
}
|
|
|
|
const TIME_CONTROLS: Record<string, { initial_ms: number; increment_ms: number }> = {
|
|
"1m": { initial_ms: 60_000, increment_ms: 0 },
|
|
"1m_1s": { initial_ms: 60_000, increment_ms: 1_000 },
|
|
"3m": { initial_ms: 180_000, increment_ms: 0 },
|
|
"3m_2s": { initial_ms: 180_000, increment_ms: 2_000 },
|
|
"10m": { initial_ms: 600_000, increment_ms: 0 },
|
|
"15m_10s": { initial_ms: 900_000, increment_ms: 10_000 },
|
|
};
|
|
|
|
function resolveTimeControl(modes: string[], options: Record<string, unknown>): { tcId: string; initial_ms: number; increment_ms: number } {
|
|
// If explicitly specified in options
|
|
if (typeof options.time_control === "string" && TIME_CONTROLS[options.time_control]) {
|
|
const tcId = options.time_control;
|
|
return { tcId, ...TIME_CONTROLS[tcId] };
|
|
}
|
|
// Otherwise deduce from mode
|
|
if (modes.includes("bullet")) {
|
|
return { tcId: "1m", ...TIME_CONTROLS["1m"] };
|
|
}
|
|
if (modes.includes("rapid")) {
|
|
return { tcId: "10m", ...TIME_CONTROLS["10m"] };
|
|
}
|
|
// Default is blitz 3m
|
|
return { tcId: "3m", ...TIME_CONTROLS["3m"] };
|
|
}
|
|
|
|
export const chess: GameDef<State> = {
|
|
manifest,
|
|
validateModes: (modes) => {
|
|
const valid = ["blitz", "bullet", "rapid", "classic"];
|
|
return modes.every((m) => valid.includes(m))
|
|
? []
|
|
: [{ code: "chess.unknown_mode", path: "/modes", message: "unknown mode" }];
|
|
},
|
|
init(create: CreateTable, ictx: InitCtx): State {
|
|
const seats = [...create.participants].sort((a, b) => a.seat - b.seat);
|
|
const first = firstSeat(create, ictx.rng, 2);
|
|
const tc = resolveTimeControl(create.modes, create.options);
|
|
const s: State = {
|
|
players: seats.map((p, i) => ({
|
|
seat: i,
|
|
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: "",
|
|
time_control: tc.tcId,
|
|
initial_time_ms: tc.initial_ms,
|
|
increment_ms: tc.increment_ms,
|
|
clocks: [tc.initial_ms, tc.initial_ms],
|
|
turn_start_ms: ictx.now,
|
|
timer_n: 0,
|
|
timer_id: null,
|
|
deadline: null,
|
|
bot_timer: null,
|
|
bot_n: 0,
|
|
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;
|
|
if (input.payload.bot_level) p.level = String(input.payload.bot_level);
|
|
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");
|
|
|
|
// Deduct elapsed time and add increment
|
|
const elapsed = Math.max(0, ctx.now - s.turn_start_ms);
|
|
s.clocks[p.seat] = Math.max(0, s.clocks[p.seat] - elapsed) + s.increment_ms;
|
|
|
|
applyMove(s, fromIdx, toIdx, p.seat, promo);
|
|
return postMove(s, ctx, p.seat);
|
|
}
|
|
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,
|
|
clocks: s.clocks,
|
|
turn_start_ms: s.turn_start_ms,
|
|
time_control: s.time_control,
|
|
increment_ms: s.increment_ms,
|
|
};
|
|
},
|
|
};
|
|
|
|
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");
|
|
if (hasInsufficientMaterial(s)) return finish(s, ctx, null, "insufficient_material");
|
|
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") {
|
|
// Deduct elapsed time and add increment for bot
|
|
const elapsed = Math.max(0, ctx.now - s.turn_start_ms);
|
|
s.clocks[seatBefore] = Math.max(0, s.clocks[seatBefore] - elapsed) + s.increment_ms;
|
|
|
|
applyMove(s, botMove.fromIdx, botMove.toIdx, seatBefore, botMove.promotion);
|
|
return postMove(s, ctx, seatBefore);
|
|
}
|
|
// 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;
|
|
const timedOutSeat = s.turn;
|
|
s.clocks[timedOutSeat] = 0;
|
|
// If the opponent does not have sufficient material to checkmate, it's a draw by timeout vs insufficient material
|
|
const oppSeat = 1 - timedOutSeat;
|
|
if (hasInsufficientMaterial(s)) {
|
|
return finish(s, ctx, null, "timeout_draw");
|
|
}
|
|
return finish(s, ctx, oppSeat, "timeout");
|
|
}
|