9444e7bb3791590fc21d329fe3e160d2dc3dd1e4
1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // NOTE: x coords: top to bottom (white perspective); y: left to right
7 // NOTE: ChessRules is aliased as window.C, and variants as window.V
8 export default class ChessRules
{
10 static get Aliases() {
11 return [{'C': ChessRules
}];
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
17 // Some variants have specific options, like the number of pawns in Monster,
18 // or the board size for Pandemonium.
19 // Users can generally select a randomness level from 0 to 2.
20 static get Options() {
22 // NOTE: some options are required for FEN generation, some aren't.
25 variable: "randomness",
28 { label: "Deterministic", value: 0 },
29 { label: "Symmetric random", value: 1 },
30 { label: "Asymmetric random", value: 2 }
35 label: "Capture king",
40 label: "Falling pawn",
45 // Game modifiers (using "elementary variants"). Default: false
48 "balance", //takes precedence over doublemove & progressive
52 "cylinder", //ok with all
56 "progressive", //(natural) priority over doublemove
65 // Pawns specifications
68 directions: { 'w': -1, 'b': 1 },
69 initShift: { w: 1, b: 1 },
73 captureBackward: false,
75 promotions: ['r', 'n', 'b', 'q']
79 // Some variants don't have flags:
88 // En-passant captures allowed?
95 !!this.options
["crazyhouse"] ||
96 (!!this.options
["recycle"] && !this.options
["teleport"])
101 return !!this.options
["dark"];
104 // Some variants use click infos:
106 if (typeof x
!= "number") return null; //click on reserves
108 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
109 this.board
[x
][y
] == ""
112 start: {x: this.captured
.x
, y: this.captured
.y
},
117 c: this.captured
.c
, //this.turn,
130 // 3 --> d (column number to letter)
131 static CoordToColumn(colnum
) {
132 return String
.fromCharCode(97 + colnum
);
135 // d --> 3 (column letter to number)
136 static ColumnToCoord(columnStr
) {
137 return columnStr
.charCodeAt(0) - 97;
140 // 7 (numeric) --> 1 (str) [from black viewpoint].
141 static CoordToRow(rownum
) {
145 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
146 static RowToCoord(rownumStr
) {
147 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
148 return parseInt(rownumStr
, 30);
151 // a2 --> {x:2,y:0} (this is in fact a6)
152 static SquareToCoords(sq
) {
154 x: C
.RowToCoord(sq
[1]),
155 // NOTE: column is always one char => max 26 columns
156 y: C
.ColumnToCoord(sq
[0])
160 // {x:0,y:4} --> e0 (should be e8)
161 static CoordsToSquare(coords
) {
162 return C
.CoordToColumn(coords
.y
) + C
.CoordToRow(coords
.x
);
166 if (typeof x
== "number")
167 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
169 return `${this.containerId}|rsq-${x}-${y}`;
172 idToCoords(targetId
) {
173 if (!targetId
) return null; //outside page, maybe...
174 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
176 idParts
.length
< 2 ||
177 idParts
[0] != this.containerId
||
178 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
182 const squares
= idParts
[1].split('-');
183 if (squares
[0] == "sq")
184 return [ parseInt(squares
[1], 30), parseInt(squares
[2], 30) ];
185 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
186 return [squares
[1], squares
[2]];
192 // Turn "wb" into "B" (for FEN)
194 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
197 // Turn "p" into "bp" (for board)
199 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
202 // Setup the initial random-or-not (asymmetric-or-not) position
203 genRandInitFen(seed
) {
204 Random
.setSeed(seed
);
206 let fen
, flags
= "0707";
207 if (!this.options
.randomness
)
209 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
213 let pieces
= { w: new Array(8), b: new Array(8) };
215 // Shuffle pieces on first (and last rank if randomness == 2)
216 for (let c
of ["w", "b"]) {
217 if (c
== 'b' && this.options
.randomness
== 1) {
218 pieces
['b'] = pieces
['w'];
223 let positions
= ArrayFun
.range(8);
225 // Get random squares for bishops
226 let randIndex
= 2 * Random
.randInt(4);
227 const bishop1Pos
= positions
[randIndex
];
228 // The second bishop must be on a square of different color
229 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
230 const bishop2Pos
= positions
[randIndex_tmp
];
231 // Remove chosen squares
232 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
233 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
235 // Get random squares for knights
236 randIndex
= Random
.randInt(6);
237 const knight1Pos
= positions
[randIndex
];
238 positions
.splice(randIndex
, 1);
239 randIndex
= Random
.randInt(5);
240 const knight2Pos
= positions
[randIndex
];
241 positions
.splice(randIndex
, 1);
243 // Get random square for queen
244 randIndex
= Random
.randInt(4);
245 const queenPos
= positions
[randIndex
];
246 positions
.splice(randIndex
, 1);
248 // Rooks and king positions are now fixed,
249 // because of the ordering rook-king-rook
250 const rook1Pos
= positions
[0];
251 const kingPos
= positions
[1];
252 const rook2Pos
= positions
[2];
254 // Finally put the shuffled pieces in the board array
255 pieces
[c
][rook1Pos
] = "r";
256 pieces
[c
][knight1Pos
] = "n";
257 pieces
[c
][bishop1Pos
] = "b";
258 pieces
[c
][queenPos
] = "q";
259 pieces
[c
][kingPos
] = "k";
260 pieces
[c
][bishop2Pos
] = "b";
261 pieces
[c
][knight2Pos
] = "n";
262 pieces
[c
][rook2Pos
] = "r";
263 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
266 pieces
["b"].join("") +
267 "/pppppppp/8/8/8/8/PPPPPPPP/" +
268 pieces
["w"].join("").toUpperCase() +
272 // Add turn + flags + enpassant (+ reserve)
274 if (this.hasFlags
) parts
.push(`"flags":"${flags}"`);
275 if (this.hasEnpassant
) parts
.push('"enpassant":"-"');
276 if (this.hasReserve
) parts
.push('"reserve":"000000000000"');
277 if (this.options
["crazyhouse"]) parts
.push('"ispawn":"-"');
278 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
282 // "Parse" FEN: just return untransformed string data
284 const fenParts
= fen
.split(" ");
286 position: fenParts
[0],
288 movesCount: fenParts
[2]
290 if (fenParts
.length
> 3) res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
294 // Return current fen (game state)
297 this.getBaseFen() + " " +
298 this.getTurnFen() + " " +
302 if (this.hasFlags
) parts
.push(`"flags":"${this.getFlagsFen()}"`);
303 if (this.hasEnpassant
)
304 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
305 if (this.hasReserve
) parts
.push(`"reserve":"${this.getReserveFen()}"`);
306 if (this.options
["crazyhouse"])
307 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
308 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
312 // Position part of the FEN string
314 const format
= (count
) => {
315 // if more than 9 consecutive free spaces, break the integer,
316 // otherwise FEN parsing will fail.
317 if (count
<= 9) return count
;
318 // Most boards of size < 18:
319 if (count
<= 18) return "9" + (count
- 9);
321 return "99" + (count
- 18);
324 for (let i
= 0; i
< this.size
.y
; i
++) {
326 for (let j
= 0; j
< this.size
.x
; j
++) {
327 if (this.board
[i
][j
] == "") emptyCount
++;
329 if (emptyCount
> 0) {
330 // Add empty squares in-between
331 position
+= format(emptyCount
);
334 position
+= this.board2fen(this.board
[i
][j
]);
339 position
+= format(emptyCount
);
340 if (i
< this.size
.y
- 1) position
+= "/"; //separate rows
349 // Flags part of the FEN string
351 return ["w", "b"].map(c
=> {
352 return this.castleFlags
[c
].map(x
=> x
.toString(30)).join("");
356 // Enpassant part of the FEN string
358 if (!this.epSquare
) return "-"; //no en-passant
359 return C
.CoordsToSquare(this.epSquare
);
364 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
369 const coords
= Object
.keys(this.ispawn
);
370 if (coords
.length
== 0) return "-";
371 return coords
.map(C
.CoordsToSquare
).join(",");
374 // Set flags from fen (castle: white a,h then black a,h)
377 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 30)),
378 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 30))
385 // Fen string fully describes the game state
387 this.options
= o
.options
;
388 this.playerColor
= o
.color
;
389 this.afterPlay
= o
.afterPlay
;
392 if (!o
.fen
) o
.fen
= this.genRandInitFen(o
.seed
);
393 const fenParsed
= this.parseFen(o
.fen
);
394 this.board
= this.getBoard(fenParsed
.position
);
395 this.turn
= fenParsed
.turn
;
396 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
397 this.setOtherVariables(fenParsed
);
399 // Graphical (can use variables defined above)
400 this.containerId
= o
.element
;
401 this.graphicalInit();
404 // Turn position fen into double array ["wb","wp","bk",...]
406 const rows
= position
.split("/");
407 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
408 for (let i
= 0; i
< rows
.length
; i
++) {
410 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
411 const character
= rows
[i
][indexInRow
];
412 const num
= parseInt(character
, 10);
413 // If num is a number, just shift j:
414 if (!isNaN(num
)) j
+= num
;
415 // Else: something at position i,j
416 else board
[i
][j
++] = this.fen2board(character
);
422 // Some additional variables from FEN (variant dependant)
423 setOtherVariables(fenParsed
) {
424 // Set flags and enpassant:
425 if (this.hasFlags
) this.setFlags(fenParsed
.flags
);
426 if (this.hasEnpassant
)
427 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
428 if (this.hasReserve
) this.initReserves(fenParsed
.reserve
);
429 if (this.options
["crazyhouse"]) this.initIspawn(fenParsed
.ispawn
);
430 this.subTurn
= 1; //may be unused
431 if (this.options
["teleport"]) {
432 this.subTurnTeleport
= 1;
433 this.captured
= null;
435 if (this.options
["dark"]) {
436 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
);
437 // Setup enlightened: squares reachable by player side
438 this.updateEnlightened(false);
442 updateEnlightened(withGraphics
) {
443 let newEnlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
444 const pawnShift
= { w: -1, b: 1 };
445 // Add pieces positions + all squares reachable by moves (includes Zen):
446 // (watch out special pawns case)
447 for (let x
=0; x
<this.size
.x
; x
++) {
448 for (let y
=0; y
<this.size
.y
; y
++) {
449 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
451 newEnlightened
[x
][y
] = true;
452 if (this.getPiece(x
, y
) == "p") {
453 // Attacking squares wouldn't be highlighted if no captures:
454 this.pieces(this.playerColor
)["p"].attack
.forEach(step
=> {
455 const [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
456 if (this.onBoard(i
, j
) && this.board
[i
][j
] == "")
457 newEnlightened
[i
][j
] = true;
460 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
461 newEnlightened
[m
.end
.x
][m
.end
.y
] = true;
466 if (this.epSquare
) this.enlightEnpassant(newEnlightened
);
467 if (withGraphics
) this.graphUpdateEnlightened(newEnlightened
);
468 this.enlightened
= newEnlightened
;
471 // Include en-passant capturing square if any:
472 enlightEnpassant(newEnlightened
) {
473 const steps
= this.pieces(this.playerColor
)["p"].attack
;
474 for (let step
of steps
) {
475 const x
= this.epSquare
.x
- step
[0],
476 y
= this.computeY(this.epSquare
.y
- step
[1]);
478 this.onBoard(x
, y
) &&
479 this.getColor(x
, y
) == this.playerColor
&&
480 this.getPieceType(x
, y
) == "p"
482 newEnlightened
[x
][this.epSquare
.y
] = true;
488 // Apply diff this.enlightened --> newEnlightened on board
489 graphUpdateEnlightened(newEnlightened
) {
490 let container
= document
.getElementById(this.containerId
);
491 const r
= container
.getBoundingClientRect();
492 const pieceWidth
= this.getPieceWidth(r
.width
);
493 for (let x
=0; x
<this.size
.x
; x
++) {
494 for (let y
=0; y
<this.size
.y
; y
++) {
495 if (this.enlightened
[x
][y
] && !newEnlightened
[x
][y
]) {
496 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
497 elt
.classList
.add("in-shadow");
498 if (this.g_pieces
[x
][y
]) {
499 this.g_pieces
[x
][y
].remove();
500 this.g_pieces
[x
][y
] = null;
503 else if (!this.enlightened
[x
][y
] && newEnlightened
[x
][y
]) {
504 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
505 elt
.classList
.remove("in-shadow");
506 if (this.board
[x
][y
] != "") {
507 const color
= this.getColor(x
, y
);
508 const piece
= this.getPiece(x
, y
);
509 this.g_pieces
[x
][y
] = document
.createElement("piece");
511 this.pieces()[piece
]["class"],
512 color
== "w" ? "white" : "black"
514 newClasses
.forEach(cl
=> this.g_pieces
[x
][y
].classList
.add(cl
));
515 this.g_pieces
[x
][y
].style
.width
= pieceWidth
+ "px";
516 this.g_pieces
[x
][y
].style
.height
= pieceWidth
+ "px";
517 const [ip
, jp
] = this.getPixelPosition(x
, y
, r
);
518 this.g_pieces
[x
][y
].style
.transform
=
519 `translate(${ip}px,${jp}px)`;
520 container
.appendChild(this.g_pieces
[x
][y
]);
527 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
528 initReserves(reserveStr
) {
529 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
530 this.reserve
= { w: {}, b: {} };
531 const pieceName
= Object
.keys(this.pieces());
532 for (let i
of ArrayFun
.range(12)) {
533 if (i
< 6) this.reserve
['w'][pieceName
[i
]] = counts
[i
];
534 else this.reserve
['b'][pieceName
[i
-6]] = counts
[i
];
538 initIspawn(ispawnStr
) {
539 if (ispawnStr
!= "-") {
540 this.ispawn
= ispawnStr
.split(",").map(C
.SquareToCoords
)
541 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
543 else this.ispawn
= {};
546 getNbReservePieces(color
) {
548 Object
.values(this.reserve
[color
]).reduce(
549 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
556 getPieceWidth(rwidth
) {
557 return (rwidth
/ this.size
.y
);
560 getSquareWidth(rwidth
) {
561 return this.getPieceWidth(rwidth
);
564 getReserveSquareSize(rwidth
, nbR
) {
565 const sqSize
= this.getSquareWidth(rwidth
);
566 return Math
.min(sqSize
, rwidth
/ nbR
);
569 getReserveNumId(color
, piece
) {
570 return `${this.containerId}|rnum-${color}${piece}`;
574 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
575 window
.onresize
= () => this.re_drawBoardElements();
576 this.re_drawBoardElements();
577 this.initMouseEvents();
578 const container
= document
.getElementById(this.containerId
);
579 new ResizeObserver(this.rescale
).observe(container
);
582 re_drawBoardElements() {
583 const board
= this.getSvgChessboard();
584 const oppCol
= C
.GetOppCol(this.playerColor
);
585 let container
= document
.getElementById(this.containerId
);
586 container
.innerHTML
= "";
587 container
.insertAdjacentHTML('beforeend', board
);
588 let cb
= container
.querySelector("#" + this.containerId
+ "_SVG");
589 const aspectRatio
= this.size
.y
/ this.size
.x
;
590 // Compare window ratio width / height to aspectRatio:
591 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
592 let cbWidth
, cbHeight
;
593 if (windowRatio
<= aspectRatio
) {
594 // Limiting dimension is width:
595 cbWidth
= Math
.min(window
.innerWidth
, 767);
596 cbHeight
= cbWidth
/ aspectRatio
;
599 // Limiting dimension is height:
600 cbHeight
= Math
.min(window
.innerHeight
, 767);
601 cbWidth
= cbHeight
* aspectRatio
;
604 const sqSize
= cbWidth
/ this.size
.y
;
605 // NOTE: allocate space for reserves (up/down) even if they are empty
606 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
607 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
608 cbWidth
= cbHeight
* aspectRatio
;
611 container
.style
.width
= cbWidth
+ "px";
612 container
.style
.height
= cbHeight
+ "px";
613 // Center chessboard:
614 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
615 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
616 container
.style
.left
= spaceLeft
+ "px";
617 container
.style
.top
= spaceTop
+ "px";
618 // Give sizes instead of recomputing them,
619 // because chessboard might not be drawn yet.
628 // Get SVG board (background, no pieces)
630 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
631 const flipped
= (this.playerColor
== 'b');
636 id="${this.containerId}_SVG">
638 for (let i
=0; i
< sizeX
; i
++) {
639 for (let j
=0; j
< sizeY
; j
++) {
640 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
641 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
642 let classes
= this.getSquareColorClass(ii
, jj
);
643 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
644 classes
+= " in-shadow";
645 // NOTE: x / y reversed because coordinates system is reversed.
648 id="${this.coordsToId([ii, jj])}"
655 board
+= "</g></svg>";
659 // Generally light square bottom-right
660 getSquareColorClass(i
, j
) {
661 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
666 // Refreshing: delete old pieces first
667 for (let i
=0; i
<this.size
.x
; i
++) {
668 for (let j
=0; j
<this.size
.y
; j
++) {
669 if (this.g_pieces
[i
][j
]) {
670 this.g_pieces
[i
][j
].remove();
671 this.g_pieces
[i
][j
] = null;
676 else this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
677 let container
= document
.getElementById(this.containerId
);
678 if (!r
) r
= container
.getBoundingClientRect();
679 const pieceWidth
= this.getPieceWidth(r
.width
);
680 for (let i
=0; i
< this.size
.x
; i
++) {
681 for (let j
=0; j
< this.size
.y
; j
++) {
683 this.board
[i
][j
] != "" &&
684 (!this.options
["dark"] || this.enlightened
[i
][j
])
686 const color
= this.getColor(i
, j
);
687 const piece
= this.getPiece(i
, j
);
688 this.g_pieces
[i
][j
] = document
.createElement("piece");
689 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
690 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
691 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
692 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
693 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
694 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
695 container
.appendChild(this.g_pieces
[i
][j
]);
699 if (this.reserve
) this.re_drawReserve(['w', 'b'], r
);
702 // NOTE: assume !!this.reserve
703 re_drawReserve(colors
, r
) {
705 // Remove (old) reserve pieces
706 for (let c
of colors
) {
707 if (!this.reserve
[c
]) continue;
708 Object
.keys(this.reserve
[c
]).forEach(p
=> {
709 if (this.r_pieces
[c
][p
]) {
710 this.r_pieces
[c
][p
].remove();
711 delete this.r_pieces
[c
][p
];
712 const numId
= this.getReserveNumId(c
, p
);
713 document
.getElementById(numId
).remove();
716 let reservesDiv
= document
.getElementById("reserves_" + c
);
717 if (reservesDiv
) reservesDiv
.remove();
720 else this.r_pieces
= { 'w': {}, 'b': {} };
722 const container
= document
.getElementById(this.containerId
);
723 r
= container
.getBoundingClientRect();
725 for (let c
of colors
) {
726 if (!this.reserve
[c
]) continue;
727 const nbR
= this.getNbReservePieces(c
);
728 if (nbR
== 0) continue;
729 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
731 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
732 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
733 let rcontainer
= document
.createElement("div");
734 rcontainer
.id
= "reserves_" + c
;
735 rcontainer
.classList
.add("reserves");
736 rcontainer
.style
.left
= i0
+ "px";
737 rcontainer
.style
.top
= j0
+ "px";
738 // NOTE: +1 fix display bug on Firefox at least
739 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
740 rcontainer
.style
.height
= sqResSize
+ "px";
741 document
.getElementById("boardContainer").appendChild(rcontainer
);
742 for (let p
of Object
.keys(this.reserve
[c
])) {
743 if (this.reserve
[c
][p
] == 0) continue;
744 let r_cell
= document
.createElement("div");
745 r_cell
.id
= this.coordsToId([c
, p
]);
746 r_cell
.classList
.add("reserve-cell");
747 r_cell
.style
.width
= sqResSize
+ "px";
748 r_cell
.style
.height
= sqResSize
+ "px";
749 rcontainer
.appendChild(r_cell
);
750 let piece
= document
.createElement("piece");
751 const pieceSpec
= this.pieces(c
)[p
];
752 piece
.classList
.add(pieceSpec
["class"]);
753 piece
.classList
.add(c
== 'w' ? "white" : "black");
754 piece
.style
.width
= "100%";
755 piece
.style
.height
= "100%";
756 this.r_pieces
[c
][p
] = piece
;
757 r_cell
.appendChild(piece
);
758 let number
= document
.createElement("div");
759 number
.textContent
= this.reserve
[c
][p
];
760 number
.classList
.add("reserve-num");
761 number
.id
= this.getReserveNumId(c
, p
);
762 const fontSize
= "1.3em";
763 number
.style
.fontSize
= fontSize
;
764 number
.style
.fontSize
= fontSize
;
765 r_cell
.appendChild(number
);
771 updateReserve(color
, piece
, count
) {
772 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
773 piece
= "k"; //capturing cannibal king: back to king form
774 const oldCount
= this.reserve
[color
][piece
];
775 this.reserve
[color
][piece
] = count
;
776 // Redrawing is much easier if count==0
777 if ([oldCount
, count
].includes(0)) this.re_drawReserve([color
]);
779 const numId
= this.getReserveNumId(color
, piece
);
780 document
.getElementById(numId
).textContent
= count
;
784 // After resize event: no need to destroy/recreate pieces
786 let container
= document
.getElementById(this.containerId
);
787 if (!container
) return; //useful at initial loading
788 const r
= container
.getBoundingClientRect();
789 const newRatio
= r
.width
/ r
.height
;
790 const aspectRatio
= this.size
.y
/ this.size
.x
;
791 let newWidth
= r
.width
,
792 newHeight
= r
.height
;
793 if (newRatio
> aspectRatio
) {
794 newWidth
= r
.height
* aspectRatio
;
795 container
.style
.width
= newWidth
+ "px";
797 else if (newRatio
< aspectRatio
) {
798 newHeight
= r
.width
/ aspectRatio
;
799 container
.style
.height
= newHeight
+ "px";
801 const newX
= (window
.innerWidth
- newWidth
) / 2;
802 container
.style
.left
= newX
+ "px";
803 const newY
= (window
.innerHeight
- newHeight
) / 2;
804 container
.style
.top
= newY
+ "px";
805 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
806 const pieceWidth
= this.getPieceWidth(newWidth
);
807 for (let i
=0; i
< this.size
.x
; i
++) {
808 for (let j
=0; j
< this.size
.y
; j
++) {
809 if (this.board
[i
][j
] != "") {
810 // NOTE: could also use CSS transform "scale"
811 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
812 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
813 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
814 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
818 if (this.reserve
) this.rescaleReserve(newR
);
822 for (let c
of ['w','b']) {
823 if (!this.reserve
[c
]) continue;
824 const nbR
= this.getNbReservePieces(c
);
825 if (nbR
== 0) continue;
826 // Resize container first
827 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
828 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
829 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
830 let rcontainer
= document
.getElementById("reserves_" + c
);
831 rcontainer
.style
.left
= i0
+ "px";
832 rcontainer
.style
.top
= j0
+ "px";
833 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
834 rcontainer
.style
.height
= sqResSize
+ "px";
835 // And then reserve cells:
836 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
837 Object
.keys(this.reserve
[c
]).forEach(p
=> {
838 if (this.reserve
[c
][p
] == 0) return;
839 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
840 r_cell
.style
.width
= sqResSize
+ "px";
841 r_cell
.style
.height
= sqResSize
+ "px";
846 // Return the absolute pixel coordinates given current position.
847 // Our coordinate system differs from CSS one (x <--> y).
848 // We return here the CSS coordinates (more useful).
849 getPixelPosition(i
, j
, r
) {
850 const sqSize
= this.getSquareWidth(r
.width
);
851 if (i
< 0 || j
< 0) return [0, 0]; //piece vanishes
852 const flipped
= (this.playerColor
== 'b');
853 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
854 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
859 let container
= document
.getElementById(this.containerId
);
861 const getOffset
= e
=> {
862 if (e
.clientX
) return {x: e
.clientX
, y: e
.clientY
}; //Mouse
863 let touchLocation
= null;
864 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
865 // Touch screen, dragstart
866 touchLocation
= e
.targetTouches
[0];
867 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
868 // Touch screen, dragend
869 touchLocation
= e
.changedTouches
[0];
871 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
872 return [0, 0]; //Big trouble here =)
875 const centerOnCursor
= (piece
, e
) => {
876 const centerShift
= sqSize
/ 2;
877 const offset
= getOffset(e
);
878 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
879 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
884 startPiece
, curPiece
= null,
886 const mousedown
= (e
) => {
887 // Disable zoom on smartphones:
888 if (e
.touches
&& e
.touches
.length
> 1) e
.preventDefault();
889 r
= container
.getBoundingClientRect();
890 sqSize
= this.getSquareWidth(r
.width
);
891 const square
= this.idToCoords(e
.target
.id
);
893 const [i
, j
] = square
;
894 const move = this.doClick([i
, j
]);
895 if (move) this.playPlusVisual(move);
897 if (typeof i
!= "number") startPiece
= this.r_pieces
[i
][j
];
898 else if (this.g_pieces
[i
][j
]) startPiece
= this.g_pieces
[i
][j
];
899 if (startPiece
&& this.canIplay(i
, j
)) {
901 start
= { x: i
, y: j
};
902 curPiece
= startPiece
.cloneNode();
903 curPiece
.style
.transform
= "none";
904 curPiece
.style
.zIndex
= 5;
905 curPiece
.style
.width
= sqSize
+ "px";
906 curPiece
.style
.height
= sqSize
+ "px";
907 centerOnCursor(curPiece
, e
);
908 document
.getElementById("boardContainer").appendChild(curPiece
);
909 startPiece
.style
.opacity
= "0.4";
910 container
.style
.cursor
= "none";
916 const mousemove
= (e
) => {
919 centerOnCursor(curPiece
, e
);
921 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
922 // Attempt to prevent horizontal swipe...
926 const mouseup
= (e
) => {
927 const newR
= container
.getBoundingClientRect();
928 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
933 const [x
, y
] = [start
.x
, start
.y
];
936 container
.style
.cursor
= "pointer";
937 startPiece
.style
.opacity
= "1";
938 const offset
= getOffset(e
);
939 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
940 const sq
= this.idToCoords(landingElt
.id
);
943 // NOTE: clearly suboptimal, but much easier, and not a big deal.
944 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
945 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
946 const moves
= this.filterValid(potentialMoves
);
947 if (moves
.length
>= 2) this.showChoices(moves
, r
);
948 else if (moves
.length
== 1) this.playPlusVisual(moves
[0], r
);
953 if ('onmousedown' in window
) {
954 document
.addEventListener("mousedown", mousedown
);
955 document
.addEventListener("mousemove", mousemove
);
956 document
.addEventListener("mouseup", mouseup
);
958 if ('ontouchstart' in window
) {
959 // https://stackoverflow.com/a/42509310/12660887
960 document
.addEventListener("touchstart", mousedown
, {passive: false});
961 document
.addEventListener("touchmove", mousemove
, {passive: false});
962 document
.addEventListener("touchend", mouseup
, {passive: false});
964 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
967 showChoices(moves
, r
) {
968 let container
= document
.getElementById(this.containerId
);
969 let choices
= document
.createElement("div");
970 choices
.id
= "choices";
971 choices
.style
.width
= r
.width
+ "px";
972 choices
.style
.height
= r
.height
+ "px";
973 choices
.style
.left
= r
.x
+ "px";
974 choices
.style
.top
= r
.y
+ "px";
975 container
.style
.opacity
= "0.5";
976 let boardContainer
= document
.getElementById("boardContainer");
977 boardContainer
.appendChild(choices
);
978 const squareWidth
= this.getSquareWidth(r
.width
);
979 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
980 const firstUpTop
= (r
.height
- squareWidth
) / 2;
981 const color
= moves
[0].appear
[0].c
;
982 const callback
= (m
) => {
983 container
.style
.opacity
= "1";
984 boardContainer
.removeChild(choices
);
985 this.playPlusVisual(m
, r
);
987 for (let i
=0; i
< moves
.length
; i
++) {
988 let choice
= document
.createElement("div");
989 choice
.classList
.add("choice");
990 choice
.style
.width
= squareWidth
+ "px";
991 choice
.style
.height
= squareWidth
+ "px";
992 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
993 choice
.style
.top
= firstUpTop
+ "px";
994 choice
.style
.backgroundColor
= "lightyellow";
995 choice
.onclick
= () => callback(moves
[i
]);
996 const piece
= document
.createElement("piece");
997 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
998 piece
.classList
.add(pieceSpec
["class"]);
999 piece
.classList
.add(color
== 'w' ? "white" : "black");
1000 piece
.style
.width
= "100%";
1001 piece
.style
.height
= "100%";
1002 choice
.appendChild(piece
);
1003 choices
.appendChild(choice
);
1011 return { "x": 8, "y": 8 };
1014 // Color of thing on square (i,j). 'undefined' if square is empty
1016 return this.board
[i
][j
].charAt(0);
1019 // Assume square i,j isn't empty
1021 return this.board
[i
][j
].charAt(1);
1024 // Piece type on square (i,j)
1025 getPieceType(i
, j
) {
1026 const p
= this.board
[i
][j
].charAt(1);
1027 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1030 // Get opponent color
1031 static GetOppCol(color
) {
1032 return (color
== "w" ? "b" : "w");
1035 // Can thing on square1 take thing on square2
1036 canTake([x1
, y1
], [x2
, y2
]) {
1038 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
)) ||
1040 (this.options
["recycle"] || this.options
["teleport"]) &&
1041 this.getPieceType(x2
, y2
) != "k"
1046 // Is (x,y) on the chessboard?
1048 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1051 // Used in interface: 'side' arg == player color
1054 this.playerColor
== this.turn
&&
1056 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1057 (typeof x
== "string" && x
== this.turn
) //reserve
1062 ////////////////////////
1063 // PIECES SPECIFICATIONS
1066 const pawnShift
= (color
== "w" ? -1 : 1);
1070 steps: [[pawnShift
, 0]],
1072 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1077 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1083 [1, 2], [1, -2], [-1, 2], [-1, -2],
1084 [2, 1], [-2, 1], [2, -1], [-2, -1]
1091 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1097 [0, 1], [0, -1], [1, 0], [-1, 0],
1098 [1, 1], [1, -1], [-1, 1], [-1, -1]
1105 [0, 1], [0, -1], [1, 0], [-1, 0],
1106 [1, 1], [1, -1], [-1, 1], [-1, -1]
1111 's': { "class": "king-pawn" },
1112 'u': { "class": "king-rook" },
1113 'o': { "class": "king-knight" },
1114 'c': { "class": "king-bishop" },
1115 't': { "class": "king-queen" }
1119 ////////////////////
1122 // For Cylinder: get Y coordinate
1124 if (!this.options
["cylinder"]) return y
;
1125 let res
= y
% this.size
.y
;
1126 if (res
< 0) res
+= this.size
.y
;
1130 // Stop at the first capture found
1131 atLeastOneCapture(color
) {
1132 color
= color
|| this.turn
;
1133 const oppCol
= C
.GetOppCol(color
);
1134 for (let i
= 0; i
< this.size
.x
; i
++) {
1135 for (let j
= 0; j
< this.size
.y
; j
++) {
1136 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1137 const specs
= this.pieces(color
)[this.getPieceType(i
, j
)];
1138 const steps
= specs
.attack
|| specs
.steps
;
1139 outerLoop: for (let step
of steps
) {
1140 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1141 let stepCounter
= 1;
1142 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1143 if (specs
.range
<= stepCounter
++) continue outerLoop
;
1145 jj
= this.computeY(jj
+ step
[1]);
1148 this.onBoard(ii
, jj
) &&
1149 this.getColor(ii
, jj
) == oppCol
&&
1151 [this.getBasicMove([i
, j
], [ii
, jj
])]
1163 getDropMovesFrom([c
, p
]) {
1164 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1165 // (but not necessarily otherwise)
1166 if (this.reserve
[c
][p
] == 0) return [];
1168 for (let i
=0; i
<this.size
.x
; i
++) {
1169 for (let j
=0; j
<this.size
.y
; j
++) {
1170 // TODO: rather simplify this "if" and add post-condition: more general
1172 this.board
[i
][j
] == "" &&
1173 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1176 (c
== 'w' && i
< this.size
.x
- 1) ||
1182 start: {x: c
, y: p
},
1184 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1194 // All possible moves from selected square
1195 getPotentialMovesFrom(sq
, color
) {
1196 if (typeof sq
[0] == "string") return this.getDropMovesFrom(sq
);
1197 if (this.options
["madrasi"] && this.isImmobilized(sq
)) return [];
1198 const piece
= this.getPieceType(sq
[0], sq
[1]);
1200 if (piece
== "p") moves
= this.getPotentialPawnMoves(sq
);
1201 else moves
= this.getPotentialMovesOf(piece
, sq
);
1205 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1207 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1209 return this.postProcessPotentialMoves(moves
);
1212 postProcessPotentialMoves(moves
) {
1213 if (moves
.length
== 0) return [];
1214 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1215 const oppCol
= C
.GetOppCol(color
);
1217 if (this.options
["capture"] && this.atLeastOneCapture()) {
1218 // Filter out non-capturing moves (not using m.vanish because of
1219 // self captures of Recycle and Teleport).
1220 moves
= moves
.filter(m
=> {
1222 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1223 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1228 if (this.options
["atomic"]) {
1229 moves
.forEach(m
=> {
1231 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1232 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1245 for (let step
of steps
) {
1246 let x
= m
.end
.x
+ step
[0];
1247 let y
= this.computeY(m
.end
.y
+ step
[1]);
1249 this.onBoard(x
, y
) &&
1250 this.board
[x
][y
] != "" &&
1251 this.getPieceType(x
, y
) != "p"
1255 p: this.getPiece(x
, y
),
1256 c: this.getColor(x
, y
),
1263 if (!this.options
["rifle"]) m
.appear
.pop(); //nothin appears
1269 this.options
["cannibal"] &&
1270 this.options
["rifle"] &&
1271 this.pawnSpecs
.promotions
1273 // In this case a rifle-capture from last rank may promote a pawn
1274 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1276 moves
.forEach(m
=> {
1278 m
.start
.x
== lastRank
&&
1279 m
.appear
.length
>= 1 &&
1280 m
.appear
[0].p
== "p" &&
1281 m
.appear
[0].x
== m
.start
.x
&&
1282 m
.appear
[0].y
== m
.start
.y
1284 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1285 m
.appear
[0].p
= this.pawnSpecs
.promotions
[0];
1286 for (let i
=1; i
<this.pawnSpecs
.promotions
.length
; i
++) {
1287 let newMv
= JSON
.parse(JSON
.stringify(m
));
1288 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1289 newMoves
.push(newMv
);
1293 Array
.prototype.push
.apply(moves
, newMoves
);
1299 static get CannibalKings() {
1309 static get CannibalKingCode() {
1323 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1328 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1329 isImmobilized([x
, y
]) {
1330 const color
= this.getColor(x
, y
);
1331 const oppCol
= C
.GetOppCol(color
);
1332 const piece
= this.getPieceType(x
, y
);
1333 const stepSpec
= this.pieces(color
)[piece
];
1334 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1335 outerLoop: for (let step
of steps
) {
1336 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1337 let stepCounter
= 1;
1338 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1339 if (range
<= stepCounter
++) continue outerLoop
;
1341 j
= this.computeY(j
+ step
[1]);
1344 this.onBoard(i
, j
) &&
1345 this.getColor(i
, j
) == oppCol
&&
1346 this.getPieceType(i
, j
) == piece
1354 // Generic method to find possible moves of "sliding or jumping" pieces
1355 getPotentialMovesOf(piece
, [x
, y
]) {
1356 const color
= this.getColor(x
, y
);
1357 const stepSpec
= this.pieces(color
)[piece
];
1358 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1360 let explored
= {}; //for Cylinder mode
1361 outerLoop: for (let step
of steps
) {
1362 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1363 let stepCounter
= 1;
1365 this.onBoard(i
, j
) &&
1366 this.board
[i
][j
] == "" &&
1367 !explored
[i
+ "." + j
]
1369 explored
[i
+ "." + j
] = true;
1370 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1371 if (range
<= stepCounter
++) continue outerLoop
;
1373 j
= this.computeY(j
+ step
[1]);
1376 this.onBoard(i
, j
) &&
1378 !this.options
["zen"] ||
1379 this.getPieceType(i
, j
) == "k" ||
1380 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1382 this.canTake([x
, y
], [i
, j
]) &&
1383 !explored
[i
+ "." + j
]
1385 explored
[i
+ "." + j
] = true;
1386 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1389 if (this.options
["zen"])
1390 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1394 getZenCaptures(x
, y
) {
1396 // Find reverse captures (opponent takes)
1397 const color
= this.getColor(x
, y
);
1398 const pieceType
= this.getPieceType(x
, y
);
1399 const oppCol
= C
.GetOppCol(color
);
1400 const pieces
= this.pieces(oppCol
);
1401 Object
.keys(pieces
).forEach(p
=> {
1404 (this.options
["cannibal"] && C
.CannibalKings
[p
])
1406 return; //king isn't captured this way
1408 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1409 if (!steps
) return; //cannibal king for example (TODO...)
1410 const range
= pieces
[p
].range
;
1411 steps
.forEach(s
=> {
1412 // From x,y: revert step
1413 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1414 let stepCounter
= 1;
1415 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1416 if (range
<= stepCounter
++) return;
1418 j
= this.computeY(j
- s
[1]);
1421 this.onBoard(i
, j
) &&
1422 this.getPieceType(i
, j
) == p
&&
1423 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1424 this.canTake([i
, j
], [x
, y
])
1426 if (pieceType
!= "p") moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1427 else this.addPawnMoves([x
, y
], [i
, j
], moves
);
1434 // Build a regular move from its initial and destination squares.
1435 // tr: transformation
1436 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1437 const initColor
= this.getColor(sx
, sy
);
1438 const initPiece
= this.getPiece(sx
, sy
);
1439 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1443 start: {x:sx
, y:sy
},
1447 !this.options
["rifle"] ||
1448 this.board
[ex
][ey
] == "" ||
1449 destColor
== initColor
//Recycle, Teleport
1455 c: !!tr
? tr
.c : initColor
,
1456 p: !!tr
? tr
.p : initPiece
1468 if (this.board
[ex
][ey
] != "") {
1473 c: this.getColor(ex
, ey
),
1474 p: this.getPiece(ex
, ey
)
1477 if (this.options
["rifle"])
1478 // Rifle captures are tricky in combination with Atomic etc,
1479 // so it's useful to mark the move :
1481 if (this.options
["cannibal"] && destColor
!= initColor
) {
1482 const lastIdx
= mv
.vanish
.length
- 1;
1483 let trPiece
= mv
.vanish
[lastIdx
].p
;
1484 if (this.isKing(this.getPiece(sx
, sy
)))
1485 trPiece
= C
.CannibalKingCode
[trPiece
];
1486 if (mv
.appear
.length
>= 1) mv
.appear
[0].p
= trPiece
;
1487 else if (this.options
["rifle"]) {
1510 // En-passant square, if any
1511 getEpSquare(moveOrSquare
) {
1512 if (typeof moveOrSquare
=== "string") {
1513 const square
= moveOrSquare
;
1514 if (square
== "-") return undefined;
1515 return C
.SquareToCoords(square
);
1517 // Argument is a move:
1518 const move = moveOrSquare
;
1519 const s
= move.start
,
1523 Math
.abs(s
.x
- e
.x
) == 2 &&
1524 // Next conditions for variants like Atomic or Rifle, Recycle...
1525 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1526 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1533 return undefined; //default
1536 // Special case of en-passant captures: treated separately
1537 getEnpassantCaptures([x
, y
], shiftX
) {
1538 const color
= this.getColor(x
, y
);
1539 const oppCol
= C
.GetOppCol(color
);
1540 let enpassantMove
= null;
1543 this.epSquare
.x
== x
+ shiftX
&&
1544 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1545 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1547 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1548 this.board
[epx
][epy
] = oppCol
+ "p";
1549 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1550 this.board
[epx
][epy
] = "";
1551 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1552 enpassantMove
.vanish
[lastIdx
].x
= x
;
1554 return !!enpassantMove
? [enpassantMove
] : [];
1557 // Consider all potential promotions.
1558 // NOTE: "promotions" arg = special override for Hiddenqueen variant
1559 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1560 let finalPieces
= ["p"];
1561 const color
= this.getColor(x1
, y1
);
1562 const oppCol
= C
.GetOppCol(color
);
1563 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1565 x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == "");
1566 if (promotionOk
&& !this.options
["pawnfall"]) {
1568 this.options
["cannibal"] &&
1569 this.board
[x2
][y2
] != "" &&
1570 this.getColor(x2
, y2
) == oppCol
1572 finalPieces
= [this.getPieceType(x2
, y2
)];
1574 else if (promotions
) finalPieces
= promotions
;
1575 else if (this.pawnSpecs
.promotions
)
1576 finalPieces
= this.pawnSpecs
.promotions
;
1578 for (let piece
of finalPieces
) {
1579 const tr
= !this.options
["pawnfall"] && piece
!= "p"
1580 ? { c: color
, p: piece
}
1582 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1583 if (promotionOk
&& this.options
["pawnfall"]) {
1584 newMove
.appear
.shift();
1585 newMove
.pawnfall
= true; //required in prePlay()
1587 moves
.push(newMove
);
1591 // What are the pawn moves from square x,y ?
1592 getPotentialPawnMoves([x
, y
], promotions
) {
1593 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1594 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1595 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1596 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1597 const forward
= (color
== 'w' ? -1 : 1);
1599 // Pawn movements in shiftX direction:
1600 const getPawnMoves
= (shiftX
) => {
1602 // NOTE: next condition is generally true (no pawn on last rank)
1603 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1604 if (this.board
[x
+ shiftX
][y
] == "") {
1605 // One square forward (or backward)
1606 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1607 // Next condition because pawns on 1st rank can generally jump
1609 this.pawnSpecs
.twoSquares
&&
1613 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1616 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1620 shiftX
== forward
&&
1621 this.board
[x
+ 2 * shiftX
][y
] == ""
1624 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1626 this.pawnSpecs
.threeSquares
&&
1627 this.board
[x
+ 3 * shiftX
, y
] == ""
1629 // Three squares jump
1630 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1636 if (this.pawnSpecs
.canCapture
) {
1637 for (let shiftY
of [-1, 1]) {
1638 const yCoord
= this.computeY(y
+ shiftY
);
1639 if (yCoord
>= 0 && yCoord
< sizeY
) {
1641 this.board
[x
+ shiftX
][yCoord
] != "" &&
1642 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1644 !this.options
["zen"] ||
1645 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1649 [x
, y
], [x
+ shiftX
, yCoord
],
1654 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1655 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1656 this.board
[x
- shiftX
][yCoord
] != "" &&
1657 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1659 !this.options
["zen"] ||
1660 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1664 [x
, y
], [x
- shiftX
, yCoord
],
1675 let pMoves
= getPawnMoves(pawnShiftX
);
1676 if (this.pawnSpecs
.bidirectional
)
1677 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1679 if (this.hasEnpassant
) {
1680 // NOTE: backward en-passant captures are not considered
1681 // because no rules define them (for now).
1682 Array
.prototype.push
.apply(
1684 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1688 if (this.options
["zen"])
1689 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1694 // "castleInCheck" arg to let some variants castle under check
1695 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1696 const c
= this.getColor(x
, y
);
1699 const oppCol
= C
.GetOppCol(c
);
1703 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1704 const castlingKing
= this.getPiece(x
, y
);
1705 castlingCheck: for (
1708 castleSide
++ //large, then small
1710 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
) continue;
1711 // If this code is reached, rook and king are on initial position
1713 // NOTE: in some variants this is not a rook
1714 const rookPos
= this.castleFlags
[c
][castleSide
];
1715 const castlingPiece
= this.getPiece(x
, rookPos
);
1717 this.board
[x
][rookPos
] == "" ||
1718 this.getColor(x
, rookPos
) != c
||
1719 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1721 // Rook is not here, or changed color (see Benedict)
1724 // Nothing on the path of the king ? (and no checks)
1725 const finDist
= finalSquares
[castleSide
][0] - y
;
1726 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1730 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1732 this.board
[x
][i
] != "" &&
1733 // NOTE: next check is enough, because of chessboard constraints
1734 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1737 continue castlingCheck
;
1740 } while (i
!= finalSquares
[castleSide
][0]);
1741 // Nothing on the path to the rook?
1742 step
= (castleSide
== 0 ? -1 : 1);
1743 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1744 if (this.board
[x
][i
] != "") continue castlingCheck
;
1747 // Nothing on final squares, except maybe king and castling rook?
1748 for (i
= 0; i
< 2; i
++) {
1750 finalSquares
[castleSide
][i
] != rookPos
&&
1751 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1753 finalSquares
[castleSide
][i
] != y
||
1754 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1757 continue castlingCheck
;
1761 // If this code is reached, castle is valid
1767 y: finalSquares
[castleSide
][0],
1773 y: finalSquares
[castleSide
][1],
1779 // King might be initially disguised (Titan...)
1780 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1781 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1784 Math
.abs(y
- rookPos
) <= 2
1785 ? { x: x
, y: rookPos
}
1786 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1794 ////////////////////
1797 // Is (king at) given position under check by "color" ?
1798 underCheck([x
, y
], color
) {
1799 if (this.options
["taking"] || this.options
["dark"]) return false;
1800 color
= color
|| C
.GetOppCol(this.getColor(x
, y
));
1801 const pieces
= this.pieces(color
);
1802 return Object
.keys(pieces
).some(p
=> {
1803 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1807 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1808 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1809 if (!steps
) return false; //cannibal king, for example
1810 const range
= stepSpec
.range
;
1811 let explored
= {}; //for Cylinder mode
1812 outerLoop: for (let step
of steps
) {
1813 let rx
= x
- step
[0],
1814 ry
= this.computeY(y
- step
[1]);
1815 let stepCounter
= 1;
1817 this.onBoard(rx
, ry
) &&
1818 this.board
[rx
][ry
] == "" &&
1819 !explored
[rx
+ "." + ry
]
1821 explored
[rx
+ "." + ry
] = true;
1822 if (range
<= stepCounter
++) continue outerLoop
;
1824 ry
= this.computeY(ry
- step
[1]);
1827 this.onBoard(rx
, ry
) &&
1828 this.board
[rx
][ry
] != "" &&
1829 this.getPieceType(rx
, ry
) == piece
&&
1830 this.getColor(rx
, ry
) == color
&&
1831 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1839 // Stop at first king found (TODO: multi-kings)
1840 searchKingPos(color
) {
1841 for (let i
=0; i
< this.size
.x
; i
++) {
1842 for (let j
=0; j
< this.size
.y
; j
++) {
1843 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1847 return [-1, -1]; //king not found
1850 filterValid(moves
) {
1851 if (moves
.length
== 0) return [];
1852 const color
= this.turn
;
1853 const oppCol
= C
.GetOppCol(color
);
1854 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1855 // Forbid moves either giving check or exploding opponent's king:
1856 const oppKingPos
= this.searchKingPos(oppCol
);
1857 moves
= moves
.filter(m
=> {
1859 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1860 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1863 this.playOnBoard(m
);
1864 const res
= !this.underCheck(oppKingPos
, color
);
1865 this.undoOnBoard(m
);
1869 if (this.options
["taking"] || this.options
["dark"]) return moves
;
1870 const kingPos
= this.searchKingPos(color
);
1871 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1872 return moves
.filter(m
=> {
1873 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1874 if (!filtered
[key
]) {
1875 this.playOnBoard(m
);
1876 let square
= kingPos
,
1877 res
= true; //a priori valid
1878 if (m
.vanish
.some(v
=> {
1879 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1881 // Search king in appear array:
1883 m
.appear
.findIndex(a
=> {
1884 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1886 if (newKingIdx
>= 0)
1887 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1890 res
&&= !this.underCheck(square
, oppCol
);
1891 this.undoOnBoard(m
);
1892 filtered
[key
] = res
;
1895 return filtered
[key
];
1902 // Aggregate flags into one object
1904 return this.castleFlags
;
1907 // Reverse operation
1908 disaggregateFlags(flags
) {
1909 this.castleFlags
= flags
;
1912 // Apply a move on board
1914 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1915 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1917 // Un-apply the played move
1919 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1920 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1923 updateCastleFlags(move) {
1924 // Update castling flags if start or arrive from/at rook/king locations
1925 move.appear
.concat(move.vanish
).forEach(psq
=> {
1927 this.board
[psq
.x
][psq
.y
] != "" &&
1928 this.getPieceType(psq
.x
, psq
.y
) == "k"
1930 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1932 // NOTE: not "else if" because king can capture enemy rook...
1934 if (psq
.x
== 0) c
= "b";
1935 else if (psq
.x
== this.size
.x
- 1) c
= "w";
1937 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1938 if (fidx
>= 0) this.castleFlags
[c
][fidx
] = this.size
.y
;
1945 typeof move.start
.x
== "number" &&
1946 (!this.options
["teleport"] || this.subTurnTeleport
== 1)
1948 // OK, not a drop move
1951 // If flags already off, no need to re-check:
1952 Object
.keys(this.castleFlags
).some(c
=> {
1953 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1955 this.updateCastleFlags(move);
1957 const initSquare
= C
.CoordsToSquare(move.start
);
1959 this.options
["crazyhouse"] &&
1960 (!this.options
["rifle"] || !move.capture
)
1962 if (this.ispawn
[initSquare
]) {
1963 delete this.ispawn
[initSquare
];
1964 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1967 move.vanish
[0].p
== "p" &&
1968 move.appear
[0].p
!= "p"
1970 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1974 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1975 if (this.hasReserve
&& !move.pawnfall
) {
1976 const color
= this.turn
;
1977 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1978 // Something appears = dropped on board (some exceptions, Chakart...)
1979 const piece
= move.appear
[i
].p
;
1980 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1982 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1983 // Something vanish: add to reserve except if recycle & opponent
1984 const piece
= move.vanish
[i
].p
;
1985 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1986 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1993 if (this.hasEnpassant
) this.epSquare
= this.getEpSquare(move);
1994 this.playOnBoard(move);
1995 this.postPlay(move);
1999 const color
= this.turn
;
2000 const oppCol
= C
.GetOppCol(color
);
2001 if (this.options
["dark"]) this.updateEnlightened(true);
2002 if (this.options
["teleport"]) {
2004 this.subTurnTeleport
== 1 &&
2005 move.vanish
.length
> move.appear
.length
&&
2006 move.vanish
[move.vanish
.length
- 1].c
== color
2008 const v
= move.vanish
[move.vanish
.length
- 1];
2009 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2010 this.subTurnTeleport
= 2;
2013 this.subTurnTeleport
= 1;
2014 this.captured
= null;
2016 if (this.options
["balance"]) {
2017 if (![1, 3].includes(this.movesCount
)) this.turn
= oppCol
;
2022 this.options
["doublemove"] &&
2023 this.movesCount
>= 1 &&
2026 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2028 const oppKingPos
= this.searchKingPos(oppCol
);
2029 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
2040 // "Stop at the first move found"
2041 atLeastOneMove(color
) {
2042 color
= color
|| this.turn
;
2043 for (let i
= 0; i
< this.size
.x
; i
++) {
2044 for (let j
= 0; j
< this.size
.y
; j
++) {
2045 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2046 // NOTE: in fact searching for all potential moves from i,j.
2047 // I don't believe this is an issue, for now at least.
2048 const moves
= this.getPotentialMovesFrom([i
, j
]);
2049 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2053 if (this.hasReserve
&& this.reserve
[color
]) {
2054 for (let p
of Object
.keys(this.reserve
[color
])) {
2055 const moves
= this.getDropMovesFrom([color
, p
]);
2056 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2062 // What is the score ? (Interesting if game is over)
2063 getCurrentScore(move) {
2064 const color
= this.turn
;
2065 const oppCol
= C
.GetOppCol(color
);
2066 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2067 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0) return "1/2";
2068 if (kingPos
[0][0] < 0) return (color
== "w" ? "0-1" : "1-0");
2069 if (kingPos
[1][0] < 0) return (color
== "w" ? "1-0" : "0-1");
2070 if (this.atLeastOneMove()) return "*";
2071 // No valid move: stalemate or checkmate?
2072 if (!this.underCheck(kingPos
, color
)) return "1/2";
2074 return (color
== "w" ? "0-1" : "1-0");
2077 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2078 playVisual(move, r
) {
2079 move.vanish
.forEach(v
=> {
2080 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
2081 this.g_pieces
[v
.x
][v
.y
].remove();
2082 this.g_pieces
[v
.x
][v
.y
] = null;
2085 let container
= document
.getElementById(this.containerId
);
2086 if (!r
) r
= container
.getBoundingClientRect();
2087 const pieceWidth
= this.getPieceWidth(r
.width
);
2088 move.appear
.forEach(a
=> {
2089 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
]) return;
2090 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2091 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2092 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2093 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2094 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2095 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2096 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2097 container
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2101 playPlusVisual(move, r
) {
2102 this.playVisual(move, r
);
2104 this.afterPlay(move); //user method
2107 // Assumes reserve on top (usage case otherwise? TODO?)
2108 getReserveShift(c
, p
, r
) {
2111 for (let pi
of Object
.keys(this.reserve
[c
])) {
2112 if (this.reserve
[c
][pi
] == 0) continue;
2113 if (pi
== p
) ridx
= nbR
;
2116 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2117 return [-ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2120 animate(move, callback
) {
2121 if (this.noAnimate
) {
2125 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2126 const dropMove
= (typeof i1
== "string");
2127 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2128 let startPiece
= startArray
[i1
][j1
];
2129 let container
= document
.getElementById(this.containerId
);
2130 const clonePiece
= (
2132 this.options
["rifle"] ||
2133 (this.options
["teleport"] && this.subTurnTeleport
== 2)
2136 startPiece
= startPiece
.cloneNode();
2137 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "0";
2138 if (this.options
["teleport"] && this.subTurnTeleport
== 2) {
2139 const pieces
= this.pieces();
2140 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2141 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2142 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2145 container
.appendChild(startPiece
);
2147 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2151 i1
== this.playerColor
? this.size
.x : 0,
2152 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2155 else startCoords
= [i1
, j1
];
2156 const r
= container
.getBoundingClientRect();
2157 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2159 if (dropMove
) rs
= this.getReserveShift(i1
, j1
, r
);
2161 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2162 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2163 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2164 const duration
= 0.2 + multFact
* 0.3;
2165 const initTransform
= startPiece
.style
.transform
;
2166 startPiece
.style
.transform
=
2167 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2168 startPiece
.style
.transitionDuration
= duration
+ "s";
2172 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "1";
2173 startPiece
.remove();
2176 startPiece
.style
.transform
= initTransform
;
2177 startPiece
.style
.transitionDuration
= "0s";
2185 playReceivedMove(moves
, callback
) {
2186 const launchAnimation
= () => {
2188 document
.getElementById(this.containerId
).getBoundingClientRect();
2189 const animateRec
= i
=> {
2190 this.animate(moves
[i
], () => {
2191 this.playVisual(moves
[i
], r
);
2192 this.play(moves
[i
]);
2193 if (i
< moves
.length
- 1) setTimeout(() => animateRec(i
+1), 300);
2199 // Delay if user wasn't focused:
2200 const checkDisplayThenAnimate
= (delay
) => {
2201 if (boardContainer
.style
.display
== "none") {
2202 alert("New move! Let's go back to game...");
2203 document
.getElementById("gameInfos").style
.display
= "none";
2204 boardContainer
.style
.display
= "block";
2205 setTimeout(launchAnimation
, 700);
2207 else setTimeout(launchAnimation
, delay
|| 0);
2209 let boardContainer
= document
.getElementById("boardContainer");
2210 if (document
.hidden
) {
2211 document
.onvisibilitychange
= () => {
2212 document
.onvisibilitychange
= undefined;
2213 checkDisplayThenAnimate(700);
2216 else checkDisplayThenAnimate();