diff --git a/client-src/package.json b/client-src/package.json index 15e3085..e0c89b2 100644 --- a/client-src/package.json +++ b/client-src/package.json @@ -1,6 +1,6 @@ { "name": "chess-client", - "version": "1.3.0", + "version": "1.4.0", "private": true, "type": "module", "scripts": { diff --git a/client-src/src/main.ts b/client-src/src/main.ts index cddda73..3c1b90c 100644 --- a/client-src/src/main.ts +++ b/client-src/src/main.ts @@ -306,7 +306,7 @@ function renderPlayerBar(barId: string, player: PlayerSnapshot | undefined, isAc const botBadge = player.bot ? `BOT` : ""; const youBadge = isMe ? `${L("شما", "YOU")}` : ""; const statusLabel = S.phase === "over" - ? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : "") + ? (S.winner === player.seat ? L("برنده 🏆", "Winner 🏆") : (S.winner === null ? L("تساوی 🤝", "Draw 🤝") : "")) : (isActive ? (isMe ? L("نوبت شماست", "Your turn") : L("در حال تفکر…", "Thinking…")) : ""); el.innerHTML = ` @@ -428,8 +428,16 @@ function renderModalContainer() { let subtitle = ""; if (isDraw) { - title = S.result_reason === "stalemate" ? L("پات — مساوی!", "Stalemate — Draw!") : L("بازی مساوی شد", "Draw!"); - subtitle = L("هیچ‌کدام از طرفین برنده نشد", "No side achieved victory"); + if (S.result_reason === "stalemate") { + title = L("پات — مساوی!", "Stalemate — Draw!"); + subtitle = L("شاه راه حرکتی ندارد", "King has no legal moves"); + } else if (S.result_reason === "insufficient_material") { + title = L("تساوی — عدم کفایت مهره‌ها", "Draw — Insufficient Material"); + subtitle = L("مهره کافی برای مات کردن در صفحه وجود ندارد", "Neither side has sufficient pieces to force checkmate"); + } else { + title = L("بازی مساوی شد", "Draw!"); + subtitle = L("هیچ‌کدام از طرفین برنده نشد", "No side achieved victory"); + } } else { const winnerName = S.players[S.winner!]?.name; title = `${winnerName} ${L("برنده شد! 🏆", "Wins! 🏆")}`; diff --git a/client/assets/index-C5l45jZa.js b/client/assets/index-C5l45jZa.js new file mode 100644 index 0000000..098e7bf --- /dev/null +++ b/client/assets/index-C5l45jZa.js @@ -0,0 +1,122 @@ +(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))t(o);new MutationObserver(o=>{for(const e of o)if(e.type==="childList")for(const a of e.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&t(a)}).observe(document,{childList:!0,subtree:!0});function r(o){const e={};return o.integrity&&(e.integrity=o.integrity),o.referrerPolicy&&(e.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?e.credentials="include":o.crossOrigin==="anonymous"?e.credentials="omit":e.credentials="same-origin",e}function t(o){if(o.ep)return;o.ep=!0;const e=r(o);fetch(o.href,e)}})();function Z(n){const s=new URLSearchParams(location.search).get("host")??"*",r=o=>window.parent.postMessage({m3:1,...o},s);let t=0;return window.addEventListener("message",o=>{var a,f,h;if(o.source!==window.parent||s!=="*"&&o.origin!==s)return;const e=o.data;if(!(!e||e.m3!==1))switch(e.type){case"init":n.onInit(e),r({type:"ready"});break;case"state":n.onState(e.env);break;case"ack":(a=n.onAck)==null||a.call(n,e);break;case"view_changed":(f=n.onViewChanged)==null||f.call(n,e.view);break;case"cmd_failed":(h=n.onCmdFailed)==null||h.call(n,e.req_id,e.code);break}}),r({type:"loaded"}),{cmd(o,e={}){const a=++t;return r({type:"cmd",cmd_type:o,payload:e,req_id:a}),a},toast(o,e,a="info"){r({type:"toast",text_fa:o,text_en:e,kind:a})}}}const tt={k:{w:` + + + + + + + `,b:` + + + + + + + `},q:{w:` + + + + + + + + `,b:` + + + + + + + + `},r:{w:` + + + + + + + `,b:` + + + + + + + `},b:{w:` + + + + + + + + + `,b:` + + + + + + + + + `},n:{w:` + + + + + + + `,b:` + + + + + + + `},p:{w:` + + `,b:` + + `}};function S(n,s){var r;return!n||!s?"":((r=tt[n])==null?void 0:r[s])??""}class et{constructor(s){this.particles=[],this.shockwaves=[],this.animId=null,this.lastTime=0,this.canvas=s,this.ctx=s.getContext("2d"),this.resize(),window.addEventListener("resize",()=>this.resize()),this.startLoop()}resize(){var t,o,e;const s=(t=this.canvas.parentElement)==null?void 0:t.getBoundingClientRect();if(!s)return;const r=window.devicePixelRatio||1;this.canvas.width=Math.round(s.width*r),this.canvas.height=Math.round(s.height*r),this.canvas.style.width=`${s.width}px`,this.canvas.style.height=`${s.height}px`,(e=(o=this.ctx).resetTransform)==null||e.call(o),this.ctx.scale(r,r)}startLoop(){if(this.animId)return;const s=r=>{const t=this.lastTime?Math.min((r-this.lastTime)/1e3,.1):.016;this.lastTime=r,this.update(t),this.render(),this.animId=requestAnimationFrame(s)};this.animId=requestAnimationFrame(s)}update(s){for(let r=this.shockwaves.length-1;r>=0;r--){const t=this.shockwaves[r];t.radius+=(t.maxRadius-t.radius)*12*s,t.alpha-=t.decay*s,(t.alpha<=0||t.radius>=t.maxRadius*.98)&&this.shockwaves.splice(r,1)}for(let r=this.particles.length-1;r>=0;r--){const t=this.particles[r];t.x+=t.vx*s,t.y+=t.vy*s,t.vx*=Math.pow(t.drag,s*60),t.vy*=Math.pow(t.drag,s*60),t.vy+=t.gravity*s,t.vRot&&t.rotation!==void 0&&(t.rotation+=t.vRot*s),t.alpha-=t.decay*s,t.alpha<=0&&this.particles.splice(r,1)}}render(){const s=this.canvas.width/(window.devicePixelRatio||1),r=this.canvas.height/(window.devicePixelRatio||1);this.ctx.clearRect(0,0,s,r);for(const t of this.shockwaves)this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(t.x,t.y,Math.max(1,t.radius),0,Math.PI*2),this.ctx.strokeStyle=t.color,this.ctx.globalAlpha=Math.max(0,t.alpha),this.ctx.lineWidth=t.lineWidth,this.ctx.stroke(),this.ctx.restore();for(const t of this.particles){if(this.ctx.save(),this.ctx.globalAlpha=Math.max(0,t.alpha),this.ctx.fillStyle=t.color,t.shape==="rect"||t.shape==="spark"){this.ctx.translate(t.x,t.y),t.rotation!==void 0&&this.ctx.rotate(t.rotation);const o=t.size||t.radius*2;t.shape==="spark"?this.ctx.fillRect(-o,-o*.25,o*2,o*.5):this.ctx.fillRect(-o*.5,-o*.5,o,o)}else this.ctx.beginPath(),this.ctx.arc(t.x,t.y,Math.max(.5,t.radius),0,Math.PI*2),this.ctx.fill();this.ctx.restore()}}captureImpact(s,r,t="w"){this.shockwaves.push({x:s,y:r,radius:4,maxRadius:48,color:t==="w"?"rgba(255, 235, 180, 0.9)":"rgba(120, 140, 180, 0.9)",alpha:.9,decay:2.8,lineWidth:3});const o=t==="w"?["#ffffff","#fef08a","#f59e0b","#fbbf24"]:["#94a3b8","#cbd5e1","#64748b","#38bdf8"],e=18;for(let a=0;a{if(c<0||c>7||p<0||p>7)return!1;const g=w(c,p),l=t.get(g);return!l||!l.color?(f.push({target:g,isCapture:!1}),!0):(l.color!==r&&f.push({target:g,isCapture:!0}),!1)};switch(o.type){case"p":{const c=r==="w"?1:-1,p=r==="w"?1:6,g=w(e,a+c),l=t.get(g);if(l&&!l.color&&(f.push({target:g,isCapture:!1}),a===p)){const d=w(e,a+c*2),u=t.get(d);u&&!u.color&&f.push({target:d,isCapture:!1})}for(const d of[-1,1])if(e+d>=0&&e+d<=7){const u=w(e+d,a+c),v=t.get(u);v&&v.color&&v.color!==r&&f.push({target:u,isCapture:!0})}break}case"n":{const c=[[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];for(const[p,g]of c){const l=e+p,d=a+g;if(l>=0&&l<=7&&d>=0&&d<=7){const u=w(l,d),v=t.get(u);!v||!v.color?f.push({target:u,isCapture:!1}):v.color!==r&&f.push({target:u,isCapture:!0})}}break}case"b":{const c=[[-1,-1],[-1,1],[1,-1],[1,1]];for(const[p,g]of c){let l=e+p,d=a+g;for(;h(l,d);)l+=p,d+=g}break}case"r":{const c=[[-1,0],[1,0],[0,-1],[0,1]];for(const[p,g]of c){let l=e+p,d=a+g;for(;h(l,d);)l+=p,d+=g}break}case"q":{const c=[[-1,-1],[-1,1],[1,-1],[1,1],[-1,0],[1,0],[0,-1],[0,1]];for(const[p,g]of c){let l=e+p,d=a+g;for(;h(l,d);)l+=p,d+=g}break}case"k":{for(let p=-1;p<=1;p++)for(let g=-1;g<=1;g++){if(p===0&&g===0)continue;const l=e+p,d=a+g;if(l>=0&&l<=7&&d>=0&&d<=7){const u=w(l,d),v=t.get(u);!v||!v.color?f.push({target:u,isCapture:!1}):v.color!==r&&f.push({target:u,isCapture:!0})}}const c=r==="w"?0:7;if(a===c&&e===4){const p=t.get(w(5,c)),g=t.get(w(6,c)),l=t.get(w(7,c));p&&!p.color&&g&&!g.color&&(l==null?void 0:l.type)==="r"&&l.color===r&&f.push({target:w(6,c),isCapture:!1});const d=t.get(w(3,c)),u=t.get(w(2,c)),v=t.get(w(1,c)),m=t.get(w(0,c));d&&!d.color&&u&&!u.color&&v&&!v.color&&(m==null?void 0:m.type)==="r"&&m.color===r&&f.push({target:w(2,c),isCapture:!1})}break}}return f.filter(c=>!ot(n,c.target,s,r))}function ot(n,s,r,t){const o=r.map(l=>{if(l.square===n)return{square:n,type:null,color:null};if(l.square===s){const d=r.find(u=>u.square===n);return{square:s,type:(d==null?void 0:d.type)??null,color:t}}return{...l}}),e=o.find(l=>l.type==="k"&&l.color===t);if(!e)return!1;const{f:a,r:f}=N(e.square),h=t==="w"?"b":"w",c=new Map;for(const l of o)c.set(l.square,l);const p=[[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];for(const[l,d]of p){const u=a+l,v=f+d;if(u>=0&&u<=7&&v>=0&&v<=7){const m=c.get(w(u,v));if(m&&m.color===h&&m.type==="n")return!0}}const g=h==="w"?1:-1;for(const l of[-1,1]){const d=a-l,u=f-g;if(d>=0&&d<=7&&u>=0&&u<=7){const v=c.get(w(d,u));if(v&&v.color===h&&v.type==="p")return!0}}for(const[l,d]of[[-1,0],[1,0],[0,-1],[0,1]]){let u=a+l,v=f+d;for(;u>=0&&u<=7&&v>=0&&v<=7;){const m=c.get(w(u,v));if(m&&m.color){if(m.color===h&&(m.type==="r"||m.type==="q"))return!0;break}u+=l,v+=d}}for(const[l,d]of[[-1,-1],[-1,1],[1,-1],[1,1]]){let u=a+l,v=f+d;for(;u>=0&&u<=7&&v>=0&&v<=7;){const m=c.get(w(u,v));if(m&&m.color){if(m.color===h&&(m.type==="b"||m.type==="q"))return!0;break}u+=l,v+=d}}for(let l=-1;l<=1;l++)for(let d=-1;d<=1;d++){if(l===0&&d===0)continue;const u=a+l,v=f+d;if(u>=0&&u<=7&&v>=0&&v<=7){const m=c.get(w(u,v));if(m&&m.color===h&&m.type==="k")return!0}}return!1}let i=null,H=null,E=null,C=null,b="",y=[],x=null,R=null,V=!1;const k=(n,s)=>(E==null?void 0:E.locale)==="en"?s:n,T=Z({onInit(n){E=n,document.documentElement.lang=n.locale,document.documentElement.dir=n.dir,document.getElementById("board-grid")||O(),z()},onState(n){n.t==="snap"&&(document.getElementById("board-grid")||O(),H=i,i=n.body,st(H,i),i.turn!==i.me&&(b="",y=[],x=null),z())},onAck(n){n.status==="rejected"&&T.toast("حرکت پذیرفته نشد","Move not accepted","warn")}});function st(n,s){var f;if(!n||!s||!C)return;const r=new Map(n.board.map(h=>[h.square,h])),t=new Map(s.board.map(h=>[h.square,h]));let o="",e="",a=null;for(const[h,c]of t.entries()){const p=r.get(h);p&&(p.color&&!c.color?o=h:c.color&&(!p.color||p.color!==c.color||p.type!==c.type)&&(e=h,p.color&&p.color!==c.color&&(a=p)))}if(o&&e){R={from:o,to:e};const h=document.querySelector(`[data-square="${e}"]`);if(h){const c=h.getBoundingClientRect(),p=(f=document.getElementById("vfx-canvas"))==null?void 0:f.getBoundingClientRect();if(p){const l=c.left-p.left+c.width/2,d=c.top-p.top+c.height/2;a?C.captureImpact(l,d,a.color):C.landingPuff(l,d)}const g=h.querySelector(".piece-wrapper");g&&(g.classList.remove("anim-land"),g.offsetWidth,g.classList.add("anim-land"))}}s.phase==="over"&&s.winner!==null&&!V&&(V=!0,setTimeout(()=>C==null?void 0:C.victoryConfetti(),350))}function O(){const n=document.getElementById("app");n.innerHTML=` +
+
+ +
+
+
+ + `;const s=document.getElementById("vfx-canvas");C=new et(s);const r=document.getElementById("board-grid");r.addEventListener("click",t=>{const o=t.target.closest(".cell");o&&o.dataset.square&&!o.disabled&&it(o.dataset.square)});for(let t=0;t<64;t++){const o=document.createElement("button");o.className="cell",o.dataset.index=String(t),r.appendChild(o)}}function z(){var m;if(!i)return;const n=i.me,s=n!=null&&i.players[n]!==void 0;let r,t;s?(r=i.players[n],t=i.players.find(M=>M.seat!==n)||i.players[1-n]):(r=i.players.find(M=>M.color==="w")||i.players[0],t=i.players.find(M=>M.color==="b")||i.players[1]);const o=(r==null?void 0:r.color)||"w",e=o==="b",a=r?i.turn===r.seat&&i.phase==="play":!1,f=t?i.turn===t.seat&&i.phase==="play":!1;_("top-bar",t,f,!1),_("bottom-bar",r,a,s);const h=new Map;for(const M of i.board)h.set(M.square,M);const c=e?[7,6,5,4,3,2,1,0]:[0,1,2,3,4,5,6,7],p=e?[0,1,2,3,4,5,6,7]:[7,6,5,4,3,2,1,0],g=document.getElementById("board-grid");if(!g)return;const l=g.children;let d=0;const u=i.phase==="play"&&i.turn===n,v=i.check&&i.phase==="play"?(m=i.board.find(M=>{var q;return M.type==="k"&&M.color===((q=i.players[i.turn])==null?void 0:q.color)}))==null?void 0:m.square:null;for(const M of p)for(const q of c){const B=String.fromCharCode(97+q)+(M+1),I=h.get(B)||{type:null,color:null},$=l[d++];$.dataset.square=B,$.dataset.color=I.color||"";const F=(q+M)%2===0?"dark":"light",j=b===B,D=R&&(R.from===B||R.to===B),W=v===B;$.className=`cell ${F}`+(j?" selected":"")+(D?" last-move":"")+(W?" in-check":"");const K=y.some(P=>P.target===B),U=y.some(P=>P.target===B&&P.isCapture);let L="";const Y=e?q===7:q===0,G=e?M===7:M===0;if(Y&&(L+=`${M+1}`),G&&(L+=`${String.fromCharCode(97+q)}`),I.type&&I.color){const P=S(I.type,I.color),X=I.type==="n"&&j?" anim-knight":"";L+=`
${P}
`}U?L+='
':K&&(L+='
'),$.innerHTML=L;const J=u&&!0&&I.color===o,Q=b?u:J;$.disabled=!Q}at()}function _(n,s,r,t){const o=document.getElementById(n);if(!o||!s||!i)return;o.className="player-bar"+(r?" active":"");const e=rt(s.color),a=nt(s.color),f=a>0?`+${a}`:"",h=s.bot?'BOT':"",c=t?`${k("شما","YOU")}`:"",p=i.phase==="over"?i.winner===s.seat?k("برنده 🏆","Winner 🏆"):i.winner===null?k("تساوی 🤝","Draw 🤝"):"":r?t?k("نوبت شماست","Your turn"):k("در حال تفکر…","Thinking…"):"";o.innerHTML=` +
+
+ ${s.color==="w"?"♔":"♚"} +
+
+
${s.name} ${h} ${c}
+
${p}
+
+
+
+ ${e.map(g=>`
${S(g.type,g.color)}
`).join("")} + ${f} +
+ `}function rt(n){if(!i)return[];const s=n==="w"?"b":"w",r={p:8,n:2,b:2,r:2,q:1},t={p:0,n:0,b:0,r:0,q:0};for(const e of i.board)e.color===s&&e.type&&t[e.type]!==void 0&&t[e.type]++;const o=[];for(const e of["q","r","b","n","p"]){const a=r[e]-(t[e]||0);for(let f=0;f +
+
${k("ارتقای پیاده به:","Promote pawn to:")}
+
+ ${["q","r","b","n"].map(e=>` + + `).join("")} +
+ +
+ + `,n.querySelectorAll("[data-promo]").forEach(e=>{e.addEventListener("click",()=>{var f;const a=e.dataset.promo;if(x&&a){T.cmd("move",{from:x.from,to:x.to,promotion:a});const h=document.querySelector(`[data-square="${x.to}"]`);if(h){const c=h.getBoundingClientRect(),p=(f=document.getElementById("vfx-canvas"))==null?void 0:f.getBoundingClientRect();p&&(C==null||C.promotionBurst(c.left-p.left+c.width/2,c.top-p.top+c.height/2))}x=null,b="",y=[],z()}})}),(r=n.querySelector("[data-cancel-promo]"))==null||r.addEventListener("click",()=>{x=null,z()});return}if(i.phase==="over"){i.winner!==null&&(i.winner,i.me);const o=i.winner===null;let e="",a="";o?i.result_reason==="stalemate"?(e=k("پات — مساوی!","Stalemate — Draw!"),a=k("شاه راه حرکتی ندارد","King has no legal moves")):i.result_reason==="insufficient_material"?(e=k("تساوی — عدم کفایت مهره‌ها","Draw — Insufficient Material"),a=k("مهره کافی برای مات کردن در صفحه وجود ندارد","Neither side has sufficient pieces to force checkmate")):(e=k("بازی مساوی شد","Draw!"),a=k("هیچ‌کدام از طرفین برنده نشد","No side achieved victory")):(e=`${(t=i.players[i.winner])==null?void 0:t.name} ${k("برنده شد! 🏆","Wins! 🏆")}`,a=i.result_reason==="checkmate"?k("با کیش و مات حریف","By checkmate"):i.result_reason==="abandoned"?k("به دلیل ترک حریف","By abandonment"):""),n.innerHTML=` +
+
${e}
+
${a}
+
+ `;return}n.innerHTML=""}}function it(n){var o;if(!i||i.phase!=="play"||x)return;const s=i.me;if(s==null||i.turn!==s)return;const r=(o=i.players[s])==null?void 0:o.color;if(!r)return;const t=i.board.find(e=>e.square===n);if(b){if(b===n){b="",y=[],z();return}if(t!=null&&t.color&&t.color===r){b=n;try{y=A(n,i.board,r)}catch{y=[]}z();return}const e=i.board.find(f=>f.square===b),a=r==="b"?"1":"8";if((e==null?void 0:e.type)==="p"&&n[1]===a){x={from:b,to:n},b="",y=[],z();return}T.cmd("move",{from:b,to:n}),b="",y=[],z()}else if(t&&t.color===r){b=n;try{y=A(n,i.board,r)}catch{y=[]}z()}} diff --git a/client/index.html b/client/index.html index b83f4b2..5bfc4f6 100644 --- a/client/index.html +++ b/client/index.html @@ -4,7 +4,7 @@ Chess — 3miz - +
…
diff --git a/game.json b/game.json index ee48a8b..a242fab 100644 --- a/game.json +++ b/game.json @@ -2,7 +2,7 @@ "bundle_format": 1, "kind": "source", "game_id": "chess", - "version": "1.3.0", + "version": "1.4.0", "server": { "entry": "server/main.ts" }, "client": { "entry": "index.html" }, "catalog": { diff --git a/manifest.json b/manifest.json index edb2f40..1de0dbe 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 1, "game_id": "chess", - "version": "1.3.0", + "version": "1.4.0", "protocol": "socketio", "protocol_version": 1, "title": { @@ -81,14 +81,14 @@ ], "achievements": [], "client": { - "entry": "https://g.3miz.ir/chess/1.3.0/index.html", + "entry": "https://g.3miz.ir/chess/1.4.0/index.html", "integrity": "sha384-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "aspect": "1:1", "min_width_px": 320, "supports_portrait": true }, "server": { - "image": "registry.3miz.ir/games/chess:1.3.0", + "image": "registry.3miz.ir/games/chess:1.4.0", "max_tables_per_instance": 500, "checkpoint_every_inputs": 20, "snapshot_every_messages": 50, diff --git a/server/bot.ts b/server/bot.ts index 41e253f..6f38b2e 100644 --- a/server/bot.ts +++ b/server/bot.ts @@ -9,6 +9,7 @@ import { isMoveLegalFor, isKingInCheck, isCheckmate, + hasInsufficientMaterial, type State, type Piece, type PieceType, @@ -293,6 +294,7 @@ function quiescence( color: "w" | "b", depthLimit: number ): number { + if (hasInsufficientMaterial(s)) return 0; const standPat = (color === "w" ? 1 : -1) * evaluateStatic(s); if (standPat >= beta) return beta; if (standPat > alpha) alpha = standPat; @@ -333,6 +335,10 @@ function negamax( return -100000 + ply; } + if (hasInsufficientMaterial(s)) { + return 0; // Drawn position + } + if (depth <= 0) { if (quiesceDepth > 0) { return quiescence(s, alpha, beta, color, quiesceDepth); diff --git a/server/game.ts b/server/game.ts index 98ced68..58f4e89 100644 --- a/server/game.ts +++ b/server/game.ts @@ -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); } diff --git a/server/package.json b/server/package.json index 517bc5e..c125b4e 100644 --- a/server/package.json +++ b/server/package.json @@ -1,6 +1,6 @@ { "name": "@3miz/chess-server", - "version": "1.3.0", + "version": "1.4.0", "private": true, "type": "module", "scripts": { "start": "tsx main.ts", "test": "node --test --import tsx ../tests/*.test.ts" }, diff --git a/tests/game.test.ts b/tests/game.test.ts index 4762c2c..16e3818 100644 --- a/tests/game.test.ts +++ b/tests/game.test.ts @@ -2,7 +2,7 @@ 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"; +import { chess, isCheckmate, isKingInCheck, isStalemate, hasInsufficientMaterial, type State } from "../server/game.ts"; export const squareIndex = (name: string): number => { const f = name.charCodeAt(0) - 97; @@ -244,3 +244,123 @@ test("stalemate: lone king with no flight squares is a draw", () => { assert.equal(isCheckmate(s, "b"), false); assert.equal(isStalemate(s, "b"), true); }); + +test("insufficient material: K vs K, KB vs K, KN vs K, KB vs KB, KN vs KN are recognized", () => { + 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 makeState = (pieces: { sq: string; type: "k" | "p" | "r" | "n" | "b" | "q"; color: "w" | "b" }[]): State => { + const s: State = { + players: [mk(0, "u0", "w"), mk(1, "u1", "b")], + board: Array(64).fill(null) as State["board"], + turn: 0, phase: "play", winner: null, result_reason: "", + turn_ms: 60000, timer_n: 0, timer_id: null, deadline: null, bot_timer: null, bot_n: 0, + moves_played: 40, captures: 28, + rights: { wk: false, wq: false, bk: false, bq: false }, ep: null, + }; + for (const p of pieces) { + s.board[squareIndex(p.sq)] = { type: p.type, color: p.color }; + } + return s; + }; + + // 1. King vs King + const kVsK = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(kVsK), true); + + // 2. King + Bishop vs King + const kbVsK = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "c4", type: "b", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(kbVsK), true); + + // 3. King + Knight vs King + const knVsK = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + { sq: "f6", type: "n", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(knVsK), true); + + // 4. King + Bishop vs King + Bishop + const kbVsKb = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "c1", type: "b", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + { sq: "c8", type: "b", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(kbVsKb), true); + + // 5. King + Knight vs King + Knight + const knVsKn = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "b1", type: "n", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + { sq: "b8", type: "n", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(knVsKn), true); + + // 6. Pawn exists -> NOT insufficient (can promote) + const withPawn = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "a2", type: "p", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(withPawn), false); + + // 7. Queen or Rook exists -> NOT insufficient + const withRook = makeState([ + { sq: "e1", type: "k", color: "w" }, + { sq: "a1", type: "r", color: "w" }, + { sq: "e8", type: "k", color: "b" }, + ]); + assert.equal(hasInsufficientMaterial(withRook), false); +}); + +test("insufficient material: capturing last pawn triggers draw immediately", () => { + 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 s0: State = { + players: [mk(0, "u0", "w"), mk(1, "u1", "b")], + board: Array(64).fill(null) as State["board"], + turn: 0, phase: "play", winner: null, result_reason: "", + turn_ms: 60000, timer_n: 0, timer_id: null, deadline: null, bot_timer: null, bot_n: 0, + moves_played: 50, captures: 29, + rights: { wk: false, wq: false, bk: false, bq: false }, ep: null, + }; + s0.board[squareIndex("d4")] = { type: "k", color: "w" }; + s0.board[squareIndex("d5")] = { type: "p", color: "b" }; + s0.board[squareIndex("f8")] = { type: "k", color: "b" }; + + const w = { + create: create(false), + game: s0, + status: "running", + seq: 1, + vseq: {}, + sseq: 1, + timers: {}, + last_cid: {}, + snap_hash: {}, + sys_hash: "", + result: null, + rng: [1, 2, 3, 4], + last_ts_ms: 1700000000000, + }; + + // White king captures the black pawn on d5 -> only Kings left! + const res = applyInput(chess, w as any, { + v: 1, type: "move", payload: { from: "d4", to: "d5" }, + uid: "u0", ci: "c0", cid: 1, role: "player", seat: 0, ts_ms: 1700000001000, + } as Input, 1); + + assert.equal(res.status, "accepted"); + assert.equal((w.game as State).phase, "over"); + assert.equal((w.game as State).winner, null); + assert.equal((w.game as State).result_reason, "insufficient_material"); + assert.equal(w.status, "finished"); +});