1 import { ArrayFun
} from "@/utils/array";
2 import { randInt
} from "@/utils/alea";
3 import { ChessRules
, PiPo
, Move
} from "@/base_rules";
5 export class EightpiecesRules
extends ChessRules
{
16 static get IMAGE_EXTENSION() {
17 // Temporarily, for the time SVG pieces are being designed:
21 // Lancer directions *from white perspective*
22 static get LANCER_DIRS() {
36 return ChessRules
.PIECES
37 .concat([V
.JAILER
, V
.SENTRY
])
38 .concat(Object
.keys(V
.LANCER_DIRS
));
42 const piece
= this.board
[i
][j
].charAt(1);
43 // Special lancer case: 8 possible orientations
44 if (Object
.keys(V
.LANCER_DIRS
).includes(piece
)) return V
.LANCER
;
48 getPpath(b
, color
, score
, orientation
) {
49 if ([V
.JAILER
, V
.SENTRY
].includes(b
[1])) return "Eightpieces/tmp_png/" + b
;
50 if (Object
.keys(V
.LANCER_DIRS
).includes(b
[1])) {
51 if (orientation
== 'w') return "Eightpieces/tmp_png/" + b
;
52 // Find opposite direction for adequate display:
80 return "Eightpieces/tmp_png/" + b
[0] + oppDir
;
82 // TODO: after we have SVG pieces, remove the folder and next prefix:
83 return "Eightpieces/tmp_png/" + b
;
86 getPPpath(m
, orientation
) {
89 m
.appear
[0].c
+ m
.appear
[0].p
,
97 static ParseFen(fen
) {
98 const fenParts
= fen
.split(" ");
100 ChessRules
.ParseFen(fen
),
101 { sentrypush: fenParts
[5] }
105 static IsGoodFen(fen
) {
106 if (!ChessRules
.IsGoodFen(fen
)) return false;
107 const fenParsed
= V
.ParseFen(fen
);
108 // 5) Check sentry push (if any)
110 fenParsed
.sentrypush
!= "-" &&
111 !fenParsed
.sentrypush
.match(/^([a-h][1-8]){2,2}$/)
119 return super.getFen() + " " + this.getSentrypushFen();
123 return super.getFenForRepeat() + "_" + this.getSentrypushFen();
127 const L
= this.sentryPush
.length
;
128 if (!this.sentryPush
[L
-1]) return "-";
130 const spL
= this.sentryPush
[L
-1].length
;
131 // Condensate path: just need initial and final squares:
133 .map(i
=> V
.CoordsToSquare(this.sentryPush
[L
-1][i
]))
137 setOtherVariables(fen
) {
138 super.setOtherVariables(fen
);
139 // subTurn == 2 only when a sentry moved, and is about to push something
141 // Sentry position just after a "capture" (subTurn from 1 to 2)
142 this.sentryPos
= null;
143 // Stack pieces' forbidden squares after a sentry move at each turn
144 const parsedFen
= V
.ParseFen(fen
);
145 if (parsedFen
.sentrypush
== "-") this.sentryPush
= [null];
147 // Expand init + dest squares into a full path:
148 const init
= V
.SquareToCoords(parsedFen
.sentrypush
.substr(0, 2)),
149 dest
= V
.SquareToCoords(parsedFen
.sentrypush
.substr(2));
150 let newPath
= [init
];
151 const delta
= ['x', 'y'].map(i
=> Math
.abs(dest
[i
] - init
[i
]));
152 // Check that it's not a knight movement:
153 if (delta
[0] == 0 || delta
[1] == 0 || delta
[0] == delta
[1]) {
154 const step
= ['x', 'y'].map((i
, idx
) => {
155 return (dest
[i
] - init
[i
]) / delta
[idx
] || 0
157 let x
= init
.x
+ step
[0],
158 y
= init
.y
+ step
[1];
159 while (x
!= dest
.x
|| y
!= dest
.y
) {
160 newPath
.push({ x: x
, y: y
});
166 this.sentryPush
= [newPath
];
170 static GenRandInitFen(randomness
) {
173 return "jfsqkbnr/pppppppp/8/8/8/8/PPPPPPPP/JDSQKBNR w 0 ahah - -";
175 let pieces
= { w: new Array(8), b: new Array(8) };
177 // Shuffle pieces on first (and last rank if randomness == 2)
178 for (let c
of ["w", "b"]) {
179 if (c
== 'b' && randomness
== 1) {
180 const lancerIdx
= pieces
['w'].findIndex(p
=> {
181 return Object
.keys(V
.LANCER_DIRS
).includes(p
);
184 pieces
['w'].slice(0, lancerIdx
)
186 .concat(pieces
['w'].slice(lancerIdx
+ 1));
191 let positions
= ArrayFun
.range(8);
193 // Get random squares for bishop and sentry
194 let randIndex
= 2 * randInt(4);
195 let bishopPos
= positions
[randIndex
];
196 // The sentry must be on a square of different color
197 let randIndex_tmp
= 2 * randInt(4) + 1;
198 let sentryPos
= positions
[randIndex_tmp
];
200 // Check if white sentry is on the same color as ours.
201 // If yes: swap bishop and sentry positions.
202 // NOTE: test % 2 == 1 because there are 7 slashes.
203 if ((pieces
['w'].indexOf('s') - sentryPos
) % 2 == 1)
204 [bishopPos
, sentryPos
] = [sentryPos
, bishopPos
];
206 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
207 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
209 // Get random squares for knight and lancer
210 randIndex
= randInt(6);
211 const knightPos
= positions
[randIndex
];
212 positions
.splice(randIndex
, 1);
213 randIndex
= randInt(5);
214 const lancerPos
= positions
[randIndex
];
215 positions
.splice(randIndex
, 1);
217 // Get random square for queen
218 randIndex
= randInt(4);
219 const queenPos
= positions
[randIndex
];
220 positions
.splice(randIndex
, 1);
222 // Rook, jailer and king positions are now almost fixed,
223 // only the ordering rook->jailer or jailer->rook must be decided.
224 let rookPos
= positions
[0];
225 let jailerPos
= positions
[2];
226 const kingPos
= positions
[1];
227 flags
+= V
.CoordToColumn(rookPos
) + V
.CoordToColumn(jailerPos
);
228 if (Math
.random() < 0.5) [rookPos
, jailerPos
] = [jailerPos
, rookPos
];
230 pieces
[c
][rookPos
] = "r";
231 pieces
[c
][knightPos
] = "n";
232 pieces
[c
][bishopPos
] = "b";
233 pieces
[c
][queenPos
] = "q";
234 pieces
[c
][kingPos
] = "k";
235 pieces
[c
][sentryPos
] = "s";
236 // Lancer faces north for white, and south for black:
237 pieces
[c
][lancerPos
] = c
== 'w' ? 'c' : 'g';
238 pieces
[c
][jailerPos
] = "j";
241 pieces
["b"].join("") +
242 "/pppppppp/8/8/8/8/PPPPPPPP/" +
243 pieces
["w"].join("").toUpperCase() +
244 " w 0 " + flags
+ " - -"
248 canTake([x1
, y1
], [x2
, y2
]) {
249 if (this.subTurn
== 2)
250 // Only self captures on this subturn:
251 return this.getColor(x1
, y1
) == this.getColor(x2
, y2
);
252 return super.canTake([x1
, y1
], [x2
, y2
]);
255 // Is piece on square (x,y) immobilized?
256 isImmobilized([x
, y
]) {
257 const color
= this.getColor(x
, y
);
258 const oppCol
= V
.GetOppCol(color
);
259 for (let step
of V
.steps
[V
.ROOK
]) {
260 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
263 this.board
[i
][j
] != V
.EMPTY
&&
264 this.getColor(i
, j
) == oppCol
266 if (this.getPiece(i
, j
) == V
.JAILER
) return [i
, j
];
272 // Because of the lancers, getPiece() could be wrong:
273 // use board[x][y][1] instead (always valid).
274 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
275 const initColor
= this.getColor(sx
, sy
);
276 const initPiece
= this.board
[sx
][sy
].charAt(1);
282 c: tr
? tr
.c : initColor
,
283 p: tr
? tr
.p : initPiece
296 // The opponent piece disappears if we take it
297 if (this.board
[ex
][ey
] != V
.EMPTY
) {
302 c: this.getColor(ex
, ey
),
303 p: this.board
[ex
][ey
].charAt(1)
311 canIplay(side
, [x
, y
]) {
313 (this.subTurn
== 1 && this.turn
== side
&& this.getColor(x
, y
) == side
)
315 (this.subTurn
== 2 && x
== this.sentryPos
.x
&& y
== this.sentryPos
.y
)
319 getPotentialMovesFrom([x
, y
]) {
320 const piece
= this.getPiece(x
, y
);
321 const L
= this.sentryPush
.length
;
322 // At subTurn == 2, jailers aren't effective (Jeff K)
323 if (this.subTurn
== 1) {
324 const jsq
= this.isImmobilized([x
, y
]);
327 // Special pass move if king:
328 if (piece
== V
.KING
) {
333 start: { x: x
, y: y
},
334 end: { x: jsq
[0], y: jsq
[1] }
338 else if (piece
== V
.LANCER
&& !!this.sentryPush
[L
-1]) {
339 // A pushed lancer next to the jailer: reorient
340 const color
= this.getColor(x
, y
);
341 const curDir
= this.board
[x
][y
].charAt(1);
342 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
345 appear: [{ x: x
, y: y
, c: color
, p: k
}],
346 vanish: [{ x: x
, y: y
, c: color
, p: curDir
}],
347 start: { x: x
, y: y
},
348 end: { x: jsq
[0], y: jsq
[1] }
359 moves
= this.getPotentialJailerMoves([x
, y
]);
362 moves
= this.getPotentialSentryMoves([x
, y
]);
365 moves
= this.getPotentialLancerMoves([x
, y
]);
368 moves
= super.getPotentialMovesFrom([x
, y
]);
371 if (!!this.sentryPush
[L
-1]) {
372 // Delete moves walking back on sentry push path,
373 // only if not a pawn, and the piece is the pushed one.
374 const pl
= this.sentryPush
[L
-1].length
;
375 const finalPushedSq
= this.sentryPush
[L
-1][pl
-1];
376 moves
= moves
.filter(m
=> {
378 m
.vanish
[0].p
!= V
.PAWN
&&
379 m
.start
.x
== finalPushedSq
.x
&& m
.start
.y
== finalPushedSq
.y
&&
380 this.sentryPush
[L
-1].some(sq
=> sq
.x
== m
.end
.x
&& sq
.y
== m
.end
.y
)
386 } else if (this.subTurn
== 2) {
387 // Put back the sentinel on board:
388 const color
= this.turn
;
390 m
.appear
.push({x: x
, y: y
, p: V
.SENTRY
, c: color
});
396 getPotentialPawnMoves([x
, y
]) {
397 const color
= this.getColor(x
, y
);
399 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
400 let shiftX
= (color
== "w" ? -1 : 1);
401 if (this.subTurn
== 2) shiftX
*= -1;
402 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
403 const startRank
= color
== "w" ? sizeX
- 2 : 1;
404 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
406 // Pawns might be pushed on 1st rank and attempt to move again:
407 if (!V
.OnBoard(x
+ shiftX
, y
)) return [];
409 // A push cannot put a pawn on last rank (it goes backward)
410 let finalPieces
= [V
.PAWN
];
411 if (x
+ shiftX
== lastRank
) {
412 // Only allow direction facing inside board:
413 const allowedLancerDirs
=
415 ? ['e', 'f', 'g', 'h', 'm']
416 : ['c', 'd', 'e', 'm', 'o'];
419 .concat([V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.SENTRY
, V
.JAILER
]);
421 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
422 // One square forward
423 for (let piece
of finalPieces
) {
425 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
432 // 2-squares jumps forbidden if pawn push
434 [startRank
, firstRank
].includes(x
) &&
435 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
438 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
442 for (let shiftY
of [-1, 1]) {
445 y
+ shiftY
< sizeY
&&
446 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
447 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
449 for (let piece
of finalPieces
) {
451 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
460 // En passant: only on subTurn == 1
461 const Lep
= this.epSquares
.length
;
462 const epSquare
= this.epSquares
[Lep
- 1];
466 epSquare
.x
== x
+ shiftX
&&
467 Math
.abs(epSquare
.y
- y
) == 1
469 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
470 enpassantMove
.vanish
.push({
474 c: this.getColor(x
, epSquare
.y
)
476 moves
.push(enpassantMove
);
483 if (isNaN(square
[0])) return null;
484 const L
= this.sentryPush
.length
;
485 const [x
, y
] = [square
[0], square
[1]];
486 const color
= this.turn
;
489 this.board
[x
][y
] == V
.EMPTY
||
490 this.getPiece(x
, y
) != V
.LANCER
||
491 this.getColor(x
, y
) != color
||
492 !!this.sentryPush
[L
-1]
497 const orientation
= this.board
[x
][y
][1];
498 const step
= V
.LANCER_DIRS
[orientation
];
499 if (!V
.OnBoard(x
+ step
[0], y
+ step
[1])) {
501 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
502 const dir
= V
.LANCER_DIRS
[k
];
504 (dir
[0] != step
[0] || dir
[1] != step
[1]) &&
505 V
.OnBoard(x
+ dir
[0], y
+ dir
[1])
525 start: { x: x
, y : y
},
526 end: { x: -1, y: -1 }
536 // Obtain all lancer moves in "step" direction
537 getPotentialLancerMoves_aux([x
, y
], step
, tr
) {
539 // Add all moves to vacant squares until opponent is met:
540 const color
= this.getColor(x
, y
);
544 // at subTurn == 2, consider own pieces as opponent
546 let sq
= [x
+ step
[0], y
+ step
[1]];
547 while (V
.OnBoard(sq
[0], sq
[1]) && this.getColor(sq
[0], sq
[1]) != oppCol
) {
548 if (this.board
[sq
[0]][sq
[1]] == V
.EMPTY
)
549 moves
.push(this.getBasicMove([x
, y
], sq
, tr
));
553 if (V
.OnBoard(sq
[0], sq
[1]))
554 // Add capturing move
555 moves
.push(this.getBasicMove([x
, y
], sq
, tr
));
559 getPotentialLancerMoves([x
, y
]) {
561 // Add all lancer possible orientations, similar to pawn promotions.
562 // Except if just after a push: allow all movements from init square then
563 const L
= this.sentryPush
.length
;
564 const color
= this.getColor(x
, y
);
565 const dirCode
= this.board
[x
][y
][1];
566 const curDir
= V
.LANCER_DIRS
[dirCode
];
567 if (!!this.sentryPush
[L
-1]) {
568 // Maybe I was pushed
569 const pl
= this.sentryPush
[L
-1].length
;
571 this.sentryPush
[L
-1][pl
-1].x
== x
&&
572 this.sentryPush
[L
-1][pl
-1].y
== y
574 // I was pushed: allow all directions (for this move only), but
575 // do not change direction after moving, *except* if I keep the
576 // same orientation in which I was pushed.
577 // Also allow simple reorientation ("capturing king"):
578 if (!V
.OnBoard(x
+ curDir
[0], y
+ curDir
[1])) {
579 const kp
= this.kingPos
[color
];
580 let reorientMoves
= [];
581 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
582 const dir
= V
.LANCER_DIRS
[k
];
584 (dir
[0] != curDir
[0] || dir
[1] != curDir
[1]) &&
585 V
.OnBoard(x
+ dir
[0], y
+ dir
[1])
605 start: { x: x
, y : y
},
606 end: { x: kp
[0], y: kp
[1] }
611 Array
.prototype.push
.apply(moves
, reorientMoves
);
613 Object
.values(V
.LANCER_DIRS
).forEach(step
=> {
614 const dirCode
= Object
.keys(V
.LANCER_DIRS
).find(k
=> {
616 V
.LANCER_DIRS
[k
][0] == step
[0] &&
617 V
.LANCER_DIRS
[k
][1] == step
[1]
621 this.getPotentialLancerMoves_aux(
624 { p: dirCode
, c: color
}
626 if (curDir
[0] == step
[0] && curDir
[1] == step
[1]) {
627 // Keeping same orientation: can choose after
628 let chooseMoves
= [];
629 dirMoves
.forEach(m
=> {
630 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
631 const newDir
= V
.LANCER_DIRS
[k
];
632 // Prevent orientations toward outer board:
633 if (V
.OnBoard(m
.end
.x
+ newDir
[0], m
.end
.y
+ newDir
[1])) {
634 let mk
= JSON
.parse(JSON
.stringify(m
));
636 chooseMoves
.push(mk
);
640 Array
.prototype.push
.apply(moves
, chooseMoves
);
642 else Array
.prototype.push
.apply(moves
, dirMoves
);
647 // I wasn't pushed: standard lancer move
649 this.getPotentialLancerMoves_aux([x
, y
], V
.LANCER_DIRS
[dirCode
]);
650 // Add all possible orientations aftermove except if I'm being pushed
651 if (this.subTurn
== 1) {
652 monodirMoves
.forEach(m
=> {
653 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
654 const newDir
= V
.LANCER_DIRS
[k
];
655 // Prevent orientations toward outer board:
656 if (V
.OnBoard(m
.end
.x
+ newDir
[0], m
.end
.y
+ newDir
[1])) {
657 let mk
= JSON
.parse(JSON
.stringify(m
));
666 // I'm pushed: add potential nudges, except for current orientation
667 let potentialNudges
= [];
668 for (let step
of V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])) {
670 (step
[0] != curDir
[0] || step
[1] != curDir
[1]) &&
671 V
.OnBoard(x
+ step
[0], y
+ step
[1]) &&
672 this.board
[x
+ step
[0]][y
+ step
[1]] == V
.EMPTY
674 const newDirCode
= Object
.keys(V
.LANCER_DIRS
).find(k
=> {
675 const codeStep
= V
.LANCER_DIRS
[k
];
676 return (codeStep
[0] == step
[0] && codeStep
[1] == step
[1]);
678 potentialNudges
.push(
681 [x
+ step
[0], y
+ step
[1]],
682 { c: color
, p: newDirCode
}
687 return monodirMoves
.concat(potentialNudges
);
691 getPotentialSentryMoves([x
, y
]) {
692 // The sentry moves a priori like a bishop:
693 let moves
= super.getPotentialBishopMoves([x
, y
]);
694 // ...but captures are replaced by special move, if and only if
695 // "captured" piece can move now, considered as the capturer unit.
696 // --> except is subTurn == 2, in this case I don't push anything.
697 if (this.subTurn
== 2) return moves
.filter(m
=> m
.vanish
.length
== 1);
699 if (m
.vanish
.length
== 2) {
700 // Temporarily cancel the sentry capture:
705 const color
= this.getColor(x
, y
);
706 const fMoves
= moves
.filter(m
=> {
707 // Can the pushed unit make any move? ...resulting in a non-self-check?
708 if (m
.appear
.length
== 0) {
711 let moves2
= this.getPotentialMovesFrom([m
.end
.x
, m
.end
.y
]);
712 for (let m2
of moves2
) {
714 res
= !this.underCheck(color
);
726 getPotentialJailerMoves([x
, y
]) {
727 return super.getPotentialRookMoves([x
, y
]).filter(m
=> {
728 // Remove jailer captures
729 return m
.vanish
[0].p
!= V
.JAILER
|| m
.vanish
.length
== 1;
733 getPotentialKingMoves(sq
) {
734 const moves
= this.getSlideNJumpMoves(
736 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
741 ? moves
.concat(this.getCastleMoves(sq
))
747 // If in second-half of a move, we already know that a move is possible
748 if (this.subTurn
== 2) return true;
749 return super.atLeastOneMove();
753 if (moves
.length
== 0) return [];
754 const basicFilter
= (m
, c
) => {
756 const res
= !this.underCheck(c
);
760 // Disable check tests for sentry pushes,
761 // because in this case the move isn't finished
762 let movesWithoutSentryPushes
= [];
763 let movesWithSentryPushes
= [];
765 // Second condition below for special king "pass" moves
766 if (m
.appear
.length
> 0 || m
.vanish
.length
== 0)
767 movesWithoutSentryPushes
.push(m
);
768 else movesWithSentryPushes
.push(m
);
770 const color
= this.turn
;
771 const oppCol
= V
.GetOppCol(color
);
772 const filteredMoves
=
773 movesWithoutSentryPushes
.filter(m
=> basicFilter(m
, color
));
774 // If at least one full move made, everything is allowed.
775 // Else: forbid checks and captures.
779 : filteredMoves
.filter(m
=> {
780 return (m
.vanish
.length
<= 1 && basicFilter(m
, oppCol
));
782 ).concat(movesWithSentryPushes
);
786 if (this.subTurn
== 1) return super.getAllValidMoves();
788 const sentrySq
= [this.sentryPos
.x
, this.sentryPos
.y
];
789 return this.filterValid(this.getPotentialMovesFrom(sentrySq
));
792 isAttacked(sq
, color
) {
794 super.isAttacked(sq
, color
) ||
795 this.isAttackedByLancer(sq
, color
) ||
796 this.isAttackedBySentry(sq
, color
)
797 // The jailer doesn't capture.
801 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
802 for (let step
of steps
) {
803 let rx
= x
+ step
[0],
805 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
811 this.getPiece(rx
, ry
) == piece
&&
812 this.getColor(rx
, ry
) == color
&&
813 !this.isImmobilized([rx
, ry
])
821 isAttackedByPawn([x
, y
], color
) {
822 const pawnShift
= (color
== "w" ? 1 : -1);
823 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
824 for (let i
of [-1, 1]) {
828 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
829 this.getColor(x
+ pawnShift
, y
+ i
) == color
&&
830 !this.isImmobilized([x
+ pawnShift
, y
+ i
])
839 isAttackedByLancer([x
, y
], color
) {
840 for (let step
of V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])) {
841 // If in this direction there are only enemy pieces and empty squares,
842 // and we meet a lancer: can he reach us?
843 // NOTE: do not stop at first lancer, there might be several!
844 let coord
= { x: x
+ step
[0], y: y
+ step
[1] };
847 V
.OnBoard(coord
.x
, coord
.y
) &&
849 this.board
[coord
.x
][coord
.y
] == V
.EMPTY
||
850 this.getColor(coord
.x
, coord
.y
) == color
854 this.getPiece(coord
.x
, coord
.y
) == V
.LANCER
&&
855 !this.isImmobilized([coord
.x
, coord
.y
])
857 lancerPos
.push({x: coord
.x
, y: coord
.y
});
862 const L
= this.sentryPush
.length
;
863 const pl
= (!!this.sentryPush
[L
-1] ? this.sentryPush
[L
-1].length : 0);
864 for (let xy
of lancerPos
) {
865 const dir
= V
.LANCER_DIRS
[this.board
[xy
.x
][xy
.y
].charAt(1)];
867 (dir
[0] == -step
[0] && dir
[1] == -step
[1]) ||
868 // If the lancer was just pushed, this is an attack too:
870 !!this.sentryPush
[L
-1] &&
871 this.sentryPush
[L
-1][pl
-1].x
== xy
.x
&&
872 this.sentryPush
[L
-1][pl
-1].y
== xy
.y
882 // Helper to check sentries attacks:
883 selfAttack([x1
, y1
], [x2
, y2
]) {
884 const color
= this.getColor(x1
, y1
);
885 const oppCol
= V
.GetOppCol(color
);
886 const sliderAttack
= (allowedSteps
, lancer
) => {
887 const deltaX
= x2
- x1
,
888 absDeltaX
= Math
.abs(deltaX
);
889 const deltaY
= y2
- y1
,
890 absDeltaY
= Math
.abs(deltaY
);
891 const step
= [ deltaX
/ absDeltaX
|| 0, deltaY
/ absDeltaY
|| 0 ];
893 // Check that the step is a priori valid:
894 (absDeltaX
!= absDeltaY
&& deltaX
!= 0 && deltaY
!= 0) ||
895 allowedSteps
.every(st
=> st
[0] != step
[0] || st
[1] != step
[1])
899 let sq
= [ x1
+ step
[0], y1
+ step
[1] ];
900 while (sq
[0] != x2
|| sq
[1] != y2
) {
902 // NOTE: no need to check OnBoard in this special case
903 (!lancer
&& this.board
[sq
[0]][sq
[1]] != V
.EMPTY
) ||
904 (!!lancer
&& this.getColor(sq
[0], sq
[1]) == oppCol
)
913 switch (this.getPiece(x1
, y1
)) {
915 // Pushed pawns move as enemy pawns
916 const shift
= (color
== 'w' ? 1 : -1);
917 return (x1
+ shift
== x2
&& Math
.abs(y1
- y2
) == 1);
920 const deltaX
= Math
.abs(x1
- x2
);
921 const deltaY
= Math
.abs(y1
- y2
);
923 deltaX
+ deltaY
== 3 &&
924 [1, 2].includes(deltaX
) &&
925 [1, 2].includes(deltaY
)
929 return sliderAttack(V
.steps
[V
.ROOK
]);
931 return sliderAttack(V
.steps
[V
.BISHOP
]);
933 return sliderAttack(V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
935 // Special case: as long as no enemy units stands in-between,
936 // it attacks (if it points toward the king).
937 const allowedStep
= V
.LANCER_DIRS
[this.board
[x1
][y1
].charAt(1)];
938 return sliderAttack([allowedStep
], "lancer");
940 // No sentries or jailer tests: they cannot self-capture
945 isAttackedBySentry([x
, y
], color
) {
946 // Attacked by sentry means it can self-take our king.
947 // Just check diagonals of enemy sentry(ies), and if it reaches
948 // one of our pieces: can I self-take?
949 const myColor
= V
.GetOppCol(color
);
951 for (let i
=0; i
<V
.size
.x
; i
++) {
952 for (let j
=0; j
<V
.size
.y
; j
++) {
954 this.getPiece(i
,j
) == V
.SENTRY
&&
955 this.getColor(i
,j
) == color
&&
956 !this.isImmobilized([i
, j
])
958 for (let step
of V
.steps
[V
.BISHOP
]) {
959 let sq
= [ i
+ step
[0], j
+ step
[1] ];
961 V
.OnBoard(sq
[0], sq
[1]) &&
962 this.board
[sq
[0]][sq
[1]] == V
.EMPTY
968 V
.OnBoard(sq
[0], sq
[1]) &&
969 this.getColor(sq
[0], sq
[1]) == myColor
971 candidates
.push([ sq
[0], sq
[1] ]);
977 for (let c
of candidates
)
978 if (this.selfAttack(c
, [x
, y
])) return true;
982 // Jailer doesn't capture or give check
985 if (move.appear
.length
== 0 && move.vanish
.length
== 1)
986 // The sentry is about to push a piece: subTurn goes from 1 to 2
987 this.sentryPos
= { x: move.end
.x
, y: move.end
.y
};
988 if (this.subTurn
== 2 && move.vanish
[0].p
!= V
.PAWN
) {
989 // A piece is pushed: forbid array of squares between start and end
990 // of move, included (except if it's a pawn)
992 if ([V
.KNIGHT
,V
.KING
].includes(move.vanish
[0].p
))
993 // short-range pieces: just forbid initial square
994 squares
.push({ x: move.start
.x
, y: move.start
.y
});
996 const deltaX
= move.end
.x
- move.start
.x
;
997 const deltaY
= move.end
.y
- move.start
.y
;
999 deltaX
/ Math
.abs(deltaX
) || 0,
1000 deltaY
/ Math
.abs(deltaY
) || 0
1003 let sq
= {x: move.start
.x
, y: move.start
.y
};
1004 sq
.x
!= move.end
.x
|| sq
.y
!= move.end
.y
;
1005 sq
.x
+= step
[0], sq
.y
+= step
[1]
1007 squares
.push({ x: sq
.x
, y: sq
.y
});
1010 // Add end square as well, to know if I was pushed (useful for lancers)
1011 squares
.push({ x: move.end
.x
, y: move.end
.y
});
1012 this.sentryPush
.push(squares
);
1013 } else this.sentryPush
.push(null);
1018 move.flags
= JSON
.stringify(this.aggregateFlags());
1019 this.epSquares
.push(this.getEpSquare(move));
1020 V
.PlayOnBoard(this.board
, move);
1021 // Is it a sentry push? (useful for undo)
1022 move.sentryPush
= (this.subTurn
== 2);
1023 if (this.subTurn
== 1) this.movesCount
++;
1024 if (move.appear
.length
== 0 && move.vanish
.length
== 1) this.subTurn
= 2;
1026 // Turn changes only if not a sentry "pre-push"
1027 this.turn
= V
.GetOppCol(this.turn
);
1030 this.postPlay(move);
1034 if (move.vanish
.length
== 0 || this.subTurn
== 2)
1035 // Special pass move of the king, or sentry pre-push: nothing to update
1037 const c
= move.vanish
[0].c
;
1038 const piece
= move.vanish
[0].p
;
1039 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
1041 if (piece
== V
.KING
) {
1042 this.kingPos
[c
][0] = move.appear
[0].x
;
1043 this.kingPos
[c
][1] = move.appear
[0].y
;
1044 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
1047 // Update castling flags if rooks are moved
1048 const oppCol
= V
.GetOppCol(c
);
1049 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
1051 move.start
.x
== firstRank
&& //our rook moves?
1052 this.castleFlags
[c
].includes(move.start
.y
)
1054 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
1055 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
1057 move.end
.x
== oppFirstRank
&& //we took opponent rook?
1058 this.castleFlags
[oppCol
].includes(move.end
.y
)
1060 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
1061 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
1066 this.epSquares
.pop();
1067 this.disaggregateFlags(JSON
.parse(move.flags
));
1068 V
.UndoOnBoard(this.board
, move);
1069 // Decrement movesCount except if the move is a sentry push
1070 if (!move.sentryPush
) this.movesCount
--;
1071 if (this.subTurn
== 2) this.subTurn
= 1;
1073 this.turn
= V
.GetOppCol(this.turn
);
1074 if (move.sentryPush
) this.subTurn
= 2;
1076 this.postUndo(move);
1080 super.postUndo(move);
1081 this.sentryPush
.pop();
1084 static get VALUES() {
1085 return Object
.assign(
1086 { l: 4.8, s: 2.8, j: 3.8 }, //Jeff K. estimations
1092 const maxeval
= V
.INFINITY
;
1093 const color
= this.turn
;
1094 let moves1
= this.getAllValidMoves();
1096 if (moves1
.length
== 0)
1097 // TODO: this situation should not happen
1100 const setEval
= (move, next
) => {
1101 const score
= this.getCurrentScore();
1102 const curEval
= move.eval
;
1107 : (score
== "1-0" ? 1 : -1) * maxeval
;
1108 } else move.eval
= this.evalPosition();
1110 // "next" is defined after sentry pushes
1113 color
== 'w' && move.eval
> curEval
||
1114 color
== 'b' && move.eval
< curEval
1121 // Just search_depth == 1 (because of sentries. TODO: can do better...)
1122 moves1
.forEach(m1
=> {
1124 if (this.subTurn
== 1) setEval(m1
);
1126 // Need to play every pushes and count:
1127 const moves2
= this.getAllValidMoves();
1128 moves2
.forEach(m2
=> {
1137 moves1
.sort((a
, b
) => {
1138 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1140 let candidates
= [0];
1141 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1143 const choice
= moves1
[candidates
[randInt(candidates
.length
)]];
1144 return (!choice
.second
? choice : [choice
, choice
.second
]);
1147 // For moves notation:
1148 static get LANCER_DIRNAMES() {
1162 // Special case "king takes jailer" is a pass move
1163 if (move.appear
.length
== 0 && move.vanish
.length
== 0) return "pass";
1164 let notation
= undefined;
1165 if (this.subTurn
== 2) {
1166 // Do not consider appear[1] (sentry) for sentry pushes
1167 const simpleMove
= {
1168 appear: [move.appear
[0]],
1169 vanish: move.vanish
,
1173 notation
= super.getNotation(simpleMove
);
1176 move.appear
.length
> 0 &&
1177 move.vanish
[0].x
== move.appear
[0].x
&&
1178 move.vanish
[0].y
== move.appear
[0].y
1180 // Lancer in-place reorientation:
1181 notation
= "L" + V
.CoordsToSquare(move.start
) + ":R";
1183 else notation
= super.getNotation(move);
1184 if (Object
.keys(V
.LANCER_DIRNAMES
).includes(move.vanish
[0].p
))
1185 // Lancer: add direction info
1186 notation
+= "=" + V
.LANCER_DIRNAMES
[move.appear
[0].p
];
1188 move.vanish
[0].p
== V
.PAWN
&&
1189 Object
.keys(V
.LANCER_DIRNAMES
).includes(move.appear
[0].p
)
1191 // Fix promotions in lancer:
1192 notation
= notation
.slice(0, -1) +
1193 "L:" + V
.LANCER_DIRNAMES
[move.appear
[0].p
];