aea3f57bbf641d743e32e818f6cc8aadbdbde1ff
1 import {Random
} from "/utils/alea.js";
2 import {ArrayFun
} from "/utils/array.js";
3 import {FenUtil
} from "/utils/setupPieces.js";
4 import PiPo
from "/utils/PiPo.js";
5 import Move
from "/utils/Move.js";
7 // Helper class for move animation
10 constructor(callOnComplete
) {
13 this.callOnComplete
= callOnComplete
;
16 if (++this.value
== this.target
)
17 this.callOnComplete();
22 // NOTE: x coords: top to bottom (white perspective); y: left to right
23 // NOTE: ChessRules is aliased as window.C, and variants as window.V
24 export default class ChessRules
{
26 static get Aliases() {
27 return {'C': ChessRules
};
30 /////////////////////////
31 // VARIANT SPECIFICATIONS
33 // Some variants have specific options, like the number of pawns in Monster,
34 // or the board size for Pandemonium.
35 // Users can generally select a randomness level from 0 to 2.
36 static get Options() {
40 variable: "randomness",
43 {label: "Deterministic", value: 0},
44 {label: "Symmetric random", value: 1},
45 {label: "Asymmetric random", value: 2}
50 label: "Capture king",
56 label: "Falling pawn",
62 // Game modifiers (using "elementary variants"). Default: false
65 "balance", //takes precedence over doublemove & progressive
69 "cylinder", //ok with all
73 "progressive", //(natural) priority over doublemove
82 get pawnPromotions() {
83 return ['q', 'r', 'n', 'b'];
86 // Some variants don't have flags:
95 // En-passant captures allowed?
102 !!this.options
["crazyhouse"] ||
103 (!!this.options
["recycle"] && !this.options
["teleport"])
106 // Some variants do not store reserve state (Align4, Chakart...)
107 get hasReserveFen() {
108 return this.hasReserve
;
112 return !!this.options
["dark"];
115 // Some variants use only click information
120 // Some variants reveal moves only after both players played
125 // Some variants do not flip board as black
127 return (this.playerColor
== 'b');
130 // Some variants use click infos:
132 if (typeof coords
.x
!= "number")
133 return null; //click on reserves
135 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
136 this.board
[coords
.x
][coords
.y
] == ""
139 start: {x: this.captured
.x
, y: this.captured
.y
},
150 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
159 // 3a --> {x:3, y:10}
160 static SquareToCoords(sq
) {
161 return ArrayFun
.toObject(["x", "y"],
162 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
165 // {x:11, y:12} --> bc
166 static CoordsToSquare(cd
) {
167 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
171 if (typeof cd
.x
== "number") {
173 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
177 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
180 idToCoords(targetId
) {
182 return null; //outside page, maybe...
183 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
185 idParts
.length
< 2 ||
186 idParts
[0] != this.containerId
||
187 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
191 const squares
= idParts
[1].split('-');
192 if (squares
[0] == "sq")
193 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
194 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
195 return {x: squares
[1], y: squares
[2]};
201 // Turn "wb" into "B" (for FEN)
203 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
206 // Turn "p" into "bp" (for board)
208 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
211 genRandInitFen(seed
) {
212 Random
.setSeed(seed
); //may be unused
213 let baseFen
= this.genRandInitBaseFen();
214 baseFen
.o
= Object
.assign({init: true}, baseFen
.o
);
215 const parts
= this.getPartFen(baseFen
.o
);
217 baseFen
.fen
+ " w 0" +
218 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
222 // Setup the initial random-or-not (asymmetric-or-not) position
223 genRandInitBaseFen() {
224 const s
= FenUtil
.setupPieces(
225 ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
227 randomness: this.options
["randomness"],
228 between: {p1: 'k', p2: 'r'},
234 fen: s
.b
.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
235 s
.w
.join("").toUpperCase(),
240 // "Parse" FEN: just return untransformed string data
242 const fenParts
= fen
.split(" ");
244 position: fenParts
[0],
246 movesCount: fenParts
[2]
248 if (fenParts
.length
> 3)
249 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
253 // Return current fen (game state)
255 const parts
= this.getPartFen({});
258 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
263 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
269 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
270 if (this.hasEnpassant
)
271 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
272 if (this.hasReserveFen
)
273 parts
["reserve"] = this.getReserveFen(o
);
274 if (this.options
["crazyhouse"])
275 parts
["ispawn"] = this.getIspawnFen(o
);
279 static FenEmptySquares(count
) {
280 // if more than 9 consecutive free spaces, break the integer,
281 // otherwise FEN parsing will fail.
284 // Most boards of size < 18:
286 return "9" + (count
- 9);
288 return "99" + (count
- 18);
291 // Position part of the FEN string
294 for (let i
= 0; i
< this.size
.x
; i
++) {
296 for (let j
= 0; j
< this.size
.y
; j
++) {
297 if (this.board
[i
][j
] == "")
300 if (emptyCount
> 0) {
301 // Add empty squares in-between
302 position
+= C
.FenEmptySquares(emptyCount
);
305 position
+= this.board2fen(this.board
[i
][j
]);
310 position
+= C
.FenEmptySquares(emptyCount
);
311 if (i
< this.size
.x
- 1)
312 position
+= "/"; //separate rows
317 // Flags part of the FEN string
319 return ["w", "b"].map(c
=> {
320 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
324 // Enpassant part of the FEN string
328 return C
.CoordsToSquare(this.epSquare
);
333 return "000000000000";
335 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
341 // NOTE: cannot merge because this.ispawn doesn't exist yet
343 const squares
= Object
.keys(this.ispawn
);
344 if (squares
.length
== 0)
346 return squares
.join(",");
349 // Set flags from fen (castle: white a,h then black a,h)
352 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
353 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
361 this.options
= o
.options
;
362 // Fill missing options (always the case if random challenge)
363 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
364 if (this.options
[opt
.variable
] === undefined)
365 this.options
[opt
.variable
] = opt
.defaut
;
369 this.playerColor
= o
.color
;
370 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
371 this.containerId
= o
.element
;
372 this.isDiagram
= o
.diagram
;
373 this.marks
= o
.marks
;
377 o
.fen
= this.genRandInitFen(o
.seed
);
378 this.re_initFromFen(o
.fen
);
379 this.graphicalInit();
382 re_initFromFen(fen
, oldBoard
) {
383 const fenParsed
= this.parseFen(fen
);
384 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
385 this.turn
= fenParsed
.turn
;
386 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
387 this.setOtherVariables(fenParsed
);
390 // Turn position fen into double array ["wb","wp","bk",...]
392 const rows
= position
.split("/");
393 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
394 for (let i
= 0; i
< rows
.length
; i
++) {
396 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
397 const character
= rows
[i
][indexInRow
];
398 const num
= parseInt(character
, 10);
399 // If num is a number, just shift j:
402 // Else: something at position i,j
404 board
[i
][j
++] = this.fen2board(character
);
410 // Some additional variables from FEN (variant dependant)
411 setOtherVariables(fenParsed
, pieceArray
) {
412 // Set flags and enpassant:
414 this.setFlags(fenParsed
.flags
);
415 if (this.hasEnpassant
)
416 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
417 if (this.hasReserve
&& !this.isDiagram
)
418 this.initReserves(fenParsed
.reserve
, pieceArray
);
419 if (this.options
["crazyhouse"])
420 this.initIspawn(fenParsed
.ispawn
);
421 if (this.options
["teleport"]) {
422 this.subTurnTeleport
= 1;
423 this.captured
= null;
425 if (this.options
["dark"]) {
426 // Setup enlightened: squares reachable by player side
427 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
428 this.updateEnlightened();
430 this.subTurn
= 1; //may be unused
431 if (!this.moveStack
) //avoid resetting (unwanted)
435 // ordering as in pieces() p,r,n,b,q,k
436 initReserves(reserveStr
, pieceArray
) {
438 pieceArray
= ['p', 'r', 'n', 'b', 'q', 'k'];
439 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
440 const L
= pieceArray
.length
;
442 w: ArrayFun
.toObject(pieceArray
, counts
.slice(0, L
)),
443 b: ArrayFun
.toObject(pieceArray
, counts
.slice(L
, 2 * L
))
447 initIspawn(ispawnStr
) {
448 if (ispawnStr
!= "-")
449 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
457 getPieceWidth(rwidth
) {
458 return (rwidth
/ this.size
.y
);
461 getReserveSquareSize(rwidth
, nbR
) {
462 const sqSize
= this.getPieceWidth(rwidth
);
463 return Math
.min(sqSize
, rwidth
/ nbR
);
466 getReserveNumId(color
, piece
) {
467 return `${this.containerId}|rnum-${color}${piece}`;
470 getNbReservePieces(color
) {
472 Object
.values(this.reserve
[color
]).reduce(
473 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
477 getRankInReserve(c
, p
) {
478 const pieces
= Object
.keys(this.pieces(c
, c
, p
));
479 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
480 let toTest
= pieces
.slice(0, lastIndex
);
481 return toTest
.reduce(
482 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
485 static AddClass_es(elt
, class_es
) {
486 if (!Array
.isArray(class_es
))
487 class_es
= [class_es
];
488 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
491 static RemoveClass_es(elt
, class_es
) {
492 if (!Array
.isArray(class_es
))
493 class_es
= [class_es
];
494 class_es
.forEach(cl
=> elt
.classList
.remove(cl
));
497 // Generally light square bottom-right
498 getSquareColorClass(x
, y
) {
499 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
503 // Works for all rectangular boards:
504 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
508 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
515 const g_init
= () => {
516 this.re_drawBoardElements();
517 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
518 this.initMouseEvents();
520 let container
= document
.getElementById(this.containerId
);
521 this.windowResizeObs
= new ResizeObserver(g_init
);
522 this.windowResizeObs
.observe(container
);
525 re_drawBoardElements() {
526 const board
= this.getSvgChessboard();
527 const container
= document
.getElementById(this.containerId
);
528 const rc
= container
.getBoundingClientRect();
529 let chessboard
= container
.querySelector(".chessboard");
530 chessboard
.innerHTML
= "";
531 chessboard
.insertAdjacentHTML('beforeend', board
);
532 // Compare window ratio width / height to aspectRatio:
533 const windowRatio
= rc
.width
/ rc
.height
;
534 let cbWidth
, cbHeight
;
535 const vRatio
= this.size
.ratio
|| 1;
536 if (windowRatio
<= vRatio
) {
537 // Limiting dimension is width:
538 cbWidth
= Math
.min(rc
.width
, 767);
539 cbHeight
= cbWidth
/ vRatio
;
542 // Limiting dimension is height:
543 cbHeight
= Math
.min(rc
.height
, 767);
544 cbWidth
= cbHeight
* vRatio
;
546 if (this.hasReserve
&& !this.isDiagram
) {
547 const sqSize
= cbWidth
/ this.size
.y
;
548 // NOTE: allocate space for reserves (up/down) even if they are empty
549 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
550 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
551 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
552 cbWidth
= cbHeight
* vRatio
;
555 chessboard
.style
.width
= cbWidth
+ "px";
556 chessboard
.style
.height
= cbHeight
+ "px";
557 // Center chessboard:
558 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
559 spaceTop
= (rc
.height
- cbHeight
) / 2;
560 chessboard
.style
.left
= spaceLeft
+ "px";
561 chessboard
.style
.top
= spaceTop
+ "px";
562 // Give sizes instead of recomputing them,
563 // because chessboard might not be drawn yet.
564 this.setupVisualPieces({
572 // Get SVG board (background, no pieces)
574 const flipped
= this.flippedBoard
;
577 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
578 class="chessboard_SVG">`;
579 for (let i
=0; i
< this.size
.x
; i
++) {
580 for (let j
=0; j
< this.size
.y
; j
++) {
581 if (!this.onBoard(i
, j
))
583 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
584 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
585 let classes
= this.getSquareColorClass(ii
, jj
);
586 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
587 classes
+= " in-shadow";
588 // NOTE: x / y reversed because coordinates system is reversed.
592 id="${this.coordsToId({x: ii, y: jj})}"
604 setupVisualPieces(r
) {
606 document
.getElementById(this.containerId
).querySelector(".chessboard");
608 r
= chessboard
.getBoundingClientRect();
609 const pieceWidth
= this.getPieceWidth(r
.width
);
610 const addPiece
= (i
, j
, arrName
, classes
) => {
611 this[arrName
][i
][j
] = document
.createElement("piece");
612 C
.AddClass_es(this[arrName
][i
][j
], classes
);
613 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
614 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
615 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
616 // Translate coordinates to use chessboard as reference:
617 this[arrName
][i
][j
].style
.transform
=
618 `translate(${ip - r.x}px,${jp - r.y}px)`;
619 chessboard
.appendChild(this[arrName
][i
][j
]);
621 const conditionalReset
= (arrName
) => {
623 // Refreshing: delete old pieces first. This isn't necessary,
624 // but simpler (this method isn't called many times)
625 for (let i
=0; i
<this.size
.x
; i
++) {
626 for (let j
=0; j
<this.size
.y
; j
++) {
627 if (this[arrName
][i
][j
]) {
628 this[arrName
][i
][j
].remove();
629 this[arrName
][i
][j
] = null;
635 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
636 if (arrName
== "d_pieces")
637 this.marks
.forEach(([i
, j
]) => addPiece(i
, j
, arrName
, "mark"));
640 conditionalReset("d_pieces");
641 conditionalReset("g_pieces");
642 for (let i
=0; i
< this.size
.x
; i
++) {
643 for (let j
=0; j
< this.size
.y
; j
++) {
644 if (this.board
[i
][j
] != "") {
645 const color
= this.getColor(i
, j
);
646 const piece
= this.getPiece(i
, j
);
647 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
648 this.g_pieces
[i
][j
].classList
.add(V
.GetColorClass(color
));
649 if (this.enlightened
&& !this.enlightened
[i
][j
])
650 this.g_pieces
[i
][j
].classList
.add("hidden");
652 if (this.marks
&& this.d_pieces
[i
][j
]) {
653 let classes
= ["mark"];
654 if (this.board
[i
][j
] != "")
655 classes
.push("transparent");
656 addPiece(i
, j
, "d_pieces", classes
);
660 if (this.hasReserve
&& !this.isDiagram
)
661 this.re_drawReserve(['w', 'b'], r
);
664 // NOTE: assume this.reserve != null
665 re_drawReserve(colors
, r
) {
667 // Remove (old) reserve pieces
668 for (let c
of colors
) {
669 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
670 this.r_pieces
[c
][p
].remove();
671 delete this.r_pieces
[c
][p
];
672 const numId
= this.getReserveNumId(c
, p
);
673 document
.getElementById(numId
).remove();
678 this.r_pieces
= { w: {}, b: {} };
679 let container
= document
.getElementById(this.containerId
);
681 r
= container
.querySelector(".chessboard").getBoundingClientRect();
682 for (let c
of colors
) {
683 let reservesDiv
= document
.getElementById("reserves_" + c
);
685 reservesDiv
.remove();
686 if (!this.reserve
[c
])
688 const nbR
= this.getNbReservePieces(c
);
691 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
693 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
694 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
695 let rcontainer
= document
.createElement("div");
696 rcontainer
.id
= "reserves_" + c
;
697 rcontainer
.classList
.add("reserves");
698 rcontainer
.style
.left
= i0
+ "px";
699 rcontainer
.style
.top
= j0
+ "px";
700 // NOTE: +1 fix display bug on Firefox at least
701 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
702 rcontainer
.style
.height
= sqResSize
+ "px";
703 container
.appendChild(rcontainer
);
704 for (let p
of Object
.keys(this.reserve
[c
])) {
705 if (this.reserve
[c
][p
] == 0)
707 let r_cell
= document
.createElement("div");
708 r_cell
.id
= this.coordsToId({x: c
, y: p
});
709 r_cell
.classList
.add("reserve-cell");
710 r_cell
.style
.width
= sqResSize
+ "px";
711 r_cell
.style
.height
= sqResSize
+ "px";
712 rcontainer
.appendChild(r_cell
);
713 let piece
= document
.createElement("piece");
714 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
715 piece
.classList
.add(V
.GetColorClass(c
));
716 piece
.style
.width
= "100%";
717 piece
.style
.height
= "100%";
718 this.r_pieces
[c
][p
] = piece
;
719 r_cell
.appendChild(piece
);
720 let number
= document
.createElement("div");
721 number
.textContent
= this.reserve
[c
][p
];
722 number
.classList
.add("reserve-num");
723 number
.id
= this.getReserveNumId(c
, p
);
724 const fontSize
= "1.3em";
725 number
.style
.fontSize
= fontSize
;
726 number
.style
.fontSize
= fontSize
;
727 r_cell
.appendChild(number
);
733 updateReserve(color
, piece
, count
) {
734 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
735 piece
= "k"; //capturing cannibal king: back to king form
736 const oldCount
= this.reserve
[color
][piece
];
737 this.reserve
[color
][piece
] = count
;
738 // Redrawing is much easier if count==0 (or undefined)
739 if ([oldCount
, count
].some(item
=> !item
))
740 this.re_drawReserve([color
]);
742 const numId
= this.getReserveNumId(color
, piece
);
743 document
.getElementById(numId
).textContent
= count
;
747 // Resize board: no need to destroy/recreate pieces
749 const container
= document
.getElementById(this.containerId
);
750 let chessboard
= container
.querySelector(".chessboard");
751 const rc
= container
.getBoundingClientRect(),
752 r
= chessboard
.getBoundingClientRect();
753 const multFact
= (mode
== "up" ? 1.05 : 0.95);
754 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
756 const vRatio
= this.size
.ratio
|| 1;
757 if (newWidth
> rc
.width
) {
759 newHeight
= newWidth
/ vRatio
;
761 if (newHeight
> rc
.height
) {
762 newHeight
= rc
.height
;
763 newWidth
= newHeight
* vRatio
;
765 chessboard
.style
.width
= newWidth
+ "px";
766 chessboard
.style
.height
= newHeight
+ "px";
767 const newX
= (rc
.width
- newWidth
) / 2;
768 chessboard
.style
.left
= newX
+ "px";
769 const newY
= (rc
.height
- newHeight
) / 2;
770 chessboard
.style
.top
= newY
+ "px";
771 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
772 const pieceWidth
= this.getPieceWidth(newWidth
);
773 // NOTE: next "if" for variants which use squares filling
774 // instead of "physical", moving pieces
776 for (let i
=0; i
< this.size
.x
; i
++) {
777 for (let j
=0; j
< this.size
.y
; j
++) {
778 if (this.g_pieces
[i
][j
]) {
779 // NOTE: could also use CSS transform "scale"
780 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
781 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
782 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
783 // Translate coordinates to use chessboard as reference:
784 this.g_pieces
[i
][j
].style
.transform
=
785 `translate(${ip - newX}px,${jp - newY}px)`;
791 this.rescaleReserve(newR
);
795 for (let c
of ['w','b']) {
796 if (!this.reserve
[c
])
798 const nbR
= this.getNbReservePieces(c
);
801 // Resize container first
802 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
803 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
804 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
805 let rcontainer
= document
.getElementById("reserves_" + c
);
806 rcontainer
.style
.left
= i0
+ "px";
807 rcontainer
.style
.top
= j0
+ "px";
808 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
809 rcontainer
.style
.height
= sqResSize
+ "px";
810 // And then reserve cells:
811 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
812 Object
.keys(this.reserve
[c
]).forEach(p
=> {
813 if (this.reserve
[c
][p
] == 0)
815 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
816 r_cell
.style
.width
= sqResSize
+ "px";
817 r_cell
.style
.height
= sqResSize
+ "px";
822 // Return the absolute pixel coordinates given current position.
823 // Our coordinate system differs from CSS one (x <--> y).
824 // We return here the CSS coordinates (more useful).
825 getPixelPosition(i
, j
, r
) {
827 return [0, 0]; //piece vanishes
829 if (typeof i
== "string") {
830 // Reserves: need to know the rank of piece
831 const nbR
= this.getNbReservePieces(i
);
832 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
833 x
= this.getRankInReserve(i
, j
) * rsqSize
;
834 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
837 const sqSize
= r
.width
/ this.size
.y
;
838 const flipped
= this.flippedBoard
;
839 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
840 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
842 return [r
.x
+ x
, r
.y
+ y
];
846 let container
= document
.getElementById(this.containerId
);
847 let chessboard
= container
.querySelector(".chessboard");
849 const getOffset
= e
=> {
852 return {x: e
.clientX
, y: e
.clientY
};
853 let touchLocation
= null;
854 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
855 // Touch screen, dragstart
856 touchLocation
= e
.targetTouches
[0];
857 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
858 // Touch screen, dragend
859 touchLocation
= e
.changedTouches
[0];
861 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
862 return {x: 0, y: 0}; //shouldn't reach here =)
865 const centerOnCursor
= (piece
, e
) => {
866 const centerShift
= this.getPieceWidth(r
.width
) / 2;
867 const offset
= getOffset(e
);
868 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
869 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
874 startPiece
, curPiece
= null,
876 const mousedown
= (e
) => {
877 // Disable zoom on smartphones:
878 if (e
.touches
&& e
.touches
.length
> 1)
880 r
= chessboard
.getBoundingClientRect();
881 pieceWidth
= this.getPieceWidth(r
.width
);
882 const cd
= this.idToCoords(e
.target
.id
);
884 const move = this.doClick(cd
);
886 this.buildMoveStack(move, r
);
887 else if (!this.clickOnly
) {
888 const [x
, y
] = Object
.values(cd
);
889 if (typeof x
!= "number")
890 startPiece
= this.r_pieces
[x
][y
];
892 startPiece
= this.g_pieces
[x
][y
];
893 if (startPiece
&& this.canIplay(x
, y
)) {
896 curPiece
= startPiece
.cloneNode();
897 curPiece
.style
.transform
= "none";
898 curPiece
.style
.zIndex
= 5;
899 curPiece
.style
.width
= pieceWidth
+ "px";
900 curPiece
.style
.height
= pieceWidth
+ "px";
901 centerOnCursor(curPiece
, e
);
902 container
.appendChild(curPiece
);
903 startPiece
.style
.opacity
= "0.4";
904 chessboard
.style
.cursor
= "none";
910 const mousemove
= (e
) => {
913 centerOnCursor(curPiece
, e
);
915 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
916 // Attempt to prevent horizontal swipe...
920 const mouseup
= (e
) => {
923 const [x
, y
] = [start
.x
, start
.y
];
926 chessboard
.style
.cursor
= "pointer";
927 startPiece
.style
.opacity
= "1";
928 const offset
= getOffset(e
);
929 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
931 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
933 // NOTE: clearly suboptimal, but much easier, and not a big deal.
934 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
935 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
936 const moves
= this.filterValid(potentialMoves
);
937 if (moves
.length
>= 2)
938 this.showChoices(moves
, r
);
939 else if (moves
.length
== 1)
940 this.buildMoveStack(moves
[0], r
);
945 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
947 if ('onmousedown' in window
) {
948 this.mouseListeners
= [
949 {type: "mousedown", listener: mousedown
},
950 {type: "mousemove", listener: mousemove
},
951 {type: "mouseup", listener: mouseup
},
952 {type: "wheel", listener: resize
}
954 this.mouseListeners
.forEach(ml
=> {
955 document
.addEventListener(ml
.type
, ml
.listener
);
958 if ('ontouchstart' in window
) {
959 this.touchListeners
= [
960 {type: "touchstart", listener: mousedown
},
961 {type: "touchmove", listener: mousemove
},
962 {type: "touchend", listener: mouseup
}
964 this.touchListeners
.forEach(tl
=> {
965 // https://stackoverflow.com/a/42509310/12660887
966 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
969 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
972 // NOTE: not called if isDiagram
974 let container
= document
.getElementById(this.containerId
);
975 this.windowResizeObs
.unobserve(container
);
976 if ('onmousedown' in window
) {
977 this.mouseListeners
.forEach(ml
=> {
978 document
.removeEventListener(ml
.type
, ml
.listener
);
981 if ('ontouchstart' in window
) {
982 this.touchListeners
.forEach(tl
=> {
983 // https://stackoverflow.com/a/42509310/12660887
984 document
.removeEventListener(tl
.type
, tl
.listener
);
989 showChoices(moves
, r
) {
990 let container
= document
.getElementById(this.containerId
);
991 let chessboard
= container
.querySelector(".chessboard");
992 let choices
= document
.createElement("div");
993 choices
.id
= "choices";
995 r
= chessboard
.getBoundingClientRect();
996 choices
.style
.width
= r
.width
+ "px";
997 choices
.style
.height
= r
.height
+ "px";
998 choices
.style
.left
= r
.x
+ "px";
999 choices
.style
.top
= r
.y
+ "px";
1000 chessboard
.style
.opacity
= "0.5";
1001 container
.appendChild(choices
);
1002 const squareWidth
= r
.width
/ this.size
.y
;
1003 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1004 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1005 const color
= moves
[0].appear
[0].c
;
1006 const callback
= (m
) => {
1007 chessboard
.style
.opacity
= "1";
1008 container
.removeChild(choices
);
1009 this.buildMoveStack(m
, r
);
1011 for (let i
=0; i
< moves
.length
; i
++) {
1012 let choice
= document
.createElement("div");
1013 choice
.classList
.add("choice");
1014 choice
.style
.width
= squareWidth
+ "px";
1015 choice
.style
.height
= squareWidth
+ "px";
1016 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1017 choice
.style
.top
= firstUpTop
+ "px";
1018 choice
.style
.backgroundColor
= "lightyellow";
1019 choice
.onclick
= () => callback(moves
[i
]);
1020 const piece
= document
.createElement("piece");
1021 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1022 C
.AddClass_es(piece
,
1023 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1024 piece
.classList
.add(V
.GetColorClass(color
));
1025 piece
.style
.width
= "100%";
1026 piece
.style
.height
= "100%";
1027 choice
.appendChild(piece
);
1028 choices
.appendChild(choice
);
1032 displayMessage(elt
, msg
, classe_s
, timeout
) {
1034 // Fixed element, e.g. for Dice Chess
1035 elt
.innerHTML
= msg
;
1037 // Temporary div (Chakart, Apocalypse...)
1038 let divMsg
= document
.createElement("div");
1039 C
.AddClass_es(divMsg
, classe_s
);
1040 divMsg
.innerHTML
= msg
;
1041 let container
= document
.getElementById(this.containerId
);
1042 container
.appendChild(divMsg
);
1043 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1050 updateEnlightened() {
1051 this.oldEnlightened
= this.enlightened
;
1052 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1053 // Add pieces positions + all squares reachable by moves (includes Zen):
1054 for (let x
=0; x
<this.size
.x
; x
++) {
1055 for (let y
=0; y
<this.size
.y
; y
++) {
1056 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1058 this.enlightened
[x
][y
] = true;
1059 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1060 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1066 this.enlightEnpassant();
1069 // Include square of the en-passant capturing square:
1070 enlightEnpassant() {
1071 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1072 // TODO: (0, 0) is wrong, would need to place an attacker here...
1073 const steps
= this.pieces(this.playerColor
, 0, 0)["p"].attack
[0].steps
;
1074 for (let step
of steps
) {
1075 const x
= this.epSquare
.x
- step
[0], //NOTE: epSquare.x not on edge
1076 y
= this.getY(this.epSquare
.y
- step
[1]);
1078 this.onBoard(x
, y
) &&
1079 this.getColor(x
, y
) == this.playerColor
&&
1080 this.getPieceType(x
, y
) == "p"
1082 this.enlightened
[x
][this.epSquare
.y
] = true;
1088 // Apply diff this.enlightened --> oldEnlightened on board
1089 graphUpdateEnlightened() {
1091 document
.getElementById(this.containerId
).querySelector(".chessboard");
1092 const r
= chessboard
.getBoundingClientRect();
1093 const pieceWidth
= this.getPieceWidth(r
.width
);
1094 for (let x
=0; x
<this.size
.x
; x
++) {
1095 for (let y
=0; y
<this.size
.y
; y
++) {
1096 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1097 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1098 elt
.classList
.add("in-shadow");
1099 if (this.g_pieces
[x
][y
])
1100 this.g_pieces
[x
][y
].classList
.add("hidden");
1102 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1103 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1104 elt
.classList
.remove("in-shadow");
1105 if (this.g_pieces
[x
][y
])
1106 this.g_pieces
[x
][y
].classList
.remove("hidden");
1119 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1123 // Color of thing on square (i,j). '' if square is empty
1125 if (typeof i
== "string")
1126 return i
; //reserves
1127 return this.board
[i
][j
].charAt(0);
1130 static GetColorClass(c
) {
1135 return "other-color"; //unidentified color
1138 // Piece on i,j. '' if square is empty
1140 if (typeof j
== "string")
1141 return j
; //reserves
1142 return this.board
[i
][j
].charAt(1);
1145 // Piece type on square (i,j)
1146 getPieceType(x
, y
, p
) {
1148 p
= this.getPiece(x
, y
);
1149 return this.pieces(this.getColor(x
, y
), x
, y
)[p
].moveas
|| p
;
1154 p
= this.getPiece(x
, y
);
1155 if (!this.options
["cannibal"])
1157 return !!C
.CannibalKings
[p
];
1160 static GetOppTurn(color
) {
1161 return (color
== 'w' ? 'b' : 'w');
1164 // Get opponent color(s): may differ from turn (e.g. Checkered)
1166 return (color
== "w" ? "b" : "w");
1169 // Is (x,y) on the chessboard?
1171 return (x
>= 0 && x
< this.size
.x
&&
1172 y
>= 0 && y
< this.size
.y
);
1175 // Am I allowed to move thing at square x,y ?
1177 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1180 ////////////////////////
1181 // PIECES SPECIFICATIONS
1183 getPawnShift(color
) {
1184 return (color
== "w" ? -1 : 1);
1186 isPawnInitRank(x
, color
) {
1187 return (color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1);
1190 pieces(color
, x
, y
) {
1191 const pawnShift
= this.getPawnShift(color
|| 'w');
1197 steps: [[pawnShift
, 0]],
1198 range: (this.isPawnInitRank(x
, color
) ? 2 : 1)
1203 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1211 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1219 [1, 2], [1, -2], [-1, 2], [-1, -2],
1220 [2, 1], [-2, 1], [2, -1], [-2, -1]
1229 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1237 [0, 1], [0, -1], [1, 0], [-1, 0],
1238 [1, 1], [1, -1], [-1, 1], [-1, -1]
1248 [0, 1], [0, -1], [1, 0], [-1, 0],
1249 [1, 1], [1, -1], [-1, 1], [-1, -1]
1256 '!': {"class": "king-pawn", moveas: "p"},
1257 '#': {"class": "king-rook", moveas: "r"},
1258 '$': {"class": "king-knight", moveas: "n"},
1259 '%': {"class": "king-bishop", moveas: "b"},
1260 '*': {"class": "king-queen", moveas: "q"}
1264 // NOTE: using special symbols to not interfere with variants' pieces codes
1265 static get CannibalKings() {
1276 static get CannibalKingCode() {
1287 //////////////////////////
1288 // MOVES GENERATION UTILS
1290 // For Cylinder: get Y coordinate
1292 if (!this.options
["cylinder"])
1294 let res
= y
% this.size
.y
;
1301 return x
; //generally, no
1304 increment([x
, y
], step
) {
1306 this.getX(x
+ step
[0]),
1307 this.getY(y
+ step
[1])
1311 getSegments(curSeg
, segStart
, segEnd
) {
1312 if (curSeg
.length
== 0)
1314 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1315 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1319 getStepSpec(color
, x
, y
, piece
) {
1320 let pieceType
= piece
;
1321 let allSpecs
= this.pieces(color
, x
, y
);
1323 pieceType
= this.getPieceType(x
, y
);
1324 else if (allSpecs
[piece
].moveas
)
1325 pieceType
= allSpecs
[piece
].moveas
;
1326 let res
= allSpecs
[pieceType
];
1336 // Can thing on square1 capture thing on square2?
1337 canTake([x1
, y1
], [x2
, y2
]) {
1338 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1341 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
1342 canSelfTake([x1
, y1
], [x2
, y2
]) {
1343 return !this.isKing(x2
, y2
);
1346 canStepOver(i
, j
, p
) {
1347 // In some variants, objects on boards don't stop movement (Chakart)
1348 return this.board
[i
][j
] == "";
1351 canDrop([c
, p
], [i
, j
]) {
1353 this.board
[i
][j
] == "" &&
1354 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1357 (c
== 'w' && i
< this.size
.x
- 1) ||
1364 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1365 isImmobilized([x
, y
]) {
1366 if (!this.options
["madrasi"])
1368 const color
= this.getColor(x
, y
);
1369 const oppCols
= this.getOppCols(color
);
1370 const piece
= this.getPieceType(x
, y
);
1371 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1372 const attacks
= stepSpec
.both
.concat(stepSpec
.attack
);
1373 for (let a
of attacks
) {
1374 outerLoop: for (let step
of a
.steps
) {
1375 let [i
, j
] = this.increment([x
, y
], step
);
1376 let stepCounter
= 0;
1377 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1378 if (a
.range
<= stepCounter
++)
1380 [i
, j
] = this.increment([i
, j
], step
);
1383 this.onBoard(i
, j
) &&
1384 oppCols
.includes(this.getColor(i
, j
)) &&
1385 this.getPieceType(i
, j
) == piece
1394 // Stop at the first capture found
1395 atLeastOneCapture(color
) {
1396 const allowed
= (sq1
, sq2
) => {
1398 // NOTE: canTake is reversed for Zen.
1399 // Generally ok because of the symmetry. TODO?
1400 this.canTake(sq1
, sq2
) &&
1402 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1405 for (let i
=0; i
<this.size
.x
; i
++) {
1406 for (let j
=0; j
<this.size
.y
; j
++) {
1407 if (this.getColor(i
, j
) == color
) {
1410 !this.options
["zen"] &&
1411 this.findDestSquares(
1423 this.options
["zen"] &&
1424 this.findCapturesOn(
1440 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1441 const epsilon
= 1e-7; //arbitrary small value
1443 if (this.options
["cylinder"])
1444 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1445 for (let sh
of shifts
) {
1446 const rx
= (x2
- x1
) / step
[0],
1447 ry
= (y2
+ sh
- y1
) / step
[1];
1449 // Zero step but non-zero interval => impossible
1450 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1451 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1452 // Negative number of step (impossible)
1453 (rx
< 0 || ry
< 0) ||
1454 // Not the same number of steps in both directions:
1455 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1459 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1460 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1462 distance
= Math
.round(distance
); //in case of (numerical...)
1463 if (!range
|| range
>= distance
)
1469 ////////////////////
1472 getDropMovesFrom([c
, p
]) {
1473 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1474 // (but not necessarily otherwise: atLeastOneMove() etc)
1475 if (this.reserve
[c
][p
] == 0)
1478 for (let i
=0; i
<this.size
.x
; i
++) {
1479 for (let j
=0; j
<this.size
.y
; j
++) {
1480 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1482 start: {x: c
, y: p
},
1484 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1487 if (this.board
[i
][j
] != "") {
1488 mv
.vanish
.push(new PiPo({
1491 c: this.getColor(i
, j
),
1492 p: this.getPiece(i
, j
)
1502 // All possible moves from selected square
1503 // TODO: generalize usage if arg "color" (e.g. Checkered)
1504 getPotentialMovesFrom([x
, y
], color
) {
1505 if (this.subTurnTeleport
== 2)
1507 if (typeof x
== "string")
1508 return this.getDropMovesFrom([x
, y
]);
1509 if (this.isImmobilized([x
, y
]))
1511 const piece
= this.getPieceType(x
, y
);
1512 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1513 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1514 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1516 this.isKing(0, 0, piece
) && this.hasCastle
&&
1517 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1519 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1521 return this.postProcessPotentialMoves(moves
);
1524 postProcessPotentialMoves(moves
) {
1525 if (moves
.length
== 0)
1527 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1528 const oppCols
= this.getOppCols(color
);
1530 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1531 moves
= this.capturePostProcess(moves
, oppCols
);
1533 if (this.options
["atomic"])
1534 moves
= this.atomicPostProcess(moves
, color
, oppCols
);
1538 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1540 moves
= this.pawnPostProcess(moves
, color
, oppCols
);
1543 if (this.options
["cannibal"] && this.options
["rifle"])
1544 // In this case a rifle-capture from last rank may promote a pawn
1545 moves
= this.riflePromotePostProcess(moves
, color
);
1550 capturePostProcess(moves
, oppCols
) {
1551 // Filter out non-capturing moves (not using m.vanish because of
1552 // self captures of Recycle and Teleport).
1553 return moves
.filter(m
=> {
1555 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1556 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1561 atomicPostProcess(moves
, color
, oppCols
) {
1562 moves
.forEach(m
=> {
1564 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1565 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1578 let mNext
= new Move({
1584 for (let step
of steps
) {
1585 let [x
, y
] = this.increment([m
.end
.x
, m
.end
.y
], step
);
1587 this.onBoard(x
, y
) &&
1588 this.board
[x
][y
] != "" &&
1589 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1590 this.getPieceType(x
, y
) != "p"
1594 p: this.getPiece(x
, y
),
1595 c: this.getColor(x
, y
),
1602 if (!this.options
["rifle"]) {
1603 // The moving piece also vanish
1604 mNext
.vanish
.unshift(
1609 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1619 pawnPostProcess(moves
, color
, oppCols
) {
1621 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1622 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1623 moves
.forEach(m
=> {
1624 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1625 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1626 const promotionOk
= (
1628 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1631 return; //nothing to do
1632 if (this.options
["pawnfall"]) {
1638 this.options
["cannibal"] &&
1639 this.board
[x2
][y2
] != "" &&
1640 oppCols
.includes(this.getColor(x2
, y2
))
1642 finalPieces
= [this.getPieceType(x2
, y2
)];
1645 finalPieces
= this.pawnPromotions
;
1646 m
.appear
[0].p
= finalPieces
[0];
1647 if (initPiece
== "!") //cannibal king-pawn
1648 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1649 for (let i
=1; i
<finalPieces
.length
; i
++) {
1650 let newMove
= JSON
.parse(JSON
.stringify(m
));
1651 const piece
= finalPieces
[i
];
1652 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1653 moreMoves
.push(newMove
);
1656 return moves
.concat(moreMoves
);
1659 riflePromotePostProcess(moves
, color
) {
1660 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1662 moves
.forEach(m
=> {
1664 m
.start
.x
== lastRank
&&
1665 m
.appear
.length
>= 1 &&
1666 m
.appear
[0].p
== "p" &&
1667 m
.appear
[0].x
== m
.start
.x
&&
1668 m
.appear
[0].y
== m
.start
.y
1670 m
.appear
[0].p
= this.pawnPromotions
[0];
1671 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1672 let newMv
= JSON
.parse(JSON
.stringify(m
));
1673 newMv
.appear
[0].p
= this.pawnPromotions
[i
];
1674 newMoves
.push(newMv
);
1678 return moves
.concat(newMoves
);
1681 // Generic method to find possible moves of "sliding or jumping" pieces
1682 getPotentialMovesOf(piece
, [x
, y
]) {
1683 const color
= this.getColor(x
, y
);
1684 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1686 if (stepSpec
.attack
) {
1687 squares
= this.findDestSquares(
1693 ([i1
, j1
], [i2
, j2
]) => {
1695 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1696 this.canTake([i1
, j1
], [i2
, j2
])
1701 const noSpecials
= this.findDestSquares(
1704 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1708 Array
.prototype.push
.apply(squares
, noSpecials
);
1709 if (this.options
["zen"]) {
1710 let zenCaptures
= this.findCapturesOn(
1712 {}, //byCol: default is ok
1713 ([i1
, j1
], [i2
, j2
]) =>
1714 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1716 // Technical step: segments (if any) are reversed
1717 zenCaptures
.forEach(z
=> {
1719 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1721 Array
.prototype.push
.apply(squares
, zenCaptures
);
1724 this.options
["recycle"] ||
1725 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1727 const selfCaptures
= this.findDestSquares(
1733 ([i1
, j1
], [i2
, j2
]) => {
1735 this.getColor(i2
, j2
) == color
&&
1736 this.canSelfTake([i1
, j1
], [i2
, j2
])
1740 Array
.prototype.push
.apply(squares
, selfCaptures
);
1742 return squares
.map(s
=> {
1743 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1745 mv
.segments
= s
.segments
;
1750 findDestSquares([x
, y
], o
, allowed
) {
1752 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1753 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1755 // Next 3 for Cylinder mode or circular (useless otherwise)
1759 const addSquare
= ([i
, j
]) => {
1760 let elt
= {sq: [i
, j
]};
1761 if (segments
.length
>= 1)
1762 elt
.segments
= this.getSegments(segments
, segStart
, [i
, j
]);
1765 const exploreSteps
= (stepArray
, mode
) => {
1766 for (let s
of stepArray
) {
1767 outerLoop: for (let step
of s
.steps
) {
1770 let [i
, j
] = [x
, y
];
1771 let stepCounter
= 0;
1773 this.onBoard(i
, j
) &&
1774 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1776 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1777 explored
[i
+ "." + j
] = true;
1780 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1782 if (o
.one
&& mode
!= "attack")
1784 if (mode
!= "attack")
1785 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1786 if (o
.captureTarget
)
1790 if (s
.range
<= stepCounter
++)
1792 const oldIJ
= [i
, j
];
1793 [i
, j
] = this.increment([i
, j
], step
);
1794 if (Math
.abs(j
- oldIJ
[1]) > 1 || Math
.abs(i
- oldIJ
[0]) > 1) {
1795 // Boundary between segments (cylinder or circular mode)
1796 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1800 if (!this.onBoard(i
, j
))
1802 const pieceIJ
= this.getPieceType(i
, j
);
1803 if (!explored
[i
+ "." + j
]) {
1804 explored
[i
+ "." + j
] = true;
1805 if (allowed([x
, y
], [i
, j
])) {
1806 if (o
.one
&& mode
!= "moves")
1808 if (mode
!= "moves")
1809 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1812 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1820 return undefined; //default, but let's explicit it
1822 if (o
.captureTarget
)
1823 return exploreSteps(o
.captureSteps
, "attack");
1826 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1829 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.moves
), "moves");
1830 if (!outOne
&& !o
.moveOnly
)
1831 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.attack
), "attack");
1832 return (o
.one
? outOne : res
);
1836 // Search for enemy (or not) pieces attacking [x, y]
1837 findCapturesOn([x
, y
], o
, allowed
) {
1839 o
.byCol
= this.getOppCols(this.getColor(x
, y
) || this.turn
);
1841 for (let i
=0; i
<this.size
.x
; i
++) {
1842 for (let j
=0; j
<this.size
.y
; j
++) {
1843 const colIJ
= this.getColor(i
, j
);
1845 this.board
[i
][j
] != "" &&
1846 o
.byCol
.includes(colIJ
) &&
1847 !this.isImmobilized([i
, j
])
1849 const apparentPiece
= this.getPiece(i
, j
);
1850 // Quick check: does this potential attacker target x,y ?
1851 if (this.canStepOver(x
, y
, apparentPiece
))
1853 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1854 const attacks
= stepSpec
.attack
.concat(stepSpec
.both
);
1855 for (let a
of attacks
) {
1856 for (let s
of a
.steps
) {
1857 // Quick check: if step isn't compatible, don't even try
1858 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1860 // Finally verify that nothing stand in-between
1861 const out
= this.findDestSquares(
1864 captureTarget: [x
, y
],
1865 captureSteps: [{steps: [s
], range: a
.range
}],
1879 return (o
.one
? false : res
);
1882 // Build a regular move from its initial and destination squares.
1883 // tr: transformation
1884 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1885 const initColor
= this.getColor(sx
, sy
);
1886 const initPiece
= this.getPiece(sx
, sy
);
1887 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1891 start: {x: sx
, y: sy
},
1895 !this.options
["rifle"] ||
1896 this.board
[ex
][ey
] == "" ||
1897 destColor
== initColor
//Recycle, Teleport
1903 c: !!tr
? tr
.c : initColor
,
1904 p: !!tr
? tr
.p : initPiece
1916 if (this.board
[ex
][ey
] != "") {
1921 c: this.getColor(ex
, ey
),
1922 p: this.getPiece(ex
, ey
)
1925 if (this.options
["cannibal"] && destColor
!= initColor
) {
1926 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1927 let trPiece
= mv
.vanish
[lastIdx
].p
;
1928 if (this.isKing(sx
, sy
))
1929 trPiece
= C
.CannibalKingCode
[trPiece
];
1930 if (mv
.appear
.length
>= 1)
1931 mv
.appear
[0].p
= trPiece
;
1932 else if (this.options
["rifle"]) {
1955 // En-passant square, if any
1956 getEpSquare(moveOrSquare
) {
1957 if (typeof moveOrSquare
=== "string") {
1958 const square
= moveOrSquare
;
1961 return C
.SquareToCoords(square
);
1963 // Argument is a move:
1964 const move = moveOrSquare
;
1965 const s
= move.start
,
1969 Math
.abs(s
.x
- e
.x
) == 2 &&
1970 // Next conditions for variants like Atomic or Rifle, Recycle...
1972 move.appear
.length
> 0 &&
1973 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1977 move.vanish
.length
> 0 &&
1978 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1986 return undefined; //default
1989 // Special case of en-passant captures: treated separately
1990 getEnpassantCaptures([x
, y
]) {
1991 const color
= this.getColor(x
, y
);
1992 const shiftX
= (color
== 'w' ? -1 : 1);
1993 const oppCols
= this.getOppCols(color
);
1996 this.epSquare
.x
== x
+ shiftX
&& //NOTE: epSquare.x not on edge
1997 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1998 // Doublemove (and Progressive?) guards:
1999 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2000 oppCols
.includes(this.getColor(x
, this.epSquare
.y
))
2002 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2003 this.board
[epx
][epy
] = this.board
[x
][this.epSquare
.y
];
2004 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2005 this.board
[epx
][epy
] = "";
2006 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2007 enpassantMove
.vanish
[lastIdx
].x
= x
;
2008 return [enpassantMove
];
2013 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2014 const c
= this.getColor(x
, y
);
2017 const oppCols
= this.getOppCols(c
);
2021 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2022 const castlingKing
= this.getPiece(x
, y
);
2023 castlingCheck: for (
2026 castleSide
++ //large, then small
2028 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2030 // If this code is reached, rook and king are on initial position
2032 // NOTE: in some variants this is not a rook
2033 const rookPos
= this.castleFlags
[c
][castleSide
];
2034 const castlingPiece
= this.getPiece(x
, rookPos
);
2036 this.board
[x
][rookPos
] == "" ||
2037 this.getColor(x
, rookPos
) != c
||
2038 (castleWith
&& !castleWith
.includes(castlingPiece
))
2040 // Rook is not here, or changed color (see Benedict)
2043 // Nothing on the path of the king ? (and no checks)
2044 const finDist
= finalSquares
[castleSide
][0] - y
;
2045 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2049 // NOTE: next weird test because underCheck() verification
2050 // will be executed in filterValid() later.
2052 i
!= finalSquares
[castleSide
][0] &&
2053 this.underCheck([[x
, i
]], oppCols
)
2057 this.board
[x
][i
] != "" &&
2058 // NOTE: next check is enough, because of chessboard constraints
2059 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2062 continue castlingCheck
;
2065 } while (i
!= finalSquares
[castleSide
][0]);
2066 // Nothing on the path to the rook?
2067 step
= (castleSide
== 0 ? -1 : 1);
2068 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2069 if (this.board
[x
][i
] != "")
2070 continue castlingCheck
;
2073 // Nothing on final squares, except maybe king and castling rook?
2074 for (i
= 0; i
< 2; i
++) {
2076 finalSquares
[castleSide
][i
] != rookPos
&&
2077 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2079 finalSquares
[castleSide
][i
] != y
||
2080 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2083 continue castlingCheck
;
2087 // If this code is reached, castle is potentially valid
2093 y: finalSquares
[castleSide
][0],
2099 y: finalSquares
[castleSide
][1],
2105 // King might be initially disguised (Titan...)
2106 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2107 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2110 Math
.abs(y
- rookPos
) <= 2
2111 ? {x: x
, y: rookPos
}
2112 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2120 ////////////////////
2123 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2124 underAttack([x
, y
], oppCols
) {
2125 // An empty square is considered as king,
2126 // since it's used only in getCastleMoves (TODO?)
2127 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2130 (!this.options
["zen"] || king
) &&
2131 this.findCapturesOn(
2141 (!!this.options
["zen"] && !king
) &&
2142 this.findDestSquares(
2148 ([i1
, j1
], [i2
, j2
]) => oppCols
.includes(this.getColor(i2
, j2
))
2154 // Argument is (very generally) an array of squares (= arrays)
2155 underCheck(square_s
, oppCols
) {
2156 if (this.options
["taking"] || this.options
["dark"])
2158 return square_s
.some(sq
=> this.underAttack(sq
, oppCols
));
2161 // Scan board for king(s)
2162 searchKingPos(color
) {
2164 for (let i
=0; i
< this.size
.x
; i
++) {
2165 for (let j
=0; j
< this.size
.y
; j
++) {
2166 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2173 // cb: callback returning a boolean (false if king missing)
2174 trackKingWrap(move, kingPos
, cb
) {
2175 if (move.appear
.length
== 0 && move.vanish
.length
== 0)
2178 (move.vanish
.length
> 0 ? move.vanish
[0].c : move.appear
[0].c
);
2179 let newKingPP
= null,
2181 res
= true; //a priori valid
2183 move.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2185 // Search king in appear array:
2187 move.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2189 sqIdx
= kingPos
.findIndex(kp
=>
2190 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2191 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2194 res
= false; //king vanished
2196 res
&&= cb(kingPos
);
2197 if (oldKingPP
&& newKingPP
)
2198 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2202 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2203 filterValid(moves
, color
) {
2206 const oppCols
= this.getOppCols(color
);
2207 let kingPos
= this.searchKingPos(color
);
2208 return moves
.filter(m
=> {
2209 this.playOnBoard(m
);
2210 const res
= this.trackKingWrap(m
, kingPos
, (kp
) => {
2211 return !this.underCheck(kp
, oppCols
);
2213 this.undoOnBoard(m
);
2221 // Apply a move on board
2223 for (let psq
of move.vanish
)
2224 this.board
[psq
.x
][psq
.y
] = "";
2225 for (let psq
of move.appear
)
2226 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2228 // Un-apply the played move
2230 for (let psq
of move.appear
)
2231 this.board
[psq
.x
][psq
.y
] = "";
2232 for (let psq
of move.vanish
)
2233 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2236 updateCastleFlags(move) {
2237 // Update castling flags if start or arrive from/at rook/king locations
2238 move.appear
.concat(move.vanish
).forEach(psq
=> {
2239 if (this.isKing(0, 0, psq
.p
))
2240 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2241 // NOTE: not "else if" because king can capture enemy rook...
2245 else if (psq
.x
== this.size
.x
- 1)
2248 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2250 this.castleFlags
[c
][fidx
] = this.size
.y
;
2258 // If flags already off, no need to re-check:
2259 Object
.values(this.castleFlags
).some(cvals
=>
2260 cvals
.some(val
=> val
< this.size
.y
))
2262 this.updateCastleFlags(move);
2264 if (this.options
["crazyhouse"]) {
2265 move.vanish
.forEach(v
=> {
2266 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2267 if (this.ispawn
[square
])
2268 delete this.ispawn
[square
];
2270 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2271 // Assumption: something is moving
2272 const initSquare
= C
.CoordsToSquare(move.start
);
2273 const destSquare
= C
.CoordsToSquare(move.end
);
2275 this.ispawn
[initSquare
] ||
2276 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2278 this.ispawn
[destSquare
] = true;
2281 this.ispawn
[destSquare
] &&
2282 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2284 move.vanish
[1].p
= 'p';
2285 delete this.ispawn
[destSquare
];
2289 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2292 // Warning; atomic pawn removal isn't a capture
2293 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2295 const color
= this.turn
;
2296 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2297 // Something appears = dropped on board (some exceptions, Chakart...)
2298 if (move.appear
[i
].c
== color
) {
2299 const piece
= move.appear
[i
].p
;
2300 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2303 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2304 // Something vanish: add to reserve except if recycle & opponent
2306 this.options
["crazyhouse"] ||
2307 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2309 const piece
= move.vanish
[i
].p
;
2310 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2318 if (this.hasEnpassant
)
2319 this.epSquare
= this.getEpSquare(move);
2320 this.playOnBoard(move);
2321 this.postPlay(move);
2325 if (this.options
["dark"])
2326 this.updateEnlightened();
2327 if (this.options
["teleport"]) {
2329 this.subTurnTeleport
== 1 &&
2330 move.vanish
.length
> move.appear
.length
&&
2331 move.vanish
[1].c
== this.turn
2333 const v
= move.vanish
[move.vanish
.length
- 1];
2334 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2335 this.subTurnTeleport
= 2;
2338 this.subTurnTeleport
= 1;
2339 this.captured
= null;
2341 this.tryChangeTurn(move);
2344 tryChangeTurn(move) {
2345 if (this.isLastMove(move)) {
2346 this.turn
= C
.GetOppTurn(this.turn
);
2350 else if (!move.next
)
2357 const color
= this.turn
;
2358 const oppKingPos
= this.searchKingPos(C
.GetOppTurn(color
));
2359 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, [color
]))
2363 !this.options
["balance"] ||
2364 ![1, 2].includes(this.movesCount
) ||
2369 !this.options
["doublemove"] ||
2370 this.movesCount
== 0 ||
2375 !this.options
["progressive"] ||
2376 this.subTurn
== this.movesCount
+ 1
2381 // "Stop at the first move found"
2382 atLeastOneMove(color
) {
2383 for (let i
= 0; i
< this.size
.x
; i
++) {
2384 for (let j
= 0; j
< this.size
.y
; j
++) {
2385 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2386 // NOTE: in fact searching for all potential moves from i,j.
2387 // I don't believe this is an issue, for now at least.
2388 const moves
= this.getPotentialMovesFrom([i
, j
], color
);
2389 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2394 if (this.hasReserve
&& this.reserve
[color
]) {
2395 for (let p
of Object
.keys(this.reserve
[color
])) {
2396 const moves
= this.getDropMovesFrom([color
, p
]);
2397 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2404 // What is the score ? (Interesting if game is over)
2405 getCurrentScore(move_s
) {
2406 const move = move_s
[move_s
.length
- 1];
2407 // Shortcut in case the score was computed before:
2410 const oppTurn
= C
.GetOppTurn(this.turn
);
2412 w: this.searchKingPos('w'),
2413 b: this.searchKingPos('b')
2415 if (kingPos
[this.turn
].length
== 0 && kingPos
[oppTurn
].length
== 0)
2417 if (kingPos
[this.turn
].length
== 0)
2418 return (this.turn
== "w" ? "0-1" : "1-0");
2419 if (kingPos
[oppTurn
].length
== 0)
2420 return (this.turn
== "w" ? "1-0" : "0-1");
2421 if (this.atLeastOneMove(this.turn
))
2423 // No valid move: stalemate or checkmate?
2424 if (!this.underCheck(kingPos
[this.turn
], this.getOppCols(this.turn
)))
2427 return (this.turn
== "w" ? "0-1" : "1-0");
2430 playVisual(move, r
) {
2431 move.vanish
.forEach(v
=> {
2432 if (this.g_pieces
[v
.x
][v
.y
]) //can be null (e.g. Apocalypse)
2433 this.g_pieces
[v
.x
][v
.y
].remove();
2434 this.g_pieces
[v
.x
][v
.y
] = null;
2437 document
.getElementById(this.containerId
).querySelector(".chessboard");
2439 r
= chessboard
.getBoundingClientRect();
2440 const pieceWidth
= this.getPieceWidth(r
.width
);
2441 move.appear
.forEach(a
=> {
2442 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2443 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2444 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2445 this.g_pieces
[a
.x
][a
.y
].classList
.add(V
.GetColorClass(a
.c
));
2446 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2447 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2448 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2449 // Translate coordinates to use chessboard as reference:
2450 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2451 `translate(${ip - r.x}px,${jp - r.y}px)`;
2452 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2453 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2454 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2456 if (this.options
["dark"])
2457 this.graphUpdateEnlightened();
2460 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2461 buildMoveStack(move, r
) {
2462 this.moveStack
.push(move);
2463 this.computeNextMove(move);
2464 const then
= () => {
2465 const newTurn
= this.turn
;
2466 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2467 this.playVisual(move, r
);
2471 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2473 this.buildMoveStack(move.next
, r
);
2476 if (this.moveStack
.length
== 1) {
2477 // Usual case (one normal move)
2478 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2479 this.moveStack
= [];
2482 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2483 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2484 this.playReceivedMove(this.moveStack
.slice(1), () => {
2485 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2486 this.moveStack
= [];
2491 // If hiding moves, then they are revealed in play() with callback
2492 this.play(move, this.hideMoves
? then : null);
2493 if (!this.hideMoves
)
2497 // Implemented in variants using (automatic) moveStack
2498 computeNextMove(move) {}
2500 animateMoving(start
, end
, drag
, segments
, cb
) {
2501 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2502 if (!initPiece
) { //TODO: shouldn't occur!
2506 // NOTE: cloning often not required, but light enough, and simpler
2507 let movingPiece
= initPiece
.cloneNode();
2508 initPiece
.style
.opacity
= "0";
2510 document
.getElementById(this.containerId
)
2511 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2512 if (typeof start
.x
== "string") {
2513 // Need to bound width/height (was 100% for reserve pieces)
2514 const pieceWidth
= this.getPieceWidth(r
.width
);
2515 movingPiece
.style
.width
= pieceWidth
+ "px";
2516 movingPiece
.style
.height
= pieceWidth
+ "px";
2518 const maxDist
= this.getMaxDistance(r
);
2519 const apparentColor
= this.getColor(start
.x
, start
.y
);
2520 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2522 const startCode
= this.getPiece(start
.x
, start
.y
);
2523 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2524 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2525 if (apparentColor
!= drag
.c
) {
2526 movingPiece
.classList
.remove(V
.GetColorClass(apparentColor
));
2527 movingPiece
.classList
.add(V
.GetColorClass(drag
.c
));
2530 container
.appendChild(movingPiece
);
2531 const animateSegment
= (index
, cb
) => {
2532 // NOTE: move.drag could be generalized per-segment (usage?)
2533 const [i1
, j1
] = segments
[index
][0];
2534 const [i2
, j2
] = segments
[index
][1];
2535 const dep
= this.getPixelPosition(i1
, j1
, r
);
2536 const arr
= this.getPixelPosition(i2
, j2
, r
);
2537 movingPiece
.style
.transitionDuration
= "0s";
2538 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2540 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2541 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2542 // TODO: unclear why we need this new delay below:
2544 movingPiece
.style
.transitionDuration
= duration
+ "s";
2545 // movingPiece is child of container: no need to adjust coordinates
2546 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2547 setTimeout(cb
, duration
* 1000);
2551 const animateSegmentCallback
= () => {
2552 if (index
< segments
.length
)
2553 animateSegment(index
++, animateSegmentCallback
);
2555 movingPiece
.remove();
2556 initPiece
.style
.opacity
= "1";
2560 animateSegmentCallback();
2563 // Input array of objects with at least fields x,y (e.g. PiPo)
2564 animateFading(arr
, cb
) {
2565 const animLength
= 350; //TODO: 350ms? More? Less?
2567 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2568 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2569 fadingPiece
.style
.opacity
= "0";
2571 setTimeout(cb
, animLength
);
2574 animate(move, callback
) {
2575 if (this.noAnimate
|| move.noAnimate
) {
2579 let segments
= move.segments
;
2581 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2582 let targetObj
= new TargetObj(callback
);
2583 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2585 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2586 () => targetObj
.increment());
2588 if (move.vanish
.length
> move.appear
.length
) {
2589 const arr
= move.vanish
.slice(move.appear
.length
)
2590 // Ignore disappearing pieces hidden by some appearing ones:
2591 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2592 if (arr
.length
> 0) {
2594 this.animateFading(arr
, () => targetObj
.increment());
2598 this.tryAnimateCastle(move, () => targetObj
.increment());
2600 this.customAnimate(move, segments
, () => targetObj
.increment());
2601 if (targetObj
.target
== 0)
2605 tryAnimateCastle(move, cb
) {
2608 move.vanish
.length
== 2 &&
2609 move.appear
.length
== 2 &&
2610 this.isKing(0, 0, move.vanish
[0].p
) &&
2611 this.isKing(0, 0, move.appear
[0].p
)
2613 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2614 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2615 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2616 this.animateMoving(start
, end
, null, segments
, cb
);
2622 // Potential other animations (e.g. for Suction variant)
2623 customAnimate(move, segments
, cb
) {
2624 return 0; //nb of targets
2627 launchAnimation(moves
, container
, callback
) {
2628 if (this.hideMoves
) {
2629 for (let i
=0; i
<moves
.length
; i
++)
2630 // If hiding moves, they are revealed into play():
2631 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2634 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2635 const animateRec
= i
=> {
2636 this.animate(moves
[i
], () => {
2637 this.play(moves
[i
]);
2638 this.playVisual(moves
[i
], r
);
2639 if (i
< moves
.length
- 1)
2640 setTimeout(() => animateRec(i
+1), 300);
2648 playReceivedMove(moves
, callback
) {
2649 // Delay if user wasn't focused:
2650 const checkDisplayThenAnimate
= (delay
) => {
2651 if (container
.style
.display
== "none") {
2652 alert("New move! Let's go back to game...");
2653 document
.getElementById("gameInfos").style
.display
= "none";
2654 container
.style
.display
= "block";
2656 () => this.launchAnimation(moves
, container
, callback
),
2662 () => this.launchAnimation(moves
, container
, callback
),
2667 let container
= document
.getElementById(this.containerId
);
2668 if (document
.hidden
) {
2669 document
.onvisibilitychange
= () => {
2670 // TODO here: page reload ?! (some issues if tab changed...)
2671 document
.onvisibilitychange
= undefined;
2672 checkDisplayThenAnimate(700);
2676 checkDisplayThenAnimate();