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