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