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