gungi.js 3.0.7 → 3.1.0

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/README.md CHANGED
@@ -8,7 +8,7 @@ gungi.js is a TypeScript gungi library for the strategy game from the HUNTER×HU
8
8
  Credit to these two reddit posts from [u/magickirua](https://www.reddit.com/r/HunterXHunter/comments/uqrtct/gungi_the_official_rules) and [u/MythicalTenshi](https://www.reddit.com/r/HunterXHunter/comments/105f43g/comment/j3evkkq)
9
9
  which translate the rule book.
10
10
 
11
- gungi.js is used for move generation/validation, piece placement/movement, and endgame detection - basically everything but the AI.
11
+ gungi.js is used for move generation/validation, piece placement/movement, piece ID tracking, and endgame detection - basically everything but the AI.
12
12
 
13
13
  ## Installation
14
14
 
@@ -82,7 +82,7 @@ export const TACTICIAN = '謀';
82
82
  // starting positions (in FEN)
83
83
  export const INTRO_POSITION =
84
84
  '3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1';
85
- export const BEGINNNER_POSITION =
85
+ export const BEGINNER_POSITION =
86
86
  '3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1';
87
87
  export const INTERMEDIATE_POSITION =
88
88
  '9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1';
@@ -125,7 +125,7 @@ let gungi = new Gungi(
125
125
  Returns a string containing an ASCII diagram of the current position with ANSI colors. Options is an optional parameter which may contain a 'english' flag to display the pieces in English symbols.
126
126
 
127
127
  ```ts
128
- const gungi = new Gungi(BEGINNNER_POSITION);
128
+ const gungi = new Gungi(BEGINNER_POSITION);
129
129
 
130
130
  // make some moves
131
131
  gungi.move('槍(8-5-1)(7-5-2)付');
@@ -232,7 +232,7 @@ gungi.board();
232
232
  Returns a list of pieces captured. Color is an optional parameter to filter pieces by player color
233
233
 
234
234
  ```ts
235
- const gungi = new Gungi(BEGINNNER_POSITION);
235
+ const gungi = new Gungi(BEGINNER_POSITION);
236
236
  gungi.move('新小(7-5-2)付');
237
237
  gungi.move('兵(3-5-1)(4-5-1)');
238
238
  gungi.move('新槍(7-4-2)付');
@@ -258,7 +258,7 @@ gungi.fen();
258
258
  Returns the FEN string for the current position.
259
259
 
260
260
  ```ts
261
- const gungi = new Gungi(BEGINNNER_POSITION);
261
+ const gungi = new Gungi(BEGINNER_POSITION);
262
262
 
263
263
  // make some moves
264
264
  gungi.move('槍(8-5-1)(7-5-2)付');
@@ -274,7 +274,7 @@ gungi.fen();
274
274
  Returns the tower of pieces on the square. Returns `undefined` if the square is empty.
275
275
 
276
276
  ```ts
277
- const gungi = new Gungi(BEGINNNER_POSITION);
277
+ const gungi = new Gungi(BEGINNER_POSITION);
278
278
 
279
279
  gungi.move('砦(7-3-1)(7-4-2)付');
280
280
 
@@ -299,12 +299,25 @@ gungi.getDraftingRights('b');
299
299
  // -> true
300
300
  ```
301
301
 
302
+ ### .getBoardWithIds()
303
+
304
+ Returns a copy of the 3D board tensor with all piece ID information included. Each piece object includes an `id` field with its unique identifier.
305
+
306
+ ```ts
307
+ const gungi = new Gungi(BEGINNER_POSITION);
308
+ const boardWithIds = gungi.getBoardWithIds();
309
+
310
+ // Access piece with ID
311
+ const piece = boardWithIds[6][0][0]; // 7-1 square
312
+ // -> { square: '7-1', tier: 1, type: '兵', color: 'w', id: '兵-w-1' }
313
+ ```
314
+
302
315
  ### .getTop(square)
303
316
 
304
317
  Returns the top piece of the tower on the square. Returns `undefined` if the square is empty.
305
318
 
306
319
  ```ts
307
- const gungi = new Gungi(BEGINNNER_POSITION);
320
+ const gungi = new Gungi(BEGINNER_POSITION);
308
321
 
309
322
  gungi.get('7-4');
310
323
  // -> [{ square: '7-4', tier: 1, type: '侍', color: 'w' }]
@@ -312,12 +325,95 @@ gungi.get('7-3');
312
325
  // -> undefined
313
326
  ```
314
327
 
328
+ ### .getHandPieceId(type, color, index)
329
+
330
+ Returns the ID of a specific hand piece by type, color, and index. Useful for selecting which specific piece to play when multiple pieces of the same type are in hand.
331
+
332
+ ```ts
333
+ const gungi = new Gungi(BEGINNER_POSITION);
334
+
335
+ // Get ID of first major general in white's hand
336
+ const firstId = gungi.getHandPieceId('小', 'w', 0);
337
+ // -> '小-w-1'
338
+
339
+ // Get ID of second major general (if exists)
340
+ const secondId = gungi.getHandPieceId('小', 'w', 1);
341
+ // -> '小-w-2' or undefined if only one exists
342
+ ```
343
+
344
+ ### .getHandPieceIds(type?, color?)
345
+
346
+ Returns an array of all hand piece IDs. Can optionally filter by piece type and color.
347
+
348
+ ```ts
349
+ const gungi = new Gungi(BEGINNER_POSITION);
350
+
351
+ // Get all white major general IDs
352
+ const whiteGeneralIds = gungi.getHandPieceIds('小', 'w');
353
+ // -> ['小-w-1', '小-w-2']
354
+
355
+ // Get all hand piece IDs
356
+ const allHandIds = gungi.getHandPieceIds();
357
+ // -> ['小-w-1', '小-w-2', '槍-w-1', ..., '小-b-1', '小-b-2', ...]
358
+ ```
359
+
360
+ ### .getHandWithIds(color?)
361
+
362
+ Returns hand pieces with individual ID arrays included. Similar to `.hand()` but includes the `ids` field for each hand piece.
363
+
364
+ ```ts
365
+ const gungi = new Gungi(BEGINNER_POSITION);
366
+
367
+ const whiteHandWithIds = gungi.getHandWithIds('w');
368
+ // -> [
369
+ // { type: '小', count: 2, color: 'w', ids: ['小-w-1', '小-w-2'] },
370
+ // { type: '槍', count: 3, color: 'w', ids: ['槍-w-1', '槍-w-2', '槍-w-3'] },
371
+ // ...
372
+ // ]
373
+ ```
374
+
375
+ ### .getPieceById(id)
376
+
377
+ Returns the piece object with the specified ID. Searches the entire board to find the piece.
378
+
379
+ ```ts
380
+ const gungi = new Gungi(BEGINNER_POSITION);
381
+
382
+ // Find piece by its unique ID
383
+ const piece = gungi.getPieceById('兵-w-1');
384
+ // -> { square: '7-1', tier: 1, type: '兵', color: 'w', id: '兵-w-1' }
385
+
386
+ // Returns undefined if piece doesn't exist or was captured
387
+ const nonexistent = gungi.getPieceById('兵-w-999');
388
+ // -> undefined
389
+ ```
390
+
391
+ ### .getPieceId(square, tier?)
392
+
393
+ Returns the unique ID of the piece at the specified location. If tier is omitted, returns the ID of the top piece.
394
+
395
+ ```ts
396
+ const gungi = new Gungi(BEGINNER_POSITION);
397
+
398
+ // Get ID of top piece at square
399
+ const topPieceId = gungi.getPieceId('7-1');
400
+ // -> '兵-w-1'
401
+
402
+ // Get ID of piece at specific tier
403
+ const specificTierId = gungi.getPieceId('7-4', 2); // After stacking
404
+ // -> '砦-w-1'
405
+
406
+ // Returns undefined if no piece at location
407
+ const emptyId = gungi.getPieceId('5-5');
408
+ // -> undefined
409
+ ```
410
+
315
411
  ### .hand(color)
316
412
 
317
413
  Returns a list of pieces in players' hand. Color is an optional parameter to filter pieces by player color
318
414
 
319
415
  ```ts
320
- const gungi = new Gungi(BEGINNNER_POSITION);
416
+ const gungi = new Gungi(BEGINNER_POSITION);
321
417
 
322
418
  // make some moves
323
419
  gungi.move('槍(8-5-1)(7-5-2)付');
@@ -350,7 +446,7 @@ Returns a list containing the moves of the current game. Options is an optional
350
446
  A FEN string of the position prior to the move being made is added to the verbose history output.
351
447
 
352
448
  ```ts
353
- const gungi = new Gungi(BEGINNNER_POSITION);
449
+ const gungi = new Gungi(BEGINNER_POSITION);
354
450
  gungi.move('新小(7-5-2)付');
355
451
  gungi.move('兵(3-5-1)(4-5-1)');
356
452
  gungi.move('新槍(7-4-2)付');
@@ -700,7 +796,7 @@ The `before` and `after` keys contain the FEN of the position before and after t
700
796
  Returns the game in PGN format. Options is an optional parameter which may include max width and/or a newline character settings.
701
797
 
702
798
  ```ts
703
- const gungi = new Gungi(BEGINNNER_POSITION);
799
+ const gungi = new Gungi(BEGINNER_POSITION);
704
800
  gungi.move('槍(8-5-1)(7-5-2)付');
705
801
  gungi.move('新馬(1-7-1)');
706
802
  gungi.move('新忍(8-7-2)付');
@@ -734,7 +830,7 @@ gungi.turn();
734
830
  Takeback the last half-move, returning a move object if successful, otherwise null.
735
831
 
736
832
  ```ts
737
- const gungi = new Gungi(BEGINNNER_POSITION);
833
+ const gungi = new Gungi(BEGINNER_POSITION);
738
834
 
739
835
  gungi.fen();
740
836
  // -> '3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1'
package/dist/index.d.ts CHANGED
@@ -4,11 +4,13 @@ type Piece = {
4
4
  tier: number;
5
5
  type: PieceType;
6
6
  color: Color;
7
+ id?: string;
7
8
  };
8
9
  type HandPiece = {
9
10
  type: PieceType;
10
11
  color: Color;
11
12
  count: number;
13
+ ids?: string[];
12
14
  };
13
15
  type Move = {
14
16
  color: Color;
@@ -50,7 +52,7 @@ declare const ENGLISH_NAMES: Record<PieceType, string>;
50
52
  declare const FEN_CODES: Record<PieceType, string>;
51
53
 
52
54
  declare const INTRO_POSITION = "3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1";
53
- declare const BEGINNNER_POSITION = "3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1";
55
+ declare const BEGINNER_POSITION = "3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1";
54
56
  declare const INTERMEDIATE_POSITION = "9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1";
55
57
  declare const ADVANCED_POSITION = "9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";
56
58
  type FenValidationResult = {
@@ -104,6 +106,19 @@ declare class Gungi {
104
106
  ok: boolean;
105
107
  error?: string;
106
108
  };
109
+ getPieceId(square: string, tier?: number): string | undefined;
110
+ getPieceById(id: string): Piece | undefined;
111
+ getHandPieceIds(type?: string, color?: Color): string[];
112
+ getBoardWithIds(): (Piece | null)[][][];
113
+ getHandWithIds(color?: Color): HandPiece[];
114
+ getHandPieceId(type: string, color: Color, index?: number): string | undefined;
115
+ removeHandPieceId(type: string, color: Color, id: string): boolean;
116
+ getIdRegistryState(): {
117
+ pieceIdMap: Map<string, string>;
118
+ handIdMap: Map<string, string[]>;
119
+ idCounters: Map<string, number>;
120
+ reverseMap: Map<string, string>;
121
+ };
107
122
  }
108
123
 
109
- export { ADVANCED_POSITION, ARATA, ARCHER, BEGINNNER_POSITION, BETRAY, BLACK, CANNON, CANONICAL_NAMES, ENGLISH_NAMES, FEN_CODES, FORTRESS, GENERAL, Gungi, INTERMEDIATE_POSITION, INTRO_POSITION, LANCER, LIEUTENANT_GENERAL, MAJOR_GENERAL, MARSHAL, MUSKETEER, RIDER, SOLDIER, SPY, SQUARES, TACTICIAN, TAKE, TSUKE, WARRIOR, WHITE, validateFen };
124
+ export { ADVANCED_POSITION, ARATA, ARCHER, BEGINNER_POSITION, BETRAY, BLACK, CANNON, CANONICAL_NAMES, ENGLISH_NAMES, FEN_CODES, FORTRESS, GENERAL, Gungi, INTERMEDIATE_POSITION, INTRO_POSITION, LANCER, LIEUTENANT_GENERAL, MAJOR_GENERAL, MARSHAL, MUSKETEER, RIDER, SOLDIER, SPY, SQUARES, TACTICIAN, TAKE, TSUKE, WARRIOR, WHITE, validateFen };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import S from"picocolors";var F=t=>Object.entries(t).reduce((e,[r,o])=>({...e,[o]:r}),{}),O={intro:0,beginner:1,intermediate:2,advanced:3},q=F(O),te="w",re="b",oe="\u4ED8",ne="\u53D6",ie="\u8FD4",se="\u65B0",ae="\u5E25",ce="\u5927",le="\u4E2D",pe="\u5C0F",ue="\u4F8D",de="\u69CD",fe="\u99AC",he="\u5FCD",me="\u7826",ge="\u5175",be="\u7832",ye="\u5F13",Ne="\u7B52",Pe="\u8B00",U=Array.from({length:9},(t,e)=>e+1).flatMap(t=>Array.from({length:9},(e,r)=>`${t}-${9-r}`)),P={marshal:"\u5E25",general:"\u5927",lieutenant_general:"\u4E2D",major_general:"\u5C0F",warrior:"\u4F8D",lancer:"\u69CD",rider:"\u99AC",spy:"\u5FCD",fortress:"\u7826",soldier:"\u5175",cannon:"\u7832",archer:"\u5F13",musketeer:"\u7B52",tactician:"\u8B00"},E=F(P),w={marshal:"m",general:"g",lieutenant_general:"i",major_general:"j",warrior:"w",lancer:"n",rider:"r",spy:"s",fortress:"f",soldier:"d",cannon:"c",archer:"a",musketeer:"k",tactician:"t"},W=F(w),D=(t,[e,r,o])=>{let n=t===t.toLowerCase()?"b":"w",s=W[t.toLowerCase()];return{square:`${e}-${r}`,tier:o,type:P[s],color:n}},K=(t,e)=>{let r=t===t.toLowerCase()?"b":"w",o=W[t.toLowerCase()];return{type:P[o],count:e,color:r}},xe={\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"},ve={\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"},Te={\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 G(t,e,r=!1){return t.forEach(o=>{let n=r?o.color==="b"?"w":"b":o.color,s=e.find(a=>a.type===o.type&&a.color===n),i=e.findIndex(a=>a.type===o.type&&a.color===n);s&&(s.count--,s.count===0&&e.splice(i,1))}),e}function J(t,e,r){let[o,n]=t.split("-").map(Number),s=C(t,r);s&&(r[o-1][9-n]=s.map(i=>(e.find(u=>JSON.stringify(u)===JSON.stringify(i))&&(i.color=i.color==="b"?"w":"b"),i)))}function B(t,e,r){let[o,n]=t.split("-").map(Number),s=C(t,r);if(!s)return;let i=s.filter(a=>!e.some(u=>JSON.stringify(u)===JSON.stringify(a)));i.length===0?r[o-1][9-n]=[null]:r[o-1][9-n]=i}function k(t,e){let[r,o]=t.split("-").map(Number),n=C(t,e);n&&(n.pop(),n.length===0&&(e[r-1][9-o]=[null]))}function V(t,e){let[r,o]=t.square.split("-").map(Number);e[r-1][9-o][0]?e[r-1][9-o].push(t):e[r-1][9-o]=[t]}function T(t,e){let r=C(t,e);return r?r.at(-1):void 0}function C(t,e){let[r,o]=t.split("-").map(Number);if(r<1||r>9||o<1||o>9)return;let n=e[r-1][9-o];if(n[0])return n}function Y(t){return t.flat().flat().filter(r=>r?.type==="\u5E25").length!==2}var z="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",we="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",Ce="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 x(t){let e=H(t);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[r,o,n,s,i,a]=t.split(" "),u=r.split("/").map((m,p)=>m.split("|").reduce((c,l)=>{if(l.includes(":")){let f=l.split(":").map((d,h)=>D(d,[p+1,9-c.length,h+1]));c.push(f)}else{let f=l.split("").reduce((d,h)=>(Number.isInteger(+h)?d=d.concat(Array(+h).fill(null)):d.push(D(h,[p+1,9-c.length-d.length,1])),d),[]).map(d=>[d]);c=c.concat(f)}return c},[])),g=o.split("/").flatMap(m=>{let p=[];if(m!=="-")for(let c=0;c<m.length;c+=2){let l=m[c],f=+m[c+1];p.push(K(l,f))}return p});return{board:u,hand:g,turn:n,mode:q[+s],drafting:{w:i.includes("w"),b:i.includes("b")},moveNumber:+a}}function I(t){let e="",r=0;for(let a=0;a<9;a++){for(let u=0;u<9;u++){let g=t.board[a][u];if(g[0]===null){r++;continue}if(r&&(e+=r,r=0),g.length>1)e+="|"+g.map(m=>{if(!m)return null;let p=w[E[m.type]];return m.color==="w"?p.toUpperCase():p}).join(":")+"|";else{let{type:m,color:p}=g[0],c=w[E[m]];e+=p==="w"?c.toUpperCase():c}}e+=r?`${r}/`:"/",r=0}let o="",n=t.hand.filter(a=>a.color==="w"),s=t.hand.filter(a=>a.color==="b");n.forEach(a=>{let u=w[E[a.type]];o+=`${a.color==="w"?u.toUpperCase():u}${a.count}`}),o+=n.length>0?"/":"-/",s.forEach(a=>{let u=w[E[a.type]];o+=`${a.color==="w"?u.toUpperCase():u}${a.count}`}),o+=s.length>0?"":"-";let i=Object.keys(t.drafting).filter(a=>t.drafting[a]);return`${e.slice(0,-1)} ${o} ${t.turn} ${O[t.mode]} ${i.length>0?i.join(""):"-"} ${t.moveNumber}`}function H(t){let e=t.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[r,o,n,s,i,a]=e,u=r.split("/");if(u.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${u.length}]`};for(let c=0;c<u.length;c++){let f=u[c].split("|"),d=0;for(let h=0;h<f.length;h++){let b=f[h];if(b.includes(":")){d++;let y=b.split(":");if(y.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${c+1}-${d})`};if(!y.every(N=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(N)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${c+1}-${d})`}}else{let y=b.split("");for(let N=0;N<y.length;N++){let R=y[N];if(Number.isInteger(+R))d+=+R;else if(d++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(R))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${c+1}-${d})`}}}}if(d!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${d}] in rank: ${c+1}`}}let g=o.split("/");if(g.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${g.length}]`};let[m,p]=g;if(m.length===1&&m!=="-"||p.length===1&&p!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(m.length>1&&m.length%2!==0||p.length>1&&p.length%2!==0)return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece count]"};if(m.length>1)for(let c=0;c<m.length;c+=2){if(!"MGIJWNRSFDCAKT".includes(m[c]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+m[c+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}if(p.length>1)for(let c=0;c<p.length;c+=2){if(!"mgijwnrsfdcakt".includes(p[c]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+p[c+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(+a)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${a}]`}}var Ee=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],$e={\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 Ae(t,e,r,o,n){let[s,i]=e,[a,u]=r,[g,m]=t,p=T(`${a}-${u}`,n),c=[],l={x:i,y:s};for(;l.x!==u||l.y!==a;){l.x-=m,l.y-=g;let h=T(`${l.y}-${l.x}`,n);if(h&&h.tier>p.tier)return[];let b=p.color==="b"?-1:1,y=T(`${l.y+b}-${l.x}`,n);if(y&&y.square===`${a}-${u}`)break}let f={x:i,y:s},d=0;for(;d<o&&!(f.x<1||f.x>9||f.y<1||f.y>9);){let h=T(`${f.y}-${f.x}`,n);if(h&&h.tier>p.tier)break;c.push(`${f.y}-${f.x}`);let b=[P.cannon,P.musketeer,P.archer];if(h&&!b.includes(p.type))break;f.x+=m,f.y+=g,d++}return c}function L(t,e){let{board:r,turn:o,mode:n,hand:s}=x(e),i=T(t,r);if(!i||o!==i.color)return[];let[a,u]=t.split("-").map(Number);return $e[i.type].flatMap((p,c)=>{let l=typeof p=="number"?p:p[0],f=typeof p=="number"?1:p[1];if(l<1)return[];let[d,h]=Ee[c];i.color==="b"&&(d*=-1,h*=-1);let[b,y]=l===1/0?[a+d,u+h]:[a+l*d,u+h],N=l===1/0?1/0:i.tier+f-1;return Ae([d,h],[b,y],[a,u],N,r)}).reduce((p,c)=>{let l=T(c,r),f=C(c,r),d=n==="advanced"?3:2,h=["advanced","intermediate"].includes(n);if(!l||!f)p.push(A(i,`${c}-1`,e,"route"));else{if(l.tier<d&&l.type!==P.marshal&&((i.type!==P.marshal||h)&&p.push(A(i,`${c}-${l.tier+1}`,e,"tsuke")),i.type===P.tactician&&l.color!==i.color)){let b=f.filter(v=>v.color!==i.color),y=s.filter(v=>v.color===i.color),N=b.reduce((v,$)=>(v.set($.type,(v.get($.type)??0)+1),v),new Map),R=Array.from(N.entries()).filter(([v,$])=>y.some(j=>j.type===v&&j.count>=$)).flatMap(([v])=>b.filter($=>$.type===v)),ee=ke(R);p.push(...ee.map(v=>A(i,`${c}-${l.tier+1}`,e,"betray",v)))}if(l.color!==i.color){let b=f.filter(N=>N.color===i.color).length+1,y=f.filter(N=>N.color!==i.color);p.push(A(i,`${c}-${b}`,e,"capture",y))}}return p},[])}function M(t,e){let{board:r,turn:o,mode:n,hand:s,drafting:i}=x(e);if(!t||o!==t.color)return[];if(!!s.some(l=>l.type===P.marshal&&l.color===t.color)&&t.type!==P.marshal)return[];let u=i.b||i.w,g=n==="advanced"?3:2,m=[],p=[];if(u)m=t.color==="w"?[7,8,9]:[1,2,3];else{let l=t.color==="b"?1:9,f=t.color==="b"?9:1,d=t.color==="b"?1:-1;for(let h=l;t.color==="b"?h<=f:h>=f;h+=d)Array.from({length:9}).map((y,N)=>T(`${h}-${N+1}`,r)).some(y=>y&&y.color===t.color)?(m.push(...p,h),p=[]):p.push(h)}return m.flatMap(l=>Array.from({length:9},(f,d)=>`${l}-${d+1}`)).reduce((l,f)=>{let d=T(f,r),h={type:t.type,color:t.color,square:f,tier:0};if(!d||d.color===h.color&&d.tier<g&&d.type!==P.marshal){let b=(d?.tier??0)+1;l.push(A(h,`${f}-${b}`,e,"arata")),i[t.color]&&l.push(A(h,`${f}-${b}`,e,"arata",[],!0))}return l},[])}function A(t,e,r,o,n,s){let i=t.tier!==0?`(${t.square}-${t.tier})`:"",a=+(e.split("-").at(-1)??0),u=o==="arata"?"\u65B0":"",g=o==="capture"?"\u53D6":"",m=o==="tsuke"||a!==1&&a-t.tier>0?"\u4ED8":"",p=o==="betray"?`\u8FD4${n?.map(h=>h.type).join("")}`:"",c=s?"\u7D42":"",l={piece:t.type,color:t.color,from:i.slice(1,-1),to:e,type:o,san:`${u}${t.type}${i}${g}(${e})${p||m}${c}`,before:r,after:"",draftFinished:s,captured:n},{after:f,gameOverSAN:d}=Re(l,l.before);return l.after=f,l.san+=d,l}function Re(t,e){let{board:r,hand:o,mode:n,turn:s,drafting:i,moveNumber:a}=x(e),[u,g,m]=t.to.split("-"),p={type:t.piece,color:t.color,square:`${u}-${g}`,tier:+m};t.type==="route"||t.type==="tsuke"?k(t.from,r):t.type==="capture"?(k(t.from,r),B(`${u}-${g}`,t.captured,r)):t.type==="betray"?(k(t.from,r),J(`${u}-${g}`,t.captured,r),G(t.captured,o,!0)):t.type==="arata"&&(G([p],o),t.draftFinished&&(i[t.color]=!1)),V(p,r),s==="b"&&(i.w||!i.b)&&a++,s==="w"&&!i.b&&!i.w&&t.draftFinished&&a++,i.w===i.b?(!t.draftFinished||s!=="w")&&(s=s==="b"?"w":"b"):!i.b&&s==="b"?s="w":!i.w&&s==="w"&&(s="b");let c="";return t.captured?.some(l=>l.type===P.marshal)&&(c="\u52DD"),{after:I({board:r,hand:o,mode:n,turn:s,drafting:i,moveNumber:a}),gameOverSAN:c}}function ke(t){let e=[];function r(o,n){n.length>0&&e.push([...n]);for(let s=o;s<t.length;s++)n.push(t[s]),r(s+1,n),n.pop()}return r(0,[]),e}function Q(t,e){let r=e?.maxWidth??6,o=e?.newline??`
2
- `,n="",s=0;return t.forEach((i,a)=>{let u=x(i.before);if(u.moveNumber!==s){let g=i.color==="w"?".":"...";n+=`${u.moveNumber}${g} `,s=u.moveNumber}n+=`${i.san} `,(a+1)%r===0&&(n+=o)}),n.replaceAll(" "," ").trim()}function X(t,e){let r=e?.newline??`
3
- `;return t.split(r).flatMap(n=>n.replace(/\d+\.+/g,"").split(" ")).filter(n=>n!=="")}var Z=class{#r;#n;#i;#s;#o;#c;#e=[];#a;#t({board:e,hand:r,turn:o,moveNumber:n,drafting:s,mode:i}){this.#r=e,this.#n=r,this.#i=o,this.#s=n,this.#o=s,this.#c=i}constructor(e){this.#a=e??z,this.#t(x(this.#a))}ascii(e){let r={1:S.yellow,2:S.blue,3:S.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 a=w[E[i.type]],u=i.color==="w"?a.toUpperCase():a,g=r[i.tier](e?.english?String.fromCharCode(u.charCodeAt(0)+65248):i.type);o+=i.color==="w"?g:S.dim(g)}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(a=>a.type===s.type&&a.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.#t(x(_)),this.#e=[]}fen(){return I({board:this.#r,hand:this.#n,turn:this.#i,mode:this.#c,drafting:this.#o,moveNumber:this.#s})}get(e){return C(e,this.#r)}getDraftingRights(e){return e?this.#o[e]:this.#o}getTop(e){return T(e,this.#r)}hand(e){return e?this.#n.filter(r=>r.color===e):this.#n}history(e){return e?.verbose?this.#e:this.#e.map(r=>r.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 r=e.reduce((o,n)=>(o.set(n,(o.get(n)||0)+1),o),new Map);return Math.max(...r.values())===4}isGameOver(){return!this.inDraft()&&(Y(this.#r)||this.isFourfoldRepetition())}load(e){this.#t(x(e))}loadPgn(e,r=_,o){this.#t(x(r)),this.#e=[],X(e,o).forEach(s=>this.move(s))}move(e){let r=this.moves({verbose:!0}),o=typeof e=="string"?r.find(n=>n.san===e):r.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(x(o.after)),o}moves(e){if(this.isGameOver())return[];if(e?.square){let r=L(e.square,this.fen());return e.verbose?r:r.map(o=>o.san)}else if(e?.arata){let r=M(e.arata,this.fen());return e.verbose?r:r.map(o=>o.san)}else if(this.inDraft()){let r=this.hand().flatMap(o=>M(o,this.fen()));return e?.verbose?r:r.map(o=>o.san)}else{let r=U.flatMap(s=>L(s,this.fen())),o=this.hand().flatMap(s=>M(s,this.fen())),n=[...r,...o];return e?.verbose?n:n.map(s=>s.san)}}moveNumber(){return this.#s}pgn(e){return Q(this.#e,e)}print(e){console.log(this.ascii(e))}reset(){this.#t(x(this.#a)),this.#e=[]}turn(){return this.#i}undo(){let e=this.#e.pop();return e?(this.#t(x(e.before)),e):null}validateFen(e){return H(e)}};export{_ as ADVANCED_POSITION,se as ARATA,ye as ARCHER,we as BEGINNNER_POSITION,ie as BETRAY,re as BLACK,be as CANNON,xe as CANONICAL_NAMES,ve as ENGLISH_NAMES,Te as FEN_CODES,me as FORTRESS,ce as GENERAL,Z as Gungi,Ce as INTERMEDIATE_POSITION,z as INTRO_POSITION,de as LANCER,le as LIEUTENANT_GENERAL,pe as MAJOR_GENERAL,ae as MARSHAL,Ne as MUSKETEER,fe as RIDER,ge as SOLDIER,he as SPY,U as SQUARES,Pe as TACTICIAN,ne as TAKE,oe as TSUKE,ue as WARRIOR,te as WHITE,H as validateFen};
1
+ import F from"picocolors";var O=o=>Object.entries(o).reduce((e,[r,t])=>({...e,[t]:r}),{}),H={intro:0,beginner:1,intermediate:2,advanced:3},j=O(H),re="w",ie="b",ne="\u4ED8",oe="\u53D6",se="\u8FD4",ce="\u65B0",ae="\u5E25",de="\u5927",le="\u4E2D",pe="\u5C0F",ue="\u4F8D",fe="\u69CD",he="\u99AC",ge="\u5FCD",me="\u7826",ye="\u5175",Pe="\u7832",be="\u5F13",Ie="\u7B52",Ne="\u8B00",U=Array.from({length:9},(o,e)=>e+1).flatMap(o=>Array.from({length:9},(e,r)=>`${o}-${9-r}`)),I={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"},C=O(I),v={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"},B=O(v),D=(o,[e,r,t])=>{let i=o===o.toLowerCase()?"b":"w",n=B[o.toLowerCase()];return{square:`${e}-${r}`,tier:t,type:I[n],color:i}},K=(o,e)=>{let r=o===o.toLowerCase()?"b":"w",t=B[o.toLowerCase()];return{type:I[t],count:e,color:r}},we={\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"},xe={\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"},ve={\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 G(o,e,r=!1){return o.forEach(t=>{let i=r?t.color==="b"?"w":"b":t.color,n=e.find(c=>c.type===t.type&&c.color===i),s=e.findIndex(c=>c.type===t.type&&c.color===i);n&&(n.count--,n.count===0&&e.splice(s,1))}),e}function J(o,e,r){let[t,i]=o.split("-").map(Number),n=$(o,r);n&&(r[t-1][9-i]=n.map(s=>(e.find(a=>JSON.stringify(a)===JSON.stringify(s))&&(s.color=s.color==="b"?"w":"b"),s)))}function z(o,e,r){let[t,i]=o.split("-").map(Number),n=$(o,r);if(!n)return;let s=n.filter(c=>!e.some(a=>JSON.stringify(a)===JSON.stringify(c)));s.length===0?r[t-1][9-i]=[null]:r[t-1][9-i]=s}function R(o,e){let[r,t]=o.split("-").map(Number),i=$(o,e);i&&(i.pop(),i.length===0&&(e[r-1][9-t]=[null]))}function V(o,e){let[r,t]=o.square.split("-").map(Number);e[r-1][9-t][0]?e[r-1][9-t].push(o):e[r-1][9-t]=[o]}function x(o,e){let r=$(o,e);return r?r.at(-1):void 0}function $(o,e){let[r,t]=o.split("-").map(Number);if(r<1||r>9||t<1||t>9)return;let i=e[r-1][9-t];if(i[0])return i}function Y(o){return o.flat().flat().filter(r=>r?.type==="\u5E25").length!==2}function $e(o,e,r){return`${o}-${e}-${r}`}var E=class{pieceIdMap=new Map;handIdMap=new Map;idCounters=new Map;reverseMap=new Map;constructor(){this.initializeCounters()}initializeCounters(){let e=["\u5E25","\u5927","\u4E2D","\u5C0F","\u4F8D","\u69CD","\u99AC","\u5FCD","\u7826","\u5175","\u7832","\u5F13","\u7B52","\u8B00"],r=["w","b"];for(let t of e)for(let i of r){let n=`${t}-${i}`;this.idCounters.set(n,0),this.handIdMap.set(n,[])}}getNextId(e,r){let t=`${e}-${r}`,n=(this.idCounters.get(t)??0)+1;return this.idCounters.set(t,n),$e(e,r,n)}setPieceId(e,r,t){let i=`${e}-${r}`;this.pieceIdMap.set(i,t),this.reverseMap.set(t,i)}getPieceId(e,r){let t=`${e}-${r}`;return this.pieceIdMap.get(t)}removePieceId(e,r){let t=`${e}-${r}`,i=this.pieceIdMap.get(t);return i&&(this.pieceIdMap.delete(t),this.reverseMap.delete(i)),i}movePiece(e,r,t,i){let n=this.removePieceId(e,r);n&&this.setPieceId(t,i,n)}addToHand(e,r,t){let i=`${e}-${r}`,n=this.handIdMap.get(i)??[];this.handIdMap.set(i,[...n,...t])}removeFromHand(e,r,t=1){let i=`${e}-${r}`;return(this.handIdMap.get(i)??[]).splice(0,t)}getHandIds(e,r){let t=`${e}-${r}`;return[...this.handIdMap.get(t)??[]]}createPieceWithId(e,r,t,i){let n=this.getNextId(e,r);return this.setPieceId(t,i,n),{type:e,color:r,square:t,tier:i,id:n}}capturePieces(e){for(let r of e)if(r.id){this.removePieceId(r.square,r.tier);let t=r.color==="w"?"b":"w";this.addToHand(r.type,t,[r.id])}}betrayPieces(e){return e.map(r=>{if(r.id){let t=r.color==="w"?"b":"w",i=this.getNextId(r.type,t);return this.removePieceId(r.square,r.tier),this.setPieceId(r.square,r.tier,i),{...r,color:t,id:i}}return r})}syncWithBoard(e,r){this.pieceIdMap.clear(),this.reverseMap.clear();for(let t=0;t<9;t++)for(let i=0;i<9;i++){let n=e[t][i];if(n&&n[0])for(let s=0;s<n.length;s++){let c=n[s];c&&c.id&&this.setPieceId(c.square,c.tier,c.id)}}for(let t of r)if(t.ids&&t.ids.length>0){let i=`${t.type}-${t.color}`;this.handIdMap.set(i,[...t.ids])}}getRegistryState(){return{pieceIdMap:new Map(this.pieceIdMap),handIdMap:new Map(this.handIdMap),idCounters:new Map(this.idCounters),reverseMap:new Map(this.reverseMap)}}};var Q="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Ce="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",Te="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",W="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function N(o){let e=_(o);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[r,t,i,n,s,c]=o.split(" "),a=r.split("/").map((d,l)=>d.split("|").reduce((p,u)=>{if(u.includes(":")){let g=u.split(":").map((f,m)=>D(f,[l+1,9-p.length,m+1]));p.push(g)}else{let g=u.split("").reduce((f,m)=>(Number.isInteger(+m)?f=f.concat(Array(+m).fill(null)):f.push(D(m,[l+1,9-p.length-f.length,1])),f),[]).map(f=>[f]);p=p.concat(g)}return p},[])),h=t.split("/").flatMap(d=>{let l=[];if(d!=="-")for(let p=0;p<d.length;p+=2){let u=d[p],g=+d[p+1];l.push(K(u,g))}return l});return{board:a,hand:h,turn:i,mode:j[+n],drafting:{w:s.includes("w"),b:s.includes("b")},moveNumber:+c}}function A(o){let e="",r=0;for(let c=0;c<9;c++){for(let a=0;a<9;a++){let h=o.board[c][a];if(h[0]===null){r++;continue}if(r&&(e+=r,r=0),h.length>1)e+="|"+h.map(d=>{if(!d)return null;let l=v[C[d.type]];return d.color==="w"?l.toUpperCase():l}).join(":")+"|";else{let{type:d,color:l}=h[0],p=v[C[d]];e+=l==="w"?p.toUpperCase():p}}e+=r?`${r}/`:"/",r=0}let t="",i=o.hand.filter(c=>c.color==="w"),n=o.hand.filter(c=>c.color==="b");i.forEach(c=>{let a=v[C[c.type]];t+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),t+=i.length>0?"/":"-/",n.forEach(c=>{let a=v[C[c.type]];t+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),t+=n.length>0?"":"-";let s=Object.keys(o.drafting).filter(c=>o.drafting[c]);return`${e.slice(0,-1)} ${t} ${o.turn} ${H[o.mode]} ${s.length>0?s.join(""):"-"} ${o.moveNumber}`}function _(o){let e=o.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[r,t,i,n,s,c]=e,a=r.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("|"),f=0;for(let m=0;m<g.length;m++){let y=g[m];if(y.includes(":")){f++;let P=y.split(":");if(P.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${f})`};if(!P.every(b=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(b)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${f})`}}else{let P=y.split("");for(let b=0;b<P.length;b++){let k=P[b];if(Number.isInteger(+k))f+=+k;else if(f++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(k))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${f})`}}}}if(f!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${f}] in rank: ${p+1}`}}let h=t.split("/");if(h.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${h.length}]`};let[d,l]=h;if(d.length===1&&d!=="-"||l.length===1&&l!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(d.length>1&&d.length%2!==0||l.length>1&&l.length%2!==0)return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece 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]"}}if(l.length>1)for(let p=0;p<l.length;p+=2){if(!"mgijwnrsfdcakt".includes(l[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+l[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return i!=="w"&&i!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${i}]`}:n.length!==1||!"0123".includes(n)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${n}]`}: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 Me=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],ke={\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 Ee(o,e,r,t,i){let[n,s]=e,[c,a]=r,[h,d]=o,l=x(`${c}-${a}`,i),p=[],u={x:s,y:n};for(;u.x!==a||u.y!==c;){u.x-=d,u.y-=h;let m=x(`${u.y}-${u.x}`,i);if(m&&m.tier>l.tier)return[];let y=l.color==="b"?-1:1,P=x(`${u.y+y}-${u.x}`,i);if(P&&P.square===`${c}-${a}`)break}let g={x:s,y:n},f=0;for(;f<t&&!(g.x<1||g.x>9||g.y<1||g.y>9);){let m=x(`${g.y}-${g.x}`,i);if(m&&m.tier>l.tier)break;p.push(`${g.y}-${g.x}`);let y=[I.cannon,I.musketeer,I.archer];if(m&&!y.includes(l.type))break;g.x+=d,g.y+=h,f++}return p}function q(o,e){let{board:r,turn:t,mode:i,hand:n}=N(e),s=x(o,r);if(!s||t!==s.color)return[];let[c,a]=o.split("-").map(Number);return ke[s.type].flatMap((l,p)=>{let u=typeof l=="number"?l:l[0],g=typeof l=="number"?1:l[1];if(u<1)return[];let[f,m]=Me[p];s.color==="b"&&(f*=-1,m*=-1);let[y,P]=u===1/0?[c+f,a+m]:[c+u*f,a+m],b=u===1/0?1/0:s.tier+g-1;return Ee([f,m],[y,P],[c,a],b,r)}).reduce((l,p)=>{let u=x(p,r),g=$(p,r),f=i==="advanced"?3:2,m=["advanced","intermediate"].includes(i);if(!u||!g)l.push(M(s,`${p}-1`,e,"route"));else{if(u.tier<f&&u.type!==I.marshal&&((s.type!==I.marshal||m)&&l.push(M(s,`${p}-${u.tier+1}`,e,"tsuke")),s.type===I.tactician&&u.color!==s.color)){let y=g.filter(w=>w.color!==s.color),P=n.filter(w=>w.color===s.color),b=y.reduce((w,T)=>(w.set(T.type,(w.get(T.type)??0)+1),w),new Map),k=Array.from(b.entries()).filter(([w,T])=>P.some(L=>L.type===w&&L.count>=T)).flatMap(([w])=>y.filter(T=>T.type===w)),te=Ae(k);l.push(...te.map(w=>M(s,`${p}-${u.tier+1}`,e,"betray",w)))}if(u.color!==s.color){let y=g.filter(b=>b.color===s.color).length+1,P=g.filter(b=>b.color!==s.color);l.push(M(s,`${p}-${y}`,e,"capture",P))}}return l},[])}function S(o,e){let{board:r,turn:t,mode:i,hand:n,drafting:s}=N(e);if(!o||t!==o.color)return[];if(!!n.some(u=>u.type===I.marshal&&u.color===o.color)&&o.type!==I.marshal)return[];let a=s.b||s.w,h=i==="advanced"?3:2,d=[],l=[];if(a)d=o.color==="w"?[7,8,9]:[1,2,3];else{let u=o.color==="b"?1:9,g=o.color==="b"?9:1,f=o.color==="b"?1:-1;for(let m=u;o.color==="b"?m<=g:m>=g;m+=f)Array.from({length:9}).map((P,b)=>x(`${m}-${b+1}`,r)).some(P=>P&&P.color===o.color)?(d.push(...l,m),l=[]):l.push(m)}return d.flatMap(u=>Array.from({length:9},(g,f)=>`${u}-${f+1}`)).reduce((u,g)=>{let f=x(g,r),m={type:o.type,color:o.color,square:g,tier:0};if(!f||f.color===m.color&&f.tier<h&&f.type!==I.marshal){let y=(f?.tier??0)+1;u.push(M(m,`${g}-${y}`,e,"arata")),s[o.color]&&u.push(M(m,`${g}-${y}`,e,"arata",[],!0))}return u},[])}function M(o,e,r,t,i,n){let s=o.tier!==0?`(${o.square}-${o.tier})`:"",c=+(e.split("-").at(-1)??0),a=t==="arata"?"\u65B0":"",h=t==="capture"?"\u53D6":"",d=t==="tsuke"||c!==1&&c-o.tier>0?"\u4ED8":"",l=t==="betray"?`\u8FD4${i?.map(m=>m.type).join("")}`:"",p=n?"\u7D42":"",u={piece:o.type,color:o.color,from:s.slice(1,-1),to:e,type:t,san:`${a}${o.type}${s}${h}(${e})${l||d}${p}`,before:r,after:"",draftFinished:n,captured:i},{after:g,gameOverSAN:f}=Re(u,u.before);return u.after=g,u.san+=f,u}function Re(o,e){let{board:r,hand:t,mode:i,turn:n,drafting:s,moveNumber:c}=N(e),[a,h,d]=o.to.split("-"),l={type:o.piece,color:o.color,square:`${a}-${h}`,tier:+d};o.type==="route"||o.type==="tsuke"?R(o.from,r):o.type==="capture"?(R(o.from,r),z(`${a}-${h}`,o.captured,r)):o.type==="betray"?(R(o.from,r),J(`${a}-${h}`,o.captured,r),G(o.captured,t,!0)):o.type==="arata"&&(G([l],t),o.draftFinished&&(s[o.color]=!1)),V(l,r),n==="b"&&(s.w||!s.b)&&c++,n==="w"&&!s.b&&!s.w&&o.draftFinished&&c++,s.w===s.b?(!o.draftFinished||n!=="w")&&(n=n==="b"?"w":"b"):!s.b&&n==="b"?n="w":!s.w&&n==="w"&&(n="b");let p="";return o.captured?.some(u=>u.type===I.marshal)&&(p="\u52DD"),{after:A({board:r,hand:t,mode:i,turn:n,drafting:s,moveNumber:c}),gameOverSAN:p}}function Ae(o){let e=[];function r(t,i){i.length>0&&e.push([...i]);for(let n=t;n<o.length;n++)i.push(o[n]),r(n+1,i),i.pop()}return r(0,[]),e}function X(o,e){let r=e?.maxWidth??6,t=e?.newline??`
2
+ `,i="",n=0;return o.forEach((s,c)=>{let a=N(s.before);if(a.moveNumber!==n){let h=s.color==="w"?".":"...";i+=`${a.moveNumber}${h} `,n=a.moveNumber}i+=`${s.san} `,(c+1)%r===0&&(i+=t)}),i.replaceAll(" "," ").trim()}function Z(o,e){let r=e?.newline??`
3
+ `;return o.split(r).flatMap(i=>i.replace(/\d+\.+/g,"").split(" ")).filter(i=>i!=="")}var ee=class{#r;#t;#s;#c;#o;#d;#i=[];#e;#a;#n({board:e,hand:r,turn:t,moveNumber:i,drafting:n,mode:s}){this.#r=e,this.#t=r,this.#s=t,this.#c=i,this.#o=n,this.#d=s,this.#l(),this.#p()}#l(){for(let e=0;e<9;e++)for(let r=0;r<9;r++){let t=this.#r[e][r];if(t&&t[0])for(let i=0;i<t.length;i++){let n=t[i];n&&!n.id&&(n.id=this.#e.createPieceWithId(n.type,n.color,n.square,n.tier).id)}}for(let e of this.#t)if(!e.ids||e.ids.length===0){e.ids=[];for(let r=0;r<e.count;r++){let t=this.#e.createPieceWithId(e.type,e.color,"hand",0).id;e.ids.push(t),this.#e.removePieceId("hand",0),this.#e.addToHand(e.type,e.color,[t])}}else if(this.#e.getHandIds(e.type,e.color).length!==e.count){let t=`${e.type}-${e.color}`;this.#e.addToHand(e.type,e.color,e.ids.slice())}}#p(){this.#e.syncWithBoard(this.#r,this.#t)}constructor(e){this.#a=e??Q,this.#e=new E,this.#n(N(this.#a))}ascii(e){let r={1:F.yellow,2:F.blue,3:F.green},t=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
4
+ `;t+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
5
+ `;for(let i=1;i<=9;i++){t+="\uFF5C";for(let n=9;n>0;n--){let s=this.getTop(`${i}-${n}`);if(!s){t+="\u30FB";continue}let c=v[C[s.type]],a=s.color==="w"?c.toUpperCase():c,h=r[s.tier](e?.english?String.fromCharCode(a.charCodeAt(0)+65248):s.type);t+=s.color==="w"?h:F.dim(h)}t+=`\uFF5C${String.fromCharCode(i-1+65297)}
6
+ `}return t+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
7
+ `,t}board(){return this.#r}captured(e){let t=this.#i.flatMap(i=>i.captured??[]).reduce((i,n)=>{let s=i.find(c=>c.type===n.type&&c.color===n.color);return s?s.count++:i.push({type:n.type,color:n.color,count:1}),i},[]);return e?t.filter(i=>i.color===e):t}clear(){this.#n(N(W)),this.#i=[]}fen(){return A({board:this.#r,hand:this.#t,turn:this.#s,mode:this.#d,drafting:this.#o,moveNumber:this.#c})}get(e){return $(e,this.#r)}getDraftingRights(e){return e?this.#o[e]:this.#o}getTop(e){return x(e,this.#r)}hand(e){return e?this.#t.filter(r=>r.color===e):this.#t}history(e){return e?.verbose?this.#i:this.#i.map(r=>r.san)}inDraft(){return this.#o.b||this.#o.w}isFourfoldRepetition(){let e=this.#i.map(t=>t.before.split(" ")[0]);e.length&&e.push(this.#i.at(-1).after.split(" ")[0]);let r=e.reduce((t,i)=>(t.set(i,(t.get(i)||0)+1),t),new Map);return Math.max(...r.values())===4}isGameOver(){return!this.inDraft()&&(Y(this.#r)||this.isFourfoldRepetition())}load(e){this.#n(N(e))}loadPgn(e,r=W,t){this.#n(N(r)),this.#i=[],Z(e,t).forEach(n=>this.move(n))}move(e){let r=this.moves({verbose:!0}),t=typeof e=="string"?r.find(n=>n.san===e):r.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(!t)throw new Error(`Illegal move: ${e}`);let i=this.#u(t);return this.#i.push(t),this.isFourfoldRepetition()&&(this.#i.at(-1).san+="\u505C"),this.#n(N(t.after)),this.#f(t,i),t}#u(e){let r={boardPieces:new Map,handPieces:new Map,movingPieceId:null,capturedIds:[],handPieceId:null};for(let t=0;t<9;t++)for(let i=0;i<9;i++){let n=this.#r[t][i];if(n&&n[0])for(let s of n)s&&s.id&&r.boardPieces.set(`${s.square}-${s.tier}`,s.id)}for(let t of this.#t)t.ids&&t.ids.length>0&&r.handPieces.set(`${t.type}-${t.color}`,[...t.ids]);if(e.from){let t=this.getTop(e.from);t&&t.id&&(r.movingPieceId=t.id)}if(e.type==="arata"){let t=this.#t.find(i=>i.type===e.piece&&i.color===e.color);t&&t.ids&&t.ids.length>0&&(r.handPieceId=t.ids[0])}return e.captured&&(r.capturedIds=e.captured.map(t=>t.id).filter(t=>t!==void 0)),r}#f(e,r){this.#e=new E;let[t,i,n]=e.to.split("-").map(Number);for(let s=0;s<9;s++)for(let c=0;c<9;c++){let a=this.#r[s][c];if(a&&a[0])for(let h=0;h<a.length;h++){let d=a[h];if(d){let l;if(s===t-1&&c===9-i&&h===n-1)e.type==="arata"&&r.handPieceId?l=r.handPieceId:r.movingPieceId?l=r.movingPieceId:l=this.#e.createPieceWithId(d.type,d.color,d.square,d.tier).id;else{let p=r.boardPieces.get(`${d.square}-${d.tier}`);p?l=p:l=this.#e.createPieceWithId(d.type,d.color,d.square,d.tier).id}d.id=l,this.#e.setPieceId(d.square,d.tier,l)}}}for(let s of this.#t){let c=`${s.type}-${s.color}`,a=r.handPieces.get(c)||[];if(e.captured&&e.type==="capture"){let h=e.captured.filter(d=>d.type===s.type&&(d.color==="w"?"b":"w")===s.color);for(let d of h)d.id&&a.push(d.id)}for(e.type==="arata"&&e.piece===s.type&&e.color===s.color&&r.handPieceId&&(a=a.filter(h=>h!==r.handPieceId));a.length<s.count;){let h=this.#e.createPieceWithId(s.type,s.color,"hand",0).id;this.#e.removePieceId("hand",0),a.push(h)}a=a.slice(0,s.count),s.ids=a,this.#e.addToHand(s.type,s.color,a)}}moves(e){if(this.isGameOver())return[];if(e?.square){let r=q(e.square,this.fen());return e.verbose?r:r.map(t=>t.san)}else if(e?.arata){let r=S(e.arata,this.fen());return e.verbose?r:r.map(t=>t.san)}else if(this.inDraft()){let r=this.hand().flatMap(t=>S(t,this.fen()));return e?.verbose?r:r.map(t=>t.san)}else{let r=U.flatMap(n=>q(n,this.fen())),t=this.hand().flatMap(n=>S(n,this.fen())),i=[...r,...t];return e?.verbose?i:i.map(n=>n.san)}}moveNumber(){return this.#c}pgn(e){return X(this.#i,e)}print(e){console.log(this.ascii(e))}reset(){this.#n(N(this.#a)),this.#i=[]}turn(){return this.#s}undo(){let e=this.#i.pop();return e?(this.#n(N(e.before)),e):null}validateFen(e){return _(e)}getPieceId(e,r){if(r!==void 0)return this.#e.getPieceId(e,r);let t=this.getTop(e);if(t)return this.#e.getPieceId(e,t.tier)}getPieceById(e){for(let r=0;r<9;r++)for(let t=0;t<9;t++){let i=this.#r[r][t];if(i&&i[0]){for(let n of i)if(n&&n.id===e)return n}}}getHandPieceIds(e,r){if(e&&r)return this.#e.getHandIds(e,r);let t=[];for(let i of this.#t)i.ids&&t.push(...i.ids);return t}getBoardWithIds(){return this.#r.map(e=>e.map(r=>r.map(t=>t?{...t}:null)))}getHandWithIds(e){let r=this.#t.map(t=>({...t}));return e?r.filter(t=>t.color===e):r}getHandPieceId(e,r,t=0){let i=this.#t.find(n=>n.type===e&&n.color===r);if(i&&i.ids&&i.ids.length>t)return i.ids[t]}removeHandPieceId(e,r,t){let i=this.#t.find(n=>n.type===e&&n.color===r);if(i&&i.ids){let n=i.ids.indexOf(t);if(n!==-1)return i.ids.splice(n,1),i.count=Math.max(0,i.count-1),this.#e.removeFromHand(e,r,1),!0}return!1}getIdRegistryState(){return this.#e.getRegistryState()}};export{W as ADVANCED_POSITION,ce as ARATA,be as ARCHER,Ce as BEGINNER_POSITION,se as BETRAY,ie as BLACK,Pe as CANNON,we as CANONICAL_NAMES,xe as ENGLISH_NAMES,ve as FEN_CODES,me as FORTRESS,de as GENERAL,ee as Gungi,Te as INTERMEDIATE_POSITION,Q as INTRO_POSITION,fe as LANCER,le as LIEUTENANT_GENERAL,pe as MAJOR_GENERAL,ae as MARSHAL,Ie as MUSKETEER,he as RIDER,ye as SOLDIER,ge as SPY,U as SQUARES,Ne as TACTICIAN,oe as TAKE,ne as TSUKE,ue as WARRIOR,re as WHITE,_ 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"],"sourcesContent":["import pc from 'picocolors';\nimport {\n\tADVANCED_POSITION,\n\tBEGINNNER_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 {\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\tBEGINNNER_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\n\t#initPosition: string;\n\n\t#initializeState({\n\t\tboard,\n\t\thand,\n\t\tturn,\n\t\tmoveNumber,\n\t\tdrafting,\n\t\tmode,\n\t}: ParsedFEN) {\n\t\tthis.#board = board;\n\t\tthis.#hand = hand;\n\t\tthis.#turn = turn;\n\t\tthis.#moveNumber = moveNumber;\n\t\tthis.#drafting = drafting;\n\t\tthis.#mode = mode;\n\t}\n\n\tconstructor(fen?: string) {\n\t\tthis.#initPosition = fen ?? INTRO_POSITION;\n\t\tthis.#initializeState(parseFEN(this.#initPosition));\n\t}\n\n\tascii(opts?: { english?: boolean }) {\n\t\tconst tierToColor = {\n\t\t\t1: pc.yellow,\n\t\t\t2: pc.blue,\n\t\t\t3: pc.green,\n\t\t} as const;\n\n\t\tlet s = ` 987654321 \\n`;\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\tfor (let rank = 1; rank <= 9; rank++) {\n\t\t\ts += `|`;\n\t\t\tfor (let file = 9; file > 0; file--) {\n\t\t\t\tconst square = this.getTop(`${rank}-${file}`);\n\t\t\t\tif (!square) {\n\t\t\t\t\ts += '・';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst code = pieceToFenCode[symbolToName[square.type]];\n\t\t\t\tconst en = square.color === 'w' ? code.toUpperCase() : code;\n\n\t\t\t\tconst coloredPiece = tierToColor[square.tier as 1 | 2 | 3](\n\t\t\t\t\topts?.english\n\t\t\t\t\t\t? String.fromCharCode(en.charCodeAt(0) + 0xfee0)\n\t\t\t\t\t\t: square.type\n\t\t\t\t);\n\n\t\t\t\ts += square.color === 'w' ? coloredPiece : pc.dim(coloredPiece);\n\t\t\t}\n\t\t\ts += `|${String.fromCharCode(rank - 1 + '1'.charCodeAt(0))}\\n`;\n\t\t}\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\treturn s;\n\t}\n\n\tboard() {\n\t\treturn this.#board;\n\t}\n\n\tcaptured(color?: Color) {\n\t\tconst allCaptured = this.#history.flatMap((move) => move.captured ?? []);\n\t\tconst capturedCounts = allCaptured.reduce((acc, p) => {\n\t\t\tconst c = acc.find((a) => a.type === p.type && a.color === p.color);\n\t\t\tif (c) {\n\t\t\t\tc.count++;\n\t\t\t} else {\n\t\t\t\tacc.push({ type: p.type, color: p.color, count: 1 });\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, [] as HandPiece[]);\n\n\t\treturn color\n\t\t\t? capturedCounts.filter((p) => p.color === color)\n\t\t\t: capturedCounts;\n\t}\n\n\tclear() {\n\t\tthis.#initializeState(parseFEN(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(parseFEN(fen));\n\t}\n\n\tloadPgn(\n\t\tpgn: string,\n\t\tfen = ADVANCED_POSITION,\n\t\topts?: Pick<PGNOptions, 'newline'>\n\t) {\n\t\tthis.#initializeState(parseFEN(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(parseFEN(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.#initializeState(parseFEN(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(parseFEN(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};\nexport type HandPiece = {\n\ttype: PieceType;\n\tcolor: Color;\n\tcount: number;\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 BEGINNNER_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"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO,CAAE,GAAGF,EAAK,CAACE,CAAK,EAAGD,CAAI,GAC/C,CAAC,CACF,EA6BYE,EAA6C,CACzD,MAAO,EACP,SAAU,EACV,aAAc,EACd,SAAU,CACX,EACaC,EAAkBN,EAAWK,CAAe,EAE5CE,GAAQ,IACRC,GAAQ,IAERC,GAAQ,SACRC,GAAO,SACPC,GAAS,SACTC,GAAQ,SAERC,GAAU,SACVC,GAAU,SACVC,GAAqB,SACrBC,GAAgB,SAChBC,GAAU,SACVC,GAAS,SACTC,GAAQ,SACRC,GAAM,SACNC,GAAW,SACXC,GAAU,SACVC,GAAS,SACTC,GAAS,SACTC,GAAY,SACZC,GAAY,SAEZC,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACC,EAAGC,IAAMA,EAAI,CAAC,EAAE,QAASA,GAC1E,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACD,EAAGE,IAAM,GAAGD,CAAC,IAAI,EAAIC,CAAC,EAAE,CACpD,EAmDaC,EAAiC,CAC7C,QAAS,SACT,QAAS,SACT,mBAAoB,SACpB,cAAe,SACf,QAAS,SACT,OAAQ,SACR,MAAO,SACP,IAAK,SACL,SAAU,SACV,QAAS,SACT,OAAQ,SACR,OAAQ,SACR,UAAW,SACX,UAAW,QACZ,EAEaC,EAAehC,EAAW+B,CAAK,EAE/BE,EAA0C,CACtD,QAAS,IACT,QAAS,IACT,mBAAoB,IACpB,cAAe,IACf,QAAS,IACT,OAAQ,IACR,MAAO,IACP,IAAK,IACL,SAAU,IACV,QAAS,IACT,OAAQ,IACR,OAAQ,IACR,UAAW,I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K","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","BEGINNNER_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","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#initPosition","#initializeState","board","hand","turn","moveNumber","drafting","mode","fen","INTRO_POSITION","parseFEN","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","move","acc","p","c","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"],"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 {\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\tPiece,\n\tPieceIdRegistry,\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#idRegistry: PieceIdRegistry;\n\n\t#initPosition: string;\n\n\t#initializeState({\n\t\tboard,\n\t\thand,\n\t\tturn,\n\t\tmoveNumber,\n\t\tdrafting,\n\t\tmode,\n\t}: ParsedFEN) {\n\t\tthis.#board = board;\n\t\tthis.#hand = hand;\n\t\tthis.#turn = turn;\n\t\tthis.#moveNumber = moveNumber;\n\t\tthis.#drafting = drafting;\n\t\tthis.#mode = mode;\n\n\t\t// Assign IDs to pieces that don't have them and sync registry\n\t\tthis.#assignMissingIds();\n\t\tthis.#syncRegistryWithState();\n\t}\n\n\t#assignMissingIds() {\n\t\t// Assign IDs to board pieces without them\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tfor (let file = 0; file < 9; file++) {\n\t\t\t\tconst tower = this.#board[rank][file];\n\t\t\t\tif (tower && tower[0]) {\n\t\t\t\t\tfor (let tierIdx = 0; tierIdx < tower.length; tierIdx++) {\n\t\t\t\t\t\tconst piece = tower[tierIdx];\n\t\t\t\t\t\tif (piece && !piece.id) {\n\t\t\t\t\t\t\tpiece.id = this.#idRegistry.createPieceWithId(\n\t\t\t\t\t\t\t\tpiece.type,\n\t\t\t\t\t\t\t\tpiece.color,\n\t\t\t\t\t\t\t\tpiece.square,\n\t\t\t\t\t\t\t\tpiece.tier\n\t\t\t\t\t\t\t).id;\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\n\t\t// Assign IDs to hand pieces without them\n\t\tfor (const handPiece of this.#hand) {\n\t\t\tif (!handPiece.ids || handPiece.ids.length === 0) {\n\t\t\t\thandPiece.ids = [];\n\t\t\t\tfor (let i = 0; i < handPiece.count; i++) {\n\t\t\t\t\tconst newId = this.#idRegistry.createPieceWithId(\n\t\t\t\t\t\thandPiece.type,\n\t\t\t\t\t\thandPiece.color,\n\t\t\t\t\t\t'hand',\n\t\t\t\t\t\t0\n\t\t\t\t\t).id!;\n\t\t\t\t\thandPiece.ids.push(newId);\n\t\t\t\t\t// Remove from board registry since it's in hand\n\t\t\t\t\tthis.#idRegistry.removePieceId('hand', 0);\n\t\t\t\t\t// Add to hand registry\n\t\t\t\t\tthis.#idRegistry.addToHand(handPiece.type, handPiece.color, [newId]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Ensure hand registry is synced\n\t\t\t\tconst existingIds = this.#idRegistry.getHandIds(\n\t\t\t\t\thandPiece.type,\n\t\t\t\t\thandPiece.color\n\t\t\t\t);\n\t\t\t\tif (existingIds.length !== handPiece.count) {\n\t\t\t\t\t// Clear and rebuild hand registry for this piece type/color\n\t\t\t\t\tconst key = `${handPiece.type}-${handPiece.color}`;\n\t\t\t\t\tthis.#idRegistry.addToHand(\n\t\t\t\t\t\thandPiece.type,\n\t\t\t\t\t\thandPiece.color,\n\t\t\t\t\t\thandPiece.ids.slice()\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t#syncRegistryWithState() {\n\t\tthis.#idRegistry.syncWithBoard(this.#board, this.#hand);\n\t}\n\n\tconstructor(fen?: string) {\n\t\tthis.#initPosition = fen ?? INTRO_POSITION;\n\t\tthis.#idRegistry = new PieceIdRegistry();\n\t\tthis.#initializeState(parseFEN(this.#initPosition));\n\t}\n\n\tascii(opts?: { english?: boolean }) {\n\t\tconst tierToColor = {\n\t\t\t1: pc.yellow,\n\t\t\t2: pc.blue,\n\t\t\t3: pc.green,\n\t\t} as const;\n\n\t\tlet s = ` 987654321 \\n`;\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\tfor (let rank = 1; rank <= 9; rank++) {\n\t\t\ts += `|`;\n\t\t\tfor (let file = 9; file > 0; file--) {\n\t\t\t\tconst square = this.getTop(`${rank}-${file}`);\n\t\t\t\tif (!square) {\n\t\t\t\t\ts += '・';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst code = pieceToFenCode[symbolToName[square.type]];\n\t\t\t\tconst en = square.color === 'w' ? code.toUpperCase() : code;\n\n\t\t\t\tconst coloredPiece = tierToColor[square.tier as 1 | 2 | 3](\n\t\t\t\t\topts?.english\n\t\t\t\t\t\t? String.fromCharCode(en.charCodeAt(0) + 0xfee0)\n\t\t\t\t\t\t: square.type\n\t\t\t\t);\n\n\t\t\t\ts += square.color === 'w' ? coloredPiece : pc.dim(coloredPiece);\n\t\t\t}\n\t\t\ts += `|${String.fromCharCode(rank - 1 + '1'.charCodeAt(0))}\\n`;\n\t\t}\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\treturn s;\n\t}\n\n\tboard() {\n\t\treturn this.#board;\n\t}\n\n\tcaptured(color?: Color) {\n\t\tconst allCaptured = this.#history.flatMap((move) => move.captured ?? []);\n\t\tconst capturedCounts = allCaptured.reduce((acc, p) => {\n\t\t\tconst c = acc.find((a) => a.type === p.type && a.color === p.color);\n\t\t\tif (c) {\n\t\t\t\tc.count++;\n\t\t\t} else {\n\t\t\t\tacc.push({ type: p.type, color: p.color, count: 1 });\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, [] as HandPiece[]);\n\n\t\treturn color\n\t\t\t? capturedCounts.filter((p) => p.color === color)\n\t\t\t: capturedCounts;\n\t}\n\n\tclear() {\n\t\tthis.#initializeState(parseFEN(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(parseFEN(fen));\n\t}\n\n\tloadPgn(\n\t\tpgn: string,\n\t\tfen = ADVANCED_POSITION,\n\t\topts?: Pick<PGNOptions, 'newline'>\n\t) {\n\t\tthis.#initializeState(parseFEN(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\t// Capture ID information before move execution\n\t\tconst idSnapshot = this.#captureIdSnapshot(found);\n\n\t\tthis.#history.push(found);\n\t\tif (this.isFourfoldRepetition()) this.#history.at(-1)!.san += '停';\n\n\t\t// Initialize new state from FEN (this loses IDs)\n\t\tthis.#initializeState(parseFEN(found.after));\n\n\t\t// Restore ID mappings accounting for the move\n\t\tthis.#restoreIdMappings(found, idSnapshot);\n\n\t\treturn found;\n\t}\n\n\t#captureIdSnapshot(move: Move) {\n\t\tconst snapshot = {\n\t\t\tboardPieces: new Map<string, string>(), // square-tier -> ID\n\t\t\thandPieces: new Map<string, string[]>(), // type-color -> IDs\n\t\t\tmovingPieceId: null as string | null,\n\t\t\tcapturedIds: [] as string[],\n\t\t\thandPieceId: null as string | null, // for arata moves\n\t\t};\n\n\t\t// Capture all board pieces\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tfor (let file = 0; file < 9; file++) {\n\t\t\t\tconst tower = this.#board[rank][file];\n\t\t\t\tif (tower && tower[0]) {\n\t\t\t\t\tfor (const piece of tower) {\n\t\t\t\t\t\tif (piece && piece.id) {\n\t\t\t\t\t\t\tsnapshot.boardPieces.set(\n\t\t\t\t\t\t\t\t`${piece.square}-${piece.tier}`,\n\t\t\t\t\t\t\t\tpiece.id\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\n\t\t// Capture hand pieces\n\t\tfor (const handPiece of this.#hand) {\n\t\t\tif (handPiece.ids && handPiece.ids.length > 0) {\n\t\t\t\tsnapshot.handPieces.set(`${handPiece.type}-${handPiece.color}`, [\n\t\t\t\t\t...handPiece.ids,\n\t\t\t\t]);\n\t\t\t}\n\t\t}\n\n\t\t// Capture moving piece ID\n\t\tif (move.from) {\n\t\t\tconst movingPiece = this.getTop(move.from);\n\t\t\tif (movingPiece && movingPiece.id) {\n\t\t\t\tsnapshot.movingPieceId = movingPiece.id;\n\t\t\t}\n\t\t}\n\n\t\t// For arata moves, capture the hand piece ID being used\n\t\tif (move.type === 'arata') {\n\t\t\tconst handPieces = this.#hand.find(\n\t\t\t\t(hp) => hp.type === move.piece && hp.color === move.color\n\t\t\t);\n\t\t\tif (handPieces && handPieces.ids && handPieces.ids.length > 0) {\n\t\t\t\tsnapshot.handPieceId = handPieces.ids[0]; // Use first available\n\t\t\t}\n\t\t}\n\n\t\t// Capture IDs of pieces being captured\n\t\tif (move.captured) {\n\t\t\tsnapshot.capturedIds = move.captured\n\t\t\t\t.map((p) => p.id)\n\t\t\t\t.filter((id): id is string => id !== undefined);\n\t\t}\n\n\t\treturn snapshot;\n\t}\n\n\t#restoreIdMappings(move: Move, snapshot: any) {\n\t\t// Clear current registry and rebuild with ID preservation\n\t\tthis.#idRegistry = new PieceIdRegistry();\n\n\t\t// Restore board pieces, accounting for the move\n\t\tconst [toRank, toFile, toTier] = move.to.split('-').map(Number);\n\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tfor (let file = 0; file < 9; file++) {\n\t\t\t\tconst tower = this.#board[rank][file];\n\t\t\t\tif (tower && tower[0]) {\n\t\t\t\t\tfor (let tierIdx = 0; tierIdx < tower.length; tierIdx++) {\n\t\t\t\t\t\tconst piece = tower[tierIdx];\n\t\t\t\t\t\tif (piece) {\n\t\t\t\t\t\t\tlet pieceId: string;\n\n\t\t\t\t\t\t\t// Check if this is the destination of our move\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\trank === toRank - 1 &&\n\t\t\t\t\t\t\t\tfile === 9 - toFile &&\n\t\t\t\t\t\t\t\ttierIdx === toTier - 1\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t// This is the piece that moved\n\t\t\t\t\t\t\t\tif (move.type === 'arata' && snapshot.handPieceId) {\n\t\t\t\t\t\t\t\t\tpieceId = snapshot.handPieceId;\n\t\t\t\t\t\t\t\t} else if (snapshot.movingPieceId) {\n\t\t\t\t\t\t\t\t\tpieceId = snapshot.movingPieceId;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Generate new ID if we can't find the original\n\t\t\t\t\t\t\t\t\tpieceId = this.#idRegistry.createPieceWithId(\n\t\t\t\t\t\t\t\t\t\tpiece.type,\n\t\t\t\t\t\t\t\t\t\tpiece.color,\n\t\t\t\t\t\t\t\t\t\tpiece.square,\n\t\t\t\t\t\t\t\t\t\tpiece.tier\n\t\t\t\t\t\t\t\t\t).id!;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Try to find existing ID for this position\n\t\t\t\t\t\t\t\tconst existingId = snapshot.boardPieces.get(\n\t\t\t\t\t\t\t\t\t`${piece.square}-${piece.tier}`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (existingId) {\n\t\t\t\t\t\t\t\t\tpieceId = existingId;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Generate new ID\n\t\t\t\t\t\t\t\t\tpieceId = this.#idRegistry.createPieceWithId(\n\t\t\t\t\t\t\t\t\t\tpiece.type,\n\t\t\t\t\t\t\t\t\t\tpiece.color,\n\t\t\t\t\t\t\t\t\t\tpiece.square,\n\t\t\t\t\t\t\t\t\t\tpiece.tier\n\t\t\t\t\t\t\t\t\t).id!;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tpiece.id = pieceId;\n\t\t\t\t\t\t\tthis.#idRegistry.setPieceId(piece.square, piece.tier, pieceId);\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\n\t\t// Restore hand pieces with proper ID tracking\n\t\tfor (const handPiece of this.#hand) {\n\t\t\tconst key = `${handPiece.type}-${handPiece.color}`;\n\t\t\tlet ids = snapshot.handPieces.get(key) || [];\n\n\t\t\t// Handle captured pieces being added to hand\n\t\t\tif (move.captured && move.type === 'capture') {\n\t\t\t\tconst capturedOfThisType = move.captured.filter(\n\t\t\t\t\t(p) =>\n\t\t\t\t\t\tp.type === handPiece.type &&\n\t\t\t\t\t\t(p.color === 'w' ? 'b' : 'w') === handPiece.color\n\t\t\t\t);\n\t\t\t\tfor (const captured of capturedOfThisType) {\n\t\t\t\t\tif (captured.id) {\n\t\t\t\t\t\tids.push(captured.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// For arata moves, remove the used piece ID\n\t\t\tif (\n\t\t\t\tmove.type === 'arata' &&\n\t\t\t\tmove.piece === handPiece.type &&\n\t\t\t\tmove.color === handPiece.color &&\n\t\t\t\tsnapshot.handPieceId\n\t\t\t) {\n\t\t\t\tids = ids.filter((id: string) => id !== snapshot.handPieceId);\n\t\t\t}\n\n\t\t\t// Ensure we have the right number of IDs\n\t\t\twhile (ids.length < handPiece.count) {\n\t\t\t\tconst newId = this.#idRegistry.createPieceWithId(\n\t\t\t\t\thandPiece.type,\n\t\t\t\t\thandPiece.color,\n\t\t\t\t\t'hand',\n\t\t\t\t\t0\n\t\t\t\t).id!;\n\t\t\t\tthis.#idRegistry.removePieceId('hand', 0);\n\t\t\t\tids.push(newId);\n\t\t\t}\n\n\t\t\tids = ids.slice(0, handPiece.count);\n\t\t\thandPiece.ids = ids;\n\t\t\tthis.#idRegistry.addToHand(handPiece.type, handPiece.color, ids);\n\t\t}\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.#initializeState(parseFEN(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(parseFEN(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\t// ID-aware methods\n\tgetPieceId(square: string, tier?: number): string | undefined {\n\t\tif (tier !== undefined) {\n\t\t\treturn this.#idRegistry.getPieceId(square, tier);\n\t\t}\n\n\t\t// Get ID of top piece if tier not specified\n\t\tconst topPiece = this.getTop(square);\n\t\tif (topPiece) {\n\t\t\treturn this.#idRegistry.getPieceId(square, topPiece.tier);\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tgetPieceById(id: string): Piece | undefined {\n\t\t// Search board for piece with this ID\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tfor (let file = 0; file < 9; file++) {\n\t\t\t\tconst tower = this.#board[rank][file];\n\t\t\t\tif (tower && tower[0]) {\n\t\t\t\t\tfor (const piece of tower) {\n\t\t\t\t\t\tif (piece && piece.id === id) {\n\t\t\t\t\t\t\treturn piece;\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\treturn undefined;\n\t}\n\n\tgetHandPieceIds(type?: string, color?: Color): string[] {\n\t\tif (type && color) {\n\t\t\treturn this.#idRegistry.getHandIds(type as any, color);\n\t\t}\n\n\t\t// Get all hand piece IDs\n\t\tconst allIds: string[] = [];\n\t\tfor (const handPiece of this.#hand) {\n\t\t\tif (handPiece.ids) {\n\t\t\t\tallIds.push(...handPiece.ids);\n\t\t\t}\n\t\t}\n\t\treturn allIds;\n\t}\n\n\tgetBoardWithIds(): (Piece | null)[][][] {\n\t\t// Return a copy of the board with all ID information\n\t\treturn this.#board.map((rank) =>\n\t\t\trank.map((tower) => tower.map((piece) => (piece ? { ...piece } : null)))\n\t\t);\n\t}\n\n\tgetHandWithIds(color?: Color): HandPiece[] {\n\t\t// Return hand pieces with ID arrays\n\t\tconst handWithIds = this.#hand.map((hp) => ({ ...hp }));\n\t\treturn color\n\t\t\t? handWithIds.filter((piece) => piece.color === color)\n\t\t\t: handWithIds;\n\t}\n\n\t// Get a specific hand piece ID (useful for selecting which piece to play)\n\tgetHandPieceId(\n\t\ttype: string,\n\t\tcolor: Color,\n\t\tindex: number = 0\n\t): string | undefined {\n\t\tconst handPiece = this.#hand.find(\n\t\t\t(hp) => hp.type === type && hp.color === color\n\t\t);\n\t\tif (handPiece && handPiece.ids && handPiece.ids.length > index) {\n\t\t\treturn handPiece.ids[index];\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Remove a specific hand piece ID (useful for implementing piece selection)\n\tremoveHandPieceId(type: string, color: Color, id: string): boolean {\n\t\tconst handPiece = this.#hand.find(\n\t\t\t(hp) => hp.type === type && hp.color === color\n\t\t);\n\t\tif (handPiece && handPiece.ids) {\n\t\t\tconst index = handPiece.ids.indexOf(id);\n\t\t\tif (index !== -1) {\n\t\t\t\thandPiece.ids.splice(index, 1);\n\t\t\t\thandPiece.count = Math.max(0, handPiece.count - 1);\n\t\t\t\tthis.#idRegistry.removeFromHand(type as any, color, 1);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t// Debug method to inspect registry state\n\tgetIdRegistryState() {\n\t\treturn this.#idRegistry.getRegistryState();\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\tids?: 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\n// ID generation utilities\nexport function generatePieceId(\n\ttype: PieceType,\n\tcolor: Color,\n\tcounter: number\n): string {\n\treturn `${type}-${color}-${counter}`;\n}\n\nexport function parsePieceId(\n\tid: string\n): { type: PieceType; color: Color; number: number } | null {\n\tconst parts = id.split('-');\n\tif (parts.length !== 3) return null;\n\n\tconst [type, color, numberStr] = parts;\n\tconst number = parseInt(numberStr, 10);\n\n\tif (isNaN(number) || !['b', 'w'].includes(color)) return null;\n\n\treturn {\n\t\ttype: type as PieceType,\n\t\tcolor: color as Color,\n\t\tnumber,\n\t};\n}\n\n// Piece ID Registry for tracking piece identities across moves\nexport class PieceIdRegistry {\n\tprivate pieceIdMap = new Map<string, string>(); // square+tier -> ID\n\tprivate handIdMap = new Map<string, string[]>(); // type+color -> ID[]\n\tprivate idCounters = new Map<string, number>(); // type+color -> counter\n\tprivate reverseMap = new Map<string, string>(); // ID -> square+tier\n\n\tconstructor() {\n\t\tthis.initializeCounters();\n\t}\n\n\tprivate initializeCounters() {\n\t\tconst pieceTypes: PieceType[] = [\n\t\t\t'帥',\n\t\t\t'大',\n\t\t\t'中',\n\t\t\t'小',\n\t\t\t'侍',\n\t\t\t'槍',\n\t\t\t'馬',\n\t\t\t'忍',\n\t\t\t'砦',\n\t\t\t'兵',\n\t\t\t'砲',\n\t\t\t'弓',\n\t\t\t'筒',\n\t\t\t'謀',\n\t\t];\n\t\tconst colors: Color[] = ['w', 'b'];\n\n\t\tfor (const type of pieceTypes) {\n\t\t\tfor (const color of colors) {\n\t\t\t\tconst key = `${type}-${color}`;\n\t\t\t\tthis.idCounters.set(key, 0);\n\t\t\t\tthis.handIdMap.set(key, []);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getNextId(type: PieceType, color: Color): string {\n\t\tconst key = `${type}-${color}`;\n\t\tconst current = this.idCounters.get(key) ?? 0;\n\t\tconst next = current + 1;\n\t\tthis.idCounters.set(key, next);\n\t\treturn generatePieceId(type, color, next);\n\t}\n\n\t// Board piece management\n\tsetPieceId(square: string, tier: number, id: string): void {\n\t\tconst key = `${square}-${tier}`;\n\t\tthis.pieceIdMap.set(key, id);\n\t\tthis.reverseMap.set(id, key);\n\t}\n\n\tgetPieceId(square: string, tier: number): string | undefined {\n\t\tconst key = `${square}-${tier}`;\n\t\treturn this.pieceIdMap.get(key);\n\t}\n\n\tremovePieceId(square: string, tier: number): string | undefined {\n\t\tconst key = `${square}-${tier}`;\n\t\tconst id = this.pieceIdMap.get(key);\n\t\tif (id) {\n\t\t\tthis.pieceIdMap.delete(key);\n\t\t\tthis.reverseMap.delete(id);\n\t\t}\n\t\treturn id;\n\t}\n\n\tmovePiece(\n\t\tfromSquare: string,\n\t\tfromTier: number,\n\t\ttoSquare: string,\n\t\ttoTier: number\n\t): void {\n\t\tconst id = this.removePieceId(fromSquare, fromTier);\n\t\tif (id) {\n\t\t\tthis.setPieceId(toSquare, toTier, id);\n\t\t}\n\t}\n\n\t// Hand piece management\n\taddToHand(type: PieceType, color: Color, ids: string[]): void {\n\t\tconst key = `${type}-${color}`;\n\t\tconst existing = this.handIdMap.get(key) ?? [];\n\t\tthis.handIdMap.set(key, [...existing, ...ids]);\n\t}\n\n\tremoveFromHand(type: PieceType, color: Color, count: number = 1): string[] {\n\t\tconst key = `${type}-${color}`;\n\t\tconst existing = this.handIdMap.get(key) ?? [];\n\t\tconst removed = existing.splice(0, count);\n\t\treturn removed;\n\t}\n\n\tgetHandIds(type: PieceType, color: Color): string[] {\n\t\tconst key = `${type}-${color}`;\n\t\treturn [...(this.handIdMap.get(key) ?? [])];\n\t}\n\n\t// Piece creation with ID generation\n\tcreatePieceWithId(\n\t\ttype: PieceType,\n\t\tcolor: Color,\n\t\tsquare: string,\n\t\ttier: number\n\t): Piece {\n\t\tconst id = this.getNextId(type, color);\n\t\tthis.setPieceId(square, tier, id);\n\n\t\treturn {\n\t\t\ttype,\n\t\t\tcolor,\n\t\t\tsquare,\n\t\t\ttier,\n\t\t\tid,\n\t\t};\n\t}\n\n\t// Convert captured pieces to hand\n\tcapturePieces(capturedPieces: Piece[]): void {\n\t\tfor (const piece of capturedPieces) {\n\t\t\tif (piece.id) {\n\t\t\t\t// Remove from board\n\t\t\t\tthis.removePieceId(piece.square, piece.tier);\n\t\t\t\t// Add to opposing hand\n\t\t\t\tconst oppositeColor = piece.color === 'w' ? 'b' : 'w';\n\t\t\t\tthis.addToHand(piece.type, oppositeColor, [piece.id]);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Handle betrayal (piece color change)\n\tbetrayPieces(pieces: Piece[]): Piece[] {\n\t\treturn pieces.map((piece) => {\n\t\t\tif (piece.id) {\n\t\t\t\t// Generate new ID for the converted piece\n\t\t\t\tconst newColor = piece.color === 'w' ? 'b' : 'w';\n\t\t\t\tconst newId = this.getNextId(piece.type, newColor);\n\n\t\t\t\t// Update registries\n\t\t\t\tthis.removePieceId(piece.square, piece.tier);\n\t\t\t\tthis.setPieceId(piece.square, piece.tier, newId);\n\n\t\t\t\treturn {\n\t\t\t\t\t...piece,\n\t\t\t\t\tcolor: newColor,\n\t\t\t\t\tid: newId,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn piece;\n\t\t});\n\t}\n\n\t// Sync with board state after FEN reinitialization\n\tsyncWithBoard(board: Board, hand: HandPiece[]): void {\n\t\t// Clear current mappings\n\t\tthis.pieceIdMap.clear();\n\t\tthis.reverseMap.clear();\n\n\t\t// Rebuild from board\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tfor (let file = 0; file < 9; file++) {\n\t\t\t\tconst tower = board[rank][file];\n\t\t\t\tif (tower && tower[0]) {\n\t\t\t\t\tfor (let tier = 0; tier < tower.length; tier++) {\n\t\t\t\t\t\tconst piece = tower[tier];\n\t\t\t\t\t\tif (piece && piece.id) {\n\t\t\t\t\t\t\tthis.setPieceId(piece.square, piece.tier, piece.id);\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\n\t\t// Rebuild hand mappings\n\t\tfor (const handPiece of hand) {\n\t\t\tif (handPiece.ids && handPiece.ids.length > 0) {\n\t\t\t\tconst key = `${handPiece.type}-${handPiece.color}`;\n\t\t\t\tthis.handIdMap.set(key, [...handPiece.ids]);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Get registry state for debugging\n\tgetRegistryState() {\n\t\treturn {\n\t\t\tpieceIdMap: new Map(this.pieceIdMap),\n\t\t\thandIdMap: new Map(this.handIdMap),\n\t\t\tidCounters: new Map(this.idCounters),\n\t\t\treverseMap: new Map(this.reverseMap),\n\t\t};\n\t}\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"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO,CAAE,GAAGF,EAAK,CAACE,CAAK,EAAGD,CAAI,GAC/C,CAAC,CACF,EA+BYE,EAA6C,CACzD,MAAO,EACP,SAAU,EACV,aAAc,EACd,SAAU,CACX,EACaC,EAAkBN,EAAWK,CAAe,EAE5CE,GAAQ,IACRC,GAAQ,IAERC,GAAQ,SACRC,GAAO,SACPC,GAAS,SACTC,GAAQ,SAERC,GAAU,SACVC,GAAU,SACVC,GAAqB,SACrBC,GAAgB,SAChBC,GAAU,SACVC,GAAS,SACTC,GAAQ,SACRC,GAAM,SACNC,GAAW,SACXC,GAAU,SACVC,GAAS,SACTC,GAAS,SACTC,GAAY,SACZC,GAAY,SAEZC,EAAU,MAAM,KAAK,CAAE,OAAQ,CAAE,EAAG,CAACC,EAAG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O,CAAC,EAC7BpE,EAAU,MAAQ,KAAK,IAAI,EAAGA,EAAU,MAAQ,CAAC,EACjD,KAAKhB,GAAY,eAAeiF,EAAa/C,EAAO,CAAC,EAC9C,EAET,CACA,MAAO,EACR,CAGA,oBAAqB,CACpB,OAAO,KAAKlC,GAAY,iBAAiB,CAC1C,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","generatePieceId","type","counter","PieceIdRegistry","pieceTypes","colors","type","color","key","next","generatePieceId","square","tier","id","fromSquare","fromTier","toSquare","toTier","ids","existing","count","capturedPieces","piece","oppositeColor","pieces","newColor","newId","board","hand","rank","file","tower","handPiece","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","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#idRegistry","#initPosition","#initializeState","board","hand","turn","moveNumber","drafting","mode","#assignMissingIds","#syncRegistryWithState","rank","file","tower","tierIdx","piece","handPiece","i","newId","key","fen","INTRO_POSITION","PieceIdRegistry","parseFEN","opts","tierToColor","pc","s","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","move","acc","p","c","a","ADVANCED_POSITION","encodeFEN","get","getTop","states","frequencyMap","map","str","isGameOver","pgn","parsePGN","moves","found","m","idSnapshot","#captureIdSnapshot","#restoreIdMappings","snapshot","movingPiece","handPieces","hp","id","toRank","toFile","toTier","pieceId","existingId","ids","capturedOfThisType","captured","generateMovesForSquare","generateArata","boardMoves","SQUARES","handMoves","encodePGN","lastMove","validateFen","tier","topPiece","type","allIds","handWithIds","index"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gungi.js",
3
- "version": "3.0.7",
3
+ "version": "3.1.0",
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",