Fix typo in Fugue rules + remove Football redundant kicks
[vchess.git] / client / src / base_rules.js
1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
3
4 import { ArrayFun } from "@/utils/array";
5 import { randInt, shuffle } from "@/utils/alea";
6
7 // class "PiPo": Piece + Position
8 export const PiPo = class PiPo {
9 // o: {piece[p], color[c], posX[x], posY[y]}
10 constructor(o) {
11 this.p = o.p;
12 this.c = o.c;
13 this.x = o.x;
14 this.y = o.y;
15 }
16 };
17
18 export const Move = class Move {
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
22 constructor(o) {
23 this.appear = o.appear;
24 this.vanish = o.vanish;
25 this.start = o.start || { x: o.vanish[0].x, y: o.vanish[0].y };
26 this.end = o.end || { x: o.appear[0].x, y: o.appear[0].y };
27 }
28 };
29
30 // NOTE: x coords = top to bottom; y = left to right
31 // (from white player perspective)
32 export const ChessRules = class ChessRules {
33
34 //////////////
35 // MISC UTILS
36
37 // Some variants don't have flags:
38 static get HasFlags() {
39 return true;
40 }
41
42 // Or castle
43 static get HasCastle() {
44 return V.HasFlags;
45 }
46
47 // Pawns specifications
48 static get PawnSpecs() {
49 return {
50 directions: { 'w': -1, 'b': 1 },
51 initShift: { w: 1, b: 1 },
52 twoSquares: true,
53 threeSquares: false,
54 promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN],
55 canCapture: true,
56 captureBackward: false,
57 bidirectional: false
58 };
59 }
60
61 // En-passant captures need a stack of squares:
62 static get HasEnpassant() {
63 return true;
64 }
65
66 // Some variants cannot have analyse mode
67 static get CanAnalyze() {
68 return true;
69 }
70 // Patch: issues with javascript OOP, objects can't access static fields.
71 get canAnalyze() {
72 return V.CanAnalyze;
73 }
74
75 // Some variants show incomplete information,
76 // and thus show only a partial moves list or no list at all.
77 static get ShowMoves() {
78 return "all";
79 }
80 get showMoves() {
81 return V.ShowMoves;
82 }
83
84 // Sometimes moves must remain hidden until game ends
85 static get SomeHiddenMoves() {
86 return false;
87 }
88 get someHiddenMoves() {
89 return V.SomeHiddenMoves;
90 }
91
92 // Generally true, unless the variant includes random effects
93 static get CorrConfirm() {
94 return true;
95 }
96
97 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
98 get showFirstTurn() {
99 return false;
100 }
101
102 // Some variants always show the same orientation
103 static get CanFlip() {
104 return true;
105 }
106 get canFlip() {
107 return V.CanFlip;
108 }
109
110 // For (generally old) variants without checkered board
111 static get Monochrome() {
112 return false;
113 }
114
115 // Some games are drawn unusually (bottom right corner is black)
116 static get DarkBottomRight() {
117 return false;
118 }
119
120 // Some variants require lines drawing
121 static get Lines() {
122 if (V.Monochrome) {
123 let lines = [];
124 // Draw all inter-squares lines
125 for (let i = 0; i <= V.size.x; i++)
126 lines.push([[i, 0], [i, V.size.y]]);
127 for (let j = 0; j <= V.size.y; j++)
128 lines.push([[0, j], [V.size.x, j]]);
129 return lines;
130 }
131 return null;
132 }
133
134 // In some variants, the player who repeat a position loses
135 static get LoseOnRepetition() {
136 return false;
137 }
138 // And in some others (Iceage), repetitions should be ignored:
139 static get IgnoreRepetition() {
140 return false;
141 }
142 loseOnRepetition() {
143 // In some variants, result depends on the position:
144 return V.LoseOnRepetition;
145 }
146
147 // At some stages, some games could wait clicks only:
148 onlyClick() {
149 return false;
150 }
151
152 // Some variants use click infos:
153 doClick() {
154 return null;
155 }
156
157 // Some variants may need to highlight squares on hover (Hamilton, Weiqi...)
158 hoverHighlight() {
159 return false;
160 }
161
162 static get IMAGE_EXTENSION() {
163 // All pieces should be in the SVG format
164 return ".svg";
165 }
166
167 // Turn "wb" into "B" (for FEN)
168 static board2fen(b) {
169 return b[0] == "w" ? b[1].toUpperCase() : b[1];
170 }
171
172 // Turn "p" into "bp" (for board)
173 static fen2board(f) {
174 return f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f;
175 }
176
177 // Check if FEN describes a board situation correctly
178 static IsGoodFen(fen) {
179 const fenParsed = V.ParseFen(fen);
180 // 1) Check position
181 if (!V.IsGoodPosition(fenParsed.position)) return false;
182 // 2) Check turn
183 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
184 // 3) Check moves count
185 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount, 10) >= 0))
186 return false;
187 // 4) Check flags
188 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
189 return false;
190 // 5) Check enpassant
191 if (
192 V.HasEnpassant &&
193 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
194 ) {
195 return false;
196 }
197 return true;
198 }
199
200 // Is position part of the FEN a priori correct?
201 static IsGoodPosition(position) {
202 if (position.length == 0) return false;
203 const rows = position.split("/");
204 if (rows.length != V.size.x) return false;
205 let kings = { "k": 0, "K": 0 };
206 for (let row of rows) {
207 let sumElts = 0;
208 for (let i = 0; i < row.length; i++) {
209 if (['K','k'].includes(row[i])) kings[row[i]]++;
210 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
211 else {
212 const num = parseInt(row[i], 10);
213 if (isNaN(num) || num <= 0) return false;
214 sumElts += num;
215 }
216 }
217 if (sumElts != V.size.y) return false;
218 }
219 // Both kings should be on board. Exactly one per color.
220 if (Object.values(kings).some(v => v != 1)) return false;
221 return true;
222 }
223
224 // For FEN checking
225 static IsGoodTurn(turn) {
226 return ["w", "b"].includes(turn);
227 }
228
229 // For FEN checking
230 static IsGoodFlags(flags) {
231 // NOTE: a little too permissive to work with more variants
232 return !!flags.match(/^[a-z]{4,4}$/);
233 }
234
235 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
236 static IsGoodEnpassant(enpassant) {
237 if (enpassant != "-") {
238 const ep = V.SquareToCoords(enpassant);
239 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
240 }
241 return true;
242 }
243
244 // 3 --> d (column number to letter)
245 static CoordToColumn(colnum) {
246 return String.fromCharCode(97 + colnum);
247 }
248
249 // d --> 3 (column letter to number)
250 static ColumnToCoord(column) {
251 return column.charCodeAt(0) - 97;
252 }
253
254 // a4 --> {x:3,y:0}
255 static SquareToCoords(sq) {
256 return {
257 // NOTE: column is always one char => max 26 columns
258 // row is counted from black side => subtraction
259 x: V.size.x - parseInt(sq.substr(1), 10),
260 y: sq[0].charCodeAt() - 97
261 };
262 }
263
264 // {x:0,y:4} --> e8
265 static CoordsToSquare(coords) {
266 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
267 }
268
269 // Path to pieces (standard ones in pieces/ folder)
270 getPpath(b) {
271 return b;
272 }
273
274 // Path to promotion pieces (usually the same)
275 getPPpath(m) {
276 return this.getPpath(m.appear[0].c + m.appear[0].p);
277 }
278
279 // Aggregates flags into one object
280 aggregateFlags() {
281 return this.castleFlags;
282 }
283
284 // Reverse operation
285 disaggregateFlags(flags) {
286 this.castleFlags = flags;
287 }
288
289 // En-passant square, if any
290 getEpSquare(moveOrSquare) {
291 if (!moveOrSquare) return undefined; //TODO: necessary line?!
292 if (typeof moveOrSquare === "string") {
293 const square = moveOrSquare;
294 if (square == "-") return undefined;
295 return V.SquareToCoords(square);
296 }
297 // Argument is a move:
298 const move = moveOrSquare;
299 const s = move.start,
300 e = move.end;
301 if (
302 s.y == e.y &&
303 Math.abs(s.x - e.x) == 2 &&
304 // Next conditions for variants like Atomic or Rifle, Recycle...
305 (move.appear.length > 0 && move.appear[0].p == V.PAWN) &&
306 (move.vanish.length > 0 && move.vanish[0].p == V.PAWN)
307 ) {
308 return {
309 x: (s.x + e.x) / 2,
310 y: s.y
311 };
312 }
313 return undefined; //default
314 }
315
316 // Can thing on square1 take thing on square2
317 canTake([x1, y1], [x2, y2]) {
318 return this.getColor(x1, y1) !== this.getColor(x2, y2);
319 }
320
321 // Is (x,y) on the chessboard?
322 static OnBoard(x, y) {
323 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
324 }
325
326 // Used in interface: 'side' arg == player color
327 canIplay(side, [x, y]) {
328 return this.turn == side && this.getColor(x, y) == side;
329 }
330
331 // On which squares is color under check ? (for interface)
332 getCheckSquares() {
333 const color = this.turn;
334 return (
335 this.underCheck(color)
336 // kingPos must be duplicated, because it may change:
337 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
338 : []
339 );
340 }
341
342 /////////////
343 // FEN UTILS
344
345 // Setup the initial random (asymmetric) position
346 static GenRandInitFen(randomness) {
347 if (randomness == 0)
348 // Deterministic:
349 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
350
351 let pieces = { w: new Array(8), b: new Array(8) };
352 let flags = "";
353 // Shuffle pieces on first (and last rank if randomness == 2)
354 for (let c of ["w", "b"]) {
355 if (c == 'b' && randomness == 1) {
356 pieces['b'] = pieces['w'];
357 flags += flags;
358 break;
359 }
360
361 let positions = ArrayFun.range(8);
362
363 // Get random squares for bishops
364 let randIndex = 2 * randInt(4);
365 const bishop1Pos = positions[randIndex];
366 // The second bishop must be on a square of different color
367 let randIndex_tmp = 2 * randInt(4) + 1;
368 const bishop2Pos = positions[randIndex_tmp];
369 // Remove chosen squares
370 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
371 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
372
373 // Get random squares for knights
374 randIndex = randInt(6);
375 const knight1Pos = positions[randIndex];
376 positions.splice(randIndex, 1);
377 randIndex = randInt(5);
378 const knight2Pos = positions[randIndex];
379 positions.splice(randIndex, 1);
380
381 // Get random square for queen
382 randIndex = randInt(4);
383 const queenPos = positions[randIndex];
384 positions.splice(randIndex, 1);
385
386 // Rooks and king positions are now fixed,
387 // because of the ordering rook-king-rook
388 const rook1Pos = positions[0];
389 const kingPos = positions[1];
390 const rook2Pos = positions[2];
391
392 // Finally put the shuffled pieces in the board array
393 pieces[c][rook1Pos] = "r";
394 pieces[c][knight1Pos] = "n";
395 pieces[c][bishop1Pos] = "b";
396 pieces[c][queenPos] = "q";
397 pieces[c][kingPos] = "k";
398 pieces[c][bishop2Pos] = "b";
399 pieces[c][knight2Pos] = "n";
400 pieces[c][rook2Pos] = "r";
401 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
402 }
403 // Add turn + flags + enpassant
404 return (
405 pieces["b"].join("") +
406 "/pppppppp/8/8/8/8/PPPPPPPP/" +
407 pieces["w"].join("").toUpperCase() +
408 " w 0 " + flags + " -"
409 );
410 }
411
412 // "Parse" FEN: just return untransformed string data
413 static ParseFen(fen) {
414 const fenParts = fen.split(" ");
415 let res = {
416 position: fenParts[0],
417 turn: fenParts[1],
418 movesCount: fenParts[2]
419 };
420 let nextIdx = 3;
421 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
422 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
423 return res;
424 }
425
426 // Return current fen (game state)
427 getFen() {
428 return (
429 this.getBaseFen() + " " +
430 this.getTurnFen() + " " +
431 this.movesCount +
432 (V.HasFlags ? " " + this.getFlagsFen() : "") +
433 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
434 );
435 }
436
437 getFenForRepeat() {
438 // Omit movesCount, only variable allowed to differ
439 return (
440 this.getBaseFen() + "_" +
441 this.getTurnFen() +
442 (V.HasFlags ? "_" + this.getFlagsFen() : "") +
443 (V.HasEnpassant ? "_" + this.getEnpassantFen() : "")
444 );
445 }
446
447 // Position part of the FEN string
448 getBaseFen() {
449 const format = (count) => {
450 // if more than 9 consecutive free spaces, break the integer,
451 // otherwise FEN parsing will fail.
452 if (count <= 9) return count;
453 // Most boards of size < 18:
454 if (count <= 18) return "9" + (count - 9);
455 // Except Gomoku:
456 return "99" + (count - 18);
457 };
458 let position = "";
459 for (let i = 0; i < V.size.x; i++) {
460 let emptyCount = 0;
461 for (let j = 0; j < V.size.y; j++) {
462 if (this.board[i][j] == V.EMPTY) emptyCount++;
463 else {
464 if (emptyCount > 0) {
465 // Add empty squares in-between
466 position += format(emptyCount);
467 emptyCount = 0;
468 }
469 position += V.board2fen(this.board[i][j]);
470 }
471 }
472 if (emptyCount > 0) {
473 // "Flush remainder"
474 position += format(emptyCount);
475 }
476 if (i < V.size.x - 1) position += "/"; //separate rows
477 }
478 return position;
479 }
480
481 getTurnFen() {
482 return this.turn;
483 }
484
485 // Flags part of the FEN string
486 getFlagsFen() {
487 let flags = "";
488 // Castling flags
489 for (let c of ["w", "b"])
490 flags += this.castleFlags[c].map(V.CoordToColumn).join("");
491 return flags;
492 }
493
494 // Enpassant part of the FEN string
495 getEnpassantFen() {
496 const L = this.epSquares.length;
497 if (!this.epSquares[L - 1]) return "-"; //no en-passant
498 return V.CoordsToSquare(this.epSquares[L - 1]);
499 }
500
501 // Turn position fen into double array ["wb","wp","bk",...]
502 static GetBoard(position) {
503 const rows = position.split("/");
504 let board = ArrayFun.init(V.size.x, V.size.y, "");
505 for (let i = 0; i < rows.length; i++) {
506 let j = 0;
507 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
508 const character = rows[i][indexInRow];
509 const num = parseInt(character, 10);
510 // If num is a number, just shift j:
511 if (!isNaN(num)) j += num;
512 // Else: something at position i,j
513 else board[i][j++] = V.fen2board(character);
514 }
515 }
516 return board;
517 }
518
519 // Extract (relevant) flags from fen
520 setFlags(fenflags) {
521 // white a-castle, h-castle, black a-castle, h-castle
522 this.castleFlags = { w: [-1, -1], b: [-1, -1] };
523 for (let i = 0; i < 4; i++) {
524 this.castleFlags[i < 2 ? "w" : "b"][i % 2] =
525 V.ColumnToCoord(fenflags.charAt(i));
526 }
527 }
528
529 //////////////////
530 // INITIALIZATION
531
532 // Fen string fully describes the game state
533 constructor(fen) {
534 if (!fen)
535 // In printDiagram() fen isn't supply because only getPpath() is used
536 // TODO: find a better solution!
537 return;
538 const fenParsed = V.ParseFen(fen);
539 this.board = V.GetBoard(fenParsed.position);
540 this.turn = fenParsed.turn;
541 this.movesCount = parseInt(fenParsed.movesCount, 10);
542 this.setOtherVariables(fen);
543 }
544
545 // Scan board for kings positions
546 // TODO: should be done from board, no need for the complete FEN
547 scanKings(fen) {
548 // Squares of white and black king:
549 this.kingPos = { w: [-1, -1], b: [-1, -1] };
550 const fenRows = V.ParseFen(fen).position.split("/");
551 for (let i = 0; i < fenRows.length; i++) {
552 let k = 0; //column index on board
553 for (let j = 0; j < fenRows[i].length; j++) {
554 switch (fenRows[i].charAt(j)) {
555 case "k":
556 this.kingPos["b"] = [i, k];
557 break;
558 case "K":
559 this.kingPos["w"] = [i, k];
560 break;
561 default: {
562 const num = parseInt(fenRows[i].charAt(j), 10);
563 if (!isNaN(num)) k += num - 1;
564 }
565 }
566 k++;
567 }
568 }
569 }
570
571 // Some additional variables from FEN (variant dependant)
572 setOtherVariables(fen) {
573 // Set flags and enpassant:
574 const parsedFen = V.ParseFen(fen);
575 if (V.HasFlags) this.setFlags(parsedFen.flags);
576 if (V.HasEnpassant) {
577 const epSq =
578 parsedFen.enpassant != "-"
579 ? this.getEpSquare(parsedFen.enpassant)
580 : undefined;
581 this.epSquares = [epSq];
582 }
583 // Search for kings positions:
584 this.scanKings(fen);
585 }
586
587 /////////////////////
588 // GETTERS & SETTERS
589
590 static get size() {
591 return { x: 8, y: 8 };
592 }
593
594 // Color of thing on square (i,j). 'undefined' if square is empty
595 getColor(i, j) {
596 return this.board[i][j].charAt(0);
597 }
598
599 // Piece type on square (i,j). 'undefined' if square is empty
600 getPiece(i, j) {
601 return this.board[i][j].charAt(1);
602 }
603
604 // Get opponent color
605 static GetOppCol(color) {
606 return color == "w" ? "b" : "w";
607 }
608
609 // Pieces codes (for a clearer code)
610 static get PAWN() {
611 return "p";
612 }
613 static get ROOK() {
614 return "r";
615 }
616 static get KNIGHT() {
617 return "n";
618 }
619 static get BISHOP() {
620 return "b";
621 }
622 static get QUEEN() {
623 return "q";
624 }
625 static get KING() {
626 return "k";
627 }
628
629 // For FEN checking:
630 static get PIECES() {
631 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
632 }
633
634 // Empty square
635 static get EMPTY() {
636 return "";
637 }
638
639 // Some pieces movements
640 static get steps() {
641 return {
642 r: [
643 [-1, 0],
644 [1, 0],
645 [0, -1],
646 [0, 1]
647 ],
648 n: [
649 [-1, -2],
650 [-1, 2],
651 [1, -2],
652 [1, 2],
653 [-2, -1],
654 [-2, 1],
655 [2, -1],
656 [2, 1]
657 ],
658 b: [
659 [-1, -1],
660 [-1, 1],
661 [1, -1],
662 [1, 1]
663 ]
664 };
665 }
666
667 ////////////////////
668 // MOVES GENERATION
669
670 // All possible moves from selected square
671 getPotentialMovesFrom(sq) {
672 switch (this.getPiece(sq[0], sq[1])) {
673 case V.PAWN: return this.getPotentialPawnMoves(sq);
674 case V.ROOK: return this.getPotentialRookMoves(sq);
675 case V.KNIGHT: return this.getPotentialKnightMoves(sq);
676 case V.BISHOP: return this.getPotentialBishopMoves(sq);
677 case V.QUEEN: return this.getPotentialQueenMoves(sq);
678 case V.KING: return this.getPotentialKingMoves(sq);
679 }
680 return []; //never reached (but some variants may use it: Bario...)
681 }
682
683 // Build a regular move from its initial and destination squares.
684 // tr: transformation
685 getBasicMove([sx, sy], [ex, ey], tr) {
686 const initColor = this.getColor(sx, sy);
687 const initPiece = this.board[sx][sy].charAt(1);
688 let mv = new Move({
689 appear: [
690 new PiPo({
691 x: ex,
692 y: ey,
693 c: !!tr ? tr.c : initColor,
694 p: !!tr ? tr.p : initPiece
695 })
696 ],
697 vanish: [
698 new PiPo({
699 x: sx,
700 y: sy,
701 c: initColor,
702 p: initPiece
703 })
704 ]
705 });
706
707 // The opponent piece disappears if we take it
708 if (this.board[ex][ey] != V.EMPTY) {
709 mv.vanish.push(
710 new PiPo({
711 x: ex,
712 y: ey,
713 c: this.getColor(ex, ey),
714 p: this.board[ex][ey].charAt(1)
715 })
716 );
717 }
718
719 return mv;
720 }
721
722 // Generic method to find possible moves of non-pawn pieces:
723 // "sliding or jumping"
724 getSlideNJumpMoves([x, y], steps, oneStep) {
725 let moves = [];
726 outerLoop: for (let step of steps) {
727 let i = x + step[0];
728 let j = y + step[1];
729 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
730 moves.push(this.getBasicMove([x, y], [i, j]));
731 if (!!oneStep) continue outerLoop;
732 i += step[0];
733 j += step[1];
734 }
735 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
736 moves.push(this.getBasicMove([x, y], [i, j]));
737 }
738 return moves;
739 }
740
741 // Special case of en-passant captures: treated separately
742 getEnpassantCaptures([x, y], shiftX) {
743 const Lep = this.epSquares.length;
744 const epSquare = this.epSquares[Lep - 1]; //always at least one element
745 let enpassantMove = null;
746 if (
747 !!epSquare &&
748 epSquare.x == x + shiftX &&
749 Math.abs(epSquare.y - y) == 1
750 ) {
751 enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
752 enpassantMove.vanish.push({
753 x: x,
754 y: epSquare.y,
755 p: this.board[x][epSquare.y].charAt(1),
756 c: this.getColor(x, epSquare.y)
757 });
758 }
759 return !!enpassantMove ? [enpassantMove] : [];
760 }
761
762 // Consider all potential promotions:
763 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
764 let finalPieces = [V.PAWN];
765 const color = this.turn; //this.getColor(x1, y1);
766 const lastRank = (color == "w" ? 0 : V.size.x - 1);
767 if (x2 == lastRank) {
768 // promotions arg: special override for Hiddenqueen variant
769 if (!!promotions) finalPieces = promotions;
770 else if (!!V.PawnSpecs.promotions) finalPieces = V.PawnSpecs.promotions;
771 }
772 for (let piece of finalPieces) {
773 const tr = (piece != V.PAWN ? { c: color, p: piece } : null);
774 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
775 }
776 }
777
778 // What are the pawn moves from square x,y ?
779 getPotentialPawnMoves([x, y], promotions) {
780 const color = this.turn; //this.getColor(x, y);
781 const [sizeX, sizeY] = [V.size.x, V.size.y];
782 const pawnShiftX = V.PawnSpecs.directions[color];
783 const firstRank = (color == "w" ? sizeX - 1 : 0);
784 const forward = (color == 'w' ? -1 : 1);
785
786 // Pawn movements in shiftX direction:
787 const getPawnMoves = (shiftX) => {
788 let moves = [];
789 // NOTE: next condition is generally true (no pawn on last rank)
790 if (x + shiftX >= 0 && x + shiftX < sizeX) {
791 if (this.board[x + shiftX][y] == V.EMPTY) {
792 // One square forward (or backward)
793 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
794 // Next condition because pawns on 1st rank can generally jump
795 if (
796 V.PawnSpecs.twoSquares &&
797 (
798 (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w'])
799 ||
800 (color == 'b' && x <= V.PawnSpecs.initShift['b'])
801 )
802 ) {
803 if (
804 shiftX == forward &&
805 this.board[x + 2 * shiftX][y] == V.EMPTY
806 ) {
807 // Two squares jump
808 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
809 if (
810 V.PawnSpecs.threeSquares &&
811 this.board[x + 3 * shiftX][y] == V.EMPTY
812 ) {
813 // Three squares jump
814 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
815 }
816 }
817 }
818 }
819 // Captures
820 if (V.PawnSpecs.canCapture) {
821 for (let shiftY of [-1, 1]) {
822 if (y + shiftY >= 0 && y + shiftY < sizeY) {
823 if (
824 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
825 this.canTake([x, y], [x + shiftX, y + shiftY])
826 ) {
827 this.addPawnMoves(
828 [x, y], [x + shiftX, y + shiftY],
829 moves, promotions
830 );
831 }
832 if (
833 V.PawnSpecs.captureBackward && shiftX == forward &&
834 x - shiftX >= 0 && x - shiftX < V.size.x &&
835 this.board[x - shiftX][y + shiftY] != V.EMPTY &&
836 this.canTake([x, y], [x - shiftX, y + shiftY])
837 ) {
838 this.addPawnMoves(
839 [x, y], [x - shiftX, y + shiftY],
840 moves, promotions
841 );
842 }
843 }
844 }
845 }
846 }
847 return moves;
848 }
849
850 let pMoves = getPawnMoves(pawnShiftX);
851 if (V.PawnSpecs.bidirectional)
852 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
853
854 if (V.HasEnpassant) {
855 // NOTE: backward en-passant captures are not considered
856 // because no rules define them (for now).
857 Array.prototype.push.apply(
858 pMoves,
859 this.getEnpassantCaptures([x, y], pawnShiftX)
860 );
861 }
862
863 return pMoves;
864 }
865
866 // What are the rook moves from square x,y ?
867 getPotentialRookMoves(sq) {
868 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
869 }
870
871 // What are the knight moves from square x,y ?
872 getPotentialKnightMoves(sq) {
873 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
874 }
875
876 // What are the bishop moves from square x,y ?
877 getPotentialBishopMoves(sq) {
878 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
879 }
880
881 // What are the queen moves from square x,y ?
882 getPotentialQueenMoves(sq) {
883 return this.getSlideNJumpMoves(
884 sq,
885 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
886 );
887 }
888
889 // What are the king moves from square x,y ?
890 getPotentialKingMoves(sq) {
891 // Initialize with normal moves
892 let moves = this.getSlideNJumpMoves(
893 sq,
894 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
895 "oneStep"
896 );
897 if (V.HasCastle && this.castleFlags[this.turn].some(v => v < V.size.y))
898 moves = moves.concat(this.getCastleMoves(sq));
899 return moves;
900 }
901
902 // "castleInCheck" arg to let some variants castle under check
903 getCastleMoves([x, y], finalSquares, castleInCheck, castleWith) {
904 const c = this.getColor(x, y);
905
906 // Castling ?
907 const oppCol = V.GetOppCol(c);
908 let moves = [];
909 // King, then rook:
910 finalSquares = finalSquares || [ [2, 3], [V.size.y - 2, V.size.y - 3] ];
911 const castlingKing = this.board[x][y].charAt(1);
912 castlingCheck: for (
913 let castleSide = 0;
914 castleSide < 2;
915 castleSide++ //large, then small
916 ) {
917 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
918 // If this code is reached, rook and king are on initial position
919
920 // NOTE: in some variants this is not a rook
921 const rookPos = this.castleFlags[c][castleSide];
922 const castlingPiece = this.board[x][rookPos].charAt(1);
923 if (
924 this.board[x][rookPos] == V.EMPTY ||
925 this.getColor(x, rookPos) != c ||
926 (!!castleWith && !castleWith.includes(castlingPiece))
927 ) {
928 // Rook is not here, or changed color (see Benedict)
929 continue;
930 }
931
932 // Nothing on the path of the king ? (and no checks)
933 const finDist = finalSquares[castleSide][0] - y;
934 let step = finDist / Math.max(1, Math.abs(finDist));
935 let i = y;
936 do {
937 if (
938 (!castleInCheck && this.isAttacked([x, i], oppCol)) ||
939 (
940 this.board[x][i] != V.EMPTY &&
941 // NOTE: next check is enough, because of chessboard constraints
942 (this.getColor(x, i) != c || ![y, rookPos].includes(i))
943 )
944 ) {
945 continue castlingCheck;
946 }
947 i += step;
948 } while (i != finalSquares[castleSide][0]);
949
950 // Nothing on the path to the rook?
951 step = castleSide == 0 ? -1 : 1;
952 for (i = y + step; i != rookPos; i += step) {
953 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
954 }
955
956 // Nothing on final squares, except maybe king and castling rook?
957 for (i = 0; i < 2; i++) {
958 if (
959 finalSquares[castleSide][i] != rookPos &&
960 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
961 (
962 finalSquares[castleSide][i] != y ||
963 this.getColor(x, finalSquares[castleSide][i]) != c
964 )
965 ) {
966 continue castlingCheck;
967 }
968 }
969
970 // If this code is reached, castle is valid
971 moves.push(
972 new Move({
973 appear: [
974 new PiPo({
975 x: x,
976 y: finalSquares[castleSide][0],
977 p: castlingKing,
978 c: c
979 }),
980 new PiPo({
981 x: x,
982 y: finalSquares[castleSide][1],
983 p: castlingPiece,
984 c: c
985 })
986 ],
987 vanish: [
988 // King might be initially disguised (Titan...)
989 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
990 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
991 ],
992 end:
993 Math.abs(y - rookPos) <= 2
994 ? { x: x, y: rookPos }
995 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
996 })
997 );
998 }
999
1000 return moves;
1001 }
1002
1003 ////////////////////
1004 // MOVES VALIDATION
1005
1006 // For the interface: possible moves for the current turn from square sq
1007 getPossibleMovesFrom(sq) {
1008 return this.filterValid(this.getPotentialMovesFrom(sq));
1009 }
1010
1011 // TODO: promotions (into R,B,N,Q) should be filtered only once
1012 filterValid(moves) {
1013 if (moves.length == 0) return [];
1014 const color = this.turn;
1015 return moves.filter(m => {
1016 this.play(m);
1017 const res = !this.underCheck(color);
1018 this.undo(m);
1019 return res;
1020 });
1021 }
1022
1023 getAllPotentialMoves() {
1024 const color = this.turn;
1025 let potentialMoves = [];
1026 for (let i = 0; i < V.size.x; i++) {
1027 for (let j = 0; j < V.size.y; j++) {
1028 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1029 Array.prototype.push.apply(
1030 potentialMoves,
1031 this.getPotentialMovesFrom([i, j])
1032 );
1033 }
1034 }
1035 }
1036 return potentialMoves;
1037 }
1038
1039 // Search for all valid moves considering current turn
1040 // (for engine and game end)
1041 getAllValidMoves() {
1042 return this.filterValid(this.getAllPotentialMoves());
1043 }
1044
1045 // Stop at the first move found
1046 // TODO: not really, it explores all moves from a square (one is enough).
1047 // Possible fix: add extra arg "oneMove" to getPotentialMovesFrom,
1048 // and then return only boolean true at first move found
1049 // (in all getPotentialXXXMoves() ... for all variants ...)
1050 atLeastOneMove() {
1051 const color = this.turn;
1052 for (let i = 0; i < V.size.x; i++) {
1053 for (let j = 0; j < V.size.y; j++) {
1054 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
1055 const moves = this.getPotentialMovesFrom([i, j]);
1056 if (moves.length > 0) {
1057 for (let k = 0; k < moves.length; k++)
1058 if (this.filterValid([moves[k]]).length > 0) return true;
1059 }
1060 }
1061 }
1062 }
1063 return false;
1064 }
1065
1066 // Check if pieces of given color are attacking (king) on square x,y
1067 isAttacked(sq, color) {
1068 return (
1069 this.isAttackedByPawn(sq, color) ||
1070 this.isAttackedByRook(sq, color) ||
1071 this.isAttackedByKnight(sq, color) ||
1072 this.isAttackedByBishop(sq, color) ||
1073 this.isAttackedByQueen(sq, color) ||
1074 this.isAttackedByKing(sq, color)
1075 );
1076 }
1077
1078 // Generic method for non-pawn pieces ("sliding or jumping"):
1079 // is x,y attacked by a piece of given color ?
1080 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
1081 for (let step of steps) {
1082 let rx = x + step[0],
1083 ry = y + step[1];
1084 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1085 rx += step[0];
1086 ry += step[1];
1087 }
1088 if (
1089 V.OnBoard(rx, ry) &&
1090 this.board[rx][ry] != V.EMPTY &&
1091 this.getPiece(rx, ry) == piece &&
1092 this.getColor(rx, ry) == color
1093 ) {
1094 return true;
1095 }
1096 }
1097 return false;
1098 }
1099
1100 // Is square x,y attacked by 'color' pawns ?
1101 isAttackedByPawn(sq, color) {
1102 const pawnShift = (color == "w" ? 1 : -1);
1103 return this.isAttackedBySlideNJump(
1104 sq,
1105 color,
1106 V.PAWN,
1107 [[pawnShift, 1], [pawnShift, -1]],
1108 "oneStep"
1109 );
1110 }
1111
1112 // Is square x,y attacked by 'color' rooks ?
1113 isAttackedByRook(sq, color) {
1114 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1115 }
1116
1117 // Is square x,y attacked by 'color' knights ?
1118 isAttackedByKnight(sq, color) {
1119 return this.isAttackedBySlideNJump(
1120 sq,
1121 color,
1122 V.KNIGHT,
1123 V.steps[V.KNIGHT],
1124 "oneStep"
1125 );
1126 }
1127
1128 // Is square x,y attacked by 'color' bishops ?
1129 isAttackedByBishop(sq, color) {
1130 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1131 }
1132
1133 // Is square x,y attacked by 'color' queens ?
1134 isAttackedByQueen(sq, color) {
1135 return this.isAttackedBySlideNJump(
1136 sq,
1137 color,
1138 V.QUEEN,
1139 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1140 );
1141 }
1142
1143 // Is square x,y attacked by 'color' king(s) ?
1144 isAttackedByKing(sq, color) {
1145 return this.isAttackedBySlideNJump(
1146 sq,
1147 color,
1148 V.KING,
1149 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1150 "oneStep"
1151 );
1152 }
1153
1154 // Is color under check after his move ?
1155 underCheck(color) {
1156 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1157 }
1158
1159 /////////////////
1160 // MOVES PLAYING
1161
1162 // Apply a move on board
1163 static PlayOnBoard(board, move) {
1164 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1165 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1166 }
1167 // Un-apply the played move
1168 static UndoOnBoard(board, move) {
1169 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1170 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1171 }
1172
1173 prePlay() {}
1174
1175 play(move) {
1176 // DEBUG:
1177 // if (!this.states) this.states = [];
1178 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1179 // this.states.push(stateFen);
1180
1181 this.prePlay(move);
1182 // Save flags (for undo)
1183 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
1184 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1185 V.PlayOnBoard(this.board, move);
1186 this.turn = V.GetOppCol(this.turn);
1187 this.movesCount++;
1188 this.postPlay(move);
1189 }
1190
1191 updateCastleFlags(move, piece, color) {
1192 // TODO: check flags. If already off, no need to always re-evaluate
1193 const c = color || V.GetOppCol(this.turn);
1194 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1195 // Update castling flags if rooks are moved
1196 const oppCol = this.turn;
1197 const oppFirstRank = V.size.x - 1 - firstRank;
1198 if (piece == V.KING && move.appear.length > 0)
1199 this.castleFlags[c] = [V.size.y, V.size.y];
1200 else if (
1201 move.start.x == firstRank && //our rook moves?
1202 this.castleFlags[c].includes(move.start.y)
1203 ) {
1204 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1205 this.castleFlags[c][flagIdx] = V.size.y;
1206 }
1207 // NOTE: not "else if" because a rook could take an opposing rook
1208 if (
1209 move.end.x == oppFirstRank && //we took opponent rook?
1210 this.castleFlags[oppCol].includes(move.end.y)
1211 ) {
1212 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1213 this.castleFlags[oppCol][flagIdx] = V.size.y;
1214 }
1215 }
1216
1217 // After move is played, update variables + flags
1218 postPlay(move) {
1219 const c = V.GetOppCol(this.turn);
1220 let piece = undefined;
1221 if (move.vanish.length >= 1)
1222 // Usual case, something is moved
1223 piece = move.vanish[0].p;
1224 else
1225 // Crazyhouse-like variants
1226 piece = move.appear[0].p;
1227
1228 // Update king position + flags
1229 if (piece == V.KING && move.appear.length > 0)
1230 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
1231 if (V.HasCastle) this.updateCastleFlags(move, piece);
1232 }
1233
1234 preUndo() {}
1235
1236 undo(move) {
1237 this.preUndo(move);
1238 if (V.HasEnpassant) this.epSquares.pop();
1239 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1240 V.UndoOnBoard(this.board, move);
1241 this.turn = V.GetOppCol(this.turn);
1242 this.movesCount--;
1243 this.postUndo(move);
1244
1245 // DEBUG:
1246 // const stateFen = this.getFen() + JSON.stringify(this.kingPos);
1247 // if (stateFen != this.states[this.states.length-1]) debugger;
1248 // this.states.pop();
1249 }
1250
1251 // After move is undo-ed *and flags resetted*, un-update other variables
1252 // TODO: more symmetry, by storing flags increment in move (?!)
1253 postUndo(move) {
1254 // (Potentially) Reset king position
1255 const c = this.getColor(move.start.x, move.start.y);
1256 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1257 this.kingPos[c] = [move.start.x, move.start.y];
1258 }
1259
1260 ///////////////
1261 // END OF GAME
1262
1263 // What is the score ? (Interesting if game is over)
1264 getCurrentScore() {
1265 if (this.atLeastOneMove()) return "*";
1266 // Game over
1267 const color = this.turn;
1268 // No valid move: stalemate or checkmate?
1269 if (!this.underCheck(color)) return "1/2";
1270 // OK, checkmate
1271 return (color == "w" ? "0-1" : "1-0");
1272 }
1273
1274 ///////////////
1275 // ENGINE PLAY
1276
1277 // Pieces values
1278 static get VALUES() {
1279 return {
1280 p: 1,
1281 r: 5,
1282 n: 3,
1283 b: 3,
1284 q: 9,
1285 k: 1000
1286 };
1287 }
1288
1289 // "Checkmate" (unreachable eval)
1290 static get INFINITY() {
1291 return 9999;
1292 }
1293
1294 // At this value or above, the game is over
1295 static get THRESHOLD_MATE() {
1296 return V.INFINITY;
1297 }
1298
1299 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
1300 static get SEARCH_DEPTH() {
1301 return 3;
1302 }
1303
1304 // 'movesList' arg for some variants to provide a custom list
1305 getComputerMove(movesList) {
1306 const maxeval = V.INFINITY;
1307 const color = this.turn;
1308 let moves1 = movesList || this.getAllValidMoves();
1309
1310 if (moves1.length == 0)
1311 // TODO: this situation should not happen
1312 return null;
1313
1314 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
1315 for (let i = 0; i < moves1.length; i++) {
1316 this.play(moves1[i]);
1317 const score1 = this.getCurrentScore();
1318 if (score1 != "*") {
1319 moves1[i].eval =
1320 score1 == "1/2"
1321 ? 0
1322 : (score1 == "1-0" ? 1 : -1) * maxeval;
1323 }
1324 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1325 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1326 this.undo(moves1[i]);
1327 continue;
1328 }
1329 // Initial self evaluation is very low: "I'm checkmated"
1330 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1331 // Initial enemy evaluation is very low too, for him
1332 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1333 // Second half-move:
1334 let moves2 = this.getAllValidMoves();
1335 for (let j = 0; j < moves2.length; j++) {
1336 this.play(moves2[j]);
1337 const score2 = this.getCurrentScore();
1338 let evalPos = 0; //1/2 value
1339 switch (score2) {
1340 case "*":
1341 evalPos = this.evalPosition();
1342 break;
1343 case "1-0":
1344 evalPos = maxeval;
1345 break;
1346 case "0-1":
1347 evalPos = -maxeval;
1348 break;
1349 }
1350 if (
1351 (color == "w" && evalPos < eval2) ||
1352 (color == "b" && evalPos > eval2)
1353 ) {
1354 eval2 = evalPos;
1355 }
1356 this.undo(moves2[j]);
1357 }
1358 if (
1359 (color == "w" && eval2 > moves1[i].eval) ||
1360 (color == "b" && eval2 < moves1[i].eval)
1361 ) {
1362 moves1[i].eval = eval2;
1363 }
1364 this.undo(moves1[i]);
1365 }
1366 moves1.sort((a, b) => {
1367 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1368 });
1369 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1370
1371 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1372 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
1373 for (let i = 0; i < moves1.length; i++) {
1374 this.play(moves1[i]);
1375 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1376 moves1[i].eval =
1377 0.1 * moves1[i].eval +
1378 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1379 this.undo(moves1[i]);
1380 }
1381 moves1.sort((a, b) => {
1382 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1383 });
1384 }
1385
1386 let candidates = [0];
1387 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1388 candidates.push(i);
1389 return moves1[candidates[randInt(candidates.length)]];
1390 }
1391
1392 alphabeta(depth, alpha, beta) {
1393 const maxeval = V.INFINITY;
1394 const color = this.turn;
1395 const score = this.getCurrentScore();
1396 if (score != "*")
1397 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1398 if (depth == 0) return this.evalPosition();
1399 const moves = this.getAllValidMoves();
1400 let v = color == "w" ? -maxeval : maxeval;
1401 if (color == "w") {
1402 for (let i = 0; i < moves.length; i++) {
1403 this.play(moves[i]);
1404 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1405 this.undo(moves[i]);
1406 alpha = Math.max(alpha, v);
1407 if (alpha >= beta) break; //beta cutoff
1408 }
1409 }
1410 else {
1411 // color=="b"
1412 for (let i = 0; i < moves.length; i++) {
1413 this.play(moves[i]);
1414 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1415 this.undo(moves[i]);
1416 beta = Math.min(beta, v);
1417 if (alpha >= beta) break; //alpha cutoff
1418 }
1419 }
1420 return v;
1421 }
1422
1423 evalPosition() {
1424 let evaluation = 0;
1425 // Just count material for now
1426 for (let i = 0; i < V.size.x; i++) {
1427 for (let j = 0; j < V.size.y; j++) {
1428 if (this.board[i][j] != V.EMPTY) {
1429 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1430 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1431 }
1432 }
1433 }
1434 return evaluation;
1435 }
1436
1437 /////////////////////////
1438 // MOVES + GAME NOTATION
1439 /////////////////////////
1440
1441 // Context: just before move is played, turn hasn't changed
1442 // TODO: un-ambiguous notation (switch on piece type, check directions...)
1443 getNotation(move) {
1444 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1445 // Castle
1446 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1447
1448 // Translate final square
1449 const finalSquare = V.CoordsToSquare(move.end);
1450
1451 const piece = this.getPiece(move.start.x, move.start.y);
1452 if (piece == V.PAWN) {
1453 // Pawn move
1454 let notation = "";
1455 if (move.vanish.length > move.appear.length) {
1456 // Capture
1457 const startColumn = V.CoordToColumn(move.start.y);
1458 notation = startColumn + "x" + finalSquare;
1459 }
1460 else notation = finalSquare;
1461 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
1462 // Promotion
1463 notation += "=" + move.appear[0].p.toUpperCase();
1464 return notation;
1465 }
1466 // Piece movement
1467 return (
1468 piece.toUpperCase() +
1469 (move.vanish.length > move.appear.length ? "x" : "") +
1470 finalSquare
1471 );
1472 }
1473
1474 static GetUnambiguousNotation(move) {
1475 // Machine-readable format with all the informations about the move
1476 return (
1477 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1478 ? V.CoordsToSquare(move.start)
1479 : "-"
1480 ) + "." +
1481 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1482 ? V.CoordsToSquare(move.end)
1483 : "-"
1484 ) + " " +
1485 (!!move.appear && move.appear.length > 0
1486 ? move.appear.map(a =>
1487 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1488 : "-"
1489 ) + "/" +
1490 (!!move.vanish && move.vanish.length > 0
1491 ? move.vanish.map(a =>
1492 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1493 : "-"
1494 )
1495 );
1496 }
1497
1498 };