UNPKG

chess-trainer-mcp

Version:

Chess Trainer MCP Server with Stockfish NNUE engine - Interactive chess training with AI coaching capabilities

1 lines 57.9 kB
class Pt{unwrap(t,n){const r=this._chain(i=>g.ok(t?t(i):i),i=>n?g.ok(n(i)):g.err(i));if(r.isErr)throw r.error;return r.value}map(t,n){return this._chain(r=>g.ok(t(r)),r=>g.err(n?n(r):r))}chain(t,n){return this._chain(t,n||(r=>g.err(r)))}}class on extends Pt{constructor(t){super(),this.value=void 0,this.isOk=!0,this.isErr=!1,this.value=t}_chain(t,n){return t(this.value)}}class sn extends Pt{constructor(t){super(),this.error=void 0,this.isOk=!1,this.isErr=!0,this.error=t}_chain(t,n){return n(this.error)}}var g;(function(e){e.ok=function(t){return new on(t)},e.err=function(t){return new sn(t||new Error)},e.all=function(t){if(Array.isArray(t)){const i=[];for(let o=0;o<t.length;o++){const s=t[o];if(s.isErr)return s;i.push(s.value)}return e.ok(i)}const n={},r=Object.keys(t);for(let i=0;i<r.length;i++){const o=t[r[i]];if(o.isErr)return o;n[r[i]]=o.value}return e.ok(n)}})(g||(g={}));const Pe=["a","b","c","d","e","f","g","h"],Et=["1","2","3","4","5","6","7","8"],X=["white","black"],B=["pawn","knight","bishop","rook","queen","king"],cn=["a","h"],ge=e=>"role"in e,at=e=>(e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),Math.imul(e+(e>>>4)&252645135,16843009)>>24),We=e=>(e=e>>>8&16711935|(e&16711935)<<8,e>>>16&65535|(e&65535)<<16),lt=e=>(e=e>>>1&1431655765|(e&1431655765)<<1,e=e>>>2&858993459|(e&858993459)<<2,e=e>>>4&252645135|(e&252645135)<<4,We(e));class a{constructor(t,n){this.lo=t|0,this.hi=n|0}static fromSquare(t){return t>=32?new a(0,1<<t-32):new a(1<<t,0)}static fromRank(t){return new a(255,0).shl64(8*t)}static fromFile(t){return new a(16843009<<t,16843009<<t)}static empty(){return new a(0,0)}static full(){return new a(4294967295,4294967295)}static corners(){return new a(129,2164260864)}static center(){return new a(402653184,24)}static backranks(){return new a(255,4278190080)}static backrank(t){return t==="white"?new a(255,0):new a(0,4278190080)}static lightSquares(){return new a(1437226410,1437226410)}static darkSquares(){return new a(2857740885,2857740885)}complement(){return new a(~this.lo,~this.hi)}xor(t){return new a(this.lo^t.lo,this.hi^t.hi)}union(t){return new a(this.lo|t.lo,this.hi|t.hi)}intersect(t){return new a(this.lo&t.lo,this.hi&t.hi)}diff(t){return new a(this.lo&~t.lo,this.hi&~t.hi)}intersects(t){return this.intersect(t).nonEmpty()}isDisjoint(t){return this.intersect(t).isEmpty()}supersetOf(t){return t.diff(this).isEmpty()}subsetOf(t){return this.diff(t).isEmpty()}shr64(t){return t>=64?a.empty():t>=32?new a(this.hi>>>t-32,0):t>0?new a(this.lo>>>t^this.hi<<32-t,this.hi>>>t):this}shl64(t){return t>=64?a.empty():t>=32?new a(0,this.lo<<t-32):t>0?new a(this.lo<<t,this.hi<<t^this.lo>>>32-t):this}bswap64(){return new a(We(this.hi),We(this.lo))}rbit64(){return new a(lt(this.hi),lt(this.lo))}minus64(t){const n=this.lo-t.lo,r=(n&t.lo&1)+(t.lo>>>1)+(n>>>1)>>>31;return new a(n,this.hi-(t.hi+r))}equals(t){return this.lo===t.lo&&this.hi===t.hi}size(){return at(this.lo)+at(this.hi)}isEmpty(){return this.lo===0&&this.hi===0}nonEmpty(){return this.lo!==0||this.hi!==0}has(t){return(t>=32?this.hi&1<<t-32:this.lo&1<<t)!==0}set(t,n){return n?this.with(t):this.without(t)}with(t){return t>=32?new a(this.lo,this.hi|1<<t-32):new a(this.lo|1<<t,this.hi)}without(t){return t>=32?new a(this.lo,this.hi&~(1<<t-32)):new a(this.lo&~(1<<t),this.hi)}toggle(t){return t>=32?new a(this.lo,this.hi^1<<t-32):new a(this.lo^1<<t,this.hi)}last(){if(this.hi!==0)return 63-Math.clz32(this.hi);if(this.lo!==0)return 31-Math.clz32(this.lo)}first(){if(this.lo!==0)return 31-Math.clz32(this.lo&-this.lo);if(this.hi!==0)return 63-Math.clz32(this.hi&-this.hi)}withoutFirst(){return this.lo!==0?new a(this.lo&this.lo-1,this.hi):new a(0,this.hi&this.hi-1)}moreThanOne(){return this.hi!==0&&this.lo!==0||(this.lo&this.lo-1)!==0||(this.hi&this.hi-1)!==0}singleSquare(){return this.moreThanOne()?void 0:this.last()}*[Symbol.iterator](){let t=this.lo,n=this.hi;for(;t!==0;){const r=31-Math.clz32(t&-t);t^=1<<r,yield r}for(;n!==0;){const r=31-Math.clz32(n&-n);n^=1<<r,yield 32+r}}*reversed(){let t=this.lo,n=this.hi;for(;n!==0;){const r=31-Math.clz32(n);n^=1<<r,yield 32+r}for(;t!==0;){const r=31-Math.clz32(t);t^=1<<r,yield r}}}class se{constructor(){}static default(){const t=new se;return t.reset(),t}reset(){this.occupied=new a(65535,4294901760),this.promoted=a.empty(),this.white=new a(65535,0),this.black=new a(0,4294901760),this.pawn=new a(65280,16711680),this.knight=new a(66,1107296256),this.bishop=new a(36,603979776),this.rook=new a(129,2164260864),this.queen=new a(8,134217728),this.king=new a(16,268435456)}static empty(){const t=new se;return t.clear(),t}clear(){this.occupied=a.empty(),this.promoted=a.empty();for(const t of X)this[t]=a.empty();for(const t of B)this[t]=a.empty()}clone(){const t=new se;t.occupied=this.occupied,t.promoted=this.promoted;for(const n of X)t[n]=this[n];for(const n of B)t[n]=this[n];return t}getColor(t){if(this.white.has(t))return"white";if(this.black.has(t))return"black"}getRole(t){for(const n of B)if(this[n].has(t))return n}get(t){const n=this.getColor(t);if(!n)return;const r=this.getRole(t),i=this.promoted.has(t);return{color:n,role:r,promoted:i}}take(t){const n=this.get(t);return n&&(this.occupied=this.occupied.without(t),this[n.color]=this[n.color].without(t),this[n.role]=this[n.role].without(t),n.promoted&&(this.promoted=this.promoted.without(t))),n}set(t,n){const r=this.take(t);return this.occupied=this.occupied.with(t),this[n.color]=this[n.color].with(t),this[n.role]=this[n.role].with(t),n.promoted&&(this.promoted=this.promoted.with(t)),r}has(t){return this.occupied.has(t)}*[Symbol.iterator](){for(const t of this.occupied)yield[t,this.get(t)]}pieces(t,n){return this[t].intersect(this[n])}rooksAndQueens(){return this.rook.union(this.queen)}bishopsAndQueens(){return this.bishop.union(this.queen)}kingOf(t){return this.pieces(t,"king").singleSquare()}}const d=e=>e!==void 0,E=e=>e==="white"?"black":"white",J=e=>e>>3,A=e=>e&7,Fe=(e,t)=>0<=e&&e<8&&0<=t&&t<8?e+8*t:void 0,Y=e=>{switch(e){case"pawn":return"p";case"knight":return"n";case"bishop":return"b";case"rook":return"r";case"queen":return"q";case"king":return"k"}};function ce(e){switch(e.toLowerCase()){case"p":return"pawn";case"n":return"knight";case"b":return"bishop";case"r":return"rook";case"q":return"queen";case"k":return"king";default:return}}function ae(e){if(e.length===2)return Fe(e.charCodeAt(0)-97,e.charCodeAt(1)-49)}const j=e=>Pe[A(e)]+Et[J(e)],Vr=e=>{if(e[1]==="@"&&e.length===4){const t=ce(e[0]),n=ae(e.slice(2));if(t&&d(n))return{role:t,to:n}}else if(e.length===4||e.length===5){const t=ae(e.slice(0,2)),n=ae(e.slice(2,4));let r;if(e.length===5&&(r=ce(e[4]),!r))return;if(d(t)&&d(n))return{from:t,to:n,promotion:r}}},Qr=e=>ge(e)?`${Y(e.role).toUpperCase()}@${j(e.to)}`:j(e.from)+j(e.to)+(e.promotion?Y(e.promotion):""),Ze=(e,t)=>e==="white"?t==="a"?2:6:t==="a"?58:62,Ye=(e,t)=>e==="white"?t==="a"?3:5:t==="a"?59:61,Ee=(e,t)=>{let n=a.empty();for(const r of t){const i=e+r;0<=i&&i<64&&Math.abs(A(e)-A(i))<=2&&(n=n.with(i))}return n},q=e=>{const t=[];for(let n=0;n<64;n++)t[n]=e(n);return t},an=q(e=>Ee(e,[-9,-8,-7,-1,1,7,8,9])),ln=q(e=>Ee(e,[-17,-15,-10,-6,6,10,15,17])),hn={white:q(e=>Ee(e,[7,9])),black:q(e=>Ee(e,[-7,-9]))},Te=e=>an[e],De=e=>ln[e],ke=(e,t)=>hn[e][t],_e=q(e=>a.fromFile(A(e)).without(e)),He=q(e=>a.fromRank(J(e)).without(e)),Ie=q(e=>{const t=new a(134480385,2151686160),n=8*(J(e)-A(e));return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),je=q(e=>{const t=new a(270549120,16909320),n=8*(J(e)+A(e)-7);return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),qe=(e,t,n)=>{let r=n.intersect(t),i=r.bswap64();return r=r.minus64(e),i=i.minus64(e.bswap64()),r.xor(i.bswap64()).intersect(t)},un=(e,t)=>qe(a.fromSquare(e),_e[e],t),fn=(e,t)=>{const n=He[e];let r=t.intersect(n),i=r.rbit64();return r=r.minus64(a.fromSquare(e)),i=i.minus64(a.fromSquare(63-e)),r.xor(i.rbit64()).intersect(n)},le=(e,t)=>{const n=a.fromSquare(e);return qe(n,Ie[e],t).xor(qe(n,je[e],t))},he=(e,t)=>un(e,t).xor(fn(e,t)),Xe=(e,t)=>le(e,t).xor(he(e,t)),dn=(e,t,n)=>{switch(e.role){case"pawn":return ke(e.color,t);case"knight":return De(t);case"bishop":return le(t,n);case"rook":return he(t,n);case"queen":return Xe(t,n);case"king":return Te(t)}},Mt=(e,t)=>{const n=a.fromSquare(t);return He[e].intersects(n)?He[e].with(e):je[e].intersects(n)?je[e].with(e):Ie[e].intersects(n)?Ie[e].with(e):_e[e].intersects(n)?_e[e].with(e):a.empty()},me=(e,t)=>Mt(e,t).intersect(a.full().shl64(e).xor(a.full().shl64(t))).withoutFirst();var I;(function(e){e.Empty="ERR_EMPTY",e.OppositeCheck="ERR_OPPOSITE_CHECK",e.PawnsOnBackrank="ERR_PAWNS_ON_BACKRANK",e.Kings="ERR_KINGS",e.Variant="ERR_VARIANT"})(I||(I={}));class re extends Error{}const pn=(e,t,n,r)=>n[t].intersect(he(e,r).intersect(n.rooksAndQueens()).union(le(e,r).intersect(n.bishopsAndQueens())).union(De(e).intersect(n.knight)).union(Te(e).intersect(n.king)).union(ke(E(t),e).intersect(n.pawn)));class Z{constructor(){}static default(){const t=new Z;return t.castlingRights=a.corners(),t.rook={white:{a:0,h:7},black:{a:56,h:63}},t.path={white:{a:new a(14,0),h:new a(96,0)},black:{a:new a(0,234881024),h:new a(0,1610612736)}},t}static empty(){const t=new Z;return t.castlingRights=a.empty(),t.rook={white:{a:void 0,h:void 0},black:{a:void 0,h:void 0}},t.path={white:{a:a.empty(),h:a.empty()},black:{a:a.empty(),h:a.empty()}},t}clone(){const t=new Z;return t.castlingRights=this.castlingRights,t.rook={white:{a:this.rook.white.a,h:this.rook.white.h},black:{a:this.rook.black.a,h:this.rook.black.h}},t.path={white:{a:this.path.white.a,h:this.path.white.h},black:{a:this.path.black.a,h:this.path.black.h}},t}add(t,n,r,i){const o=Ze(t,n),s=Ye(t,n);this.castlingRights=this.castlingRights.with(i),this.rook[t][n]=i,this.path[t][n]=me(i,s).with(s).union(me(r,o).with(o)).without(r).without(i)}static fromSetup(t){const n=Z.empty(),r=t.castlingRights.intersect(t.board.rook);for(const i of X){const o=a.backrank(i),s=t.board.kingOf(i);if(!d(s)||!o.has(s))continue;const c=r.intersect(t.board[i]).intersect(o),h=c.first();d(h)&&h<s&&n.add(i,"a",s,h);const l=c.last();d(l)&&s<l&&n.add(i,"h",s,l)}return n}discardRook(t){if(this.castlingRights.has(t)){this.castlingRights=this.castlingRights.without(t);for(const n of X)for(const r of cn)this.rook[n][r]===t&&(this.rook[n][r]=void 0)}}discardColor(t){this.castlingRights=this.castlingRights.diff(a.backrank(t)),this.rook[t].a=void 0,this.rook[t].h=void 0}}class gn{constructor(t){this.rules=t}reset(){this.board=se.default(),this.pockets=void 0,this.turn="white",this.castles=Z.default(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){this.board=t.board.clone(),this.board.promoted=a.empty(),this.pockets=void 0,this.turn=t.turn,this.castles=Z.fromSetup(t),this.epSquare=mn(this,t.epSquare),this.remainingChecks=void 0,this.halfmoves=t.halfmoves,this.fullmoves=t.fullmoves}kingAttackers(t,n,r){return pn(t,n,this.board,r)}playCaptureAt(t,n){this.halfmoves=0,n.role==="rook"&&this.castles.discardRook(t),this.pockets&&this.pockets[E(n.color)][n.promoted?"pawn":n.role]++}ctx(){const t=this.isVariantEnd(),n=this.board.kingOf(this.turn);if(!d(n))return{king:n,blockers:a.empty(),checkers:a.empty(),variantEnd:t,mustCapture:!1};const r=he(n,a.empty()).intersect(this.board.rooksAndQueens()).union(le(n,a.empty()).intersect(this.board.bishopsAndQueens())).intersect(this.board[E(this.turn)]);let i=a.empty();for(const s of r){const c=me(n,s).intersect(this.board.occupied);c.moreThanOne()||(i=i.union(c))}const o=this.kingAttackers(n,E(this.turn),this.board.occupied);return{king:n,blockers:i,checkers:o,variantEnd:t,mustCapture:!1}}clone(){var t,n;const r=new this.constructor;return r.board=this.board.clone(),r.pockets=(t=this.pockets)===null||t===void 0?void 0:t.clone(),r.turn=this.turn,r.castles=this.castles.clone(),r.epSquare=this.epSquare,r.remainingChecks=(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),r.halfmoves=this.halfmoves,r.fullmoves=this.fullmoves,r}validate(){if(this.board.occupied.isEmpty())return g.err(new re(I.Empty));if(this.board.king.size()!==2)return g.err(new re(I.Kings));if(!d(this.board.kingOf(this.turn)))return g.err(new re(I.Kings));const t=this.board.kingOf(E(this.turn));return d(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?g.err(new re(I.OppositeCheck)):a.backranks().intersects(this.board.pawn)?g.err(new re(I.PawnsOnBackrank)):g.ok(void 0):g.err(new re(I.Kings))}dropDests(t){return a.empty()}dests(t,n){if(n=n||this.ctx(),n.variantEnd)return a.empty();const r=this.board.get(t);if(!r||r.color!==this.turn)return a.empty();let i,o;if(r.role==="pawn"){i=ke(this.turn,t).intersect(this.board[E(this.turn)]);const s=this.turn==="white"?8:-8,c=t+s;if(0<=c&&c<64&&!this.board.occupied.has(c)){i=i.with(c);const h=this.turn==="white"?t<16:t>=48,l=c+s;h&&!this.board.occupied.has(l)&&(i=i.with(l))}d(this.epSquare)&&bn(this,t,n)&&(o=a.fromSquare(this.epSquare))}else r.role==="bishop"?i=le(t,this.board.occupied):r.role==="knight"?i=De(t):r.role==="rook"?i=he(t,this.board.occupied):r.role==="queen"?i=Xe(t,this.board.occupied):i=Te(t);if(i=i.diff(this.board[this.turn]),d(n.king)){if(r.role==="king"){const s=this.board.occupied.without(t);for(const c of i)this.kingAttackers(c,E(this.turn),s).nonEmpty()&&(i=i.without(c));return i.union(ht(this,"a",n)).union(ht(this,"h",n))}if(n.checkers.nonEmpty()){const s=n.checkers.singleSquare();if(!d(s))return a.empty();i=i.intersect(me(s,n.king).with(s))}n.blockers.has(t)&&(i=i.intersect(Mt(t,n.king)))}return o&&(i=i.union(o)),i}isVariantEnd(){return!1}variantOutcome(t){}hasInsufficientMaterial(t){return this.board[t].intersect(this.board.pawn.union(this.board.rooksAndQueens())).nonEmpty()?!1:this.board[t].intersects(this.board.knight)?this.board[t].size()<=2&&this.board[E(t)].diff(this.board.king).diff(this.board.queen).isEmpty():this.board[t].intersects(this.board.bishop)?(!this.board.bishop.intersects(a.darkSquares())||!this.board.bishop.intersects(a.lightSquares()))&&this.board.pawn.isEmpty()&&this.board.knight.isEmpty():!0}toSetup(){var t,n;return{board:this.board.clone(),pockets:(t=this.pockets)===null||t===void 0?void 0:t.clone(),turn:this.turn,castlingRights:this.castles.castlingRights,epSquare:wn(this),remainingChecks:(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),halfmoves:Math.min(this.halfmoves,150),fullmoves:Math.min(Math.max(this.fullmoves,1),9999)}}isInsufficientMaterial(){return X.every(t=>this.hasInsufficientMaterial(t))}hasDests(t){t=t||this.ctx();for(const n of this.board[this.turn])if(this.dests(n,t).nonEmpty())return!0;return this.dropDests(t).nonEmpty()}isLegal(t,n){if(ge(t))return!this.pockets||this.pockets[this.turn][t.role]<=0||t.role==="pawn"&&a.backranks().has(t.to)?!1:this.dropDests(n).has(t.to);{if(t.promotion==="pawn"||t.promotion==="king"&&this.rules!=="antichess"||!!t.promotion!==(this.board.pawn.has(t.from)&&a.backranks().has(t.to)))return!1;const r=this.dests(t.from,n);return r.has(t.to)||r.has(kn(this,t).to)}}isCheck(){const t=this.board.kingOf(this.turn);return d(t)&&this.kingAttackers(t,E(this.turn),this.board.occupied).nonEmpty()}isEnd(t){return(t?t.variantEnd:this.isVariantEnd())?!0:this.isInsufficientMaterial()||!this.hasDests(t)}isCheckmate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.nonEmpty()&&!this.hasDests(t)}isStalemate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.isEmpty()&&!this.hasDests(t)}outcome(t){const n=this.variantOutcome(t);return n||(t=t||this.ctx(),this.isCheckmate(t)?{winner:E(this.turn)}:this.isInsufficientMaterial()||this.isStalemate(t)?{winner:void 0}:void 0)}allDests(t){t=t||this.ctx();const n=new Map;if(t.variantEnd)return n;for(const r of this.board[this.turn])n.set(r,this.dests(r,t));return n}play(t){const n=this.turn,r=this.epSquare,i=At(this,t);if(this.epSquare=void 0,this.halfmoves+=1,n==="black"&&(this.fullmoves+=1),this.turn=E(n),ge(t))this.board.set(t.to,{role:t.role,color:n}),this.pockets&&this.pockets[n][t.role]--,t.role==="pawn"&&(this.halfmoves=0);else{const o=this.board.take(t.from);if(!o)return;let s;if(o.role==="pawn"){this.halfmoves=0,t.to===r&&(s=this.board.take(t.to+(n==="white"?-8:8)));const c=t.from-t.to;Math.abs(c)===16&&8<=t.from&&t.from<=55&&(this.epSquare=t.from+t.to>>1),t.promotion&&(o.role=t.promotion,o.promoted=!!this.pockets)}else if(o.role==="rook")this.castles.discardRook(t.from);else if(o.role==="king"){if(i){const c=this.castles.rook[n][i];if(d(c)){const h=this.board.take(c);this.board.set(Ze(n,i),o),h&&this.board.set(Ye(n,i),h)}}this.castles.discardColor(n)}if(!i){const c=this.board.set(t.to,o)||s;c&&this.playCaptureAt(t.to,c)}}this.remainingChecks&&this.isCheck()&&(this.remainingChecks[n]=Math.max(this.remainingChecks[n]-1,0))}}class Zr extends gn{constructor(){super("chess")}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(r=>n)}clone(){return super.clone()}}const mn=(e,t)=>{if(!d(t))return;const n=e.turn==="white"?5:2,r=e.turn==="white"?8:-8;if(J(t)!==n||e.board.occupied.has(t+r))return;const i=t-r;if(!(!e.board.pawn.has(i)||!e.board[E(e.turn)].has(i)))return t},wn=e=>{if(!d(e.epSquare))return;const t=e.ctx(),r=e.board.pieces(e.turn,"pawn").intersect(ke(E(e.turn),e.epSquare));for(const i of r)if(e.dests(i,t).has(e.epSquare))return e.epSquare},bn=(e,t,n)=>{if(!d(e.epSquare)||!ke(e.turn,t).has(e.epSquare))return!1;if(!d(n.king))return!0;const r=e.turn==="white"?8:-8,i=e.epSquare-r;return e.kingAttackers(n.king,E(e.turn),e.board.occupied.toggle(t).toggle(i).with(e.epSquare)).without(i).isEmpty()},ht=(e,t,n)=>{if(!d(n.king)||n.checkers.nonEmpty())return a.empty();const r=e.castles.rook[e.turn][t];if(!d(r)||e.castles.path[e.turn][t].intersects(e.board.occupied))return a.empty();const i=Ze(e.turn,t),o=me(n.king,i),s=e.board.occupied.without(n.king);for(const l of o)if(e.kingAttackers(l,E(e.turn),s).nonEmpty())return a.empty();const c=Ye(e.turn,t),h=e.board.occupied.toggle(n.king).toggle(r).toggle(c);return e.kingAttackers(i,E(e.turn),h).nonEmpty()?a.empty():a.fromSquare(r)},At=(e,t)=>{if(ge(t))return;const n=t.to-t.from;if(!(Math.abs(n)!==2&&!e.board[e.turn].has(t.to))&&e.board.king.has(t.from))return n>0?"h":"a"},kn=(e,t)=>{const n=At(e,t);if(!n)return t;const r=e.castles.rook[e.turn][n];return{from:t.from,to:d(r)?r:t.to}};class F{constructor(){}static empty(){const t=new F;for(const n of B)t[n]=0;return t}static fromBoard(t,n){const r=new F;for(const i of B)r[i]=t.pieces(n,i).size();return r}clone(){const t=new F;for(const n of B)t[n]=this[n];return t}equals(t){return B.every(n=>this[n]===t[n])}add(t){const n=new F;for(const r of B)n[r]=this[r]+t[r];return n}nonEmpty(){return B.some(t=>this[t]>0)}isEmpty(){return!this.nonEmpty()}hasPawns(){return this.pawn>0}hasNonPawns(){return this.knight>0||this.bishop>0||this.rook>0||this.queen>0||this.king>0}size(){return this.pawn+this.knight+this.bishop+this.rook+this.queen+this.king}}class ie{constructor(t,n){this.white=t,this.black=n}static empty(){return new ie(F.empty(),F.empty())}static fromBoard(t){return new ie(F.fromBoard(t,"white"),F.fromBoard(t,"black"))}clone(){return new ie(this.white.clone(),this.black.clone())}equals(t){return this.white.equals(t.white)&&this.black.equals(t.black)}add(t){return new ie(this.white.add(t.white),this.black.add(t.black))}count(t){return this.white[t]+this.black[t]}size(){return this.white.size()+this.black.size()}isEmpty(){return this.white.isEmpty()&&this.black.isEmpty()}nonEmpty(){return!this.isEmpty()}hasPawns(){return this.white.hasPawns()||this.black.hasPawns()}hasNonPawns(){return this.white.hasNonPawns()||this.black.hasNonPawns()}}class we{constructor(t,n){this.white=t,this.black=n}static default(){return new we(3,3)}clone(){return new we(this.white,this.black)}equals(t){return this.white===t.white&&this.black===t.black}}var y;(function(e){e.Fen="ERR_FEN",e.Board="ERR_BOARD",e.Pockets="ERR_POCKETS",e.Turn="ERR_TURN",e.Castling="ERR_CASTLING",e.EpSquare="ERR_EP_SQUARE",e.RemainingChecks="ERR_REMAINING_CHECKS",e.Halfmoves="ERR_HALFMOVES",e.Fullmoves="ERR_FULLMOVES"})(y||(y={}));class M extends Error{}const vn=(e,t,n)=>{let r=e.indexOf(t);for(;n-- >0&&r!==-1;)r=e.indexOf(t,r+t.length);return r},oe=e=>/^\d{1,4}$/.test(e)?parseInt(e,10):void 0,Rt=e=>{const t=ce(e);return t&&{role:t,color:e.toLowerCase()===e?"black":"white"}},Ke=e=>{const t=se.empty();let n=7,r=0;for(let i=0;i<e.length;i++){const o=e[i];if(o==="/"&&r===8)r=0,n--;else{const s=parseInt(o,10);if(s>0)r+=s;else{if(r>=8||n<0)return g.err(new M(y.Board));const c=r+n*8,h=Rt(o);if(!h)return g.err(new M(y.Board));e[i+1]==="~"&&(h.promoted=!0,i++),t.set(c,h),r++}}}return n!==0||r!==8?g.err(new M(y.Board)):g.ok(t)},ut=e=>{if(e.length>64)return g.err(new M(y.Pockets));const t=ie.empty();for(const n of e){const r=Rt(n);if(!r)return g.err(new M(y.Pockets));t[r.color][r.role]++}return g.ok(t)},yn=(e,t)=>{let n=a.empty();if(t==="-")return g.ok(n);for(const r of t){const i=r.toLowerCase(),o=r===i?"black":"white",s=o==="white"?0:7;if("a"<=i&&i<="h")n=n.with(Fe(i.charCodeAt(0)-97,s));else if(i==="k"||i==="q"){const c=e[o].intersect(a.backrank(o)).intersect(e.rook.union(e.king)),h=i==="k"?c.last():c.first();n=n.with(d(h)&&e.rook.has(h)?h:Fe(i==="k"?7:0,s))}else return g.err(new M(y.Castling))}return X.some(r=>a.backrank(r).intersect(n).size()>2)?g.err(new M(y.Castling)):g.ok(n)},ft=e=>{const t=e.split("+");if(t.length===3&&t[0]===""){const n=oe(t[1]),r=oe(t[2]);return!d(n)||n>3||!d(r)||r>3?g.err(new M(y.RemainingChecks)):g.ok(new we(3-n,3-r))}else if(t.length===2){const n=oe(t[0]),r=oe(t[1]);return!d(n)||n>3||!d(r)||r>3?g.err(new M(y.RemainingChecks)):g.ok(new we(n,r))}else return g.err(new M(y.RemainingChecks))},Yr=e=>{const t=e.split(/[\s_]+/),n=t.shift();let r,i=g.ok(void 0);if(n.endsWith("]")){const c=n.indexOf("[");if(c===-1)return g.err(new M(y.Fen));r=Ke(n.slice(0,c)),i=ut(n.slice(c+1,-1))}else{const c=vn(n,"/",7);c===-1?r=Ke(n):(r=Ke(n.slice(0,c)),i=ut(n.slice(c+1)))}let o;const s=t.shift();if(!d(s)||s==="w")o="white";else if(s==="b")o="black";else return g.err(new M(y.Turn));return r.chain(c=>{const h=t.shift(),l=d(h)?yn(c,h):g.ok(a.empty()),f=t.shift();let u;if(d(f)&&f!=="-"&&(u=ae(f),!d(u)))return g.err(new M(y.EpSquare));let w=t.shift(),m;d(w)&&w.includes("+")&&(m=ft(w),w=t.shift());const b=d(w)?oe(w):0;if(!d(b))return g.err(new M(y.Halfmoves));const p=t.shift(),T=d(p)?oe(p):1;if(!d(T))return g.err(new M(y.Fullmoves));const S=t.shift();let P=g.ok(void 0);if(d(S)){if(d(m))return g.err(new M(y.RemainingChecks));P=ft(S)}else d(m)&&(P=m);return t.length>0?g.err(new M(y.Fen)):i.chain(V=>l.chain(ue=>P.map(D=>({board:c,pockets:V,turn:o,castlingRights:ue,remainingChecks:D,epSquare:u,halfmoves:b,fullmoves:Math.max(1,T)}))))})},Cn=e=>{let t=Y(e.role);return e.color==="white"&&(t=t.toUpperCase()),e.promoted&&(t+="~"),t},Pn=e=>{let t="",n=0;for(let r=7;r>=0;r--)for(let i=0;i<8;i++){const o=i+r*8,s=e.get(o);s?(n>0&&(t+=n,n=0),t+=Cn(s)):n++,i===7&&(n>0&&(t+=n,n=0),r!==0&&(t+="/"))}return t},dt=e=>B.map(t=>Y(t).repeat(e[t])).join(""),En=e=>dt(e.white).toUpperCase()+dt(e.black),Mn=(e,t)=>{let n="";for(const r of X){const i=a.backrank(r);let o=e.kingOf(r);d(o)&&!i.has(o)&&(o=void 0);const s=e.pieces(r,"rook").intersect(i);for(const c of t.intersect(i).reversed())if(c===s.first()&&d(o)&&c<o)n+=r==="white"?"Q":"q";else if(c===s.last()&&d(o)&&o<c)n+=r==="white"?"K":"k";else{const h=Pe[A(c)];n+=r==="white"?h.toUpperCase():h}}return n||"-"},An=e=>`${e.white}+${e.black}`,Xr=(e,t)=>[Pn(e.board)+(e.pockets?`[${En(e.pockets)}]`:""),e.turn[0],Mn(e.board,e.castlingRights),d(e.epSquare)?j(e.epSquare):"-",...e.remainingChecks?[An(e.remainingChecks)]:[],Math.max(0,Math.min(e.halfmoves,9999)),Math.max(1,Math.min(e.fullmoves,9999))].join(" "),Rn=(e,t)=>{let n="";if(ge(t))t.role!=="pawn"&&(n=Y(t.role).toUpperCase()),n+="@"+j(t.to);else{const r=e.board.getRole(t.from);if(!r)return"--";if(r==="king"&&(e.board[e.turn].has(t.to)||Math.abs(t.to-t.from)===2))n=t.to>t.from?"O-O":"O-O-O";else{const i=e.board.occupied.has(t.to)||r==="pawn"&&A(t.from)!==A(t.to);if(r!=="pawn"){n=Y(r).toUpperCase();let o;if(r==="king"?o=Te(t.to).intersect(e.board.king):r==="queen"?o=Xe(t.to,e.board.occupied).intersect(e.board.queen):r==="rook"?o=he(t.to,e.board.occupied).intersect(e.board.rook):r==="bishop"?o=le(t.to,e.board.occupied).intersect(e.board.bishop):o=De(t.to).intersect(e.board.knight),o=o.intersect(e.board[e.turn]).without(t.from),o.nonEmpty()){const s=e.ctx();for(const c of o)e.dests(c,s).has(t.to)||(o=o.without(c));if(o.nonEmpty()){let c=!1,h=o.intersects(a.fromRank(J(t.from)));o.intersects(a.fromFile(A(t.from)))?c=!0:h=!0,h&&(n+=Pe[A(t.from)]),c&&(n+=Et[J(t.from)])}}}else i&&(n=Pe[A(t.from)]);i&&(n+="x"),n+=j(t.to),t.promotion&&(n+="="+Y(t.promotion).toUpperCase())}}return n},Sn=(e,t)=>{var n;const r=Rn(e,t);return e.play(t),!((n=e.outcome())===null||n===void 0)&&n.winner?r+"#":e.isCheck()?r+"+":r},Jr=(e,t)=>Sn(e.clone(),t),ei=(e,t)=>{const n=e.ctx(),r=t.match(/^([NBRQK])?([a-h])?([1-8])?[-x]?([a-h][1-8])(?:=?([nbrqkNBRQK]))?[+#]?$/);if(!r){let f;if(t==="O-O"||t==="O-O+"||t==="O-O#"?f="h":(t==="O-O-O"||t==="O-O-O+"||t==="O-O-O#")&&(f="a"),f){const m=e.castles.rook[e.turn][f];return!d(n.king)||!d(m)||!e.dests(n.king,n).has(m)?void 0:{from:n.king,to:m}}const u=t.match(/^([pnbrqkPNBRQK])?@([a-h][1-8])[+#]?$/);if(!u)return;const w={role:u[1]?ce(u[1]):"pawn",to:ae(u[2])};return e.isLegal(w,n)?w:void 0}const i=r[1]?ce(r[1]):"pawn",o=ae(r[4]),s=r[5]?ce(r[5]):void 0;if(!!s!==(i==="pawn"&&a.backranks().has(o))||s==="king"&&e.rules!=="antichess")return;let c=e.board.pieces(e.turn,i);i==="pawn"&&!r[2]?c=c.intersect(a.fromFile(A(o))):r[2]&&(c=c.intersect(a.fromFile(r[2].charCodeAt(0)-97))),r[3]&&(c=c.intersect(a.fromRank(r[3].charCodeAt(0)-49)));const h=i==="pawn"?a.fromFile(A(o)):a.empty();c=c.intersect(h.union(dn({color:E(e.turn),role:i},o,e.board.occupied)));let l;for(const f of c)if(e.dests(f,n).has(o)){if(d(l))return;l=f}if(d(l))return{from:l,to:o,promotion:s}},ti=(e,t)=>{const n=new Map,r=e.ctx();for(const[i,o]of e.allDests(r))if(o.nonEmpty()){const s=Array.from(o,j);i===r.king&&A(i)===4&&(o.has(0)?s.push("c1"):o.has(56)&&s.push("c8"),o.has(7)?s.push("g1"):o.has(63)&&s.push("g8")),n.set(j(i),s)}return n},On=["white","black"],Me=["a","b","c","d","e","f","g","h"],Ae=["1","2","3","4","5","6","7","8"],xn=[...Ae].reverse(),Je=Array.prototype.concat(...Me.map(e=>Ae.map(t=>e+t))),N=e=>Je[8*e[0]+e[1]],k=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],St=Je.map(k);function Tn(e){let t;const n=()=>(t===void 0&&(t=e()),t);return n.clear=()=>{t=void 0},n}const Dn=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;const t=performance.now()-e;return e=void 0,t}}},et=e=>e==="white"?"black":"white",be=(e,t)=>{const n=e[0]-t[0],r=e[1]-t[1];return n*n+r*r},Ue=(e,t)=>e.role===t.role&&e.color===t.color,ve=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],L=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},Ot=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},tt=(e,t)=>{e.style.visibility=t?"visible":"hidden"},te=e=>{var t;if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(!((t=e.targetTouches)===null||t===void 0)&&t[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},xt=e=>e.button===2,_=(e,t)=>{const n=document.createElement(e);return t&&(n.className=t),n};function Tt(e,t,n){const r=k(e);return t||(r[0]=7-r[0],r[1]=7-r[1]),[n.left+n.width*r[0]/8+n.width/16,n.top+n.height*(7-r[1])/8+n.height/16]}const ee=(e,t)=>Math.abs(e-t),Nn=e=>(t,n,r,i)=>ee(t,r)<2&&(e==="white"?i===n+1||n<=1&&i===n+2&&t===r:i===n-1||n>=6&&i===n-2&&t===r),Dt=(e,t,n,r)=>{const i=ee(e,n),o=ee(t,r);return i===1&&o===2||i===2&&o===1},Nt=(e,t,n,r)=>ee(e,n)===ee(t,r),Kt=(e,t,n,r)=>e===n||t===r,$t=(e,t,n,r)=>Nt(e,t,n,r)||Kt(e,t,n,r),Kn=(e,t,n)=>(r,i,o,s)=>ee(r,o)<2&&ee(i,s)<2||n&&i===s&&i===(e==="white"?0:7)&&(r===4&&(o===2&&t.includes(0)||o===6&&t.includes(7))||t.includes(o));function $n(e,t){const n=t==="white"?"1":"8",r=[];for(const[i,o]of e)i[1]===n&&o.color===t&&o.role==="rook"&&r.push(k(i)[0]);return r}function zt(e,t,n){const r=e.get(t);if(!r)return[];const i=k(t),o=r.role,s=o==="pawn"?Nn(r.color):o==="knight"?Dt:o==="bishop"?Nt:o==="rook"?Kt:o==="queen"?$t:Kn(r.color,$n(e,r.color),n);return St.filter(c=>(i[0]!==c[0]||i[1]!==c[1])&&s(i[0],i[1],c[0],c[1])).map(N)}function O(e,...t){e&&setTimeout(()=>e(...t),1)}function zn(e){e.orientation=et(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function Ln(e,t){for(const[n,r]of t)r?e.pieces.set(n,r):e.pieces.delete(n)}function Bn(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(const[n,r]of e.pieces)r.role==="king"&&r.color===t&&(e.check=n)}function Wn(e,t,n,r){G(e),e.premovable.current=[t,n],O(e.premovable.events.set,t,n,r)}function U(e){e.premovable.current&&(e.premovable.current=void 0,O(e.premovable.events.unset))}function Fn(e,t,n){U(e),e.predroppable.current={role:t,key:n},O(e.predroppable.events.set,t,n)}function G(e){const t=e.predroppable;t.current&&(t.current=void 0,O(t.events.unset))}function _n(e,t,n){if(!e.autoCastle)return!1;const r=e.pieces.get(t);if(!r||r.role!=="king")return!1;const i=k(t),o=k(n);if(i[1]!==0&&i[1]!==7||i[1]!==o[1])return!1;i[0]===4&&!e.pieces.has(n)&&(o[0]===6?n=N([7,o[1]]):o[0]===2&&(n=N([0,o[1]])));const s=e.pieces.get(n);return!s||s.color!==r.color||s.role!=="rook"?!1:(e.pieces.delete(t),e.pieces.delete(n),i[0]<o[0]?(e.pieces.set(N([6,o[1]]),r),e.pieces.set(N([5,o[1]]),s)):(e.pieces.set(N([2,o[1]]),r),e.pieces.set(N([3,o[1]]),s)),!0)}function Lt(e,t,n){const r=e.pieces.get(t),i=e.pieces.get(n);if(t===n||!r)return!1;const o=i&&i.color!==r.color?i:void 0;return n===e.selected&&K(e),O(e.events.move,t,n,o),_n(e,t,n)||(e.pieces.set(n,r),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,O(e.events.change),o||!0}function nt(e,t,n,r){if(e.pieces.has(n))if(r)e.pieces.delete(n);else return!1;return O(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,O(e.events.change),e.movable.dests=void 0,e.turnColor=et(e.turnColor),!0}function Bt(e,t,n){const r=Lt(e,t,n);return r&&(e.movable.dests=void 0,e.turnColor=et(e.turnColor),e.animation.current=void 0),r}function Wt(e,t,n){if(rt(e,t,n)){const r=Bt(e,t,n);if(r){const i=e.hold.stop();K(e);const o={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:i};return r!==!0&&(o.captured=r),O(e.movable.events.after,t,n,o),!0}}else if(In(e,t,n))return Wn(e,t,n,{ctrlKey:e.stats.ctrlKey}),K(e),!0;return K(e),!1}function Ft(e,t,n,r){const i=e.pieces.get(t);i&&(Hn(e,t,n)||r)?(e.pieces.delete(t),nt(e,i,n,r),O(e.movable.events.afterNewPiece,i.role,n,{premove:!1,predrop:!1})):i&&jn(e,t,n)?Fn(e,i.role,n):(U(e),G(e)),e.pieces.delete(t),K(e)}function Ge(e,t,n){if(O(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){K(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&Wt(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(Ht(e,t)||it(e,t))&&(_t(e,t),e.hold.start())}function _t(e,t){e.selected=t,it(e,t)?e.premovable.customDests||(e.premovable.dests=zt(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function K(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function Ht(e,t){const n=e.pieces.get(t);return!!n&&(e.movable.color==="both"||e.movable.color===n.color&&e.turnColor===n.color)}const rt=(e,t,n)=>{var r,i;return t!==n&&Ht(e,t)&&(e.movable.free||!!(!((i=(r=e.movable.dests)===null||r===void 0?void 0:r.get(t))===null||i===void 0)&&i.includes(n)))};function Hn(e,t,n){const r=e.pieces.get(t);return!!r&&(t===n||!e.pieces.has(n))&&(e.movable.color==="both"||e.movable.color===r.color&&e.turnColor===r.color)}function it(e,t){const n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function In(e,t,n){var r,i;const o=(i=(r=e.premovable.customDests)===null||r===void 0?void 0:r.get(t))!==null&&i!==void 0?i:zt(e.pieces,t,e.premovable.castle);return t!==n&&it(e,t)&&o.includes(n)}function jn(e,t,n){const r=e.pieces.get(t),i=e.pieces.get(n);return!!r&&(!i||i.color!==e.movable.color)&&e.predroppable.enabled&&(r.role!=="pawn"||n[1]!=="1"&&n[1]!=="8")&&e.movable.color===r.color&&e.turnColor!==r.color}function qn(e,t){const n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color==="both"||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function Un(e){const t=e.premovable.current;if(!t)return!1;const n=t[0],r=t[1];let i=!1;if(rt(e,n,r)){const o=Bt(e,n,r);if(o){const s={premove:!0};o!==!0&&(s.captured=o),O(e.movable.events.after,n,r,s),i=!0}}return U(e),i}function Gn(e,t){const n=e.predroppable.current;let r=!1;if(!n)return!1;if(t(n)){const i={role:n.role,color:e.movable.color};nt(e,i,n.key)&&(O(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),r=!0)}return G(e),r}function ot(e){U(e),G(e),K(e)}function pt(e){e.movable.color=e.movable.dests=e.animation.current=void 0,ot(e)}function ne(e,t,n){let r=Math.floor(8*(e[0]-n.left)/n.width);t||(r=7-r);let i=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(i=7-i),r>=0&&r<8&&i>=0&&i<8?N([r,i]):void 0}function Vn(e,t,n,r){const i=k(e),o=St.filter(l=>$t(i[0],i[1],l[0],l[1])||Dt(i[0],i[1],l[0],l[1])),c=o.map(l=>Tt(N(l),n,r)).map(l=>be(t,l)),[,h]=c.reduce((l,f,u)=>l[0]<f?l:[f,u],[c[0],0]);return N(o[h])}const x=e=>e.orientation==="white",It="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",Qn={p:"pawn",r:"rook",n:"knight",b:"bishop",q:"queen",k:"king"},Zn={pawn:"p",rook:"r",knight:"n",bishop:"b",queen:"q",king:"k"};function jt(e){e==="start"&&(e=It);const t=new Map;let n=7,r=0;for(const i of e)switch(i){case" ":case"[":return t;case"/":if(--n,n<0)return t;r=0;break;case"~":{const o=t.get(N([r-1,n]));o&&(o.promoted=!0);break}default:{const o=i.charCodeAt(0);if(o<57)r+=o-48;else{const s=i.toLowerCase();t.set(N([r,n]),{role:Qn[s],color:i===s?"black":"white"}),++r}}}return t}function Yn(e){return xn.map(t=>Me.map(n=>{const r=e.get(n+t);if(r){let i=Zn[r.role];return r.color==="white"&&(i=i.toUpperCase()),r.promoted&&(i+="~"),i}else return"1"}).join("")).join("/").replace(/1{2,}/g,t=>t.length.toString())}function qt(e,t){t.animation&&(st(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function Ut(e,t){var n,r,i;if(!((n=t.movable)===null||n===void 0)&&n.dests&&(e.movable.dests=void 0),!((r=t.drawable)===null||r===void 0)&&r.autoShapes&&(e.drawable.autoShapes=[]),st(e,t),t.fen&&(e.pieces=jt(t.fen),e.drawable.shapes=((i=t.drawable)===null||i===void 0?void 0:i.shapes)||[]),"check"in t&&Bn(e,t.check||!1),"lastMove"in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&_t(e,e.selected),qt(e,t),!e.movable.rookCastle&&e.movable.dests){const o=e.movable.color==="white"?"1":"8",s="e"+o,c=e.movable.dests.get(s),h=e.pieces.get(s);if(!c||!h||h.role!=="king")return;e.movable.dests.set(s,c.filter(l=>!(l==="a"+o&&c.includes("c"+o))&&!(l==="h"+o&&c.includes("g"+o))))}}function st(e,t){for(const n in t)n==="__proto__"||n==="constructor"||!Object.prototype.hasOwnProperty.call(t,n)||(Object.prototype.hasOwnProperty.call(e,n)&&gt(e[n])&&gt(t[n])?st(e[n],t[n]):e[n]=t[n])}function gt(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const Q=(e,t)=>t.animation.enabled?er(e,t):H(e,t);function H(e,t){const n=e(t);return t.dom.redraw(),n}const $e=(e,t)=>({key:e,pos:k(e),piece:t}),Xn=(e,t)=>t.sort((n,r)=>be(e.pos,n.pos)-be(e.pos,r.pos))[0];function Jn(e,t){const n=new Map,r=[],i=new Map,o=[],s=[],c=new Map;let h,l,f;for(const[u,w]of e)c.set(u,$e(u,w));for(const u of Je)h=t.pieces.get(u),l=c.get(u),h?l?Ue(h,l.piece)||(o.push(l),s.push($e(u,h))):s.push($e(u,h)):l&&o.push(l);for(const u of s)l=Xn(u,o.filter(w=>Ue(u.piece,w.piece))),l&&(f=[l.pos[0]-u.pos[0],l.pos[1]-u.pos[1]],n.set(u.key,f.concat(f)),r.push(l.key));for(const u of o)r.includes(u.key)||i.set(u.key,u.piece);return{anims:n,fadings:i}}function Gt(e,t){const n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}const r=1-(t-n.start)*n.frequency;if(r<=0)e.animation.current=void 0,e.dom.redrawNow();else{const i=tr(r);for(const o of n.plan.anims.values())o[2]=o[0]*i,o[3]=o[1]*i;e.dom.redrawNow(!0),requestAnimationFrame((o=performance.now())=>Gt(e,o))}}function er(e,t){const n=new Map(t.pieces),r=e(t),i=Jn(n,t);if(i.anims.size||i.fadings.size){const o=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:i},o||Gt(t,performance.now())}else t.dom.redraw();return r}const tr=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,nr=["green","red","blue","yellow"];function rr(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?K(e):ot(e);const n=te(t),r=ne(n,x(e),e.dom.bounds());r&&(e.drawable.current={orig:r,pos:n,brush:cr(t),snapToValidMove:e.drawable.defaultSnapToValidMove},Vt(e))}function Vt(e){requestAnimationFrame(()=>{const t=e.drawable.current;if(t){const n=ne(t.pos,x(e),e.dom.bounds());n||(t.snapToValidMove=!1);const r=t.snapToValidMove?Vn(t.orig,t.pos,x(e),e.dom.bounds()):n;r!==t.mouseSq&&(t.mouseSq=r,t.dest=r!==t.orig?r:void 0,e.dom.redrawNow()),Vt(e)}})}function ir(e,t){e.drawable.current&&(e.drawable.current.pos=te(t))}function or(e){const t=e.drawable.current;t&&(t.mouseSq&&ar(e.drawable,t),Qt(e))}function Qt(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}function sr(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),Zt(e.drawable))}function cr(e){var t;const n=(e.shiftKey||e.ctrlKey)&&xt(e),r=e.altKey||e.metaKey||((t=e.getModifierState)===null||t===void 0?void 0:t.call(e,"AltGraph"));return nr[(n?1:0)+(r?2:0)]}function ar(e,t){const n=i=>i.orig===t.orig&&i.dest===t.dest,r=e.shapes.find(n);r&&(e.shapes=e.shapes.filter(i=>!n(i))),(!r||r.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),Zt(e)}function Zt(e){e.onChange&&e.onChange(e.shapes)}function lr(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;const n=e.dom.bounds(),r=te(t),i=ne(r,x(e),n);if(!i)return;const o=e.pieces.get(i),s=e.selected;if(!s&&e.drawable.enabled&&(e.drawable.eraseOnClick||!o||o.color!==e.turnColor)&&sr(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||o||s||hr(e,r)))t.preventDefault();else if(t.touches)return;const c=!!e.premovable.current,h=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&rt(e,e.selected,i)?Q(u=>Ge(u,i),e):Ge(e,i);const l=e.selected===i,f=Xt(e,i);if(o&&f&&l&&qn(e,i)){e.draggable.current={orig:i,piece:o,origPos:r,pos:r,started:e.draggable.autoDistance&&e.stats.dragged,element:f,previouslySelected:s,originTarget:t.target,keyHasChanged:!1},f.cgDragging=!0,f.classList.add("dragging");const u=e.dom.elements.ghost;u&&(u.className=`ghost ${o.color} ${o.role}`,L(u,ve(n)(k(i),x(e))),tt(u,!0)),ct(e)}else c&&U(e),h&&G(e);e.dom.redraw()}function hr(e,t){const n=x(e),r=e.dom.bounds(),i=Math.pow(r.width/8,2);for(const o of e.pieces.keys()){const s=Tt(o,n,r);if(be(s,t)<=i)return!0}return!1}function ur(e,t,n,r){const i="a0";e.pieces.set(i,t),e.dom.redraw();const o=te(n);e.draggable.current={orig:i,piece:t,origPos:o,pos:o,started:!0,element:()=>Xt(e,i),originTarget:n.target,newPiece:!0,force:!!r,keyHasChanged:!1},ct(e)}function ct(e){requestAnimationFrame(()=>{var t;const n=e.draggable.current;if(!n)return;!((t=e.animation.current)===null||t===void 0)&&t.plan.anims.has(n.orig)&&(e.animation.current=void 0);const r=e.pieces.get(n.orig);if(!r||!Ue(r,n.piece))Re(e);else if(!n.started&&be(n.pos,n.origPos)>=Math.pow(e.draggable.distance,2)&&(n.started=!0),n.started){if(typeof n.element=="function"){const o=n.element();if(!o)return;o.cgDragging=!0,o.classList.add("dragging"),n.element=o}const i=e.dom.bounds();L(n.element,[n.pos[0]-i.left-i.width/16,n.pos[1]-i.top-i.height/16]),n.keyHasChanged||(n.keyHasChanged=n.orig!==ne(n.pos,x(e),i))}ct(e)})}function fr(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=te(t))}function dr(e,t){const n=e.draggable.current;if(!n)return;if(t.type==="touchend"&&t.cancelable!==!1&&t.preventDefault(),t.type==="touchend"&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}U(e),G(e);const r=te(t)||n.pos,i=ne(r,x(e),e.dom.bounds());i&&n.started&&n.orig!==i?n.newPiece?Ft(e,n.orig,i,n.force):(e.stats.ctrlKey=t.ctrlKey,Wt(e,n.orig,i)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!i&&(e.pieces.delete(n.orig),O(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===i||!i)?K(e):e.selectable.enabled||K(e),Yt(e),e.draggable.current=void 0,e.dom.redraw()}function Re(e){const t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,K(e),Yt(e),e.dom.redraw())}function Yt(e){const t=e.dom.elements;t.ghost&&tt(t.ghost,!1)}function Xt(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName==="PIECE")return n;n=n.nextSibling}}function pr(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{mt(e,2),setTimeout(()=>mt(e,void 0),120)},120)}function mt(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function gr(e,t){function n(){zn(e),t()}return{set(r){r.orientation&&r.orientation!==e.orientation&&n(),qt(e,r),(r.fen?Q:H)(i=>Ut(i,r),e)},state:e,getFen:()=>Yn(e.pieces),toggleOrientation:n,setPieces(r){Q(i=>Ln(i,r),e)},selectSquare(r,i){r?Q(o=>Ge(o,r,i),e):e.selected&&(K(e),e.dom.redraw())},move(r,i){Q(o=>Lt(o,r,i),e)},newPiece(r,i){Q(o=>nt(o,r,i),e)},playPremove(){if(e.premovable.current){if(Q(Un,e))return!0;e.dom.redraw()}return!1},playPredrop(r){if(e.predroppable.current){const i=Gn(e,r);return e.dom.redraw(),i}return!1},cancelPremove(){H(U,e)},cancelPredrop(){H(G,e)},cancelMove(){H(r=>{ot(r),Re(r)},e)},stop(){H(r=>{pt(r),Re(r)},e)},explode(r){pr(e,r)},setAutoShapes(r){H(i=>i.drawable.autoShapes=r,e)},setShapes(r){H(i=>i.drawable.shapes=r,e)},getKeyAtDomPos(r){return ne(r,x(e),e.dom.bounds())},redrawAll:t,dragNewPiece(r,i,o){ur(e,r,i,o)},destroy(){pt(e),e.dom.unbind&&e.dom.unbind(),e.dom.destroyed=!0}}}function mr(){return{pieces:jt(It),orientation:"white",turnColor:"white",coordinates:!0,coordinatesOnSquares:!1,ranksPosition:"right",autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:"both",showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!("ontouchstart"in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:"g",color:"#15781B",opacity:1,lineWidth:10},red:{key:"r",color:"#882020",opacity:1,lineWidth:10},blue:{key:"b",color:"#003088",opacity:1,lineWidth:10},yellow:{key:"y",color:"#e68f00",opacity:1,lineWidth:10},paleBlue:{key:"pb",color:"#003088",opacity:.4,lineWidth:15},paleGreen:{key:"pg",color:"#15781B",opacity:.4,lineWidth:15},paleRed:{key:"pr",color:"#882020",opacity:.4,lineWidth:15},paleGrey:{key:"pgr",color:"#4a4a4a",opacity:.35,lineWidth:15},purple:{key:"purple",color:"#68217a",opacity:.65,lineWidth:10},pink:{key:"pink",color:"#ee2080",opacity:.5,lineWidth:10},white:{key:"white",color:"white",opacity:1,lineWidth:10}},prevSvgHash:""},hold:Dn()}}const wt={hilitePrimary:{key:"hilitePrimary",color:"#3291ff",opacity:1,lineWidth:1},hiliteWhite:{key:"hiliteWhite",color:"#ffffff",opacity:1,lineWidth:1}};function wr(){const e=C("defs"),t=R(C("filter"),{id:"cg-filter-blur"});return t.appendChild(R(C("feGaussianBlur"),{stdDeviation:"0.019"})),e.appendChild(t),e}function br(e,t,n){var r;const i=e.drawable,o=i.current,s=o&&o.mouseSq?o:void 0,c=new Map,h=e.dom.bounds(),l=i.autoShapes.filter(m=>!m.piece);for(const m of i.shapes.concat(l).concat(s?[s]:[])){if(!m.dest)continue;const b=(r=c.get(m.dest))!==null&&r!==void 0?r:new Set,p=xe(Oe(k(m.orig),e.orientation),h),T=xe(Oe(k(m.dest),e.orientation),h);b.add(Qe(p,T)),c.set(m.dest,b)}const f=i.shapes.concat(l).map(m=>({shape:m,current:!1,hash:bt(m,Ve(m.dest,c),!1,h)}));s&&f.push({shape:s,current:!0,hash:bt(s,Ve(s.dest,c),!0,h)});const u=f.map(m=>m.hash).join(";");if(u===e.drawable.prevSvgHash)return;e.drawable.prevSvgHash=u;const w=t.querySelector("defs");kr(i,f,w),vr(f,t.querySelector("g"),n.querySelector("g"),m=>Pr(e,m,i.brushes,c,h))}function kr(e,t,n){var r;const i=new Map;let o;for(const h of t.filter(l=>l.shape.dest&&l.shape.brush))o=Jt(e.brushes[h.shape.brush],h.shape.modifiers),!((r=h.shape.modifiers)===null||r===void 0)&&r.hilite&&i.set(Se(o).key,Se(o)),i.set(o.key,o);const s=new Set;let c=n.firstElementChild;for(;c;)s.add(c.getAttribute("cgKey")),c=c.nextElementSibling;for(const[h,l]of i.entries())s.has(h)||n.appendChild(Ar(l))}function vr(e,t,n,r){const i=new Map;for(const o of e)i.set(o.hash,!1);for(const o of[t,n]){const s=[];let c=o.firstElementChild,h;for(;c;)h=c.getAttribute("cgHash"),i.has(h)?i.set(h,!0):s.push(c),c=c.nextElementSibling;for(const l of s)o.removeChild(l)}for(const o of e.filter(s=>!i.get(s.hash)))for(const s of r(o))s.isCustom?n.appendChild(s.el):t.appendChild(s.el)}function bt({orig:e,dest:t,brush:n,piece:r,modifiers:i,customSvg:o,label:s},c,h,l){var f,u;return[l.width,l.height,h,e,t,n,c&&"-",r&&yr(r),i&&Cr(i),o&&`custom-${kt(o.html)},${(u=(f=o.center)===null||f===void 0?void 0:f[0])!==null&&u!==void 0?u:"o"}`,s&&`label-${kt(s.text)}`].filter(w=>w).join(",")}function yr(e){return[e.color,e.role,e.scale].filter(t=>t).join(",")}function Cr(e){return[e.lineWidth,e.hilite&&"*"].filter(t=>t).join(",")}function kt(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function Pr(e,{shape:t,current:n,hash:r},i,o,s){var c,h;const l=xe(Oe(k(t.orig),e.orientation),s),f=t.dest?xe(Oe(k(t.dest),e.orientation),s):l,u=t.brush&&Jt(i[t.brush],t.modifiers),w=o.get(t.dest),m=[];if(u){const b=R(C("g"),{cgHash:r});m.push({el:b}),l[0]!==f[0]||l[1]!==f[1]?b.appendChild(Mr(t,u,l,f,n,Ve(t.dest,o))):b.appendChild(Er(i[t.brush],l,n,s))}if(t.label){const b=t.label;(c=b.fill)!==null&&c!==void 0||(b.fill=t.brush&&i[t.brush].color);const p=t.brush?void 0:"tr";m.push({el:Rr(b,r,l,f,w,p),isCustom:!0})}if(t.customSvg){const b=(h=t.customSvg.center)!==null&&h!==void 0?h:"orig",[p,T]=b==="label"?tn(l,f,w).map(P=>P-.5):b==="dest"?f:l,S=R(C("g"),{transform:`translate(${p},${T})`,cgHash:r});S.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,m.push({el:S,isCustom:!0})}return m}function Er(e,t,n,r){const i=Sr(),o=(r.width+r.height)/(4*Math.max(r.width,r.height));return R(C("circle"),{stroke:e.color,"stroke-width":i[n?0:1],fill:"none",opacity:en(e,n),cx:t[0],cy:t[1],r:o-i[1]/2})}function Se(e){return["#ffffff","#fff","white"].includes(e.color)?wt.hilitePrimary:wt.hiliteWhite}function Mr(e,t,n,r,i,o){var s;function c(f){var u;const w=xr(o&&!i),m=r[0]-n[0],b=r[1]-n[1],p=Math.atan2(b,m),T=Math.cos(p)*w,S=Math.sin(p)*w;return R(C("line"),{stroke:f?Se(t).color:t.color,"stroke-width":Or(t,i)+(f?.04:0),"stroke-linecap":"round","marker-end":`url(#arrowhead-${f?Se(t).key:t.key})`,opacity:!((u=e.modifiers)===null||u===void 0)&&u.hilite?1:en(t,i),x1:n[0],y1:n[1],x2:r[0]-T,y2:r[1]-S})}if(!(!((s=e.modifiers)===null||s===void 0)&&s.hilite))return c(!1);const h=C("g"),l=R(C("g"),{filter:"url(#cg-filter-blur)"});return l.appendChild(Tr(n,r)),l.appendChild(c(!0)),h.appendChild(l),h.appendChild(c(!1)),h}function Ar(e){const t=R(C("marker"),{id:"arrowhead-"+e.key,orient:"auto",overflow:"visible",markerWidth:4,markerHeight:4,refX:e.key.startsWith("hilite")?1.86:2.05,refY:2});return t.appendChild(R(C("path"),{d:"M0,0 V4 L3,2 Z",fill:e.color})),t.setAttribute("cgKey",e.key),t}function Rr(e,t,n,r,i,o){var s;const h=.4*.75**e.text.length,l=tn(n,r,i),f=o==="tr"?.4:0,u=R(C("g"),{transform:`translate(${l[0]+f},${l[1]-f})`,cgHash:t});u.appendChild(R(C("circle"),{r:.4/2,"fill-opacity":o?1:.8,"stroke-opacity":o?1:.7,"stroke-width":.03,fill:(s=e.fill)!==null&&s!==void 0?s:"#666",stroke:"white"}));const w=R(C("text"),{"font-size":h,"font-family":"Noto Sans","text-anchor":"middle",fill:"white",y:.13*.75**e.text.length});return w.innerHTML=e.text,u.appendChild(w),u}function Oe(e,t){return t==="white"?e:[7-e[0],7-e[1]]}function Ve(e,t){return(e&&t.has(e)&&t.get(e).size>1)===!0}function C(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function R(e,t){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function Jt(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(n=>n).join("")}:e}function Sr(){return[3/64,4/64]}function Or(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function en(e,t){return(e.opacity||1)*(t?.9:1)}function xr(e){return(e?20:10)/64}function xe(e,t){const n=Math.min(1,t.width/t.height),r=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*r]}function Tr(e,t){const n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return R(C("rect"),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:"none",stroke:"none"})}function Qe(e,t,n=!0){const r=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(r*8/Math.PI)+16)%16:r}function Dr(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((n,r)=>n+r*r,0))}function tn(e,t,n){let r=Dr(e,t);const i=Qe(e,t,!1);if(n&&(r-=33/64,n.size>1)){r-=10/64;const o=Qe(e,t);(n.has((o+1)%16)||n.has((o+15)%16))&&o&1&&(r-=.4)}return[e[0]-Math.cos(i)*r,e[1]-Math.sin(i)*r].