1 import { ChessRules
, PiPo
, Move
} from "@/base_rules";
2 import { ArrayFun
} from "@/utils/array";
3 import { sample
, shuffle
} from "@/utils/alea";
5 export class ShogiRules
extends ChessRules
{
6 static get HasFlags() {
10 static get HasEnpassant() {
14 static get Monochrome() {
18 static get Notoodark() {
22 static IsGoodFen(fen
) {
23 if (!ChessRules
.IsGoodFen(fen
)) return false;
24 const fenParsed
= V
.ParseFen(fen
);
26 if (!fenParsed
.reserve
|| !fenParsed
.reserve
.match(/^[0-9]{14,14}$/))
31 static ParseFen(fen
) {
32 const fenParts
= fen
.split(" ");
34 ChessRules
.ParseFen(fen
),
35 { reserve: fenParts
[3] }
39 // pawns, rooks, knights, bishops and king kept from ChessRules
43 static get SILVER_G() {
54 static get P_KNIGHT() {
57 static get P_SILVER() {
60 static get P_LANCE() {
66 static get P_BISHOP() {
89 getPpath(b
, color
, score
, orientation
) {
90 // 'i' for "inversed":
91 const suffix
= (b
[0] == orientation
? "" : "i");
92 return "Shogi/" + b
+ suffix
;
95 getPPpath(m
, orientation
) {
98 m
.appear
[0].c
+ m
.appear
[0].p
,
106 static GenRandInitFen(randomness
) {
107 if (randomness
== 0) {
109 "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL " +
113 // Randomization following these indications:
114 // http://www.shogi.net/shogi-l/Archive/2007/Nmar16-02.txt
115 let pieces1
= { w: new Array(4), b: new Array(4) };
116 let positions2
= { w: new Array(2), b: new Array(2) };
117 for (let c
of ["w", "b"]) {
118 if (c
== 'b' && randomness
== 1) {
119 pieces1
['b'] = JSON
.parse(JSON
.stringify(pieces1
['w'])).reverse();
121 JSON
.parse(JSON
.stringify(positions2
['w'])).reverse()
125 let positions
= shuffle(ArrayFun
.range(4));
126 const composition
= ['s', 's', 'g', 'g'];
127 for (let i
= 0; i
< 4; i
++) pieces1
[c
][positions
[i
]] = composition
[i
];
128 positions2
[c
] = sample(ArrayFun
.range(9), 2).sort();
133 pieces1
["b"].slice(0, 2).join("") +
135 pieces1
["b"].slice(2, 4).join("") +
139 (positions2
['b'][0] || "") + 'r' +
140 (positions2
['b'][1] - positions2
['b'][0] - 1 || "") + 'b' +
141 (8 - positions2
['b'][1] || "")
143 "/ppppppppp/9/9/9/PPPPPPPPP/" +
145 (positions2
['w'][0] || "") + 'B' +
146 (positions2
['w'][1] - positions2
['w'][0] - 1 || "") + 'R' +
147 (8 - positions2
['w'][1] || "")
151 pieces1
["w"].slice(0, 2).join("").toUpperCase() +
153 pieces1
["w"].slice(2, 4).join("").toUpperCase() +
156 " w 0 00000000000000"
161 return super.getFen() + " " + this.getReserveFen();
165 return super.getFenForRepeat() + "_" + this.getReserveFen();
169 let counts
= new Array(14);
170 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
171 counts
[i
] = this.reserve
["w"][V
.RESERVE_PIECES
[i
]];
172 counts
[7 + i
] = this.reserve
["b"][V
.RESERVE_PIECES
[i
]];
174 return counts
.join("");
177 setOtherVariables(fen
) {
178 super.setOtherVariables(fen
);
179 const fenParsed
= V
.ParseFen(fen
);
180 // Also init reserves (used by the interface to show landable pieces)
183 [V
.PAWN
]: parseInt(fenParsed
.reserve
[0]),
184 [V
.ROOK
]: parseInt(fenParsed
.reserve
[1]),
185 [V
.BISHOP
]: parseInt(fenParsed
.reserve
[2]),
186 [V
.GOLD_G
]: parseInt(fenParsed
.reserve
[3]),
187 [V
.SILVER_G
]: parseInt(fenParsed
.reserve
[4]),
188 [V
.KNIGHT
]: parseInt(fenParsed
.reserve
[5]),
189 [V
.LANCE
]: parseInt(fenParsed
.reserve
[6])
192 [V
.PAWN
]: parseInt(fenParsed
.reserve
[7]),
193 [V
.ROOK
]: parseInt(fenParsed
.reserve
[8]),
194 [V
.BISHOP
]: parseInt(fenParsed
.reserve
[9]),
195 [V
.GOLD_G
]: parseInt(fenParsed
.reserve
[10]),
196 [V
.SILVER_G
]: parseInt(fenParsed
.reserve
[11]),
197 [V
.KNIGHT
]: parseInt(fenParsed
.reserve
[12]),
198 [V
.LANCE
]: parseInt(fenParsed
.reserve
[13])
204 if (i
>= V
.size
.x
) return i
== V
.size
.x
? "w" : "b";
205 return this.board
[i
][j
].charAt(0);
209 if (i
>= V
.size
.x
) return V
.RESERVE_PIECES
[j
];
210 return this.board
[i
][j
].charAt(1);
214 return { x: 9, y: 9};
217 getReservePpath(index
, color
, orientation
) {
219 "Shogi/" + color
+ V
.RESERVE_PIECES
[index
] +
220 (color
!= orientation
? 'i' : '')
224 // Ordering on reserve pieces
225 static get RESERVE_PIECES() {
227 [V
.PAWN
, V
.ROOK
, V
.BISHOP
, V
.GOLD_G
, V
.SILVER_G
, V
.KNIGHT
, V
.LANCE
]
231 getReserveMoves([x
, y
]) {
232 const color
= this.turn
;
233 const p
= V
.RESERVE_PIECES
[y
];
235 var oppCol
= V
.GetOppCol(color
);
237 [...Array(9).keys()].filter(j
=>
238 [...Array(9).keys()].every(i
=> {
240 this.board
[i
][j
] == V
.EMPTY
||
241 this.getColor(i
, j
) != color
||
242 this.getPiece(i
, j
) != V
.PAWN
247 if (this.reserve
[color
][p
] == 0) return [];
249 const forward
= color
== 'w' ? -1 : 1;
250 const lastRanks
= color
== 'w' ? [0, 1] : [8, 7];
251 for (let i
= 0; i
< V
.size
.x
; i
++) {
253 (i
== lastRanks
[0] && [V
.PAWN
, V
.KNIGHT
, V
.LANCE
].includes(p
)) ||
254 (i
== lastRanks
[1] && p
== V
.KNIGHT
)
258 for (let j
= 0; j
< V
.size
.y
; j
++) {
260 this.board
[i
][j
] == V
.EMPTY
&&
261 (p
!= V
.PAWN
|| allowedFiles
.includes(j
))
273 start: { x: x
, y: y
}, //a bit artificial...
277 // Do not drop on checkmate:
279 const res
= (this.underCheck(oppCol
) && !this.atLeastOneMove());
290 getPotentialMovesFrom([x
, y
]) {
292 // Reserves, outside of board: x == sizeX(+1)
293 return this.getReserveMoves([x
, y
]);
295 switch (this.getPiece(x
, y
)) {
297 return this.getPotentialPawnMoves([x
, y
]);
299 return this.getPotentialRookMoves([x
, y
]);
301 return this.getPotentialKnightMoves([x
, y
]);
303 return this.getPotentialBishopMoves([x
, y
]);
305 return this.getPotentialSilverMoves([x
, y
]);
307 return this.getPotentialLanceMoves([x
, y
]);
309 return this.getPotentialKingMoves([x
, y
]);
311 return this.getPotentialDragonMoves([x
, y
]);
313 return this.getPotentialHorseMoves([x
, y
]);
319 return this.getPotentialGoldMoves([x
, y
]);
321 return []; //never reached
324 // Modified to take promotions into account
325 getSlideNJumpMoves([x
, y
], steps
, options
) {
326 options
= options
|| {};
327 const color
= this.turn
;
328 const oneStep
= options
.oneStep
;
329 const forcePromoteOnLastRank
= options
.force
;
330 const promoteInto
= options
.promote
;
331 const lastRanks
= (color
== 'w' ? [0, 1, 2] : [9, 8, 7]);
333 outerLoop: for (let step
of steps
) {
336 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
337 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
338 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
339 if (!!promoteInto
&& lastRanks
.includes(i
)) {
342 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
345 if (oneStep
) continue outerLoop
;
349 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
])) {
350 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
351 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
352 if (!!promoteInto
&& lastRanks
.includes(i
)) {
355 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
363 getPotentialGoldMoves(sq
) {
364 const forward
= (this.turn
== 'w' ? -1 : 1);
365 return this.getSlideNJumpMoves(
367 V
.steps
[V
.ROOK
].concat([ [forward
, 1], [forward
, -1] ]),
372 getPotentialPawnMoves(sq
) {
373 const forward
= (this.turn
== 'w' ? -1 : 1);
375 this.getSlideNJumpMoves(
387 getPotentialSilverMoves(sq
) {
388 const forward
= (this.turn
== 'w' ? -1 : 1);
389 return this.getSlideNJumpMoves(
391 V
.steps
[V
.BISHOP
].concat([ [forward
, 0] ]),
399 getPotentialKnightMoves(sq
) {
400 const forward
= (this.turn
== 'w' ? -2 : 2);
401 return this.getSlideNJumpMoves(
403 [ [forward
, 1], [forward
, -1] ],
412 getPotentialLanceMoves(sq
) {
413 const forward
= (this.turn
== 'w' ? -1 : 1);
414 return this.getSlideNJumpMoves(
424 getPotentialRookMoves(sq
) {
425 return this.getSlideNJumpMoves(
426 sq
, V
.steps
[V
.ROOK
], { promote: V
.P_ROOK
});
429 getPotentialBishopMoves(sq
) {
430 return this.getSlideNJumpMoves(
431 sq
, V
.steps
[V
.BISHOP
], { promote: V
.P_BISHOP
});
434 getPotentialDragonMoves(sq
) {
436 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]).concat(
437 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
], { oneStep: true }))
441 getPotentialHorseMoves(sq
) {
443 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]).concat(
444 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
], { oneStep: true }))
448 getPotentialKingMoves(sq
) {
449 return this.getSlideNJumpMoves(
451 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
456 isAttacked(sq
, color
) {
458 this.isAttackedByPawn(sq
, color
) ||
459 this.isAttackedByRook(sq
, color
) ||
460 this.isAttackedByDragon(sq
, color
) ||
461 this.isAttackedByKnight(sq
, color
) ||
462 this.isAttackedByBishop(sq
, color
) ||
463 this.isAttackedByHorse(sq
, color
) ||
464 this.isAttackedByLance(sq
, color
) ||
465 this.isAttackedBySilver(sq
, color
) ||
466 this.isAttackedByGold(sq
, color
) ||
467 this.isAttackedByKing(sq
, color
)
471 isAttackedByGold([x
, y
], color
) {
472 const shift
= (color
== 'w' ? 1 : -1);
473 for (let step
of V
.steps
[V
.ROOK
].concat([[shift
, 1], [shift
, -1]])) {
474 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
477 this.board
[i
][j
] != V
.EMPTY
&&
478 this.getColor(i
, j
) == color
&&
479 [V
.GOLD_G
, V
.P_PAWN
, V
.P_SILVER
, V
.P_KNIGHT
, V
.P_LANCE
]
480 .includes(this.getPiece(i
, j
))
488 isAttackedBySilver([x
, y
], color
) {
489 const shift
= (color
== 'w' ? 1 : -1);
490 for (let step
of V
.steps
[V
.BISHOP
].concat([[shift
, 0]])) {
491 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
494 this.board
[i
][j
] != V
.EMPTY
&&
495 this.getColor(i
, j
) == color
&&
496 this.getPiece(i
, j
) == V
.SILVER_G
504 isAttackedByPawn([x
, y
], color
) {
505 const shift
= (color
== 'w' ? 1 : -1);
506 const [i
, j
] = [x
+ shift
, y
];
509 this.board
[i
][j
] != V
.EMPTY
&&
510 this.getColor(i
, j
) == color
&&
511 this.getPiece(i
, j
) == V
.PAWN
515 isAttackedByKnight(sq
, color
) {
516 const forward
= (color
== 'w' ? 2 : -2);
517 return this.isAttackedBySlideNJump(
518 sq
, color
, V
.KNIGHT
, [[forward
, 1], [forward
, -1]], "oneStep");
521 isAttackedByLance(sq
, color
) {
522 const forward
= (color
== 'w' ? 1 : -1);
523 return this.isAttackedBySlideNJump(sq
, color
, V
.LANCE
, [[forward
, 0]]);
526 isAttackedByDragon(sq
, color
) {
528 this.isAttackedBySlideNJump(sq
, color
, V
.P_ROOK
, V
.steps
[V
.ROOK
]) ||
529 this.isAttackedBySlideNJump(
530 sq
, color
, V
.P_ROOK
, V
.steps
[V
.BISHOP
], "oneStep")
534 isAttackedByHorse(sq
, color
) {
536 this.isAttackedBySlideNJump(sq
, color
, V
.P_BISHOP
, V
.steps
[V
.BISHOP
]) ||
537 this.isAttackedBySlideNJump(
538 sq
, color
, V
.P_BISHOP
, V
.steps
[V
.ROOK
], "oneStep")
543 let moves
= super.getAllPotentialMoves();
544 const color
= this.turn
;
545 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
546 moves
= moves
.concat(
547 this.getReserveMoves([V
.size
.x
+ (color
== "w" ? 0 : 1), i
])
550 return this.filterValid(moves
);
554 if (!super.atLeastOneMove()) {
555 // Search one reserve move
556 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
557 let moves
= this.filterValid(
558 this.getReserveMoves([V
.size
.x
+ (this.turn
== "w" ? 0 : 1), i
])
560 if (moves
.length
> 0) return true;
567 static get P_CORRESPONDANCES() {
578 static MayDecode(piece
) {
579 if (Object
.keys(V
.P_CORRESPONDANCES
).includes(piece
))
580 return V
.P_CORRESPONDANCES
[piece
];
585 super.postPlay(move);
586 const color
= move.appear
[0].c
;
587 if (move.vanish
.length
== 0)
588 // Drop unpromoted piece:
589 this.reserve
[color
][move.appear
[0].p
]--;
590 else if (move.vanish
.length
== 2)
591 // May capture a promoted piece:
592 this.reserve
[color
][V
.MayDecode(move.vanish
[1].p
)]++;
596 super.postUndo(move);
597 const color
= this.turn
;
598 if (move.vanish
.length
== 0)
599 this.reserve
[color
][move.appear
[0].p
]++;
600 else if (move.vanish
.length
== 2)
601 this.reserve
[color
][V
.MayDecode(move.vanish
[1].p
)]--;
604 static get SEARCH_DEPTH() {
608 static get VALUES() {
609 // TODO: very arbitrary and wrong
629 let evaluation
= super.evalPosition();
631 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
632 const p
= V
.RESERVE_PIECES
[i
];
633 evaluation
+= this.reserve
["w"][p
] * V
.VALUES
[p
];
634 evaluation
-= this.reserve
["b"][p
] * V
.VALUES
[p
];
640 const finalSquare
= V
.CoordsToSquare(move.end
);
641 if (move.vanish
.length
== 0) {
643 const piece
= move.appear
[0].p
.toUpperCase();
644 return (piece
!= 'P' ? piece : "") + "@" + finalSquare
;
646 const piece
= move.vanish
[0].p
.toUpperCase();
648 (piece
!= 'P' || move.vanish
.length
== 2 ? piece : "") +
649 (move.vanish
.length
== 2 ? "x" : "") +
652 move.appear
[0].p
!= move.vanish
[0].p
653 ? "=" + move.appear
[0].p
.toUpperCase()