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