98c6bd412c776a0275a1714715e9283c24764a1e
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
) {
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
);
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
);
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(
1416 segments: this.options
["cylinder"]
1424 this.options
["zen"] &&
1425 this.findCapturesOn(
1429 segments: this.options
["cylinder"]
1444 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1445 const epsilon
= 1e-7; //arbitrary small value
1447 if (this.options
["cylinder"])
1448 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1449 for (let sh
of shifts
) {
1450 const rx
= (x2
- x1
) / step
[0],
1451 ry
= (y2
+ sh
- y1
) / step
[1];
1453 // Zero step but non-zero interval => impossible
1454 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1455 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1456 // Negative number of step (impossible)
1457 (rx
< 0 || ry
< 0) ||
1458 // Not the same number of steps in both directions:
1459 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1463 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1464 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1466 distance
= Math
.round(distance
); //in case of (numerical...)
1467 if (!range
|| range
>= distance
)
1473 ////////////////////
1476 getDropMovesFrom([c
, p
]) {
1477 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1478 // (but not necessarily otherwise: atLeastOneMove() etc)
1479 if (this.reserve
[c
][p
] == 0)
1482 for (let i
=0; i
<this.size
.x
; i
++) {
1483 for (let j
=0; j
<this.size
.y
; j
++) {
1484 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1486 start: {x: c
, y: p
},
1488 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1491 if (this.board
[i
][j
] != "") {
1492 mv
.vanish
.push(new PiPo({
1495 c: this.getColor(i
, j
),
1496 p: this.getPiece(i
, j
)
1506 // All possible moves from selected square
1507 // TODO: generalize usage if arg "color" (e.g. Checkered)
1508 getPotentialMovesFrom([x
, y
], color
) {
1509 if (this.subTurnTeleport
== 2)
1511 if (typeof x
== "string")
1512 return this.getDropMovesFrom([x
, y
]);
1513 if (this.isImmobilized([x
, y
]))
1515 const piece
= this.getPieceType(x
, y
);
1516 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1517 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1518 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1520 this.isKing(0, 0, piece
) && this.hasCastle
&&
1521 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1523 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1525 return this.postProcessPotentialMoves(moves
);
1528 postProcessPotentialMoves(moves
) {
1529 if (moves
.length
== 0)
1531 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1532 const oppCols
= this.getOppCols(color
);
1534 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1535 moves
= this.capturePostProcess(moves
, oppCols
);
1537 if (this.options
["atomic"])
1538 moves
= this.atomicPostProcess(moves
, color
, oppCols
);
1542 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1544 moves
= this.pawnPostProcess(moves
, color
, oppCols
);
1547 if (this.options
["cannibal"] && this.options
["rifle"])
1548 // In this case a rifle-capture from last rank may promote a pawn
1549 moves
= this.riflePromotePostProcess(moves
, color
);
1554 capturePostProcess(moves
, oppCols
) {
1555 // Filter out non-capturing moves (not using m.vanish because of
1556 // self captures of Recycle and Teleport).
1557 return moves
.filter(m
=> {
1559 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1560 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1565 atomicPostProcess(moves
, color
, oppCols
) {
1566 moves
.forEach(m
=> {
1568 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1569 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1582 let mNext
= new Move({
1588 for (let step
of steps
) {
1589 let [x
, y
] = this.increment([m
.end
.x
, m
.end
.y
], step
);
1591 this.onBoard(x
, y
) &&
1592 this.board
[x
][y
] != "" &&
1593 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1594 this.getPieceType(x
, y
) != "p"
1598 p: this.getPiece(x
, y
),
1599 c: this.getColor(x
, y
),
1606 if (!this.options
["rifle"]) {
1607 // The moving piece also vanish
1608 mNext
.vanish
.unshift(
1613 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1623 pawnPostProcess(moves
, color
, oppCols
) {
1625 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1626 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1627 moves
.forEach(m
=> {
1628 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1629 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1630 const promotionOk
= (
1632 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1635 return; //nothing to do
1636 if (this.options
["pawnfall"]) {
1642 this.options
["cannibal"] &&
1643 this.board
[x2
][y2
] != "" &&
1644 oppCols
.includes(this.getColor(x2
, y2
))
1646 finalPieces
= [this.getPieceType(x2
, y2
)];
1649 finalPieces
= this.pawnPromotions
;
1650 m
.appear
[0].p
= finalPieces
[0];
1651 if (initPiece
== "!") //cannibal king-pawn
1652 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1653 for (let i
=1; i
<finalPieces
.length
; i
++) {
1654 let newMove
= JSON
.parse(JSON
.stringify(m
));
1655 const piece
= finalPieces
[i
];
1656 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1657 moreMoves
.push(newMove
);
1660 return moves
.concat(moreMoves
);
1663 riflePromotePostProcess(moves
, color
) {
1664 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1666 moves
.forEach(m
=> {
1668 m
.start
.x
== lastRank
&&
1669 m
.appear
.length
>= 1 &&
1670 m
.appear
[0].p
== "p" &&
1671 m
.appear
[0].x
== m
.start
.x
&&
1672 m
.appear
[0].y
== m
.start
.y
1674 m
.appear
[0].p
= this.pawnPromotions
[0];
1675 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1676 let newMv
= JSON
.parse(JSON
.stringify(m
));
1677 newMv
.appear
[0].p
= this.pawnPromotions
[i
];
1678 newMoves
.push(newMv
);
1682 return moves
.concat(newMoves
);
1685 // Generic method to find possible moves of "sliding or jumping" pieces
1686 getPotentialMovesOf(piece
, [x
, y
]) {
1687 const color
= this.getColor(x
, y
);
1688 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1690 if (stepSpec
.attack
) {
1691 squares
= this.findDestSquares(
1695 segments: this.options
["cylinder"],
1698 ([i1
, j1
], [i2
, j2
]) => {
1700 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1701 this.canTake([i1
, j1
], [i2
, j2
])
1706 const noSpecials
= this.findDestSquares(
1709 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1710 segments: this.options
["cylinder"],
1714 Array
.prototype.push
.apply(squares
, noSpecials
);
1715 if (this.options
["zen"]) {
1716 let zenCaptures
= this.findCapturesOn(
1718 {}, //byCol: default is ok
1719 ([i1
, j1
], [i2
, j2
]) =>
1720 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1722 // Technical step: segments (if any) are reversed
1723 if (this.options
["cylinder"]) {
1724 zenCaptures
.forEach(z
=> {
1725 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1728 Array
.prototype.push
.apply(squares
, zenCaptures
);
1731 this.options
["recycle"] ||
1732 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1734 const selfCaptures
= this.findDestSquares(
1738 segments: this.options
["cylinder"],
1741 ([i1
, j1
], [i2
, j2
]) => {
1743 this.getColor(i2
, j2
) == color
&&
1744 this.canSelfTake([i1
, j1
], [i2
, j2
])
1748 Array
.prototype.push
.apply(squares
, selfCaptures
);
1750 return squares
.map(s
=> {
1751 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1752 if (this.options
["cylinder"] && !!s
.segments
&& s
.segments
.length
>= 2)
1753 mv
.segments
= s
.segments
;
1758 findDestSquares([x
, y
], o
, allowed
) {
1760 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1761 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1763 // Next 3 for Cylinder mode: (unused if !o.segments)
1767 const addSquare
= ([i
, j
]) => {
1768 let elt
= {sq: [i
, j
]};
1770 elt
.segments
= this.getSegments(segments
, segStart
, [i
, j
]);
1773 const exploreSteps
= (stepArray
, mode
) => {
1774 for (let s
of stepArray
) {
1775 outerLoop: for (let step
of s
.steps
) {
1780 let [i
, j
] = [x
, y
];
1781 let stepCounter
= 0;
1783 this.onBoard(i
, j
) &&
1784 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1786 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1787 explored
[i
+ "." + j
] = true;
1790 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1792 if (o
.one
&& mode
!= "attack")
1794 if (mode
!= "attack")
1795 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1796 if (o
.captureTarget
)
1800 if (s
.range
<= stepCounter
++)
1802 const oldIJ
= [i
, j
];
1803 [i
, j
] = this.increment([i
, j
], step
);
1804 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1805 // Boundary between segments (cylinder mode)
1806 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1810 if (!this.onBoard(i
, j
))
1812 const pieceIJ
= this.getPieceType(i
, j
);
1813 if (!explored
[i
+ "." + j
]) {
1814 explored
[i
+ "." + j
] = true;
1815 if (allowed([x
, y
], [i
, j
])) {
1816 if (o
.one
&& mode
!= "moves")
1818 if (mode
!= "moves")
1819 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1822 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1830 return undefined; //default, but let's explicit it
1832 if (o
.captureTarget
)
1833 return exploreSteps(o
.captureSteps
, "attack");
1836 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1839 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.moves
), "moves");
1840 if (!outOne
&& !o
.moveOnly
)
1841 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.attack
), "attack");
1842 return (o
.one
? outOne : res
);
1846 // Search for enemy (or not) pieces attacking [x, y]
1847 findCapturesOn([x
, y
], o
, allowed
) {
1849 o
.byCol
= this.getOppCols(this.getColor(x
, y
) || this.turn
);
1851 for (let i
=0; i
<this.size
.x
; i
++) {
1852 for (let j
=0; j
<this.size
.y
; j
++) {
1853 const colIJ
= this.getColor(i
, j
);
1855 this.board
[i
][j
] != "" &&
1856 o
.byCol
.includes(colIJ
) &&
1857 !this.isImmobilized([i
, j
])
1859 const apparentPiece
= this.getPiece(i
, j
);
1860 // Quick check: does this potential attacker target x,y ?
1861 if (this.canStepOver(x
, y
, apparentPiece
))
1863 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1864 const attacks
= stepSpec
.attack
.concat(stepSpec
.both
);
1865 for (let a
of attacks
) {
1866 for (let s
of a
.steps
) {
1867 // Quick check: if step isn't compatible, don't even try
1868 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1870 // Finally verify that nothing stand in-between
1871 const out
= this.findDestSquares(
1874 captureTarget: [x
, y
],
1875 captureSteps: [{steps: [s
], range: a
.range
}],
1876 segments: o
.segments
1890 return (o
.one
? false : res
);
1893 // Build a regular move from its initial and destination squares.
1894 // tr: transformation
1895 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1896 const initColor
= this.getColor(sx
, sy
);
1897 const initPiece
= this.getPiece(sx
, sy
);
1898 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1902 start: {x: sx
, y: sy
},
1906 !this.options
["rifle"] ||
1907 this.board
[ex
][ey
] == "" ||
1908 destColor
== initColor
//Recycle, Teleport
1914 c: !!tr
? tr
.c : initColor
,
1915 p: !!tr
? tr
.p : initPiece
1927 if (this.board
[ex
][ey
] != "") {
1932 c: this.getColor(ex
, ey
),
1933 p: this.getPiece(ex
, ey
)
1936 if (this.options
["cannibal"] && destColor
!= initColor
) {
1937 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1938 let trPiece
= mv
.vanish
[lastIdx
].p
;
1939 if (this.isKing(sx
, sy
))
1940 trPiece
= C
.CannibalKingCode
[trPiece
];
1941 if (mv
.appear
.length
>= 1)
1942 mv
.appear
[0].p
= trPiece
;
1943 else if (this.options
["rifle"]) {
1966 // En-passant square, if any
1967 getEpSquare(moveOrSquare
) {
1968 if (typeof moveOrSquare
=== "string") {
1969 const square
= moveOrSquare
;
1972 return C
.SquareToCoords(square
);
1974 // Argument is a move:
1975 const move = moveOrSquare
;
1976 const s
= move.start
,
1980 Math
.abs(s
.x
- e
.x
) == 2 &&
1981 // Next conditions for variants like Atomic or Rifle, Recycle...
1983 move.appear
.length
> 0 &&
1984 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1988 move.vanish
.length
> 0 &&
1989 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1997 return undefined; //default
2000 // Special case of en-passant captures: treated separately
2001 getEnpassantCaptures([x
, y
]) {
2002 const color
= this.getColor(x
, y
);
2003 const shiftX
= (color
== 'w' ? -1 : 1);
2004 const oppCols
= this.getOppCols(color
);
2007 this.epSquare
.x
== x
+ shiftX
&& //NOTE: epSquare.x not on edge
2008 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2009 // Doublemove (and Progressive?) guards:
2010 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2011 oppCols
.includes(this.getColor(x
, this.epSquare
.y
))
2013 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2014 this.board
[epx
][epy
] = this.board
[x
][this.epSquare
.y
];
2015 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2016 this.board
[epx
][epy
] = "";
2017 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2018 enpassantMove
.vanish
[lastIdx
].x
= x
;
2019 return [enpassantMove
];
2024 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2025 const c
= this.getColor(x
, y
);
2028 const oppCols
= this.getOppCols(c
);
2032 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2033 const castlingKing
= this.getPiece(x
, y
);
2034 castlingCheck: for (
2037 castleSide
++ //large, then small
2039 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2041 // If this code is reached, rook and king are on initial position
2043 // NOTE: in some variants this is not a rook
2044 const rookPos
= this.castleFlags
[c
][castleSide
];
2045 const castlingPiece
= this.getPiece(x
, rookPos
);
2047 this.board
[x
][rookPos
] == "" ||
2048 this.getColor(x
, rookPos
) != c
||
2049 (castleWith
&& !castleWith
.includes(castlingPiece
))
2051 // Rook is not here, or changed color (see Benedict)
2054 // Nothing on the path of the king ? (and no checks)
2055 const finDist
= finalSquares
[castleSide
][0] - y
;
2056 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2060 // NOTE: next weird test because underCheck() verification
2061 // will be executed in filterValid() later.
2063 i
!= finalSquares
[castleSide
][0] &&
2064 this.underCheck([[x
, i
]], oppCols
)
2068 this.board
[x
][i
] != "" &&
2069 // NOTE: next check is enough, because of chessboard constraints
2070 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2073 continue castlingCheck
;
2076 } while (i
!= finalSquares
[castleSide
][0]);
2077 // Nothing on the path to the rook?
2078 step
= (castleSide
== 0 ? -1 : 1);
2079 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2080 if (this.board
[x
][i
] != "")
2081 continue castlingCheck
;
2084 // Nothing on final squares, except maybe king and castling rook?
2085 for (i
= 0; i
< 2; i
++) {
2087 finalSquares
[castleSide
][i
] != rookPos
&&
2088 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2090 finalSquares
[castleSide
][i
] != y
||
2091 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2094 continue castlingCheck
;
2098 // If this code is reached, castle is potentially valid
2104 y: finalSquares
[castleSide
][0],
2110 y: finalSquares
[castleSide
][1],
2116 // King might be initially disguised (Titan...)
2117 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2118 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2121 Math
.abs(y
- rookPos
) <= 2
2122 ? {x: x
, y: rookPos
}
2123 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2131 ////////////////////
2134 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2135 underAttack([x
, y
], oppCols
) {
2136 // An empty square is considered as king,
2137 // since it's used only in getCastleMoves (TODO?)
2138 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2141 (!this.options
["zen"] || king
) &&
2142 this.findCapturesOn(
2146 segments: this.options
["cylinder"],
2153 (!!this.options
["zen"] && !king
) &&
2154 this.findDestSquares(
2158 segments: this.options
["cylinder"],
2161 ([i1
, j1
], [i2
, j2
]) => oppCols
.includes(this.getColor(i2
, j2
))
2167 // Argument is (very generally) an array of squares (= arrays)
2168 underCheck(square_s
, oppCols
) {
2169 if (this.options
["taking"] || this.options
["dark"])
2171 return square_s
.some(sq
=> this.underAttack(sq
, oppCols
));
2174 // Scan board for king(s)
2175 searchKingPos(color
) {
2177 for (let i
=0; i
< this.size
.x
; i
++) {
2178 for (let j
=0; j
< this.size
.y
; j
++) {
2179 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2186 // cb: callback returning a boolean (false if king missing)
2187 trackKingWrap(move, kingPos
, cb
) {
2188 if (move.appear
.length
== 0 && move.vanish
.length
== 0)
2191 (move.vanish
.length
> 0 ? move.vanish
[0].c : move.appear
[0].c
);
2192 let newKingPP
= null,
2194 res
= true; //a priori valid
2196 move.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2198 // Search king in appear array:
2200 move.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2202 sqIdx
= kingPos
.findIndex(kp
=>
2203 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2204 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2207 res
= false; //king vanished
2209 res
&&= cb(kingPos
);
2210 if (oldKingPP
&& newKingPP
)
2211 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2215 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2216 filterValid(moves
, color
) {
2219 const oppCols
= this.getOppCols(color
);
2220 let kingPos
= this.searchKingPos(color
);
2221 return moves
.filter(m
=> {
2222 this.playOnBoard(m
);
2223 const res
= this.trackKingWrap(m
, kingPos
, (kp
) => {
2224 return !this.underCheck(kp
, oppCols
);
2226 this.undoOnBoard(m
);
2234 // Apply a move on board
2236 for (let psq
of move.vanish
)
2237 this.board
[psq
.x
][psq
.y
] = "";
2238 for (let psq
of move.appear
)
2239 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2241 // Un-apply the played move
2243 for (let psq
of move.appear
)
2244 this.board
[psq
.x
][psq
.y
] = "";
2245 for (let psq
of move.vanish
)
2246 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2249 updateCastleFlags(move) {
2250 // Update castling flags if start or arrive from/at rook/king locations
2251 move.appear
.concat(move.vanish
).forEach(psq
=> {
2252 if (this.isKing(0, 0, psq
.p
))
2253 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2254 // NOTE: not "else if" because king can capture enemy rook...
2258 else if (psq
.x
== this.size
.x
- 1)
2261 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2263 this.castleFlags
[c
][fidx
] = this.size
.y
;
2271 // If flags already off, no need to re-check:
2272 Object
.values(this.castleFlags
).some(cvals
=>
2273 cvals
.some(val
=> val
< this.size
.y
))
2275 this.updateCastleFlags(move);
2277 if (this.options
["crazyhouse"]) {
2278 move.vanish
.forEach(v
=> {
2279 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2280 if (this.ispawn
[square
])
2281 delete this.ispawn
[square
];
2283 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2284 // Assumption: something is moving
2285 const initSquare
= C
.CoordsToSquare(move.start
);
2286 const destSquare
= C
.CoordsToSquare(move.end
);
2288 this.ispawn
[initSquare
] ||
2289 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2291 this.ispawn
[destSquare
] = true;
2294 this.ispawn
[destSquare
] &&
2295 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2297 move.vanish
[1].p
= 'p';
2298 delete this.ispawn
[destSquare
];
2302 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2305 // Warning; atomic pawn removal isn't a capture
2306 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2308 const color
= this.turn
;
2309 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2310 // Something appears = dropped on board (some exceptions, Chakart...)
2311 if (move.appear
[i
].c
== color
) {
2312 const piece
= move.appear
[i
].p
;
2313 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2316 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2317 // Something vanish: add to reserve except if recycle & opponent
2319 this.options
["crazyhouse"] ||
2320 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2322 const piece
= move.vanish
[i
].p
;
2323 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2331 if (this.hasEnpassant
)
2332 this.epSquare
= this.getEpSquare(move);
2333 this.playOnBoard(move);
2334 this.postPlay(move);
2338 if (this.options
["dark"])
2339 this.updateEnlightened();
2340 if (this.options
["teleport"]) {
2342 this.subTurnTeleport
== 1 &&
2343 move.vanish
.length
> move.appear
.length
&&
2344 move.vanish
[1].c
== this.turn
2346 const v
= move.vanish
[move.vanish
.length
- 1];
2347 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2348 this.subTurnTeleport
= 2;
2351 this.subTurnTeleport
= 1;
2352 this.captured
= null;
2354 this.tryChangeTurn(move);
2357 tryChangeTurn(move) {
2358 if (this.isLastMove(move)) {
2359 this.turn
= C
.GetOppTurn(this.turn
);
2363 else if (!move.next
)
2370 const color
= this.turn
;
2371 const oppKingPos
= this.searchKingPos(C
.GetOppTurn(color
));
2372 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, [color
]))
2376 !this.options
["balance"] ||
2377 ![1, 2].includes(this.movesCount
) ||
2382 !this.options
["doublemove"] ||
2383 this.movesCount
== 0 ||
2388 !this.options
["progressive"] ||
2389 this.subTurn
== this.movesCount
+ 1
2394 // "Stop at the first move found"
2395 atLeastOneMove(color
) {
2396 for (let i
= 0; i
< this.size
.x
; i
++) {
2397 for (let j
= 0; j
< this.size
.y
; j
++) {
2398 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2399 // NOTE: in fact searching for all potential moves from i,j.
2400 // I don't believe this is an issue, for now at least.
2401 const moves
= this.getPotentialMovesFrom([i
, j
], color
);
2402 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2407 if (this.hasReserve
&& this.reserve
[color
]) {
2408 for (let p
of Object
.keys(this.reserve
[color
])) {
2409 const moves
= this.getDropMovesFrom([color
, p
]);
2410 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2417 // What is the score ? (Interesting if game is over)
2418 getCurrentScore(move_s
) {
2419 const move = move_s
[move_s
.length
- 1];
2420 // Shortcut in case the score was computed before:
2423 const oppTurn
= C
.GetOppTurn(this.turn
);
2425 w: this.searchKingPos('w'),
2426 b: this.searchKingPos('b')
2428 if (kingPos
[this.turn
].length
== 0 && kingPos
[oppTurn
].length
== 0)
2430 if (kingPos
[this.turn
].length
== 0)
2431 return (this.turn
== "w" ? "0-1" : "1-0");
2432 if (kingPos
[oppTurn
].length
== 0)
2433 return (this.turn
== "w" ? "1-0" : "0-1");
2434 if (this.atLeastOneMove(this.turn
))
2436 // No valid move: stalemate or checkmate?
2437 if (!this.underCheck(kingPos
[this.turn
], this.getOppCols(this.turn
)))
2440 return (this.turn
== "w" ? "0-1" : "1-0");
2443 playVisual(move, r
) {
2444 move.vanish
.forEach(v
=> {
2445 if (this.g_pieces
[v
.x
][v
.y
]) //can be null (e.g. Apocalypse)
2446 this.g_pieces
[v
.x
][v
.y
].remove();
2447 this.g_pieces
[v
.x
][v
.y
] = null;
2450 document
.getElementById(this.containerId
).querySelector(".chessboard");
2452 r
= chessboard
.getBoundingClientRect();
2453 const pieceWidth
= this.getPieceWidth(r
.width
);
2454 move.appear
.forEach(a
=> {
2455 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2456 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2457 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2458 this.g_pieces
[a
.x
][a
.y
].classList
.add(V
.GetColorClass(a
.c
));
2459 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2460 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2461 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2462 // Translate coordinates to use chessboard as reference:
2463 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2464 `translate(${ip - r.x}px,${jp - r.y}px)`;
2465 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2466 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2467 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2469 if (this.options
["dark"])
2470 this.graphUpdateEnlightened();
2473 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2474 buildMoveStack(move, r
) {
2475 this.moveStack
.push(move);
2476 this.computeNextMove(move);
2477 const then
= () => {
2478 const newTurn
= this.turn
;
2479 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2480 this.playVisual(move, r
);
2484 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2486 this.buildMoveStack(move.next
, r
);
2489 if (this.moveStack
.length
== 1) {
2490 // Usual case (one normal move)
2491 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2492 this.moveStack
= [];
2495 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2496 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2497 this.playReceivedMove(this.moveStack
.slice(1), () => {
2498 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2499 this.moveStack
= [];
2504 // If hiding moves, then they are revealed in play() with callback
2505 this.play(move, this.hideMoves
? then : null);
2506 if (!this.hideMoves
)
2510 // Implemented in variants using (automatic) moveStack
2511 computeNextMove(move) {}
2513 animateMoving(start
, end
, drag
, segments
, cb
) {
2514 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2515 if (!initPiece
) { //TODO: shouldn't occur!
2519 // NOTE: cloning often not required, but light enough, and simpler
2520 let movingPiece
= initPiece
.cloneNode();
2521 initPiece
.style
.opacity
= "0";
2523 document
.getElementById(this.containerId
)
2524 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2525 if (typeof start
.x
== "string") {
2526 // Need to bound width/height (was 100% for reserve pieces)
2527 const pieceWidth
= this.getPieceWidth(r
.width
);
2528 movingPiece
.style
.width
= pieceWidth
+ "px";
2529 movingPiece
.style
.height
= pieceWidth
+ "px";
2531 const maxDist
= this.getMaxDistance(r
);
2532 const apparentColor
= this.getColor(start
.x
, start
.y
);
2533 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2535 const startCode
= this.getPiece(start
.x
, start
.y
);
2536 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2537 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2538 if (apparentColor
!= drag
.c
) {
2539 movingPiece
.classList
.remove(V
.GetColorClass(apparentColor
));
2540 movingPiece
.classList
.add(V
.GetColorClass(drag
.c
));
2543 container
.appendChild(movingPiece
);
2544 const animateSegment
= (index
, cb
) => {
2545 // NOTE: move.drag could be generalized per-segment (usage?)
2546 const [i1
, j1
] = segments
[index
][0];
2547 const [i2
, j2
] = segments
[index
][1];
2548 const dep
= this.getPixelPosition(i1
, j1
, r
);
2549 const arr
= this.getPixelPosition(i2
, j2
, r
);
2550 movingPiece
.style
.transitionDuration
= "0s";
2551 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2553 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2554 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2555 // TODO: unclear why we need this new delay below:
2557 movingPiece
.style
.transitionDuration
= duration
+ "s";
2558 // movingPiece is child of container: no need to adjust coordinates
2559 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2560 setTimeout(cb
, duration
* 1000);
2564 const animateSegmentCallback
= () => {
2565 if (index
< segments
.length
)
2566 animateSegment(index
++, animateSegmentCallback
);
2568 movingPiece
.remove();
2569 initPiece
.style
.opacity
= "1";
2573 animateSegmentCallback();
2576 // Input array of objects with at least fields x,y (e.g. PiPo)
2577 animateFading(arr
, cb
) {
2578 const animLength
= 350; //TODO: 350ms? More? Less?
2580 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2581 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2582 fadingPiece
.style
.opacity
= "0";
2584 setTimeout(cb
, animLength
);
2587 animate(move, callback
) {
2588 if (this.noAnimate
|| move.noAnimate
) {
2592 let segments
= move.segments
;
2594 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2595 let targetObj
= new TargetObj(callback
);
2596 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2598 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2599 () => targetObj
.increment());
2601 if (move.vanish
.length
> move.appear
.length
) {
2602 const arr
= move.vanish
.slice(move.appear
.length
)
2603 // Ignore disappearing pieces hidden by some appearing ones:
2604 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2605 if (arr
.length
> 0) {
2607 this.animateFading(arr
, () => targetObj
.increment());
2611 this.tryAnimateCastle(move, () => targetObj
.increment());
2613 this.customAnimate(move, segments
, () => targetObj
.increment());
2614 if (targetObj
.target
== 0)
2618 tryAnimateCastle(move, cb
) {
2621 move.vanish
.length
== 2 &&
2622 move.appear
.length
== 2 &&
2623 this.isKing(0, 0, move.vanish
[0].p
) &&
2624 this.isKing(0, 0, move.appear
[0].p
)
2626 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2627 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2628 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2629 this.animateMoving(start
, end
, null, segments
, cb
);
2635 // Potential other animations (e.g. for Suction variant)
2636 customAnimate(move, segments
, cb
) {
2637 return 0; //nb of targets
2640 launchAnimation(moves
, container
, callback
) {
2641 if (this.hideMoves
) {
2642 for (let i
=0; i
<moves
.length
; i
++)
2643 // If hiding moves, they are revealed into play():
2644 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2647 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2648 const animateRec
= i
=> {
2649 this.animate(moves
[i
], () => {
2650 this.play(moves
[i
]);
2651 this.playVisual(moves
[i
], r
);
2652 if (i
< moves
.length
- 1)
2653 setTimeout(() => animateRec(i
+1), 300);
2661 playReceivedMove(moves
, callback
) {
2662 // Delay if user wasn't focused:
2663 const checkDisplayThenAnimate
= (delay
) => {
2664 if (container
.style
.display
== "none") {
2665 alert("New move! Let's go back to game...");
2666 document
.getElementById("gameInfos").style
.display
= "none";
2667 container
.style
.display
= "block";
2669 () => this.launchAnimation(moves
, container
, callback
),
2675 () => this.launchAnimation(moves
, container
, callback
),
2680 let container
= document
.getElementById(this.containerId
);
2681 if (document
.hidden
) {
2682 document
.onvisibilitychange
= () => {
2683 // TODO here: page reload ?! (some issues if tab changed...)
2684 document
.onvisibilitychange
= undefined;
2685 checkDisplayThenAnimate(700);
2689 checkDisplayThenAnimate();