added insufficient material condition for draw

This commit is contained in:
2026-10-19 14:03:09 +03:30
parent 8ff113cfba
commit be54bdd5a7
10 changed files with 327 additions and 11 deletions
+60
View File
@@ -290,6 +290,65 @@ export function isStalemate(state: State, color: Color): boolean {
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;
@@ -516,6 +575,7 @@ function postMove(s: State, ctx: Ctx, mover: number) {
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);
}