ea34a3d806d1c26b2a645d88c1a6bdf730f86f9f
1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // Helper class for move animation
9 constructor(callOnComplete
) {
12 this.callOnComplete
= callOnComplete
;
15 if (++this.value
== this.target
)
16 this.callOnComplete();
21 // NOTE: x coords: top to bottom (white perspective); y: left to right
22 // NOTE: ChessRules is aliased as window.C, and variants as window.V
23 export default class ChessRules
{
25 static get Aliases() {
26 return {'C': ChessRules
};
29 /////////////////////////
30 // VARIANT SPECIFICATIONS
32 // Some variants have specific options, like the number of pawns in Monster,
33 // or the board size for Pandemonium.
34 // Users can generally select a randomness level from 0 to 2.
35 static get Options() {
39 variable: "randomness",
42 {label: "Deterministic", value: 0},
43 {label: "Symmetric random", value: 1},
44 {label: "Asymmetric random", value: 2}
49 label: "Capture king",
55 label: "Falling pawn",
61 // Game modifiers (using "elementary variants"). Default: false
64 "balance", //takes precedence over doublemove & progressive
68 "cylinder", //ok with all
72 "progressive", //(natural) priority over doublemove
81 get pawnPromotions() {
82 return ['q', 'r', 'n', 'b'];
85 // Some variants don't have flags:
94 // En-passant captures allowed?
101 !!this.options
["crazyhouse"] ||
102 (!!this.options
["recycle"] && !this.options
["teleport"])
105 // Some variants do not store reserve state (Align4, Chakart...)
106 get hasReserveFen() {
107 return this.hasReserve
;
111 return !!this.options
["dark"];
114 // Some variants use only click information
119 // Some variants use click infos:
121 if (typeof coords
.x
!= "number")
122 return null; //click on reserves
124 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
125 this.board
[coords
.x
][coords
.y
] == ""
128 start: {x: this.captured
.x
, y: this.captured
.y
},
139 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
148 // 3a --> {x:3, y:10}
149 static SquareToCoords(sq
) {
150 return ArrayFun
.toObject(["x", "y"],
151 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
154 // {x:11, y:12} --> bc
155 static CoordsToSquare(cd
) {
156 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
160 if (typeof cd
.x
== "number") {
162 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
166 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
169 idToCoords(targetId
) {
171 return null; //outside page, maybe...
172 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
174 idParts
.length
< 2 ||
175 idParts
[0] != this.containerId
||
176 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
180 const squares
= idParts
[1].split('-');
181 if (squares
[0] == "sq")
182 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
183 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
184 return {x: squares
[1], y: squares
[2]};
190 // Turn "wb" into "B" (for FEN)
192 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
195 // Turn "p" into "bp" (for board)
197 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
200 // Setup the initial random-or-not (asymmetric-or-not) position
201 genRandInitFen(seed
) {
202 let fen
, flags
= "0707";
203 if (!this.options
.randomness
)
205 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
209 Random
.setSeed(seed
);
210 let pieces
= {w: new Array(8), b: new Array(8)};
212 // Shuffle pieces on first (and last rank if randomness == 2)
213 for (let c
of ["w", "b"]) {
214 if (c
== 'b' && this.options
.randomness
== 1) {
215 pieces
['b'] = pieces
['w'];
220 let positions
= ArrayFun
.range(8);
222 // Get random squares for bishops
223 let randIndex
= 2 * Random
.randInt(4);
224 const bishop1Pos
= positions
[randIndex
];
225 // The second bishop must be on a square of different color
226 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
227 const bishop2Pos
= positions
[randIndex_tmp
];
228 // Remove chosen squares
229 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
230 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
232 // Get random squares for knights
233 randIndex
= Random
.randInt(6);
234 const knight1Pos
= positions
[randIndex
];
235 positions
.splice(randIndex
, 1);
236 randIndex
= Random
.randInt(5);
237 const knight2Pos
= positions
[randIndex
];
238 positions
.splice(randIndex
, 1);
240 // Get random square for queen
241 randIndex
= Random
.randInt(4);
242 const queenPos
= positions
[randIndex
];
243 positions
.splice(randIndex
, 1);
245 // Rooks and king positions are now fixed,
246 // because of the ordering rook-king-rook
247 const rook1Pos
= positions
[0];
248 const kingPos
= positions
[1];
249 const rook2Pos
= positions
[2];
251 // Finally put the shuffled pieces in the board array
252 pieces
[c
][rook1Pos
] = "r";
253 pieces
[c
][knight1Pos
] = "n";
254 pieces
[c
][bishop1Pos
] = "b";
255 pieces
[c
][queenPos
] = "q";
256 pieces
[c
][kingPos
] = "k";
257 pieces
[c
][bishop2Pos
] = "b";
258 pieces
[c
][knight2Pos
] = "n";
259 pieces
[c
][rook2Pos
] = "r";
260 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
263 pieces
["b"].join("") +
264 "/pppppppp/8/8/8/8/PPPPPPPP/" +
265 pieces
["w"].join("").toUpperCase() +
269 // Add turn + flags + enpassant (+ reserve)
272 parts
.push(`"flags":"${flags}"`);
273 if (this.hasEnpassant
)
274 parts
.push('"enpassant":"-"');
275 if (this.hasReserveFen
)
276 parts
.push('"reserve":"000000000000"');
277 if (this.options
["crazyhouse"])
278 parts
.push('"ispawn":"-"');
279 if (parts
.length
>= 1)
280 fen
+= " {" + parts
.join(",") + "}";
284 // "Parse" FEN: just return untransformed string data
286 const fenParts
= fen
.split(" ");
288 position: fenParts
[0],
290 movesCount: fenParts
[2]
292 if (fenParts
.length
> 3)
293 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
297 // Return current fen (game state)
300 this.getPosition() + " " +
301 this.getTurnFen() + " " +
306 parts
.push(`"flags":"${this.getFlagsFen()}"`);
307 if (this.hasEnpassant
)
308 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
309 if (this.hasReserveFen
)
310 parts
.push(`"reserve":"${this.getReserveFen()}"`);
311 if (this.options
["crazyhouse"])
312 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
313 if (parts
.length
>= 1)
314 fen
+= " {" + parts
.join(",") + "}";
318 static FenEmptySquares(count
) {
319 // if more than 9 consecutive free spaces, break the integer,
320 // otherwise FEN parsing will fail.
323 // Most boards of size < 18:
325 return "9" + (count
- 9);
327 return "99" + (count
- 18);
330 // Position part of the FEN string
333 for (let i
= 0; i
< this.size
.y
; i
++) {
335 for (let j
= 0; j
< this.size
.x
; j
++) {
336 if (this.board
[i
][j
] == "")
339 if (emptyCount
> 0) {
340 // Add empty squares in-between
341 position
+= C
.FenEmptySquares(emptyCount
);
344 position
+= this.board2fen(this.board
[i
][j
]);
349 position
+= C
.FenEmptySquares(emptyCount
);
350 if (i
< this.size
.y
- 1)
351 position
+= "/"; //separate rows
360 // Flags part of the FEN string
362 return ["w", "b"].map(c
=> {
363 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
367 // Enpassant part of the FEN string
370 return "-"; //no en-passant
371 return C
.CoordsToSquare(this.epSquare
);
376 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
381 const squares
= Object
.keys(this.ispawn
);
382 if (squares
.length
== 0)
384 return squares
.join(",");
387 // Set flags from fen (castle: white a,h then black a,h)
390 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
391 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
399 this.options
= o
.options
;
400 // Fill missing options (always the case if random challenge)
401 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
402 if (this.options
[opt
.variable
] === undefined)
403 this.options
[opt
.variable
] = opt
.defaut
;
406 // This object will be used only for initial FEN generation
408 this.playerColor
= o
.color
;
409 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
411 // Fen string fully describes the game state
413 o
.fen
= this.genRandInitFen(o
.seed
);
414 this.re_initFromFen(o
.fen
);
416 // Graphical (can use variables defined above)
417 this.containerId
= o
.element
;
418 this.graphicalInit();
421 re_initFromFen(fen
, oldBoard
) {
422 const fenParsed
= this.parseFen(fen
);
423 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
424 this.turn
= fenParsed
.turn
;
425 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
426 this.setOtherVariables(fenParsed
);
429 // Turn position fen into double array ["wb","wp","bk",...]
431 const rows
= position
.split("/");
432 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
433 for (let i
= 0; i
< rows
.length
; i
++) {
435 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
436 const character
= rows
[i
][indexInRow
];
437 const num
= parseInt(character
, 10);
438 // If num is a number, just shift j:
441 // Else: something at position i,j
443 board
[i
][j
++] = this.fen2board(character
);
449 // Some additional variables from FEN (variant dependant)
450 setOtherVariables(fenParsed
) {
451 // Set flags and enpassant:
453 this.setFlags(fenParsed
.flags
);
454 if (this.hasEnpassant
)
455 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
457 this.initReserves(fenParsed
.reserve
);
458 if (this.options
["crazyhouse"])
459 this.initIspawn(fenParsed
.ispawn
);
460 if (this.options
["teleport"]) {
461 this.subTurnTeleport
= 1;
462 this.captured
= null;
464 if (this.options
["dark"]) {
465 // Setup enlightened: squares reachable by player side
466 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
467 this.updateEnlightened();
469 this.subTurn
= 1; //may be unused
470 if (!this.moveStack
) //avoid resetting (unwanted)
474 // ordering as in pieces() p,r,n,b,q,k
475 initReserves(reserveStr
) {
476 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
477 this.reserve
= { w: {}, b: {} };
478 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
479 const L
= pieceName
.length
;
480 for (let i
of ArrayFun
.range(2 * L
)) {
482 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
484 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
488 initIspawn(ispawnStr
) {
489 if (ispawnStr
!= "-")
490 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
498 getPieceWidth(rwidth
) {
499 return (rwidth
/ this.size
.y
);
502 getReserveSquareSize(rwidth
, nbR
) {
503 const sqSize
= this.getPieceWidth(rwidth
);
504 return Math
.min(sqSize
, rwidth
/ nbR
);
507 getReserveNumId(color
, piece
) {
508 return `${this.containerId}|rnum-${color}${piece}`;
511 getNbReservePieces(color
) {
513 Object
.values(this.reserve
[color
]).reduce(
514 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
518 getRankInReserve(c
, p
) {
519 const pieces
= Object
.keys(this.pieces());
520 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
521 let toTest
= pieces
.slice(0, lastIndex
);
522 return toTest
.reduce(
523 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
526 static AddClass_es(piece
, class_es
) {
527 if (!Array
.isArray(class_es
))
528 class_es
= [class_es
];
529 class_es
.forEach(cl
=> {
530 piece
.classList
.add(cl
);
534 static RemoveClass_es(piece
, class_es
) {
535 if (!Array
.isArray(class_es
))
536 class_es
= [class_es
];
537 class_es
.forEach(cl
=> {
538 piece
.classList
.remove(cl
);
542 // Generally light square bottom-right
543 getSquareColorClass(x
, y
) {
544 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
548 // Works for all rectangular boards:
549 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
553 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
560 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
561 window
.onresize
= () => this.re_drawBoardElements();
562 const g_init
= () => {
563 this.re_drawBoardElements();
564 this.initMouseEvents();
566 let container
= document
.getElementById(this.containerId
);
567 if (container
.getBoundingClientRect().width
== 0) {
568 // Element not ready yet
569 let ro
= new ResizeObserver(() => {
570 ro
.unobserve(container
);
573 ro
.observe(container
);
579 re_drawBoardElements() {
580 const board
= this.getSvgChessboard();
581 const oppCol
= C
.GetOppCol(this.playerColor
);
582 const container
= document
.getElementById(this.containerId
);
583 const rc
= container
.getBoundingClientRect();
584 let chessboard
= container
.querySelector(".chessboard");
585 chessboard
.innerHTML
= "";
586 chessboard
.insertAdjacentHTML('beforeend', board
);
587 // Compare window ratio width / height to aspectRatio:
588 const windowRatio
= rc
.width
/ rc
.height
;
589 let cbWidth
, cbHeight
;
590 const vRatio
= this.size
.ratio
|| 1;
591 if (windowRatio
<= vRatio
) {
592 // Limiting dimension is width:
593 cbWidth
= Math
.min(rc
.width
, 767);
594 cbHeight
= cbWidth
/ vRatio
;
597 // Limiting dimension is height:
598 cbHeight
= Math
.min(rc
.height
, 767);
599 cbWidth
= cbHeight
* vRatio
;
601 if (this.hasReserve
) {
602 const sqSize
= cbWidth
/ this.size
.y
;
603 // NOTE: allocate space for reserves (up/down) even if they are empty
604 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
605 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
606 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
607 cbWidth
= cbHeight
* vRatio
;
610 chessboard
.style
.width
= cbWidth
+ "px";
611 chessboard
.style
.height
= cbHeight
+ "px";
612 // Center chessboard:
613 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
614 spaceTop
= (rc
.height
- cbHeight
) / 2;
615 chessboard
.style
.left
= spaceLeft
+ "px";
616 chessboard
.style
.top
= spaceTop
+ "px";
617 // Give sizes instead of recomputing them,
618 // because chessboard might not be drawn yet.
627 // Get SVG board (background, no pieces)
629 const flipped
= (this.playerColor
== 'b');
632 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
633 class="chessboard_SVG">`;
634 for (let i
=0; i
< this.size
.x
; i
++) {
635 for (let j
=0; j
< this.size
.y
; j
++) {
636 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
637 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
638 let classes
= this.getSquareColorClass(ii
, jj
);
639 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
640 classes
+= " in-shadow";
641 // NOTE: x / y reversed because coordinates system is reversed.
645 id="${this.coordsToId({x: ii, y: jj})}"
659 // Refreshing: delete old pieces first
660 for (let i
=0; i
<this.size
.x
; i
++) {
661 for (let j
=0; j
<this.size
.y
; j
++) {
662 if (this.g_pieces
[i
][j
]) {
663 this.g_pieces
[i
][j
].remove();
664 this.g_pieces
[i
][j
] = null;
670 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
672 document
.getElementById(this.containerId
).querySelector(".chessboard");
674 r
= chessboard
.getBoundingClientRect();
675 const pieceWidth
= this.getPieceWidth(r
.width
);
676 for (let i
=0; i
< this.size
.x
; i
++) {
677 for (let j
=0; j
< this.size
.y
; j
++) {
678 if (this.board
[i
][j
] != "") {
679 const color
= this.getColor(i
, j
);
680 const piece
= this.getPiece(i
, j
);
681 this.g_pieces
[i
][j
] = document
.createElement("piece");
682 C
.AddClass_es(this.g_pieces
[i
][j
],
683 this.pieces(color
, i
, j
)[piece
]["class"]);
684 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
685 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
686 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
687 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
688 // Translate coordinates to use chessboard as reference:
689 this.g_pieces
[i
][j
].style
.transform
=
690 `translate(${ip - r.x}px,${jp - r.y}px)`;
691 if (this.enlightened
&& !this.enlightened
[i
][j
])
692 this.g_pieces
[i
][j
].classList
.add("hidden");
693 chessboard
.appendChild(this.g_pieces
[i
][j
]);
698 this.re_drawReserve(['w', 'b'], r
);
701 // NOTE: assume this.reserve != null
702 re_drawReserve(colors
, r
) {
704 // Remove (old) reserve pieces
705 for (let c
of colors
) {
706 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
707 this.r_pieces
[c
][p
].remove();
708 delete this.r_pieces
[c
][p
];
709 const numId
= this.getReserveNumId(c
, p
);
710 document
.getElementById(numId
).remove();
715 this.r_pieces
= { w: {}, b: {} };
716 let container
= document
.getElementById(this.containerId
);
718 r
= container
.querySelector(".chessboard").getBoundingClientRect();
719 for (let c
of colors
) {
720 let reservesDiv
= document
.getElementById("reserves_" + c
);
722 reservesDiv
.remove();
723 if (!this.reserve
[c
])
725 const nbR
= this.getNbReservePieces(c
);
728 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
730 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
731 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
732 let rcontainer
= document
.createElement("div");
733 rcontainer
.id
= "reserves_" + c
;
734 rcontainer
.classList
.add("reserves");
735 rcontainer
.style
.left
= i0
+ "px";
736 rcontainer
.style
.top
= j0
+ "px";
737 // NOTE: +1 fix display bug on Firefox at least
738 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
739 rcontainer
.style
.height
= sqResSize
+ "px";
740 container
.appendChild(rcontainer
);
741 for (let p
of Object
.keys(this.reserve
[c
])) {
742 if (this.reserve
[c
][p
] == 0)
744 let r_cell
= document
.createElement("div");
745 r_cell
.id
= this.coordsToId({x: c
, y: p
});
746 r_cell
.classList
.add("reserve-cell");
747 r_cell
.style
.width
= sqResSize
+ "px";
748 r_cell
.style
.height
= sqResSize
+ "px";
749 rcontainer
.appendChild(r_cell
);
750 let piece
= document
.createElement("piece");
751 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
752 piece
.classList
.add(C
.GetColorClass(c
));
753 piece
.style
.width
= "100%";
754 piece
.style
.height
= "100%";
755 this.r_pieces
[c
][p
] = piece
;
756 r_cell
.appendChild(piece
);
757 let number
= document
.createElement("div");
758 number
.textContent
= this.reserve
[c
][p
];
759 number
.classList
.add("reserve-num");
760 number
.id
= this.getReserveNumId(c
, p
);
761 const fontSize
= "1.3em";
762 number
.style
.fontSize
= fontSize
;
763 number
.style
.fontSize
= fontSize
;
764 r_cell
.appendChild(number
);
770 updateReserve(color
, piece
, count
) {
771 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
772 piece
= "k"; //capturing cannibal king: back to king form
773 const oldCount
= this.reserve
[color
][piece
];
774 this.reserve
[color
][piece
] = count
;
775 // Redrawing is much easier if count==0
776 if ([oldCount
, count
].includes(0))
777 this.re_drawReserve([color
]);
779 const numId
= this.getReserveNumId(color
, piece
);
780 document
.getElementById(numId
).textContent
= count
;
784 // Resize board: no need to destroy/recreate pieces
786 const container
= document
.getElementById(this.containerId
);
787 let chessboard
= container
.querySelector(".chessboard");
788 const rc
= container
.getBoundingClientRect(),
789 r
= chessboard
.getBoundingClientRect();
790 const multFact
= (mode
== "up" ? 1.05 : 0.95);
791 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
793 const vRatio
= this.size
.ratio
|| 1;
794 if (newWidth
> rc
.width
) {
796 newHeight
= newWidth
/ vRatio
;
798 if (newHeight
> rc
.height
) {
799 newHeight
= rc
.height
;
800 newWidth
= newHeight
* vRatio
;
802 chessboard
.style
.width
= newWidth
+ "px";
803 chessboard
.style
.height
= newHeight
+ "px";
804 const newX
= (rc
.width
- newWidth
) / 2;
805 chessboard
.style
.left
= newX
+ "px";
806 const newY
= (rc
.height
- newHeight
) / 2;
807 chessboard
.style
.top
= newY
+ "px";
808 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
809 const pieceWidth
= this.getPieceWidth(newWidth
);
810 // NOTE: next "if" for variants which use squares filling
811 // instead of "physical", moving pieces
813 for (let i
=0; i
< this.size
.x
; i
++) {
814 for (let j
=0; j
< this.size
.y
; j
++) {
815 if (this.g_pieces
[i
][j
]) {
816 // NOTE: could also use CSS transform "scale"
817 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
818 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
819 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
820 // Translate coordinates to use chessboard as reference:
821 this.g_pieces
[i
][j
].style
.transform
=
822 `translate(${ip - newX}px,${jp - newY}px)`;
828 this.rescaleReserve(newR
);
832 for (let c
of ['w','b']) {
833 if (!this.reserve
[c
])
835 const nbR
= this.getNbReservePieces(c
);
838 // Resize container first
839 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
840 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
841 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
842 let rcontainer
= document
.getElementById("reserves_" + c
);
843 rcontainer
.style
.left
= i0
+ "px";
844 rcontainer
.style
.top
= j0
+ "px";
845 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
846 rcontainer
.style
.height
= sqResSize
+ "px";
847 // And then reserve cells:
848 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
849 Object
.keys(this.reserve
[c
]).forEach(p
=> {
850 if (this.reserve
[c
][p
] == 0)
852 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
853 r_cell
.style
.width
= sqResSize
+ "px";
854 r_cell
.style
.height
= sqResSize
+ "px";
859 // Return the absolute pixel coordinates given current position.
860 // Our coordinate system differs from CSS one (x <--> y).
861 // We return here the CSS coordinates (more useful).
862 getPixelPosition(i
, j
, r
) {
864 return [0, 0]; //piece vanishes
866 if (typeof i
== "string") {
867 // Reserves: need to know the rank of piece
868 const nbR
= this.getNbReservePieces(i
);
869 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
870 x
= this.getRankInReserve(i
, j
) * rsqSize
;
871 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
874 const sqSize
= r
.width
/ this.size
.y
;
875 const flipped
= (this.playerColor
== 'b');
876 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
877 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
879 return [r
.x
+ x
, r
.y
+ y
];
883 let container
= document
.getElementById(this.containerId
);
884 let chessboard
= container
.querySelector(".chessboard");
886 const getOffset
= e
=> {
889 return {x: e
.clientX
, y: e
.clientY
};
890 let touchLocation
= null;
891 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
892 // Touch screen, dragstart
893 touchLocation
= e
.targetTouches
[0];
894 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
895 // Touch screen, dragend
896 touchLocation
= e
.changedTouches
[0];
898 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
899 return {x: 0, y: 0}; //shouldn't reach here =)
902 const centerOnCursor
= (piece
, e
) => {
903 const centerShift
= this.getPieceWidth(r
.width
) / 2;
904 const offset
= getOffset(e
);
905 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
906 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
911 startPiece
, curPiece
= null,
913 const mousedown
= (e
) => {
914 // Disable zoom on smartphones:
915 if (e
.touches
&& e
.touches
.length
> 1)
917 r
= chessboard
.getBoundingClientRect();
918 pieceWidth
= this.getPieceWidth(r
.width
);
919 const cd
= this.idToCoords(e
.target
.id
);
921 const move = this.doClick(cd
);
923 this.buildMoveStack(move, r
);
924 else if (!this.clickOnly
) {
925 const [x
, y
] = Object
.values(cd
);
926 if (typeof x
!= "number")
927 startPiece
= this.r_pieces
[x
][y
];
929 startPiece
= this.g_pieces
[x
][y
];
930 if (startPiece
&& this.canIplay(x
, y
)) {
933 curPiece
= startPiece
.cloneNode();
934 curPiece
.style
.transform
= "none";
935 curPiece
.style
.zIndex
= 5;
936 curPiece
.style
.width
= pieceWidth
+ "px";
937 curPiece
.style
.height
= pieceWidth
+ "px";
938 centerOnCursor(curPiece
, e
);
939 container
.appendChild(curPiece
);
940 startPiece
.style
.opacity
= "0.4";
941 chessboard
.style
.cursor
= "none";
947 const mousemove
= (e
) => {
950 centerOnCursor(curPiece
, e
);
952 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
953 // Attempt to prevent horizontal swipe...
957 const mouseup
= (e
) => {
960 const [x
, y
] = [start
.x
, start
.y
];
963 chessboard
.style
.cursor
= "pointer";
964 startPiece
.style
.opacity
= "1";
965 const offset
= getOffset(e
);
966 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
968 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
970 // NOTE: clearly suboptimal, but much easier, and not a big deal.
971 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
972 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
973 const moves
= this.filterValid(potentialMoves
);
974 if (moves
.length
>= 2)
975 this.showChoices(moves
, r
);
976 else if (moves
.length
== 1)
977 this.buildMoveStack(moves
[0], r
);
982 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
984 if ('onmousedown' in window
) {
985 this.mouseListeners
= [
986 {type: "mousedown", listener: mousedown
},
987 {type: "mousemove", listener: mousemove
},
988 {type: "mouseup", listener: mouseup
},
989 {type: "wheel", listener: resize
}
991 this.mouseListeners
.forEach(ml
=> {
992 document
.addEventListener(ml
.type
, ml
.listener
);
995 if ('ontouchstart' in window
) {
996 this.touchListeners
= [
997 {type: "touchstart", listener: mousedown
},
998 {type: "touchmove", listener: mousemove
},
999 {type: "touchend", listener: mouseup
}
1001 this.touchListeners
.forEach(tl
=> {
1002 // https://stackoverflow.com/a/42509310/12660887
1003 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
1006 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1010 if ('onmousedown' in window
) {
1011 this.mouseListeners
.forEach(ml
=> {
1012 document
.removeEventListener(ml
.type
, ml
.listener
);
1015 if ('ontouchstart' in window
) {
1016 this.touchListeners
.forEach(tl
=> {
1017 // https://stackoverflow.com/a/42509310/12660887
1018 document
.removeEventListener(tl
.type
, tl
.listener
);
1023 showChoices(moves
, r
) {
1024 let container
= document
.getElementById(this.containerId
);
1025 let chessboard
= container
.querySelector(".chessboard");
1026 let choices
= document
.createElement("div");
1027 choices
.id
= "choices";
1029 r
= chessboard
.getBoundingClientRect();
1030 choices
.style
.width
= r
.width
+ "px";
1031 choices
.style
.height
= r
.height
+ "px";
1032 choices
.style
.left
= r
.x
+ "px";
1033 choices
.style
.top
= r
.y
+ "px";
1034 chessboard
.style
.opacity
= "0.5";
1035 container
.appendChild(choices
);
1036 const squareWidth
= r
.width
/ this.size
.y
;
1037 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1038 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1039 const color
= moves
[0].appear
[0].c
;
1040 const callback
= (m
) => {
1041 chessboard
.style
.opacity
= "1";
1042 container
.removeChild(choices
);
1043 this.buildMoveStack(m
, r
);
1045 for (let i
=0; i
< moves
.length
; i
++) {
1046 let choice
= document
.createElement("div");
1047 choice
.classList
.add("choice");
1048 choice
.style
.width
= squareWidth
+ "px";
1049 choice
.style
.height
= squareWidth
+ "px";
1050 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1051 choice
.style
.top
= firstUpTop
+ "px";
1052 choice
.style
.backgroundColor
= "lightyellow";
1053 choice
.onclick
= () => callback(moves
[i
]);
1054 const piece
= document
.createElement("piece");
1055 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1056 C
.AddClass_es(piece
,
1057 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1058 piece
.classList
.add(C
.GetColorClass(color
));
1059 piece
.style
.width
= "100%";
1060 piece
.style
.height
= "100%";
1061 choice
.appendChild(piece
);
1062 choices
.appendChild(choice
);
1069 updateEnlightened() {
1070 this.oldEnlightened
= this.enlightened
;
1071 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1072 // Add pieces positions + all squares reachable by moves (includes Zen):
1073 for (let x
=0; x
<this.size
.x
; x
++) {
1074 for (let y
=0; y
<this.size
.y
; y
++) {
1075 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1077 this.enlightened
[x
][y
] = true;
1078 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1079 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1085 this.enlightEnpassant();
1088 // Include square of the en-passant capturing square:
1089 enlightEnpassant() {
1090 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1091 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1092 for (let step
of steps
) {
1093 const x
= this.epSquare
.x
- step
[0],
1094 y
= this.getY(this.epSquare
.y
- step
[1]);
1096 this.onBoard(x
, y
) &&
1097 this.getColor(x
, y
) == this.playerColor
&&
1098 this.getPieceType(x
, y
) == "p"
1100 this.enlightened
[x
][this.epSquare
.y
] = true;
1106 // Apply diff this.enlightened --> oldEnlightened on board
1107 graphUpdateEnlightened() {
1109 document
.getElementById(this.containerId
).querySelector(".chessboard");
1110 const r
= chessboard
.getBoundingClientRect();
1111 const pieceWidth
= this.getPieceWidth(r
.width
);
1112 for (let x
=0; x
<this.size
.x
; x
++) {
1113 for (let y
=0; y
<this.size
.y
; y
++) {
1114 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1115 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1116 elt
.classList
.add("in-shadow");
1117 if (this.g_pieces
[x
][y
])
1118 this.g_pieces
[x
][y
].classList
.add("hidden");
1120 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1121 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1122 elt
.classList
.remove("in-shadow");
1123 if (this.g_pieces
[x
][y
])
1124 this.g_pieces
[x
][y
].classList
.remove("hidden");
1137 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1141 // Color of thing on square (i,j). '' if square is empty
1143 if (typeof i
== "string")
1144 return i
; //reserves
1145 return this.board
[i
][j
].charAt(0);
1148 static GetColorClass(c
) {
1153 return "other-color"; //unidentified color
1156 // Piece on i,j. '' if square is empty
1158 if (typeof j
== "string")
1159 return j
; //reserves
1160 return this.board
[i
][j
].charAt(1);
1163 // Piece type on square (i,j)
1164 getPieceType(x
, y
, p
) {
1166 p
= this.getPiece(x
, y
);
1167 return this.pieces()[p
].moveas
|| p
;
1172 p
= this.getPiece(x
, y
);
1173 if (!this.options
["cannibal"])
1175 return !!C
.CannibalKings
[p
];
1178 // Get opponent color
1179 static GetOppCol(color
) {
1180 return (color
== "w" ? "b" : "w");
1183 // Is (x,y) on the chessboard?
1185 return (x
>= 0 && x
< this.size
.x
&&
1186 y
>= 0 && y
< this.size
.y
);
1189 // Am I allowed to move thing at square x,y ?
1191 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1194 ////////////////////////
1195 // PIECES SPECIFICATIONS
1197 pieces(color
, x
, y
) {
1198 const pawnShift
= (color
== "w" ? -1 : 1);
1199 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1200 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1206 steps: [[pawnShift
, 0]],
1207 range: (initRank
? 2 : 1)
1212 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1220 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1228 [1, 2], [1, -2], [-1, 2], [-1, -2],
1229 [2, 1], [-2, 1], [2, -1], [-2, -1]
1238 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1246 [0, 1], [0, -1], [1, 0], [-1, 0],
1247 [1, 1], [1, -1], [-1, 1], [-1, -1]
1257 [0, 1], [0, -1], [1, 0], [-1, 0],
1258 [1, 1], [1, -1], [-1, 1], [-1, -1]
1265 '!': {"class": "king-pawn", moveas: "p"},
1266 '#': {"class": "king-rook", moveas: "r"},
1267 '$': {"class": "king-knight", moveas: "n"},
1268 '%': {"class": "king-bishop", moveas: "b"},
1269 '*': {"class": "king-queen", moveas: "q"}
1273 // NOTE: using special symbols to not interfere with variants' pieces codes
1274 static get CannibalKings() {
1285 static get CannibalKingCode() {
1296 //////////////////////////
1297 // MOVES GENERATION UTILS
1299 // For Cylinder: get Y coordinate
1301 if (!this.options
["cylinder"])
1303 let res
= y
% this.size
.y
;
1309 getSegments(curSeg
, segStart
, segEnd
) {
1310 if (curSeg
.length
== 0)
1312 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1313 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1317 getStepSpec(color
, x
, y
, piece
) {
1318 return this.pieces(color
, x
, y
)[piece
|| this.getPieceType(x
, y
)];
1321 // Can thing on square1 capture thing on square2?
1322 canTake([x1
, y1
], [x2
, y2
]) {
1323 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1326 canStepOver(i
, j
, p
) {
1327 // In some variants, objects on boards don't stop movement (Chakart)
1328 return this.board
[i
][j
] == "";
1331 canDrop([c
, p
], [i
, j
]) {
1333 this.board
[i
][j
] == "" &&
1334 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1337 (c
== 'w' && i
< this.size
.x
- 1) ||
1344 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1345 isImmobilized([x
, y
]) {
1346 if (!this.options
["madrasi"])
1348 const color
= this.getColor(x
, y
);
1349 const oppCol
= C
.GetOppCol(color
);
1350 const piece
= this.getPieceType(x
, y
);
1351 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1352 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1353 for (let a
of attacks
) {
1354 outerLoop: for (let step
of a
.steps
) {
1355 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1356 let stepCounter
= 1;
1357 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1358 if (a
.range
<= stepCounter
++)
1361 j
= this.getY(j
+ step
[1]);
1364 this.onBoard(i
, j
) &&
1365 this.getColor(i
, j
) == oppCol
&&
1366 this.getPieceType(i
, j
) == piece
1375 // Stop at the first capture found
1376 atLeastOneCapture(color
) {
1377 const oppCol
= C
.GetOppCol(color
);
1378 const allowed
= (sq1
, sq2
) => {
1380 // NOTE: canTake is reversed for Zen.
1381 // Generally ok because of the symmetry. TODO?
1382 this.canTake(sq1
, sq2
) &&
1384 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1387 for (let i
=0; i
<this.size
.x
; i
++) {
1388 for (let j
=0; j
<this.size
.y
; j
++) {
1389 if (this.getColor(i
, j
) == color
) {
1392 !this.options
["zen"] &&
1393 this.findDestSquares(
1398 segments: this.options
["cylinder"]
1406 this.options
["zen"] &&
1407 this.findCapturesOn(
1411 segments: this.options
["cylinder"]
1426 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1427 const epsilon
= 1e-7; //arbitrary small value
1429 if (this.options
["cylinder"])
1430 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1431 for (let sh
of shifts
) {
1432 const rx
= (x2
- x1
) / step
[0],
1433 ry
= (y2
+ sh
- y1
) / step
[1];
1435 // Zero step but non-zero interval => impossible
1436 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1437 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1438 // Negative number of step (impossible)
1439 (rx
< 0 || ry
< 0) ||
1440 // Not the same number of steps in both directions:
1441 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1445 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1446 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1448 distance
= Math
.round(distance
); //in case of (numerical...)
1449 if (!range
|| range
>= distance
)
1455 ////////////////////
1458 getDropMovesFrom([c
, p
]) {
1459 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1460 // (but not necessarily otherwise: atLeastOneMove() etc)
1461 if (this.reserve
[c
][p
] == 0)
1464 for (let i
=0; i
<this.size
.x
; i
++) {
1465 for (let j
=0; j
<this.size
.y
; j
++) {
1466 if (this.canDrop([c
, p
], [i
, j
])) {
1468 start: {x: c
, y: p
},
1470 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1473 if (this.board
[i
][j
] != "") {
1474 mv
.vanish
.push(new PiPo({
1477 c: this.getColor(i
, j
),
1478 p: this.getPiece(i
, j
)
1488 // All possible moves from selected square
1489 getPotentialMovesFrom([x
, y
], color
) {
1490 if (this.subTurnTeleport
== 2)
1492 if (typeof x
== "string")
1493 return this.getDropMovesFrom([x
, y
]);
1494 if (this.isImmobilized([x
, y
]))
1496 const piece
= this.getPieceType(x
, y
);
1497 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1498 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1499 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1501 piece
== "k" && this.hasCastle
&&
1502 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1504 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1506 return this.postProcessPotentialMoves(moves
);
1509 postProcessPotentialMoves(moves
) {
1510 if (moves
.length
== 0)
1512 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1513 const oppCol
= C
.GetOppCol(color
);
1515 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1516 moves
= this.capturePostProcess(moves
, oppCol
);
1518 if (this.options
["atomic"])
1519 this.atomicPostProcess(moves
, color
, oppCol
);
1523 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1525 this.pawnPostProcess(moves
, color
, oppCol
);
1528 if (this.options
["cannibal"] && this.options
["rifle"])
1529 // In this case a rifle-capture from last rank may promote a pawn
1530 this.riflePromotePostProcess(moves
, color
);
1535 capturePostProcess(moves
, oppCol
) {
1536 // Filter out non-capturing moves (not using m.vanish because of
1537 // self captures of Recycle and Teleport).
1538 return moves
.filter(m
=> {
1540 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1541 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1546 atomicPostProcess(moves
, color
, oppCol
) {
1547 moves
.forEach(m
=> {
1549 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1550 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1563 let mNext
= new Move({
1569 for (let step
of steps
) {
1570 let x
= m
.end
.x
+ step
[0];
1571 let y
= this.getY(m
.end
.y
+ step
[1]);
1573 this.onBoard(x
, y
) &&
1574 this.board
[x
][y
] != "" &&
1575 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1576 this.getPieceType(x
, y
) != "p"
1580 p: this.getPiece(x
, y
),
1581 c: this.getColor(x
, y
),
1588 if (!this.options
["rifle"]) {
1589 // The moving piece also vanish
1590 mNext
.vanish
.unshift(
1595 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1604 pawnPostProcess(moves
, color
, oppCol
) {
1606 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1607 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1608 moves
.forEach(m
=> {
1609 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1610 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1611 const promotionOk
= (
1613 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1616 return; //nothing to do
1617 if (this.options
["pawnfall"]) {
1621 let finalPieces
= ["p"];
1623 this.options
["cannibal"] &&
1624 this.board
[x2
][y2
] != "" &&
1625 this.getColor(x2
, y2
) == oppCol
1627 finalPieces
= [this.getPieceType(x2
, y2
)];
1630 finalPieces
= this.pawnPromotions
;
1631 m
.appear
[0].p
= finalPieces
[0];
1632 if (initPiece
== "!") //cannibal king-pawn
1633 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1634 for (let i
=1; i
<finalPieces
.length
; i
++) {
1635 const piece
= finalPieces
[i
];
1638 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1640 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1641 moreMoves
.push(newMove
);
1644 Array
.prototype.push
.apply(moves
, moreMoves
);
1647 riflePromotePostProcess(moves
, color
) {
1648 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1650 moves
.forEach(m
=> {
1652 m
.start
.x
== lastRank
&&
1653 m
.appear
.length
>= 1 &&
1654 m
.appear
[0].p
== "p" &&
1655 m
.appear
[0].x
== m
.start
.x
&&
1656 m
.appear
[0].y
== m
.start
.y
1658 m
.appear
[0].p
= this.pawnPromotions
[0];
1659 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1660 let newMv
= JSON
.parse(JSON
.stringify(m
));
1661 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1662 newMoves
.push(newMv
);
1666 Array
.prototype.push
.apply(moves
, newMoves
);
1669 // Generic method to find possible moves of "sliding or jumping" pieces
1670 getPotentialMovesOf(piece
, [x
, y
]) {
1671 const color
= this.getColor(x
, y
);
1672 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1674 if (stepSpec
.attack
) {
1675 squares
= this.findDestSquares(
1679 segments: this.options
["cylinder"],
1682 ([i1
, j1
], [i2
, j2
]) => {
1684 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1685 this.canTake([i1
, j1
], [i2
, j2
])
1690 const noSpecials
= this.findDestSquares(
1693 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1694 segments: this.options
["cylinder"],
1698 Array
.prototype.push
.apply(squares
, noSpecials
);
1699 if (this.options
["zen"]) {
1700 let zenCaptures
= this.findCapturesOn(
1702 {}, //byCol: default is ok
1703 ([i1
, j1
], [i2
, j2
]) =>
1704 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1706 // Technical step: segments (if any) are reversed
1707 if (this.options
["cylinder"]) {
1708 zenCaptures
.forEach(z
=> {
1709 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1712 Array
.prototype.push
.apply(squares
, zenCaptures
);
1715 this.options
["recycle"] ||
1716 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1718 const selfCaptures
= this.findDestSquares(
1722 segments: this.options
["cylinder"],
1725 ([i1
, j1
], [i2
, j2
]) =>
1726 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1728 Array
.prototype.push
.apply(squares
, selfCaptures
);
1730 return squares
.map(s
=> {
1731 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1732 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1733 mv
.segments
= s
.segments
;
1738 findDestSquares([x
, y
], o
, allowed
) {
1740 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1741 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1743 // Next 3 for Cylinder mode: (unused if !o.segments)
1747 const addSquare
= ([i
, j
]) => {
1748 let elt
= {sq: [i
, j
]};
1750 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1753 const exploreSteps
= (stepArray
) => {
1754 for (let s
of stepArray
) {
1755 outerLoop: for (let step
of s
.steps
) {
1760 let [i
, j
] = [x
, y
];
1761 let stepCounter
= 0;
1763 this.onBoard(i
, j
) &&
1764 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1766 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1767 explored
[i
+ "." + j
] = true;
1770 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1772 if (o
.one
&& !o
.attackOnly
)
1775 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1776 if (o
.captureTarget
)
1780 if (s
.range
<= stepCounter
++)
1782 const oldIJ
= [i
, j
];
1784 j
= this.getY(j
+ step
[1]);
1785 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1786 // Boundary between segments (cylinder mode)
1787 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1791 if (!this.onBoard(i
, j
))
1793 const pieceIJ
= this.getPieceType(i
, j
);
1794 if (!explored
[i
+ "." + j
]) {
1795 explored
[i
+ "." + j
] = true;
1796 if (allowed([x
, y
], [i
, j
])) {
1797 if (o
.one
&& !o
.moveOnly
)
1800 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1803 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1811 return undefined; //default, but let's explicit it
1813 if (o
.captureTarget
)
1814 return exploreSteps(o
.captureSteps
)
1817 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1819 if (!o
.attackOnly
|| !stepSpec
.attack
)
1820 outOne
= exploreSteps(stepSpec
.moves
);
1821 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1822 o
.attackOnly
= true; //ok because o is always a temporary object
1823 outOne
= exploreSteps(stepSpec
.attack
);
1825 return (o
.one
? outOne : res
);
1829 // Search for enemy (or not) pieces attacking [x, y]
1830 findCapturesOn([x
, y
], o
, allowed
) {
1832 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1834 for (let i
=0; i
<this.size
.x
; i
++) {
1835 for (let j
=0; j
<this.size
.y
; j
++) {
1836 const colIJ
= this.getColor(i
, j
);
1838 this.board
[i
][j
] != "" &&
1839 o
.byCol
.includes(colIJ
) &&
1840 !this.isImmobilized([i
, j
])
1842 const apparentPiece
= this.getPiece(i
, j
);
1843 // Quick check: does this potential attacker target x,y ?
1844 if (this.canStepOver(x
, y
, apparentPiece
))
1846 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1847 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1848 for (let a
of attacks
) {
1849 for (let s
of a
.steps
) {
1850 // Quick check: if step isn't compatible, don't even try
1851 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1853 // Finally verify that nothing stand in-between
1854 const out
= this.findDestSquares(
1857 captureTarget: [x
, y
],
1858 captureSteps: [{steps: [s
], range: a
.range
}],
1859 segments: o
.segments
,
1861 one: false //one and captureTarget are mutually exclusive
1875 return (o
.one
? false : res
);
1878 // Build a regular move from its initial and destination squares.
1879 // tr: transformation
1880 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1881 const initColor
= this.getColor(sx
, sy
);
1882 const initPiece
= this.getPiece(sx
, sy
);
1883 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1887 start: {x: sx
, y: sy
},
1891 !this.options
["rifle"] ||
1892 this.board
[ex
][ey
] == "" ||
1893 destColor
== initColor
//Recycle, Teleport
1899 c: !!tr
? tr
.c : initColor
,
1900 p: !!tr
? tr
.p : initPiece
1912 if (this.board
[ex
][ey
] != "") {
1917 c: this.getColor(ex
, ey
),
1918 p: this.getPiece(ex
, ey
)
1921 if (this.options
["cannibal"] && destColor
!= initColor
) {
1922 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1923 let trPiece
= mv
.vanish
[lastIdx
].p
;
1924 if (this.isKing(sx
, sy
))
1925 trPiece
= C
.CannibalKingCode
[trPiece
];
1926 if (mv
.appear
.length
>= 1)
1927 mv
.appear
[0].p
= trPiece
;
1928 else if (this.options
["rifle"]) {
1951 // En-passant square, if any
1952 getEpSquare(moveOrSquare
) {
1953 if (typeof moveOrSquare
=== "string") {
1954 const square
= moveOrSquare
;
1957 return C
.SquareToCoords(square
);
1959 // Argument is a move:
1960 const move = moveOrSquare
;
1961 const s
= move.start
,
1965 Math
.abs(s
.x
- e
.x
) == 2 &&
1966 // Next conditions for variants like Atomic or Rifle, Recycle...
1968 move.appear
.length
> 0 &&
1969 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1973 move.vanish
.length
> 0 &&
1974 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1982 return undefined; //default
1985 // Special case of en-passant captures: treated separately
1986 getEnpassantCaptures([x
, y
]) {
1987 const color
= this.getColor(x
, y
);
1988 const shiftX
= (color
== 'w' ? -1 : 1);
1989 const oppCol
= C
.GetOppCol(color
);
1992 this.epSquare
.x
== x
+ shiftX
&&
1993 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1994 // Doublemove (and Progressive?) guards:
1995 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
1996 this.getColor(x
, this.epSquare
.y
) == oppCol
1998 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1999 this.board
[epx
][epy
] = oppCol
+ 'p';
2000 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2001 this.board
[epx
][epy
] = "";
2002 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2003 enpassantMove
.vanish
[lastIdx
].x
= x
;
2004 return [enpassantMove
];
2009 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2010 const c
= this.getColor(x
, y
);
2013 const oppCol
= C
.GetOppCol(c
);
2017 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2018 const castlingKing
= this.getPiece(x
, y
);
2019 castlingCheck: for (
2022 castleSide
++ //large, then small
2024 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2026 // If this code is reached, rook and king are on initial position
2028 // NOTE: in some variants this is not a rook
2029 const rookPos
= this.castleFlags
[c
][castleSide
];
2030 const castlingPiece
= this.getPiece(x
, rookPos
);
2032 this.board
[x
][rookPos
] == "" ||
2033 this.getColor(x
, rookPos
) != c
||
2034 (castleWith
&& !castleWith
.includes(castlingPiece
))
2036 // Rook is not here, or changed color (see Benedict)
2039 // Nothing on the path of the king ? (and no checks)
2040 const finDist
= finalSquares
[castleSide
][0] - y
;
2041 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2045 // NOTE: next weird test because underCheck() verification
2046 // will be executed in filterValid() later.
2048 i
!= finalSquares
[castleSide
][0] &&
2049 this.underCheck([x
, i
], oppCol
)
2053 this.board
[x
][i
] != "" &&
2054 // NOTE: next check is enough, because of chessboard constraints
2055 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2058 continue castlingCheck
;
2061 } while (i
!= finalSquares
[castleSide
][0]);
2062 // Nothing on the path to the rook?
2063 step
= (castleSide
== 0 ? -1 : 1);
2064 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2065 if (this.board
[x
][i
] != "")
2066 continue castlingCheck
;
2069 // Nothing on final squares, except maybe king and castling rook?
2070 for (i
= 0; i
< 2; i
++) {
2072 finalSquares
[castleSide
][i
] != rookPos
&&
2073 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2075 finalSquares
[castleSide
][i
] != y
||
2076 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2079 continue castlingCheck
;
2083 // If this code is reached, castle is potentially valid
2089 y: finalSquares
[castleSide
][0],
2095 y: finalSquares
[castleSide
][1],
2101 // King might be initially disguised (Titan...)
2102 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2103 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2106 Math
.abs(y
- rookPos
) <= 2
2107 ? {x: x
, y: rookPos
}
2108 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2116 ////////////////////
2119 // Is piece (or square) at given position attacked by "oppCol" ?
2120 underAttack([x
, y
], oppCol
) {
2121 // An empty square is considered as king,
2122 // since it's used only in getCastleMoves (TODO?)
2123 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2126 (!this.options
["zen"] || king
) &&
2127 this.findCapturesOn(
2131 segments: this.options
["cylinder"],
2138 (!!this.options
["zen"] && !king
) &&
2139 this.findDestSquares(
2143 segments: this.options
["cylinder"],
2146 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2152 underCheck([x
, y
], oppCol
) {
2153 if (this.options
["taking"] || this.options
["dark"])
2155 return this.underAttack([x
, y
], oppCol
);
2158 // Stop at first king found (TODO: multi-kings)
2159 searchKingPos(color
) {
2160 for (let i
=0; i
< this.size
.x
; i
++) {
2161 for (let j
=0; j
< this.size
.y
; j
++) {
2162 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2166 return [-1, -1]; //king not found
2169 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2170 filterValid(moves
, color
) {
2173 const oppCol
= C
.GetOppCol(color
);
2174 const kingPos
= this.searchKingPos(color
);
2175 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2176 return moves
.filter(m
=> {
2177 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2178 if (!filtered
[key
]) {
2179 this.playOnBoard(m
);
2180 let square
= kingPos
,
2181 res
= true; //a priori valid
2182 if (m
.vanish
.some(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
)) {
2183 // Search king in appear array:
2185 m
.appear
.findIndex(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2186 if (newKingIdx
>= 0)
2187 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
2191 res
&&= !this.underCheck(square
, oppCol
);
2192 this.undoOnBoard(m
);
2193 filtered
[key
] = res
;
2196 return filtered
[key
];
2203 // Apply a move on board
2205 for (let psq
of move.vanish
)
2206 this.board
[psq
.x
][psq
.y
] = "";
2207 for (let psq
of move.appear
)
2208 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2210 // Un-apply the played move
2212 for (let psq
of move.appear
)
2213 this.board
[psq
.x
][psq
.y
] = "";
2214 for (let psq
of move.vanish
)
2215 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2218 updateCastleFlags(move) {
2219 // Update castling flags if start or arrive from/at rook/king locations
2220 move.appear
.concat(move.vanish
).forEach(psq
=> {
2221 if (this.isKing(0, 0, psq
.p
))
2222 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2223 // NOTE: not "else if" because king can capture enemy rook...
2227 else if (psq
.x
== this.size
.x
- 1)
2230 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2232 this.castleFlags
[c
][fidx
] = this.size
.y
;
2240 // If flags already off, no need to re-check:
2241 Object
.values(this.castleFlags
).some(cvals
=>
2242 cvals
.some(val
=> val
< this.size
.y
))
2244 this.updateCastleFlags(move);
2246 if (this.options
["crazyhouse"]) {
2247 move.vanish
.forEach(v
=> {
2248 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2249 if (this.ispawn
[square
])
2250 delete this.ispawn
[square
];
2252 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2253 // Assumption: something is moving
2254 const initSquare
= C
.CoordsToSquare(move.start
);
2255 const destSquare
= C
.CoordsToSquare(move.end
);
2257 this.ispawn
[initSquare
] ||
2258 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2260 this.ispawn
[destSquare
] = true;
2263 this.ispawn
[destSquare
] &&
2264 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2266 move.vanish
[1].p
= 'p';
2267 delete this.ispawn
[destSquare
];
2271 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2274 // Warning; atomic pawn removal isn't a capture
2275 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2277 const color
= this.turn
;
2278 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2279 // Something appears = dropped on board (some exceptions, Chakart...)
2280 if (move.appear
[i
].c
== color
) {
2281 const piece
= move.appear
[i
].p
;
2282 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2285 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2286 // Something vanish: add to reserve except if recycle & opponent
2288 this.options
["crazyhouse"] ||
2289 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2291 const piece
= move.vanish
[i
].p
;
2292 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2300 if (this.hasEnpassant
)
2301 this.epSquare
= this.getEpSquare(move);
2302 this.playOnBoard(move);
2303 this.postPlay(move);
2307 const color
= this.turn
;
2308 if (this.options
["dark"])
2309 this.updateEnlightened();
2310 if (this.options
["teleport"]) {
2312 this.subTurnTeleport
== 1 &&
2313 move.vanish
.length
> move.appear
.length
&&
2314 move.vanish
[1].c
== color
2316 const v
= move.vanish
[move.vanish
.length
- 1];
2317 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2318 this.subTurnTeleport
= 2;
2321 this.subTurnTeleport
= 1;
2322 this.captured
= null;
2324 if (this.isLastMove(move)) {
2325 this.turn
= C
.GetOppCol(color
);
2329 else if (!move.next
)
2336 const color
= this.turn
;
2337 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2338 if (oppKingPos
[0] < 0 || this.underCheck(oppKingPos
, color
))
2342 !this.options
["balance"] ||
2343 ![1, 2].includes(this.movesCount
) ||
2348 !this.options
["doublemove"] ||
2349 this.movesCount
== 0 ||
2354 !this.options
["progressive"] ||
2355 this.subTurn
== this.movesCount
+ 1
2360 // "Stop at the first move found"
2361 atLeastOneMove(color
) {
2362 for (let i
= 0; i
< this.size
.x
; i
++) {
2363 for (let j
= 0; j
< this.size
.y
; j
++) {
2364 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2365 // NOTE: in fact searching for all potential moves from i,j.
2366 // I don't believe this is an issue, for now at least.
2367 const moves
= this.getPotentialMovesFrom([i
, j
]);
2368 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2373 if (this.hasReserve
&& this.reserve
[color
]) {
2374 for (let p
of Object
.keys(this.reserve
[color
])) {
2375 const moves
= this.getDropMovesFrom([color
, p
]);
2376 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2383 // What is the score ? (Interesting if game is over)
2384 getCurrentScore(move) {
2385 const color
= this.turn
;
2386 const oppCol
= C
.GetOppCol(color
);
2387 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2388 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2390 if (kingPos
[0][0] < 0)
2391 return (color
== "w" ? "0-1" : "1-0");
2392 if (kingPos
[1][0] < 0)
2393 return (color
== "w" ? "1-0" : "0-1");
2394 if (this.atLeastOneMove(color
))
2396 // No valid move: stalemate or checkmate?
2397 if (!this.underCheck(kingPos
[0], oppCol
))
2400 return (color
== "w" ? "0-1" : "1-0");
2403 playVisual(move, r
) {
2404 move.vanish
.forEach(v
=> {
2405 this.g_pieces
[v
.x
][v
.y
].remove();
2406 this.g_pieces
[v
.x
][v
.y
] = null;
2409 document
.getElementById(this.containerId
).querySelector(".chessboard");
2411 r
= chessboard
.getBoundingClientRect();
2412 const pieceWidth
= this.getPieceWidth(r
.width
);
2413 move.appear
.forEach(a
=> {
2414 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2415 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2416 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2417 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2418 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2419 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2420 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2421 // Translate coordinates to use chessboard as reference:
2422 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2423 `translate(${ip - r.x}px,${jp - r.y}px)`;
2424 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2425 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2426 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2428 if (this.options
["dark"])
2429 this.graphUpdateEnlightened();
2432 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2433 buildMoveStack(move, r
) {
2434 this.moveStack
.push(move);
2435 this.computeNextMove(move);
2437 const newTurn
= this.turn
;
2438 if (this.moveStack
.length
== 1)
2439 this.playVisual(move, r
);
2443 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2445 this.buildMoveStack(move.next
, r
);
2448 if (this.moveStack
.length
== 1) {
2449 // Usual case (one normal move)
2450 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2454 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2455 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2456 this.playReceivedMove(this.moveStack
.slice(1), () => {
2457 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2464 // Implemented in variants using (automatic) moveStack
2465 computeNextMove(move) {}
2467 animateMoving(start
, end
, drag
, segments
, cb
) {
2468 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2469 // NOTE: cloning often not required, but light enough, and simpler
2470 let movingPiece
= initPiece
.cloneNode();
2471 initPiece
.style
.opacity
= "0";
2473 document
.getElementById(this.containerId
)
2474 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2475 if (typeof start
.x
== "string") {
2476 // Need to bound width/height (was 100% for reserve pieces)
2477 const pieceWidth
= this.getPieceWidth(r
.width
);
2478 movingPiece
.style
.width
= pieceWidth
+ "px";
2479 movingPiece
.style
.height
= pieceWidth
+ "px";
2481 const maxDist
= this.getMaxDistance(r
);
2482 const apparentColor
= this.getColor(start
.x
, start
.y
);
2483 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2485 const startCode
= this.getPiece(start
.x
, start
.y
);
2486 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2487 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2488 if (apparentColor
!= drag
.c
) {
2489 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2490 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2493 container
.appendChild(movingPiece
);
2494 const animateSegment
= (index
, cb
) => {
2495 // NOTE: move.drag could be generalized per-segment (usage?)
2496 const [i1
, j1
] = segments
[index
][0];
2497 const [i2
, j2
] = segments
[index
][1];
2498 const dep
= this.getPixelPosition(i1
, j1
, r
);
2499 const arr
= this.getPixelPosition(i2
, j2
, r
);
2500 movingPiece
.style
.transitionDuration
= "0s";
2501 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2503 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2504 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2505 // TODO: unclear why we need this new delay below:
2507 movingPiece
.style
.transitionDuration
= duration
+ "s";
2508 // movingPiece is child of container: no need to adjust coordinates
2509 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2510 setTimeout(cb
, duration
* 1000);
2514 const animateSegmentCallback
= () => {
2515 if (index
< segments
.length
)
2516 animateSegment(index
++, animateSegmentCallback
);
2518 movingPiece
.remove();
2519 initPiece
.style
.opacity
= "1";
2523 animateSegmentCallback();
2526 // Input array of objects with at least fields x,y (e.g. PiPo)
2527 animateFading(arr
, cb
) {
2528 const animLength
= 350; //TODO: 350ms? More? Less?
2530 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2531 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2532 fadingPiece
.style
.opacity
= "0";
2534 setTimeout(cb
, animLength
);
2537 animate(move, callback
) {
2538 if (this.noAnimate
|| move.noAnimate
) {
2542 let segments
= move.segments
;
2544 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2545 let targetObj
= new TargetObj(callback
);
2546 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2548 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2549 () => targetObj
.increment());
2551 if (move.vanish
.length
> move.appear
.length
) {
2552 const arr
= move.vanish
.slice(move.appear
.length
)
2553 // Ignore disappearing pieces hidden by some appearing ones:
2554 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2555 if (arr
.length
> 0) {
2557 this.animateFading(arr
, () => targetObj
.increment());
2561 this.customAnimate(move, segments
, () => targetObj
.increment());
2562 if (targetObj
.target
== 0)
2566 // Potential other animations (e.g. for Suction variant)
2567 customAnimate(move, segments
, cb
) {
2568 return 0; //nb of targets
2571 playReceivedMove(moves
, callback
) {
2572 const launchAnimation
= () => {
2573 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2574 const animateRec
= i
=> {
2575 this.animate(moves
[i
], () => {
2576 this.play(moves
[i
]);
2577 this.playVisual(moves
[i
], r
);
2578 if (i
< moves
.length
- 1)
2579 setTimeout(() => animateRec(i
+1), 300);
2586 // Delay if user wasn't focused:
2587 const checkDisplayThenAnimate
= (delay
) => {
2588 if (container
.style
.display
== "none") {
2589 alert("New move! Let's go back to game...");
2590 document
.getElementById("gameInfos").style
.display
= "none";
2591 container
.style
.display
= "block";
2592 setTimeout(launchAnimation
, 700);
2595 setTimeout(launchAnimation
, delay
|| 0);
2597 let container
= document
.getElementById(this.containerId
);
2598 if (document
.hidden
) {
2599 document
.onvisibilitychange
= () => {
2600 document
.onvisibilitychange
= undefined;
2601 checkDisplayThenAnimate(700);
2605 checkDisplayThenAnimate();