e3a34fbada483cf022b756c71d3f23b682c6c09a
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.marks
= o
.marks
;
420 this.graphicalInit();
423 re_initFromFen(fen
, oldBoard
) {
424 const fenParsed
= this.parseFen(fen
);
425 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
426 this.turn
= fenParsed
.turn
;
427 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
428 this.setOtherVariables(fenParsed
);
431 // Turn position fen into double array ["wb","wp","bk",...]
433 const rows
= position
.split("/");
434 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
435 for (let i
= 0; i
< rows
.length
; i
++) {
437 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
438 const character
= rows
[i
][indexInRow
];
439 const num
= parseInt(character
, 10);
440 // If num is a number, just shift j:
443 // Else: something at position i,j
445 board
[i
][j
++] = this.fen2board(character
);
451 // Some additional variables from FEN (variant dependant)
452 setOtherVariables(fenParsed
) {
453 // Set flags and enpassant:
455 this.setFlags(fenParsed
.flags
);
456 if (this.hasEnpassant
)
457 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
458 if (this.hasReserve
&& !this.isDiagram
)
459 this.initReserves(fenParsed
.reserve
);
460 if (this.options
["crazyhouse"])
461 this.initIspawn(fenParsed
.ispawn
);
462 if (this.options
["teleport"]) {
463 this.subTurnTeleport
= 1;
464 this.captured
= null;
466 if (this.options
["dark"]) {
467 // Setup enlightened: squares reachable by player side
468 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
469 this.updateEnlightened();
471 this.subTurn
= 1; //may be unused
472 if (!this.moveStack
) //avoid resetting (unwanted)
476 // ordering as in pieces() p,r,n,b,q,k
477 initReserves(reserveStr
) {
478 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
479 this.reserve
= { w: {}, b: {} };
480 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
481 const L
= pieceName
.length
;
482 for (let i
of ArrayFun
.range(2 * L
)) {
484 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
486 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
490 initIspawn(ispawnStr
) {
491 if (ispawnStr
!= "-")
492 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
500 getPieceWidth(rwidth
) {
501 return (rwidth
/ this.size
.y
);
504 getReserveSquareSize(rwidth
, nbR
) {
505 const sqSize
= this.getPieceWidth(rwidth
);
506 return Math
.min(sqSize
, rwidth
/ nbR
);
509 getReserveNumId(color
, piece
) {
510 return `${this.containerId}|rnum-${color}${piece}`;
513 getNbReservePieces(color
) {
515 Object
.values(this.reserve
[color
]).reduce(
516 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
520 getRankInReserve(c
, p
) {
521 const pieces
= Object
.keys(this.pieces());
522 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
523 let toTest
= pieces
.slice(0, lastIndex
);
524 return toTest
.reduce(
525 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
528 static AddClass_es(piece
, class_es
) {
529 if (!Array
.isArray(class_es
))
530 class_es
= [class_es
];
531 class_es
.forEach(cl
=> {
532 piece
.classList
.add(cl
);
536 static RemoveClass_es(piece
, class_es
) {
537 if (!Array
.isArray(class_es
))
538 class_es
= [class_es
];
539 class_es
.forEach(cl
=> {
540 piece
.classList
.remove(cl
);
544 // Generally light square bottom-right
545 getSquareColorClass(x
, y
) {
546 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
550 // Works for all rectangular boards:
551 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
555 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
562 const g_init
= () => {
563 this.re_drawBoardElements();
564 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
565 this.initMouseEvents();
567 let container
= document
.getElementById(this.containerId
);
568 this.windowResizeObs
= new ResizeObserver(g_init
);
569 this.windowResizeObs
.observe(container
);
572 re_drawBoardElements() {
573 const board
= this.getSvgChessboard();
574 const oppCol
= C
.GetOppCol(this.playerColor
);
575 const container
= document
.getElementById(this.containerId
);
576 const rc
= container
.getBoundingClientRect();
577 let chessboard
= container
.querySelector(".chessboard");
578 chessboard
.innerHTML
= "";
579 chessboard
.insertAdjacentHTML('beforeend', board
);
580 // Compare window ratio width / height to aspectRatio:
581 const windowRatio
= rc
.width
/ rc
.height
;
582 let cbWidth
, cbHeight
;
583 const vRatio
= this.size
.ratio
|| 1;
584 if (windowRatio
<= vRatio
) {
585 // Limiting dimension is width:
586 cbWidth
= Math
.min(rc
.width
, 767);
587 cbHeight
= cbWidth
/ vRatio
;
590 // Limiting dimension is height:
591 cbHeight
= Math
.min(rc
.height
, 767);
592 cbWidth
= cbHeight
* vRatio
;
594 if (this.hasReserve
&& !this.isDiagram
) {
595 const sqSize
= cbWidth
/ this.size
.y
;
596 // NOTE: allocate space for reserves (up/down) even if they are empty
597 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
598 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
599 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
600 cbWidth
= cbHeight
* vRatio
;
603 chessboard
.style
.width
= cbWidth
+ "px";
604 chessboard
.style
.height
= cbHeight
+ "px";
605 // Center chessboard:
606 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
607 spaceTop
= (rc
.height
- cbHeight
) / 2;
608 chessboard
.style
.left
= spaceLeft
+ "px";
609 chessboard
.style
.top
= spaceTop
+ "px";
610 // Give sizes instead of recomputing them,
611 // because chessboard might not be drawn yet.
620 // Get SVG board (background, no pieces)
622 const flipped
= (this.playerColor
== 'b');
625 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
626 class="chessboard_SVG">`;
627 for (let i
=0; i
< this.size
.x
; i
++) {
628 for (let j
=0; j
< this.size
.y
; j
++) {
629 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
630 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
631 let classes
= this.getSquareColorClass(ii
, jj
);
632 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
633 classes
+= " in-shadow";
634 // NOTE: x / y reversed because coordinates system is reversed.
638 id="${this.coordsToId({x: ii, y: jj})}"
652 document
.getElementById(this.containerId
).querySelector(".chessboard");
654 r
= chessboard
.getBoundingClientRect();
655 const pieceWidth
= this.getPieceWidth(r
.width
);
656 const addPiece
= (i
, j
, arrName
, classes
) => {
657 this[arrName
][i
][j
] = document
.createElement("piece");
658 C
.AddClass_es(this[arrName
][i
][j
], classes
);
659 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
660 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
661 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
662 // Translate coordinates to use chessboard as reference:
663 this[arrName
][i
][j
].style
.transform
=
664 `translate(${ip - r.x}px,${jp - r.y}px)`;
665 chessboard
.appendChild(this[arrName
][i
][j
]);
667 const conditionalReset
= (arrName
) => {
669 // Refreshing: delete old pieces first. This isn't necessary,
670 // but simpler (this method isn't called many times)
671 for (let i
=0; i
<this.size
.x
; i
++) {
672 for (let j
=0; j
<this.size
.y
; j
++) {
673 if (this[arrName
][i
][j
]) {
674 this[arrName
][i
][j
].remove();
675 this[arrName
][i
][j
] = null;
681 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
682 if (arrName
== "d_pieces")
683 this.marks
.forEach(([i
, j
]) => addPiece(i
, j
, arrName
, "mark"));
686 conditionalReset("d_pieces");
687 conditionalReset("g_pieces");
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 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
694 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
695 if (this.enlightened
&& !this.enlightened
[i
][j
])
696 this.g_pieces
[i
][j
].classList
.add("hidden");
698 if (this.marks
&& this.d_pieces
[i
][j
]) {
699 let classes
= ["mark"];
700 if (this.board
[i
][j
] != "")
701 classes
.push("transparent");
702 addPiece(i
, j
, "d_pieces", classes
);
706 if (this.hasReserve
&& !this.isDiagram
)
707 this.re_drawReserve(['w', 'b'], r
);
710 // NOTE: assume this.reserve != null
711 re_drawReserve(colors
, r
) {
713 // Remove (old) reserve pieces
714 for (let c
of colors
) {
715 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
716 this.r_pieces
[c
][p
].remove();
717 delete this.r_pieces
[c
][p
];
718 const numId
= this.getReserveNumId(c
, p
);
719 document
.getElementById(numId
).remove();
724 this.r_pieces
= { w: {}, b: {} };
725 let container
= document
.getElementById(this.containerId
);
727 r
= container
.querySelector(".chessboard").getBoundingClientRect();
728 for (let c
of colors
) {
729 let reservesDiv
= document
.getElementById("reserves_" + c
);
731 reservesDiv
.remove();
732 if (!this.reserve
[c
])
734 const nbR
= this.getNbReservePieces(c
);
737 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
739 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
740 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
741 let rcontainer
= document
.createElement("div");
742 rcontainer
.id
= "reserves_" + c
;
743 rcontainer
.classList
.add("reserves");
744 rcontainer
.style
.left
= i0
+ "px";
745 rcontainer
.style
.top
= j0
+ "px";
746 // NOTE: +1 fix display bug on Firefox at least
747 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
748 rcontainer
.style
.height
= sqResSize
+ "px";
749 container
.appendChild(rcontainer
);
750 for (let p
of Object
.keys(this.reserve
[c
])) {
751 if (this.reserve
[c
][p
] == 0)
753 let r_cell
= document
.createElement("div");
754 r_cell
.id
= this.coordsToId({x: c
, y: p
});
755 r_cell
.classList
.add("reserve-cell");
756 r_cell
.style
.width
= sqResSize
+ "px";
757 r_cell
.style
.height
= sqResSize
+ "px";
758 rcontainer
.appendChild(r_cell
);
759 let piece
= document
.createElement("piece");
760 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
761 piece
.classList
.add(C
.GetColorClass(c
));
762 piece
.style
.width
= "100%";
763 piece
.style
.height
= "100%";
764 this.r_pieces
[c
][p
] = piece
;
765 r_cell
.appendChild(piece
);
766 let number
= document
.createElement("div");
767 number
.textContent
= this.reserve
[c
][p
];
768 number
.classList
.add("reserve-num");
769 number
.id
= this.getReserveNumId(c
, p
);
770 const fontSize
= "1.3em";
771 number
.style
.fontSize
= fontSize
;
772 number
.style
.fontSize
= fontSize
;
773 r_cell
.appendChild(number
);
779 updateReserve(color
, piece
, count
) {
780 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
781 piece
= "k"; //capturing cannibal king: back to king form
782 const oldCount
= this.reserve
[color
][piece
];
783 this.reserve
[color
][piece
] = count
;
784 // Redrawing is much easier if count==0
785 if ([oldCount
, count
].includes(0))
786 this.re_drawReserve([color
]);
788 const numId
= this.getReserveNumId(color
, piece
);
789 document
.getElementById(numId
).textContent
= count
;
793 // Resize board: no need to destroy/recreate pieces
795 const container
= document
.getElementById(this.containerId
);
796 let chessboard
= container
.querySelector(".chessboard");
797 const rc
= container
.getBoundingClientRect(),
798 r
= chessboard
.getBoundingClientRect();
799 const multFact
= (mode
== "up" ? 1.05 : 0.95);
800 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
802 const vRatio
= this.size
.ratio
|| 1;
803 if (newWidth
> rc
.width
) {
805 newHeight
= newWidth
/ vRatio
;
807 if (newHeight
> rc
.height
) {
808 newHeight
= rc
.height
;
809 newWidth
= newHeight
* vRatio
;
811 chessboard
.style
.width
= newWidth
+ "px";
812 chessboard
.style
.height
= newHeight
+ "px";
813 const newX
= (rc
.width
- newWidth
) / 2;
814 chessboard
.style
.left
= newX
+ "px";
815 const newY
= (rc
.height
- newHeight
) / 2;
816 chessboard
.style
.top
= newY
+ "px";
817 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
818 const pieceWidth
= this.getPieceWidth(newWidth
);
819 // NOTE: next "if" for variants which use squares filling
820 // instead of "physical", moving pieces
822 for (let i
=0; i
< this.size
.x
; i
++) {
823 for (let j
=0; j
< this.size
.y
; j
++) {
824 if (this.g_pieces
[i
][j
]) {
825 // NOTE: could also use CSS transform "scale"
826 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
827 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
828 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
829 // Translate coordinates to use chessboard as reference:
830 this.g_pieces
[i
][j
].style
.transform
=
831 `translate(${ip - newX}px,${jp - newY}px)`;
837 this.rescaleReserve(newR
);
841 for (let c
of ['w','b']) {
842 if (!this.reserve
[c
])
844 const nbR
= this.getNbReservePieces(c
);
847 // Resize container first
848 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
849 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
850 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
851 let rcontainer
= document
.getElementById("reserves_" + c
);
852 rcontainer
.style
.left
= i0
+ "px";
853 rcontainer
.style
.top
= j0
+ "px";
854 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
855 rcontainer
.style
.height
= sqResSize
+ "px";
856 // And then reserve cells:
857 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
858 Object
.keys(this.reserve
[c
]).forEach(p
=> {
859 if (this.reserve
[c
][p
] == 0)
861 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
862 r_cell
.style
.width
= sqResSize
+ "px";
863 r_cell
.style
.height
= sqResSize
+ "px";
868 // Return the absolute pixel coordinates given current position.
869 // Our coordinate system differs from CSS one (x <--> y).
870 // We return here the CSS coordinates (more useful).
871 getPixelPosition(i
, j
, r
) {
873 return [0, 0]; //piece vanishes
875 if (typeof i
== "string") {
876 // Reserves: need to know the rank of piece
877 const nbR
= this.getNbReservePieces(i
);
878 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
879 x
= this.getRankInReserve(i
, j
) * rsqSize
;
880 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
883 const sqSize
= r
.width
/ this.size
.y
;
884 const flipped
= (this.playerColor
== 'b');
885 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
886 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
888 return [r
.x
+ x
, r
.y
+ y
];
892 let container
= document
.getElementById(this.containerId
);
893 let chessboard
= container
.querySelector(".chessboard");
895 const getOffset
= e
=> {
898 return {x: e
.clientX
, y: e
.clientY
};
899 let touchLocation
= null;
900 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
901 // Touch screen, dragstart
902 touchLocation
= e
.targetTouches
[0];
903 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
904 // Touch screen, dragend
905 touchLocation
= e
.changedTouches
[0];
907 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
908 return {x: 0, y: 0}; //shouldn't reach here =)
911 const centerOnCursor
= (piece
, e
) => {
912 const centerShift
= this.getPieceWidth(r
.width
) / 2;
913 const offset
= getOffset(e
);
914 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
915 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
920 startPiece
, curPiece
= null,
922 const mousedown
= (e
) => {
923 // Disable zoom on smartphones:
924 if (e
.touches
&& e
.touches
.length
> 1)
926 r
= chessboard
.getBoundingClientRect();
927 pieceWidth
= this.getPieceWidth(r
.width
);
928 const cd
= this.idToCoords(e
.target
.id
);
930 const move = this.doClick(cd
);
932 this.buildMoveStack(move, r
);
933 else if (!this.clickOnly
) {
934 const [x
, y
] = Object
.values(cd
);
935 if (typeof x
!= "number")
936 startPiece
= this.r_pieces
[x
][y
];
938 startPiece
= this.g_pieces
[x
][y
];
939 if (startPiece
&& this.canIplay(x
, y
)) {
942 curPiece
= startPiece
.cloneNode();
943 curPiece
.style
.transform
= "none";
944 curPiece
.style
.zIndex
= 5;
945 curPiece
.style
.width
= pieceWidth
+ "px";
946 curPiece
.style
.height
= pieceWidth
+ "px";
947 centerOnCursor(curPiece
, e
);
948 container
.appendChild(curPiece
);
949 startPiece
.style
.opacity
= "0.4";
950 chessboard
.style
.cursor
= "none";
956 const mousemove
= (e
) => {
959 centerOnCursor(curPiece
, e
);
961 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
962 // Attempt to prevent horizontal swipe...
966 const mouseup
= (e
) => {
969 const [x
, y
] = [start
.x
, start
.y
];
972 chessboard
.style
.cursor
= "pointer";
973 startPiece
.style
.opacity
= "1";
974 const offset
= getOffset(e
);
975 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
977 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
979 // NOTE: clearly suboptimal, but much easier, and not a big deal.
980 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
981 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
982 const moves
= this.filterValid(potentialMoves
);
983 if (moves
.length
>= 2)
984 this.showChoices(moves
, r
);
985 else if (moves
.length
== 1)
986 this.buildMoveStack(moves
[0], r
);
991 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
993 if ('onmousedown' in window
) {
994 this.mouseListeners
= [
995 {type: "mousedown", listener: mousedown
},
996 {type: "mousemove", listener: mousemove
},
997 {type: "mouseup", listener: mouseup
},
998 {type: "wheel", listener: resize
}
1000 this.mouseListeners
.forEach(ml
=> {
1001 document
.addEventListener(ml
.type
, ml
.listener
);
1004 if ('ontouchstart' in window
) {
1005 this.touchListeners
= [
1006 {type: "touchstart", listener: mousedown
},
1007 {type: "touchmove", listener: mousemove
},
1008 {type: "touchend", listener: mouseup
}
1010 this.touchListeners
.forEach(tl
=> {
1011 // https://stackoverflow.com/a/42509310/12660887
1012 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
1015 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1019 let container
= document
.getElementById(this.containerId
);
1020 this.windowResizeObs
.unobserve(container
);
1022 return; //no listeners in this case
1023 if ('onmousedown' in window
) {
1024 this.mouseListeners
.forEach(ml
=> {
1025 document
.removeEventListener(ml
.type
, ml
.listener
);
1028 if ('ontouchstart' in window
) {
1029 this.touchListeners
.forEach(tl
=> {
1030 // https://stackoverflow.com/a/42509310/12660887
1031 document
.removeEventListener(tl
.type
, tl
.listener
);
1036 showChoices(moves
, r
) {
1037 let container
= document
.getElementById(this.containerId
);
1038 let chessboard
= container
.querySelector(".chessboard");
1039 let choices
= document
.createElement("div");
1040 choices
.id
= "choices";
1042 r
= chessboard
.getBoundingClientRect();
1043 choices
.style
.width
= r
.width
+ "px";
1044 choices
.style
.height
= r
.height
+ "px";
1045 choices
.style
.left
= r
.x
+ "px";
1046 choices
.style
.top
= r
.y
+ "px";
1047 chessboard
.style
.opacity
= "0.5";
1048 container
.appendChild(choices
);
1049 const squareWidth
= r
.width
/ this.size
.y
;
1050 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1051 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1052 const color
= moves
[0].appear
[0].c
;
1053 const callback
= (m
) => {
1054 chessboard
.style
.opacity
= "1";
1055 container
.removeChild(choices
);
1056 this.buildMoveStack(m
, r
);
1058 for (let i
=0; i
< moves
.length
; i
++) {
1059 let choice
= document
.createElement("div");
1060 choice
.classList
.add("choice");
1061 choice
.style
.width
= squareWidth
+ "px";
1062 choice
.style
.height
= squareWidth
+ "px";
1063 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1064 choice
.style
.top
= firstUpTop
+ "px";
1065 choice
.style
.backgroundColor
= "lightyellow";
1066 choice
.onclick
= () => callback(moves
[i
]);
1067 const piece
= document
.createElement("piece");
1068 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1069 C
.AddClass_es(piece
,
1070 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1071 piece
.classList
.add(C
.GetColorClass(color
));
1072 piece
.style
.width
= "100%";
1073 piece
.style
.height
= "100%";
1074 choice
.appendChild(piece
);
1075 choices
.appendChild(choice
);
1082 updateEnlightened() {
1083 this.oldEnlightened
= this.enlightened
;
1084 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1085 // Add pieces positions + all squares reachable by moves (includes Zen):
1086 for (let x
=0; x
<this.size
.x
; x
++) {
1087 for (let y
=0; y
<this.size
.y
; y
++) {
1088 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1090 this.enlightened
[x
][y
] = true;
1091 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1092 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1098 this.enlightEnpassant();
1101 // Include square of the en-passant capturing square:
1102 enlightEnpassant() {
1103 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1104 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1105 for (let step
of steps
) {
1106 const x
= this.epSquare
.x
- step
[0],
1107 y
= this.getY(this.epSquare
.y
- step
[1]);
1109 this.onBoard(x
, y
) &&
1110 this.getColor(x
, y
) == this.playerColor
&&
1111 this.getPieceType(x
, y
) == "p"
1113 this.enlightened
[x
][this.epSquare
.y
] = true;
1119 // Apply diff this.enlightened --> oldEnlightened on board
1120 graphUpdateEnlightened() {
1122 document
.getElementById(this.containerId
).querySelector(".chessboard");
1123 const r
= chessboard
.getBoundingClientRect();
1124 const pieceWidth
= this.getPieceWidth(r
.width
);
1125 for (let x
=0; x
<this.size
.x
; x
++) {
1126 for (let y
=0; y
<this.size
.y
; y
++) {
1127 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1128 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1129 elt
.classList
.add("in-shadow");
1130 if (this.g_pieces
[x
][y
])
1131 this.g_pieces
[x
][y
].classList
.add("hidden");
1133 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1134 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1135 elt
.classList
.remove("in-shadow");
1136 if (this.g_pieces
[x
][y
])
1137 this.g_pieces
[x
][y
].classList
.remove("hidden");
1150 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1154 // Color of thing on square (i,j). '' if square is empty
1156 if (typeof i
== "string")
1157 return i
; //reserves
1158 return this.board
[i
][j
].charAt(0);
1161 static GetColorClass(c
) {
1166 return "other-color"; //unidentified color
1169 // Piece on i,j. '' if square is empty
1171 if (typeof j
== "string")
1172 return j
; //reserves
1173 return this.board
[i
][j
].charAt(1);
1176 // Piece type on square (i,j)
1177 getPieceType(x
, y
, p
) {
1179 p
= this.getPiece(x
, y
);
1180 return this.pieces()[p
].moveas
|| p
;
1185 p
= this.getPiece(x
, y
);
1186 if (!this.options
["cannibal"])
1188 return !!C
.CannibalKings
[p
];
1191 // Get opponent color
1192 static GetOppCol(color
) {
1193 return (color
== "w" ? "b" : "w");
1196 // Is (x,y) on the chessboard?
1198 return (x
>= 0 && x
< this.size
.x
&&
1199 y
>= 0 && y
< this.size
.y
);
1202 // Am I allowed to move thing at square x,y ?
1204 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1207 ////////////////////////
1208 // PIECES SPECIFICATIONS
1210 pieces(color
, x
, y
) {
1211 const pawnShift
= (color
== "w" ? -1 : 1);
1212 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1213 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1219 steps: [[pawnShift
, 0]],
1220 range: (initRank
? 2 : 1)
1225 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1233 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1241 [1, 2], [1, -2], [-1, 2], [-1, -2],
1242 [2, 1], [-2, 1], [2, -1], [-2, -1]
1251 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1259 [0, 1], [0, -1], [1, 0], [-1, 0],
1260 [1, 1], [1, -1], [-1, 1], [-1, -1]
1270 [0, 1], [0, -1], [1, 0], [-1, 0],
1271 [1, 1], [1, -1], [-1, 1], [-1, -1]
1278 '!': {"class": "king-pawn", moveas: "p"},
1279 '#': {"class": "king-rook", moveas: "r"},
1280 '$': {"class": "king-knight", moveas: "n"},
1281 '%': {"class": "king-bishop", moveas: "b"},
1282 '*': {"class": "king-queen", moveas: "q"}
1286 // NOTE: using special symbols to not interfere with variants' pieces codes
1287 static get CannibalKings() {
1298 static get CannibalKingCode() {
1309 //////////////////////////
1310 // MOVES GENERATION UTILS
1312 // For Cylinder: get Y coordinate
1314 if (!this.options
["cylinder"])
1316 let res
= y
% this.size
.y
;
1322 getSegments(curSeg
, segStart
, segEnd
) {
1323 if (curSeg
.length
== 0)
1325 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1326 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1330 getStepSpec(color
, x
, y
, piece
) {
1331 return this.pieces(color
, x
, y
)[piece
|| this.getPieceType(x
, y
)];
1334 // Can thing on square1 capture thing on square2?
1335 canTake([x1
, y1
], [x2
, y2
]) {
1336 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1339 canStepOver(i
, j
, p
) {
1340 // In some variants, objects on boards don't stop movement (Chakart)
1341 return this.board
[i
][j
] == "";
1344 canDrop([c
, p
], [i
, j
]) {
1346 this.board
[i
][j
] == "" &&
1347 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1350 (c
== 'w' && i
< this.size
.x
- 1) ||
1357 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1358 isImmobilized([x
, y
]) {
1359 if (!this.options
["madrasi"])
1361 const color
= this.getColor(x
, y
);
1362 const oppCol
= C
.GetOppCol(color
);
1363 const piece
= this.getPieceType(x
, y
);
1364 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1365 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1366 for (let a
of attacks
) {
1367 outerLoop: for (let step
of a
.steps
) {
1368 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1369 let stepCounter
= 1;
1370 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1371 if (a
.range
<= stepCounter
++)
1374 j
= this.getY(j
+ step
[1]);
1377 this.onBoard(i
, j
) &&
1378 this.getColor(i
, j
) == oppCol
&&
1379 this.getPieceType(i
, j
) == piece
1388 // Stop at the first capture found
1389 atLeastOneCapture(color
) {
1390 const oppCol
= C
.GetOppCol(color
);
1391 const allowed
= (sq1
, sq2
) => {
1393 // NOTE: canTake is reversed for Zen.
1394 // Generally ok because of the symmetry. TODO?
1395 this.canTake(sq1
, sq2
) &&
1397 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1400 for (let i
=0; i
<this.size
.x
; i
++) {
1401 for (let j
=0; j
<this.size
.y
; j
++) {
1402 if (this.getColor(i
, j
) == color
) {
1405 !this.options
["zen"] &&
1406 this.findDestSquares(
1411 segments: this.options
["cylinder"]
1419 this.options
["zen"] &&
1420 this.findCapturesOn(
1424 segments: this.options
["cylinder"]
1439 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1440 const epsilon
= 1e-7; //arbitrary small value
1442 if (this.options
["cylinder"])
1443 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1444 for (let sh
of shifts
) {
1445 const rx
= (x2
- x1
) / step
[0],
1446 ry
= (y2
+ sh
- y1
) / step
[1];
1448 // Zero step but non-zero interval => impossible
1449 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1450 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1451 // Negative number of step (impossible)
1452 (rx
< 0 || ry
< 0) ||
1453 // Not the same number of steps in both directions:
1454 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1458 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1459 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1461 distance
= Math
.round(distance
); //in case of (numerical...)
1462 if (!range
|| range
>= distance
)
1468 ////////////////////
1471 getDropMovesFrom([c
, p
]) {
1472 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1473 // (but not necessarily otherwise: atLeastOneMove() etc)
1474 if (this.reserve
[c
][p
] == 0)
1477 for (let i
=0; i
<this.size
.x
; i
++) {
1478 for (let j
=0; j
<this.size
.y
; j
++) {
1479 if (this.canDrop([c
, p
], [i
, j
])) {
1481 start: {x: c
, y: p
},
1483 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1486 if (this.board
[i
][j
] != "") {
1487 mv
.vanish
.push(new PiPo({
1490 c: this.getColor(i
, j
),
1491 p: this.getPiece(i
, j
)
1501 // All possible moves from selected square
1502 getPotentialMovesFrom([x
, y
], color
) {
1503 if (this.subTurnTeleport
== 2)
1505 if (typeof x
== "string")
1506 return this.getDropMovesFrom([x
, y
]);
1507 if (this.isImmobilized([x
, y
]))
1509 const piece
= this.getPieceType(x
, y
);
1510 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1511 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1512 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1514 this.isKing(0, 0, piece
) && this.hasCastle
&&
1515 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1517 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1519 return this.postProcessPotentialMoves(moves
);
1522 postProcessPotentialMoves(moves
) {
1523 if (moves
.length
== 0)
1525 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1526 const oppCol
= C
.GetOppCol(color
);
1528 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1529 moves
= this.capturePostProcess(moves
, oppCol
);
1531 if (this.options
["atomic"])
1532 this.atomicPostProcess(moves
, color
, oppCol
);
1536 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1538 this.pawnPostProcess(moves
, color
, oppCol
);
1541 if (this.options
["cannibal"] && this.options
["rifle"])
1542 // In this case a rifle-capture from last rank may promote a pawn
1543 this.riflePromotePostProcess(moves
, color
);
1548 capturePostProcess(moves
, oppCol
) {
1549 // Filter out non-capturing moves (not using m.vanish because of
1550 // self captures of Recycle and Teleport).
1551 return moves
.filter(m
=> {
1553 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1554 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1559 atomicPostProcess(moves
, color
, oppCol
) {
1560 moves
.forEach(m
=> {
1562 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1563 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1576 let mNext
= new Move({
1582 for (let step
of steps
) {
1583 let x
= m
.end
.x
+ step
[0];
1584 let y
= this.getY(m
.end
.y
+ step
[1]);
1586 this.onBoard(x
, y
) &&
1587 this.board
[x
][y
] != "" &&
1588 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1589 this.getPieceType(x
, y
) != "p"
1593 p: this.getPiece(x
, y
),
1594 c: this.getColor(x
, y
),
1601 if (!this.options
["rifle"]) {
1602 // The moving piece also vanish
1603 mNext
.vanish
.unshift(
1608 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1617 pawnPostProcess(moves
, color
, oppCol
) {
1619 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1620 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1621 moves
.forEach(m
=> {
1622 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1623 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1624 const promotionOk
= (
1626 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1629 return; //nothing to do
1630 if (this.options
["pawnfall"]) {
1634 let finalPieces
= ["p"];
1636 this.options
["cannibal"] &&
1637 this.board
[x2
][y2
] != "" &&
1638 this.getColor(x2
, y2
) == oppCol
1640 finalPieces
= [this.getPieceType(x2
, y2
)];
1643 finalPieces
= this.pawnPromotions
;
1644 m
.appear
[0].p
= finalPieces
[0];
1645 if (initPiece
== "!") //cannibal king-pawn
1646 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1647 for (let i
=1; i
<finalPieces
.length
; i
++) {
1648 const piece
= finalPieces
[i
];
1651 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1653 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1654 moreMoves
.push(newMove
);
1657 Array
.prototype.push
.apply(moves
, moreMoves
);
1660 riflePromotePostProcess(moves
, color
) {
1661 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1663 moves
.forEach(m
=> {
1665 m
.start
.x
== lastRank
&&
1666 m
.appear
.length
>= 1 &&
1667 m
.appear
[0].p
== "p" &&
1668 m
.appear
[0].x
== m
.start
.x
&&
1669 m
.appear
[0].y
== m
.start
.y
1671 m
.appear
[0].p
= this.pawnPromotions
[0];
1672 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1673 let newMv
= JSON
.parse(JSON
.stringify(m
));
1674 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1675 newMoves
.push(newMv
);
1679 Array
.prototype.push
.apply(moves
, newMoves
);
1682 // Generic method to find possible moves of "sliding or jumping" pieces
1683 getPotentialMovesOf(piece
, [x
, y
]) {
1684 const color
= this.getColor(x
, y
);
1685 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1687 if (stepSpec
.attack
) {
1688 squares
= this.findDestSquares(
1692 segments: this.options
["cylinder"],
1695 ([i1
, j1
], [i2
, j2
]) => {
1697 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1698 this.canTake([i1
, j1
], [i2
, j2
])
1703 const noSpecials
= this.findDestSquares(
1706 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1707 segments: this.options
["cylinder"],
1711 Array
.prototype.push
.apply(squares
, noSpecials
);
1712 if (this.options
["zen"]) {
1713 let zenCaptures
= this.findCapturesOn(
1715 {}, //byCol: default is ok
1716 ([i1
, j1
], [i2
, j2
]) =>
1717 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1719 // Technical step: segments (if any) are reversed
1720 if (this.options
["cylinder"]) {
1721 zenCaptures
.forEach(z
=> {
1722 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1725 Array
.prototype.push
.apply(squares
, zenCaptures
);
1728 this.options
["recycle"] ||
1729 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1731 const selfCaptures
= this.findDestSquares(
1735 segments: this.options
["cylinder"],
1738 ([i1
, j1
], [i2
, j2
]) =>
1739 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1741 Array
.prototype.push
.apply(squares
, selfCaptures
);
1743 return squares
.map(s
=> {
1744 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1745 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1746 mv
.segments
= s
.segments
;
1751 findDestSquares([x
, y
], o
, allowed
) {
1753 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1754 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1756 // Next 3 for Cylinder mode: (unused if !o.segments)
1760 const addSquare
= ([i
, j
]) => {
1761 let elt
= {sq: [i
, j
]};
1763 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1766 const exploreSteps
= (stepArray
) => {
1767 for (let s
of stepArray
) {
1768 outerLoop: for (let step
of s
.steps
) {
1773 let [i
, j
] = [x
, y
];
1774 let stepCounter
= 0;
1776 this.onBoard(i
, j
) &&
1777 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1779 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1780 explored
[i
+ "." + j
] = true;
1783 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1785 if (o
.one
&& !o
.attackOnly
)
1788 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1789 if (o
.captureTarget
)
1793 if (s
.range
<= stepCounter
++)
1795 const oldIJ
= [i
, j
];
1797 j
= this.getY(j
+ step
[1]);
1798 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1799 // Boundary between segments (cylinder mode)
1800 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1804 if (!this.onBoard(i
, j
))
1806 const pieceIJ
= this.getPieceType(i
, j
);
1807 if (!explored
[i
+ "." + j
]) {
1808 explored
[i
+ "." + j
] = true;
1809 if (allowed([x
, y
], [i
, j
])) {
1810 if (o
.one
&& !o
.moveOnly
)
1813 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1816 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1824 return undefined; //default, but let's explicit it
1826 if (o
.captureTarget
)
1827 return exploreSteps(o
.captureSteps
)
1830 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1832 if (!o
.attackOnly
|| !stepSpec
.attack
)
1833 outOne
= exploreSteps(stepSpec
.moves
);
1834 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1835 o
.attackOnly
= true; //ok because o is always a temporary object
1836 outOne
= exploreSteps(stepSpec
.attack
);
1838 return (o
.one
? outOne : res
);
1842 // Search for enemy (or not) pieces attacking [x, y]
1843 findCapturesOn([x
, y
], o
, allowed
) {
1845 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1847 for (let i
=0; i
<this.size
.x
; i
++) {
1848 for (let j
=0; j
<this.size
.y
; j
++) {
1849 const colIJ
= this.getColor(i
, j
);
1851 this.board
[i
][j
] != "" &&
1852 o
.byCol
.includes(colIJ
) &&
1853 !this.isImmobilized([i
, j
])
1855 const apparentPiece
= this.getPiece(i
, j
);
1856 // Quick check: does this potential attacker target x,y ?
1857 if (this.canStepOver(x
, y
, apparentPiece
))
1859 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1860 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1861 for (let a
of attacks
) {
1862 for (let s
of a
.steps
) {
1863 // Quick check: if step isn't compatible, don't even try
1864 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1866 // Finally verify that nothing stand in-between
1867 const out
= this.findDestSquares(
1870 captureTarget: [x
, y
],
1871 captureSteps: [{steps: [s
], range: a
.range
}],
1872 segments: o
.segments
,
1874 one: false //one and captureTarget are mutually exclusive
1888 return (o
.one
? false : res
);
1891 // Build a regular move from its initial and destination squares.
1892 // tr: transformation
1893 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1894 const initColor
= this.getColor(sx
, sy
);
1895 const initPiece
= this.getPiece(sx
, sy
);
1896 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1900 start: {x: sx
, y: sy
},
1904 !this.options
["rifle"] ||
1905 this.board
[ex
][ey
] == "" ||
1906 destColor
== initColor
//Recycle, Teleport
1912 c: !!tr
? tr
.c : initColor
,
1913 p: !!tr
? tr
.p : initPiece
1925 if (this.board
[ex
][ey
] != "") {
1930 c: this.getColor(ex
, ey
),
1931 p: this.getPiece(ex
, ey
)
1934 if (this.options
["cannibal"] && destColor
!= initColor
) {
1935 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1936 let trPiece
= mv
.vanish
[lastIdx
].p
;
1937 if (this.isKing(sx
, sy
))
1938 trPiece
= C
.CannibalKingCode
[trPiece
];
1939 if (mv
.appear
.length
>= 1)
1940 mv
.appear
[0].p
= trPiece
;
1941 else if (this.options
["rifle"]) {
1964 // En-passant square, if any
1965 getEpSquare(moveOrSquare
) {
1966 if (typeof moveOrSquare
=== "string") {
1967 const square
= moveOrSquare
;
1970 return C
.SquareToCoords(square
);
1972 // Argument is a move:
1973 const move = moveOrSquare
;
1974 const s
= move.start
,
1978 Math
.abs(s
.x
- e
.x
) == 2 &&
1979 // Next conditions for variants like Atomic or Rifle, Recycle...
1981 move.appear
.length
> 0 &&
1982 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1986 move.vanish
.length
> 0 &&
1987 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1995 return undefined; //default
1998 // Special case of en-passant captures: treated separately
1999 getEnpassantCaptures([x
, y
]) {
2000 const color
= this.getColor(x
, y
);
2001 const shiftX
= (color
== 'w' ? -1 : 1);
2002 const oppCol
= C
.GetOppCol(color
);
2005 this.epSquare
.x
== x
+ shiftX
&&
2006 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2007 // Doublemove (and Progressive?) guards:
2008 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2009 this.getColor(x
, this.epSquare
.y
) == oppCol
2011 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2012 this.board
[epx
][epy
] = oppCol
+ 'p';
2013 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2014 this.board
[epx
][epy
] = "";
2015 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2016 enpassantMove
.vanish
[lastIdx
].x
= x
;
2017 return [enpassantMove
];
2022 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2023 const c
= this.getColor(x
, y
);
2026 const oppCol
= C
.GetOppCol(c
);
2030 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2031 const castlingKing
= this.getPiece(x
, y
);
2032 castlingCheck: for (
2035 castleSide
++ //large, then small
2037 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2039 // If this code is reached, rook and king are on initial position
2041 // NOTE: in some variants this is not a rook
2042 const rookPos
= this.castleFlags
[c
][castleSide
];
2043 const castlingPiece
= this.getPiece(x
, rookPos
);
2045 this.board
[x
][rookPos
] == "" ||
2046 this.getColor(x
, rookPos
) != c
||
2047 (castleWith
&& !castleWith
.includes(castlingPiece
))
2049 // Rook is not here, or changed color (see Benedict)
2052 // Nothing on the path of the king ? (and no checks)
2053 const finDist
= finalSquares
[castleSide
][0] - y
;
2054 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2058 // NOTE: next weird test because underCheck() verification
2059 // will be executed in filterValid() later.
2061 i
!= finalSquares
[castleSide
][0] &&
2062 this.underCheck([x
, i
], oppCol
)
2066 this.board
[x
][i
] != "" &&
2067 // NOTE: next check is enough, because of chessboard constraints
2068 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2071 continue castlingCheck
;
2074 } while (i
!= finalSquares
[castleSide
][0]);
2075 // Nothing on the path to the rook?
2076 step
= (castleSide
== 0 ? -1 : 1);
2077 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2078 if (this.board
[x
][i
] != "")
2079 continue castlingCheck
;
2082 // Nothing on final squares, except maybe king and castling rook?
2083 for (i
= 0; i
< 2; i
++) {
2085 finalSquares
[castleSide
][i
] != rookPos
&&
2086 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2088 finalSquares
[castleSide
][i
] != y
||
2089 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2092 continue castlingCheck
;
2096 // If this code is reached, castle is potentially valid
2102 y: finalSquares
[castleSide
][0],
2108 y: finalSquares
[castleSide
][1],
2114 // King might be initially disguised (Titan...)
2115 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2116 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2119 Math
.abs(y
- rookPos
) <= 2
2120 ? {x: x
, y: rookPos
}
2121 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2129 ////////////////////
2132 // Is piece (or square) at given position attacked by "oppCol" ?
2133 underAttack([x
, y
], oppCol
) {
2134 // An empty square is considered as king,
2135 // since it's used only in getCastleMoves (TODO?)
2136 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2139 (!this.options
["zen"] || king
) &&
2140 this.findCapturesOn(
2144 segments: this.options
["cylinder"],
2151 (!!this.options
["zen"] && !king
) &&
2152 this.findDestSquares(
2156 segments: this.options
["cylinder"],
2159 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2165 underCheck(square_s
, oppCol
) {
2166 if (this.options
["taking"] || this.options
["dark"])
2168 if (!Array
.isArray(square_s
))
2169 square_s
= [square_s
];
2170 return square_s
.some(sq
=> this.underAttack(sq
, oppCol
));
2173 // Scan board for king(s)
2174 searchKingPos(color
) {
2176 for (let i
=0; i
< this.size
.x
; i
++) {
2177 for (let j
=0; j
< this.size
.y
; j
++) {
2178 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2185 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2186 filterValid(moves
, color
) {
2189 const oppCol
= C
.GetOppCol(color
);
2190 let kingPos
= this.searchKingPos(color
);
2191 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2192 return moves
.filter(m
=> {
2193 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2194 if (!filtered
[key
]) {
2195 this.playOnBoard(m
);
2196 let newKingPP
= null,
2198 res
= true; //a priori valid
2199 const oldKingPP
= m
.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2201 // Search king in appear array:
2203 m
.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2205 sqIdx
= kingPos
.findIndex(kp
=> kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
[.y
);
2206 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2209 res
= false; //king vanished
2211 res
&&= !this.underCheck(square_s
, oppCol
);
2212 if (oldKingPP
&& newKingPP
)
2213 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2214 this.undoOnBoard(m
);
2215 filtered
[key
] = res
;
2218 return filtered
[key
];
2225 // Apply a move on board
2227 for (let psq
of move.vanish
)
2228 this.board
[psq
.x
][psq
.y
] = "";
2229 for (let psq
of move.appear
)
2230 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2232 // Un-apply the played move
2234 for (let psq
of move.appear
)
2235 this.board
[psq
.x
][psq
.y
] = "";
2236 for (let psq
of move.vanish
)
2237 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2240 updateCastleFlags(move) {
2241 // Update castling flags if start or arrive from/at rook/king locations
2242 move.appear
.concat(move.vanish
).forEach(psq
=> {
2243 if (this.isKing(0, 0, psq
.p
))
2244 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2245 // NOTE: not "else if" because king can capture enemy rook...
2249 else if (psq
.x
== this.size
.x
- 1)
2252 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2254 this.castleFlags
[c
][fidx
] = this.size
.y
;
2262 // If flags already off, no need to re-check:
2263 Object
.values(this.castleFlags
).some(cvals
=>
2264 cvals
.some(val
=> val
< this.size
.y
))
2266 this.updateCastleFlags(move);
2268 if (this.options
["crazyhouse"]) {
2269 move.vanish
.forEach(v
=> {
2270 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2271 if (this.ispawn
[square
])
2272 delete this.ispawn
[square
];
2274 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2275 // Assumption: something is moving
2276 const initSquare
= C
.CoordsToSquare(move.start
);
2277 const destSquare
= C
.CoordsToSquare(move.end
);
2279 this.ispawn
[initSquare
] ||
2280 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2282 this.ispawn
[destSquare
] = true;
2285 this.ispawn
[destSquare
] &&
2286 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2288 move.vanish
[1].p
= 'p';
2289 delete this.ispawn
[destSquare
];
2293 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2296 // Warning; atomic pawn removal isn't a capture
2297 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2299 const color
= this.turn
;
2300 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2301 // Something appears = dropped on board (some exceptions, Chakart...)
2302 if (move.appear
[i
].c
== color
) {
2303 const piece
= move.appear
[i
].p
;
2304 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2307 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2308 // Something vanish: add to reserve except if recycle & opponent
2310 this.options
["crazyhouse"] ||
2311 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2313 const piece
= move.vanish
[i
].p
;
2314 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2322 if (this.hasEnpassant
)
2323 this.epSquare
= this.getEpSquare(move);
2324 this.playOnBoard(move);
2325 this.postPlay(move);
2329 const color
= this.turn
;
2330 if (this.options
["dark"])
2331 this.updateEnlightened();
2332 if (this.options
["teleport"]) {
2334 this.subTurnTeleport
== 1 &&
2335 move.vanish
.length
> move.appear
.length
&&
2336 move.vanish
[1].c
== color
2338 const v
= move.vanish
[move.vanish
.length
- 1];
2339 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2340 this.subTurnTeleport
= 2;
2343 this.subTurnTeleport
= 1;
2344 this.captured
= null;
2346 if (this.isLastMove(move)) {
2347 this.turn
= C
.GetOppCol(color
);
2351 else if (!move.next
)
2358 const color
= this.turn
;
2359 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2360 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, color
))
2364 !this.options
["balance"] ||
2365 ![1, 2].includes(this.movesCount
) ||
2370 !this.options
["doublemove"] ||
2371 this.movesCount
== 0 ||
2376 !this.options
["progressive"] ||
2377 this.subTurn
== this.movesCount
+ 1
2382 // "Stop at the first move found"
2383 atLeastOneMove(color
) {
2384 for (let i
= 0; i
< this.size
.x
; i
++) {
2385 for (let j
= 0; j
< this.size
.y
; j
++) {
2386 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2387 // NOTE: in fact searching for all potential moves from i,j.
2388 // I don't believe this is an issue, for now at least.
2389 const moves
= this.getPotentialMovesFrom([i
, j
]);
2390 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2395 if (this.hasReserve
&& this.reserve
[color
]) {
2396 for (let p
of Object
.keys(this.reserve
[color
])) {
2397 const moves
= this.getDropMovesFrom([color
, p
]);
2398 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2405 // What is the score ? (Interesting if game is over)
2406 getCurrentScore(move) {
2407 const color
= this.turn
;
2408 const oppCol
= C
.GetOppCol(color
);
2410 [color
]: this.searchKingPos(color
),
2411 [oppCol
]: this.searchKingPos(oppCol
)
2413 if (kingPos
[color
].length
== 0 && kingPos
[oppCol
].length
== 0)
2415 if (kingPos
[color
].length
== 0)
2416 return (color
== "w" ? "0-1" : "1-0");
2417 if (kingPos
[oppCol
].length
== 0)
2418 return (color
== "w" ? "1-0" : "0-1");
2419 if (this.atLeastOneMove(color
))
2421 // No valid move: stalemate or checkmate?
2422 if (!this.underCheck(kingPos
[color
], oppCol
))
2425 return (color
== "w" ? "0-1" : "1-0");
2428 playVisual(move, r
) {
2429 move.vanish
.forEach(v
=> {
2430 this.g_pieces
[v
.x
][v
.y
].remove();
2431 this.g_pieces
[v
.x
][v
.y
] = null;
2434 document
.getElementById(this.containerId
).querySelector(".chessboard");
2436 r
= chessboard
.getBoundingClientRect();
2437 const pieceWidth
= this.getPieceWidth(r
.width
);
2438 move.appear
.forEach(a
=> {
2439 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2440 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2441 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2442 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2443 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2444 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2445 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2446 // Translate coordinates to use chessboard as reference:
2447 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2448 `translate(${ip - r.x}px,${jp - r.y}px)`;
2449 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2450 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2451 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2453 if (this.options
["dark"])
2454 this.graphUpdateEnlightened();
2457 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2458 buildMoveStack(move, r
) {
2459 this.moveStack
.push(move);
2460 this.computeNextMove(move);
2462 const newTurn
= this.turn
;
2463 if (this.moveStack
.length
== 1)
2464 this.playVisual(move, r
);
2468 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2470 this.buildMoveStack(move.next
, r
);
2473 if (this.moveStack
.length
== 1) {
2474 // Usual case (one normal move)
2475 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2479 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2480 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2481 this.playReceivedMove(this.moveStack
.slice(1), () => {
2482 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2489 // Implemented in variants using (automatic) moveStack
2490 computeNextMove(move) {}
2492 animateMoving(start
, end
, drag
, segments
, cb
) {
2493 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2494 // NOTE: cloning often not required, but light enough, and simpler
2495 let movingPiece
= initPiece
.cloneNode();
2496 initPiece
.style
.opacity
= "0";
2498 document
.getElementById(this.containerId
)
2499 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2500 if (typeof start
.x
== "string") {
2501 // Need to bound width/height (was 100% for reserve pieces)
2502 const pieceWidth
= this.getPieceWidth(r
.width
);
2503 movingPiece
.style
.width
= pieceWidth
+ "px";
2504 movingPiece
.style
.height
= pieceWidth
+ "px";
2506 const maxDist
= this.getMaxDistance(r
);
2507 const apparentColor
= this.getColor(start
.x
, start
.y
);
2508 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2510 const startCode
= this.getPiece(start
.x
, start
.y
);
2511 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2512 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2513 if (apparentColor
!= drag
.c
) {
2514 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2515 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2518 container
.appendChild(movingPiece
);
2519 const animateSegment
= (index
, cb
) => {
2520 // NOTE: move.drag could be generalized per-segment (usage?)
2521 const [i1
, j1
] = segments
[index
][0];
2522 const [i2
, j2
] = segments
[index
][1];
2523 const dep
= this.getPixelPosition(i1
, j1
, r
);
2524 const arr
= this.getPixelPosition(i2
, j2
, r
);
2525 movingPiece
.style
.transitionDuration
= "0s";
2526 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2528 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2529 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2530 // TODO: unclear why we need this new delay below:
2532 movingPiece
.style
.transitionDuration
= duration
+ "s";
2533 // movingPiece is child of container: no need to adjust coordinates
2534 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2535 setTimeout(cb
, duration
* 1000);
2539 const animateSegmentCallback
= () => {
2540 if (index
< segments
.length
)
2541 animateSegment(index
++, animateSegmentCallback
);
2543 movingPiece
.remove();
2544 initPiece
.style
.opacity
= "1";
2548 animateSegmentCallback();
2551 // Input array of objects with at least fields x,y (e.g. PiPo)
2552 animateFading(arr
, cb
) {
2553 const animLength
= 350; //TODO: 350ms? More? Less?
2555 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2556 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2557 fadingPiece
.style
.opacity
= "0";
2559 setTimeout(cb
, animLength
);
2562 animate(move, callback
) {
2563 if (this.noAnimate
|| move.noAnimate
) {
2567 let segments
= move.segments
;
2569 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2570 let targetObj
= new TargetObj(callback
);
2571 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2573 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2574 () => targetObj
.increment());
2576 if (move.vanish
.length
> move.appear
.length
) {
2577 const arr
= move.vanish
.slice(move.appear
.length
)
2578 // Ignore disappearing pieces hidden by some appearing ones:
2579 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2580 if (arr
.length
> 0) {
2582 this.animateFading(arr
, () => targetObj
.increment());
2586 this.customAnimate(move, segments
, () => targetObj
.increment());
2587 if (targetObj
.target
== 0)
2591 // Potential other animations (e.g. for Suction variant)
2592 customAnimate(move, segments
, cb
) {
2593 return 0; //nb of targets
2596 playReceivedMove(moves
, callback
) {
2597 const launchAnimation
= () => {
2598 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2599 const animateRec
= i
=> {
2600 this.animate(moves
[i
], () => {
2601 this.play(moves
[i
]);
2602 this.playVisual(moves
[i
], r
);
2603 if (i
< moves
.length
- 1)
2604 setTimeout(() => animateRec(i
+1), 300);
2611 // Delay if user wasn't focused:
2612 const checkDisplayThenAnimate
= (delay
) => {
2613 if (container
.style
.display
== "none") {
2614 alert("New move! Let's go back to game...");
2615 document
.getElementById("gameInfos").style
.display
= "none";
2616 container
.style
.display
= "block";
2617 setTimeout(launchAnimation
, 700);
2620 setTimeout(launchAnimation
, delay
|| 0);
2622 let container
= document
.getElementById(this.containerId
);
2623 if (document
.hidden
) {
2624 document
.onvisibilitychange
= () => {
2625 document
.onvisibilitychange
= undefined;
2626 checkDisplayThenAnimate(700);
2630 checkDisplayThenAnimate();