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
{
7 static get HasFlags() {
11 static get HasEnpassant() {
15 static get Monochrome() {
23 static get Notoodark() {
27 static IsGoodFen(fen
) {
28 if (!ChessRules
.IsGoodFen(fen
)) return false;
29 const fenParsed
= V
.ParseFen(fen
);
31 if (!fenParsed
.reserve
|| !fenParsed
.reserve
.match(/^[0-9]{14,14}$/))
36 static ParseFen(fen
) {
37 const fenParts
= fen
.split(" ");
39 ChessRules
.ParseFen(fen
),
40 { reserve: fenParts
[3] }
44 // pawns, rooks, knights, bishops and king kept from ChessRules
48 static get SILVER_G() {
59 static get P_KNIGHT() {
62 static get P_SILVER() {
65 static get P_LANCE() {
71 static get P_BISHOP() {
94 getPpath(b
, color
, score
, orientation
) {
95 // 'i' for "inversed":
96 const suffix
= (b
[0] == orientation
? "" : "i");
97 return "Shogi/" + b
+ suffix
;
100 getPPpath(m
, orientation
) {
103 m
.appear
[0].c
+ m
.appear
[0].p
,
111 static GenRandInitFen(randomness
) {
112 if (randomness
== 0) {
114 "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL " +
118 // Randomization following these indications:
119 // http://www.shogi.net/shogi-l/Archive/2007/Nmar16-02.txt
120 let pieces1
= { w: new Array(4), b: new Array(4) };
121 let positions2
= { w: new Array(2), b: new Array(2) };
122 for (let c
of ["w", "b"]) {
123 if (c
== 'b' && randomness
== 1) {
124 pieces1
['b'] = JSON
.parse(JSON
.stringify(pieces1
['w'])).reverse();
126 JSON
.parse(JSON
.stringify(positions2
['w'])).reverse()
130 let positions
= shuffle(ArrayFun
.range(4));
131 const composition
= ['s', 's', 'g', 'g'];
132 for (let i
= 0; i
< 4; i
++) pieces1
[c
][positions
[i
]] = composition
[i
];
133 positions2
[c
] = sample(ArrayFun
.range(9), 2).sort();
138 pieces1
["b"].slice(0, 2).join("") +
140 pieces1
["b"].slice(2, 4).join("") +
144 (positions2
['b'][0] || "") + 'r' +
145 (positions2
['b'][1] - positions2
['b'][0] - 1 || "") + 'b' +
146 (8 - positions2
['b'][1] || "")
148 "/ppppppppp/9/9/9/PPPPPPPPP/" +
150 (positions2
['w'][0] || "") + 'B' +
151 (positions2
['w'][1] - positions2
['w'][0] - 1 || "") + 'R' +
152 (8 - positions2
['w'][1] || "")
156 pieces1
["w"].slice(0, 2).join("").toUpperCase() +
158 pieces1
["w"].slice(2, 4).join("").toUpperCase() +
161 " w 0 00000000000000"
166 return super.getFen() + " " + this.getReserveFen();
170 return super.getFenForRepeat() + "_" + this.getReserveFen();
174 let counts
= new Array(14);
175 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
176 counts
[i
] = this.reserve
["w"][V
.RESERVE_PIECES
[i
]];
177 counts
[7 + i
] = this.reserve
["b"][V
.RESERVE_PIECES
[i
]];
179 return counts
.join("");
182 setOtherVariables(fen
) {
183 super.setOtherVariables(fen
);
184 // Also init reserves (used by the interface to show landable pieces)
186 V
.ParseFen(fen
).reserve
.split("").map(x
=> parseInt(x
, 10));
189 [V
.PAWN
]: reserve
[0],
190 [V
.ROOK
]: reserve
[1],
191 [V
.BISHOP
]: reserve
[2],
192 [V
.GOLD_G
]: reserve
[3],
193 [V
.SILVER_G
]: reserve
[4],
194 [V
.KNIGHT
]: reserve
[5],
195 [V
.LANCE
]: reserve
[6]
198 [V
.PAWN
]: reserve
[7],
199 [V
.ROOK
]: reserve
[8],
200 [V
.BISHOP
]: reserve
[9],
201 [V
.GOLD_G
]: reserve
[10],
202 [V
.SILVER_G
]: reserve
[11],
203 [V
.KNIGHT
]: reserve
[12],
204 [V
.LANCE
]: reserve
[13]
210 if (i
>= V
.size
.x
) return i
== V
.size
.x
? "w" : "b";
211 return this.board
[i
][j
].charAt(0);
215 if (i
>= V
.size
.x
) return V
.RESERVE_PIECES
[j
];
216 return this.board
[i
][j
].charAt(1);
220 return { x: 9, y: 9};
223 getReservePpath(index
, color
, orientation
) {
225 "Shogi/" + color
+ V
.RESERVE_PIECES
[index
] +
226 (color
!= orientation
? 'i' : '')
230 // Ordering on reserve pieces
231 static get RESERVE_PIECES() {
233 [V
.PAWN
, V
.ROOK
, V
.BISHOP
, V
.GOLD_G
, V
.SILVER_G
, V
.KNIGHT
, V
.LANCE
]
237 getReserveMoves([x
, y
]) {
238 const color
= this.turn
;
239 const p
= V
.RESERVE_PIECES
[y
];
241 var oppCol
= V
.GetOppCol(color
);
243 [...Array(9).keys()].filter(j
=>
244 [...Array(9).keys()].every(i
=> {
246 this.board
[i
][j
] == V
.EMPTY
||
247 this.getColor(i
, j
) != color
||
248 this.getPiece(i
, j
) != V
.PAWN
253 if (this.reserve
[color
][p
] == 0) return [];
255 const forward
= color
== 'w' ? -1 : 1;
256 const lastRanks
= color
== 'w' ? [0, 1] : [8, 7];
257 for (let i
= 0; i
< V
.size
.x
; i
++) {
259 (i
== lastRanks
[0] && [V
.PAWN
, V
.KNIGHT
, V
.LANCE
].includes(p
)) ||
260 (i
== lastRanks
[1] && p
== V
.KNIGHT
)
264 for (let j
= 0; j
< V
.size
.y
; j
++) {
266 this.board
[i
][j
] == V
.EMPTY
&&
267 (p
!= V
.PAWN
|| allowedFiles
.includes(j
))
279 start: { x: x
, y: y
}, //a bit artificial...
283 // Do not drop on checkmate:
286 this.underCheck(oppCol
) && !this.atLeastOneMove("noReserve")
298 getPotentialMovesFrom([x
, y
]) {
300 // Reserves, outside of board: x == sizeX(+1)
301 return this.getReserveMoves([x
, y
]);
303 switch (this.getPiece(x
, y
)) {
305 return this.getPotentialPawnMoves([x
, y
]);
307 return this.getPotentialRookMoves([x
, y
]);
309 return this.getPotentialKnightMoves([x
, y
]);
311 return this.getPotentialBishopMoves([x
, y
]);
313 return this.getPotentialSilverMoves([x
, y
]);
315 return this.getPotentialLanceMoves([x
, y
]);
317 return super.getPotentialKingMoves([x
, y
]);
319 return this.getPotentialDragonMoves([x
, y
]);
321 return this.getPotentialHorseMoves([x
, y
]);
327 return this.getPotentialGoldMoves([x
, y
]);
329 return []; //never reached
332 // Modified to take promotions into account
333 getSlideNJumpMoves([x
, y
], steps
, options
) {
334 options
= options
|| {};
335 const color
= this.turn
;
336 const oneStep
= options
.oneStep
;
337 const forcePromoteOnLastRank
= options
.force
;
338 const promoteInto
= options
.promote
;
339 const lastRanks
= (color
== 'w' ? [0, 1, 2] : [9, 8, 7]);
341 outerLoop: for (let step
of steps
) {
344 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
345 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
346 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
347 if (!!promoteInto
&& lastRanks
.includes(i
)) {
350 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
353 if (oneStep
) continue outerLoop
;
357 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
])) {
358 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
359 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
360 if (!!promoteInto
&& lastRanks
.includes(i
)) {
363 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
371 getPotentialGoldMoves(sq
) {
372 const forward
= (this.turn
== 'w' ? -1 : 1);
373 return this.getSlideNJumpMoves(
375 V
.steps
[V
.ROOK
].concat([ [forward
, 1], [forward
, -1] ]),
380 getPotentialPawnMoves(sq
) {
381 const forward
= (this.turn
== 'w' ? -1 : 1);
383 this.getSlideNJumpMoves(
395 getPotentialSilverMoves(sq
) {
396 const forward
= (this.turn
== 'w' ? -1 : 1);
397 return this.getSlideNJumpMoves(
399 V
.steps
[V
.BISHOP
].concat([ [forward
, 0] ]),
407 getPotentialKnightMoves(sq
) {
408 const forward
= (this.turn
== 'w' ? -2 : 2);
409 return this.getSlideNJumpMoves(
411 [ [forward
, 1], [forward
, -1] ],
420 getPotentialLanceMoves(sq
) {
421 const forward
= (this.turn
== 'w' ? -1 : 1);
422 return this.getSlideNJumpMoves(
432 getPotentialRookMoves(sq
) {
433 return this.getSlideNJumpMoves(
434 sq
, V
.steps
[V
.ROOK
], { promote: V
.P_ROOK
});
437 getPotentialBishopMoves(sq
) {
438 return this.getSlideNJumpMoves(
439 sq
, V
.steps
[V
.BISHOP
], { promote: V
.P_BISHOP
});
442 getPotentialDragonMoves(sq
) {
444 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]).concat(
445 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
], { oneStep: true }))
449 getPotentialHorseMoves(sq
) {
451 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]).concat(
452 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
], { oneStep: true }))
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
);
553 atLeastOneMove(noReserve
) {
554 if (!super.atLeastOneMove()) {
556 // Search one reserve move
557 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
558 let moves
= this.filterValid(
559 this.getReserveMoves([V
.size
.x
+ (this.turn
== "w" ? 0 : 1), i
])
561 if (moves
.length
> 0) return true;
569 static get P_CORRESPONDANCES() {
580 static MayDecode(piece
) {
581 if (Object
.keys(V
.P_CORRESPONDANCES
).includes(piece
))
582 return V
.P_CORRESPONDANCES
[piece
];
587 super.postPlay(move);
588 const color
= move.appear
[0].c
;
589 if (move.vanish
.length
== 0)
590 // Drop unpromoted piece:
591 this.reserve
[color
][move.appear
[0].p
]--;
592 else if (move.vanish
.length
== 2)
593 // May capture a promoted piece:
594 this.reserve
[color
][V
.MayDecode(move.vanish
[1].p
)]++;
598 super.postUndo(move);
599 const color
= this.turn
;
600 if (move.vanish
.length
== 0)
601 this.reserve
[color
][move.appear
[0].p
]++;
602 else if (move.vanish
.length
== 2)
603 this.reserve
[color
][V
.MayDecode(move.vanish
[1].p
)]--;
606 static get SEARCH_DEPTH() {
610 static get VALUES() {
611 // TODO: very arbitrary and wrong
631 let evaluation
= super.evalPosition();
633 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
634 const p
= V
.RESERVE_PIECES
[i
];
635 evaluation
+= this.reserve
["w"][p
] * V
.VALUES
[p
];
636 evaluation
-= this.reserve
["b"][p
] * V
.VALUES
[p
];
642 const finalSquare
= V
.CoordsToSquare(move.end
);
643 if (move.vanish
.length
== 0) {
645 const piece
= move.appear
[0].p
.toUpperCase();
646 return (piece
!= 'P' ? piece : "") + "@" + finalSquare
;
648 const piece
= move.vanish
[0].p
.toUpperCase();
650 (piece
!= 'P' || move.vanish
.length
== 2 ? piece : "") +
651 (move.vanish
.length
== 2 ? "x" : "") +
654 move.appear
[0].p
!= move.vanish
[0].p
655 ? "=" + move.appear
[0].p
.toUpperCase()