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