e8b179185db972d187407d2e9755b605a55437fe
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() {
19 static get Notoodark() {
23 static IsGoodFen(fen
) {
24 if (!ChessRules
.IsGoodFen(fen
)) return false;
25 const fenParsed
= V
.ParseFen(fen
);
27 if (!fenParsed
.reserve
|| !fenParsed
.reserve
.match(/^[0-9]{14,14}$/))
32 static ParseFen(fen
) {
33 const fenParts
= fen
.split(" ");
35 ChessRules
.ParseFen(fen
),
36 { reserve: fenParts
[3] }
40 // pawns, rooks, knights, bishops and king kept from ChessRules
44 static get SILVER_G() {
55 static get P_KNIGHT() {
58 static get P_SILVER() {
61 static get P_LANCE() {
67 static get P_BISHOP() {
90 getPpath(b
, color
, score
, orientation
) {
91 // 'i' for "inversed":
92 const suffix
= (b
[0] == orientation
? "" : "i");
93 return "Shogi/" + b
+ suffix
;
96 getPPpath(m
, orientation
) {
99 m
.appear
[0].c
+ m
.appear
[0].p
,
107 static GenRandInitFen(randomness
) {
108 if (randomness
== 0) {
110 "lnsgkgsnl/1r5b1/ppppppppp/9/9/9/PPPPPPPPP/1B5R1/LNSGKGSNL " +
114 // Randomization following these indications:
115 // http://www.shogi.net/shogi-l/Archive/2007/Nmar16-02.txt
116 let pieces1
= { w: new Array(4), b: new Array(4) };
117 let positions2
= { w: new Array(2), b: new Array(2) };
118 for (let c
of ["w", "b"]) {
119 if (c
== 'b' && randomness
== 1) {
120 pieces1
['b'] = JSON
.parse(JSON
.stringify(pieces1
['w'])).reverse();
122 JSON
.parse(JSON
.stringify(positions2
['w'])).reverse()
126 let positions
= shuffle(ArrayFun
.range(4));
127 const composition
= ['s', 's', 'g', 'g'];
128 for (let i
= 0; i
< 4; i
++) pieces1
[c
][positions
[i
]] = composition
[i
];
129 positions2
[c
] = sample(ArrayFun
.range(9), 2).sort();
134 pieces1
["b"].slice(0, 2).join("") +
136 pieces1
["b"].slice(2, 4).join("") +
140 (positions2
['b'][0] || "") + 'r' +
141 (positions2
['b'][1] - positions2
['b'][0] - 1 || "") + 'b' +
142 (8 - positions2
['b'][1] || "")
144 "/ppppppppp/9/9/9/PPPPPPPPP/" +
146 (positions2
['w'][0] || "") + 'B' +
147 (positions2
['w'][1] - positions2
['w'][0] - 1 || "") + 'R' +
148 (8 - positions2
['w'][1] || "")
152 pieces1
["w"].slice(0, 2).join("").toUpperCase() +
154 pieces1
["w"].slice(2, 4).join("").toUpperCase() +
157 " w 0 00000000000000"
162 return super.getFen() + " " + this.getReserveFen();
166 return super.getFenForRepeat() + "_" + this.getReserveFen();
170 let counts
= new Array(14);
171 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
172 counts
[i
] = this.reserve
["w"][V
.RESERVE_PIECES
[i
]];
173 counts
[7 + i
] = this.reserve
["b"][V
.RESERVE_PIECES
[i
]];
175 return counts
.join("");
178 setOtherVariables(fen
) {
179 super.setOtherVariables(fen
);
180 // Also init reserves (used by the interface to show landable pieces)
182 V
.ParseFen(fen
).reserve
.split("").map(x
=> parseInt(x
, 10));
185 [V
.PAWN
]: reserve
[0],
186 [V
.ROOK
]: reserve
[1],
187 [V
.BISHOP
]: reserve
[2],
188 [V
.GOLD_G
]: reserve
[3],
189 [V
.SILVER_G
]: reserve
[4],
190 [V
.KNIGHT
]: reserve
[5],
191 [V
.LANCE
]: reserve
[6]
194 [V
.PAWN
]: reserve
[7],
195 [V
.ROOK
]: reserve
[8],
196 [V
.BISHOP
]: reserve
[9],
197 [V
.GOLD_G
]: reserve
[10],
198 [V
.SILVER_G
]: reserve
[11],
199 [V
.KNIGHT
]: reserve
[12],
200 [V
.LANCE
]: reserve
[13]
206 if (i
>= V
.size
.x
) return i
== V
.size
.x
? "w" : "b";
207 return this.board
[i
][j
].charAt(0);
211 if (i
>= V
.size
.x
) return V
.RESERVE_PIECES
[j
];
212 return this.board
[i
][j
].charAt(1);
216 return { x: 9, y: 9};
219 getReservePpath(index
, color
, orientation
) {
221 "Shogi/" + color
+ V
.RESERVE_PIECES
[index
] +
222 (color
!= orientation
? 'i' : '')
226 // Ordering on reserve pieces
227 static get RESERVE_PIECES() {
229 [V
.PAWN
, V
.ROOK
, V
.BISHOP
, V
.GOLD_G
, V
.SILVER_G
, V
.KNIGHT
, V
.LANCE
]
233 getReserveMoves([x
, y
]) {
234 const color
= this.turn
;
235 const p
= V
.RESERVE_PIECES
[y
];
237 var oppCol
= V
.GetOppCol(color
);
239 [...Array(9).keys()].filter(j
=>
240 [...Array(9).keys()].every(i
=> {
242 this.board
[i
][j
] == V
.EMPTY
||
243 this.getColor(i
, j
) != color
||
244 this.getPiece(i
, j
) != V
.PAWN
249 if (this.reserve
[color
][p
] == 0) return [];
251 const forward
= color
== 'w' ? -1 : 1;
252 const lastRanks
= color
== 'w' ? [0, 1] : [8, 7];
253 for (let i
= 0; i
< V
.size
.x
; i
++) {
255 (i
== lastRanks
[0] && [V
.PAWN
, V
.KNIGHT
, V
.LANCE
].includes(p
)) ||
256 (i
== lastRanks
[1] && p
== V
.KNIGHT
)
260 for (let j
= 0; j
< V
.size
.y
; j
++) {
262 this.board
[i
][j
] == V
.EMPTY
&&
263 (p
!= V
.PAWN
|| allowedFiles
.includes(j
))
275 start: { x: x
, y: y
}, //a bit artificial...
279 // Do not drop on checkmate:
281 const res
= (this.underCheck(oppCol
) && !this.atLeastOneMove());
292 getPotentialMovesFrom([x
, y
]) {
294 // Reserves, outside of board: x == sizeX(+1)
295 return this.getReserveMoves([x
, y
]);
297 switch (this.getPiece(x
, y
)) {
299 return this.getPotentialPawnMoves([x
, y
]);
301 return this.getPotentialRookMoves([x
, y
]);
303 return this.getPotentialKnightMoves([x
, y
]);
305 return this.getPotentialBishopMoves([x
, y
]);
307 return this.getPotentialSilverMoves([x
, y
]);
309 return this.getPotentialLanceMoves([x
, y
]);
311 return this.getPotentialKingMoves([x
, y
]);
313 return this.getPotentialDragonMoves([x
, y
]);
315 return this.getPotentialHorseMoves([x
, y
]);
321 return this.getPotentialGoldMoves([x
, y
]);
323 return []; //never reached
326 // Modified to take promotions into account
327 getSlideNJumpMoves([x
, y
], steps
, options
) {
328 options
= options
|| {};
329 const color
= this.turn
;
330 const oneStep
= options
.oneStep
;
331 const forcePromoteOnLastRank
= options
.force
;
332 const promoteInto
= options
.promote
;
333 const lastRanks
= (color
== 'w' ? [0, 1, 2] : [9, 8, 7]);
335 outerLoop: for (let step
of steps
) {
338 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
339 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
340 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
341 if (!!promoteInto
&& lastRanks
.includes(i
)) {
344 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
347 if (oneStep
) continue outerLoop
;
351 if (V
.OnBoard(i
, j
) && this.canTake([x
, y
], [i
, j
])) {
352 if (i
!= lastRanks
[0] || !forcePromoteOnLastRank
)
353 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
354 if (!!promoteInto
&& lastRanks
.includes(i
)) {
357 [x
, y
], [i
, j
], { c: color
, p: promoteInto
})
365 getPotentialGoldMoves(sq
) {
366 const forward
= (this.turn
== 'w' ? -1 : 1);
367 return this.getSlideNJumpMoves(
369 V
.steps
[V
.ROOK
].concat([ [forward
, 1], [forward
, -1] ]),
374 getPotentialPawnMoves(sq
) {
375 const forward
= (this.turn
== 'w' ? -1 : 1);
377 this.getSlideNJumpMoves(
389 getPotentialSilverMoves(sq
) {
390 const forward
= (this.turn
== 'w' ? -1 : 1);
391 return this.getSlideNJumpMoves(
393 V
.steps
[V
.BISHOP
].concat([ [forward
, 0] ]),
401 getPotentialKnightMoves(sq
) {
402 const forward
= (this.turn
== 'w' ? -2 : 2);
403 return this.getSlideNJumpMoves(
405 [ [forward
, 1], [forward
, -1] ],
414 getPotentialLanceMoves(sq
) {
415 const forward
= (this.turn
== 'w' ? -1 : 1);
416 return this.getSlideNJumpMoves(
426 getPotentialRookMoves(sq
) {
427 return this.getSlideNJumpMoves(
428 sq
, V
.steps
[V
.ROOK
], { promote: V
.P_ROOK
});
431 getPotentialBishopMoves(sq
) {
432 return this.getSlideNJumpMoves(
433 sq
, V
.steps
[V
.BISHOP
], { promote: V
.P_BISHOP
});
436 getPotentialDragonMoves(sq
) {
438 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]).concat(
439 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
], { oneStep: true }))
443 getPotentialHorseMoves(sq
) {
445 this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]).concat(
446 this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
], { oneStep: true }))
450 getPotentialKingMoves(sq
) {
451 return this.getSlideNJumpMoves(
453 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
458 isAttacked(sq
, color
) {
460 this.isAttackedByPawn(sq
, color
) ||
461 this.isAttackedByRook(sq
, color
) ||
462 this.isAttackedByDragon(sq
, color
) ||
463 this.isAttackedByKnight(sq
, color
) ||
464 this.isAttackedByBishop(sq
, color
) ||
465 this.isAttackedByHorse(sq
, color
) ||
466 this.isAttackedByLance(sq
, color
) ||
467 this.isAttackedBySilver(sq
, color
) ||
468 this.isAttackedByGold(sq
, color
) ||
469 this.isAttackedByKing(sq
, color
)
473 isAttackedByGold([x
, y
], color
) {
474 const shift
= (color
== 'w' ? 1 : -1);
475 for (let step
of V
.steps
[V
.ROOK
].concat([[shift
, 1], [shift
, -1]])) {
476 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
479 this.board
[i
][j
] != V
.EMPTY
&&
480 this.getColor(i
, j
) == color
&&
481 [V
.GOLD_G
, V
.P_PAWN
, V
.P_SILVER
, V
.P_KNIGHT
, V
.P_LANCE
]
482 .includes(this.getPiece(i
, j
))
490 isAttackedBySilver([x
, y
], color
) {
491 const shift
= (color
== 'w' ? 1 : -1);
492 for (let step
of V
.steps
[V
.BISHOP
].concat([[shift
, 0]])) {
493 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
496 this.board
[i
][j
] != V
.EMPTY
&&
497 this.getColor(i
, j
) == color
&&
498 this.getPiece(i
, j
) == V
.SILVER_G
506 isAttackedByPawn([x
, y
], color
) {
507 const shift
= (color
== 'w' ? 1 : -1);
508 const [i
, j
] = [x
+ shift
, y
];
511 this.board
[i
][j
] != V
.EMPTY
&&
512 this.getColor(i
, j
) == color
&&
513 this.getPiece(i
, j
) == V
.PAWN
517 isAttackedByKnight(sq
, color
) {
518 const forward
= (color
== 'w' ? 2 : -2);
519 return this.isAttackedBySlideNJump(
520 sq
, color
, V
.KNIGHT
, [[forward
, 1], [forward
, -1]], "oneStep");
523 isAttackedByLance(sq
, color
) {
524 const forward
= (color
== 'w' ? 1 : -1);
525 return this.isAttackedBySlideNJump(sq
, color
, V
.LANCE
, [[forward
, 0]]);
528 isAttackedByDragon(sq
, color
) {
530 this.isAttackedBySlideNJump(sq
, color
, V
.P_ROOK
, V
.steps
[V
.ROOK
]) ||
531 this.isAttackedBySlideNJump(
532 sq
, color
, V
.P_ROOK
, V
.steps
[V
.BISHOP
], "oneStep")
536 isAttackedByHorse(sq
, color
) {
538 this.isAttackedBySlideNJump(sq
, color
, V
.P_BISHOP
, V
.steps
[V
.BISHOP
]) ||
539 this.isAttackedBySlideNJump(
540 sq
, color
, V
.P_BISHOP
, V
.steps
[V
.ROOK
], "oneStep")
545 let moves
= super.getAllPotentialMoves();
546 const color
= this.turn
;
547 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
548 moves
= moves
.concat(
549 this.getReserveMoves([V
.size
.x
+ (color
== "w" ? 0 : 1), i
])
552 return this.filterValid(moves
);
556 if (!super.atLeastOneMove()) {
557 // Search one reserve move
558 for (let i
= 0; i
< V
.RESERVE_PIECES
.length
; i
++) {
559 let moves
= this.filterValid(
560 this.getReserveMoves([V
.size
.x
+ (this.turn
== "w" ? 0 : 1), i
])
562 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()