gungi.js 3.4.7 → 3.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import D from"picocolors";var H=r=>Object.entries(r).reduce((e,[t,n])=>({...e,[n]:t}),{}),x={intro:0,beginner:1,intermediate:2,advanced:3},V=H(x),me="w",ge="b",ye="\u4ED8",be="\u53D6",Pe="\u8FD4",Ne="\u65B0",Ce="\u5E25",Ee="\u5927",$e="\u4E2D",Te="\u5C0F",we="\u4F8D",ke="\u69CD",xe="\u99AC",Me="\u5FCD",Ae="\u7826",Ie="\u5175",Fe="\u7832",ve="\u5F13",Re="\u7B52",Se="\u8B00",M=Array.from({length:9},(r,e)=>e+1).flatMap(r=>Array.from({length:9},(e,t)=>`${r}-${9-t}`)),P={marshal:"\u5E25",general:"\u5927",lieutenant_general:"\u4E2D",major_general:"\u5C0F",warrior:"\u4F8D",lancer:"\u69CD",rider:"\u99AC",spy:"\u5FCD",fortress:"\u7826",soldier:"\u5175",cannon:"\u7832",archer:"\u5F13",musketeer:"\u7B52",tactician:"\u8B00"},A=H(P),w={marshal:"m",general:"g",lieutenant_general:"i",major_general:"j",warrior:"w",lancer:"n",rider:"r",spy:"s",fortress:"f",soldier:"d",cannon:"c",archer:"a",musketeer:"k",tactician:"t"},Y=H(w),_=(r,[e,t,n])=>{let i=r===r.toLowerCase()?"b":"w",o=Y[r.toLowerCase()];return{square:`${e}-${t}`,tier:n,type:P[o],color:i}},Q=(r,e)=>{let t=r===r.toLowerCase()?"b":"w",n=Y[r.toLowerCase()];return{type:P[n],count:e,color:t}},Oe={\u5E25:"sui",\u5927:"taishou",\u4E2D:"chuujou",\u5C0F:"shoushou",\u4F8D:"samurai",\u69CD:"yari",\u99AC:"kiba",\u5FCD:"shinobi",\u7826:"toride",\u5175:"hyou",\u7832:"oodzutsu",\u5F13:"yumi",\u7B52:"tsutsu",\u8B00:"boushou"},qe={\u5E25:"marshal",\u5927:"general",\u4E2D:"lieutenant general",\u5C0F:"major general",\u4F8D:"warrior",\u69CD:"lancer",\u99AC:"rider",\u5FCD:"spy",\u7826:"fortress",\u5175:"soldier",\u7832:"cannon",\u5F13:"archer",\u7B52:"musketeer",\u8B00:"tactician"},De={\u5E25:"m",\u5927:"g",\u4E2D:"i",\u5C0F:"j",\u4F8D:"w",\u69CD:"n",\u99AC:"r",\u5FCD:"s",\u7826:"f",\u5175:"d",\u7832:"c",\u5F13:"a",\u7B52:"k",\u8B00:"t"};function B(r,e,t=!1){return r.forEach(n=>{let i=t?n.color==="b"?"w":"b":n.color,o=e.find(a=>a.type===n.type&&a.color===i),s=e.findIndex(a=>a.type===n.type&&a.color===i);o&&(o.count--,o.count===0&&e.splice(s,1))}),e}function X(r,e,t){let[n,i]=r.split("-").map(Number),o=k(r,t);o&&(t[n-1][9-i]=o.map(s=>(e.find(c=>JSON.stringify(c)===JSON.stringify(s))&&(s.color=s.color==="b"?"w":"b"),s)))}function Z(r,e,t){let[n,i]=r.split("-").map(Number),o=k(r,t);if(!o)return;let s=o.filter(a=>!e.some(c=>JSON.stringify(c)===JSON.stringify(a)));s.length===0?t[n-1][9-i]=[null]:t[n-1][9-i]=s}function S(r,e){let[t,n]=r.split("-").map(Number),i=k(r,e);i&&(i.pop(),i.length===0&&(e[t-1][9-n]=[null]))}function ee(r,e){let[t,n]=r.square.split("-").map(Number);e[t-1][9-n][0]?e[t-1][9-n].push(r):e[t-1][9-n]=[r]}function C(r,e){let t=k(r,e);return t?t.at(-1):void 0}function k(r,e){let[t,n]=r.split("-").map(Number);if(t<1||t>9||n<1||n>9)return;let i=e[t-1][9-n];if(i[0])return i}function O(r){return r.flat().flat().filter(t=>t?.type==="\u5E25").length!==2}var te="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Ge="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",He="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",L="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function T(r){let e=j(r);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[t,n,i,o,s,a]=r.split(" "),c=t.split("/").map((f,l)=>f.split("|").reduce((p,d)=>{if(d.includes(":")){let h=d.split(":").map((m,g)=>_(m,[l+1,9-p.length,g+1]));p.push(h)}else{let h=d.split("").reduce((m,g)=>(Number.isInteger(+g)?m=m.concat(Array(+g).fill(null)):m.push(_(g,[l+1,9-p.length-m.length,1])),m),[]).map(m=>[m]);p=p.concat(h)}return p},[])),u=n.split("/").flatMap(f=>{let l=[];if(f!=="-")for(let p=0;p<f.length;p+=2){let d=f[p],h=+f[p+1];l.push(Q(d,h))}return l});return{board:c,hand:u,turn:i,mode:V[+o],drafting:{w:s.includes("w"),b:s.includes("b")},moveNumber:+a}}function q(r){let e="",t=0;for(let a=0;a<9;a++){for(let c=0;c<9;c++){let u=r.board[a][c];if(!u[0]){t++;continue}if(t&&(e+=t,t=0),u.length>1)e+="|"+u.map(f=>{if(!f)return null;let l=w[A[f.type]];return f.color==="w"?l.toUpperCase():l}).join(":")+"|";else{let{type:f,color:l}=u[0],p=w[A[f]];e+=l==="w"?p.toUpperCase():p}}e+=t?`${t}/`:"/",t=0}let n="",i=r.hand.filter(a=>a.color==="w"),o=r.hand.filter(a=>a.color==="b");i.forEach(a=>{let c=w[A[a.type]];n+=`${a.color==="w"?c.toUpperCase():c}${a.count}`}),n+=i.length>0?"/":"-/",o.forEach(a=>{let c=w[A[a.type]];n+=`${a.color==="w"?c.toUpperCase():c}${a.count}`}),n+=o.length>0?"":"-";let s=Object.keys(r.drafting).filter(a=>r.drafting[a]);return`${e.slice(0,-1)} ${n} ${r.turn} ${x[r.mode]} ${s.length>0?s.join(""):"-"} ${r.moveNumber}`}function j(r){let e=r.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[t,n,i,o,s,a]=e,c=t.split("/");if(c.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${c.length}]`};for(let p=0;p<c.length;p++){let h=c[p].split("|"),m=0;for(let g=0;g<h.length;g++){let y=h[g];if(y.includes(":")){m++;let b=y.split(":");if(b.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${m})`};if(!b.every(N=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(N)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${m})`}}else{let b=y.split("");for(let N=0;N<b.length;N++){let $=b[N];if(Number.isInteger(+$))m+=+$;else if(m++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes($))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${m})`}}}}if(m!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${m}] in rank: ${p+1}`}}let u=n.split("/");if(u.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${u.length}]`};let[f,l]=u;if(f.length===1&&f!=="-"||l.length===1&&l!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(f.length>1&&f.length%2!==0||l.length>1&&l.length%2!==0)return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece count]"};if(f.length>1)for(let p=0;p<f.length;p+=2){if(!"MGIJWNRSFDCAKT".includes(f[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+f[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}if(l.length>1)for(let p=0;p<l.length;p+=2){if(!"mgijwnrsfdcakt".includes(l[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+l[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return i!=="w"&&i!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${i}]`}:o.length!==1||!"0123".includes(o)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${o}]`}:s!=="-"&&!"wb".includes(s)?{ok:!1,error:`5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${s}]`}:Number.isInteger(+a)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${a}]`}}var re=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],oe={\u5E25:[1,1,1,1,1,1,1,1],\u5927:[1,1/0,1,1/0,1/0,1,1/0,1],\u4E2D:[1/0,1,1/0,1,1,1/0,1,1/0],\u5C0F:[1,1,1,1,1,0,1,0],\u4F8D:[1,1,1,0,0,0,1,0],\u69CD:[1,[1,2],1,0,0,0,1,0],\u99AC:[0,[1,2],0,1,1,0,[1,2],0],\u5FCD:[[1,2],0,[1,2],0,0,[1,2],0,[1,2]],\u7826:[0,1,0,1,1,1,0,1],\u5175:[0,1,0,0,0,0,1,0],\u7832:[0,3,0,1,1,0,1,0],\u5F13:[2,2,2,0,0,0,1,0],\u7B52:[0,2,0,0,0,1,0,1],\u8B00:[1,0,1,0,0,0,1,0]};function ne(r,e,t,n,i){let[o,s]=e,[a,c]=t,[u,f]=r,l=C(`${a}-${c}`,i),p=[],d={x:s,y:o};for(;d.x!==c||d.y!==a;){d.x-=f,d.y-=u;let g=C(`${d.y}-${d.x}`,i);if(g&&g.tier>l.tier)return[];let y=l.color==="b"?-1:1,b=C(`${d.y+y}-${d.x}`,i);if(b&&b.square===`${a}-${c}`)break}let h={x:s,y:o},m=0;for(;m<n&&!(h.x<1||h.x>9||h.y<1||h.y>9);){let g=C(`${h.y}-${h.x}`,i);if(g&&g.tier>l.tier)break;p.push(`${h.y}-${h.x}`);let y=[P.cannon,P.musketeer,P.archer];if(g&&!y.includes(l.type))break;h.x+=f,h.y+=u,m++}return p}function R(r,e){let{board:t,turn:n,mode:i,hand:o}=T(e),s=C(r,t);if(!s||n!==s.color)return[];let[a,c]=r.split("-").map(Number);return oe[s.type].flatMap((l,p)=>{let d=typeof l=="number"?l:l[0],h=typeof l=="number"?1:l[1];if(d<1)return[];let[m,g]=re[p];s.color==="b"&&(m*=-1,g*=-1);let[y,b]=d===1/0?[a+m,c+g]:[a+d*m,c+g],N=d===1/0?1/0:s.tier+h-1;return ne([m,g],[y,b],[a,c],N,t)}).reduce((l,p)=>{let d=C(p,t),h=k(p,t),m=i==="advanced"?3:2,g=["advanced","intermediate"].includes(i);if(!d||!h)l.push(I(s,`${p}-1`,e,"route"));else{if(d.tier<m&&d.type!==P.marshal&&((s.type!==P.marshal||g)&&l.push(I(s,`${p}-${d.tier+1}`,e,"tsuke")),s.type===P.tactician&&d.color!==s.color)){let y=h.filter(E=>E.color!==s.color),b=o.filter(E=>E.color===s.color),N=y.reduce((E,v)=>(E.set(v.type,(E.get(v.type)??0)+1),E),new Map),$=Array.from(N.entries()).filter(([E,v])=>b.some(z=>z.type===E&&z.count>=v)).flatMap(([E])=>y.filter(v=>v.type===E)),G=Be($);l.push(...G.map(E=>I(s,`${p}-${d.tier+1}`,e,"betray",E)))}if(d.color!==s.color){let y=h.filter(N=>N.color===s.color).length+1,b=h.filter(N=>N.color!==s.color);l.push(I(s,`${p}-${y}`,e,"capture",b))}}return l},[])}function F(r,e){let{board:t,turn:n,mode:i,hand:o,drafting:s}=T(e);if(!r||n!==r.color)return[];if(!!o.some(d=>d.type===P.marshal&&d.color===r.color)&&r.type!==P.marshal)return[];let c=s.b||s.w,u=i==="advanced"?3:2,f=[],l=[];if(c)f=r.color==="w"?[7,8,9]:[1,2,3];else{let d=r.color==="b"?1:9,h=r.color==="b"?9:1,m=r.color==="b"?1:-1;for(let g=d;r.color==="b"?g<=h:g>=h;g+=m)Array.from({length:9}).map((b,N)=>C(`${g}-${N+1}`,t)).some(b=>b&&b.color===r.color)?(f.push(...l,g),l=[]):l.push(g)}return f.flatMap(d=>Array.from({length:9},(h,m)=>`${d}-${m+1}`)).reduce((d,h)=>{let m=C(h,t),g={type:r.type,color:r.color,square:h,tier:0};if(!m||m.color===g.color&&m.tier<u&&m.type!==P.marshal){let y=(m?.tier??0)+1,N=o.filter($=>$.color===r.color).reduce(($,G)=>$+G.count,0)===1;s[r.color]?(N||d.push(I(g,`${h}-${y}`,e,"arata")),d.push(I(g,`${h}-${y}`,e,"arata",[],!0))):d.push(I(g,`${h}-${y}`,e,"arata"))}return d},[])}function I(r,e,t,n,i,o){let s=r.tier!==0?`(${r.square}-${r.tier})`:"",a=+(e.split("-").at(-1)??0),c=n==="arata"?"\u65B0":"",u=n==="capture"?"\u53D6":"",f=n==="tsuke"||a!==1&&a-r.tier>0?"\u4ED8":"",l=n==="betray"?`\u8FD4${i?.map(g=>g.type).join("")}`:"",p=o?"\u7D42":"",d={piece:r.type,color:r.color,from:s.slice(1,-1),to:e,type:n,san:`${c}${r.type}${s}${u}(${e})${l||f}${p}`,before:t,after:"",draftFinished:o,captured:i},{after:h,gameOverSAN:m}=_e(d,d.before);return d.after=h,d.san+=m,d}function _e(r,e){let{board:t,hand:n,mode:i,turn:o,drafting:s,moveNumber:a}=T(e),[c,u,f]=r.to.split("-"),l={type:r.piece,color:r.color,square:`${c}-${u}`,tier:+f};r.type==="route"||r.type==="tsuke"?S(r.from,t):r.type==="capture"?(S(r.from,t),Z(`${c}-${u}`,r.captured,t)):r.type==="betray"?(S(r.from,t),X(`${c}-${u}`,r.captured,t),B(r.captured,n,!0)):r.type==="arata"&&(B([l],n),r.draftFinished&&(s[r.color]=!1)),ee(l,t),o==="b"&&(s.w||!s.b)&&a++,o==="w"&&!s.b&&!s.w&&r.draftFinished&&a++,s.w===s.b?(!r.draftFinished||o!=="w")&&(o=o==="b"?"w":"b"):!s.b&&o==="b"?o="w":!s.w&&o==="w"&&(o="b");let p="";return r.captured?.some(d=>d.type===P.marshal)&&(p="#"),{after:q({board:t,hand:n,mode:i,turn:o,drafting:s,moveNumber:a}),gameOverSAN:p}}function Be(r){let e=[];function t(n,i){i.length>0&&e.push([...i]);for(let o=n;o<r.length;o++)i.push(r[o]),t(o+1,i),i.pop()}return t(0,[]),e}function Le(r,e){let t=C(r,e);if(!t)return[];let[n,i]=r.split("-").map(Number);return oe[t.type].flatMap((s,a)=>{let c=typeof s=="number"?s:s[0],u=typeof s=="number"?1:s[1];if(c<1)return[];let[f,l]=re[a];t.color==="b"&&(f*=-1,l*=-1);let[p,d]=c===1/0?[n+f,i+l]:[n+c*f,i+l],h=c===1/0?1/0:t.tier+u-1;return ne([f,l],[p,d],[n,i],h,e)})}function ie(r,e,t){let[n,i]=r.split("-").map(Number),o=`${n}-${i}`;for(let s of M){let a=C(s,t);if(!a||a.color!==e)continue;if(Le(s,t).some(u=>u.startsWith(o)))return!0}return!1}function W(r,e){let{board:t}=T(e),n=r==="w"?"b":"w";for(let i of M){let o=C(i,t);if(o?.type===P.marshal&&o.color===r)return ie(i,n,t)}return!1}function U(r){return W(r.color,r.after)}function se(r,e){let t=e?.maxWidth??6,n=e?.newline??`
2
- `,i=e?.withComments??!1,o=e?.comments??new Map,s="",a=0;return r.forEach((c,u)=>{let f=T(c.before);if(f.moveNumber!==a){let l=c.color==="w"?".":"...";s+=`${f.moveNumber}${l} `,a=f.moveNumber}s+=`${c.san} `,i&&o.has(c.after)&&(s+=`{${o.get(c.after)}} `),(u+1)%t===0&&(s+=n)}),s.replaceAll(" "," ").trim()}function ae(r,e){let t=e?.newline??`
3
- `,n=new Map,i=[],o=r.split(t).join(" ").replace(/\d+\.+/g,"").trim();for(;o.length>0&&(o=o.trim(),o.length!==0);){if(o.startsWith("{")){let a=o.indexOf("}");if(a!==-1){let c=o.slice(1,a).trim();i.length>0&&c&&n.set(i.length-1,c),o=o.slice(a+1);continue}}let s=o.match(/^(\S+)/);if(s){let a=s[1];a&&!a.startsWith("{")&&i.push(a),o=o.slice(a.length)}else break}return{moves:i,comments:n}}function ce(r,e,t){let n=T(r);return e?t?We(n,e,t):Qe(n,e):je(n)}function je(r){let e=pe(r),t=x[r.mode],n=de(e);return Object.entries(n).forEach(([i,o])=>{let[s,a]=i.split("|");Ze(o).forEach((u,f)=>{u.id=`${t}-${s}-${a}-${f+1}`})}),e}function We(r,e,t){let n=et(r),i=x[r.mode],o=Ue(t);return Ke(n,e,o),Je(n,e,t,i),le(n,i),n}function Ue(r){let e=[],t=[],n,i;switch(r.type){case"route":case"tsuke":if(r.from){let[o,s,a]=r.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:r.piece,color:r.color}}break;case"capture":if(r.from){let[o,s,a]=r.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:r.piece,color:r.color}}r.captured&&r.captured.forEach(o=>{e.push({square:r.to,tier:o.tier,type:o.type,color:o.color})});break;case"arata":t.push({color:r.color,type:r.piece}),i=r.to;break;case"betray":if(r.from){let[o,s,a]=r.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:r.piece,color:r.color}}r.captured&&(r.captured.forEach(o=>{e.push({square:r.to,tier:o.tier,type:o.type,color:o.color})}),r.captured.forEach(o=>{t.push({color:r.color,type:o.type})}));break}return{movingPiece:n,capturedPieces:e,placementSquare:i,handPieceTypes:t}}function Ke(r,e,t){let n=(i,o,s,a)=>!!(t.movingPiece&&t.movingPiece.square===i&&t.movingPiece.tier===o&&t.movingPiece.type===s&&t.movingPiece.color===a||t.capturedPieces.some(c=>c.square===i&&c.tier===o&&c.type===s&&c.color===a)||t.placementSquare===i);for(let i=0;i<9;i++)for(let o=0;o<9;o++){let s=`${i+1}-${9-o}`,a=r.board[i][o],c=e.board[i][o];for(let u=0;u<Math.min(a.length,c.length);u++){let f=a[u],l=c[u];f&&l&&f.type===l.type&&f.color===l.color&&l.id&&(n(s,u+1,f.type,f.color)||(f.id=l.id))}}r.hand.forEach(i=>{if(!t.handPieceTypes.some(s=>s.color===i.color&&s.type===i.type)){let s=e.hand.find(a=>a.type===i.type&&a.color===i.color);s?.id&&(i.id=s.id)}})}function Je(r,e,t,n){switch(t.type){case"route":case"tsuke":J(r,e,t);break;case"capture":ze(r,e,t);break;case"arata":Ve(r,e,t,n);break;case"betray":Ye(r,e,t,n);break}}function J(r,e,t){if(!t.from)return;let[n,i,o]=t.from.split("-").map(Number),s=`${n}-${i}`,a=K(e.board,s,t.piece,t.color,o);if(!a?.id)return;let[c,u,f]=t.to.split("-").map(Number),l=`${c}-${u}`,p=K(r.board,l,t.piece,t.color,f);p&&(p.id=a.id)}function ze(r,e,t){J(r,e,t)}function Ve(r,e,t,n){let i=e.hand.find(l=>l.type===t.piece&&l.color===t.color);if(!i?.id)return;let[o,s,a]=t.to.split("-").map(Number),c=`${o}-${s}`,u=K(r.board,c,t.piece,t.color,a);u&&(u.id=i.id);let f=r.hand.find(l=>l.type===t.piece&&l.color===t.color);if(f){let l=fe(r,n,t.color,t.piece);f.id=l}}function Ye(r,e,t,n){J(r,e,t),t.captured&&t.captured.forEach(i=>{let o=r.hand.find(s=>s.type===i.type&&s.color===t.color);if(o&&!o.id){let s=fe(r,n,t.color,i.type);o.id=s}})}function Qe(r,e){let t=pe(r),n=x[r.mode],i=new Set;for(let o of e.hand){let s=t.hand.find(u=>u.type===o.type&&u.color===o.color),a=o.count,c=s?.count??0;if(a>c&&o.id){let u=Xe(t.board,e.board,o.type,o.color);u&&(u.id=o.id,i.add(o.id))}}for(let o=0;o<9;o++)for(let s=0;s<9;s++){let a=t.board[o][s],c=e.board[o][s];for(let u=0;u<Math.min(a.length,c.length);u++){let f=a[u],l=c[u];f&&!f.id&&l&&f.type===l.type&&f.color===l.color&&l.id&&(f.id=l.id)}}return t.hand.forEach(o=>{if(o.id)return;let s=e.hand.find(a=>a.type===o.type&&a.color===o.color);s?.id&&!i.has(s.id)&&(o.id=s.id)}),le(t,n),t}function Xe(r,e,t,n){for(let i=0;i<9;i++)for(let o=0;o<9;o++){let s=r[i][o],a=e[i][o];for(let c=0;c<s.length;c++){let u=s[c];if(u&&u.type===t&&u.color===n&&!u.id){let f=a[c];if(!f||f.type!==t||f.color!==n)return u}}}return null}function le(r,e){let t=new Set(ue(r)),n=de(r);Object.entries(n).forEach(([i,o])=>{let[s,a]=i.split("|");o.forEach(c=>{if(!c.id){let u=1,f=`${e}-${s}-${a}-${u}`;for(;t.has(f);)u++,f=`${e}-${s}-${a}-${u}`;c.id=f,t.add(f)}})})}function fe(r,e,t,n){let i=new Set(ue(r)),o=1,s=`${e}-${t}-${n}-${o}`;for(;i.has(s);)o++,s=`${e}-${t}-${n}-${o}`;return s}function ue(r){let e=[];for(let t of r.board)for(let n of t)for(let i of n)i?.id&&e.push(i.id);for(let t of r.hand)t.id&&e.push(t.id);return e}function de(r){let e={};for(let t of r.board)for(let n of t)for(let i of n)if(i){let o=`${i.color}|${i.type}`;e[o]||(e[o]=[]),e[o].push(i)}for(let t of r.hand){let n=`${t.color}|${t.type}`;e[n]||(e[n]=[]),e[n].push(t)}return e}function Ze(r){return r.sort((e,t)=>{let n="square"in e,i="square"in t;if(n&&!i)return-1;if(!n&&i)return 1;if(n&&i){let o=e,s=t;if(o.square!==s.square){let[a,c]=o.square.split("-").map(Number),[u,f]=s.square.split("-").map(Number);return a!==u?a-u:c-f}return o.tier-s.tier}return 0})}function K(r,e,t,n,i){let[o,s]=e.split("-").map(Number);if(o<1||o>9||s<1||s>9)return null;let a=r[o-1][9-s];for(let c of a)if(c&&(!t||c.type===t)&&(!n||c.color===n)&&(!i||c.tier===i))return c;return null}function pe(r){return{board:r.board.map(e=>e.map(t=>t.map(n=>n&&{...n}))),hand:r.hand.map(e=>({...e})),turn:r.turn,mode:r.mode,drafting:{...r.drafting},moveNumber:r.moveNumber}}function et(r){return{board:r.board.map(e=>e.map(t=>t.map(n=>n&&{...n,id:void 0}))),hand:r.hand.map(e=>({...e,id:void 0})),turn:r.turn,mode:r.mode,drafting:{...r.drafting},moveNumber:r.moveNumber}}var he=class{#r;#o;#s;#a;#i;#l;#e=[];#f=null;#t=new Map;#c;#n(e,t){let n=ce(e,this.#f,t);this.#r=n.board,this.#o=n.hand,this.#s=n.turn,this.#a=n.moveNumber,this.#i=n.drafting,this.#l=n.mode,this.#f=n}constructor(e){this.#c=e??te,this.#n(this.#c)}ascii(e){let t={1:D.yellow,2:D.blue,3:D.green},n=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
1
+ import D from"picocolors";var H=t=>Object.entries(t).reduce((e,[r,n])=>({...e,[n]:r}),{}),x={intro:0,beginner:1,intermediate:2,advanced:3},V=H(x),me="w",ge="b",ye="\u4ED8",be="\u53D6",Pe="\u8FD4",Ne="\u65B0",Ce="\u5E25",Ee="\u5927",$e="\u4E2D",Te="\u5C0F",we="\u4F8D",ke="\u69CD",xe="\u99AC",Me="\u5FCD",Ae="\u7826",Ie="\u5175",Fe="\u7832",ve="\u5F13",Re="\u7B52",Se="\u8B00",M=Array.from({length:9},(t,e)=>e+1).flatMap(t=>Array.from({length:9},(e,r)=>`${t}-${9-r}`)),b={marshal:"\u5E25",general:"\u5927",lieutenant_general:"\u4E2D",major_general:"\u5C0F",warrior:"\u4F8D",lancer:"\u69CD",rider:"\u99AC",spy:"\u5FCD",fortress:"\u7826",soldier:"\u5175",cannon:"\u7832",archer:"\u5F13",musketeer:"\u7B52",tactician:"\u8B00"},A=H(b),w={marshal:"m",general:"g",lieutenant_general:"i",major_general:"j",warrior:"w",lancer:"n",rider:"r",spy:"s",fortress:"f",soldier:"d",cannon:"c",archer:"a",musketeer:"k",tactician:"t"},Y=H(w),_=(t,[e,r,n])=>{let i=t===t.toLowerCase()?"b":"w",o=Y[t.toLowerCase()];return{square:`${e}-${r}`,tier:n,type:b[o],color:i}},Q=(t,e)=>{let r=t===t.toLowerCase()?"b":"w",n=Y[t.toLowerCase()];return{type:b[n],count:e,color:r}},Oe={\u5E25:"sui",\u5927:"taishou",\u4E2D:"chuujou",\u5C0F:"shoushou",\u4F8D:"samurai",\u69CD:"yari",\u99AC:"kiba",\u5FCD:"shinobi",\u7826:"toride",\u5175:"hyou",\u7832:"oodzutsu",\u5F13:"yumi",\u7B52:"tsutsu",\u8B00:"boushou"},qe={\u5E25:"marshal",\u5927:"general",\u4E2D:"lieutenant general",\u5C0F:"major general",\u4F8D:"warrior",\u69CD:"lancer",\u99AC:"rider",\u5FCD:"spy",\u7826:"fortress",\u5175:"soldier",\u7832:"cannon",\u5F13:"archer",\u7B52:"musketeer",\u8B00:"tactician"},De={\u5E25:"m",\u5927:"g",\u4E2D:"i",\u5C0F:"j",\u4F8D:"w",\u69CD:"n",\u99AC:"r",\u5FCD:"s",\u7826:"f",\u5175:"d",\u7832:"c",\u5F13:"a",\u7B52:"k",\u8B00:"t"};function B(t,e,r=!1){return t.forEach(n=>{let i=r?n.color==="b"?"w":"b":n.color,o=e.find(a=>a.type===n.type&&a.color===i),s=e.findIndex(a=>a.type===n.type&&a.color===i);o&&(o.count--,o.count===0&&e.splice(s,1))}),e}function X(t,e,r){let[n,i]=t.split("-").map(Number),o=k(t,r);o&&(r[n-1][9-i]=o.map(s=>(e.find(c=>JSON.stringify(c)===JSON.stringify(s))&&(s.color=s.color==="b"?"w":"b"),s)))}function Z(t,e,r){let[n,i]=t.split("-").map(Number),o=k(t,r);if(!o)return;let s=o.filter(a=>!e.some(c=>JSON.stringify(c)===JSON.stringify(a)));s.length===0?r[n-1][9-i]=[null]:r[n-1][9-i]=s}function S(t,e){let[r,n]=t.split("-").map(Number),i=k(t,e);i&&(i.pop(),i.length===0&&(e[r-1][9-n]=[null]))}function ee(t,e){let[r,n]=t.square.split("-").map(Number);e[r-1][9-n][0]?e[r-1][9-n].push(t):e[r-1][9-n]=[t]}function C(t,e){let r=k(t,e);return r?r.at(-1):void 0}function k(t,e){let[r,n]=t.split("-").map(Number);if(r<1||r>9||n<1||n>9)return;let i=e[r-1][9-n];if(i[0])return i}function O(t){return t.flat().flat().filter(r=>r?.type==="\u5E25").length!==2}var re="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Ge="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",He="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",L="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function T(t){let e=j(t);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[r,n,i,o,s,a]=t.split(" "),c=r.split("/").map((f,l)=>f.split("|").reduce((p,d)=>{if(d.includes(":")){let h=d.split(":").map((m,g)=>_(m,[l+1,9-p.length,g+1]));p.push(h)}else{let h=d.split("").reduce((m,g)=>(Number.isInteger(+g)?m=m.concat(Array(+g).fill(null)):m.push(_(g,[l+1,9-p.length-m.length,1])),m),[]).map(m=>[m]);p=p.concat(h)}return p},[])),u=n.split("/").flatMap(f=>{let l=[];if(f!=="-")for(let p=0;p<f.length;p+=2){let d=f[p],h=+f[p+1];l.push(Q(d,h))}return l});return{board:c,hand:u,turn:i,mode:V[+o],drafting:{w:s.includes("w"),b:s.includes("b")},moveNumber:+a}}function q(t){let e="",r=0;for(let a=0;a<9;a++){for(let c=0;c<9;c++){let u=t.board[a][c];if(!u[0]){r++;continue}if(r&&(e+=r,r=0),u.length>1)e+="|"+u.map(f=>{if(!f)return null;let l=w[A[f.type]];return f.color==="w"?l.toUpperCase():l}).join(":")+"|";else{let{type:f,color:l}=u[0],p=w[A[f]];e+=l==="w"?p.toUpperCase():p}}e+=r?`${r}/`:"/",r=0}let n="",i=t.hand.filter(a=>a.color==="w"),o=t.hand.filter(a=>a.color==="b");i.forEach(a=>{let c=w[A[a.type]];n+=`${a.color==="w"?c.toUpperCase():c}${a.count}`}),n+=i.length>0?"/":"-/",o.forEach(a=>{let c=w[A[a.type]];n+=`${a.color==="w"?c.toUpperCase():c}${a.count}`}),n+=o.length>0?"":"-";let s=Object.keys(t.drafting).filter(a=>t.drafting[a]);return`${e.slice(0,-1)} ${n} ${t.turn} ${x[t.mode]} ${s.length>0?s.join(""):"-"} ${t.moveNumber}`}function j(t){let e=t.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[r,n,i,o,s,a]=e,c=r.split("/");if(c.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${c.length}]`};for(let p=0;p<c.length;p++){let h=c[p].split("|"),m=0;for(let g=0;g<h.length;g++){let P=h[g];if(P.includes(":")){m++;let y=P.split(":");if(y.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${m})`};if(!y.every(N=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(N)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${m})`}}else{let y=P.split("");for(let N=0;N<y.length;N++){let $=y[N];if(Number.isInteger(+$))m+=+$;else if(m++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes($))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${m})`}}}}if(m!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${m}] in rank: ${p+1}`}}let u=n.split("/");if(u.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${u.length}]`};let[f,l]=u;if(f.length===1&&f!=="-"||l.length===1&&l!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(f.length>1&&f.length%2!==0||l.length>1&&l.length%2!==0)return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece count]"};if(f.length>1)for(let p=0;p<f.length;p+=2){if(!"MGIJWNRSFDCAKT".includes(f[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+f[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}if(l.length>1)for(let p=0;p<l.length;p+=2){if(!"mgijwnrsfdcakt".includes(l[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+l[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return i!=="w"&&i!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${i}]`}:o.length!==1||!"0123".includes(o)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${o}]`}:s!=="-"&&!"wb".includes(s)?{ok:!1,error:`5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${s}]`}:Number.isInteger(+a)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${a}]`}}var te=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],oe={\u5E25:[1,1,1,1,1,1,1,1],\u5927:[1,1/0,1,1/0,1/0,1,1/0,1],\u4E2D:[1/0,1,1/0,1,1,1/0,1,1/0],\u5C0F:[1,1,1,1,1,0,1,0],\u4F8D:[1,1,1,0,0,0,1,0],\u69CD:[1,[1,2],1,0,0,0,1,0],\u99AC:[0,[1,2],0,1,1,0,[1,2],0],\u5FCD:[[1,2],0,[1,2],0,0,[1,2],0,[1,2]],\u7826:[0,1,0,1,1,1,0,1],\u5175:[0,1,0,0,0,0,1,0],\u7832:[0,3,0,1,1,0,1,0],\u5F13:[2,2,2,0,0,0,1,0],\u7B52:[0,2,0,0,0,1,0,1],\u8B00:[1,0,1,0,0,0,1,0]};function ne(t,e,r,n,i){let[o,s]=e,[a,c]=r,[u,f]=t,l=C(`${a}-${c}`,i);if(l.type===b.archer&&Math.abs(u)===1&&Math.abs(f)===1){let g=C(`${a+u}-${c+f}`,i);if(g&&g.tier>l.tier)return[]}let p=[],d={x:s,y:o};for(;d.x!==c||d.y!==a;){d.x-=f,d.y-=u;let g=C(`${d.y}-${d.x}`,i);if(g&&g.tier>l.tier)return[];let P=l.color==="b"?-1:1,y=C(`${d.y+P}-${d.x}`,i);if(y&&y.square===`${a}-${c}`)break}let h={x:s,y:o},m=0;for(;m<n&&!(h.x<1||h.x>9||h.y<1||h.y>9);){let g=C(`${h.y}-${h.x}`,i);if(g&&g.tier>l.tier)break;p.push(`${h.y}-${h.x}`);let P=[b.cannon,b.musketeer,b.archer];if(g&&(!P.includes(l.type)||!(l.color==="w"?u<0:u>0)))break;h.x+=f,h.y+=u,m++}return p}function R(t,e){let{board:r,turn:n,mode:i,hand:o}=T(e),s=C(t,r);if(!s||n!==s.color)return[];let[a,c]=t.split("-").map(Number);return oe[s.type].flatMap((l,p)=>{let d=typeof l=="number"?l:l[0],h=typeof l=="number"?1:l[1];if(d<1)return[];let[m,g]=te[p];s.color==="b"&&(m*=-1,g*=-1);let[P,y]=d===1/0?[a+m,c+g]:[a+d*m,c+g],N=d===1/0?1/0:s.tier+h-1;return ne([m,g],[P,y],[a,c],N,r)}).reduce((l,p)=>{let d=C(p,r),h=k(p,r),m=i==="advanced"?3:2,g=["advanced","intermediate"].includes(i);if(!d||!h)l.push(I(s,`${p}-1`,e,"route"));else{if(d.tier<m&&d.type!==b.marshal&&((s.type!==b.marshal||g)&&l.push(I(s,`${p}-${d.tier+1}`,e,"tsuke")),s.type===b.tactician&&d.color!==s.color)){let P=h.filter(E=>E.color!==s.color),y=o.filter(E=>E.color===s.color),N=P.reduce((E,v)=>(E.set(v.type,(E.get(v.type)??0)+1),E),new Map),$=Array.from(N.entries()).filter(([E,v])=>y.some(z=>z.type===E&&z.count>=v)).flatMap(([E])=>P.filter(v=>v.type===E)),G=Be($);l.push(...G.map(E=>I(s,`${p}-${d.tier+1}`,e,"betray",E)))}if(d.color!==s.color){let P=h.filter(N=>N.color===s.color).length+1,y=h.filter(N=>N.color!==s.color);l.push(I(s,`${p}-${P}`,e,"capture",y))}}return l},[])}function F(t,e){let{board:r,turn:n,mode:i,hand:o,drafting:s}=T(e);if(!t||n!==t.color)return[];if(!!o.some(d=>d.type===b.marshal&&d.color===t.color)&&t.type!==b.marshal)return[];let c=s.b||s.w,u=i==="advanced"?3:2,f=[],l=[];if(c)f=t.color==="w"?[7,8,9]:[1,2,3];else{let d=t.color==="b"?1:9,h=t.color==="b"?9:1,m=t.color==="b"?1:-1;for(let g=d;t.color==="b"?g<=h:g>=h;g+=m)Array.from({length:9}).map((y,N)=>C(`${g}-${N+1}`,r)).some(y=>y&&y.color===t.color)?(f.push(...l,g),l=[]):l.push(g)}return f.flatMap(d=>Array.from({length:9},(h,m)=>`${d}-${m+1}`)).reduce((d,h)=>{let m=C(h,r),g={type:t.type,color:t.color,square:h,tier:0};if(!m||m.color===g.color&&m.tier<u&&m.type!==b.marshal){let P=(m?.tier??0)+1,N=o.filter($=>$.color===t.color).reduce(($,G)=>$+G.count,0)===1;s[t.color]?(N||d.push(I(g,`${h}-${P}`,e,"arata")),d.push(I(g,`${h}-${P}`,e,"arata",[],!0))):d.push(I(g,`${h}-${P}`,e,"arata"))}return d},[])}function I(t,e,r,n,i,o){let s=t.tier!==0?`(${t.square}-${t.tier})`:"",a=+(e.split("-").at(-1)??0),c=n==="arata"?"\u65B0":"",u=n==="capture"?"\u53D6":"",f=n==="tsuke"||a!==1&&a-t.tier>0?"\u4ED8":"",l=n==="betray"?`\u8FD4${i?.map(g=>g.type).join("")}`:"",p=o?"\u7D42":"",d={piece:t.type,color:t.color,from:s.slice(1,-1),to:e,type:n,san:`${c}${t.type}${s}${u}(${e})${l||f}${p}`,before:r,after:"",draftFinished:o,captured:i},{after:h,gameOverSAN:m}=_e(d,d.before);return d.after=h,d.san+=m,d}function _e(t,e){let{board:r,hand:n,mode:i,turn:o,drafting:s,moveNumber:a}=T(e),[c,u,f]=t.to.split("-"),l={type:t.piece,color:t.color,square:`${c}-${u}`,tier:+f};t.type==="route"||t.type==="tsuke"?S(t.from,r):t.type==="capture"?(S(t.from,r),Z(`${c}-${u}`,t.captured,r)):t.type==="betray"?(S(t.from,r),X(`${c}-${u}`,t.captured,r),B(t.captured,n,!0)):t.type==="arata"&&(B([l],n),t.draftFinished&&(s[t.color]=!1,t.color==="b"&&(s.w=!1))),ee(l,r),o==="b"&&(s.w||!s.b)&&a++,o==="w"&&!s.b&&!s.w&&t.draftFinished&&a++,s.w===s.b?(!t.draftFinished||o!=="w")&&(o=o==="b"?"w":"b"):!s.b&&o==="b"?o="w":!s.w&&o==="w"&&(o="b");let p="";return t.captured?.some(d=>d.type===b.marshal)&&(p="#"),{after:q({board:r,hand:n,mode:i,turn:o,drafting:s,moveNumber:a}),gameOverSAN:p}}function Be(t){let e=[];function r(n,i){i.length>0&&e.push([...i]);for(let o=n;o<t.length;o++)i.push(t[o]),r(o+1,i),i.pop()}return r(0,[]),e}function Le(t,e){let r=C(t,e);if(!r)return[];let[n,i]=t.split("-").map(Number);return oe[r.type].flatMap((s,a)=>{let c=typeof s=="number"?s:s[0],u=typeof s=="number"?1:s[1];if(c<1)return[];let[f,l]=te[a];r.color==="b"&&(f*=-1,l*=-1);let[p,d]=c===1/0?[n+f,i+l]:[n+c*f,i+l],h=c===1/0?1/0:r.tier+u-1;return ne([f,l],[p,d],[n,i],h,e)})}function ie(t,e,r){let[n,i]=t.split("-").map(Number),o=`${n}-${i}`;for(let s of M){let a=C(s,r);if(!a||a.color!==e)continue;if(Le(s,r).some(u=>u.startsWith(o)))return!0}return!1}function W(t,e){let{board:r}=T(e),n=t==="w"?"b":"w";for(let i of M){let o=C(i,r);if(o?.type===b.marshal&&o.color===t)return ie(i,n,r)}return!1}function U(t){return W(t.color,t.after)}function se(t,e){let r=e?.maxWidth??6,n=e?.newline??`
2
+ `,i=e?.withComments??!1,o=e?.comments??new Map,s="",a=0;return t.forEach((c,u)=>{let f=T(c.before);if(f.moveNumber!==a){let l=c.color==="w"?".":"...";s+=`${f.moveNumber}${l} `,a=f.moveNumber}s+=`${c.san} `,i&&o.has(c.after)&&(s+=`{${o.get(c.after)}} `),(u+1)%r===0&&(s+=n)}),s.replaceAll(" "," ").trim()}function ae(t,e){let r=e?.newline??`
3
+ `,n=new Map,i=[],o=t.split(r).join(" ").replace(/\d+\.+/g,"").trim();for(;o.length>0&&(o=o.trim(),o.length!==0);){if(o.startsWith("{")){let a=o.indexOf("}");if(a!==-1){let c=o.slice(1,a).trim();i.length>0&&c&&n.set(i.length-1,c),o=o.slice(a+1);continue}}let s=o.match(/^(\S+)/);if(s){let a=s[1];a&&!a.startsWith("{")&&i.push(a),o=o.slice(a.length)}else break}return{moves:i,comments:n}}function ce(t,e,r){let n=T(t);return e?r?We(n,e,r):Qe(n,e):je(n)}function je(t){let e=pe(t),r=x[t.mode],n=de(e);return Object.entries(n).forEach(([i,o])=>{let[s,a]=i.split("|");Ze(o).forEach((u,f)=>{u.id=`${r}-${s}-${a}-${f+1}`})}),e}function We(t,e,r){let n=er(t),i=x[t.mode],o=Ue(r);return Ke(n,e,o),Je(n,e,r,i),le(n,i),n}function Ue(t){let e=[],r=[],n,i;switch(t.type){case"route":case"tsuke":if(t.from){let[o,s,a]=t.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:t.piece,color:t.color}}break;case"capture":if(t.from){let[o,s,a]=t.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:t.piece,color:t.color}}t.captured&&t.captured.forEach(o=>{e.push({square:t.to,tier:o.tier,type:o.type,color:o.color})});break;case"arata":r.push({color:t.color,type:t.piece}),i=t.to;break;case"betray":if(t.from){let[o,s,a]=t.from.split("-").map(Number);n={square:`${o}-${s}`,tier:a,type:t.piece,color:t.color}}t.captured&&(t.captured.forEach(o=>{e.push({square:t.to,tier:o.tier,type:o.type,color:o.color})}),t.captured.forEach(o=>{r.push({color:t.color,type:o.type})}));break}return{movingPiece:n,capturedPieces:e,placementSquare:i,handPieceTypes:r}}function Ke(t,e,r){let n=(i,o,s,a)=>!!(r.movingPiece&&r.movingPiece.square===i&&r.movingPiece.tier===o&&r.movingPiece.type===s&&r.movingPiece.color===a||r.capturedPieces.some(c=>c.square===i&&c.tier===o&&c.type===s&&c.color===a)||r.placementSquare===i);for(let i=0;i<9;i++)for(let o=0;o<9;o++){let s=`${i+1}-${9-o}`,a=t.board[i][o],c=e.board[i][o];for(let u=0;u<Math.min(a.length,c.length);u++){let f=a[u],l=c[u];f&&l&&f.type===l.type&&f.color===l.color&&l.id&&(n(s,u+1,f.type,f.color)||(f.id=l.id))}}t.hand.forEach(i=>{if(!r.handPieceTypes.some(s=>s.color===i.color&&s.type===i.type)){let s=e.hand.find(a=>a.type===i.type&&a.color===i.color);s?.id&&(i.id=s.id)}})}function Je(t,e,r,n){switch(r.type){case"route":case"tsuke":J(t,e,r);break;case"capture":ze(t,e,r);break;case"arata":Ve(t,e,r,n);break;case"betray":Ye(t,e,r,n);break}}function J(t,e,r){if(!r.from)return;let[n,i,o]=r.from.split("-").map(Number),s=`${n}-${i}`,a=K(e.board,s,r.piece,r.color,o);if(!a?.id)return;let[c,u,f]=r.to.split("-").map(Number),l=`${c}-${u}`,p=K(t.board,l,r.piece,r.color,f);p&&(p.id=a.id)}function ze(t,e,r){J(t,e,r)}function Ve(t,e,r,n){let i=e.hand.find(l=>l.type===r.piece&&l.color===r.color);if(!i?.id)return;let[o,s,a]=r.to.split("-").map(Number),c=`${o}-${s}`,u=K(t.board,c,r.piece,r.color,a);u&&(u.id=i.id);let f=t.hand.find(l=>l.type===r.piece&&l.color===r.color);if(f){let l=fe(t,n,r.color,r.piece);f.id=l}}function Ye(t,e,r,n){J(t,e,r),r.captured&&r.captured.forEach(i=>{let o=t.hand.find(s=>s.type===i.type&&s.color===r.color);if(o&&!o.id){let s=fe(t,n,r.color,i.type);o.id=s}})}function Qe(t,e){let r=pe(t),n=x[t.mode],i=new Set;for(let o of e.hand){let s=r.hand.find(u=>u.type===o.type&&u.color===o.color),a=o.count,c=s?.count??0;if(a>c&&o.id){let u=Xe(r.board,e.board,o.type,o.color);u&&(u.id=o.id,i.add(o.id))}}for(let o=0;o<9;o++)for(let s=0;s<9;s++){let a=r.board[o][s],c=e.board[o][s];for(let u=0;u<Math.min(a.length,c.length);u++){let f=a[u],l=c[u];f&&!f.id&&l&&f.type===l.type&&f.color===l.color&&l.id&&(f.id=l.id)}}return r.hand.forEach(o=>{if(o.id)return;let s=e.hand.find(a=>a.type===o.type&&a.color===o.color);s?.id&&!i.has(s.id)&&(o.id=s.id)}),le(r,n),r}function Xe(t,e,r,n){for(let i=0;i<9;i++)for(let o=0;o<9;o++){let s=t[i][o],a=e[i][o];for(let c=0;c<s.length;c++){let u=s[c];if(u&&u.type===r&&u.color===n&&!u.id){let f=a[c];if(!f||f.type!==r||f.color!==n)return u}}}return null}function le(t,e){let r=new Set(ue(t)),n=de(t);Object.entries(n).forEach(([i,o])=>{let[s,a]=i.split("|");o.forEach(c=>{if(!c.id){let u=1,f=`${e}-${s}-${a}-${u}`;for(;r.has(f);)u++,f=`${e}-${s}-${a}-${u}`;c.id=f,r.add(f)}})})}function fe(t,e,r,n){let i=new Set(ue(t)),o=1,s=`${e}-${r}-${n}-${o}`;for(;i.has(s);)o++,s=`${e}-${r}-${n}-${o}`;return s}function ue(t){let e=[];for(let r of t.board)for(let n of r)for(let i of n)i?.id&&e.push(i.id);for(let r of t.hand)r.id&&e.push(r.id);return e}function de(t){let e={};for(let r of t.board)for(let n of r)for(let i of n)if(i){let o=`${i.color}|${i.type}`;e[o]||(e[o]=[]),e[o].push(i)}for(let r of t.hand){let n=`${r.color}|${r.type}`;e[n]||(e[n]=[]),e[n].push(r)}return e}function Ze(t){return t.sort((e,r)=>{let n="square"in e,i="square"in r;if(n&&!i)return-1;if(!n&&i)return 1;if(n&&i){let o=e,s=r;if(o.square!==s.square){let[a,c]=o.square.split("-").map(Number),[u,f]=s.square.split("-").map(Number);return a!==u?a-u:c-f}return o.tier-s.tier}return 0})}function K(t,e,r,n,i){let[o,s]=e.split("-").map(Number);if(o<1||o>9||s<1||s>9)return null;let a=t[o-1][9-s];for(let c of a)if(c&&(!r||c.type===r)&&(!n||c.color===n)&&(!i||c.tier===i))return c;return null}function pe(t){return{board:t.board.map(e=>e.map(r=>r.map(n=>n&&{...n}))),hand:t.hand.map(e=>({...e})),turn:t.turn,mode:t.mode,drafting:{...t.drafting},moveNumber:t.moveNumber}}function er(t){return{board:t.board.map(e=>e.map(r=>r.map(n=>n&&{...n,id:void 0}))),hand:t.hand.map(e=>({...e,id:void 0})),turn:t.turn,mode:t.mode,drafting:{...t.drafting},moveNumber:t.moveNumber}}var he=class{#t;#o;#s;#a;#i;#l;#e=[];#f=null;#r=new Map;#c;#n(e,r){let n=ce(e,this.#f,r);this.#t=n.board,this.#o=n.hand,this.#s=n.turn,this.#a=n.moveNumber,this.#i=n.drafting,this.#l=n.mode,this.#f=n}constructor(e){this.#c=e??re,this.#n(this.#c)}ascii(e){let r={1:D.yellow,2:D.blue,3:D.green},n=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
4
4
  `;n+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
5
- `;for(let i=1;i<=9;i++){n+="\uFF5C";for(let o=9;o>0;o--){let s=this.getTop(`${i}-${o}`);if(!s){n+="\u30FB";continue}let a=w[A[s.type]],c=s.color==="w"?a.toUpperCase():a,u=t[s.tier](e?.english?String.fromCharCode(c.charCodeAt(0)+65248):s.type);n+=s.color==="w"?u:D.dim(u)}n+=`\uFF5C${String.fromCharCode(i-1+65297)}
5
+ `;for(let i=1;i<=9;i++){n+="\uFF5C";for(let o=9;o>0;o--){let s=this.getTop(`${i}-${o}`);if(!s){n+="\u30FB";continue}let a=w[A[s.type]],c=s.color==="w"?a.toUpperCase():a,u=r[s.tier](e?.english?String.fromCharCode(c.charCodeAt(0)+65248):s.type);n+=s.color==="w"?u:D.dim(u)}n+=`\uFF5C${String.fromCharCode(i-1+65297)}
6
6
  `}return n+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
7
- `,n}board(){return this.#r}captured(e){let n=this.#e.flatMap(i=>i.captured??[]).reduce((i,o)=>{let s=i.find(a=>a.type===o.type&&a.color===o.color);return s?s.count++:i.push({type:o.type,color:o.color,count:1}),i},[]);return e?n.filter(i=>i.color===e):n}clear(){this.#n(L),this.#e=[],this.#t.clear()}fen(){return q({board:this.#r,hand:this.#o,turn:this.#s,mode:this.#l,drafting:this.#i,moveNumber:this.#a})}get(e){return k(e,this.#r)}getDraftingRights(e){return e?this.#i[e]:this.#i}getTop(e){return C(e,this.#r)}hand(e){return e?this.#o.filter(t=>t.color===e):this.#o}history(e){return e?.verbose?this.#e:this.#e.map(t=>t.san)}inDraft(){return this.#i.b||this.#i.w}isFourfoldRepetition(){let e=this.#e.map(n=>n.before.split(" ")[0]);e.length&&e.push(this.#e.at(-1).after.split(" ")[0]);let t=e.reduce((n,i)=>(n.set(i,(n.get(i)||0)+1),n),new Map);return Math.max(...t.values())===4}#d(){let e=this.fen();if(this.inDraft())return this.#o.every(t=>F(t,e).length===0);for(let t of M)if(R(t,e).length>0)return!1;for(let t of this.#o)if(F(t,e).length>0)return!1;return!0}#u(){let e=this.fen();for(let t of M){let n=R(t,e);for(let i of n)if(!U(i))return!0}for(let t of this.#o){let n=F(t,e);for(let i of n)if(!U(i))return!0}return!1}inCheck(e){let t=e??this.turn();return W(t,this.fen())}isCheckmate(){return this.inDraft()||O(this.#r)?!1:this.inCheck()&&!this.#u()}isStalemate(){return this.inDraft()||O(this.#r)?!1:!this.inCheck()&&!this.#u()}isInsufficientMaterial(){if(this.inDraft()||this.#o.some(d=>d.type!==P.marshal))return!1;let e=this.#r.flat().flat().filter(d=>d!==null);if(e.filter(d=>d.type!==P.marshal).length>0)return!1;let n=e.filter(d=>d.type===P.marshal);if(n.length!==2)return!1;let[i,o]=n,[s,a]=i.square.split("-").map(Number),[c,u]=o.square.split("-").map(Number),f=Math.abs(s-c),l=Math.abs(a-u);return!(f<=1&&l<=1)}isDraw(){return this.isStalemate()||this.isFourfoldRepetition()||this.isInsufficientMaterial()}isGameOver(){return this.inDraft()?!1:O(this.#r)||this.isFourfoldRepetition()||this.isInsufficientMaterial()?!0:this.isCheckmate()||this.isStalemate()}load(e){this.#n(e)}loadPgn(e,t=L,n){this.#n(t),this.#e=[],this.#t.clear();let i=ae(e,n);i.moves.forEach((o,s)=>{this.move(o);let a=i.comments.get(s);a&&this.setComment(a)})}move(e){let t=this.moves({verbose:!0}),n=typeof e=="string"?e.replace(/[=#]$/,""):null,i=typeof e=="string"?t.find(o=>o.san===n||o.san===e):t.find(o=>e.piece===o.piece&&e.type===o.type&&e.from===o.from&&e.to===o.to&&e.captured===o.captured&&e.draftFinished===o.draftFinished);if(!i)throw new Error(`Illegal move: ${e}`);return this.#e.push(i),this.#n(i.after,i),this.isCheckmate()?this.#e.at(-1).san+="#":(this.isStalemate()||this.isFourfoldRepetition()||this.isInsufficientMaterial())&&(this.#e.at(-1).san+="="),i}moves(e){if(this.isGameOver())return[];if(e?.square){let t=R(e.square,this.fen());return e.verbose?t:t.map(n=>n.san)}else if(e?.arata){let t=F(e.arata,this.fen());return e.verbose?t:t.map(n=>n.san)}else if(this.inDraft()){let t=this.hand().flatMap(n=>F(n,this.fen()));return e?.verbose?t:t.map(n=>n.san)}else{let t=M.flatMap(o=>R(o,this.fen())),n=this.hand().flatMap(o=>F(o,this.fen())),i=[...t,...n];return e?.verbose?i:i.map(o=>o.san)}}moveNumber(){return this.#a}pgn(e){return se(this.#e,{...e,comments:this.#t})}print(e){console.log(this.ascii(e))}reset(){this.#n(this.#c),this.#e=[],this.#t.clear()}turn(){return this.#s}undo(){let e=this.#e.pop();return e?(this.#n(e.before),e):null}setComment(e){this.#t.set(this.fen(),e)}getComment(){return this.#t.get(this.fen())}removeComment(){let e=this.fen(),t=this.#t.get(e);return this.#t.delete(e),t}getComments(){let e=[];for(let[t,n]of this.#t)e.push({fen:t,comment:n});return e}removeComments(){let e=this.getComments();return this.#t.clear(),e}validateFen(e){return j(e)}};export{L as ADVANCED_POSITION,Ne as ARATA,ve as ARCHER,Ge as BEGINNER_POSITION,Pe as BETRAY,ge as BLACK,Fe as CANNON,Oe as CANONICAL_NAMES,qe as ENGLISH_NAMES,De as FEN_CODES,Ae as FORTRESS,Ee as GENERAL,he as Gungi,He as INTERMEDIATE_POSITION,te as INTRO_POSITION,ke as LANCER,$e as LIEUTENANT_GENERAL,Te as MAJOR_GENERAL,Ce as MARSHAL,Re as MUSKETEER,xe as RIDER,Ie as SOLDIER,Me as SPY,M as SQUARES,Se as TACTICIAN,be as TAKE,ye as TSUKE,we as WARRIOR,me as WHITE,ie as isSquareAttacked,j as validateFen};
7
+ `,n}board(){return this.#t}captured(e){let n=this.#e.flatMap(i=>i.captured??[]).reduce((i,o)=>{let s=i.find(a=>a.type===o.type&&a.color===o.color);return s?s.count++:i.push({type:o.type,color:o.color,count:1}),i},[]);return e?n.filter(i=>i.color===e):n}clear(){this.#n(L),this.#e=[],this.#r.clear()}fen(){return q({board:this.#t,hand:this.#o,turn:this.#s,mode:this.#l,drafting:this.#i,moveNumber:this.#a})}get(e){return k(e,this.#t)}getDraftingRights(e){return e?this.#i[e]:this.#i}getTop(e){return C(e,this.#t)}hand(e){return e?this.#o.filter(r=>r.color===e):this.#o}history(e){return e?.verbose?this.#e:this.#e.map(r=>r.san)}inDraft(){return this.#i.b||this.#i.w}isFourfoldRepetition(){let e=this.#e.map(n=>n.before.split(" ")[0]);e.length&&e.push(this.#e.at(-1).after.split(" ")[0]);let r=e.reduce((n,i)=>(n.set(i,(n.get(i)||0)+1),n),new Map);return Math.max(...r.values())===4}#d(){let e=this.fen();if(this.inDraft())return this.#o.every(r=>F(r,e).length===0);for(let r of M)if(R(r,e).length>0)return!1;for(let r of this.#o)if(F(r,e).length>0)return!1;return!0}#u(){let e=this.fen();for(let r of M){let n=R(r,e);for(let i of n)if(!U(i))return!0}for(let r of this.#o){let n=F(r,e);for(let i of n)if(!U(i))return!0}return!1}inCheck(e){let r=e??this.turn();return W(r,this.fen())}isCheckmate(){return this.inDraft()||O(this.#t)?!1:this.inCheck()&&!this.#u()}isStalemate(){return this.inDraft()||O(this.#t)?!1:!this.inCheck()&&!this.#u()}isInsufficientMaterial(){if(this.inDraft()||this.#o.some(d=>d.type!==b.marshal))return!1;let e=this.#t.flat().flat().filter(d=>d!==null);if(e.filter(d=>d.type!==b.marshal).length>0)return!1;let n=e.filter(d=>d.type===b.marshal);if(n.length!==2)return!1;let[i,o]=n,[s,a]=i.square.split("-").map(Number),[c,u]=o.square.split("-").map(Number),f=Math.abs(s-c),l=Math.abs(a-u);return!(f<=1&&l<=1)}isDraw(){return this.isStalemate()||this.isFourfoldRepetition()||this.isInsufficientMaterial()}isGameOver(){return this.inDraft()?!1:O(this.#t)||this.isFourfoldRepetition()||this.isInsufficientMaterial()?!0:this.isCheckmate()||this.isStalemate()}load(e){this.#n(e)}loadPgn(e,r=L,n){this.#n(r),this.#e=[],this.#r.clear();let i=ae(e,n);i.moves.forEach((o,s)=>{this.move(o);let a=i.comments.get(s);a&&this.setComment(a)})}move(e){let r=this.moves({verbose:!0}),n=typeof e=="string"?e.replace(/[=#]$/,""):null,i=typeof e=="string"?r.find(o=>o.san===n||o.san===e):r.find(o=>e.piece===o.piece&&e.type===o.type&&e.from===o.from&&e.to===o.to&&e.captured===o.captured&&e.draftFinished===o.draftFinished);if(!i)throw new Error(`Illegal move: ${e}`);return this.#e.push(i),this.#n(i.after,i),this.isCheckmate()?this.#e.at(-1).san+="#":(this.isStalemate()||this.isFourfoldRepetition()||this.isInsufficientMaterial())&&(this.#e.at(-1).san+="="),i}moves(e){if(this.isGameOver())return[];if(e?.square){let r=R(e.square,this.fen());return e.verbose?r:r.map(n=>n.san)}else if(e?.arata){let r=F(e.arata,this.fen());return e.verbose?r:r.map(n=>n.san)}else if(this.inDraft()){let r=this.hand().flatMap(n=>F(n,this.fen()));return e?.verbose?r:r.map(n=>n.san)}else{let r=M.flatMap(o=>R(o,this.fen())),n=this.hand().flatMap(o=>F(o,this.fen())),i=[...r,...n];return e?.verbose?i:i.map(o=>o.san)}}moveNumber(){return this.#a}pgn(e){return se(this.#e,{...e,comments:this.#r})}print(e){console.log(this.ascii(e))}reset(){this.#n(this.#c),this.#e=[],this.#r.clear()}turn(){return this.#s}undo(){let e=this.#e.pop();return e?(this.#n(e.before),e):null}setComment(e){this.#r.set(this.fen(),e)}getComment(){return this.#r.get(this.fen())}removeComment(){let e=this.fen(),r=this.#r.get(e);return this.#r.delete(e),r}getComments(){let e=[];for(let[r,n]of this.#r)e.push({fen:r,comment:n});return e}removeComments(){let e=this.getComments();return this.#r.clear(),e}validateFen(e){return j(e)}};export{L as ADVANCED_POSITION,Ne as ARATA,ve as ARCHER,Ge as BEGINNER_POSITION,Pe as BETRAY,ge as BLACK,Fe as CANNON,Oe as CANONICAL_NAMES,qe as ENGLISH_NAMES,De as FEN_CODES,Ae as FORTRESS,Ee as GENERAL,he as Gungi,He as INTERMEDIATE_POSITION,re as INTRO_POSITION,ke as LANCER,$e as LIEUTENANT_GENERAL,Te as MAJOR_GENERAL,Ce as MARSHAL,Re as MUSKETEER,xe as RIDER,Ie as SOLDIER,Me as SPY,M as SQUARES,Se as TACTICIAN,be as TAKE,ye as TSUKE,we as WARRIOR,me as WHITE,ie as isSquareAttacked,j as validateFen};
8
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/gungi/gungi.ts","../src/gungi/utils.ts","../src/gungi/fen.ts","../src/gungi/move_gen.ts","../src/gungi/pgn.ts","../src/gungi/piece-ids.ts"],"sourcesContent":["import pc from 'picocolors';\nimport type { ParsedFEN } from './fen';\nimport type { PGNOptions } from './pgn';\nimport type { Board, Color, HandPiece, Move, Piece, SetupMode } from './utils';\nimport {\n\tADVANCED_POSITION,\n\tBEGINNER_POSITION,\n\tencodeFEN,\n\tINTERMEDIATE_POSITION,\n\tINTRO_POSITION,\n\tvalidateFen,\n} from './fen';\nimport {\n\tinCheck as checkDetection,\n\tgenerateArata,\n\tgenerateMovesForSquare,\n\tisSquareAttacked,\n\twouldBeInCheckAfterMove,\n} from './move_gen';\nimport { encodePGN, parsePGN } from './pgn';\nimport { assignPieceIdsWithState } from './piece-ids';\nimport {\n\tARATA,\n\tARCHER,\n\tBETRAY,\n\tBLACK,\n\tCANNON,\n\tCANONICAL_NAMES,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tFORTRESS,\n\tGENERAL,\n\tget,\n\tgetTop,\n\tisGameOver,\n\tLANCER,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tMARSHAL,\n\tMUSKETEER,\n\tpiece,\n\tpieceToFenCode,\n\tRIDER,\n\tSOLDIER,\n\tSPY,\n\tSQUARES,\n\tsymbolToName,\n\tTACTICIAN,\n\tTAKE,\n\tTSUKE,\n\tWARRIOR,\n\tWHITE,\n} from './utils';\n\nexport {\n\tWHITE,\n\tBLACK,\n\tMARSHAL,\n\tGENERAL,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tWARRIOR,\n\tLANCER,\n\tRIDER,\n\tSPY,\n\tFORTRESS,\n\tSOLDIER,\n\tCANNON,\n\tARCHER,\n\tMUSKETEER,\n\tTACTICIAN,\n\tTSUKE,\n\tTAKE,\n\tBETRAY,\n\tARATA,\n\tINTRO_POSITION,\n\tBEGINNER_POSITION,\n\tINTERMEDIATE_POSITION,\n\tADVANCED_POSITION,\n\tSQUARES,\n\tCANONICAL_NAMES,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tvalidateFen,\n\tisSquareAttacked,\n};\n\nexport class Gungi {\n\t#board!: Board;\n\t#hand!: HandPiece[];\n\t#turn!: Color;\n\t#moveNumber!: number;\n\t#drafting!: Record<Color, boolean>;\n\t#mode!: SetupMode;\n\n\t#history: Move[] = [];\n\t#previousState: ParsedFEN | null = null;\n\t#comments: Map<string, string> = new Map();\n\n\t#initPosition: string;\n\n\t#initializeState(fen: string, move?: Move | null) {\n\t\t// Assign IDs using the previous state and move info for stability\n\t\tconst stateWithIds = assignPieceIdsWithState(\n\t\t\tfen,\n\t\t\tthis.#previousState,\n\t\t\tmove\n\t\t);\n\n\t\tthis.#board = stateWithIds.board;\n\t\tthis.#hand = stateWithIds.hand;\n\t\tthis.#turn = stateWithIds.turn;\n\t\tthis.#moveNumber = stateWithIds.moveNumber;\n\t\tthis.#drafting = stateWithIds.drafting;\n\t\tthis.#mode = stateWithIds.mode;\n\n\t\t// Update the previous state for next time\n\t\tthis.#previousState = stateWithIds;\n\t}\n\n\tconstructor(fen?: string) {\n\t\tthis.#initPosition = fen ?? INTRO_POSITION;\n\t\tthis.#initializeState(this.#initPosition);\n\t}\n\n\tascii(opts?: { english?: boolean }) {\n\t\tconst tierToColor = {\n\t\t\t1: pc.yellow,\n\t\t\t2: pc.blue,\n\t\t\t3: pc.green,\n\t\t} as const;\n\n\t\tlet s = ` 987654321 \\n`;\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\tfor (let rank = 1; rank <= 9; rank++) {\n\t\t\ts += `|`;\n\t\t\tfor (let file = 9; file > 0; file--) {\n\t\t\t\tconst square = this.getTop(`${rank}-${file}`);\n\t\t\t\tif (!square) {\n\t\t\t\t\ts += '・';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst code = pieceToFenCode[symbolToName[square.type]];\n\t\t\t\tconst en = square.color === 'w' ? code.toUpperCase() : code;\n\n\t\t\t\tconst coloredPiece = tierToColor[square.tier as 1 | 2 | 3](\n\t\t\t\t\topts?.english\n\t\t\t\t\t\t? String.fromCharCode(en.charCodeAt(0) + 0xfee0)\n\t\t\t\t\t\t: square.type\n\t\t\t\t);\n\n\t\t\t\ts += square.color === 'w' ? coloredPiece : pc.dim(coloredPiece);\n\t\t\t}\n\t\t\ts += `|${String.fromCharCode(rank - 1 + '1'.charCodeAt(0))}\\n`;\n\t\t}\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\treturn s;\n\t}\n\n\tboard() {\n\t\treturn this.#board;\n\t}\n\n\tcaptured(color?: Color) {\n\t\tconst allCaptured = this.#history.flatMap((move) => move.captured ?? []);\n\t\tconst capturedCounts = allCaptured.reduce((acc, p) => {\n\t\t\tconst c = acc.find((a) => a.type === p.type && a.color === p.color);\n\t\t\tif (c) {\n\t\t\t\tc.count++;\n\t\t\t} else {\n\t\t\t\tacc.push({ type: p.type, color: p.color, count: 1 });\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, [] as HandPiece[]);\n\n\t\treturn color\n\t\t\t? capturedCounts.filter((p) => p.color === color)\n\t\t\t: capturedCounts;\n\t}\n\n\tclear() {\n\t\tthis.#initializeState(ADVANCED_POSITION);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\t}\n\n\tfen() {\n\t\treturn encodeFEN({\n\t\t\tboard: this.#board,\n\t\t\thand: this.#hand,\n\t\t\tturn: this.#turn,\n\t\t\tmode: this.#mode,\n\t\t\tdrafting: this.#drafting,\n\t\t\tmoveNumber: this.#moveNumber,\n\t\t});\n\t}\n\n\tget(square: string) {\n\t\treturn get(square, this.#board);\n\t}\n\n\tgetDraftingRights(color?: Color) {\n\t\treturn color ? this.#drafting[color] : this.#drafting;\n\t}\n\n\tgetTop(square: string) {\n\t\treturn getTop(square, this.#board);\n\t}\n\n\thand(color?: Color) {\n\t\treturn color\n\t\t\t? this.#hand.filter((piece) => piece.color === color)\n\t\t\t: this.#hand;\n\t}\n\n\thistory(opts?: { verbose?: boolean }) {\n\t\treturn opts?.verbose\n\t\t\t? this.#history\n\t\t\t: this.#history.map((move) => move.san);\n\t}\n\n\tinDraft() {\n\t\treturn this.#drafting.b || this.#drafting.w;\n\t}\n\n\tisFourfoldRepetition() {\n\t\tconst states = this.#history.map((move) => move.before.split(' ')[0]);\n\t\tif (states.length) states.push(this.#history.at(-1)!.after.split(' ')[0]);\n\t\tconst frequencyMap = states.reduce((map, str) => {\n\t\t\tmap.set(str, (map.get(str) || 0) + 1);\n\t\t\treturn map;\n\t\t}, new Map<string, number>());\n\n\t\treturn Math.max(...frequencyMap.values()) === 4;\n\t}\n\n\t#hasNoLegalMoves(): boolean {\n\t\tconst fen = this.fen();\n\t\tif (this.inDraft()) {\n\t\t\treturn this.#hand.every((hp) => generateArata(hp, fen).length === 0);\n\t\t}\n\n\t\tfor (const sq of SQUARES) {\n\t\t\tif (generateMovesForSquare(sq, fen).length > 0) return false;\n\t\t}\n\t\tfor (const hp of this.#hand) {\n\t\t\tif (generateArata(hp, fen).length > 0) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t#hasEscapingMove(): boolean {\n\t\tconst fen = this.fen();\n\n\t\tfor (const sq of SQUARES) {\n\t\t\tconst moves = generateMovesForSquare(sq, fen);\n\t\t\tfor (const move of moves) {\n\t\t\t\tif (!wouldBeInCheckAfterMove(move)) return true;\n\t\t\t}\n\t\t}\n\n\t\tfor (const hp of this.#hand) {\n\t\t\tconst moves = generateArata(hp, fen);\n\t\t\tfor (const move of moves) {\n\t\t\t\tif (!wouldBeInCheckAfterMove(move)) return true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tinCheck(color?: Color): boolean {\n\t\tconst c = color ?? this.turn();\n\t\treturn checkDetection(c, this.fen());\n\t}\n\n\tisCheckmate(): boolean {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return false;\n\t\treturn this.inCheck() && !this.#hasEscapingMove();\n\t}\n\n\tisStalemate(): boolean {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return false;\n\t\treturn !this.inCheck() && !this.#hasEscapingMove();\n\t}\n\n\tisInsufficientMaterial(): boolean {\n\t\tif (this.inDraft()) return false;\n\n\t\tif (this.#hand.some((p) => p.type !== piece.marshal)) return false;\n\n\t\tconst pieces = this.#board\n\t\t\t.flat()\n\t\t\t.flat()\n\t\t\t.filter((p) => p !== null) as Piece[];\n\t\tconst nonMarshals = pieces.filter((p) => p.type !== piece.marshal);\n\t\tif (nonMarshals.length > 0) return false;\n\n\t\tconst marshals = pieces.filter((p) => p.type === piece.marshal);\n\t\tif (marshals.length !== 2) return false;\n\n\t\tconst [m1, m2] = marshals;\n\t\tconst [r1, f1] = m1.square.split('-').map(Number);\n\t\tconst [r2, f2] = m2.square.split('-').map(Number);\n\n\t\tconst rankDiff = Math.abs(r1 - r2);\n\t\tconst fileDiff = Math.abs(f1 - f2);\n\n\t\tconst isAdjacent = rankDiff <= 1 && fileDiff <= 1;\n\n\t\treturn !isAdjacent;\n\t}\n\n\tisDraw(): boolean {\n\t\treturn (\n\t\t\tthis.isStalemate() ||\n\t\t\tthis.isFourfoldRepetition() ||\n\t\t\tthis.isInsufficientMaterial()\n\t\t);\n\t}\n\n\tisGameOver() {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return true; // marshal captured\n\t\tif (this.isFourfoldRepetition()) return true;\n\t\tif (this.isInsufficientMaterial()) return true;\n\t\treturn this.isCheckmate() || this.isStalemate();\n\t}\n\n\tload(fen: string) {\n\t\tthis.#initializeState(fen);\n\t}\n\n\tloadPgn(\n\t\tpgn: string,\n\t\tfen = ADVANCED_POSITION,\n\t\topts?: Pick<PGNOptions, 'newline'>\n\t) {\n\t\tthis.#initializeState(fen);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\n\t\tconst parsed = parsePGN(pgn, opts);\n\t\tparsed.moves.forEach((move, i) => {\n\t\t\tthis.move(move);\n\t\t\tconst comment = parsed.comments.get(i);\n\t\t\tif (comment) {\n\t\t\t\tthis.setComment(comment);\n\t\t\t}\n\t\t});\n\t}\n\n\tmove(move: string | Exclude<Move, 'color' | 'san' | 'before' | 'after'>) {\n\t\tconst moves = this.moves({ verbose: true }) as Move[];\n\t\tconst normalizedInput =\n\t\t\ttypeof move === 'string' ? move.replace(/[=#]$/, '') : null;\n\t\tconst found =\n\t\t\ttypeof move === 'string'\n\t\t\t\t? moves.find((m) => m.san === normalizedInput || m.san === move)\n\t\t\t\t: moves.find(\n\t\t\t\t\t\t(m) =>\n\t\t\t\t\t\t\tmove.piece === m.piece &&\n\t\t\t\t\t\t\tmove.type === m.type &&\n\t\t\t\t\t\t\tmove.from === m.from &&\n\t\t\t\t\t\t\tmove.to === m.to &&\n\t\t\t\t\t\t\tmove.captured === m.captured &&\n\t\t\t\t\t\t\tmove.draftFinished === m.draftFinished\n\t\t\t\t\t);\n\t\tif (!found) throw new Error(`Illegal move: ${move}`);\n\n\t\tthis.#history.push(found);\n\t\tthis.#initializeState(found.after, found);\n\n\t\t// Append game state symbols to SAN\n\t\tif (this.isCheckmate()) {\n\t\t\tthis.#history.at(-1)!.san += '#';\n\t\t} else if (\n\t\t\tthis.isStalemate() ||\n\t\t\tthis.isFourfoldRepetition() ||\n\t\t\tthis.isInsufficientMaterial()\n\t\t) {\n\t\t\tthis.#history.at(-1)!.san += '=';\n\t\t}\n\n\t\treturn found;\n\t}\n\n\tmoves(opts?: { square?: string; arata?: HandPiece; verbose?: boolean }) {\n\t\tif (this.isGameOver()) return [];\n\n\t\tif (opts?.square) {\n\t\t\tconst moves = generateMovesForSquare(opts.square, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (opts?.arata) {\n\t\t\tconst moves = generateArata(opts.arata, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (this.inDraft()) {\n\t\t\tconst moves = this.hand().flatMap((hp) => generateArata(hp, this.fen()));\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t} else {\n\t\t\tconst boardMoves = SQUARES.flatMap((square) =>\n\t\t\t\tgenerateMovesForSquare(square, this.fen())\n\t\t\t);\n\n\t\t\tconst handMoves = this.hand().flatMap((hp) =>\n\t\t\t\tgenerateArata(hp, this.fen())\n\t\t\t);\n\n\t\t\tconst moves = [...boardMoves, ...handMoves];\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t}\n\t}\n\n\tmoveNumber() {\n\t\treturn this.#moveNumber;\n\t}\n\n\tpgn(opts?: PGNOptions) {\n\t\treturn encodePGN(this.#history, { ...opts, comments: this.#comments });\n\t}\n\n\tprint(opts?: { english?: boolean }) {\n\t\tconsole.log(this.ascii(opts));\n\t}\n\n\treset() {\n\t\tthis.#initializeState(this.#initPosition);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\t}\n\n\tturn() {\n\t\treturn this.#turn;\n\t}\n\n\tundo() {\n\t\tconst lastMove = this.#history.pop();\n\t\tif (lastMove) {\n\t\t\tthis.#initializeState(lastMove.before);\n\t\t\treturn lastMove;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tsetComment(comment: string) {\n\t\tthis.#comments.set(this.fen(), comment);\n\t}\n\n\tgetComment() {\n\t\treturn this.#comments.get(this.fen());\n\t}\n\n\tremoveComment() {\n\t\tconst fen = this.fen();\n\t\tconst comment = this.#comments.get(fen);\n\t\tthis.#comments.delete(fen);\n\t\treturn comment;\n\t}\n\n\tgetComments() {\n\t\tconst result: { fen: string; comment: string }[] = [];\n\t\tfor (const [fen, comment] of this.#comments) {\n\t\t\tresult.push({ fen, comment });\n\t\t}\n\t\treturn result;\n\t}\n\n\tremoveComments() {\n\t\tconst comments = this.getComments();\n\t\tthis.#comments.clear();\n\t\treturn comments;\n\t}\n\n\tvalidateFen(fen: string) {\n\t\treturn validateFen(fen);\n\t}\n}\n","const inverseMap = <T extends Record<string, string | number | symbol>>(\n\tmap: T\n): Record<T[keyof T], keyof T> =>\n\tObject.entries(map).reduce(\n\t\t(acc, [key, value]) => ({ ...acc, [value]: key }),\n\t\t{} as Record<T[keyof T], keyof T>\n\t);\n\nexport type Board = (Piece | null)[][][];\nexport type Piece = {\n\tsquare: string;\n\ttier: number;\n\ttype: PieceType;\n\tcolor: Color;\n\tid?: string;\n};\nexport type HandPiece = {\n\ttype: PieceType;\n\tcolor: Color;\n\tcount: number;\n\tid?: string;\n};\n\nexport type Move = {\n\tcolor: Color;\n\tpiece: PieceType;\n\tfrom?: string;\n\tto: string;\n\tsan: string;\n\tbefore: string;\n\tafter: string;\n\ttype: 'route' | 'capture' | 'tsuke' | 'betray' | 'arata';\n\tdraftFinished?: boolean;\n\tcaptured?: Piece[];\n};\n\nexport type SetupMode = 'intro' | 'beginner' | 'intermediate' | 'advanced';\nexport const setupModeToCode: Record<SetupMode, number> = {\n\tintro: 0,\n\tbeginner: 1,\n\tintermediate: 2,\n\tadvanced: 3,\n};\nexport const setupCodeToMode = inverseMap(setupModeToCode);\n\nexport const WHITE = 'w';\nexport const BLACK = 'b';\n\nexport const TSUKE = '付';\nexport const TAKE = '取';\nexport const BETRAY = '返';\nexport const ARATA = '新';\n\nexport const MARSHAL = '帥';\nexport const GENERAL = '大';\nexport const LIEUTENANT_GENERAL = '中';\nexport const MAJOR_GENERAL = '小';\nexport const WARRIOR = '侍';\nexport const LANCER = '槍';\nexport const RIDER = '馬';\nexport const SPY = '忍';\nexport const FORTRESS = '砦';\nexport const SOLDIER = '兵';\nexport const CANNON = '砲';\nexport const ARCHER = '弓';\nexport const MUSKETEER = '筒';\nexport const TACTICIAN = '謀';\n\nexport const SQUARES = Array.from({ length: 9 }, (_, x) => x + 1).flatMap((x) =>\n\tArray.from({ length: 9 }, (_, y) => `${x}-${9 - y}`)\n);\n\nexport type Color = 'b' | 'w';\nexport type PieceType =\n\t| '帥'\n\t| '大'\n\t| '中'\n\t| '小'\n\t| '侍'\n\t| '槍'\n\t| '馬'\n\t| '忍'\n\t| '砦'\n\t| '兵'\n\t| '砲'\n\t| '弓'\n\t| '筒'\n\t| '謀';\n\nexport type PieceCode =\n\t| 'm'\n\t| 'g'\n\t| 'i'\n\t| 'j'\n\t| 'w'\n\t| 'n'\n\t| 'r'\n\t| 's'\n\t| 'f'\n\t| 'd'\n\t| 'c'\n\t| 'a'\n\t| 'k'\n\t| 't';\n\nexport type Name =\n\t| 'marshal'\n\t| 'general'\n\t| 'lieutenant_general'\n\t| 'major_general'\n\t| 'warrior'\n\t| 'lancer'\n\t| 'rider'\n\t| 'spy'\n\t| 'fortress'\n\t| 'soldier'\n\t| 'cannon'\n\t| 'archer'\n\t| 'musketeer'\n\t| 'tactician';\n\nexport const piece: Record<Name, PieceType> = {\n\tmarshal: '帥',\n\tgeneral: '大',\n\tlieutenant_general: '中',\n\tmajor_general: '小',\n\twarrior: '侍',\n\tlancer: '槍',\n\trider: '馬',\n\tspy: '忍',\n\tfortress: '砦',\n\tsoldier: '兵',\n\tcannon: '砲',\n\tarcher: '弓',\n\tmusketeer: '筒',\n\ttactician: '謀',\n};\n\nexport const symbolToName = inverseMap(piece);\n\nexport const pieceToFenCode: Record<Name, PieceCode> = {\n\tmarshal: 'm',\n\tgeneral: 'g',\n\tlieutenant_general: 'i',\n\tmajor_general: 'j',\n\twarrior: 'w',\n\tlancer: 'n',\n\trider: 'r',\n\tspy: 's',\n\tfortress: 'f',\n\tsoldier: 'd',\n\tcannon: 'c',\n\tarcher: 'a',\n\tmusketeer: 'k',\n\ttactician: 't',\n};\n\nexport const fenCodeToPiece = inverseMap(pieceToFenCode);\n\nexport const createPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\t[y, x, z]: [number, number, number]\n): Piece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\tsquare: `${y}-${x}`,\n\t\ttier: z,\n\t\ttype: piece[name],\n\t\tcolor,\n\t};\n};\n\nexport const createHandPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\tcount: number\n): HandPiece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\ttype: piece[name],\n\t\tcount,\n\t\tcolor,\n\t};\n};\n\nexport const CANONICAL_NAMES: Record<PieceType, string> = {\n\t帥: 'sui',\n\t大: 'taishou',\n\t中: 'chuujou',\n\t小: 'shoushou',\n\t侍: 'samurai',\n\t槍: 'yari',\n\t馬: 'kiba',\n\t忍: 'shinobi',\n\t砦: 'toride',\n\t兵: 'hyou',\n\t砲: 'oodzutsu',\n\t弓: 'yumi',\n\t筒: 'tsutsu',\n\t謀: 'boushou',\n};\n\nexport const ENGLISH_NAMES: Record<PieceType, string> = {\n\t帥: 'marshal',\n\t大: 'general',\n\t中: 'lieutenant general',\n\t小: 'major general',\n\t侍: 'warrior',\n\t槍: 'lancer',\n\t馬: 'rider',\n\t忍: 'spy',\n\t砦: 'fortress',\n\t兵: 'soldier',\n\t砲: 'cannon',\n\t弓: 'archer',\n\t筒: 'musketeer',\n\t謀: 'tactician',\n};\n\nexport const FEN_CODES: Record<PieceType, string> = {\n\t帥: 'm',\n\t大: 'g',\n\t中: 'i',\n\t小: 'j',\n\t侍: 'w',\n\t槍: 'n',\n\t馬: 'r',\n\t忍: 's',\n\t砦: 'f',\n\t兵: 'd',\n\t砲: 'c',\n\t弓: 'a',\n\t筒: 'k',\n\t謀: 't',\n};\n\nexport function updateHand(\n\tpieces: Piece[],\n\thand: HandPiece[],\n\toppositeColor = false\n): HandPiece[] {\n\tpieces.forEach((p) => {\n\t\tconst c = oppositeColor ? (p.color === 'b' ? 'w' : 'b') : p.color;\n\t\tconst hp = hand.find((h) => h.type === p.type && h.color === c);\n\t\tconst hpi = hand.findIndex((h) => h.type === p.type && h.color === c);\n\n\t\tif (hp) {\n\t\t\thp.count--;\n\t\t\tif (hp.count === 0) hand.splice(hpi, 1);\n\t\t}\n\t});\n\n\treturn hand;\n}\n\nexport function convert(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tboard[rank - 1][9 - file] = tower.map((piece) => {\n\t\tconst p = pieces.find((p) => JSON.stringify(p) === JSON.stringify(piece));\n\t\tif (p) {\n\t\t\tpiece.color = piece.color === 'b' ? 'w' : 'b';\n\t\t}\n\t\treturn piece;\n\t});\n}\n\nexport function remove(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tconst newTower = tower.filter(\n\t\t(piece) => !pieces.some((p) => JSON.stringify(p) === JSON.stringify(piece))\n\t);\n\n\tif (newTower.length === 0) board[rank - 1][9 - file] = [null];\n\telse board[rank - 1][9 - file] = newTower;\n}\n\nexport function removeTop(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\ttower.pop();\n\tif (tower.length === 0) board[rank - 1][9 - file] = [null];\n}\n\nexport function put(piece: Piece, board: (Piece | null)[][][]) {\n\tconst [rank, file] = piece.square.split('-').map(Number);\n\tconst occupied = board[rank - 1][9 - file];\n\n\tif (!occupied[0]) board[rank - 1][9 - file] = [piece];\n\telse board[rank - 1][9 - file].push(piece);\n}\n\nexport function getTop(square: string, board: (Piece | null)[][][]) {\n\tconst tower = get(square, board);\n\treturn tower ? tower.at(-1)! : undefined;\n}\n\nexport function get(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return undefined;\n\n\tconst s = board[rank - 1][9 - file];\n\tif (!s[0]) return undefined;\n\n\treturn s as Piece[];\n}\n\nexport function isGameOver(board: (Piece | null)[][][]) {\n\tconst marshal = board\n\t\t.flat()\n\t\t.flat()\n\t\t.filter((p) => p?.type === '帥');\n\treturn marshal.length !== 2;\n}\n","// Forsyth–Edwards Notation (FEN) Parser and Serializer for Gungi games.\n// Read more about FEN for chess: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation\n//\n// Gungi FEN will have\n// 1. Piece placement data:\n// Each rank is described, starting with rank 1 and ending with rank 9, with a '/' between each one; within each rank,\n// the contents of the squares are described from file 9 to file 1; within each square the tower is described\n// from bottom to top (towers of 2 or higher are surrounded with a '|' with ':' in between pices).\n// Each pieces is represented by a single character from the standard English names\n//\n// 帥 marshal = m\n// 大 general = g\n// 中 lieutenant_general = i\n// 小 major_general = j\n// 侍 warrior = w\n// 槍 lancer = n\n// 馬 rider = r\n// 忍 spy = s\n// 砦 fortress = f\n// 兵 soldier = d\n// 砲 cannon = c\n// 弓 archer = a\n// 筒 musketeer = k\n// 謀 tactician = t\n//\n// Black pieces are designated using lowercase (\"mgijwnrsfdcakt\"),\n// while white pieces use uppercase (\"MGIJWNRSFDCAKT\")\n//\n// A set of one or more consecutive empty squares within a rank is denoted by a digit from \"1\" to \"9\", corresponding to the number of squares.\n// 2: Hand piece data:\n// Each piece in hand is represented by a single character (see above) followed by the number of that piece in hand (1-9);\n// white's hand piecs come first followed by black's separated by a '/'. if a player has no pieces in hand, it's represented with the character '-'\n// 3: Active player:\n// \"w\" means that White is to move; \"b\" means that Black is to move.\n// 4: Setup mode:\n// \"0\" means intro placement, \"1\" for Beginner, \"2\" for Intermediate, \"3\" for Advanced\n// 5: Drafting availability:\n// If neither side has the ability to draft, this field uses the character \"-\". Otherwise, this field contains one or more letters: \"w\" if White can draft and 'b' if Black can draft\n// 6: Full move number:\n// The number of the full moves. It starts at 1 and is incremented after Black's move.\n//\n// Examples\n//\n// FEN for the starting position of a beginner game of gungi:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1\"\n// and after the move 1.大(6-9-1)(5-8-2)付:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 b 1 - 1\"\n// and then after 1...槍(5-2-1)(4-3-2)付:\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 2\"\n// and then after 2.新忍(3-8-2)付\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1|A:S|R1/4MI3 J2N2R1D1/j2n2s1r1d1 b 1 - 2\"\n\nimport {\n\tBoard,\n\tColor,\n\tcreateHandPieceFromFenCode,\n\tcreatePieceFromFenCode,\n\tHandPiece,\n\tPiece,\n\tPieceCode,\n\tpieceToFenCode,\n\tsetupCodeToMode,\n\tSetupMode,\n\tsetupModeToCode,\n\tsymbolToName,\n} from './utils';\n\nexport const INTRO_POSITION =\n\t'3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1';\nexport const BEGINNER_POSITION =\n\t'3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1';\nexport const INTERMEDIATE_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1';\nexport const ADVANCED_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1';\n\nexport type ParsedFEN = {\n\tboard: Board;\n\thand: HandPiece[];\n\tturn: Color;\n\tmode: SetupMode;\n\tdrafting: Record<Color, boolean>;\n\tmoveNumber: number;\n};\n\nexport function parseFEN(fen: string): ParsedFEN {\n\tconst result = validateFen(fen);\n\tif (!result.ok) throw new Error(`Invalid FEN: ${result.error}`);\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] =\n\t\tfen.split(' ');\n\n\tconst board = placement.split('/').map((rank, y) => {\n\t\treturn rank.split('|').reduce(\n\t\t\t(outeracc, partial) => {\n\t\t\t\tif (partial.includes(':')) {\n\t\t\t\t\tconst tower = partial.split(':').map((piece, z) => {\n\t\t\t\t\t\treturn createPieceFromFenCode(\n\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length, z + 1]\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\touteracc.push(tower);\n\t\t\t\t} else {\n\t\t\t\t\tconst partialPieces = partial\n\t\t\t\t\t\t.split('')\n\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t(acc, piece) => {\n\t\t\t\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\t\t\t\tacc = acc.concat(Array(+piece).fill(null));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tacc.push(\n\t\t\t\t\t\t\t\t\t\tcreatePieceFromFenCode(\n\t\t\t\t\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length - acc.length, 1]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t[] as (Piece | null)[]\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.map((square) => [square]);\n\t\t\t\t\touteracc = outeracc.concat(partialPieces);\n\t\t\t\t}\n\n\t\t\t\treturn outeracc;\n\t\t\t},\n\t\t\t[] as (Piece | null)[][]\n\t\t);\n\t});\n\n\tconst hand = handpieces.split('/').flatMap((playerHand) => {\n\t\tconst pieces: HandPiece[] = [];\n\t\tif (playerHand !== '-') {\n\t\t\tfor (let i = 0; i < playerHand.length; i += 2) {\n\t\t\t\tconst piece = playerHand[i] as PieceCode | Uppercase<PieceCode>;\n\t\t\t\tconst count = +playerHand[i + 1];\n\t\t\t\tpieces.push(createHandPieceFromFenCode(piece, count));\n\t\t\t}\n\t\t}\n\t\treturn pieces;\n\t});\n\n\treturn {\n\t\tboard,\n\t\thand,\n\t\tturn: turn as Color,\n\t\tmode: setupCodeToMode[+mode],\n\t\tdrafting: {\n\t\t\tw: drafting.includes('w'),\n\t\t\tb: drafting.includes('b'),\n\t\t},\n\t\tmoveNumber: +moveNumber,\n\t};\n}\n\nexport function encodeFEN(fen: ParsedFEN) {\n\tlet placement = '';\n\tlet emptyCount = 0;\n\n\tfor (let file = 0; file < 9; file++) {\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tconst square = fen.board[file][rank];\n\t\t\tif (!square[0]) {\n\t\t\t\temptyCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (emptyCount) {\n\t\t\t\tplacement += emptyCount;\n\t\t\t\temptyCount = 0;\n\t\t\t}\n\n\t\t\tif (square.length > 1) {\n\t\t\t\tplacement +=\n\t\t\t\t\t'|' +\n\t\t\t\t\tsquare\n\t\t\t\t\t\t.map((p) => {\n\t\t\t\t\t\t\tif (!p) return null;\n\t\t\t\t\t\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\t\t\t\t\t\treturn p.color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(':') +\n\t\t\t\t\t'|';\n\t\t\t} else {\n\t\t\t\tconst { type, color } = square[0];\n\t\t\t\tconst piece = pieceToFenCode[symbolToName[type]];\n\t\t\t\tplacement += color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t}\n\t\t}\n\n\t\tplacement += emptyCount ? `${emptyCount}/` : '/';\n\t\temptyCount = 0;\n\t}\n\n\tlet hand = '';\n\tconst whiteHand = fen.hand.filter((p) => p.color === 'w');\n\tconst blackHand = fen.hand.filter((p) => p.color === 'b');\n\twhiteHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += whiteHand.length > 0 ? '/' : '-/';\n\tblackHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += blackHand.length > 0 ? '' : '-';\n\n\tconst draftKeys = Object.keys(fen.drafting).filter(\n\t\t(key) => fen.drafting[key as Color]\n\t);\n\n\treturn `${placement.slice(0, -1)} ${hand} ${fen.turn} ${setupModeToCode[fen.mode]} ${draftKeys.length > 0 ? draftKeys.join('') : '-'} ${fen.moveNumber}`;\n}\n\ntype FenValidationResult = {\n\tok: boolean;\n\terror?: string;\n};\n\nexport function validateFen(fen: string): FenValidationResult {\n\tconst parts = fen.split(' ');\n\tif (parts.length !== 6)\n\t\treturn { ok: false, error: `expected 6 fields, received ${parts.length}` };\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] = parts;\n\tconst ranks = placement.split('/');\n\tif (ranks.length !== 9)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `1st field (piece positions) is invalid [expected 9 ranks, received ${ranks.length}]`,\n\t\t};\n\n\tfor (let i = 0; i < ranks.length; i++) {\n\t\tconst rank = ranks[i];\n\t\tconst fileParts = rank.split('|');\n\t\tlet fileCount = 0;\n\n\t\tfor (let k = 0; k < fileParts.length; k++) {\n\t\t\tconst filePart = fileParts[k];\n\t\t\tif (filePart.includes(':')) {\n\t\t\t\tfileCount++;\n\t\t\t\tconst towerPieces = filePart.split(':');\n\t\t\t\tif (towerPieces.length > 3) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [tower size] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!towerPieces.every((p) => 'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(p))\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst pieces = filePart.split('');\n\n\t\t\t\tfor (let l = 0; l < pieces.length; l++) {\n\t\t\t\t\tconst piece = pieces[l];\n\n\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\tfileCount += +piece;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfileCount++;\n\t\t\t\t\t\tif (!'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(piece)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (fileCount !== 9) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `1st field (piece positions) is invalid [expected 9 squares, received ${fileCount}] in rank: ${i + 1}`,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst hands = handpieces.split('/');\n\tif (hands.length !== 2)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [expected 2 hands, received ${hands.length}]`,\n\t\t};\n\n\tconst [whiteHand, blackHand] = hands;\n\tif (\n\t\t(whiteHand.length === 1 && whiteHand !== '-') ||\n\t\t(blackHand.length === 1 && blackHand !== '-')\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t};\n\t}\n\n\tif (\n\t\t(whiteHand.length > 1 && whiteHand.length % 2 !== 0) ||\n\t\t(blackHand.length > 1 && blackHand.length % 2 !== 0)\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece count]`,\n\t\t};\n\t}\n\n\tif (whiteHand.length > 1) {\n\t\tfor (let i = 0; i < whiteHand.length; i += 2) {\n\t\t\tif (!'MGIJWNRSFDCAKT'.includes(whiteHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+whiteHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (blackHand.length > 1) {\n\t\tfor (let i = 0; i < blackHand.length; i += 2) {\n\t\t\tif (!'mgijwnrsfdcakt'.includes(blackHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+blackHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (turn !== 'w' && turn !== 'b') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `3rd field (active player) is invalid [expected 'w' or 'b', received ${turn}]`,\n\t\t};\n\t}\n\n\tif (mode.length !== 1 || !'0123'.includes(mode)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${mode}]`,\n\t\t};\n\t}\n\n\tif (drafting !== '-' && !'wb'.includes(drafting)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${drafting}]`,\n\t\t};\n\t}\n\n\tif (!Number.isInteger(+moveNumber)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `6th field (full move number) is invalid [expected an integer, received ${moveNumber}]`,\n\t\t};\n\t}\n\n\treturn { ok: true };\n}\n","import { encodeFEN, parseFEN } from './fen';\nimport {\n\tBoard,\n\tColor,\n\tconvert,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tpiece as pieceType,\n\tput,\n\tremove,\n\tremoveTop,\n\tSQUARES,\n\tupdateHand,\n} from './utils';\n\nexport const dirs = [\n\t[-1, 1],\n\t[-1, 0],\n\t[-1, -1],\n\t[0, 1],\n\t[0, -1],\n\t[1, 1],\n\t[1, 0],\n\t[1, -1],\n];\n\nexport const pieceProbes: Record<PieceType, (number[] | number)[]> = {\n\t帥: [1, 1, 1, 1, 1, 1, 1, 1],\n\t大: [1, Infinity, 1, Infinity, Infinity, 1, Infinity, 1],\n\t中: [Infinity, 1, Infinity, 1, 1, Infinity, 1, Infinity],\n\t小: [1, 1, 1, 1, 1, 0, 1, 0],\n\t侍: [1, 1, 1, 0, 0, 0, 1, 0],\n\t槍: [1, [1, 2], 1, 0, 0, 0, 1, 0],\n\t馬: [0, [1, 2], 0, 1, 1, 0, [1, 2], 0],\n\t忍: [[1, 2], 0, [1, 2], 0, 0, [1, 2], 0, [1, 2]],\n\t砦: [0, 1, 0, 1, 1, 1, 0, 1],\n\t兵: [0, 1, 0, 0, 0, 0, 1, 0],\n\t砲: [0, 3, 0, 1, 1, 0, 1, 0],\n\t弓: [2, 2, 2, 0, 0, 0, 1, 0],\n\t筒: [0, 2, 0, 0, 0, 1, 0, 1],\n\t謀: [1, 0, 1, 0, 0, 0, 1, 0],\n};\n\nfunction getAvailableSquares(\n\tdir: [number, number],\n\tstart: [number, number],\n\torigin: [number, number],\n\tlength: number,\n\tboard: (Piece | null)[][][]\n) {\n\tconst [y, x] = start;\n\tconst [py, px] = origin;\n\tconst [dy, dx] = dir;\n\tconst originPiece = getTop(`${py}-${px}`, board)!;\n\n\tconst availableSquares: string[] = [];\n\n\t// first probe in the reverse direction until origin is reached to see if there are any pieces in the way\n\tconst reverse = { x, y };\n\twhile (reverse.x !== px || reverse.y !== py) {\n\t\treverse.x -= dx;\n\t\treverse.y -= dy;\n\t\tconst piece = getTop(`${reverse.y}-${reverse.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst side = originPiece.color === 'b' ? -1 : 1;\n\t\tconst below = getTop(`${reverse.y + side}-${reverse.x}`, board);\n\n\t\tif (below && below.square === `${py}-${px}`) break;\n\t}\n\n\t// then probe in the forward direction to see if there are any pieces in the way\n\tconst forward = { x, y };\n\tlet step = 0;\n\twhile (step < length) {\n\t\tif (forward.x < 1 || forward.x > 9 || forward.y < 1 || forward.y > 9) break;\n\n\t\tconst piece = getTop(`${forward.y}-${forward.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) break;\n\n\t\tavailableSquares.push(`${forward.y}-${forward.x}`);\n\n\t\tconst leapPieces = [\n\t\t\tpieceType.cannon,\n\t\t\tpieceType.musketeer,\n\t\t\tpieceType.archer,\n\t\t];\n\t\tif (piece && !leapPieces.includes(originPiece.type)) break;\n\n\t\tforward.x += dx;\n\t\tforward.y += dy;\n\t\tstep++;\n\t}\n\n\treturn availableSquares;\n}\n\nexport function generateMovesForSquare(square: string, fen: string) {\n\tconst { board, turn, mode, hand } = parseFEN(fen);\n\tconst piece = getTop(square, board);\n\tif (!piece || turn !== piece.color) return [];\n\n\tconst [py, px] = square.split('-').map(Number);\n\n\tconst probes = pieceProbes[piece.type];\n\tconst squares = probes.flatMap((probe, i) => {\n\t\tconst pval = typeof probe === 'number' ? probe : probe[0];\n\t\tconst pcarry = typeof probe === 'number' ? 1 : probe[1];\n\t\tif (pval < 1) return [];\n\n\t\tlet [dy, dx] = dirs[i];\n\t\tif (piece.color === 'b') {\n\t\t\tdy *= -1;\n\t\t\tdx *= -1;\n\t\t}\n\n\t\tconst [y, x] =\n\t\t\tpval === Infinity ? [py + dy, px + dx] : [py + pval * dy, px + dx];\n\t\tconst length = pval === Infinity ? Infinity : piece.tier + pcarry - 1;\n\n\t\treturn getAvailableSquares([dy, dx], [y, x], [py, px], length, board);\n\t});\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst t = get(s, board);\n\n\t\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\t\tconst marshalCanStack = ['advanced', 'intermediate'].includes(mode);\n\n\t\tif (!p || !t) {\n\t\t\tacc.push(createMove(piece, `${s}-1`, fen, 'route'));\n\t\t} else {\n\t\t\t// tsuke\n\t\t\tif (p.tier < maxTier && p.type !== pieceType.marshal) {\n\t\t\t\tif (piece.type !== pieceType.marshal || marshalCanStack) {\n\t\t\t\t\tacc.push(createMove(piece, `${s}-${p.tier + 1}`, fen, 'tsuke'));\n\t\t\t\t}\n\n\t\t\t\t// betrayal\n\t\t\t\tif (piece.type === pieceType.tactician && p.color !== piece.color) {\n\t\t\t\t\tconst enemies = t.filter((p) => p.color !== piece.color);\n\t\t\t\t\tconst playerHand = hand.filter((p) => p.color === piece.color);\n\t\t\t\t\tconst enemyCountMap = enemies.reduce((acc, e) => {\n\t\t\t\t\t\tacc.set(e.type, (acc.get(e.type) ?? 0) + 1);\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, new Map<PieceType, number>());\n\n\t\t\t\t\tconst betrayalOptions = Array.from(enemyCountMap.entries())\n\t\t\t\t\t\t.filter(([type, count]) =>\n\t\t\t\t\t\t\tplayerHand.some((p) => p.type === type && p.count >= count)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.flatMap(([type]) => enemies.filter((e) => e.type === type));\n\n\t\t\t\t\tconst combos = generateCombinations(betrayalOptions);\n\t\t\t\t\tacc.push(\n\t\t\t\t\t\t...combos.map((combo) =>\n\t\t\t\t\t\t\tcreateMove(piece, `${s}-${p.tier + 1}`, fen, 'betray', combo)\n\t\t\t\t\t\t)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// capture\n\t\t\tif (p.color !== piece.color) {\n\t\t\t\tconst newTier = t.filter((p) => p.color === piece.color).length + 1;\n\t\t\t\tconst captured = t.filter((p) => p.color !== piece.color);\n\t\t\t\tacc.push(\n\t\t\t\t\tcreateMove(piece, `${s}-${newTier}`, fen, 'capture', captured)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nexport function generateArata(piece: HandPiece, fen: string) {\n\tconst { board, turn, mode, hand, drafting } = parseFEN(fen);\n\tif (!piece || turn !== piece.color) return [];\n\tconst isMarshalPlaced = !hand.some(\n\t\t(p) => p.type === pieceType.marshal && p.color === piece.color\n\t);\n\tif (!isMarshalPlaced && piece.type !== pieceType.marshal) return [];\n\n\tconst isDraft = drafting.b || drafting.w;\n\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\tlet ranks: number[] = [];\n\tlet maybe: number[] = [];\n\n\t// if in draft can only place within your first 3 ranks, otherwise can placed as far as your deepest piece\n\tif (isDraft) {\n\t\tranks = piece.color === 'w' ? [7, 8, 9] : [1, 2, 3];\n\t} else {\n\t\tconst start = piece.color === 'b' ? 1 : 9;\n\t\tconst end = piece.color === 'b' ? 9 : 1;\n\t\tconst step = piece.color === 'b' ? 1 : -1;\n\t\tfor (\n\t\t\tlet rank = start;\n\t\t\tpiece.color === 'b' ? rank <= end : rank >= end;\n\t\t\trank += step\n\t\t) {\n\t\t\tconst tops = Array.from({ length: 9 }).map((_, i) =>\n\t\t\t\tgetTop(`${rank}-${i + 1}`, board)\n\t\t\t);\n\t\t\tif (tops.some((p) => p && p.color === piece.color)) {\n\t\t\t\tranks.push(...maybe, rank);\n\t\t\t\tmaybe = [];\n\t\t\t} else {\n\t\t\t\tmaybe.push(rank);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst squares = ranks.flatMap((rank) =>\n\t\tArray.from({ length: 9 }, (_, i) => `${rank}-${i + 1}`)\n\t);\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst arata = {\n\t\t\ttype: piece.type,\n\t\t\tcolor: piece.color,\n\t\t\tsquare: s,\n\t\t\ttier: 0,\n\t\t};\n\n\t\t// you can arata an empty square or a tower with your own piece on top\n\t\tif (\n\t\t\t!p ||\n\t\t\t(p.color === arata.color &&\n\t\t\t\tp.tier < maxTier &&\n\t\t\t\tp.type !== pieceType.marshal)\n\t\t) {\n\t\t\tconst t = (p?.tier ?? 0) + 1;\n\t\t\tconst playerHandCount = hand\n\t\t\t\t.filter((h) => h.color === piece.color)\n\t\t\t\t.reduce((sum, h) => sum + h.count, 0);\n\t\t\tconst isLastPiece = playerHandCount === 1;\n\n\t\t\tif (drafting[piece.color]) {\n\t\t\t\t// If only 1 piece left, must end draft - no option to continue\n\t\t\t\tif (!isLastPiece) {\n\t\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\t\t}\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata', [], true));\n\t\t\t} else {\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nfunction createMove(\n\tpiece: Piece,\n\tto: string,\n\tfen: string,\n\ttype: Move['type'],\n\tcaptured?: Piece[],\n\tdraftFinished?: boolean\n) {\n\tconst from = piece.tier !== 0 ? `(${piece.square}-${piece.tier})` : '';\n\tconst toTier = +(to.split('-').at(-1) ?? 0);\n\tconst arata = type === 'arata' ? '新' : '';\n\tconst capture = type === 'capture' ? '取' : '';\n\tconst tsuke =\n\t\ttype === 'tsuke' || (toTier !== 1 && toTier - piece.tier > 0) ? '付' : '';\n\tconst betray =\n\t\ttype === 'betray' ? `返${captured?.map((p) => p.type).join('')}` : '';\n\tconst draftDone = draftFinished ? '終' : '';\n\n\tconst move: Move = {\n\t\tpiece: piece.type,\n\t\tcolor: piece.color,\n\t\tfrom: from.slice(1, -1),\n\t\tto,\n\t\ttype,\n\t\tsan: `${arata}${piece.type}${from}${capture}(${to})${betray || tsuke}${draftDone}`,\n\t\tbefore: fen,\n\t\tafter: '',\n\t\tdraftFinished,\n\t\tcaptured,\n\t};\n\n\tconst { after, gameOverSAN } = makeMove(move, move.before);\n\tmove.after = after;\n\tmove.san += gameOverSAN;\n\n\treturn move;\n}\n\nfunction makeMove(move: Move, fen: string) {\n\tlet { board, hand, mode, turn, drafting, moveNumber } = parseFEN(fen);\n\tconst [rank, file, tier] = move.to.split('-');\n\tconst to = {\n\t\ttype: move.piece,\n\t\tcolor: move.color,\n\t\tsquare: `${rank}-${file}`,\n\t\ttier: +tier,\n\t};\n\n\tif (move.type === 'route' || move.type === 'tsuke') {\n\t\tremoveTop(move.from!, board);\n\t} else if (move.type === 'capture') {\n\t\tremoveTop(move.from!, board);\n\t\tremove(`${rank}-${file}`, move.captured!, board);\n\t} else if (move.type === 'betray') {\n\t\tremoveTop(move.from!, board);\n\t\tconvert(`${rank}-${file}`, move.captured!, board);\n\t\tupdateHand(move.captured!, hand, true);\n\t} else if (move.type === 'arata') {\n\t\tupdateHand([to], hand);\n\t\tif (move.draftFinished) drafting[move.color] = false;\n\t}\n\n\tput(to, board);\n\n\tif (turn === 'b' && (drafting.w || !drafting.b)) moveNumber++;\n\tif (turn === 'w' && !drafting.b && !drafting.w && move.draftFinished)\n\t\tmoveNumber++;\n\n\tif (drafting.w === drafting.b) {\n\t\tif (!move.draftFinished || turn !== 'w') {\n\t\t\tturn = turn === 'b' ? 'w' : 'b';\n\t\t}\n\t} else {\n\t\tif (!drafting.b && turn === 'b') {\n\t\t\tturn = 'w';\n\t\t} else if (!drafting.w && turn === 'w') {\n\t\t\tturn = 'b';\n\t\t}\n\t}\n\n\tlet gameOverSAN = '';\n\tif (move.captured?.some((p) => p.type === pieceType.marshal))\n\t\tgameOverSAN = '#';\n\n\treturn {\n\t\tafter: encodeFEN({ board, hand, mode, turn, drafting, moveNumber }),\n\t\tgameOverSAN,\n\t};\n}\n\nfunction generateCombinations<T>(items: T[]): T[][] {\n\tconst result: T[][] = [];\n\n\tfunction helper(start: number, currentCombination: T[]) {\n\t\tif (currentCombination.length > 0) {\n\t\t\tresult.push([...currentCombination]);\n\t\t}\n\n\t\tfor (let i = start; i < items.length; i++) {\n\t\t\tcurrentCombination.push(items[i]);\n\t\t\thelper(i + 1, currentCombination);\n\t\t\tcurrentCombination.pop(); // Backtrack\n\t\t}\n\t}\n\n\thelper(0, []);\n\n\treturn result;\n}\n\nfunction getAttackedSquares(square: string, board: Board): string[] {\n\tconst piece = getTop(square, board);\n\tif (!piece) return [];\n\n\tconst [py, px] = square.split('-').map(Number);\n\tconst probes = pieceProbes[piece.type];\n\n\treturn probes.flatMap((probe, i) => {\n\t\tconst pval = typeof probe === 'number' ? probe : probe[0];\n\t\tconst pcarry = typeof probe === 'number' ? 1 : probe[1];\n\t\tif (pval < 1) return [];\n\n\t\tlet [dy, dx] = dirs[i];\n\t\tif (piece.color === 'b') {\n\t\t\tdy *= -1;\n\t\t\tdx *= -1;\n\t\t}\n\n\t\tconst [y, x] =\n\t\t\tpval === Infinity ? [py + dy, px + dx] : [py + pval * dy, px + dx];\n\t\tconst length = pval === Infinity ? Infinity : piece.tier + pcarry - 1;\n\n\t\treturn getAvailableSquares([dy, dx], [y, x], [py, px], length, board);\n\t});\n}\n\nexport function isSquareAttacked(\n\tsquare: string,\n\tbyColor: Color,\n\tboard: Board\n): boolean {\n\tconst [targetRank, targetFile] = square.split('-').map(Number);\n\tconst targetSquare = `${targetRank}-${targetFile}`;\n\n\tfor (const sq of SQUARES) {\n\t\tconst piece = getTop(sq, board);\n\t\tif (!piece || piece.color !== byColor) continue;\n\n\t\tconst attackedSquares = getAttackedSquares(sq, board);\n\t\tif (attackedSquares.some((s) => s.startsWith(targetSquare))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function inCheck(color: Color, fen: string): boolean {\n\tconst { board } = parseFEN(fen);\n\tconst oppositeColor = color === 'w' ? 'b' : 'w';\n\n\t// Find marshal position\n\tfor (const sq of SQUARES) {\n\t\tconst piece = getTop(sq, board);\n\t\tif (piece?.type === pieceType.marshal && piece.color === color) {\n\t\t\treturn isSquareAttacked(sq, oppositeColor, board);\n\t\t}\n\t}\n\n\treturn false; // Marshal not found (already captured)\n}\n\nexport function wouldBeInCheckAfterMove(move: Move): boolean {\n\treturn inCheck(move.color, move.after);\n}\n","// Portable Game Notation (PGN) parser and serializer for Gungi games.\n// Read more about PGN for chess: https://en.wikipedia.org/wiki/Portable_Game_Notation\n//\n// Movetext\n// The movetext describes the actual moves of the game. This includes move number indicators (numbers followed by either one or three periods;\n// one if the next move is White's move, three if the next move is Black's move) and movetext in Standard Algebraic Notation (SAN).\n//\n// For most moves the SAN consists of the kanji for the piece, the coordinate tuple of the square the piece moved from, an 取 if there is a capture, and the tuple of the final square it moved to.\n// The kanji are 帥 (marshal), 大 (general), 中 (lieutenant general), 小 (major general), 侍 (warrior), 槍 (lancer), 馬 (rider), 忍 (spy), 砦 (fortress), 兵 (soldier),\n// 砲 (cannon), 弓 (archer), 筒 (musketeer), and 謀 (tactician).\n//\n// The algebraic name of any square is a little different from algebraic chess notation; from white's perspective,\n// the rightmost square farthest from white is (1-1-1), the leftmost square farthest from the white is (9-1-1), and the leftmost (from white's perspective) square closest to white's side is (9-9-1).\n// the coordinates are given in the from (rank-file-tier) where tier can be (1, 2, or 3) depending on the height of the tower. If performing a stack ツケ (tsuke) then 付 is appended.\n// Thus 中(4-9-1)(5-8-2)付 denotes the major general stacking on a piece, and if we wanted to take the piece instead, we would write 中(4-9-1)取(5-8-1).\n//\n// Omitting the from square and prepending 新 to the piece indicates arata - a new piece is being placed on the board (e.g. 新小(8-7-1)) . In non-beginner games,\n// all the first moves are of this form until both players say they are finished placing pieces;\n// If a player is finished, after they place their final piece in their setup, 終 is appended (e.g. 新兵(4-2-1)終).\n//\n// If the tactician performs a ツケ (tsuke), they have the option to convert some or all of the enemy pieces in the tower.\n// (only if they have the piece in their hand they capture the enemy piece and replaces it with their own); this is denoted by a '返'\n// after the last coordinate followed by the piece(s) they are converting (in no particular order). Thus 謀(4-9-2)(5-8-3)返中槍 denotes\n// the tactician converting a major general and a lancer in a tower.\n//\n// If the move captures the enemy marshal, \"勝\" is appended and the game is over.\n// If the move is a fourfold repetition, \"停\" is appended and the game is a draw.\n\nimport { parseFEN } from './fen';\nimport { Move } from './utils';\n\nexport type PGNOptions = {\n\tmaxWidth?: number;\n\tnewline?: string;\n\twithComments?: boolean;\n};\n\ntype InternalPGNOptions = PGNOptions & {\n\tcomments?: Map<string, string>;\n};\n\nexport function encodePGN(history: Move[], opts?: InternalPGNOptions) {\n\tconst maxWidth = opts?.maxWidth ?? 6;\n\tconst newline = opts?.newline ?? '\\n';\n\tconst withComments = opts?.withComments ?? false;\n\tconst comments = opts?.comments ?? new Map<string, string>();\n\n\tlet pgn = '';\n\tlet prev = 0;\n\thistory.forEach((move, i) => {\n\t\tconst state = parseFEN(move.before);\n\t\tif (state.moveNumber !== prev) {\n\t\t\tconst indicator = move.color === 'w' ? '.' : '...';\n\t\t\tpgn += `${state.moveNumber}${indicator} `;\n\t\t\tprev = state.moveNumber;\n\t\t}\n\n\t\tpgn += `${move.san} `;\n\n\t\tif (withComments && comments.has(move.after)) {\n\t\t\tpgn += `{${comments.get(move.after)}} `;\n\t\t}\n\n\t\tif ((i + 1) % maxWidth === 0) {\n\t\t\tpgn += newline;\n\t\t}\n\t});\n\n\treturn pgn.replaceAll(' ', ' ').trim();\n}\n\nexport type ParsedPGN = {\n\tmoves: string[];\n\tcomments: Map<number, string>;\n};\n\nexport function parsePGN(\n\tpgn: string,\n\topts?: Pick<PGNOptions, 'newline'>\n): ParsedPGN {\n\tconst newline = opts?.newline ?? '\\n';\n\tconst comments = new Map<number, string>();\n\tconst moves: string[] = [];\n\n\tlet normalized = pgn\n\t\t.split(newline)\n\t\t.join(' ')\n\t\t.replace(/\\d+\\.+/g, '')\n\t\t.trim();\n\n\twhile (normalized.length > 0) {\n\t\tnormalized = normalized.trim();\n\t\tif (normalized.length === 0) break;\n\n\t\tif (normalized.startsWith('{')) {\n\t\t\tconst endIdx = normalized.indexOf('}');\n\t\t\tif (endIdx !== -1) {\n\t\t\t\tconst comment = normalized.slice(1, endIdx).trim();\n\t\t\t\tif (moves.length > 0 && comment) {\n\t\t\t\t\tcomments.set(moves.length - 1, comment);\n\t\t\t\t}\n\t\t\t\tnormalized = normalized.slice(endIdx + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst match = normalized.match(/^(\\S+)/);\n\t\tif (match) {\n\t\t\tconst move = match[1];\n\t\t\tif (move && !move.startsWith('{')) {\n\t\t\t\tmoves.push(move);\n\t\t\t}\n\t\t\tnormalized = normalized.slice(move.length);\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { moves, comments };\n}\n","import { ParsedFEN, parseFEN } from './fen';\nimport {\n\tBoard,\n\tColor,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tsetupModeToCode,\n} from './utils';\n\n/**\n * Assigns piece IDs with proper stability across moves\n * Uses explicit move tracking for maximum reliability\n */\nexport function assignPieceIdsWithState(\n\tcurrentFen: string,\n\tpreviousState?: ParsedFEN | null,\n\tmove?: Move | null\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousState) {\n\t\treturn assignCanonicalIds(currentState);\n\t}\n\n\tif (move) {\n\t\treturn assignIdsWithExplicitMove(currentState, previousState, move);\n\t}\n\n\t// Fallback: try to preserve IDs based on position matching\n\treturn assignIdsWithPositionMatching(currentState, previousState);\n}\n\n/**\n * Assigns IDs canonically for initial state\n * Format: mode-color-type-number (e.g., \"1-w-兵-1\")\n */\nfunction assignCanonicalIds(state: ParsedFEN): ParsedFEN {\n\tconst result = cloneState(state);\n\tconst modeCode = setupModeToCode[state.mode];\n\n\t// Group all pieces by type and color\n\tconst pieceGroups = groupPiecesByTypeAndColor(result);\n\n\t// Assign IDs sequentially within each group\n\tObject.entries(pieceGroups).forEach(([key, pieces]) => {\n\t\tconst [color, type] = key.split('|') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces by position, then hand pieces\n\t\tconst sortedPieces = sortPiecesCanonically(pieces);\n\n\t\tsortedPieces.forEach((piece, index) => {\n\t\t\tpiece.id = `${modeCode}-${color}-${type}-${index + 1}`;\n\t\t});\n\t});\n\n\treturn result;\n}\n\n/**\n * Assigns IDs using explicit move tracking - the core robust method\n */\nfunction assignIdsWithExplicitMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): ParsedFEN {\n\tconst result = cloneStateWithoutIds(currentState);\n\tconst modeCode = setupModeToCode[currentState.mode];\n\n\t// Step 1: Identify exactly which pieces are affected by this move\n\tconst affectedPieces = identifyAffectedPieces(move);\n\n\t// Step 2: Preserve IDs for all NON-affected pieces\n\tpreserveUnaffectedPieceIds(result, previousState, affectedPieces);\n\n\t// Step 3: Handle affected pieces explicitly based on move type\n\thandleAffectedPieces(result, previousState, move, modeCode);\n\n\t// Step 4: Assign IDs to any remaining pieces without IDs\n\tassignMissingIds(result, modeCode);\n\n\treturn result;\n}\n\n/**\n * Identify exactly which pieces are affected by a move\n */\nfunction identifyAffectedPieces(move: Move): {\n\tmovingPiece?: { square: string; tier: number; type: PieceType; color: Color };\n\tcapturedPieces: Array<{\n\t\tsquare: string;\n\t\ttier: number;\n\t\ttype: PieceType;\n\t\tcolor: Color;\n\t}>;\n\tplacementSquare?: string;\n\thandPieceTypes: Array<{ color: Color; type: PieceType }>;\n} {\n\tconst capturedPieces: Array<{\n\t\tsquare: string;\n\t\ttier: number;\n\t\ttype: PieceType;\n\t\tcolor: Color;\n\t}> = [];\n\tconst handPieceTypes: Array<{ color: Color; type: PieceType }> = [];\n\tlet movingPiece:\n\t\t| { square: string; tier: number; type: PieceType; color: Color }\n\t\t| undefined;\n\tlet placementSquare: string | undefined;\n\n\tswitch (move.type) {\n\t\tcase 'route':\n\t\tcase 'tsuke':\n\t\t\t// Track the specific moving piece\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'capture':\n\t\t\t// Track moving piece and captured pieces\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Track captured pieces\n\t\t\tif (move.captured) {\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\tcapturedPieces.push({\n\t\t\t\t\t\tsquare: move.to,\n\t\t\t\t\t\ttier: capturedPiece.tier,\n\t\t\t\t\t\ttype: capturedPiece.type,\n\t\t\t\t\t\tcolor: capturedPiece.color,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'arata':\n\t\t\t// Hand piece affected + placement square\n\t\t\thandPieceTypes.push({ color: move.color, type: move.piece });\n\t\t\tplacementSquare = move.to;\n\t\t\tbreak;\n\n\t\tcase 'betray':\n\t\t\t// Track moving tactician and captured/converted pieces\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Track captured pieces\n\t\t\tif (move.captured) {\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\tcapturedPieces.push({\n\t\t\t\t\t\tsquare: move.to,\n\t\t\t\t\t\ttier: capturedPiece.tier,\n\t\t\t\t\t\ttype: capturedPiece.type,\n\t\t\t\t\t\tcolor: capturedPiece.color,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\t// Hand pieces for converted pieces\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\thandPieceTypes.push({ color: move.color, type: capturedPiece.type });\n\t\t\t\t});\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\treturn { movingPiece, capturedPieces, placementSquare, handPieceTypes };\n}\n\n/**\n * Preserve IDs for all pieces NOT affected by the move\n */\nfunction preserveUnaffectedPieceIds(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\taffectedPieces: {\n\t\tmovingPiece?: {\n\t\t\tsquare: string;\n\t\t\ttier: number;\n\t\t\ttype: PieceType;\n\t\t\tcolor: Color;\n\t\t};\n\t\tcapturedPieces: Array<{\n\t\t\tsquare: string;\n\t\t\ttier: number;\n\t\t\ttype: PieceType;\n\t\t\tcolor: Color;\n\t\t}>;\n\t\tplacementSquare?: string;\n\t\thandPieceTypes: Array<{ color: Color; type: PieceType }>;\n\t}\n): void {\n\t// Helper function to check if a specific piece is affected\n\tconst isPieceAffected = (\n\t\tsquare: string,\n\t\ttier: number,\n\t\ttype: PieceType,\n\t\tcolor: Color\n\t): boolean => {\n\t\t// Check if it's the moving piece\n\t\tif (\n\t\t\taffectedPieces.movingPiece &&\n\t\t\taffectedPieces.movingPiece.square === square &&\n\t\t\taffectedPieces.movingPiece.tier === tier &&\n\t\t\taffectedPieces.movingPiece.type === type &&\n\t\t\taffectedPieces.movingPiece.color === color\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if it's a captured piece\n\t\tif (\n\t\t\taffectedPieces.capturedPieces.some(\n\t\t\t\t(captured) =>\n\t\t\t\t\tcaptured.square === square &&\n\t\t\t\t\tcaptured.tier === tier &&\n\t\t\t\t\tcaptured.type === type &&\n\t\t\t\t\tcaptured.color === color\n\t\t\t)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if it's at the placement square (for arata moves)\n\t\tif (affectedPieces.placementSquare === square) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\t// Preserve board piece IDs (skip only specifically affected pieces)\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst square = `${rank + 1}-${9 - file}`;\n\t\t\tconst currentTower = currentState.board[rank][file];\n\t\t\tconst previousTower = previousState.board[rank][file];\n\n\t\t\t// Check each piece in the tower individually\n\t\t\tfor (\n\t\t\t\tlet tier = 0;\n\t\t\t\ttier < Math.min(currentTower.length, previousTower.length);\n\t\t\t\ttier++\n\t\t\t) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tconst previousPiece = previousTower[tier];\n\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\tpreviousPiece &&\n\t\t\t\t\tcurrentPiece.type === previousPiece.type &&\n\t\t\t\t\tcurrentPiece.color === previousPiece.color &&\n\t\t\t\t\tpreviousPiece.id\n\t\t\t\t) {\n\t\t\t\t\t// Only preserve ID if this specific piece was not affected\n\t\t\t\t\tif (\n\t\t\t\t\t\t!isPieceAffected(\n\t\t\t\t\t\t\tsquare,\n\t\t\t\t\t\t\ttier + 1,\n\t\t\t\t\t\t\tcurrentPiece.type,\n\t\t\t\t\t\t\tcurrentPiece.color\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentPiece.id = previousPiece.id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Preserve hand piece IDs (skip affected types)\n\tcurrentState.hand.forEach((currentHandPiece) => {\n\t\tconst isAffected = affectedPieces.handPieceTypes.some(\n\t\t\t(affected) =>\n\t\t\t\taffected.color === currentHandPiece.color &&\n\t\t\t\taffected.type === currentHandPiece.type\n\t\t);\n\n\t\tif (!isAffected) {\n\t\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t\t(hp) =>\n\t\t\t\t\thp.type === currentHandPiece.type &&\n\t\t\t\t\thp.color === currentHandPiece.color\n\t\t\t);\n\t\t\tif (previousHandPiece?.id) {\n\t\t\t\tcurrentHandPiece.id = previousHandPiece.id;\n\t\t\t}\n\t\t}\n\t});\n}\n\n/**\n * Handle pieces that are affected by the move\n */\nfunction handleAffectedPieces(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\tswitch (move.type) {\n\t\tcase 'route':\n\t\tcase 'tsuke':\n\t\t\thandleRegularMove(currentState, previousState, move);\n\t\t\tbreak;\n\n\t\tcase 'capture':\n\t\t\thandleCaptureMove(currentState, previousState, move);\n\t\t\tbreak;\n\n\t\tcase 'arata':\n\t\t\thandleArataMove(currentState, previousState, move, modeCode);\n\t\t\tbreak;\n\n\t\tcase 'betray':\n\t\t\thandleBetrayalMove(currentState, previousState, move, modeCode);\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Handle regular moves (route/tsuke) - preserve the moving piece's ID\n */\nfunction handleRegularMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): void {\n\tif (!move.from) return;\n\n\t// Parse the from position to get tier info\n\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\tconst fromSquare = `${fromRank}-${fromFile}`;\n\n\t// Find the piece that moved in the previous state with exact tier\n\tconst movedPiece = findPieceAtSquare(\n\t\tpreviousState.board,\n\t\tfromSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\tfromTier\n\t);\n\tif (!movedPiece?.id) return;\n\n\t// Parse the to position to get tier info\n\tconst [toRank, toFile, toTier] = move.to.split('-').map(Number);\n\tconst toSquare = `${toRank}-${toFile}`;\n\n\t// Find where it ended up in the current state with exact tier\n\tconst newPiece = findPieceAtSquare(\n\t\tcurrentState.board,\n\t\ttoSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\ttoTier\n\t);\n\tif (newPiece) {\n\t\tnewPiece.id = movedPiece.id;\n\t}\n}\n\n/**\n * Handle capture moves - preserve moving piece, captured pieces are removed\n */\nfunction handleCaptureMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): void {\n\t// Handle the moving piece same as regular move\n\thandleRegularMove(currentState, previousState, move);\n\t// Captured pieces are already removed from the board, their IDs are freed\n}\n\n/**\n * Handle arata moves - board piece inherits hand ID for animation continuity,\n * hand piece (if still has count > 0) gets new ID\n */\nfunction handleArataMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\t// Find the hand piece in the previous state\n\tconst prevHandPiece = previousState.hand.find(\n\t\t(hp) => hp.type === move.piece && hp.color === move.color\n\t);\n\n\tif (!prevHandPiece?.id) return;\n\n\t// Parse the to position to get tier info for finding the exact placed piece\n\tconst [toRank, toFile, toTier] = move.to.split('-').map(Number);\n\tconst toSquare = `${toRank}-${toFile}`;\n\n\t// CRITICAL: Board piece INHERITS the hand piece's ID for animation continuity\n\t// This allows framer-motion layoutId to animate the piece from hand to board\n\tconst placedPiece = findPieceAtSquare(\n\t\tcurrentState.board,\n\t\ttoSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\ttoTier\n\t);\n\tif (placedPiece) {\n\t\tplacedPiece.id = prevHandPiece.id;\n\t}\n\n\t// Hand piece (if still exists with count > 0) gets a NEW ID\n\t// This ensures unique IDs and allows the \"remaining\" hand pieces to be distinct\n\tconst currentHandPiece = currentState.hand.find(\n\t\t(hp) => hp.type === move.piece && hp.color === move.color\n\t);\n\tif (currentHandPiece) {\n\t\tconst nextId = findNextAvailableId(\n\t\t\tcurrentState,\n\t\t\tmodeCode,\n\t\t\tmove.color,\n\t\t\tmove.piece\n\t\t);\n\t\tcurrentHandPiece.id = nextId;\n\t}\n}\n\n/**\n * Handle betrayal moves - complex move with conversions\n */\nfunction handleBetrayalMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\t// Handle the tactician's movement\n\thandleRegularMove(currentState, previousState, move);\n\n\t// Handle hand piece additions from conversions\n\tif (move.captured) {\n\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\tconst handPiece = currentState.hand.find(\n\t\t\t\t(hp) => hp.type === capturedPiece.type && hp.color === move.color\n\t\t\t);\n\t\t\t// Hand pieces from conversions get new IDs (they're essentially new pieces)\n\t\t\tif (handPiece && !handPiece.id) {\n\t\t\t\tconst nextId = findNextAvailableId(\n\t\t\t\t\tcurrentState,\n\t\t\t\t\tmodeCode,\n\t\t\t\t\tmove.color,\n\t\t\t\t\tcapturedPiece.type\n\t\t\t\t);\n\t\t\t\thandPiece.id = nextId;\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * Fallback method using position-based matching when move info unavailable\n */\nfunction assignIdsWithPositionMatching(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN\n): ParsedFEN {\n\tconst result = cloneState(currentState);\n\tconst modeCode = setupModeToCode[currentState.mode];\n\n\t// Track which hand piece IDs were used for arata detection\n\tconst handIdsUsedForArata = new Set<string>();\n\n\t// First pass: detect arata moves (hand count decreased, new board piece appeared)\n\tfor (const prevHandPiece of previousState.hand) {\n\t\tconst currHandPiece = result.hand.find(\n\t\t\t(hp) => hp.type === prevHandPiece.type && hp.color === prevHandPiece.color\n\t\t);\n\t\tconst prevCount = prevHandPiece.count;\n\t\tconst currCount = currHandPiece?.count ?? 0;\n\n\t\tif (prevCount > currCount && prevHandPiece.id) {\n\t\t\t// Hand count decreased - find the new board piece of this type\n\t\t\tconst newBoardPiece = findNewBoardPiece(\n\t\t\t\tresult.board,\n\t\t\t\tpreviousState.board,\n\t\t\t\tprevHandPiece.type,\n\t\t\t\tprevHandPiece.color\n\t\t\t);\n\t\t\tif (newBoardPiece) {\n\t\t\t\t// Board piece inherits hand ID for animation\n\t\t\t\tnewBoardPiece.id = prevHandPiece.id;\n\t\t\t\thandIdsUsedForArata.add(prevHandPiece.id);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: position-based matching for board pieces that didn't come from arata\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst currentTower = result.board[rank][file];\n\t\t\tconst previousTower = previousState.board[rank][file];\n\n\t\t\tfor (\n\t\t\t\tlet tier = 0;\n\t\t\t\ttier < Math.min(currentTower.length, previousTower.length);\n\t\t\t\ttier++\n\t\t\t) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tconst previousPiece = previousTower[tier];\n\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\t!currentPiece.id &&\n\t\t\t\t\tpreviousPiece &&\n\t\t\t\t\tcurrentPiece.type === previousPiece.type &&\n\t\t\t\t\tcurrentPiece.color === previousPiece.color &&\n\t\t\t\t\tpreviousPiece.id\n\t\t\t\t) {\n\t\t\t\t\tcurrentPiece.id = previousPiece.id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Third pass: match remaining hand pieces, but give new IDs if their ID was used for arata\n\tresult.hand.forEach((currentHandPiece) => {\n\t\tif (currentHandPiece.id) return;\n\n\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t(hp) =>\n\t\t\t\thp.type === currentHandPiece.type && hp.color === currentHandPiece.color\n\t\t);\n\t\tif (\n\t\t\tpreviousHandPiece?.id &&\n\t\t\t!handIdsUsedForArata.has(previousHandPiece.id)\n\t\t) {\n\t\t\tcurrentHandPiece.id = previousHandPiece.id;\n\t\t}\n\t});\n\n\t// Assign missing IDs\n\tassignMissingIds(result, modeCode);\n\n\treturn result;\n}\n\nfunction findNewBoardPiece(\n\tcurrentBoard: Board,\n\tpreviousBoard: Board,\n\ttype: PieceType,\n\tcolor: Color\n): Piece | null {\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst currentTower = currentBoard[rank][file];\n\t\t\tconst previousTower = previousBoard[rank][file];\n\n\t\t\tfor (let tier = 0; tier < currentTower.length; tier++) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\tcurrentPiece.type === type &&\n\t\t\t\t\tcurrentPiece.color === color &&\n\t\t\t\t\t!currentPiece.id\n\t\t\t\t) {\n\t\t\t\t\t// Check if this piece wasn't in the previous state at this position\n\t\t\t\t\tconst prevPiece = previousTower[tier];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!prevPiece ||\n\t\t\t\t\t\tprevPiece.type !== type ||\n\t\t\t\t\t\tprevPiece.color !== color\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn currentPiece;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Assign IDs to pieces that don't have them yet\n */\nfunction assignMissingIds(state: ParsedFEN, modeCode: number): void {\n\tconst usedIds = new Set(getAllUsedIds(state));\n\tconst pieceGroups = groupPiecesByTypeAndColor(state);\n\n\tObject.entries(pieceGroups).forEach(([key, pieces]) => {\n\t\tconst [color, type] = key.split('|') as [Color, PieceType];\n\n\t\tpieces.forEach((piece) => {\n\t\t\tif (!piece.id) {\n\t\t\t\t// Find the next available number for this type/color combination\n\t\t\t\tlet number = 1;\n\t\t\t\tlet candidateId = `${modeCode}-${color}-${type}-${number}`;\n\n\t\t\t\twhile (usedIds.has(candidateId)) {\n\t\t\t\t\tnumber++;\n\t\t\t\t\tcandidateId = `${modeCode}-${color}-${type}-${number}`;\n\t\t\t\t}\n\n\t\t\t\tpiece.id = candidateId;\n\t\t\t\tusedIds.add(candidateId);\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * Find the next available ID for a specific piece type and color\n */\nfunction findNextAvailableId(\n\tstate: ParsedFEN,\n\tmodeCode: number,\n\tcolor: Color,\n\ttype: PieceType\n): string {\n\tconst usedIds = new Set(getAllUsedIds(state));\n\n\tlet number = 1;\n\tlet candidateId = `${modeCode}-${color}-${type}-${number}`;\n\n\twhile (usedIds.has(candidateId)) {\n\t\tnumber++;\n\t\tcandidateId = `${modeCode}-${color}-${type}-${number}`;\n\t}\n\n\treturn candidateId;\n}\n\n/**\n * Get all currently used IDs in the state\n */\nfunction getAllUsedIds(state: ParsedFEN): string[] {\n\tconst ids: string[] = [];\n\n\t// Collect from board\n\tfor (const rank of state.board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece?.id) {\n\t\t\t\t\tids.push(piece.id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Collect from hand\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.id) {\n\t\t\tids.push(handPiece.id);\n\t\t}\n\t}\n\n\treturn ids;\n}\n\n/**\n * Group all pieces by type and color for ID assignment\n */\nfunction groupPiecesByTypeAndColor(\n\tstate: ParsedFEN\n): Record<string, Array<Piece | HandPiece>> {\n\tconst groups: Record<string, Array<Piece | HandPiece>> = {};\n\n\t// Process board pieces\n\tfor (const rank of state.board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece) {\n\t\t\t\t\tconst key = `${piece.color}|${piece.type}`;\n\t\t\t\t\tif (!groups[key]) groups[key] = [];\n\t\t\t\t\tgroups[key].push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Process hand pieces\n\tfor (const handPiece of state.hand) {\n\t\tconst key = `${handPiece.color}|${handPiece.type}`;\n\t\tif (!groups[key]) groups[key] = [];\n\t\tgroups[key].push(handPiece);\n\t}\n\n\treturn groups;\n}\n\n/**\n * Sort pieces canonically for consistent ID assignment\n */\nfunction sortPiecesCanonically(\n\tpieces: Array<Piece | HandPiece>\n): Array<Piece | HandPiece> {\n\treturn pieces.sort((a, b) => {\n\t\t// Board pieces come before hand pieces\n\t\tconst aIsBoard = 'square' in a;\n\t\tconst bIsBoard = 'square' in b;\n\n\t\tif (aIsBoard && !bIsBoard) return -1;\n\t\tif (!aIsBoard && bIsBoard) return 1;\n\n\t\t// Both are board pieces - sort by square and tier\n\t\tif (aIsBoard && bIsBoard) {\n\t\t\tconst aPiece = a as Piece;\n\t\t\tconst bPiece = b as Piece;\n\n\t\t\tif (aPiece.square !== bPiece.square) {\n\t\t\t\tconst [aRank, aFile] = aPiece.square.split('-').map(Number);\n\t\t\t\tconst [bRank, bFile] = bPiece.square.split('-').map(Number);\n\n\t\t\t\tif (aRank !== bRank) return aRank - bRank;\n\t\t\t\treturn aFile - bFile;\n\t\t\t}\n\n\t\t\treturn aPiece.tier - bPiece.tier;\n\t\t}\n\n\t\t// Both are hand pieces - maintain original order\n\t\treturn 0;\n\t});\n}\n\n/**\n * Find a piece at a specific square with optional filters\n */\nfunction findPieceAtSquare(\n\tboard: Board,\n\tsquare: string,\n\ttype?: PieceType,\n\tcolor?: Color,\n\ttier?: number\n): Piece | null {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return null;\n\n\tconst tower = board[rank - 1][9 - file];\n\tfor (const piece of tower) {\n\t\tif (\n\t\t\tpiece &&\n\t\t\t(!type || piece.type === type) &&\n\t\t\t(!color || piece.color === color) &&\n\t\t\t(!tier || piece.tier === tier)\n\t\t) {\n\t\t\treturn piece;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Create a deep clone of the parsed FEN state\n */\nfunction cloneState(state: ParsedFEN): ParsedFEN {\n\treturn {\n\t\tboard: state.board.map((rank) =>\n\t\t\trank.map((file) => file.map((piece) => (piece ? { ...piece } : piece)))\n\t\t),\n\t\thand: state.hand.map((hp) => ({ ...hp })),\n\t\tturn: state.turn,\n\t\tmode: state.mode,\n\t\tdrafting: { ...state.drafting },\n\t\tmoveNumber: state.moveNumber,\n\t};\n}\n\n/**\n * Create a deep clone of the parsed FEN state WITHOUT any IDs\n */\nfunction cloneStateWithoutIds(state: ParsedFEN): ParsedFEN {\n\treturn {\n\t\tboard: state.board.map((rank) =>\n\t\t\trank.map((file) =>\n\t\t\t\tfile.map((piece) => (piece ? { ...piece, id: undefined } : piece))\n\t\t\t)\n\t\t),\n\t\thand: state.hand.map((hp) => ({ ...hp, id: undefined })),\n\t\tturn: state.turn,\n\t\tmode: state.mode,\n\t\tdrafting: { ...state.drafting },\n\t\tmoveNumber: state.moveNumber,\n\t};\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO,CAAE,GAAGF,EAAK,CAACE,CAAK,EAAGD,CAAI,GAC/C,CAAC,CACF,EA+BYE,EAA6C,CACzD,MAAO,EACP,SAAU,EACV,aAAc,EACd,SAAU,CACX,EACaC,EAAkBN,EAAWK,CAAe,EAE5CE,GAAQ,IACRC,GAAQ,IAERC,GAAQ,SACRC,GAAO,SACPC,GAAS,SACTC,GAAQ,SAERC,GAAU,SACVC,GAAU,SACVC,GAAqB,SACrBC,GAAgB,SAChBC,GAAU,SACVC,GAAS,SACTC,GAAQ,SACRC,GAAM,SACNC,GAAW,SACXC,GAAU,SACVC,GAAS,SACTC,GAAS,SACTC,GAAY,SACZC,GAAY,SAEZC,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACC,EAAGC,IAAMA,EAAI,CAAC,EAAE,QAASA,GAC1E,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACD,EAAG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AAKH,GAAW,CAAC,EACjB,KAAKE,GAAU,MAAM,CACtB,CAEA,MAAO,CACN,OAAO,KAAKN,EACb,CAEA,MAAO,CACN,IAAMwE,EAAW,KAAKpE,GAAS,IAAI,EACnC,OAAIoE,GACH,KAAKhE,GAAiBgE,EAAS,MAAM,EAC9BA,GAGD,IACR,CAEA,WAAWP,EAAiB,CAC3B,KAAK3D,GAAU,IAAI,KAAK,IAAI,EAAG2D,CAAO,CACvC,CAEA,YAAa,CACZ,OAAO,KAAK3D,GAAU,IAAI,KAAK,IAAI,CAAC,CACrC,CAEA,eAAgB,CACf,IAAMG,EAAM,KAAK,IAAI,EACfwD,EAAU,KAAK3D,GAAU,IAAIG,CAAG,EACtC,YAAKH,GAAU,OAAOG,CAAG,EAClBwD,CACR,CAEA,aAAc,CACb,IAAMQ,EAA6C,CAAC,EACpD,OAAW,CAAChE,EAAKwD,CAAO,IAAK,KAAK3D,GACjCmE,EAAO,KAAK,CAAE,IAAAhE,EAAK,QAAAwD,CAAQ,CAAC,EAE7B,OAAOQ,CACR,CAEA,gBAAiB,CAChB,IAAMC,EAAW,KAAK,YAAY,EAClC,YAAKpE,GAAU,MAAM,EACdoE,CACR,CAEA,YAAYjE,EAAa,CACxB,OAAOkE,EAAYlE,CAAG,CACvB,CACD","names":["pc","inverseMap","map","acc","key","value","setupModeToCode","setupCodeToMode","WHITE","BLACK","TSUKE","TAKE","BETRAY","ARATA","MARSHAL","GENERAL","LIEUTENANT_GENERAL","MAJOR_GENERAL","WARRIOR","LANCER","RIDER","SPY","FORTRESS","SOLDIER","CANNON","ARCHER","MUSKETEER","TACTICIAN","SQUARES","_","x","y","piece","symbolToName","pieceToFenCode","fenCodeToPiece","createPieceFromFenCode","code","z","color","name","createHandPieceFromFenCode","count","CANONICAL_NAMES","ENGLISH_NAMES","FEN_CODES","updateHand","pieces","hand","oppositeColor","p","c","hp","h","hpi","convert","square","board","rank","file","tower","get","remove","newTower","removeTop","put","getTop","s","isGameOver","INTRO_POSITION","BEGINNER_POSITION","INTERMEDIATE_POSITION","ADVANCED_POSITION","parseFEN","fen","result","validateFen","placement","handpieces","turn","mode","drafting","moveNumber","board","rank","y","outeracc","partial","tower","piece","z","createPieceFromFenCode","partialPieces","acc","square","hand","playerHand","pieces","i","count","createHandPieceFromFenCode","setupCodeToMode","encodeFEN","emptyCount","file","p","pieceToFenCode","symbolToName","type","color","whiteHand","blackHand","draftKeys","key","setupModeToCode","parts","ranks","fileParts","fileCount","k","filePart","towerPieces","l","hands","dirs","pieceProbes","getAvailableSquares","dir","start","origin","length","board","y","x","py","px","dy","dx","originPiece","getTop","availableSquares","reverse","piece","side","below","forward","step","leapPieces","generateMovesForSquare","square","fen","turn","mode","hand","parseFEN","probe","i","pval","pcarry","acc","s","p","t","get","maxTier","marshalCanStack","createMove","enemies","playerHand","enemyCountMap","e","betrayalOptions","type","count","combos","generateCombinations","combo","newTier","captured","generateArata","drafting","isDraft","ranks","maybe","end","rank","_","arata","isLastPiece","h","sum","to","draftFinished","from","toTier","capture","tsuke","betray","draftDone","move","after","gameOverSAN","makeMove","moveNumber","file","tier","removeTop","remove","convert","updateHand","put","encodeFEN","items","result","helper","currentCombination","getAttackedSquares","isSquareAttacked","byColor","targetRank","targetFile","targetSquare","sq","SQUARES","inCheck","color","oppositeColor","wouldBeInCheckAfterMove","encodePGN","history","opts","maxWidth","newline","withComments","comments","pgn","prev","move","i","state","parseFEN","indicator","parsePGN","moves","normalized","endIdx","comment","match","assignPieceIdsWithState","currentFen","previousState","move","currentState","parseFEN","assignIdsWithExplicitMove","assignIdsWithPositionMatching","assignCanonicalIds","state","result","cloneState","modeCode","setupModeToCode","pieceGroups","groupPiecesByTypeAndColor","key","pieces","color","type","sortPiecesCanonically","piece","index","cloneStateWithoutIds","affectedPieces","identifyAffectedPieces","preserveUnaffectedPieceIds","handleAffectedPieces","assignMissingIds","capturedPieces","handPieceTypes","movingPiece","placementSquare","fromRank","fromFile","fromTier","capturedPiece","isPieceAffected","square","tier","captured","rank","file","currentTower","previousTower","currentPiece","previousPiece","currentHandPiece","affected","previousHandPiece","hp","handleRegularMove","handleCaptureMove","handleArataMove","handleBetrayalMove","fromSquare","movedPiece","findPieceAtSquare","toRank","toFile","toTier","toSquare","newPiece","prevHandPiece","placedPiece","nextId","findNextAvailableId","handPiece","handIdsUsedForArata","currHandPiece","prevCount","currCount","newBoardPiece","findNewBoardPiece","currentBoard","previousBoard","prevPiece","usedIds","getAllUsedIds","number","candidateId","ids","groups","a","b","aIsBoard","bIsBoard","aPiece","bPiece","aRank","aFile","bRank","bFile","board","tower","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#previousState","#comments","#initPosition","#initializeState","fen","move","stateWithIds","assignPieceIdsWithState","INTRO_POSITION","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","acc","p","c","ADVANCED_POSITION","encodeFEN","get","getTop","piece","states","frequencyMap","map","str","#hasNoLegalMoves","hp","generateArata","sq","SQUARES","generateMovesForSquare","#hasEscapingMove","moves","wouldBeInCheckAfterMove","inCheck","isGameOver","pieces","marshals","m1","m2","r1","f1","r2","f2","rankDiff","fileDiff","pgn","parsed","parsePGN","i","comment","normalizedInput","found","m","boardMoves","handMoves","encodePGN","lastMove","result","comments","validateFen"]}
1
+ {"version":3,"sources":["../src/gungi/gungi.ts","../src/gungi/utils.ts","../src/gungi/fen.ts","../src/gungi/move_gen.ts","../src/gungi/pgn.ts","../src/gungi/piece-ids.ts"],"sourcesContent":["import pc from 'picocolors';\nimport type { ParsedFEN } from './fen';\nimport type { PGNOptions } from './pgn';\nimport type { Board, Color, HandPiece, Move, Piece, SetupMode } from './utils';\nimport {\n\tADVANCED_POSITION,\n\tBEGINNER_POSITION,\n\tencodeFEN,\n\tINTERMEDIATE_POSITION,\n\tINTRO_POSITION,\n\tvalidateFen,\n} from './fen';\nimport {\n\tinCheck as checkDetection,\n\tgenerateArata,\n\tgenerateMovesForSquare,\n\tisSquareAttacked,\n\twouldBeInCheckAfterMove,\n} from './move_gen';\nimport { encodePGN, parsePGN } from './pgn';\nimport { assignPieceIdsWithState } from './piece-ids';\nimport {\n\tARATA,\n\tARCHER,\n\tBETRAY,\n\tBLACK,\n\tCANNON,\n\tCANONICAL_NAMES,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tFORTRESS,\n\tGENERAL,\n\tget,\n\tgetTop,\n\tisGameOver,\n\tLANCER,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tMARSHAL,\n\tMUSKETEER,\n\tpiece,\n\tpieceToFenCode,\n\tRIDER,\n\tSOLDIER,\n\tSPY,\n\tSQUARES,\n\tsymbolToName,\n\tTACTICIAN,\n\tTAKE,\n\tTSUKE,\n\tWARRIOR,\n\tWHITE,\n} from './utils';\n\nexport {\n\tWHITE,\n\tBLACK,\n\tMARSHAL,\n\tGENERAL,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tWARRIOR,\n\tLANCER,\n\tRIDER,\n\tSPY,\n\tFORTRESS,\n\tSOLDIER,\n\tCANNON,\n\tARCHER,\n\tMUSKETEER,\n\tTACTICIAN,\n\tTSUKE,\n\tTAKE,\n\tBETRAY,\n\tARATA,\n\tINTRO_POSITION,\n\tBEGINNER_POSITION,\n\tINTERMEDIATE_POSITION,\n\tADVANCED_POSITION,\n\tSQUARES,\n\tCANONICAL_NAMES,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tvalidateFen,\n\tisSquareAttacked,\n};\n\nexport class Gungi {\n\t#board!: Board;\n\t#hand!: HandPiece[];\n\t#turn!: Color;\n\t#moveNumber!: number;\n\t#drafting!: Record<Color, boolean>;\n\t#mode!: SetupMode;\n\n\t#history: Move[] = [];\n\t#previousState: ParsedFEN | null = null;\n\t#comments: Map<string, string> = new Map();\n\n\t#initPosition: string;\n\n\t#initializeState(fen: string, move?: Move | null) {\n\t\t// Assign IDs using the previous state and move info for stability\n\t\tconst stateWithIds = assignPieceIdsWithState(\n\t\t\tfen,\n\t\t\tthis.#previousState,\n\t\t\tmove\n\t\t);\n\n\t\tthis.#board = stateWithIds.board;\n\t\tthis.#hand = stateWithIds.hand;\n\t\tthis.#turn = stateWithIds.turn;\n\t\tthis.#moveNumber = stateWithIds.moveNumber;\n\t\tthis.#drafting = stateWithIds.drafting;\n\t\tthis.#mode = stateWithIds.mode;\n\n\t\t// Update the previous state for next time\n\t\tthis.#previousState = stateWithIds;\n\t}\n\n\tconstructor(fen?: string) {\n\t\tthis.#initPosition = fen ?? INTRO_POSITION;\n\t\tthis.#initializeState(this.#initPosition);\n\t}\n\n\tascii(opts?: { english?: boolean }) {\n\t\tconst tierToColor = {\n\t\t\t1: pc.yellow,\n\t\t\t2: pc.blue,\n\t\t\t3: pc.green,\n\t\t} as const;\n\n\t\tlet s = ` 987654321 \\n`;\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\tfor (let rank = 1; rank <= 9; rank++) {\n\t\t\ts += `|`;\n\t\t\tfor (let file = 9; file > 0; file--) {\n\t\t\t\tconst square = this.getTop(`${rank}-${file}`);\n\t\t\t\tif (!square) {\n\t\t\t\t\ts += '・';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst code = pieceToFenCode[symbolToName[square.type]];\n\t\t\t\tconst en = square.color === 'w' ? code.toUpperCase() : code;\n\n\t\t\t\tconst coloredPiece = tierToColor[square.tier as 1 | 2 | 3](\n\t\t\t\t\topts?.english\n\t\t\t\t\t\t? String.fromCharCode(en.charCodeAt(0) + 0xfee0)\n\t\t\t\t\t\t: square.type\n\t\t\t\t);\n\n\t\t\t\ts += square.color === 'w' ? coloredPiece : pc.dim(coloredPiece);\n\t\t\t}\n\t\t\ts += `|${String.fromCharCode(rank - 1 + '1'.charCodeAt(0))}\\n`;\n\t\t}\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\treturn s;\n\t}\n\n\tboard() {\n\t\treturn this.#board;\n\t}\n\n\tcaptured(color?: Color) {\n\t\tconst allCaptured = this.#history.flatMap((move) => move.captured ?? []);\n\t\tconst capturedCounts = allCaptured.reduce((acc, p) => {\n\t\t\tconst c = acc.find((a) => a.type === p.type && a.color === p.color);\n\t\t\tif (c) {\n\t\t\t\tc.count++;\n\t\t\t} else {\n\t\t\t\tacc.push({ type: p.type, color: p.color, count: 1 });\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, [] as HandPiece[]);\n\n\t\treturn color\n\t\t\t? capturedCounts.filter((p) => p.color === color)\n\t\t\t: capturedCounts;\n\t}\n\n\tclear() {\n\t\tthis.#initializeState(ADVANCED_POSITION);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\t}\n\n\tfen() {\n\t\treturn encodeFEN({\n\t\t\tboard: this.#board,\n\t\t\thand: this.#hand,\n\t\t\tturn: this.#turn,\n\t\t\tmode: this.#mode,\n\t\t\tdrafting: this.#drafting,\n\t\t\tmoveNumber: this.#moveNumber,\n\t\t});\n\t}\n\n\tget(square: string) {\n\t\treturn get(square, this.#board);\n\t}\n\n\tgetDraftingRights(color?: Color) {\n\t\treturn color ? this.#drafting[color] : this.#drafting;\n\t}\n\n\tgetTop(square: string) {\n\t\treturn getTop(square, this.#board);\n\t}\n\n\thand(color?: Color) {\n\t\treturn color\n\t\t\t? this.#hand.filter((piece) => piece.color === color)\n\t\t\t: this.#hand;\n\t}\n\n\thistory(opts?: { verbose?: boolean }) {\n\t\treturn opts?.verbose\n\t\t\t? this.#history\n\t\t\t: this.#history.map((move) => move.san);\n\t}\n\n\tinDraft() {\n\t\treturn this.#drafting.b || this.#drafting.w;\n\t}\n\n\tisFourfoldRepetition() {\n\t\tconst states = this.#history.map((move) => move.before.split(' ')[0]);\n\t\tif (states.length) states.push(this.#history.at(-1)!.after.split(' ')[0]);\n\t\tconst frequencyMap = states.reduce((map, str) => {\n\t\t\tmap.set(str, (map.get(str) || 0) + 1);\n\t\t\treturn map;\n\t\t}, new Map<string, number>());\n\n\t\treturn Math.max(...frequencyMap.values()) === 4;\n\t}\n\n\t#hasNoLegalMoves(): boolean {\n\t\tconst fen = this.fen();\n\t\tif (this.inDraft()) {\n\t\t\treturn this.#hand.every((hp) => generateArata(hp, fen).length === 0);\n\t\t}\n\n\t\tfor (const sq of SQUARES) {\n\t\t\tif (generateMovesForSquare(sq, fen).length > 0) return false;\n\t\t}\n\t\tfor (const hp of this.#hand) {\n\t\t\tif (generateArata(hp, fen).length > 0) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t#hasEscapingMove(): boolean {\n\t\tconst fen = this.fen();\n\n\t\tfor (const sq of SQUARES) {\n\t\t\tconst moves = generateMovesForSquare(sq, fen);\n\t\t\tfor (const move of moves) {\n\t\t\t\tif (!wouldBeInCheckAfterMove(move)) return true;\n\t\t\t}\n\t\t}\n\n\t\tfor (const hp of this.#hand) {\n\t\t\tconst moves = generateArata(hp, fen);\n\t\t\tfor (const move of moves) {\n\t\t\t\tif (!wouldBeInCheckAfterMove(move)) return true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tinCheck(color?: Color): boolean {\n\t\tconst c = color ?? this.turn();\n\t\treturn checkDetection(c, this.fen());\n\t}\n\n\tisCheckmate(): boolean {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return false;\n\t\treturn this.inCheck() && !this.#hasEscapingMove();\n\t}\n\n\tisStalemate(): boolean {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return false;\n\t\treturn !this.inCheck() && !this.#hasEscapingMove();\n\t}\n\n\tisInsufficientMaterial(): boolean {\n\t\tif (this.inDraft()) return false;\n\n\t\tif (this.#hand.some((p) => p.type !== piece.marshal)) return false;\n\n\t\tconst pieces = this.#board\n\t\t\t.flat()\n\t\t\t.flat()\n\t\t\t.filter((p) => p !== null) as Piece[];\n\t\tconst nonMarshals = pieces.filter((p) => p.type !== piece.marshal);\n\t\tif (nonMarshals.length > 0) return false;\n\n\t\tconst marshals = pieces.filter((p) => p.type === piece.marshal);\n\t\tif (marshals.length !== 2) return false;\n\n\t\tconst [m1, m2] = marshals;\n\t\tconst [r1, f1] = m1.square.split('-').map(Number);\n\t\tconst [r2, f2] = m2.square.split('-').map(Number);\n\n\t\tconst rankDiff = Math.abs(r1 - r2);\n\t\tconst fileDiff = Math.abs(f1 - f2);\n\n\t\tconst isAdjacent = rankDiff <= 1 && fileDiff <= 1;\n\n\t\treturn !isAdjacent;\n\t}\n\n\tisDraw(): boolean {\n\t\treturn (\n\t\t\tthis.isStalemate() ||\n\t\t\tthis.isFourfoldRepetition() ||\n\t\t\tthis.isInsufficientMaterial()\n\t\t);\n\t}\n\n\tisGameOver() {\n\t\tif (this.inDraft()) return false;\n\t\tif (isGameOver(this.#board)) return true; // marshal captured\n\t\tif (this.isFourfoldRepetition()) return true;\n\t\tif (this.isInsufficientMaterial()) return true;\n\t\treturn this.isCheckmate() || this.isStalemate();\n\t}\n\n\tload(fen: string) {\n\t\tthis.#initializeState(fen);\n\t}\n\n\tloadPgn(\n\t\tpgn: string,\n\t\tfen = ADVANCED_POSITION,\n\t\topts?: Pick<PGNOptions, 'newline'>\n\t) {\n\t\tthis.#initializeState(fen);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\n\t\tconst parsed = parsePGN(pgn, opts);\n\t\tparsed.moves.forEach((move, i) => {\n\t\t\tthis.move(move);\n\t\t\tconst comment = parsed.comments.get(i);\n\t\t\tif (comment) {\n\t\t\t\tthis.setComment(comment);\n\t\t\t}\n\t\t});\n\t}\n\n\tmove(move: string | Exclude<Move, 'color' | 'san' | 'before' | 'after'>) {\n\t\tconst moves = this.moves({ verbose: true }) as Move[];\n\t\tconst normalizedInput =\n\t\t\ttypeof move === 'string' ? move.replace(/[=#]$/, '') : null;\n\t\tconst found =\n\t\t\ttypeof move === 'string'\n\t\t\t\t? moves.find((m) => m.san === normalizedInput || m.san === move)\n\t\t\t\t: moves.find(\n\t\t\t\t\t\t(m) =>\n\t\t\t\t\t\t\tmove.piece === m.piece &&\n\t\t\t\t\t\t\tmove.type === m.type &&\n\t\t\t\t\t\t\tmove.from === m.from &&\n\t\t\t\t\t\t\tmove.to === m.to &&\n\t\t\t\t\t\t\tmove.captured === m.captured &&\n\t\t\t\t\t\t\tmove.draftFinished === m.draftFinished\n\t\t\t\t\t);\n\t\tif (!found) throw new Error(`Illegal move: ${move}`);\n\n\t\tthis.#history.push(found);\n\t\tthis.#initializeState(found.after, found);\n\n\t\t// Append game state symbols to SAN\n\t\tif (this.isCheckmate()) {\n\t\t\tthis.#history.at(-1)!.san += '#';\n\t\t} else if (\n\t\t\tthis.isStalemate() ||\n\t\t\tthis.isFourfoldRepetition() ||\n\t\t\tthis.isInsufficientMaterial()\n\t\t) {\n\t\t\tthis.#history.at(-1)!.san += '=';\n\t\t}\n\n\t\treturn found;\n\t}\n\n\tmoves(opts?: { square?: string; arata?: HandPiece; verbose?: boolean }) {\n\t\tif (this.isGameOver()) return [];\n\n\t\tif (opts?.square) {\n\t\t\tconst moves = generateMovesForSquare(opts.square, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (opts?.arata) {\n\t\t\tconst moves = generateArata(opts.arata, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (this.inDraft()) {\n\t\t\tconst moves = this.hand().flatMap((hp) => generateArata(hp, this.fen()));\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t} else {\n\t\t\tconst boardMoves = SQUARES.flatMap((square) =>\n\t\t\t\tgenerateMovesForSquare(square, this.fen())\n\t\t\t);\n\n\t\t\tconst handMoves = this.hand().flatMap((hp) =>\n\t\t\t\tgenerateArata(hp, this.fen())\n\t\t\t);\n\n\t\t\tconst moves = [...boardMoves, ...handMoves];\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t}\n\t}\n\n\tmoveNumber() {\n\t\treturn this.#moveNumber;\n\t}\n\n\tpgn(opts?: PGNOptions) {\n\t\treturn encodePGN(this.#history, { ...opts, comments: this.#comments });\n\t}\n\n\tprint(opts?: { english?: boolean }) {\n\t\tconsole.log(this.ascii(opts));\n\t}\n\n\treset() {\n\t\tthis.#initializeState(this.#initPosition);\n\t\tthis.#history = [];\n\t\tthis.#comments.clear();\n\t}\n\n\tturn() {\n\t\treturn this.#turn;\n\t}\n\n\tundo() {\n\t\tconst lastMove = this.#history.pop();\n\t\tif (lastMove) {\n\t\t\tthis.#initializeState(lastMove.before);\n\t\t\treturn lastMove;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tsetComment(comment: string) {\n\t\tthis.#comments.set(this.fen(), comment);\n\t}\n\n\tgetComment() {\n\t\treturn this.#comments.get(this.fen());\n\t}\n\n\tremoveComment() {\n\t\tconst fen = this.fen();\n\t\tconst comment = this.#comments.get(fen);\n\t\tthis.#comments.delete(fen);\n\t\treturn comment;\n\t}\n\n\tgetComments() {\n\t\tconst result: { fen: string; comment: string }[] = [];\n\t\tfor (const [fen, comment] of this.#comments) {\n\t\t\tresult.push({ fen, comment });\n\t\t}\n\t\treturn result;\n\t}\n\n\tremoveComments() {\n\t\tconst comments = this.getComments();\n\t\tthis.#comments.clear();\n\t\treturn comments;\n\t}\n\n\tvalidateFen(fen: string) {\n\t\treturn validateFen(fen);\n\t}\n}\n","const inverseMap = <T extends Record<string, string | number | symbol>>(\n\tmap: T\n): Record<T[keyof T], keyof T> =>\n\tObject.entries(map).reduce(\n\t\t(acc, [key, value]) => ({ ...acc, [value]: key }),\n\t\t{} as Record<T[keyof T], keyof T>\n\t);\n\nexport type Board = (Piece | null)[][][];\nexport type Piece = {\n\tsquare: string;\n\ttier: number;\n\ttype: PieceType;\n\tcolor: Color;\n\tid?: string;\n};\nexport type HandPiece = {\n\ttype: PieceType;\n\tcolor: Color;\n\tcount: number;\n\tid?: string;\n};\n\nexport type Move = {\n\tcolor: Color;\n\tpiece: PieceType;\n\tfrom?: string;\n\tto: string;\n\tsan: string;\n\tbefore: string;\n\tafter: string;\n\ttype: 'route' | 'capture' | 'tsuke' | 'betray' | 'arata';\n\tdraftFinished?: boolean;\n\tcaptured?: Piece[];\n};\n\nexport type SetupMode = 'intro' | 'beginner' | 'intermediate' | 'advanced';\nexport const setupModeToCode: Record<SetupMode, number> = {\n\tintro: 0,\n\tbeginner: 1,\n\tintermediate: 2,\n\tadvanced: 3,\n};\nexport const setupCodeToMode = inverseMap(setupModeToCode);\n\nexport const WHITE = 'w';\nexport const BLACK = 'b';\n\nexport const TSUKE = '付';\nexport const TAKE = '取';\nexport const BETRAY = '返';\nexport const ARATA = '新';\n\nexport const MARSHAL = '帥';\nexport const GENERAL = '大';\nexport const LIEUTENANT_GENERAL = '中';\nexport const MAJOR_GENERAL = '小';\nexport const WARRIOR = '侍';\nexport const LANCER = '槍';\nexport const RIDER = '馬';\nexport const SPY = '忍';\nexport const FORTRESS = '砦';\nexport const SOLDIER = '兵';\nexport const CANNON = '砲';\nexport const ARCHER = '弓';\nexport const MUSKETEER = '筒';\nexport const TACTICIAN = '謀';\n\nexport const SQUARES = Array.from({ length: 9 }, (_, x) => x + 1).flatMap((x) =>\n\tArray.from({ length: 9 }, (_, y) => `${x}-${9 - y}`)\n);\n\nexport type Color = 'b' | 'w';\nexport type PieceType =\n\t| '帥'\n\t| '大'\n\t| '中'\n\t| '小'\n\t| '侍'\n\t| '槍'\n\t| '馬'\n\t| '忍'\n\t| '砦'\n\t| '兵'\n\t| '砲'\n\t| '弓'\n\t| '筒'\n\t| '謀';\n\nexport type PieceCode =\n\t| 'm'\n\t| 'g'\n\t| 'i'\n\t| 'j'\n\t| 'w'\n\t| 'n'\n\t| 'r'\n\t| 's'\n\t| 'f'\n\t| 'd'\n\t| 'c'\n\t| 'a'\n\t| 'k'\n\t| 't';\n\nexport type Name =\n\t| 'marshal'\n\t| 'general'\n\t| 'lieutenant_general'\n\t| 'major_general'\n\t| 'warrior'\n\t| 'lancer'\n\t| 'rider'\n\t| 'spy'\n\t| 'fortress'\n\t| 'soldier'\n\t| 'cannon'\n\t| 'archer'\n\t| 'musketeer'\n\t| 'tactician';\n\nexport const piece: Record<Name, PieceType> = {\n\tmarshal: '帥',\n\tgeneral: '大',\n\tlieutenant_general: '中',\n\tmajor_general: '小',\n\twarrior: '侍',\n\tlancer: '槍',\n\trider: '馬',\n\tspy: '忍',\n\tfortress: '砦',\n\tsoldier: '兵',\n\tcannon: '砲',\n\tarcher: '弓',\n\tmusketeer: '筒',\n\ttactician: '謀',\n};\n\nexport const symbolToName = inverseMap(piece);\n\nexport const pieceToFenCode: Record<Name, PieceCode> = {\n\tmarshal: 'm',\n\tgeneral: 'g',\n\tlieutenant_general: 'i',\n\tmajor_general: 'j',\n\twarrior: 'w',\n\tlancer: 'n',\n\trider: 'r',\n\tspy: 's',\n\tfortress: 'f',\n\tsoldier: 'd',\n\tcannon: 'c',\n\tarcher: 'a',\n\tmusketeer: 'k',\n\ttactician: 't',\n};\n\nexport const fenCodeToPiece = inverseMap(pieceToFenCode);\n\nexport const createPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\t[y, x, z]: [number, number, number]\n): Piece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\tsquare: `${y}-${x}`,\n\t\ttier: z,\n\t\ttype: piece[name],\n\t\tcolor,\n\t};\n};\n\nexport const createHandPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\tcount: number\n): HandPiece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\ttype: piece[name],\n\t\tcount,\n\t\tcolor,\n\t};\n};\n\nexport const CANONICAL_NAMES: Record<PieceType, string> = {\n\t帥: 'sui',\n\t大: 'taishou',\n\t中: 'chuujou',\n\t小: 'shoushou',\n\t侍: 'samurai',\n\t槍: 'yari',\n\t馬: 'kiba',\n\t忍: 'shinobi',\n\t砦: 'toride',\n\t兵: 'hyou',\n\t砲: 'oodzutsu',\n\t弓: 'yumi',\n\t筒: 'tsutsu',\n\t謀: 'boushou',\n};\n\nexport const ENGLISH_NAMES: Record<PieceType, string> = {\n\t帥: 'marshal',\n\t大: 'general',\n\t中: 'lieutenant general',\n\t小: 'major general',\n\t侍: 'warrior',\n\t槍: 'lancer',\n\t馬: 'rider',\n\t忍: 'spy',\n\t砦: 'fortress',\n\t兵: 'soldier',\n\t砲: 'cannon',\n\t弓: 'archer',\n\t筒: 'musketeer',\n\t謀: 'tactician',\n};\n\nexport const FEN_CODES: Record<PieceType, string> = {\n\t帥: 'm',\n\t大: 'g',\n\t中: 'i',\n\t小: 'j',\n\t侍: 'w',\n\t槍: 'n',\n\t馬: 'r',\n\t忍: 's',\n\t砦: 'f',\n\t兵: 'd',\n\t砲: 'c',\n\t弓: 'a',\n\t筒: 'k',\n\t謀: 't',\n};\n\nexport function updateHand(\n\tpieces: Piece[],\n\thand: HandPiece[],\n\toppositeColor = false\n): HandPiece[] {\n\tpieces.forEach((p) => {\n\t\tconst c = oppositeColor ? (p.color === 'b' ? 'w' : 'b') : p.color;\n\t\tconst hp = hand.find((h) => h.type === p.type && h.color === c);\n\t\tconst hpi = hand.findIndex((h) => h.type === p.type && h.color === c);\n\n\t\tif (hp) {\n\t\t\thp.count--;\n\t\t\tif (hp.count === 0) hand.splice(hpi, 1);\n\t\t}\n\t});\n\n\treturn hand;\n}\n\nexport function convert(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tboard[rank - 1][9 - file] = tower.map((piece) => {\n\t\tconst p = pieces.find((p) => JSON.stringify(p) === JSON.stringify(piece));\n\t\tif (p) {\n\t\t\tpiece.color = piece.color === 'b' ? 'w' : 'b';\n\t\t}\n\t\treturn piece;\n\t});\n}\n\nexport function remove(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tconst newTower = tower.filter(\n\t\t(piece) => !pieces.some((p) => JSON.stringify(p) === JSON.stringify(piece))\n\t);\n\n\tif (newTower.length === 0) board[rank - 1][9 - file] = [null];\n\telse board[rank - 1][9 - file] = newTower;\n}\n\nexport function removeTop(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\ttower.pop();\n\tif (tower.length === 0) board[rank - 1][9 - file] = [null];\n}\n\nexport function put(piece: Piece, board: (Piece | null)[][][]) {\n\tconst [rank, file] = piece.square.split('-').map(Number);\n\tconst occupied = board[rank - 1][9 - file];\n\n\tif (!occupied[0]) board[rank - 1][9 - file] = [piece];\n\telse board[rank - 1][9 - file].push(piece);\n}\n\nexport function getTop(square: string, board: (Piece | null)[][][]) {\n\tconst tower = get(square, board);\n\treturn tower ? tower.at(-1)! : undefined;\n}\n\nexport function get(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return undefined;\n\n\tconst s = board[rank - 1][9 - file];\n\tif (!s[0]) return undefined;\n\n\treturn s as Piece[];\n}\n\nexport function isGameOver(board: (Piece | null)[][][]) {\n\tconst marshal = board\n\t\t.flat()\n\t\t.flat()\n\t\t.filter((p) => p?.type === '帥');\n\treturn marshal.length !== 2;\n}\n","// Forsyth–Edwards Notation (FEN) Parser and Serializer for Gungi games.\n// Read more about FEN for chess: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation\n//\n// Gungi FEN will have\n// 1. Piece placement data:\n// Each rank is described, starting with rank 1 and ending with rank 9, with a '/' between each one; within each rank,\n// the contents of the squares are described from file 9 to file 1; within each square the tower is described\n// from bottom to top (towers of 2 or higher are surrounded with a '|' with ':' in between pices).\n// Each pieces is represented by a single character from the standard English names\n//\n// 帥 marshal = m\n// 大 general = g\n// 中 lieutenant_general = i\n// 小 major_general = j\n// 侍 warrior = w\n// 槍 lancer = n\n// 馬 rider = r\n// 忍 spy = s\n// 砦 fortress = f\n// 兵 soldier = d\n// 砲 cannon = c\n// 弓 archer = a\n// 筒 musketeer = k\n// 謀 tactician = t\n//\n// Black pieces are designated using lowercase (\"mgijwnrsfdcakt\"),\n// while white pieces use uppercase (\"MGIJWNRSFDCAKT\")\n//\n// A set of one or more consecutive empty squares within a rank is denoted by a digit from \"1\" to \"9\", corresponding to the number of squares.\n// 2: Hand piece data:\n// Each piece in hand is represented by a single character (see above) followed by the number of that piece in hand (1-9);\n// white's hand piecs come first followed by black's separated by a '/'. if a player has no pieces in hand, it's represented with the character '-'\n// 3: Active player:\n// \"w\" means that White is to move; \"b\" means that Black is to move.\n// 4: Setup mode:\n// \"0\" means intro placement, \"1\" for Beginner, \"2\" for Intermediate, \"3\" for Advanced\n// 5: Drafting availability:\n// If neither side has the ability to draft, this field uses the character \"-\". Otherwise, this field contains one or more letters: \"w\" if White can draft and 'b' if Black can draft\n// 6: Full move number:\n// The number of the full moves. It starts at 1 and is incremented after Black's move.\n//\n// Examples\n//\n// FEN for the starting position of a beginner game of gungi:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1\"\n// and after the move 1.大(6-9-1)(5-8-2)付:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 b 1 - 1\"\n// and then after 1...槍(5-2-1)(4-3-2)付:\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 2\"\n// and then after 2.新忍(3-8-2)付\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1|A:S|R1/4MI3 J2N2R1D1/j2n2s1r1d1 b 1 - 2\"\n\nimport {\n\tBoard,\n\tColor,\n\tcreateHandPieceFromFenCode,\n\tcreatePieceFromFenCode,\n\tHandPiece,\n\tPiece,\n\tPieceCode,\n\tpieceToFenCode,\n\tsetupCodeToMode,\n\tSetupMode,\n\tsetupModeToCode,\n\tsymbolToName,\n} from './utils';\n\nexport const INTRO_POSITION =\n\t'3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1';\nexport const BEGINNER_POSITION =\n\t'3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1';\nexport const INTERMEDIATE_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1';\nexport const ADVANCED_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1';\n\nexport type ParsedFEN = {\n\tboard: Board;\n\thand: HandPiece[];\n\tturn: Color;\n\tmode: SetupMode;\n\tdrafting: Record<Color, boolean>;\n\tmoveNumber: number;\n};\n\nexport function parseFEN(fen: string): ParsedFEN {\n\tconst result = validateFen(fen);\n\tif (!result.ok) throw new Error(`Invalid FEN: ${result.error}`);\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] =\n\t\tfen.split(' ');\n\n\tconst board = placement.split('/').map((rank, y) => {\n\t\treturn rank.split('|').reduce(\n\t\t\t(outeracc, partial) => {\n\t\t\t\tif (partial.includes(':')) {\n\t\t\t\t\tconst tower = partial.split(':').map((piece, z) => {\n\t\t\t\t\t\treturn createPieceFromFenCode(\n\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length, z + 1]\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\touteracc.push(tower);\n\t\t\t\t} else {\n\t\t\t\t\tconst partialPieces = partial\n\t\t\t\t\t\t.split('')\n\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t(acc, piece) => {\n\t\t\t\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\t\t\t\tacc = acc.concat(Array(+piece).fill(null));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tacc.push(\n\t\t\t\t\t\t\t\t\t\tcreatePieceFromFenCode(\n\t\t\t\t\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length - acc.length, 1]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t[] as (Piece | null)[]\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.map((square) => [square]);\n\t\t\t\t\touteracc = outeracc.concat(partialPieces);\n\t\t\t\t}\n\n\t\t\t\treturn outeracc;\n\t\t\t},\n\t\t\t[] as (Piece | null)[][]\n\t\t);\n\t});\n\n\tconst hand = handpieces.split('/').flatMap((playerHand) => {\n\t\tconst pieces: HandPiece[] = [];\n\t\tif (playerHand !== '-') {\n\t\t\tfor (let i = 0; i < playerHand.length; i += 2) {\n\t\t\t\tconst piece = playerHand[i] as PieceCode | Uppercase<PieceCode>;\n\t\t\t\tconst count = +playerHand[i + 1];\n\t\t\t\tpieces.push(createHandPieceFromFenCode(piece, count));\n\t\t\t}\n\t\t}\n\t\treturn pieces;\n\t});\n\n\treturn {\n\t\tboard,\n\t\thand,\n\t\tturn: turn as Color,\n\t\tmode: setupCodeToMode[+mode],\n\t\tdrafting: {\n\t\t\tw: drafting.includes('w'),\n\t\t\tb: drafting.includes('b'),\n\t\t},\n\t\tmoveNumber: +moveNumber,\n\t};\n}\n\nexport function encodeFEN(fen: ParsedFEN) {\n\tlet placement = '';\n\tlet emptyCount = 0;\n\n\tfor (let file = 0; file < 9; file++) {\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tconst square = fen.board[file][rank];\n\t\t\tif (!square[0]) {\n\t\t\t\temptyCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (emptyCount) {\n\t\t\t\tplacement += emptyCount;\n\t\t\t\temptyCount = 0;\n\t\t\t}\n\n\t\t\tif (square.length > 1) {\n\t\t\t\tplacement +=\n\t\t\t\t\t'|' +\n\t\t\t\t\tsquare\n\t\t\t\t\t\t.map((p) => {\n\t\t\t\t\t\t\tif (!p) return null;\n\t\t\t\t\t\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\t\t\t\t\t\treturn p.color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(':') +\n\t\t\t\t\t'|';\n\t\t\t} else {\n\t\t\t\tconst { type, color } = square[0];\n\t\t\t\tconst piece = pieceToFenCode[symbolToName[type]];\n\t\t\t\tplacement += color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t}\n\t\t}\n\n\t\tplacement += emptyCount ? `${emptyCount}/` : '/';\n\t\temptyCount = 0;\n\t}\n\n\tlet hand = '';\n\tconst whiteHand = fen.hand.filter((p) => p.color === 'w');\n\tconst blackHand = fen.hand.filter((p) => p.color === 'b');\n\twhiteHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += whiteHand.length > 0 ? '/' : '-/';\n\tblackHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += blackHand.length > 0 ? '' : '-';\n\n\tconst draftKeys = Object.keys(fen.drafting).filter(\n\t\t(key) => fen.drafting[key as Color]\n\t);\n\n\treturn `${placement.slice(0, -1)} ${hand} ${fen.turn} ${setupModeToCode[fen.mode]} ${draftKeys.length > 0 ? draftKeys.join('') : '-'} ${fen.moveNumber}`;\n}\n\ntype FenValidationResult = {\n\tok: boolean;\n\terror?: string;\n};\n\nexport function validateFen(fen: string): FenValidationResult {\n\tconst parts = fen.split(' ');\n\tif (parts.length !== 6)\n\t\treturn { ok: false, error: `expected 6 fields, received ${parts.length}` };\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] = parts;\n\tconst ranks = placement.split('/');\n\tif (ranks.length !== 9)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `1st field (piece positions) is invalid [expected 9 ranks, received ${ranks.length}]`,\n\t\t};\n\n\tfor (let i = 0; i < ranks.length; i++) {\n\t\tconst rank = ranks[i];\n\t\tconst fileParts = rank.split('|');\n\t\tlet fileCount = 0;\n\n\t\tfor (let k = 0; k < fileParts.length; k++) {\n\t\t\tconst filePart = fileParts[k];\n\t\t\tif (filePart.includes(':')) {\n\t\t\t\tfileCount++;\n\t\t\t\tconst towerPieces = filePart.split(':');\n\t\t\t\tif (towerPieces.length > 3) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [tower size] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!towerPieces.every((p) => 'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(p))\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst pieces = filePart.split('');\n\n\t\t\t\tfor (let l = 0; l < pieces.length; l++) {\n\t\t\t\t\tconst piece = pieces[l];\n\n\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\tfileCount += +piece;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfileCount++;\n\t\t\t\t\t\tif (!'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(piece)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (fileCount !== 9) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `1st field (piece positions) is invalid [expected 9 squares, received ${fileCount}] in rank: ${i + 1}`,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst hands = handpieces.split('/');\n\tif (hands.length !== 2)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [expected 2 hands, received ${hands.length}]`,\n\t\t};\n\n\tconst [whiteHand, blackHand] = hands;\n\tif (\n\t\t(whiteHand.length === 1 && whiteHand !== '-') ||\n\t\t(blackHand.length === 1 && blackHand !== '-')\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t};\n\t}\n\n\tif (\n\t\t(whiteHand.length > 1 && whiteHand.length % 2 !== 0) ||\n\t\t(blackHand.length > 1 && blackHand.length % 2 !== 0)\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece count]`,\n\t\t};\n\t}\n\n\tif (whiteHand.length > 1) {\n\t\tfor (let i = 0; i < whiteHand.length; i += 2) {\n\t\t\tif (!'MGIJWNRSFDCAKT'.includes(whiteHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+whiteHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (blackHand.length > 1) {\n\t\tfor (let i = 0; i < blackHand.length; i += 2) {\n\t\t\tif (!'mgijwnrsfdcakt'.includes(blackHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+blackHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (turn !== 'w' && turn !== 'b') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `3rd field (active player) is invalid [expected 'w' or 'b', received ${turn}]`,\n\t\t};\n\t}\n\n\tif (mode.length !== 1 || !'0123'.includes(mode)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${mode}]`,\n\t\t};\n\t}\n\n\tif (drafting !== '-' && !'wb'.includes(drafting)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${drafting}]`,\n\t\t};\n\t}\n\n\tif (!Number.isInteger(+moveNumber)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `6th field (full move number) is invalid [expected an integer, received ${moveNumber}]`,\n\t\t};\n\t}\n\n\treturn { ok: true };\n}\n","import type { Board, Color, HandPiece, Move, Piece, PieceType } from './utils';\nimport { encodeFEN, parseFEN } from './fen';\nimport {\n\tconvert,\n\tget,\n\tgetTop,\n\tpiece as pieceType,\n\tput,\n\tremove,\n\tremoveTop,\n\tSQUARES,\n\tupdateHand,\n} from './utils';\n\nexport const dirs = [\n\t[-1, 1],\n\t[-1, 0],\n\t[-1, -1],\n\t[0, 1],\n\t[0, -1],\n\t[1, 1],\n\t[1, 0],\n\t[1, -1],\n];\n\nexport const pieceProbes: Record<PieceType, (number[] | number)[]> = {\n\t帥: [1, 1, 1, 1, 1, 1, 1, 1],\n\t大: [1, Infinity, 1, Infinity, Infinity, 1, Infinity, 1],\n\t中: [Infinity, 1, Infinity, 1, 1, Infinity, 1, Infinity],\n\t小: [1, 1, 1, 1, 1, 0, 1, 0],\n\t侍: [1, 1, 1, 0, 0, 0, 1, 0],\n\t槍: [1, [1, 2], 1, 0, 0, 0, 1, 0],\n\t馬: [0, [1, 2], 0, 1, 1, 0, [1, 2], 0],\n\t忍: [[1, 2], 0, [1, 2], 0, 0, [1, 2], 0, [1, 2]],\n\t砦: [0, 1, 0, 1, 1, 1, 0, 1],\n\t兵: [0, 1, 0, 0, 0, 0, 1, 0],\n\t砲: [0, 3, 0, 1, 1, 0, 1, 0],\n\t弓: [2, 2, 2, 0, 0, 0, 1, 0],\n\t筒: [0, 2, 0, 0, 0, 1, 0, 1],\n\t謀: [1, 0, 1, 0, 0, 0, 1, 0],\n};\n\nfunction getAvailableSquares(\n\tdir: [number, number],\n\tstart: [number, number],\n\torigin: [number, number],\n\tlength: number,\n\tboard: (Piece | null)[][][]\n) {\n\tconst [y, x] = start;\n\tconst [py, px] = origin;\n\tconst [dy, dx] = dir;\n\tconst originPiece = getTop(`${py}-${px}`, board)!;\n\n\tif (\n\t\toriginPiece.type === pieceType.archer &&\n\t\tMath.abs(dy) === 1 &&\n\t\tMath.abs(dx) === 1\n\t) {\n\t\tconst wing = getTop(`${py + dy}-${px + dx}`, board);\n\t\tif (wing && wing.tier > originPiece.tier) {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tconst availableSquares: string[] = [];\n\n\t// first probe in the reverse direction until origin is reached to see if there are any pieces in the way\n\tconst reverse = { x, y };\n\twhile (reverse.x !== px || reverse.y !== py) {\n\t\treverse.x -= dx;\n\t\treverse.y -= dy;\n\t\tconst piece = getTop(`${reverse.y}-${reverse.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst side = originPiece.color === 'b' ? -1 : 1;\n\t\tconst below = getTop(`${reverse.y + side}-${reverse.x}`, board);\n\n\t\tif (below && below.square === `${py}-${px}`) break;\n\t}\n\n\t// then probe in the forward direction to see if there are any pieces in the way\n\tconst forward = { x, y };\n\tlet step = 0;\n\twhile (step < length) {\n\t\tif (forward.x < 1 || forward.x > 9 || forward.y < 1 || forward.y > 9) break;\n\n\t\tconst piece = getTop(`${forward.y}-${forward.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) break;\n\n\t\tavailableSquares.push(`${forward.y}-${forward.x}`);\n\n\t\tconst leapPieces = [\n\t\t\tpieceType.cannon,\n\t\t\tpieceType.musketeer,\n\t\t\tpieceType.archer,\n\t\t];\n\t\tif (piece) {\n\t\t\tif (!leapPieces.includes(originPiece.type)) break;\n\n\t\t\tconst movingForward = originPiece.color === 'w' ? dy < 0 : dy > 0;\n\t\t\tif (!movingForward) break;\n\t\t}\n\n\t\tforward.x += dx;\n\t\tforward.y += dy;\n\t\tstep++;\n\t}\n\n\treturn availableSquares;\n}\n\nexport function generateMovesForSquare(square: string, fen: string) {\n\tconst { board, turn, mode, hand } = parseFEN(fen);\n\tconst piece = getTop(square, board);\n\tif (!piece || turn !== piece.color) return [];\n\n\tconst [py, px] = square.split('-').map(Number);\n\n\tconst probes = pieceProbes[piece.type];\n\tconst squares = probes.flatMap((probe, i) => {\n\t\tconst pval = typeof probe === 'number' ? probe : probe[0];\n\t\tconst pcarry = typeof probe === 'number' ? 1 : probe[1];\n\t\tif (pval < 1) return [];\n\n\t\tlet [dy, dx] = dirs[i];\n\t\tif (piece.color === 'b') {\n\t\t\tdy *= -1;\n\t\t\tdx *= -1;\n\t\t}\n\n\t\tconst [y, x] =\n\t\t\tpval === Infinity ? [py + dy, px + dx] : [py + pval * dy, px + dx];\n\t\tconst length = pval === Infinity ? Infinity : piece.tier + pcarry - 1;\n\n\t\treturn getAvailableSquares([dy, dx], [y, x], [py, px], length, board);\n\t});\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst t = get(s, board);\n\n\t\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\t\tconst marshalCanStack = ['advanced', 'intermediate'].includes(mode);\n\n\t\tif (!p || !t) {\n\t\t\tacc.push(createMove(piece, `${s}-1`, fen, 'route'));\n\t\t} else {\n\t\t\t// tsuke\n\t\t\tif (p.tier < maxTier && p.type !== pieceType.marshal) {\n\t\t\t\tif (piece.type !== pieceType.marshal || marshalCanStack) {\n\t\t\t\t\tacc.push(createMove(piece, `${s}-${p.tier + 1}`, fen, 'tsuke'));\n\t\t\t\t}\n\n\t\t\t\t// betrayal\n\t\t\t\tif (piece.type === pieceType.tactician && p.color !== piece.color) {\n\t\t\t\t\tconst enemies = t.filter((p) => p.color !== piece.color);\n\t\t\t\t\tconst playerHand = hand.filter((p) => p.color === piece.color);\n\t\t\t\t\tconst enemyCountMap = enemies.reduce((acc, e) => {\n\t\t\t\t\t\tacc.set(e.type, (acc.get(e.type) ?? 0) + 1);\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, new Map<PieceType, number>());\n\n\t\t\t\t\tconst betrayalOptions = Array.from(enemyCountMap.entries())\n\t\t\t\t\t\t.filter(([type, count]) =>\n\t\t\t\t\t\t\tplayerHand.some((p) => p.type === type && p.count >= count)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.flatMap(([type]) => enemies.filter((e) => e.type === type));\n\n\t\t\t\t\tconst combos = generateCombinations(betrayalOptions);\n\t\t\t\t\tacc.push(\n\t\t\t\t\t\t...combos.map((combo) =>\n\t\t\t\t\t\t\tcreateMove(piece, `${s}-${p.tier + 1}`, fen, 'betray', combo)\n\t\t\t\t\t\t)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// capture\n\t\t\tif (p.color !== piece.color) {\n\t\t\t\tconst newTier = t.filter((p) => p.color === piece.color).length + 1;\n\t\t\t\tconst captured = t.filter((p) => p.color !== piece.color);\n\t\t\t\tacc.push(\n\t\t\t\t\tcreateMove(piece, `${s}-${newTier}`, fen, 'capture', captured)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nexport function generateArata(piece: HandPiece, fen: string) {\n\tconst { board, turn, mode, hand, drafting } = parseFEN(fen);\n\tif (!piece || turn !== piece.color) return [];\n\tconst isMarshalPlaced = !hand.some(\n\t\t(p) => p.type === pieceType.marshal && p.color === piece.color\n\t);\n\tif (!isMarshalPlaced && piece.type !== pieceType.marshal) return [];\n\n\tconst isDraft = drafting.b || drafting.w;\n\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\tlet ranks: number[] = [];\n\tlet maybe: number[] = [];\n\n\t// if in draft can only place within your first 3 ranks, otherwise can placed as far as your deepest piece\n\tif (isDraft) {\n\t\tranks = piece.color === 'w' ? [7, 8, 9] : [1, 2, 3];\n\t} else {\n\t\tconst start = piece.color === 'b' ? 1 : 9;\n\t\tconst end = piece.color === 'b' ? 9 : 1;\n\t\tconst step = piece.color === 'b' ? 1 : -1;\n\t\tfor (\n\t\t\tlet rank = start;\n\t\t\tpiece.color === 'b' ? rank <= end : rank >= end;\n\t\t\trank += step\n\t\t) {\n\t\t\tconst tops = Array.from({ length: 9 }).map((_, i) =>\n\t\t\t\tgetTop(`${rank}-${i + 1}`, board)\n\t\t\t);\n\t\t\tif (tops.some((p) => p && p.color === piece.color)) {\n\t\t\t\tranks.push(...maybe, rank);\n\t\t\t\tmaybe = [];\n\t\t\t} else {\n\t\t\t\tmaybe.push(rank);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst squares = ranks.flatMap((rank) =>\n\t\tArray.from({ length: 9 }, (_, i) => `${rank}-${i + 1}`)\n\t);\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst arata = {\n\t\t\ttype: piece.type,\n\t\t\tcolor: piece.color,\n\t\t\tsquare: s,\n\t\t\ttier: 0,\n\t\t};\n\n\t\t// you can arata an empty square or a tower with your own piece on top\n\t\tif (\n\t\t\t!p ||\n\t\t\t(p.color === arata.color &&\n\t\t\t\tp.tier < maxTier &&\n\t\t\t\tp.type !== pieceType.marshal)\n\t\t) {\n\t\t\tconst t = (p?.tier ?? 0) + 1;\n\t\t\tconst playerHandCount = hand\n\t\t\t\t.filter((h) => h.color === piece.color)\n\t\t\t\t.reduce((sum, h) => sum + h.count, 0);\n\t\t\tconst isLastPiece = playerHandCount === 1;\n\n\t\t\tif (drafting[piece.color]) {\n\t\t\t\t// If only 1 piece left, must end draft - no option to continue\n\t\t\t\tif (!isLastPiece) {\n\t\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\t\t}\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata', [], true));\n\t\t\t} else {\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nfunction createMove(\n\tpiece: Piece,\n\tto: string,\n\tfen: string,\n\ttype: Move['type'],\n\tcaptured?: Piece[],\n\tdraftFinished?: boolean\n) {\n\tconst from = piece.tier !== 0 ? `(${piece.square}-${piece.tier})` : '';\n\tconst toTier = +(to.split('-').at(-1) ?? 0);\n\tconst arata = type === 'arata' ? '新' : '';\n\tconst capture = type === 'capture' ? '取' : '';\n\tconst tsuke =\n\t\ttype === 'tsuke' || (toTier !== 1 && toTier - piece.tier > 0) ? '付' : '';\n\tconst betray =\n\t\ttype === 'betray' ? `返${captured?.map((p) => p.type).join('')}` : '';\n\tconst draftDone = draftFinished ? '終' : '';\n\n\tconst move: Move = {\n\t\tpiece: piece.type,\n\t\tcolor: piece.color,\n\t\tfrom: from.slice(1, -1),\n\t\tto,\n\t\ttype,\n\t\tsan: `${arata}${piece.type}${from}${capture}(${to})${betray || tsuke}${draftDone}`,\n\t\tbefore: fen,\n\t\tafter: '',\n\t\tdraftFinished,\n\t\tcaptured,\n\t};\n\n\tconst { after, gameOverSAN } = makeMove(move, move.before);\n\tmove.after = after;\n\tmove.san += gameOverSAN;\n\n\treturn move;\n}\n\nfunction makeMove(move: Move, fen: string) {\n\tlet { board, hand, mode, turn, drafting, moveNumber } = parseFEN(fen);\n\tconst [rank, file, tier] = move.to.split('-');\n\tconst to = {\n\t\ttype: move.piece,\n\t\tcolor: move.color,\n\t\tsquare: `${rank}-${file}`,\n\t\ttier: +tier,\n\t};\n\n\tif (move.type === 'route' || move.type === 'tsuke') {\n\t\tremoveTop(move.from!, board);\n\t} else if (move.type === 'capture') {\n\t\tremoveTop(move.from!, board);\n\t\tremove(`${rank}-${file}`, move.captured!, board);\n\t} else if (move.type === 'betray') {\n\t\tremoveTop(move.from!, board);\n\t\tconvert(`${rank}-${file}`, move.captured!, board);\n\t\tupdateHand(move.captured!, hand, true);\n\t} else if (move.type === 'arata') {\n\t\tupdateHand([to], hand);\n\t\tif (move.draftFinished) {\n\t\t\tdrafting[move.color] = false;\n\t\t\tif (move.color === 'b') drafting.w = false;\n\t\t}\n\t}\n\n\tput(to, board);\n\n\tif (turn === 'b' && (drafting.w || !drafting.b)) moveNumber++;\n\tif (turn === 'w' && !drafting.b && !drafting.w && move.draftFinished)\n\t\tmoveNumber++;\n\n\tif (drafting.w === drafting.b) {\n\t\tif (!move.draftFinished || turn !== 'w') {\n\t\t\tturn = turn === 'b' ? 'w' : 'b';\n\t\t}\n\t} else {\n\t\tif (!drafting.b && turn === 'b') {\n\t\t\tturn = 'w';\n\t\t} else if (!drafting.w && turn === 'w') {\n\t\t\tturn = 'b';\n\t\t}\n\t}\n\n\tlet gameOverSAN = '';\n\tif (move.captured?.some((p) => p.type === pieceType.marshal))\n\t\tgameOverSAN = '#';\n\n\treturn {\n\t\tafter: encodeFEN({ board, hand, mode, turn, drafting, moveNumber }),\n\t\tgameOverSAN,\n\t};\n}\n\nfunction generateCombinations<T>(items: T[]): T[][] {\n\tconst result: T[][] = [];\n\n\tfunction helper(start: number, currentCombination: T[]) {\n\t\tif (currentCombination.length > 0) {\n\t\t\tresult.push([...currentCombination]);\n\t\t}\n\n\t\tfor (let i = start; i < items.length; i++) {\n\t\t\tcurrentCombination.push(items[i]);\n\t\t\thelper(i + 1, currentCombination);\n\t\t\tcurrentCombination.pop(); // Backtrack\n\t\t}\n\t}\n\n\thelper(0, []);\n\n\treturn result;\n}\n\nfunction getAttackedSquares(square: string, board: Board): string[] {\n\tconst piece = getTop(square, board);\n\tif (!piece) return [];\n\n\tconst [py, px] = square.split('-').map(Number);\n\tconst probes = pieceProbes[piece.type];\n\n\treturn probes.flatMap((probe, i) => {\n\t\tconst pval = typeof probe === 'number' ? probe : probe[0];\n\t\tconst pcarry = typeof probe === 'number' ? 1 : probe[1];\n\t\tif (pval < 1) return [];\n\n\t\tlet [dy, dx] = dirs[i];\n\t\tif (piece.color === 'b') {\n\t\t\tdy *= -1;\n\t\t\tdx *= -1;\n\t\t}\n\n\t\tconst [y, x] =\n\t\t\tpval === Infinity ? [py + dy, px + dx] : [py + pval * dy, px + dx];\n\t\tconst length = pval === Infinity ? Infinity : piece.tier + pcarry - 1;\n\n\t\treturn getAvailableSquares([dy, dx], [y, x], [py, px], length, board);\n\t});\n}\n\nexport function isSquareAttacked(\n\tsquare: string,\n\tbyColor: Color,\n\tboard: Board\n): boolean {\n\tconst [targetRank, targetFile] = square.split('-').map(Number);\n\tconst targetSquare = `${targetRank}-${targetFile}`;\n\n\tfor (const sq of SQUARES) {\n\t\tconst piece = getTop(sq, board);\n\t\tif (!piece || piece.color !== byColor) continue;\n\n\t\tconst attackedSquares = getAttackedSquares(sq, board);\n\t\tif (attackedSquares.some((s) => s.startsWith(targetSquare))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nexport function inCheck(color: Color, fen: string): boolean {\n\tconst { board } = parseFEN(fen);\n\tconst oppositeColor = color === 'w' ? 'b' : 'w';\n\n\t// Find marshal position\n\tfor (const sq of SQUARES) {\n\t\tconst piece = getTop(sq, board);\n\t\tif (piece?.type === pieceType.marshal && piece.color === color) {\n\t\t\treturn isSquareAttacked(sq, oppositeColor, board);\n\t\t}\n\t}\n\n\treturn false; // Marshal not found (already captured)\n}\n\nexport function wouldBeInCheckAfterMove(move: Move): boolean {\n\treturn inCheck(move.color, move.after);\n}\n","// Portable Game Notation (PGN) parser and serializer for Gungi games.\n// Read more about PGN for chess: https://en.wikipedia.org/wiki/Portable_Game_Notation\n//\n// Movetext\n// The movetext describes the actual moves of the game. This includes move number indicators (numbers followed by either one or three periods;\n// one if the next move is White's move, three if the next move is Black's move) and movetext in Standard Algebraic Notation (SAN).\n//\n// For most moves the SAN consists of the kanji for the piece, the coordinate tuple of the square the piece moved from, an 取 if there is a capture, and the tuple of the final square it moved to.\n// The kanji are 帥 (marshal), 大 (general), 中 (lieutenant general), 小 (major general), 侍 (warrior), 槍 (lancer), 馬 (rider), 忍 (spy), 砦 (fortress), 兵 (soldier),\n// 砲 (cannon), 弓 (archer), 筒 (musketeer), and 謀 (tactician).\n//\n// The algebraic name of any square is a little different from algebraic chess notation; from white's perspective,\n// the rightmost square farthest from white is (1-1-1), the leftmost square farthest from the white is (9-1-1), and the leftmost (from white's perspective) square closest to white's side is (9-9-1).\n// the coordinates are given in the from (rank-file-tier) where tier can be (1, 2, or 3) depending on the height of the tower. If performing a stack ツケ (tsuke) then 付 is appended.\n// Thus 中(4-9-1)(5-8-2)付 denotes the major general stacking on a piece, and if we wanted to take the piece instead, we would write 中(4-9-1)取(5-8-1).\n//\n// Omitting the from square and prepending 新 to the piece indicates arata - a new piece is being placed on the board (e.g. 新小(8-7-1)) . In non-beginner games,\n// all the first moves are of this form until both players say they are finished placing pieces;\n// If a player is finished, after they place their final piece in their setup, 終 is appended (e.g. 新兵(4-2-1)終).\n//\n// If the tactician performs a ツケ (tsuke), they have the option to convert some or all of the enemy pieces in the tower.\n// (only if they have the piece in their hand they capture the enemy piece and replaces it with their own); this is denoted by a '返'\n// after the last coordinate followed by the piece(s) they are converting (in no particular order). Thus 謀(4-9-2)(5-8-3)返中槍 denotes\n// the tactician converting a major general and a lancer in a tower.\n//\n// If the move captures the enemy marshal, \"勝\" is appended and the game is over.\n// If the move is a fourfold repetition, \"停\" is appended and the game is a draw.\n\nimport { parseFEN } from './fen';\nimport { Move } from './utils';\n\nexport type PGNOptions = {\n\tmaxWidth?: number;\n\tnewline?: string;\n\twithComments?: boolean;\n};\n\ntype InternalPGNOptions = PGNOptions & {\n\tcomments?: Map<string, string>;\n};\n\nexport function encodePGN(history: Move[], opts?: InternalPGNOptions) {\n\tconst maxWidth = opts?.maxWidth ?? 6;\n\tconst newline = opts?.newline ?? '\\n';\n\tconst withComments = opts?.withComments ?? false;\n\tconst comments = opts?.comments ?? new Map<string, string>();\n\n\tlet pgn = '';\n\tlet prev = 0;\n\thistory.forEach((move, i) => {\n\t\tconst state = parseFEN(move.before);\n\t\tif (state.moveNumber !== prev) {\n\t\t\tconst indicator = move.color === 'w' ? '.' : '...';\n\t\t\tpgn += `${state.moveNumber}${indicator} `;\n\t\t\tprev = state.moveNumber;\n\t\t}\n\n\t\tpgn += `${move.san} `;\n\n\t\tif (withComments && comments.has(move.after)) {\n\t\t\tpgn += `{${comments.get(move.after)}} `;\n\t\t}\n\n\t\tif ((i + 1) % maxWidth === 0) {\n\t\t\tpgn += newline;\n\t\t}\n\t});\n\n\treturn pgn.replaceAll(' ', ' ').trim();\n}\n\nexport type ParsedPGN = {\n\tmoves: string[];\n\tcomments: Map<number, string>;\n};\n\nexport function parsePGN(\n\tpgn: string,\n\topts?: Pick<PGNOptions, 'newline'>\n): ParsedPGN {\n\tconst newline = opts?.newline ?? '\\n';\n\tconst comments = new Map<number, string>();\n\tconst moves: string[] = [];\n\n\tlet normalized = pgn\n\t\t.split(newline)\n\t\t.join(' ')\n\t\t.replace(/\\d+\\.+/g, '')\n\t\t.trim();\n\n\twhile (normalized.length > 0) {\n\t\tnormalized = normalized.trim();\n\t\tif (normalized.length === 0) break;\n\n\t\tif (normalized.startsWith('{')) {\n\t\t\tconst endIdx = normalized.indexOf('}');\n\t\t\tif (endIdx !== -1) {\n\t\t\t\tconst comment = normalized.slice(1, endIdx).trim();\n\t\t\t\tif (moves.length > 0 && comment) {\n\t\t\t\t\tcomments.set(moves.length - 1, comment);\n\t\t\t\t}\n\t\t\t\tnormalized = normalized.slice(endIdx + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tconst match = normalized.match(/^(\\S+)/);\n\t\tif (match) {\n\t\t\tconst move = match[1];\n\t\t\tif (move && !move.startsWith('{')) {\n\t\t\t\tmoves.push(move);\n\t\t\t}\n\t\t\tnormalized = normalized.slice(move.length);\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn { moves, comments };\n}\n","import { ParsedFEN, parseFEN } from './fen';\nimport {\n\tBoard,\n\tColor,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tsetupModeToCode,\n} from './utils';\n\n/**\n * Assigns piece IDs with proper stability across moves\n * Uses explicit move tracking for maximum reliability\n */\nexport function assignPieceIdsWithState(\n\tcurrentFen: string,\n\tpreviousState?: ParsedFEN | null,\n\tmove?: Move | null\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousState) {\n\t\treturn assignCanonicalIds(currentState);\n\t}\n\n\tif (move) {\n\t\treturn assignIdsWithExplicitMove(currentState, previousState, move);\n\t}\n\n\t// Fallback: try to preserve IDs based on position matching\n\treturn assignIdsWithPositionMatching(currentState, previousState);\n}\n\n/**\n * Assigns IDs canonically for initial state\n * Format: mode-color-type-number (e.g., \"1-w-兵-1\")\n */\nfunction assignCanonicalIds(state: ParsedFEN): ParsedFEN {\n\tconst result = cloneState(state);\n\tconst modeCode = setupModeToCode[state.mode];\n\n\t// Group all pieces by type and color\n\tconst pieceGroups = groupPiecesByTypeAndColor(result);\n\n\t// Assign IDs sequentially within each group\n\tObject.entries(pieceGroups).forEach(([key, pieces]) => {\n\t\tconst [color, type] = key.split('|') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces by position, then hand pieces\n\t\tconst sortedPieces = sortPiecesCanonically(pieces);\n\n\t\tsortedPieces.forEach((piece, index) => {\n\t\t\tpiece.id = `${modeCode}-${color}-${type}-${index + 1}`;\n\t\t});\n\t});\n\n\treturn result;\n}\n\n/**\n * Assigns IDs using explicit move tracking - the core robust method\n */\nfunction assignIdsWithExplicitMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): ParsedFEN {\n\tconst result = cloneStateWithoutIds(currentState);\n\tconst modeCode = setupModeToCode[currentState.mode];\n\n\t// Step 1: Identify exactly which pieces are affected by this move\n\tconst affectedPieces = identifyAffectedPieces(move);\n\n\t// Step 2: Preserve IDs for all NON-affected pieces\n\tpreserveUnaffectedPieceIds(result, previousState, affectedPieces);\n\n\t// Step 3: Handle affected pieces explicitly based on move type\n\thandleAffectedPieces(result, previousState, move, modeCode);\n\n\t// Step 4: Assign IDs to any remaining pieces without IDs\n\tassignMissingIds(result, modeCode);\n\n\treturn result;\n}\n\n/**\n * Identify exactly which pieces are affected by a move\n */\nfunction identifyAffectedPieces(move: Move): {\n\tmovingPiece?: { square: string; tier: number; type: PieceType; color: Color };\n\tcapturedPieces: Array<{\n\t\tsquare: string;\n\t\ttier: number;\n\t\ttype: PieceType;\n\t\tcolor: Color;\n\t}>;\n\tplacementSquare?: string;\n\thandPieceTypes: Array<{ color: Color; type: PieceType }>;\n} {\n\tconst capturedPieces: Array<{\n\t\tsquare: string;\n\t\ttier: number;\n\t\ttype: PieceType;\n\t\tcolor: Color;\n\t}> = [];\n\tconst handPieceTypes: Array<{ color: Color; type: PieceType }> = [];\n\tlet movingPiece:\n\t\t| { square: string; tier: number; type: PieceType; color: Color }\n\t\t| undefined;\n\tlet placementSquare: string | undefined;\n\n\tswitch (move.type) {\n\t\tcase 'route':\n\t\tcase 'tsuke':\n\t\t\t// Track the specific moving piece\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'capture':\n\t\t\t// Track moving piece and captured pieces\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Track captured pieces\n\t\t\tif (move.captured) {\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\tcapturedPieces.push({\n\t\t\t\t\t\tsquare: move.to,\n\t\t\t\t\t\ttier: capturedPiece.tier,\n\t\t\t\t\t\ttype: capturedPiece.type,\n\t\t\t\t\t\tcolor: capturedPiece.color,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase 'arata':\n\t\t\t// Hand piece affected + placement square\n\t\t\thandPieceTypes.push({ color: move.color, type: move.piece });\n\t\t\tplacementSquare = move.to;\n\t\t\tbreak;\n\n\t\tcase 'betray':\n\t\t\t// Track moving tactician and captured/converted pieces\n\t\t\tif (move.from) {\n\t\t\t\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\t\t\t\tmovingPiece = {\n\t\t\t\t\tsquare: `${fromRank}-${fromFile}`,\n\t\t\t\t\ttier: fromTier,\n\t\t\t\t\ttype: move.piece,\n\t\t\t\t\tcolor: move.color,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Track captured pieces\n\t\t\tif (move.captured) {\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\tcapturedPieces.push({\n\t\t\t\t\t\tsquare: move.to,\n\t\t\t\t\t\ttier: capturedPiece.tier,\n\t\t\t\t\t\ttype: capturedPiece.type,\n\t\t\t\t\t\tcolor: capturedPiece.color,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\t// Hand pieces for converted pieces\n\t\t\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\t\t\thandPieceTypes.push({ color: move.color, type: capturedPiece.type });\n\t\t\t\t});\n\t\t\t}\n\t\t\tbreak;\n\t}\n\n\treturn { movingPiece, capturedPieces, placementSquare, handPieceTypes };\n}\n\n/**\n * Preserve IDs for all pieces NOT affected by the move\n */\nfunction preserveUnaffectedPieceIds(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\taffectedPieces: {\n\t\tmovingPiece?: {\n\t\t\tsquare: string;\n\t\t\ttier: number;\n\t\t\ttype: PieceType;\n\t\t\tcolor: Color;\n\t\t};\n\t\tcapturedPieces: Array<{\n\t\t\tsquare: string;\n\t\t\ttier: number;\n\t\t\ttype: PieceType;\n\t\t\tcolor: Color;\n\t\t}>;\n\t\tplacementSquare?: string;\n\t\thandPieceTypes: Array<{ color: Color; type: PieceType }>;\n\t}\n): void {\n\t// Helper function to check if a specific piece is affected\n\tconst isPieceAffected = (\n\t\tsquare: string,\n\t\ttier: number,\n\t\ttype: PieceType,\n\t\tcolor: Color\n\t): boolean => {\n\t\t// Check if it's the moving piece\n\t\tif (\n\t\t\taffectedPieces.movingPiece &&\n\t\t\taffectedPieces.movingPiece.square === square &&\n\t\t\taffectedPieces.movingPiece.tier === tier &&\n\t\t\taffectedPieces.movingPiece.type === type &&\n\t\t\taffectedPieces.movingPiece.color === color\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if it's a captured piece\n\t\tif (\n\t\t\taffectedPieces.capturedPieces.some(\n\t\t\t\t(captured) =>\n\t\t\t\t\tcaptured.square === square &&\n\t\t\t\t\tcaptured.tier === tier &&\n\t\t\t\t\tcaptured.type === type &&\n\t\t\t\t\tcaptured.color === color\n\t\t\t)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\t// Check if it's at the placement square (for arata moves)\n\t\tif (affectedPieces.placementSquare === square) {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t};\n\n\t// Preserve board piece IDs (skip only specifically affected pieces)\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst square = `${rank + 1}-${9 - file}`;\n\t\t\tconst currentTower = currentState.board[rank][file];\n\t\t\tconst previousTower = previousState.board[rank][file];\n\n\t\t\t// Check each piece in the tower individually\n\t\t\tfor (\n\t\t\t\tlet tier = 0;\n\t\t\t\ttier < Math.min(currentTower.length, previousTower.length);\n\t\t\t\ttier++\n\t\t\t) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tconst previousPiece = previousTower[tier];\n\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\tpreviousPiece &&\n\t\t\t\t\tcurrentPiece.type === previousPiece.type &&\n\t\t\t\t\tcurrentPiece.color === previousPiece.color &&\n\t\t\t\t\tpreviousPiece.id\n\t\t\t\t) {\n\t\t\t\t\t// Only preserve ID if this specific piece was not affected\n\t\t\t\t\tif (\n\t\t\t\t\t\t!isPieceAffected(\n\t\t\t\t\t\t\tsquare,\n\t\t\t\t\t\t\ttier + 1,\n\t\t\t\t\t\t\tcurrentPiece.type,\n\t\t\t\t\t\t\tcurrentPiece.color\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcurrentPiece.id = previousPiece.id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Preserve hand piece IDs (skip affected types)\n\tcurrentState.hand.forEach((currentHandPiece) => {\n\t\tconst isAffected = affectedPieces.handPieceTypes.some(\n\t\t\t(affected) =>\n\t\t\t\taffected.color === currentHandPiece.color &&\n\t\t\t\taffected.type === currentHandPiece.type\n\t\t);\n\n\t\tif (!isAffected) {\n\t\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t\t(hp) =>\n\t\t\t\t\thp.type === currentHandPiece.type &&\n\t\t\t\t\thp.color === currentHandPiece.color\n\t\t\t);\n\t\t\tif (previousHandPiece?.id) {\n\t\t\t\tcurrentHandPiece.id = previousHandPiece.id;\n\t\t\t}\n\t\t}\n\t});\n}\n\n/**\n * Handle pieces that are affected by the move\n */\nfunction handleAffectedPieces(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\tswitch (move.type) {\n\t\tcase 'route':\n\t\tcase 'tsuke':\n\t\t\thandleRegularMove(currentState, previousState, move);\n\t\t\tbreak;\n\n\t\tcase 'capture':\n\t\t\thandleCaptureMove(currentState, previousState, move);\n\t\t\tbreak;\n\n\t\tcase 'arata':\n\t\t\thandleArataMove(currentState, previousState, move, modeCode);\n\t\t\tbreak;\n\n\t\tcase 'betray':\n\t\t\thandleBetrayalMove(currentState, previousState, move, modeCode);\n\t\t\tbreak;\n\t}\n}\n\n/**\n * Handle regular moves (route/tsuke) - preserve the moving piece's ID\n */\nfunction handleRegularMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): void {\n\tif (!move.from) return;\n\n\t// Parse the from position to get tier info\n\tconst [fromRank, fromFile, fromTier] = move.from.split('-').map(Number);\n\tconst fromSquare = `${fromRank}-${fromFile}`;\n\n\t// Find the piece that moved in the previous state with exact tier\n\tconst movedPiece = findPieceAtSquare(\n\t\tpreviousState.board,\n\t\tfromSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\tfromTier\n\t);\n\tif (!movedPiece?.id) return;\n\n\t// Parse the to position to get tier info\n\tconst [toRank, toFile, toTier] = move.to.split('-').map(Number);\n\tconst toSquare = `${toRank}-${toFile}`;\n\n\t// Find where it ended up in the current state with exact tier\n\tconst newPiece = findPieceAtSquare(\n\t\tcurrentState.board,\n\t\ttoSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\ttoTier\n\t);\n\tif (newPiece) {\n\t\tnewPiece.id = movedPiece.id;\n\t}\n}\n\n/**\n * Handle capture moves - preserve moving piece, captured pieces are removed\n */\nfunction handleCaptureMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move\n): void {\n\t// Handle the moving piece same as regular move\n\thandleRegularMove(currentState, previousState, move);\n\t// Captured pieces are already removed from the board, their IDs are freed\n}\n\n/**\n * Handle arata moves - board piece inherits hand ID for animation continuity,\n * hand piece (if still has count > 0) gets new ID\n */\nfunction handleArataMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\t// Find the hand piece in the previous state\n\tconst prevHandPiece = previousState.hand.find(\n\t\t(hp) => hp.type === move.piece && hp.color === move.color\n\t);\n\n\tif (!prevHandPiece?.id) return;\n\n\t// Parse the to position to get tier info for finding the exact placed piece\n\tconst [toRank, toFile, toTier] = move.to.split('-').map(Number);\n\tconst toSquare = `${toRank}-${toFile}`;\n\n\t// CRITICAL: Board piece INHERITS the hand piece's ID for animation continuity\n\t// This allows framer-motion layoutId to animate the piece from hand to board\n\tconst placedPiece = findPieceAtSquare(\n\t\tcurrentState.board,\n\t\ttoSquare,\n\t\tmove.piece,\n\t\tmove.color,\n\t\ttoTier\n\t);\n\tif (placedPiece) {\n\t\tplacedPiece.id = prevHandPiece.id;\n\t}\n\n\t// Hand piece (if still exists with count > 0) gets a NEW ID\n\t// This ensures unique IDs and allows the \"remaining\" hand pieces to be distinct\n\tconst currentHandPiece = currentState.hand.find(\n\t\t(hp) => hp.type === move.piece && hp.color === move.color\n\t);\n\tif (currentHandPiece) {\n\t\tconst nextId = findNextAvailableId(\n\t\t\tcurrentState,\n\t\t\tmodeCode,\n\t\t\tmove.color,\n\t\t\tmove.piece\n\t\t);\n\t\tcurrentHandPiece.id = nextId;\n\t}\n}\n\n/**\n * Handle betrayal moves - complex move with conversions\n */\nfunction handleBetrayalMove(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tmove: Move,\n\tmodeCode: number\n): void {\n\t// Handle the tactician's movement\n\thandleRegularMove(currentState, previousState, move);\n\n\t// Handle hand piece additions from conversions\n\tif (move.captured) {\n\t\tmove.captured.forEach((capturedPiece) => {\n\t\t\tconst handPiece = currentState.hand.find(\n\t\t\t\t(hp) => hp.type === capturedPiece.type && hp.color === move.color\n\t\t\t);\n\t\t\t// Hand pieces from conversions get new IDs (they're essentially new pieces)\n\t\t\tif (handPiece && !handPiece.id) {\n\t\t\t\tconst nextId = findNextAvailableId(\n\t\t\t\t\tcurrentState,\n\t\t\t\t\tmodeCode,\n\t\t\t\t\tmove.color,\n\t\t\t\t\tcapturedPiece.type\n\t\t\t\t);\n\t\t\t\thandPiece.id = nextId;\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * Fallback method using position-based matching when move info unavailable\n */\nfunction assignIdsWithPositionMatching(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN\n): ParsedFEN {\n\tconst result = cloneState(currentState);\n\tconst modeCode = setupModeToCode[currentState.mode];\n\n\t// Track which hand piece IDs were used for arata detection\n\tconst handIdsUsedForArata = new Set<string>();\n\n\t// First pass: detect arata moves (hand count decreased, new board piece appeared)\n\tfor (const prevHandPiece of previousState.hand) {\n\t\tconst currHandPiece = result.hand.find(\n\t\t\t(hp) => hp.type === prevHandPiece.type && hp.color === prevHandPiece.color\n\t\t);\n\t\tconst prevCount = prevHandPiece.count;\n\t\tconst currCount = currHandPiece?.count ?? 0;\n\n\t\tif (prevCount > currCount && prevHandPiece.id) {\n\t\t\t// Hand count decreased - find the new board piece of this type\n\t\t\tconst newBoardPiece = findNewBoardPiece(\n\t\t\t\tresult.board,\n\t\t\t\tpreviousState.board,\n\t\t\t\tprevHandPiece.type,\n\t\t\t\tprevHandPiece.color\n\t\t\t);\n\t\t\tif (newBoardPiece) {\n\t\t\t\t// Board piece inherits hand ID for animation\n\t\t\t\tnewBoardPiece.id = prevHandPiece.id;\n\t\t\t\thandIdsUsedForArata.add(prevHandPiece.id);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: position-based matching for board pieces that didn't come from arata\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst currentTower = result.board[rank][file];\n\t\t\tconst previousTower = previousState.board[rank][file];\n\n\t\t\tfor (\n\t\t\t\tlet tier = 0;\n\t\t\t\ttier < Math.min(currentTower.length, previousTower.length);\n\t\t\t\ttier++\n\t\t\t) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tconst previousPiece = previousTower[tier];\n\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\t!currentPiece.id &&\n\t\t\t\t\tpreviousPiece &&\n\t\t\t\t\tcurrentPiece.type === previousPiece.type &&\n\t\t\t\t\tcurrentPiece.color === previousPiece.color &&\n\t\t\t\t\tpreviousPiece.id\n\t\t\t\t) {\n\t\t\t\t\tcurrentPiece.id = previousPiece.id;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Third pass: match remaining hand pieces, but give new IDs if their ID was used for arata\n\tresult.hand.forEach((currentHandPiece) => {\n\t\tif (currentHandPiece.id) return;\n\n\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t(hp) =>\n\t\t\t\thp.type === currentHandPiece.type && hp.color === currentHandPiece.color\n\t\t);\n\t\tif (\n\t\t\tpreviousHandPiece?.id &&\n\t\t\t!handIdsUsedForArata.has(previousHandPiece.id)\n\t\t) {\n\t\t\tcurrentHandPiece.id = previousHandPiece.id;\n\t\t}\n\t});\n\n\t// Assign missing IDs\n\tassignMissingIds(result, modeCode);\n\n\treturn result;\n}\n\nfunction findNewBoardPiece(\n\tcurrentBoard: Board,\n\tpreviousBoard: Board,\n\ttype: PieceType,\n\tcolor: Color\n): Piece | null {\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst currentTower = currentBoard[rank][file];\n\t\t\tconst previousTower = previousBoard[rank][file];\n\n\t\t\tfor (let tier = 0; tier < currentTower.length; tier++) {\n\t\t\t\tconst currentPiece = currentTower[tier];\n\t\t\t\tif (\n\t\t\t\t\tcurrentPiece &&\n\t\t\t\t\tcurrentPiece.type === type &&\n\t\t\t\t\tcurrentPiece.color === color &&\n\t\t\t\t\t!currentPiece.id\n\t\t\t\t) {\n\t\t\t\t\t// Check if this piece wasn't in the previous state at this position\n\t\t\t\t\tconst prevPiece = previousTower[tier];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!prevPiece ||\n\t\t\t\t\t\tprevPiece.type !== type ||\n\t\t\t\t\t\tprevPiece.color !== color\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn currentPiece;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Assign IDs to pieces that don't have them yet\n */\nfunction assignMissingIds(state: ParsedFEN, modeCode: number): void {\n\tconst usedIds = new Set(getAllUsedIds(state));\n\tconst pieceGroups = groupPiecesByTypeAndColor(state);\n\n\tObject.entries(pieceGroups).forEach(([key, pieces]) => {\n\t\tconst [color, type] = key.split('|') as [Color, PieceType];\n\n\t\tpieces.forEach((piece) => {\n\t\t\tif (!piece.id) {\n\t\t\t\t// Find the next available number for this type/color combination\n\t\t\t\tlet number = 1;\n\t\t\t\tlet candidateId = `${modeCode}-${color}-${type}-${number}`;\n\n\t\t\t\twhile (usedIds.has(candidateId)) {\n\t\t\t\t\tnumber++;\n\t\t\t\t\tcandidateId = `${modeCode}-${color}-${type}-${number}`;\n\t\t\t\t}\n\n\t\t\t\tpiece.id = candidateId;\n\t\t\t\tusedIds.add(candidateId);\n\t\t\t}\n\t\t});\n\t});\n}\n\n/**\n * Find the next available ID for a specific piece type and color\n */\nfunction findNextAvailableId(\n\tstate: ParsedFEN,\n\tmodeCode: number,\n\tcolor: Color,\n\ttype: PieceType\n): string {\n\tconst usedIds = new Set(getAllUsedIds(state));\n\n\tlet number = 1;\n\tlet candidateId = `${modeCode}-${color}-${type}-${number}`;\n\n\twhile (usedIds.has(candidateId)) {\n\t\tnumber++;\n\t\tcandidateId = `${modeCode}-${color}-${type}-${number}`;\n\t}\n\n\treturn candidateId;\n}\n\n/**\n * Get all currently used IDs in the state\n */\nfunction getAllUsedIds(state: ParsedFEN): string[] {\n\tconst ids: string[] = [];\n\n\t// Collect from board\n\tfor (const rank of state.board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece?.id) {\n\t\t\t\t\tids.push(piece.id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Collect from hand\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.id) {\n\t\t\tids.push(handPiece.id);\n\t\t}\n\t}\n\n\treturn ids;\n}\n\n/**\n * Group all pieces by type and color for ID assignment\n */\nfunction groupPiecesByTypeAndColor(\n\tstate: ParsedFEN\n): Record<string, Array<Piece | HandPiece>> {\n\tconst groups: Record<string, Array<Piece | HandPiece>> = {};\n\n\t// Process board pieces\n\tfor (const rank of state.board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece) {\n\t\t\t\t\tconst key = `${piece.color}|${piece.type}`;\n\t\t\t\t\tif (!groups[key]) groups[key] = [];\n\t\t\t\t\tgroups[key].push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Process hand pieces\n\tfor (const handPiece of state.hand) {\n\t\tconst key = `${handPiece.color}|${handPiece.type}`;\n\t\tif (!groups[key]) groups[key] = [];\n\t\tgroups[key].push(handPiece);\n\t}\n\n\treturn groups;\n}\n\n/**\n * Sort pieces canonically for consistent ID assignment\n */\nfunction sortPiecesCanonically(\n\tpieces: Array<Piece | HandPiece>\n): Array<Piece | HandPiece> {\n\treturn pieces.sort((a, b) => {\n\t\t// Board pieces come before hand pieces\n\t\tconst aIsBoard = 'square' in a;\n\t\tconst bIsBoard = 'square' in b;\n\n\t\tif (aIsBoard && !bIsBoard) return -1;\n\t\tif (!aIsBoard && bIsBoard) return 1;\n\n\t\t// Both are board pieces - sort by square and tier\n\t\tif (aIsBoard && bIsBoard) {\n\t\t\tconst aPiece = a as Piece;\n\t\t\tconst bPiece = b as Piece;\n\n\t\t\tif (aPiece.square !== bPiece.square) {\n\t\t\t\tconst [aRank, aFile] = aPiece.square.split('-').map(Number);\n\t\t\t\tconst [bRank, bFile] = bPiece.square.split('-').map(Number);\n\n\t\t\t\tif (aRank !== bRank) return aRank - bRank;\n\t\t\t\treturn aFile - bFile;\n\t\t\t}\n\n\t\t\treturn aPiece.tier - bPiece.tier;\n\t\t}\n\n\t\t// Both are hand pieces - maintain original order\n\t\treturn 0;\n\t});\n}\n\n/**\n * Find a piece at a specific square with optional filters\n */\nfunction findPieceAtSquare(\n\tboard: Board,\n\tsquare: string,\n\ttype?: PieceType,\n\tcolor?: Color,\n\ttier?: number\n): Piece | null {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return null;\n\n\tconst tower = board[rank - 1][9 - file];\n\tfor (const piece of tower) {\n\t\tif (\n\t\t\tpiece &&\n\t\t\t(!type || piece.type === type) &&\n\t\t\t(!color || piece.color === color) &&\n\t\t\t(!tier || piece.tier === tier)\n\t\t) {\n\t\t\treturn piece;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/**\n * Create a deep clone of the parsed FEN state\n */\nfunction cloneState(state: ParsedFEN): ParsedFEN {\n\treturn {\n\t\tboard: state.board.map((rank) =>\n\t\t\trank.map((file) => file.map((piece) => (piece ? { ...piece } : piece)))\n\t\t),\n\t\thand: state.hand.map((hp) => ({ ...hp })),\n\t\tturn: state.turn,\n\t\tmode: state.mode,\n\t\tdrafting: { ...state.drafting },\n\t\tmoveNumber: state.moveNumber,\n\t};\n}\n\n/**\n * Create a deep clone of the parsed FEN state WITHOUT any IDs\n */\nfunction cloneStateWithoutIds(state: ParsedFEN): ParsedFEN {\n\treturn {\n\t\tboard: state.board.map((rank) =>\n\t\t\trank.map((file) =>\n\t\t\t\tfile.map((piece) => (piece ? { ...piece, id: undefined } : piece))\n\t\t\t)\n\t\t),\n\t\thand: state.hand.map((hp) => ({ ...hp, id: undefined })),\n\t\tturn: state.turn,\n\t\tmode: state.mode,\n\t\tdrafting: { ...state.drafting },\n\t\tmoveNumber: state.moveNumber,\n\t};\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO,CAAE,GAAGF,EAAK,CAACE,CAAK,EAAGD,CAAI,GAC/C,CAAC,CACF,EA+BYE,EAA6C,CACzD,MAAO,EACP,SAAU,EACV,aAAc,EACd,SAAU,CACX,EACaC,EAAkBN,EAAWK,CAAe,EAE5CE,GAAQ,IACRC,GAAQ,IAERC,GAAQ,SACRC,GAAO,SACPC,GAAS,SACTC,GAAQ,SAERC,GAAU,SACVC,GAAU,SACVC,GAAqB,SACrBC,GAAgB,SAChBC,GAAU,SACVC,GAAS,SACTC,GAAQ,SACRC,GAAM,SACNC,GAAW,SACXC,GAAU,SACVC,GAAS,SACTC,GAAS,SACTC,GAAY,SACZC,GAAY,SAEZC,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACC,EAAGC,IAAM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verseMap","map","acc","key","value","setupModeToCode","setupCodeToMode","WHITE","BLACK","TSUKE","TAKE","BETRAY","ARATA","MARSHAL","GENERAL","LIEUTENANT_GENERAL","MAJOR_GENERAL","WARRIOR","LANCER","RIDER","SPY","FORTRESS","SOLDIER","CANNON","ARCHER","MUSKETEER","TACTICIAN","SQUARES","_","x","y","piece","symbolToName","pieceToFenCode","fenCodeToPiece","createPieceFromFenCode","code","z","color","name","createHandPieceFromFenCode","count","CANONICAL_NAMES","ENGLISH_NAMES","FEN_CODES","updateHand","pieces","hand","oppositeColor","p","c","hp","h","hpi","convert","square","board","rank","file","tower","get","remove","newTower","removeTop","put","getTop","s","isGameOver","INTRO_POSITION","BEGINNER_POSITION","INTERMEDIATE_POSITION","ADVANCED_POSITION","parseFEN","fen","result","validateFen","placement","handpieces","turn","mode","drafting","moveNumber","board","rank","y","outeracc","partial","tower","piece","z","createPieceFromFenCode","partialPieces","acc","square","hand","playerHand","pieces","i","count","createHandPieceFromFenCode","setupCodeToMode","encodeFEN","emptyCount","file","p","pieceToFenCode","symbolToName","type","color","whiteHand","blackHand","draftKeys","key","setupModeToCode","parts","ranks","fileParts","fileCount","k","filePart","towerPieces","l","hands","dirs","pieceProbes","getAvailableSquares","dir","start","origin","length","board","y","x","py","px","dy","dx","originPiece","getTop","piece","wing","availableSquares","reverse","side","below","forward","step","leapPieces","generateMovesForSquare","square","fen","turn","mode","hand","parseFEN","probe","i","pval","pcarry","acc","s","p","t","get","maxTier","marshalCanStack","createMove","enemies","playerHand","enemyCountMap","e","betrayalOptions","type","count","combos","generateCombinations","combo","newTier","captured","generateArata","drafting","isDraft","ranks","maybe","end","rank","_","arata","isLastPiece","h","sum","to","draftFinished","from","toTier","capture","tsuke","betray","draftDone","move","after","gameOverSAN","makeMove","moveNumber","file","tier","removeTop","remove","convert","updateHand","put","encodeFEN","items","result","helper","currentCombination","getAttackedSquares","isSquareAttacked","byColor","targetRank","targetFile","targetSquare","sq","SQUARES","inCheck","color","oppositeColor","wouldBeInCheckAfterMove","encodePGN","history","opts","maxWidth","newline","withComments","comments","pgn","prev","move","i","state","parseFEN","indicator","parsePGN","moves","normalized","endIdx","comment","match","assignPieceIdsWithState","currentFen","previousState","move","currentState","parseFEN","assignIdsWithExplicitMove","assignIdsWithPositionMatching","assignCanonicalIds","state","result","cloneState","modeCode","setupModeToCode","pieceGroups","groupPiecesByTypeAndColor","key","pieces","color","type","sortPiecesCanonically","piece","index","cloneStateWithoutIds","affectedPieces","identifyAffectedPieces","preserveUnaffectedPieceIds","handleAffectedPieces","assignMissingIds","capturedPieces","handPieceTypes","movingPiece","placementSquare","fromRank","fromFile","fromTier","capturedPiece","isPieceAffected","square","tier","captured","rank","file","currentTower","previousTower","currentPiece","previousPiece","currentHandPiece","affected","previousHandPiece","hp","handleRegularMove","handleCaptureMove","handleArataMove","handleBetrayalMove","fromSquare","movedPiece","findPieceAtSquare","toRank","toFile","toTier","toSquare","newPiece","prevHandPiece","placedPiece","nextId","findNextAvailableId","handPiece","handIdsUsedForArata","currHandPiece","prevCount","currCount","newBoardPiece","findNewBoardPiece","currentBoard","previousBoard","prevPiece","usedIds","getAllUsedIds","number","candidateId","ids","groups","a","b","aIsBoard","bIsBoard","aPiece","bPiece","aRank","aFile","bRank","bFile","board","tower","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#previousState","#comments","#initPosition","#initializeState","fen","move","stateWithIds","assignPieceIdsWithState","INTRO_POSITION","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","acc","p","c","ADVANCED_POSITION","encodeFEN","get","getTop","piece","states","frequencyMap","map","str","#hasNoLegalMoves","hp","generateArata","sq","SQUARES","generateMovesForSquare","#hasEscapingMove","moves","wouldBeInCheckAfterMove","inCheck","isGameOver","pieces","marshals","m1","m2","r1","f1","r2","f2","rankDiff","fileDiff","pgn","parsed","parsePGN","i","comment","normalizedInput","found","m","boardMoves","handMoves","encodePGN","lastMove","result","comments","validateFen"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gungi.js",
3
- "version": "3.4.7",
3
+ "version": "3.4.9",
4
4
  "type": "module",
5
5
  "description": "library which contains all the necessary logic for the strategy game from the HUNTER×HUNTER manga",
6
6
  "main": "lib/gungi.js",