gungi.js 3.2.0 → 3.2.1

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 F from"picocolors";var q=r=>Object.entries(r).reduce((e,[t,o])=>({...e,[o]:t}),{}),O={intro:0,beginner:1,intermediate:2,advanced:3},G=q(O),se="w",ae="b",ce="\u4ED8",le="\u53D6",de="\u8FD4",pe="\u65B0",fe="\u5E25",ue="\u5927",he="\u4E2D",me="\u5C0F",Pe="\u4F8D",ge="\u69CD",ye="\u99AC",be="\u5FCD",Ne="\u7826",ve="\u5175",Ce="\u7832",we="\u5F13",Te="\u7B52",xe="\u8B00",U=Array.from({length:9},(r,e)=>e+1).flatMap(r=>Array.from({length:9},(e,t)=>`${r}-${9-t}`)),N={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"},E=q(N),T={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"},K=q(T),H=(r,[e,t,o])=>{let n=r===r.toLowerCase()?"b":"w",s=K[r.toLowerCase()];return{square:`${e}-${t}`,tier:o,type:N[s],color:n}},J=(r,e)=>{let t=r===r.toLowerCase()?"b":"w",o=K[r.toLowerCase()];return{type:N[o],count:e,color:t}},Ee={\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"},$e={\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"},Me={\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 D(r,e,t=!1){return r.forEach(o=>{let n=t?o.color==="b"?"w":"b":o.color,s=e.find(c=>c.type===o.type&&c.color===n),i=e.findIndex(c=>c.type===o.type&&c.color===n);s&&(s.count--,s.count===0&&e.splice(i,1))}),e}function V(r,e,t){let[o,n]=r.split("-").map(Number),s=x(r,t);s&&(t[o-1][9-n]=s.map(i=>(e.find(a=>JSON.stringify(a)===JSON.stringify(i))&&(i.color=i.color==="b"?"w":"b"),i)))}function Y(r,e,t){let[o,n]=r.split("-").map(Number),s=x(r,t);if(!s)return;let i=s.filter(c=>!e.some(a=>JSON.stringify(a)===JSON.stringify(c)));i.length===0?t[o-1][9-n]=[null]:t[o-1][9-n]=i}function S(r,e){let[t,o]=r.split("-").map(Number),n=x(r,e);n&&(n.pop(),n.length===0&&(e[t-1][9-o]=[null]))}function z(r,e){let[t,o]=r.square.split("-").map(Number);e[t-1][9-o][0]?e[t-1][9-o].push(r):e[t-1][9-o]=[r]}function C(r,e){let t=x(r,e);return t?t.at(-1):void 0}function x(r,e){let[t,o]=r.split("-").map(Number);if(t<1||t>9||o<1||o>9)return;let n=e[t-1][9-o];if(n[0])return n}function Q(r){return r.flat().flat().filter(t=>t?.type==="\u5E25").length!==2}var X="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Ae="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",ke="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",_="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function w(r){let e=L(r);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[t,o,n,s,i,c]=r.split(" "),a=t.split("/").map((f,d)=>f.split("|").reduce((p,u)=>{if(u.includes(":")){let m=u.split(":").map((h,P)=>H(h,[d+1,9-p.length,P+1]));p.push(m)}else{let m=u.split("").reduce((h,P)=>(Number.isInteger(+P)?h=h.concat(Array(+P).fill(null)):h.push(H(P,[d+1,9-p.length-h.length,1])),h),[]).map(h=>[h]);p=p.concat(m)}return p},[])),l=o.split("/").flatMap(f=>{let d=[];if(f!=="-")for(let p=0;p<f.length;p+=2){let u=f[p],m=+f[p+1];d.push(J(u,m))}return d});return{board:a,hand:l,turn:n,mode:G[+s],drafting:{w:i.includes("w"),b:i.includes("b")},moveNumber:+c}}function M(r){let e="",t=0;for(let c=0;c<9;c++){for(let a=0;a<9;a++){let l=r.board[c][a];if(l[0]===null){t++;continue}if(t&&(e+=t,t=0),l.length>1)e+="|"+l.map(f=>{if(!f)return null;let d=T[E[f.type]];return f.color==="w"?d.toUpperCase():d}).join(":")+"|";else{let{type:f,color:d}=l[0],p=T[E[f]];e+=d==="w"?p.toUpperCase():p}}e+=t?`${t}/`:"/",t=0}let o="",n=r.hand.filter(c=>c.color==="w"),s=r.hand.filter(c=>c.color==="b");n.forEach(c=>{let a=T[E[c.type]];o+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),o+=n.length>0?"/":"-/",s.forEach(c=>{let a=T[E[c.type]];o+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),o+=s.length>0?"":"-";let i=Object.keys(r.drafting).filter(c=>r.drafting[c]);return`${e.slice(0,-1)} ${o} ${r.turn} ${O[r.mode]} ${i.length>0?i.join(""):"-"} ${r.moveNumber}`}function L(r){let e=r.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[t,o,n,s,i,c]=e,a=t.split("/");if(a.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${a.length}]`};for(let p=0;p<a.length;p++){let m=a[p].split("|"),h=0;for(let P=0;P<m.length;P++){let g=m[P];if(g.includes(":")){h++;let y=g.split(":");if(y.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${h})`};if(!y.every(b=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(b)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}else{let y=g.split("");for(let b=0;b<y.length;b++){let k=y[b];if(Number.isInteger(+k))h+=+k;else if(h++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(k))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}}}if(h!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${h}] in rank: ${p+1}`}}let l=o.split("/");if(l.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${l.length}]`};let[f,d]=l;if(f.length===1&&f!=="-"||d.length===1&&d!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(f.length>1&&f.length%2!==0||d.length>1&&d.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(d.length>1)for(let p=0;p<d.length;p+=2){if(!"mgijwnrsfdcakt".includes(d[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+d[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return n!=="w"&&n!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${n}]`}:s.length!==1||!"0123".includes(s)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${s}]`}:i!=="-"&&!"wb".includes(i)?{ok:!1,error:`5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${i}]`}:Number.isInteger(+c)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${c}]`}}var Se=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],Ie={\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 Re(r,e,t,o,n){let[s,i]=e,[c,a]=t,[l,f]=r,d=C(`${c}-${a}`,n),p=[],u={x:i,y:s};for(;u.x!==a||u.y!==c;){u.x-=f,u.y-=l;let P=C(`${u.y}-${u.x}`,n);if(P&&P.tier>d.tier)return[];let g=d.color==="b"?-1:1,y=C(`${u.y+g}-${u.x}`,n);if(y&&y.square===`${c}-${a}`)break}let m={x:i,y:s},h=0;for(;h<o&&!(m.x<1||m.x>9||m.y<1||m.y>9);){let P=C(`${m.y}-${m.x}`,n);if(P&&P.tier>d.tier)break;p.push(`${m.y}-${m.x}`);let g=[N.cannon,N.musketeer,N.archer];if(P&&!g.includes(d.type))break;m.x+=f,m.y+=l,h++}return p}function j(r,e){let{board:t,turn:o,mode:n,hand:s}=w(e),i=C(r,t);if(!i||o!==i.color)return[];let[c,a]=r.split("-").map(Number);return Ie[i.type].flatMap((d,p)=>{let u=typeof d=="number"?d:d[0],m=typeof d=="number"?1:d[1];if(u<1)return[];let[h,P]=Se[p];i.color==="b"&&(h*=-1,P*=-1);let[g,y]=u===1/0?[c+h,a+P]:[c+u*h,a+P],b=u===1/0?1/0:i.tier+m-1;return Re([h,P],[g,y],[c,a],b,t)}).reduce((d,p)=>{let u=C(p,t),m=x(p,t),h=n==="advanced"?3:2,P=["advanced","intermediate"].includes(n);if(!u||!m)d.push(A(i,`${p}-1`,e,"route"));else{if(u.tier<h&&u.type!==N.marshal&&((i.type!==N.marshal||P)&&d.push(A(i,`${p}-${u.tier+1}`,e,"tsuke")),i.type===N.tactician&&u.color!==i.color)){let g=m.filter(v=>v.color!==i.color),y=s.filter(v=>v.color===i.color),b=g.reduce((v,$)=>(v.set($.type,(v.get($.type)??0)+1),v),new Map),k=Array.from(b.entries()).filter(([v,$])=>y.some(B=>B.type===v&&B.count>=$)).flatMap(([v])=>g.filter($=>$.type===v)),ie=qe(k);d.push(...ie.map(v=>A(i,`${p}-${u.tier+1}`,e,"betray",v)))}if(u.color!==i.color){let g=m.filter(b=>b.color===i.color).length+1,y=m.filter(b=>b.color!==i.color);d.push(A(i,`${p}-${g}`,e,"capture",y))}}return d},[])}function I(r,e){let{board:t,turn:o,mode:n,hand:s,drafting:i}=w(e);if(!r||o!==r.color)return[];if(!!s.some(u=>u.type===N.marshal&&u.color===r.color)&&r.type!==N.marshal)return[];let a=i.b||i.w,l=n==="advanced"?3:2,f=[],d=[];if(a)f=r.color==="w"?[7,8,9]:[1,2,3];else{let u=r.color==="b"?1:9,m=r.color==="b"?9:1,h=r.color==="b"?1:-1;for(let P=u;r.color==="b"?P<=m:P>=m;P+=h)Array.from({length:9}).map((y,b)=>C(`${P}-${b+1}`,t)).some(y=>y&&y.color===r.color)?(f.push(...d,P),d=[]):d.push(P)}return f.flatMap(u=>Array.from({length:9},(m,h)=>`${u}-${h+1}`)).reduce((u,m)=>{let h=C(m,t),P={type:r.type,color:r.color,square:m,tier:0};if(!h||h.color===P.color&&h.tier<l&&h.type!==N.marshal){let g=(h?.tier??0)+1;u.push(A(P,`${m}-${g}`,e,"arata")),i[r.color]&&u.push(A(P,`${m}-${g}`,e,"arata",[],!0))}return u},[])}function A(r,e,t,o,n,s){let i=r.tier!==0?`(${r.square}-${r.tier})`:"",c=+(e.split("-").at(-1)??0),a=o==="arata"?"\u65B0":"",l=o==="capture"?"\u53D6":"",f=o==="tsuke"||c!==1&&c-r.tier>0?"\u4ED8":"",d=o==="betray"?`\u8FD4${n?.map(P=>P.type).join("")}`:"",p=s?"\u7D42":"",u={piece:r.type,color:r.color,from:i.slice(1,-1),to:e,type:o,san:`${a}${r.type}${i}${l}(${e})${d||f}${p}`,before:t,after:"",draftFinished:s,captured:n},{after:m,gameOverSAN:h}=Fe(u,u.before);return u.after=m,u.san+=h,u}function Fe(r,e){let{board:t,hand:o,mode:n,turn:s,drafting:i,moveNumber:c}=w(e),[a,l,f]=r.to.split("-"),d={type:r.piece,color:r.color,square:`${a}-${l}`,tier:+f};r.type==="route"||r.type==="tsuke"?S(r.from,t):r.type==="capture"?(S(r.from,t),Y(`${a}-${l}`,r.captured,t)):r.type==="betray"?(S(r.from,t),V(`${a}-${l}`,r.captured,t),D(r.captured,o,!0)):r.type==="arata"&&(D([d],o),r.draftFinished&&(i[r.color]=!1)),z(d,t),s==="b"&&(i.w||!i.b)&&c++,s==="w"&&!i.b&&!i.w&&r.draftFinished&&c++,i.w===i.b?(!r.draftFinished||s!=="w")&&(s=s==="b"?"w":"b"):!i.b&&s==="b"?s="w":!i.w&&s==="w"&&(s="b");let p="";return r.captured?.some(u=>u.type===N.marshal)&&(p="\u52DD"),{after:M({board:t,hand:o,mode:n,turn:s,drafting:i,moveNumber:c}),gameOverSAN:p}}function qe(r){let e=[];function t(o,n){n.length>0&&e.push([...n]);for(let s=o;s<r.length;s++)n.push(r[s]),t(s+1,n),n.pop()}return t(0,[]),e}function Z(r,e){let t=e?.maxWidth??6,o=e?.newline??`
2
- `,n="",s=0;return r.forEach((i,c)=>{let a=w(i.before);if(a.moveNumber!==s){let l=i.color==="w"?".":"...";n+=`${a.moveNumber}${l} `,s=a.moveNumber}n+=`${i.san} `,(c+1)%t===0&&(n+=o)}),n.replaceAll(" "," ").trim()}function ee(r,e){let t=e?.newline??`
3
- `;return r.split(t).flatMap(n=>n.replace(/\d+\.+/g,"").split(" ")).filter(n=>n!=="")}function re(r,e){let t=w(r);if(!e)return te(t);let o=M({board:e.board,hand:e.hand,turn:e.turn,moveNumber:e.moveNumber,drafting:e.drafting,mode:e.mode}),n=Oe(o,r);return n.isSingleMove&&n.movedPiece?_e(t,e,n):te(t)}function te(r){let e={...r,board:r.board.map(o=>o.map(n=>n.map(s=>s&&{...s}))),hand:r.hand.map(o=>({...o}))},t=R(e.board,e.hand);for(let o in t){let n=t[o],[s,i]=o.split("-");[...n.boardPieces.sort(oe),...n.handPieces].forEach((a,l)=>{a.id=`${s}-${i}-${l+1}`})}return e}function Oe(r,e){let t=w(r),o=w(e),n=He(t.board,o.board),s=De(t.hand,o.hand),i=n.disappeared.length+n.appeared.length,c=Math.abs(s.whiteChange)+Math.abs(s.blackChange);if(i===2&&c<=1){let a=n.disappeared[0],l=n.appeared[0];if(a&&l&&a.type===l.type&&a.color===l.color)return{isSingleMove:!0,movedPiece:{fromSquare:a.square,toSquare:l.square,piece:l,isArata:!1,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===0){let a=n.appeared[0];if(s.changes.find(f=>f.type===a.type&&f.color===a.color&&f.countDiff<0))return{isSingleMove:!0,movedPiece:{toSquare:a.square,piece:a,isArata:!0,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===2){let a=n.appeared[0],l=n.disappeared.find(d=>d.type===a.type&&d.color===a.color),f=n.disappeared.find(d=>d.type!==a.type||d.color!==a.color);if(l&&f)return{isSingleMove:!0,movedPiece:{fromSquare:l.square,toSquare:a.square,piece:a,isArata:!1,isCapture:!0},capturedPieces:[f]}}return{isSingleMove:!1}}function He(r,e){let t=[],o=[],n=new Map,s=new Map;for(let i of r)for(let c of i)for(let a of c)a&&(n.has(a.square)||n.set(a.square,[]),n.get(a.square).push(a));for(let i of e)for(let c of i)for(let a of c)a&&(s.has(a.square)||s.set(a.square,[]),s.get(a.square).push(a));for(let[i,c]of n){let a=s.get(i)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||t.push(l)}for(let[i,c]of s){let a=n.get(i)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||o.push(l)}return{disappeared:t,appeared:o}}function De(r,e){let t=new Map,o=new Map;for(let a of r){let l=`${a.color}-${a.type}`;t.set(l,a.count)}for(let a of e){let l=`${a.color}-${a.type}`;o.set(l,a.count)}let n=[],s=0,i=0,c=new Set([...t.keys(),...o.keys()]);for(let a of c){let l=t.get(a)||0,d=(o.get(a)||0)-l;if(d!==0){let[p,u]=a.split("-");n.push({type:u,color:p,countDiff:d}),p==="w"?s+=Math.abs(d):i+=Math.abs(d)}}return{changes:n,whiteChange:s,blackChange:i}}function _e(r,e,t){let o={...r,board:r.board.map(a=>a.map(l=>l.map(f=>f&&{...f,id:void 0}))),hand:r.hand.map(a=>({...a,id:void 0}))};if(!t.movedPiece)return o;Le(o,e,t),Be(o);let{fromSquare:n,toSquare:s,piece:i,isArata:c}=t.movedPiece;if(c){let a=e.hand.find(l=>l.type===i.type&&l.color===i.color);if(a?.id){let l=W(o.board,s,i.type,i.color,i.tier);l&&(l.id=a.id);let f=o.hand.find(d=>d.type===i.type&&d.color===i.color);f&&a.id&&(f.id=a.id)}}else{let a=n?W(e.board,n,i.type,i.color):null;if(a?.id){let l=W(o.board,s,i.type,i.color,i.tier);l&&(l.id=a.id)}}return o}function W(r,e,t,o,n){let[s,i]=e.split("-").map(Number);if(s<1||s>9||i<1||i>9)return null;let c=r[s-1][9-i];for(let a of c)if(a&&(!t||a.type===t)&&(!o||a.color===o)&&(!n||a.tier===n))return a;return null}function Le(r,e,t){if(!t.movedPiece)return;let{fromSquare:o,toSquare:n,piece:s,isArata:i}=t.movedPiece,c=R(e.board,e.hand),a=R(r.board,r.hand);for(let l in c){let f=c[l],d=a[l];if(!d)continue;let[p,u]=l.split("-");s.type===u&&s.color===p?We(d,f,o,n,i):je(d,f)}}function je(r,e){for(let t of r.boardPieces){let o=e.boardPieces.find(n=>n.square===t.square&&n.tier===t.tier);o?.id&&(t.id=o.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let t=r.handPieces[0],o=e.handPieces[0];o.id&&(t.id=o.id)}}function We(r,e,t,o,n){if(n){for(let s of r.boardPieces){if(s.square===o)continue;let i=e.boardPieces.find(c=>c.square===s.square&&c.tier===s.tier);i?.id&&(s.id=i.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let s=r.handPieces[0],i=e.handPieces[0];i.id&&(s.id=i.id)}}else{for(let s of r.boardPieces){if(s.square===o)continue;let i=e.boardPieces.find(c=>c.square===s.square&&c.tier===s.tier);i?.id&&(s.id=i.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let s=r.handPieces[0],i=e.handPieces[0];i.id&&(s.id=i.id)}}}function R(r,e){let t={};for(let o of r)for(let n of o)for(let s of n)if(s){let i=`${s.color}-${s.type}`;t[i]||(t[i]={boardPieces:[],handPieces:[]}),t[i].boardPieces.push(s)}for(let o of e){let n=`${o.color}-${o.type}`;t[n]||(t[n]={boardPieces:[],handPieces:[]}),t[n].handPieces.push(o)}return t}function Be(r){let e=R(r.board,r.hand);for(let t in e){let o=e[t],[n,s]=t.split("-"),i=[...o.boardPieces.sort(oe),...o.handPieces],c=1;for(let a of i)if(!a.id){for(;i.some(l=>l.id===`${n}-${s}-${c}`);)c++;a.id=`${n}-${s}-${c}`,c++}}}function oe(r,e){let[t,o]=r.square.split("-").map(Number),[n,s]=e.square.split("-").map(Number);return t!==n?t-n:o!==s?o-s:r.tier-e.tier}var ne=class{#r;#n;#s;#a;#o;#l;#e=[];#i=null;#d=null;#c;#t(e){let t=re(e,this.#d);this.#r=t.board,this.#n=t.hand,this.#s=t.turn,this.#a=t.moveNumber,this.#o=t.drafting,this.#l=t.mode,this.#i=e,this.#d=t}constructor(e){this.#c=e??X,this.#t(this.#c)}ascii(e){let t={1:F.yellow,2:F.blue,3:F.green},o=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
4
- `;o+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
5
- `;for(let n=1;n<=9;n++){o+="\uFF5C";for(let s=9;s>0;s--){let i=this.getTop(`${n}-${s}`);if(!i){o+="\u30FB";continue}let c=T[E[i.type]],a=i.color==="w"?c.toUpperCase():c,l=t[i.tier](e?.english?String.fromCharCode(a.charCodeAt(0)+65248):i.type);o+=i.color==="w"?l:F.dim(l)}o+=`\uFF5C${String.fromCharCode(n-1+65297)}
6
- `}return o+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
7
- `,o}board(){return this.#r}captured(e){let o=this.#e.flatMap(n=>n.captured??[]).reduce((n,s)=>{let i=n.find(c=>c.type===s.type&&c.color===s.color);return i?i.count++:n.push({type:s.type,color:s.color,count:1}),n},[]);return e?o.filter(n=>n.color===e):o}clear(){this.#i=null,this.#t(_),this.#e=[]}fen(){return M({board:this.#r,hand:this.#n,turn:this.#s,mode:this.#l,drafting:this.#o,moveNumber:this.#a})}get(e){return x(e,this.#r)}getDraftingRights(e){return e?this.#o[e]:this.#o}getTop(e){return C(e,this.#r)}hand(e){return e?this.#n.filter(t=>t.color===e):this.#n}history(e){return e?.verbose?this.#e:this.#e.map(t=>t.san)}inDraft(){return this.#o.b||this.#o.w}isFourfoldRepetition(){let e=this.#e.map(o=>o.before.split(" ")[0]);e.length&&e.push(this.#e.at(-1).after.split(" ")[0]);let t=e.reduce((o,n)=>(o.set(n,(o.get(n)||0)+1),o),new Map);return Math.max(...t.values())===4}isGameOver(){return!this.inDraft()&&(Q(this.#r)||this.isFourfoldRepetition())}load(e){this.#t(e)}loadPgn(e,t=_,o){this.#i=null,this.#t(t),this.#e=[],ee(e,o).forEach(s=>this.move(s))}move(e){let t=this.moves({verbose:!0}),o=typeof e=="string"?t.find(n=>n.san===e):t.find(n=>e.piece===n.piece&&e.type===n.type&&e.from===n.from&&e.to===n.to&&e.captured===n.captured&&e.draftFinished===n.draftFinished);if(!o)throw new Error(`Illegal move: ${e}`);return this.#e.push(o),this.isFourfoldRepetition()&&(this.#e.at(-1).san+="\u505C"),this.#t(o.after),o}moves(e){if(this.isGameOver())return[];if(e?.square){let t=j(e.square,this.fen());return e.verbose?t:t.map(o=>o.san)}else if(e?.arata){let t=I(e.arata,this.fen());return e.verbose?t:t.map(o=>o.san)}else if(this.inDraft()){let t=this.hand().flatMap(o=>I(o,this.fen()));return e?.verbose?t:t.map(o=>o.san)}else{let t=U.flatMap(s=>j(s,this.fen())),o=this.hand().flatMap(s=>I(s,this.fen())),n=[...t,...o];return e?.verbose?n:n.map(s=>s.san)}}moveNumber(){return this.#a}pgn(e){return Z(this.#e,e)}print(e){console.log(this.ascii(e))}reset(){this.#i=null,this.#t(this.#c),this.#e=[]}turn(){return this.#s}undo(){let e=this.#e.pop();return e?(this.#t(e.before),e):null}validateFen(e){return L(e)}};export{_ as ADVANCED_POSITION,pe as ARATA,we as ARCHER,Ae as BEGINNER_POSITION,de as BETRAY,ae as BLACK,Ce as CANNON,Ee as CANONICAL_NAMES,$e as ENGLISH_NAMES,Me as FEN_CODES,Ne as FORTRESS,ue as GENERAL,ne as Gungi,ke as INTERMEDIATE_POSITION,X as INTRO_POSITION,ge as LANCER,he as LIEUTENANT_GENERAL,me as MAJOR_GENERAL,fe as MARSHAL,Te as MUSKETEER,ye as RIDER,ve as SOLDIER,be as SPY,U as SQUARES,xe as TACTICIAN,le as TAKE,ce as TSUKE,Pe as WARRIOR,se as WHITE,L as validateFen};
1
+ import F from"picocolors";var q=o=>Object.entries(o).reduce((e,[t,r])=>({...e,[r]:t}),{}),O={intro:0,beginner:1,intermediate:2,advanced:3},W=q(O),le="w",de="b",fe="\u4ED8",pe="\u53D6",ue="\u8FD4",he="\u65B0",ge="\u5E25",me="\u5927",Pe="\u4E2D",ye="\u5C0F",be="\u4F8D",Ne="\u69CD",ve="\u99AC",Ce="\u5FCD",we="\u7826",xe="\u5175",Ee="\u7832",Te="\u5F13",$e="\u7B52",Me="\u8B00",B=Array.from({length:9},(o,e)=>e+1).flatMap(o=>Array.from({length:9},(e,t)=>`${o}-${9-t}`)),N={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"},T=q(N),x={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"},G=q(x),H=(o,[e,t,r])=>{let n=o===o.toLowerCase()?"b":"w",i=G[o.toLowerCase()];return{square:`${e}-${t}`,tier:r,type:N[i],color:n}},K=(o,e)=>{let t=o===o.toLowerCase()?"b":"w",r=G[o.toLowerCase()];return{type:N[r],count:e,color:t}},ke={\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"},Ae={\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"},Ie={\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 D(o,e,t=!1){return o.forEach(r=>{let n=t?r.color==="b"?"w":"b":r.color,i=e.find(c=>c.type===r.type&&c.color===n),s=e.findIndex(c=>c.type===r.type&&c.color===n);i&&(i.count--,i.count===0&&e.splice(s,1))}),e}function J(o,e,t){let[r,n]=o.split("-").map(Number),i=E(o,t);i&&(t[r-1][9-n]=i.map(s=>(e.find(a=>JSON.stringify(a)===JSON.stringify(s))&&(s.color=s.color==="b"?"w":"b"),s)))}function V(o,e,t){let[r,n]=o.split("-").map(Number),i=E(o,t);if(!i)return;let s=i.filter(c=>!e.some(a=>JSON.stringify(a)===JSON.stringify(c)));s.length===0?t[r-1][9-n]=[null]:t[r-1][9-n]=s}function I(o,e){let[t,r]=o.split("-").map(Number),n=E(o,e);n&&(n.pop(),n.length===0&&(e[t-1][9-r]=[null]))}function Y(o,e){let[t,r]=o.square.split("-").map(Number);e[t-1][9-r][0]?e[t-1][9-r].push(o):e[t-1][9-r]=[o]}function C(o,e){let t=E(o,e);return t?t.at(-1):void 0}function E(o,e){let[t,r]=o.split("-").map(Number);if(t<1||t>9||r<1||r>9)return;let n=e[t-1][9-r];if(n[0])return n}function z(o){return o.flat().flat().filter(t=>t?.type==="\u5E25").length!==2}var Q="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Se="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",Re="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",_="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function w(o){let e=L(o);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[t,r,n,i,s,c]=o.split(" "),a=t.split("/").map((f,d)=>f.split("|").reduce((p,u)=>{if(u.includes(":")){let g=u.split(":").map((h,m)=>H(h,[d+1,9-p.length,m+1]));p.push(g)}else{let g=u.split("").reduce((h,m)=>(Number.isInteger(+m)?h=h.concat(Array(+m).fill(null)):h.push(H(m,[d+1,9-p.length-h.length,1])),h),[]).map(h=>[h]);p=p.concat(g)}return p},[])),l=r.split("/").flatMap(f=>{let d=[];if(f!=="-")for(let p=0;p<f.length;p+=2){let u=f[p],g=+f[p+1];d.push(K(u,g))}return d});return{board:a,hand:l,turn:n,mode:W[+i],drafting:{w:s.includes("w"),b:s.includes("b")},moveNumber:+c}}function M(o){let e="",t=0;for(let c=0;c<9;c++){for(let a=0;a<9;a++){let l=o.board[c][a];if(l[0]===null){t++;continue}if(t&&(e+=t,t=0),l.length>1)e+="|"+l.map(f=>{if(!f)return null;let d=x[T[f.type]];return f.color==="w"?d.toUpperCase():d}).join(":")+"|";else{let{type:f,color:d}=l[0],p=x[T[f]];e+=d==="w"?p.toUpperCase():p}}e+=t?`${t}/`:"/",t=0}let r="",n=o.hand.filter(c=>c.color==="w"),i=o.hand.filter(c=>c.color==="b");n.forEach(c=>{let a=x[T[c.type]];r+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),r+=n.length>0?"/":"-/",i.forEach(c=>{let a=x[T[c.type]];r+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),r+=i.length>0?"":"-";let s=Object.keys(o.drafting).filter(c=>o.drafting[c]);return`${e.slice(0,-1)} ${r} ${o.turn} ${O[o.mode]} ${s.length>0?s.join(""):"-"} ${o.moveNumber}`}function L(o){let e=o.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[t,r,n,i,s,c]=e,a=t.split("/");if(a.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${a.length}]`};for(let p=0;p<a.length;p++){let g=a[p].split("|"),h=0;for(let m=0;m<g.length;m++){let P=g[m];if(P.includes(":")){h++;let y=P.split(":");if(y.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${h})`};if(!y.every(b=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(b)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}else{let y=P.split("");for(let b=0;b<y.length;b++){let A=y[b];if(Number.isInteger(+A))h+=+A;else if(h++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(A))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}}}if(h!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${h}] in rank: ${p+1}`}}let l=r.split("/");if(l.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${l.length}]`};let[f,d]=l;if(f.length===1&&f!=="-"||d.length===1&&d!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(f.length>1&&f.length%2!==0||d.length>1&&d.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(d.length>1)for(let p=0;p<d.length;p+=2){if(!"mgijwnrsfdcakt".includes(d[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+d[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return n!=="w"&&n!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${n}]`}:i.length!==1||!"0123".includes(i)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${i}]`}:s!=="-"&&!"wb".includes(s)?{ok:!1,error:`5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${s}]`}:Number.isInteger(+c)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${c}]`}}var Fe=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],qe={\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 Oe(o,e,t,r,n){let[i,s]=e,[c,a]=t,[l,f]=o,d=C(`${c}-${a}`,n),p=[],u={x:s,y:i};for(;u.x!==a||u.y!==c;){u.x-=f,u.y-=l;let m=C(`${u.y}-${u.x}`,n);if(m&&m.tier>d.tier)return[];let P=d.color==="b"?-1:1,y=C(`${u.y+P}-${u.x}`,n);if(y&&y.square===`${c}-${a}`)break}let g={x:s,y:i},h=0;for(;h<r&&!(g.x<1||g.x>9||g.y<1||g.y>9);){let m=C(`${g.y}-${g.x}`,n);if(m&&m.tier>d.tier)break;p.push(`${g.y}-${g.x}`);let P=[N.cannon,N.musketeer,N.archer];if(m&&!P.includes(d.type))break;g.x+=f,g.y+=l,h++}return p}function j(o,e){let{board:t,turn:r,mode:n,hand:i}=w(e),s=C(o,t);if(!s||r!==s.color)return[];let[c,a]=o.split("-").map(Number);return qe[s.type].flatMap((d,p)=>{let u=typeof d=="number"?d:d[0],g=typeof d=="number"?1:d[1];if(u<1)return[];let[h,m]=Fe[p];s.color==="b"&&(h*=-1,m*=-1);let[P,y]=u===1/0?[c+h,a+m]:[c+u*h,a+m],b=u===1/0?1/0:s.tier+g-1;return Oe([h,m],[P,y],[c,a],b,t)}).reduce((d,p)=>{let u=C(p,t),g=E(p,t),h=n==="advanced"?3:2,m=["advanced","intermediate"].includes(n);if(!u||!g)d.push(k(s,`${p}-1`,e,"route"));else{if(u.tier<h&&u.type!==N.marshal&&((s.type!==N.marshal||m)&&d.push(k(s,`${p}-${u.tier+1}`,e,"tsuke")),s.type===N.tactician&&u.color!==s.color)){let P=g.filter(v=>v.color!==s.color),y=i.filter(v=>v.color===s.color),b=P.reduce((v,$)=>(v.set($.type,(v.get($.type)??0)+1),v),new Map),A=Array.from(b.entries()).filter(([v,$])=>y.some(U=>U.type===v&&U.count>=$)).flatMap(([v])=>P.filter($=>$.type===v)),ce=De(A);d.push(...ce.map(v=>k(s,`${p}-${u.tier+1}`,e,"betray",v)))}if(u.color!==s.color){let P=g.filter(b=>b.color===s.color).length+1,y=g.filter(b=>b.color!==s.color);d.push(k(s,`${p}-${P}`,e,"capture",y))}}return d},[])}function S(o,e){let{board:t,turn:r,mode:n,hand:i,drafting:s}=w(e);if(!o||r!==o.color)return[];if(!!i.some(u=>u.type===N.marshal&&u.color===o.color)&&o.type!==N.marshal)return[];let a=s.b||s.w,l=n==="advanced"?3:2,f=[],d=[];if(a)f=o.color==="w"?[7,8,9]:[1,2,3];else{let u=o.color==="b"?1:9,g=o.color==="b"?9:1,h=o.color==="b"?1:-1;for(let m=u;o.color==="b"?m<=g:m>=g;m+=h)Array.from({length:9}).map((y,b)=>C(`${m}-${b+1}`,t)).some(y=>y&&y.color===o.color)?(f.push(...d,m),d=[]):d.push(m)}return f.flatMap(u=>Array.from({length:9},(g,h)=>`${u}-${h+1}`)).reduce((u,g)=>{let h=C(g,t),m={type:o.type,color:o.color,square:g,tier:0};if(!h||h.color===m.color&&h.tier<l&&h.type!==N.marshal){let P=(h?.tier??0)+1;u.push(k(m,`${g}-${P}`,e,"arata")),s[o.color]&&u.push(k(m,`${g}-${P}`,e,"arata",[],!0))}return u},[])}function k(o,e,t,r,n,i){let s=o.tier!==0?`(${o.square}-${o.tier})`:"",c=+(e.split("-").at(-1)??0),a=r==="arata"?"\u65B0":"",l=r==="capture"?"\u53D6":"",f=r==="tsuke"||c!==1&&c-o.tier>0?"\u4ED8":"",d=r==="betray"?`\u8FD4${n?.map(m=>m.type).join("")}`:"",p=i?"\u7D42":"",u={piece:o.type,color:o.color,from:s.slice(1,-1),to:e,type:r,san:`${a}${o.type}${s}${l}(${e})${d||f}${p}`,before:t,after:"",draftFinished:i,captured:n},{after:g,gameOverSAN:h}=He(u,u.before);return u.after=g,u.san+=h,u}function He(o,e){let{board:t,hand:r,mode:n,turn:i,drafting:s,moveNumber:c}=w(e),[a,l,f]=o.to.split("-"),d={type:o.piece,color:o.color,square:`${a}-${l}`,tier:+f};o.type==="route"||o.type==="tsuke"?I(o.from,t):o.type==="capture"?(I(o.from,t),V(`${a}-${l}`,o.captured,t)):o.type==="betray"?(I(o.from,t),J(`${a}-${l}`,o.captured,t),D(o.captured,r,!0)):o.type==="arata"&&(D([d],r),o.draftFinished&&(s[o.color]=!1)),Y(d,t),i==="b"&&(s.w||!s.b)&&c++,i==="w"&&!s.b&&!s.w&&o.draftFinished&&c++,s.w===s.b?(!o.draftFinished||i!=="w")&&(i=i==="b"?"w":"b"):!s.b&&i==="b"?i="w":!s.w&&i==="w"&&(i="b");let p="";return o.captured?.some(u=>u.type===N.marshal)&&(p="\u52DD"),{after:M({board:t,hand:r,mode:n,turn:i,drafting:s,moveNumber:c}),gameOverSAN:p}}function De(o){let e=[];function t(r,n){n.length>0&&e.push([...n]);for(let i=r;i<o.length;i++)n.push(o[i]),t(i+1,n),n.pop()}return t(0,[]),e}function X(o,e){let t=e?.maxWidth??6,r=e?.newline??`
2
+ `,n="",i=0;return o.forEach((s,c)=>{let a=w(s.before);if(a.moveNumber!==i){let l=s.color==="w"?".":"...";n+=`${a.moveNumber}${l} `,i=a.moveNumber}n+=`${s.san} `,(c+1)%t===0&&(n+=r)}),n.replaceAll(" "," ").trim()}function Z(o,e){let t=e?.newline??`
3
+ `;return o.split(t).flatMap(n=>n.replace(/\d+\.+/g,"").split(" ")).filter(n=>n!=="")}function oe(o,e){let t=w(o);if(!e){let i=ee(t);return ne(i,!0)}let r=M({board:e.board,hand:e.hand,turn:e.turn,moveNumber:e.moveNumber,drafting:e.drafting,mode:e.mode}),n=_e(r,o);if(n.isSingleMove&&n.movedPiece){let i=Ue(t,e,n);return Ke(i)}else{let i=ee(t);return ne(i,!0)}}function ee(o){let e={...o,board:o.board.map(r=>r.map(n=>n.map(i=>i&&{...i}))),hand:o.hand.map(r=>({...r}))},t=R(e.board,e.hand);for(let r in t){let n=t[r],[i,s]=r.split("-");[...n.boardPieces.sort(se),...n.handPieces].forEach((a,l)=>{a.id=`${i}-${s}-${l+1}`})}return e}function _e(o,e){let t=w(o),r=w(e),n=Le(t.board,r.board),i=je(t.hand,r.hand),s=n.disappeared.length+n.appeared.length,c=Math.abs(i.whiteChange)+Math.abs(i.blackChange);if(s===2&&c<=1){let a=n.disappeared[0],l=n.appeared[0];if(a&&l&&a.type===l.type&&a.color===l.color)return{isSingleMove:!0,movedPiece:{fromSquare:a.square,toSquare:l.square,piece:l,isArata:!1,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===0){let a=n.appeared[0];if(i.changes.find(f=>f.type===a.type&&f.color===a.color&&f.countDiff<0))return{isSingleMove:!0,movedPiece:{toSquare:a.square,piece:a,isArata:!0,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===2){let a=n.appeared[0],l=n.disappeared.find(d=>d.type===a.type&&d.color===a.color),f=n.disappeared.find(d=>d.type!==a.type||d.color!==a.color);if(l&&f)return{isSingleMove:!0,movedPiece:{fromSquare:l.square,toSquare:a.square,piece:a,isArata:!1,isCapture:!0},capturedPieces:[f]}}return{isSingleMove:!1}}function Le(o,e){let t=[],r=[],n=new Map,i=new Map;for(let s of o)for(let c of s)for(let a of c)a&&(n.has(a.square)||n.set(a.square,[]),n.get(a.square).push(a));for(let s of e)for(let c of s)for(let a of c)a&&(i.has(a.square)||i.set(a.square,[]),i.get(a.square).push(a));for(let[s,c]of n){let a=i.get(s)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||t.push(l)}for(let[s,c]of i){let a=n.get(s)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||r.push(l)}return{disappeared:t,appeared:r}}function je(o,e){let t=new Map,r=new Map;for(let a of o){let l=`${a.color}-${a.type}`;t.set(l,a.count)}for(let a of e){let l=`${a.color}-${a.type}`;r.set(l,a.count)}let n=[],i=0,s=0,c=new Set([...t.keys(),...r.keys()]);for(let a of c){let l=t.get(a)||0,d=(r.get(a)||0)-l;if(d!==0){let[p,u]=a.split("-");n.push({type:u,color:p,countDiff:d}),p==="w"?i+=Math.abs(d):s+=Math.abs(d)}}return{changes:n,whiteChange:i,blackChange:s}}function Ue(o,e,t){let r={...o,board:o.board.map(a=>a.map(l=>l.map(f=>f&&{...f,id:void 0}))),hand:o.hand.map(a=>({...a,id:void 0}))};if(!t.movedPiece)return r;We(r,e,t),ie(r);let{fromSquare:n,toSquare:i,piece:s,isArata:c}=t.movedPiece;if(c){let a=e.hand.find(l=>l.type===s.type&&l.color===s.color);if(a?.id){let l=r.hand.find(f=>f.type===s.type&&f.color===s.color);l&&a.id&&(l.id=a.id)}}else{let a=n?te(e.board,n,s.type,s.color):null;if(a?.id){let l=te(r.board,i,s.type,s.color,s.tier);l&&(l.id=a.id)}}return r}function te(o,e,t,r,n){let[i,s]=e.split("-").map(Number);if(i<1||i>9||s<1||s>9)return null;let c=o[i-1][9-s];for(let a of c)if(a&&(!t||a.type===t)&&(!r||a.color===r)&&(!n||a.tier===n))return a;return null}function We(o,e,t){if(!t.movedPiece)return;let{fromSquare:r,toSquare:n,piece:i,isArata:s}=t.movedPiece,c=R(e.board,e.hand),a=R(o.board,o.hand);for(let l in c){let f=c[l],d=a[l];if(!d)continue;let[p,u]=l.split("-");i.type===u&&i.color===p?Ge(d,f,r,n,s):Be(d,f)}}function Be(o,e){for(let t of o.boardPieces){let r=e.boardPieces.find(n=>n.square===t.square&&n.tier===t.tier);r?.id&&(t.id=r.id)}if(o.handPieces.length>0&&e.handPieces.length>0){let t=o.handPieces[0],r=e.handPieces[0];r.id&&(t.id=r.id)}}function Ge(o,e,t,r,n){if(n){for(let i of o.boardPieces){if(i.square===r)continue;let s=e.boardPieces.find(c=>c.square===i.square&&c.tier===i.tier);s?.id&&(i.id=s.id)}if(o.handPieces.length>0&&e.handPieces.length>0){let i=o.handPieces[0],s=e.handPieces[0];s.id&&(i.id=s.id)}}else{for(let i of o.boardPieces){if(i.square===r)continue;let s=e.boardPieces.find(c=>c.square===i.square&&c.tier===i.tier);s?.id&&(i.id=s.id)}if(o.handPieces.length>0&&e.handPieces.length>0){let i=o.handPieces[0],s=e.handPieces[0];s.id&&(i.id=s.id)}}}function R(o,e){let t={};for(let r of o)for(let n of r)for(let i of n)if(i){let s=`${i.color}-${i.type}`;t[s]||(t[s]={boardPieces:[],handPieces:[]}),t[s].boardPieces.push(i)}for(let r of e){let n=`${r.color}-${r.type}`;t[n]||(t[n]={boardPieces:[],handPieces:[]}),t[n].handPieces.push(r)}return t}function ie(o){let e=R(o.board,o.hand);for(let t in e){let r=e[t],[n,i]=t.split("-"),s=[...r.boardPieces.sort(se),...r.handPieces],c=new Set;for(let l of s)if(l.id){let f=l.id.match(new RegExp(`${n}-${i}-(\\d+)$`));f&&c.add(parseInt(f[1],10))}let a=1;for(let l of s)if(!l.id){for(;c.has(a);)a++;l.id=`${n}-${i}-${a}`,c.add(a),a++}}}function re(o){let e=new Map,t=[];for(let r of o.board)for(let n of r)for(let i of n)i?.id&&e.set(i.id,(e.get(i.id)||0)+1);for(let r of o.hand)r.id&&e.set(r.id,(e.get(r.id)||0)+1);for(let[r,n]of e)n>1&&t.push(r);return{hasDuplicates:t.length>0,duplicates:t}}function Ke(o){let e=re(o);if(!e.hasDuplicates)return o;let t=new Map;for(let r of o.board)for(let n of r)for(let i of n)i?.id&&e.duplicates.includes(i.id)&&(t.has(i.id)||t.set(i.id,[]),t.get(i.id).push({piece:i,location:"board"}));for(let r of o.hand)r.id&&e.duplicates.includes(r.id)&&(t.has(r.id)||t.set(r.id,[]),t.get(r.id).push({piece:r,location:"hand"}));for(let[r,n]of t)if(n.length>1)for(let i=1;i<n.length;i++){let{piece:s}=n[i],[c,a]=r.split("-").slice(0,2),l=1;for(;;){let f=`${c}-${a}-${l}`;if(!re(o).duplicates.includes(f)&&!Je(o).includes(f)){s.id=f;break}l++}}return o}function Je(o){let e=[];for(let t of o.board)for(let r of t)for(let n of r)n?.id&&e.push(n.id);for(let t of o.hand)t.id&&e.push(t.id);return e}function ne(o,e=!1){let t=new Map;for(let n=0;n<9;n++)for(let i=0;i<9;i++){let s=o.board[n][i];for(let c=0;c<s.length;c++){let a=s[c];a?.id&&(t.has(a.id)||t.set(a.id,[]),t.get(a.id).push({piece:a,location:`board-${n}-${i}-${c}`}))}}for(let n=0;n<o.hand.length;n++){let i=o.hand[n];i.id&&(t.has(i.id)||t.set(i.id,[]),t.get(i.id).push({piece:i,location:`hand-${n}`}))}let r=!1;for(let[n,i]of t)if(i.length>1){r=!0,e||console.warn(`Detected duplicate piece ID: ${n} used by ${i.length} pieces`);for(let s=1;s<i.length;s++){let{piece:c}=i[s];c.id=void 0}}return r&&(e||console.warn("Reassigning all pieces without IDs to resolve conflicts"),ie(o)),o}function se(o,e){let[t,r]=o.square.split("-").map(Number),[n,i]=e.square.split("-").map(Number);return t!==n?t-n:r!==i?r-i:o.tier-e.tier}var ae=class{#r;#o;#s;#a;#n;#l;#e=[];#i=null;#d=null;#c;#t(e){let t=oe(e,this.#d);this.#r=t.board,this.#o=t.hand,this.#s=t.turn,this.#a=t.moveNumber,this.#n=t.drafting,this.#l=t.mode,this.#i=e,this.#d=t}constructor(e){this.#c=e??Q,this.#t(this.#c)}ascii(e){let t={1:F.yellow,2:F.blue,3:F.green},r=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
4
+ `;r+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
5
+ `;for(let n=1;n<=9;n++){r+="\uFF5C";for(let i=9;i>0;i--){let s=this.getTop(`${n}-${i}`);if(!s){r+="\u30FB";continue}let c=x[T[s.type]],a=s.color==="w"?c.toUpperCase():c,l=t[s.tier](e?.english?String.fromCharCode(a.charCodeAt(0)+65248):s.type);r+=s.color==="w"?l:F.dim(l)}r+=`\uFF5C${String.fromCharCode(n-1+65297)}
6
+ `}return r+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
7
+ `,r}board(){return this.#r}captured(e){let r=this.#e.flatMap(n=>n.captured??[]).reduce((n,i)=>{let s=n.find(c=>c.type===i.type&&c.color===i.color);return s?s.count++:n.push({type:i.type,color:i.color,count:1}),n},[]);return e?r.filter(n=>n.color===e):r}clear(){this.#i=null,this.#t(_),this.#e=[]}fen(){return M({board:this.#r,hand:this.#o,turn:this.#s,mode:this.#l,drafting:this.#n,moveNumber:this.#a})}get(e){return E(e,this.#r)}getDraftingRights(e){return e?this.#n[e]:this.#n}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.#n.b||this.#n.w}isFourfoldRepetition(){let e=this.#e.map(r=>r.before.split(" ")[0]);e.length&&e.push(this.#e.at(-1).after.split(" ")[0]);let t=e.reduce((r,n)=>(r.set(n,(r.get(n)||0)+1),r),new Map);return Math.max(...t.values())===4}isGameOver(){return!this.inDraft()&&(z(this.#r)||this.isFourfoldRepetition())}load(e){this.#t(e)}loadPgn(e,t=_,r){this.#i=null,this.#t(t),this.#e=[],Z(e,r).forEach(i=>this.move(i))}move(e){let t=this.moves({verbose:!0}),r=typeof e=="string"?t.find(n=>n.san===e):t.find(n=>e.piece===n.piece&&e.type===n.type&&e.from===n.from&&e.to===n.to&&e.captured===n.captured&&e.draftFinished===n.draftFinished);if(!r)throw new Error(`Illegal move: ${e}`);return this.#e.push(r),this.isFourfoldRepetition()&&(this.#e.at(-1).san+="\u505C"),this.#t(r.after),r}moves(e){if(this.isGameOver())return[];if(e?.square){let t=j(e.square,this.fen());return e.verbose?t:t.map(r=>r.san)}else if(e?.arata){let t=S(e.arata,this.fen());return e.verbose?t:t.map(r=>r.san)}else if(this.inDraft()){let t=this.hand().flatMap(r=>S(r,this.fen()));return e?.verbose?t:t.map(r=>r.san)}else{let t=B.flatMap(i=>j(i,this.fen())),r=this.hand().flatMap(i=>S(i,this.fen())),n=[...t,...r];return e?.verbose?n:n.map(i=>i.san)}}moveNumber(){return this.#a}pgn(e){return X(this.#e,e)}print(e){console.log(this.ascii(e))}reset(){this.#i=null,this.#t(this.#c),this.#e=[]}turn(){return this.#s}undo(){let e=this.#e.pop();return e?(this.#t(e.before),e):null}validateFen(e){return L(e)}};export{_ as ADVANCED_POSITION,he as ARATA,Te as ARCHER,Se as BEGINNER_POSITION,ue as BETRAY,de as BLACK,Ee as CANNON,ke as CANONICAL_NAMES,Ae as ENGLISH_NAMES,Ie as FEN_CODES,we as FORTRESS,me as GENERAL,ae as Gungi,Re as INTERMEDIATE_POSITION,Q as INTRO_POSITION,Ne as LANCER,Pe as LIEUTENANT_GENERAL,ye as MAJOR_GENERAL,ge as MARSHAL,$e as MUSKETEER,ve as RIDER,xe as SOLDIER,Ce as SPY,B as SQUARES,Me as TACTICIAN,pe as TAKE,fe as TSUKE,be as WARRIOR,le as WHITE,L 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 {\n\tADVANCED_POSITION,\n\tBEGINNER_POSITION,\n\tencodeFEN,\n\tINTERMEDIATE_POSITION,\n\tINTRO_POSITION,\n\tParsedFEN,\n\tparseFEN,\n\tvalidateFen,\n} from './fen';\nimport { generateArata, generateMovesForSquare } from './move_gen';\nimport { encodePGN, parsePGN, PGNOptions } from './pgn';\nimport { assignPieceIds, assignPieceIdsWithState } from './piece-ids';\nimport {\n\tARATA,\n\tARCHER,\n\tBETRAY,\n\tBLACK,\n\tBoard,\n\tCANNON,\n\tCANONICAL_NAMES,\n\tColor,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tFORTRESS,\n\tGENERAL,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tisGameOver,\n\tLANCER,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tMARSHAL,\n\tMove,\n\tMUSKETEER,\n\tpieceToFenCode,\n\tRIDER,\n\tSetupMode,\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};\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#previousFen: string | null = null;\n\t#previousState: ParsedFEN | null = null;\n\n\t#initPosition: string;\n\n\t#initializeState(fen: string) {\n\t\t// Assign IDs using the previous state for stability\n\t\tconst stateWithIds = assignPieceIdsWithState(fen, this.#previousState);\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.#previousFen = fen;\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.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(ADVANCED_POSITION);\n\t\tthis.#history = [];\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\tisGameOver() {\n\t\treturn (\n\t\t\t!this.inDraft() &&\n\t\t\t(isGameOver(this.#board) || this.isFourfoldRepetition())\n\t\t);\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.#previousFen = null; // Reset tracking for new game\n\t\tthis.#initializeState(fen);\n\t\tthis.#history = [];\n\t\tconst moves = parsePGN(pgn, opts);\n\t\tmoves.forEach((move) => this.move(move));\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 found =\n\t\t\ttypeof move === 'string'\n\t\t\t\t? moves.find((m) => 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\tif (this.isFourfoldRepetition()) this.#history.at(-1)!.san += '停';\n\t\tthis.#initializeState(found.after);\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);\n\t}\n\n\tprint(opts?: { english?: boolean }) {\n\t\tconsole.log(this.ascii(opts));\n\t}\n\n\treset() {\n\t\tthis.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(this.#initPosition);\n\t\tthis.#history = [];\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\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] === null) {\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\tconvert,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tpiece as pieceType,\n\tput,\n\tremove,\n\tremoveTop,\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\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\tif (drafting[piece.color]) {\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata', [], true));\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","// 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};\n\nexport function encodePGN(history: Move[], opts?: PGNOptions) {\n\tconst maxWidth = opts?.maxWidth ?? 6;\n\tconst newline = opts?.newline ?? '\\n';\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 ((i + 1) % maxWidth === 0) {\n\t\t\tpgn += newline;\n\t\t}\n\t});\n\n\treturn pgn.replaceAll(' ', ' ').trim();\n}\n\nexport function parsePGN(pgn: string, opts?: Pick<PGNOptions, 'newline'>) {\n\tconst newline = opts?.newline ?? '\\n';\n\tconst moves = pgn\n\t\t.split(newline)\n\t\t.flatMap((line) => {\n\t\t\treturn line.replace(/\\d+\\.+/g, '').split(' ');\n\t\t})\n\t\t.filter((move) => move !== '');\n\n\treturn moves;\n}\n","import { encodeFEN, ParsedFEN, parseFEN } from './fen';\nimport { Board, Color, HandPiece, Piece, PieceType } from './utils';\n\nexport type PieceInventory = {\n\t[key: string]: {\n\t\tboardPieces: Piece[];\n\t\thandPieces: HandPiece[];\n\t};\n};\n\nexport type MoveChange = {\n\tisSingleMove: boolean;\n\tmovedPiece?: {\n\t\tfromSquare?: string;\n\t\ttoSquare: string;\n\t\tpiece: Piece;\n\t\tisArata: boolean;\n\t\tisCapture: boolean;\n\t};\n\tcapturedPieces?: Piece[];\n};\n\n/**\n * Main entry point for assigning piece IDs\n * Uses canonical assignment for base case, move-aware assignment for stability\n */\nexport function assignPieceIds(\n\tcurrentFen: string,\n\tpreviousFen?: string\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousFen) {\n\t\t// Base case: pure canonical assignment\n\t\treturn assignCanonically(currentState);\n\t}\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID\n\t\t// IMPORTANT: Parse previous FEN directly, don't recurse to avoid corruption\n\t\tconst previousState = parseFEN(previousFen);\n\t\treturn preserveMovingPieceId(currentState, previousState, changes);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\treturn assignCanonically(currentState);\n\t}\n}\n\n/**\n * Main entry point for assigning piece IDs with previous state\n * Uses previous parsed state with IDs for better stability\n */\nexport function assignPieceIdsWithState(\n\tcurrentFen: string,\n\tpreviousState?: ParsedFEN | null\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousState) {\n\t\t// Base case: pure canonical assignment\n\t\treturn assignCanonically(currentState);\n\t}\n\n\t// Get the previous FEN to detect changes\n\tconst previousFen = encodeFEN({\n\t\tboard: previousState.board,\n\t\thand: previousState.hand,\n\t\tturn: previousState.turn,\n\t\tmoveNumber: previousState.moveNumber,\n\t\tdrafting: previousState.drafting,\n\t\tmode: previousState.mode,\n\t});\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID using the state with IDs\n\t\treturn preserveMovingPieceId(currentState, previousState, changes);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\treturn assignCanonically(currentState);\n\t}\n}\n\n/**\n * Assigns IDs based purely on canonical positioning\n * Deterministic: same game state always produces same IDs\n */\nfunction assignCanonically(state: ParsedFEN): ParsedFEN {\n\t// Clone the state to avoid mutations\n\tconst result: ParsedFEN = {\n\t\t...state,\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};\n\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(result.board, result.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// Assign sequential IDs\n\t\tallPieces.forEach((piece, index) => {\n\t\t\tpiece.id = `${color}-${pieceType}-${index + 1}`;\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Detects changes between two FEN strings\n * Returns information about what moved for stability purposes\n */\nfunction detectMoveBetween(oldFen: string, newFen: string): MoveChange {\n\tconst oldState = parseFEN(oldFen);\n\tconst newState = parseFEN(newFen);\n\n\t// Compare board states\n\tconst boardChanges = detectBoardChanges(oldState.board, newState.board);\n\tconst handChanges = detectHandChanges(oldState.hand, newState.hand);\n\n\t// Check if this looks like a single move\n\tconst totalChanges =\n\t\tboardChanges.disappeared.length + boardChanges.appeared.length;\n\tconst handPieceChanges =\n\t\tMath.abs(handChanges.whiteChange) + Math.abs(handChanges.blackChange);\n\n\t// Simple single move: one piece disappeared, one appeared, minimal hand changes\n\tif (totalChanges === 2 && handPieceChanges <= 1) {\n\t\tconst disappeared = boardChanges.disappeared[0];\n\t\tconst appeared = boardChanges.appeared[0];\n\n\t\t// Check if same piece type and color\n\t\tif (\n\t\t\tdisappeared &&\n\t\t\tappeared &&\n\t\t\tdisappeared.type === appeared.type &&\n\t\t\tdisappeared.color === appeared.color\n\t\t) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: disappeared.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for arata move (hand to board)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 0\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst handChange = handChanges.changes.find(\n\t\t\t(change) =>\n\t\t\t\tchange.type === appeared.type &&\n\t\t\t\tchange.color === appeared.color &&\n\t\t\t\tchange.countDiff < 0\n\t\t);\n\n\t\tif (handChange) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: true,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for capture move (one piece moved, one disappeared)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 2\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst possibleMover = boardChanges.disappeared.find(\n\t\t\t(p) => p.type === appeared.type && p.color === appeared.color\n\t\t);\n\t\tconst possibleCaptured = boardChanges.disappeared.find(\n\t\t\t(p) => p.type !== appeared.type || p.color !== appeared.color\n\t\t);\n\n\t\tif (possibleMover && possibleCaptured) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: possibleMover.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: true,\n\t\t\t\t},\n\t\t\t\tcapturedPieces: [possibleCaptured],\n\t\t\t};\n\t\t}\n\t}\n\n\treturn { isSingleMove: false };\n}\n\n/**\n * Compare board states to find what pieces appeared/disappeared\n */\nfunction detectBoardChanges(oldBoard: Board, newBoard: Board) {\n\tconst disappeared: Piece[] = [];\n\tconst appeared: Piece[] = [];\n\n\t// Create maps of pieces by position for easy comparison\n\tconst oldPieces = new Map<string, Piece[]>();\n\tconst newPieces = new Map<string, Piece[]>();\n\n\t// Build old pieces map\n\tfor (const rank of oldBoard) {\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\tif (!oldPieces.has(piece.square)) {\n\t\t\t\t\t\toldPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\toldPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build new pieces map\n\tfor (const rank of newBoard) {\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\tif (!newPieces.has(piece.square)) {\n\t\t\t\t\t\tnewPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\tnewPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find disappeared pieces\n\tfor (const [square, pieces] of oldPieces) {\n\t\tconst newSquarePieces = newPieces.get(square) || [];\n\t\tfor (const oldPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) still exists at this position\n\t\t\tconst stillExists = newSquarePieces.some(\n\t\t\t\t(newPiece) =>\n\t\t\t\t\tnewPiece.type === oldPiece.type &&\n\t\t\t\t\tnewPiece.color === oldPiece.color &&\n\t\t\t\t\tnewPiece.tier === oldPiece.tier\n\t\t\t);\n\t\t\tif (!stillExists) {\n\t\t\t\tdisappeared.push(oldPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find appeared pieces\n\tfor (const [square, pieces] of newPieces) {\n\t\tconst oldSquarePieces = oldPieces.get(square) || [];\n\t\tfor (const newPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) was already at this position\n\t\t\tconst wasAlreadyThere = oldSquarePieces.some(\n\t\t\t\t(oldPiece) =>\n\t\t\t\t\toldPiece.type === newPiece.type &&\n\t\t\t\t\toldPiece.color === newPiece.color &&\n\t\t\t\t\toldPiece.tier === newPiece.tier\n\t\t\t);\n\t\t\tif (!wasAlreadyThere) {\n\t\t\t\tappeared.push(newPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { disappeared, appeared };\n}\n\n/**\n * Compare hand states to find what changed\n */\nfunction detectHandChanges(oldHand: HandPiece[], newHand: HandPiece[]) {\n\tconst oldMap = new Map<string, number>();\n\tconst newMap = new Map<string, number>();\n\n\t// Build maps of piece counts\n\tfor (const hp of oldHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\toldMap.set(key, hp.count);\n\t}\n\n\tfor (const hp of newHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\tnewMap.set(key, hp.count);\n\t}\n\n\t// Calculate changes\n\tconst changes: Array<{ type: PieceType; color: Color; countDiff: number }> =\n\t\t[];\n\tlet whiteChange = 0;\n\tlet blackChange = 0;\n\n\t// Find all unique keys\n\tconst allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n\n\tfor (const key of allKeys) {\n\t\tconst oldCount = oldMap.get(key) || 0;\n\t\tconst newCount = newMap.get(key) || 0;\n\t\tconst diff = newCount - oldCount;\n\n\t\tif (diff !== 0) {\n\t\t\tconst [color, type] = key.split('-') as [Color, PieceType];\n\t\t\tchanges.push({ type, color, countDiff: diff });\n\n\t\t\tif (color === 'w') {\n\t\t\t\twhiteChange += Math.abs(diff);\n\t\t\t} else {\n\t\t\t\tblackChange += Math.abs(diff);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { changes, whiteChange, blackChange };\n}\n\n/**\n * Preserves the moving piece's ID when a single move is detected\n */\nfunction preserveMovingPieceId(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): ParsedFEN {\n\t// Clone the current state without any IDs initially\n\tconst result: ParsedFEN = {\n\t\t...currentState,\n\t\tboard: currentState.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: currentState.hand.map((hp) => ({ ...hp, id: undefined })),\n\t};\n\n\tif (!changes.movedPiece) return result;\n\n\t// First, preserve ALL non-moving pieces by copying their IDs from previous state\n\tpreserveAllNonMovingPieceIds(result, previousState, changes);\n\n\t// Then apply canonical assignment ONLY to pieces that don't already have IDs\n\tapplyCanonicalToMissingIds(result);\n\n\tconst { fromSquare, toSquare, piece, isArata } = changes.movedPiece;\n\n\tif (isArata) {\n\t\t// Arata move (hand to board): find the hand piece that moved and preserve its ID\n\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t);\n\n\t\tif (previousHandPiece?.id) {\n\t\t\t// Find the new board piece at the target square and give it the hand piece's ID\n\t\t\tconst boardPiece = findPieceAtSquare(\n\t\t\t\tresult.board,\n\t\t\t\ttoSquare,\n\t\t\t\tpiece.type,\n\t\t\t\tpiece.color,\n\t\t\t\tpiece.tier\n\t\t\t);\n\t\t\tif (boardPiece) {\n\t\t\t\tboardPiece.id = previousHandPiece.id;\n\t\t\t}\n\n\t\t\t// Update the hand piece count but keep its base ID structure\n\t\t\tconst newHandPiece = result.hand.find(\n\t\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t\t);\n\t\t\tif (newHandPiece && previousHandPiece.id) {\n\t\t\t\t// Keep the same base ID for the remaining hand pieces\n\t\t\t\tnewHandPiece.id = previousHandPiece.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular move (board to board): preserve the piece's ID\n\t\tconst previousPiece = fromSquare\n\t\t\t? findPieceAtSquare(\n\t\t\t\t\tpreviousState.board,\n\t\t\t\t\tfromSquare,\n\t\t\t\t\tpiece.type,\n\t\t\t\t\tpiece.color\n\t\t\t\t)\n\t\t\t: null;\n\n\t\tif (previousPiece?.id) {\n\t\t\t// Find the piece at the new location and assign the same ID\n\t\t\tconst newPiece = findPieceAtSquare(\n\t\t\t\tresult.board,\n\t\t\t\ttoSquare,\n\t\t\t\tpiece.type,\n\t\t\t\tpiece.color,\n\t\t\t\tpiece.tier\n\t\t\t);\n\t\t\tif (newPiece) {\n\t\t\t\tnewPiece.id = previousPiece.id;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Find a piece at a specific square with optional type/color/tier 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\treturn null;\n}\n\n/**\n * Preserve IDs for ALL pieces that didn't move using ID-based matching\n */\nfunction preserveAllNonMovingPieceIds(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): void {\n\tif (!changes.movedPiece) return;\n\n\tconst {\n\t\tfromSquare,\n\t\ttoSquare,\n\t\tpiece: movedPiece,\n\t\tisArata,\n\t} = changes.movedPiece;\n\n\t// For each piece type/color group, preserve IDs for non-moving pieces\n\tconst previousInventory = getPieceInventory(\n\t\tpreviousState.board,\n\t\tpreviousState.hand\n\t);\n\tconst currentInventory = getPieceInventory(\n\t\tcurrentState.board,\n\t\tcurrentState.hand\n\t);\n\n\tfor (const typeColorKey in previousInventory) {\n\t\tconst prevGroup = previousInventory[typeColorKey];\n\t\tconst currentGroup = currentInventory[typeColorKey];\n\n\t\tif (!currentGroup) continue; // No pieces of this type in current state\n\n\t\tconst [color, pieceType] = typeColorKey.split('-') as [Color, PieceType];\n\n\t\t// Check if this is the type that moved\n\t\tconst isMovedType =\n\t\t\tmovedPiece.type === pieceType && movedPiece.color === color;\n\n\t\tif (isMovedType) {\n\t\t\t// For the moved piece type, we need to carefully preserve non-moving pieces\n\t\t\tpreserveNonMovingPiecesOfType(\n\t\t\t\tcurrentGroup,\n\t\t\t\tprevGroup,\n\t\t\t\tfromSquare,\n\t\t\t\ttoSquare,\n\t\t\t\tisArata\n\t\t\t);\n\t\t} else {\n\t\t\t// For non-moved types, preserve all IDs by canonical position\n\t\t\tpreserveAllPiecesOfType(currentGroup, prevGroup);\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for all pieces of a type that didn't move at all\n */\nfunction preserveAllPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] }\n): void {\n\t// For board pieces, match by exact position and tier\n\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t(prev) =>\n\t\t\t\tprev.square === currentPiece.square && prev.tier === currentPiece.tier\n\t\t);\n\n\t\tif (prevAtSamePos?.id) {\n\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t}\n\t}\n\n\t// Match hand pieces directly (should be 1-to-1 mapping)\n\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\tconst currentHand = currentGroup.handPieces[0];\n\t\tconst prevHand = prevGroup.handPieces[0];\n\t\tif (prevHand.id) {\n\t\t\tcurrentHand.id = prevHand.id;\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for pieces of the moved type, excluding the actual moved piece\n */\nfunction preserveNonMovingPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tfromSquare?: string,\n\ttoSquare?: string,\n\tisArata?: boolean\n): void {\n\tif (isArata) {\n\t\t// Arata move: a hand piece moved to board\n\t\t// All current board pieces except the destination should preserve their position-based IDs\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\tif (currentPiece.square === toSquare) continue; // Skip the moved piece\n\n\t\t\t// Find previous piece at same position\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces: preserve the hand piece ID structure\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular board move: preserve all board pieces except source and destination\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\t// Skip the moved piece destination\n\t\t\tif (currentPiece.square === toSquare) continue;\n\n\t\t\t// Find previous piece at same position (should be same piece if it didn't move)\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces should be unchanged for regular moves\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Get all board and hand pieces of a specific type and color\n */\nfunction getAllPiecesOfType(state: ParsedFEN, type: PieceType, color: Color) {\n\tconst boardPieces: Piece[] = [];\n\tconst handPieces: HandPiece[] = [];\n\n\t// Collect 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 && piece.type === type && piece.color === color) {\n\t\t\t\t\tboardPieces.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Collect hand pieces\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.type === type && handPiece.color === color) {\n\t\t\thandPieces.push(handPiece);\n\t\t}\n\t}\n\n\treturn { boardPieces, handPieces };\n}\n\n/**\n * Groups pieces by type and color for ID assignment\n */\nfunction getPieceInventory(board: Board, hand: HandPiece[]): PieceInventory {\n\tconst inventory: PieceInventory = {};\n\n\t// Process board pieces\n\tfor (const rank of 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 (!inventory[key]) {\n\t\t\t\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t\t\t\t}\n\t\t\t\t\tinventory[key].boardPieces.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 hand) {\n\t\tconst key = `${handPiece.color}-${handPiece.type}`;\n\t\tif (!inventory[key]) {\n\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t}\n\t\tinventory[key].handPieces.push(handPiece);\n\t}\n\n\treturn inventory;\n}\n\n/**\n * Apply canonical assignment only to pieces that don't already have IDs\n */\nfunction applyCanonicalToMissingIds(state: ParsedFEN): void {\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(state.board, state.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// Only assign IDs to pieces that don't already have them\n\t\tlet nextNumber = 1;\n\t\tfor (const piece of allPieces) {\n\t\t\tif (!piece.id) {\n\t\t\t\t// Find the next available number\n\t\t\t\twhile (\n\t\t\t\t\tallPieces.some((p) => p.id === `${color}-${pieceType}-${nextNumber}`)\n\t\t\t\t) {\n\t\t\t\t\tnextNumber++;\n\t\t\t\t}\n\t\t\t\tpiece.id = `${color}-${pieceType}-${nextNumber}`;\n\t\t\t\tnextNumber++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Canonical comparison function for board pieces\n * Sort by: rank, file, tier (lexicographic order)\n */\nfunction comparePiecesCanonically(a: Piece, b: Piece): number {\n\tconst [aRank, aFile] = a.square.split('-').map(Number);\n\tconst [bRank, bFile] = b.square.split('-').map(Number);\n\n\t// Compare by rank first\n\tif (aRank !== bRank) return aRank - bRank;\n\n\t// Then by file\n\tif (aFile !== bFile) return aFile - bFile;\n\n\t// Finally by tier\n\treturn a.tier - b.tier;\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO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,GAAM,QAAU+B,EAAQA,EAAM,IAAKjB,GAASA,EAAK,GAAG,CAC5D,CACD,CAEA,YAAa,CACZ,OAAO,KAAK1B,EACb,CAEA,IAAIY,EAAmB,CACtB,OAAOwC,EAAU,KAAKjD,GAAUS,CAAI,CACrC,CAEA,MAAMA,EAA8B,CACnC,QAAQ,IAAI,KAAK,MAAMA,CAAI,CAAC,CAC7B,CAEA,OAAQ,CACP,KAAKR,GAAe,KACpB,KAAKG,GAAiB,KAAKD,EAAa,EACxC,KAAKH,GAAW,CAAC,CAClB,CAEA,MAAO,CACN,OAAO,KAAKJ,EACb,CAEA,MAAO,CACN,IAAMsD,EAAW,KAAKlD,GAAS,IAAI,EACnC,OAAIkD,GACH,KAAK9C,GAAiB8C,EAAS,MAAM,EAC9BA,GAGD,IACR,CAEA,YAAY7C,EAAa,CACxB,OAAO8C,EAAY9C,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","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","encodePGN","history","opts","maxWidth","newline","pgn","prev","move","i","state","parseFEN","indicator","parsePGN","line","assignPieceIdsWithState","currentFen","previousState","currentState","parseFEN","assignCanonically","previousFen","encodeFEN","changes","detectMoveBetween","preserveMovingPieceId","state","result","rank","file","piece","hp","inventory","getPieceInventory","key","group","color","pieceType","comparePiecesCanonically","index","oldFen","newFen","oldState","newState","boardChanges","detectBoardChanges","handChanges","detectHandChanges","totalChanges","handPieceChanges","disappeared","appeared","change","possibleMover","p","possibleCaptured","oldBoard","newBoard","oldPieces","newPieces","square","pieces","newSquarePieces","oldPiece","newPiece","oldSquarePieces","oldHand","newHand","oldMap","newMap","whiteChange","blackChange","allKeys","oldCount","diff","type","preserveAllNonMovingPieceIds","applyCanonicalToMissingIds","fromSquare","toSquare","isArata","previousHandPiece","boardPiece","findPieceAtSquare","newHandPiece","previousPiece","board","tier","tower","movedPiece","previousInventory","currentInventory","typeColorKey","prevGroup","currentGroup","preserveNonMovingPiecesOfType","preserveAllPiecesOfType","currentPiece","prevAtSamePos","prev","currentHand","prevHand","getPieceInventory","board","hand","inventory","rank","file","piece","key","handPiece","applyCanonicalToMissingIds","state","group","color","pieceType","allPieces","comparePiecesCanonically","nextNumber","p","a","b","aRank","aFile","bRank","bFile","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#previousFen","#previousState","#initPosition","#initializeState","fen","stateWithIds","assignPieceIdsWithState","INTRO_POSITION","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","move","acc","p","c","a","ADVANCED_POSITION","encodeFEN","get","getTop","piece","states","frequencyMap","map","str","isGameOver","pgn","parsePGN","moves","found","m","generateMovesForSquare","generateArata","hp","boardMoves","SQUARES","handMoves","encodePGN","lastMove","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 {\n\tADVANCED_POSITION,\n\tBEGINNER_POSITION,\n\tencodeFEN,\n\tINTERMEDIATE_POSITION,\n\tINTRO_POSITION,\n\tParsedFEN,\n\tparseFEN,\n\tvalidateFen,\n} from './fen';\nimport { generateArata, generateMovesForSquare } from './move_gen';\nimport { encodePGN, parsePGN, PGNOptions } from './pgn';\nimport { assignPieceIds, assignPieceIdsWithState } from './piece-ids';\nimport {\n\tARATA,\n\tARCHER,\n\tBETRAY,\n\tBLACK,\n\tBoard,\n\tCANNON,\n\tCANONICAL_NAMES,\n\tColor,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tFORTRESS,\n\tGENERAL,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tisGameOver,\n\tLANCER,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tMARSHAL,\n\tMove,\n\tMUSKETEER,\n\tpieceToFenCode,\n\tRIDER,\n\tSetupMode,\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};\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#previousFen: string | null = null;\n\t#previousState: ParsedFEN | null = null;\n\n\t#initPosition: string;\n\n\t#initializeState(fen: string) {\n\t\t// Assign IDs using the previous state for stability\n\t\tconst stateWithIds = assignPieceIdsWithState(fen, this.#previousState);\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.#previousFen = fen;\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.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(ADVANCED_POSITION);\n\t\tthis.#history = [];\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\tisGameOver() {\n\t\treturn (\n\t\t\t!this.inDraft() &&\n\t\t\t(isGameOver(this.#board) || this.isFourfoldRepetition())\n\t\t);\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.#previousFen = null; // Reset tracking for new game\n\t\tthis.#initializeState(fen);\n\t\tthis.#history = [];\n\t\tconst moves = parsePGN(pgn, opts);\n\t\tmoves.forEach((move) => this.move(move));\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 found =\n\t\t\ttypeof move === 'string'\n\t\t\t\t? moves.find((m) => 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\tif (this.isFourfoldRepetition()) this.#history.at(-1)!.san += '停';\n\t\tthis.#initializeState(found.after);\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);\n\t}\n\n\tprint(opts?: { english?: boolean }) {\n\t\tconsole.log(this.ascii(opts));\n\t}\n\n\treset() {\n\t\tthis.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(this.#initPosition);\n\t\tthis.#history = [];\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\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] === null) {\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\tconvert,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tpiece as pieceType,\n\tput,\n\tremove,\n\tremoveTop,\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\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\tif (drafting[piece.color]) {\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata', [], true));\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","// 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};\n\nexport function encodePGN(history: Move[], opts?: PGNOptions) {\n\tconst maxWidth = opts?.maxWidth ?? 6;\n\tconst newline = opts?.newline ?? '\\n';\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 ((i + 1) % maxWidth === 0) {\n\t\t\tpgn += newline;\n\t\t}\n\t});\n\n\treturn pgn.replaceAll(' ', ' ').trim();\n}\n\nexport function parsePGN(pgn: string, opts?: Pick<PGNOptions, 'newline'>) {\n\tconst newline = opts?.newline ?? '\\n';\n\tconst moves = pgn\n\t\t.split(newline)\n\t\t.flatMap((line) => {\n\t\t\treturn line.replace(/\\d+\\.+/g, '').split(' ');\n\t\t})\n\t\t.filter((move) => move !== '');\n\n\treturn moves;\n}\n","import { encodeFEN, ParsedFEN, parseFEN } from './fen';\nimport { Board, Color, HandPiece, Piece, PieceType } from './utils';\n\nexport type PieceInventory = {\n\t[key: string]: {\n\t\tboardPieces: Piece[];\n\t\thandPieces: HandPiece[];\n\t};\n};\n\nexport type MoveChange = {\n\tisSingleMove: boolean;\n\tmovedPiece?: {\n\t\tfromSquare?: string;\n\t\ttoSquare: string;\n\t\tpiece: Piece;\n\t\tisArata: boolean;\n\t\tisCapture: boolean;\n\t};\n\tcapturedPieces?: Piece[];\n};\n\n/**\n * Main entry point for assigning piece IDs\n * Uses canonical assignment for base case, move-aware assignment for stability\n */\nexport function assignPieceIds(\n\tcurrentFen: string,\n\tpreviousFen?: string\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousFen) {\n\t\t// Base case: pure canonical assignment\n\t\tconst result = assignCanonically(currentState);\n\t\treturn ensureUniqueIds(result, true); // Silent for canonical assignment\n\t}\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID\n\t\t// IMPORTANT: Parse previous FEN directly, don't recurse to avoid corruption\n\t\tconst previousState = parseFEN(previousFen);\n\t\tconst result = preserveMovingPieceId(currentState, previousState, changes);\n\t\t// Only apply safeguard if there are actual duplicates, don't force canonical reassignment\n\t\treturn ensureUniqueIdsLenient(result);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\tconst result = assignCanonically(currentState);\n\t\treturn ensureUniqueIds(result, true); // Silent for canonical assignment\n\t}\n}\n\n/**\n * Main entry point for assigning piece IDs with previous state\n * Uses previous parsed state with IDs for better stability\n */\nexport function assignPieceIdsWithState(\n\tcurrentFen: string,\n\tpreviousState?: ParsedFEN | null\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousState) {\n\t\t// Base case: pure canonical assignment\n\t\tconst result = assignCanonically(currentState);\n\t\treturn ensureUniqueIds(result, true); // Silent for canonical assignment\n\t}\n\n\t// Get the previous FEN to detect changes\n\tconst previousFen = encodeFEN({\n\t\tboard: previousState.board,\n\t\thand: previousState.hand,\n\t\tturn: previousState.turn,\n\t\tmoveNumber: previousState.moveNumber,\n\t\tdrafting: previousState.drafting,\n\t\tmode: previousState.mode,\n\t});\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID using the state with IDs\n\t\tconst result = preserveMovingPieceId(currentState, previousState, changes);\n\t\t// Only apply safeguard if there are actual duplicates, don't force canonical reassignment\n\t\treturn ensureUniqueIdsLenient(result);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\tconst result = assignCanonically(currentState);\n\t\treturn ensureUniqueIds(result, true); // Silent for canonical assignment\n\t}\n}\n\n/**\n * Assigns IDs based purely on canonical positioning\n * Deterministic: same game state always produces same IDs\n */\nfunction assignCanonically(state: ParsedFEN): ParsedFEN {\n\t// Clone the state to avoid mutations\n\tconst result: ParsedFEN = {\n\t\t...state,\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};\n\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(result.board, result.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// Assign sequential IDs\n\t\tallPieces.forEach((piece, index) => {\n\t\t\tpiece.id = `${color}-${pieceType}-${index + 1}`;\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Detects changes between two FEN strings\n * Returns information about what moved for stability purposes\n */\nfunction detectMoveBetween(oldFen: string, newFen: string): MoveChange {\n\tconst oldState = parseFEN(oldFen);\n\tconst newState = parseFEN(newFen);\n\n\t// Compare board states\n\tconst boardChanges = detectBoardChanges(oldState.board, newState.board);\n\tconst handChanges = detectHandChanges(oldState.hand, newState.hand);\n\n\t// Check if this looks like a single move\n\tconst totalChanges =\n\t\tboardChanges.disappeared.length + boardChanges.appeared.length;\n\tconst handPieceChanges =\n\t\tMath.abs(handChanges.whiteChange) + Math.abs(handChanges.blackChange);\n\n\t// Simple single move: one piece disappeared, one appeared, minimal hand changes\n\tif (totalChanges === 2 && handPieceChanges <= 1) {\n\t\tconst disappeared = boardChanges.disappeared[0];\n\t\tconst appeared = boardChanges.appeared[0];\n\n\t\t// Check if same piece type and color\n\t\tif (\n\t\t\tdisappeared &&\n\t\t\tappeared &&\n\t\t\tdisappeared.type === appeared.type &&\n\t\t\tdisappeared.color === appeared.color\n\t\t) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: disappeared.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for arata move (hand to board)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 0\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst handChange = handChanges.changes.find(\n\t\t\t(change) =>\n\t\t\t\tchange.type === appeared.type &&\n\t\t\t\tchange.color === appeared.color &&\n\t\t\t\tchange.countDiff < 0\n\t\t);\n\n\t\tif (handChange) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: true,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for capture move (one piece moved, one disappeared)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 2\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst possibleMover = boardChanges.disappeared.find(\n\t\t\t(p) => p.type === appeared.type && p.color === appeared.color\n\t\t);\n\t\tconst possibleCaptured = boardChanges.disappeared.find(\n\t\t\t(p) => p.type !== appeared.type || p.color !== appeared.color\n\t\t);\n\n\t\tif (possibleMover && possibleCaptured) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: possibleMover.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: true,\n\t\t\t\t},\n\t\t\t\tcapturedPieces: [possibleCaptured],\n\t\t\t};\n\t\t}\n\t}\n\n\treturn { isSingleMove: false };\n}\n\n/**\n * Compare board states to find what pieces appeared/disappeared\n */\nfunction detectBoardChanges(oldBoard: Board, newBoard: Board) {\n\tconst disappeared: Piece[] = [];\n\tconst appeared: Piece[] = [];\n\n\t// Create maps of pieces by position for easy comparison\n\tconst oldPieces = new Map<string, Piece[]>();\n\tconst newPieces = new Map<string, Piece[]>();\n\n\t// Build old pieces map\n\tfor (const rank of oldBoard) {\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\tif (!oldPieces.has(piece.square)) {\n\t\t\t\t\t\toldPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\toldPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build new pieces map\n\tfor (const rank of newBoard) {\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\tif (!newPieces.has(piece.square)) {\n\t\t\t\t\t\tnewPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\tnewPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find disappeared pieces\n\tfor (const [square, pieces] of oldPieces) {\n\t\tconst newSquarePieces = newPieces.get(square) || [];\n\t\tfor (const oldPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) still exists at this position\n\t\t\tconst stillExists = newSquarePieces.some(\n\t\t\t\t(newPiece) =>\n\t\t\t\t\tnewPiece.type === oldPiece.type &&\n\t\t\t\t\tnewPiece.color === oldPiece.color &&\n\t\t\t\t\tnewPiece.tier === oldPiece.tier\n\t\t\t);\n\t\t\tif (!stillExists) {\n\t\t\t\tdisappeared.push(oldPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find appeared pieces\n\tfor (const [square, pieces] of newPieces) {\n\t\tconst oldSquarePieces = oldPieces.get(square) || [];\n\t\tfor (const newPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) was already at this position\n\t\t\tconst wasAlreadyThere = oldSquarePieces.some(\n\t\t\t\t(oldPiece) =>\n\t\t\t\t\toldPiece.type === newPiece.type &&\n\t\t\t\t\toldPiece.color === newPiece.color &&\n\t\t\t\t\toldPiece.tier === newPiece.tier\n\t\t\t);\n\t\t\tif (!wasAlreadyThere) {\n\t\t\t\tappeared.push(newPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { disappeared, appeared };\n}\n\n/**\n * Compare hand states to find what changed\n */\nfunction detectHandChanges(oldHand: HandPiece[], newHand: HandPiece[]) {\n\tconst oldMap = new Map<string, number>();\n\tconst newMap = new Map<string, number>();\n\n\t// Build maps of piece counts\n\tfor (const hp of oldHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\toldMap.set(key, hp.count);\n\t}\n\n\tfor (const hp of newHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\tnewMap.set(key, hp.count);\n\t}\n\n\t// Calculate changes\n\tconst changes: Array<{ type: PieceType; color: Color; countDiff: number }> =\n\t\t[];\n\tlet whiteChange = 0;\n\tlet blackChange = 0;\n\n\t// Find all unique keys\n\tconst allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n\n\tfor (const key of allKeys) {\n\t\tconst oldCount = oldMap.get(key) || 0;\n\t\tconst newCount = newMap.get(key) || 0;\n\t\tconst diff = newCount - oldCount;\n\n\t\tif (diff !== 0) {\n\t\t\tconst [color, type] = key.split('-') as [Color, PieceType];\n\t\t\tchanges.push({ type, color, countDiff: diff });\n\n\t\t\tif (color === 'w') {\n\t\t\t\twhiteChange += Math.abs(diff);\n\t\t\t} else {\n\t\t\t\tblackChange += Math.abs(diff);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { changes, whiteChange, blackChange };\n}\n\n/**\n * Preserves the moving piece's ID when a single move is detected\n */\nfunction preserveMovingPieceId(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): ParsedFEN {\n\t// Clone the current state without any IDs initially\n\tconst result: ParsedFEN = {\n\t\t...currentState,\n\t\tboard: currentState.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: currentState.hand.map((hp) => ({ ...hp, id: undefined })),\n\t};\n\n\tif (!changes.movedPiece) return result;\n\n\t// First, preserve ALL non-moving pieces by copying their IDs from previous state\n\tpreserveAllNonMovingPieceIds(result, previousState, changes);\n\n\t// Then apply canonical assignment ONLY to pieces that don't already have IDs\n\tapplyCanonicalToMissingIds(result);\n\n\tconst { fromSquare, toSquare, piece, isArata } = changes.movedPiece;\n\n\tif (isArata) {\n\t\t// Arata move (hand to board): find the hand piece that moved and preserve its ID\n\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t);\n\n\t\tif (previousHandPiece?.id) {\n\t\t\t// Update the hand piece count but keep its base ID structure for stability\n\t\t\tconst newHandPiece = result.hand.find(\n\t\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t\t);\n\t\t\tif (newHandPiece && previousHandPiece.id) {\n\t\t\t\t// Keep the same base ID for the remaining hand pieces\n\t\t\t\tnewHandPiece.id = previousHandPiece.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular move (board to board): preserve the piece's ID\n\t\tconst previousPiece = fromSquare\n\t\t\t? findPieceAtSquare(\n\t\t\t\t\tpreviousState.board,\n\t\t\t\t\tfromSquare,\n\t\t\t\t\tpiece.type,\n\t\t\t\t\tpiece.color\n\t\t\t\t)\n\t\t\t: null;\n\n\t\tif (previousPiece?.id) {\n\t\t\t// Find the piece at the new location and assign the same ID\n\t\t\tconst newPiece = findPieceAtSquare(\n\t\t\t\tresult.board,\n\t\t\t\ttoSquare,\n\t\t\t\tpiece.type,\n\t\t\t\tpiece.color,\n\t\t\t\tpiece.tier\n\t\t\t);\n\t\t\tif (newPiece) {\n\t\t\t\tnewPiece.id = previousPiece.id;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Find a piece at a specific square with optional type/color/tier 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\treturn null;\n}\n\n/**\n * Preserve IDs for ALL pieces that didn't move using ID-based matching\n */\nfunction preserveAllNonMovingPieceIds(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): void {\n\tif (!changes.movedPiece) return;\n\n\tconst {\n\t\tfromSquare,\n\t\ttoSquare,\n\t\tpiece: movedPiece,\n\t\tisArata,\n\t} = changes.movedPiece;\n\n\t// For each piece type/color group, preserve IDs for non-moving pieces\n\tconst previousInventory = getPieceInventory(\n\t\tpreviousState.board,\n\t\tpreviousState.hand\n\t);\n\tconst currentInventory = getPieceInventory(\n\t\tcurrentState.board,\n\t\tcurrentState.hand\n\t);\n\n\tfor (const typeColorKey in previousInventory) {\n\t\tconst prevGroup = previousInventory[typeColorKey];\n\t\tconst currentGroup = currentInventory[typeColorKey];\n\n\t\tif (!currentGroup) continue; // No pieces of this type in current state\n\n\t\tconst [color, pieceType] = typeColorKey.split('-') as [Color, PieceType];\n\n\t\t// Check if this is the type that moved\n\t\tconst isMovedType =\n\t\t\tmovedPiece.type === pieceType && movedPiece.color === color;\n\n\t\tif (isMovedType) {\n\t\t\t// For the moved piece type, we need to carefully preserve non-moving pieces\n\t\t\tpreserveNonMovingPiecesOfType(\n\t\t\t\tcurrentGroup,\n\t\t\t\tprevGroup,\n\t\t\t\tfromSquare,\n\t\t\t\ttoSquare,\n\t\t\t\tisArata\n\t\t\t);\n\t\t} else {\n\t\t\t// For non-moved types, preserve all IDs by canonical position\n\t\t\tpreserveAllPiecesOfType(currentGroup, prevGroup);\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for all pieces of a type that didn't move at all\n */\nfunction preserveAllPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] }\n): void {\n\t// For board pieces, match by exact position and tier\n\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t(prev) =>\n\t\t\t\tprev.square === currentPiece.square && prev.tier === currentPiece.tier\n\t\t);\n\n\t\tif (prevAtSamePos?.id) {\n\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t}\n\t}\n\n\t// Match hand pieces directly (should be 1-to-1 mapping)\n\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\tconst currentHand = currentGroup.handPieces[0];\n\t\tconst prevHand = prevGroup.handPieces[0];\n\t\tif (prevHand.id) {\n\t\t\tcurrentHand.id = prevHand.id;\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for pieces of the moved type, excluding the actual moved piece\n */\nfunction preserveNonMovingPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\t_fromSquare?: string,\n\ttoSquare?: string,\n\tisArata?: boolean\n): void {\n\tif (isArata) {\n\t\t// Arata move: a hand piece moved to board\n\t\t// All current board pieces except the destination should preserve their position-based IDs\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\tif (currentPiece.square === toSquare) continue; // Skip the moved piece\n\n\t\t\t// Find previous piece at same position\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces: preserve the hand piece ID structure\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular board move: preserve all board pieces except source and destination\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\t// Skip the moved piece destination\n\t\t\tif (currentPiece.square === toSquare) continue;\n\n\t\t\t// Find previous piece at same position (should be same piece if it didn't move)\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces should be unchanged for regular moves\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Groups pieces by type and color for ID assignment\n */\nfunction getPieceInventory(board: Board, hand: HandPiece[]): PieceInventory {\n\tconst inventory: PieceInventory = {};\n\n\t// Process board pieces\n\tfor (const rank of 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 (!inventory[key]) {\n\t\t\t\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t\t\t\t}\n\t\t\t\t\tinventory[key].boardPieces.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 hand) {\n\t\tconst key = `${handPiece.color}-${handPiece.type}`;\n\t\tif (!inventory[key]) {\n\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t}\n\t\tinventory[key].handPieces.push(handPiece);\n\t}\n\n\treturn inventory;\n}\n\n/**\n * Apply canonical assignment only to pieces that don't already have IDs\n */\nfunction applyCanonicalToMissingIds(state: ParsedFEN): void {\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(state.board, state.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// First, collect all existing IDs to track what numbers are already used\n\t\tconst usedNumbers = new Set<number>();\n\t\tfor (const piece of allPieces) {\n\t\t\tif (piece.id) {\n\t\t\t\tconst match = piece.id.match(\n\t\t\t\t\tnew RegExp(`${color}-${pieceType}-(\\\\d+)$`)\n\t\t\t\t);\n\t\t\t\tif (match) {\n\t\t\t\t\tusedNumbers.add(parseInt(match[1], 10));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Only assign IDs to pieces that don't already have them\n\t\tlet nextNumber = 1;\n\t\tfor (const piece of allPieces) {\n\t\t\tif (!piece.id) {\n\t\t\t\t// Find the next available number\n\t\t\t\twhile (usedNumbers.has(nextNumber)) {\n\t\t\t\t\tnextNumber++;\n\t\t\t\t}\n\t\t\t\tpiece.id = `${color}-${pieceType}-${nextNumber}`;\n\t\t\t\tusedNumbers.add(nextNumber);\n\t\t\t\tnextNumber++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Checks for duplicate piece IDs without fixing them\n * Returns information about any duplicates found\n */\nexport function checkForDuplicateIds(state: ParsedFEN): {\n\thasDuplicates: boolean;\n\tduplicates: string[];\n} {\n\tconst allIds = new Map<string, number>();\n\tconst duplicates: string[] = [];\n\n\t// Count ID occurrences from 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?.id) {\n\t\t\t\t\tallIds.set(piece.id, (allIds.get(piece.id) || 0) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count ID occurrences from hand pieces\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.id) {\n\t\t\tallIds.set(handPiece.id, (allIds.get(handPiece.id) || 0) + 1);\n\t\t}\n\t}\n\n\t// Find duplicates\n\tfor (const [id, count] of allIds) {\n\t\tif (count > 1) {\n\t\t\tduplicates.push(id);\n\t\t}\n\t}\n\n\treturn {\n\t\thasDuplicates: duplicates.length > 0,\n\t\tduplicates,\n\t};\n}\n\n/**\n * Lenient version that only fixes actual duplicates without forcing complete reassignment\n * Preserves ID stability for close FEN states\n */\nfunction ensureUniqueIdsLenient(state: ParsedFEN): ParsedFEN {\n\tconst duplicateCheck = checkForDuplicateIds(state);\n\n\tif (!duplicateCheck.hasDuplicates) {\n\t\treturn state; // No duplicates, return as-is to preserve stability\n\t}\n\n\t// Only fix actual duplicates by reassigning the minimal number of pieces\n\tconst allIds = new Map<\n\t\tstring,\n\t\tArray<{ piece: Piece | HandPiece; location: string }>\n\t>();\n\n\t// Collect pieces with duplicate IDs\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 && duplicateCheck.duplicates.includes(piece.id)) {\n\t\t\t\t\tif (!allIds.has(piece.id)) {\n\t\t\t\t\t\tallIds.set(piece.id, []);\n\t\t\t\t\t}\n\t\t\t\t\tallIds.get(piece.id)!.push({ piece, location: `board` });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.id && duplicateCheck.duplicates.includes(handPiece.id)) {\n\t\t\tif (!allIds.has(handPiece.id)) {\n\t\t\t\tallIds.set(handPiece.id, []);\n\t\t\t}\n\t\t\tallIds.get(handPiece.id)!.push({ piece: handPiece, location: `hand` });\n\t\t}\n\t}\n\n\t// Fix only the duplicates by reassigning subsequent pieces\n\tfor (const [id, pieces] of allIds) {\n\t\tif (pieces.length > 1) {\n\t\t\t// Keep first piece with original ID, reassign others minimally\n\t\t\tfor (let i = 1; i < pieces.length; i++) {\n\t\t\t\tconst { piece } = pieces[i];\n\t\t\t\tconst [color, type] = id.split('-').slice(0, 2) as [string, string];\n\n\t\t\t\t// Find next available number for this type\n\t\t\t\tlet nextNum = 1;\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst testId = `${color}-${type}-${nextNum}`;\n\t\t\t\t\tconst check = checkForDuplicateIds(state);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!check.duplicates.includes(testId) &&\n\t\t\t\t\t\t!getAllCurrentIds(state).includes(testId)\n\t\t\t\t\t) {\n\t\t\t\t\t\tpiece.id = testId;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tnextNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn state;\n}\n\n/**\n * Helper to get all current IDs in state\n */\nfunction getAllCurrentIds(state: ParsedFEN): string[] {\n\tconst ids: string[] = [];\n\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) ids.push(piece.id);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.id) ids.push(handPiece.id);\n\t}\n\n\treturn ids;\n}\n\n/**\n * Ensures all piece IDs are unique by detecting and fixing duplicates\n * This serves as a safety net against race conditions or other edge cases\n */\nfunction ensureUniqueIds(state: ParsedFEN, silent = false): ParsedFEN {\n\t// Collect all existing IDs to detect duplicates\n\tconst allIds = new Map<\n\t\tstring,\n\t\tArray<{ piece: Piece | HandPiece; location: string }>\n\t>();\n\n\t// Scan board pieces\n\tfor (let rank = 0; rank < 9; rank++) {\n\t\tfor (let file = 0; file < 9; file++) {\n\t\t\tconst tower = state.board[rank][file];\n\t\t\tfor (let tier = 0; tier < tower.length; tier++) {\n\t\t\t\tconst piece = tower[tier];\n\t\t\t\tif (piece?.id) {\n\t\t\t\t\tif (!allIds.has(piece.id)) {\n\t\t\t\t\t\tallIds.set(piece.id, []);\n\t\t\t\t\t}\n\t\t\t\t\tallIds.get(piece.id)!.push({\n\t\t\t\t\t\tpiece,\n\t\t\t\t\t\tlocation: `board-${rank}-${file}-${tier}`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Scan hand pieces\n\tfor (let i = 0; i < state.hand.length; i++) {\n\t\tconst handPiece = state.hand[i];\n\t\tif (handPiece.id) {\n\t\t\tif (!allIds.has(handPiece.id)) {\n\t\t\t\tallIds.set(handPiece.id, []);\n\t\t\t}\n\t\t\tallIds.get(handPiece.id)!.push({\n\t\t\t\tpiece: handPiece,\n\t\t\t\tlocation: `hand-${i}`,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Find and fix duplicates\n\tlet hasConflicts = false;\n\tfor (const [id, pieces] of allIds) {\n\t\tif (pieces.length > 1) {\n\t\t\thasConflicts = true;\n\t\t\tif (!silent) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`Detected duplicate piece ID: ${id} used by ${pieces.length} pieces`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Keep the first piece with the original ID, reassign others\n\t\t\tfor (let i = 1; i < pieces.length; i++) {\n\t\t\t\tconst { piece } = pieces[i];\n\t\t\t\tpiece.id = undefined; // Will be reassigned below\n\t\t\t}\n\t\t}\n\t}\n\n\t// If we found conflicts, do a complete reassignment to fix them\n\tif (hasConflicts) {\n\t\tif (!silent) {\n\t\t\tconsole.warn('Reassigning all pieces without IDs to resolve conflicts');\n\t\t}\n\t\tapplyCanonicalToMissingIds(state);\n\t}\n\n\treturn state;\n}\n\n/**\n * Canonical comparison function for board pieces\n * Sort by: rank, file, tier (lexicographic order)\n */\nfunction comparePiecesCanonically(a: Piece, b: Piece): number {\n\tconst [aRank, aFile] = a.square.split('-').map(Number);\n\tconst [bRank, bFile] = b.square.split('-').map(Number);\n\n\t// Compare by rank first\n\tif (aRank !== bRank) return aRank - bRank;\n\n\t// Then by file\n\tif (aFile !== bFile) return aFile - bFile;\n\n\t// Finally by tier\n\treturn a.tier - b.tier;\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EA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AAK,MAAMA,CAAI,CAAC,CAC7B,CAEA,OAAQ,CACP,KAAKR,GAAe,KACpB,KAAKG,GAAiB,KAAKD,EAAa,EACxC,KAAKH,GAAW,CAAC,CAClB,CAEA,MAAO,CACN,OAAO,KAAKJ,EACb,CAEA,MAAO,CACN,IAAMsD,EAAW,KAAKlD,GAAS,IAAI,EACnC,OAAIkD,GACH,KAAK9C,GAAiB8C,EAAS,MAAM,EAC9BA,GAGD,IACR,CAEA,YAAY7C,EAAa,CACxB,OAAO8C,EAAY9C,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","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","encodePGN","history","opts","maxWidth","newline","pgn","prev","move","i","state","parseFEN","indicator","parsePGN","line","assignPieceIdsWithState","currentFen","previousState","currentState","parseFEN","result","assignCanonically","ensureUniqueIds","previousFen","encodeFEN","changes","detectMoveBetween","preserveMovingPieceId","ensureUniqueIdsLenient","state","rank","file","piece","hp","inventory","getPieceInventory","key","group","color","pieceType","comparePiecesCanonically","index","oldFen","newFen","oldState","newState","boardChanges","detectBoardChanges","handChanges","detectHandChanges","totalChanges","handPieceChanges","disappeared","appeared","change","possibleMover","p","possibleCaptured","oldBoard","newBoard","oldPieces","newPieces","square","pieces","newSquarePieces","oldPiece","newPiece","oldSquarePieces","oldHand","newHand","oldMap","newMap","whiteChange","blackChange","allKeys","oldCount","diff","type","preserveAllNonMovingPieceIds","applyCanonicalToMissingIds","fromSquare","toSquare","isArata","previousHandPiece","newHandPiece","previousPiece","findPieceAtSquare","board","tier","tower","movedPiece","previousInventory","currentInventory","typeColorKey","prevGroup","currentGroup","preserveNonMovingPiecesOfType","preserveAllPiecesOfType","currentPiece","prevAtSamePos","prev","currentHand","prevHand","_fromSquare","hand","handPiece","allPieces","usedNumbers","match","nextNumber","checkForDuplicateIds","allIds","duplicates","id","count","duplicateCheck","nextNum","testId","getAllCurrentIds","ids","silent","i","hasConflicts","a","b","aRank","aFile","bRank","bFile","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#previousFen","#previousState","#initPosition","#initializeState","fen","stateWithIds","assignPieceIdsWithState","INTRO_POSITION","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","move","acc","p","c","a","ADVANCED_POSITION","encodeFEN","get","getTop","piece","states","frequencyMap","map","str","isGameOver","pgn","parsePGN","moves","found","m","generateMovesForSquare","generateArata","hp","boardMoves","SQUARES","handMoves","encodePGN","lastMove","validateFen"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gungi.js",
3
- "version": "3.2.0",
3
+ "version": "3.2.1",
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",