9100173c2b17bf1b3d0044acdabbd63973ea74d9
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 /////////////////////////
11 // VARIANT SPECIFICATIONS
13 // Some variants have specific options, like the number of pawns in Monster,
14 // or the board size for Pandemonium.
15 // Users can generally select a randomness level from 0 to 2.
16 static get Options() {
18 // NOTE: some options are required for FEN generation, some aren't.
21 variable: "randomness",
24 { label: "Deterministic", value: 0 },
25 { label: "Symmetric random", value: 1 },
26 { label: "Asymmetric random", value: 2 }
31 label: "Capture king",
36 label: "Falling pawn",
41 // Game modifiers (using "elementary variants"). Default: false
44 "balance", //takes precedence over doublemove & progressive
48 "cylinder", //ok with all
52 "progressive", //(natural) priority over doublemove
61 // Pawns specifications
64 directions: { 'w': -1, 'b': 1 },
65 initShift: { w: 1, b: 1 },
69 captureBackward: false,
71 promotions: ['r', 'n', 'b', 'q']
75 // Some variants don't have flags:
84 // En-passant captures allowed?
91 !!this.options
["crazyhouse"] ||
92 (!!this.options
["recycle"] && !this.options
["teleport"])
97 return !!this.options
["dark"];
100 // Some variants use click infos:
102 if (typeof x
!= "number") return null; //click on reserves
104 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
105 this.board
[x
][y
] == ""
108 start: {x: this.captured
.x
, y: this.captured
.y
},
113 c: this.captured
.c
, //this.turn,
126 // 3 --> d (column number to letter)
127 static CoordToColumn(colnum
) {
128 return String
.fromCharCode(97 + colnum
);
131 // d --> 3 (column letter to number)
132 static ColumnToCoord(columnStr
) {
133 return columnStr
.charCodeAt(0) - 97;
136 // 7 (numeric) --> 1 (str) [from black viewpoint].
137 static CoordToRow(rownum
) {
141 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
142 static RowToCoord(rownumStr
) {
143 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
144 return parseInt(rownumStr
, 30);
147 // a2 --> {x:2,y:0} (this is in fact a6)
148 static SquareToCoords(sq
) {
150 x: C
.RowToCoord(sq
[1]),
151 // NOTE: column is always one char => max 26 columns
152 y: C
.ColumnToCoord(sq
[0])
156 // {x:0,y:4} --> e0 (should be e8)
157 static CoordsToSquare(coords
) {
158 return C
.CoordToColumn(coords
.y
) + C
.CoordToRow(coords
.x
);
162 if (typeof x
== "number")
163 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
165 return `${this.containerId}|rsq-${x}-${y}`;
168 idToCoords(targetId
) {
169 if (!targetId
) return null; //outside page, maybe...
170 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
172 idParts
.length
< 2 ||
173 idParts
[0] != this.containerId
||
174 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
178 const squares
= idParts
[1].split('-');
179 if (squares
[0] == "sq")
180 return [ parseInt(squares
[1], 30), parseInt(squares
[2], 30) ];
181 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
182 return [squares
[1], squares
[2]];
188 // Turn "wb" into "B" (for FEN)
190 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
193 // Turn "p" into "bp" (for board)
195 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
198 // Setup the initial random-or-not (asymmetric-or-not) position
199 genRandInitFen(seed
) {
200 Random
.setSeed(seed
);
202 let fen
, flags
= "0707";
203 if (!this.options
.randomness
)
205 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
209 let pieces
= { w: new Array(8), b: new Array(8) };
211 // Shuffle pieces on first (and last rank if randomness == 2)
212 for (let c
of ["w", "b"]) {
213 if (c
== 'b' && this.options
.randomness
== 1) {
214 pieces
['b'] = pieces
['w'];
219 let positions
= ArrayFun
.range(8);
221 // Get random squares for bishops
222 let randIndex
= 2 * Random
.randInt(4);
223 const bishop1Pos
= positions
[randIndex
];
224 // The second bishop must be on a square of different color
225 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
226 const bishop2Pos
= positions
[randIndex_tmp
];
227 // Remove chosen squares
228 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
229 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
231 // Get random squares for knights
232 randIndex
= Random
.randInt(6);
233 const knight1Pos
= positions
[randIndex
];
234 positions
.splice(randIndex
, 1);
235 randIndex
= Random
.randInt(5);
236 const knight2Pos
= positions
[randIndex
];
237 positions
.splice(randIndex
, 1);
239 // Get random square for queen
240 randIndex
= Random
.randInt(4);
241 const queenPos
= positions
[randIndex
];
242 positions
.splice(randIndex
, 1);
244 // Rooks and king positions are now fixed,
245 // because of the ordering rook-king-rook
246 const rook1Pos
= positions
[0];
247 const kingPos
= positions
[1];
248 const rook2Pos
= positions
[2];
250 // Finally put the shuffled pieces in the board array
251 pieces
[c
][rook1Pos
] = "r";
252 pieces
[c
][knight1Pos
] = "n";
253 pieces
[c
][bishop1Pos
] = "b";
254 pieces
[c
][queenPos
] = "q";
255 pieces
[c
][kingPos
] = "k";
256 pieces
[c
][bishop2Pos
] = "b";
257 pieces
[c
][knight2Pos
] = "n";
258 pieces
[c
][rook2Pos
] = "r";
259 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
262 pieces
["b"].join("") +
263 "/pppppppp/8/8/8/8/PPPPPPPP/" +
264 pieces
["w"].join("").toUpperCase() +
268 // Add turn + flags + enpassant (+ reserve)
270 if (this.hasFlags
) parts
.push(`"flags":"${flags}"`);
271 if (this.hasEnpassant
) parts
.push('"enpassant":"-"');
272 if (this.hasReserve
) parts
.push('"reserve":"000000000000"');
273 if (this.options
["crazyhouse"]) parts
.push('"ispawn":"-"');
274 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
278 // "Parse" FEN: just return untransformed string data
280 const fenParts
= fen
.split(" ");
282 position: fenParts
[0],
284 movesCount: fenParts
[2]
286 if (fenParts
.length
> 3) res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
290 // Return current fen (game state)
293 this.getBaseFen() + " " +
294 this.getTurnFen() + " " +
298 if (this.hasFlags
) parts
.push(`"flags":"${this.getFlagsFen()}"`);
299 if (this.hasEnpassant
)
300 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
301 if (this.hasReserve
) parts
.push(`"reserve":"${this.getReserveFen()}"`);
302 if (this.options
["crazyhouse"])
303 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
304 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
308 // Position part of the FEN string
310 const format
= (count
) => {
311 // if more than 9 consecutive free spaces, break the integer,
312 // otherwise FEN parsing will fail.
313 if (count
<= 9) return count
;
314 // Most boards of size < 18:
315 if (count
<= 18) return "9" + (count
- 9);
317 return "99" + (count
- 18);
320 for (let i
= 0; i
< this.size
.y
; i
++) {
322 for (let j
= 0; j
< this.size
.x
; j
++) {
323 if (this.board
[i
][j
] == "") emptyCount
++;
325 if (emptyCount
> 0) {
326 // Add empty squares in-between
327 position
+= format(emptyCount
);
330 position
+= this.board2fen(this.board
[i
][j
]);
335 position
+= format(emptyCount
);
336 if (i
< this.size
.y
- 1) position
+= "/"; //separate rows
345 // Flags part of the FEN string
347 return ["w", "b"].map(c
=> {
348 return this.castleFlags
[c
].map(x
=> x
.toString(30)).join("");
352 // Enpassant part of the FEN string
354 if (!this.epSquare
) return "-"; //no en-passant
355 return C
.CoordsToSquare(this.epSquare
);
360 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
365 const coords
= Object
.keys(this.ispawn
);
366 if (coords
.length
== 0) return "-";
367 return coords
.map(C
.CoordsToSquare
).join(",");
370 // Set flags from fen (castle: white a,h then black a,h)
373 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 30)),
374 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 30))
381 // Fen string fully describes the game state
383 window
.C
= ChessRules
; //easier alias
385 this.options
= o
.options
;
386 this.playerColor
= o
.color
;
387 this.afterPlay
= o
.afterPlay
;
390 if (!o
.fen
) o
.fen
= this.genRandInitFen(o
.seed
);
391 const fenParsed
= this.parseFen(o
.fen
);
392 this.board
= this.getBoard(fenParsed
.position
);
393 this.turn
= fenParsed
.turn
;
394 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
395 this.setOtherVariables(fenParsed
);
397 // Graphical (can use variables defined above)
398 this.containerId
= o
.element
;
399 this.graphicalInit();
402 // Turn position fen into double array ["wb","wp","bk",...]
404 const rows
= position
.split("/");
405 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
406 for (let i
= 0; i
< rows
.length
; i
++) {
408 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
409 const character
= rows
[i
][indexInRow
];
410 const num
= parseInt(character
, 10);
411 // If num is a number, just shift j:
412 if (!isNaN(num
)) j
+= num
;
413 // Else: something at position i,j
414 else board
[i
][j
++] = this.fen2board(character
);
420 // Some additional variables from FEN (variant dependant)
421 setOtherVariables(fenParsed
) {
422 // Set flags and enpassant:
423 if (this.hasFlags
) this.setFlags(fenParsed
.flags
);
424 if (this.hasEnpassant
)
425 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
426 if (this.hasReserve
) this.initReserves(fenParsed
.reserve
);
427 if (this.options
["crazyhouse"]) this.initIspawn(fenParsed
.ispawn
);
428 this.subTurn
= 1; //may be unused
429 if (this.options
["teleport"]) {
430 this.subTurnTeleport
= 1;
431 this.captured
= null;
433 if (this.options
["dark"]) {
434 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
);
435 // Setup enlightened: squares reachable by player side
436 this.updateEnlightened(false);
440 updateEnlightened(withGraphics
) {
441 let newEnlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
442 const pawnShift
= { w: -1, b: 1 };
443 // Add pieces positions + all squares reachable by moves (includes Zen):
444 // (watch out special pawns case)
445 for (let x
=0; x
<this.size
.x
; x
++) {
446 for (let y
=0; y
<this.size
.y
; y
++) {
447 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
449 newEnlightened
[x
][y
] = true;
450 if (this.getPiece(x
, y
) == "p") {
451 // Attacking squares wouldn't be highlighted if no captures:
452 this.pieces(this.playerColor
)["p"].attack
.forEach(step
=> {
453 const [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
454 if (this.onBoard(i
, j
) && this.board
[i
][j
] == "")
455 newEnlightened
[i
][j
] = true;
458 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
459 newEnlightened
[m
.end
.x
][m
.end
.y
] = true;
464 if (this.epSquare
) this.enlightEnpassant(newEnlightened
);
465 if (withGraphics
) this.graphUpdateEnlightened(newEnlightened
);
466 this.enlightened
= newEnlightened
;
469 // Include en-passant capturing square if any:
470 enlightEnpassant(newEnlightened
) {
471 const steps
= this.pieces(this.playerColor
)["p"].attack
;
472 for (let step
of steps
) {
473 const x
= this.epSquare
.x
- step
[0],
474 y
= this.computeY(this.epSquare
.y
- step
[1]);
476 this.onBoard(x
, y
) &&
477 this.getColor(x
, y
) == this.playerColor
&&
478 this.getPieceType(x
, y
) == "p"
480 newEnlightened
[x
][this.epSquare
.y
] = true;
486 // Apply diff this.enlightened --> newEnlightened on board
487 graphUpdateEnlightened(newEnlightened
) {
488 let container
= document
.getElementById(this.containerId
);
489 const r
= container
.getBoundingClientRect();
490 const pieceWidth
= this.getPieceWidth(r
.width
);
491 for (let x
=0; x
<this.size
.x
; x
++) {
492 for (let y
=0; y
<this.size
.y
; y
++) {
493 if (this.enlightened
[x
][y
] && !newEnlightened
[x
][y
]) {
494 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
495 elt
.classList
.add("in-shadow");
496 if (this.g_pieces
[x
][y
]) {
497 this.g_pieces
[x
][y
].remove();
498 this.g_pieces
[x
][y
] = null;
501 else if (!this.enlightened
[x
][y
] && newEnlightened
[x
][y
]) {
502 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
503 elt
.classList
.remove("in-shadow");
504 if (this.board
[x
][y
] != "") {
505 const color
= this.getColor(x
, y
);
506 const piece
= this.getPiece(x
, y
);
507 this.g_pieces
[x
][y
] = document
.createElement("piece");
509 this.pieces()[piece
]["class"],
510 color
== "w" ? "white" : "black"
512 newClasses
.forEach(cl
=> this.g_pieces
[x
][y
].classList
.add(cl
));
513 this.g_pieces
[x
][y
].style
.width
= pieceWidth
+ "px";
514 this.g_pieces
[x
][y
].style
.height
= pieceWidth
+ "px";
515 const [ip
, jp
] = this.getPixelPosition(x
, y
, r
);
516 this.g_pieces
[x
][y
].style
.transform
=
517 `translate(${ip}px,${jp}px)`;
518 container
.appendChild(this.g_pieces
[x
][y
]);
525 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
526 initReserves(reserveStr
) {
527 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
528 this.reserve
= { w: {}, b: {} };
529 const pieceName
= Object
.keys(this.pieces());
530 for (let i
of ArrayFun
.range(12)) {
531 if (i
< 6) this.reserve
['w'][pieceName
[i
]] = counts
[i
];
532 else this.reserve
['b'][pieceName
[i
-6]] = counts
[i
];
536 initIspawn(ispawnStr
) {
537 if (ispawnStr
!= "-") {
538 this.ispawn
= ispawnStr
.split(",").map(C
.SquareToCoords
)
539 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
541 else this.ispawn
= {};
544 getNbReservePieces(color
) {
546 Object
.values(this.reserve
[color
]).reduce(
547 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
554 getPieceWidth(rwidth
) {
555 return (rwidth
/ this.size
.y
);
558 getSquareWidth(rwidth
) {
559 return this.getPieceWidth(rwidth
);
562 getReserveSquareSize(rwidth
, nbR
) {
563 const sqSize
= this.getSquareWidth(rwidth
);
564 return Math
.min(sqSize
, rwidth
/ nbR
);
567 getReserveNumId(color
, piece
) {
568 return `${this.containerId}|rnum-${color}${piece}`;
572 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
573 window
.onresize
= () => this.re_drawBoardElements();
574 this.re_drawBoardElements();
575 this.initMouseEvents();
576 const container
= document
.getElementById(this.containerId
);
577 new ResizeObserver(this.rescale
).observe(container
);
580 re_drawBoardElements() {
581 const board
= this.getSvgChessboard();
582 const oppCol
= C
.GetOppCol(this.playerColor
);
583 let container
= document
.getElementById(this.containerId
);
584 container
.innerHTML
= "";
585 container
.insertAdjacentHTML('beforeend', board
);
586 let cb
= container
.querySelector("#" + this.containerId
+ "_SVG");
587 const aspectRatio
= this.size
.y
/ this.size
.x
;
588 // Compare window ratio width / height to aspectRatio:
589 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
590 let cbWidth
, cbHeight
;
591 if (windowRatio
<= aspectRatio
) {
592 // Limiting dimension is width:
593 cbWidth
= Math
.min(window
.innerWidth
, 767);
594 cbHeight
= cbWidth
/ aspectRatio
;
597 // Limiting dimension is height:
598 cbHeight
= Math
.min(window
.innerHeight
, 767);
599 cbWidth
= cbHeight
* aspectRatio
;
602 const sqSize
= cbWidth
/ this.size
.y
;
603 // NOTE: allocate space for reserves (up/down) even if they are empty
604 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
605 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
606 cbWidth
= cbHeight
* aspectRatio
;
609 container
.style
.width
= cbWidth
+ "px";
610 container
.style
.height
= cbHeight
+ "px";
611 // Center chessboard:
612 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
613 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
614 container
.style
.left
= spaceLeft
+ "px";
615 container
.style
.top
= spaceTop
+ "px";
616 // Give sizes instead of recomputing them,
617 // because chessboard might not be drawn yet.
626 // Get SVG board (background, no pieces)
628 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
629 const flipped
= (this.playerColor
== 'b');
634 id="${this.containerId}_SVG">
636 for (let i
=0; i
< sizeX
; i
++) {
637 for (let j
=0; j
< sizeY
; j
++) {
638 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
639 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
640 let classes
= this.getSquareColorClass(ii
, jj
);
641 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
642 classes
+= " in-shadow";
643 // NOTE: x / y reversed because coordinates system is reversed.
646 id="${this.coordsToId([ii, jj])}"
653 board
+= "</g></svg>";
657 // Generally light square bottom-right
658 getSquareColorClass(i
, j
) {
659 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
664 // Refreshing: delete old pieces first
665 for (let i
=0; i
<this.size
.x
; i
++) {
666 for (let j
=0; j
<this.size
.y
; j
++) {
667 if (this.g_pieces
[i
][j
]) {
668 this.g_pieces
[i
][j
].remove();
669 this.g_pieces
[i
][j
] = null;
674 else this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
675 let container
= document
.getElementById(this.containerId
);
676 if (!r
) r
= container
.getBoundingClientRect();
677 const pieceWidth
= this.getPieceWidth(r
.width
);
678 for (let i
=0; i
< this.size
.x
; i
++) {
679 for (let j
=0; j
< this.size
.y
; j
++) {
681 this.board
[i
][j
] != "" &&
682 (!this.options
["dark"] || this.enlightened
[i
][j
])
684 const color
= this.getColor(i
, j
);
685 const piece
= this.getPiece(i
, j
);
686 this.g_pieces
[i
][j
] = document
.createElement("piece");
687 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
688 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
689 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
690 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
691 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
692 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
693 container
.appendChild(this.g_pieces
[i
][j
]);
697 if (this.reserve
) this.re_drawReserve(['w', 'b'], r
);
700 // NOTE: assume !!this.reserve
701 re_drawReserve(colors
, r
) {
703 // Remove (old) reserve pieces
704 for (let c
of colors
) {
705 if (!this.reserve
[c
]) continue;
706 Object
.keys(this.reserve
[c
]).forEach(p
=> {
707 if (this.r_pieces
[c
][p
]) {
708 this.r_pieces
[c
][p
].remove();
709 delete this.r_pieces
[c
][p
];
710 const numId
= this.getReserveNumId(c
, p
);
711 document
.getElementById(numId
).remove();
714 let reservesDiv
= document
.getElementById("reserves_" + c
);
715 if (reservesDiv
) reservesDiv
.remove();
718 else this.r_pieces
= { 'w': {}, 'b': {} };
720 const container
= document
.getElementById(this.containerId
);
721 r
= container
.getBoundingClientRect();
723 for (let c
of colors
) {
724 if (!this.reserve
[c
]) continue;
725 const nbR
= this.getNbReservePieces(c
);
726 if (nbR
== 0) continue;
727 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
729 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
730 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
731 let rcontainer
= document
.createElement("div");
732 rcontainer
.id
= "reserves_" + c
;
733 rcontainer
.classList
.add("reserves");
734 rcontainer
.style
.left
= i0
+ "px";
735 rcontainer
.style
.top
= j0
+ "px";
736 // NOTE: +1 fix display bug on Firefox at least
737 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
738 rcontainer
.style
.height
= sqResSize
+ "px";
739 document
.getElementById("boardContainer").appendChild(rcontainer
);
740 for (let p
of Object
.keys(this.reserve
[c
])) {
741 if (this.reserve
[c
][p
] == 0) continue;
742 let r_cell
= document
.createElement("div");
743 r_cell
.id
= this.coordsToId([c
, p
]);
744 r_cell
.classList
.add("reserve-cell");
745 r_cell
.style
.width
= sqResSize
+ "px";
746 r_cell
.style
.height
= sqResSize
+ "px";
747 rcontainer
.appendChild(r_cell
);
748 let piece
= document
.createElement("piece");
749 const pieceSpec
= this.pieces(c
)[p
];
750 piece
.classList
.add(pieceSpec
["class"]);
751 piece
.classList
.add(c
== 'w' ? "white" : "black");
752 piece
.style
.width
= "100%";
753 piece
.style
.height
= "100%";
754 this.r_pieces
[c
][p
] = piece
;
755 r_cell
.appendChild(piece
);
756 let number
= document
.createElement("div");
757 number
.textContent
= this.reserve
[c
][p
];
758 number
.classList
.add("reserve-num");
759 number
.id
= this.getReserveNumId(c
, p
);
760 const fontSize
= "1.3em";
761 number
.style
.fontSize
= fontSize
;
762 number
.style
.fontSize
= fontSize
;
763 r_cell
.appendChild(number
);
769 updateReserve(color
, piece
, count
) {
770 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
771 piece
= "k"; //capturing cannibal king: back to king form
772 const oldCount
= this.reserve
[color
][piece
];
773 this.reserve
[color
][piece
] = count
;
774 // Redrawing is much easier if count==0
775 if ([oldCount
, count
].includes(0)) this.re_drawReserve([color
]);
777 const numId
= this.getReserveNumId(color
, piece
);
778 document
.getElementById(numId
).textContent
= count
;
782 // After resize event: no need to destroy/recreate pieces
784 let container
= document
.getElementById(this.containerId
);
785 if (!container
) return; //useful at initial loading
786 const r
= container
.getBoundingClientRect();
787 const newRatio
= r
.width
/ r
.height
;
788 const aspectRatio
= this.size
.y
/ this.size
.x
;
789 let newWidth
= r
.width
,
790 newHeight
= r
.height
;
791 if (newRatio
> aspectRatio
) {
792 newWidth
= r
.height
* aspectRatio
;
793 container
.style
.width
= newWidth
+ "px";
795 else if (newRatio
< aspectRatio
) {
796 newHeight
= r
.width
/ aspectRatio
;
797 container
.style
.height
= newHeight
+ "px";
799 const newX
= (window
.innerWidth
- newWidth
) / 2;
800 container
.style
.left
= newX
+ "px";
801 const newY
= (window
.innerHeight
- newHeight
) / 2;
802 container
.style
.top
= newY
+ "px";
803 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
804 const pieceWidth
= this.getPieceWidth(newWidth
);
805 for (let i
=0; i
< this.size
.x
; i
++) {
806 for (let j
=0; j
< this.size
.y
; j
++) {
807 if (this.board
[i
][j
] != "") {
808 // NOTE: could also use CSS transform "scale"
809 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
810 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
811 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
812 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
816 if (this.reserve
) this.rescaleReserve(newR
);
820 for (let c
of ['w','b']) {
821 if (!this.reserve
[c
]) continue;
822 const nbR
= this.getNbReservePieces(c
);
823 if (nbR
== 0) continue;
824 // Resize container first
825 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
826 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
827 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
828 let rcontainer
= document
.getElementById("reserves_" + c
);
829 rcontainer
.style
.left
= i0
+ "px";
830 rcontainer
.style
.top
= j0
+ "px";
831 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
832 rcontainer
.style
.height
= sqResSize
+ "px";
833 // And then reserve cells:
834 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
835 Object
.keys(this.reserve
[c
]).forEach(p
=> {
836 if (this.reserve
[c
][p
] == 0) return;
837 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
838 r_cell
.style
.width
= sqResSize
+ "px";
839 r_cell
.style
.height
= sqResSize
+ "px";
844 // Return the absolute pixel coordinates given current position.
845 // Our coordinate system differs from CSS one (x <--> y).
846 // We return here the CSS coordinates (more useful).
847 getPixelPosition(i
, j
, r
) {
848 const sqSize
= this.getSquareWidth(r
.width
);
849 if (i
< 0 || j
< 0) return [0, 0]; //piece vanishes
850 const flipped
= (this.playerColor
== 'b');
851 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
852 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
857 let container
= document
.getElementById(this.containerId
);
859 const getOffset
= e
=> {
860 if (e
.clientX
) return {x: e
.clientX
, y: e
.clientY
}; //Mouse
861 let touchLocation
= null;
862 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
863 // Touch screen, dragstart
864 touchLocation
= e
.targetTouches
[0];
865 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
866 // Touch screen, dragend
867 touchLocation
= e
.changedTouches
[0];
869 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
870 return [0, 0]; //Big trouble here =)
873 const centerOnCursor
= (piece
, e
) => {
874 const centerShift
= sqSize
/ 2;
875 const offset
= getOffset(e
);
876 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
877 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
882 startPiece
, curPiece
= null,
884 const mousedown
= (e
) => {
885 // Disable zoom on smartphones:
886 if (e
.touches
&& e
.touches
.length
> 1) e
.preventDefault();
887 r
= container
.getBoundingClientRect();
888 sqSize
= this.getSquareWidth(r
.width
);
889 const square
= this.idToCoords(e
.target
.id
);
891 const [i
, j
] = square
;
892 const move = this.doClick([i
, j
]);
893 if (move) this.playPlusVisual(move);
895 if (typeof i
!= "number") startPiece
= this.r_pieces
[i
][j
];
896 else if (this.g_pieces
[i
][j
]) startPiece
= this.g_pieces
[i
][j
];
897 if (startPiece
&& this.canIplay(i
, j
)) {
899 start
= { x: i
, y: j
};
900 curPiece
= startPiece
.cloneNode();
901 curPiece
.style
.transform
= "none";
902 curPiece
.style
.zIndex
= 5;
903 curPiece
.style
.width
= sqSize
+ "px";
904 curPiece
.style
.height
= sqSize
+ "px";
905 centerOnCursor(curPiece
, e
);
906 document
.getElementById("boardContainer").appendChild(curPiece
);
907 startPiece
.style
.opacity
= "0.4";
908 container
.style
.cursor
= "none";
914 const mousemove
= (e
) => {
917 centerOnCursor(curPiece
, e
);
919 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
920 // Attempt to prevent horizontal swipe...
924 const mouseup
= (e
) => {
925 const newR
= container
.getBoundingClientRect();
926 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
931 const [x
, y
] = [start
.x
, start
.y
];
934 container
.style
.cursor
= "pointer";
935 startPiece
.style
.opacity
= "1";
936 const offset
= getOffset(e
);
937 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
938 const sq
= this.idToCoords(landingElt
.id
);
941 // NOTE: clearly suboptimal, but much easier, and not a big deal.
942 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
943 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
944 const moves
= this.filterValid(potentialMoves
);
945 if (moves
.length
>= 2) this.showChoices(moves
, r
);
946 else if (moves
.length
== 1) this.playPlusVisual(moves
[0], r
);
951 if ('onmousedown' in window
) {
952 document
.addEventListener("mousedown", mousedown
);
953 document
.addEventListener("mousemove", mousemove
);
954 document
.addEventListener("mouseup", mouseup
);
956 if ('ontouchstart' in window
) {
957 // https://stackoverflow.com/a/42509310/12660887
958 document
.addEventListener("touchstart", mousedown
, {passive: false});
959 document
.addEventListener("touchmove", mousemove
, {passive: false});
960 document
.addEventListener("touchend", mouseup
, {passive: false});
962 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
965 showChoices(moves
, r
) {
966 let container
= document
.getElementById(this.containerId
);
967 let choices
= document
.createElement("div");
968 choices
.id
= "choices";
969 choices
.style
.width
= r
.width
+ "px";
970 choices
.style
.height
= r
.height
+ "px";
971 choices
.style
.left
= r
.x
+ "px";
972 choices
.style
.top
= r
.y
+ "px";
973 container
.style
.opacity
= "0.5";
974 let boardContainer
= document
.getElementById("boardContainer");
975 boardContainer
.appendChild(choices
);
976 const squareWidth
= this.getSquareWidth(r
.width
);
977 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
978 const firstUpTop
= (r
.height
- squareWidth
) / 2;
979 const color
= moves
[0].appear
[0].c
;
980 const callback
= (m
) => {
981 container
.style
.opacity
= "1";
982 boardContainer
.removeChild(choices
);
983 this.playPlusVisual(m
, r
);
985 for (let i
=0; i
< moves
.length
; i
++) {
986 let choice
= document
.createElement("div");
987 choice
.classList
.add("choice");
988 choice
.style
.width
= squareWidth
+ "px";
989 choice
.style
.height
= squareWidth
+ "px";
990 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
991 choice
.style
.top
= firstUpTop
+ "px";
992 choice
.style
.backgroundColor
= "lightyellow";
993 choice
.onclick
= () => callback(moves
[i
]);
994 const piece
= document
.createElement("piece");
995 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
996 piece
.classList
.add(pieceSpec
["class"]);
997 piece
.classList
.add(color
== 'w' ? "white" : "black");
998 piece
.style
.width
= "100%";
999 piece
.style
.height
= "100%";
1000 choice
.appendChild(piece
);
1001 choices
.appendChild(choice
);
1009 return { "x": 8, "y": 8 };
1012 // Color of thing on square (i,j). 'undefined' if square is empty
1014 return this.board
[i
][j
].charAt(0);
1017 // Assume square i,j isn't empty
1019 return this.board
[i
][j
].charAt(1);
1022 // Piece type on square (i,j)
1023 getPieceType(i
, j
) {
1024 const p
= this.board
[i
][j
].charAt(1);
1025 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1028 // Get opponent color
1029 static GetOppCol(color
) {
1030 return (color
== "w" ? "b" : "w");
1033 // Can thing on square1 take thing on square2
1034 canTake([x1
, y1
], [x2
, y2
]) {
1036 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
)) ||
1038 (this.options
["recycle"] || this.options
["teleport"]) &&
1039 this.getPieceType(x2
, y2
) != "k"
1044 // Is (x,y) on the chessboard?
1046 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1049 // Used in interface: 'side' arg == player color
1052 this.playerColor
== this.turn
&&
1054 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1055 (typeof x
== "string" && x
== this.turn
) //reserve
1060 ////////////////////////
1061 // PIECES SPECIFICATIONS
1064 const pawnShift
= (color
== "w" ? -1 : 1);
1068 steps: [[pawnShift
, 0]],
1070 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1075 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1081 [1, 2], [1, -2], [-1, 2], [-1, -2],
1082 [2, 1], [-2, 1], [2, -1], [-2, -1]
1089 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1095 [0, 1], [0, -1], [1, 0], [-1, 0],
1096 [1, 1], [1, -1], [-1, 1], [-1, -1]
1103 [0, 1], [0, -1], [1, 0], [-1, 0],
1104 [1, 1], [1, -1], [-1, 1], [-1, -1]
1109 's': { "class": "king-pawn" },
1110 'u': { "class": "king-rook" },
1111 'o': { "class": "king-knight" },
1112 'c': { "class": "king-bishop" },
1113 't': { "class": "king-queen" }
1117 ////////////////////
1120 // For Cylinder: get Y coordinate
1122 if (!this.options
["cylinder"]) return y
;
1123 let res
= y
% this.size
.y
;
1124 if (res
< 0) res
+= this.size
.y
;
1128 // Stop at the first capture found
1129 atLeastOneCapture(color
) {
1130 color
= color
|| this.turn
;
1131 const oppCol
= C
.GetOppCol(color
);
1132 for (let i
= 0; i
< this.size
.x
; i
++) {
1133 for (let j
= 0; j
< this.size
.y
; j
++) {
1134 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1135 const specs
= this.pieces(color
)[this.getPieceType(i
, j
)];
1136 const steps
= specs
.attack
|| specs
.steps
;
1137 outerLoop: for (let step
of steps
) {
1138 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1139 let stepCounter
= 1;
1140 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1141 if (specs
.range
<= stepCounter
++) continue outerLoop
;
1143 jj
= this.computeY(jj
+ step
[1]);
1146 this.onBoard(ii
, jj
) &&
1147 this.getColor(ii
, jj
) == oppCol
&&
1149 [this.getBasicMove([i
, j
], [ii
, jj
])]
1161 getDropMovesFrom([c
, p
]) {
1162 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1163 // (but not necessarily otherwise)
1164 if (this.reserve
[c
][p
] == 0) return [];
1166 for (let i
=0; i
<this.size
.x
; i
++) {
1167 for (let j
=0; j
<this.size
.y
; j
++) {
1168 // TODO: rather simplify this "if" and add post-condition: more general
1170 this.board
[i
][j
] == "" &&
1171 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1174 (c
== 'w' && i
< this.size
.x
- 1) ||
1180 start: {x: c
, y: p
},
1182 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1192 // All possible moves from selected square
1193 getPotentialMovesFrom(sq
, color
) {
1194 if (typeof sq
[0] == "string") return this.getDropMovesFrom(sq
);
1195 if (this.options
["madrasi"] && this.isImmobilized(sq
)) return [];
1196 const piece
= this.getPieceType(sq
[0], sq
[1]);
1198 if (piece
== "p") moves
= this.getPotentialPawnMoves(sq
);
1199 else moves
= this.getPotentialMovesOf(piece
, sq
);
1203 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1205 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1207 return this.postProcessPotentialMoves(moves
);
1210 postProcessPotentialMoves(moves
) {
1211 if (moves
.length
== 0) return [];
1212 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1213 const oppCol
= C
.GetOppCol(color
);
1215 if (this.options
["capture"] && this.atLeastOneCapture()) {
1216 // Filter out non-capturing moves (not using m.vanish because of
1217 // self captures of Recycle and Teleport).
1218 moves
= moves
.filter(m
=> {
1220 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1221 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1226 if (this.options
["atomic"]) {
1227 moves
.forEach(m
=> {
1229 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1230 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1243 for (let step
of steps
) {
1244 let x
= m
.end
.x
+ step
[0];
1245 let y
= this.computeY(m
.end
.y
+ step
[1]);
1247 this.onBoard(x
, y
) &&
1248 this.board
[x
][y
] != "" &&
1249 this.getPieceType(x
, y
) != "p"
1253 p: this.getPiece(x
, y
),
1254 c: this.getColor(x
, y
),
1261 if (!this.options
["rifle"]) m
.appear
.pop(); //nothin appears
1267 this.options
["cannibal"] &&
1268 this.options
["rifle"] &&
1269 this.pawnSpecs
.promotions
1271 // In this case a rifle-capture from last rank may promote a pawn
1272 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1274 moves
.forEach(m
=> {
1276 m
.start
.x
== lastRank
&&
1277 m
.appear
.length
>= 1 &&
1278 m
.appear
[0].p
== "p" &&
1279 m
.appear
[0].x
== m
.start
.x
&&
1280 m
.appear
[0].y
== m
.start
.y
1282 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1283 m
.appear
[0].p
= this.pawnSpecs
.promotions
[0];
1284 for (let i
=1; i
<this.pawnSpecs
.promotions
.length
; i
++) {
1285 let newMv
= JSON
.parse(JSON
.stringify(m
));
1286 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1287 newMoves
.push(newMv
);
1291 Array
.prototype.push
.apply(moves
, newMoves
);
1297 static get CannibalKings() {
1307 static get CannibalKingCode() {
1321 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1326 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1327 isImmobilized([x
, y
]) {
1328 const color
= this.getColor(x
, y
);
1329 const oppCol
= C
.GetOppCol(color
);
1330 const piece
= this.getPieceType(x
, y
);
1331 const stepSpec
= this.pieces(color
)[piece
];
1332 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1333 outerLoop: for (let step
of steps
) {
1334 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1335 let stepCounter
= 1;
1336 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1337 if (range
<= stepCounter
++) continue outerLoop
;
1339 j
= this.computeY(j
+ step
[1]);
1342 this.onBoard(i
, j
) &&
1343 this.getColor(i
, j
) == oppCol
&&
1344 this.getPieceType(i
, j
) == piece
1352 // Generic method to find possible moves of "sliding or jumping" pieces
1353 getPotentialMovesOf(piece
, [x
, y
]) {
1354 const color
= this.getColor(x
, y
);
1355 const stepSpec
= this.pieces(color
)[piece
];
1356 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1358 let explored
= {}; //for Cylinder mode
1359 outerLoop: for (let step
of steps
) {
1360 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1361 let stepCounter
= 1;
1363 this.onBoard(i
, j
) &&
1364 this.board
[i
][j
] == "" &&
1365 !explored
[i
+ "." + j
]
1367 explored
[i
+ "." + j
] = true;
1368 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1369 if (range
<= stepCounter
++) continue outerLoop
;
1371 j
= this.computeY(j
+ step
[1]);
1374 this.onBoard(i
, j
) &&
1376 !this.options
["zen"] ||
1377 this.getPieceType(i
, j
) == "k" ||
1378 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1380 this.canTake([x
, y
], [i
, j
]) &&
1381 !explored
[i
+ "." + j
]
1383 explored
[i
+ "." + j
] = true;
1384 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1387 if (this.options
["zen"])
1388 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1392 getZenCaptures(x
, y
) {
1394 // Find reverse captures (opponent takes)
1395 const color
= this.getColor(x
, y
);
1396 const pieceType
= this.getPieceType(x
, y
);
1397 const oppCol
= C
.GetOppCol(color
);
1398 const pieces
= this.pieces(oppCol
);
1399 Object
.keys(pieces
).forEach(p
=> {
1402 (this.options
["cannibal"] && C
.CannibalKings
[p
])
1404 return; //king isn't captured this way
1406 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1407 if (!steps
) return; //cannibal king for example (TODO...)
1408 const range
= pieces
[p
].range
;
1409 steps
.forEach(s
=> {
1410 // From x,y: revert step
1411 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1412 let stepCounter
= 1;
1413 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1414 if (range
<= stepCounter
++) return;
1416 j
= this.computeY(j
- s
[1]);
1419 this.onBoard(i
, j
) &&
1420 this.getPieceType(i
, j
) == p
&&
1421 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1422 this.canTake([i
, j
], [x
, y
])
1424 if (pieceType
!= "p") moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1425 else this.addPawnMoves([x
, y
], [i
, j
], moves
);
1432 // Build a regular move from its initial and destination squares.
1433 // tr: transformation
1434 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1435 const initColor
= this.getColor(sx
, sy
);
1436 const initPiece
= this.getPiece(sx
, sy
);
1437 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1441 start: {x:sx
, y:sy
},
1445 !this.options
["rifle"] ||
1446 this.board
[ex
][ey
] == "" ||
1447 destColor
== initColor
//Recycle, Teleport
1453 c: !!tr
? tr
.c : initColor
,
1454 p: !!tr
? tr
.p : initPiece
1466 if (this.board
[ex
][ey
] != "") {
1471 c: this.getColor(ex
, ey
),
1472 p: this.getPiece(ex
, ey
)
1475 if (this.options
["rifle"])
1476 // Rifle captures are tricky in combination with Atomic etc,
1477 // so it's useful to mark the move :
1479 if (this.options
["cannibal"] && destColor
!= initColor
) {
1480 const lastIdx
= mv
.vanish
.length
- 1;
1481 let trPiece
= mv
.vanish
[lastIdx
].p
;
1482 if (this.isKing(this.getPiece(sx
, sy
)))
1483 trPiece
= C
.CannibalKingCode
[trPiece
];
1484 if (mv
.appear
.length
>= 1) mv
.appear
[0].p
= trPiece
;
1485 else if (this.options
["rifle"]) {
1508 // En-passant square, if any
1509 getEpSquare(moveOrSquare
) {
1510 if (typeof moveOrSquare
=== "string") {
1511 const square
= moveOrSquare
;
1512 if (square
== "-") return undefined;
1513 return C
.SquareToCoords(square
);
1515 // Argument is a move:
1516 const move = moveOrSquare
;
1517 const s
= move.start
,
1521 Math
.abs(s
.x
- e
.x
) == 2 &&
1522 // Next conditions for variants like Atomic or Rifle, Recycle...
1523 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1524 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1531 return undefined; //default
1534 // Special case of en-passant captures: treated separately
1535 getEnpassantCaptures([x
, y
], shiftX
) {
1536 const color
= this.getColor(x
, y
);
1537 const oppCol
= C
.GetOppCol(color
);
1538 let enpassantMove
= null;
1541 this.epSquare
.x
== x
+ shiftX
&&
1542 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1543 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1545 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1546 this.board
[epx
][epy
] = oppCol
+ "p";
1547 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1548 this.board
[epx
][epy
] = "";
1549 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1550 enpassantMove
.vanish
[lastIdx
].x
= x
;
1552 return !!enpassantMove
? [enpassantMove
] : [];
1555 // Consider all potential promotions.
1556 // NOTE: "promotions" arg = special override for Hiddenqueen variant
1557 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1558 let finalPieces
= ["p"];
1559 const color
= this.getColor(x1
, y1
);
1560 const oppCol
= C
.GetOppCol(color
);
1561 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1563 x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == "");
1564 if (promotionOk
&& !this.options
["pawnfall"]) {
1566 this.options
["cannibal"] &&
1567 this.board
[x2
][y2
] != "" &&
1568 this.getColor(x2
, y2
) == oppCol
1570 finalPieces
= [this.getPieceType(x2
, y2
)];
1572 else if (promotions
) finalPieces
= promotions
;
1573 else if (this.pawnSpecs
.promotions
)
1574 finalPieces
= this.pawnSpecs
.promotions
;
1576 for (let piece
of finalPieces
) {
1577 const tr
= !this.options
["pawnfall"] && piece
!= "p"
1578 ? { c: color
, p: piece
}
1580 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1581 if (promotionOk
&& this.options
["pawnfall"]) {
1582 newMove
.appear
.shift();
1583 newMove
.pawnfall
= true; //required in prePlay()
1585 moves
.push(newMove
);
1589 // What are the pawn moves from square x,y ?
1590 getPotentialPawnMoves([x
, y
], promotions
) {
1591 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1592 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1593 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1594 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1595 const forward
= (color
== 'w' ? -1 : 1);
1597 // Pawn movements in shiftX direction:
1598 const getPawnMoves
= (shiftX
) => {
1600 // NOTE: next condition is generally true (no pawn on last rank)
1601 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1602 if (this.board
[x
+ shiftX
][y
] == "") {
1603 // One square forward (or backward)
1604 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1605 // Next condition because pawns on 1st rank can generally jump
1607 this.pawnSpecs
.twoSquares
&&
1611 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1614 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1618 shiftX
== forward
&&
1619 this.board
[x
+ 2 * shiftX
][y
] == ""
1622 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1624 this.pawnSpecs
.threeSquares
&&
1625 this.board
[x
+ 3 * shiftX
, y
] == ""
1627 // Three squares jump
1628 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1634 if (this.pawnSpecs
.canCapture
) {
1635 for (let shiftY
of [-1, 1]) {
1636 const yCoord
= this.computeY(y
+ shiftY
);
1637 if (yCoord
>= 0 && yCoord
< sizeY
) {
1639 this.board
[x
+ shiftX
][yCoord
] != "" &&
1640 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1642 !this.options
["zen"] ||
1643 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1647 [x
, y
], [x
+ shiftX
, yCoord
],
1652 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1653 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1654 this.board
[x
- shiftX
][yCoord
] != "" &&
1655 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1657 !this.options
["zen"] ||
1658 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1662 [x
, y
], [x
- shiftX
, yCoord
],
1673 let pMoves
= getPawnMoves(pawnShiftX
);
1674 if (this.pawnSpecs
.bidirectional
)
1675 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1677 if (this.hasEnpassant
) {
1678 // NOTE: backward en-passant captures are not considered
1679 // because no rules define them (for now).
1680 Array
.prototype.push
.apply(
1682 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1686 if (this.options
["zen"])
1687 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1692 // "castleInCheck" arg to let some variants castle under check
1693 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1694 const c
= this.getColor(x
, y
);
1697 const oppCol
= C
.GetOppCol(c
);
1701 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1702 const castlingKing
= this.getPiece(x
, y
);
1703 castlingCheck: for (
1706 castleSide
++ //large, then small
1708 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
) continue;
1709 // If this code is reached, rook and king are on initial position
1711 // NOTE: in some variants this is not a rook
1712 const rookPos
= this.castleFlags
[c
][castleSide
];
1713 const castlingPiece
= this.getPiece(x
, rookPos
);
1715 this.board
[x
][rookPos
] == "" ||
1716 this.getColor(x
, rookPos
) != c
||
1717 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1719 // Rook is not here, or changed color (see Benedict)
1722 // Nothing on the path of the king ? (and no checks)
1723 const finDist
= finalSquares
[castleSide
][0] - y
;
1724 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1728 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1730 this.board
[x
][i
] != "" &&
1731 // NOTE: next check is enough, because of chessboard constraints
1732 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1735 continue castlingCheck
;
1738 } while (i
!= finalSquares
[castleSide
][0]);
1739 // Nothing on the path to the rook?
1740 step
= (castleSide
== 0 ? -1 : 1);
1741 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1742 if (this.board
[x
][i
] != "") continue castlingCheck
;
1745 // Nothing on final squares, except maybe king and castling rook?
1746 for (i
= 0; i
< 2; i
++) {
1748 finalSquares
[castleSide
][i
] != rookPos
&&
1749 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1751 finalSquares
[castleSide
][i
] != y
||
1752 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1755 continue castlingCheck
;
1759 // If this code is reached, castle is valid
1765 y: finalSquares
[castleSide
][0],
1771 y: finalSquares
[castleSide
][1],
1777 // King might be initially disguised (Titan...)
1778 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1779 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1782 Math
.abs(y
- rookPos
) <= 2
1783 ? { x: x
, y: rookPos
}
1784 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1792 ////////////////////
1795 // Is (king at) given position under check by "color" ?
1796 underCheck([x
, y
], color
) {
1797 if (this.options
["taking"] || this.options
["dark"]) return false;
1798 color
= color
|| C
.GetOppCol(this.getColor(x
, y
));
1799 const pieces
= this.pieces(color
);
1800 return Object
.keys(pieces
).some(p
=> {
1801 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1805 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1806 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1807 if (!steps
) return false; //cannibal king, for example
1808 const range
= stepSpec
.range
;
1809 let explored
= {}; //for Cylinder mode
1810 outerLoop: for (let step
of steps
) {
1811 let rx
= x
- step
[0],
1812 ry
= this.computeY(y
- step
[1]);
1813 let stepCounter
= 1;
1815 this.onBoard(rx
, ry
) &&
1816 this.board
[rx
][ry
] == "" &&
1817 !explored
[rx
+ "." + ry
]
1819 explored
[rx
+ "." + ry
] = true;
1820 if (range
<= stepCounter
++) continue outerLoop
;
1822 ry
= this.computeY(ry
- step
[1]);
1825 this.onBoard(rx
, ry
) &&
1826 this.board
[rx
][ry
] != "" &&
1827 this.getPieceType(rx
, ry
) == piece
&&
1828 this.getColor(rx
, ry
) == color
&&
1829 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1837 // Stop at first king found (TODO: multi-kings)
1838 searchKingPos(color
) {
1839 for (let i
=0; i
< this.size
.x
; i
++) {
1840 for (let j
=0; j
< this.size
.y
; j
++) {
1841 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1845 return [-1, -1]; //king not found
1848 filterValid(moves
) {
1849 if (moves
.length
== 0) return [];
1850 const color
= this.turn
;
1851 const oppCol
= C
.GetOppCol(color
);
1852 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1853 // Forbid moves either giving check or exploding opponent's king:
1854 const oppKingPos
= this.searchKingPos(oppCol
);
1855 moves
= moves
.filter(m
=> {
1857 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1858 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1861 this.playOnBoard(m
);
1862 const res
= !this.underCheck(oppKingPos
, color
);
1863 this.undoOnBoard(m
);
1867 if (this.options
["taking"] || this.options
["dark"]) return moves
;
1868 const kingPos
= this.searchKingPos(color
);
1869 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1870 return moves
.filter(m
=> {
1871 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1872 if (!filtered
[key
]) {
1873 this.playOnBoard(m
);
1874 let square
= kingPos
,
1875 res
= true; //a priori valid
1876 if (m
.vanish
.some(v
=> {
1877 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1879 // Search king in appear array:
1881 m
.appear
.findIndex(a
=> {
1882 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1884 if (newKingIdx
>= 0)
1885 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1888 res
&&= !this.underCheck(square
, oppCol
);
1889 this.undoOnBoard(m
);
1890 filtered
[key
] = res
;
1893 return filtered
[key
];
1900 // Aggregate flags into one object
1902 return this.castleFlags
;
1905 // Reverse operation
1906 disaggregateFlags(flags
) {
1907 this.castleFlags
= flags
;
1910 // Apply a move on board
1912 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1913 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1915 // Un-apply the played move
1917 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1918 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1921 updateCastleFlags(move) {
1922 // Update castling flags if start or arrive from/at rook/king locations
1923 move.appear
.concat(move.vanish
).forEach(psq
=> {
1925 this.board
[psq
.x
][psq
.y
] != "" &&
1926 this.getPieceType(psq
.x
, psq
.y
) == "k"
1928 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1930 // NOTE: not "else if" because king can capture enemy rook...
1932 if (psq
.x
== 0) c
= "b";
1933 else if (psq
.x
== this.size
.x
- 1) c
= "w";
1935 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1936 if (fidx
>= 0) this.castleFlags
[c
][fidx
] = this.size
.y
;
1943 typeof move.start
.x
== "number" &&
1944 (!this.options
["teleport"] || this.subTurnTeleport
== 1)
1946 // OK, not a drop move
1949 // If flags already off, no need to re-check:
1950 Object
.keys(this.castleFlags
).some(c
=> {
1951 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1953 this.updateCastleFlags(move);
1955 const initSquare
= C
.CoordsToSquare(move.start
);
1957 this.options
["crazyhouse"] &&
1958 (!this.options
["rifle"] || !move.capture
)
1960 if (this.ispawn
[initSquare
]) {
1961 delete this.ispawn
[initSquare
];
1962 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1965 move.vanish
[0].p
== "p" &&
1966 move.appear
[0].p
!= "p"
1968 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1972 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1973 if (this.hasReserve
&& !move.pawnfall
) {
1974 const color
= this.turn
;
1975 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1976 // Something appears = dropped on board (some exceptions, Chakart...)
1977 const piece
= move.appear
[i
].p
;
1978 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1980 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1981 // Something vanish: add to reserve except if recycle & opponent
1982 const piece
= move.vanish
[i
].p
;
1983 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1984 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1991 if (this.hasEnpassant
) this.epSquare
= this.getEpSquare(move);
1992 this.playOnBoard(move);
1993 this.postPlay(move);
1997 const color
= this.turn
;
1998 const oppCol
= C
.GetOppCol(color
);
1999 if (this.options
["dark"]) this.updateEnlightened(true);
2000 if (this.options
["teleport"]) {
2002 this.subTurnTeleport
== 1 &&
2003 move.vanish
.length
> move.appear
.length
&&
2004 move.vanish
[move.vanish
.length
- 1].c
== color
2006 const v
= move.vanish
[move.vanish
.length
- 1];
2007 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2008 this.subTurnTeleport
= 2;
2011 this.subTurnTeleport
= 1;
2012 this.captured
= null;
2014 if (this.options
["balance"]) {
2015 if (![1, 3].includes(this.movesCount
)) this.turn
= oppCol
;
2020 this.options
["doublemove"] &&
2021 this.movesCount
>= 1 &&
2024 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2026 const oppKingPos
= this.searchKingPos(oppCol
);
2027 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
2038 // "Stop at the first move found"
2039 atLeastOneMove(color
) {
2040 color
= color
|| this.turn
;
2041 for (let i
= 0; i
< this.size
.x
; i
++) {
2042 for (let j
= 0; j
< this.size
.y
; j
++) {
2043 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2044 // NOTE: in fact searching for all potential moves from i,j.
2045 // I don't believe this is an issue, for now at least.
2046 const moves
= this.getPotentialMovesFrom([i
, j
]);
2047 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2051 if (this.hasReserve
&& this.reserve
[color
]) {
2052 for (let p
of Object
.keys(this.reserve
[color
])) {
2053 const moves
= this.getDropMovesFrom([color
, p
]);
2054 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2060 // What is the score ? (Interesting if game is over)
2061 getCurrentScore(move) {
2062 const color
= this.turn
;
2063 const oppCol
= C
.GetOppCol(color
);
2064 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2065 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0) return "1/2";
2066 if (kingPos
[0][0] < 0) return (color
== "w" ? "0-1" : "1-0");
2067 if (kingPos
[1][0] < 0) return (color
== "w" ? "1-0" : "0-1");
2068 if (this.atLeastOneMove()) return "*";
2069 // No valid move: stalemate or checkmate?
2070 if (!this.underCheck(kingPos
, color
)) return "1/2";
2072 return (color
== "w" ? "0-1" : "1-0");
2075 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2076 playVisual(move, r
) {
2077 move.vanish
.forEach(v
=> {
2078 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
2079 this.g_pieces
[v
.x
][v
.y
].remove();
2080 this.g_pieces
[v
.x
][v
.y
] = null;
2083 let container
= document
.getElementById(this.containerId
);
2084 if (!r
) r
= container
.getBoundingClientRect();
2085 const pieceWidth
= this.getPieceWidth(r
.width
);
2086 move.appear
.forEach(a
=> {
2087 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
]) return;
2088 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2089 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2090 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2091 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2092 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2093 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2094 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2095 container
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2099 playPlusVisual(move, r
) {
2100 this.playVisual(move, r
);
2102 this.afterPlay(move); //user method
2105 // Assumes reserve on top (usage case otherwise? TODO?)
2106 getReserveShift(c
, p
, r
) {
2109 for (let pi
of Object
.keys(this.reserve
[c
])) {
2110 if (this.reserve
[c
][pi
] == 0) continue;
2111 if (pi
== p
) ridx
= nbR
;
2114 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2115 return [-ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2118 animate(move, callback
) {
2119 if (this.noAnimate
) {
2123 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2124 const dropMove
= (typeof i1
== "string");
2125 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2126 let startPiece
= startArray
[i1
][j1
];
2127 let container
= document
.getElementById(this.containerId
);
2128 const clonePiece
= (
2130 this.options
["rifle"] ||
2131 (this.options
["teleport"] && this.subTurnTeleport
== 2)
2134 startPiece
= startPiece
.cloneNode();
2135 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "0";
2136 if (this.options
["teleport"] && this.subTurnTeleport
== 2) {
2137 const pieces
= this.pieces();
2138 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2139 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2140 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2143 container
.appendChild(startPiece
);
2145 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2149 i1
== this.playerColor
? this.size
.x : 0,
2150 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2153 else startCoords
= [i1
, j1
];
2154 const r
= container
.getBoundingClientRect();
2155 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2157 if (dropMove
) rs
= this.getReserveShift(i1
, j1
, r
);
2159 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2160 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2161 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2162 const duration
= 0.2 + multFact
* 0.3;
2163 const initTransform
= startPiece
.style
.transform
;
2164 startPiece
.style
.transform
=
2165 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2166 startPiece
.style
.transitionDuration
= duration
+ "s";
2170 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "1";
2171 startPiece
.remove();
2174 startPiece
.style
.transform
= initTransform
;
2175 startPiece
.style
.transitionDuration
= "0s";
2183 playReceivedMove(moves
, callback
) {
2184 const launchAnimation
= () => {
2186 document
.getElementById(this.containerId
).getBoundingClientRect();
2187 const animateRec
= i
=> {
2188 this.animate(moves
[i
], () => {
2189 this.playVisual(moves
[i
], r
);
2190 this.play(moves
[i
]);
2191 if (i
< moves
.length
- 1) setTimeout(() => animateRec(i
+1), 300);
2197 // Delay if user wasn't focused:
2198 const checkDisplayThenAnimate
= (delay
) => {
2199 if (boardContainer
.style
.display
== "none") {
2200 alert("New move! Let's go back to game...");
2201 document
.getElementById("gameInfos").style
.display
= "none";
2202 boardContainer
.style
.display
= "block";
2203 setTimeout(launchAnimation
, 700);
2205 else setTimeout(launchAnimation
, delay
|| 0);
2207 let boardContainer
= document
.getElementById("boardContainer");
2208 if (document
.hidden
) {
2209 document
.onvisibilitychange
= () => {
2210 document
.onvisibilitychange
= undefined;
2211 checkDisplayThenAnimate(700);
2214 else checkDisplayThenAnimate();