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(b
, orientation
) {
87 return this.getPpath(b
, null, null, orientation
);
90 static ParseFen(fen
) {
91 const fenParts
= fen
.split(" ");
93 ChessRules
.ParseFen(fen
),
94 { sentrypush: fenParts
[5] }
98 static IsGoodFen(fen
) {
99 if (!ChessRules
.IsGoodFen(fen
)) return false;
100 const fenParsed
= V
.ParseFen(fen
);
101 // 5) Check sentry push (if any)
103 fenParsed
.sentrypush
!= "-" &&
104 !fenParsed
.sentrypush
.match(/^([a-h][1-8],?)+$/)
112 return super.getFen() + " " + this.getSentrypushFen();
116 return super.getFenForRepeat() + "_" + this.getSentrypushFen();
120 const L
= this.sentryPush
.length
;
121 if (!this.sentryPush
[L
-1]) return "-";
123 this.sentryPush
[L
-1].forEach(coords
=>
124 res
+= V
.CoordsToSquare(coords
) + ",");
125 return res
.slice(0, -1);
128 setOtherVariables(fen
) {
129 super.setOtherVariables(fen
);
130 // subTurn == 2 only when a sentry moved, and is about to push something
132 // Sentry position just after a "capture" (subTurn from 1 to 2)
133 this.sentryPos
= null;
134 // Stack pieces' forbidden squares after a sentry move at each turn
135 const parsedFen
= V
.ParseFen(fen
);
136 if (parsedFen
.sentrypush
== "-") this.sentryPush
= [null];
139 parsedFen
.sentrypush
.split(",").map(sq
=> {
140 return V
.SquareToCoords(sq
);
146 static GenRandInitFen(randomness
) {
149 return "jsfqkbnr/pppppppp/8/8/8/8/PPPPPPPP/JSDQKBNR w 0 ahah - -";
151 let pieces
= { w: new Array(8), b: new Array(8) };
153 // Shuffle pieces on first (and last rank if randomness == 2)
154 for (let c
of ["w", "b"]) {
155 if (c
== 'b' && randomness
== 1) {
156 const lancerIdx
= pieces
['w'].findIndex(p
=> {
157 return Object
.keys(V
.LANCER_DIRS
).includes(p
);
160 pieces
['w'].slice(0, lancerIdx
)
162 .concat(pieces
['w'].slice(lancerIdx
+ 1));
167 let positions
= ArrayFun
.range(8);
169 // Get random squares for bishop and sentry
170 let randIndex
= 2 * randInt(4);
171 let bishopPos
= positions
[randIndex
];
172 // The sentry must be on a square of different color
173 let randIndex_tmp
= 2 * randInt(4) + 1;
174 let sentryPos
= positions
[randIndex_tmp
];
176 // Check if white sentry is on the same color as ours.
177 // If yes: swap bishop and sentry positions.
178 if ((pieces
['w'].indexOf('s') - sentryPos
) % 2 == 0)
179 [bishopPos
, sentryPos
] = [sentryPos
, bishopPos
];
181 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
182 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
184 // Get random squares for knight and lancer
185 randIndex
= randInt(6);
186 const knightPos
= positions
[randIndex
];
187 positions
.splice(randIndex
, 1);
188 randIndex
= randInt(5);
189 const lancerPos
= positions
[randIndex
];
190 positions
.splice(randIndex
, 1);
192 // Get random square for queen
193 randIndex
= randInt(4);
194 const queenPos
= positions
[randIndex
];
195 positions
.splice(randIndex
, 1);
197 // Rook, jailer and king positions are now almost fixed,
198 // only the ordering rook-> jailer or jailer->rook must be decided.
199 let rookPos
= positions
[0];
200 let jailerPos
= positions
[2];
201 const kingPos
= positions
[1];
202 flags
+= V
.CoordToColumn(rookPos
) + V
.CoordToColumn(jailerPos
);
203 if (Math
.random() < 0.5) [rookPos
, jailerPos
] = [jailerPos
, rookPos
];
205 pieces
[c
][rookPos
] = "r";
206 pieces
[c
][knightPos
] = "n";
207 pieces
[c
][bishopPos
] = "b";
208 pieces
[c
][queenPos
] = "q";
209 pieces
[c
][kingPos
] = "k";
210 pieces
[c
][sentryPos
] = "s";
211 // Lancer faces north for white, and south for black:
212 pieces
[c
][lancerPos
] = c
== 'w' ? 'c' : 'g';
213 pieces
[c
][jailerPos
] = "j";
216 pieces
["b"].join("") +
217 "/pppppppp/8/8/8/8/PPPPPPPP/" +
218 pieces
["w"].join("").toUpperCase() +
219 " w 0 " + flags
+ " - -"
223 canTake([x1
, y1
], [x2
, y2
]) {
224 if (this.subTurn
== 2)
225 // Only self captures on this subturn:
226 return this.getColor(x1
, y1
) == this.getColor(x2
, y2
);
227 return super.canTake([x1
, y1
], [x2
, y2
]);
230 // Is piece on square (x,y) immobilized?
231 isImmobilized([x
, y
]) {
232 const color
= this.getColor(x
, y
);
233 const oppCol
= V
.GetOppCol(color
);
234 for (let step
of V
.steps
[V
.ROOK
]) {
235 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
238 this.board
[i
][j
] != V
.EMPTY
&&
239 this.getColor(i
, j
) == oppCol
241 if (this.getPiece(i
, j
) == V
.JAILER
) return [i
, j
];
247 // Because of the lancers, getPiece() could be wrong:
248 // use board[x][y][1] instead (always valid).
249 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
250 const initColor
= this.getColor(sx
, sy
);
251 const initPiece
= this.board
[sx
][sy
].charAt(1);
257 c: tr
? tr
.c : initColor
,
258 p: tr
? tr
.p : initPiece
271 // The opponent piece disappears if we take it
272 if (this.board
[ex
][ey
] != V
.EMPTY
) {
277 c: this.getColor(ex
, ey
),
278 p: this.board
[ex
][ey
].charAt(1)
286 canIplay(side
, [x
, y
]) {
288 (this.subTurn
== 1 && this.turn
== side
&& this.getColor(x
, y
) == side
) ||
289 (this.subTurn
== 2 && x
== this.sentryPos
.x
&& y
== this.sentryPos
.y
)
293 getPotentialMovesFrom([x
, y
]) {
294 // At subTurn == 2, jailers aren't effective (Jeff K)
295 const piece
= this.getPiece(x
, y
);
296 const L
= this.sentryPush
.length
;
297 if (this.subTurn
== 1) {
298 const jsq
= this.isImmobilized([x
, y
]);
301 // Special pass move if king:
302 if (piece
== V
.KING
) {
307 start: { x: x
, y: y
},
308 end: { x: jsq
[0], y: jsq
[1] }
312 else if (piece
== V
.LANCER
&& !!this.sentryPush
[L
-1]) {
313 // A pushed lancer next to the jailer: reorient
314 const color
= this.getColor(x
, y
);
315 const curDir
= this.board
[x
][y
].charAt(1);
316 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
319 appear: [{ x: x
, y: y
, c: color
, p: k
}],
320 vanish: [{ x: x
, y: y
, c: color
, p: curDir
}],
321 start: { x: x
, y: y
},
322 end: { x: jsq
[0], y: jsq
[1] }
333 moves
= this.getPotentialJailerMoves([x
, y
]);
336 moves
= this.getPotentialSentryMoves([x
, y
]);
339 moves
= this.getPotentialLancerMoves([x
, y
]);
342 moves
= super.getPotentialMovesFrom([x
, y
]);
345 if (!!this.sentryPush
[L
-1]) {
346 // Delete moves walking back on sentry push path,
347 // only if not a pawn, and the piece is the pushed one.
348 const pl
= this.sentryPush
[L
-1].length
;
349 const finalPushedSq
= this.sentryPush
[L
-1][pl
-1];
350 moves
= moves
.filter(m
=> {
352 m
.vanish
[0].p
!= V
.PAWN
&&
353 m
.start
.x
== finalPushedSq
.x
&& m
.start
.y
== finalPushedSq
.y
&&
354 this.sentryPush
[L
-1].some(sq
=> sq
.x
== m
.end
.x
&& sq
.y
== m
.end
.y
)
360 } else if (this.subTurn
== 2) {
361 // Put back the sentinel on board:
362 const color
= this.turn
;
364 m
.appear
.push({x: x
, y: y
, p: V
.SENTRY
, c: color
});
370 getPotentialPawnMoves([x
, y
]) {
371 const color
= this.getColor(x
, y
);
373 const [sizeX
, sizeY
] = [V
.size
.x
, V
.size
.y
];
374 let shiftX
= (color
== "w" ? -1 : 1);
375 if (this.subTurn
== 2) shiftX
*= -1;
376 const firstRank
= color
== "w" ? sizeX
- 1 : 0;
377 const startRank
= color
== "w" ? sizeX
- 2 : 1;
378 const lastRank
= color
== "w" ? 0 : sizeX
- 1;
380 // Pawns might be pushed on 1st rank and attempt to move again:
381 if (!V
.OnBoard(x
+ shiftX
, y
)) return [];
384 // A push cannot put a pawn on last rank (it goes backward)
385 x
+ shiftX
== lastRank
386 ? Object
.keys(V
.LANCER_DIRS
).concat(
387 [V
.ROOK
, V
.KNIGHT
, V
.BISHOP
, V
.QUEEN
, V
.SENTRY
, V
.JAILER
])
389 if (this.board
[x
+ shiftX
][y
] == V
.EMPTY
) {
390 // One square forward
391 for (let piece
of finalPieces
) {
393 this.getBasicMove([x
, y
], [x
+ shiftX
, y
], {
400 // 2-squares jumps forbidden if pawn push
402 [startRank
, firstRank
].includes(x
) &&
403 this.board
[x
+ 2 * shiftX
][y
] == V
.EMPTY
406 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
410 for (let shiftY
of [-1, 1]) {
413 y
+ shiftY
< sizeY
&&
414 this.board
[x
+ shiftX
][y
+ shiftY
] != V
.EMPTY
&&
415 this.canTake([x
, y
], [x
+ shiftX
, y
+ shiftY
])
417 for (let piece
of finalPieces
) {
419 this.getBasicMove([x
, y
], [x
+ shiftX
, y
+ shiftY
], {
428 // En passant: only on subTurn == 1
429 const Lep
= this.epSquares
.length
;
430 const epSquare
= this.epSquares
[Lep
- 1];
434 epSquare
.x
== x
+ shiftX
&&
435 Math
.abs(epSquare
.y
- y
) == 1
437 let enpassantMove
= this.getBasicMove([x
, y
], [epSquare
.x
, epSquare
.y
]);
438 enpassantMove
.vanish
.push({
442 c: this.getColor(x
, epSquare
.y
)
444 moves
.push(enpassantMove
);
450 // Obtain all lancer moves in "step" direction
451 getPotentialLancerMoves_aux([x
, y
], step
, tr
) {
453 // Add all moves to vacant squares until opponent is met:
454 const color
= this.getColor(x
, y
);
458 // at subTurn == 2, consider own pieces as opponent
460 let sq
= [x
+ step
[0], y
+ step
[1]];
461 while (V
.OnBoard(sq
[0], sq
[1]) && this.getColor(sq
[0], sq
[1]) != oppCol
) {
462 if (this.board
[sq
[0]][sq
[1]] == V
.EMPTY
)
463 moves
.push(this.getBasicMove([x
, y
], sq
, tr
));
467 if (V
.OnBoard(sq
[0], sq
[1]))
468 // Add capturing move
469 moves
.push(this.getBasicMove([x
, y
], sq
, tr
));
473 getPotentialLancerMoves([x
, y
]) {
475 // Add all lancer possible orientations, similar to pawn promotions.
476 // Except if just after a push: allow all movements from init square then
477 const L
= this.sentryPush
.length
;
478 const color
= this.getColor(x
, y
);
479 if (!!this.sentryPush
[L
-1]) {
480 // Maybe I was pushed
481 const pl
= this.sentryPush
[L
-1].length
;
483 this.sentryPush
[L
-1][pl
-1].x
== x
&&
484 this.sentryPush
[L
-1][pl
-1].y
== y
486 // I was pushed: allow all directions (for this move only), but
487 // do not change direction after moving, *except* if I keep the
488 // same orientation in which I was pushed.
489 const curDir
= V
.LANCER_DIRS
[this.board
[x
][y
].charAt(1)];
490 Object
.values(V
.LANCER_DIRS
).forEach(step
=> {
491 const dirCode
= Object
.keys(V
.LANCER_DIRS
).find(k
=> {
493 V
.LANCER_DIRS
[k
][0] == step
[0] &&
494 V
.LANCER_DIRS
[k
][1] == step
[1]
498 this.getPotentialLancerMoves_aux(
501 { p: dirCode
, c: color
}
503 if (curDir
[0] == step
[0] && curDir
[1] == step
[1]) {
504 // Keeping same orientation: can choose after
505 let chooseMoves
= [];
506 dirMoves
.forEach(m
=> {
507 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
508 let mk
= JSON
.parse(JSON
.stringify(m
));
513 Array
.prototype.push
.apply(moves
, chooseMoves
);
514 } else Array
.prototype.push
.apply(moves
, dirMoves
);
519 // I wasn't pushed: standard lancer move
520 const dirCode
= this.board
[x
][y
][1];
522 this.getPotentialLancerMoves_aux([x
, y
], V
.LANCER_DIRS
[dirCode
]);
523 // Add all possible orientations aftermove except if I'm being pushed
524 if (this.subTurn
== 1) {
525 monodirMoves
.forEach(m
=> {
526 Object
.keys(V
.LANCER_DIRS
).forEach(k
=> {
527 let mk
= JSON
.parse(JSON
.stringify(m
));
534 // I'm pushed: add potential nudges
535 let potentialNudges
= [];
536 for (let step
of V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])) {
538 V
.OnBoard(x
+ step
[0], y
+ step
[1]) &&
539 this.board
[x
+ step
[0]][y
+ step
[1]] == V
.EMPTY
541 const newDirCode
= Object
.keys(V
.LANCER_DIRS
).find(k
=> {
542 const codeStep
= V
.LANCER_DIRS
[k
];
543 return (codeStep
[0] == step
[0] && codeStep
[1] == step
[1]);
545 potentialNudges
.push(
548 [x
+ step
[0], y
+ step
[1]],
549 { c: color
, p: newDirCode
}
554 return monodirMoves
.concat(potentialNudges
);
558 getPotentialSentryMoves([x
, y
]) {
559 // The sentry moves a priori like a bishop:
560 let moves
= super.getPotentialBishopMoves([x
, y
]);
561 // ...but captures are replaced by special move, if and only if
562 // "captured" piece can move now, considered as the capturer unit.
563 // --> except is subTurn == 2, in this case I don't push anything.
564 if (this.subTurn
== 2) return moves
.filter(m
=> m
.vanish
.length
== 1);
566 if (m
.vanish
.length
== 2) {
567 // Temporarily cancel the sentry capture:
572 const color
= this.getColor(x
, y
);
573 const fMoves
= moves
.filter(m
=> {
574 // Can the pushed unit make any move? ...resulting in a non-self-check?
575 if (m
.appear
.length
== 0) {
578 let moves2
= this.getPotentialMovesFrom([m
.end
.x
, m
.end
.y
]);
579 for (let m2
of moves2
) {
581 res
= !this.underCheck(color
);
593 getPotentialJailerMoves([x
, y
]) {
594 return super.getPotentialRookMoves([x
, y
]).filter(m
=> {
595 // Remove jailer captures
596 return m
.vanish
[0].p
!= V
.JAILER
|| m
.vanish
.length
== 1;
600 getPotentialKingMoves(sq
) {
601 const moves
= this.getSlideNJumpMoves(
603 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]),
608 ? moves
.concat(this.getCastleMoves(sq
))
613 // Adapted: castle with jailer possible
614 getCastleMoves([x
, y
]) {
615 const c
= this.getColor(x
, y
);
616 const firstRank
= (c
== "w" ? V
.size
.x
- 1 : 0);
617 if (x
!= firstRank
|| y
!= this.INIT_COL_KING
[c
])
620 const oppCol
= V
.GetOppCol(c
);
623 // King, then rook or jailer:
624 const finalSquares
= [
626 [V
.size
.y
- 2, V
.size
.y
- 3]
633 if (this.castleFlags
[c
][castleSide
] >= 8) continue;
634 // Rook (or jailer) and king are on initial position
635 const finDist
= finalSquares
[castleSide
][0] - y
;
636 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
640 this.isAttacked([x
, i
], oppCol
) ||
641 (this.board
[x
][i
] != V
.EMPTY
&&
642 (this.getColor(x
, i
) != c
||
643 ![V
.KING
, V
.ROOK
, V
.JAILER
].includes(this.getPiece(x
, i
))))
645 continue castlingCheck
;
648 } while (i
!= finalSquares
[castleSide
][0]);
649 step
= castleSide
== 0 ? -1 : 1;
650 const rookOrJailerPos
= this.castleFlags
[c
][castleSide
];
651 for (i
= y
+ step
; i
!= rookOrJailerPos
; i
+= step
)
652 if (this.board
[x
][i
] != V
.EMPTY
) continue castlingCheck
;
654 // Nothing on final squares, except maybe king and castling rook or jailer?
655 for (i
= 0; i
< 2; i
++) {
657 this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
658 this.getPiece(x
, finalSquares
[castleSide
][i
]) != V
.KING
&&
659 finalSquares
[castleSide
][i
] != rookOrJailerPos
661 continue castlingCheck
;
665 // If this code is reached, castle is valid
666 const castlingPiece
= this.getPiece(firstRank
, rookOrJailerPos
);
670 new PiPo({ x: x
, y: finalSquares
[castleSide
][0], p: V
.KING
, c: c
}),
671 new PiPo({ x: x
, y: finalSquares
[castleSide
][1], p: castlingPiece
, c: c
})
674 new PiPo({ x: x
, y: y
, p: V
.KING
, c: c
}),
675 new PiPo({ x: x
, y: rookOrJailerPos
, p: castlingPiece
, c: c
})
678 Math
.abs(y
- rookOrJailerPos
) <= 2
679 ? { x: x
, y: rookOrJailerPos
}
680 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
689 // If in second-half of a move, we already know that a move is possible
690 if (this.subTurn
== 2) return true;
691 return super.atLeastOneMove();
695 if (moves
.length
== 0) return [];
696 const basicFilter
= (m
, c
) => {
698 const res
= !this.underCheck(c
);
702 // Disable check tests for sentry pushes,
703 // because in this case the move isn't finished
704 let movesWithoutSentryPushes
= [];
705 let movesWithSentryPushes
= [];
707 // Second condition below for special king "pass" moves
708 if (m
.appear
.length
> 0 || m
.vanish
.length
== 0)
709 movesWithoutSentryPushes
.push(m
);
710 else movesWithSentryPushes
.push(m
);
712 const color
= this.turn
;
713 const oppCol
= V
.GetOppCol(color
);
714 const filteredMoves
=
715 movesWithoutSentryPushes
.filter(m
=> basicFilter(m
, color
));
716 // If at least one full move made, everything is allowed.
717 // Else: forbid checks and captures.
721 : filteredMoves
.filter(m
=> {
722 return (m
.vanish
.length
<= 1 && basicFilter(m
, oppCol
));
724 ).concat(movesWithSentryPushes
);
728 if (this.subTurn
== 1) return super.getAllValidMoves();
730 const sentrySq
= [this.sentryPos
.x
, this.sentryPos
.y
];
731 return this.filterValid(this.getPotentialMovesFrom(sentrySq
));
735 if (move.appear
.length
== 0 && move.vanish
.length
== 1)
736 // The sentry is about to push a piece: subTurn goes from 1 to 2
737 this.sentryPos
= { x: move.end
.x
, y: move.end
.y
};
738 if (this.subTurn
== 2 && move.vanish
[0].p
!= V
.PAWN
) {
739 // A piece is pushed: forbid array of squares between start and end
740 // of move, included (except if it's a pawn)
742 if ([V
.KNIGHT
,V
.KING
].includes(move.vanish
[0].p
))
743 // short-range pieces: just forbid initial square
744 squares
.push({ x: move.start
.x
, y: move.start
.y
});
746 const deltaX
= move.end
.x
- move.start
.x
;
747 const deltaY
= move.end
.y
- move.start
.y
;
749 deltaX
/ Math
.abs(deltaX
) || 0,
750 deltaY
/ Math
.abs(deltaY
) || 0
753 let sq
= {x: move.start
.x
, y: move.start
.y
};
754 sq
.x
!= move.end
.x
|| sq
.y
!= move.end
.y
;
755 sq
.x
+= step
[0], sq
.y
+= step
[1]
757 squares
.push({ x: sq
.x
, y: sq
.y
});
760 // Add end square as well, to know if I was pushed (useful for lancers)
761 squares
.push({ x: move.end
.x
, y: move.end
.y
});
762 this.sentryPush
.push(squares
);
763 } else this.sentryPush
.push(null);
767 // if (!this.states) this.states = [];
768 // const stateFen = this.getFen();
769 // this.states.push(stateFen);
772 move.flags
= JSON
.stringify(this.aggregateFlags());
773 this.epSquares
.push(this.getEpSquare(move));
774 V
.PlayOnBoard(this.board
, move);
775 // Is it a sentry push? (useful for undo)
776 move.sentryPush
= (this.subTurn
== 2);
777 if (this.subTurn
== 1) this.movesCount
++;
778 if (move.appear
.length
== 0 && move.vanish
.length
== 1) this.subTurn
= 2;
780 // Turn changes only if not a sentry "pre-push"
781 this.turn
= V
.GetOppCol(this.turn
);
788 if (move.vanish
.length
== 0 || this.subTurn
== 2)
789 // Special pass move of the king, or sentry pre-push: nothing to update
791 const c
= move.vanish
[0].c
;
792 const piece
= move.vanish
[0].p
;
793 const firstRank
= c
== "w" ? V
.size
.x
- 1 : 0;
795 if (piece
== V
.KING
) {
796 this.kingPos
[c
][0] = move.appear
[0].x
;
797 this.kingPos
[c
][1] = move.appear
[0].y
;
798 this.castleFlags
[c
] = [V
.size
.y
, V
.size
.y
];
801 // Update castling flags if rooks are moved
802 const oppCol
= V
.GetOppCol(c
);
803 const oppFirstRank
= V
.size
.x
- 1 - firstRank
;
805 move.start
.x
== firstRank
&& //our rook moves?
806 this.castleFlags
[c
].includes(move.start
.y
)
808 const flagIdx
= (move.start
.y
== this.castleFlags
[c
][0] ? 0 : 1);
809 this.castleFlags
[c
][flagIdx
] = V
.size
.y
;
811 move.end
.x
== oppFirstRank
&& //we took opponent rook?
812 this.castleFlags
[oppCol
].includes(move.end
.y
)
814 const flagIdx
= (move.end
.y
== this.castleFlags
[oppCol
][0] ? 0 : 1);
815 this.castleFlags
[oppCol
][flagIdx
] = V
.size
.y
;
820 this.epSquares
.pop();
821 this.disaggregateFlags(JSON
.parse(move.flags
));
822 V
.UndoOnBoard(this.board
, move);
823 // Decrement movesCount except if the move is a sentry push
824 if (!move.sentryPush
) this.movesCount
--;
825 if (this.subTurn
== 2) this.subTurn
= 1;
827 this.turn
= V
.GetOppCol(this.turn
);
828 if (move.sentryPush
) this.subTurn
= 2;
832 // const stateFen = this.getFen();
833 // if (stateFen != this.states[this.states.length-1]) debugger;
834 // this.states.pop();
838 super.postUndo(move);
839 this.sentryPush
.pop();
842 isAttacked(sq
, color
) {
844 super.isAttacked(sq
, color
) ||
845 this.isAttackedByLancer(sq
, color
) ||
846 this.isAttackedBySentry(sq
, color
)
850 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
851 for (let step
of steps
) {
852 let rx
= x
+ step
[0],
854 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
860 this.getPiece(rx
, ry
) == piece
&&
861 this.getColor(rx
, ry
) == color
&&
862 !this.isImmobilized([rx
, ry
])
870 isAttackedByPawn([x
, y
], color
) {
871 const pawnShift
= (color
== "w" ? 1 : -1);
872 if (x
+ pawnShift
>= 0 && x
+ pawnShift
< V
.size
.x
) {
873 for (let i
of [-1, 1]) {
877 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
878 this.getColor(x
+ pawnShift
, y
+ i
) == color
&&
879 !this.isImmobilized([x
+ pawnShift
, y
+ i
])
888 isAttackedByLancer([x
, y
], color
) {
889 for (let step
of V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])) {
890 // If in this direction there are only enemy pieces and empty squares,
891 // and we meet a lancer: can he reach us?
892 // NOTE: do not stop at first lancer, there might be several!
893 let coord
= { x: x
+ step
[0], y: y
+ step
[1] };
896 V
.OnBoard(coord
.x
, coord
.y
) &&
898 this.board
[coord
.x
][coord
.y
] == V
.EMPTY
||
899 this.getColor(coord
.x
, coord
.y
) == color
903 this.getPiece(coord
.x
, coord
.y
) == V
.LANCER
&&
904 !this.isImmobilized([coord
.x
, coord
.y
])
906 lancerPos
.push({x: coord
.x
, y: coord
.y
});
911 for (let xy
of lancerPos
) {
912 const dir
= V
.LANCER_DIRS
[this.board
[xy
.x
][xy
.y
].charAt(1)];
913 if (dir
[0] == -step
[0] && dir
[1] == -step
[1]) return true;
919 // Helper to check sentries attacks:
920 selfAttack([x1
, y1
], [x2
, y2
]) {
921 const color
= this.getColor(x1
, y1
);
922 const sliderAttack
= (allowedSteps
, lancer
) => {
923 const deltaX
= x2
- x1
,
924 absDeltaX
= Math
.abs(deltaX
);
925 const deltaY
= y2
- y1
,
926 absDeltaY
= Math
.abs(deltaY
);
927 const step
= [ deltaX
/ absDeltaX
|| 0, deltaY
/ absDeltaY
|| 0 ];
929 // Check that the step is a priori valid:
930 (absDeltaX
!= absDeltaY
&& deltaX
!= 0 && deltaY
!= 0) ||
931 allowedSteps
.every(st
=> st
[0] != step
[0] || st
[1] != step
[1])
935 let sq
= [ x1
+ step
[0], y1
+ step
[1] ];
936 while (sq
[0] != x2
|| sq
[1] != y2
) {
938 // NOTE: no need to check OnBoard in this special case
939 (!lancer
&& this.board
[sq
[0]][sq
[1]] != V
.EMPTY
) ||
940 (!!lancer
&& this.getColor(sq
[0], sq
[1]) != color
)
949 switch (this.getPiece(x1
, y1
)) {
951 // Pushed pawns move as enemy pawns
952 const shift
= (color
== 'w' ? 1 : -1);
953 return (x1
+ shift
== x2
&& Math
.abs(y1
- y2
) == 1);
956 const deltaX
= Math
.abs(x1
- x2
);
957 const deltaY
= Math
.abs(y1
- y2
);
959 deltaX
+ deltaY
== 3 &&
960 [1, 2].includes(deltaX
) &&
961 [1, 2].includes(deltaY
)
965 return sliderAttack(V
.steps
[V
.ROOK
]);
967 return sliderAttack(V
.steps
[V
.BISHOP
]);
969 return sliderAttack(V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
971 // Special case: as long as no enemy units stands in-between, it attacks
972 // (if it points toward the king).
973 const allowedStep
= V
.LANCER_DIRS
[this.board
[x1
][y1
].charAt(1)];
974 return sliderAttack([allowedStep
], "lancer");
976 // No sentries or jailer tests: they cannot self-capture
981 isAttackedBySentry([x
, y
], color
) {
982 // Attacked by sentry means it can self-take our king.
983 // Just check diagonals of enemy sentry(ies), and if it reaches
984 // one of our pieces: can I self-take?
985 const myColor
= V
.GetOppCol(color
);
987 for (let i
=0; i
<V
.size
.x
; i
++) {
988 for (let j
=0; j
<V
.size
.y
; j
++) {
990 this.getPiece(i
,j
) == V
.SENTRY
&&
991 this.getColor(i
,j
) == color
&&
992 !this.isImmobilized([i
, j
])
994 for (let step
of V
.steps
[V
.BISHOP
]) {
995 let sq
= [ i
+ step
[0], j
+ step
[1] ];
997 V
.OnBoard(sq
[0], sq
[1]) &&
998 this.board
[sq
[0]][sq
[1]] == V
.EMPTY
1004 V
.OnBoard(sq
[0], sq
[1]) &&
1005 this.getColor(sq
[0], sq
[1]) == myColor
1007 candidates
.push([ sq
[0], sq
[1] ]);
1013 for (let c
of candidates
)
1014 if (this.selfAttack(c
, [x
, y
])) return true;
1018 // Jailer doesn't capture or give check
1020 static get VALUES() {
1021 return Object
.assign(
1022 { l: 4.8, s: 2.8, j: 3.8 }, //Jeff K. estimations
1028 const maxeval
= V
.INFINITY
;
1029 const color
= this.turn
;
1030 let moves1
= this.getAllValidMoves();
1032 if (moves1
.length
== 0)
1033 // TODO: this situation should not happen
1036 const setEval
= (move, next
) => {
1037 const score
= this.getCurrentScore();
1038 const curEval
= move.eval
;
1043 : (score
== "1-0" ? 1 : -1) * maxeval
;
1044 } else move.eval
= this.evalPosition();
1046 // "next" is defined after sentry pushes
1049 color
== 'w' && move.eval
> curEval
||
1050 color
== 'b' && move.eval
< curEval
1057 // Just search_depth == 1 (because of sentries. TODO: can do better...)
1058 moves1
.forEach(m1
=> {
1060 if (this.subTurn
== 1) setEval(m1
);
1062 // Need to play every pushes and count:
1063 const moves2
= this.getAllValidMoves();
1064 moves2
.forEach(m2
=> {
1073 moves1
.sort((a
, b
) => {
1074 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
1076 let candidates
= [0];
1077 for (let j
= 1; j
< moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1079 const choice
= moves1
[candidates
[randInt(candidates
.length
)]];
1080 return (!choice
.second
? choice : [choice
, choice
.second
]);
1083 // For moves notation:
1084 static get LANCER_DIRNAMES() {
1098 // Special case "king takes jailer" is a pass move
1099 if (move.appear
.length
== 0 && move.vanish
.length
== 0) return "pass";
1100 let notation
= undefined;
1101 if (this.subTurn
== 2) {
1102 // Do not consider appear[1] (sentry) for sentry pushes
1103 const simpleMove
= {
1104 appear: [move.appear
[0]],
1105 vanish: move.vanish
,
1109 notation
= super.getNotation(simpleMove
);
1110 } else notation
= super.getNotation(move);
1111 if (Object
.keys(V
.LANCER_DIRNAMES
).includes(move.vanish
[0].p
))
1112 // Lancer: add direction info
1113 notation
+= "=" + V
.LANCER_DIRNAMES
[move.appear
[0].p
];