8eed3d35250e521b0a6cb78d4a85d67222c8341d
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 reveal moves only after both players played
124 // Some variants use click infos:
126 if (typeof coords
.x
!= "number")
127 return null; //click on reserves
129 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
130 this.board
[coords
.x
][coords
.y
] == ""
133 start: {x: this.captured
.x
, y: this.captured
.y
},
144 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
153 // 3a --> {x:3, y:10}
154 static SquareToCoords(sq
) {
155 return ArrayFun
.toObject(["x", "y"],
156 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
159 // {x:11, y:12} --> bc
160 static CoordsToSquare(cd
) {
161 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
165 if (typeof cd
.x
== "number") {
167 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
171 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
174 idToCoords(targetId
) {
176 return null; //outside page, maybe...
177 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
179 idParts
.length
< 2 ||
180 idParts
[0] != this.containerId
||
181 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
185 const squares
= idParts
[1].split('-');
186 if (squares
[0] == "sq")
187 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
188 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
189 return {x: squares
[1], y: squares
[2]};
195 // Turn "wb" into "B" (for FEN)
197 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
200 // Turn "p" into "bp" (for board)
202 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
205 genRandInitFen(seed
) {
206 Random
.setSeed(seed
); //may be unused
207 let baseFen
= this.genRandInitBaseFen();
208 baseFen
.o
= Object
.assign({init: true}, baseFen
.o
);
209 const parts
= this.getPartFen(baseFen
.o
);
212 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
216 // Setup the initial random-or-not (asymmetric-or-not) position
217 genRandInitBaseFen() {
218 let fen
, flags
= "0707";
219 if (!this.options
.randomness
)
221 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
225 let pieces
= {w: new Array(8), b: new Array(8)};
227 // Shuffle pieces on first (and last rank if randomness == 2)
228 for (let c
of ["w", "b"]) {
229 if (c
== 'b' && this.options
.randomness
== 1) {
230 pieces
['b'] = pieces
['w'];
234 let positions
= ArrayFun
.range(8);
235 // Get random squares for bishops
236 let randIndex
= 2 * Random
.randInt(4);
237 const bishop1Pos
= positions
[randIndex
];
238 // The second bishop must be on a square of different color
239 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
240 const bishop2Pos
= positions
[randIndex_tmp
];
241 // Remove chosen squares
242 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
243 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
244 // Get random squares for knights
245 randIndex
= Random
.randInt(6);
246 const knight1Pos
= positions
[randIndex
];
247 positions
.splice(randIndex
, 1);
248 randIndex
= Random
.randInt(5);
249 const knight2Pos
= positions
[randIndex
];
250 positions
.splice(randIndex
, 1);
251 // Get random square for queen
252 randIndex
= Random
.randInt(4);
253 const queenPos
= positions
[randIndex
];
254 positions
.splice(randIndex
, 1);
255 // Rooks and king positions are now fixed,
256 // because of the ordering rook-king-rook
257 const rook1Pos
= positions
[0];
258 const kingPos
= positions
[1];
259 const rook2Pos
= positions
[2];
260 // Finally put the shuffled pieces in the board array
261 pieces
[c
][rook1Pos
] = "r";
262 pieces
[c
][knight1Pos
] = "n";
263 pieces
[c
][bishop1Pos
] = "b";
264 pieces
[c
][queenPos
] = "q";
265 pieces
[c
][kingPos
] = "k";
266 pieces
[c
][bishop2Pos
] = "b";
267 pieces
[c
][knight2Pos
] = "n";
268 pieces
[c
][rook2Pos
] = "r";
269 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
272 pieces
["b"].join("") +
273 "/pppppppp/8/8/8/8/PPPPPPPP/" +
274 pieces
["w"].join("").toUpperCase() +
278 return { fen: fen
, o: {flags: flags
} };
281 // "Parse" FEN: just return untransformed string data
283 const fenParts
= fen
.split(" ");
285 position: fenParts
[0],
287 movesCount: fenParts
[2]
289 if (fenParts
.length
> 3)
290 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
294 // Return current fen (game state)
296 const parts
= this.getPartFen({});
299 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
304 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
310 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
311 if (this.hasEnpassant
)
312 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
313 if (this.hasReserveFen
)
314 parts
["reserve"] = this.getReserveFen(o
);
315 if (this.options
["crazyhouse"])
316 parts
["ispawn"] = this.getIspawnFen(o
);
320 static FenEmptySquares(count
) {
321 // if more than 9 consecutive free spaces, break the integer,
322 // otherwise FEN parsing will fail.
325 // Most boards of size < 18:
327 return "9" + (count
- 9);
329 return "99" + (count
- 18);
332 // Position part of the FEN string
335 for (let i
= 0; i
< this.size
.y
; i
++) {
337 for (let j
= 0; j
< this.size
.x
; j
++) {
338 if (this.board
[i
][j
] == "")
341 if (emptyCount
> 0) {
342 // Add empty squares in-between
343 position
+= C
.FenEmptySquares(emptyCount
);
346 position
+= this.board2fen(this.board
[i
][j
]);
351 position
+= C
.FenEmptySquares(emptyCount
);
352 if (i
< this.size
.y
- 1)
353 position
+= "/"; //separate rows
358 // Flags part of the FEN string
360 return ["w", "b"].map(c
=> {
361 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
365 // Enpassant part of the FEN string
369 return C
.CoordsToSquare(this.epSquare
);
374 return "000000000000";
376 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
382 // NOTE: cannot merge because this.ispawn doesn't exist yet
384 const squares
= Object
.keys(this.ispawn
);
385 if (squares
.length
== 0)
387 return squares
.join(",");
390 // Set flags from fen (castle: white a,h then black a,h)
393 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
394 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
402 this.options
= o
.options
;
403 // Fill missing options (always the case if random challenge)
404 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
405 if (this.options
[opt
.variable
] === undefined)
406 this.options
[opt
.variable
] = opt
.defaut
;
409 // This object will be used only for initial FEN generation
413 this.playerColor
= o
.color
;
414 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
415 this.containerId
= o
.element
;
416 this.isDiagram
= o
.diagram
;
417 this.marks
= o
.marks
;
421 o
.fen
= this.genRandInitFen(o
.seed
);
422 this.re_initFromFen(o
.fen
);
423 this.graphicalInit();
426 re_initFromFen(fen
, oldBoard
) {
427 const fenParsed
= this.parseFen(fen
);
428 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
429 this.turn
= fenParsed
.turn
;
430 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
431 this.setOtherVariables(fenParsed
);
434 // Turn position fen into double array ["wb","wp","bk",...]
436 const rows
= position
.split("/");
437 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
438 for (let i
= 0; i
< rows
.length
; i
++) {
440 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
441 const character
= rows
[i
][indexInRow
];
442 const num
= parseInt(character
, 10);
443 // If num is a number, just shift j:
446 // Else: something at position i,j
448 board
[i
][j
++] = this.fen2board(character
);
454 // Some additional variables from FEN (variant dependant)
455 setOtherVariables(fenParsed
) {
456 // Set flags and enpassant:
458 this.setFlags(fenParsed
.flags
);
459 if (this.hasEnpassant
)
460 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
461 if (this.hasReserve
&& !this.isDiagram
)
462 this.initReserves(fenParsed
.reserve
);
463 if (this.options
["crazyhouse"])
464 this.initIspawn(fenParsed
.ispawn
);
465 if (this.options
["teleport"]) {
466 this.subTurnTeleport
= 1;
467 this.captured
= null;
469 if (this.options
["dark"]) {
470 // Setup enlightened: squares reachable by player side
471 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
472 this.updateEnlightened();
474 this.subTurn
= 1; //may be unused
475 if (!this.moveStack
) //avoid resetting (unwanted)
479 // ordering as in pieces() p,r,n,b,q,k
480 initReserves(reserveStr
) {
481 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
482 this.reserve
= { w: {}, b: {} };
483 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
484 const L
= pieceName
.length
;
485 for (let i
of ArrayFun
.range(2 * L
)) {
487 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
489 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
493 initIspawn(ispawnStr
) {
494 if (ispawnStr
!= "-")
495 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
503 getPieceWidth(rwidth
) {
504 return (rwidth
/ this.size
.y
);
507 getReserveSquareSize(rwidth
, nbR
) {
508 const sqSize
= this.getPieceWidth(rwidth
);
509 return Math
.min(sqSize
, rwidth
/ nbR
);
512 getReserveNumId(color
, piece
) {
513 return `${this.containerId}|rnum-${color}${piece}`;
516 getNbReservePieces(color
) {
518 Object
.values(this.reserve
[color
]).reduce(
519 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
523 getRankInReserve(c
, p
) {
524 const pieces
= Object
.keys(this.pieces());
525 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
526 let toTest
= pieces
.slice(0, lastIndex
);
527 return toTest
.reduce(
528 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
531 static AddClass_es(elt
, class_es
) {
532 if (!Array
.isArray(class_es
))
533 class_es
= [class_es
];
534 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
537 static RemoveClass_es(elt
, class_es
) {
538 if (!Array
.isArray(class_es
))
539 class_es
= [class_es
];
540 class_es
.forEach(cl
=> elt
.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 if (!this.onBoard(i
, j
))
630 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
631 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
632 let classes
= this.getSquareColorClass(ii
, jj
);
633 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
634 classes
+= " in-shadow";
635 // NOTE: x / y reversed because coordinates system is reversed.
639 id="${this.coordsToId({x: ii, y: jj})}"
653 document
.getElementById(this.containerId
).querySelector(".chessboard");
655 r
= chessboard
.getBoundingClientRect();
656 const pieceWidth
= this.getPieceWidth(r
.width
);
657 const addPiece
= (i
, j
, arrName
, classes
) => {
658 this[arrName
][i
][j
] = document
.createElement("piece");
659 C
.AddClass_es(this[arrName
][i
][j
], classes
);
660 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
661 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
662 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
663 // Translate coordinates to use chessboard as reference:
664 this[arrName
][i
][j
].style
.transform
=
665 `translate(${ip - r.x}px,${jp - r.y}px)`;
666 chessboard
.appendChild(this[arrName
][i
][j
]);
668 const conditionalReset
= (arrName
) => {
670 // Refreshing: delete old pieces first. This isn't necessary,
671 // but simpler (this method isn't called many times)
672 for (let i
=0; i
<this.size
.x
; i
++) {
673 for (let j
=0; j
<this.size
.y
; j
++) {
674 if (this[arrName
][i
][j
]) {
675 this[arrName
][i
][j
].remove();
676 this[arrName
][i
][j
] = null;
682 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
683 if (arrName
== "d_pieces")
684 this.marks
.forEach(([i
, j
]) => addPiece(i
, j
, arrName
, "mark"));
687 conditionalReset("d_pieces");
688 conditionalReset("g_pieces");
689 for (let i
=0; i
< this.size
.x
; i
++) {
690 for (let j
=0; j
< this.size
.y
; j
++) {
691 if (this.board
[i
][j
] != "") {
692 const color
= this.getColor(i
, j
);
693 const piece
= this.getPiece(i
, j
);
694 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
695 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
696 if (this.enlightened
&& !this.enlightened
[i
][j
])
697 this.g_pieces
[i
][j
].classList
.add("hidden");
699 if (this.marks
&& this.d_pieces
[i
][j
]) {
700 let classes
= ["mark"];
701 if (this.board
[i
][j
] != "")
702 classes
.push("transparent");
703 addPiece(i
, j
, "d_pieces", classes
);
707 if (this.hasReserve
&& !this.isDiagram
)
708 this.re_drawReserve(['w', 'b'], r
);
711 // NOTE: assume this.reserve != null
712 re_drawReserve(colors
, r
) {
714 // Remove (old) reserve pieces
715 for (let c
of colors
) {
716 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
717 this.r_pieces
[c
][p
].remove();
718 delete this.r_pieces
[c
][p
];
719 const numId
= this.getReserveNumId(c
, p
);
720 document
.getElementById(numId
).remove();
725 this.r_pieces
= { w: {}, b: {} };
726 let container
= document
.getElementById(this.containerId
);
728 r
= container
.querySelector(".chessboard").getBoundingClientRect();
729 for (let c
of colors
) {
730 let reservesDiv
= document
.getElementById("reserves_" + c
);
732 reservesDiv
.remove();
733 if (!this.reserve
[c
])
735 const nbR
= this.getNbReservePieces(c
);
738 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
740 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
741 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
742 let rcontainer
= document
.createElement("div");
743 rcontainer
.id
= "reserves_" + c
;
744 rcontainer
.classList
.add("reserves");
745 rcontainer
.style
.left
= i0
+ "px";
746 rcontainer
.style
.top
= j0
+ "px";
747 // NOTE: +1 fix display bug on Firefox at least
748 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
749 rcontainer
.style
.height
= sqResSize
+ "px";
750 container
.appendChild(rcontainer
);
751 for (let p
of Object
.keys(this.reserve
[c
])) {
752 if (this.reserve
[c
][p
] == 0)
754 let r_cell
= document
.createElement("div");
755 r_cell
.id
= this.coordsToId({x: c
, y: p
});
756 r_cell
.classList
.add("reserve-cell");
757 r_cell
.style
.width
= sqResSize
+ "px";
758 r_cell
.style
.height
= sqResSize
+ "px";
759 rcontainer
.appendChild(r_cell
);
760 let piece
= document
.createElement("piece");
761 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
762 piece
.classList
.add(C
.GetColorClass(c
));
763 piece
.style
.width
= "100%";
764 piece
.style
.height
= "100%";
765 this.r_pieces
[c
][p
] = piece
;
766 r_cell
.appendChild(piece
);
767 let number
= document
.createElement("div");
768 number
.textContent
= this.reserve
[c
][p
];
769 number
.classList
.add("reserve-num");
770 number
.id
= this.getReserveNumId(c
, p
);
771 const fontSize
= "1.3em";
772 number
.style
.fontSize
= fontSize
;
773 number
.style
.fontSize
= fontSize
;
774 r_cell
.appendChild(number
);
780 updateReserve(color
, piece
, count
) {
781 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
782 piece
= "k"; //capturing cannibal king: back to king form
783 const oldCount
= this.reserve
[color
][piece
];
784 this.reserve
[color
][piece
] = count
;
785 // Redrawing is much easier if count==0
786 if ([oldCount
, count
].includes(0))
787 this.re_drawReserve([color
]);
789 const numId
= this.getReserveNumId(color
, piece
);
790 document
.getElementById(numId
).textContent
= count
;
794 // Resize board: no need to destroy/recreate pieces
796 const container
= document
.getElementById(this.containerId
);
797 let chessboard
= container
.querySelector(".chessboard");
798 const rc
= container
.getBoundingClientRect(),
799 r
= chessboard
.getBoundingClientRect();
800 const multFact
= (mode
== "up" ? 1.05 : 0.95);
801 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
803 const vRatio
= this.size
.ratio
|| 1;
804 if (newWidth
> rc
.width
) {
806 newHeight
= newWidth
/ vRatio
;
808 if (newHeight
> rc
.height
) {
809 newHeight
= rc
.height
;
810 newWidth
= newHeight
* vRatio
;
812 chessboard
.style
.width
= newWidth
+ "px";
813 chessboard
.style
.height
= newHeight
+ "px";
814 const newX
= (rc
.width
- newWidth
) / 2;
815 chessboard
.style
.left
= newX
+ "px";
816 const newY
= (rc
.height
- newHeight
) / 2;
817 chessboard
.style
.top
= newY
+ "px";
818 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
819 const pieceWidth
= this.getPieceWidth(newWidth
);
820 // NOTE: next "if" for variants which use squares filling
821 // instead of "physical", moving pieces
823 for (let i
=0; i
< this.size
.x
; i
++) {
824 for (let j
=0; j
< this.size
.y
; j
++) {
825 if (this.g_pieces
[i
][j
]) {
826 // NOTE: could also use CSS transform "scale"
827 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
828 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
829 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
830 // Translate coordinates to use chessboard as reference:
831 this.g_pieces
[i
][j
].style
.transform
=
832 `translate(${ip - newX}px,${jp - newY}px)`;
838 this.rescaleReserve(newR
);
842 for (let c
of ['w','b']) {
843 if (!this.reserve
[c
])
845 const nbR
= this.getNbReservePieces(c
);
848 // Resize container first
849 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
850 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
851 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
852 let rcontainer
= document
.getElementById("reserves_" + c
);
853 rcontainer
.style
.left
= i0
+ "px";
854 rcontainer
.style
.top
= j0
+ "px";
855 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
856 rcontainer
.style
.height
= sqResSize
+ "px";
857 // And then reserve cells:
858 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
859 Object
.keys(this.reserve
[c
]).forEach(p
=> {
860 if (this.reserve
[c
][p
] == 0)
862 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
863 r_cell
.style
.width
= sqResSize
+ "px";
864 r_cell
.style
.height
= sqResSize
+ "px";
869 // Return the absolute pixel coordinates given current position.
870 // Our coordinate system differs from CSS one (x <--> y).
871 // We return here the CSS coordinates (more useful).
872 getPixelPosition(i
, j
, r
) {
874 return [0, 0]; //piece vanishes
876 if (typeof i
== "string") {
877 // Reserves: need to know the rank of piece
878 const nbR
= this.getNbReservePieces(i
);
879 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
880 x
= this.getRankInReserve(i
, j
) * rsqSize
;
881 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
884 const sqSize
= r
.width
/ this.size
.y
;
885 const flipped
= (this.playerColor
== 'b');
886 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
887 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
889 return [r
.x
+ x
, r
.y
+ y
];
893 let container
= document
.getElementById(this.containerId
);
894 let chessboard
= container
.querySelector(".chessboard");
896 const getOffset
= e
=> {
899 return {x: e
.clientX
, y: e
.clientY
};
900 let touchLocation
= null;
901 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
902 // Touch screen, dragstart
903 touchLocation
= e
.targetTouches
[0];
904 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
905 // Touch screen, dragend
906 touchLocation
= e
.changedTouches
[0];
908 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
909 return {x: 0, y: 0}; //shouldn't reach here =)
912 const centerOnCursor
= (piece
, e
) => {
913 const centerShift
= this.getPieceWidth(r
.width
) / 2;
914 const offset
= getOffset(e
);
915 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
916 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
921 startPiece
, curPiece
= null,
923 const mousedown
= (e
) => {
924 // Disable zoom on smartphones:
925 if (e
.touches
&& e
.touches
.length
> 1)
927 r
= chessboard
.getBoundingClientRect();
928 pieceWidth
= this.getPieceWidth(r
.width
);
929 const cd
= this.idToCoords(e
.target
.id
);
931 const move = this.doClick(cd
);
933 this.buildMoveStack(move, r
);
934 else if (!this.clickOnly
) {
935 const [x
, y
] = Object
.values(cd
);
936 if (typeof x
!= "number")
937 startPiece
= this.r_pieces
[x
][y
];
939 startPiece
= this.g_pieces
[x
][y
];
940 if (startPiece
&& this.canIplay(x
, y
)) {
943 curPiece
= startPiece
.cloneNode();
944 curPiece
.style
.transform
= "none";
945 curPiece
.style
.zIndex
= 5;
946 curPiece
.style
.width
= pieceWidth
+ "px";
947 curPiece
.style
.height
= pieceWidth
+ "px";
948 centerOnCursor(curPiece
, e
);
949 container
.appendChild(curPiece
);
950 startPiece
.style
.opacity
= "0.4";
951 chessboard
.style
.cursor
= "none";
957 const mousemove
= (e
) => {
960 centerOnCursor(curPiece
, e
);
962 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
963 // Attempt to prevent horizontal swipe...
967 const mouseup
= (e
) => {
970 const [x
, y
] = [start
.x
, start
.y
];
973 chessboard
.style
.cursor
= "pointer";
974 startPiece
.style
.opacity
= "1";
975 const offset
= getOffset(e
);
976 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
978 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
980 // NOTE: clearly suboptimal, but much easier, and not a big deal.
981 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
982 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
983 const moves
= this.filterValid(potentialMoves
);
984 if (moves
.length
>= 2)
985 this.showChoices(moves
, r
);
986 else if (moves
.length
== 1)
987 this.buildMoveStack(moves
[0], r
);
992 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
994 if ('onmousedown' in window
) {
995 this.mouseListeners
= [
996 {type: "mousedown", listener: mousedown
},
997 {type: "mousemove", listener: mousemove
},
998 {type: "mouseup", listener: mouseup
},
999 {type: "wheel", listener: resize
}
1001 this.mouseListeners
.forEach(ml
=> {
1002 document
.addEventListener(ml
.type
, ml
.listener
);
1005 if ('ontouchstart' in window
) {
1006 this.touchListeners
= [
1007 {type: "touchstart", listener: mousedown
},
1008 {type: "touchmove", listener: mousemove
},
1009 {type: "touchend", listener: mouseup
}
1011 this.touchListeners
.forEach(tl
=> {
1012 // https://stackoverflow.com/a/42509310/12660887
1013 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
1016 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1020 let container
= document
.getElementById(this.containerId
);
1021 this.windowResizeObs
.unobserve(container
);
1023 return; //no listeners in this case
1024 if ('onmousedown' in window
) {
1025 this.mouseListeners
.forEach(ml
=> {
1026 document
.removeEventListener(ml
.type
, ml
.listener
);
1029 if ('ontouchstart' in window
) {
1030 this.touchListeners
.forEach(tl
=> {
1031 // https://stackoverflow.com/a/42509310/12660887
1032 document
.removeEventListener(tl
.type
, tl
.listener
);
1037 showChoices(moves
, r
) {
1038 let container
= document
.getElementById(this.containerId
);
1039 let chessboard
= container
.querySelector(".chessboard");
1040 let choices
= document
.createElement("div");
1041 choices
.id
= "choices";
1043 r
= chessboard
.getBoundingClientRect();
1044 choices
.style
.width
= r
.width
+ "px";
1045 choices
.style
.height
= r
.height
+ "px";
1046 choices
.style
.left
= r
.x
+ "px";
1047 choices
.style
.top
= r
.y
+ "px";
1048 chessboard
.style
.opacity
= "0.5";
1049 container
.appendChild(choices
);
1050 const squareWidth
= r
.width
/ this.size
.y
;
1051 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1052 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1053 const color
= moves
[0].appear
[0].c
;
1054 const callback
= (m
) => {
1055 chessboard
.style
.opacity
= "1";
1056 container
.removeChild(choices
);
1057 this.buildMoveStack(m
, r
);
1059 for (let i
=0; i
< moves
.length
; i
++) {
1060 let choice
= document
.createElement("div");
1061 choice
.classList
.add("choice");
1062 choice
.style
.width
= squareWidth
+ "px";
1063 choice
.style
.height
= squareWidth
+ "px";
1064 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1065 choice
.style
.top
= firstUpTop
+ "px";
1066 choice
.style
.backgroundColor
= "lightyellow";
1067 choice
.onclick
= () => callback(moves
[i
]);
1068 const piece
= document
.createElement("piece");
1069 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1070 C
.AddClass_es(piece
,
1071 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1072 piece
.classList
.add(C
.GetColorClass(color
));
1073 piece
.style
.width
= "100%";
1074 piece
.style
.height
= "100%";
1075 choice
.appendChild(piece
);
1076 choices
.appendChild(choice
);
1080 displayMessage(elt
, msg
, classe_s
, timeout
) {
1082 // Fixed element, e.g. for Dice Chess
1083 elt
.innerHTML
= msg
;
1085 // Temporary div (Chakart, Apocalypse...)
1086 let divMsg
= document
.createElement("div");
1087 C
.AddClass_es(divMsg
, classe_s
);
1088 divMsg
.innerHTML
= msg
;
1089 let container
= document
.getElementById(this.containerId
);
1090 container
.appendChild(divMsg
);
1091 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1098 updateEnlightened() {
1099 this.oldEnlightened
= this.enlightened
;
1100 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1101 // Add pieces positions + all squares reachable by moves (includes Zen):
1102 for (let x
=0; x
<this.size
.x
; x
++) {
1103 for (let y
=0; y
<this.size
.y
; y
++) {
1104 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1106 this.enlightened
[x
][y
] = true;
1107 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1108 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1114 this.enlightEnpassant();
1117 // Include square of the en-passant capturing square:
1118 enlightEnpassant() {
1119 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1120 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1121 for (let step
of steps
) {
1122 const x
= this.epSquare
.x
- step
[0],
1123 y
= this.getY(this.epSquare
.y
- step
[1]);
1125 this.onBoard(x
, y
) &&
1126 this.getColor(x
, y
) == this.playerColor
&&
1127 this.getPieceType(x
, y
) == "p"
1129 this.enlightened
[x
][this.epSquare
.y
] = true;
1135 // Apply diff this.enlightened --> oldEnlightened on board
1136 graphUpdateEnlightened() {
1138 document
.getElementById(this.containerId
).querySelector(".chessboard");
1139 const r
= chessboard
.getBoundingClientRect();
1140 const pieceWidth
= this.getPieceWidth(r
.width
);
1141 for (let x
=0; x
<this.size
.x
; x
++) {
1142 for (let y
=0; y
<this.size
.y
; y
++) {
1143 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1144 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1145 elt
.classList
.add("in-shadow");
1146 if (this.g_pieces
[x
][y
])
1147 this.g_pieces
[x
][y
].classList
.add("hidden");
1149 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1150 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1151 elt
.classList
.remove("in-shadow");
1152 if (this.g_pieces
[x
][y
])
1153 this.g_pieces
[x
][y
].classList
.remove("hidden");
1166 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1170 // Color of thing on square (i,j). '' if square is empty
1172 if (typeof i
== "string")
1173 return i
; //reserves
1174 return this.board
[i
][j
].charAt(0);
1177 static GetColorClass(c
) {
1182 return "other-color"; //unidentified color
1185 // Piece on i,j. '' if square is empty
1187 if (typeof j
== "string")
1188 return j
; //reserves
1189 return this.board
[i
][j
].charAt(1);
1192 // Piece type on square (i,j)
1193 getPieceType(x
, y
, p
) {
1195 p
= this.getPiece(x
, y
);
1196 return this.pieces()[p
].moveas
|| p
;
1201 p
= this.getPiece(x
, y
);
1202 if (!this.options
["cannibal"])
1204 return !!C
.CannibalKings
[p
];
1207 // Get opponent color
1208 static GetOppCol(color
) {
1209 return (color
== "w" ? "b" : "w");
1212 // Is (x,y) on the chessboard?
1214 return (x
>= 0 && x
< this.size
.x
&&
1215 y
>= 0 && y
< this.size
.y
);
1218 // Am I allowed to move thing at square x,y ?
1220 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1223 ////////////////////////
1224 // PIECES SPECIFICATIONS
1226 pieces(color
, x
, y
) {
1227 const pawnShift
= (color
== "w" ? -1 : 1);
1228 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1229 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1235 steps: [[pawnShift
, 0]],
1236 range: (initRank
? 2 : 1)
1241 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1249 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1257 [1, 2], [1, -2], [-1, 2], [-1, -2],
1258 [2, 1], [-2, 1], [2, -1], [-2, -1]
1267 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1275 [0, 1], [0, -1], [1, 0], [-1, 0],
1276 [1, 1], [1, -1], [-1, 1], [-1, -1]
1286 [0, 1], [0, -1], [1, 0], [-1, 0],
1287 [1, 1], [1, -1], [-1, 1], [-1, -1]
1294 '!': {"class": "king-pawn", moveas: "p"},
1295 '#': {"class": "king-rook", moveas: "r"},
1296 '$': {"class": "king-knight", moveas: "n"},
1297 '%': {"class": "king-bishop", moveas: "b"},
1298 '*': {"class": "king-queen", moveas: "q"}
1302 // NOTE: using special symbols to not interfere with variants' pieces codes
1303 static get CannibalKings() {
1314 static get CannibalKingCode() {
1325 //////////////////////////
1326 // MOVES GENERATION UTILS
1328 // For Cylinder: get Y coordinate
1330 if (!this.options
["cylinder"])
1332 let res
= y
% this.size
.y
;
1338 getSegments(curSeg
, segStart
, segEnd
) {
1339 if (curSeg
.length
== 0)
1341 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1342 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1346 getStepSpec(color
, x
, y
, piece
) {
1347 return this.pieces(color
, x
, y
)[piece
|| this.getPieceType(x
, y
)];
1350 // Can thing on square1 capture thing on square2?
1351 canTake([x1
, y1
], [x2
, y2
]) {
1352 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1355 canStepOver(i
, j
, p
) {
1356 // In some variants, objects on boards don't stop movement (Chakart)
1357 return this.board
[i
][j
] == "";
1360 canDrop([c
, p
], [i
, j
]) {
1362 this.board
[i
][j
] == "" &&
1363 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1366 (c
== 'w' && i
< this.size
.x
- 1) ||
1373 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1374 isImmobilized([x
, y
]) {
1375 if (!this.options
["madrasi"])
1377 const color
= this.getColor(x
, y
);
1378 const oppCol
= C
.GetOppCol(color
);
1379 const piece
= this.getPieceType(x
, y
);
1380 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1381 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1382 for (let a
of attacks
) {
1383 outerLoop: for (let step
of a
.steps
) {
1384 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1385 let stepCounter
= 1;
1386 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1387 if (a
.range
<= stepCounter
++)
1390 j
= this.getY(j
+ step
[1]);
1393 this.onBoard(i
, j
) &&
1394 this.getColor(i
, j
) == oppCol
&&
1395 this.getPieceType(i
, j
) == piece
1404 // Stop at the first capture found
1405 atLeastOneCapture(color
) {
1406 const oppCol
= C
.GetOppCol(color
);
1407 const allowed
= (sq1
, sq2
) => {
1409 // NOTE: canTake is reversed for Zen.
1410 // Generally ok because of the symmetry. TODO?
1411 this.canTake(sq1
, sq2
) &&
1413 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1416 for (let i
=0; i
<this.size
.x
; i
++) {
1417 for (let j
=0; j
<this.size
.y
; j
++) {
1418 if (this.getColor(i
, j
) == color
) {
1421 !this.options
["zen"] &&
1422 this.findDestSquares(
1427 segments: this.options
["cylinder"]
1435 this.options
["zen"] &&
1436 this.findCapturesOn(
1440 segments: this.options
["cylinder"]
1455 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1456 const epsilon
= 1e-7; //arbitrary small value
1458 if (this.options
["cylinder"])
1459 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1460 for (let sh
of shifts
) {
1461 const rx
= (x2
- x1
) / step
[0],
1462 ry
= (y2
+ sh
- y1
) / step
[1];
1464 // Zero step but non-zero interval => impossible
1465 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1466 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1467 // Negative number of step (impossible)
1468 (rx
< 0 || ry
< 0) ||
1469 // Not the same number of steps in both directions:
1470 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1474 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1475 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1477 distance
= Math
.round(distance
); //in case of (numerical...)
1478 if (!range
|| range
>= distance
)
1484 ////////////////////
1487 getDropMovesFrom([c
, p
]) {
1488 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1489 // (but not necessarily otherwise: atLeastOneMove() etc)
1490 if (this.reserve
[c
][p
] == 0)
1493 for (let i
=0; i
<this.size
.x
; i
++) {
1494 for (let j
=0; j
<this.size
.y
; j
++) {
1495 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1497 start: {x: c
, y: p
},
1499 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1502 if (this.board
[i
][j
] != "") {
1503 mv
.vanish
.push(new PiPo({
1506 c: this.getColor(i
, j
),
1507 p: this.getPiece(i
, j
)
1517 // All possible moves from selected square
1518 getPotentialMovesFrom([x
, y
], color
) {
1519 if (this.subTurnTeleport
== 2)
1521 if (typeof x
== "string")
1522 return this.getDropMovesFrom([x
, y
]);
1523 if (this.isImmobilized([x
, y
]))
1525 const piece
= this.getPieceType(x
, y
);
1526 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1527 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1528 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1530 this.isKing(0, 0, piece
) && this.hasCastle
&&
1531 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1533 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1535 return this.postProcessPotentialMoves(moves
);
1538 postProcessPotentialMoves(moves
) {
1539 if (moves
.length
== 0)
1541 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1542 const oppCol
= C
.GetOppCol(color
);
1544 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1545 moves
= this.capturePostProcess(moves
, oppCol
);
1547 if (this.options
["atomic"])
1548 moves
= this.atomicPostProcess(moves
, color
, oppCol
);
1552 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1554 moves
= this.pawnPostProcess(moves
, color
, oppCol
);
1557 if (this.options
["cannibal"] && this.options
["rifle"])
1558 // In this case a rifle-capture from last rank may promote a pawn
1559 moves
= this.riflePromotePostProcess(moves
, color
);
1564 capturePostProcess(moves
, oppCol
) {
1565 // Filter out non-capturing moves (not using m.vanish because of
1566 // self captures of Recycle and Teleport).
1567 return moves
.filter(m
=> {
1569 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1570 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1575 atomicPostProcess(moves
, color
, oppCol
) {
1576 moves
.forEach(m
=> {
1578 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1579 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1592 let mNext
= new Move({
1598 for (let step
of steps
) {
1599 let x
= m
.end
.x
+ step
[0];
1600 let y
= this.getY(m
.end
.y
+ step
[1]);
1602 this.onBoard(x
, y
) &&
1603 this.board
[x
][y
] != "" &&
1604 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1605 this.getPieceType(x
, y
) != "p"
1609 p: this.getPiece(x
, y
),
1610 c: this.getColor(x
, y
),
1617 if (!this.options
["rifle"]) {
1618 // The moving piece also vanish
1619 mNext
.vanish
.unshift(
1624 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1634 pawnPostProcess(moves
, color
, oppCol
) {
1636 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1637 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1638 moves
.forEach(m
=> {
1639 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1640 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1641 const promotionOk
= (
1643 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1646 return; //nothing to do
1647 if (this.options
["pawnfall"]) {
1653 this.options
["cannibal"] &&
1654 this.board
[x2
][y2
] != "" &&
1655 this.getColor(x2
, y2
) == oppCol
1657 finalPieces
= [this.getPieceType(x2
, y2
)];
1660 finalPieces
= this.pawnPromotions
;
1661 m
.appear
[0].p
= finalPieces
[0];
1662 if (initPiece
== "!") //cannibal king-pawn
1663 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1664 for (let i
=1; i
<finalPieces
.length
; i
++) {
1665 let newMove
= JSON
.parse(JSON
.stringify(m
));
1666 const piece
= finalPieces
[i
];
1667 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1668 moreMoves
.push(newMove
);
1671 return moves
.concat(moreMoves
);
1674 riflePromotePostProcess(moves
, color
) {
1675 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1677 moves
.forEach(m
=> {
1679 m
.start
.x
== lastRank
&&
1680 m
.appear
.length
>= 1 &&
1681 m
.appear
[0].p
== "p" &&
1682 m
.appear
[0].x
== m
.start
.x
&&
1683 m
.appear
[0].y
== m
.start
.y
1685 m
.appear
[0].p
= this.pawnPromotions
[0];
1686 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1687 let newMv
= JSON
.parse(JSON
.stringify(m
));
1688 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1689 newMoves
.push(newMv
);
1693 return moves
.concat(newMoves
);
1696 // Generic method to find possible moves of "sliding or jumping" pieces
1697 getPotentialMovesOf(piece
, [x
, y
]) {
1698 const color
= this.getColor(x
, y
);
1699 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1701 if (stepSpec
.attack
) {
1702 squares
= this.findDestSquares(
1706 segments: this.options
["cylinder"],
1709 ([i1
, j1
], [i2
, j2
]) => {
1711 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1712 this.canTake([i1
, j1
], [i2
, j2
])
1717 const noSpecials
= this.findDestSquares(
1720 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1721 segments: this.options
["cylinder"],
1725 Array
.prototype.push
.apply(squares
, noSpecials
);
1726 if (this.options
["zen"]) {
1727 let zenCaptures
= this.findCapturesOn(
1729 {}, //byCol: default is ok
1730 ([i1
, j1
], [i2
, j2
]) =>
1731 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1733 // Technical step: segments (if any) are reversed
1734 if (this.options
["cylinder"]) {
1735 zenCaptures
.forEach(z
=> {
1736 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1739 Array
.prototype.push
.apply(squares
, zenCaptures
);
1742 this.options
["recycle"] ||
1743 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1745 const selfCaptures
= this.findDestSquares(
1749 segments: this.options
["cylinder"],
1752 ([i1
, j1
], [i2
, j2
]) =>
1753 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1755 Array
.prototype.push
.apply(squares
, selfCaptures
);
1757 return squares
.map(s
=> {
1758 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1759 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1760 mv
.segments
= s
.segments
;
1765 findDestSquares([x
, y
], o
, allowed
) {
1767 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1768 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1770 // Next 3 for Cylinder mode: (unused if !o.segments)
1774 const addSquare
= ([i
, j
]) => {
1775 let elt
= {sq: [i
, j
]};
1777 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1780 const exploreSteps
= (stepArray
) => {
1781 for (let s
of stepArray
) {
1782 outerLoop: for (let step
of s
.steps
) {
1787 let [i
, j
] = [x
, y
];
1788 let stepCounter
= 0;
1790 this.onBoard(i
, j
) &&
1791 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1793 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1794 explored
[i
+ "." + j
] = true;
1797 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1799 if (o
.one
&& !o
.attackOnly
)
1802 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1803 if (o
.captureTarget
)
1807 if (s
.range
<= stepCounter
++)
1809 const oldIJ
= [i
, j
];
1811 j
= this.getY(j
+ step
[1]);
1812 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1813 // Boundary between segments (cylinder mode)
1814 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1818 if (!this.onBoard(i
, j
))
1820 const pieceIJ
= this.getPieceType(i
, j
);
1821 if (!explored
[i
+ "." + j
]) {
1822 explored
[i
+ "." + j
] = true;
1823 if (allowed([x
, y
], [i
, j
])) {
1824 if (o
.one
&& !o
.moveOnly
)
1827 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1830 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1838 return undefined; //default, but let's explicit it
1840 if (o
.captureTarget
)
1841 return exploreSteps(o
.captureSteps
)
1844 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1846 if (!o
.attackOnly
|| !stepSpec
.attack
)
1847 outOne
= exploreSteps(stepSpec
.moves
);
1848 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1849 o
.attackOnly
= true; //ok because o is always a temporary object
1850 outOne
= exploreSteps(stepSpec
.attack
);
1852 return (o
.one
? outOne : res
);
1856 // Search for enemy (or not) pieces attacking [x, y]
1857 findCapturesOn([x
, y
], o
, allowed
) {
1859 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1861 for (let i
=0; i
<this.size
.x
; i
++) {
1862 for (let j
=0; j
<this.size
.y
; j
++) {
1863 const colIJ
= this.getColor(i
, j
);
1865 this.board
[i
][j
] != "" &&
1866 o
.byCol
.includes(colIJ
) &&
1867 !this.isImmobilized([i
, j
])
1869 const apparentPiece
= this.getPiece(i
, j
);
1870 // Quick check: does this potential attacker target x,y ?
1871 if (this.canStepOver(x
, y
, apparentPiece
))
1873 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1874 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1875 for (let a
of attacks
) {
1876 for (let s
of a
.steps
) {
1877 // Quick check: if step isn't compatible, don't even try
1878 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1880 // Finally verify that nothing stand in-between
1881 const out
= this.findDestSquares(
1884 captureTarget: [x
, y
],
1885 captureSteps: [{steps: [s
], range: a
.range
}],
1886 segments: o
.segments
,
1888 one: false //one and captureTarget are mutually exclusive
1902 return (o
.one
? false : res
);
1905 // Build a regular move from its initial and destination squares.
1906 // tr: transformation
1907 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1908 const initColor
= this.getColor(sx
, sy
);
1909 const initPiece
= this.getPiece(sx
, sy
);
1910 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1914 start: {x: sx
, y: sy
},
1918 !this.options
["rifle"] ||
1919 this.board
[ex
][ey
] == "" ||
1920 destColor
== initColor
//Recycle, Teleport
1926 c: !!tr
? tr
.c : initColor
,
1927 p: !!tr
? tr
.p : initPiece
1939 if (this.board
[ex
][ey
] != "") {
1944 c: this.getColor(ex
, ey
),
1945 p: this.getPiece(ex
, ey
)
1948 if (this.options
["cannibal"] && destColor
!= initColor
) {
1949 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1950 let trPiece
= mv
.vanish
[lastIdx
].p
;
1951 if (this.isKing(sx
, sy
))
1952 trPiece
= C
.CannibalKingCode
[trPiece
];
1953 if (mv
.appear
.length
>= 1)
1954 mv
.appear
[0].p
= trPiece
;
1955 else if (this.options
["rifle"]) {
1978 // En-passant square, if any
1979 getEpSquare(moveOrSquare
) {
1980 if (typeof moveOrSquare
=== "string") {
1981 const square
= moveOrSquare
;
1984 return C
.SquareToCoords(square
);
1986 // Argument is a move:
1987 const move = moveOrSquare
;
1988 const s
= move.start
,
1992 Math
.abs(s
.x
- e
.x
) == 2 &&
1993 // Next conditions for variants like Atomic or Rifle, Recycle...
1995 move.appear
.length
> 0 &&
1996 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
2000 move.vanish
.length
> 0 &&
2001 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
2009 return undefined; //default
2012 // Special case of en-passant captures: treated separately
2013 getEnpassantCaptures([x
, y
]) {
2014 const color
= this.getColor(x
, y
);
2015 const shiftX
= (color
== 'w' ? -1 : 1);
2016 const oppCol
= C
.GetOppCol(color
);
2019 this.epSquare
.x
== x
+ shiftX
&&
2020 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2021 // Doublemove (and Progressive?) guards:
2022 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2023 this.getColor(x
, this.epSquare
.y
) == oppCol
2025 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2026 this.board
[epx
][epy
] = oppCol
+ 'p';
2027 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2028 this.board
[epx
][epy
] = "";
2029 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2030 enpassantMove
.vanish
[lastIdx
].x
= x
;
2031 return [enpassantMove
];
2036 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2037 const c
= this.getColor(x
, y
);
2040 const oppCol
= C
.GetOppCol(c
);
2044 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2045 const castlingKing
= this.getPiece(x
, y
);
2046 castlingCheck: for (
2049 castleSide
++ //large, then small
2051 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2053 // If this code is reached, rook and king are on initial position
2055 // NOTE: in some variants this is not a rook
2056 const rookPos
= this.castleFlags
[c
][castleSide
];
2057 const castlingPiece
= this.getPiece(x
, rookPos
);
2059 this.board
[x
][rookPos
] == "" ||
2060 this.getColor(x
, rookPos
) != c
||
2061 (castleWith
&& !castleWith
.includes(castlingPiece
))
2063 // Rook is not here, or changed color (see Benedict)
2066 // Nothing on the path of the king ? (and no checks)
2067 const finDist
= finalSquares
[castleSide
][0] - y
;
2068 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2072 // NOTE: next weird test because underCheck() verification
2073 // will be executed in filterValid() later.
2075 i
!= finalSquares
[castleSide
][0] &&
2076 this.underCheck([x
, i
], oppCol
)
2080 this.board
[x
][i
] != "" &&
2081 // NOTE: next check is enough, because of chessboard constraints
2082 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2085 continue castlingCheck
;
2088 } while (i
!= finalSquares
[castleSide
][0]);
2089 // Nothing on the path to the rook?
2090 step
= (castleSide
== 0 ? -1 : 1);
2091 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2092 if (this.board
[x
][i
] != "")
2093 continue castlingCheck
;
2096 // Nothing on final squares, except maybe king and castling rook?
2097 for (i
= 0; i
< 2; i
++) {
2099 finalSquares
[castleSide
][i
] != rookPos
&&
2100 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2102 finalSquares
[castleSide
][i
] != y
||
2103 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2106 continue castlingCheck
;
2110 // If this code is reached, castle is potentially valid
2116 y: finalSquares
[castleSide
][0],
2122 y: finalSquares
[castleSide
][1],
2128 // King might be initially disguised (Titan...)
2129 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2130 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2133 Math
.abs(y
- rookPos
) <= 2
2134 ? {x: x
, y: rookPos
}
2135 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2143 ////////////////////
2146 // Is piece (or square) at given position attacked by "oppCol" ?
2147 underAttack([x
, y
], oppCol
) {
2148 // An empty square is considered as king,
2149 // since it's used only in getCastleMoves (TODO?)
2150 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2153 (!this.options
["zen"] || king
) &&
2154 this.findCapturesOn(
2158 segments: this.options
["cylinder"],
2165 (!!this.options
["zen"] && !king
) &&
2166 this.findDestSquares(
2170 segments: this.options
["cylinder"],
2173 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2179 // Argument is (very generally) an array of squares (= arrays)
2180 underCheck(square_s
, oppCol
) {
2181 if (this.options
["taking"] || this.options
["dark"])
2183 if (!Array
.isArray(square_s
[0]))
2184 square_s
= [square_s
];
2185 return square_s
.some(sq
=> this.underAttack(sq
, oppCol
));
2188 // Scan board for king(s)
2189 searchKingPos(color
) {
2191 for (let i
=0; i
< this.size
.x
; i
++) {
2192 for (let j
=0; j
< this.size
.y
; j
++) {
2193 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2200 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2201 filterValid(moves
, color
) {
2204 const oppCol
= C
.GetOppCol(color
);
2205 let kingPos
= this.searchKingPos(color
);
2206 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2207 return moves
.filter(m
=> {
2208 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2209 if (!filtered
[key
]) {
2210 this.playOnBoard(m
);
2211 let newKingPP
= null,
2213 res
= true; //a priori valid
2215 m
.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2217 // Search king in appear array:
2219 m
.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2221 sqIdx
= kingPos
.findIndex(kp
=>
2222 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2223 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2226 res
= false; //king vanished
2228 res
&&= !this.underCheck(kingPos
, oppCol
);
2229 if (oldKingPP
&& newKingPP
)
2230 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2231 this.undoOnBoard(m
);
2232 filtered
[key
] = res
;
2235 return filtered
[key
];
2242 // Apply a move on board
2244 for (let psq
of move.vanish
)
2245 this.board
[psq
.x
][psq
.y
] = "";
2246 for (let psq
of move.appear
)
2247 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2249 // Un-apply the played move
2251 for (let psq
of move.appear
)
2252 this.board
[psq
.x
][psq
.y
] = "";
2253 for (let psq
of move.vanish
)
2254 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2257 updateCastleFlags(move) {
2258 // Update castling flags if start or arrive from/at rook/king locations
2259 move.appear
.concat(move.vanish
).forEach(psq
=> {
2260 if (this.isKing(0, 0, psq
.p
))
2261 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2262 // NOTE: not "else if" because king can capture enemy rook...
2266 else if (psq
.x
== this.size
.x
- 1)
2269 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2271 this.castleFlags
[c
][fidx
] = this.size
.y
;
2279 // If flags already off, no need to re-check:
2280 Object
.values(this.castleFlags
).some(cvals
=>
2281 cvals
.some(val
=> val
< this.size
.y
))
2283 this.updateCastleFlags(move);
2285 if (this.options
["crazyhouse"]) {
2286 move.vanish
.forEach(v
=> {
2287 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2288 if (this.ispawn
[square
])
2289 delete this.ispawn
[square
];
2291 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2292 // Assumption: something is moving
2293 const initSquare
= C
.CoordsToSquare(move.start
);
2294 const destSquare
= C
.CoordsToSquare(move.end
);
2296 this.ispawn
[initSquare
] ||
2297 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2299 this.ispawn
[destSquare
] = true;
2302 this.ispawn
[destSquare
] &&
2303 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2305 move.vanish
[1].p
= 'p';
2306 delete this.ispawn
[destSquare
];
2310 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2313 // Warning; atomic pawn removal isn't a capture
2314 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2316 const color
= this.turn
;
2317 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2318 // Something appears = dropped on board (some exceptions, Chakart...)
2319 if (move.appear
[i
].c
== color
) {
2320 const piece
= move.appear
[i
].p
;
2321 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2324 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2325 // Something vanish: add to reserve except if recycle & opponent
2327 this.options
["crazyhouse"] ||
2328 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2330 const piece
= move.vanish
[i
].p
;
2331 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2339 if (this.hasEnpassant
)
2340 this.epSquare
= this.getEpSquare(move);
2341 this.playOnBoard(move);
2342 this.postPlay(move);
2346 const color
= this.turn
;
2347 if (this.options
["dark"])
2348 this.updateEnlightened();
2349 if (this.options
["teleport"]) {
2351 this.subTurnTeleport
== 1 &&
2352 move.vanish
.length
> move.appear
.length
&&
2353 move.vanish
[1].c
== color
2355 const v
= move.vanish
[move.vanish
.length
- 1];
2356 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2357 this.subTurnTeleport
= 2;
2360 this.subTurnTeleport
= 1;
2361 this.captured
= null;
2363 if (this.isLastMove(move)) {
2364 this.turn
= C
.GetOppCol(color
);
2368 else if (!move.next
)
2375 const color
= this.turn
;
2376 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2377 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, color
))
2381 !this.options
["balance"] ||
2382 ![1, 2].includes(this.movesCount
) ||
2387 !this.options
["doublemove"] ||
2388 this.movesCount
== 0 ||
2393 !this.options
["progressive"] ||
2394 this.subTurn
== this.movesCount
+ 1
2399 // "Stop at the first move found"
2400 atLeastOneMove(color
) {
2401 for (let i
= 0; i
< this.size
.x
; i
++) {
2402 for (let j
= 0; j
< this.size
.y
; j
++) {
2403 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2404 // NOTE: in fact searching for all potential moves from i,j.
2405 // I don't believe this is an issue, for now at least.
2406 const moves
= this.getPotentialMovesFrom([i
, j
]);
2407 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2412 if (this.hasReserve
&& this.reserve
[color
]) {
2413 for (let p
of Object
.keys(this.reserve
[color
])) {
2414 const moves
= this.getDropMovesFrom([color
, p
]);
2415 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2422 // What is the score ? (Interesting if game is over)
2423 getCurrentScore(move_s
) {
2424 const move = move_s
[move_s
.length
- 1];
2425 // Shortcut in case the score was computed before:
2428 const color
= this.turn
;
2429 const oppCol
= C
.GetOppCol(color
);
2431 [color
]: this.searchKingPos(color
),
2432 [oppCol
]: this.searchKingPos(oppCol
)
2434 if (kingPos
[color
].length
== 0 && kingPos
[oppCol
].length
== 0)
2436 if (kingPos
[color
].length
== 0)
2437 return (color
== "w" ? "0-1" : "1-0");
2438 if (kingPos
[oppCol
].length
== 0)
2439 return (color
== "w" ? "1-0" : "0-1");
2440 if (this.atLeastOneMove(color
))
2442 // No valid move: stalemate or checkmate?
2443 if (!this.underCheck(kingPos
[color
], oppCol
))
2446 return (color
== "w" ? "0-1" : "1-0");
2449 playVisual(move, r
) {
2450 move.vanish
.forEach(v
=> {
2451 this.g_pieces
[v
.x
][v
.y
].remove();
2452 this.g_pieces
[v
.x
][v
.y
] = null;
2455 document
.getElementById(this.containerId
).querySelector(".chessboard");
2457 r
= chessboard
.getBoundingClientRect();
2458 const pieceWidth
= this.getPieceWidth(r
.width
);
2459 move.appear
.forEach(a
=> {
2460 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2461 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2462 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2463 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2464 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2465 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2466 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2467 // Translate coordinates to use chessboard as reference:
2468 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2469 `translate(${ip - r.x}px,${jp - r.y}px)`;
2470 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2471 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2472 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2474 if (this.options
["dark"])
2475 this.graphUpdateEnlightened();
2478 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2479 buildMoveStack(move, r
) {
2480 this.moveStack
.push(move);
2481 this.computeNextMove(move);
2483 const newTurn
= this.turn
;
2484 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2485 this.playVisual(move, r
);
2489 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2491 this.buildMoveStack(move.next
, r
);
2494 if (this.moveStack
.length
== 1) {
2495 // Usual case (one normal move)
2496 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2500 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2501 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2502 this.playReceivedMove(this.moveStack
.slice(1), () => {
2503 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2510 // Implemented in variants using (automatic) moveStack
2511 computeNextMove(move) {}
2513 animateMoving(start
, end
, drag
, segments
, cb
) {
2514 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2515 // NOTE: cloning often not required, but light enough, and simpler
2516 let movingPiece
= initPiece
.cloneNode();
2517 initPiece
.style
.opacity
= "0";
2519 document
.getElementById(this.containerId
)
2520 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2521 if (typeof start
.x
== "string") {
2522 // Need to bound width/height (was 100% for reserve pieces)
2523 const pieceWidth
= this.getPieceWidth(r
.width
);
2524 movingPiece
.style
.width
= pieceWidth
+ "px";
2525 movingPiece
.style
.height
= pieceWidth
+ "px";
2527 const maxDist
= this.getMaxDistance(r
);
2528 const apparentColor
= this.getColor(start
.x
, start
.y
);
2529 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2531 const startCode
= this.getPiece(start
.x
, start
.y
);
2532 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2533 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2534 if (apparentColor
!= drag
.c
) {
2535 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2536 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2539 container
.appendChild(movingPiece
);
2540 const animateSegment
= (index
, cb
) => {
2541 // NOTE: move.drag could be generalized per-segment (usage?)
2542 const [i1
, j1
] = segments
[index
][0];
2543 const [i2
, j2
] = segments
[index
][1];
2544 const dep
= this.getPixelPosition(i1
, j1
, r
);
2545 const arr
= this.getPixelPosition(i2
, j2
, r
);
2546 movingPiece
.style
.transitionDuration
= "0s";
2547 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2549 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2550 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2551 // TODO: unclear why we need this new delay below:
2553 movingPiece
.style
.transitionDuration
= duration
+ "s";
2554 // movingPiece is child of container: no need to adjust coordinates
2555 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2556 setTimeout(cb
, duration
* 1000);
2560 const animateSegmentCallback
= () => {
2561 if (index
< segments
.length
)
2562 animateSegment(index
++, animateSegmentCallback
);
2564 movingPiece
.remove();
2565 initPiece
.style
.opacity
= "1";
2569 animateSegmentCallback();
2572 // Input array of objects with at least fields x,y (e.g. PiPo)
2573 animateFading(arr
, cb
) {
2574 const animLength
= 350; //TODO: 350ms? More? Less?
2576 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2577 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2578 fadingPiece
.style
.opacity
= "0";
2580 setTimeout(cb
, animLength
);
2583 animate(move, callback
) {
2584 if (this.noAnimate
|| move.noAnimate
) {
2588 let segments
= move.segments
;
2590 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2591 let targetObj
= new TargetObj(callback
);
2592 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2594 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2595 () => targetObj
.increment());
2597 if (move.vanish
.length
> move.appear
.length
) {
2598 const arr
= move.vanish
.slice(move.appear
.length
)
2599 // Ignore disappearing pieces hidden by some appearing ones:
2600 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2601 if (arr
.length
> 0) {
2603 this.animateFading(arr
, () => targetObj
.increment());
2607 this.tryAnimateCastle(move, () => targetObj
.increment());
2609 this.customAnimate(move, segments
, () => targetObj
.increment());
2610 if (targetObj
.target
== 0)
2614 tryAnimateCastle(move, cb
) {
2617 move.vanish
.length
== 2 &&
2618 move.appear
.length
== 2 &&
2619 this.isKing(0, 0, move.vanish
[0].p
) &&
2620 this.isKing(0, 0, move.appear
[0].p
)
2622 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2623 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2624 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2625 this.animateMoving(start
, end
, null, segments
, cb
);
2631 // Potential other animations (e.g. for Suction variant)
2632 customAnimate(move, segments
, cb
) {
2633 return 0; //nb of targets
2636 launchAnimation(moves
, container
, callback
) {
2637 if (this.hideMoves
) {
2638 moves
.forEach(m
=> this.play(m
));
2642 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2643 const animateRec
= i
=> {
2644 this.animate(moves
[i
], () => {
2645 this.play(moves
[i
]);
2646 this.playVisual(moves
[i
], r
);
2647 if (i
< moves
.length
- 1)
2648 setTimeout(() => animateRec(i
+1), 300);
2656 playReceivedMove(moves
, callback
) {
2657 // Delay if user wasn't focused:
2658 const checkDisplayThenAnimate
= (delay
) => {
2659 if (container
.style
.display
== "none") {
2660 alert("New move! Let's go back to game...");
2661 document
.getElementById("gameInfos").style
.display
= "none";
2662 container
.style
.display
= "block";
2664 () => this.launchAnimation(moves
, container
, callback
),
2670 () => this.launchAnimation(moves
, container
, callback
),
2675 let container
= document
.getElementById(this.containerId
);
2676 if (document
.hidden
) {
2677 document
.onvisibilitychange
= () => {
2678 document
.onvisibilitychange
= undefined;
2679 checkDisplayThenAnimate(700);
2683 checkDisplayThenAnimate();