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