217d0556f1c6402bc9ac3c12b4539b3f6e39b8f4
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?
100 // Allow to take (moving: not disappearing) own pieces?
101 get hasSelfCaptures() {
103 this.options
["recycle"] ||
104 (this.options
["teleport"] && this.subTurnTeleport
== 1)
110 !!this.options
["crazyhouse"] ||
111 (!!this.options
["recycle"] && !this.options
["teleport"])
114 // Some variants do not store reserve state (Align4, Chakart...)
115 get hasReserveFen() {
116 return this.hasReserve
;
120 return !!this.options
["dark"];
123 // Some variants use only click information
128 // Some variants reveal moves only after both players played
133 // Some variants do not flip board as black
135 return (this.playerColor
== 'b');
138 // Some variants use click infos:
140 if (typeof coords
.x
!= "number")
141 return null; //click on reserves
143 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
144 this.board
[coords
.x
][coords
.y
] == ""
147 start: {x: this.captured
.x
, y: this.captured
.y
},
158 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
167 // 3a --> {x:3, y:10}
168 static SquareToCoords(sq
) {
169 return ArrayFun
.toObject(["x", "y"],
170 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
173 // {x:11, y:12} --> bc
174 static CoordsToSquare(cd
) {
175 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
179 if (typeof cd
.x
== "number") {
181 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
185 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
188 idToCoords(targetId
) {
190 return null; //outside page, maybe...
191 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
193 idParts
.length
< 2 ||
194 idParts
[0] != this.containerId
||
195 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
199 const squares
= idParts
[1].split('-');
200 if (squares
[0] == "sq")
201 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
202 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
203 return {x: squares
[1], y: squares
[2]};
209 // Turn "wb" into "B" (for FEN)
211 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
214 // Turn "p" into "bp" (for board)
216 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
219 genRandInitFen(seed
) {
220 Random
.setSeed(seed
); //may be unused
221 let baseFen
= this.genRandInitBaseFen();
222 baseFen
.o
= Object
.assign({init: true}, baseFen
.o
);
223 const parts
= this.getPartFen(baseFen
.o
);
225 baseFen
.fen
+ " w 0" +
226 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
230 // Setup the initial random-or-not (asymmetric-or-not) position
231 genRandInitBaseFen() {
232 const s
= FenUtil
.setupPieces(
233 ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
235 randomness: this.options
["randomness"],
236 between: [{p1: 'k', p2: 'r'}],
242 fen: s
.b
.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
243 s
.w
.join("").toUpperCase(),
248 // "Parse" FEN: just return untransformed string data
250 const fenParts
= fen
.split(" ");
252 position: fenParts
[0],
254 movesCount: fenParts
[2]
256 if (fenParts
.length
> 3)
257 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
261 // Return current fen (game state)
263 const parts
= this.getPartFen({});
266 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
271 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
277 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
278 if (this.hasEnpassant
)
279 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
280 if (this.hasReserveFen
)
281 parts
["reserve"] = this.getReserveFen(o
);
282 if (this.options
["crazyhouse"])
283 parts
["ispawn"] = this.getIspawnFen(o
);
287 static FenEmptySquares(count
) {
288 // if more than 9 consecutive free spaces, break the integer,
289 // otherwise FEN parsing will fail.
292 // Most boards of size < 18:
294 return "9" + (count
- 9);
296 return "99" + (count
- 18);
299 // Position part of the FEN string
302 for (let i
= 0; i
< this.size
.x
; i
++) {
304 for (let j
= 0; j
< this.size
.y
; j
++) {
305 if (this.board
[i
][j
] == "")
308 if (emptyCount
> 0) {
309 // Add empty squares in-between
310 position
+= C
.FenEmptySquares(emptyCount
);
313 position
+= this.board2fen(this.board
[i
][j
]);
318 position
+= C
.FenEmptySquares(emptyCount
);
319 if (i
< this.size
.x
- 1)
320 position
+= "/"; //separate rows
325 // Flags part of the FEN string
327 return ['w', 'b'].map(c
=> {
328 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
332 // Enpassant part of the FEN string
336 return C
.CoordsToSquare(this.epSquare
);
341 return Array(2 * V
.ReserveArray
.length
).fill('0').join("");
343 ['w', 'b'].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
349 // NOTE: cannot merge because this.ispawn doesn't exist yet
351 const squares
= Object
.keys(this.ispawn
);
352 if (squares
.length
== 0)
354 return squares
.join(",");
357 // Set flags from fen (castle: white a,h then black a,h)
360 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
361 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
369 this.options
= o
.options
;
370 // Fill missing options (always the case if random challenge)
371 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
372 if (this.options
[opt
.variable
] === undefined)
373 this.options
[opt
.variable
] = opt
.defaut
;
377 this.playerColor
= o
.color
;
378 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
379 this.containerId
= o
.element
;
380 this.isDiagram
= o
.diagram
;
381 this.marks
= o
.marks
;
385 o
.fen
= this.genRandInitFen(o
.seed
);
386 this.re_initFromFen(o
.fen
);
387 this.graphicalInit();
390 re_initFromFen(fen
, oldBoard
) {
391 const fenParsed
= this.parseFen(fen
);
392 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
393 this.turn
= fenParsed
.turn
;
394 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
395 this.setOtherVariables(fenParsed
);
398 // Turn position fen into double array ["wb","wp","bk",...]
400 const rows
= position
.split("/");
401 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
402 for (let i
= 0; i
< rows
.length
; i
++) {
404 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
405 const character
= rows
[i
][indexInRow
];
406 const num
= parseInt(character
, 10);
407 // If num is a number, just shift j:
410 // Else: something at position i,j
412 board
[i
][j
++] = this.fen2board(character
);
418 // Some additional variables from FEN (variant dependant)
419 setOtherVariables(fenParsed
) {
420 // Set flags and enpassant:
422 this.setFlags(fenParsed
.flags
);
423 if (this.hasEnpassant
)
424 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
425 if (this.hasReserve
&& !this.isDiagram
)
426 this.initReserves(fenParsed
.reserve
);
427 if (this.options
["crazyhouse"])
428 this.initIspawn(fenParsed
.ispawn
);
429 if (this.options
["teleport"]) {
430 this.subTurnTeleport
= 1;
431 this.captured
= null;
433 if (this.options
["dark"]) {
434 // Setup enlightened: squares reachable by player side
435 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
436 this.updateEnlightened();
438 this.subTurn
= 1; //may be unused
439 if (!this.moveStack
) //avoid resetting (unwanted)
443 // ordering as in pieces() p,r,n,b,q,k
444 static get ReserveArray() {
445 return ['p', 'r', 'n', 'b', 'q', 'k'];
448 initReserves(reserveStr
) {
449 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
450 const L
= V
.ReserveArray
.length
;
452 w: ArrayFun
.toObject(V
.ReserveArray
, counts
.slice(0, L
)),
453 b: ArrayFun
.toObject(V
.ReserveArray
, counts
.slice(L
, 2 * L
))
457 initIspawn(ispawnStr
) {
458 if (ispawnStr
!= "-")
459 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
467 getPieceWidth(rwidth
) {
468 return (rwidth
/ this.size
.y
);
471 getReserveSquareSize(rwidth
, nbR
) {
472 const sqSize
= this.getPieceWidth(rwidth
);
473 return Math
.min(sqSize
, rwidth
/ nbR
);
476 getReserveNumId(color
, piece
) {
477 return `${this.containerId}|rnum-${color}${piece}`;
480 getNbReservePieces(color
) {
482 Object
.values(this.reserve
[color
]).reduce(
483 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
487 getRankInReserve(c
, p
) {
488 const pieces
= Object
.keys(this.pieces(c
, c
, p
));
489 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
490 let toTest
= pieces
.slice(0, lastIndex
);
491 return toTest
.reduce(
492 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
495 static AddClass_es(elt
, class_es
) {
496 if (!Array
.isArray(class_es
))
497 class_es
= [class_es
];
498 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
501 static RemoveClass_es(elt
, class_es
) {
502 if (!Array
.isArray(class_es
))
503 class_es
= [class_es
];
504 class_es
.forEach(cl
=> elt
.classList
.remove(cl
));
507 // Generally light square bottom-right
508 getSquareColorClass(x
, y
) {
509 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
513 // Works for all rectangular boards:
514 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
518 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
525 const g_init
= () => {
526 this.re_drawBoardElements();
527 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
528 this.initMouseEvents();
530 let container
= document
.getElementById(this.containerId
);
531 this.windowResizeObs
= new ResizeObserver(g_init
);
532 this.windowResizeObs
.observe(container
);
535 re_drawBoardElements() {
536 const board
= this.getSvgChessboard();
537 const container
= document
.getElementById(this.containerId
);
538 const rc
= container
.getBoundingClientRect();
539 let chessboard
= container
.querySelector(".chessboard");
540 chessboard
.innerHTML
= "";
541 chessboard
.insertAdjacentHTML('beforeend', board
);
542 // Compare window ratio width / height to aspectRatio:
543 const windowRatio
= rc
.width
/ rc
.height
;
544 let cbWidth
, cbHeight
;
545 const vRatio
= this.size
.ratio
|| 1;
546 if (windowRatio
<= vRatio
) {
547 // Limiting dimension is width:
548 cbWidth
= Math
.min(rc
.width
, 767);
549 cbHeight
= cbWidth
/ vRatio
;
552 // Limiting dimension is height:
553 cbHeight
= Math
.min(rc
.height
, 767);
554 cbWidth
= cbHeight
* vRatio
;
556 if (this.hasReserve
&& !this.isDiagram
) {
557 const sqSize
= cbWidth
/ this.size
.y
;
558 // NOTE: allocate space for reserves (up/down) even if they are empty
559 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
560 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
561 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
562 cbWidth
= cbHeight
* vRatio
;
565 chessboard
.style
.width
= cbWidth
+ "px";
566 chessboard
.style
.height
= cbHeight
+ "px";
567 // Center chessboard:
568 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
569 spaceTop
= (rc
.height
- cbHeight
) / 2;
570 chessboard
.style
.left
= spaceLeft
+ "px";
571 chessboard
.style
.top
= spaceTop
+ "px";
572 // Give sizes instead of recomputing them,
573 // because chessboard might not be drawn yet.
574 this.setupVisualPieces({
582 // Get SVG board (background, no pieces)
586 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
587 class="chessboard_SVG">`;
588 board
+= this.getBaseSvgChessboard();
593 getBaseSvgChessboard() {
595 const flipped
= this.flippedBoard
;
596 for (let i
=0; i
< this.size
.x
; i
++) {
597 for (let j
=0; j
< this.size
.y
; j
++) {
598 if (!this.onBoard(i
, j
))
600 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
601 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
602 let classes
= this.getSquareColorClass(ii
, jj
);
603 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
604 classes
+= " in-shadow";
605 // NOTE: x / y reversed because coordinates system is reversed.
609 id="${this.coordsToId({x: ii, y: jj})}"
620 setupVisualPieces(r
) {
622 document
.getElementById(this.containerId
).querySelector(".chessboard");
624 r
= chessboard
.getBoundingClientRect();
625 const pieceWidth
= this.getPieceWidth(r
.width
);
626 const addPiece
= (i
, j
, arrName
, classes
) => {
627 this[arrName
][i
][j
] = document
.createElement("piece");
628 C
.AddClass_es(this[arrName
][i
][j
], classes
);
629 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
630 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
631 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
632 // Translate coordinates to use chessboard as reference:
633 this[arrName
][i
][j
].style
.transform
=
634 `translate(${ip - r.x}px,${jp - r.y}px)`;
635 chessboard
.appendChild(this[arrName
][i
][j
]);
637 const conditionalReset
= (arrName
) => {
639 // Refreshing: delete old pieces first. This isn't necessary,
640 // but simpler (this method isn't called many times)
641 for (let i
=0; i
<this.size
.x
; i
++) {
642 for (let j
=0; j
<this.size
.y
; j
++) {
643 if (this[arrName
][i
][j
]) {
644 this[arrName
][i
][j
].remove();
645 this[arrName
][i
][j
] = null;
651 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
652 if (arrName
== "d_pieces")
653 this.marks
.forEach((m
) => {
654 const formattedSquare
=
655 (this.size
.x
- parseInt(m
.substring(1), 10)).toString(36) +
656 (m
.charCodeAt(0) - 97).toString(36);
657 const mCoords
= V
.SquareToCoords(formattedSquare
);
658 addPiece(mCoords
.x
, mCoords
.y
, arrName
, "mark");
662 conditionalReset("d_pieces");
663 conditionalReset("g_pieces");
664 for (let i
=0; i
< this.size
.x
; i
++) {
665 for (let j
=0; j
< this.size
.y
; j
++) {
666 if (this.board
[i
][j
] != "") {
667 const color
= this.getColor(i
, j
);
668 const piece
= this.getPiece(i
, j
);
669 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
670 this.g_pieces
[i
][j
].classList
.add(V
.GetColorClass(color
));
671 if (this.enlightened
&& !this.enlightened
[i
][j
])
672 this.g_pieces
[i
][j
].classList
.add("hidden");
674 if (this.marks
&& this.d_pieces
[i
][j
]) {
675 let classes
= ["mark"];
676 if (this.board
[i
][j
] != "")
677 classes
.push("transparent");
678 addPiece(i
, j
, "d_pieces", classes
);
682 if (this.hasReserve
&& !this.isDiagram
)
683 this.re_drawReserve(['w', 'b'], r
);
686 // NOTE: assume this.reserve != null
687 re_drawReserve(colors
, r
) {
689 // Remove (old) reserve pieces
690 for (let c
of colors
) {
691 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
692 this.r_pieces
[c
][p
].remove();
693 delete this.r_pieces
[c
][p
];
694 const numId
= this.getReserveNumId(c
, p
);
695 document
.getElementById(numId
).remove();
700 this.r_pieces
= { w: {}, b: {} };
701 let container
= document
.getElementById(this.containerId
);
703 r
= container
.querySelector(".chessboard").getBoundingClientRect();
704 for (let c
of colors
) {
705 let reservesDiv
= document
.getElementById("reserves_" + c
);
707 reservesDiv
.remove();
708 if (!this.reserve
[c
])
710 const nbR
= this.getNbReservePieces(c
);
713 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
715 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
716 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
717 let rcontainer
= document
.createElement("div");
718 rcontainer
.id
= "reserves_" + c
;
719 rcontainer
.classList
.add("reserves");
720 rcontainer
.style
.left
= i0
+ "px";
721 rcontainer
.style
.top
= j0
+ "px";
722 // NOTE: +1 fix display bug on Firefox at least
723 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
724 rcontainer
.style
.height
= sqResSize
+ "px";
725 container
.appendChild(rcontainer
);
726 for (let p
of Object
.keys(this.reserve
[c
])) {
727 if (this.reserve
[c
][p
] == 0)
729 let r_cell
= document
.createElement("div");
730 r_cell
.id
= this.coordsToId({x: c
, y: p
});
731 r_cell
.classList
.add("reserve-cell");
732 r_cell
.style
.width
= sqResSize
+ "px";
733 r_cell
.style
.height
= sqResSize
+ "px";
734 rcontainer
.appendChild(r_cell
);
735 let piece
= document
.createElement("piece");
736 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
737 piece
.classList
.add(V
.GetColorClass(c
));
738 piece
.style
.width
= "100%";
739 piece
.style
.height
= "100%";
740 this.r_pieces
[c
][p
] = piece
;
741 r_cell
.appendChild(piece
);
742 let number
= document
.createElement("div");
743 number
.textContent
= this.reserve
[c
][p
];
744 number
.classList
.add("reserve-num");
745 number
.id
= this.getReserveNumId(c
, p
);
746 const fontSize
= "1.3em";
747 number
.style
.fontSize
= fontSize
;
748 number
.style
.fontSize
= fontSize
;
749 r_cell
.appendChild(number
);
755 updateReserve(color
, piece
, count
) {
756 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
757 piece
= "k"; //capturing cannibal king: back to king form
758 const oldCount
= this.reserve
[color
][piece
];
759 this.reserve
[color
][piece
] = count
;
760 // Redrawing is much easier if count==0 (or undefined)
761 if ([oldCount
, count
].some(item
=> !item
))
762 this.re_drawReserve([color
]);
764 const numId
= this.getReserveNumId(color
, piece
);
765 document
.getElementById(numId
).textContent
= count
;
769 // Resize board: no need to destroy/recreate pieces
771 const container
= document
.getElementById(this.containerId
);
772 let chessboard
= container
.querySelector(".chessboard");
773 const rc
= container
.getBoundingClientRect(),
774 r
= chessboard
.getBoundingClientRect();
775 const multFact
= (mode
== "up" ? 1.05 : 0.95);
776 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
778 const vRatio
= this.size
.ratio
|| 1;
779 if (newWidth
> rc
.width
) {
781 newHeight
= newWidth
/ vRatio
;
783 if (newHeight
> rc
.height
) {
784 newHeight
= rc
.height
;
785 newWidth
= newHeight
* vRatio
;
787 chessboard
.style
.width
= newWidth
+ "px";
788 chessboard
.style
.height
= newHeight
+ "px";
789 const newX
= (rc
.width
- newWidth
) / 2;
790 chessboard
.style
.left
= newX
+ "px";
791 const newY
= (rc
.height
- newHeight
) / 2;
792 chessboard
.style
.top
= newY
+ "px";
793 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
794 const pieceWidth
= this.getPieceWidth(newWidth
);
795 // NOTE: next "if" for variants which use squares filling
796 // instead of "physical", moving pieces
798 for (let i
=0; i
< this.size
.x
; i
++) {
799 for (let j
=0; j
< this.size
.y
; j
++) {
800 if (this.g_pieces
[i
][j
]) {
801 // NOTE: could also use CSS transform "scale"
802 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
803 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
804 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
805 // Translate coordinates to use chessboard as reference:
806 this.g_pieces
[i
][j
].style
.transform
=
807 `translate(${ip - newX}px,${jp - newY}px)`;
813 this.rescaleReserve(newR
);
817 for (let c
of ['w','b']) {
818 if (!this.reserve
[c
])
820 const nbR
= this.getNbReservePieces(c
);
823 // Resize container first
824 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
825 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
826 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
827 let rcontainer
= document
.getElementById("reserves_" + c
);
828 rcontainer
.style
.left
= i0
+ "px";
829 rcontainer
.style
.top
= j0
+ "px";
830 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
831 rcontainer
.style
.height
= sqResSize
+ "px";
832 // And then reserve cells:
833 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
834 Object
.keys(this.reserve
[c
]).forEach(p
=> {
835 if (this.reserve
[c
][p
] == 0)
837 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
838 r_cell
.style
.width
= sqResSize
+ "px";
839 r_cell
.style
.height
= sqResSize
+ "px";
844 // Return the absolute pixel coordinates given current position.
845 // Our coordinate system differs from CSS one (x <--> y).
846 // We return here the CSS coordinates (more useful).
847 getPixelPosition(i
, j
, r
) {
849 return [0, 0]; //piece vanishes
851 if (typeof i
== "string") {
852 // Reserves: need to know the rank of piece
853 const nbR
= this.getNbReservePieces(i
);
854 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
855 x
= this.getRankInReserve(i
, j
) * rsqSize
;
856 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
859 const sqSize
= r
.width
/ this.size
.y
;
860 const flipped
= this.flippedBoard
;
861 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
862 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
864 return [r
.x
+ x
, r
.y
+ y
];
868 let container
= document
.getElementById(this.containerId
);
869 let chessboard
= container
.querySelector(".chessboard");
871 const getOffset
= e
=> {
874 return {x: e
.clientX
, y: e
.clientY
};
875 let touchLocation
= null;
876 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
877 // Touch screen, dragstart
878 touchLocation
= e
.targetTouches
[0];
879 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
880 // Touch screen, dragend
881 touchLocation
= e
.changedTouches
[0];
883 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
884 return {x: 0, y: 0}; //shouldn't reach here =)
887 const centerOnCursor
= (piece
, e
) => {
888 const centerShift
= this.getPieceWidth(r
.width
) / 2;
889 const offset
= getOffset(e
);
890 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
891 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
896 startPiece
, curPiece
= null,
898 const mousedown
= (e
) => {
899 // Disable zoom on smartphones:
900 if (e
.touches
&& e
.touches
.length
> 1)
902 r
= chessboard
.getBoundingClientRect();
903 pieceWidth
= this.getPieceWidth(r
.width
);
904 const cd
= this.idToCoords(e
.target
.id
);
906 const move = this.doClick(cd
);
908 this.buildMoveStack(move, r
);
909 else if (!this.clickOnly
) {
910 const [x
, y
] = Object
.values(cd
);
911 if (typeof x
!= "number")
912 startPiece
= this.r_pieces
[x
][y
];
914 startPiece
= this.g_pieces
[x
][y
];
915 if (startPiece
&& this.canIplay(x
, y
)) {
918 curPiece
= startPiece
.cloneNode();
919 curPiece
.style
.transform
= "none";
920 curPiece
.style
.zIndex
= 5;
921 curPiece
.style
.width
= pieceWidth
+ "px";
922 curPiece
.style
.height
= pieceWidth
+ "px";
923 centerOnCursor(curPiece
, e
);
924 container
.appendChild(curPiece
);
925 startPiece
.style
.opacity
= "0.4";
926 chessboard
.style
.cursor
= "none";
932 const mousemove
= (e
) => {
935 centerOnCursor(curPiece
, e
);
937 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
938 // Attempt to prevent horizontal swipe...
942 const mouseup
= (e
) => {
945 const [x
, y
] = [start
.x
, start
.y
];
948 chessboard
.style
.cursor
= "pointer";
949 startPiece
.style
.opacity
= "1";
950 const offset
= getOffset(e
);
951 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
953 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
955 // NOTE: clearly suboptimal, but much easier, and not a big deal.
956 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
957 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
958 const moves
= this.filterValid(potentialMoves
);
959 if (moves
.length
>= 2)
960 this.showChoices(moves
, r
);
961 else if (moves
.length
== 1)
962 this.buildMoveStack(moves
[0], r
);
967 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
969 if ('onmousedown' in window
) {
970 this.mouseListeners
= [
971 {type: "mousedown", listener: mousedown
},
972 {type: "mousemove", listener: mousemove
},
973 {type: "mouseup", listener: mouseup
},
974 {type: "wheel", listener: resize
}
976 this.mouseListeners
.forEach(ml
=> {
977 document
.addEventListener(ml
.type
, ml
.listener
);
980 if ('ontouchstart' in window
) {
981 this.touchListeners
= [
982 {type: "touchstart", listener: mousedown
},
983 {type: "touchmove", listener: mousemove
},
984 {type: "touchend", listener: mouseup
}
986 this.touchListeners
.forEach(tl
=> {
987 // https://stackoverflow.com/a/42509310/12660887
988 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
991 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
994 // NOTE: not called if isDiagram
996 let container
= document
.getElementById(this.containerId
);
997 this.windowResizeObs
.unobserve(container
);
998 if ('onmousedown' in window
) {
999 this.mouseListeners
.forEach(ml
=> {
1000 document
.removeEventListener(ml
.type
, ml
.listener
);
1003 if ('ontouchstart' in window
) {
1004 this.touchListeners
.forEach(tl
=> {
1005 // https://stackoverflow.com/a/42509310/12660887
1006 document
.removeEventListener(tl
.type
, tl
.listener
);
1011 showChoices(moves
, r
) {
1012 let container
= document
.getElementById(this.containerId
);
1013 let chessboard
= container
.querySelector(".chessboard");
1014 let choices
= document
.createElement("div");
1015 choices
.id
= "choices";
1017 r
= chessboard
.getBoundingClientRect();
1018 choices
.style
.width
= r
.width
+ "px";
1019 choices
.style
.height
= r
.height
+ "px";
1020 choices
.style
.left
= r
.x
+ "px";
1021 choices
.style
.top
= r
.y
+ "px";
1022 chessboard
.style
.opacity
= "0.5";
1023 container
.appendChild(choices
);
1024 const squareWidth
= r
.width
/ this.size
.y
;
1025 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1026 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1027 const color
= moves
[0].appear
[0].c
;
1028 const callback
= (m
) => {
1029 chessboard
.style
.opacity
= "1";
1030 container
.removeChild(choices
);
1031 this.buildMoveStack(m
, r
);
1033 for (let i
=0; i
< moves
.length
; i
++) {
1034 let choice
= document
.createElement("div");
1035 choice
.classList
.add("choice");
1036 choice
.style
.width
= squareWidth
+ "px";
1037 choice
.style
.height
= squareWidth
+ "px";
1038 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1039 choice
.style
.top
= firstUpTop
+ "px";
1040 choice
.style
.backgroundColor
= "lightyellow";
1041 choice
.onclick
= () => callback(moves
[i
]);
1042 const piece
= document
.createElement("piece");
1043 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1044 C
.AddClass_es(piece
,
1045 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1046 piece
.classList
.add(V
.GetColorClass(color
));
1047 piece
.style
.width
= "100%";
1048 piece
.style
.height
= "100%";
1049 choice
.appendChild(piece
);
1050 choices
.appendChild(choice
);
1054 displayMessage(elt
, msg
, classe_s
, timeout
) {
1056 // Fixed element, e.g. for Dice Chess
1057 elt
.innerHTML
= msg
;
1059 // Temporary div (Chakart, Apocalypse...)
1060 let divMsg
= document
.createElement("div");
1061 C
.AddClass_es(divMsg
, classe_s
);
1062 divMsg
.innerHTML
= msg
;
1063 let container
= document
.getElementById(this.containerId
);
1064 container
.appendChild(divMsg
);
1065 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1072 updateEnlightened() {
1073 this.oldEnlightened
= this.enlightened
;
1074 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1075 // Add pieces positions + all squares reachable by moves (includes Zen):
1076 for (let x
=0; x
<this.size
.x
; x
++) {
1077 for (let y
=0; y
<this.size
.y
; y
++) {
1078 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1080 this.enlightened
[x
][y
] = true;
1081 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1082 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1088 this.enlightEnpassant();
1091 // Include square of the en-passant capturing square:
1092 enlightEnpassant() {
1093 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1094 // TODO: (0, 0) is wrong, would need to place an attacker here...
1095 const steps
= this.pieces(this.playerColor
, 0, 0)["p"].attack
[0].steps
;
1096 for (let step
of steps
) {
1097 const x
= this.epSquare
.x
- step
[0], //NOTE: epSquare.x not on edge
1098 y
= this.getY(this.epSquare
.y
- step
[1]);
1100 this.onBoard(x
, y
) &&
1101 this.getColor(x
, y
) == this.playerColor
&&
1102 this.getPieceType(x
, y
) == "p"
1104 this.enlightened
[x
][this.epSquare
.y
] = true;
1110 // Apply diff this.enlightened --> oldEnlightened on board
1111 graphUpdateEnlightened() {
1113 document
.getElementById(this.containerId
).querySelector(".chessboard");
1114 const r
= chessboard
.getBoundingClientRect();
1115 const pieceWidth
= this.getPieceWidth(r
.width
);
1116 for (let x
=0; x
<this.size
.x
; x
++) {
1117 for (let y
=0; y
<this.size
.y
; y
++) {
1118 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1119 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1120 elt
.classList
.add("in-shadow");
1121 if (this.g_pieces
[x
][y
])
1122 this.g_pieces
[x
][y
].classList
.add("hidden");
1124 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1125 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1126 elt
.classList
.remove("in-shadow");
1127 if (this.g_pieces
[x
][y
])
1128 this.g_pieces
[x
][y
].classList
.remove("hidden");
1141 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1145 // Color of thing on square (i,j). '' if square is empty
1147 if (typeof i
== "string")
1148 return i
; //reserves
1149 return this.board
[i
][j
].charAt(0);
1152 static GetColorClass(c
) {
1157 return "other-color"; //unidentified color
1160 // Piece on i,j. '' if square is empty
1162 if (typeof j
== "string")
1163 return j
; //reserves
1164 return this.board
[i
][j
].charAt(1);
1167 // Piece type on square (i,j)
1168 getPieceType(x
, y
, p
) {
1170 p
= this.getPiece(x
, y
);
1171 return this.pieces(this.getColor(x
, y
), x
, y
)[p
].moveas
|| p
;
1176 p
= this.getPiece(x
, y
);
1177 if (!this.options
["cannibal"])
1179 return !!C
.CannibalKings
[p
];
1182 static GetOppTurn(color
) {
1183 return (color
== 'w' ? 'b' : 'w');
1186 // Get opponent color(s): may differ from turn (e.g. Checkered)
1188 return (color
== "w" ? "b" : "w");
1191 // Is (x,y) on the chessboard?
1193 return (x
>= 0 && x
< this.size
.x
&&
1194 y
>= 0 && y
< this.size
.y
);
1197 // Am I allowed to move thing at square x,y ?
1199 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1202 ////////////////////////
1203 // PIECES SPECIFICATIONS
1205 getPawnShift(color
) {
1206 return (color
== "w" ? -1 : 1);
1208 isPawnInitRank(x
, color
) {
1209 return (color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1);
1212 pieces(color
, x
, y
) {
1213 const pawnShift
= this.getPawnShift(color
|| 'w');
1219 steps: [[pawnShift
, 0]],
1220 range: (this.isPawnInitRank(x
, color
) ? 2 : 1)
1225 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1233 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1241 [1, 2], [1, -2], [-1, 2], [-1, -2],
1242 [2, 1], [-2, 1], [2, -1], [-2, -1]
1251 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1259 [0, 1], [0, -1], [1, 0], [-1, 0],
1260 [1, 1], [1, -1], [-1, 1], [-1, -1]
1270 [0, 1], [0, -1], [1, 0], [-1, 0],
1271 [1, 1], [1, -1], [-1, 1], [-1, -1]
1278 '!': {"class": "king-pawn", moveas: "p"},
1279 '#': {"class": "king-rook", moveas: "r"},
1280 '$': {"class": "king-knight", moveas: "n"},
1281 '%': {"class": "king-bishop", moveas: "b"},
1282 '*': {"class": "king-queen", moveas: "q"}
1286 // NOTE: using special symbols to not interfere with variants' pieces codes
1287 static get CannibalKings() {
1298 static get CannibalKingCode() {
1309 //////////////////////////
1310 // MOVES GENERATION UTILS
1312 // For Cylinder: get Y coordinate
1314 if (!this.options
["cylinder"])
1316 let res
= y
% this.size
.y
;
1323 return x
; //generally, no
1326 increment([x
, y
], step
) {
1328 this.getX(x
+ step
[0]),
1329 this.getY(y
+ step
[1])
1333 getSegments(curSeg
, segStart
, segEnd
) {
1334 if (curSeg
.length
== 0)
1336 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1337 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1341 getStepSpec(color
, x
, y
, piece
) {
1342 let pieceType
= piece
;
1343 let allSpecs
= this.pieces(color
, x
, y
);
1345 pieceType
= this.getPieceType(x
, y
);
1346 else if (allSpecs
[piece
].moveas
)
1347 pieceType
= allSpecs
[piece
].moveas
;
1348 let res
= allSpecs
[pieceType
];
1358 // Can thing on square1 capture thing on square2?
1359 canTake([x1
, y1
], [x2
, y2
]) {
1360 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1363 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
1364 canSelfTake([x1
, y1
], [x2
, y2
]) {
1365 return !this.isKing(x2
, y2
);
1368 canStepOver(i
, j
, p
) {
1369 // In some variants, objects on boards don't stop movement (Chakart)
1370 return this.board
[i
][j
] == "";
1373 canDrop([c
, p
], [i
, j
]) {
1375 this.board
[i
][j
] == "" &&
1376 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1379 (c
== 'w' && i
< this.size
.x
- 1) ||
1386 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1387 isImmobilized([x
, y
]) {
1388 if (!this.options
["madrasi"])
1390 const color
= this.getColor(x
, y
);
1391 const oppCols
= this.getOppCols(color
);
1392 const piece
= this.getPieceType(x
, y
);
1393 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1394 const attacks
= stepSpec
.both
.concat(stepSpec
.attack
);
1395 for (let a
of attacks
) {
1396 outerLoop: for (let step
of a
.steps
) {
1397 let [i
, j
] = this.increment([x
, y
], step
);
1398 let stepCounter
= 0;
1399 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1400 if (a
.range
<= stepCounter
++)
1402 [i
, j
] = this.increment([i
, j
], step
);
1405 this.onBoard(i
, j
) &&
1406 oppCols
.includes(this.getColor(i
, j
)) &&
1407 this.getPieceType(i
, j
) == piece
1416 // Stop at the first capture found
1417 atLeastOneCapture(color
) {
1418 const allowed
= (sq1
, sq2
) => {
1420 // NOTE: canTake is reversed for Zen.
1421 // Generally ok because of the symmetry. TODO?
1422 this.canTake(sq1
, sq2
) &&
1424 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1427 for (let i
=0; i
<this.size
.x
; i
++) {
1428 for (let j
=0; j
<this.size
.y
; j
++) {
1429 if (this.getColor(i
, j
) == color
) {
1432 !this.options
["zen"] &&
1433 this.findDestSquares(
1445 this.options
["zen"] &&
1446 this.findCapturesOn(
1462 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1463 const epsilon
= 1e-7; //arbitrary small value
1465 if (this.options
["cylinder"])
1466 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1467 for (let sh
of shifts
) {
1468 const rx
= (x2
- x1
) / step
[0],
1469 ry
= (y2
+ sh
- y1
) / step
[1];
1471 // Zero step but non-zero interval => impossible
1472 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1473 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1474 // Negative number of step (impossible)
1475 (rx
< 0 || ry
< 0) ||
1476 // Not the same number of steps in both directions:
1477 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1481 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1482 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1484 distance
= Math
.round(distance
); //in case of (numerical...)
1485 if (!range
|| range
>= distance
)
1491 ////////////////////
1494 getDropMovesFrom([c
, p
]) {
1495 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1496 // (but not necessarily otherwise: atLeastOneMove() etc)
1497 if (this.reserve
[c
][p
] == 0)
1500 for (let i
=0; i
<this.size
.x
; i
++) {
1501 for (let j
=0; j
<this.size
.y
; j
++) {
1502 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1504 start: {x: c
, y: p
},
1506 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1509 if (this.board
[i
][j
] != "") {
1510 mv
.vanish
.push(new PiPo({
1513 c: this.getColor(i
, j
),
1514 p: this.getPiece(i
, j
)
1524 // All possible moves from selected square
1525 // TODO: generalize usage if arg "color" (e.g. Checkered)
1526 getPotentialMovesFrom([x
, y
], color
) {
1527 if (this.subTurnTeleport
== 2)
1529 if (typeof x
== "string")
1530 return this.getDropMovesFrom([x
, y
]);
1531 if (this.isImmobilized([x
, y
]))
1533 const piece
= this.getPieceType(x
, y
);
1534 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1535 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1536 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1537 if (this.isKing(0, 0, piece
) && this.hasCastle
)
1538 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1539 return this.postProcessPotentialMoves(moves
);
1542 postProcessPotentialMoves(moves
) {
1543 if (moves
.length
== 0)
1545 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1546 const oppCols
= this.getOppCols(color
);
1548 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1549 moves
= this.capturePostProcess(moves
, oppCols
);
1551 if (this.options
["atomic"])
1552 moves
= this.atomicPostProcess(moves
, color
, oppCols
);
1556 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1558 moves
= this.pawnPostProcess(moves
, color
, oppCols
);
1561 if (this.options
["cannibal"] && this.options
["rifle"])
1562 // In this case a rifle-capture from last rank may promote a pawn
1563 moves
= this.riflePromotePostProcess(moves
, color
);
1568 capturePostProcess(moves
, oppCols
) {
1569 // Filter out non-capturing moves (not using m.vanish because of
1570 // self captures of Recycle and Teleport).
1571 return moves
.filter(m
=> {
1573 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1574 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1579 atomicPostProcess(moves
, color
, oppCols
) {
1580 moves
.forEach(m
=> {
1582 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1583 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1596 let mNext
= new Move({
1602 for (let step
of steps
) {
1603 let [x
, y
] = this.increment([m
.end
.x
, m
.end
.y
], step
);
1605 this.onBoard(x
, y
) &&
1606 this.board
[x
][y
] != "" &&
1607 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1608 this.getPieceType(x
, y
) != "p"
1612 p: this.getPiece(x
, y
),
1613 c: this.getColor(x
, y
),
1620 if (!this.options
["rifle"]) {
1621 // The moving piece also vanish
1622 mNext
.vanish
.unshift(
1627 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1637 pawnPostProcess(moves
, color
, oppCols
) {
1639 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1640 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1641 moves
.forEach(m
=> {
1642 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1643 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1644 const promotionOk
= (
1646 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1649 return; //nothing to do
1650 if (this.options
["pawnfall"]) {
1656 this.options
["cannibal"] &&
1657 this.board
[x2
][y2
] != "" &&
1658 oppCols
.includes(this.getColor(x2
, y2
))
1660 finalPieces
= [this.getPieceType(x2
, y2
)];
1663 finalPieces
= this.pawnPromotions
;
1664 m
.appear
[0].p
= finalPieces
[0];
1665 if (initPiece
== "!") //cannibal king-pawn
1666 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1667 for (let i
=1; i
<finalPieces
.length
; i
++) {
1668 let newMove
= JSON
.parse(JSON
.stringify(m
));
1669 const piece
= finalPieces
[i
];
1670 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1671 moreMoves
.push(newMove
);
1674 return moves
.concat(moreMoves
);
1677 riflePromotePostProcess(moves
, color
) {
1678 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1680 moves
.forEach(m
=> {
1682 m
.start
.x
== lastRank
&&
1683 m
.appear
.length
>= 1 &&
1684 m
.appear
[0].p
== "p" &&
1685 m
.appear
[0].x
== m
.start
.x
&&
1686 m
.appear
[0].y
== m
.start
.y
1688 m
.appear
[0].p
= this.pawnPromotions
[0];
1689 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1690 let newMv
= JSON
.parse(JSON
.stringify(m
));
1691 newMv
.appear
[0].p
= this.pawnPromotions
[i
];
1692 newMoves
.push(newMv
);
1696 return moves
.concat(newMoves
);
1699 // Generic method to find possible moves of "sliding or jumping" pieces
1700 getPotentialMovesOf(piece
, [x
, y
]) {
1701 const color
= this.getColor(x
, y
);
1702 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1704 if (stepSpec
.attack
) {
1705 squares
= this.findDestSquares(
1711 ([i1
, j1
], [i2
, j2
]) => {
1713 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1714 this.canTake([i1
, j1
], [i2
, j2
])
1719 const noSpecials
= this.findDestSquares(
1722 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1726 Array
.prototype.push
.apply(squares
, noSpecials
);
1727 if (this.options
["zen"]) {
1728 let zenCaptures
= this.findCapturesOn(
1730 {}, //byCol: default is ok
1731 ([i1
, j1
], [i2
, j2
]) =>
1732 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1734 // Technical step: segments (if any) are reversed
1735 zenCaptures
.forEach(z
=> {
1737 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1739 Array
.prototype.push
.apply(squares
, zenCaptures
);
1741 if (this.hasSelfCaptures
) {
1742 const selfCaptures
= this.findDestSquares(
1748 ([i1
, j1
], [i2
, j2
]) => {
1750 this.getColor(i2
, j2
) == color
&&
1751 this.canSelfTake([i1
, j1
], [i2
, j2
])
1755 Array
.prototype.push
.apply(squares
, selfCaptures
);
1757 return squares
.map(s
=> {
1758 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1760 mv
.segments
= s
.segments
;
1765 findDestSquares([x
, y
], o
, allowed
) {
1767 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1768 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1770 // Next 3 for Cylinder mode or circular (useless otherwise)
1774 const addSquare
= ([i
, j
]) => {
1775 let elt
= {sq: [i
, j
]};
1776 if (segments
.length
>= 1)
1777 elt
.segments
= this.getSegments(segments
, segStart
, [i
, j
]);
1780 const exploreSteps
= (stepArray
, mode
) => {
1781 for (let s
of stepArray
) {
1782 outerLoop: for (let step
of s
.steps
) {
1785 let [i
, j
] = [x
, y
];
1786 let stepCounter
= 0;
1788 this.onBoard(i
, j
) &&
1789 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1791 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1792 explored
[i
+ "." + j
] = true;
1795 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1797 if (o
.one
&& mode
!= "attack")
1799 if (mode
!= "attack")
1800 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1801 if (o
.captureTarget
)
1805 if (s
.range
<= stepCounter
++)
1807 const oldIJ
= [i
, j
];
1808 [i
, j
] = this.increment([i
, j
], step
);
1810 Math
.abs(i
- oldIJ
[0]) != Math
.abs(step
[0]) ||
1811 Math
.abs(j
- oldIJ
[1]) != Math
.abs(step
[1])
1813 // Boundary between segments (cylinder or circular mode)
1814 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1818 if (!this.onBoard(i
, j
))
1820 const pieceIJ
= this.getPieceType(i
, j
);
1821 if (!explored
[i
+ "." + j
]) {
1822 explored
[i
+ "." + j
] = true;
1823 if (allowed([x
, y
], [i
, j
])) {
1824 if (o
.one
&& mode
!= "moves")
1826 if (mode
!= "moves")
1827 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1830 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1838 return undefined; //default, but let's explicit it
1840 if (o
.captureTarget
)
1841 return exploreSteps(o
.captureSteps
, "attack");
1844 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1847 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.moves
), "moves");
1848 if (!outOne
&& !o
.moveOnly
)
1849 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.attack
), "attack");
1850 return (o
.one
? outOne : res
);
1854 // Search for enemy (or not) pieces attacking [x, y]
1855 findCapturesOn([x
, y
], o
, allowed
) {
1857 o
.byCol
= this.getOppCols(this.getColor(x
, y
) || this.turn
);
1859 for (let i
=0; i
<this.size
.x
; i
++) {
1860 for (let j
=0; j
<this.size
.y
; j
++) {
1861 const colIJ
= this.getColor(i
, j
);
1863 this.board
[i
][j
] != "" &&
1864 o
.byCol
.includes(colIJ
) &&
1865 !this.isImmobilized([i
, j
])
1867 const apparentPiece
= this.getPiece(i
, j
);
1868 // Quick check: does this potential attacker target x,y ?
1869 if (this.canStepOver(x
, y
, apparentPiece
))
1871 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1872 const attacks
= stepSpec
.attack
.concat(stepSpec
.both
);
1873 for (let a
of attacks
) {
1874 for (let s
of a
.steps
) {
1875 // Quick check: if step isn't compatible, don't even try
1876 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1878 // Finally verify that nothing stand in-between
1879 const out
= this.findDestSquares(
1882 captureTarget: [x
, y
],
1883 captureSteps: [{steps: [s
], range: a
.range
}],
1897 return (o
.one
? false : res
);
1900 // Build a regular move from its initial and destination squares.
1901 // tr: transformation
1902 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1903 const initColor
= this.getColor(sx
, sy
);
1904 const initPiece
= this.getPiece(sx
, sy
);
1905 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1909 start: {x: sx
, y: sy
},
1913 !this.options
["rifle"] ||
1914 this.board
[ex
][ey
] == "" ||
1915 destColor
== initColor
//Recycle, Teleport
1921 c: !!tr
? tr
.c : initColor
,
1922 p: !!tr
? tr
.p : initPiece
1934 if (this.board
[ex
][ey
] != "") {
1939 c: this.getColor(ex
, ey
),
1940 p: this.getPiece(ex
, ey
)
1943 if (this.options
["cannibal"] && destColor
!= initColor
) {
1944 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1945 let trPiece
= mv
.vanish
[lastIdx
].p
;
1946 if (this.isKing(sx
, sy
))
1947 trPiece
= C
.CannibalKingCode
[trPiece
];
1948 if (mv
.appear
.length
>= 1)
1949 mv
.appear
[0].p
= trPiece
;
1950 else if (this.options
["rifle"]) {
1973 // En-passant square, if any
1974 getEpSquare(moveOrSquare
) {
1975 if (typeof moveOrSquare
=== "string") {
1976 const square
= moveOrSquare
;
1979 return C
.SquareToCoords(square
);
1981 // Argument is a move:
1982 const move = moveOrSquare
;
1983 const s
= move.start
,
1987 Math
.abs(s
.x
- e
.x
) == 2 &&
1988 // Next conditions for variants like Atomic or Rifle, Recycle...
1990 move.appear
.length
> 0 &&
1991 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1995 move.vanish
.length
> 0 &&
1996 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
2004 return undefined; //default
2007 // Special case of en-passant captures: treated separately
2008 getEnpassantCaptures([x
, y
]) {
2009 const color
= this.getColor(x
, y
);
2010 const shiftX
= (color
== 'w' ? -1 : 1);
2011 const oppCols
= this.getOppCols(color
);
2014 this.epSquare
.x
== x
+ shiftX
&& //NOTE: epSquare.x not on edge
2015 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2016 // Doublemove (and Progressive?) guards:
2017 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2018 oppCols
.includes(this.getColor(x
, this.epSquare
.y
))
2020 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2021 this.board
[epx
][epy
] = this.board
[x
][this.epSquare
.y
];
2022 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2023 this.board
[epx
][epy
] = "";
2024 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2025 enpassantMove
.vanish
[lastIdx
].x
= x
;
2026 return [enpassantMove
];
2031 getCastleMoves([x
, y
], finalSquares
, castleWith
, castleFlags
) {
2032 const c
= this.getColor(x
, y
);
2033 castleFlags
= castleFlags
|| this.castleFlags
[c
];
2036 const oppCols
= this.getOppCols(c
);
2040 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2041 const castlingKing
= this.getPiece(x
, y
);
2042 castlingCheck: for (
2045 castleSide
++ //large, then small
2047 if (castleFlags
[castleSide
] >= this.size
.y
)
2049 // If this code is reached, rook and king are on initial position
2051 // NOTE: in some variants this is not a rook
2052 const rookPos
= castleFlags
[castleSide
];
2053 const castlingPiece
= this.getPiece(x
, rookPos
);
2055 this.board
[x
][rookPos
] == "" ||
2056 this.getColor(x
, rookPos
) != c
||
2057 (castleWith
&& !castleWith
.includes(castlingPiece
))
2059 // Rook is not here, or changed color (see Benedict)
2062 // Nothing on the path of the king ? (and no checks)
2063 const finDist
= finalSquares
[castleSide
][0] - y
;
2064 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2068 // NOTE: next weird test because underCheck() verification
2069 // will be executed in filterValid() later.
2071 i
!= finalSquares
[castleSide
][0] &&
2072 this.underCheck([[x
, i
]], oppCols
)
2076 this.board
[x
][i
] != "" &&
2077 // NOTE: next check is enough, because of chessboard constraints
2078 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2081 continue castlingCheck
;
2084 } while (i
!= finalSquares
[castleSide
][0]);
2085 // Nothing on the path to the rook?
2086 step
= (castleSide
== 0 ? -1 : 1);
2087 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2088 if (this.board
[x
][i
] != "")
2089 continue castlingCheck
;
2092 // Nothing on final squares, except maybe king and castling rook?
2093 for (i
= 0; i
< 2; i
++) {
2095 finalSquares
[castleSide
][i
] != rookPos
&&
2096 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2098 finalSquares
[castleSide
][i
] != y
||
2099 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2102 continue castlingCheck
;
2106 // If this code is reached, castle is potentially valid
2112 y: finalSquares
[castleSide
][0],
2118 y: finalSquares
[castleSide
][1],
2124 // King might be initially disguised (Titan...)
2125 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2126 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2129 Math
.abs(y
- rookPos
) <= 2
2130 ? {x: x
, y: rookPos
}
2131 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2139 ////////////////////
2142 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2143 underAttack([x
, y
], oppCols
) {
2144 // An empty square is considered as king,
2145 // since it's used only in getCastleMoves (TODO?)
2146 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2149 (!this.options
["zen"] || king
) &&
2150 this.findCapturesOn(
2160 (!!this.options
["zen"] && !king
) &&
2161 this.findDestSquares(
2167 ([i1
, j1
], [i2
, j2
]) => oppCols
.includes(this.getColor(i2
, j2
))
2173 // Argument is (very generally) an array of squares (= arrays)
2174 underCheck(square_s
, oppCols
) {
2175 if (this.options
["taking"] || this.options
["dark"])
2177 return square_s
.some(sq
=> this.underAttack(sq
, oppCols
));
2180 // Scan board for king(s)
2181 searchKingPos(color
) {
2183 for (let i
=0; i
< this.size
.x
; i
++) {
2184 for (let j
=0; j
< this.size
.y
; j
++) {
2185 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2192 // cb: callback returning a boolean (false if king missing)
2193 trackKingWrap(move, kingPos
, cb
) {
2194 if (move.appear
.length
== 0 && move.vanish
.length
== 0)
2197 (move.vanish
.length
> 0 ? move.vanish
[0].c : move.appear
[0].c
);
2198 let newKingPP
= null,
2200 res
= true; //a priori valid
2202 move.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2204 // Search king in appear array:
2206 move.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2208 sqIdx
= kingPos
.findIndex(kp
=>
2209 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2210 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2213 res
= false; //king vanished
2215 res
&&= cb(kingPos
);
2216 if (oldKingPP
&& newKingPP
)
2217 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2221 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2222 filterValid(moves
, color
) {
2225 const oppCols
= this.getOppCols(color
);
2226 let kingPos
= this.searchKingPos(color
);
2227 return moves
.filter(m
=> {
2228 this.playOnBoard(m
);
2229 const res
= this.trackKingWrap(m
, kingPos
, (kp
) => {
2230 return !this.underCheck(kp
, oppCols
);
2232 this.undoOnBoard(m
);
2240 // Apply a move on board
2242 for (let psq
of move.vanish
)
2243 this.board
[psq
.x
][psq
.y
] = "";
2244 for (let psq
of move.appear
)
2245 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2247 // Un-apply the played move
2249 for (let psq
of move.appear
)
2250 this.board
[psq
.x
][psq
.y
] = "";
2251 for (let psq
of move.vanish
)
2252 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2255 // NOTE: arg "castleFlags" for Coregal or Twokings
2256 updateCastleFlags(move, castleFlags
, king
) {
2257 castleFlags
= castleFlags
|| this.castleFlags
;
2258 // If flags already off, no need to re-check:
2260 Object
.values(castleFlags
).every(cvals
=>
2261 cvals
.every(val
=> val
>= this.size
.y
))
2265 // Update castling flags if start or arrive from/at rook/king locations
2266 move.appear
.concat(move.vanish
).forEach(psq
=> {
2267 if ((king
&& psq
.p
== king
) || (!king
&& this.isKing(0, 0, psq
.p
)))
2268 castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2269 // NOTE: not "else if" because king can capture enemy rook...
2273 else if (psq
.x
== this.size
.x
- 1)
2276 const fidx
= castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2278 castleFlags
[c
][fidx
] = this.size
.y
;
2285 this.updateCastleFlags(move);
2286 if (this.options
["crazyhouse"]) {
2287 move.vanish
.forEach(v
=> {
2288 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2289 if (this.ispawn
[square
])
2290 delete this.ispawn
[square
];
2292 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2293 // Assumption: something is moving
2294 const initSquare
= C
.CoordsToSquare(move.start
);
2295 const destSquare
= C
.CoordsToSquare(move.end
);
2297 this.ispawn
[initSquare
] ||
2298 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2300 this.ispawn
[destSquare
] = true;
2303 this.ispawn
[destSquare
] &&
2304 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2306 move.vanish
[1].p
= 'p';
2307 delete this.ispawn
[destSquare
];
2311 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2314 // Warning; atomic pawn removal isn't a capture
2315 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2317 const color
= this.turn
;
2318 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2319 // Something appears = dropped on board (some exceptions, Chakart...)
2320 if (move.appear
[i
].c
== color
) {
2321 const piece
= move.appear
[i
].p
;
2322 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2325 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2326 // Something vanish: add to reserve except if recycle & opponent
2328 this.options
["crazyhouse"] ||
2329 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2331 const piece
= move.vanish
[i
].p
;
2332 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2340 if (this.hasEnpassant
)
2341 this.epSquare
= this.getEpSquare(move);
2342 this.playOnBoard(move);
2343 this.postPlay(move);
2347 if (this.options
["dark"])
2348 this.updateEnlightened();
2349 if (this.options
["teleport"]) {
2351 this.subTurnTeleport
== 1 &&
2352 move.vanish
.length
== 2 &&
2353 move.appear
.length
== 1 &&
2354 move.vanish
[1].c
== this.turn
2356 const v
= move.vanish
[1];
2357 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2358 this.subTurnTeleport
= 2;
2361 this.subTurnTeleport
= 1;
2362 this.captured
= null;
2364 this.tryChangeTurn(move);
2367 tryChangeTurn(move) {
2368 if (this.isLastMove(move)) {
2369 this.turn
= C
.GetOppTurn(this.turn
);
2373 else if (!move.next
)
2380 const color
= this.turn
;
2381 const oppKingPos
= this.searchKingPos(C
.GetOppTurn(color
));
2382 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, [color
]))
2386 !this.options
["balance"] ||
2387 ![1, 2].includes(this.movesCount
) ||
2392 !this.options
["doublemove"] ||
2393 this.movesCount
== 0 ||
2398 !this.options
["progressive"] ||
2399 this.subTurn
== this.movesCount
+ 1
2404 // "Stop at the first move found"
2405 atLeastOneMove(color
) {
2406 for (let i
= 0; i
< this.size
.x
; i
++) {
2407 for (let j
= 0; j
< this.size
.y
; j
++) {
2408 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2409 // NOTE: in fact searching for all potential moves from i,j.
2410 // I don't believe this is an issue, for now at least.
2411 const moves
= this.getPotentialMovesFrom([i
, j
], color
);
2412 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2417 if (this.hasReserve
&& this.reserve
[color
]) {
2418 for (let p
of Object
.keys(this.reserve
[color
])) {
2419 const moves
= this.getDropMovesFrom([color
, p
]);
2420 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2427 // What is the score ? (Interesting if game is over)
2428 getCurrentScore(move_s
) {
2429 const move = move_s
[move_s
.length
- 1];
2430 // Shortcut in case the score was computed before:
2433 const oppTurn
= C
.GetOppTurn(this.turn
);
2435 w: this.searchKingPos('w'),
2436 b: this.searchKingPos('b')
2438 if (kingPos
[this.turn
].length
== 0 && kingPos
[oppTurn
].length
== 0)
2440 if (kingPos
[this.turn
].length
== 0)
2441 return (this.turn
== "w" ? "0-1" : "1-0");
2442 if (kingPos
[oppTurn
].length
== 0)
2443 return (this.turn
== "w" ? "1-0" : "0-1");
2444 if (this.atLeastOneMove(this.turn
))
2446 // No valid move: stalemate or checkmate?
2447 if (!this.underCheck(kingPos
[this.turn
], this.getOppCols(this.turn
)))
2450 return (this.turn
== "w" ? "0-1" : "1-0");
2453 playVisual(move, r
) {
2454 move.vanish
.forEach(v
=> {
2455 if (this.g_pieces
[v
.x
][v
.y
]) //can be null (e.g. Apocalypse)
2456 this.g_pieces
[v
.x
][v
.y
].remove();
2457 this.g_pieces
[v
.x
][v
.y
] = null;
2460 document
.getElementById(this.containerId
).querySelector(".chessboard");
2462 r
= chessboard
.getBoundingClientRect();
2463 const pieceWidth
= this.getPieceWidth(r
.width
);
2464 move.appear
.forEach(a
=> {
2465 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2466 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2467 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2468 this.g_pieces
[a
.x
][a
.y
].classList
.add(V
.GetColorClass(a
.c
));
2469 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2470 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2471 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2472 // Translate coordinates to use chessboard as reference:
2473 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2474 `translate(${ip - r.x}px,${jp - r.y}px)`;
2475 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2476 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2477 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2479 if (this.options
["dark"])
2480 this.graphUpdateEnlightened();
2483 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2484 buildMoveStack(move, r
) {
2485 this.moveStack
.push(move);
2486 this.computeNextMove(move);
2487 const then
= () => {
2488 const newTurn
= this.turn
;
2489 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2490 this.playVisual(move, r
);
2494 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2496 this.buildMoveStack(move.next
, r
);
2499 if (this.moveStack
.length
== 1) {
2500 // Usual case (one normal move)
2501 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2502 this.moveStack
= [];
2505 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2506 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2507 this.playReceivedMove(this.moveStack
.slice(1), () => {
2508 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2509 this.moveStack
= [];
2514 // If hiding moves, then they are revealed in play() with callback
2515 this.play(move, this.hideMoves
? then : null);
2516 if (!this.hideMoves
)
2520 // Implemented in variants using (automatic) moveStack
2521 computeNextMove(move) {}
2523 animateMoving(start
, end
, drag
, segments
, cb
) {
2524 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2525 if (!initPiece
) { //TODO: shouldn't occur!
2529 // NOTE: cloning often not required, but light enough, and simpler
2530 let movingPiece
= initPiece
.cloneNode();
2531 initPiece
.style
.opacity
= "0";
2533 document
.getElementById(this.containerId
)
2534 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2535 if (typeof start
.x
== "string") {
2536 // Need to bound width/height (was 100% for reserve pieces)
2537 const pieceWidth
= this.getPieceWidth(r
.width
);
2538 movingPiece
.style
.width
= pieceWidth
+ "px";
2539 movingPiece
.style
.height
= pieceWidth
+ "px";
2541 const maxDist
= this.getMaxDistance(r
);
2542 const apparentColor
= this.getColor(start
.x
, start
.y
);
2543 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2545 const startCode
= this.getPiece(start
.x
, start
.y
);
2546 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2547 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2548 if (apparentColor
!= drag
.c
) {
2549 movingPiece
.classList
.remove(V
.GetColorClass(apparentColor
));
2550 movingPiece
.classList
.add(V
.GetColorClass(drag
.c
));
2553 container
.appendChild(movingPiece
);
2554 const animateSegment
= (index
, cb
) => {
2555 // NOTE: move.drag could be generalized per-segment (usage?)
2556 const [i1
, j1
] = segments
[index
][0];
2557 const [i2
, j2
] = segments
[index
][1];
2558 const dep
= this.getPixelPosition(i1
, j1
, r
);
2559 const arr
= this.getPixelPosition(i2
, j2
, r
);
2560 movingPiece
.style
.transitionDuration
= "0s";
2561 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2563 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2564 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2565 // TODO: unclear why we need this new delay below:
2567 movingPiece
.style
.transitionDuration
= duration
+ "s";
2568 // movingPiece is child of container: no need to adjust coordinates
2569 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2570 setTimeout(cb
, duration
* 1000);
2574 const animateSegmentCallback
= () => {
2575 if (index
< segments
.length
)
2576 animateSegment(index
++, animateSegmentCallback
);
2578 movingPiece
.remove();
2579 initPiece
.style
.opacity
= "1";
2583 animateSegmentCallback();
2586 // Input array of objects with at least fields x,y (e.g. PiPo)
2587 animateFading(arr
, cb
) {
2588 const animLength
= 350; //TODO: 350ms? More? Less?
2590 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2591 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2592 fadingPiece
.style
.opacity
= "0";
2594 setTimeout(cb
, animLength
);
2597 animate(move, callback
) {
2598 if (this.noAnimate
|| move.noAnimate
) {
2602 let segments
= move.segments
;
2604 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2605 let targetObj
= new TargetObj(callback
);
2606 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2608 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2609 () => targetObj
.increment());
2611 if (move.vanish
.length
> move.appear
.length
) {
2612 const arr
= move.vanish
.slice(move.appear
.length
)
2613 // Ignore disappearing pieces hidden by some appearing ones:
2614 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2615 if (arr
.length
> 0) {
2617 this.animateFading(arr
, () => targetObj
.increment());
2621 this.tryAnimateCastle(move, () => targetObj
.increment());
2623 this.customAnimate(move, segments
, () => targetObj
.increment());
2624 if (targetObj
.target
== 0)
2628 tryAnimateCastle(move, cb
) {
2631 move.vanish
.length
== 2 &&
2632 move.appear
.length
== 2 &&
2633 this.isKing(0, 0, move.vanish
[0].p
) &&
2634 this.isKing(0, 0, move.appear
[0].p
)
2636 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2637 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2638 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2639 this.animateMoving(start
, end
, null, segments
, cb
);
2645 // Potential other animations (e.g. for Suction variant)
2646 customAnimate(move, segments
, cb
) {
2647 return 0; //nb of targets
2650 launchAnimation(moves
, container
, callback
) {
2651 if (this.hideMoves
) {
2652 for (let i
=0; i
<moves
.length
; i
++)
2653 // If hiding moves, they are revealed into play():
2654 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2657 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2658 const animateRec
= i
=> {
2659 this.animate(moves
[i
], () => {
2660 this.play(moves
[i
]);
2661 this.playVisual(moves
[i
], r
);
2662 if (i
< moves
.length
- 1)
2663 setTimeout(() => animateRec(i
+1), 300);
2671 playReceivedMove(moves
, callback
) {
2672 // Delay if user wasn't focused:
2673 const checkDisplayThenAnimate
= (delay
) => {
2674 if (container
.style
.display
== "none") {
2675 alert("New move! Let's go back to game...");
2676 document
.getElementById("gameInfos").style
.display
= "none";
2677 container
.style
.display
= "block";
2679 () => this.launchAnimation(moves
, container
, callback
),
2685 () => this.launchAnimation(moves
, container
, callback
),
2690 let container
= document
.getElementById(this.containerId
);
2691 if (document
.hidden
) {
2692 document
.onvisibilitychange
= () => {
2693 // TODO here: page reload ?! (some issues if tab changed...)
2694 document
.onvisibilitychange
= undefined;
2695 checkDisplayThenAnimate(700);
2699 checkDisplayThenAnimate();