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