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"];
114 // Some variants use only click information
119 // Some variants use click infos:
121 if (typeof coords
.x
!= "number")
122 return null; //click on reserves
124 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
125 this.board
[coords
.x
][coords
.y
] == ""
128 start: {x: this.captured
.x
, y: this.captured
.y
},
139 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
148 // 3a --> {x:3, y:10}
149 static SquareToCoords(sq
) {
150 return ArrayFun
.toObject(["x", "y"],
151 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
154 // {x:11, y:12} --> bc
155 static CoordsToSquare(cd
) {
156 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
160 if (typeof cd
.x
== "number") {
162 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
166 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
169 idToCoords(targetId
) {
171 return null; //outside page, maybe...
172 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
174 idParts
.length
< 2 ||
175 idParts
[0] != this.containerId
||
176 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
180 const squares
= idParts
[1].split('-');
181 if (squares
[0] == "sq")
182 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
183 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
184 return {x: squares
[1], y: squares
[2]};
190 // Turn "wb" into "B" (for FEN)
192 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
195 // Turn "p" into "bp" (for board)
197 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
200 // Setup the initial random-or-not (asymmetric-or-not) position
201 genRandInitFen(seed
) {
202 let fen
, flags
= "0707";
203 if (!this.options
.randomness
)
205 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
209 Random
.setSeed(seed
);
210 let pieces
= {w: new Array(8), b: new Array(8)};
212 // Shuffle pieces on first (and last rank if randomness == 2)
213 for (let c
of ["w", "b"]) {
214 if (c
== 'b' && this.options
.randomness
== 1) {
215 pieces
['b'] = pieces
['w'];
220 let positions
= ArrayFun
.range(8);
222 // Get random squares for bishops
223 let randIndex
= 2 * Random
.randInt(4);
224 const bishop1Pos
= positions
[randIndex
];
225 // The second bishop must be on a square of different color
226 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
227 const bishop2Pos
= positions
[randIndex_tmp
];
228 // Remove chosen squares
229 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
230 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
232 // Get random squares for knights
233 randIndex
= Random
.randInt(6);
234 const knight1Pos
= positions
[randIndex
];
235 positions
.splice(randIndex
, 1);
236 randIndex
= Random
.randInt(5);
237 const knight2Pos
= positions
[randIndex
];
238 positions
.splice(randIndex
, 1);
240 // Get random square for queen
241 randIndex
= Random
.randInt(4);
242 const queenPos
= positions
[randIndex
];
243 positions
.splice(randIndex
, 1);
245 // Rooks and king positions are now fixed,
246 // because of the ordering rook-king-rook
247 const rook1Pos
= positions
[0];
248 const kingPos
= positions
[1];
249 const rook2Pos
= positions
[2];
251 // Finally put the shuffled pieces in the board array
252 pieces
[c
][rook1Pos
] = "r";
253 pieces
[c
][knight1Pos
] = "n";
254 pieces
[c
][bishop1Pos
] = "b";
255 pieces
[c
][queenPos
] = "q";
256 pieces
[c
][kingPos
] = "k";
257 pieces
[c
][bishop2Pos
] = "b";
258 pieces
[c
][knight2Pos
] = "n";
259 pieces
[c
][rook2Pos
] = "r";
260 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
263 pieces
["b"].join("") +
264 "/pppppppp/8/8/8/8/PPPPPPPP/" +
265 pieces
["w"].join("").toUpperCase() +
269 // Add turn + flags + enpassant (+ reserve)
272 parts
.push(`"flags":"${flags}"`);
273 if (this.hasEnpassant
)
274 parts
.push('"enpassant":"-"');
275 if (this.hasReserveFen
)
276 parts
.push('"reserve":"000000000000"');
277 if (this.options
["crazyhouse"])
278 parts
.push('"ispawn":"-"');
279 if (parts
.length
>= 1)
280 fen
+= " {" + parts
.join(",") + "}";
284 // "Parse" FEN: just return untransformed string data
286 const fenParts
= fen
.split(" ");
288 position: fenParts
[0],
290 movesCount: fenParts
[2]
292 if (fenParts
.length
> 3)
293 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
297 // Return current fen (game state)
300 this.getPosition() + " " +
301 this.getTurnFen() + " " +
306 parts
.push(`"flags":"${this.getFlagsFen()}"`);
307 if (this.hasEnpassant
)
308 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
309 if (this.hasReserveFen
)
310 parts
.push(`"reserve":"${this.getReserveFen()}"`);
311 if (this.options
["crazyhouse"])
312 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
313 if (parts
.length
>= 1)
314 fen
+= " {" + parts
.join(",") + "}";
318 static FenEmptySquares(count
) {
319 // if more than 9 consecutive free spaces, break the integer,
320 // otherwise FEN parsing will fail.
323 // Most boards of size < 18:
325 return "9" + (count
- 9);
327 return "99" + (count
- 18);
330 // Position part of the FEN string
333 for (let i
= 0; i
< this.size
.y
; i
++) {
335 for (let j
= 0; j
< this.size
.x
; j
++) {
336 if (this.board
[i
][j
] == "")
339 if (emptyCount
> 0) {
340 // Add empty squares in-between
341 position
+= C
.FenEmptySquares(emptyCount
);
344 position
+= this.board2fen(this.board
[i
][j
]);
349 position
+= C
.FenEmptySquares(emptyCount
);
350 if (i
< this.size
.y
- 1)
351 position
+= "/"; //separate rows
360 // Flags part of the FEN string
362 return ["w", "b"].map(c
=> {
363 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
367 // Enpassant part of the FEN string
370 return "-"; //no en-passant
371 return C
.CoordsToSquare(this.epSquare
);
376 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
381 const squares
= Object
.keys(this.ispawn
);
382 if (squares
.length
== 0)
384 return squares
.join(",");
387 // Set flags from fen (castle: white a,h then black a,h)
390 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
391 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
399 this.options
= o
.options
;
400 // Fill missing options (always the case if random challenge)
401 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
402 if (this.options
[opt
.variable
] === undefined)
403 this.options
[opt
.variable
] = opt
.defaut
;
406 // This object will be used only for initial FEN generation
408 this.playerColor
= o
.color
;
409 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
411 // Fen string fully describes the game state
413 o
.fen
= this.genRandInitFen(o
.seed
);
414 this.re_initFromFen(o
.fen
);
416 // Graphical (can use variables defined above)
417 this.containerId
= o
.element
;
418 this.isDiagram
= o
.diagram
;
419 this.graphicalInit();
422 re_initFromFen(fen
, oldBoard
) {
423 const fenParsed
= this.parseFen(fen
);
424 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
425 this.turn
= fenParsed
.turn
;
426 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
427 this.setOtherVariables(fenParsed
);
430 // Turn position fen into double array ["wb","wp","bk",...]
432 const rows
= position
.split("/");
433 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
434 for (let i
= 0; i
< rows
.length
; i
++) {
436 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
437 const character
= rows
[i
][indexInRow
];
438 const num
= parseInt(character
, 10);
439 // If num is a number, just shift j:
442 // Else: something at position i,j
444 board
[i
][j
++] = this.fen2board(character
);
450 // Some additional variables from FEN (variant dependant)
451 setOtherVariables(fenParsed
) {
452 // Set flags and enpassant:
454 this.setFlags(fenParsed
.flags
);
455 if (this.hasEnpassant
)
456 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
457 if (this.hasReserve
&& !this.isDiagram
)
458 this.initReserves(fenParsed
.reserve
);
459 if (this.options
["crazyhouse"])
460 this.initIspawn(fenParsed
.ispawn
);
461 if (this.options
["teleport"]) {
462 this.subTurnTeleport
= 1;
463 this.captured
= null;
465 if (this.options
["dark"]) {
466 // Setup enlightened: squares reachable by player side
467 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
468 this.updateEnlightened();
470 this.subTurn
= 1; //may be unused
471 if (!this.moveStack
) //avoid resetting (unwanted)
475 // ordering as in pieces() p,r,n,b,q,k
476 initReserves(reserveStr
) {
477 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
478 this.reserve
= { w: {}, b: {} };
479 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
480 const L
= pieceName
.length
;
481 for (let i
of ArrayFun
.range(2 * L
)) {
483 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
485 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
489 initIspawn(ispawnStr
) {
490 if (ispawnStr
!= "-")
491 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
499 getPieceWidth(rwidth
) {
500 return (rwidth
/ this.size
.y
);
503 getReserveSquareSize(rwidth
, nbR
) {
504 const sqSize
= this.getPieceWidth(rwidth
);
505 return Math
.min(sqSize
, rwidth
/ nbR
);
508 getReserveNumId(color
, piece
) {
509 return `${this.containerId}|rnum-${color}${piece}`;
512 getNbReservePieces(color
) {
514 Object
.values(this.reserve
[color
]).reduce(
515 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
519 getRankInReserve(c
, p
) {
520 const pieces
= Object
.keys(this.pieces());
521 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
522 let toTest
= pieces
.slice(0, lastIndex
);
523 return toTest
.reduce(
524 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
527 static AddClass_es(piece
, class_es
) {
528 if (!Array
.isArray(class_es
))
529 class_es
= [class_es
];
530 class_es
.forEach(cl
=> {
531 piece
.classList
.add(cl
);
535 static RemoveClass_es(piece
, class_es
) {
536 if (!Array
.isArray(class_es
))
537 class_es
= [class_es
];
538 class_es
.forEach(cl
=> {
539 piece
.classList
.remove(cl
);
543 // Generally light square bottom-right
544 getSquareColorClass(x
, y
) {
545 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
549 // Works for all rectangular boards:
550 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
554 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
561 const g_init
= () => {
562 this.re_drawBoardElements();
563 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
564 this.initMouseEvents();
566 let container
= document
.getElementById(this.containerId
);
567 this.windowResizeObs
= new ResizeObserver(g_init
);
568 this.windowResizeObs
.observe(container
);
571 re_drawBoardElements() {
572 const board
= this.getSvgChessboard();
573 const oppCol
= C
.GetOppCol(this.playerColor
);
574 const container
= document
.getElementById(this.containerId
);
575 const rc
= container
.getBoundingClientRect();
576 let chessboard
= container
.querySelector(".chessboard");
577 chessboard
.innerHTML
= "";
578 chessboard
.insertAdjacentHTML('beforeend', board
);
579 // Compare window ratio width / height to aspectRatio:
580 const windowRatio
= rc
.width
/ rc
.height
;
581 let cbWidth
, cbHeight
;
582 const vRatio
= this.size
.ratio
|| 1;
583 if (windowRatio
<= vRatio
) {
584 // Limiting dimension is width:
585 cbWidth
= Math
.min(rc
.width
, 767);
586 cbHeight
= cbWidth
/ vRatio
;
589 // Limiting dimension is height:
590 cbHeight
= Math
.min(rc
.height
, 767);
591 cbWidth
= cbHeight
* vRatio
;
593 if (this.hasReserve
&& !this.isDiagram
) {
594 const sqSize
= cbWidth
/ this.size
.y
;
595 // NOTE: allocate space for reserves (up/down) even if they are empty
596 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
597 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
598 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
599 cbWidth
= cbHeight
* vRatio
;
602 chessboard
.style
.width
= cbWidth
+ "px";
603 chessboard
.style
.height
= cbHeight
+ "px";
604 // Center chessboard:
605 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
606 spaceTop
= (rc
.height
- cbHeight
) / 2;
607 chessboard
.style
.left
= spaceLeft
+ "px";
608 chessboard
.style
.top
= spaceTop
+ "px";
609 // Give sizes instead of recomputing them,
610 // because chessboard might not be drawn yet.
619 // Get SVG board (background, no pieces)
621 const flipped
= (this.playerColor
== 'b');
624 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
625 class="chessboard_SVG">`;
626 for (let i
=0; i
< this.size
.x
; i
++) {
627 for (let j
=0; j
< this.size
.y
; j
++) {
628 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
629 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
630 let classes
= this.getSquareColorClass(ii
, jj
);
631 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
632 classes
+= " in-shadow";
633 // NOTE: x / y reversed because coordinates system is reversed.
637 id="${this.coordsToId({x: ii, y: jj})}"
650 // TODO: d_pieces : only markers (for diagrams) / also in rescale()
652 // Refreshing: delete old pieces first
653 for (let i
=0; i
<this.size
.x
; i
++) {
654 for (let j
=0; j
<this.size
.y
; j
++) {
655 if (this.g_pieces
[i
][j
]) {
656 this.g_pieces
[i
][j
].remove();
657 this.g_pieces
[i
][j
] = null;
663 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
665 document
.getElementById(this.containerId
).querySelector(".chessboard");
667 r
= chessboard
.getBoundingClientRect();
668 const pieceWidth
= this.getPieceWidth(r
.width
);
669 for (let i
=0; i
< this.size
.x
; i
++) {
670 for (let j
=0; j
< this.size
.y
; j
++) {
671 if (this.board
[i
][j
] != "") {
672 const color
= this.getColor(i
, j
);
673 const piece
= this.getPiece(i
, j
);
674 this.g_pieces
[i
][j
] = document
.createElement("piece");
675 C
.AddClass_es(this.g_pieces
[i
][j
],
676 this.pieces(color
, i
, j
)[piece
]["class"]);
677 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
678 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
679 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
680 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
681 // Translate coordinates to use chessboard as reference:
682 this.g_pieces
[i
][j
].style
.transform
=
683 `translate(${ip - r.x}px,${jp - r.y}px)`;
684 if (this.enlightened
&& !this.enlightened
[i
][j
])
685 this.g_pieces
[i
][j
].classList
.add("hidden");
686 chessboard
.appendChild(this.g_pieces
[i
][j
]);
690 if (this.hasReserve
&& !this.isDiagram
)
691 this.re_drawReserve(['w', 'b'], r
);
694 // NOTE: assume this.reserve != null
695 re_drawReserve(colors
, r
) {
697 // Remove (old) reserve pieces
698 for (let c
of colors
) {
699 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
700 this.r_pieces
[c
][p
].remove();
701 delete this.r_pieces
[c
][p
];
702 const numId
= this.getReserveNumId(c
, p
);
703 document
.getElementById(numId
).remove();
708 this.r_pieces
= { w: {}, b: {} };
709 let container
= document
.getElementById(this.containerId
);
711 r
= container
.querySelector(".chessboard").getBoundingClientRect();
712 for (let c
of colors
) {
713 let reservesDiv
= document
.getElementById("reserves_" + c
);
715 reservesDiv
.remove();
716 if (!this.reserve
[c
])
718 const nbR
= this.getNbReservePieces(c
);
721 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
723 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
724 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
725 let rcontainer
= document
.createElement("div");
726 rcontainer
.id
= "reserves_" + c
;
727 rcontainer
.classList
.add("reserves");
728 rcontainer
.style
.left
= i0
+ "px";
729 rcontainer
.style
.top
= j0
+ "px";
730 // NOTE: +1 fix display bug on Firefox at least
731 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
732 rcontainer
.style
.height
= sqResSize
+ "px";
733 container
.appendChild(rcontainer
);
734 for (let p
of Object
.keys(this.reserve
[c
])) {
735 if (this.reserve
[c
][p
] == 0)
737 let r_cell
= document
.createElement("div");
738 r_cell
.id
= this.coordsToId({x: c
, y: p
});
739 r_cell
.classList
.add("reserve-cell");
740 r_cell
.style
.width
= sqResSize
+ "px";
741 r_cell
.style
.height
= sqResSize
+ "px";
742 rcontainer
.appendChild(r_cell
);
743 let piece
= document
.createElement("piece");
744 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
745 piece
.classList
.add(C
.GetColorClass(c
));
746 piece
.style
.width
= "100%";
747 piece
.style
.height
= "100%";
748 this.r_pieces
[c
][p
] = piece
;
749 r_cell
.appendChild(piece
);
750 let number
= document
.createElement("div");
751 number
.textContent
= this.reserve
[c
][p
];
752 number
.classList
.add("reserve-num");
753 number
.id
= this.getReserveNumId(c
, p
);
754 const fontSize
= "1.3em";
755 number
.style
.fontSize
= fontSize
;
756 number
.style
.fontSize
= fontSize
;
757 r_cell
.appendChild(number
);
763 updateReserve(color
, piece
, count
) {
764 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
765 piece
= "k"; //capturing cannibal king: back to king form
766 const oldCount
= this.reserve
[color
][piece
];
767 this.reserve
[color
][piece
] = count
;
768 // Redrawing is much easier if count==0
769 if ([oldCount
, count
].includes(0))
770 this.re_drawReserve([color
]);
772 const numId
= this.getReserveNumId(color
, piece
);
773 document
.getElementById(numId
).textContent
= count
;
777 // Resize board: no need to destroy/recreate pieces
779 const container
= document
.getElementById(this.containerId
);
780 let chessboard
= container
.querySelector(".chessboard");
781 const rc
= container
.getBoundingClientRect(),
782 r
= chessboard
.getBoundingClientRect();
783 const multFact
= (mode
== "up" ? 1.05 : 0.95);
784 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
786 const vRatio
= this.size
.ratio
|| 1;
787 if (newWidth
> rc
.width
) {
789 newHeight
= newWidth
/ vRatio
;
791 if (newHeight
> rc
.height
) {
792 newHeight
= rc
.height
;
793 newWidth
= newHeight
* vRatio
;
795 chessboard
.style
.width
= newWidth
+ "px";
796 chessboard
.style
.height
= newHeight
+ "px";
797 const newX
= (rc
.width
- newWidth
) / 2;
798 chessboard
.style
.left
= newX
+ "px";
799 const newY
= (rc
.height
- newHeight
) / 2;
800 chessboard
.style
.top
= newY
+ "px";
801 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
802 const pieceWidth
= this.getPieceWidth(newWidth
);
803 // NOTE: next "if" for variants which use squares filling
804 // instead of "physical", moving pieces
806 for (let i
=0; i
< this.size
.x
; i
++) {
807 for (let j
=0; j
< this.size
.y
; j
++) {
808 if (this.g_pieces
[i
][j
]) {
809 // NOTE: could also use CSS transform "scale"
810 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
811 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
812 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
813 // Translate coordinates to use chessboard as reference:
814 this.g_pieces
[i
][j
].style
.transform
=
815 `translate(${ip - newX}px,${jp - newY}px)`;
820 if (this.hasReserve
&& !this.isDiagram
)
821 this.rescaleReserve(newR
);
825 for (let c
of ['w','b']) {
826 if (!this.reserve
[c
])
828 const nbR
= this.getNbReservePieces(c
);
831 // Resize container first
832 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
833 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
834 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
835 let rcontainer
= document
.getElementById("reserves_" + c
);
836 rcontainer
.style
.left
= i0
+ "px";
837 rcontainer
.style
.top
= j0
+ "px";
838 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
839 rcontainer
.style
.height
= sqResSize
+ "px";
840 // And then reserve cells:
841 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
842 Object
.keys(this.reserve
[c
]).forEach(p
=> {
843 if (this.reserve
[c
][p
] == 0)
845 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
846 r_cell
.style
.width
= sqResSize
+ "px";
847 r_cell
.style
.height
= sqResSize
+ "px";
852 // Return the absolute pixel coordinates given current position.
853 // Our coordinate system differs from CSS one (x <--> y).
854 // We return here the CSS coordinates (more useful).
855 getPixelPosition(i
, j
, r
) {
857 return [0, 0]; //piece vanishes
859 if (typeof i
== "string") {
860 // Reserves: need to know the rank of piece
861 const nbR
= this.getNbReservePieces(i
);
862 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
863 x
= this.getRankInReserve(i
, j
) * rsqSize
;
864 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
867 const sqSize
= r
.width
/ this.size
.y
;
868 const flipped
= (this.playerColor
== 'b');
869 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
870 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
872 return [r
.x
+ x
, r
.y
+ y
];
876 let container
= document
.getElementById(this.containerId
);
877 let chessboard
= container
.querySelector(".chessboard");
879 const getOffset
= e
=> {
882 return {x: e
.clientX
, y: e
.clientY
};
883 let touchLocation
= null;
884 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
885 // Touch screen, dragstart
886 touchLocation
= e
.targetTouches
[0];
887 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
888 // Touch screen, dragend
889 touchLocation
= e
.changedTouches
[0];
891 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
892 return {x: 0, y: 0}; //shouldn't reach here =)
895 const centerOnCursor
= (piece
, e
) => {
896 const centerShift
= this.getPieceWidth(r
.width
) / 2;
897 const offset
= getOffset(e
);
898 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
899 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
904 startPiece
, curPiece
= null,
906 const mousedown
= (e
) => {
907 // Disable zoom on smartphones:
908 if (e
.touches
&& e
.touches
.length
> 1)
910 r
= chessboard
.getBoundingClientRect();
911 pieceWidth
= this.getPieceWidth(r
.width
);
912 const cd
= this.idToCoords(e
.target
.id
);
914 const move = this.doClick(cd
);
916 this.buildMoveStack(move, r
);
917 else if (!this.clickOnly
) {
918 const [x
, y
] = Object
.values(cd
);
919 if (typeof x
!= "number")
920 startPiece
= this.r_pieces
[x
][y
];
922 startPiece
= this.g_pieces
[x
][y
];
923 if (startPiece
&& this.canIplay(x
, y
)) {
926 curPiece
= startPiece
.cloneNode();
927 curPiece
.style
.transform
= "none";
928 curPiece
.style
.zIndex
= 5;
929 curPiece
.style
.width
= pieceWidth
+ "px";
930 curPiece
.style
.height
= pieceWidth
+ "px";
931 centerOnCursor(curPiece
, e
);
932 container
.appendChild(curPiece
);
933 startPiece
.style
.opacity
= "0.4";
934 chessboard
.style
.cursor
= "none";
940 const mousemove
= (e
) => {
943 centerOnCursor(curPiece
, e
);
945 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
946 // Attempt to prevent horizontal swipe...
950 const mouseup
= (e
) => {
953 const [x
, y
] = [start
.x
, start
.y
];
956 chessboard
.style
.cursor
= "pointer";
957 startPiece
.style
.opacity
= "1";
958 const offset
= getOffset(e
);
959 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
961 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
963 // NOTE: clearly suboptimal, but much easier, and not a big deal.
964 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
965 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
966 const moves
= this.filterValid(potentialMoves
);
967 if (moves
.length
>= 2)
968 this.showChoices(moves
, r
);
969 else if (moves
.length
== 1)
970 this.buildMoveStack(moves
[0], r
);
975 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
977 if ('onmousedown' in window
) {
978 this.mouseListeners
= [
979 {type: "mousedown", listener: mousedown
},
980 {type: "mousemove", listener: mousemove
},
981 {type: "mouseup", listener: mouseup
},
982 {type: "wheel", listener: resize
}
984 this.mouseListeners
.forEach(ml
=> {
985 document
.addEventListener(ml
.type
, ml
.listener
);
988 if ('ontouchstart' in window
) {
989 this.touchListeners
= [
990 {type: "touchstart", listener: mousedown
},
991 {type: "touchmove", listener: mousemove
},
992 {type: "touchend", listener: mouseup
}
994 this.touchListeners
.forEach(tl
=> {
995 // https://stackoverflow.com/a/42509310/12660887
996 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
999 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1003 let container
= document
.getElementById(this.containerId
);
1004 this.windowResizeObs
.unobserve(container
);
1006 return; //no listeners in this case
1007 if ('onmousedown' in window
) {
1008 this.mouseListeners
.forEach(ml
=> {
1009 document
.removeEventListener(ml
.type
, ml
.listener
);
1012 if ('ontouchstart' in window
) {
1013 this.touchListeners
.forEach(tl
=> {
1014 // https://stackoverflow.com/a/42509310/12660887
1015 document
.removeEventListener(tl
.type
, tl
.listener
);
1020 showChoices(moves
, r
) {
1021 let container
= document
.getElementById(this.containerId
);
1022 let chessboard
= container
.querySelector(".chessboard");
1023 let choices
= document
.createElement("div");
1024 choices
.id
= "choices";
1026 r
= chessboard
.getBoundingClientRect();
1027 choices
.style
.width
= r
.width
+ "px";
1028 choices
.style
.height
= r
.height
+ "px";
1029 choices
.style
.left
= r
.x
+ "px";
1030 choices
.style
.top
= r
.y
+ "px";
1031 chessboard
.style
.opacity
= "0.5";
1032 container
.appendChild(choices
);
1033 const squareWidth
= r
.width
/ this.size
.y
;
1034 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1035 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1036 const color
= moves
[0].appear
[0].c
;
1037 const callback
= (m
) => {
1038 chessboard
.style
.opacity
= "1";
1039 container
.removeChild(choices
);
1040 this.buildMoveStack(m
, r
);
1042 for (let i
=0; i
< moves
.length
; i
++) {
1043 let choice
= document
.createElement("div");
1044 choice
.classList
.add("choice");
1045 choice
.style
.width
= squareWidth
+ "px";
1046 choice
.style
.height
= squareWidth
+ "px";
1047 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1048 choice
.style
.top
= firstUpTop
+ "px";
1049 choice
.style
.backgroundColor
= "lightyellow";
1050 choice
.onclick
= () => callback(moves
[i
]);
1051 const piece
= document
.createElement("piece");
1052 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1053 C
.AddClass_es(piece
,
1054 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1055 piece
.classList
.add(C
.GetColorClass(color
));
1056 piece
.style
.width
= "100%";
1057 piece
.style
.height
= "100%";
1058 choice
.appendChild(piece
);
1059 choices
.appendChild(choice
);
1066 updateEnlightened() {
1067 this.oldEnlightened
= this.enlightened
;
1068 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1069 // Add pieces positions + all squares reachable by moves (includes Zen):
1070 for (let x
=0; x
<this.size
.x
; x
++) {
1071 for (let y
=0; y
<this.size
.y
; y
++) {
1072 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1074 this.enlightened
[x
][y
] = true;
1075 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1076 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1082 this.enlightEnpassant();
1085 // Include square of the en-passant capturing square:
1086 enlightEnpassant() {
1087 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1088 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1089 for (let step
of steps
) {
1090 const x
= this.epSquare
.x
- step
[0],
1091 y
= this.getY(this.epSquare
.y
- step
[1]);
1093 this.onBoard(x
, y
) &&
1094 this.getColor(x
, y
) == this.playerColor
&&
1095 this.getPieceType(x
, y
) == "p"
1097 this.enlightened
[x
][this.epSquare
.y
] = true;
1103 // Apply diff this.enlightened --> oldEnlightened on board
1104 graphUpdateEnlightened() {
1106 document
.getElementById(this.containerId
).querySelector(".chessboard");
1107 const r
= chessboard
.getBoundingClientRect();
1108 const pieceWidth
= this.getPieceWidth(r
.width
);
1109 for (let x
=0; x
<this.size
.x
; x
++) {
1110 for (let y
=0; y
<this.size
.y
; y
++) {
1111 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1112 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1113 elt
.classList
.add("in-shadow");
1114 if (this.g_pieces
[x
][y
])
1115 this.g_pieces
[x
][y
].classList
.add("hidden");
1117 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1118 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1119 elt
.classList
.remove("in-shadow");
1120 if (this.g_pieces
[x
][y
])
1121 this.g_pieces
[x
][y
].classList
.remove("hidden");
1134 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1138 // Color of thing on square (i,j). '' if square is empty
1140 if (typeof i
== "string")
1141 return i
; //reserves
1142 return this.board
[i
][j
].charAt(0);
1145 static GetColorClass(c
) {
1150 return "other-color"; //unidentified color
1153 // Piece on i,j. '' if square is empty
1155 if (typeof j
== "string")
1156 return j
; //reserves
1157 return this.board
[i
][j
].charAt(1);
1160 // Piece type on square (i,j)
1161 getPieceType(x
, y
, p
) {
1163 p
= this.getPiece(x
, y
);
1164 return this.pieces()[p
].moveas
|| p
;
1169 p
= this.getPiece(x
, y
);
1170 if (!this.options
["cannibal"])
1172 return !!C
.CannibalKings
[p
];
1175 // Get opponent color
1176 static GetOppCol(color
) {
1177 return (color
== "w" ? "b" : "w");
1180 // Is (x,y) on the chessboard?
1182 return (x
>= 0 && x
< this.size
.x
&&
1183 y
>= 0 && y
< this.size
.y
);
1186 // Am I allowed to move thing at square x,y ?
1188 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1191 ////////////////////////
1192 // PIECES SPECIFICATIONS
1194 pieces(color
, x
, y
) {
1195 const pawnShift
= (color
== "w" ? -1 : 1);
1196 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1197 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1203 steps: [[pawnShift
, 0]],
1204 range: (initRank
? 2 : 1)
1209 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1217 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1225 [1, 2], [1, -2], [-1, 2], [-1, -2],
1226 [2, 1], [-2, 1], [2, -1], [-2, -1]
1235 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1243 [0, 1], [0, -1], [1, 0], [-1, 0],
1244 [1, 1], [1, -1], [-1, 1], [-1, -1]
1254 [0, 1], [0, -1], [1, 0], [-1, 0],
1255 [1, 1], [1, -1], [-1, 1], [-1, -1]
1262 '!': {"class": "king-pawn", moveas: "p"},
1263 '#': {"class": "king-rook", moveas: "r"},
1264 '$': {"class": "king-knight", moveas: "n"},
1265 '%': {"class": "king-bishop", moveas: "b"},
1266 '*': {"class": "king-queen", moveas: "q"}
1270 // NOTE: using special symbols to not interfere with variants' pieces codes
1271 static get CannibalKings() {
1282 static get CannibalKingCode() {
1293 //////////////////////////
1294 // MOVES GENERATION UTILS
1296 // For Cylinder: get Y coordinate
1298 if (!this.options
["cylinder"])
1300 let res
= y
% this.size
.y
;
1306 getSegments(curSeg
, segStart
, segEnd
) {
1307 if (curSeg
.length
== 0)
1309 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1310 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1314 getStepSpec(color
, x
, y
, piece
) {
1315 return this.pieces(color
, x
, y
)[piece
|| this.getPieceType(x
, y
)];
1318 // Can thing on square1 capture thing on square2?
1319 canTake([x1
, y1
], [x2
, y2
]) {
1320 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1323 canStepOver(i
, j
, p
) {
1324 // In some variants, objects on boards don't stop movement (Chakart)
1325 return this.board
[i
][j
] == "";
1328 canDrop([c
, p
], [i
, j
]) {
1330 this.board
[i
][j
] == "" &&
1331 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1334 (c
== 'w' && i
< this.size
.x
- 1) ||
1341 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1342 isImmobilized([x
, y
]) {
1343 if (!this.options
["madrasi"])
1345 const color
= this.getColor(x
, y
);
1346 const oppCol
= C
.GetOppCol(color
);
1347 const piece
= this.getPieceType(x
, y
);
1348 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1349 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1350 for (let a
of attacks
) {
1351 outerLoop: for (let step
of a
.steps
) {
1352 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1353 let stepCounter
= 1;
1354 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1355 if (a
.range
<= stepCounter
++)
1358 j
= this.getY(j
+ step
[1]);
1361 this.onBoard(i
, j
) &&
1362 this.getColor(i
, j
) == oppCol
&&
1363 this.getPieceType(i
, j
) == piece
1372 // Stop at the first capture found
1373 atLeastOneCapture(color
) {
1374 const oppCol
= C
.GetOppCol(color
);
1375 const allowed
= (sq1
, sq2
) => {
1377 // NOTE: canTake is reversed for Zen.
1378 // Generally ok because of the symmetry. TODO?
1379 this.canTake(sq1
, sq2
) &&
1381 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1384 for (let i
=0; i
<this.size
.x
; i
++) {
1385 for (let j
=0; j
<this.size
.y
; j
++) {
1386 if (this.getColor(i
, j
) == color
) {
1389 !this.options
["zen"] &&
1390 this.findDestSquares(
1395 segments: this.options
["cylinder"]
1403 this.options
["zen"] &&
1404 this.findCapturesOn(
1408 segments: this.options
["cylinder"]
1423 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1424 const epsilon
= 1e-7; //arbitrary small value
1426 if (this.options
["cylinder"])
1427 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1428 for (let sh
of shifts
) {
1429 const rx
= (x2
- x1
) / step
[0],
1430 ry
= (y2
+ sh
- y1
) / step
[1];
1432 // Zero step but non-zero interval => impossible
1433 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1434 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1435 // Negative number of step (impossible)
1436 (rx
< 0 || ry
< 0) ||
1437 // Not the same number of steps in both directions:
1438 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1442 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1443 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1445 distance
= Math
.round(distance
); //in case of (numerical...)
1446 if (!range
|| range
>= distance
)
1452 ////////////////////
1455 getDropMovesFrom([c
, p
]) {
1456 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1457 // (but not necessarily otherwise: atLeastOneMove() etc)
1458 if (this.reserve
[c
][p
] == 0)
1461 for (let i
=0; i
<this.size
.x
; i
++) {
1462 for (let j
=0; j
<this.size
.y
; j
++) {
1463 if (this.canDrop([c
, p
], [i
, j
])) {
1465 start: {x: c
, y: p
},
1467 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1470 if (this.board
[i
][j
] != "") {
1471 mv
.vanish
.push(new PiPo({
1474 c: this.getColor(i
, j
),
1475 p: this.getPiece(i
, j
)
1485 // All possible moves from selected square
1486 getPotentialMovesFrom([x
, y
], color
) {
1487 if (this.subTurnTeleport
== 2)
1489 if (typeof x
== "string")
1490 return this.getDropMovesFrom([x
, y
]);
1491 if (this.isImmobilized([x
, y
]))
1493 const piece
= this.getPieceType(x
, y
);
1494 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1495 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1496 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1498 piece
== "k" && this.hasCastle
&&
1499 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1501 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1503 return this.postProcessPotentialMoves(moves
);
1506 postProcessPotentialMoves(moves
) {
1507 if (moves
.length
== 0)
1509 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1510 const oppCol
= C
.GetOppCol(color
);
1512 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1513 moves
= this.capturePostProcess(moves
, oppCol
);
1515 if (this.options
["atomic"])
1516 this.atomicPostProcess(moves
, color
, oppCol
);
1520 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1522 this.pawnPostProcess(moves
, color
, oppCol
);
1525 if (this.options
["cannibal"] && this.options
["rifle"])
1526 // In this case a rifle-capture from last rank may promote a pawn
1527 this.riflePromotePostProcess(moves
, color
);
1532 capturePostProcess(moves
, oppCol
) {
1533 // Filter out non-capturing moves (not using m.vanish because of
1534 // self captures of Recycle and Teleport).
1535 return moves
.filter(m
=> {
1537 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1538 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1543 atomicPostProcess(moves
, color
, oppCol
) {
1544 moves
.forEach(m
=> {
1546 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1547 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1560 let mNext
= new Move({
1566 for (let step
of steps
) {
1567 let x
= m
.end
.x
+ step
[0];
1568 let y
= this.getY(m
.end
.y
+ step
[1]);
1570 this.onBoard(x
, y
) &&
1571 this.board
[x
][y
] != "" &&
1572 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1573 this.getPieceType(x
, y
) != "p"
1577 p: this.getPiece(x
, y
),
1578 c: this.getColor(x
, y
),
1585 if (!this.options
["rifle"]) {
1586 // The moving piece also vanish
1587 mNext
.vanish
.unshift(
1592 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1601 pawnPostProcess(moves
, color
, oppCol
) {
1603 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1604 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1605 moves
.forEach(m
=> {
1606 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1607 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1608 const promotionOk
= (
1610 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1613 return; //nothing to do
1614 if (this.options
["pawnfall"]) {
1618 let finalPieces
= ["p"];
1620 this.options
["cannibal"] &&
1621 this.board
[x2
][y2
] != "" &&
1622 this.getColor(x2
, y2
) == oppCol
1624 finalPieces
= [this.getPieceType(x2
, y2
)];
1627 finalPieces
= this.pawnPromotions
;
1628 m
.appear
[0].p
= finalPieces
[0];
1629 if (initPiece
== "!") //cannibal king-pawn
1630 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1631 for (let i
=1; i
<finalPieces
.length
; i
++) {
1632 const piece
= finalPieces
[i
];
1635 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1637 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1638 moreMoves
.push(newMove
);
1641 Array
.prototype.push
.apply(moves
, moreMoves
);
1644 riflePromotePostProcess(moves
, color
) {
1645 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1647 moves
.forEach(m
=> {
1649 m
.start
.x
== lastRank
&&
1650 m
.appear
.length
>= 1 &&
1651 m
.appear
[0].p
== "p" &&
1652 m
.appear
[0].x
== m
.start
.x
&&
1653 m
.appear
[0].y
== m
.start
.y
1655 m
.appear
[0].p
= this.pawnPromotions
[0];
1656 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1657 let newMv
= JSON
.parse(JSON
.stringify(m
));
1658 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1659 newMoves
.push(newMv
);
1663 Array
.prototype.push
.apply(moves
, newMoves
);
1666 // Generic method to find possible moves of "sliding or jumping" pieces
1667 getPotentialMovesOf(piece
, [x
, y
]) {
1668 const color
= this.getColor(x
, y
);
1669 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1671 if (stepSpec
.attack
) {
1672 squares
= this.findDestSquares(
1676 segments: this.options
["cylinder"],
1679 ([i1
, j1
], [i2
, j2
]) => {
1681 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1682 this.canTake([i1
, j1
], [i2
, j2
])
1687 const noSpecials
= this.findDestSquares(
1690 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1691 segments: this.options
["cylinder"],
1695 Array
.prototype.push
.apply(squares
, noSpecials
);
1696 if (this.options
["zen"]) {
1697 let zenCaptures
= this.findCapturesOn(
1699 {}, //byCol: default is ok
1700 ([i1
, j1
], [i2
, j2
]) =>
1701 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1703 // Technical step: segments (if any) are reversed
1704 if (this.options
["cylinder"]) {
1705 zenCaptures
.forEach(z
=> {
1706 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1709 Array
.prototype.push
.apply(squares
, zenCaptures
);
1712 this.options
["recycle"] ||
1713 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1715 const selfCaptures
= this.findDestSquares(
1719 segments: this.options
["cylinder"],
1722 ([i1
, j1
], [i2
, j2
]) =>
1723 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1725 Array
.prototype.push
.apply(squares
, selfCaptures
);
1727 return squares
.map(s
=> {
1728 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1729 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1730 mv
.segments
= s
.segments
;
1735 findDestSquares([x
, y
], o
, allowed
) {
1737 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1738 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1740 // Next 3 for Cylinder mode: (unused if !o.segments)
1744 const addSquare
= ([i
, j
]) => {
1745 let elt
= {sq: [i
, j
]};
1747 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1750 const exploreSteps
= (stepArray
) => {
1751 for (let s
of stepArray
) {
1752 outerLoop: for (let step
of s
.steps
) {
1757 let [i
, j
] = [x
, y
];
1758 let stepCounter
= 0;
1760 this.onBoard(i
, j
) &&
1761 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1763 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1764 explored
[i
+ "." + j
] = true;
1767 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1769 if (o
.one
&& !o
.attackOnly
)
1772 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1773 if (o
.captureTarget
)
1777 if (s
.range
<= stepCounter
++)
1779 const oldIJ
= [i
, j
];
1781 j
= this.getY(j
+ step
[1]);
1782 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1783 // Boundary between segments (cylinder mode)
1784 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1788 if (!this.onBoard(i
, j
))
1790 const pieceIJ
= this.getPieceType(i
, j
);
1791 if (!explored
[i
+ "." + j
]) {
1792 explored
[i
+ "." + j
] = true;
1793 if (allowed([x
, y
], [i
, j
])) {
1794 if (o
.one
&& !o
.moveOnly
)
1797 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1800 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1808 return undefined; //default, but let's explicit it
1810 if (o
.captureTarget
)
1811 return exploreSteps(o
.captureSteps
)
1814 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1816 if (!o
.attackOnly
|| !stepSpec
.attack
)
1817 outOne
= exploreSteps(stepSpec
.moves
);
1818 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1819 o
.attackOnly
= true; //ok because o is always a temporary object
1820 outOne
= exploreSteps(stepSpec
.attack
);
1822 return (o
.one
? outOne : res
);
1826 // Search for enemy (or not) pieces attacking [x, y]
1827 findCapturesOn([x
, y
], o
, allowed
) {
1829 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1831 for (let i
=0; i
<this.size
.x
; i
++) {
1832 for (let j
=0; j
<this.size
.y
; j
++) {
1833 const colIJ
= this.getColor(i
, j
);
1835 this.board
[i
][j
] != "" &&
1836 o
.byCol
.includes(colIJ
) &&
1837 !this.isImmobilized([i
, j
])
1839 const apparentPiece
= this.getPiece(i
, j
);
1840 // Quick check: does this potential attacker target x,y ?
1841 if (this.canStepOver(x
, y
, apparentPiece
))
1843 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1844 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1845 for (let a
of attacks
) {
1846 for (let s
of a
.steps
) {
1847 // Quick check: if step isn't compatible, don't even try
1848 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1850 // Finally verify that nothing stand in-between
1851 const out
= this.findDestSquares(
1854 captureTarget: [x
, y
],
1855 captureSteps: [{steps: [s
], range: a
.range
}],
1856 segments: o
.segments
,
1858 one: false //one and captureTarget are mutually exclusive
1872 return (o
.one
? false : res
);
1875 // Build a regular move from its initial and destination squares.
1876 // tr: transformation
1877 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1878 const initColor
= this.getColor(sx
, sy
);
1879 const initPiece
= this.getPiece(sx
, sy
);
1880 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1884 start: {x: sx
, y: sy
},
1888 !this.options
["rifle"] ||
1889 this.board
[ex
][ey
] == "" ||
1890 destColor
== initColor
//Recycle, Teleport
1896 c: !!tr
? tr
.c : initColor
,
1897 p: !!tr
? tr
.p : initPiece
1909 if (this.board
[ex
][ey
] != "") {
1914 c: this.getColor(ex
, ey
),
1915 p: this.getPiece(ex
, ey
)
1918 if (this.options
["cannibal"] && destColor
!= initColor
) {
1919 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1920 let trPiece
= mv
.vanish
[lastIdx
].p
;
1921 if (this.isKing(sx
, sy
))
1922 trPiece
= C
.CannibalKingCode
[trPiece
];
1923 if (mv
.appear
.length
>= 1)
1924 mv
.appear
[0].p
= trPiece
;
1925 else if (this.options
["rifle"]) {
1948 // En-passant square, if any
1949 getEpSquare(moveOrSquare
) {
1950 if (typeof moveOrSquare
=== "string") {
1951 const square
= moveOrSquare
;
1954 return C
.SquareToCoords(square
);
1956 // Argument is a move:
1957 const move = moveOrSquare
;
1958 const s
= move.start
,
1962 Math
.abs(s
.x
- e
.x
) == 2 &&
1963 // Next conditions for variants like Atomic or Rifle, Recycle...
1965 move.appear
.length
> 0 &&
1966 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1970 move.vanish
.length
> 0 &&
1971 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1979 return undefined; //default
1982 // Special case of en-passant captures: treated separately
1983 getEnpassantCaptures([x
, y
]) {
1984 const color
= this.getColor(x
, y
);
1985 const shiftX
= (color
== 'w' ? -1 : 1);
1986 const oppCol
= C
.GetOppCol(color
);
1989 this.epSquare
.x
== x
+ shiftX
&&
1990 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1991 // Doublemove (and Progressive?) guards:
1992 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
1993 this.getColor(x
, this.epSquare
.y
) == oppCol
1995 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1996 this.board
[epx
][epy
] = oppCol
+ 'p';
1997 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1998 this.board
[epx
][epy
] = "";
1999 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2000 enpassantMove
.vanish
[lastIdx
].x
= x
;
2001 return [enpassantMove
];
2006 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2007 const c
= this.getColor(x
, y
);
2010 const oppCol
= C
.GetOppCol(c
);
2014 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2015 const castlingKing
= this.getPiece(x
, y
);
2016 castlingCheck: for (
2019 castleSide
++ //large, then small
2021 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2023 // If this code is reached, rook and king are on initial position
2025 // NOTE: in some variants this is not a rook
2026 const rookPos
= this.castleFlags
[c
][castleSide
];
2027 const castlingPiece
= this.getPiece(x
, rookPos
);
2029 this.board
[x
][rookPos
] == "" ||
2030 this.getColor(x
, rookPos
) != c
||
2031 (castleWith
&& !castleWith
.includes(castlingPiece
))
2033 // Rook is not here, or changed color (see Benedict)
2036 // Nothing on the path of the king ? (and no checks)
2037 const finDist
= finalSquares
[castleSide
][0] - y
;
2038 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2042 // NOTE: next weird test because underCheck() verification
2043 // will be executed in filterValid() later.
2045 i
!= finalSquares
[castleSide
][0] &&
2046 this.underCheck([x
, i
], oppCol
)
2050 this.board
[x
][i
] != "" &&
2051 // NOTE: next check is enough, because of chessboard constraints
2052 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2055 continue castlingCheck
;
2058 } while (i
!= finalSquares
[castleSide
][0]);
2059 // Nothing on the path to the rook?
2060 step
= (castleSide
== 0 ? -1 : 1);
2061 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2062 if (this.board
[x
][i
] != "")
2063 continue castlingCheck
;
2066 // Nothing on final squares, except maybe king and castling rook?
2067 for (i
= 0; i
< 2; i
++) {
2069 finalSquares
[castleSide
][i
] != rookPos
&&
2070 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2072 finalSquares
[castleSide
][i
] != y
||
2073 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2076 continue castlingCheck
;
2080 // If this code is reached, castle is potentially valid
2086 y: finalSquares
[castleSide
][0],
2092 y: finalSquares
[castleSide
][1],
2098 // King might be initially disguised (Titan...)
2099 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2100 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2103 Math
.abs(y
- rookPos
) <= 2
2104 ? {x: x
, y: rookPos
}
2105 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2113 ////////////////////
2116 // Is piece (or square) at given position attacked by "oppCol" ?
2117 underAttack([x
, y
], oppCol
) {
2118 // An empty square is considered as king,
2119 // since it's used only in getCastleMoves (TODO?)
2120 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2123 (!this.options
["zen"] || king
) &&
2124 this.findCapturesOn(
2128 segments: this.options
["cylinder"],
2135 (!!this.options
["zen"] && !king
) &&
2136 this.findDestSquares(
2140 segments: this.options
["cylinder"],
2143 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2149 underCheck([x
, y
], oppCol
) {
2150 if (this.options
["taking"] || this.options
["dark"])
2152 return this.underAttack([x
, y
], oppCol
);
2155 // Stop at first king found (TODO: multi-kings)
2156 searchKingPos(color
) {
2157 for (let i
=0; i
< this.size
.x
; i
++) {
2158 for (let j
=0; j
< this.size
.y
; j
++) {
2159 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2163 return [-1, -1]; //king not found
2166 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2167 filterValid(moves
, color
) {
2170 const oppCol
= C
.GetOppCol(color
);
2171 const kingPos
= this.searchKingPos(color
);
2172 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2173 return moves
.filter(m
=> {
2174 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2175 if (!filtered
[key
]) {
2176 this.playOnBoard(m
);
2177 let square
= kingPos
,
2178 res
= true; //a priori valid
2179 if (m
.vanish
.some(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
)) {
2180 // Search king in appear array:
2182 m
.appear
.findIndex(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2183 if (newKingIdx
>= 0)
2184 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
2188 res
&&= !this.underCheck(square
, oppCol
);
2189 this.undoOnBoard(m
);
2190 filtered
[key
] = res
;
2193 return filtered
[key
];
2200 // Apply a move on board
2202 for (let psq
of move.vanish
)
2203 this.board
[psq
.x
][psq
.y
] = "";
2204 for (let psq
of move.appear
)
2205 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2207 // Un-apply the played move
2209 for (let psq
of move.appear
)
2210 this.board
[psq
.x
][psq
.y
] = "";
2211 for (let psq
of move.vanish
)
2212 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2215 updateCastleFlags(move) {
2216 // Update castling flags if start or arrive from/at rook/king locations
2217 move.appear
.concat(move.vanish
).forEach(psq
=> {
2218 if (this.isKing(0, 0, psq
.p
))
2219 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2220 // NOTE: not "else if" because king can capture enemy rook...
2224 else if (psq
.x
== this.size
.x
- 1)
2227 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2229 this.castleFlags
[c
][fidx
] = this.size
.y
;
2237 // If flags already off, no need to re-check:
2238 Object
.values(this.castleFlags
).some(cvals
=>
2239 cvals
.some(val
=> val
< this.size
.y
))
2241 this.updateCastleFlags(move);
2243 if (this.options
["crazyhouse"]) {
2244 move.vanish
.forEach(v
=> {
2245 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2246 if (this.ispawn
[square
])
2247 delete this.ispawn
[square
];
2249 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2250 // Assumption: something is moving
2251 const initSquare
= C
.CoordsToSquare(move.start
);
2252 const destSquare
= C
.CoordsToSquare(move.end
);
2254 this.ispawn
[initSquare
] ||
2255 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2257 this.ispawn
[destSquare
] = true;
2260 this.ispawn
[destSquare
] &&
2261 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2263 move.vanish
[1].p
= 'p';
2264 delete this.ispawn
[destSquare
];
2268 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2271 // Warning; atomic pawn removal isn't a capture
2272 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2274 const color
= this.turn
;
2275 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2276 // Something appears = dropped on board (some exceptions, Chakart...)
2277 if (move.appear
[i
].c
== color
) {
2278 const piece
= move.appear
[i
].p
;
2279 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2282 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2283 // Something vanish: add to reserve except if recycle & opponent
2285 this.options
["crazyhouse"] ||
2286 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2288 const piece
= move.vanish
[i
].p
;
2289 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2297 if (this.hasEnpassant
)
2298 this.epSquare
= this.getEpSquare(move);
2299 this.playOnBoard(move);
2300 this.postPlay(move);
2304 const color
= this.turn
;
2305 if (this.options
["dark"])
2306 this.updateEnlightened();
2307 if (this.options
["teleport"]) {
2309 this.subTurnTeleport
== 1 &&
2310 move.vanish
.length
> move.appear
.length
&&
2311 move.vanish
[1].c
== color
2313 const v
= move.vanish
[move.vanish
.length
- 1];
2314 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2315 this.subTurnTeleport
= 2;
2318 this.subTurnTeleport
= 1;
2319 this.captured
= null;
2321 if (this.isLastMove(move)) {
2322 this.turn
= C
.GetOppCol(color
);
2326 else if (!move.next
)
2333 const color
= this.turn
;
2334 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2335 if (oppKingPos
[0] < 0 || this.underCheck(oppKingPos
, color
))
2339 !this.options
["balance"] ||
2340 ![1, 2].includes(this.movesCount
) ||
2345 !this.options
["doublemove"] ||
2346 this.movesCount
== 0 ||
2351 !this.options
["progressive"] ||
2352 this.subTurn
== this.movesCount
+ 1
2357 // "Stop at the first move found"
2358 atLeastOneMove(color
) {
2359 for (let i
= 0; i
< this.size
.x
; i
++) {
2360 for (let j
= 0; j
< this.size
.y
; j
++) {
2361 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2362 // NOTE: in fact searching for all potential moves from i,j.
2363 // I don't believe this is an issue, for now at least.
2364 const moves
= this.getPotentialMovesFrom([i
, j
]);
2365 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2370 if (this.hasReserve
&& this.reserve
[color
]) {
2371 for (let p
of Object
.keys(this.reserve
[color
])) {
2372 const moves
= this.getDropMovesFrom([color
, p
]);
2373 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2380 // What is the score ? (Interesting if game is over)
2381 getCurrentScore(move) {
2382 const color
= this.turn
;
2383 const oppCol
= C
.GetOppCol(color
);
2384 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2385 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2387 if (kingPos
[0][0] < 0)
2388 return (color
== "w" ? "0-1" : "1-0");
2389 if (kingPos
[1][0] < 0)
2390 return (color
== "w" ? "1-0" : "0-1");
2391 if (this.atLeastOneMove(color
))
2393 // No valid move: stalemate or checkmate?
2394 if (!this.underCheck(kingPos
[0], oppCol
))
2397 return (color
== "w" ? "0-1" : "1-0");
2400 playVisual(move, r
) {
2401 move.vanish
.forEach(v
=> {
2402 this.g_pieces
[v
.x
][v
.y
].remove();
2403 this.g_pieces
[v
.x
][v
.y
] = null;
2406 document
.getElementById(this.containerId
).querySelector(".chessboard");
2408 r
= chessboard
.getBoundingClientRect();
2409 const pieceWidth
= this.getPieceWidth(r
.width
);
2410 move.appear
.forEach(a
=> {
2411 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2412 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2413 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2414 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2415 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2416 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2417 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2418 // Translate coordinates to use chessboard as reference:
2419 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2420 `translate(${ip - r.x}px,${jp - r.y}px)`;
2421 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2422 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2423 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2425 if (this.options
["dark"])
2426 this.graphUpdateEnlightened();
2429 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2430 buildMoveStack(move, r
) {
2431 this.moveStack
.push(move);
2432 this.computeNextMove(move);
2434 const newTurn
= this.turn
;
2435 if (this.moveStack
.length
== 1)
2436 this.playVisual(move, r
);
2440 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2442 this.buildMoveStack(move.next
, r
);
2445 if (this.moveStack
.length
== 1) {
2446 // Usual case (one normal move)
2447 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2451 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2452 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2453 this.playReceivedMove(this.moveStack
.slice(1), () => {
2454 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2461 // Implemented in variants using (automatic) moveStack
2462 computeNextMove(move) {}
2464 animateMoving(start
, end
, drag
, segments
, cb
) {
2465 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2466 // NOTE: cloning often not required, but light enough, and simpler
2467 let movingPiece
= initPiece
.cloneNode();
2468 initPiece
.style
.opacity
= "0";
2470 document
.getElementById(this.containerId
)
2471 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2472 if (typeof start
.x
== "string") {
2473 // Need to bound width/height (was 100% for reserve pieces)
2474 const pieceWidth
= this.getPieceWidth(r
.width
);
2475 movingPiece
.style
.width
= pieceWidth
+ "px";
2476 movingPiece
.style
.height
= pieceWidth
+ "px";
2478 const maxDist
= this.getMaxDistance(r
);
2479 const apparentColor
= this.getColor(start
.x
, start
.y
);
2480 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2482 const startCode
= this.getPiece(start
.x
, start
.y
);
2483 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2484 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2485 if (apparentColor
!= drag
.c
) {
2486 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2487 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2490 container
.appendChild(movingPiece
);
2491 const animateSegment
= (index
, cb
) => {
2492 // NOTE: move.drag could be generalized per-segment (usage?)
2493 const [i1
, j1
] = segments
[index
][0];
2494 const [i2
, j2
] = segments
[index
][1];
2495 const dep
= this.getPixelPosition(i1
, j1
, r
);
2496 const arr
= this.getPixelPosition(i2
, j2
, r
);
2497 movingPiece
.style
.transitionDuration
= "0s";
2498 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2500 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2501 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2502 // TODO: unclear why we need this new delay below:
2504 movingPiece
.style
.transitionDuration
= duration
+ "s";
2505 // movingPiece is child of container: no need to adjust coordinates
2506 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2507 setTimeout(cb
, duration
* 1000);
2511 const animateSegmentCallback
= () => {
2512 if (index
< segments
.length
)
2513 animateSegment(index
++, animateSegmentCallback
);
2515 movingPiece
.remove();
2516 initPiece
.style
.opacity
= "1";
2520 animateSegmentCallback();
2523 // Input array of objects with at least fields x,y (e.g. PiPo)
2524 animateFading(arr
, cb
) {
2525 const animLength
= 350; //TODO: 350ms? More? Less?
2527 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2528 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2529 fadingPiece
.style
.opacity
= "0";
2531 setTimeout(cb
, animLength
);
2534 animate(move, callback
) {
2535 if (this.noAnimate
|| move.noAnimate
) {
2539 let segments
= move.segments
;
2541 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2542 let targetObj
= new TargetObj(callback
);
2543 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2545 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2546 () => targetObj
.increment());
2548 if (move.vanish
.length
> move.appear
.length
) {
2549 const arr
= move.vanish
.slice(move.appear
.length
)
2550 // Ignore disappearing pieces hidden by some appearing ones:
2551 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2552 if (arr
.length
> 0) {
2554 this.animateFading(arr
, () => targetObj
.increment());
2558 this.customAnimate(move, segments
, () => targetObj
.increment());
2559 if (targetObj
.target
== 0)
2563 // Potential other animations (e.g. for Suction variant)
2564 customAnimate(move, segments
, cb
) {
2565 return 0; //nb of targets
2568 playReceivedMove(moves
, callback
) {
2569 const launchAnimation
= () => {
2570 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2571 const animateRec
= i
=> {
2572 this.animate(moves
[i
], () => {
2573 this.play(moves
[i
]);
2574 this.playVisual(moves
[i
], r
);
2575 if (i
< moves
.length
- 1)
2576 setTimeout(() => animateRec(i
+1), 300);
2583 // Delay if user wasn't focused:
2584 const checkDisplayThenAnimate
= (delay
) => {
2585 if (container
.style
.display
== "none") {
2586 alert("New move! Let's go back to game...");
2587 document
.getElementById("gameInfos").style
.display
= "none";
2588 container
.style
.display
= "block";
2589 setTimeout(launchAnimation
, 700);
2592 setTimeout(launchAnimation
, delay
|| 0);
2594 let container
= document
.getElementById(this.containerId
);
2595 if (document
.hidden
) {
2596 document
.onvisibilitychange
= () => {
2597 document
.onvisibilitychange
= undefined;
2598 checkDisplayThenAnimate(700);
2602 checkDisplayThenAnimate();