bot freezing solved and difficulty levels reduced to the original three

This commit is contained in:
2026-10-15 14:08:13 +03:30
parent d8adef472e
commit 8ff113cfba
7 changed files with 148 additions and 126 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ 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` monorepo: deterministic TypeScript game server on the `@3miz/game-server-sdk`
(contract 40) plus a sandboxed iframe client (contract 43). (contract 40) plus a sandboxed iframe client (contract 43).
- `game_id`: `chess`, version `1.0.0` - `game_id`: `chess`, version `1.1.0`
- Lafayette orientation: the board is shown from your own side (white sees `a8` - Lafayette orientation: the board is shown from your own side (white sees `a8`
top-left, black sees `h1` top-left); `a1` is always dark. top-left, black sees `h1` top-left); `a1` is always dark.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "chess-client", "name": "chess-client",
"version": "1.0.0", "version": "1.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {
+1 -1
View File
@@ -2,7 +2,7 @@
"bundle_format": 1, "bundle_format": 1,
"kind": "source", "kind": "source",
"game_id": "chess", "game_id": "chess",
"version": "1.0.0", "version": "1.3.0",
"server": { "entry": "server/main.ts" }, "server": { "entry": "server/main.ts" },
"client": { "entry": "index.html" }, "client": { "entry": "index.html" },
"catalog": { "catalog": {
+3 -3
View File
@@ -1,7 +1,7 @@
{ {
"manifest_version": 1, "manifest_version": 1,
"game_id": "chess", "game_id": "chess",
"version": "1.0.0", "version": "1.3.0",
"protocol": "socketio", "protocol": "socketio",
"protocol_version": 1, "protocol_version": 1,
"title": { "title": {
@@ -81,14 +81,14 @@
], ],
"achievements": [], "achievements": [],
"client": { "client": {
"entry": "https://g.3miz.ir/chess/1.0.0/index.html", "entry": "https://g.3miz.ir/chess/1.3.0/index.html",
"integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"aspect": "1:1", "aspect": "1:1",
"min_width_px": 320, "min_width_px": 320,
"supports_portrait": true "supports_portrait": true
}, },
"server": { "server": {
"image": "registry.3miz.ir/games/chess:1.0.0", "image": "registry.3miz.ir/games/chess:1.3.0",
"max_tables_per_instance": 500, "max_tables_per_instance": 500,
"checkpoint_every_inputs": 20, "checkpoint_every_inputs": 20,
"snapshot_every_messages": 50, "snapshot_every_messages": 50,
+99 -91
View File
@@ -1,11 +1,12 @@
/** /**
* Advanced Chess AI Engine — deterministic minimax with alpha-beta pruning, * Chess AI Engine — deterministic negamax with alpha-beta pruning,
* piece-square tables (PST), MVV-LVA move ordering, and quiescence search. * piece-square tables (PST), MVV-LVA move ordering, and quiescence search.
* Differentiated depth and strategic profiles for Easy, Basic, and Hard.
*/ */
import type { Rng } from "@3miz/game-server-sdk"; import type { Rng } from "@3miz/game-server-sdk";
import { import {
isValidMove, isMoveLegalFor,
isKingInCheck, isKingInCheck,
isCheckmate, isCheckmate,
type State, type State,
@@ -104,8 +105,8 @@ function getPstScore(type: PieceType, color: "w" | "b", sq: number): number {
} }
/** /**
* Static position evaluation from the perspective of white. * Static position evaluation from White's perspective.
* Returns a score in centipawns: positive favors White, negative favors Black. * Positive favors White, negative favors Black.
*/ */
function evaluateStatic(s: State): number { function evaluateStatic(s: State): number {
let material = 0; let material = 0;
@@ -115,17 +116,15 @@ function evaluateStatic(s: State): number {
const p = s.board[sq]; const p = s.board[sq];
if (!p) continue; if (!p) continue;
const val = PIECE_VALUES[p.type] ?? 0; const val = PIECE_VALUES[p.type] ?? 0;
const pst = getPstScore(p.type, p.color, sq);
if (p.color === "w") { if (p.color === "w") {
material += val; material += val;
positional += pst; positional += getPstScore(p.type, p.color, sq);
} else { } else {
material -= val; material -= val;
positional -= pst; positional -= getPstScore(p.type, p.color, sq);
} }
} }
// King check penalties / bonuses
if (isKingInCheck(s, "w")) positional -= 40; if (isKingInCheck(s, "w")) positional -= 40;
if (isKingInCheck(s, "b")) positional += 40; if (isKingInCheck(s, "b")) positional += 40;
@@ -232,10 +231,10 @@ function unmakeMove(s: State, undo: UndoRecord) {
} }
/** /**
* Generate all legal moves for a given seat, ordered using MVV-LVA heuristics * Generate all legal moves for a given color, ordered using MVV-LVA heuristics.
* Uses isMoveLegalFor so it is independent of whose turn it currently is in the root state.
*/ */
function generateOrderedMoves(s: State, seat: number): MoveCandidate[] { function generateOrderedMoves(s: State, color: "w" | "b", prioritizeCaptures = true): MoveCandidate[] {
const color = s.players[seat].color;
const moves: MoveCandidate[] = []; const moves: MoveCandidate[] = [];
for (let from = 0; from < 64; from++) { for (let from = 0; from < 64; from++) {
@@ -243,15 +242,15 @@ function generateOrderedMoves(s: State, seat: number): MoveCandidate[] {
if (!p || p.color !== color) continue; if (!p || p.color !== color) continue;
for (let to = 0; to < 64; to++) { for (let to = 0; to < 64; to++) {
if (isValidMove(s, from, to, seat)) { if (isMoveLegalFor(s, from, to, color)) {
const target = s.board[to]; const target = s.board[to];
let moveScore = 0; let moveScore = 0;
if (prioritizeCaptures) {
// MVV-LVA: Most Valuable Victim - Least Valuable Attacker // MVV-LVA: Most Valuable Victim - Least Valuable Attacker
if (target) { if (target) {
moveScore = 1000 + (PIECE_VALUES[target.type] ?? 0) * 10 - (PIECE_VALUES[p.type] ?? 0); moveScore = 1000 + (PIECE_VALUES[target.type] ?? 0) * 10 - (PIECE_VALUES[p.type] ?? 0);
} else if (to === s.ep && p.type === "p") { } else if (to === s.ep && p.type === "p") {
// En passant capture
moveScore = 1000 + 100 * 10 - 100; moveScore = 1000 + 100 * 10 - 100;
} }
@@ -265,28 +264,30 @@ function generateOrderedMoves(s: State, seat: number): MoveCandidate[] {
// Positional gain // Positional gain
const pstGain = getPstScore(p.type, color, to) - getPstScore(p.type, color, from); const pstGain = getPstScore(p.type, color, to) - getPstScore(p.type, color, from);
moveScore += pstGain; moveScore += pstGain;
}
const isPawnPromo = p.type === "p" && Math.floor(to / 8) === (color === "w" ? 7 : 0);
moves.push({ moves.push({
from, from,
to, to,
promotion: isPromo ? "q" : undefined, promotion: isPawnPromo ? "q" : undefined,
score: moveScore, score: moveScore,
}); });
} }
} }
} }
// Sort moves in descending order of predicted potential if (prioritizeCaptures) {
moves.sort((a, b) => b.score - a.score); moves.sort((a, b) => b.score - a.score);
}
return moves; return moves;
} }
/** /**
* Quiescence search to avoid horizon effect on loud capture positions * Quiescence search for loud capture sequences
*/ */
function quiescence( function quiescence(
s: State, s: State,
seat: number,
alpha: number, alpha: number,
beta: number, beta: number,
color: "w" | "b", color: "w" | "b",
@@ -297,12 +298,14 @@ function quiescence(
if (standPat > alpha) alpha = standPat; if (standPat > alpha) alpha = standPat;
if (depthLimit <= 0) return alpha; if (depthLimit <= 0) return alpha;
const moves = generateOrderedMoves(s, seat).filter((m) => s.board[m.to] !== null || m.to === s.ep); const oppColor = color === "w" ? "b" : "w";
const oppSeat = 1 - seat; const moves = generateOrderedMoves(s, color, true).filter(
(m) => s.board[m.to] !== null || m.to === s.ep
);
for (const move of moves) { for (const move of moves) {
const undo = makeMove(s, move.from, move.to, move.promotion); const undo = makeMove(s, move.from, move.to, move.promotion);
const score = -quiescence(s, oppSeat, -beta, -alpha, color === "w" ? "b" : "w", depthLimit - 1); const score = -quiescence(s, -beta, -alpha, oppColor, depthLimit - 1);
unmakeMove(s, undo); unmakeMove(s, undo);
if (score >= beta) return beta; if (score >= beta) return beta;
@@ -312,66 +315,50 @@ function quiescence(
} }
/** /**
* Minimax with Alpha-Beta Pruning * Negamax with Alpha-Beta Pruning
*/ */
function alphaBeta( function negamax(
s: State, s: State,
depth: number, depth: number,
alpha: number, alpha: number,
beta: number, beta: number,
seat: number, color: "w" | "b",
botColor: "w" | "b", ply: number,
ply: number quiesceDepth: number
): number { ): number {
const currentColor = s.players[seat].color; const oppColor = color === "w" ? "b" : "w";
const isBotTurn = currentColor === botColor;
if (isCheckmate(s, currentColor)) { if (isCheckmate(s, color)) {
// Checkmate penalty/reward scaled by ply to prefer faster mates // Current side to move is mated -> large penalty scaled by distance to root
return isBotTurn ? -100000 + ply : 100000 - ply; return -100000 + ply;
} }
if (depth <= 0) { if (depth <= 0) {
return quiescence(s, seat, alpha, beta, currentColor, 2); if (quiesceDepth > 0) {
return quiescence(s, alpha, beta, color, quiesceDepth);
}
return (color === "w" ? 1 : -1) * evaluateStatic(s);
} }
const moves = generateOrderedMoves(s, seat); const moves = generateOrderedMoves(s, color, true);
if (moves.length === 0) { if (moves.length === 0) {
// Stalemate is a draw (0) // Stalemate is a draw (0)
return 0; return 0;
} }
const oppSeat = 1 - seat;
if (isBotTurn) {
let maxEval = -Infinity;
for (const move of moves) { for (const move of moves) {
const undo = makeMove(s, move.from, move.to, move.promotion); const undo = makeMove(s, move.from, move.to, move.promotion);
const evalScore = alphaBeta(s, depth - 1, alpha, beta, oppSeat, botColor, ply + 1); const score = -negamax(s, depth - 1, -beta, -alpha, oppColor, ply + 1, quiesceDepth);
unmakeMove(s, undo); unmakeMove(s, undo);
maxEval = Math.max(maxEval, evalScore); if (score >= beta) return beta;
alpha = Math.max(alpha, evalScore); if (score > alpha) alpha = score;
if (beta <= alpha) break; // Beta cutoff
}
return maxEval;
} else {
let minEval = Infinity;
for (const move of moves) {
const undo = makeMove(s, move.from, move.to, move.promotion);
const evalScore = alphaBeta(s, depth - 1, alpha, beta, oppSeat, botColor, ply + 1);
unmakeMove(s, undo);
minEval = Math.min(minEval, evalScore);
beta = Math.min(beta, evalScore);
if (beta <= alpha) break; // Alpha cutoff
}
return minEval;
} }
return alpha;
} }
/** /**
* Standard book openings for classic initial turns * Standard opening book moves
*/ */
const OPENING_BOOK_WHITE = [ const OPENING_BOOK_WHITE = [
{ from: 12, to: 28 }, // e2 -> e4 { from: 12, to: 28 }, // e2 -> e4
@@ -390,12 +377,12 @@ const OPENING_BOOK_BLACK: Record<string, { from: number; to: number }[]> = {
// Against d2-d4: // Against d2-d4:
"27": [ "27": [
{ from: 51, to: 35 }, // d7 -> d5 { from: 51, to: 35 }, // d7 -> d5
{ from: 62, to: 45 }, // g8 -> f6 (Indian Defense) { from: 62, to: 45 }, // g8 -> f6 (Indian)
], ],
}; };
/** /**
* Main bot entry point called by the game server * Main bot decision engine
*/ */
export function decideBot( export function decideBot(
s: State, s: State,
@@ -406,8 +393,8 @@ export function decideBot(
if (!player) return null; if (!player) return null;
const color = player.color; const color = player.color;
const level = player.level || "basic"; const rawLevel = (player.level || "").toLowerCase().trim();
const legalMoves = generateOrderedMoves(s, seat); const legalMoves = generateOrderedMoves(s, color, true);
if (legalMoves.length === 0) return null; if (legalMoves.length === 0) return null;
if (legalMoves.length === 1) { if (legalMoves.length === 1) {
@@ -418,52 +405,74 @@ export function decideBot(
}; };
} }
// 1. Opening book selection on the first 2 moves of the game // Difficulty profiles: easy (آسون), basic (معمولی), hard (سخت)
let searchDepth = 2;
let quiesceDepth = 1;
let noiseRange = 0;
let useOpeningBook = true;
let blunderChancePercent = 0;
if (rawLevel === "hard" || rawLevel === "expert" || rawLevel === "master") {
// Hard (سخت): Depth 3 + 2 plies quiescence. Sharp, tactical, 0 blunders (~160ms).
searchDepth = 3;
quiesceDepth = 2;
noiseRange = 0;
useOpeningBook = true;
blunderChancePercent = 0;
} else if (rawLevel === "basic" || rawLevel === "normal") {
// Basic / Normal (معمولی): Depth 2 + 1 ply quiescence. Solid play, small noise (~2ms).
searchDepth = 2;
quiesceDepth = 1;
noiseRange = 10;
useOpeningBook = true;
blunderChancePercent = 5;
} else {
// Easy (آسون): Depth 1, no quiescence, higher noise & 25% casual blunders (~1ms).
searchDepth = 1;
quiesceDepth = 0;
noiseRange = 50;
useOpeningBook = false;
blunderChancePercent = 25;
}
// 1. Opening book selection on the first 2 moves of the game (if enabled)
if (useOpeningBook) {
if (s.moves_played === 0 && color === "w") { if (s.moves_played === 0 && color === "w") {
const bookPick = OPENING_BOOK_WHITE[rng.int(OPENING_BOOK_WHITE.length)]; const pick = OPENING_BOOK_WHITE[rng.int(OPENING_BOOK_WHITE.length)];
if (isValidMove(s, bookPick.from, bookPick.to, seat)) { if (isMoveLegalFor(s, pick.from, pick.to, color)) {
return { fromIdx: bookPick.from, toIdx: bookPick.to }; return { fromIdx: pick.from, toIdx: pick.to };
} }
} else if (s.moves_played === 1 && color === "b") { } else if (s.moves_played === 1 && color === "b") {
// Find what white played const cand = s.board[28]?.type === "p" && s.board[28]?.color === "w"
const whitePawnOnE4 = s.board[28]?.type === "p" && s.board[28]?.color === "w";
const whitePawnOnD4 = s.board[27]?.type === "p" && s.board[27]?.color === "w";
const candidates = whitePawnOnE4
? OPENING_BOOK_BLACK["28"] ? OPENING_BOOK_BLACK["28"]
: (whitePawnOnD4 ? OPENING_BOOK_BLACK["27"] : null); : (s.board[27]?.type === "p" && s.board[27]?.color === "w" ? OPENING_BOOK_BLACK["27"] : null);
if (candidates) { if (cand) {
const bookPick = candidates[rng.int(candidates.length)]; const pick = cand[rng.int(cand.length)];
if (isValidMove(s, bookPick.from, bookPick.to, seat)) { if (isMoveLegalFor(s, pick.from, pick.to, color)) {
return { fromIdx: bookPick.from, toIdx: bookPick.to }; return { fromIdx: pick.from, toIdx: pick.to };
}
} }
} }
} }
// 2. Search depth based on configured difficulty level // 2. Beginner blunder mechanism: integer-based check using rng.int(100) (never rng.float)
let searchDepth = 2; if (blunderChancePercent > 0 && rng.int(100) < blunderChancePercent) {
let noiseRange = 0; const nonCaptures = legalMoves.filter((m) => s.board[m.to] === null);
if (nonCaptures.length > 0) {
if (level === "hard") { const pick = nonCaptures[rng.int(nonCaptures.length)];
searchDepth = 3; return { fromIdx: pick.from, toIdx: pick.to, promotion: pick.promotion };
noiseRange = 0; }
} else if (level === "easy") {
searchDepth = 1;
noiseRange = 35; // Casual noise to allow human-like minor inaccuracies
} else {
// "basic"
searchDepth = 2;
noiseRange = 8;
} }
// 3. Minimax evaluation over all candidate root moves // 3. Negamax evaluation over all candidate root moves
const oppSeat = 1 - seat; const oppColor = color === "w" ? "b" : "w";
let bestScore = -Infinity; let bestScore = -Infinity;
let bestMoves: MoveCandidate[] = []; let bestMoves: MoveCandidate[] = [];
for (const move of legalMoves) { for (const move of legalMoves) {
const undo = makeMove(s, move.from, move.to, move.promotion); const undo = makeMove(s, move.from, move.to, move.promotion);
let evalScore = alphaBeta(s, searchDepth - 1, -Infinity, Infinity, oppSeat, color, 1); let evalScore = -negamax(s, searchDepth - 1, -Infinity, Infinity, oppColor, 1, quiesceDepth);
unmakeMove(s, undo); unmakeMove(s, undo);
// Apply difficulty noise // Apply difficulty noise
@@ -480,8 +489,7 @@ export function decideBot(
} }
} }
// Tie-breaker using deterministic rng const selected = bestMoves.length > 0 ? bestMoves[rng.int(bestMoves.length)] : legalMoves[0];
const selected = bestMoves[rng.int(bestMoves.length)] || legalMoves[0];
return { return {
fromIdx: selected.from, fromIdx: selected.from,
+18 -4
View File
@@ -27,6 +27,7 @@ export interface State {
timer_id: string | null; timer_id: string | null;
deadline: number | null; deadline: number | null;
bot_timer: string | null; bot_timer: string | null;
bot_n: number;
moves_played: number; moves_played: number;
captures: number; captures: number;
// Castling rights decay as kings/rooks move or corner rooks are captured. // Castling rights decay as kings/rooks move or corner rooks are captured.
@@ -234,7 +235,7 @@ export function isValidMove(state: State, from: number, to: number, seat: number
} }
// Geometry + king safety, without any turn/phase/seat checks. // Geometry + king safety, without any turn/phase/seat checks.
function isMoveLegalFor(s: State, from: number, to: number, moverColor: Color): boolean { export function isMoveLegalFor(s: State, from: number, to: number, moverColor: Color): boolean {
if (!pieceCanMove(s, from, to, moverColor)) return false; if (!pieceCanMove(s, from, to, moverColor)) return false;
return !wouldLeaveInCheck(s, from, to, moverColor); return !wouldLeaveInCheck(s, from, to, moverColor);
} }
@@ -297,10 +298,19 @@ function setDeadline(s: State, t: { now: number; setTimer(id: string, due: numbe
t.setTimer(s.timer_id, s.deadline); 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 }) { function scheduleBot(s: State, t: { now: number; setTimer(id: string, due: number): void; clearTimer?(id: string): void }) {
const p = s.players[s.turn]; if (!pendingBot(s)) {
if (s.phase !== "play" || !p.bot || s.bot_timer) return; if (s.bot_timer) {
s.bot_timer = `bot-${s.timer_n}`; 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); t.setTimer(s.bot_timer, t.now + 600);
} }
@@ -365,6 +375,8 @@ function finish(s: State, ctx: Ctx, winner: number | null, reason: string = "com
s.deadline = null; s.deadline = null;
if (s.timer_id) ctx.clearTimer(s.timer_id); if (s.timer_id) ctx.clearTimer(s.timer_id);
s.timer_id = null; s.timer_id = null;
if (s.bot_timer) ctx.clearTimer(s.bot_timer);
s.bot_timer = null;
ctx.finish({ ctx.finish({
reason: reason === "abandoned" ? "abandoned" : "completed", reason: reason === "abandoned" ? "abandoned" : "completed",
standings: s.players.map((p) => ({ standings: s.players.map((p) => ({
@@ -410,6 +422,7 @@ export const chess: GameDef<State> = {
timer_id: null, timer_id: null,
deadline: null, deadline: null,
bot_timer: null, bot_timer: null,
bot_n: 0,
moves_played: 0, moves_played: 0,
captures: 0, captures: 0,
rights: { wk: true, wq: true, bk: true, bq: true }, rights: { wk: true, wq: true, bk: true, bq: true },
@@ -439,6 +452,7 @@ export const chess: GameDef<State> = {
p.user_id = String(input.payload.bot_user_id); p.user_id = String(input.payload.bot_user_id);
p.name = String(input.payload.display?.name ?? "🤖"); p.name = String(input.payload.display?.name ?? "🤖");
p.bot = true; p.bot = true;
if (input.payload.bot_level) p.level = String(input.payload.bot_level);
scheduleBot(s, ctx); scheduleBot(s, ctx);
} }
return; return;
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@3miz/chess-server", "name": "@3miz/chess-server",
"version": "1.0.0", "version": "1.3.0",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" }, "scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" },