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 // Helper class for move animation
9 constructor(callOnComplete
) {
12 this.callOnComplete
= callOnComplete
;
15 if (++this.value
== this.target
)
16 this.callOnComplete();
21 // NOTE: x coords: top to bottom (white perspective); y: left to right
22 // NOTE: ChessRules is aliased as window.C, and variants as window.V
23 export default class ChessRules
{
25 static get Aliases() {
26 return {'C': ChessRules
};
29 /////////////////////////
30 // VARIANT SPECIFICATIONS
32 // Some variants have specific options, like the number of pawns in Monster,
33 // or the board size for Pandemonium.
34 // Users can generally select a randomness level from 0 to 2.
35 static get Options() {
39 variable: "randomness",
42 {label: "Deterministic", value: 0},
43 {label: "Symmetric random", value: 1},
44 {label: "Asymmetric random", value: 2}
49 label: "Capture king",
55 label: "Falling pawn",
61 // Game modifiers (using "elementary variants"). Default: false
64 "balance", //takes precedence over doublemove & progressive
68 "cylinder", //ok with all
72 "progressive", //(natural) priority over doublemove
81 get pawnPromotions() {
82 return ['q', 'r', 'n', 'b'];
85 // Some variants don't have flags:
94 // En-passant captures allowed?
101 !!this.options
["crazyhouse"] ||
102 (!!this.options
["recycle"] && !this.options
["teleport"])
105 // Some variants do not store reserve state (Align4, Chakart...)
106 get hasReserveFen() {
107 return this.hasReserve
;
111 return !!this.options
["dark"];
118 // Some variants use click infos:
120 if (typeof coords
.x
!= "number")
121 return null; //click on reserves
123 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
124 this.board
[coords
.x
][coords
.y
] == ""
127 start: {x: this.captured
.x
, y: this.captured
.y
},
132 c: this.captured
.c
, //this.turn,
138 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
147 // 3a --> {x:3, y:10}
148 static SquareToCoords(sq
) {
149 return ArrayFun
.toObject(["x", "y"],
150 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
153 // {x:11, y:12} --> bc
154 static CoordsToSquare(cd
) {
155 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
159 if (typeof cd
.x
== "number") {
161 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
165 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
168 idToCoords(targetId
) {
170 return null; //outside page, maybe...
171 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
173 idParts
.length
< 2 ||
174 idParts
[0] != this.containerId
||
175 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
179 const squares
= idParts
[1].split('-');
180 if (squares
[0] == "sq")
181 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
182 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
183 return {x: squares
[1], y: squares
[2]};
189 // Turn "wb" into "B" (for FEN)
191 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
194 // Turn "p" into "bp" (for board)
196 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
199 // Setup the initial random-or-not (asymmetric-or-not) position
200 genRandInitFen(seed
) {
201 let fen
, flags
= "0707";
202 if (!this.options
.randomness
)
204 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
208 Random
.setSeed(seed
);
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)
271 parts
.push(`"flags":"${flags}"`);
272 if (this.hasEnpassant
)
273 parts
.push('"enpassant":"-"');
274 if (this.hasReserveFen
)
275 parts
.push('"reserve":"000000000000"');
276 if (this.options
["crazyhouse"])
277 parts
.push('"ispawn":"-"');
278 if (parts
.length
>= 1)
279 fen
+= " {" + parts
.join(",") + "}";
283 // "Parse" FEN: just return untransformed string data
285 const fenParts
= fen
.split(" ");
287 position: fenParts
[0],
289 movesCount: fenParts
[2]
291 if (fenParts
.length
> 3)
292 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
296 // Return current fen (game state)
299 this.getPosition() + " " +
300 this.getTurnFen() + " " +
305 parts
.push(`"flags":"${this.getFlagsFen()}"`);
306 if (this.hasEnpassant
)
307 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
308 if (this.hasReserveFen
)
309 parts
.push(`"reserve":"${this.getReserveFen()}"`);
310 if (this.options
["crazyhouse"])
311 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
312 if (parts
.length
>= 1)
313 fen
+= " {" + parts
.join(",") + "}";
317 static FenEmptySquares(count
) {
318 // if more than 9 consecutive free spaces, break the integer,
319 // otherwise FEN parsing will fail.
322 // Most boards of size < 18:
324 return "9" + (count
- 9);
326 return "99" + (count
- 18);
329 // Position part of the FEN string
332 for (let i
= 0; i
< this.size
.y
; i
++) {
334 for (let j
= 0; j
< this.size
.x
; j
++) {
335 if (this.board
[i
][j
] == "")
338 if (emptyCount
> 0) {
339 // Add empty squares in-between
340 position
+= C
.FenEmptySquares(emptyCount
);
343 position
+= this.board2fen(this.board
[i
][j
]);
348 position
+= C
.FenEmptySquares(emptyCount
);
349 if (i
< this.size
.y
- 1)
350 position
+= "/"; //separate rows
359 // Flags part of the FEN string
361 return ["w", "b"].map(c
=> {
362 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
366 // Enpassant part of the FEN string
369 return "-"; //no en-passant
370 return C
.CoordsToSquare(this.epSquare
);
375 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
380 const squares
= Object
.keys(this.ispawn
);
381 if (squares
.length
== 0)
383 return squares
.join(",");
386 // Set flags from fen (castle: white a,h then black a,h)
389 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
390 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
398 this.options
= o
.options
;
399 // Fill missing options (always the case if random challenge)
400 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
401 if (this.options
[opt
.variable
] === undefined)
402 this.options
[opt
.variable
] = opt
.defaut
;
405 // This object will be used only for initial FEN generation
407 this.playerColor
= o
.color
;
408 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
410 // Fen string fully describes the game state
412 o
.fen
= this.genRandInitFen(o
.seed
);
413 this.re_initFromFen(o
.fen
);
415 // Graphical (can use variables defined above)
416 this.containerId
= o
.element
;
417 this.graphicalInit();
420 re_initFromFen(fen
, oldBoard
) {
421 const fenParsed
= this.parseFen(fen
);
422 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
423 this.turn
= fenParsed
.turn
;
424 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
425 this.setOtherVariables(fenParsed
);
428 // Turn position fen into double array ["wb","wp","bk",...]
430 const rows
= position
.split("/");
431 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
432 for (let i
= 0; i
< rows
.length
; i
++) {
434 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
435 const character
= rows
[i
][indexInRow
];
436 const num
= parseInt(character
, 10);
437 // If num is a number, just shift j:
440 // Else: something at position i,j
442 board
[i
][j
++] = this.fen2board(character
);
448 // Some additional variables from FEN (variant dependant)
449 setOtherVariables(fenParsed
) {
450 // Set flags and enpassant:
452 this.setFlags(fenParsed
.flags
);
453 if (this.hasEnpassant
)
454 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
456 this.initReserves(fenParsed
.reserve
);
457 if (this.options
["crazyhouse"])
458 this.initIspawn(fenParsed
.ispawn
);
459 if (this.options
["teleport"]) {
460 this.subTurnTeleport
= 1;
461 this.captured
= null;
463 if (this.options
["dark"]) {
464 // Setup enlightened: squares reachable by player side
465 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
466 this.updateEnlightened();
468 this.subTurn
= 1; //may be unused
469 if (!this.moveStack
) //avoid resetting (unwanted)
473 updateEnlightened() {
474 this.oldEnlightened
= this.enlightened
;
475 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
476 // Add pieces positions + all squares reachable by moves (includes Zen):
477 for (let x
=0; x
<this.size
.x
; x
++) {
478 for (let y
=0; y
<this.size
.y
; y
++) {
479 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
481 this.enlightened
[x
][y
] = true;
482 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
483 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
489 this.enlightEnpassant();
492 // Include square of the en-passant capturing square:
494 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
495 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
496 for (let step
of steps
) {
497 const x
= this.epSquare
.x
- step
[0],
498 y
= this.getY(this.epSquare
.y
- step
[1]);
500 this.onBoard(x
, y
) &&
501 this.getColor(x
, y
) == this.playerColor
&&
502 this.getPieceType(x
, y
) == "p"
504 this.enlightened
[x
][this.epSquare
.y
] = true;
510 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
511 initReserves(reserveStr
) {
512 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
513 this.reserve
= { w: {}, b: {} };
514 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
515 const L
= pieceName
.length
;
516 for (let i
of ArrayFun
.range(2 * L
)) {
518 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
520 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
524 initIspawn(ispawnStr
) {
525 if (ispawnStr
!= "-")
526 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
531 getNbReservePieces(color
) {
533 Object
.values(this.reserve
[color
]).reduce(
534 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
538 getRankInReserve(c
, p
) {
539 const pieces
= Object
.keys(this.pieces());
540 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
541 let toTest
= pieces
.slice(0, lastIndex
);
542 return toTest
.reduce(
543 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
549 getPieceWidth(rwidth
) {
550 return (rwidth
/ this.size
.y
);
553 getReserveSquareSize(rwidth
, nbR
) {
554 const sqSize
= this.getPieceWidth(rwidth
);
555 return Math
.min(sqSize
, rwidth
/ nbR
);
558 getReserveNumId(color
, piece
) {
559 return `${this.containerId}|rnum-${color}${piece}`;
562 static AddClass_es(piece
, class_es
) {
563 if (!Array
.isArray(class_es
))
564 class_es
= [class_es
];
565 class_es
.forEach(cl
=> {
566 piece
.classList
.add(cl
);
570 static RemoveClass_es(piece
, class_es
) {
571 if (!Array
.isArray(class_es
))
572 class_es
= [class_es
];
573 class_es
.forEach(cl
=> {
574 piece
.classList
.remove(cl
);
579 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
580 window
.onresize
= () => this.re_drawBoardElements();
581 this.re_drawBoardElements();
582 this.initMouseEvents();
584 document
.getElementById(this.containerId
).querySelector(".chessboard");
587 re_drawBoardElements() {
588 const board
= this.getSvgChessboard();
589 const oppCol
= C
.GetOppCol(this.playerColor
);
591 document
.getElementById(this.containerId
).querySelector(".chessboard");
592 chessboard
.innerHTML
= "";
593 chessboard
.insertAdjacentHTML('beforeend', board
);
594 // Compare window ratio width / height to aspectRatio:
595 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
596 let cbWidth
, cbHeight
;
597 const vRatio
= this.size
.ratio
|| 1;
598 if (windowRatio
<= vRatio
) {
599 // Limiting dimension is width:
600 cbWidth
= Math
.min(window
.innerWidth
, 767);
601 cbHeight
= cbWidth
/ vRatio
;
604 // Limiting dimension is height:
605 cbHeight
= Math
.min(window
.innerHeight
, 767);
606 cbWidth
= cbHeight
* vRatio
;
608 if (this.hasReserve
) {
609 const sqSize
= cbWidth
/ this.size
.y
;
610 // NOTE: allocate space for reserves (up/down) even if they are empty
611 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
612 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
613 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
614 cbWidth
= cbHeight
* vRatio
;
617 chessboard
.style
.width
= cbWidth
+ "px";
618 chessboard
.style
.height
= cbHeight
+ "px";
619 // Center chessboard:
620 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
621 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
622 chessboard
.style
.left
= spaceLeft
+ "px";
623 chessboard
.style
.top
= spaceTop
+ "px";
624 // Give sizes instead of recomputing them,
625 // because chessboard might not be drawn yet.
634 // Get SVG board (background, no pieces)
636 const flipped
= (this.playerColor
== 'b');
639 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
640 class="chessboard_SVG">`;
641 for (let i
=0; i
< this.size
.x
; i
++) {
642 for (let j
=0; j
< this.size
.y
; j
++) {
643 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
644 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
645 let classes
= this.getSquareColorClass(ii
, jj
);
646 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
647 classes
+= " in-shadow";
648 // NOTE: x / y reversed because coordinates system is reversed.
652 id="${this.coordsToId({x: ii, y: jj})}"
664 // Generally light square bottom-right
665 getSquareColorClass(x
, y
) {
666 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
671 // Refreshing: delete old pieces first
672 for (let i
=0; i
<this.size
.x
; i
++) {
673 for (let j
=0; j
<this.size
.y
; j
++) {
674 if (this.g_pieces
[i
][j
]) {
675 this.g_pieces
[i
][j
].remove();
676 this.g_pieces
[i
][j
] = null;
682 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
684 document
.getElementById(this.containerId
).querySelector(".chessboard");
686 r
= chessboard
.getBoundingClientRect();
687 const pieceWidth
= this.getPieceWidth(r
.width
);
688 for (let i
=0; i
< this.size
.x
; i
++) {
689 for (let j
=0; j
< this.size
.y
; j
++) {
690 if (this.board
[i
][j
] != "") {
691 const color
= this.getColor(i
, j
);
692 const piece
= this.getPiece(i
, j
);
693 this.g_pieces
[i
][j
] = document
.createElement("piece");
694 C
.AddClass_es(this.g_pieces
[i
][j
],
695 this.pieces(color
, i
, j
)[piece
]["class"]);
696 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
697 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
698 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
699 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
700 // Translate coordinates to use chessboard as reference:
701 this.g_pieces
[i
][j
].style
.transform
=
702 `translate(${ip - r.x}px,${jp - r.y}px)`;
703 if (this.enlightened
&& !this.enlightened
[i
][j
])
704 this.g_pieces
[i
][j
].classList
.add("hidden");
705 chessboard
.appendChild(this.g_pieces
[i
][j
]);
710 this.re_drawReserve(['w', 'b'], r
);
713 // NOTE: assume this.reserve != null
714 re_drawReserve(colors
, r
) {
716 // Remove (old) reserve pieces
717 for (let c
of colors
) {
718 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
719 this.r_pieces
[c
][p
].remove();
720 delete this.r_pieces
[c
][p
];
721 const numId
= this.getReserveNumId(c
, p
);
722 document
.getElementById(numId
).remove();
727 this.r_pieces
= { w: {}, b: {} };
728 let container
= document
.getElementById(this.containerId
);
730 r
= container
.querySelector(".chessboard").getBoundingClientRect();
731 for (let c
of colors
) {
732 let reservesDiv
= document
.getElementById("reserves_" + c
);
734 reservesDiv
.remove();
735 if (!this.reserve
[c
])
737 const nbR
= this.getNbReservePieces(c
);
740 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
742 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
743 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
744 let rcontainer
= document
.createElement("div");
745 rcontainer
.id
= "reserves_" + c
;
746 rcontainer
.classList
.add("reserves");
747 rcontainer
.style
.left
= i0
+ "px";
748 rcontainer
.style
.top
= j0
+ "px";
749 // NOTE: +1 fix display bug on Firefox at least
750 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
751 rcontainer
.style
.height
= sqResSize
+ "px";
752 container
.appendChild(rcontainer
);
753 for (let p
of Object
.keys(this.reserve
[c
])) {
754 if (this.reserve
[c
][p
] == 0)
756 let r_cell
= document
.createElement("div");
757 r_cell
.id
= this.coordsToId({x: c
, y: p
});
758 r_cell
.classList
.add("reserve-cell");
759 r_cell
.style
.width
= sqResSize
+ "px";
760 r_cell
.style
.height
= sqResSize
+ "px";
761 rcontainer
.appendChild(r_cell
);
762 let piece
= document
.createElement("piece");
763 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
764 piece
.classList
.add(C
.GetColorClass(c
));
765 piece
.style
.width
= "100%";
766 piece
.style
.height
= "100%";
767 this.r_pieces
[c
][p
] = piece
;
768 r_cell
.appendChild(piece
);
769 let number
= document
.createElement("div");
770 number
.textContent
= this.reserve
[c
][p
];
771 number
.classList
.add("reserve-num");
772 number
.id
= this.getReserveNumId(c
, p
);
773 const fontSize
= "1.3em";
774 number
.style
.fontSize
= fontSize
;
775 number
.style
.fontSize
= fontSize
;
776 r_cell
.appendChild(number
);
782 updateReserve(color
, piece
, count
) {
783 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
784 piece
= "k"; //capturing cannibal king: back to king form
785 const oldCount
= this.reserve
[color
][piece
];
786 this.reserve
[color
][piece
] = count
;
787 // Redrawing is much easier if count==0
788 if ([oldCount
, count
].includes(0))
789 this.re_drawReserve([color
]);
791 const numId
= this.getReserveNumId(color
, piece
);
792 document
.getElementById(numId
).textContent
= count
;
796 // Apply diff this.enlightened --> oldEnlightened on board
797 graphUpdateEnlightened() {
799 document
.getElementById(this.containerId
).querySelector(".chessboard");
800 const r
= chessboard
.getBoundingClientRect();
801 const pieceWidth
= this.getPieceWidth(r
.width
);
802 for (let x
=0; x
<this.size
.x
; x
++) {
803 for (let y
=0; y
<this.size
.y
; y
++) {
804 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
805 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
806 elt
.classList
.add("in-shadow");
807 if (this.g_pieces
[x
][y
])
808 this.g_pieces
[x
][y
].classList
.add("hidden");
810 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
811 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
812 elt
.classList
.remove("in-shadow");
813 if (this.g_pieces
[x
][y
])
814 this.g_pieces
[x
][y
].classList
.remove("hidden");
820 // Resize board: no need to destroy/recreate pieces
823 document
.getElementById(this.containerId
).querySelector(".chessboard");
824 const r
= chessboard
.getBoundingClientRect();
825 const multFact
= (mode
== "up" ? 1.05 : 0.95);
826 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
828 const vRatio
= this.size
.ratio
|| 1;
829 if (newWidth
> window
.innerWidth
) {
830 newWidth
= window
.innerWidth
;
831 newHeight
= newWidth
/ vRatio
;
833 if (newHeight
> window
.innerHeight
) {
834 newHeight
= window
.innerHeight
;
835 newWidth
= newHeight
* vRatio
;
837 chessboard
.style
.width
= newWidth
+ "px";
838 chessboard
.style
.height
= newHeight
+ "px";
839 const newX
= (window
.innerWidth
- newWidth
) / 2;
840 chessboard
.style
.left
= newX
+ "px";
841 const newY
= (window
.innerHeight
- newHeight
) / 2;
842 chessboard
.style
.top
= newY
+ "px";
843 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
844 const pieceWidth
= this.getPieceWidth(newWidth
);
845 // NOTE: next "if" for variants which use squares filling
846 // instead of "physical", moving pieces
848 for (let i
=0; i
< this.size
.x
; i
++) {
849 for (let j
=0; j
< this.size
.y
; j
++) {
850 if (this.g_pieces
[i
][j
]) {
851 // NOTE: could also use CSS transform "scale"
852 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
853 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
854 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
855 // Translate coordinates to use chessboard as reference:
856 this.g_pieces
[i
][j
].style
.transform
=
857 `translate(${ip - newX}px,${jp - newY}px)`;
863 this.rescaleReserve(newR
);
867 for (let c
of ['w','b']) {
868 if (!this.reserve
[c
])
870 const nbR
= this.getNbReservePieces(c
);
873 // Resize container first
874 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
875 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
876 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
877 let rcontainer
= document
.getElementById("reserves_" + c
);
878 rcontainer
.style
.left
= i0
+ "px";
879 rcontainer
.style
.top
= j0
+ "px";
880 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
881 rcontainer
.style
.height
= sqResSize
+ "px";
882 // And then reserve cells:
883 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
884 Object
.keys(this.reserve
[c
]).forEach(p
=> {
885 if (this.reserve
[c
][p
] == 0)
887 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
888 r_cell
.style
.width
= sqResSize
+ "px";
889 r_cell
.style
.height
= sqResSize
+ "px";
894 // Return the absolute pixel coordinates given current position.
895 // Our coordinate system differs from CSS one (x <--> y).
896 // We return here the CSS coordinates (more useful).
897 getPixelPosition(i
, j
, r
) {
899 return [0, 0]; //piece vanishes
901 if (typeof i
== "string") {
902 // Reserves: need to know the rank of piece
903 const nbR
= this.getNbReservePieces(i
);
904 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
905 x
= this.getRankInReserve(i
, j
) * rsqSize
;
906 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
909 const sqSize
= r
.width
/ this.size
.y
;
910 const flipped
= (this.playerColor
== 'b');
911 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
912 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
914 return [r
.x
+ x
, r
.y
+ y
];
918 let container
= document
.getElementById(this.containerId
);
919 let chessboard
= container
.querySelector(".chessboard");
921 const getOffset
= e
=> {
924 return {x: e
.clientX
, y: e
.clientY
};
925 let touchLocation
= null;
926 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
927 // Touch screen, dragstart
928 touchLocation
= e
.targetTouches
[0];
929 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
930 // Touch screen, dragend
931 touchLocation
= e
.changedTouches
[0];
933 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
934 return {x: 0, y: 0}; //shouldn't reach here =)
937 const centerOnCursor
= (piece
, e
) => {
938 const centerShift
= this.getPieceWidth(r
.width
) / 2;
939 const offset
= getOffset(e
);
940 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
941 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
946 startPiece
, curPiece
= null,
948 const mousedown
= (e
) => {
949 // Disable zoom on smartphones:
950 if (e
.touches
&& e
.touches
.length
> 1)
952 r
= chessboard
.getBoundingClientRect();
953 pieceWidth
= this.getPieceWidth(r
.width
);
954 const cd
= this.idToCoords(e
.target
.id
);
956 const move = this.doClick(cd
);
958 this.playPlusVisual(move);
960 const [x
, y
] = Object
.values(cd
);
961 if (typeof x
!= "number")
962 startPiece
= this.r_pieces
[x
][y
];
964 startPiece
= this.g_pieces
[x
][y
];
965 if (startPiece
&& this.canIplay(x
, y
)) {
968 curPiece
= startPiece
.cloneNode();
969 curPiece
.style
.transform
= "none";
970 curPiece
.style
.zIndex
= 5;
971 curPiece
.style
.width
= pieceWidth
+ "px";
972 curPiece
.style
.height
= pieceWidth
+ "px";
973 centerOnCursor(curPiece
, e
);
974 container
.appendChild(curPiece
);
975 startPiece
.style
.opacity
= "0.4";
976 chessboard
.style
.cursor
= "none";
982 const mousemove
= (e
) => {
985 centerOnCursor(curPiece
, e
);
987 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
988 // Attempt to prevent horizontal swipe...
992 const mouseup
= (e
) => {
995 const [x
, y
] = [start
.x
, start
.y
];
998 chessboard
.style
.cursor
= "pointer";
999 startPiece
.style
.opacity
= "1";
1000 const offset
= getOffset(e
);
1001 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
1003 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
1005 // NOTE: clearly suboptimal, but much easier, and not a big deal.
1006 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
1007 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
1008 const moves
= this.filterValid(potentialMoves
);
1009 if (moves
.length
>= 2)
1010 this.showChoices(moves
, r
);
1011 else if (moves
.length
== 1)
1012 this.playPlusVisual(moves
[0], r
);
1017 if ('onmousedown' in window
) {
1018 document
.addEventListener("mousedown", mousedown
);
1019 document
.addEventListener("mousemove", mousemove
);
1020 document
.addEventListener("mouseup", mouseup
);
1021 document
.addEventListener("wheel",
1022 (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down"));
1024 if ('ontouchstart' in window
) {
1025 // https://stackoverflow.com/a/42509310/12660887
1026 document
.addEventListener("touchstart", mousedown
, {passive: false});
1027 document
.addEventListener("touchmove", mousemove
, {passive: false});
1028 document
.addEventListener("touchend", mouseup
, {passive: false});
1030 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1033 showChoices(moves
, r
) {
1034 let container
= document
.getElementById(this.containerId
);
1035 let chessboard
= container
.querySelector(".chessboard");
1036 let choices
= document
.createElement("div");
1037 choices
.id
= "choices";
1039 r
= chessboard
.getBoundingClientRect();
1040 choices
.style
.width
= r
.width
+ "px";
1041 choices
.style
.height
= r
.height
+ "px";
1042 choices
.style
.left
= r
.x
+ "px";
1043 choices
.style
.top
= r
.y
+ "px";
1044 chessboard
.style
.opacity
= "0.5";
1045 container
.appendChild(choices
);
1046 const squareWidth
= r
.width
/ this.size
.y
;
1047 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1048 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1049 const color
= moves
[0].appear
[0].c
;
1050 const callback
= (m
) => {
1051 chessboard
.style
.opacity
= "1";
1052 container
.removeChild(choices
);
1053 this.playPlusVisual(m
, r
);
1055 for (let i
=0; i
< moves
.length
; i
++) {
1056 let choice
= document
.createElement("div");
1057 choice
.classList
.add("choice");
1058 choice
.style
.width
= squareWidth
+ "px";
1059 choice
.style
.height
= squareWidth
+ "px";
1060 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1061 choice
.style
.top
= firstUpTop
+ "px";
1062 choice
.style
.backgroundColor
= "lightyellow";
1063 choice
.onclick
= () => callback(moves
[i
]);
1064 const piece
= document
.createElement("piece");
1065 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1066 C
.AddClass_es(piece
,
1067 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1068 piece
.classList
.add(C
.GetColorClass(color
));
1069 piece
.style
.width
= "100%";
1070 piece
.style
.height
= "100%";
1071 choice
.appendChild(piece
);
1072 choices
.appendChild(choice
);
1083 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1087 // Color of thing on square (i,j). 'undefined' if square is empty
1089 if (typeof i
== "string")
1090 return i
; //reserves
1091 return this.board
[i
][j
].charAt(0);
1094 static GetColorClass(c
) {
1099 return "other-color"; //unidentified color
1102 // Assume square i,j isn't empty
1104 if (typeof j
== "string")
1105 return j
; //reserves
1106 return this.board
[i
][j
].charAt(1);
1109 // Piece type on square (i,j)
1110 getPieceType(i
, j
, p
) {
1112 p
= this.getPiece(i
, j
);
1113 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1116 // Get opponent color
1117 static GetOppCol(color
) {
1118 return (color
== "w" ? "b" : "w");
1121 // Can thing on square1 capture (enemy) thing on square2?
1122 canTake([x1
, y1
], [x2
, y2
]) {
1123 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1126 // Is (x,y) on the chessboard?
1128 return (x
>= 0 && x
< this.size
.x
&&
1129 y
>= 0 && y
< this.size
.y
);
1132 // Am I allowed to move thing at square x,y ?
1134 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1137 ////////////////////////
1138 // PIECES SPECIFICATIONS
1140 pieces(color
, x
, y
) {
1141 const pawnShift
= (color
== "w" ? -1 : 1);
1142 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1143 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1149 steps: [[pawnShift
, 0]],
1150 range: (initRank
? 2 : 1)
1155 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1164 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1173 [1, 2], [1, -2], [-1, 2], [-1, -2],
1174 [2, 1], [-2, 1], [2, -1], [-2, -1]
1184 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1193 [0, 1], [0, -1], [1, 0], [-1, 0],
1194 [1, 1], [1, -1], [-1, 1], [-1, -1]
1205 [0, 1], [0, -1], [1, 0], [-1, 0],
1206 [1, 1], [1, -1], [-1, 1], [-1, -1]
1213 '!': {"class": "king-pawn", moveas: "p"},
1214 '#': {"class": "king-rook", moveas: "r"},
1215 '$': {"class": "king-knight", moveas: "n"},
1216 '%': {"class": "king-bishop", moveas: "b"},
1217 '*': {"class": "king-queen", moveas: "q"}
1221 ////////////////////
1224 // For Cylinder: get Y coordinate
1226 if (!this.options
["cylinder"])
1228 let res
= y
% this.size
.y
;
1234 // Stop at the first capture found
1235 atLeastOneCapture(color
) {
1236 color
= color
|| this.turn
;
1237 const oppCol
= C
.GetOppCol(color
);
1238 for (let i
= 0; i
< this.size
.x
; i
++) {
1239 for (let j
= 0; j
< this.size
.y
; j
++) {
1240 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1241 const allSpecs
= this.pieces(color
, i
, j
)
1242 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1244 specs
= allSpecs
[specs
.moveas
];
1245 const attacks
= specs
.attack
|| specs
.moves
;
1246 for (let a
of attacks
) {
1247 outerLoop: for (let step
of a
.steps
) {
1248 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1249 let stepCounter
= 1;
1250 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1251 if (a
.range
<= stepCounter
++)
1254 jj
= this.getY(jj
+ step
[1]);
1257 this.onBoard(ii
, jj
) &&
1258 this.getColor(ii
, jj
) == oppCol
&&
1260 [this.getBasicMove([i
, j
], [ii
, jj
])]
1273 getDropMovesFrom([c
, p
]) {
1274 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1275 // (but not necessarily otherwise: atLeastOneMove() etc)
1276 if (this.reserve
[c
][p
] == 0)
1279 for (let i
=0; i
<this.size
.x
; i
++) {
1280 for (let j
=0; j
<this.size
.y
; j
++) {
1282 this.board
[i
][j
] == "" &&
1283 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1286 (c
== 'w' && i
< this.size
.x
- 1) ||
1292 start: {x: c
, y: p
},
1294 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1304 // All possible moves from selected square
1305 getPotentialMovesFrom(sq
, color
) {
1306 if (this.subTurnTeleport
== 2)
1308 if (typeof sq
[0] == "string")
1309 return this.getDropMovesFrom(sq
);
1310 if (this.isImmobilized(sq
))
1312 const piece
= this.getPieceType(sq
[0], sq
[1]);
1313 let moves
= this.getPotentialMovesOf(piece
, sq
);
1316 this.hasEnpassant
&&
1319 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1324 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1326 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1328 return this.postProcessPotentialMoves(moves
);
1331 postProcessPotentialMoves(moves
) {
1332 if (moves
.length
== 0)
1334 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1335 const oppCol
= C
.GetOppCol(color
);
1337 if (this.options
["capture"] && this.atLeastOneCapture())
1338 moves
= this.capturePostProcess(moves
, oppCol
);
1340 if (this.options
["atomic"])
1341 this.atomicPostProcess(moves
, oppCol
);
1345 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1347 this.pawnPostProcess(moves
, color
, oppCol
);
1351 this.options
["cannibal"] &&
1352 this.options
["rifle"]
1354 // In this case a rifle-capture from last rank may promote a pawn
1355 this.riflePromotePostProcess(moves
, color
);
1361 capturePostProcess(moves
, oppCol
) {
1362 // Filter out non-capturing moves (not using m.vanish because of
1363 // self captures of Recycle and Teleport).
1364 return moves
.filter(m
=> {
1366 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1367 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1372 atomicPostProcess(moves
, oppCol
) {
1373 moves
.forEach(m
=> {
1375 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1376 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1389 for (let step
of steps
) {
1390 let x
= m
.end
.x
+ step
[0];
1391 let y
= this.getY(m
.end
.y
+ step
[1]);
1393 this.onBoard(x
, y
) &&
1394 this.board
[x
][y
] != "" &&
1395 this.getPieceType(x
, y
) != "p"
1399 p: this.getPiece(x
, y
),
1400 c: this.getColor(x
, y
),
1407 if (!this.options
["rifle"])
1408 m
.appear
.pop(); //nothing appears
1413 pawnPostProcess(moves
, color
, oppCol
) {
1415 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1416 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1417 moves
.forEach(m
=> {
1418 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1419 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1420 const promotionOk
= (
1422 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1425 return; //nothing to do
1426 if (this.options
["pawnfall"]) {
1430 let finalPieces
= ["p"];
1432 this.options
["cannibal"] &&
1433 this.board
[x2
][y2
] != "" &&
1434 this.getColor(x2
, y2
) == oppCol
1436 finalPieces
= [this.getPieceType(x2
, y2
)];
1439 finalPieces
= this.pawnPromotions
;
1440 m
.appear
[0].p
= finalPieces
[0];
1441 if (initPiece
== "!") //cannibal king-pawn
1442 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1443 for (let i
=1; i
<finalPieces
.length
; i
++) {
1444 const piece
= finalPieces
[i
];
1447 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1449 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1450 moreMoves
.push(newMove
);
1453 Array
.prototype.push
.apply(moves
, moreMoves
);
1456 riflePromotePostProcess(moves
, color
) {
1457 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1459 moves
.forEach(m
=> {
1461 m
.start
.x
== lastRank
&&
1462 m
.appear
.length
>= 1 &&
1463 m
.appear
[0].p
== "p" &&
1464 m
.appear
[0].x
== m
.start
.x
&&
1465 m
.appear
[0].y
== m
.start
.y
1467 m
.appear
[0].p
= this.pawnPromotions
[0];
1468 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1469 let newMv
= JSON
.parse(JSON
.stringify(m
));
1470 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1471 newMoves
.push(newMv
);
1475 Array
.prototype.push
.apply(moves
, newMoves
);
1478 // NOTE: using special symbols to not interfere with variants' pieces codes
1479 static get CannibalKings() {
1490 static get CannibalKingCode() {
1502 return !!C
.CannibalKings
[symbol
];
1506 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1507 isImmobilized([x
, y
]) {
1508 if (!this.options
["madrasi"])
1510 const color
= this.getColor(x
, y
);
1511 const oppCol
= C
.GetOppCol(color
);
1512 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1513 const allSpecs
= this.pieces(color
, x
, y
);
1514 let stepSpec
= allSpecs
[piece
];
1515 if (stepSpec
.moveas
)
1516 stepSpec
= allSpecs
[stepSpec
.moveas
];
1517 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1518 for (let a
of attacks
) {
1519 outerLoop: for (let step
of a
.steps
) {
1520 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1521 let stepCounter
= 1;
1522 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1523 if (a
.range
<= stepCounter
++)
1526 j
= this.getY(j
+ step
[1]);
1529 this.onBoard(i
, j
) &&
1530 this.getColor(i
, j
) == oppCol
&&
1531 this.getPieceType(i
, j
) == piece
1540 canStepOver(i
, j
, p
) {
1541 // In some variants, objects on boards don't stop movement (Chakart)
1542 return this.board
[i
][j
] == "";
1545 // Generic method to find possible moves of "sliding or jumping" pieces
1546 getPotentialMovesOf(piece
, [x
, y
]) {
1547 const color
= this.getColor(x
, y
);
1548 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1549 const allSpecs
= this.pieces(color
, x
, y
);
1550 let stepSpec
= allSpecs
[piece
];
1551 if (stepSpec
.moveas
)
1552 stepSpec
= allSpecs
[stepSpec
.moveas
];
1554 // Next 3 for Cylinder mode:
1559 const addMove
= (start
, end
) => {
1560 let newMove
= this.getBasicMove(start
, end
);
1561 if (segments
.length
> 0) {
1562 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1563 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1565 moves
.push(newMove
);
1568 const findAddMoves
= (type
, stepArray
) => {
1569 for (let s
of stepArray
) {
1570 outerLoop: for (let step
of s
.steps
) {
1573 let [i
, j
] = [x
, y
];
1574 let stepCounter
= 0;
1576 this.onBoard(i
, j
) &&
1577 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1581 !explored
[i
+ "." + j
] &&
1584 explored
[i
+ "." + j
] = true;
1585 addMove([x
, y
], [i
, j
]);
1587 if (s
.range
<= stepCounter
++)
1589 const oldIJ
= [i
, j
];
1591 j
= this.getY(j
+ step
[1]);
1592 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1593 // Boundary between segments (cylinder mode)
1594 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1598 if (!this.onBoard(i
, j
))
1600 const pieceIJ
= this.getPieceType(i
, j
);
1602 type
!= "moveonly" &&
1603 !explored
[i
+ "." + j
] &&
1605 !this.options
["zen"] ||
1609 this.canTake([x
, y
], [i
, j
]) ||
1611 (this.options
["recycle"] || this.options
["teleport"]) &&
1616 explored
[i
+ "." + j
] = true;
1617 addMove([x
, y
], [i
, j
]);
1623 const specialAttack
= !!stepSpec
.attack
;
1625 findAddMoves("attack", stepSpec
.attack
);
1626 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1627 if (this.options
["zen"]) {
1628 Array
.prototype.push
.apply(moves
,
1629 this.findCapturesOn([x
, y
], {zen: true}));
1634 // Search for enemy (or not) pieces attacking [x, y]
1635 findCapturesOn([x
, y
], args
) {
1638 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1639 for (let i
=0; i
<this.size
.x
; i
++) {
1640 for (let j
=0; j
<this.size
.y
; j
++) {
1642 this.board
[i
][j
] != "" &&
1643 this.getColor(i
, j
) == args
.oppCol
&&
1644 !this.isImmobilized([i
, j
])
1646 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1647 continue; //king not captured in this way
1648 const apparentPiece
= this.getPiece(i
, j
);
1649 // Quick check: does this potential attacker target x,y ?
1650 if (this.canStepOver(x
, y
, apparentPiece
))
1652 const allSpecs
= this.pieces(args
.oppCol
, i
, j
);
1653 let stepSpec
= allSpecs
[this.getPieceType(i
, j
)];
1654 if (stepSpec
.moveas
)
1655 stepSpec
= allSpecs
[stepSpec
.moveas
];
1656 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1657 for (let a
of attacks
) {
1658 for (let s
of a
.steps
) {
1659 // Quick check: if step isn't compatible, don't even try
1660 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1662 // Finally verify that nothing stand in-between
1663 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1664 let stepCounter
= 1;
1666 this.onBoard(ii
, jj
) &&
1667 this.board
[ii
][jj
] == "" &&
1668 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1671 jj
= this.getY(jj
+ s
[1]);
1673 if (ii
== x
&& jj
== y
) {
1676 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1678 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1680 return moves
; //test for underCheck
1690 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1691 const rx
= (x2
- x1
) / step
[0],
1692 ry
= (y2
- y1
) / step
[1];
1694 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1695 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1699 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1700 // TODO: 1e-7 here is totally arbitrary
1701 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1703 distance
= Math
.round(distance
); //in case of (numerical...)
1704 if (range
< distance
)
1709 // Build a regular move from its initial and destination squares.
1710 // tr: transformation
1711 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1712 const initColor
= this.getColor(sx
, sy
);
1713 const initPiece
= this.getPiece(sx
, sy
);
1714 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1718 start: {x: sx
, y: sy
},
1722 !this.options
["rifle"] ||
1723 this.board
[ex
][ey
] == "" ||
1724 destColor
== initColor
//Recycle, Teleport
1730 c: !!tr
? tr
.c : initColor
,
1731 p: !!tr
? tr
.p : initPiece
1743 if (this.board
[ex
][ey
] != "") {
1748 c: this.getColor(ex
, ey
),
1749 p: this.getPiece(ex
, ey
)
1752 if (this.options
["cannibal"] && destColor
!= initColor
) {
1753 const lastIdx
= mv
.vanish
.length
- 1;
1754 let trPiece
= mv
.vanish
[lastIdx
].p
;
1755 if (this.isKing(this.getPiece(sx
, sy
)))
1756 trPiece
= C
.CannibalKingCode
[trPiece
];
1757 if (mv
.appear
.length
>= 1)
1758 mv
.appear
[0].p
= trPiece
;
1759 else if (this.options
["rifle"]) {
1782 // En-passant square, if any
1783 getEpSquare(moveOrSquare
) {
1784 if (typeof moveOrSquare
=== "string") {
1785 const square
= moveOrSquare
;
1788 return C
.SquareToCoords(square
);
1790 // Argument is a move:
1791 const move = moveOrSquare
;
1792 const s
= move.start
,
1796 Math
.abs(s
.x
- e
.x
) == 2 &&
1797 // Next conditions for variants like Atomic or Rifle, Recycle...
1799 move.appear
.length
> 0 &&
1800 this.getPieceType(0, 0, move.appear
[0].p
) == "p"
1804 move.vanish
.length
> 0 &&
1805 this.getPieceType(0, 0, move.vanish
[0].p
) == "p"
1813 return undefined; //default
1816 // Special case of en-passant captures: treated separately
1817 getEnpassantCaptures([x
, y
]) {
1818 const color
= this.getColor(x
, y
);
1819 const shiftX
= (color
== 'w' ? -1 : 1);
1820 const oppCol
= C
.GetOppCol(color
);
1821 let enpassantMove
= null;
1824 this.epSquare
.x
== x
+ shiftX
&&
1825 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1826 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1828 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1829 this.board
[epx
][epy
] = oppCol
+ "p";
1830 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1831 this.board
[epx
][epy
] = "";
1832 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1833 enpassantMove
.vanish
[lastIdx
].x
= x
;
1835 return !!enpassantMove
? [enpassantMove
] : [];
1838 // "castleInCheck" arg to let some variants castle under check
1839 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1840 const c
= this.getColor(x
, y
);
1843 const oppCol
= C
.GetOppCol(c
);
1847 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1848 const castlingKing
= this.getPiece(x
, y
);
1849 castlingCheck: for (
1852 castleSide
++ //large, then small
1854 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1856 // If this code is reached, rook and king are on initial position
1858 // NOTE: in some variants this is not a rook
1859 const rookPos
= this.castleFlags
[c
][castleSide
];
1860 const castlingPiece
= this.getPiece(x
, rookPos
);
1862 this.board
[x
][rookPos
] == "" ||
1863 this.getColor(x
, rookPos
) != c
||
1864 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1866 // Rook is not here, or changed color (see Benedict)
1869 // Nothing on the path of the king ? (and no checks)
1870 const finDist
= finalSquares
[castleSide
][0] - y
;
1871 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1875 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1877 this.board
[x
][i
] != "" &&
1878 // NOTE: next check is enough, because of chessboard constraints
1879 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1882 continue castlingCheck
;
1885 } while (i
!= finalSquares
[castleSide
][0]);
1886 // Nothing on the path to the rook?
1887 step
= (castleSide
== 0 ? -1 : 1);
1888 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1889 if (this.board
[x
][i
] != "")
1890 continue castlingCheck
;
1893 // Nothing on final squares, except maybe king and castling rook?
1894 for (i
= 0; i
< 2; i
++) {
1896 finalSquares
[castleSide
][i
] != rookPos
&&
1897 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1899 finalSquares
[castleSide
][i
] != y
||
1900 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1903 continue castlingCheck
;
1907 // If this code is reached, castle is valid
1913 y: finalSquares
[castleSide
][0],
1919 y: finalSquares
[castleSide
][1],
1925 // King might be initially disguised (Titan...)
1926 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1927 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1930 Math
.abs(y
- rookPos
) <= 2
1931 ? {x: x
, y: rookPos
}
1932 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1940 ////////////////////
1943 // Is (king at) given position under check by "oppCol" ?
1944 underCheck([x
, y
], oppCol
) {
1945 if (this.options
["taking"] || this.options
["dark"])
1948 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1952 // Stop at first king found (TODO: multi-kings)
1953 searchKingPos(color
) {
1954 for (let i
=0; i
< this.size
.x
; i
++) {
1955 for (let j
=0; j
< this.size
.y
; j
++) {
1956 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1960 return [-1, -1]; //king not found
1963 // Some variants (e.g. Refusal) may need to check opponent moves too
1964 filterValid(moves
, color
) {
1965 if (moves
.length
== 0)
1969 const oppCol
= C
.GetOppCol(color
);
1970 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1971 // Forbid moves either giving check or exploding opponent's king:
1972 const oppKingPos
= this.searchKingPos(oppCol
);
1973 moves
= moves
.filter(m
=> {
1975 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1976 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1979 this.playOnBoard(m
);
1980 const res
= !this.underCheck(oppKingPos
, color
);
1981 this.undoOnBoard(m
);
1985 if (this.options
["taking"] || this.options
["dark"])
1987 const kingPos
= this.searchKingPos(color
);
1988 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1989 return moves
.filter(m
=> {
1990 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1991 if (!filtered
[key
]) {
1992 this.playOnBoard(m
);
1993 let square
= kingPos
,
1994 res
= true; //a priori valid
1995 if (m
.vanish
.some(v
=> {
1996 return this.isKing(v
.p
) && v
.c
== color
;
1998 // Search king in appear array:
2000 m
.appear
.findIndex(a
=> {
2001 return this.isKing(a
.p
) && a
.c
== color
;
2003 if (newKingIdx
>= 0)
2004 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
2008 res
&&= !this.underCheck(square
, oppCol
);
2009 this.undoOnBoard(m
);
2010 filtered
[key
] = res
;
2013 return filtered
[key
];
2020 // Aggregate flags into one object
2022 return this.castleFlags
;
2025 // Reverse operation
2026 disaggregateFlags(flags
) {
2027 this.castleFlags
= flags
;
2030 // Apply a move on board
2032 for (let psq
of move.vanish
)
2033 this.board
[psq
.x
][psq
.y
] = "";
2034 for (let psq
of move.appear
)
2035 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2037 // Un-apply the played move
2039 for (let psq
of move.appear
)
2040 this.board
[psq
.x
][psq
.y
] = "";
2041 for (let psq
of move.vanish
)
2042 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2045 updateCastleFlags(move) {
2046 // Update castling flags if start or arrive from/at rook/king locations
2047 move.appear
.concat(move.vanish
).forEach(psq
=> {
2049 this.board
[psq
.x
][psq
.y
] != "" &&
2050 this.getPieceType(psq
.x
, psq
.y
) == "k"
2052 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2054 // NOTE: not "else if" because king can capture enemy rook...
2058 else if (psq
.x
== this.size
.x
- 1)
2061 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2063 this.castleFlags
[c
][fidx
] = this.size
.y
;
2071 // If flags already off, no need to re-check:
2072 Object
.keys(this.castleFlags
).some(c
=> {
2073 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
2075 this.updateCastleFlags(move);
2077 if (this.options
["crazyhouse"]) {
2078 move.vanish
.forEach(v
=> {
2079 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2080 if (this.ispawn
[square
])
2081 delete this.ispawn
[square
];
2083 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2084 // Assumption: something is moving
2085 const initSquare
= C
.CoordsToSquare(move.start
);
2086 const destSquare
= C
.CoordsToSquare(move.end
);
2088 this.ispawn
[initSquare
] ||
2089 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2091 this.ispawn
[destSquare
] = true;
2094 this.ispawn
[destSquare
] &&
2095 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2097 move.vanish
[1].p
= "p";
2098 delete this.ispawn
[destSquare
];
2102 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2105 // Warning; atomic pawn removal isn't a capture
2106 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2108 const color
= this.turn
;
2109 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2110 // Something appears = dropped on board (some exceptions, Chakart...)
2111 if (move.appear
[i
].c
== color
) {
2112 const piece
= move.appear
[i
].p
;
2113 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2116 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2117 // Something vanish: add to reserve except if recycle & opponent
2119 this.options
["crazyhouse"] ||
2120 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2122 const piece
= move.vanish
[i
].p
;
2123 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2131 if (this.hasEnpassant
)
2132 this.epSquare
= this.getEpSquare(move);
2133 this.playOnBoard(move);
2134 this.postPlay(move);
2138 const color
= this.turn
;
2139 const oppCol
= C
.GetOppCol(color
);
2140 if (this.options
["dark"])
2141 this.updateEnlightened();
2142 if (this.options
["teleport"]) {
2144 this.subTurnTeleport
== 1 &&
2145 move.vanish
.length
> move.appear
.length
&&
2146 move.vanish
[move.vanish
.length
- 1].c
== color
2148 const v
= move.vanish
[move.vanish
.length
- 1];
2149 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2150 this.subTurnTeleport
= 2;
2153 this.subTurnTeleport
= 1;
2154 this.captured
= null;
2158 this.options
["doublemove"] &&
2159 this.movesCount
>= 1 &&
2162 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2164 const oppKingPos
= this.searchKingPos(oppCol
);
2166 oppKingPos
[0] >= 0 &&
2168 this.options
["taking"] ||
2169 !this.underCheck(oppKingPos
, color
)
2176 if (this.isLastMove(move)) {
2185 (this.options
["balance"] && ![1, 3].includes(this.movesCount
)) ||
2190 // "Stop at the first move found"
2191 atLeastOneMove(color
) {
2192 color
= color
|| this.turn
;
2193 for (let i
= 0; i
< this.size
.x
; i
++) {
2194 for (let j
= 0; j
< this.size
.y
; j
++) {
2195 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2196 // NOTE: in fact searching for all potential moves from i,j.
2197 // I don't believe this is an issue, for now at least.
2198 const moves
= this.getPotentialMovesFrom([i
, j
]);
2199 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2204 if (this.hasReserve
&& this.reserve
[color
]) {
2205 for (let p
of Object
.keys(this.reserve
[color
])) {
2206 const moves
= this.getDropMovesFrom([color
, p
]);
2207 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2214 // What is the score ? (Interesting if game is over)
2215 getCurrentScore(move) {
2216 const color
= this.turn
;
2217 const oppCol
= C
.GetOppCol(color
);
2218 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2219 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2221 if (kingPos
[0][0] < 0)
2222 return (color
== "w" ? "0-1" : "1-0");
2223 if (kingPos
[1][0] < 0)
2224 return (color
== "w" ? "1-0" : "0-1");
2225 if (this.atLeastOneMove())
2227 // No valid move: stalemate or checkmate?
2228 if (!this.underCheck(kingPos
[0], color
))
2231 return (color
== "w" ? "0-1" : "1-0");
2234 playVisual(move, r
) {
2235 move.vanish
.forEach(v
=> {
2236 this.g_pieces
[v
.x
][v
.y
].remove();
2237 this.g_pieces
[v
.x
][v
.y
] = null;
2240 document
.getElementById(this.containerId
).querySelector(".chessboard");
2242 r
= chessboard
.getBoundingClientRect();
2243 const pieceWidth
= this.getPieceWidth(r
.width
);
2244 move.appear
.forEach(a
=> {
2245 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2246 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2247 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2248 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2249 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2250 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2251 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2252 // Translate coordinates to use chessboard as reference:
2253 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2254 `translate(${ip - r.x}px,${jp - r.y}px)`;
2255 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2256 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2257 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2259 if (this.options
["dark"])
2260 this.graphUpdateEnlightened();
2263 playPlusVisual(move, r
) {
2264 if (this.hasMoveStack
)
2265 this.buildMoveStack(move);
2268 this.playVisual(move, r
);
2269 this.afterPlay(move, this.turn
, {send: true, res: true}); //user method
2273 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2274 buildMoveStack(move) {
2275 this.moveStack
.push(move);
2276 this.computeNextMove(move);
2278 const newTurn
= this.turn
;
2279 if (this.moveStack
.length
== 1) {
2280 this.playVisual(move);
2283 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2287 this.buildMoveStack(move.next
);
2289 // Send, animate + play until here
2290 if (this.moveStack
.length
== 1) {
2291 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2295 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2296 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2297 this.playReceivedMove(this.moveStack
.slice(1), () => {
2298 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2305 // Implemented in variants using (automatic) moveStack
2306 computeNextMove(move) {}
2309 // Works for all rectangular boards:
2310 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
2314 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2317 animateMoving(start
, end
, drag
, segments
, cb
) {
2318 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2319 // NOTE: cloning often not required, but light enough, and simpler
2320 let movingPiece
= initPiece
.cloneNode();
2321 initPiece
.style
.opacity
= "0";
2323 document
.getElementById(this.containerId
)
2324 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2325 if (typeof start
.x
== "string") {
2326 // Need to bound width/height (was 100% for reserve pieces)
2327 const pieceWidth
= this.getPieceWidth(r
.width
);
2328 movingPiece
.style
.width
= pieceWidth
+ "px";
2329 movingPiece
.style
.height
= pieceWidth
+ "px";
2331 const maxDist
= this.getMaxDistance(r
);
2332 const apparentColor
= this.getColor(start
.x
, start
.y
);
2333 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2335 const startCode
= this.getPiece(start
.x
, start
.y
);
2336 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2337 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2338 if (apparentColor
!= drag
.c
) {
2339 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2340 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2343 container
.appendChild(movingPiece
);
2344 const animateSegment
= (index
, cb
) => {
2345 // NOTE: move.drag could be generalized per-segment (usage?)
2346 const [i1
, j1
] = segments
[index
][0];
2347 const [i2
, j2
] = segments
[index
][1];
2348 const dep
= this.getPixelPosition(i1
, j1
, r
);
2349 const arr
= this.getPixelPosition(i2
, j2
, r
);
2350 movingPiece
.style
.transitionDuration
= "0s";
2351 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2353 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2354 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2355 // TODO: unclear why we need this new delay below:
2357 movingPiece
.style
.transitionDuration
= duration
+ "s";
2358 // movingPiece is child of container: no need to adjust coordinates
2359 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2360 setTimeout(cb
, duration
* 1000);
2364 const animateSegmentCallback
= () => {
2365 if (index
< segments
.length
)
2366 animateSegment(index
++, animateSegmentCallback
);
2368 movingPiece
.remove();
2369 initPiece
.style
.opacity
= "1";
2373 animateSegmentCallback();
2376 // Input array of objects with at least fields x,y (e.g. PiPo)
2377 animateFading(arr
, cb
) {
2378 const animLength
= 350; //TODO: 350ms? More? Less?
2380 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2381 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2382 fadingPiece
.style
.opacity
= "0";
2384 setTimeout(cb
, animLength
);
2387 animate(move, callback
) {
2388 if (this.noAnimate
|| move.noAnimate
) {
2392 let segments
= move.segments
;
2394 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2395 let targetObj
= new TargetObj(callback
);
2396 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2398 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2399 () => targetObj
.increment());
2401 if (move.vanish
.length
> move.appear
.length
) {
2402 const arr
= move.vanish
.slice(move.appear
.length
)
2403 .filter(v
=> v
.x
!= move.end
.x
|| v
.y
!= move.end
.y
);
2404 if (arr
.length
> 0) {
2406 this.animateFading(arr
, () => targetObj
.increment());
2410 this.customAnimate(move, segments
, () => targetObj
.increment());
2411 if (targetObj
.target
== 0)
2415 // Potential other animations (e.g. for Suction variant)
2416 customAnimate(move, segments
, cb
) {
2417 return 0; //nb of targets
2420 playReceivedMove(moves
, callback
) {
2421 const launchAnimation
= () => {
2422 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2423 const animateRec
= i
=> {
2424 this.animate(moves
[i
], () => {
2425 this.play(moves
[i
]);
2426 this.playVisual(moves
[i
], r
);
2427 if (i
< moves
.length
- 1)
2428 setTimeout(() => animateRec(i
+1), 300);
2435 // Delay if user wasn't focused:
2436 const checkDisplayThenAnimate
= (delay
) => {
2437 if (container
.style
.display
== "none") {
2438 alert("New move! Let's go back to game...");
2439 document
.getElementById("gameInfos").style
.display
= "none";
2440 container
.style
.display
= "block";
2441 setTimeout(launchAnimation
, 700);
2444 setTimeout(launchAnimation
, delay
|| 0);
2446 let container
= document
.getElementById(this.containerId
);
2447 if (document
.hidden
) {
2448 document
.onvisibilitychange
= () => {
2449 document
.onvisibilitychange
= undefined;
2450 checkDisplayThenAnimate(700);
2454 checkDisplayThenAnimate();