Fix forbidden captures and checks within first move for Eightpieces variant
[vchess.git] / client / src / variants / Eightpieces.js
... / ...
CommitLineData
1import { ArrayFun } from "@/utils/array";
2import { randInt } from "@/utils/alea";
3import { ChessRules, PiPo, Move } from "@/base_rules";
4
5export const VariantRules = class EightpiecesRules extends ChessRules {
6 static get JAILER() {
7 return "j";
8 }
9 static get SENTRY() {
10 return "s";
11 }
12 static get LANCER() {
13 return "l";
14 }
15
16 // Lancer directions *from white perspective*
17 static get LANCER_DIRS() {
18 return {
19 'c': [-1, 0], //north
20 'd': [-1, 1], //N-E
21 'e': [0, 1], //east
22 'f': [1, 1], //S-E
23 'g': [1, 0], //south
24 'h': [1, -1], //S-W
25 'm': [0, -1], //west
26 'o': [-1, -1] //N-W
27 };
28 }
29
30 static get PIECES() {
31 return ChessRules.PIECES
32 .concat([V.JAILER, V.SENTRY])
33 .concat(Object.keys(V.LANCER_DIRS));
34 }
35
36 getPiece(i, j) {
37 const piece = this.board[i][j].charAt(1);
38 // Special lancer case: 8 possible orientations
39 if (Object.keys(V.LANCER_DIRS).includes(piece)) return V.LANCER;
40 return piece;
41 }
42
43 getPpath(b, color, score, orientation) {
44 if ([V.JAILER, V.SENTRY].includes(b[1])) return "Eightpieces/" + b;
45 if (Object.keys(V.LANCER_DIRS).includes(b[1])) {
46 if (orientation == 'w') return "Eightpieces/" + b;
47 // Find opposite direction for adequate display:
48 let oppDir = '';
49 switch (b[1]) {
50 case 'c':
51 oppDir = 'g';
52 break;
53 case 'g':
54 oppDir = 'c';
55 break;
56 case 'd':
57 oppDir = 'h';
58 break;
59 case 'h':
60 oppDir = 'd';
61 break;
62 case 'e':
63 oppDir = 'm';
64 break;
65 case 'm':
66 oppDir = 'e';
67 break;
68 case 'f':
69 oppDir = 'o';
70 break;
71 case 'o':
72 oppDir = 'f';
73 break;
74 }
75 return "Eightpieces/" + b[0] + oppDir;
76 }
77 return b;
78 }
79
80 getPPpath(b, orientation) {
81 return this.getPpath(b, null, null, orientation);
82 }
83
84 static ParseFen(fen) {
85 const fenParts = fen.split(" ");
86 return Object.assign(
87 ChessRules.ParseFen(fen),
88 { sentrypush: fenParts[5] }
89 );
90 }
91
92 static IsGoodFen(fen) {
93 if (!ChessRules.IsGoodFen(fen)) return false;
94 const fenParsed = V.ParseFen(fen);
95 // 5) Check sentry push (if any)
96 if (
97 fenParsed.sentrypush != "-" &&
98 !fenParsed.sentrypush.match(/^([a-h][1-8],?)+$/)
99 ) {
100 return false;
101 }
102 return true;
103 }
104
105 getFen() {
106 return super.getFen() + " " + this.getSentrypushFen();
107 }
108
109 getFenForRepeat() {
110 return super.getFenForRepeat() + "_" + this.getSentrypushFen();
111 }
112
113 getSentrypushFen() {
114 const L = this.sentryPush.length;
115 if (!this.sentryPush[L-1]) return "-";
116 let res = "";
117 this.sentryPush[L-1].forEach(coords =>
118 res += V.CoordsToSquare(coords) + ",");
119 return res.slice(0, -1);
120 }
121
122 setOtherVariables(fen) {
123 super.setOtherVariables(fen);
124 // subTurn == 2 only when a sentry moved, and is about to push something
125 this.subTurn = 1;
126 // Sentry position just after a "capture" (subTurn from 1 to 2)
127 this.sentryPos = null;
128 // Stack pieces' forbidden squares after a sentry move at each turn
129 const parsedFen = V.ParseFen(fen);
130 if (parsedFen.sentrypush == "-") this.sentryPush = [null];
131 else {
132 this.sentryPush = [
133 parsedFen.sentrypush.split(",").map(sq => {
134 return V.SquareToCoords(sq);
135 })
136 ];
137 }
138 }
139
140 static GenRandInitFen(randomness) {
141 if (randomness == 0)
142 // Deterministic:
143 return "jsfqkbnr/pppppppp/8/8/8/8/PPPPPPPP/JSDQKBNR w 0 ahah - -";
144
145 let pieces = { w: new Array(8), b: new Array(8) };
146 let flags = "";
147 // Shuffle pieces on first (and last rank if randomness == 2)
148 for (let c of ["w", "b"]) {
149 if (c == 'b' && randomness == 1) {
150 const lancerIdx = pieces['w'].findIndex(p => {
151 return Object.keys(V.LANCER_DIRS).includes(p);
152 });
153 pieces['b'] =
154 pieces['w'].slice(0, lancerIdx)
155 .concat(['g'])
156 .concat(pieces['w'].slice(lancerIdx + 1));
157 flags += flags;
158 break;
159 }
160
161 let positions = ArrayFun.range(8);
162
163 // Get random squares for bishop and sentry
164 let randIndex = 2 * randInt(4);
165 let bishopPos = positions[randIndex];
166 // The sentry must be on a square of different color
167 let randIndex_tmp = 2 * randInt(4) + 1;
168 let sentryPos = positions[randIndex_tmp];
169 if (c == 'b') {
170 // Check if white sentry is on the same color as ours.
171 // If yes: swap bishop and sentry positions.
172 if ((pieces['w'].indexOf('s') - sentryPos) % 2 == 0)
173 [bishopPos, sentryPos] = [sentryPos, bishopPos];
174 }
175 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
176 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
177
178 // Get random squares for knight and lancer
179 randIndex = randInt(6);
180 const knightPos = positions[randIndex];
181 positions.splice(randIndex, 1);
182 randIndex = randInt(5);
183 const lancerPos = positions[randIndex];
184 positions.splice(randIndex, 1);
185
186 // Get random square for queen
187 randIndex = randInt(4);
188 const queenPos = positions[randIndex];
189 positions.splice(randIndex, 1);
190
191 // Rook, jailer and king positions are now almost fixed,
192 // only the ordering rook-> jailer or jailer->rook must be decided.
193 let rookPos = positions[0];
194 let jailerPos = positions[2];
195 const kingPos = positions[1];
196 flags += V.CoordToColumn(rookPos) + V.CoordToColumn(jailerPos);
197 if (Math.random() < 0.5) [rookPos, jailerPos] = [jailerPos, rookPos];
198
199 pieces[c][rookPos] = "r";
200 pieces[c][knightPos] = "n";
201 pieces[c][bishopPos] = "b";
202 pieces[c][queenPos] = "q";
203 pieces[c][kingPos] = "k";
204 pieces[c][sentryPos] = "s";
205 // Lancer faces north for white, and south for black:
206 pieces[c][lancerPos] = c == 'w' ? 'c' : 'g';
207 pieces[c][jailerPos] = "j";
208 }
209 return (
210 pieces["b"].join("") +
211 "/pppppppp/8/8/8/8/PPPPPPPP/" +
212 pieces["w"].join("").toUpperCase() +
213 " w 0 " + flags + " - -"
214 );
215 }
216
217 canTake([x1, y1], [x2, y2]) {
218 if (this.subTurn == 2)
219 // Only self captures on this subturn:
220 return this.getColor(x1, y1) == this.getColor(x2, y2);
221 return super.canTake([x1, y1], [x2, y2]);
222 }
223
224 // Is piece on square (x,y) immobilized?
225 isImmobilized([x, y]) {
226 const color = this.getColor(x, y);
227 const oppCol = V.GetOppCol(color);
228 for (let step of V.steps[V.ROOK]) {
229 const [i, j] = [x + step[0], y + step[1]];
230 if (
231 V.OnBoard(i, j) &&
232 this.board[i][j] != V.EMPTY &&
233 this.getColor(i, j) == oppCol
234 ) {
235 if (this.getPiece(i, j) == V.JAILER) return [i, j];
236 }
237 }
238 return null;
239 }
240
241 // Because of the lancers, getPiece() could be wrong:
242 // use board[x][y][1] instead (always valid).
243 getBasicMove([sx, sy], [ex, ey], tr) {
244 let mv = new Move({
245 appear: [
246 new PiPo({
247 x: ex,
248 y: ey,
249 c: tr ? tr.c : this.getColor(sx, sy),
250 p: tr ? tr.p : this.board[sx][sy].charAt(1)
251 })
252 ],
253 vanish: [
254 new PiPo({
255 x: sx,
256 y: sy,
257 c: this.getColor(sx, sy),
258 p: this.board[sx][sy].charAt(1)
259 })
260 ]
261 });
262
263 // The opponent piece disappears if we take it
264 if (this.board[ex][ey] != V.EMPTY) {
265 mv.vanish.push(
266 new PiPo({
267 x: ex,
268 y: ey,
269 c: this.getColor(ex, ey),
270 p: this.board[ex][ey].charAt(1)
271 })
272 );
273 }
274
275 return mv;
276 }
277
278 canIplay(side, [x, y]) {
279 return (
280 (this.subTurn == 1 && this.turn == side && this.getColor(x, y) == side) ||
281 (this.subTurn == 2 && x == this.sentryPos.x && y == this.sentryPos.y)
282 );
283 }
284
285 getPotentialMovesFrom([x, y]) {
286 // At subTurn == 2, jailers aren't effective (Jeff K)
287 if (this.subTurn == 1) {
288 const jsq = this.isImmobilized([x, y]);
289 if (!!jsq) {
290 let moves = [];
291 // Special pass move if king:
292 if (this.getPiece(x, y) == V.KING) {
293 moves.push(
294 new Move({
295 appear: [],
296 vanish: [],
297 start: { x: x, y: y },
298 end: { x: jsq[0], y: jsq[1] }
299 })
300 );
301 }
302 return moves;
303 }
304 }
305 let moves = [];
306 switch (this.getPiece(x, y)) {
307 case V.JAILER:
308 moves = this.getPotentialJailerMoves([x, y]);
309 break;
310 case V.SENTRY:
311 moves = this.getPotentialSentryMoves([x, y]);
312 break;
313 case V.LANCER:
314 moves = this.getPotentialLancerMoves([x, y]);
315 break;
316 default:
317 moves = super.getPotentialMovesFrom([x, y]);
318 break;
319 }
320 const L = this.sentryPush.length;
321 if (!!this.sentryPush[L-1]) {
322 // Delete moves walking back on sentry push path
323 moves = moves.filter(m => {
324 if (
325 m.vanish[0].p != V.PAWN &&
326 this.sentryPush[L-1].some(sq => sq.x == m.end.x && sq.y == m.end.y)
327 ) {
328 return false;
329 }
330 return true;
331 });
332 } else if (this.subTurn == 2) {
333 // Put back the sentinel on board:
334 const color = this.turn;
335 moves.forEach(m => {
336 m.appear.push({x: x, y: y, p: V.SENTRY, c: color});
337 });
338 }
339 return moves;
340 }
341
342 getPotentialPawnMoves([x, y]) {
343 const color = this.getColor(x, y);
344 let moves = [];
345 const [sizeX, sizeY] = [V.size.x, V.size.y];
346 let shiftX = color == "w" ? -1 : 1;
347 if (this.subTurn == 2) shiftX *= -1;
348 const startRank = color == "w" ? sizeX - 2 : 1;
349 const lastRank = color == "w" ? 0 : sizeX - 1;
350
351 // Pawns might be pushed on 1st rank and attempt to move again:
352 if (!V.OnBoard(x + shiftX, y)) return [];
353
354 const finalPieces =
355 // No promotions after pushes!
356 x + shiftX == lastRank && this.subTurn == 1
357 ?
358 Object.keys(V.LANCER_DIRS).concat(
359 [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.SENTRY, V.JAILER])
360 : [V.PAWN];
361 if (this.board[x + shiftX][y] == V.EMPTY) {
362 // One square forward
363 for (let piece of finalPieces) {
364 moves.push(
365 this.getBasicMove([x, y], [x + shiftX, y], {
366 c: color,
367 p: piece
368 })
369 );
370 }
371 if (
372 x == startRank &&
373 this.board[x + 2 * shiftX][y] == V.EMPTY
374 ) {
375 // Two squares jump
376 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
377 }
378 }
379 // Captures
380 for (let shiftY of [-1, 1]) {
381 if (
382 y + shiftY >= 0 &&
383 y + shiftY < sizeY &&
384 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
385 this.canTake([x, y], [x + shiftX, y + shiftY])
386 ) {
387 for (let piece of finalPieces) {
388 moves.push(
389 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
390 c: color,
391 p: piece
392 })
393 );
394 }
395 }
396 }
397
398 // En passant:
399 const Lep = this.epSquares.length;
400 const epSquare = this.epSquares[Lep - 1];
401 if (
402 !!epSquare &&
403 epSquare.x == x + shiftX &&
404 Math.abs(epSquare.y - y) == 1
405 ) {
406 let enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
407 enpassantMove.vanish.push({
408 x: x,
409 y: epSquare.y,
410 p: "p",
411 c: this.getColor(x, epSquare.y)
412 });
413 moves.push(enpassantMove);
414 }
415
416 return moves;
417 }
418
419 // Obtain all lancer moves in "step" direction
420 getPotentialLancerMoves_aux([x, y], step, tr) {
421 let moves = [];
422 // Add all moves to vacant squares until opponent is met:
423 const color = this.getColor(x, y);
424 const oppCol =
425 this.subTurn == 1
426 ? V.GetOppCol(color)
427 // at subTurn == 2, consider own pieces as opponent
428 : color;
429 let sq = [x + step[0], y + step[1]];
430 while (V.OnBoard(sq[0], sq[1]) && this.getColor(sq[0], sq[1]) != oppCol) {
431 if (this.board[sq[0]][sq[1]] == V.EMPTY)
432 moves.push(this.getBasicMove([x, y], sq, tr));
433 sq[0] += step[0];
434 sq[1] += step[1];
435 }
436 if (V.OnBoard(sq[0], sq[1]))
437 // Add capturing move
438 moves.push(this.getBasicMove([x, y], sq, tr));
439 return moves;
440 }
441
442 getPotentialLancerMoves([x, y]) {
443 let moves = [];
444 // Add all lancer possible orientations, similar to pawn promotions.
445 // Except if just after a push: allow all movements from init square then
446 const L = this.sentryPush.length;
447 if (!!this.sentryPush[L-1]) {
448 // Maybe I was pushed
449 const pl = this.sentryPush[L-1].length;
450 if (
451 this.sentryPush[L-1][pl-1].x == x &&
452 this.sentryPush[L-1][pl-1].y == y
453 ) {
454 // I was pushed: allow all directions (for this move only), but
455 // do not change direction after moving, *except* if I keep the
456 // same orientation in which I was pushed.
457 const color = this.getColor(x, y);
458 const curDir = V.LANCER_DIRS[this.board[x][y].charAt(1)];
459 Object.values(V.LANCER_DIRS).forEach(step => {
460 const dirCode = Object.keys(V.LANCER_DIRS).find(k => {
461 return (
462 V.LANCER_DIRS[k][0] == step[0] &&
463 V.LANCER_DIRS[k][1] == step[1]
464 );
465 });
466 const dirMoves =
467 this.getPotentialLancerMoves_aux(
468 [x, y],
469 step,
470 { p: dirCode, c: color }
471 );
472 if (curDir[0] == step[0] && curDir[1] == step[1]) {
473 // Keeping same orientation: can choose after
474 let chooseMoves = [];
475 dirMoves.forEach(m => {
476 Object.keys(V.LANCER_DIRS).forEach(k => {
477 let mk = JSON.parse(JSON.stringify(m));
478 mk.appear[0].p = k;
479 moves.push(mk);
480 });
481 });
482 Array.prototype.push.apply(moves, chooseMoves);
483 } else Array.prototype.push.apply(moves, dirMoves);
484 });
485 return moves;
486 }
487 }
488 // I wasn't pushed: standard lancer move
489 const dirCode = this.board[x][y][1];
490 const monodirMoves =
491 this.getPotentialLancerMoves_aux([x, y], V.LANCER_DIRS[dirCode]);
492 // Add all possible orientations aftermove except if I'm being pushed
493 if (this.subTurn == 1) {
494 monodirMoves.forEach(m => {
495 Object.keys(V.LANCER_DIRS).forEach(k => {
496 let mk = JSON.parse(JSON.stringify(m));
497 mk.appear[0].p = k;
498 moves.push(mk);
499 });
500 });
501 return moves;
502 } else {
503 // I'm pushed: add potential nudges
504 let potentialNudges = [];
505 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
506 if (
507 V.OnBoard(x + step[0], y + step[1]) &&
508 this.board[x + step[0]][y + step[1]] == V.EMPTY
509 ) {
510 potentialNudges.push(
511 this.getBasicMove(
512 [x, y],
513 [x + step[0], y + step[1]]
514 )
515 );
516 }
517 }
518 return monodirMoves.concat(potentialNudges);
519 }
520 }
521
522 getPotentialSentryMoves([x, y]) {
523 // The sentry moves a priori like a bishop:
524 let moves = super.getPotentialBishopMoves([x, y]);
525 // ...but captures are replaced by special move, if and only if
526 // "captured" piece can move now, considered as the capturer unit.
527 // --> except is subTurn == 2, in this case I don't push anything.
528 if (this.subTurn == 2) return moves.filter(m => m.vanish.length == 1);
529 moves.forEach(m => {
530 if (m.vanish.length == 2) {
531 // Temporarily cancel the sentry capture:
532 m.appear.pop();
533 m.vanish.pop();
534 }
535 });
536 const color = this.getColor(x, y);
537 const fMoves = moves.filter(m => {
538 // Can the pushed unit make any move? ...resulting in a non-self-check?
539 if (m.appear.length == 0) {
540 let res = false;
541 this.play(m);
542 let moves2 = this.getPotentialMovesFrom([m.end.x, m.end.y]);
543 for (let m2 of moves2) {
544 this.play(m2);
545 res = !this.underCheck(color);
546 this.undo(m2);
547 if (res) break;
548 }
549 this.undo(m);
550 return res;
551 }
552 return true;
553 });
554 return fMoves;
555 }
556
557 getPotentialJailerMoves([x, y]) {
558 return super.getPotentialRookMoves([x, y]).filter(m => {
559 // Remove jailer captures
560 return m.vanish[0].p != V.JAILER || m.vanish.length == 1;
561 });
562 }
563
564 getPotentialKingMoves(sq) {
565 const moves = this.getSlideNJumpMoves(
566 sq,
567 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
568 "oneStep"
569 );
570 return (
571 this.subTurn == 1
572 ? moves.concat(this.getCastleMoves(sq))
573 : moves
574 );
575 }
576
577 // Adapted: castle with jailer possible
578 getCastleMoves([x, y]) {
579 const c = this.getColor(x, y);
580 const firstRank = (c == "w" ? V.size.x - 1 : 0);
581 if (x != firstRank || y != this.INIT_COL_KING[c])
582 return [];
583
584 const oppCol = V.GetOppCol(c);
585 let moves = [];
586 let i = 0;
587 // King, then rook or jailer:
588 const finalSquares = [
589 [2, 3],
590 [V.size.y - 2, V.size.y - 3]
591 ];
592 castlingCheck: for (
593 let castleSide = 0;
594 castleSide < 2;
595 castleSide++
596 ) {
597 if (this.castleFlags[c][castleSide] >= 8) continue;
598 // Rook (or jailer) and king are on initial position
599 const finDist = finalSquares[castleSide][0] - y;
600 let step = finDist / Math.max(1, Math.abs(finDist));
601 i = y;
602 do {
603 if (
604 this.isAttacked([x, i], [oppCol]) ||
605 (this.board[x][i] != V.EMPTY &&
606 (this.getColor(x, i) != c ||
607 ![V.KING, V.ROOK, V.JAILER].includes(this.getPiece(x, i))))
608 ) {
609 continue castlingCheck;
610 }
611 i += step;
612 } while (i != finalSquares[castleSide][0]);
613 step = castleSide == 0 ? -1 : 1;
614 const rookOrJailerPos = this.castleFlags[c][castleSide];
615 for (i = y + step; i != rookOrJailerPos; i += step)
616 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
617
618 // Nothing on final squares, except maybe king and castling rook or jailer?
619 for (i = 0; i < 2; i++) {
620 if (
621 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
622 this.getPiece(x, finalSquares[castleSide][i]) != V.KING &&
623 finalSquares[castleSide][i] != rookOrJailerPos
624 ) {
625 continue castlingCheck;
626 }
627 }
628
629 // If this code is reached, castle is valid
630 const castlingPiece = this.getPiece(firstRank, rookOrJailerPos);
631 moves.push(
632 new Move({
633 appear: [
634 new PiPo({ x: x, y: finalSquares[castleSide][0], p: V.KING, c: c }),
635 new PiPo({ x: x, y: finalSquares[castleSide][1], p: castlingPiece, c: c })
636 ],
637 vanish: [
638 new PiPo({ x: x, y: y, p: V.KING, c: c }),
639 new PiPo({ x: x, y: rookOrJailerPos, p: castlingPiece, c: c })
640 ],
641 end:
642 Math.abs(y - rookOrJailerPos) <= 2
643 ? { x: x, y: rookOrJailerPos }
644 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
645 })
646 );
647 }
648
649 return moves;
650 }
651
652 atLeastOneMove() {
653 // If in second-half of a move, we already know that a move is possible
654 if (this.subTurn == 2) return true;
655 return super.atLeastOneMove();
656 }
657
658 filterValid(moves) {
659 if (moves.length == 0) return [];
660 const basicFilter = (m, c) => {
661 this.play(m);
662 const res = !this.underCheck(c);
663 this.undo(m);
664 return res;
665 };
666 // Disable check tests for sentry pushes,
667 // because in this case the move isn't finished
668 let movesWithoutSentryPushes = [];
669 let movesWithSentryPushes = [];
670 moves.forEach(m => {
671 // Second condition below for special king "pass" moves
672 if (m.appear.length > 0 || m.vanish.length == 0)
673 movesWithoutSentryPushes.push(m);
674 else movesWithSentryPushes.push(m);
675 });
676 const color = this.turn;
677 const oppCol = V.GetOppCol(color);
678 const filteredMoves =
679 movesWithoutSentryPushes.filter(m => basicFilter(m, color));
680 // If at least one full move made, everything is allowed.
681 // Else: forbid checks and captures.
682 return (
683 this.movesCount >= 2
684 ? filteredMoves
685 : filteredMoves.filter(m => {
686 return (m.vanish.length <= 1 && basicFilter(m, oppCol));
687 })
688 ).concat(movesWithSentryPushes);
689 }
690
691 getAllValidMoves() {
692 if (this.subTurn == 1) return super.getAllValidMoves();
693 // Sentry push:
694 const sentrySq = [this.sentryPos.x, this.sentryPos.y];
695 return this.filterValid(this.getPotentialMovesFrom(sentrySq));
696 }
697
698 prePlay(move) {
699 if (move.appear.length == 0 && move.vanish.length == 1)
700 // The sentry is about to push a piece: subTurn goes from 1 to 2
701 this.sentryPos = { x: move.end.x, y: move.end.y };
702 if (this.subTurn == 2 && move.vanish[0].p != V.PAWN) {
703 // A piece is pushed: forbid array of squares between start and end
704 // of move, included (except if it's a pawn)
705 let squares = [];
706 if ([V.KNIGHT,V.KING].includes(move.vanish[0].p))
707 // short-range pieces: just forbid initial square
708 squares.push({ x: move.start.x, y: move.start.y });
709 else {
710 const deltaX = move.end.x - move.start.x;
711 const deltaY = move.end.y - move.start.y;
712 const step = [
713 deltaX / Math.abs(deltaX) || 0,
714 deltaY / Math.abs(deltaY) || 0
715 ];
716 for (
717 let sq = {x: move.start.x, y: move.start.y};
718 sq.x != move.end.x || sq.y != move.end.y;
719 sq.x += step[0], sq.y += step[1]
720 ) {
721 squares.push({ x: sq.x, y: sq.y });
722 }
723 }
724 // Add end square as well, to know if I was pushed (useful for lancers)
725 squares.push({ x: move.end.x, y: move.end.y });
726 this.sentryPush.push(squares);
727 } else this.sentryPush.push(null);
728 }
729
730 play(move) {
731 if (!this.states) this.states = [];
732 const stateFen = this.getFen();
733 this.states.push(stateFen);
734
735 this.prePlay(move);
736 move.flags = JSON.stringify(this.aggregateFlags());
737 this.epSquares.push(this.getEpSquare(move));
738 V.PlayOnBoard(this.board, move);
739 // Is it a sentry push? (useful for undo)
740 move.sentryPush = (this.subTurn == 2);
741 if (this.subTurn == 1) this.movesCount++;
742 if (move.appear.length == 0 && move.vanish.length == 1) this.subTurn = 2;
743 else {
744 // Turn changes only if not a sentry "pre-push"
745 this.turn = V.GetOppCol(this.turn);
746 this.subTurn = 1;
747 }
748 this.postPlay(move);
749 }
750
751 postPlay(move) {
752 if (move.vanish.length == 0 || this.subTurn == 2)
753 // Special pass move of the king, or sentry pre-push: nothing to update
754 return;
755 const c = move.vanish[0].c;
756 const piece = move.vanish[0].p;
757 const firstRank = c == "w" ? V.size.x - 1 : 0;
758
759 if (piece == V.KING) {
760 this.kingPos[c][0] = move.appear[0].x;
761 this.kingPos[c][1] = move.appear[0].y;
762 this.castleFlags[c] = [V.size.y, V.size.y];
763 return;
764 }
765 // Update castling flags if rooks are moved
766 const oppCol = V.GetOppCol(c);
767 const oppFirstRank = V.size.x - 1 - firstRank;
768 if (
769 move.start.x == firstRank && //our rook moves?
770 this.castleFlags[c].includes(move.start.y)
771 ) {
772 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
773 this.castleFlags[c][flagIdx] = V.size.y;
774 } else if (
775 move.end.x == oppFirstRank && //we took opponent rook?
776 this.castleFlags[oppCol].includes(move.end.y)
777 ) {
778 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
779 this.castleFlags[oppCol][flagIdx] = V.size.y;
780 }
781 }
782
783 undo(move) {
784 this.epSquares.pop();
785 this.disaggregateFlags(JSON.parse(move.flags));
786 V.UndoOnBoard(this.board, move);
787 // Decrement movesCount except if the move is a sentry push
788 if (!move.sentryPush) this.movesCount--;
789 if (this.subTurn == 2) this.subTurn = 1;
790 else {
791 this.turn = V.GetOppCol(this.turn);
792 if (move.sentryPush) this.subTurn = 2;
793 }
794 this.postUndo(move);
795
796 const stateFen = this.getFen();
797 if (stateFen != this.states[this.states.length-1]) debugger;
798 this.states.pop();
799 }
800
801 postUndo(move) {
802 super.postUndo(move);
803 this.sentryPush.pop();
804 }
805
806 isAttacked(sq, colors) {
807 return (
808 super.isAttacked(sq, colors) ||
809 this.isAttackedByLancer(sq, colors) ||
810 this.isAttackedBySentry(sq, colors)
811 );
812 }
813
814 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
815 for (let step of steps) {
816 let rx = x + step[0],
817 ry = y + step[1];
818 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
819 rx += step[0];
820 ry += step[1];
821 }
822 if (
823 V.OnBoard(rx, ry) &&
824 this.getPiece(rx, ry) === piece &&
825 colors.includes(this.getColor(rx, ry)) &&
826 !this.isImmobilized([rx, ry])
827 ) {
828 return true;
829 }
830 }
831 return false;
832 }
833
834 isAttackedByPawn([x, y], colors) {
835 for (let c of colors) {
836 const pawnShift = c == "w" ? 1 : -1;
837 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
838 for (let i of [-1, 1]) {
839 if (
840 y + i >= 0 &&
841 y + i < V.size.y &&
842 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
843 this.getColor(x + pawnShift, y + i) == c &&
844 !this.isImmobilized([x + pawnShift, y + i])
845 ) {
846 return true;
847 }
848 }
849 }
850 }
851 return false;
852 }
853
854 isAttackedByLancer([x, y], colors) {
855 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
856 // If in this direction there are only enemy pieces and empty squares,
857 // and we meet a lancer: can he reach us?
858 // NOTE: do not stop at first lancer, there might be several!
859 let coord = { x: x + step[0], y: y + step[1] };
860 let lancerPos = [];
861 while (
862 V.OnBoard(coord.x, coord.y) &&
863 (
864 this.board[coord.x][coord.y] == V.EMPTY ||
865 colors.includes(this.getColor(coord.x, coord.y))
866 )
867 ) {
868 if (
869 this.getPiece(coord.x, coord.y) == V.LANCER &&
870 !this.isImmobilized([coord.x, coord.y])
871 ) {
872 lancerPos.push({x: coord.x, y: coord.y});
873 }
874 coord.x += step[0];
875 coord.y += step[1];
876 }
877 for (let xy of lancerPos) {
878 const dir = V.LANCER_DIRS[this.board[xy.x][xy.y].charAt(1)];
879 if (dir[0] == -step[0] && dir[1] == -step[1]) return true;
880 }
881 }
882 return false;
883 }
884
885 // Helper to check sentries attacks:
886 selfAttack([x1, y1], [x2, y2]) {
887 const color = this.getColor(x1, y1);
888 const sliderAttack = (allowedSteps, lancer) => {
889 const deltaX = x2 - x1;
890 const deltaY = y2 - y1;
891 const step = [ deltaX / Math.abs(deltaX), deltaY / Math.abs(deltaY) ];
892 if (allowedSteps.every(st => st[0] != step[0] || st[1] != step[1]))
893 return false;
894 let sq = [ x1 + step[0], y1 + step[1] ];
895 while (sq[0] != x2 && sq[1] != y2) {
896 if (
897 // NOTE: no need to check OnBoard in this special case
898 (!lancer && this.board[sq[0]][sq[1]] != V.EMPTY) ||
899 (!!lancer && this.getColor(sq[0], sq[1]) != color)
900 ) {
901 return false;
902 }
903 sq[0] += step[0];
904 sq[1] += step[1];
905 }
906 return true;
907 };
908 switch (this.getPiece(x1, y1)) {
909 case V.PAWN: {
910 // Pushed pawns move as enemy pawns
911 const shift = (color == 'w' ? 1 : -1);
912 return (x1 + shift == x2 && Math.abs(y1 - y2) == 1);
913 }
914 case V.KNIGHT: {
915 const deltaX = Math.abs(x1 - x2);
916 const deltaY = Math.abs(y1 - y2);
917 return (
918 deltaX + deltaY == 3 &&
919 [1, 2].includes(deltaX) &&
920 [1, 2].includes(deltaY)
921 );
922 }
923 case V.ROOK:
924 return sliderAttack(V.steps[V.ROOK]);
925 case V.BISHOP:
926 return sliderAttack(V.steps[V.BISHOP]);
927 case V.QUEEN:
928 return sliderAttack(V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
929 case V.LANCER: {
930 // Special case: as long as no enemy units stands in-between, it attacks
931 // (if it points toward the king).
932 const allowedStep = V.LANCER_DIRS[this.board[x1][y1].charAt(1)];
933 return sliderAttack([allowedStep], "lancer");
934 }
935 // No sentries or jailer tests: they cannot self-capture
936 }
937 return false;
938 }
939
940 isAttackedBySentry([x, y], colors) {
941 // Attacked by sentry means it can self-take our king.
942 // Just check diagonals of enemy sentry(ies), and if it reaches
943 // one of our pieces: can I self-take?
944 const color = V.GetOppCol(colors[0]);
945 let candidates = [];
946 for (let i=0; i<V.size.x; i++) {
947 for (let j=0; j<V.size.y; j++) {
948 if (
949 this.getPiece(i,j) == V.SENTRY &&
950 colors.includes(this.getColor(i,j)) &&
951 !this.isImmobilized([i, j])
952 ) {
953 for (let step of V.steps[V.BISHOP]) {
954 let sq = [ i + step[0], j + step[1] ];
955 while (
956 V.OnBoard(sq[0], sq[1]) &&
957 this.board[sq[0]][sq[1]] == V.EMPTY
958 ) {
959 sq[0] += step[0];
960 sq[1] += step[1];
961 }
962 if (
963 V.OnBoard(sq[0], sq[1]) &&
964 this.getColor(sq[0], sq[1]) == color
965 ) {
966 candidates.push([ sq[0], sq[1] ]);
967 }
968 }
969 }
970 }
971 }
972 for (let c of candidates)
973 if (this.selfAttack(c, [x, y])) return true;
974 return false;
975 }
976
977 // Jailer doesn't capture or give check
978
979 static get VALUES() {
980 return Object.assign(
981 { l: 4.8, s: 2.8, j: 3.8 }, //Jeff K. estimations
982 ChessRules.VALUES
983 );
984 }
985
986 getComputerMove() {
987 const maxeval = V.INFINITY;
988 const color = this.turn;
989 let moves1 = this.getAllValidMoves();
990
991 if (moves1.length == 0)
992 // TODO: this situation should not happen
993 return null;
994
995 const setEval = (move, next) => {
996 const score = this.getCurrentScore();
997 const curEval = move.eval;
998 if (score != "*") {
999 move.eval =
1000 score == "1/2"
1001 ? 0
1002 : (score == "1-0" ? 1 : -1) * maxeval;
1003 } else move.eval = this.evalPosition();
1004 if (
1005 // "next" is defined after sentry pushes
1006 !!next && (
1007 !curEval ||
1008 color == 'w' && move.eval > curEval ||
1009 color == 'b' && move.eval < curEval
1010 )
1011 ) {
1012 move.second = next;
1013 }
1014 };
1015
1016 // Just search_depth == 1 (because of sentries. TODO: can do better...)
1017 moves1.forEach(m1 => {
1018 this.play(m1);
1019 if (this.subTurn == 1) setEval(m1);
1020 else {
1021 // Need to play every pushes and count:
1022 const moves2 = this.getAllValidMoves();
1023 moves2.forEach(m2 => {
1024 this.play(m2);
1025 setEval(m1, m2);
1026 this.undo(m2);
1027 });
1028 }
1029 this.undo(m1);
1030 });
1031
1032 moves1.sort((a, b) => {
1033 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1034 });
1035 let candidates = [0];
1036 for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++)
1037 candidates.push(j);
1038 const choice = moves1[candidates[randInt(candidates.length)]];
1039 return (!choice.second ? choice : [choice, choice.second]);
1040 }
1041
1042 getNotation(move) {
1043 // Special case "king takes jailer" is a pass move
1044 if (move.appear.length == 0 && move.vanish.length == 0) return "pass";
1045 if (this.subTurn == 2) {
1046 // Do not consider appear[1] (sentry) for sentry pushes
1047 const simpleMove = {
1048 appear: [move.appear[0]],
1049 vanish: move.vanish,
1050 start: move.start,
1051 end: move.end
1052 };
1053 return super.getNotation(simpleMove);
1054 }
1055 return super.getNotation(move);
1056 }
1057};