gungi.js 3.1.0 → 3.2.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 +29 -125
- package/dist/index.d.ts +1 -14
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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,
|
|
11
|
+
gungi.js is used for move generation/validation, piece placement/movement, and endgame detection - basically everything but the AI.
|
|
12
12
|
|
|
13
13
|
## Installation
|
|
14
14
|
|
|
@@ -162,7 +162,7 @@ gungi.ascii({ english: true });
|
|
|
162
162
|
|
|
163
163
|
### .board()
|
|
164
164
|
|
|
165
|
-
Returns a 3D tensor representation of the current position (9x9x3 array). Empty squares are represented by `null`.
|
|
165
|
+
Returns a 3D tensor representation of the current position (9x9x3 array). Empty squares are represented by `null`. Each piece includes an optional `id` property for stable tracking across moves.
|
|
166
166
|
|
|
167
167
|
```ts
|
|
168
168
|
const gungi = new Gungi();
|
|
@@ -171,30 +171,30 @@ gungi.board();
|
|
|
171
171
|
// -> [[[null],
|
|
172
172
|
// [null],
|
|
173
173
|
// [null],
|
|
174
|
-
// [{ square: '1-6', tier: 1, type: '中', color: 'b' }],
|
|
175
|
-
// [{ square: '1-5', tier: 1, type: '帥', color: 'b' }],
|
|
176
|
-
// [{ square: '1-4', tier: 1, type: '大', color: 'b' }],
|
|
174
|
+
// [{ square: '1-6', tier: 1, type: '中', color: 'b', id: 'b-中-1' }],
|
|
175
|
+
// [{ square: '1-5', tier: 1, type: '帥', color: 'b', id: 'b-帥-1' }],
|
|
176
|
+
// [{ square: '1-4', tier: 1, type: '大', color: 'b', id: 'b-大-1' }],
|
|
177
177
|
// [null],
|
|
178
178
|
// [null],
|
|
179
179
|
// [null]],
|
|
180
180
|
// [[null],
|
|
181
|
-
// [{ square: '2-8', tier: 1, type: '忍', color: 'b' }],
|
|
181
|
+
// [{ square: '2-8', tier: 1, type: '忍', color: 'b', id: 'b-忍-2' }],
|
|
182
182
|
// [null],
|
|
183
183
|
// [null],
|
|
184
|
-
// [{ square: '2-5', tier: 1, type: '槍', color: 'b' }],
|
|
184
|
+
// [{ square: '2-5', tier: 1, type: '槍', color: 'b', id: 'b-槍-1' }],
|
|
185
185
|
// [null],
|
|
186
186
|
// [null],
|
|
187
|
-
// [{ square: '2-2', tier: 1, type: '忍', color: 'b' }],
|
|
187
|
+
// [{ square: '2-2', tier: 1, type: '忍', color: 'b', id: 'b-忍-1' }],
|
|
188
188
|
// [null]],
|
|
189
|
-
// [[{ square: '3-9', tier: 1, type: '兵', color: 'b' }],
|
|
189
|
+
// [[{ square: '3-9', tier: 1, type: '兵', color: 'b', id: 'b-兵-3' }],
|
|
190
190
|
// [null],
|
|
191
|
-
// [{ square: '3-7', tier: 1, type: '砦', color: 'b' }],
|
|
192
|
-
// [{ square: '3-6', tier: 1, type: '侍', color: 'b' }],
|
|
193
|
-
// [{ square: '3-5', tier: 1, type: '兵', color: 'b' }],
|
|
194
|
-
// [{ square: '3-4', tier: 1, type: '侍', color: 'b' }],
|
|
195
|
-
// [{ square: '3-3', tier: 1, type: '砦', color: 'b' }],
|
|
191
|
+
// [{ square: '3-7', tier: 1, type: '砦', color: 'b', id: 'b-砦-2' }],
|
|
192
|
+
// [{ square: '3-6', tier: 1, type: '侍', color: 'b', id: 'b-侍-2' }],
|
|
193
|
+
// [{ square: '3-5', tier: 1, type: '兵', color: 'b', id: 'b-兵-2' }],
|
|
194
|
+
// [{ square: '3-4', tier: 1, type: '侍', color: 'b', id: 'b-侍-1' }],
|
|
195
|
+
// [{ square: '3-3', tier: 1, type: '砦', color: 'b', id: 'b-砦-1' }],
|
|
196
196
|
// [null],
|
|
197
|
-
// [{ square: '3-1', tier: 1, type: '兵', color: 'b' }]],
|
|
197
|
+
// [{ square: '3-1', tier: 1, type: '兵', color: 'b', id: 'b-兵-1' }]],
|
|
198
198
|
// [...],
|
|
199
199
|
// [...],
|
|
200
200
|
// [...],
|
|
@@ -279,7 +279,7 @@ const gungi = new Gungi(BEGINNER_POSITION);
|
|
|
279
279
|
gungi.move('砦(7-3-1)(7-4-2)付');
|
|
280
280
|
|
|
281
281
|
gungi.get('7-4');
|
|
282
|
-
// -> [{ square: '7-4', tier: 1, type: '侍', color: 'w' }, { square: '7-4', tier: 2, type: '砦', color: 'w' }]
|
|
282
|
+
// -> [{ square: '7-4', tier: 1, type: '侍', color: 'w', id: 'w-侍-1' }, { square: '7-4', tier: 2, type: '砦', color: 'w', id: 'w-砦-1' }]
|
|
283
283
|
gungi.get('7-3');
|
|
284
284
|
// -> undefined
|
|
285
285
|
```
|
|
@@ -299,19 +299,6 @@ 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
|
-
|
|
315
302
|
### .getTop(square)
|
|
316
303
|
|
|
317
304
|
Returns the top piece of the tower on the square. Returns `undefined` if the square is empty.
|
|
@@ -325,92 +312,9 @@ gungi.get('7-3');
|
|
|
325
312
|
// -> undefined
|
|
326
313
|
```
|
|
327
314
|
|
|
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
|
-
|
|
411
315
|
### .hand(color)
|
|
412
316
|
|
|
413
|
-
Returns a list of pieces in players' hand. Color is an optional parameter to filter pieces by player color
|
|
317
|
+
Returns a list of pieces in players' hand. Color is an optional parameter to filter pieces by player color. Each hand piece includes an optional `id` property for stable tracking across moves.
|
|
414
318
|
|
|
415
319
|
```ts
|
|
416
320
|
const gungi = new Gungi(BEGINNER_POSITION);
|
|
@@ -422,21 +326,21 @@ gungi.move('新忍(8-7-2)付');
|
|
|
422
326
|
|
|
423
327
|
gungi.hand();
|
|
424
328
|
// -> [
|
|
425
|
-
// { type: '小', count: 2, color: 'w' },
|
|
426
|
-
// { type: '槍', count: 2, color: 'w' },
|
|
427
|
-
// { type: '馬', count: 1, color: 'w' },
|
|
428
|
-
// { type: '兵', count: 1, color: 'w' },
|
|
429
|
-
// { type: '小', count: 2, color: 'b' },
|
|
430
|
-
// { type: '槍', count: 2, color: 'b' },
|
|
431
|
-
// { type: '忍', count: 1, color: 'b' },
|
|
432
|
-
// { type: '兵', count: 1, color: 'b' }
|
|
329
|
+
// { type: '小', count: 2, color: 'w', id: 'w-小-1' },
|
|
330
|
+
// { type: '槍', count: 2, color: 'w', id: 'w-槍-1' },
|
|
331
|
+
// { type: '馬', count: 1, color: 'w', id: 'w-馬-1' },
|
|
332
|
+
// { type: '兵', count: 1, color: 'w', id: 'w-兵-1' },
|
|
333
|
+
// { type: '小', count: 2, color: 'b', id: 'b-小-1' },
|
|
334
|
+
// { type: '槍', count: 2, color: 'b', id: 'b-槍-1' },
|
|
335
|
+
// { type: '忍', count: 1, color: 'b', id: 'b-忍-1' },
|
|
336
|
+
// { type: '兵', count: 1, color: 'b', id: 'b-兵-1' }
|
|
433
337
|
// ]
|
|
434
338
|
gungi.hand('w');
|
|
435
339
|
// [
|
|
436
|
-
// { type: '小', count: 2, color: 'w' },
|
|
437
|
-
// { type: '槍', count: 2, color: 'w' },
|
|
438
|
-
// { type: '馬', count: 1, color: 'w' },
|
|
439
|
-
// { type: '兵', count: 1, color: 'w' }
|
|
340
|
+
// { type: '小', count: 2, color: 'w', id: 'w-小-1' },
|
|
341
|
+
// { type: '槍', count: 2, color: 'w', id: 'w-槍-1' },
|
|
342
|
+
// { type: '馬', count: 1, color: 'w', id: 'w-馬-1' },
|
|
343
|
+
// { type: '兵', count: 1, color: 'w', id: 'w-兵-1' }
|
|
440
344
|
// ]
|
|
441
345
|
```
|
|
442
346
|
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ type HandPiece = {
|
|
|
10
10
|
type: PieceType;
|
|
11
11
|
color: Color;
|
|
12
12
|
count: number;
|
|
13
|
-
|
|
13
|
+
id?: string;
|
|
14
14
|
};
|
|
15
15
|
type Move = {
|
|
16
16
|
color: Color;
|
|
@@ -106,19 +106,6 @@ declare class Gungi {
|
|
|
106
106
|
ok: boolean;
|
|
107
107
|
error?: string;
|
|
108
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
|
-
};
|
|
122
109
|
}
|
|
123
110
|
|
|
124
111
|
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 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
|
-
`,
|
|
3
|
-
`;return
|
|
4
|
-
`;
|
|
5
|
-
`;for(let
|
|
6
|
-
`}return
|
|
7
|
-
`,
|
|
1
|
+
import F from"picocolors";var q=r=>Object.entries(r).reduce((e,[t,o])=>({...e,[o]:t}),{}),O={intro:0,beginner:1,intermediate:2,advanced:3},G=q(O),se="w",ae="b",ce="\u4ED8",le="\u53D6",de="\u8FD4",pe="\u65B0",fe="\u5E25",ue="\u5927",he="\u4E2D",me="\u5C0F",Pe="\u4F8D",ge="\u69CD",ye="\u99AC",be="\u5FCD",Ne="\u7826",ve="\u5175",Ce="\u7832",we="\u5F13",Te="\u7B52",xe="\u8B00",U=Array.from({length:9},(r,e)=>e+1).flatMap(r=>Array.from({length:9},(e,t)=>`${r}-${9-t}`)),N={marshal:"\u5E25",general:"\u5927",lieutenant_general:"\u4E2D",major_general:"\u5C0F",warrior:"\u4F8D",lancer:"\u69CD",rider:"\u99AC",spy:"\u5FCD",fortress:"\u7826",soldier:"\u5175",cannon:"\u7832",archer:"\u5F13",musketeer:"\u7B52",tactician:"\u8B00"},E=q(N),T={marshal:"m",general:"g",lieutenant_general:"i",major_general:"j",warrior:"w",lancer:"n",rider:"r",spy:"s",fortress:"f",soldier:"d",cannon:"c",archer:"a",musketeer:"k",tactician:"t"},K=q(T),H=(r,[e,t,o])=>{let n=r===r.toLowerCase()?"b":"w",s=K[r.toLowerCase()];return{square:`${e}-${t}`,tier:o,type:N[s],color:n}},J=(r,e)=>{let t=r===r.toLowerCase()?"b":"w",o=K[r.toLowerCase()];return{type:N[o],count:e,color:t}},Ee={\u5E25:"sui",\u5927:"taishou",\u4E2D:"chuujou",\u5C0F:"shoushou",\u4F8D:"samurai",\u69CD:"yari",\u99AC:"kiba",\u5FCD:"shinobi",\u7826:"toride",\u5175:"hyou",\u7832:"oodzutsu",\u5F13:"yumi",\u7B52:"tsutsu",\u8B00:"boushou"},$e={\u5E25:"marshal",\u5927:"general",\u4E2D:"lieutenant general",\u5C0F:"major general",\u4F8D:"warrior",\u69CD:"lancer",\u99AC:"rider",\u5FCD:"spy",\u7826:"fortress",\u5175:"soldier",\u7832:"cannon",\u5F13:"archer",\u7B52:"musketeer",\u8B00:"tactician"},Me={\u5E25:"m",\u5927:"g",\u4E2D:"i",\u5C0F:"j",\u4F8D:"w",\u69CD:"n",\u99AC:"r",\u5FCD:"s",\u7826:"f",\u5175:"d",\u7832:"c",\u5F13:"a",\u7B52:"k",\u8B00:"t"};function D(r,e,t=!1){return r.forEach(o=>{let n=t?o.color==="b"?"w":"b":o.color,s=e.find(c=>c.type===o.type&&c.color===n),i=e.findIndex(c=>c.type===o.type&&c.color===n);s&&(s.count--,s.count===0&&e.splice(i,1))}),e}function V(r,e,t){let[o,n]=r.split("-").map(Number),s=x(r,t);s&&(t[o-1][9-n]=s.map(i=>(e.find(a=>JSON.stringify(a)===JSON.stringify(i))&&(i.color=i.color==="b"?"w":"b"),i)))}function Y(r,e,t){let[o,n]=r.split("-").map(Number),s=x(r,t);if(!s)return;let i=s.filter(c=>!e.some(a=>JSON.stringify(a)===JSON.stringify(c)));i.length===0?t[o-1][9-n]=[null]:t[o-1][9-n]=i}function S(r,e){let[t,o]=r.split("-").map(Number),n=x(r,e);n&&(n.pop(),n.length===0&&(e[t-1][9-o]=[null]))}function z(r,e){let[t,o]=r.square.split("-").map(Number);e[t-1][9-o][0]?e[t-1][9-o].push(r):e[t-1][9-o]=[r]}function C(r,e){let t=x(r,e);return t?t.at(-1):void 0}function x(r,e){let[t,o]=r.split("-").map(Number);if(t<1||t>9||o<1||o>9)return;let n=e[t-1][9-o];if(n[0])return n}function Q(r){return r.flat().flat().filter(t=>t?.type==="\u5E25").length!==2}var X="3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1",Ae="3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1",ke="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1",_="9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1";function w(r){let e=L(r);if(!e.ok)throw new Error(`Invalid FEN: ${e.error}`);let[t,o,n,s,i,c]=r.split(" "),a=t.split("/").map((f,d)=>f.split("|").reduce((p,u)=>{if(u.includes(":")){let m=u.split(":").map((h,P)=>H(h,[d+1,9-p.length,P+1]));p.push(m)}else{let m=u.split("").reduce((h,P)=>(Number.isInteger(+P)?h=h.concat(Array(+P).fill(null)):h.push(H(P,[d+1,9-p.length-h.length,1])),h),[]).map(h=>[h]);p=p.concat(m)}return p},[])),l=o.split("/").flatMap(f=>{let d=[];if(f!=="-")for(let p=0;p<f.length;p+=2){let u=f[p],m=+f[p+1];d.push(J(u,m))}return d});return{board:a,hand:l,turn:n,mode:G[+s],drafting:{w:i.includes("w"),b:i.includes("b")},moveNumber:+c}}function M(r){let e="",t=0;for(let c=0;c<9;c++){for(let a=0;a<9;a++){let l=r.board[c][a];if(l[0]===null){t++;continue}if(t&&(e+=t,t=0),l.length>1)e+="|"+l.map(f=>{if(!f)return null;let d=T[E[f.type]];return f.color==="w"?d.toUpperCase():d}).join(":")+"|";else{let{type:f,color:d}=l[0],p=T[E[f]];e+=d==="w"?p.toUpperCase():p}}e+=t?`${t}/`:"/",t=0}let o="",n=r.hand.filter(c=>c.color==="w"),s=r.hand.filter(c=>c.color==="b");n.forEach(c=>{let a=T[E[c.type]];o+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),o+=n.length>0?"/":"-/",s.forEach(c=>{let a=T[E[c.type]];o+=`${c.color==="w"?a.toUpperCase():a}${c.count}`}),o+=s.length>0?"":"-";let i=Object.keys(r.drafting).filter(c=>r.drafting[c]);return`${e.slice(0,-1)} ${o} ${r.turn} ${O[r.mode]} ${i.length>0?i.join(""):"-"} ${r.moveNumber}`}function L(r){let e=r.split(" ");if(e.length!==6)return{ok:!1,error:`expected 6 fields, received ${e.length}`};let[t,o,n,s,i,c]=e,a=t.split("/");if(a.length!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 ranks, received ${a.length}]`};for(let p=0;p<a.length;p++){let m=a[p].split("|"),h=0;for(let P=0;P<m.length;P++){let g=m[P];if(g.includes(":")){h++;let y=g.split(":");if(y.length>3)return{ok:!1,error:`1st field (piece positions) is invalid [tower size] @(${p+1}-${h})`};if(!y.every(b=>"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(b)))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}else{let y=g.split("");for(let b=0;b<y.length;b++){let k=y[b];if(Number.isInteger(+k))h+=+k;else if(h++,!"mgijwnrsfdcaktMGIJWNRSFDCAKT".includes(k))return{ok:!1,error:`1st field (piece positions) is invalid [invalid piece] @(${p+1}-${h})`}}}}if(h!==9)return{ok:!1,error:`1st field (piece positions) is invalid [expected 9 squares, received ${h}] in rank: ${p+1}`}}let l=o.split("/");if(l.length!==2)return{ok:!1,error:`2nd field (hand pieces) is invalid [expected 2 hands, received ${l.length}]`};let[f,d]=l;if(f.length===1&&f!=="-"||d.length===1&&d!=="-")return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(f.length>1&&f.length%2!==0||d.length>1&&d.length%2!==0)return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece count]"};if(f.length>1)for(let p=0;p<f.length;p+=2){if(!"MGIJWNRSFDCAKT".includes(f[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+f[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}if(d.length>1)for(let p=0;p<d.length;p+=2){if(!"mgijwnrsfdcakt".includes(d[p]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid piece]"};if(!Number.isInteger(+d[p+1]))return{ok:!1,error:"2nd field (hand pieces) is invalid [invalid count]"}}return n!=="w"&&n!=="b"?{ok:!1,error:`3rd field (active player) is invalid [expected 'w' or 'b', received ${n}]`}:s.length!==1||!"0123".includes(s)?{ok:!1,error:`4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${s}]`}:i!=="-"&&!"wb".includes(i)?{ok:!1,error:`5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${i}]`}:Number.isInteger(+c)?{ok:!0}:{ok:!1,error:`6th field (full move number) is invalid [expected an integer, received ${c}]`}}var Se=[[-1,1],[-1,0],[-1,-1],[0,1],[0,-1],[1,1],[1,0],[1,-1]],Ie={\u5E25:[1,1,1,1,1,1,1,1],\u5927:[1,1/0,1,1/0,1/0,1,1/0,1],\u4E2D:[1/0,1,1/0,1,1,1/0,1,1/0],\u5C0F:[1,1,1,1,1,0,1,0],\u4F8D:[1,1,1,0,0,0,1,0],\u69CD:[1,[1,2],1,0,0,0,1,0],\u99AC:[0,[1,2],0,1,1,0,[1,2],0],\u5FCD:[[1,2],0,[1,2],0,0,[1,2],0,[1,2]],\u7826:[0,1,0,1,1,1,0,1],\u5175:[0,1,0,0,0,0,1,0],\u7832:[0,3,0,1,1,0,1,0],\u5F13:[2,2,2,0,0,0,1,0],\u7B52:[0,2,0,0,0,1,0,1],\u8B00:[1,0,1,0,0,0,1,0]};function Re(r,e,t,o,n){let[s,i]=e,[c,a]=t,[l,f]=r,d=C(`${c}-${a}`,n),p=[],u={x:i,y:s};for(;u.x!==a||u.y!==c;){u.x-=f,u.y-=l;let P=C(`${u.y}-${u.x}`,n);if(P&&P.tier>d.tier)return[];let g=d.color==="b"?-1:1,y=C(`${u.y+g}-${u.x}`,n);if(y&&y.square===`${c}-${a}`)break}let m={x:i,y:s},h=0;for(;h<o&&!(m.x<1||m.x>9||m.y<1||m.y>9);){let P=C(`${m.y}-${m.x}`,n);if(P&&P.tier>d.tier)break;p.push(`${m.y}-${m.x}`);let g=[N.cannon,N.musketeer,N.archer];if(P&&!g.includes(d.type))break;m.x+=f,m.y+=l,h++}return p}function j(r,e){let{board:t,turn:o,mode:n,hand:s}=w(e),i=C(r,t);if(!i||o!==i.color)return[];let[c,a]=r.split("-").map(Number);return Ie[i.type].flatMap((d,p)=>{let u=typeof d=="number"?d:d[0],m=typeof d=="number"?1:d[1];if(u<1)return[];let[h,P]=Se[p];i.color==="b"&&(h*=-1,P*=-1);let[g,y]=u===1/0?[c+h,a+P]:[c+u*h,a+P],b=u===1/0?1/0:i.tier+m-1;return Re([h,P],[g,y],[c,a],b,t)}).reduce((d,p)=>{let u=C(p,t),m=x(p,t),h=n==="advanced"?3:2,P=["advanced","intermediate"].includes(n);if(!u||!m)d.push(A(i,`${p}-1`,e,"route"));else{if(u.tier<h&&u.type!==N.marshal&&((i.type!==N.marshal||P)&&d.push(A(i,`${p}-${u.tier+1}`,e,"tsuke")),i.type===N.tactician&&u.color!==i.color)){let g=m.filter(v=>v.color!==i.color),y=s.filter(v=>v.color===i.color),b=g.reduce((v,$)=>(v.set($.type,(v.get($.type)??0)+1),v),new Map),k=Array.from(b.entries()).filter(([v,$])=>y.some(B=>B.type===v&&B.count>=$)).flatMap(([v])=>g.filter($=>$.type===v)),ie=qe(k);d.push(...ie.map(v=>A(i,`${p}-${u.tier+1}`,e,"betray",v)))}if(u.color!==i.color){let g=m.filter(b=>b.color===i.color).length+1,y=m.filter(b=>b.color!==i.color);d.push(A(i,`${p}-${g}`,e,"capture",y))}}return d},[])}function I(r,e){let{board:t,turn:o,mode:n,hand:s,drafting:i}=w(e);if(!r||o!==r.color)return[];if(!!s.some(u=>u.type===N.marshal&&u.color===r.color)&&r.type!==N.marshal)return[];let a=i.b||i.w,l=n==="advanced"?3:2,f=[],d=[];if(a)f=r.color==="w"?[7,8,9]:[1,2,3];else{let u=r.color==="b"?1:9,m=r.color==="b"?9:1,h=r.color==="b"?1:-1;for(let P=u;r.color==="b"?P<=m:P>=m;P+=h)Array.from({length:9}).map((y,b)=>C(`${P}-${b+1}`,t)).some(y=>y&&y.color===r.color)?(f.push(...d,P),d=[]):d.push(P)}return f.flatMap(u=>Array.from({length:9},(m,h)=>`${u}-${h+1}`)).reduce((u,m)=>{let h=C(m,t),P={type:r.type,color:r.color,square:m,tier:0};if(!h||h.color===P.color&&h.tier<l&&h.type!==N.marshal){let g=(h?.tier??0)+1;u.push(A(P,`${m}-${g}`,e,"arata")),i[r.color]&&u.push(A(P,`${m}-${g}`,e,"arata",[],!0))}return u},[])}function A(r,e,t,o,n,s){let i=r.tier!==0?`(${r.square}-${r.tier})`:"",c=+(e.split("-").at(-1)??0),a=o==="arata"?"\u65B0":"",l=o==="capture"?"\u53D6":"",f=o==="tsuke"||c!==1&&c-r.tier>0?"\u4ED8":"",d=o==="betray"?`\u8FD4${n?.map(P=>P.type).join("")}`:"",p=s?"\u7D42":"",u={piece:r.type,color:r.color,from:i.slice(1,-1),to:e,type:o,san:`${a}${r.type}${i}${l}(${e})${d||f}${p}`,before:t,after:"",draftFinished:s,captured:n},{after:m,gameOverSAN:h}=Fe(u,u.before);return u.after=m,u.san+=h,u}function Fe(r,e){let{board:t,hand:o,mode:n,turn:s,drafting:i,moveNumber:c}=w(e),[a,l,f]=r.to.split("-"),d={type:r.piece,color:r.color,square:`${a}-${l}`,tier:+f};r.type==="route"||r.type==="tsuke"?S(r.from,t):r.type==="capture"?(S(r.from,t),Y(`${a}-${l}`,r.captured,t)):r.type==="betray"?(S(r.from,t),V(`${a}-${l}`,r.captured,t),D(r.captured,o,!0)):r.type==="arata"&&(D([d],o),r.draftFinished&&(i[r.color]=!1)),z(d,t),s==="b"&&(i.w||!i.b)&&c++,s==="w"&&!i.b&&!i.w&&r.draftFinished&&c++,i.w===i.b?(!r.draftFinished||s!=="w")&&(s=s==="b"?"w":"b"):!i.b&&s==="b"?s="w":!i.w&&s==="w"&&(s="b");let p="";return r.captured?.some(u=>u.type===N.marshal)&&(p="\u52DD"),{after:M({board:t,hand:o,mode:n,turn:s,drafting:i,moveNumber:c}),gameOverSAN:p}}function qe(r){let e=[];function t(o,n){n.length>0&&e.push([...n]);for(let s=o;s<r.length;s++)n.push(r[s]),t(s+1,n),n.pop()}return t(0,[]),e}function Z(r,e){let t=e?.maxWidth??6,o=e?.newline??`
|
|
2
|
+
`,n="",s=0;return r.forEach((i,c)=>{let a=w(i.before);if(a.moveNumber!==s){let l=i.color==="w"?".":"...";n+=`${a.moveNumber}${l} `,s=a.moveNumber}n+=`${i.san} `,(c+1)%t===0&&(n+=o)}),n.replaceAll(" "," ").trim()}function ee(r,e){let t=e?.newline??`
|
|
3
|
+
`;return r.split(t).flatMap(n=>n.replace(/\d+\.+/g,"").split(" ")).filter(n=>n!=="")}function re(r,e){let t=w(r);if(!e)return te(t);let o=M({board:e.board,hand:e.hand,turn:e.turn,moveNumber:e.moveNumber,drafting:e.drafting,mode:e.mode}),n=Oe(o,r);return n.isSingleMove&&n.movedPiece?_e(t,e,n):te(t)}function te(r){let e={...r,board:r.board.map(o=>o.map(n=>n.map(s=>s&&{...s}))),hand:r.hand.map(o=>({...o}))},t=R(e.board,e.hand);for(let o in t){let n=t[o],[s,i]=o.split("-");[...n.boardPieces.sort(oe),...n.handPieces].forEach((a,l)=>{a.id=`${s}-${i}-${l+1}`})}return e}function Oe(r,e){let t=w(r),o=w(e),n=He(t.board,o.board),s=De(t.hand,o.hand),i=n.disappeared.length+n.appeared.length,c=Math.abs(s.whiteChange)+Math.abs(s.blackChange);if(i===2&&c<=1){let a=n.disappeared[0],l=n.appeared[0];if(a&&l&&a.type===l.type&&a.color===l.color)return{isSingleMove:!0,movedPiece:{fromSquare:a.square,toSquare:l.square,piece:l,isArata:!1,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===0){let a=n.appeared[0];if(s.changes.find(f=>f.type===a.type&&f.color===a.color&&f.countDiff<0))return{isSingleMove:!0,movedPiece:{toSquare:a.square,piece:a,isArata:!0,isCapture:!1}}}if(n.appeared.length===1&&n.disappeared.length===2){let a=n.appeared[0],l=n.disappeared.find(d=>d.type===a.type&&d.color===a.color),f=n.disappeared.find(d=>d.type!==a.type||d.color!==a.color);if(l&&f)return{isSingleMove:!0,movedPiece:{fromSquare:l.square,toSquare:a.square,piece:a,isArata:!1,isCapture:!0},capturedPieces:[f]}}return{isSingleMove:!1}}function He(r,e){let t=[],o=[],n=new Map,s=new Map;for(let i of r)for(let c of i)for(let a of c)a&&(n.has(a.square)||n.set(a.square,[]),n.get(a.square).push(a));for(let i of e)for(let c of i)for(let a of c)a&&(s.has(a.square)||s.set(a.square,[]),s.get(a.square).push(a));for(let[i,c]of n){let a=s.get(i)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||t.push(l)}for(let[i,c]of s){let a=n.get(i)||[];for(let l of c)a.some(d=>d.type===l.type&&d.color===l.color&&d.tier===l.tier)||o.push(l)}return{disappeared:t,appeared:o}}function De(r,e){let t=new Map,o=new Map;for(let a of r){let l=`${a.color}-${a.type}`;t.set(l,a.count)}for(let a of e){let l=`${a.color}-${a.type}`;o.set(l,a.count)}let n=[],s=0,i=0,c=new Set([...t.keys(),...o.keys()]);for(let a of c){let l=t.get(a)||0,d=(o.get(a)||0)-l;if(d!==0){let[p,u]=a.split("-");n.push({type:u,color:p,countDiff:d}),p==="w"?s+=Math.abs(d):i+=Math.abs(d)}}return{changes:n,whiteChange:s,blackChange:i}}function _e(r,e,t){let o={...r,board:r.board.map(a=>a.map(l=>l.map(f=>f&&{...f,id:void 0}))),hand:r.hand.map(a=>({...a,id:void 0}))};if(!t.movedPiece)return o;Le(o,e,t),Be(o);let{fromSquare:n,toSquare:s,piece:i,isArata:c}=t.movedPiece;if(c){let a=e.hand.find(l=>l.type===i.type&&l.color===i.color);if(a?.id){let l=W(o.board,s,i.type,i.color,i.tier);l&&(l.id=a.id);let f=o.hand.find(d=>d.type===i.type&&d.color===i.color);f&&a.id&&(f.id=a.id)}}else{let a=n?W(e.board,n,i.type,i.color):null;if(a?.id){let l=W(o.board,s,i.type,i.color,i.tier);l&&(l.id=a.id)}}return o}function W(r,e,t,o,n){let[s,i]=e.split("-").map(Number);if(s<1||s>9||i<1||i>9)return null;let c=r[s-1][9-i];for(let a of c)if(a&&(!t||a.type===t)&&(!o||a.color===o)&&(!n||a.tier===n))return a;return null}function Le(r,e,t){if(!t.movedPiece)return;let{fromSquare:o,toSquare:n,piece:s,isArata:i}=t.movedPiece,c=R(e.board,e.hand),a=R(r.board,r.hand);for(let l in c){let f=c[l],d=a[l];if(!d)continue;let[p,u]=l.split("-");s.type===u&&s.color===p?We(d,f,o,n,i):je(d,f)}}function je(r,e){for(let t of r.boardPieces){let o=e.boardPieces.find(n=>n.square===t.square&&n.tier===t.tier);o?.id&&(t.id=o.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let t=r.handPieces[0],o=e.handPieces[0];o.id&&(t.id=o.id)}}function We(r,e,t,o,n){if(n){for(let s of r.boardPieces){if(s.square===o)continue;let i=e.boardPieces.find(c=>c.square===s.square&&c.tier===s.tier);i?.id&&(s.id=i.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let s=r.handPieces[0],i=e.handPieces[0];i.id&&(s.id=i.id)}}else{for(let s of r.boardPieces){if(s.square===o)continue;let i=e.boardPieces.find(c=>c.square===s.square&&c.tier===s.tier);i?.id&&(s.id=i.id)}if(r.handPieces.length>0&&e.handPieces.length>0){let s=r.handPieces[0],i=e.handPieces[0];i.id&&(s.id=i.id)}}}function R(r,e){let t={};for(let o of r)for(let n of o)for(let s of n)if(s){let i=`${s.color}-${s.type}`;t[i]||(t[i]={boardPieces:[],handPieces:[]}),t[i].boardPieces.push(s)}for(let o of e){let n=`${o.color}-${o.type}`;t[n]||(t[n]={boardPieces:[],handPieces:[]}),t[n].handPieces.push(o)}return t}function Be(r){let e=R(r.board,r.hand);for(let t in e){let o=e[t],[n,s]=t.split("-"),i=[...o.boardPieces.sort(oe),...o.handPieces],c=1;for(let a of i)if(!a.id){for(;i.some(l=>l.id===`${n}-${s}-${c}`);)c++;a.id=`${n}-${s}-${c}`,c++}}}function oe(r,e){let[t,o]=r.square.split("-").map(Number),[n,s]=e.square.split("-").map(Number);return t!==n?t-n:o!==s?o-s:r.tier-e.tier}var ne=class{#r;#n;#s;#a;#o;#l;#e=[];#i=null;#d=null;#c;#t(e){let t=re(e,this.#d);this.#r=t.board,this.#n=t.hand,this.#s=t.turn,this.#a=t.moveNumber,this.#o=t.drafting,this.#l=t.mode,this.#i=e,this.#d=t}constructor(e){this.#c=e??X,this.#t(this.#c)}ascii(e){let t={1:F.yellow,2:F.blue,3:F.green},o=`\u3000\uFF19\uFF18\uFF17\uFF16\uFF15\uFF14\uFF13\uFF12\uFF11\u3000
|
|
4
|
+
`;o+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
|
|
5
|
+
`;for(let n=1;n<=9;n++){o+="\uFF5C";for(let s=9;s>0;s--){let i=this.getTop(`${n}-${s}`);if(!i){o+="\u30FB";continue}let c=T[E[i.type]],a=i.color==="w"?c.toUpperCase():c,l=t[i.tier](e?.english?String.fromCharCode(a.charCodeAt(0)+65248):i.type);o+=i.color==="w"?l:F.dim(l)}o+=`\uFF5C${String.fromCharCode(n-1+65297)}
|
|
6
|
+
`}return o+=`\uFF0B\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\uFF0B
|
|
7
|
+
`,o}board(){return this.#r}captured(e){let o=this.#e.flatMap(n=>n.captured??[]).reduce((n,s)=>{let i=n.find(c=>c.type===s.type&&c.color===s.color);return i?i.count++:n.push({type:s.type,color:s.color,count:1}),n},[]);return e?o.filter(n=>n.color===e):o}clear(){this.#i=null,this.#t(_),this.#e=[]}fen(){return M({board:this.#r,hand:this.#n,turn:this.#s,mode:this.#l,drafting:this.#o,moveNumber:this.#a})}get(e){return x(e,this.#r)}getDraftingRights(e){return e?this.#o[e]:this.#o}getTop(e){return C(e,this.#r)}hand(e){return e?this.#n.filter(t=>t.color===e):this.#n}history(e){return e?.verbose?this.#e:this.#e.map(t=>t.san)}inDraft(){return this.#o.b||this.#o.w}isFourfoldRepetition(){let e=this.#e.map(o=>o.before.split(" ")[0]);e.length&&e.push(this.#e.at(-1).after.split(" ")[0]);let t=e.reduce((o,n)=>(o.set(n,(o.get(n)||0)+1),o),new Map);return Math.max(...t.values())===4}isGameOver(){return!this.inDraft()&&(Q(this.#r)||this.isFourfoldRepetition())}load(e){this.#t(e)}loadPgn(e,t=_,o){this.#i=null,this.#t(t),this.#e=[],ee(e,o).forEach(s=>this.move(s))}move(e){let t=this.moves({verbose:!0}),o=typeof e=="string"?t.find(n=>n.san===e):t.find(n=>e.piece===n.piece&&e.type===n.type&&e.from===n.from&&e.to===n.to&&e.captured===n.captured&&e.draftFinished===n.draftFinished);if(!o)throw new Error(`Illegal move: ${e}`);return this.#e.push(o),this.isFourfoldRepetition()&&(this.#e.at(-1).san+="\u505C"),this.#t(o.after),o}moves(e){if(this.isGameOver())return[];if(e?.square){let t=j(e.square,this.fen());return e.verbose?t:t.map(o=>o.san)}else if(e?.arata){let t=I(e.arata,this.fen());return e.verbose?t:t.map(o=>o.san)}else if(this.inDraft()){let t=this.hand().flatMap(o=>I(o,this.fen()));return e?.verbose?t:t.map(o=>o.san)}else{let t=U.flatMap(s=>j(s,this.fen())),o=this.hand().flatMap(s=>I(s,this.fen())),n=[...t,...o];return e?.verbose?n:n.map(s=>s.san)}}moveNumber(){return this.#a}pgn(e){return Z(this.#e,e)}print(e){console.log(this.ascii(e))}reset(){this.#i=null,this.#t(this.#c),this.#e=[]}turn(){return this.#s}undo(){let e=this.#e.pop();return e?(this.#t(e.before),e):null}validateFen(e){return L(e)}};export{_ as ADVANCED_POSITION,pe as ARATA,we as ARCHER,Ae as BEGINNER_POSITION,de as BETRAY,ae as BLACK,Ce as CANNON,Ee as CANONICAL_NAMES,$e as ENGLISH_NAMES,Me as FEN_CODES,Ne as FORTRESS,ue as GENERAL,ne as Gungi,ke as INTERMEDIATE_POSITION,X as INTRO_POSITION,ge as LANCER,he as LIEUTENANT_GENERAL,me as MAJOR_GENERAL,fe as MARSHAL,Te as MUSKETEER,ye as RIDER,ve as SOLDIER,be as SPY,U as SQUARES,xe as TACTICIAN,le as TAKE,ce as TSUKE,Pe as WARRIOR,se as WHITE,L as validateFen};
|
|
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\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,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AOA,EAAG,OAASoB,GAAQpB,EAAG,QAAU3B,CAC1C,EACA,GAAIlB,GAAaA,EAAU,KAAOA,EAAU,IAAI,OAASoE,EACxD,OAAOpE,EAAU,IAAIoE,CAAK,CAG5B,CAGA,kBAAkBH,EAAc/C,EAAc4B,EAAqB,CAClE,IAAM9C,EAAY,KAAKtB,GAAM,KAC3BmE,GAAOA,EAAG,OAASoB,GAAQpB,EAAG,QAAU3B,CAC1C,EACA,GAAIlB,GAAaA,EAAU,IAAK,CAC/B,IAAMoE,EAAQpE,EAAU,IAAI,QAAQ8C,CAAE,EACtC,GAAIsB,IAAU,GACb,OAAApE,EAAU,IAAI,OAAOoE,EAAO,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/gungi/gungi.ts","../src/gungi/utils.ts","../src/gungi/fen.ts","../src/gungi/move_gen.ts","../src/gungi/pgn.ts","../src/gungi/piece-ids.ts"],"sourcesContent":["import pc from 'picocolors';\nimport {\n\tADVANCED_POSITION,\n\tBEGINNER_POSITION,\n\tencodeFEN,\n\tINTERMEDIATE_POSITION,\n\tINTRO_POSITION,\n\tParsedFEN,\n\tparseFEN,\n\tvalidateFen,\n} from './fen';\nimport { generateArata, generateMovesForSquare } from './move_gen';\nimport { encodePGN, parsePGN, PGNOptions } from './pgn';\nimport { assignPieceIds, assignPieceIdsWithState } from './piece-ids';\nimport {\n\tARATA,\n\tARCHER,\n\tBETRAY,\n\tBLACK,\n\tBoard,\n\tCANNON,\n\tCANONICAL_NAMES,\n\tColor,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tFORTRESS,\n\tGENERAL,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tisGameOver,\n\tLANCER,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tMARSHAL,\n\tMove,\n\tMUSKETEER,\n\tpieceToFenCode,\n\tRIDER,\n\tSetupMode,\n\tSOLDIER,\n\tSPY,\n\tSQUARES,\n\tsymbolToName,\n\tTACTICIAN,\n\tTAKE,\n\tTSUKE,\n\tWARRIOR,\n\tWHITE,\n} from './utils';\n\nexport {\n\tWHITE,\n\tBLACK,\n\tMARSHAL,\n\tGENERAL,\n\tLIEUTENANT_GENERAL,\n\tMAJOR_GENERAL,\n\tWARRIOR,\n\tLANCER,\n\tRIDER,\n\tSPY,\n\tFORTRESS,\n\tSOLDIER,\n\tCANNON,\n\tARCHER,\n\tMUSKETEER,\n\tTACTICIAN,\n\tTSUKE,\n\tTAKE,\n\tBETRAY,\n\tARATA,\n\tINTRO_POSITION,\n\tBEGINNER_POSITION,\n\tINTERMEDIATE_POSITION,\n\tADVANCED_POSITION,\n\tSQUARES,\n\tCANONICAL_NAMES,\n\tENGLISH_NAMES,\n\tFEN_CODES,\n\tvalidateFen,\n};\n\nexport class Gungi {\n\t#board!: Board;\n\t#hand!: HandPiece[];\n\t#turn!: Color;\n\t#moveNumber!: number;\n\t#drafting!: Record<Color, boolean>;\n\t#mode!: SetupMode;\n\n\t#history: Move[] = [];\n\t#previousFen: string | null = null;\n\t#previousState: ParsedFEN | null = null;\n\n\t#initPosition: string;\n\n\t#initializeState(fen: string) {\n\t\t// Assign IDs using the previous state for stability\n\t\tconst stateWithIds = assignPieceIdsWithState(fen, this.#previousState);\n\n\t\tthis.#board = stateWithIds.board;\n\t\tthis.#hand = stateWithIds.hand;\n\t\tthis.#turn = stateWithIds.turn;\n\t\tthis.#moveNumber = stateWithIds.moveNumber;\n\t\tthis.#drafting = stateWithIds.drafting;\n\t\tthis.#mode = stateWithIds.mode;\n\n\t\t// Update the previous state for next time\n\t\tthis.#previousFen = fen;\n\t\tthis.#previousState = stateWithIds;\n\t}\n\n\tconstructor(fen?: string) {\n\t\tthis.#initPosition = fen ?? INTRO_POSITION;\n\t\tthis.#initializeState(this.#initPosition);\n\t}\n\n\tascii(opts?: { english?: boolean }) {\n\t\tconst tierToColor = {\n\t\t\t1: pc.yellow,\n\t\t\t2: pc.blue,\n\t\t\t3: pc.green,\n\t\t} as const;\n\n\t\tlet s = ` 987654321 \\n`;\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\tfor (let rank = 1; rank <= 9; rank++) {\n\t\t\ts += `|`;\n\t\t\tfor (let file = 9; file > 0; file--) {\n\t\t\t\tconst square = this.getTop(`${rank}-${file}`);\n\t\t\t\tif (!square) {\n\t\t\t\t\ts += '・';\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst code = pieceToFenCode[symbolToName[square.type]];\n\t\t\t\tconst en = square.color === 'w' ? code.toUpperCase() : code;\n\n\t\t\t\tconst coloredPiece = tierToColor[square.tier as 1 | 2 | 3](\n\t\t\t\t\topts?.english\n\t\t\t\t\t\t? String.fromCharCode(en.charCodeAt(0) + 0xfee0)\n\t\t\t\t\t\t: square.type\n\t\t\t\t);\n\n\t\t\t\ts += square.color === 'w' ? coloredPiece : pc.dim(coloredPiece);\n\t\t\t}\n\t\t\ts += `|${String.fromCharCode(rank - 1 + '1'.charCodeAt(0))}\\n`;\n\t\t}\n\t\ts += `+ーーーーーーーーー+\\n`;\n\t\treturn s;\n\t}\n\n\tboard() {\n\t\treturn this.#board;\n\t}\n\n\tcaptured(color?: Color) {\n\t\tconst allCaptured = this.#history.flatMap((move) => move.captured ?? []);\n\t\tconst capturedCounts = allCaptured.reduce((acc, p) => {\n\t\t\tconst c = acc.find((a) => a.type === p.type && a.color === p.color);\n\t\t\tif (c) {\n\t\t\t\tc.count++;\n\t\t\t} else {\n\t\t\t\tacc.push({ type: p.type, color: p.color, count: 1 });\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, [] as HandPiece[]);\n\n\t\treturn color\n\t\t\t? capturedCounts.filter((p) => p.color === color)\n\t\t\t: capturedCounts;\n\t}\n\n\tclear() {\n\t\tthis.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(ADVANCED_POSITION);\n\t\tthis.#history = [];\n\t}\n\n\tfen() {\n\t\treturn encodeFEN({\n\t\t\tboard: this.#board,\n\t\t\thand: this.#hand,\n\t\t\tturn: this.#turn,\n\t\t\tmode: this.#mode,\n\t\t\tdrafting: this.#drafting,\n\t\t\tmoveNumber: this.#moveNumber,\n\t\t});\n\t}\n\n\tget(square: string) {\n\t\treturn get(square, this.#board);\n\t}\n\n\tgetDraftingRights(color?: Color) {\n\t\treturn color ? this.#drafting[color] : this.#drafting;\n\t}\n\n\tgetTop(square: string) {\n\t\treturn getTop(square, this.#board);\n\t}\n\n\thand(color?: Color) {\n\t\treturn color\n\t\t\t? this.#hand.filter((piece) => piece.color === color)\n\t\t\t: this.#hand;\n\t}\n\n\thistory(opts?: { verbose?: boolean }) {\n\t\treturn opts?.verbose\n\t\t\t? this.#history\n\t\t\t: this.#history.map((move) => move.san);\n\t}\n\n\tinDraft() {\n\t\treturn this.#drafting.b || this.#drafting.w;\n\t}\n\n\tisFourfoldRepetition() {\n\t\tconst states = this.#history.map((move) => move.before.split(' ')[0]);\n\t\tif (states.length) states.push(this.#history.at(-1)!.after.split(' ')[0]);\n\t\tconst frequencyMap = states.reduce((map, str) => {\n\t\t\tmap.set(str, (map.get(str) || 0) + 1);\n\t\t\treturn map;\n\t\t}, new Map<string, number>());\n\n\t\treturn Math.max(...frequencyMap.values()) === 4;\n\t}\n\n\tisGameOver() {\n\t\treturn (\n\t\t\t!this.inDraft() &&\n\t\t\t(isGameOver(this.#board) || this.isFourfoldRepetition())\n\t\t);\n\t}\n\n\tload(fen: string) {\n\t\tthis.#initializeState(fen);\n\t}\n\n\tloadPgn(\n\t\tpgn: string,\n\t\tfen = ADVANCED_POSITION,\n\t\topts?: Pick<PGNOptions, 'newline'>\n\t) {\n\t\tthis.#previousFen = null; // Reset tracking for new game\n\t\tthis.#initializeState(fen);\n\t\tthis.#history = [];\n\t\tconst moves = parsePGN(pgn, opts);\n\t\tmoves.forEach((move) => this.move(move));\n\t}\n\n\tmove(move: string | Exclude<Move, 'color' | 'san' | 'before' | 'after'>) {\n\t\tconst moves = this.moves({ verbose: true }) as Move[];\n\t\tconst found =\n\t\t\ttypeof move === 'string'\n\t\t\t\t? moves.find((m) => m.san === move)\n\t\t\t\t: moves.find(\n\t\t\t\t\t\t(m) =>\n\t\t\t\t\t\t\tmove.piece === m.piece &&\n\t\t\t\t\t\t\tmove.type === m.type &&\n\t\t\t\t\t\t\tmove.from === m.from &&\n\t\t\t\t\t\t\tmove.to === m.to &&\n\t\t\t\t\t\t\tmove.captured === m.captured &&\n\t\t\t\t\t\t\tmove.draftFinished === m.draftFinished\n\t\t\t\t\t);\n\t\tif (!found) throw new Error(`Illegal move: ${move}`);\n\n\t\tthis.#history.push(found);\n\t\tif (this.isFourfoldRepetition()) this.#history.at(-1)!.san += '停';\n\t\tthis.#initializeState(found.after);\n\t\treturn found;\n\t}\n\n\tmoves(opts?: { square?: string; arata?: HandPiece; verbose?: boolean }) {\n\t\tif (this.isGameOver()) return [];\n\n\t\tif (opts?.square) {\n\t\t\tconst moves = generateMovesForSquare(opts.square, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (opts?.arata) {\n\t\t\tconst moves = generateArata(opts.arata, this.fen());\n\t\t\treturn opts.verbose ? moves : moves.map((move) => move.san);\n\t\t} else if (this.inDraft()) {\n\t\t\tconst moves = this.hand().flatMap((hp) => generateArata(hp, this.fen()));\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t} else {\n\t\t\tconst boardMoves = SQUARES.flatMap((square) =>\n\t\t\t\tgenerateMovesForSquare(square, this.fen())\n\t\t\t);\n\n\t\t\tconst handMoves = this.hand().flatMap((hp) =>\n\t\t\t\tgenerateArata(hp, this.fen())\n\t\t\t);\n\n\t\t\tconst moves = [...boardMoves, ...handMoves];\n\t\t\treturn opts?.verbose ? moves : moves.map((move) => move.san);\n\t\t}\n\t}\n\n\tmoveNumber() {\n\t\treturn this.#moveNumber;\n\t}\n\n\tpgn(opts?: PGNOptions) {\n\t\treturn encodePGN(this.#history, opts);\n\t}\n\n\tprint(opts?: { english?: boolean }) {\n\t\tconsole.log(this.ascii(opts));\n\t}\n\n\treset() {\n\t\tthis.#previousFen = null; // Reset tracking for fresh start\n\t\tthis.#initializeState(this.#initPosition);\n\t\tthis.#history = [];\n\t}\n\n\tturn() {\n\t\treturn this.#turn;\n\t}\n\n\tundo() {\n\t\tconst lastMove = this.#history.pop();\n\t\tif (lastMove) {\n\t\t\tthis.#initializeState(lastMove.before);\n\t\t\treturn lastMove;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tvalidateFen(fen: string) {\n\t\treturn validateFen(fen);\n\t}\n}\n","const inverseMap = <T extends Record<string, string | number | symbol>>(\n\tmap: T\n): Record<T[keyof T], keyof T> =>\n\tObject.entries(map).reduce(\n\t\t(acc, [key, value]) => ({ ...acc, [value]: key }),\n\t\t{} as Record<T[keyof T], keyof T>\n\t);\n\nexport type Board = (Piece | null)[][][];\nexport type Piece = {\n\tsquare: string;\n\ttier: number;\n\ttype: PieceType;\n\tcolor: Color;\n\tid?: string;\n};\nexport type HandPiece = {\n\ttype: PieceType;\n\tcolor: Color;\n\tcount: number;\n\tid?: string;\n};\n\nexport type Move = {\n\tcolor: Color;\n\tpiece: PieceType;\n\tfrom?: string;\n\tto: string;\n\tsan: string;\n\tbefore: string;\n\tafter: string;\n\ttype: 'route' | 'capture' | 'tsuke' | 'betray' | 'arata';\n\tdraftFinished?: boolean;\n\tcaptured?: Piece[];\n};\n\nexport type SetupMode = 'intro' | 'beginner' | 'intermediate' | 'advanced';\nexport const setupModeToCode: Record<SetupMode, number> = {\n\tintro: 0,\n\tbeginner: 1,\n\tintermediate: 2,\n\tadvanced: 3,\n};\nexport const setupCodeToMode = inverseMap(setupModeToCode);\n\nexport const WHITE = 'w';\nexport const BLACK = 'b';\n\nexport const TSUKE = '付';\nexport const TAKE = '取';\nexport const BETRAY = '返';\nexport const ARATA = '新';\n\nexport const MARSHAL = '帥';\nexport const GENERAL = '大';\nexport const LIEUTENANT_GENERAL = '中';\nexport const MAJOR_GENERAL = '小';\nexport const WARRIOR = '侍';\nexport const LANCER = '槍';\nexport const RIDER = '馬';\nexport const SPY = '忍';\nexport const FORTRESS = '砦';\nexport const SOLDIER = '兵';\nexport const CANNON = '砲';\nexport const ARCHER = '弓';\nexport const MUSKETEER = '筒';\nexport const TACTICIAN = '謀';\n\nexport const SQUARES = Array.from({ length: 9 }, (_, x) => x + 1).flatMap((x) =>\n\tArray.from({ length: 9 }, (_, y) => `${x}-${9 - y}`)\n);\n\nexport type Color = 'b' | 'w';\nexport type PieceType =\n\t| '帥'\n\t| '大'\n\t| '中'\n\t| '小'\n\t| '侍'\n\t| '槍'\n\t| '馬'\n\t| '忍'\n\t| '砦'\n\t| '兵'\n\t| '砲'\n\t| '弓'\n\t| '筒'\n\t| '謀';\n\nexport type PieceCode =\n\t| 'm'\n\t| 'g'\n\t| 'i'\n\t| 'j'\n\t| 'w'\n\t| 'n'\n\t| 'r'\n\t| 's'\n\t| 'f'\n\t| 'd'\n\t| 'c'\n\t| 'a'\n\t| 'k'\n\t| 't';\n\nexport type Name =\n\t| 'marshal'\n\t| 'general'\n\t| 'lieutenant_general'\n\t| 'major_general'\n\t| 'warrior'\n\t| 'lancer'\n\t| 'rider'\n\t| 'spy'\n\t| 'fortress'\n\t| 'soldier'\n\t| 'cannon'\n\t| 'archer'\n\t| 'musketeer'\n\t| 'tactician';\n\nexport const piece: Record<Name, PieceType> = {\n\tmarshal: '帥',\n\tgeneral: '大',\n\tlieutenant_general: '中',\n\tmajor_general: '小',\n\twarrior: '侍',\n\tlancer: '槍',\n\trider: '馬',\n\tspy: '忍',\n\tfortress: '砦',\n\tsoldier: '兵',\n\tcannon: '砲',\n\tarcher: '弓',\n\tmusketeer: '筒',\n\ttactician: '謀',\n};\n\nexport const symbolToName = inverseMap(piece);\n\nexport const pieceToFenCode: Record<Name, PieceCode> = {\n\tmarshal: 'm',\n\tgeneral: 'g',\n\tlieutenant_general: 'i',\n\tmajor_general: 'j',\n\twarrior: 'w',\n\tlancer: 'n',\n\trider: 'r',\n\tspy: 's',\n\tfortress: 'f',\n\tsoldier: 'd',\n\tcannon: 'c',\n\tarcher: 'a',\n\tmusketeer: 'k',\n\ttactician: 't',\n};\n\nexport const fenCodeToPiece = inverseMap(pieceToFenCode);\n\nexport const createPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\t[y, x, z]: [number, number, number]\n): Piece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\tsquare: `${y}-${x}`,\n\t\ttier: z,\n\t\ttype: piece[name],\n\t\tcolor,\n\t};\n};\n\nexport const createHandPieceFromFenCode = (\n\tcode: PieceCode | Uppercase<PieceCode>,\n\tcount: number\n): HandPiece => {\n\tconst color = code === code.toLowerCase() ? 'b' : 'w';\n\tconst name = fenCodeToPiece[code.toLowerCase() as PieceCode];\n\n\treturn {\n\t\ttype: piece[name],\n\t\tcount,\n\t\tcolor,\n\t};\n};\n\nexport const CANONICAL_NAMES: Record<PieceType, string> = {\n\t帥: 'sui',\n\t大: 'taishou',\n\t中: 'chuujou',\n\t小: 'shoushou',\n\t侍: 'samurai',\n\t槍: 'yari',\n\t馬: 'kiba',\n\t忍: 'shinobi',\n\t砦: 'toride',\n\t兵: 'hyou',\n\t砲: 'oodzutsu',\n\t弓: 'yumi',\n\t筒: 'tsutsu',\n\t謀: 'boushou',\n};\n\nexport const ENGLISH_NAMES: Record<PieceType, string> = {\n\t帥: 'marshal',\n\t大: 'general',\n\t中: 'lieutenant general',\n\t小: 'major general',\n\t侍: 'warrior',\n\t槍: 'lancer',\n\t馬: 'rider',\n\t忍: 'spy',\n\t砦: 'fortress',\n\t兵: 'soldier',\n\t砲: 'cannon',\n\t弓: 'archer',\n\t筒: 'musketeer',\n\t謀: 'tactician',\n};\n\nexport const FEN_CODES: Record<PieceType, string> = {\n\t帥: 'm',\n\t大: 'g',\n\t中: 'i',\n\t小: 'j',\n\t侍: 'w',\n\t槍: 'n',\n\t馬: 'r',\n\t忍: 's',\n\t砦: 'f',\n\t兵: 'd',\n\t砲: 'c',\n\t弓: 'a',\n\t筒: 'k',\n\t謀: 't',\n};\n\nexport function updateHand(\n\tpieces: Piece[],\n\thand: HandPiece[],\n\toppositeColor = false\n): HandPiece[] {\n\tpieces.forEach((p) => {\n\t\tconst c = oppositeColor ? (p.color === 'b' ? 'w' : 'b') : p.color;\n\t\tconst hp = hand.find((h) => h.type === p.type && h.color === c);\n\t\tconst hpi = hand.findIndex((h) => h.type === p.type && h.color === c);\n\n\t\tif (hp) {\n\t\t\thp.count--;\n\t\t\tif (hp.count === 0) hand.splice(hpi, 1);\n\t\t}\n\t});\n\n\treturn hand;\n}\n\nexport function convert(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tboard[rank - 1][9 - file] = tower.map((piece) => {\n\t\tconst p = pieces.find((p) => JSON.stringify(p) === JSON.stringify(piece));\n\t\tif (p) {\n\t\t\tpiece.color = piece.color === 'b' ? 'w' : 'b';\n\t\t}\n\t\treturn piece;\n\t});\n}\n\nexport function remove(\n\tsquare: string,\n\tpieces: Piece[],\n\tboard: (Piece | null)[][][]\n) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\tconst newTower = tower.filter(\n\t\t(piece) => !pieces.some((p) => JSON.stringify(p) === JSON.stringify(piece))\n\t);\n\n\tif (newTower.length === 0) board[rank - 1][9 - file] = [null];\n\telse board[rank - 1][9 - file] = newTower;\n}\n\nexport function removeTop(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tconst tower = get(square, board);\n\tif (!tower) return;\n\n\ttower.pop();\n\tif (tower.length === 0) board[rank - 1][9 - file] = [null];\n}\n\nexport function put(piece: Piece, board: (Piece | null)[][][]) {\n\tconst [rank, file] = piece.square.split('-').map(Number);\n\tconst occupied = board[rank - 1][9 - file];\n\n\tif (!occupied[0]) board[rank - 1][9 - file] = [piece];\n\telse board[rank - 1][9 - file].push(piece);\n}\n\nexport function getTop(square: string, board: (Piece | null)[][][]) {\n\tconst tower = get(square, board);\n\treturn tower ? tower.at(-1)! : undefined;\n}\n\nexport function get(square: string, board: (Piece | null)[][][]) {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return undefined;\n\n\tconst s = board[rank - 1][9 - file];\n\tif (!s[0]) return undefined;\n\n\treturn s as Piece[];\n}\n\nexport function isGameOver(board: (Piece | null)[][][]) {\n\tconst marshal = board\n\t\t.flat()\n\t\t.flat()\n\t\t.filter((p) => p?.type === '帥');\n\treturn marshal.length !== 2;\n}\n","// Forsyth–Edwards Notation (FEN) Parser and Serializer for Gungi games.\n// Read more about FEN for chess: https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation\n//\n// Gungi FEN will have\n// 1. Piece placement data:\n// Each rank is described, starting with rank 1 and ending with rank 9, with a '/' between each one; within each rank,\n// the contents of the squares are described from file 9 to file 1; within each square the tower is described\n// from bottom to top (towers of 2 or higher are surrounded with a '|' with ':' in between pices).\n// Each pieces is represented by a single character from the standard English names\n//\n// 帥 marshal = m\n// 大 general = g\n// 中 lieutenant_general = i\n// 小 major_general = j\n// 侍 warrior = w\n// 槍 lancer = n\n// 馬 rider = r\n// 忍 spy = s\n// 砦 fortress = f\n// 兵 soldier = d\n// 砲 cannon = c\n// 弓 archer = a\n// 筒 musketeer = k\n// 謀 tactician = t\n//\n// Black pieces are designated using lowercase (\"mgijwnrsfdcakt\"),\n// while white pieces use uppercase (\"MGIJWNRSFDCAKT\")\n//\n// A set of one or more consecutive empty squares within a rank is denoted by a digit from \"1\" to \"9\", corresponding to the number of squares.\n// 2: Hand piece data:\n// Each piece in hand is represented by a single character (see above) followed by the number of that piece in hand (1-9);\n// white's hand piecs come first followed by black's separated by a '/'. if a player has no pieces in hand, it's represented with the character '-'\n// 3: Active player:\n// \"w\" means that White is to move; \"b\" means that Black is to move.\n// 4: Setup mode:\n// \"0\" means intro placement, \"1\" for Beginner, \"2\" for Intermediate, \"3\" for Advanced\n// 5: Drafting availability:\n// If neither side has the ability to draft, this field uses the character \"-\". Otherwise, this field contains one or more letters: \"w\" if White can draft and 'b' if Black can draft\n// 6: Full move number:\n// The number of the full moves. It starts at 1 and is incremented after Black's move.\n//\n// Examples\n//\n// FEN for the starting position of a beginner game of gungi:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1\"\n// and after the move 1.大(6-9-1)(5-8-2)付:\n// \"3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 b 1 - 1\"\n// and then after 1...槍(5-2-1)(4-3-2)付:\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1AR1/4MI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 2\"\n// and then after 2.新忍(3-8-2)付\n// \"3img3/1ra3as1/d1fwd|w:n|f1d/9/9/9/D1FWDWF1D/1SA1|N:G|1|A:S|R1/4MI3 J2N2R1D1/j2n2s1r1d1 b 1 - 2\"\n\nimport {\n\tBoard,\n\tColor,\n\tcreateHandPieceFromFenCode,\n\tcreatePieceFromFenCode,\n\tHandPiece,\n\tPiece,\n\tPieceCode,\n\tpieceToFenCode,\n\tsetupCodeToMode,\n\tSetupMode,\n\tsetupModeToCode,\n\tsymbolToName,\n} from './utils';\n\nexport const INTRO_POSITION =\n\t'3img3/1s2n2s1/d1fwdwf1d/9/9/9/D1FWDWF1D/1S2N2S1/3GMI3 J2N2R2D1/j2n2r2d1 w 0 - 1';\nexport const BEGINNER_POSITION =\n\t'3img3/1ra1n1as1/d1fwdwf1d/9/9/9/D1FWDWF1D/1SA1N1AR1/3GMI3 J2N2S1R1D1/j2n2s1r1d1 w 1 - 1';\nexport const INTERMEDIATE_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 2 wb 1';\nexport const ADVANCED_POSITION =\n\t'9/9/9/9/9/9/9/9/9 M1G1I1J2W2N3R2S2F2D4C1A2K1T1/m1g1i1j2w2n3r2s2f2d4c1a2k1t1 w 3 wb 1';\n\nexport type ParsedFEN = {\n\tboard: Board;\n\thand: HandPiece[];\n\tturn: Color;\n\tmode: SetupMode;\n\tdrafting: Record<Color, boolean>;\n\tmoveNumber: number;\n};\n\nexport function parseFEN(fen: string): ParsedFEN {\n\tconst result = validateFen(fen);\n\tif (!result.ok) throw new Error(`Invalid FEN: ${result.error}`);\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] =\n\t\tfen.split(' ');\n\n\tconst board = placement.split('/').map((rank, y) => {\n\t\treturn rank.split('|').reduce(\n\t\t\t(outeracc, partial) => {\n\t\t\t\tif (partial.includes(':')) {\n\t\t\t\t\tconst tower = partial.split(':').map((piece, z) => {\n\t\t\t\t\t\treturn createPieceFromFenCode(\n\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length, z + 1]\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t\touteracc.push(tower);\n\t\t\t\t} else {\n\t\t\t\t\tconst partialPieces = partial\n\t\t\t\t\t\t.split('')\n\t\t\t\t\t\t.reduce(\n\t\t\t\t\t\t\t(acc, piece) => {\n\t\t\t\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\t\t\t\tacc = acc.concat(Array(+piece).fill(null));\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tacc.push(\n\t\t\t\t\t\t\t\t\t\tcreatePieceFromFenCode(\n\t\t\t\t\t\t\t\t\t\t\tpiece as PieceCode | Uppercase<PieceCode>,\n\t\t\t\t\t\t\t\t\t\t\t[y + 1, 9 - outeracc.length - acc.length, 1]\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t[] as (Piece | null)[]\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.map((square) => [square]);\n\t\t\t\t\touteracc = outeracc.concat(partialPieces);\n\t\t\t\t}\n\n\t\t\t\treturn outeracc;\n\t\t\t},\n\t\t\t[] as (Piece | null)[][]\n\t\t);\n\t});\n\n\tconst hand = handpieces.split('/').flatMap((playerHand) => {\n\t\tconst pieces: HandPiece[] = [];\n\t\tif (playerHand !== '-') {\n\t\t\tfor (let i = 0; i < playerHand.length; i += 2) {\n\t\t\t\tconst piece = playerHand[i] as PieceCode | Uppercase<PieceCode>;\n\t\t\t\tconst count = +playerHand[i + 1];\n\t\t\t\tpieces.push(createHandPieceFromFenCode(piece, count));\n\t\t\t}\n\t\t}\n\t\treturn pieces;\n\t});\n\n\treturn {\n\t\tboard,\n\t\thand,\n\t\tturn: turn as Color,\n\t\tmode: setupCodeToMode[+mode],\n\t\tdrafting: {\n\t\t\tw: drafting.includes('w'),\n\t\t\tb: drafting.includes('b'),\n\t\t},\n\t\tmoveNumber: +moveNumber,\n\t};\n}\n\nexport function encodeFEN(fen: ParsedFEN) {\n\tlet placement = '';\n\tlet emptyCount = 0;\n\n\tfor (let file = 0; file < 9; file++) {\n\t\tfor (let rank = 0; rank < 9; rank++) {\n\t\t\tconst square = fen.board[file][rank];\n\t\t\tif (square[0] === null) {\n\t\t\t\temptyCount++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (emptyCount) {\n\t\t\t\tplacement += emptyCount;\n\t\t\t\temptyCount = 0;\n\t\t\t}\n\n\t\t\tif (square.length > 1) {\n\t\t\t\tplacement +=\n\t\t\t\t\t'|' +\n\t\t\t\t\tsquare\n\t\t\t\t\t\t.map((p) => {\n\t\t\t\t\t\t\tif (!p) return null;\n\t\t\t\t\t\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\t\t\t\t\t\treturn p.color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(':') +\n\t\t\t\t\t'|';\n\t\t\t} else {\n\t\t\t\tconst { type, color } = square[0];\n\t\t\t\tconst piece = pieceToFenCode[symbolToName[type]];\n\t\t\t\tplacement += color === 'w' ? piece.toUpperCase() : piece;\n\t\t\t}\n\t\t}\n\n\t\tplacement += emptyCount ? `${emptyCount}/` : '/';\n\t\temptyCount = 0;\n\t}\n\n\tlet hand = '';\n\tconst whiteHand = fen.hand.filter((p) => p.color === 'w');\n\tconst blackHand = fen.hand.filter((p) => p.color === 'b');\n\twhiteHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += whiteHand.length > 0 ? '/' : '-/';\n\tblackHand.forEach((p) => {\n\t\tconst piece = pieceToFenCode[symbolToName[p.type]];\n\t\thand += `${p.color === 'w' ? piece.toUpperCase() : piece}${p.count}`;\n\t});\n\thand += blackHand.length > 0 ? '' : '-';\n\n\tconst draftKeys = Object.keys(fen.drafting).filter(\n\t\t(key) => fen.drafting[key as Color]\n\t);\n\n\treturn `${placement.slice(0, -1)} ${hand} ${fen.turn} ${setupModeToCode[fen.mode]} ${draftKeys.length > 0 ? draftKeys.join('') : '-'} ${fen.moveNumber}`;\n}\n\ntype FenValidationResult = {\n\tok: boolean;\n\terror?: string;\n};\n\nexport function validateFen(fen: string): FenValidationResult {\n\tconst parts = fen.split(' ');\n\tif (parts.length !== 6)\n\t\treturn { ok: false, error: `expected 6 fields, received ${parts.length}` };\n\n\tconst [placement, handpieces, turn, mode, drafting, moveNumber] = parts;\n\tconst ranks = placement.split('/');\n\tif (ranks.length !== 9)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `1st field (piece positions) is invalid [expected 9 ranks, received ${ranks.length}]`,\n\t\t};\n\n\tfor (let i = 0; i < ranks.length; i++) {\n\t\tconst rank = ranks[i];\n\t\tconst fileParts = rank.split('|');\n\t\tlet fileCount = 0;\n\n\t\tfor (let k = 0; k < fileParts.length; k++) {\n\t\t\tconst filePart = fileParts[k];\n\t\t\tif (filePart.includes(':')) {\n\t\t\t\tfileCount++;\n\t\t\t\tconst towerPieces = filePart.split(':');\n\t\t\t\tif (towerPieces.length > 3) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [tower size] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!towerPieces.every((p) => 'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(p))\n\t\t\t\t) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst pieces = filePart.split('');\n\n\t\t\t\tfor (let l = 0; l < pieces.length; l++) {\n\t\t\t\t\tconst piece = pieces[l];\n\n\t\t\t\t\tif (Number.isInteger(+piece)) {\n\t\t\t\t\t\tfileCount += +piece;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfileCount++;\n\t\t\t\t\t\tif (!'mgijwnrsfdcaktMGIJWNRSFDCAKT'.includes(piece)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\t\terror: `1st field (piece positions) is invalid [invalid piece] @(${i + 1}-${fileCount})`,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (fileCount !== 9) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `1st field (piece positions) is invalid [expected 9 squares, received ${fileCount}] in rank: ${i + 1}`,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst hands = handpieces.split('/');\n\tif (hands.length !== 2)\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [expected 2 hands, received ${hands.length}]`,\n\t\t};\n\n\tconst [whiteHand, blackHand] = hands;\n\tif (\n\t\t(whiteHand.length === 1 && whiteHand !== '-') ||\n\t\t(blackHand.length === 1 && blackHand !== '-')\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t};\n\t}\n\n\tif (\n\t\t(whiteHand.length > 1 && whiteHand.length % 2 !== 0) ||\n\t\t(blackHand.length > 1 && blackHand.length % 2 !== 0)\n\t) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece count]`,\n\t\t};\n\t}\n\n\tif (whiteHand.length > 1) {\n\t\tfor (let i = 0; i < whiteHand.length; i += 2) {\n\t\t\tif (!'MGIJWNRSFDCAKT'.includes(whiteHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+whiteHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (blackHand.length > 1) {\n\t\tfor (let i = 0; i < blackHand.length; i += 2) {\n\t\t\tif (!'mgijwnrsfdcakt'.includes(blackHand[i])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid piece]`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (!Number.isInteger(+blackHand[i + 1])) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `2nd field (hand pieces) is invalid [invalid count]`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (turn !== 'w' && turn !== 'b') {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `3rd field (active player) is invalid [expected 'w' or 'b', received ${turn}]`,\n\t\t};\n\t}\n\n\tif (mode.length !== 1 || !'0123'.includes(mode)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `4th field (setup mode) is invalid [expected '0', '1', '2', or '3', received ${mode}]`,\n\t\t};\n\t}\n\n\tif (drafting !== '-' && !'wb'.includes(drafting)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `5th field (drafting availability) is invalid [expected '-', 'w', 'b', or 'wb', received ${drafting}]`,\n\t\t};\n\t}\n\n\tif (!Number.isInteger(+moveNumber)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `6th field (full move number) is invalid [expected an integer, received ${moveNumber}]`,\n\t\t};\n\t}\n\n\treturn { ok: true };\n}\n","import { encodeFEN, parseFEN } from './fen';\nimport {\n\tconvert,\n\tget,\n\tgetTop,\n\tHandPiece,\n\tMove,\n\tPiece,\n\tPieceType,\n\tpiece as pieceType,\n\tput,\n\tremove,\n\tremoveTop,\n\tupdateHand,\n} from './utils';\n\nexport const dirs = [\n\t[-1, 1],\n\t[-1, 0],\n\t[-1, -1],\n\t[0, 1],\n\t[0, -1],\n\t[1, 1],\n\t[1, 0],\n\t[1, -1],\n];\n\nexport const pieceProbes: Record<PieceType, (number[] | number)[]> = {\n\t帥: [1, 1, 1, 1, 1, 1, 1, 1],\n\t大: [1, Infinity, 1, Infinity, Infinity, 1, Infinity, 1],\n\t中: [Infinity, 1, Infinity, 1, 1, Infinity, 1, Infinity],\n\t小: [1, 1, 1, 1, 1, 0, 1, 0],\n\t侍: [1, 1, 1, 0, 0, 0, 1, 0],\n\t槍: [1, [1, 2], 1, 0, 0, 0, 1, 0],\n\t馬: [0, [1, 2], 0, 1, 1, 0, [1, 2], 0],\n\t忍: [[1, 2], 0, [1, 2], 0, 0, [1, 2], 0, [1, 2]],\n\t砦: [0, 1, 0, 1, 1, 1, 0, 1],\n\t兵: [0, 1, 0, 0, 0, 0, 1, 0],\n\t砲: [0, 3, 0, 1, 1, 0, 1, 0],\n\t弓: [2, 2, 2, 0, 0, 0, 1, 0],\n\t筒: [0, 2, 0, 0, 0, 1, 0, 1],\n\t謀: [1, 0, 1, 0, 0, 0, 1, 0],\n};\n\nfunction getAvailableSquares(\n\tdir: [number, number],\n\tstart: [number, number],\n\torigin: [number, number],\n\tlength: number,\n\tboard: (Piece | null)[][][]\n) {\n\tconst [y, x] = start;\n\tconst [py, px] = origin;\n\tconst [dy, dx] = dir;\n\tconst originPiece = getTop(`${py}-${px}`, board)!;\n\n\tconst availableSquares: string[] = [];\n\n\t// first probe in the reverse direction until origin is reached to see if there are any pieces in the way\n\tconst reverse = { x, y };\n\twhile (reverse.x !== px || reverse.y !== py) {\n\t\treverse.x -= dx;\n\t\treverse.y -= dy;\n\t\tconst piece = getTop(`${reverse.y}-${reverse.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst side = originPiece.color === 'b' ? -1 : 1;\n\t\tconst below = getTop(`${reverse.y + side}-${reverse.x}`, board);\n\n\t\tif (below && below.square === `${py}-${px}`) break;\n\t}\n\n\t// then probe in the forward direction to see if there are any pieces in the way\n\tconst forward = { x, y };\n\tlet step = 0;\n\twhile (step < length) {\n\t\tif (forward.x < 1 || forward.x > 9 || forward.y < 1 || forward.y > 9) break;\n\n\t\tconst piece = getTop(`${forward.y}-${forward.x}`, board);\n\t\tif (piece && piece.tier > originPiece.tier) break;\n\n\t\tavailableSquares.push(`${forward.y}-${forward.x}`);\n\n\t\tconst leapPieces = [\n\t\t\tpieceType.cannon,\n\t\t\tpieceType.musketeer,\n\t\t\tpieceType.archer,\n\t\t];\n\t\tif (piece && !leapPieces.includes(originPiece.type)) break;\n\n\t\tforward.x += dx;\n\t\tforward.y += dy;\n\t\tstep++;\n\t}\n\n\treturn availableSquares;\n}\n\nexport function generateMovesForSquare(square: string, fen: string) {\n\tconst { board, turn, mode, hand } = parseFEN(fen);\n\tconst piece = getTop(square, board);\n\tif (!piece || turn !== piece.color) return [];\n\n\tconst [py, px] = square.split('-').map(Number);\n\n\tconst probes = pieceProbes[piece.type];\n\tconst squares = probes.flatMap((probe, i) => {\n\t\tconst pval = typeof probe === 'number' ? probe : probe[0];\n\t\tconst pcarry = typeof probe === 'number' ? 1 : probe[1];\n\t\tif (pval < 1) return [];\n\n\t\tlet [dy, dx] = dirs[i];\n\t\tif (piece.color === 'b') {\n\t\t\tdy *= -1;\n\t\t\tdx *= -1;\n\t\t}\n\n\t\tconst [y, x] =\n\t\t\tpval === Infinity ? [py + dy, px + dx] : [py + pval * dy, px + dx];\n\t\tconst length = pval === Infinity ? Infinity : piece.tier + pcarry - 1;\n\n\t\treturn getAvailableSquares([dy, dx], [y, x], [py, px], length, board);\n\t});\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst t = get(s, board);\n\n\t\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\t\tconst marshalCanStack = ['advanced', 'intermediate'].includes(mode);\n\n\t\tif (!p || !t) {\n\t\t\tacc.push(createMove(piece, `${s}-1`, fen, 'route'));\n\t\t} else {\n\t\t\t// tsuke\n\t\t\tif (p.tier < maxTier && p.type !== pieceType.marshal) {\n\t\t\t\tif (piece.type !== pieceType.marshal || marshalCanStack) {\n\t\t\t\t\tacc.push(createMove(piece, `${s}-${p.tier + 1}`, fen, 'tsuke'));\n\t\t\t\t}\n\n\t\t\t\t// betrayal\n\t\t\t\tif (piece.type === pieceType.tactician && p.color !== piece.color) {\n\t\t\t\t\tconst enemies = t.filter((p) => p.color !== piece.color);\n\t\t\t\t\tconst playerHand = hand.filter((p) => p.color === piece.color);\n\t\t\t\t\tconst enemyCountMap = enemies.reduce((acc, e) => {\n\t\t\t\t\t\tacc.set(e.type, (acc.get(e.type) ?? 0) + 1);\n\t\t\t\t\t\treturn acc;\n\t\t\t\t\t}, new Map<PieceType, number>());\n\n\t\t\t\t\tconst betrayalOptions = Array.from(enemyCountMap.entries())\n\t\t\t\t\t\t.filter(([type, count]) =>\n\t\t\t\t\t\t\tplayerHand.some((p) => p.type === type && p.count >= count)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.flatMap(([type]) => enemies.filter((e) => e.type === type));\n\n\t\t\t\t\tconst combos = generateCombinations(betrayalOptions);\n\t\t\t\t\tacc.push(\n\t\t\t\t\t\t...combos.map((combo) =>\n\t\t\t\t\t\t\tcreateMove(piece, `${s}-${p.tier + 1}`, fen, 'betray', combo)\n\t\t\t\t\t\t)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// capture\n\t\t\tif (p.color !== piece.color) {\n\t\t\t\tconst newTier = t.filter((p) => p.color === piece.color).length + 1;\n\t\t\t\tconst captured = t.filter((p) => p.color !== piece.color);\n\t\t\t\tacc.push(\n\t\t\t\t\tcreateMove(piece, `${s}-${newTier}`, fen, 'capture', captured)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nexport function generateArata(piece: HandPiece, fen: string) {\n\tconst { board, turn, mode, hand, drafting } = parseFEN(fen);\n\tif (!piece || turn !== piece.color) return [];\n\tconst isMarshalPlaced = !hand.some(\n\t\t(p) => p.type === pieceType.marshal && p.color === piece.color\n\t);\n\tif (!isMarshalPlaced && piece.type !== pieceType.marshal) return [];\n\n\tconst isDraft = drafting.b || drafting.w;\n\tconst maxTier = mode === 'advanced' ? 3 : 2;\n\tlet ranks: number[] = [];\n\tlet maybe: number[] = [];\n\n\t// if in draft can only place within your first 3 ranks, otherwise can placed as far as your deepest piece\n\tif (isDraft) {\n\t\tranks = piece.color === 'w' ? [7, 8, 9] : [1, 2, 3];\n\t} else {\n\t\tconst start = piece.color === 'b' ? 1 : 9;\n\t\tconst end = piece.color === 'b' ? 9 : 1;\n\t\tconst step = piece.color === 'b' ? 1 : -1;\n\t\tfor (\n\t\t\tlet rank = start;\n\t\t\tpiece.color === 'b' ? rank <= end : rank >= end;\n\t\t\trank += step\n\t\t) {\n\t\t\tconst tops = Array.from({ length: 9 }).map((_, i) =>\n\t\t\t\tgetTop(`${rank}-${i + 1}`, board)\n\t\t\t);\n\t\t\tif (tops.some((p) => p && p.color === piece.color)) {\n\t\t\t\tranks.push(...maybe, rank);\n\t\t\t\tmaybe = [];\n\t\t\t} else {\n\t\t\t\tmaybe.push(rank);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst squares = ranks.flatMap((rank) =>\n\t\tArray.from({ length: 9 }, (_, i) => `${rank}-${i + 1}`)\n\t);\n\n\treturn squares.reduce((acc, s) => {\n\t\tconst p = getTop(s, board);\n\t\tconst arata = {\n\t\t\ttype: piece.type,\n\t\t\tcolor: piece.color,\n\t\t\tsquare: s,\n\t\t\ttier: 0,\n\t\t};\n\n\t\t// you can arata an empty square or a tower with your own piece on top\n\t\tif (\n\t\t\t!p ||\n\t\t\t(p.color === arata.color &&\n\t\t\t\tp.tier < maxTier &&\n\t\t\t\tp.type !== pieceType.marshal)\n\t\t) {\n\t\t\tconst t = (p?.tier ?? 0) + 1;\n\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata'));\n\t\t\tif (drafting[piece.color]) {\n\t\t\t\tacc.push(createMove(arata, `${s}-${t}`, fen, 'arata', [], true));\n\t\t\t}\n\t\t}\n\n\t\treturn acc;\n\t}, [] as Move[]);\n}\n\nfunction createMove(\n\tpiece: Piece,\n\tto: string,\n\tfen: string,\n\ttype: Move['type'],\n\tcaptured?: Piece[],\n\tdraftFinished?: boolean\n) {\n\tconst from = piece.tier !== 0 ? `(${piece.square}-${piece.tier})` : '';\n\tconst toTier = +(to.split('-').at(-1) ?? 0);\n\tconst arata = type === 'arata' ? '新' : '';\n\tconst capture = type === 'capture' ? '取' : '';\n\tconst tsuke =\n\t\ttype === 'tsuke' || (toTier !== 1 && toTier - piece.tier > 0) ? '付' : '';\n\tconst betray =\n\t\ttype === 'betray' ? `返${captured?.map((p) => p.type).join('')}` : '';\n\tconst draftDone = draftFinished ? '終' : '';\n\n\tconst move: Move = {\n\t\tpiece: piece.type,\n\t\tcolor: piece.color,\n\t\tfrom: from.slice(1, -1),\n\t\tto,\n\t\ttype,\n\t\tsan: `${arata}${piece.type}${from}${capture}(${to})${betray || tsuke}${draftDone}`,\n\t\tbefore: fen,\n\t\tafter: '',\n\t\tdraftFinished,\n\t\tcaptured,\n\t};\n\n\tconst { after, gameOverSAN } = makeMove(move, move.before);\n\tmove.after = after;\n\tmove.san += gameOverSAN;\n\n\treturn move;\n}\n\nfunction makeMove(move: Move, fen: string) {\n\tlet { board, hand, mode, turn, drafting, moveNumber } = parseFEN(fen);\n\tconst [rank, file, tier] = move.to.split('-');\n\tconst to = {\n\t\ttype: move.piece,\n\t\tcolor: move.color,\n\t\tsquare: `${rank}-${file}`,\n\t\ttier: +tier,\n\t};\n\n\tif (move.type === 'route' || move.type === 'tsuke') {\n\t\tremoveTop(move.from!, board);\n\t} else if (move.type === 'capture') {\n\t\tremoveTop(move.from!, board);\n\t\tremove(`${rank}-${file}`, move.captured!, board);\n\t} else if (move.type === 'betray') {\n\t\tremoveTop(move.from!, board);\n\t\tconvert(`${rank}-${file}`, move.captured!, board);\n\t\tupdateHand(move.captured!, hand, true);\n\t} else if (move.type === 'arata') {\n\t\tupdateHand([to], hand);\n\t\tif (move.draftFinished) drafting[move.color] = false;\n\t}\n\n\tput(to, board);\n\n\tif (turn === 'b' && (drafting.w || !drafting.b)) moveNumber++;\n\tif (turn === 'w' && !drafting.b && !drafting.w && move.draftFinished)\n\t\tmoveNumber++;\n\n\tif (drafting.w === drafting.b) {\n\t\tif (!move.draftFinished || turn !== 'w') {\n\t\t\tturn = turn === 'b' ? 'w' : 'b';\n\t\t}\n\t} else {\n\t\tif (!drafting.b && turn === 'b') {\n\t\t\tturn = 'w';\n\t\t} else if (!drafting.w && turn === 'w') {\n\t\t\tturn = 'b';\n\t\t}\n\t}\n\n\tlet gameOverSAN = '';\n\tif (move.captured?.some((p) => p.type === pieceType.marshal))\n\t\tgameOverSAN = '勝';\n\n\treturn {\n\t\tafter: encodeFEN({ board, hand, mode, turn, drafting, moveNumber }),\n\t\tgameOverSAN,\n\t};\n}\n\nfunction generateCombinations<T>(items: T[]): T[][] {\n\tconst result: T[][] = [];\n\n\tfunction helper(start: number, currentCombination: T[]) {\n\t\tif (currentCombination.length > 0) {\n\t\t\tresult.push([...currentCombination]);\n\t\t}\n\n\t\tfor (let i = start; i < items.length; i++) {\n\t\t\tcurrentCombination.push(items[i]);\n\t\t\thelper(i + 1, currentCombination);\n\t\t\tcurrentCombination.pop(); // Backtrack\n\t\t}\n\t}\n\n\thelper(0, []);\n\n\treturn result;\n}\n","// Portable Game Notation (PGN) parser and serializer for Gungi games.\n// Read more about PGN for chess: https://en.wikipedia.org/wiki/Portable_Game_Notation\n//\n// Movetext\n// The movetext describes the actual moves of the game. This includes move number indicators (numbers followed by either one or three periods;\n// one if the next move is White's move, three if the next move is Black's move) and movetext in Standard Algebraic Notation (SAN).\n//\n// For most moves the SAN consists of the kanji for the piece, the coordinate tuple of the square the piece moved from, an 取 if there is a capture, and the tuple of the final square it moved to.\n// The kanji are 帥 (marshal), 大 (general), 中 (lieutenant general), 小 (major general), 侍 (warrior), 槍 (lancer), 馬 (rider), 忍 (spy), 砦 (fortress), 兵 (soldier),\n// 砲 (cannon), 弓 (archer), 筒 (musketeer), and 謀 (tactician).\n//\n// The algebraic name of any square is a little different from algebraic chess notation; from white's perspective,\n// the rightmost square farthest from white is (1-1-1), the leftmost square farthest from the white is (9-1-1), and the leftmost (from white's perspective) square closest to white's side is (9-9-1).\n// the coordinates are given in the from (rank-file-tier) where tier can be (1, 2, or 3) depending on the height of the tower. If performing a stack ツケ (tsuke) then 付 is appended.\n// Thus 中(4-9-1)(5-8-2)付 denotes the major general stacking on a piece, and if we wanted to take the piece instead, we would write 中(4-9-1)取(5-8-1).\n//\n// Omitting the from square and prepending 新 to the piece indicates arata - a new piece is being placed on the board (e.g. 新小(8-7-1)) . In non-beginner games,\n// all the first moves are of this form until both players say they are finished placing pieces;\n// If a player is finished, after they place their final piece in their setup, 終 is appended (e.g. 新兵(4-2-1)終).\n//\n// If the tactician performs a ツケ (tsuke), they have the option to convert some or all of the enemy pieces in the tower.\n// (only if they have the piece in their hand they capture the enemy piece and replaces it with their own); this is denoted by a '返'\n// after the last coordinate followed by the piece(s) they are converting (in no particular order). Thus 謀(4-9-2)(5-8-3)返中槍 denotes\n// the tactician converting a major general and a lancer in a tower.\n//\n// If the move captures the enemy marshal, \"勝\" is appended and the game is over.\n// If the move is a fourfold repetition, \"停\" is appended and the game is a draw.\n\nimport { parseFEN } from './fen';\nimport { Move } from './utils';\n\nexport type PGNOptions = {\n\tmaxWidth?: number;\n\tnewline?: string;\n};\n\nexport function encodePGN(history: Move[], opts?: PGNOptions) {\n\tconst maxWidth = opts?.maxWidth ?? 6;\n\tconst newline = opts?.newline ?? '\\n';\n\n\tlet pgn = '';\n\tlet prev = 0;\n\thistory.forEach((move, i) => {\n\t\tconst state = parseFEN(move.before);\n\t\tif (state.moveNumber !== prev) {\n\t\t\tconst indicator = move.color === 'w' ? '.' : '...';\n\t\t\tpgn += `${state.moveNumber}${indicator} `;\n\t\t\tprev = state.moveNumber;\n\t\t}\n\n\t\tpgn += `${move.san} `;\n\n\t\tif ((i + 1) % maxWidth === 0) {\n\t\t\tpgn += newline;\n\t\t}\n\t});\n\n\treturn pgn.replaceAll(' ', ' ').trim();\n}\n\nexport function parsePGN(pgn: string, opts?: Pick<PGNOptions, 'newline'>) {\n\tconst newline = opts?.newline ?? '\\n';\n\tconst moves = pgn\n\t\t.split(newline)\n\t\t.flatMap((line) => {\n\t\t\treturn line.replace(/\\d+\\.+/g, '').split(' ');\n\t\t})\n\t\t.filter((move) => move !== '');\n\n\treturn moves;\n}\n","import { encodeFEN, ParsedFEN, parseFEN } from './fen';\nimport { Board, Color, HandPiece, Piece, PieceType } from './utils';\n\nexport type PieceInventory = {\n\t[key: string]: {\n\t\tboardPieces: Piece[];\n\t\thandPieces: HandPiece[];\n\t};\n};\n\nexport type MoveChange = {\n\tisSingleMove: boolean;\n\tmovedPiece?: {\n\t\tfromSquare?: string;\n\t\ttoSquare: string;\n\t\tpiece: Piece;\n\t\tisArata: boolean;\n\t\tisCapture: boolean;\n\t};\n\tcapturedPieces?: Piece[];\n};\n\n/**\n * Main entry point for assigning piece IDs\n * Uses canonical assignment for base case, move-aware assignment for stability\n */\nexport function assignPieceIds(\n\tcurrentFen: string,\n\tpreviousFen?: string\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousFen) {\n\t\t// Base case: pure canonical assignment\n\t\treturn assignCanonically(currentState);\n\t}\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID\n\t\t// IMPORTANT: Parse previous FEN directly, don't recurse to avoid corruption\n\t\tconst previousState = parseFEN(previousFen);\n\t\treturn preserveMovingPieceId(currentState, previousState, changes);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\treturn assignCanonically(currentState);\n\t}\n}\n\n/**\n * Main entry point for assigning piece IDs with previous state\n * Uses previous parsed state with IDs for better stability\n */\nexport function assignPieceIdsWithState(\n\tcurrentFen: string,\n\tpreviousState?: ParsedFEN | null\n): ParsedFEN {\n\tconst currentState = parseFEN(currentFen);\n\n\tif (!previousState) {\n\t\t// Base case: pure canonical assignment\n\t\treturn assignCanonically(currentState);\n\t}\n\n\t// Get the previous FEN to detect changes\n\tconst previousFen = encodeFEN({\n\t\tboard: previousState.board,\n\t\thand: previousState.hand,\n\t\tturn: previousState.turn,\n\t\tmoveNumber: previousState.moveNumber,\n\t\tdrafting: previousState.drafting,\n\t\tmode: previousState.mode,\n\t});\n\n\t// Detect what changed between the FENs\n\tconst changes = detectMoveBetween(previousFen, currentFen);\n\n\tif (changes.isSingleMove && changes.movedPiece) {\n\t\t// Preserve the moving piece's ID using the state with IDs\n\t\treturn preserveMovingPieceId(currentState, previousState, changes);\n\t} else {\n\t\t// Fall back to canonical for complex changes\n\t\treturn assignCanonically(currentState);\n\t}\n}\n\n/**\n * Assigns IDs based purely on canonical positioning\n * Deterministic: same game state always produces same IDs\n */\nfunction assignCanonically(state: ParsedFEN): ParsedFEN {\n\t// Clone the state to avoid mutations\n\tconst result: ParsedFEN = {\n\t\t...state,\n\t\tboard: state.board.map((rank) =>\n\t\t\trank.map((file) => file.map((piece) => (piece ? { ...piece } : piece)))\n\t\t),\n\t\thand: state.hand.map((hp) => ({ ...hp })),\n\t};\n\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(result.board, result.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// Assign sequential IDs\n\t\tallPieces.forEach((piece, index) => {\n\t\t\tpiece.id = `${color}-${pieceType}-${index + 1}`;\n\t\t});\n\t}\n\n\treturn result;\n}\n\n/**\n * Detects changes between two FEN strings\n * Returns information about what moved for stability purposes\n */\nfunction detectMoveBetween(oldFen: string, newFen: string): MoveChange {\n\tconst oldState = parseFEN(oldFen);\n\tconst newState = parseFEN(newFen);\n\n\t// Compare board states\n\tconst boardChanges = detectBoardChanges(oldState.board, newState.board);\n\tconst handChanges = detectHandChanges(oldState.hand, newState.hand);\n\n\t// Check if this looks like a single move\n\tconst totalChanges =\n\t\tboardChanges.disappeared.length + boardChanges.appeared.length;\n\tconst handPieceChanges =\n\t\tMath.abs(handChanges.whiteChange) + Math.abs(handChanges.blackChange);\n\n\t// Simple single move: one piece disappeared, one appeared, minimal hand changes\n\tif (totalChanges === 2 && handPieceChanges <= 1) {\n\t\tconst disappeared = boardChanges.disappeared[0];\n\t\tconst appeared = boardChanges.appeared[0];\n\n\t\t// Check if same piece type and color\n\t\tif (\n\t\t\tdisappeared &&\n\t\t\tappeared &&\n\t\t\tdisappeared.type === appeared.type &&\n\t\t\tdisappeared.color === appeared.color\n\t\t) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: disappeared.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for arata move (hand to board)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 0\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst handChange = handChanges.changes.find(\n\t\t\t(change) =>\n\t\t\t\tchange.type === appeared.type &&\n\t\t\t\tchange.color === appeared.color &&\n\t\t\t\tchange.countDiff < 0\n\t\t);\n\n\t\tif (handChange) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: true,\n\t\t\t\t\tisCapture: false,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t}\n\n\t// Check for capture move (one piece moved, one disappeared)\n\tif (\n\t\tboardChanges.appeared.length === 1 &&\n\t\tboardChanges.disappeared.length === 2\n\t) {\n\t\tconst appeared = boardChanges.appeared[0];\n\t\tconst possibleMover = boardChanges.disappeared.find(\n\t\t\t(p) => p.type === appeared.type && p.color === appeared.color\n\t\t);\n\t\tconst possibleCaptured = boardChanges.disappeared.find(\n\t\t\t(p) => p.type !== appeared.type || p.color !== appeared.color\n\t\t);\n\n\t\tif (possibleMover && possibleCaptured) {\n\t\t\treturn {\n\t\t\t\tisSingleMove: true,\n\t\t\t\tmovedPiece: {\n\t\t\t\t\tfromSquare: possibleMover.square,\n\t\t\t\t\ttoSquare: appeared.square,\n\t\t\t\t\tpiece: appeared,\n\t\t\t\t\tisArata: false,\n\t\t\t\t\tisCapture: true,\n\t\t\t\t},\n\t\t\t\tcapturedPieces: [possibleCaptured],\n\t\t\t};\n\t\t}\n\t}\n\n\treturn { isSingleMove: false };\n}\n\n/**\n * Compare board states to find what pieces appeared/disappeared\n */\nfunction detectBoardChanges(oldBoard: Board, newBoard: Board) {\n\tconst disappeared: Piece[] = [];\n\tconst appeared: Piece[] = [];\n\n\t// Create maps of pieces by position for easy comparison\n\tconst oldPieces = new Map<string, Piece[]>();\n\tconst newPieces = new Map<string, Piece[]>();\n\n\t// Build old pieces map\n\tfor (const rank of oldBoard) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece) {\n\t\t\t\t\tif (!oldPieces.has(piece.square)) {\n\t\t\t\t\t\toldPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\toldPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Build new pieces map\n\tfor (const rank of newBoard) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece) {\n\t\t\t\t\tif (!newPieces.has(piece.square)) {\n\t\t\t\t\t\tnewPieces.set(piece.square, []);\n\t\t\t\t\t}\n\t\t\t\t\tnewPieces.get(piece.square)!.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find disappeared pieces\n\tfor (const [square, pieces] of oldPieces) {\n\t\tconst newSquarePieces = newPieces.get(square) || [];\n\t\tfor (const oldPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) still exists at this position\n\t\t\tconst stillExists = newSquarePieces.some(\n\t\t\t\t(newPiece) =>\n\t\t\t\t\tnewPiece.type === oldPiece.type &&\n\t\t\t\t\tnewPiece.color === oldPiece.color &&\n\t\t\t\t\tnewPiece.tier === oldPiece.tier\n\t\t\t);\n\t\t\tif (!stillExists) {\n\t\t\t\tdisappeared.push(oldPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Find appeared pieces\n\tfor (const [square, pieces] of newPieces) {\n\t\tconst oldSquarePieces = oldPieces.get(square) || [];\n\t\tfor (const newPiece of pieces) {\n\t\t\t// Check if this exact piece (type, color, tier) was already at this position\n\t\t\tconst wasAlreadyThere = oldSquarePieces.some(\n\t\t\t\t(oldPiece) =>\n\t\t\t\t\toldPiece.type === newPiece.type &&\n\t\t\t\t\toldPiece.color === newPiece.color &&\n\t\t\t\t\toldPiece.tier === newPiece.tier\n\t\t\t);\n\t\t\tif (!wasAlreadyThere) {\n\t\t\t\tappeared.push(newPiece);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { disappeared, appeared };\n}\n\n/**\n * Compare hand states to find what changed\n */\nfunction detectHandChanges(oldHand: HandPiece[], newHand: HandPiece[]) {\n\tconst oldMap = new Map<string, number>();\n\tconst newMap = new Map<string, number>();\n\n\t// Build maps of piece counts\n\tfor (const hp of oldHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\toldMap.set(key, hp.count);\n\t}\n\n\tfor (const hp of newHand) {\n\t\tconst key = `${hp.color}-${hp.type}`;\n\t\tnewMap.set(key, hp.count);\n\t}\n\n\t// Calculate changes\n\tconst changes: Array<{ type: PieceType; color: Color; countDiff: number }> =\n\t\t[];\n\tlet whiteChange = 0;\n\tlet blackChange = 0;\n\n\t// Find all unique keys\n\tconst allKeys = new Set([...oldMap.keys(), ...newMap.keys()]);\n\n\tfor (const key of allKeys) {\n\t\tconst oldCount = oldMap.get(key) || 0;\n\t\tconst newCount = newMap.get(key) || 0;\n\t\tconst diff = newCount - oldCount;\n\n\t\tif (diff !== 0) {\n\t\t\tconst [color, type] = key.split('-') as [Color, PieceType];\n\t\t\tchanges.push({ type, color, countDiff: diff });\n\n\t\t\tif (color === 'w') {\n\t\t\t\twhiteChange += Math.abs(diff);\n\t\t\t} else {\n\t\t\t\tblackChange += Math.abs(diff);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { changes, whiteChange, blackChange };\n}\n\n/**\n * Preserves the moving piece's ID when a single move is detected\n */\nfunction preserveMovingPieceId(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): ParsedFEN {\n\t// Clone the current state without any IDs initially\n\tconst result: ParsedFEN = {\n\t\t...currentState,\n\t\tboard: currentState.board.map((rank) =>\n\t\t\trank.map((file) =>\n\t\t\t\tfile.map((piece) => (piece ? { ...piece, id: undefined } : piece))\n\t\t\t)\n\t\t),\n\t\thand: currentState.hand.map((hp) => ({ ...hp, id: undefined })),\n\t};\n\n\tif (!changes.movedPiece) return result;\n\n\t// First, preserve ALL non-moving pieces by copying their IDs from previous state\n\tpreserveAllNonMovingPieceIds(result, previousState, changes);\n\n\t// Then apply canonical assignment ONLY to pieces that don't already have IDs\n\tapplyCanonicalToMissingIds(result);\n\n\tconst { fromSquare, toSquare, piece, isArata } = changes.movedPiece;\n\n\tif (isArata) {\n\t\t// Arata move (hand to board): find the hand piece that moved and preserve its ID\n\t\tconst previousHandPiece = previousState.hand.find(\n\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t);\n\n\t\tif (previousHandPiece?.id) {\n\t\t\t// Find the new board piece at the target square and give it the hand piece's ID\n\t\t\tconst boardPiece = findPieceAtSquare(\n\t\t\t\tresult.board,\n\t\t\t\ttoSquare,\n\t\t\t\tpiece.type,\n\t\t\t\tpiece.color,\n\t\t\t\tpiece.tier\n\t\t\t);\n\t\t\tif (boardPiece) {\n\t\t\t\tboardPiece.id = previousHandPiece.id;\n\t\t\t}\n\n\t\t\t// Update the hand piece count but keep its base ID structure\n\t\t\tconst newHandPiece = result.hand.find(\n\t\t\t\t(hp) => hp.type === piece.type && hp.color === piece.color\n\t\t\t);\n\t\t\tif (newHandPiece && previousHandPiece.id) {\n\t\t\t\t// Keep the same base ID for the remaining hand pieces\n\t\t\t\tnewHandPiece.id = previousHandPiece.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular move (board to board): preserve the piece's ID\n\t\tconst previousPiece = fromSquare\n\t\t\t? findPieceAtSquare(\n\t\t\t\t\tpreviousState.board,\n\t\t\t\t\tfromSquare,\n\t\t\t\t\tpiece.type,\n\t\t\t\t\tpiece.color\n\t\t\t\t)\n\t\t\t: null;\n\n\t\tif (previousPiece?.id) {\n\t\t\t// Find the piece at the new location and assign the same ID\n\t\t\tconst newPiece = findPieceAtSquare(\n\t\t\t\tresult.board,\n\t\t\t\ttoSquare,\n\t\t\t\tpiece.type,\n\t\t\t\tpiece.color,\n\t\t\t\tpiece.tier\n\t\t\t);\n\t\t\tif (newPiece) {\n\t\t\t\tnewPiece.id = previousPiece.id;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/**\n * Find a piece at a specific square with optional type/color/tier filters\n */\nfunction findPieceAtSquare(\n\tboard: Board,\n\tsquare: string,\n\ttype?: PieceType,\n\tcolor?: Color,\n\ttier?: number\n): Piece | null {\n\tconst [rank, file] = square.split('-').map(Number);\n\tif (rank < 1 || rank > 9 || file < 1 || file > 9) return null;\n\n\tconst tower = board[rank - 1][9 - file];\n\tfor (const piece of tower) {\n\t\tif (\n\t\t\tpiece &&\n\t\t\t(!type || piece.type === type) &&\n\t\t\t(!color || piece.color === color) &&\n\t\t\t(!tier || piece.tier === tier)\n\t\t) {\n\t\t\treturn piece;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Preserve IDs for ALL pieces that didn't move using ID-based matching\n */\nfunction preserveAllNonMovingPieceIds(\n\tcurrentState: ParsedFEN,\n\tpreviousState: ParsedFEN,\n\tchanges: MoveChange\n): void {\n\tif (!changes.movedPiece) return;\n\n\tconst {\n\t\tfromSquare,\n\t\ttoSquare,\n\t\tpiece: movedPiece,\n\t\tisArata,\n\t} = changes.movedPiece;\n\n\t// For each piece type/color group, preserve IDs for non-moving pieces\n\tconst previousInventory = getPieceInventory(\n\t\tpreviousState.board,\n\t\tpreviousState.hand\n\t);\n\tconst currentInventory = getPieceInventory(\n\t\tcurrentState.board,\n\t\tcurrentState.hand\n\t);\n\n\tfor (const typeColorKey in previousInventory) {\n\t\tconst prevGroup = previousInventory[typeColorKey];\n\t\tconst currentGroup = currentInventory[typeColorKey];\n\n\t\tif (!currentGroup) continue; // No pieces of this type in current state\n\n\t\tconst [color, pieceType] = typeColorKey.split('-') as [Color, PieceType];\n\n\t\t// Check if this is the type that moved\n\t\tconst isMovedType =\n\t\t\tmovedPiece.type === pieceType && movedPiece.color === color;\n\n\t\tif (isMovedType) {\n\t\t\t// For the moved piece type, we need to carefully preserve non-moving pieces\n\t\t\tpreserveNonMovingPiecesOfType(\n\t\t\t\tcurrentGroup,\n\t\t\t\tprevGroup,\n\t\t\t\tfromSquare,\n\t\t\t\ttoSquare,\n\t\t\t\tisArata\n\t\t\t);\n\t\t} else {\n\t\t\t// For non-moved types, preserve all IDs by canonical position\n\t\t\tpreserveAllPiecesOfType(currentGroup, prevGroup);\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for all pieces of a type that didn't move at all\n */\nfunction preserveAllPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] }\n): void {\n\t// For board pieces, match by exact position and tier\n\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t(prev) =>\n\t\t\t\tprev.square === currentPiece.square && prev.tier === currentPiece.tier\n\t\t);\n\n\t\tif (prevAtSamePos?.id) {\n\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t}\n\t}\n\n\t// Match hand pieces directly (should be 1-to-1 mapping)\n\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\tconst currentHand = currentGroup.handPieces[0];\n\t\tconst prevHand = prevGroup.handPieces[0];\n\t\tif (prevHand.id) {\n\t\t\tcurrentHand.id = prevHand.id;\n\t\t}\n\t}\n}\n\n/**\n * Preserve IDs for pieces of the moved type, excluding the actual moved piece\n */\nfunction preserveNonMovingPiecesOfType(\n\tcurrentGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tprevGroup: { boardPieces: Piece[]; handPieces: HandPiece[] },\n\tfromSquare?: string,\n\ttoSquare?: string,\n\tisArata?: boolean\n): void {\n\tif (isArata) {\n\t\t// Arata move: a hand piece moved to board\n\t\t// All current board pieces except the destination should preserve their position-based IDs\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\tif (currentPiece.square === toSquare) continue; // Skip the moved piece\n\n\t\t\t// Find previous piece at same position\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces: preserve the hand piece ID structure\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Regular board move: preserve all board pieces except source and destination\n\t\tfor (const currentPiece of currentGroup.boardPieces) {\n\t\t\t// Skip the moved piece destination\n\t\t\tif (currentPiece.square === toSquare) continue;\n\n\t\t\t// Find previous piece at same position (should be same piece if it didn't move)\n\t\t\tconst prevAtSamePos = prevGroup.boardPieces.find(\n\t\t\t\t(p) => p.square === currentPiece.square && p.tier === currentPiece.tier\n\t\t\t);\n\n\t\t\tif (prevAtSamePos?.id) {\n\t\t\t\tcurrentPiece.id = prevAtSamePos.id;\n\t\t\t}\n\t\t}\n\n\t\t// Hand pieces should be unchanged for regular moves\n\t\tif (currentGroup.handPieces.length > 0 && prevGroup.handPieces.length > 0) {\n\t\t\tconst currentHand = currentGroup.handPieces[0];\n\t\t\tconst prevHand = prevGroup.handPieces[0];\n\t\t\tif (prevHand.id) {\n\t\t\t\tcurrentHand.id = prevHand.id;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Get all board and hand pieces of a specific type and color\n */\nfunction getAllPiecesOfType(state: ParsedFEN, type: PieceType, color: Color) {\n\tconst boardPieces: Piece[] = [];\n\tconst handPieces: HandPiece[] = [];\n\n\t// Collect board pieces\n\tfor (const rank of state.board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece && piece.type === type && piece.color === color) {\n\t\t\t\t\tboardPieces.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Collect hand pieces\n\tfor (const handPiece of state.hand) {\n\t\tif (handPiece.type === type && handPiece.color === color) {\n\t\t\thandPieces.push(handPiece);\n\t\t}\n\t}\n\n\treturn { boardPieces, handPieces };\n}\n\n/**\n * Groups pieces by type and color for ID assignment\n */\nfunction getPieceInventory(board: Board, hand: HandPiece[]): PieceInventory {\n\tconst inventory: PieceInventory = {};\n\n\t// Process board pieces\n\tfor (const rank of board) {\n\t\tfor (const file of rank) {\n\t\t\tfor (const piece of file) {\n\t\t\t\tif (piece) {\n\t\t\t\t\tconst key = `${piece.color}-${piece.type}`;\n\t\t\t\t\tif (!inventory[key]) {\n\t\t\t\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t\t\t\t}\n\t\t\t\t\tinventory[key].boardPieces.push(piece);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Process hand pieces\n\tfor (const handPiece of hand) {\n\t\tconst key = `${handPiece.color}-${handPiece.type}`;\n\t\tif (!inventory[key]) {\n\t\t\tinventory[key] = { boardPieces: [], handPieces: [] };\n\t\t}\n\t\tinventory[key].handPieces.push(handPiece);\n\t}\n\n\treturn inventory;\n}\n\n/**\n * Apply canonical assignment only to pieces that don't already have IDs\n */\nfunction applyCanonicalToMissingIds(state: ParsedFEN): void {\n\t// Get inventory of all pieces by type and color\n\tconst inventory = getPieceInventory(state.board, state.hand);\n\n\t// Assign IDs to each piece type/color group\n\tfor (const key in inventory) {\n\t\tconst group = inventory[key];\n\t\tconst [color, pieceType] = key.split('-') as [Color, PieceType];\n\n\t\t// Sort pieces canonically: board pieces first, then hand pieces\n\t\tconst allPieces = [\n\t\t\t...group.boardPieces.sort(comparePiecesCanonically),\n\t\t\t...group.handPieces,\n\t\t];\n\n\t\t// Only assign IDs to pieces that don't already have them\n\t\tlet nextNumber = 1;\n\t\tfor (const piece of allPieces) {\n\t\t\tif (!piece.id) {\n\t\t\t\t// Find the next available number\n\t\t\t\twhile (\n\t\t\t\t\tallPieces.some((p) => p.id === `${color}-${pieceType}-${nextNumber}`)\n\t\t\t\t) {\n\t\t\t\t\tnextNumber++;\n\t\t\t\t}\n\t\t\t\tpiece.id = `${color}-${pieceType}-${nextNumber}`;\n\t\t\t\tnextNumber++;\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Canonical comparison function for board pieces\n * Sort by: rank, file, tier (lexicographic order)\n */\nfunction comparePiecesCanonically(a: Piece, b: Piece): number {\n\tconst [aRank, aFile] = a.square.split('-').map(Number);\n\tconst [bRank, bFile] = b.square.split('-').map(Number);\n\n\t// Compare by rank first\n\tif (aRank !== bRank) return aRank - bRank;\n\n\t// Then by file\n\tif (aFile !== bFile) return aFile - bFile;\n\n\t// Finally by tier\n\treturn a.tier - b.tier;\n}\n"],"mappings":"AAAA,OAAOA,MAAQ,aCAf,IAAMC,EACLC,GAEA,OAAO,QAAQA,CAAG,EAAE,OACnB,CAACC,EAAK,CAACC,EAAKC,CAAK,KAAO,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,G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,KAAKG,GAAiB,KAAKD,EAAa,EACxC,KAAKH,GAAW,CAAC,CAClB,CAEA,MAAO,CACN,OAAO,KAAKJ,EACb,CAEA,MAAO,CACN,IAAMsD,EAAW,KAAKlD,GAAS,IAAI,EACnC,OAAIkD,GACH,KAAK9C,GAAiB8C,EAAS,MAAM,EAC9BA,GAGD,IACR,CAEA,YAAY7C,EAAa,CACxB,OAAO8C,EAAY9C,CAAG,CACvB,CACD","names":["pc","inverseMap","map","acc","key","value","setupModeToCode","setupCodeToMode","WHITE","BLACK","TSUKE","TAKE","BETRAY","ARATA","MARSHAL","GENERAL","LIEUTENANT_GENERAL","MAJOR_GENERAL","WARRIOR","LANCER","RIDER","SPY","FORTRESS","SOLDIER","CANNON","ARCHER","MUSKETEER","TACTICIAN","SQUARES","_","x","y","piece","symbolToName","pieceToFenCode","fenCodeToPiece","createPieceFromFenCode","code","z","color","name","createHandPieceFromFenCode","count","CANONICAL_NAMES","ENGLISH_NAMES","FEN_CODES","updateHand","pieces","hand","oppositeColor","p","c","hp","h","hpi","convert","square","board","rank","file","tower","get","remove","newTower","removeTop","put","getTop","s","isGameOver","INTRO_POSITION","BEGINNER_POSITION","INTERMEDIATE_POSITION","ADVANCED_POSITION","parseFEN","fen","result","validateFen","placement","handpieces","turn","mode","drafting","moveNumber","board","rank","y","outeracc","partial","tower","piece","z","createPieceFromFenCode","partialPieces","acc","square","hand","playerHand","pieces","i","count","createHandPieceFromFenCode","setupCodeToMode","encodeFEN","emptyCount","file","p","pieceToFenCode","symbolToName","type","color","whiteHand","blackHand","draftKeys","key","setupModeToCode","parts","ranks","fileParts","fileCount","k","filePart","towerPieces","l","hands","dirs","pieceProbes","getAvailableSquares","dir","start","origin","length","board","y","x","py","px","dy","dx","originPiece","getTop","availableSquares","reverse","piece","side","below","forward","step","leapPieces","generateMovesForSquare","square","fen","turn","mode","hand","parseFEN","probe","i","pval","pcarry","acc","s","p","t","get","maxTier","marshalCanStack","createMove","enemies","playerHand","enemyCountMap","e","betrayalOptions","type","count","combos","generateCombinations","combo","newTier","captured","generateArata","drafting","isDraft","ranks","maybe","end","rank","_","arata","to","draftFinished","from","toTier","capture","tsuke","betray","draftDone","move","after","gameOverSAN","makeMove","moveNumber","file","tier","removeTop","remove","convert","updateHand","put","encodeFEN","items","result","helper","currentCombination","encodePGN","history","opts","maxWidth","newline","pgn","prev","move","i","state","parseFEN","indicator","parsePGN","line","assignPieceIdsWithState","currentFen","previousState","currentState","parseFEN","assignCanonically","previousFen","encodeFEN","changes","detectMoveBetween","preserveMovingPieceId","state","result","rank","file","piece","hp","inventory","getPieceInventory","key","group","color","pieceType","comparePiecesCanonically","index","oldFen","newFen","oldState","newState","boardChanges","detectBoardChanges","handChanges","detectHandChanges","totalChanges","handPieceChanges","disappeared","appeared","change","possibleMover","p","possibleCaptured","oldBoard","newBoard","oldPieces","newPieces","square","pieces","newSquarePieces","oldPiece","newPiece","oldSquarePieces","oldHand","newHand","oldMap","newMap","whiteChange","blackChange","allKeys","oldCount","diff","type","preserveAllNonMovingPieceIds","applyCanonicalToMissingIds","fromSquare","toSquare","isArata","previousHandPiece","boardPiece","findPieceAtSquare","newHandPiece","previousPiece","board","tier","tower","movedPiece","previousInventory","currentInventory","typeColorKey","prevGroup","currentGroup","preserveNonMovingPiecesOfType","preserveAllPiecesOfType","currentPiece","prevAtSamePos","prev","currentHand","prevHand","getPieceInventory","board","hand","inventory","rank","file","piece","key","handPiece","applyCanonicalToMissingIds","state","group","color","pieceType","allPieces","comparePiecesCanonically","nextNumber","p","a","b","aRank","aFile","bRank","bFile","Gungi","#board","#hand","#turn","#moveNumber","#drafting","#mode","#history","#previousFen","#previousState","#initPosition","#initializeState","fen","stateWithIds","assignPieceIdsWithState","INTRO_POSITION","opts","tierToColor","pc","s","rank","file","square","code","pieceToFenCode","symbolToName","en","coloredPiece","color","capturedCounts","move","acc","p","c","a","ADVANCED_POSITION","encodeFEN","get","getTop","piece","states","frequencyMap","map","str","isGameOver","pgn","parsePGN","moves","found","m","generateMovesForSquare","generateArata","hp","boardMoves","SQUARES","handMoves","encodePGN","lastMove","validateFen"]}
|