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
);
211 baseFen
.fen
+ " w 0" +
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";
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()
277 return { fen: fen
, o: {flags: flags
} };
280 // "Parse" FEN: just return untransformed string data
282 const fenParts
= fen
.split(" ");
284 position: fenParts
[0],
286 movesCount: fenParts
[2]
288 if (fenParts
.length
> 3)
289 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
293 // Return current fen (game state)
295 const parts
= this.getPartFen({});
298 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
303 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
309 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
310 if (this.hasEnpassant
)
311 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
312 if (this.hasReserveFen
)
313 parts
["reserve"] = this.getReserveFen(o
);
314 if (this.options
["crazyhouse"])
315 parts
["ispawn"] = this.getIspawnFen(o
);
319 static FenEmptySquares(count
) {
320 // if more than 9 consecutive free spaces, break the integer,
321 // otherwise FEN parsing will fail.
324 // Most boards of size < 18:
326 return "9" + (count
- 9);
328 return "99" + (count
- 18);
331 // Position part of the FEN string
334 for (let i
= 0; i
< this.size
.y
; i
++) {
336 for (let j
= 0; j
< this.size
.x
; j
++) {
337 if (this.board
[i
][j
] == "")
340 if (emptyCount
> 0) {
341 // Add empty squares in-between
342 position
+= C
.FenEmptySquares(emptyCount
);
345 position
+= this.board2fen(this.board
[i
][j
]);
350 position
+= C
.FenEmptySquares(emptyCount
);
351 if (i
< this.size
.y
- 1)
352 position
+= "/"; //separate rows
357 // Flags part of the FEN string
359 return ["w", "b"].map(c
=> {
360 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
364 // Enpassant part of the FEN string
368 return C
.CoordsToSquare(this.epSquare
);
373 return "000000000000";
375 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
381 // NOTE: cannot merge because this.ispawn doesn't exist yet
383 const squares
= Object
.keys(this.ispawn
);
384 if (squares
.length
== 0)
386 return squares
.join(",");
389 // Set flags from fen (castle: white a,h then black a,h)
392 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
393 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
401 this.options
= o
.options
;
402 // Fill missing options (always the case if random challenge)
403 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
404 if (this.options
[opt
.variable
] === undefined)
405 this.options
[opt
.variable
] = opt
.defaut
;
408 // This object will be used only for initial FEN generation
412 this.playerColor
= o
.color
;
413 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
414 this.containerId
= o
.element
;
415 this.isDiagram
= o
.diagram
;
416 this.marks
= o
.marks
;
420 o
.fen
= this.genRandInitFen(o
.seed
);
421 this.re_initFromFen(o
.fen
);
422 this.graphicalInit();
425 re_initFromFen(fen
, oldBoard
) {
426 const fenParsed
= this.parseFen(fen
);
427 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
428 this.turn
= fenParsed
.turn
;
429 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
430 this.setOtherVariables(fenParsed
);
433 // Turn position fen into double array ["wb","wp","bk",...]
435 const rows
= position
.split("/");
436 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
437 for (let i
= 0; i
< rows
.length
; i
++) {
439 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
440 const character
= rows
[i
][indexInRow
];
441 const num
= parseInt(character
, 10);
442 // If num is a number, just shift j:
445 // Else: something at position i,j
447 board
[i
][j
++] = this.fen2board(character
);
453 // Some additional variables from FEN (variant dependant)
454 setOtherVariables(fenParsed
) {
455 // Set flags and enpassant:
457 this.setFlags(fenParsed
.flags
);
458 if (this.hasEnpassant
)
459 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
460 if (this.hasReserve
&& !this.isDiagram
)
461 this.initReserves(fenParsed
.reserve
);
462 if (this.options
["crazyhouse"])
463 this.initIspawn(fenParsed
.ispawn
);
464 if (this.options
["teleport"]) {
465 this.subTurnTeleport
= 1;
466 this.captured
= null;
468 if (this.options
["dark"]) {
469 // Setup enlightened: squares reachable by player side
470 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
471 this.updateEnlightened();
473 this.subTurn
= 1; //may be unused
474 if (!this.moveStack
) //avoid resetting (unwanted)
478 // ordering as in pieces() p,r,n,b,q,k
479 initReserves(reserveStr
, pieceArray
) {
481 pieceArray
= ['p', 'r', 'n', 'b', 'q', 'k'];
482 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
483 const L
= pieceArray
.length
;
485 w: ArrayFun
.toObject(pieceArray
, counts
.slice(0, L
)),
486 b: ArrayFun
.toObject(pieceArray
, counts
.slice(L
, 2 * L
))
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(elt
, class_es
) {
529 if (!Array
.isArray(class_es
))
530 class_es
= [class_es
];
531 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
534 static RemoveClass_es(elt
, class_es
) {
535 if (!Array
.isArray(class_es
))
536 class_es
= [class_es
];
537 class_es
.forEach(cl
=> elt
.classList
.remove(cl
));
540 // Generally light square bottom-right
541 getSquareColorClass(x
, y
) {
542 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
546 // Works for all rectangular boards:
547 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
551 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
558 const g_init
= () => {
559 this.re_drawBoardElements();
560 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
561 this.initMouseEvents();
563 let container
= document
.getElementById(this.containerId
);
564 this.windowResizeObs
= new ResizeObserver(g_init
);
565 this.windowResizeObs
.observe(container
);
568 re_drawBoardElements() {
569 const board
= this.getSvgChessboard();
570 const oppCol
= C
.GetOppCol(this.playerColor
);
571 const container
= document
.getElementById(this.containerId
);
572 const rc
= container
.getBoundingClientRect();
573 let chessboard
= container
.querySelector(".chessboard");
574 chessboard
.innerHTML
= "";
575 chessboard
.insertAdjacentHTML('beforeend', board
);
576 // Compare window ratio width / height to aspectRatio:
577 const windowRatio
= rc
.width
/ rc
.height
;
578 let cbWidth
, cbHeight
;
579 const vRatio
= this.size
.ratio
|| 1;
580 if (windowRatio
<= vRatio
) {
581 // Limiting dimension is width:
582 cbWidth
= Math
.min(rc
.width
, 767);
583 cbHeight
= cbWidth
/ vRatio
;
586 // Limiting dimension is height:
587 cbHeight
= Math
.min(rc
.height
, 767);
588 cbWidth
= cbHeight
* vRatio
;
590 if (this.hasReserve
&& !this.isDiagram
) {
591 const sqSize
= cbWidth
/ this.size
.y
;
592 // NOTE: allocate space for reserves (up/down) even if they are empty
593 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
594 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
595 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
596 cbWidth
= cbHeight
* vRatio
;
599 chessboard
.style
.width
= cbWidth
+ "px";
600 chessboard
.style
.height
= cbHeight
+ "px";
601 // Center chessboard:
602 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
603 spaceTop
= (rc
.height
- cbHeight
) / 2;
604 chessboard
.style
.left
= spaceLeft
+ "px";
605 chessboard
.style
.top
= spaceTop
+ "px";
606 // Give sizes instead of recomputing them,
607 // because chessboard might not be drawn yet.
616 // Get SVG board (background, no pieces)
618 const flipped
= (this.playerColor
== 'b');
621 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
622 class="chessboard_SVG">`;
623 for (let i
=0; i
< this.size
.x
; i
++) {
624 for (let j
=0; j
< this.size
.y
; j
++) {
625 if (!this.onBoard(i
, j
))
627 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
628 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
629 let classes
= this.getSquareColorClass(ii
, jj
);
630 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
631 classes
+= " in-shadow";
632 // NOTE: x / y reversed because coordinates system is reversed.
636 id="${this.coordsToId({x: ii, y: jj})}"
650 document
.getElementById(this.containerId
).querySelector(".chessboard");
652 r
= chessboard
.getBoundingClientRect();
653 const pieceWidth
= this.getPieceWidth(r
.width
);
654 const addPiece
= (i
, j
, arrName
, classes
) => {
655 this[arrName
][i
][j
] = document
.createElement("piece");
656 C
.AddClass_es(this[arrName
][i
][j
], classes
);
657 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
658 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
659 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
660 // Translate coordinates to use chessboard as reference:
661 this[arrName
][i
][j
].style
.transform
=
662 `translate(${ip - r.x}px,${jp - r.y}px)`;
663 chessboard
.appendChild(this[arrName
][i
][j
]);
665 const conditionalReset
= (arrName
) => {
667 // Refreshing: delete old pieces first. This isn't necessary,
668 // but simpler (this method isn't called many times)
669 for (let i
=0; i
<this.size
.x
; i
++) {
670 for (let j
=0; j
<this.size
.y
; j
++) {
671 if (this[arrName
][i
][j
]) {
672 this[arrName
][i
][j
].remove();
673 this[arrName
][i
][j
] = null;
679 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
680 if (arrName
== "d_pieces")
681 this.marks
.forEach(([i
, j
]) => addPiece(i
, j
, arrName
, "mark"));
684 conditionalReset("d_pieces");
685 conditionalReset("g_pieces");
686 for (let i
=0; i
< this.size
.x
; i
++) {
687 for (let j
=0; j
< this.size
.y
; j
++) {
688 if (this.board
[i
][j
] != "") {
689 const color
= this.getColor(i
, j
);
690 const piece
= this.getPiece(i
, j
);
691 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
692 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
693 if (this.enlightened
&& !this.enlightened
[i
][j
])
694 this.g_pieces
[i
][j
].classList
.add("hidden");
696 if (this.marks
&& this.d_pieces
[i
][j
]) {
697 let classes
= ["mark"];
698 if (this.board
[i
][j
] != "")
699 classes
.push("transparent");
700 addPiece(i
, j
, "d_pieces", classes
);
704 if (this.hasReserve
&& !this.isDiagram
)
705 this.re_drawReserve(['w', 'b'], r
);
708 // NOTE: assume this.reserve != null
709 re_drawReserve(colors
, r
) {
711 // Remove (old) reserve pieces
712 for (let c
of colors
) {
713 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
714 this.r_pieces
[c
][p
].remove();
715 delete this.r_pieces
[c
][p
];
716 const numId
= this.getReserveNumId(c
, p
);
717 document
.getElementById(numId
).remove();
722 this.r_pieces
= { w: {}, b: {} };
723 let container
= document
.getElementById(this.containerId
);
725 r
= container
.querySelector(".chessboard").getBoundingClientRect();
726 for (let c
of colors
) {
727 let reservesDiv
= document
.getElementById("reserves_" + c
);
729 reservesDiv
.remove();
730 if (!this.reserve
[c
])
732 const nbR
= this.getNbReservePieces(c
);
735 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
737 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
738 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
739 let rcontainer
= document
.createElement("div");
740 rcontainer
.id
= "reserves_" + c
;
741 rcontainer
.classList
.add("reserves");
742 rcontainer
.style
.left
= i0
+ "px";
743 rcontainer
.style
.top
= j0
+ "px";
744 // NOTE: +1 fix display bug on Firefox at least
745 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
746 rcontainer
.style
.height
= sqResSize
+ "px";
747 container
.appendChild(rcontainer
);
748 for (let p
of Object
.keys(this.reserve
[c
])) {
749 if (this.reserve
[c
][p
] == 0)
751 let r_cell
= document
.createElement("div");
752 r_cell
.id
= this.coordsToId({x: c
, y: p
});
753 r_cell
.classList
.add("reserve-cell");
754 r_cell
.style
.width
= sqResSize
+ "px";
755 r_cell
.style
.height
= sqResSize
+ "px";
756 rcontainer
.appendChild(r_cell
);
757 let piece
= document
.createElement("piece");
758 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
759 piece
.classList
.add(C
.GetColorClass(c
));
760 piece
.style
.width
= "100%";
761 piece
.style
.height
= "100%";
762 this.r_pieces
[c
][p
] = piece
;
763 r_cell
.appendChild(piece
);
764 let number
= document
.createElement("div");
765 number
.textContent
= this.reserve
[c
][p
];
766 number
.classList
.add("reserve-num");
767 number
.id
= this.getReserveNumId(c
, p
);
768 const fontSize
= "1.3em";
769 number
.style
.fontSize
= fontSize
;
770 number
.style
.fontSize
= fontSize
;
771 r_cell
.appendChild(number
);
777 updateReserve(color
, piece
, count
) {
778 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
779 piece
= "k"; //capturing cannibal king: back to king form
780 const oldCount
= this.reserve
[color
][piece
];
781 this.reserve
[color
][piece
] = count
;
782 // Redrawing is much easier if count==0 (or undefined)
783 if ([oldCount
, count
].some(item
=> !item
))
784 this.re_drawReserve([color
]);
786 const numId
= this.getReserveNumId(color
, piece
);
787 document
.getElementById(numId
).textContent
= count
;
791 // Resize board: no need to destroy/recreate pieces
793 const container
= document
.getElementById(this.containerId
);
794 let chessboard
= container
.querySelector(".chessboard");
795 const rc
= container
.getBoundingClientRect(),
796 r
= chessboard
.getBoundingClientRect();
797 const multFact
= (mode
== "up" ? 1.05 : 0.95);
798 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
800 const vRatio
= this.size
.ratio
|| 1;
801 if (newWidth
> rc
.width
) {
803 newHeight
= newWidth
/ vRatio
;
805 if (newHeight
> rc
.height
) {
806 newHeight
= rc
.height
;
807 newWidth
= newHeight
* vRatio
;
809 chessboard
.style
.width
= newWidth
+ "px";
810 chessboard
.style
.height
= newHeight
+ "px";
811 const newX
= (rc
.width
- newWidth
) / 2;
812 chessboard
.style
.left
= newX
+ "px";
813 const newY
= (rc
.height
- newHeight
) / 2;
814 chessboard
.style
.top
= newY
+ "px";
815 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
816 const pieceWidth
= this.getPieceWidth(newWidth
);
817 // NOTE: next "if" for variants which use squares filling
818 // instead of "physical", moving pieces
820 for (let i
=0; i
< this.size
.x
; i
++) {
821 for (let j
=0; j
< this.size
.y
; j
++) {
822 if (this.g_pieces
[i
][j
]) {
823 // NOTE: could also use CSS transform "scale"
824 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
825 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
826 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
827 // Translate coordinates to use chessboard as reference:
828 this.g_pieces
[i
][j
].style
.transform
=
829 `translate(${ip - newX}px,${jp - newY}px)`;
835 this.rescaleReserve(newR
);
839 for (let c
of ['w','b']) {
840 if (!this.reserve
[c
])
842 const nbR
= this.getNbReservePieces(c
);
845 // Resize container first
846 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
847 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
848 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
849 let rcontainer
= document
.getElementById("reserves_" + c
);
850 rcontainer
.style
.left
= i0
+ "px";
851 rcontainer
.style
.top
= j0
+ "px";
852 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
853 rcontainer
.style
.height
= sqResSize
+ "px";
854 // And then reserve cells:
855 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
856 Object
.keys(this.reserve
[c
]).forEach(p
=> {
857 if (this.reserve
[c
][p
] == 0)
859 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
860 r_cell
.style
.width
= sqResSize
+ "px";
861 r_cell
.style
.height
= sqResSize
+ "px";
866 // Return the absolute pixel coordinates given current position.
867 // Our coordinate system differs from CSS one (x <--> y).
868 // We return here the CSS coordinates (more useful).
869 getPixelPosition(i
, j
, r
) {
871 return [0, 0]; //piece vanishes
873 if (typeof i
== "string") {
874 // Reserves: need to know the rank of piece
875 const nbR
= this.getNbReservePieces(i
);
876 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
877 x
= this.getRankInReserve(i
, j
) * rsqSize
;
878 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
881 const sqSize
= r
.width
/ this.size
.y
;
882 const flipped
= (this.playerColor
== 'b');
883 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
884 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
886 return [r
.x
+ x
, r
.y
+ y
];
890 let container
= document
.getElementById(this.containerId
);
891 let chessboard
= container
.querySelector(".chessboard");
893 const getOffset
= e
=> {
896 return {x: e
.clientX
, y: e
.clientY
};
897 let touchLocation
= null;
898 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
899 // Touch screen, dragstart
900 touchLocation
= e
.targetTouches
[0];
901 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
902 // Touch screen, dragend
903 touchLocation
= e
.changedTouches
[0];
905 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
906 return {x: 0, y: 0}; //shouldn't reach here =)
909 const centerOnCursor
= (piece
, e
) => {
910 const centerShift
= this.getPieceWidth(r
.width
) / 2;
911 const offset
= getOffset(e
);
912 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
913 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
918 startPiece
, curPiece
= null,
920 const mousedown
= (e
) => {
921 // Disable zoom on smartphones:
922 if (e
.touches
&& e
.touches
.length
> 1)
924 r
= chessboard
.getBoundingClientRect();
925 pieceWidth
= this.getPieceWidth(r
.width
);
926 const cd
= this.idToCoords(e
.target
.id
);
928 const move = this.doClick(cd
);
930 this.buildMoveStack(move, r
);
931 else if (!this.clickOnly
) {
932 const [x
, y
] = Object
.values(cd
);
933 if (typeof x
!= "number")
934 startPiece
= this.r_pieces
[x
][y
];
936 startPiece
= this.g_pieces
[x
][y
];
937 if (startPiece
&& this.canIplay(x
, y
)) {
940 curPiece
= startPiece
.cloneNode();
941 curPiece
.style
.transform
= "none";
942 curPiece
.style
.zIndex
= 5;
943 curPiece
.style
.width
= pieceWidth
+ "px";
944 curPiece
.style
.height
= pieceWidth
+ "px";
945 centerOnCursor(curPiece
, e
);
946 container
.appendChild(curPiece
);
947 startPiece
.style
.opacity
= "0.4";
948 chessboard
.style
.cursor
= "none";
954 const mousemove
= (e
) => {
957 centerOnCursor(curPiece
, e
);
959 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
960 // Attempt to prevent horizontal swipe...
964 const mouseup
= (e
) => {
967 const [x
, y
] = [start
.x
, start
.y
];
970 chessboard
.style
.cursor
= "pointer";
971 startPiece
.style
.opacity
= "1";
972 const offset
= getOffset(e
);
973 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
975 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
977 // NOTE: clearly suboptimal, but much easier, and not a big deal.
978 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
979 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
980 const moves
= this.filterValid(potentialMoves
);
981 if (moves
.length
>= 2)
982 this.showChoices(moves
, r
);
983 else if (moves
.length
== 1)
984 this.buildMoveStack(moves
[0], r
);
989 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
991 if ('onmousedown' in window
) {
992 this.mouseListeners
= [
993 {type: "mousedown", listener: mousedown
},
994 {type: "mousemove", listener: mousemove
},
995 {type: "mouseup", listener: mouseup
},
996 {type: "wheel", listener: resize
}
998 this.mouseListeners
.forEach(ml
=> {
999 document
.addEventListener(ml
.type
, ml
.listener
);
1002 if ('ontouchstart' in window
) {
1003 this.touchListeners
= [
1004 {type: "touchstart", listener: mousedown
},
1005 {type: "touchmove", listener: mousemove
},
1006 {type: "touchend", listener: mouseup
}
1008 this.touchListeners
.forEach(tl
=> {
1009 // https://stackoverflow.com/a/42509310/12660887
1010 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
1013 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1016 // NOTE: not called if isDiagram, or genFenOnly
1018 let container
= document
.getElementById(this.containerId
);
1019 this.windowResizeObs
.unobserve(container
);
1020 if ('onmousedown' in window
) {
1021 this.mouseListeners
.forEach(ml
=> {
1022 document
.removeEventListener(ml
.type
, ml
.listener
);
1025 if ('ontouchstart' in window
) {
1026 this.touchListeners
.forEach(tl
=> {
1027 // https://stackoverflow.com/a/42509310/12660887
1028 document
.removeEventListener(tl
.type
, tl
.listener
);
1033 showChoices(moves
, r
) {
1034 let container
= document
.getElementById(this.containerId
);
1035 let chessboard
= container
.querySelector(".chessboard");
1036 let choices
= document
.createElement("div");
1037 choices
.id
= "choices";
1039 r
= chessboard
.getBoundingClientRect();
1040 choices
.style
.width
= r
.width
+ "px";
1041 choices
.style
.height
= r
.height
+ "px";
1042 choices
.style
.left
= r
.x
+ "px";
1043 choices
.style
.top
= r
.y
+ "px";
1044 chessboard
.style
.opacity
= "0.5";
1045 container
.appendChild(choices
);
1046 const squareWidth
= r
.width
/ this.size
.y
;
1047 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1048 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1049 const color
= moves
[0].appear
[0].c
;
1050 const callback
= (m
) => {
1051 chessboard
.style
.opacity
= "1";
1052 container
.removeChild(choices
);
1053 this.buildMoveStack(m
, r
);
1055 for (let i
=0; i
< moves
.length
; i
++) {
1056 let choice
= document
.createElement("div");
1057 choice
.classList
.add("choice");
1058 choice
.style
.width
= squareWidth
+ "px";
1059 choice
.style
.height
= squareWidth
+ "px";
1060 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1061 choice
.style
.top
= firstUpTop
+ "px";
1062 choice
.style
.backgroundColor
= "lightyellow";
1063 choice
.onclick
= () => callback(moves
[i
]);
1064 const piece
= document
.createElement("piece");
1065 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1066 C
.AddClass_es(piece
,
1067 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1068 piece
.classList
.add(C
.GetColorClass(color
));
1069 piece
.style
.width
= "100%";
1070 piece
.style
.height
= "100%";
1071 choice
.appendChild(piece
);
1072 choices
.appendChild(choice
);
1076 displayMessage(elt
, msg
, classe_s
, timeout
) {
1078 // Fixed element, e.g. for Dice Chess
1079 elt
.innerHTML
= msg
;
1081 // Temporary div (Chakart, Apocalypse...)
1082 let divMsg
= document
.createElement("div");
1083 C
.AddClass_es(divMsg
, classe_s
);
1084 divMsg
.innerHTML
= msg
;
1085 let container
= document
.getElementById(this.containerId
);
1086 container
.appendChild(divMsg
);
1087 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1094 updateEnlightened() {
1095 this.oldEnlightened
= this.enlightened
;
1096 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1097 // Add pieces positions + all squares reachable by moves (includes Zen):
1098 for (let x
=0; x
<this.size
.x
; x
++) {
1099 for (let y
=0; y
<this.size
.y
; y
++) {
1100 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1102 this.enlightened
[x
][y
] = true;
1103 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1104 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1110 this.enlightEnpassant();
1113 // Include square of the en-passant capturing square:
1114 enlightEnpassant() {
1115 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1116 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1117 for (let step
of steps
) {
1118 const x
= this.epSquare
.x
- step
[0],
1119 y
= this.getY(this.epSquare
.y
- step
[1]);
1121 this.onBoard(x
, y
) &&
1122 this.getColor(x
, y
) == this.playerColor
&&
1123 this.getPieceType(x
, y
) == "p"
1125 this.enlightened
[x
][this.epSquare
.y
] = true;
1131 // Apply diff this.enlightened --> oldEnlightened on board
1132 graphUpdateEnlightened() {
1134 document
.getElementById(this.containerId
).querySelector(".chessboard");
1135 const r
= chessboard
.getBoundingClientRect();
1136 const pieceWidth
= this.getPieceWidth(r
.width
);
1137 for (let x
=0; x
<this.size
.x
; x
++) {
1138 for (let y
=0; y
<this.size
.y
; y
++) {
1139 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1140 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1141 elt
.classList
.add("in-shadow");
1142 if (this.g_pieces
[x
][y
])
1143 this.g_pieces
[x
][y
].classList
.add("hidden");
1145 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1146 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1147 elt
.classList
.remove("in-shadow");
1148 if (this.g_pieces
[x
][y
])
1149 this.g_pieces
[x
][y
].classList
.remove("hidden");
1162 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1166 // Color of thing on square (i,j). '' if square is empty
1168 if (typeof i
== "string")
1169 return i
; //reserves
1170 return this.board
[i
][j
].charAt(0);
1173 static GetColorClass(c
) {
1178 return "other-color"; //unidentified color
1181 // Piece on i,j. '' if square is empty
1183 if (typeof j
== "string")
1184 return j
; //reserves
1185 return this.board
[i
][j
].charAt(1);
1188 // Piece type on square (i,j)
1189 getPieceType(x
, y
, p
) {
1191 p
= this.getPiece(x
, y
);
1192 return this.pieces()[p
].moveas
|| p
;
1197 p
= this.getPiece(x
, y
);
1198 if (!this.options
["cannibal"])
1200 return !!C
.CannibalKings
[p
];
1203 // Get opponent color
1204 static GetOppCol(color
) {
1205 return (color
== "w" ? "b" : "w");
1208 // Is (x,y) on the chessboard?
1210 return (x
>= 0 && x
< this.size
.x
&&
1211 y
>= 0 && y
< this.size
.y
);
1214 // Am I allowed to move thing at square x,y ?
1216 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1219 ////////////////////////
1220 // PIECES SPECIFICATIONS
1222 pieces(color
, x
, y
) {
1223 const pawnShift
= (color
== "w" ? -1 : 1);
1224 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1225 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1231 steps: [[pawnShift
, 0]],
1232 range: (initRank
? 2 : 1)
1237 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1245 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1253 [1, 2], [1, -2], [-1, 2], [-1, -2],
1254 [2, 1], [-2, 1], [2, -1], [-2, -1]
1263 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1271 [0, 1], [0, -1], [1, 0], [-1, 0],
1272 [1, 1], [1, -1], [-1, 1], [-1, -1]
1282 [0, 1], [0, -1], [1, 0], [-1, 0],
1283 [1, 1], [1, -1], [-1, 1], [-1, -1]
1290 '!': {"class": "king-pawn", moveas: "p"},
1291 '#': {"class": "king-rook", moveas: "r"},
1292 '$': {"class": "king-knight", moveas: "n"},
1293 '%': {"class": "king-bishop", moveas: "b"},
1294 '*': {"class": "king-queen", moveas: "q"}
1298 // NOTE: using special symbols to not interfere with variants' pieces codes
1299 static get CannibalKings() {
1310 static get CannibalKingCode() {
1321 //////////////////////////
1322 // MOVES GENERATION UTILS
1324 // For Cylinder: get Y coordinate
1326 if (!this.options
["cylinder"])
1328 let res
= y
% this.size
.y
;
1334 getSegments(curSeg
, segStart
, segEnd
) {
1335 if (curSeg
.length
== 0)
1337 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1338 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1342 getStepSpec(color
, x
, y
, piece
) {
1343 let pieceType
= piece
;
1344 const allSpecs
= this.pieces(color
, x
, y
);
1346 pieceType
= this.getPieceType(x
, y
);
1347 else if (allSpecs
[piece
].moveas
)
1348 pieceType
= allSpecs
[piece
].moveas
;
1349 return allSpecs
[pieceType
];
1352 // Can thing on square1 capture thing on square2?
1353 canTake([x1
, y1
], [x2
, y2
]) {
1354 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1357 canStepOver(i
, j
, p
) {
1358 // In some variants, objects on boards don't stop movement (Chakart)
1359 return this.board
[i
][j
] == "";
1362 canDrop([c
, p
], [i
, j
]) {
1364 this.board
[i
][j
] == "" &&
1365 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1368 (c
== 'w' && i
< this.size
.x
- 1) ||
1375 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1376 isImmobilized([x
, y
]) {
1377 if (!this.options
["madrasi"])
1379 const color
= this.getColor(x
, y
);
1380 const oppCol
= C
.GetOppCol(color
);
1381 const piece
= this.getPieceType(x
, y
);
1382 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1383 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1384 for (let a
of attacks
) {
1385 outerLoop: for (let step
of a
.steps
) {
1386 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1387 let stepCounter
= 1;
1388 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1389 if (a
.range
<= stepCounter
++)
1392 j
= this.getY(j
+ step
[1]);
1395 this.onBoard(i
, j
) &&
1396 this.getColor(i
, j
) == oppCol
&&
1397 this.getPieceType(i
, j
) == piece
1406 // Stop at the first capture found
1407 atLeastOneCapture(color
) {
1408 const oppCol
= C
.GetOppCol(color
);
1409 const allowed
= (sq1
, sq2
) => {
1411 // NOTE: canTake is reversed for Zen.
1412 // Generally ok because of the symmetry. TODO?
1413 this.canTake(sq1
, sq2
) &&
1415 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1418 for (let i
=0; i
<this.size
.x
; i
++) {
1419 for (let j
=0; j
<this.size
.y
; j
++) {
1420 if (this.getColor(i
, j
) == color
) {
1423 !this.options
["zen"] &&
1424 this.findDestSquares(
1429 segments: this.options
["cylinder"]
1437 this.options
["zen"] &&
1438 this.findCapturesOn(
1442 segments: this.options
["cylinder"]
1457 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1458 const epsilon
= 1e-7; //arbitrary small value
1460 if (this.options
["cylinder"])
1461 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1462 for (let sh
of shifts
) {
1463 const rx
= (x2
- x1
) / step
[0],
1464 ry
= (y2
+ sh
- y1
) / step
[1];
1466 // Zero step but non-zero interval => impossible
1467 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1468 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1469 // Negative number of step (impossible)
1470 (rx
< 0 || ry
< 0) ||
1471 // Not the same number of steps in both directions:
1472 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1476 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1477 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1479 distance
= Math
.round(distance
); //in case of (numerical...)
1480 if (!range
|| range
>= distance
)
1486 ////////////////////
1489 getDropMovesFrom([c
, p
]) {
1490 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1491 // (but not necessarily otherwise: atLeastOneMove() etc)
1492 if (this.reserve
[c
][p
] == 0)
1495 for (let i
=0; i
<this.size
.x
; i
++) {
1496 for (let j
=0; j
<this.size
.y
; j
++) {
1497 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1499 start: {x: c
, y: p
},
1501 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1504 if (this.board
[i
][j
] != "") {
1505 mv
.vanish
.push(new PiPo({
1508 c: this.getColor(i
, j
),
1509 p: this.getPiece(i
, j
)
1519 // All possible moves from selected square
1520 getPotentialMovesFrom([x
, y
], color
) {
1521 if (this.subTurnTeleport
== 2)
1523 if (typeof x
== "string")
1524 return this.getDropMovesFrom([x
, y
]);
1525 if (this.isImmobilized([x
, y
]))
1527 const piece
= this.getPieceType(x
, y
);
1528 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1529 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1530 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1532 this.isKing(0, 0, piece
) && this.hasCastle
&&
1533 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1535 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1537 return this.postProcessPotentialMoves(moves
);
1540 postProcessPotentialMoves(moves
) {
1541 if (moves
.length
== 0)
1543 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1544 const oppCol
= C
.GetOppCol(color
);
1546 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1547 moves
= this.capturePostProcess(moves
, oppCol
);
1549 if (this.options
["atomic"])
1550 moves
= this.atomicPostProcess(moves
, color
, oppCol
);
1554 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1556 moves
= this.pawnPostProcess(moves
, color
, oppCol
);
1559 if (this.options
["cannibal"] && this.options
["rifle"])
1560 // In this case a rifle-capture from last rank may promote a pawn
1561 moves
= this.riflePromotePostProcess(moves
, color
);
1566 capturePostProcess(moves
, oppCol
) {
1567 // Filter out non-capturing moves (not using m.vanish because of
1568 // self captures of Recycle and Teleport).
1569 return moves
.filter(m
=> {
1571 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1572 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1577 atomicPostProcess(moves
, color
, oppCol
) {
1578 moves
.forEach(m
=> {
1580 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1581 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1594 let mNext
= new Move({
1600 for (let step
of steps
) {
1601 let x
= m
.end
.x
+ step
[0];
1602 let y
= this.getY(m
.end
.y
+ step
[1]);
1604 this.onBoard(x
, y
) &&
1605 this.board
[x
][y
] != "" &&
1606 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1607 this.getPieceType(x
, y
) != "p"
1611 p: this.getPiece(x
, y
),
1612 c: this.getColor(x
, y
),
1619 if (!this.options
["rifle"]) {
1620 // The moving piece also vanish
1621 mNext
.vanish
.unshift(
1626 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1636 pawnPostProcess(moves
, color
, oppCol
) {
1638 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1639 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1640 moves
.forEach(m
=> {
1641 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1642 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1643 const promotionOk
= (
1645 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1648 return; //nothing to do
1649 if (this.options
["pawnfall"]) {
1655 this.options
["cannibal"] &&
1656 this.board
[x2
][y2
] != "" &&
1657 this.getColor(x2
, y2
) == oppCol
1659 finalPieces
= [this.getPieceType(x2
, y2
)];
1662 finalPieces
= this.pawnPromotions
;
1663 m
.appear
[0].p
= finalPieces
[0];
1664 if (initPiece
== "!") //cannibal king-pawn
1665 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1666 for (let i
=1; i
<finalPieces
.length
; i
++) {
1667 let newMove
= JSON
.parse(JSON
.stringify(m
));
1668 const piece
= finalPieces
[i
];
1669 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1670 moreMoves
.push(newMove
);
1673 return moves
.concat(moreMoves
);
1676 riflePromotePostProcess(moves
, color
) {
1677 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1679 moves
.forEach(m
=> {
1681 m
.start
.x
== lastRank
&&
1682 m
.appear
.length
>= 1 &&
1683 m
.appear
[0].p
== "p" &&
1684 m
.appear
[0].x
== m
.start
.x
&&
1685 m
.appear
[0].y
== m
.start
.y
1687 m
.appear
[0].p
= this.pawnPromotions
[0];
1688 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1689 let newMv
= JSON
.parse(JSON
.stringify(m
));
1690 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1691 newMoves
.push(newMv
);
1695 return moves
.concat(newMoves
);
1698 // Generic method to find possible moves of "sliding or jumping" pieces
1699 getPotentialMovesOf(piece
, [x
, y
]) {
1700 const color
= this.getColor(x
, y
);
1701 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1703 if (stepSpec
.attack
) {
1704 squares
= this.findDestSquares(
1708 segments: this.options
["cylinder"],
1711 ([i1
, j1
], [i2
, j2
]) => {
1713 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1714 this.canTake([i1
, j1
], [i2
, j2
])
1719 const noSpecials
= this.findDestSquares(
1722 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1723 segments: this.options
["cylinder"],
1727 Array
.prototype.push
.apply(squares
, noSpecials
);
1728 if (this.options
["zen"]) {
1729 let zenCaptures
= this.findCapturesOn(
1731 {}, //byCol: default is ok
1732 ([i1
, j1
], [i2
, j2
]) =>
1733 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1735 // Technical step: segments (if any) are reversed
1736 if (this.options
["cylinder"]) {
1737 zenCaptures
.forEach(z
=> {
1738 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1741 Array
.prototype.push
.apply(squares
, zenCaptures
);
1744 this.options
["recycle"] ||
1745 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1747 const selfCaptures
= this.findDestSquares(
1751 segments: this.options
["cylinder"],
1754 ([i1
, j1
], [i2
, j2
]) =>
1755 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1757 Array
.prototype.push
.apply(squares
, selfCaptures
);
1759 return squares
.map(s
=> {
1760 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1761 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1762 mv
.segments
= s
.segments
;
1767 findDestSquares([x
, y
], o
, allowed
) {
1769 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1770 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1772 // Next 3 for Cylinder mode: (unused if !o.segments)
1776 const addSquare
= ([i
, j
]) => {
1777 let elt
= {sq: [i
, j
]};
1779 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1782 const exploreSteps
= (stepArray
) => {
1783 for (let s
of stepArray
) {
1784 outerLoop: for (let step
of s
.steps
) {
1789 let [i
, j
] = [x
, y
];
1790 let stepCounter
= 0;
1792 this.onBoard(i
, j
) &&
1793 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1795 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1796 explored
[i
+ "." + j
] = true;
1799 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1801 if (o
.one
&& !o
.attackOnly
)
1804 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1805 if (o
.captureTarget
)
1809 if (s
.range
<= stepCounter
++)
1811 const oldIJ
= [i
, j
];
1813 j
= this.getY(j
+ step
[1]);
1814 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1815 // Boundary between segments (cylinder mode)
1816 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1820 if (!this.onBoard(i
, j
))
1822 const pieceIJ
= this.getPieceType(i
, j
);
1823 if (!explored
[i
+ "." + j
]) {
1824 explored
[i
+ "." + j
] = true;
1825 if (allowed([x
, y
], [i
, j
])) {
1826 if (o
.one
&& !o
.moveOnly
)
1829 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1832 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1840 return undefined; //default, but let's explicit it
1842 if (o
.captureTarget
)
1843 return exploreSteps(o
.captureSteps
)
1846 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1848 if (!o
.attackOnly
|| !stepSpec
.attack
)
1849 outOne
= exploreSteps(stepSpec
.moves
);
1850 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1851 o
.attackOnly
= true; //ok because o is always a temporary object
1852 outOne
= exploreSteps(stepSpec
.attack
);
1854 return (o
.one
? outOne : res
);
1858 // Search for enemy (or not) pieces attacking [x, y]
1859 findCapturesOn([x
, y
], o
, allowed
) {
1861 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1863 for (let i
=0; i
<this.size
.x
; i
++) {
1864 for (let j
=0; j
<this.size
.y
; j
++) {
1865 const colIJ
= this.getColor(i
, j
);
1867 this.board
[i
][j
] != "" &&
1868 o
.byCol
.includes(colIJ
) &&
1869 !this.isImmobilized([i
, j
])
1871 const apparentPiece
= this.getPiece(i
, j
);
1872 // Quick check: does this potential attacker target x,y ?
1873 if (this.canStepOver(x
, y
, apparentPiece
))
1875 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1876 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1877 for (let a
of attacks
) {
1878 for (let s
of a
.steps
) {
1879 // Quick check: if step isn't compatible, don't even try
1880 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1882 // Finally verify that nothing stand in-between
1883 const out
= this.findDestSquares(
1886 captureTarget: [x
, y
],
1887 captureSteps: [{steps: [s
], range: a
.range
}],
1888 segments: o
.segments
,
1890 one: false //one and captureTarget are mutually exclusive
1904 return (o
.one
? false : res
);
1907 // Build a regular move from its initial and destination squares.
1908 // tr: transformation
1909 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1910 const initColor
= this.getColor(sx
, sy
);
1911 const initPiece
= this.getPiece(sx
, sy
);
1912 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1916 start: {x: sx
, y: sy
},
1920 !this.options
["rifle"] ||
1921 this.board
[ex
][ey
] == "" ||
1922 destColor
== initColor
//Recycle, Teleport
1928 c: !!tr
? tr
.c : initColor
,
1929 p: !!tr
? tr
.p : initPiece
1941 if (this.board
[ex
][ey
] != "") {
1946 c: this.getColor(ex
, ey
),
1947 p: this.getPiece(ex
, ey
)
1950 if (this.options
["cannibal"] && destColor
!= initColor
) {
1951 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1952 let trPiece
= mv
.vanish
[lastIdx
].p
;
1953 if (this.isKing(sx
, sy
))
1954 trPiece
= C
.CannibalKingCode
[trPiece
];
1955 if (mv
.appear
.length
>= 1)
1956 mv
.appear
[0].p
= trPiece
;
1957 else if (this.options
["rifle"]) {
1980 // En-passant square, if any
1981 getEpSquare(moveOrSquare
) {
1982 if (typeof moveOrSquare
=== "string") {
1983 const square
= moveOrSquare
;
1986 return C
.SquareToCoords(square
);
1988 // Argument is a move:
1989 const move = moveOrSquare
;
1990 const s
= move.start
,
1994 Math
.abs(s
.x
- e
.x
) == 2 &&
1995 // Next conditions for variants like Atomic or Rifle, Recycle...
1997 move.appear
.length
> 0 &&
1998 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
2002 move.vanish
.length
> 0 &&
2003 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
2011 return undefined; //default
2014 // Special case of en-passant captures: treated separately
2015 getEnpassantCaptures([x
, y
]) {
2016 const color
= this.getColor(x
, y
);
2017 const shiftX
= (color
== 'w' ? -1 : 1);
2018 const oppCol
= C
.GetOppCol(color
);
2021 this.epSquare
.x
== x
+ shiftX
&&
2022 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2023 // Doublemove (and Progressive?) guards:
2024 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2025 this.getColor(x
, this.epSquare
.y
) == oppCol
2027 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2028 this.board
[epx
][epy
] = oppCol
+ 'p';
2029 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2030 this.board
[epx
][epy
] = "";
2031 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2032 enpassantMove
.vanish
[lastIdx
].x
= x
;
2033 return [enpassantMove
];
2038 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2039 const c
= this.getColor(x
, y
);
2042 const oppCol
= C
.GetOppCol(c
);
2046 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2047 const castlingKing
= this.getPiece(x
, y
);
2048 castlingCheck: for (
2051 castleSide
++ //large, then small
2053 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2055 // If this code is reached, rook and king are on initial position
2057 // NOTE: in some variants this is not a rook
2058 const rookPos
= this.castleFlags
[c
][castleSide
];
2059 const castlingPiece
= this.getPiece(x
, rookPos
);
2061 this.board
[x
][rookPos
] == "" ||
2062 this.getColor(x
, rookPos
) != c
||
2063 (castleWith
&& !castleWith
.includes(castlingPiece
))
2065 // Rook is not here, or changed color (see Benedict)
2068 // Nothing on the path of the king ? (and no checks)
2069 const finDist
= finalSquares
[castleSide
][0] - y
;
2070 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2074 // NOTE: next weird test because underCheck() verification
2075 // will be executed in filterValid() later.
2077 i
!= finalSquares
[castleSide
][0] &&
2078 this.underCheck([x
, i
], oppCol
)
2082 this.board
[x
][i
] != "" &&
2083 // NOTE: next check is enough, because of chessboard constraints
2084 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2087 continue castlingCheck
;
2090 } while (i
!= finalSquares
[castleSide
][0]);
2091 // Nothing on the path to the rook?
2092 step
= (castleSide
== 0 ? -1 : 1);
2093 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2094 if (this.board
[x
][i
] != "")
2095 continue castlingCheck
;
2098 // Nothing on final squares, except maybe king and castling rook?
2099 for (i
= 0; i
< 2; i
++) {
2101 finalSquares
[castleSide
][i
] != rookPos
&&
2102 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2104 finalSquares
[castleSide
][i
] != y
||
2105 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2108 continue castlingCheck
;
2112 // If this code is reached, castle is potentially valid
2118 y: finalSquares
[castleSide
][0],
2124 y: finalSquares
[castleSide
][1],
2130 // King might be initially disguised (Titan...)
2131 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2132 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2135 Math
.abs(y
- rookPos
) <= 2
2136 ? {x: x
, y: rookPos
}
2137 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2145 ////////////////////
2148 // Is piece (or square) at given position attacked by "oppCol" ?
2149 underAttack([x
, y
], oppCol
) {
2150 // An empty square is considered as king,
2151 // since it's used only in getCastleMoves (TODO?)
2152 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2155 (!this.options
["zen"] || king
) &&
2156 this.findCapturesOn(
2160 segments: this.options
["cylinder"],
2167 (!!this.options
["zen"] && !king
) &&
2168 this.findDestSquares(
2172 segments: this.options
["cylinder"],
2175 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2181 // Argument is (very generally) an array of squares (= arrays)
2182 underCheck(square_s
, oppCol
) {
2183 if (this.options
["taking"] || this.options
["dark"])
2185 if (!Array
.isArray(square_s
[0]))
2186 square_s
= [square_s
];
2187 return square_s
.some(sq
=> this.underAttack(sq
, oppCol
));
2190 // Scan board for king(s)
2191 searchKingPos(color
) {
2193 for (let i
=0; i
< this.size
.x
; i
++) {
2194 for (let j
=0; j
< this.size
.y
; j
++) {
2195 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2202 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2203 filterValid(moves
, color
) {
2206 const oppCol
= C
.GetOppCol(color
);
2207 let kingPos
= this.searchKingPos(color
);
2208 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2209 return moves
.filter(m
=> {
2210 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2211 if (!filtered
[key
]) {
2212 this.playOnBoard(m
);
2213 let newKingPP
= null,
2215 res
= true; //a priori valid
2217 m
.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2219 // Search king in appear array:
2221 m
.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2223 sqIdx
= kingPos
.findIndex(kp
=>
2224 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2225 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2228 res
= false; //king vanished
2230 res
&&= !this.underCheck(kingPos
, oppCol
);
2231 if (oldKingPP
&& newKingPP
)
2232 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2233 this.undoOnBoard(m
);
2234 filtered
[key
] = res
;
2237 return filtered
[key
];
2244 // Apply a move on board
2246 for (let psq
of move.vanish
)
2247 this.board
[psq
.x
][psq
.y
] = "";
2248 for (let psq
of move.appear
)
2249 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2251 // Un-apply the played move
2253 for (let psq
of move.appear
)
2254 this.board
[psq
.x
][psq
.y
] = "";
2255 for (let psq
of move.vanish
)
2256 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2259 updateCastleFlags(move) {
2260 // Update castling flags if start or arrive from/at rook/king locations
2261 move.appear
.concat(move.vanish
).forEach(psq
=> {
2262 if (this.isKing(0, 0, psq
.p
))
2263 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2264 // NOTE: not "else if" because king can capture enemy rook...
2268 else if (psq
.x
== this.size
.x
- 1)
2271 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2273 this.castleFlags
[c
][fidx
] = this.size
.y
;
2281 // If flags already off, no need to re-check:
2282 Object
.values(this.castleFlags
).some(cvals
=>
2283 cvals
.some(val
=> val
< this.size
.y
))
2285 this.updateCastleFlags(move);
2287 if (this.options
["crazyhouse"]) {
2288 move.vanish
.forEach(v
=> {
2289 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2290 if (this.ispawn
[square
])
2291 delete this.ispawn
[square
];
2293 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2294 // Assumption: something is moving
2295 const initSquare
= C
.CoordsToSquare(move.start
);
2296 const destSquare
= C
.CoordsToSquare(move.end
);
2298 this.ispawn
[initSquare
] ||
2299 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2301 this.ispawn
[destSquare
] = true;
2304 this.ispawn
[destSquare
] &&
2305 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2307 move.vanish
[1].p
= 'p';
2308 delete this.ispawn
[destSquare
];
2312 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2315 // Warning; atomic pawn removal isn't a capture
2316 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2318 const color
= this.turn
;
2319 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2320 // Something appears = dropped on board (some exceptions, Chakart...)
2321 if (move.appear
[i
].c
== color
) {
2322 const piece
= move.appear
[i
].p
;
2323 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2326 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2327 // Something vanish: add to reserve except if recycle & opponent
2329 this.options
["crazyhouse"] ||
2330 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2332 const piece
= move.vanish
[i
].p
;
2333 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2341 if (this.hasEnpassant
)
2342 this.epSquare
= this.getEpSquare(move);
2343 this.playOnBoard(move);
2344 this.postPlay(move);
2348 if (this.options
["dark"])
2349 this.updateEnlightened();
2350 if (this.options
["teleport"]) {
2352 this.subTurnTeleport
== 1 &&
2353 move.vanish
.length
> move.appear
.length
&&
2354 move.vanish
[1].c
== this.turn
2356 const v
= move.vanish
[move.vanish
.length
- 1];
2357 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2358 this.subTurnTeleport
= 2;
2361 this.subTurnTeleport
= 1;
2362 this.captured
= null;
2364 this.tryChangeTurn(move);
2367 tryChangeTurn(move) {
2368 if (this.isLastMove(move)) {
2369 this.turn
= C
.GetOppCol(this.turn
);
2373 else if (!move.next
)
2380 const color
= this.turn
;
2381 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2382 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, color
))
2386 !this.options
["balance"] ||
2387 ![1, 2].includes(this.movesCount
) ||
2392 !this.options
["doublemove"] ||
2393 this.movesCount
== 0 ||
2398 !this.options
["progressive"] ||
2399 this.subTurn
== this.movesCount
+ 1
2404 // "Stop at the first move found"
2405 atLeastOneMove(color
) {
2406 for (let i
= 0; i
< this.size
.x
; i
++) {
2407 for (let j
= 0; j
< this.size
.y
; j
++) {
2408 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2409 // NOTE: in fact searching for all potential moves from i,j.
2410 // I don't believe this is an issue, for now at least.
2411 const moves
= this.getPotentialMovesFrom([i
, j
]);
2412 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2417 if (this.hasReserve
&& this.reserve
[color
]) {
2418 for (let p
of Object
.keys(this.reserve
[color
])) {
2419 const moves
= this.getDropMovesFrom([color
, p
]);
2420 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2427 // What is the score ? (Interesting if game is over)
2428 getCurrentScore(move_s
) {
2429 const move = move_s
[move_s
.length
- 1];
2430 // Shortcut in case the score was computed before:
2433 const color
= this.turn
;
2434 const oppCol
= C
.GetOppCol(color
);
2436 [color
]: this.searchKingPos(color
),
2437 [oppCol
]: this.searchKingPos(oppCol
)
2439 if (kingPos
[color
].length
== 0 && kingPos
[oppCol
].length
== 0)
2441 if (kingPos
[color
].length
== 0)
2442 return (color
== "w" ? "0-1" : "1-0");
2443 if (kingPos
[oppCol
].length
== 0)
2444 return (color
== "w" ? "1-0" : "0-1");
2445 if (this.atLeastOneMove(color
))
2447 // No valid move: stalemate or checkmate?
2448 if (!this.underCheck(kingPos
[color
], oppCol
))
2451 return (color
== "w" ? "0-1" : "1-0");
2454 playVisual(move, r
) {
2455 move.vanish
.forEach(v
=> {
2456 this.g_pieces
[v
.x
][v
.y
].remove();
2457 this.g_pieces
[v
.x
][v
.y
] = null;
2460 document
.getElementById(this.containerId
).querySelector(".chessboard");
2462 r
= chessboard
.getBoundingClientRect();
2463 const pieceWidth
= this.getPieceWidth(r
.width
);
2464 move.appear
.forEach(a
=> {
2465 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2466 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2467 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2468 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2469 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2470 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2471 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2472 // Translate coordinates to use chessboard as reference:
2473 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2474 `translate(${ip - r.x}px,${jp - r.y}px)`;
2475 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2476 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2477 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2479 if (this.options
["dark"])
2480 this.graphUpdateEnlightened();
2483 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2484 buildMoveStack(move, r
) {
2485 this.moveStack
.push(move);
2486 this.computeNextMove(move);
2487 const then
= () => {
2488 const newTurn
= this.turn
;
2489 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2490 this.playVisual(move, r
);
2494 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2496 this.buildMoveStack(move.next
, r
);
2499 if (this.moveStack
.length
== 1) {
2500 // Usual case (one normal move)
2501 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2502 this.moveStack
= [];
2505 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2506 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2507 this.playReceivedMove(this.moveStack
.slice(1), () => {
2508 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2509 this.moveStack
= [];
2514 // If hiding moves, then they are revealed in play() with callback
2515 this.play(move, this.hideMoves
? then : null);
2516 if (!this.hideMoves
)
2520 // Implemented in variants using (automatic) moveStack
2521 computeNextMove(move) {}
2523 animateMoving(start
, end
, drag
, segments
, cb
) {
2524 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2525 // NOTE: cloning often not required, but light enough, and simpler
2526 let movingPiece
= initPiece
.cloneNode();
2527 initPiece
.style
.opacity
= "0";
2529 document
.getElementById(this.containerId
)
2530 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2531 if (typeof start
.x
== "string") {
2532 // Need to bound width/height (was 100% for reserve pieces)
2533 const pieceWidth
= this.getPieceWidth(r
.width
);
2534 movingPiece
.style
.width
= pieceWidth
+ "px";
2535 movingPiece
.style
.height
= pieceWidth
+ "px";
2537 const maxDist
= this.getMaxDistance(r
);
2538 const apparentColor
= this.getColor(start
.x
, start
.y
);
2539 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2541 const startCode
= this.getPiece(start
.x
, start
.y
);
2542 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2543 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2544 if (apparentColor
!= drag
.c
) {
2545 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2546 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2549 container
.appendChild(movingPiece
);
2550 const animateSegment
= (index
, cb
) => {
2551 // NOTE: move.drag could be generalized per-segment (usage?)
2552 const [i1
, j1
] = segments
[index
][0];
2553 const [i2
, j2
] = segments
[index
][1];
2554 const dep
= this.getPixelPosition(i1
, j1
, r
);
2555 const arr
= this.getPixelPosition(i2
, j2
, r
);
2556 movingPiece
.style
.transitionDuration
= "0s";
2557 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2559 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2560 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2561 // TODO: unclear why we need this new delay below:
2563 movingPiece
.style
.transitionDuration
= duration
+ "s";
2564 // movingPiece is child of container: no need to adjust coordinates
2565 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2566 setTimeout(cb
, duration
* 1000);
2570 const animateSegmentCallback
= () => {
2571 if (index
< segments
.length
)
2572 animateSegment(index
++, animateSegmentCallback
);
2574 movingPiece
.remove();
2575 initPiece
.style
.opacity
= "1";
2579 animateSegmentCallback();
2582 // Input array of objects with at least fields x,y (e.g. PiPo)
2583 animateFading(arr
, cb
) {
2584 const animLength
= 350; //TODO: 350ms? More? Less?
2586 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2587 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2588 fadingPiece
.style
.opacity
= "0";
2590 setTimeout(cb
, animLength
);
2593 animate(move, callback
) {
2594 if (this.noAnimate
|| move.noAnimate
) {
2598 let segments
= move.segments
;
2600 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2601 let targetObj
= new TargetObj(callback
);
2602 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2604 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2605 () => targetObj
.increment());
2607 if (move.vanish
.length
> move.appear
.length
) {
2608 const arr
= move.vanish
.slice(move.appear
.length
)
2609 // Ignore disappearing pieces hidden by some appearing ones:
2610 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2611 if (arr
.length
> 0) {
2613 this.animateFading(arr
, () => targetObj
.increment());
2617 this.tryAnimateCastle(move, () => targetObj
.increment());
2619 this.customAnimate(move, segments
, () => targetObj
.increment());
2620 if (targetObj
.target
== 0)
2624 tryAnimateCastle(move, cb
) {
2627 move.vanish
.length
== 2 &&
2628 move.appear
.length
== 2 &&
2629 this.isKing(0, 0, move.vanish
[0].p
) &&
2630 this.isKing(0, 0, move.appear
[0].p
)
2632 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2633 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2634 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2635 this.animateMoving(start
, end
, null, segments
, cb
);
2641 // Potential other animations (e.g. for Suction variant)
2642 customAnimate(move, segments
, cb
) {
2643 return 0; //nb of targets
2646 launchAnimation(moves
, container
, callback
) {
2647 if (this.hideMoves
) {
2648 for (let i
=0; i
<moves
.length
; i
++)
2649 // If hiding moves, they are revealed into play():
2650 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2653 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2654 const animateRec
= i
=> {
2655 this.animate(moves
[i
], () => {
2656 this.play(moves
[i
]);
2657 this.playVisual(moves
[i
], r
);
2658 if (i
< moves
.length
- 1)
2659 setTimeout(() => animateRec(i
+1), 300);
2667 playReceivedMove(moves
, callback
) {
2668 // Delay if user wasn't focused:
2669 const checkDisplayThenAnimate
= (delay
) => {
2670 if (container
.style
.display
== "none") {
2671 alert("New move! Let's go back to game...");
2672 document
.getElementById("gameInfos").style
.display
= "none";
2673 container
.style
.display
= "block";
2675 () => this.launchAnimation(moves
, container
, callback
),
2681 () => this.launchAnimation(moves
, container
, callback
),
2686 let container
= document
.getElementById(this.containerId
);
2687 if (document
.hidden
) {
2688 document
.onvisibilitychange
= () => {
2689 document
.onvisibilitychange
= undefined;
2690 checkDisplayThenAnimate(700);
2694 checkDisplayThenAnimate();