4e2eddd93423e5ab8a3fb94d48484acdf5c92e49
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
) {
491 document
.getElementById(this.containerId
).querySelector(".chessboard");
492 const r
= chessboard
.getBoundingClientRect();
493 const pieceWidth
= this.getPieceWidth(r
.width
);
494 for (let x
=0; x
<this.size
.x
; x
++) {
495 for (let y
=0; y
<this.size
.y
; y
++) {
496 if (this.enlightened
[x
][y
] && !newEnlightened
[x
][y
]) {
497 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
498 elt
.classList
.add("in-shadow");
499 if (this.g_pieces
[x
][y
]) {
500 this.g_pieces
[x
][y
].remove();
501 this.g_pieces
[x
][y
] = null;
504 else if (!this.enlightened
[x
][y
] && newEnlightened
[x
][y
]) {
505 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
506 elt
.classList
.remove("in-shadow");
507 if (this.board
[x
][y
] != "") {
508 const color
= this.getColor(x
, y
);
509 const piece
= this.getPiece(x
, y
);
510 this.g_pieces
[x
][y
] = document
.createElement("piece");
512 this.pieces()[piece
]["class"],
513 color
== "w" ? "white" : "black"
515 newClasses
.forEach(cl
=> this.g_pieces
[x
][y
].classList
.add(cl
));
516 this.g_pieces
[x
][y
].style
.width
= pieceWidth
+ "px";
517 this.g_pieces
[x
][y
].style
.height
= pieceWidth
+ "px";
518 const [ip
, jp
] = this.getPixelPosition(x
, y
, r
);
519 this.g_pieces
[x
][y
].style
.transform
=
520 `translate(${ip}px,${jp}px)`;
521 chessboard
.appendChild(this.g_pieces
[x
][y
]);
528 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
529 initReserves(reserveStr
) {
530 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
531 this.reserve
= { w: {}, b: {} };
532 const pieceName
= Object
.keys(this.pieces());
533 for (let i
of ArrayFun
.range(12)) {
534 if (i
< 6) this.reserve
['w'][pieceName
[i
]] = counts
[i
];
535 else this.reserve
['b'][pieceName
[i
-6]] = counts
[i
];
539 initIspawn(ispawnStr
) {
540 if (ispawnStr
!= "-") {
541 this.ispawn
= ispawnStr
.split(",").map(C
.SquareToCoords
)
542 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
544 else this.ispawn
= {};
547 getNbReservePieces(color
) {
549 Object
.values(this.reserve
[color
]).reduce(
550 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
557 getPieceWidth(rwidth
) {
558 return (rwidth
/ this.size
.y
);
561 getSquareWidth(rwidth
) {
562 return this.getPieceWidth(rwidth
);
565 getReserveSquareSize(rwidth
, nbR
) {
566 const sqSize
= this.getSquareWidth(rwidth
);
567 return Math
.min(sqSize
, rwidth
/ nbR
);
570 getReserveNumId(color
, piece
) {
571 return `${this.containerId}|rnum-${color}${piece}`;
575 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
576 window
.onresize
= () => this.re_drawBoardElements();
577 this.re_drawBoardElements();
578 this.initMouseEvents();
580 document
.getElementById(this.containerId
).querySelector(".chessboard");
581 new ResizeObserver(this.rescale
).observe(chessboard
);
584 re_drawBoardElements() {
585 const board
= this.getSvgChessboard();
586 const oppCol
= C
.GetOppCol(this.playerColor
);
588 document
.getElementById(this.containerId
).querySelector(".chessboard");
589 chessboard
.innerHTML
= "";
590 chessboard
.insertAdjacentHTML('beforeend', board
);
591 const aspectRatio
= this.size
.y
/ this.size
.x
;
592 // Compare window ratio width / height to aspectRatio:
593 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
594 let cbWidth
, cbHeight
;
595 if (windowRatio
<= aspectRatio
) {
596 // Limiting dimension is width:
597 cbWidth
= Math
.min(window
.innerWidth
, 767);
598 cbHeight
= cbWidth
/ aspectRatio
;
601 // Limiting dimension is height:
602 cbHeight
= Math
.min(window
.innerHeight
, 767);
603 cbWidth
= cbHeight
* aspectRatio
;
606 const sqSize
= cbWidth
/ this.size
.y
;
607 // NOTE: allocate space for reserves (up/down) even if they are empty
608 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
609 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
610 cbWidth
= cbHeight
* aspectRatio
;
613 chessboard
.style
.width
= cbWidth
+ "px";
614 chessboard
.style
.height
= cbHeight
+ "px";
615 // Center chessboard:
616 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
617 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
618 chessboard
.style
.left
= spaceLeft
+ "px";
619 chessboard
.style
.top
= spaceTop
+ "px";
620 // Give sizes instead of recomputing them,
621 // because chessboard might not be drawn yet.
630 // Get SVG board (background, no pieces)
632 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
633 const flipped
= (this.playerColor
== 'b');
638 class="chessboard_SVG">
640 for (let i
=0; i
< sizeX
; i
++) {
641 for (let j
=0; j
< sizeY
; j
++) {
642 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
643 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
644 let classes
= this.getSquareColorClass(ii
, jj
);
645 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
646 classes
+= " in-shadow";
647 // NOTE: x / y reversed because coordinates system is reversed.
650 id="${this.coordsToId([ii, jj])}"
657 board
+= "</g></svg>";
661 // Generally light square bottom-right
662 getSquareColorClass(i
, j
) {
663 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
668 // Refreshing: delete old pieces first
669 for (let i
=0; i
<this.size
.x
; i
++) {
670 for (let j
=0; j
<this.size
.y
; j
++) {
671 if (this.g_pieces
[i
][j
]) {
672 this.g_pieces
[i
][j
].remove();
673 this.g_pieces
[i
][j
] = null;
678 else this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
680 document
.getElementById(this.containerId
).querySelector(".chessboard");
681 if (!r
) r
= chessboard
.getBoundingClientRect();
682 const pieceWidth
= this.getPieceWidth(r
.width
);
683 for (let i
=0; i
< this.size
.x
; i
++) {
684 for (let j
=0; j
< this.size
.y
; j
++) {
686 this.board
[i
][j
] != "" &&
687 (!this.options
["dark"] || this.enlightened
[i
][j
])
689 const color
= this.getColor(i
, j
);
690 const piece
= this.getPiece(i
, j
);
691 this.g_pieces
[i
][j
] = document
.createElement("piece");
692 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
693 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
694 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
695 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
696 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
697 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
698 chessboard
.appendChild(this.g_pieces
[i
][j
]);
702 if (this.reserve
) this.re_drawReserve(['w', 'b'], r
);
705 // NOTE: assume !!this.reserve
706 re_drawReserve(colors
, r
) {
708 // Remove (old) reserve pieces
709 for (let c
of colors
) {
710 if (!this.reserve
[c
]) continue;
711 Object
.keys(this.reserve
[c
]).forEach(p
=> {
712 if (this.r_pieces
[c
][p
]) {
713 this.r_pieces
[c
][p
].remove();
714 delete this.r_pieces
[c
][p
];
715 const numId
= this.getReserveNumId(c
, p
);
716 document
.getElementById(numId
).remove();
719 let reservesDiv
= document
.getElementById("reserves_" + c
);
720 if (reservesDiv
) reservesDiv
.remove();
723 else this.r_pieces
= { 'w': {}, 'b': {} };
725 document
.getElementById(this.containerId
).querySelector(".chessboard");
726 if (!r
) r
= chessboard
.getBoundingClientRect();
727 for (let c
of colors
) {
728 if (!this.reserve
[c
]) continue;
729 const nbR
= this.getNbReservePieces(c
);
730 if (nbR
== 0) continue;
731 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
733 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
734 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
735 let rcontainer
= document
.createElement("div");
736 rcontainer
.id
= "reserves_" + c
;
737 rcontainer
.classList
.add("reserves");
738 rcontainer
.style
.left
= i0
+ "px";
739 rcontainer
.style
.top
= j0
+ "px";
740 // NOTE: +1 fix display bug on Firefox at least
741 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
742 rcontainer
.style
.height
= sqResSize
+ "px";
743 chessboard
.appendChild(rcontainer
);
744 for (let p
of Object
.keys(this.reserve
[c
])) {
745 if (this.reserve
[c
][p
] == 0) continue;
746 let r_cell
= document
.createElement("div");
747 r_cell
.id
= this.coordsToId([c
, p
]);
748 r_cell
.classList
.add("reserve-cell");
749 r_cell
.style
.width
= sqResSize
+ "px";
750 r_cell
.style
.height
= sqResSize
+ "px";
751 rcontainer
.appendChild(r_cell
);
752 let piece
= document
.createElement("piece");
753 const pieceSpec
= this.pieces(c
)[p
];
754 piece
.classList
.add(pieceSpec
["class"]);
755 piece
.classList
.add(c
== 'w' ? "white" : "black");
756 piece
.style
.width
= "100%";
757 piece
.style
.height
= "100%";
758 this.r_pieces
[c
][p
] = piece
;
759 r_cell
.appendChild(piece
);
760 let number
= document
.createElement("div");
761 number
.textContent
= this.reserve
[c
][p
];
762 number
.classList
.add("reserve-num");
763 number
.id
= this.getReserveNumId(c
, p
);
764 const fontSize
= "1.3em";
765 number
.style
.fontSize
= fontSize
;
766 number
.style
.fontSize
= fontSize
;
767 r_cell
.appendChild(number
);
773 updateReserve(color
, piece
, count
) {
774 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
775 piece
= "k"; //capturing cannibal king: back to king form
776 const oldCount
= this.reserve
[color
][piece
];
777 this.reserve
[color
][piece
] = count
;
778 // Redrawing is much easier if count==0
779 if ([oldCount
, count
].includes(0)) this.re_drawReserve([color
]);
781 const numId
= this.getReserveNumId(color
, piece
);
782 document
.getElementById(numId
).textContent
= count
;
786 // After resize event: no need to destroy/recreate pieces
788 const container
= document
.getElementById(this.containerId
);
789 if (!container
) return; //useful at initial loading
790 let chessboard
= container
.querySelector(".chessboard");
791 const r
= chessboard
.getBoundingClientRect();
792 const newRatio
= r
.width
/ r
.height
;
793 const aspectRatio
= this.size
.y
/ this.size
.x
;
794 let newWidth
= r
.width
,
795 newHeight
= r
.height
;
796 if (newRatio
> aspectRatio
) {
797 newWidth
= r
.height
* aspectRatio
;
798 chessboard
.style
.width
= newWidth
+ "px";
800 else if (newRatio
< aspectRatio
) {
801 newHeight
= r
.width
/ aspectRatio
;
802 chessboard
.style
.height
= newHeight
+ "px";
804 const newX
= (window
.innerWidth
- newWidth
) / 2;
805 chessboard
.style
.left
= newX
+ "px";
806 const newY
= (window
.innerHeight
- newHeight
) / 2;
807 chessboard
.style
.top
= newY
+ "px";
808 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
809 const pieceWidth
= this.getPieceWidth(newWidth
);
810 for (let i
=0; i
< this.size
.x
; i
++) {
811 for (let j
=0; j
< this.size
.y
; j
++) {
812 if (this.board
[i
][j
] != "") {
813 // NOTE: could also use CSS transform "scale"
814 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
815 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
816 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
817 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
821 if (this.reserve
) this.rescaleReserve(newR
);
825 for (let c
of ['w','b']) {
826 if (!this.reserve
[c
]) continue;
827 const nbR
= this.getNbReservePieces(c
);
828 if (nbR
== 0) continue;
829 // Resize container first
830 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
831 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
832 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
833 let rcontainer
= document
.getElementById("reserves_" + c
);
834 rcontainer
.style
.left
= i0
+ "px";
835 rcontainer
.style
.top
= j0
+ "px";
836 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
837 rcontainer
.style
.height
= sqResSize
+ "px";
838 // And then reserve cells:
839 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
840 Object
.keys(this.reserve
[c
]).forEach(p
=> {
841 if (this.reserve
[c
][p
] == 0) return;
842 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
843 r_cell
.style
.width
= sqResSize
+ "px";
844 r_cell
.style
.height
= sqResSize
+ "px";
849 // Return the absolute pixel coordinates (on board) given current position.
850 // Our coordinate system differs from CSS one (x <--> y).
851 // We return here the CSS coordinates (more useful).
852 getPixelPosition(i
, j
, r
) {
853 const sqSize
= this.getSquareWidth(r
.width
);
854 if (i
< 0 || j
< 0) return [0, 0]; //piece vanishes
855 const flipped
= (this.playerColor
== 'b');
856 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
857 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
863 document
.getElementById(this.containerId
).querySelector(".chessboard");
865 const getOffset
= e
=> {
868 return {x: e
.clientX
, y: e
.clientY
};
869 let touchLocation
= null;
870 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
871 // Touch screen, dragstart
872 touchLocation
= e
.targetTouches
[0];
873 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
874 // Touch screen, dragend
875 touchLocation
= e
.changedTouches
[0];
877 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
878 return [0, 0]; //shouldn't reach here =)
881 const centerOnCursor
= (piece
, e
) => {
882 const centerShift
= sqSize
/ 2;
883 const offset
= getOffset(e
);
884 piece
.style
.left
= (offset
.x
- r
.x
- centerShift
) + "px";
885 piece
.style
.top
= (offset
.y
- r
.y
- centerShift
) + "px";
890 startPiece
, curPiece
= null,
892 const mousedown
= (e
) => {
893 // Disable zoom on smartphones:
894 if (e
.touches
&& e
.touches
.length
> 1) e
.preventDefault();
895 r
= chessboard
.getBoundingClientRect();
896 sqSize
= this.getSquareWidth(r
.width
);
897 const square
= this.idToCoords(e
.target
.id
);
899 const [i
, j
] = square
;
900 const move = this.doClick([i
, j
]);
901 if (move) this.playPlusVisual(move);
903 if (typeof i
!= "number") startPiece
= this.r_pieces
[i
][j
];
904 else if (this.g_pieces
[i
][j
]) startPiece
= this.g_pieces
[i
][j
];
905 if (startPiece
&& this.canIplay(i
, j
)) {
907 start
= { x: i
, y: j
};
908 curPiece
= startPiece
.cloneNode();
909 curPiece
.style
.transform
= "none";
910 curPiece
.style
.zIndex
= 5;
911 curPiece
.style
.width
= sqSize
+ "px";
912 curPiece
.style
.height
= sqSize
+ "px";
913 centerOnCursor(curPiece
, e
);
914 chessboard
.appendChild(curPiece
);
915 startPiece
.style
.opacity
= "0.4";
916 chessboard
.style
.cursor
= "none";
922 const mousemove
= (e
) => {
925 centerOnCursor(curPiece
, e
);
927 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
928 // Attempt to prevent horizontal swipe...
932 const mouseup
= (e
) => {
933 const newR
= chessboard
.getBoundingClientRect();
934 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
939 const [x
, y
] = [start
.x
, start
.y
];
942 chessboard
.style
.cursor
= "pointer";
943 startPiece
.style
.opacity
= "1";
944 const offset
= getOffset(e
);
945 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
946 const sq
= this.idToCoords(landingElt
.id
);
949 // NOTE: clearly suboptimal, but much easier, and not a big deal.
950 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
951 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
952 const moves
= this.filterValid(potentialMoves
);
953 if (moves
.length
>= 2) this.showChoices(moves
, r
);
954 else if (moves
.length
== 1) this.playPlusVisual(moves
[0], r
);
959 if ('onmousedown' in window
) {
960 document
.addEventListener("mousedown", mousedown
);
961 document
.addEventListener("mousemove", mousemove
);
962 document
.addEventListener("mouseup", mouseup
);
964 if ('ontouchstart' in window
) {
965 // https://stackoverflow.com/a/42509310/12660887
966 document
.addEventListener("touchstart", mousedown
, {passive: false});
967 document
.addEventListener("touchmove", mousemove
, {passive: false});
968 document
.addEventListener("touchend", mouseup
, {passive: false});
970 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
973 showChoices(moves
, r
) {
974 let container
= document
.getElementById(this.containerId
);
975 let chessboard
= container
.querySelector(".chessboard");
976 let choices
= document
.createElement("div");
977 choices
.id
= "choices";
978 choices
.style
.width
= r
.width
+ "px";
979 choices
.style
.height
= r
.height
+ "px";
980 choices
.style
.left
= r
.x
+ "px";
981 choices
.style
.top
= r
.y
+ "px";
982 chessboard
.style
.opacity
= "0.5";
983 container
.appendChild(choices
);
984 const squareWidth
= this.getSquareWidth(r
.width
);
985 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
986 const firstUpTop
= (r
.height
- squareWidth
) / 2;
987 const color
= moves
[0].appear
[0].c
;
988 const callback
= (m
) => {
989 chessboard
.style
.opacity
= "1";
990 container
.removeChild(choices
);
991 this.playPlusVisual(m
, r
);
993 for (let i
=0; i
< moves
.length
; i
++) {
994 let choice
= document
.createElement("div");
995 choice
.classList
.add("choice");
996 choice
.style
.width
= squareWidth
+ "px";
997 choice
.style
.height
= squareWidth
+ "px";
998 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
999 choice
.style
.top
= firstUpTop
+ "px";
1000 choice
.style
.backgroundColor
= "lightyellow";
1001 choice
.onclick
= () => callback(moves
[i
]);
1002 const piece
= document
.createElement("piece");
1003 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
1004 piece
.classList
.add(pieceSpec
["class"]);
1005 piece
.classList
.add(color
== 'w' ? "white" : "black");
1006 piece
.style
.width
= "100%";
1007 piece
.style
.height
= "100%";
1008 choice
.appendChild(piece
);
1009 choices
.appendChild(choice
);
1017 return { "x": 8, "y": 8 };
1020 // Color of thing on square (i,j). 'undefined' if square is empty
1022 return this.board
[i
][j
].charAt(0);
1025 // Assume square i,j isn't empty
1027 return this.board
[i
][j
].charAt(1);
1030 // Piece type on square (i,j)
1031 getPieceType(i
, j
) {
1032 const p
= this.board
[i
][j
].charAt(1);
1033 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1036 // Get opponent color
1037 static GetOppCol(color
) {
1038 return (color
== "w" ? "b" : "w");
1041 // Can thing on square1 take thing on square2
1042 canTake([x1
, y1
], [x2
, y2
]) {
1044 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
)) ||
1046 (this.options
["recycle"] || this.options
["teleport"]) &&
1047 this.getPieceType(x2
, y2
) != "k"
1052 // Is (x,y) on the chessboard?
1054 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1057 // Used in interface: 'side' arg == player color
1060 this.playerColor
== this.turn
&&
1062 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1063 (typeof x
== "string" && x
== this.turn
) //reserve
1068 ////////////////////////
1069 // PIECES SPECIFICATIONS
1072 const pawnShift
= (color
== "w" ? -1 : 1);
1076 steps: [[pawnShift
, 0]],
1078 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1083 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1089 [1, 2], [1, -2], [-1, 2], [-1, -2],
1090 [2, 1], [-2, 1], [2, -1], [-2, -1]
1097 steps: [[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]
1111 [0, 1], [0, -1], [1, 0], [-1, 0],
1112 [1, 1], [1, -1], [-1, 1], [-1, -1]
1117 's': { "class": "king-pawn" },
1118 'u': { "class": "king-rook" },
1119 'o': { "class": "king-knight" },
1120 'c': { "class": "king-bishop" },
1121 't': { "class": "king-queen" }
1125 ////////////////////
1128 // For Cylinder: get Y coordinate
1130 if (!this.options
["cylinder"]) return y
;
1131 let res
= y
% this.size
.y
;
1132 if (res
< 0) res
+= this.size
.y
;
1136 // Stop at the first capture found
1137 atLeastOneCapture(color
) {
1138 color
= color
|| this.turn
;
1139 const oppCol
= C
.GetOppCol(color
);
1140 for (let i
= 0; i
< this.size
.x
; i
++) {
1141 for (let j
= 0; j
< this.size
.y
; j
++) {
1142 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1143 const specs
= this.pieces(color
)[this.getPieceType(i
, j
)];
1144 const steps
= specs
.attack
|| specs
.steps
;
1145 outerLoop: for (let step
of steps
) {
1146 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1147 let stepCounter
= 1;
1148 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1149 if (specs
.range
<= stepCounter
++) continue outerLoop
;
1151 jj
= this.computeY(jj
+ step
[1]);
1154 this.onBoard(ii
, jj
) &&
1155 this.getColor(ii
, jj
) == oppCol
&&
1157 [this.getBasicMove([i
, j
], [ii
, jj
])]
1169 getDropMovesFrom([c
, p
]) {
1170 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1171 // (but not necessarily otherwise)
1172 if (this.reserve
[c
][p
] == 0) return [];
1174 for (let i
=0; i
<this.size
.x
; i
++) {
1175 for (let j
=0; j
<this.size
.y
; j
++) {
1176 // TODO: rather simplify this "if" and add post-condition: more general
1178 this.board
[i
][j
] == "" &&
1179 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1182 (c
== 'w' && i
< this.size
.x
- 1) ||
1188 start: {x: c
, y: p
},
1190 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1200 // All possible moves from selected square
1201 getPotentialMovesFrom(sq
, color
) {
1202 if (typeof sq
[0] == "string") return this.getDropMovesFrom(sq
);
1203 if (this.options
["madrasi"] && this.isImmobilized(sq
)) return [];
1204 const piece
= this.getPieceType(sq
[0], sq
[1]);
1206 if (piece
== "p") moves
= this.getPotentialPawnMoves(sq
);
1207 else moves
= this.getPotentialMovesOf(piece
, sq
);
1211 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1213 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1215 return this.postProcessPotentialMoves(moves
);
1218 postProcessPotentialMoves(moves
) {
1219 if (moves
.length
== 0) return [];
1220 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1221 const oppCol
= C
.GetOppCol(color
);
1223 if (this.options
["capture"] && this.atLeastOneCapture()) {
1224 // Filter out non-capturing moves (not using m.vanish because of
1225 // self captures of Recycle and Teleport).
1226 moves
= moves
.filter(m
=> {
1228 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1229 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1234 if (this.options
["atomic"]) {
1235 moves
.forEach(m
=> {
1237 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1238 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1251 for (let step
of steps
) {
1252 let x
= m
.end
.x
+ step
[0];
1253 let y
= this.computeY(m
.end
.y
+ step
[1]);
1255 this.onBoard(x
, y
) &&
1256 this.board
[x
][y
] != "" &&
1257 this.getPieceType(x
, y
) != "p"
1261 p: this.getPiece(x
, y
),
1262 c: this.getColor(x
, y
),
1269 if (!this.options
["rifle"]) m
.appear
.pop(); //nothin appears
1275 this.options
["cannibal"] &&
1276 this.options
["rifle"] &&
1277 this.pawnSpecs
.promotions
1279 // In this case a rifle-capture from last rank may promote a pawn
1280 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1282 moves
.forEach(m
=> {
1284 m
.start
.x
== lastRank
&&
1285 m
.appear
.length
>= 1 &&
1286 m
.appear
[0].p
== "p" &&
1287 m
.appear
[0].x
== m
.start
.x
&&
1288 m
.appear
[0].y
== m
.start
.y
1290 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1291 m
.appear
[0].p
= this.pawnSpecs
.promotions
[0];
1292 for (let i
=1; i
<this.pawnSpecs
.promotions
.length
; i
++) {
1293 let newMv
= JSON
.parse(JSON
.stringify(m
));
1294 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1295 newMoves
.push(newMv
);
1299 Array
.prototype.push
.apply(moves
, newMoves
);
1305 static get CannibalKings() {
1315 static get CannibalKingCode() {
1329 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1334 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1335 isImmobilized([x
, y
]) {
1336 const color
= this.getColor(x
, y
);
1337 const oppCol
= C
.GetOppCol(color
);
1338 const piece
= this.getPieceType(x
, y
);
1339 const stepSpec
= this.pieces(color
)[piece
];
1340 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1341 outerLoop: for (let step
of steps
) {
1342 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1343 let stepCounter
= 1;
1344 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1345 if (range
<= stepCounter
++) continue outerLoop
;
1347 j
= this.computeY(j
+ step
[1]);
1350 this.onBoard(i
, j
) &&
1351 this.getColor(i
, j
) == oppCol
&&
1352 this.getPieceType(i
, j
) == piece
1360 // Generic method to find possible moves of "sliding or jumping" pieces
1361 getPotentialMovesOf(piece
, [x
, y
]) {
1362 const color
= this.getColor(x
, y
);
1363 const stepSpec
= this.pieces(color
)[piece
];
1364 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1366 let explored
= {}; //for Cylinder mode
1367 outerLoop: for (let step
of steps
) {
1368 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1369 let stepCounter
= 1;
1371 this.onBoard(i
, j
) &&
1372 this.board
[i
][j
] == "" &&
1373 !explored
[i
+ "." + j
]
1375 explored
[i
+ "." + j
] = true;
1376 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1377 if (range
<= stepCounter
++) continue outerLoop
;
1379 j
= this.computeY(j
+ step
[1]);
1382 this.onBoard(i
, j
) &&
1384 !this.options
["zen"] ||
1385 this.getPieceType(i
, j
) == "k" ||
1386 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1388 this.canTake([x
, y
], [i
, j
]) &&
1389 !explored
[i
+ "." + j
]
1391 explored
[i
+ "." + j
] = true;
1392 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1395 if (this.options
["zen"])
1396 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1400 getZenCaptures(x
, y
) {
1402 // Find reverse captures (opponent takes)
1403 const color
= this.getColor(x
, y
);
1404 const pieceType
= this.getPieceType(x
, y
);
1405 const oppCol
= C
.GetOppCol(color
);
1406 const pieces
= this.pieces(oppCol
);
1407 Object
.keys(pieces
).forEach(p
=> {
1410 (this.options
["cannibal"] && C
.CannibalKings
[p
])
1412 return; //king isn't captured this way
1414 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1415 if (!steps
) return; //cannibal king for example (TODO...)
1416 const range
= pieces
[p
].range
;
1417 steps
.forEach(s
=> {
1418 // From x,y: revert step
1419 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1420 let stepCounter
= 1;
1421 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1422 if (range
<= stepCounter
++) return;
1424 j
= this.computeY(j
- s
[1]);
1427 this.onBoard(i
, j
) &&
1428 this.getPieceType(i
, j
) == p
&&
1429 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1430 this.canTake([i
, j
], [x
, y
])
1432 if (pieceType
!= "p") moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1433 else this.addPawnMoves([x
, y
], [i
, j
], moves
);
1440 // Build a regular move from its initial and destination squares.
1441 // tr: transformation
1442 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1443 const initColor
= this.getColor(sx
, sy
);
1444 const initPiece
= this.getPiece(sx
, sy
);
1445 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1449 start: {x:sx
, y:sy
},
1453 !this.options
["rifle"] ||
1454 this.board
[ex
][ey
] == "" ||
1455 destColor
== initColor
//Recycle, Teleport
1461 c: !!tr
? tr
.c : initColor
,
1462 p: !!tr
? tr
.p : initPiece
1474 if (this.board
[ex
][ey
] != "") {
1479 c: this.getColor(ex
, ey
),
1480 p: this.getPiece(ex
, ey
)
1483 if (this.options
["rifle"])
1484 // Rifle captures are tricky in combination with Atomic etc,
1485 // so it's useful to mark the move :
1487 if (this.options
["cannibal"] && destColor
!= initColor
) {
1488 const lastIdx
= mv
.vanish
.length
- 1;
1489 let trPiece
= mv
.vanish
[lastIdx
].p
;
1490 if (this.isKing(this.getPiece(sx
, sy
)))
1491 trPiece
= C
.CannibalKingCode
[trPiece
];
1492 if (mv
.appear
.length
>= 1) mv
.appear
[0].p
= trPiece
;
1493 else if (this.options
["rifle"]) {
1516 // En-passant square, if any
1517 getEpSquare(moveOrSquare
) {
1518 if (typeof moveOrSquare
=== "string") {
1519 const square
= moveOrSquare
;
1520 if (square
== "-") return undefined;
1521 return C
.SquareToCoords(square
);
1523 // Argument is a move:
1524 const move = moveOrSquare
;
1525 const s
= move.start
,
1529 Math
.abs(s
.x
- e
.x
) == 2 &&
1530 // Next conditions for variants like Atomic or Rifle, Recycle...
1531 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1532 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1539 return undefined; //default
1542 // Special case of en-passant captures: treated separately
1543 getEnpassantCaptures([x
, y
], shiftX
) {
1544 const color
= this.getColor(x
, y
);
1545 const oppCol
= C
.GetOppCol(color
);
1546 let enpassantMove
= null;
1549 this.epSquare
.x
== x
+ shiftX
&&
1550 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1551 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1553 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1554 this.board
[epx
][epy
] = oppCol
+ "p";
1555 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1556 this.board
[epx
][epy
] = "";
1557 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1558 enpassantMove
.vanish
[lastIdx
].x
= x
;
1560 return !!enpassantMove
? [enpassantMove
] : [];
1563 // Consider all potential promotions.
1564 // NOTE: "promotions" arg = special override for Hiddenqueen variant
1565 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1566 let finalPieces
= ["p"];
1567 const color
= this.getColor(x1
, y1
);
1568 const oppCol
= C
.GetOppCol(color
);
1569 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1571 x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == "");
1572 if (promotionOk
&& !this.options
["pawnfall"]) {
1574 this.options
["cannibal"] &&
1575 this.board
[x2
][y2
] != "" &&
1576 this.getColor(x2
, y2
) == oppCol
1578 finalPieces
= [this.getPieceType(x2
, y2
)];
1580 else if (promotions
) finalPieces
= promotions
;
1581 else if (this.pawnSpecs
.promotions
)
1582 finalPieces
= this.pawnSpecs
.promotions
;
1584 for (let piece
of finalPieces
) {
1585 const tr
= !this.options
["pawnfall"] && piece
!= "p"
1586 ? { c: color
, p: piece
}
1588 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1589 if (promotionOk
&& this.options
["pawnfall"]) {
1590 newMove
.appear
.shift();
1591 newMove
.pawnfall
= true; //required in prePlay()
1593 moves
.push(newMove
);
1597 // What are the pawn moves from square x,y ?
1598 getPotentialPawnMoves([x
, y
], promotions
) {
1599 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1600 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1601 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1602 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1603 const forward
= (color
== 'w' ? -1 : 1);
1605 // Pawn movements in shiftX direction:
1606 const getPawnMoves
= (shiftX
) => {
1608 // NOTE: next condition is generally true (no pawn on last rank)
1609 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1610 if (this.board
[x
+ shiftX
][y
] == "") {
1611 // One square forward (or backward)
1612 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1613 // Next condition because pawns on 1st rank can generally jump
1615 this.pawnSpecs
.twoSquares
&&
1619 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1622 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1626 shiftX
== forward
&&
1627 this.board
[x
+ 2 * shiftX
][y
] == ""
1630 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1632 this.pawnSpecs
.threeSquares
&&
1633 this.board
[x
+ 3 * shiftX
, y
] == ""
1635 // Three squares jump
1636 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1642 if (this.pawnSpecs
.canCapture
) {
1643 for (let shiftY
of [-1, 1]) {
1644 const yCoord
= this.computeY(y
+ shiftY
);
1645 if (yCoord
>= 0 && yCoord
< sizeY
) {
1647 this.board
[x
+ shiftX
][yCoord
] != "" &&
1648 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1650 !this.options
["zen"] ||
1651 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1655 [x
, y
], [x
+ shiftX
, yCoord
],
1660 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1661 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1662 this.board
[x
- shiftX
][yCoord
] != "" &&
1663 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1665 !this.options
["zen"] ||
1666 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1670 [x
, y
], [x
- shiftX
, yCoord
],
1681 let pMoves
= getPawnMoves(pawnShiftX
);
1682 if (this.pawnSpecs
.bidirectional
)
1683 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1685 if (this.hasEnpassant
) {
1686 // NOTE: backward en-passant captures are not considered
1687 // because no rules define them (for now).
1688 Array
.prototype.push
.apply(
1690 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1694 if (this.options
["zen"])
1695 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1700 // "castleInCheck" arg to let some variants castle under check
1701 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1702 const c
= this.getColor(x
, y
);
1705 const oppCol
= C
.GetOppCol(c
);
1709 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1710 const castlingKing
= this.getPiece(x
, y
);
1711 castlingCheck: for (
1714 castleSide
++ //large, then small
1716 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
) continue;
1717 // If this code is reached, rook and king are on initial position
1719 // NOTE: in some variants this is not a rook
1720 const rookPos
= this.castleFlags
[c
][castleSide
];
1721 const castlingPiece
= this.getPiece(x
, rookPos
);
1723 this.board
[x
][rookPos
] == "" ||
1724 this.getColor(x
, rookPos
) != c
||
1725 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1727 // Rook is not here, or changed color (see Benedict)
1730 // Nothing on the path of the king ? (and no checks)
1731 const finDist
= finalSquares
[castleSide
][0] - y
;
1732 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1736 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1738 this.board
[x
][i
] != "" &&
1739 // NOTE: next check is enough, because of chessboard constraints
1740 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1743 continue castlingCheck
;
1746 } while (i
!= finalSquares
[castleSide
][0]);
1747 // Nothing on the path to the rook?
1748 step
= (castleSide
== 0 ? -1 : 1);
1749 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1750 if (this.board
[x
][i
] != "") continue castlingCheck
;
1753 // Nothing on final squares, except maybe king and castling rook?
1754 for (i
= 0; i
< 2; i
++) {
1756 finalSquares
[castleSide
][i
] != rookPos
&&
1757 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1759 finalSquares
[castleSide
][i
] != y
||
1760 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1763 continue castlingCheck
;
1767 // If this code is reached, castle is valid
1773 y: finalSquares
[castleSide
][0],
1779 y: finalSquares
[castleSide
][1],
1785 // King might be initially disguised (Titan...)
1786 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1787 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1790 Math
.abs(y
- rookPos
) <= 2
1791 ? { x: x
, y: rookPos
}
1792 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1800 ////////////////////
1803 // Is (king at) given position under check by "color" ?
1804 underCheck([x
, y
], color
) {
1805 if (this.options
["taking"] || this.options
["dark"]) return false;
1806 color
= color
|| C
.GetOppCol(this.getColor(x
, y
));
1807 const pieces
= this.pieces(color
);
1808 return Object
.keys(pieces
).some(p
=> {
1809 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1813 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1814 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1815 if (!steps
) return false; //cannibal king, for example
1816 const range
= stepSpec
.range
;
1817 let explored
= {}; //for Cylinder mode
1818 outerLoop: for (let step
of steps
) {
1819 let rx
= x
- step
[0],
1820 ry
= this.computeY(y
- step
[1]);
1821 let stepCounter
= 1;
1823 this.onBoard(rx
, ry
) &&
1824 this.board
[rx
][ry
] == "" &&
1825 !explored
[rx
+ "." + ry
]
1827 explored
[rx
+ "." + ry
] = true;
1828 if (range
<= stepCounter
++) continue outerLoop
;
1830 ry
= this.computeY(ry
- step
[1]);
1833 this.onBoard(rx
, ry
) &&
1834 this.board
[rx
][ry
] != "" &&
1835 this.getPieceType(rx
, ry
) == piece
&&
1836 this.getColor(rx
, ry
) == color
&&
1837 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1845 // Stop at first king found (TODO: multi-kings)
1846 searchKingPos(color
) {
1847 for (let i
=0; i
< this.size
.x
; i
++) {
1848 for (let j
=0; j
< this.size
.y
; j
++) {
1849 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1853 return [-1, -1]; //king not found
1856 filterValid(moves
) {
1857 if (moves
.length
== 0) return [];
1858 const color
= this.turn
;
1859 const oppCol
= C
.GetOppCol(color
);
1860 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1861 // Forbid moves either giving check or exploding opponent's king:
1862 const oppKingPos
= this.searchKingPos(oppCol
);
1863 moves
= moves
.filter(m
=> {
1865 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1866 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1869 this.playOnBoard(m
);
1870 const res
= !this.underCheck(oppKingPos
, color
);
1871 this.undoOnBoard(m
);
1875 if (this.options
["taking"] || this.options
["dark"]) return moves
;
1876 const kingPos
= this.searchKingPos(color
);
1877 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1878 return moves
.filter(m
=> {
1879 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1880 if (!filtered
[key
]) {
1881 this.playOnBoard(m
);
1882 let square
= kingPos
,
1883 res
= true; //a priori valid
1884 if (m
.vanish
.some(v
=> {
1885 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1887 // Search king in appear array:
1889 m
.appear
.findIndex(a
=> {
1890 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1892 if (newKingIdx
>= 0)
1893 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1896 res
&&= !this.underCheck(square
, oppCol
);
1897 this.undoOnBoard(m
);
1898 filtered
[key
] = res
;
1901 return filtered
[key
];
1908 // Aggregate flags into one object
1910 return this.castleFlags
;
1913 // Reverse operation
1914 disaggregateFlags(flags
) {
1915 this.castleFlags
= flags
;
1918 // Apply a move on board
1920 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1921 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1923 // Un-apply the played move
1925 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1926 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1929 updateCastleFlags(move) {
1930 // Update castling flags if start or arrive from/at rook/king locations
1931 move.appear
.concat(move.vanish
).forEach(psq
=> {
1933 this.board
[psq
.x
][psq
.y
] != "" &&
1934 this.getPieceType(psq
.x
, psq
.y
) == "k"
1936 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1938 // NOTE: not "else if" because king can capture enemy rook...
1940 if (psq
.x
== 0) c
= "b";
1941 else if (psq
.x
== this.size
.x
- 1) c
= "w";
1943 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1944 if (fidx
>= 0) this.castleFlags
[c
][fidx
] = this.size
.y
;
1951 typeof move.start
.x
== "number" &&
1952 (!this.options
["teleport"] || this.subTurnTeleport
== 1)
1954 // OK, not a drop move
1957 // If flags already off, no need to re-check:
1958 Object
.keys(this.castleFlags
).some(c
=> {
1959 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1961 this.updateCastleFlags(move);
1963 const initSquare
= C
.CoordsToSquare(move.start
);
1965 this.options
["crazyhouse"] &&
1966 (!this.options
["rifle"] || !move.capture
)
1968 if (this.ispawn
[initSquare
]) {
1969 delete this.ispawn
[initSquare
];
1970 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1973 move.vanish
[0].p
== "p" &&
1974 move.appear
[0].p
!= "p"
1976 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
1980 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1981 if (this.hasReserve
&& !move.pawnfall
) {
1982 const color
= this.turn
;
1983 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1984 // Something appears = dropped on board (some exceptions, Chakart...)
1985 const piece
= move.appear
[i
].p
;
1986 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1988 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1989 // Something vanish: add to reserve except if recycle & opponent
1990 const piece
= move.vanish
[i
].p
;
1991 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1992 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1999 if (this.hasEnpassant
) this.epSquare
= this.getEpSquare(move);
2000 this.playOnBoard(move);
2001 this.postPlay(move);
2005 const color
= this.turn
;
2006 const oppCol
= C
.GetOppCol(color
);
2007 if (this.options
["dark"]) this.updateEnlightened(true);
2008 if (this.options
["teleport"]) {
2010 this.subTurnTeleport
== 1 &&
2011 move.vanish
.length
> move.appear
.length
&&
2012 move.vanish
[move.vanish
.length
- 1].c
== color
2014 const v
= move.vanish
[move.vanish
.length
- 1];
2015 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2016 this.subTurnTeleport
= 2;
2019 this.subTurnTeleport
= 1;
2020 this.captured
= null;
2022 if (this.options
["balance"]) {
2023 if (![1, 3].includes(this.movesCount
)) this.turn
= oppCol
;
2028 this.options
["doublemove"] &&
2029 this.movesCount
>= 1 &&
2032 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2034 const oppKingPos
= this.searchKingPos(oppCol
);
2035 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
2046 // "Stop at the first move found"
2047 atLeastOneMove(color
) {
2048 color
= color
|| this.turn
;
2049 for (let i
= 0; i
< this.size
.x
; i
++) {
2050 for (let j
= 0; j
< this.size
.y
; j
++) {
2051 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2052 // NOTE: in fact searching for all potential moves from i,j.
2053 // I don't believe this is an issue, for now at least.
2054 const moves
= this.getPotentialMovesFrom([i
, j
]);
2055 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2059 if (this.hasReserve
&& this.reserve
[color
]) {
2060 for (let p
of Object
.keys(this.reserve
[color
])) {
2061 const moves
= this.getDropMovesFrom([color
, p
]);
2062 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
2068 // What is the score ? (Interesting if game is over)
2069 getCurrentScore(move) {
2070 const color
= this.turn
;
2071 const oppCol
= C
.GetOppCol(color
);
2072 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2073 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0) return "1/2";
2074 if (kingPos
[0][0] < 0) return (color
== "w" ? "0-1" : "1-0");
2075 if (kingPos
[1][0] < 0) return (color
== "w" ? "1-0" : "0-1");
2076 if (this.atLeastOneMove()) return "*";
2077 // No valid move: stalemate or checkmate?
2078 if (!this.underCheck(kingPos
, color
)) return "1/2";
2080 return (color
== "w" ? "0-1" : "1-0");
2083 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2084 playVisual(move, r
) {
2085 move.vanish
.forEach(v
=> {
2086 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
2087 this.g_pieces
[v
.x
][v
.y
].remove();
2088 this.g_pieces
[v
.x
][v
.y
] = null;
2092 document
.getElementById(this.containerId
).querySelector(".chessboard");
2093 if (!r
) r
= chessboard
.getBoundingClientRect();
2094 const pieceWidth
= this.getPieceWidth(r
.width
);
2095 move.appear
.forEach(a
=> {
2096 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
]) return;
2097 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2098 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2099 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2100 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2101 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2102 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2103 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2104 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2108 playPlusVisual(move, r
) {
2109 this.playVisual(move, r
);
2111 this.afterPlay(move); //user method
2114 // Assumes reserve on top (usage case otherwise? TODO?)
2115 getReserveShift(c
, p
, r
) {
2118 for (let pi
of Object
.keys(this.reserve
[c
])) {
2119 if (this.reserve
[c
][pi
] == 0) continue;
2120 if (pi
== p
) ridx
= nbR
;
2123 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2124 return [-ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2127 animate(move, callback
) {
2128 if (this.noAnimate
) {
2132 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2133 const dropMove
= (typeof i1
== "string");
2134 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2135 let startPiece
= startArray
[i1
][j1
];
2137 document
.getElementById(this.containerId
).querySelector(".chessboard");
2138 const clonePiece
= (
2140 this.options
["rifle"] ||
2141 (this.options
["teleport"] && this.subTurnTeleport
== 2)
2144 startPiece
= startPiece
.cloneNode();
2145 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "0";
2146 if (this.options
["teleport"] && this.subTurnTeleport
== 2) {
2147 const pieces
= this.pieces();
2148 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2149 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2150 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2153 chessboard
.appendChild(startPiece
);
2155 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2159 i1
== this.playerColor
? this.size
.x : 0,
2160 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2163 else startCoords
= [i1
, j1
];
2164 const r
= chessboard
.getBoundingClientRect();
2165 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2167 if (dropMove
) rs
= this.getReserveShift(i1
, j1
, r
);
2169 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2170 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2171 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2172 const duration
= 0.2 + multFact
* 0.3;
2173 const initTransform
= startPiece
.style
.transform
;
2174 startPiece
.style
.transform
=
2175 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2176 startPiece
.style
.transitionDuration
= duration
+ "s";
2180 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "1";
2181 startPiece
.remove();
2184 startPiece
.style
.transform
= initTransform
;
2185 startPiece
.style
.transitionDuration
= "0s";
2193 playReceivedMove(moves
, callback
) {
2194 const launchAnimation
= () => {
2195 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2196 const animateRec
= i
=> {
2197 this.animate(moves
[i
], () => {
2198 this.playVisual(moves
[i
], r
);
2199 this.play(moves
[i
]);
2200 if (i
< moves
.length
- 1) setTimeout(() => animateRec(i
+1), 300);
2206 // Delay if user wasn't focused:
2207 const checkDisplayThenAnimate
= (delay
) => {
2208 if (container
.style
.display
== "none") {
2209 alert("New move! Let's go back to game...");
2210 document
.getElementById("gameInfos").style
.display
= "none";
2211 container
.style
.display
= "block";
2212 setTimeout(launchAnimation
, 700);
2214 else setTimeout(launchAnimation
, delay
|| 0);
2216 let container
= document
.getElementById(this.containerId
);
2217 if (document
.hidden
) {
2218 document
.onvisibilitychange
= () => {
2219 document
.onvisibilitychange
= undefined;
2220 checkDisplayThenAnimate(700);
2223 else checkDisplayThenAnimate();