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