ad30c0a04cd97d376d252adb1a6f0428b0fd3a34
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.isDiagram
= o
.diagram
;
419 this.graphicalInit();
422 re_initFromFen(fen
, oldBoard
) {
423 const fenParsed
= this.parseFen(fen
);
424 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
425 this.turn
= fenParsed
.turn
;
426 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
427 this.setOtherVariables(fenParsed
);
430 // Turn position fen into double array ["wb","wp","bk",...]
432 const rows
= position
.split("/");
433 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
434 for (let i
= 0; i
< rows
.length
; i
++) {
436 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
437 const character
= rows
[i
][indexInRow
];
438 const num
= parseInt(character
, 10);
439 // If num is a number, just shift j:
442 // Else: something at position i,j
444 board
[i
][j
++] = this.fen2board(character
);
450 // Some additional variables from FEN (variant dependant)
451 setOtherVariables(fenParsed
) {
452 // Set flags and enpassant:
454 this.setFlags(fenParsed
.flags
);
455 if (this.hasEnpassant
)
456 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
458 this.initReserves(fenParsed
.reserve
);
459 if (this.options
["crazyhouse"])
460 this.initIspawn(fenParsed
.ispawn
);
461 if (this.options
["teleport"]) {
462 this.subTurnTeleport
= 1;
463 this.captured
= null;
465 if (this.options
["dark"]) {
466 // Setup enlightened: squares reachable by player side
467 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
468 this.updateEnlightened();
470 this.subTurn
= 1; //may be unused
471 if (!this.moveStack
) //avoid resetting (unwanted)
475 // ordering as in pieces() p,r,n,b,q,k
476 initReserves(reserveStr
) {
477 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
478 this.reserve
= { w: {}, b: {} };
479 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
480 const L
= pieceName
.length
;
481 for (let i
of ArrayFun
.range(2 * L
)) {
483 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
485 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
489 initIspawn(ispawnStr
) {
490 if (ispawnStr
!= "-")
491 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
499 getPieceWidth(rwidth
) {
500 return (rwidth
/ this.size
.y
);
503 getReserveSquareSize(rwidth
, nbR
) {
504 const sqSize
= this.getPieceWidth(rwidth
);
505 return Math
.min(sqSize
, rwidth
/ nbR
);
508 getReserveNumId(color
, piece
) {
509 return `${this.containerId}|rnum-${color}${piece}`;
512 getNbReservePieces(color
) {
514 Object
.values(this.reserve
[color
]).reduce(
515 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
519 getRankInReserve(c
, p
) {
520 const pieces
= Object
.keys(this.pieces());
521 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
522 let toTest
= pieces
.slice(0, lastIndex
);
523 return toTest
.reduce(
524 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
527 static AddClass_es(piece
, class_es
) {
528 if (!Array
.isArray(class_es
))
529 class_es
= [class_es
];
530 class_es
.forEach(cl
=> {
531 piece
.classList
.add(cl
);
535 static RemoveClass_es(piece
, class_es
) {
536 if (!Array
.isArray(class_es
))
537 class_es
= [class_es
];
538 class_es
.forEach(cl
=> {
539 piece
.classList
.remove(cl
);
543 // Generally light square bottom-right
544 getSquareColorClass(x
, y
) {
545 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
549 // Works for all rectangular boards:
550 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
554 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
561 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
562 window
.onresize
= () => this.re_drawBoardElements();
563 const g_init
= () => {
564 this.re_drawBoardElements();
566 this.initMouseEvents();
568 let container
= document
.getElementById(this.containerId
);
569 if (container
.getBoundingClientRect().width
== 0) {
570 // Element not ready yet
571 let ro
= new ResizeObserver(() => {
572 ro
.unobserve(container
);
575 ro
.observe(container
);
581 re_drawBoardElements() {
582 const board
= this.getSvgChessboard();
583 const oppCol
= C
.GetOppCol(this.playerColor
);
584 const container
= document
.getElementById(this.containerId
);
585 const rc
= container
.getBoundingClientRect();
586 let chessboard
= container
.querySelector(".chessboard");
587 chessboard
.innerHTML
= "";
588 chessboard
.insertAdjacentHTML('beforeend', board
);
589 // Compare window ratio width / height to aspectRatio:
590 const windowRatio
= rc
.width
/ rc
.height
;
591 let cbWidth
, cbHeight
;
592 const vRatio
= this.size
.ratio
|| 1;
593 if (windowRatio
<= vRatio
) {
594 // Limiting dimension is width:
595 cbWidth
= Math
.min(rc
.width
, 767);
596 cbHeight
= cbWidth
/ vRatio
;
599 // Limiting dimension is height:
600 cbHeight
= Math
.min(rc
.height
, 767);
601 cbWidth
= cbHeight
* vRatio
;
603 if (this.hasReserve
) {
604 const sqSize
= cbWidth
/ this.size
.y
;
605 // NOTE: allocate space for reserves (up/down) even if they are empty
606 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
607 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
608 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
609 cbWidth
= cbHeight
* vRatio
;
612 chessboard
.style
.width
= cbWidth
+ "px";
613 chessboard
.style
.height
= cbHeight
+ "px";
614 // Center chessboard:
615 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
616 spaceTop
= (rc
.height
- cbHeight
) / 2;
617 chessboard
.style
.left
= spaceLeft
+ "px";
618 chessboard
.style
.top
= spaceTop
+ "px";
619 // Give sizes instead of recomputing them,
620 // because chessboard might not be drawn yet.
629 // Get SVG board (background, no pieces)
631 const flipped
= (this.playerColor
== 'b');
634 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
635 class="chessboard_SVG">`;
636 for (let i
=0; i
< this.size
.x
; i
++) {
637 for (let j
=0; j
< this.size
.y
; j
++) {
638 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
639 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
640 let classes
= this.getSquareColorClass(ii
, jj
);
641 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
642 classes
+= " in-shadow";
643 // NOTE: x / y reversed because coordinates system is reversed.
647 id="${this.coordsToId({x: ii, y: jj})}"
660 // TODO: d_pieces : only markers (for diagrams) / also in rescale()
662 // Refreshing: delete old pieces first
663 for (let i
=0; i
<this.size
.x
; i
++) {
664 for (let j
=0; j
<this.size
.y
; j
++) {
665 if (this.g_pieces
[i
][j
]) {
666 this.g_pieces
[i
][j
].remove();
667 this.g_pieces
[i
][j
] = null;
673 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
675 document
.getElementById(this.containerId
).querySelector(".chessboard");
677 r
= chessboard
.getBoundingClientRect();
678 const pieceWidth
= this.getPieceWidth(r
.width
);
679 for (let i
=0; i
< this.size
.x
; i
++) {
680 for (let j
=0; j
< this.size
.y
; j
++) {
681 if (this.board
[i
][j
] != "") {
682 const color
= this.getColor(i
, j
);
683 const piece
= this.getPiece(i
, j
);
684 this.g_pieces
[i
][j
] = document
.createElement("piece");
685 C
.AddClass_es(this.g_pieces
[i
][j
],
686 this.pieces(color
, i
, j
)[piece
]["class"]);
687 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
688 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
689 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
690 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
691 // Translate coordinates to use chessboard as reference:
692 this.g_pieces
[i
][j
].style
.transform
=
693 `translate(${ip - r.x}px,${jp - r.y}px)`;
694 if (this.enlightened
&& !this.enlightened
[i
][j
])
695 this.g_pieces
[i
][j
].classList
.add("hidden");
696 chessboard
.appendChild(this.g_pieces
[i
][j
]);
701 this.re_drawReserve(['w', 'b'], r
);
704 // NOTE: assume this.reserve != null
705 re_drawReserve(colors
, r
) {
707 // Remove (old) reserve pieces
708 for (let c
of colors
) {
709 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
710 this.r_pieces
[c
][p
].remove();
711 delete this.r_pieces
[c
][p
];
712 const numId
= this.getReserveNumId(c
, p
);
713 document
.getElementById(numId
).remove();
718 this.r_pieces
= { w: {}, b: {} };
719 let container
= document
.getElementById(this.containerId
);
721 r
= container
.querySelector(".chessboard").getBoundingClientRect();
722 for (let c
of colors
) {
723 let reservesDiv
= document
.getElementById("reserves_" + c
);
725 reservesDiv
.remove();
726 if (!this.reserve
[c
])
728 const nbR
= this.getNbReservePieces(c
);
731 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
733 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
734 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
735 let rcontainer
= document
.createElement("div");
736 rcontainer
.id
= "reserves_" + c
;
737 rcontainer
.classList
.add("reserves");
738 rcontainer
.style
.left
= i0
+ "px";
739 rcontainer
.style
.top
= j0
+ "px";
740 // NOTE: +1 fix display bug on Firefox at least
741 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
742 rcontainer
.style
.height
= sqResSize
+ "px";
743 container
.appendChild(rcontainer
);
744 for (let p
of Object
.keys(this.reserve
[c
])) {
745 if (this.reserve
[c
][p
] == 0)
747 let r_cell
= document
.createElement("div");
748 r_cell
.id
= this.coordsToId({x: c
, y: p
});
749 r_cell
.classList
.add("reserve-cell");
750 r_cell
.style
.width
= sqResSize
+ "px";
751 r_cell
.style
.height
= sqResSize
+ "px";
752 rcontainer
.appendChild(r_cell
);
753 let piece
= document
.createElement("piece");
754 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
755 piece
.classList
.add(C
.GetColorClass(c
));
756 piece
.style
.width
= "100%";
757 piece
.style
.height
= "100%";
758 this.r_pieces
[c
][p
] = piece
;
759 r_cell
.appendChild(piece
);
760 let number
= document
.createElement("div");
761 number
.textContent
= this.reserve
[c
][p
];
762 number
.classList
.add("reserve-num");
763 number
.id
= this.getReserveNumId(c
, p
);
764 const fontSize
= "1.3em";
765 number
.style
.fontSize
= fontSize
;
766 number
.style
.fontSize
= fontSize
;
767 r_cell
.appendChild(number
);
773 updateReserve(color
, piece
, count
) {
774 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
775 piece
= "k"; //capturing cannibal king: back to king form
776 const oldCount
= this.reserve
[color
][piece
];
777 this.reserve
[color
][piece
] = count
;
778 // Redrawing is much easier if count==0
779 if ([oldCount
, count
].includes(0))
780 this.re_drawReserve([color
]);
782 const numId
= this.getReserveNumId(color
, piece
);
783 document
.getElementById(numId
).textContent
= count
;
787 // Resize board: no need to destroy/recreate pieces
789 const container
= document
.getElementById(this.containerId
);
790 let chessboard
= container
.querySelector(".chessboard");
791 const rc
= container
.getBoundingClientRect(),
792 r
= chessboard
.getBoundingClientRect();
793 const multFact
= (mode
== "up" ? 1.05 : 0.95);
794 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
796 const vRatio
= this.size
.ratio
|| 1;
797 if (newWidth
> rc
.width
) {
799 newHeight
= newWidth
/ vRatio
;
801 if (newHeight
> rc
.height
) {
802 newHeight
= rc
.height
;
803 newWidth
= newHeight
* vRatio
;
805 chessboard
.style
.width
= newWidth
+ "px";
806 chessboard
.style
.height
= newHeight
+ "px";
807 const newX
= (rc
.width
- newWidth
) / 2;
808 chessboard
.style
.left
= newX
+ "px";
809 const newY
= (rc
.height
- newHeight
) / 2;
810 chessboard
.style
.top
= newY
+ "px";
811 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
812 const pieceWidth
= this.getPieceWidth(newWidth
);
813 // NOTE: next "if" for variants which use squares filling
814 // instead of "physical", moving pieces
816 for (let i
=0; i
< this.size
.x
; i
++) {
817 for (let j
=0; j
< this.size
.y
; j
++) {
818 if (this.g_pieces
[i
][j
]) {
819 // NOTE: could also use CSS transform "scale"
820 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
821 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
822 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
823 // Translate coordinates to use chessboard as reference:
824 this.g_pieces
[i
][j
].style
.transform
=
825 `translate(${ip - newX}px,${jp - newY}px)`;
831 this.rescaleReserve(newR
);
835 for (let c
of ['w','b']) {
836 if (!this.reserve
[c
])
838 const nbR
= this.getNbReservePieces(c
);
841 // Resize container first
842 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
843 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
844 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
845 let rcontainer
= document
.getElementById("reserves_" + c
);
846 rcontainer
.style
.left
= i0
+ "px";
847 rcontainer
.style
.top
= j0
+ "px";
848 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
849 rcontainer
.style
.height
= sqResSize
+ "px";
850 // And then reserve cells:
851 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
852 Object
.keys(this.reserve
[c
]).forEach(p
=> {
853 if (this.reserve
[c
][p
] == 0)
855 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
856 r_cell
.style
.width
= sqResSize
+ "px";
857 r_cell
.style
.height
= sqResSize
+ "px";
862 // Return the absolute pixel coordinates given current position.
863 // Our coordinate system differs from CSS one (x <--> y).
864 // We return here the CSS coordinates (more useful).
865 getPixelPosition(i
, j
, r
) {
867 return [0, 0]; //piece vanishes
869 if (typeof i
== "string") {
870 // Reserves: need to know the rank of piece
871 const nbR
= this.getNbReservePieces(i
);
872 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
873 x
= this.getRankInReserve(i
, j
) * rsqSize
;
874 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
877 const sqSize
= r
.width
/ this.size
.y
;
878 const flipped
= (this.playerColor
== 'b');
879 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
880 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
882 return [r
.x
+ x
, r
.y
+ y
];
886 let container
= document
.getElementById(this.containerId
);
887 let chessboard
= container
.querySelector(".chessboard");
889 const getOffset
= e
=> {
892 return {x: e
.clientX
, y: e
.clientY
};
893 let touchLocation
= null;
894 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
895 // Touch screen, dragstart
896 touchLocation
= e
.targetTouches
[0];
897 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
898 // Touch screen, dragend
899 touchLocation
= e
.changedTouches
[0];
901 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
902 return {x: 0, y: 0}; //shouldn't reach here =)
905 const centerOnCursor
= (piece
, e
) => {
906 const centerShift
= this.getPieceWidth(r
.width
) / 2;
907 const offset
= getOffset(e
);
908 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
909 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
914 startPiece
, curPiece
= null,
916 const mousedown
= (e
) => {
917 // Disable zoom on smartphones:
918 if (e
.touches
&& e
.touches
.length
> 1)
920 r
= chessboard
.getBoundingClientRect();
921 pieceWidth
= this.getPieceWidth(r
.width
);
922 const cd
= this.idToCoords(e
.target
.id
);
924 const move = this.doClick(cd
);
926 this.buildMoveStack(move, r
);
927 else if (!this.clickOnly
) {
928 const [x
, y
] = Object
.values(cd
);
929 if (typeof x
!= "number")
930 startPiece
= this.r_pieces
[x
][y
];
932 startPiece
= this.g_pieces
[x
][y
];
933 if (startPiece
&& this.canIplay(x
, y
)) {
936 curPiece
= startPiece
.cloneNode();
937 curPiece
.style
.transform
= "none";
938 curPiece
.style
.zIndex
= 5;
939 curPiece
.style
.width
= pieceWidth
+ "px";
940 curPiece
.style
.height
= pieceWidth
+ "px";
941 centerOnCursor(curPiece
, e
);
942 container
.appendChild(curPiece
);
943 startPiece
.style
.opacity
= "0.4";
944 chessboard
.style
.cursor
= "none";
950 const mousemove
= (e
) => {
953 centerOnCursor(curPiece
, e
);
955 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
956 // Attempt to prevent horizontal swipe...
960 const mouseup
= (e
) => {
963 const [x
, y
] = [start
.x
, start
.y
];
966 chessboard
.style
.cursor
= "pointer";
967 startPiece
.style
.opacity
= "1";
968 const offset
= getOffset(e
);
969 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
971 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
973 // NOTE: clearly suboptimal, but much easier, and not a big deal.
974 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
975 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
976 const moves
= this.filterValid(potentialMoves
);
977 if (moves
.length
>= 2)
978 this.showChoices(moves
, r
);
979 else if (moves
.length
== 1)
980 this.buildMoveStack(moves
[0], r
);
985 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
987 if ('onmousedown' in window
) {
988 this.mouseListeners
= [
989 {type: "mousedown", listener: mousedown
},
990 {type: "mousemove", listener: mousemove
},
991 {type: "mouseup", listener: mouseup
},
992 {type: "wheel", listener: resize
}
994 this.mouseListeners
.forEach(ml
=> {
995 document
.addEventListener(ml
.type
, ml
.listener
);
998 if ('ontouchstart' in window
) {
999 this.touchListeners
= [
1000 {type: "touchstart", listener: mousedown
},
1001 {type: "touchmove", listener: mousemove
},
1002 {type: "touchend", listener: mouseup
}
1004 this.touchListeners
.forEach(tl
=> {
1005 // https://stackoverflow.com/a/42509310/12660887
1006 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
1009 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1014 return; //no listeners in this case
1015 if ('onmousedown' in window
) {
1016 this.mouseListeners
.forEach(ml
=> {
1017 document
.removeEventListener(ml
.type
, ml
.listener
);
1020 if ('ontouchstart' in window
) {
1021 this.touchListeners
.forEach(tl
=> {
1022 // https://stackoverflow.com/a/42509310/12660887
1023 document
.removeEventListener(tl
.type
, tl
.listener
);
1028 showChoices(moves
, r
) {
1029 let container
= document
.getElementById(this.containerId
);
1030 let chessboard
= container
.querySelector(".chessboard");
1031 let choices
= document
.createElement("div");
1032 choices
.id
= "choices";
1034 r
= chessboard
.getBoundingClientRect();
1035 choices
.style
.width
= r
.width
+ "px";
1036 choices
.style
.height
= r
.height
+ "px";
1037 choices
.style
.left
= r
.x
+ "px";
1038 choices
.style
.top
= r
.y
+ "px";
1039 chessboard
.style
.opacity
= "0.5";
1040 container
.appendChild(choices
);
1041 const squareWidth
= r
.width
/ this.size
.y
;
1042 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1043 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1044 const color
= moves
[0].appear
[0].c
;
1045 const callback
= (m
) => {
1046 chessboard
.style
.opacity
= "1";
1047 container
.removeChild(choices
);
1048 this.buildMoveStack(m
, r
);
1050 for (let i
=0; i
< moves
.length
; i
++) {
1051 let choice
= document
.createElement("div");
1052 choice
.classList
.add("choice");
1053 choice
.style
.width
= squareWidth
+ "px";
1054 choice
.style
.height
= squareWidth
+ "px";
1055 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1056 choice
.style
.top
= firstUpTop
+ "px";
1057 choice
.style
.backgroundColor
= "lightyellow";
1058 choice
.onclick
= () => callback(moves
[i
]);
1059 const piece
= document
.createElement("piece");
1060 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1061 C
.AddClass_es(piece
,
1062 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1063 piece
.classList
.add(C
.GetColorClass(color
));
1064 piece
.style
.width
= "100%";
1065 piece
.style
.height
= "100%";
1066 choice
.appendChild(piece
);
1067 choices
.appendChild(choice
);
1074 updateEnlightened() {
1075 this.oldEnlightened
= this.enlightened
;
1076 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1077 // Add pieces positions + all squares reachable by moves (includes Zen):
1078 for (let x
=0; x
<this.size
.x
; x
++) {
1079 for (let y
=0; y
<this.size
.y
; y
++) {
1080 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1082 this.enlightened
[x
][y
] = true;
1083 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1084 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1090 this.enlightEnpassant();
1093 // Include square of the en-passant capturing square:
1094 enlightEnpassant() {
1095 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1096 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
1097 for (let step
of steps
) {
1098 const x
= this.epSquare
.x
- step
[0],
1099 y
= this.getY(this.epSquare
.y
- step
[1]);
1101 this.onBoard(x
, y
) &&
1102 this.getColor(x
, y
) == this.playerColor
&&
1103 this.getPieceType(x
, y
) == "p"
1105 this.enlightened
[x
][this.epSquare
.y
] = true;
1111 // Apply diff this.enlightened --> oldEnlightened on board
1112 graphUpdateEnlightened() {
1114 document
.getElementById(this.containerId
).querySelector(".chessboard");
1115 const r
= chessboard
.getBoundingClientRect();
1116 const pieceWidth
= this.getPieceWidth(r
.width
);
1117 for (let x
=0; x
<this.size
.x
; x
++) {
1118 for (let y
=0; y
<this.size
.y
; y
++) {
1119 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1120 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1121 elt
.classList
.add("in-shadow");
1122 if (this.g_pieces
[x
][y
])
1123 this.g_pieces
[x
][y
].classList
.add("hidden");
1125 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1126 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1127 elt
.classList
.remove("in-shadow");
1128 if (this.g_pieces
[x
][y
])
1129 this.g_pieces
[x
][y
].classList
.remove("hidden");
1142 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1146 // Color of thing on square (i,j). '' if square is empty
1148 if (typeof i
== "string")
1149 return i
; //reserves
1150 return this.board
[i
][j
].charAt(0);
1153 static GetColorClass(c
) {
1158 return "other-color"; //unidentified color
1161 // Piece on i,j. '' if square is empty
1163 if (typeof j
== "string")
1164 return j
; //reserves
1165 return this.board
[i
][j
].charAt(1);
1168 // Piece type on square (i,j)
1169 getPieceType(x
, y
, p
) {
1171 p
= this.getPiece(x
, y
);
1172 return this.pieces()[p
].moveas
|| p
;
1177 p
= this.getPiece(x
, y
);
1178 if (!this.options
["cannibal"])
1180 return !!C
.CannibalKings
[p
];
1183 // Get opponent color
1184 static GetOppCol(color
) {
1185 return (color
== "w" ? "b" : "w");
1188 // Is (x,y) on the chessboard?
1190 return (x
>= 0 && x
< this.size
.x
&&
1191 y
>= 0 && y
< this.size
.y
);
1194 // Am I allowed to move thing at square x,y ?
1196 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1199 ////////////////////////
1200 // PIECES SPECIFICATIONS
1202 pieces(color
, x
, y
) {
1203 const pawnShift
= (color
== "w" ? -1 : 1);
1204 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1205 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1211 steps: [[pawnShift
, 0]],
1212 range: (initRank
? 2 : 1)
1217 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1225 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1233 [1, 2], [1, -2], [-1, 2], [-1, -2],
1234 [2, 1], [-2, 1], [2, -1], [-2, -1]
1243 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1251 [0, 1], [0, -1], [1, 0], [-1, 0],
1252 [1, 1], [1, -1], [-1, 1], [-1, -1]
1262 [0, 1], [0, -1], [1, 0], [-1, 0],
1263 [1, 1], [1, -1], [-1, 1], [-1, -1]
1270 '!': {"class": "king-pawn", moveas: "p"},
1271 '#': {"class": "king-rook", moveas: "r"},
1272 '$': {"class": "king-knight", moveas: "n"},
1273 '%': {"class": "king-bishop", moveas: "b"},
1274 '*': {"class": "king-queen", moveas: "q"}
1278 // NOTE: using special symbols to not interfere with variants' pieces codes
1279 static get CannibalKings() {
1290 static get CannibalKingCode() {
1301 //////////////////////////
1302 // MOVES GENERATION UTILS
1304 // For Cylinder: get Y coordinate
1306 if (!this.options
["cylinder"])
1308 let res
= y
% this.size
.y
;
1314 getSegments(curSeg
, segStart
, segEnd
) {
1315 if (curSeg
.length
== 0)
1317 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1318 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1322 getStepSpec(color
, x
, y
, piece
) {
1323 return this.pieces(color
, x
, y
)[piece
|| this.getPieceType(x
, y
)];
1326 // Can thing on square1 capture thing on square2?
1327 canTake([x1
, y1
], [x2
, y2
]) {
1328 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1331 canStepOver(i
, j
, p
) {
1332 // In some variants, objects on boards don't stop movement (Chakart)
1333 return this.board
[i
][j
] == "";
1336 canDrop([c
, p
], [i
, j
]) {
1338 this.board
[i
][j
] == "" &&
1339 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1342 (c
== 'w' && i
< this.size
.x
- 1) ||
1349 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1350 isImmobilized([x
, y
]) {
1351 if (!this.options
["madrasi"])
1353 const color
= this.getColor(x
, y
);
1354 const oppCol
= C
.GetOppCol(color
);
1355 const piece
= this.getPieceType(x
, y
);
1356 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1357 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1358 for (let a
of attacks
) {
1359 outerLoop: for (let step
of a
.steps
) {
1360 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1361 let stepCounter
= 1;
1362 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1363 if (a
.range
<= stepCounter
++)
1366 j
= this.getY(j
+ step
[1]);
1369 this.onBoard(i
, j
) &&
1370 this.getColor(i
, j
) == oppCol
&&
1371 this.getPieceType(i
, j
) == piece
1380 // Stop at the first capture found
1381 atLeastOneCapture(color
) {
1382 const oppCol
= C
.GetOppCol(color
);
1383 const allowed
= (sq1
, sq2
) => {
1385 // NOTE: canTake is reversed for Zen.
1386 // Generally ok because of the symmetry. TODO?
1387 this.canTake(sq1
, sq2
) &&
1389 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1392 for (let i
=0; i
<this.size
.x
; i
++) {
1393 for (let j
=0; j
<this.size
.y
; j
++) {
1394 if (this.getColor(i
, j
) == color
) {
1397 !this.options
["zen"] &&
1398 this.findDestSquares(
1403 segments: this.options
["cylinder"]
1411 this.options
["zen"] &&
1412 this.findCapturesOn(
1416 segments: this.options
["cylinder"]
1431 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1432 const epsilon
= 1e-7; //arbitrary small value
1434 if (this.options
["cylinder"])
1435 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1436 for (let sh
of shifts
) {
1437 const rx
= (x2
- x1
) / step
[0],
1438 ry
= (y2
+ sh
- y1
) / step
[1];
1440 // Zero step but non-zero interval => impossible
1441 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1442 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1443 // Negative number of step (impossible)
1444 (rx
< 0 || ry
< 0) ||
1445 // Not the same number of steps in both directions:
1446 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1450 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1451 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1453 distance
= Math
.round(distance
); //in case of (numerical...)
1454 if (!range
|| range
>= distance
)
1460 ////////////////////
1463 getDropMovesFrom([c
, p
]) {
1464 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1465 // (but not necessarily otherwise: atLeastOneMove() etc)
1466 if (this.reserve
[c
][p
] == 0)
1469 for (let i
=0; i
<this.size
.x
; i
++) {
1470 for (let j
=0; j
<this.size
.y
; j
++) {
1471 if (this.canDrop([c
, p
], [i
, j
])) {
1473 start: {x: c
, y: p
},
1475 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1478 if (this.board
[i
][j
] != "") {
1479 mv
.vanish
.push(new PiPo({
1482 c: this.getColor(i
, j
),
1483 p: this.getPiece(i
, j
)
1493 // All possible moves from selected square
1494 getPotentialMovesFrom([x
, y
], color
) {
1495 if (this.subTurnTeleport
== 2)
1497 if (typeof x
== "string")
1498 return this.getDropMovesFrom([x
, y
]);
1499 if (this.isImmobilized([x
, y
]))
1501 const piece
= this.getPieceType(x
, y
);
1502 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1503 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1504 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1506 piece
== "k" && this.hasCastle
&&
1507 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1509 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1511 return this.postProcessPotentialMoves(moves
);
1514 postProcessPotentialMoves(moves
) {
1515 if (moves
.length
== 0)
1517 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1518 const oppCol
= C
.GetOppCol(color
);
1520 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1521 moves
= this.capturePostProcess(moves
, oppCol
);
1523 if (this.options
["atomic"])
1524 this.atomicPostProcess(moves
, color
, oppCol
);
1528 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1530 this.pawnPostProcess(moves
, color
, oppCol
);
1533 if (this.options
["cannibal"] && this.options
["rifle"])
1534 // In this case a rifle-capture from last rank may promote a pawn
1535 this.riflePromotePostProcess(moves
, color
);
1540 capturePostProcess(moves
, oppCol
) {
1541 // Filter out non-capturing moves (not using m.vanish because of
1542 // self captures of Recycle and Teleport).
1543 return moves
.filter(m
=> {
1545 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1546 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1551 atomicPostProcess(moves
, color
, oppCol
) {
1552 moves
.forEach(m
=> {
1554 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1555 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1568 let mNext
= new Move({
1574 for (let step
of steps
) {
1575 let x
= m
.end
.x
+ step
[0];
1576 let y
= this.getY(m
.end
.y
+ step
[1]);
1578 this.onBoard(x
, y
) &&
1579 this.board
[x
][y
] != "" &&
1580 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1581 this.getPieceType(x
, y
) != "p"
1585 p: this.getPiece(x
, y
),
1586 c: this.getColor(x
, y
),
1593 if (!this.options
["rifle"]) {
1594 // The moving piece also vanish
1595 mNext
.vanish
.unshift(
1600 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1609 pawnPostProcess(moves
, color
, oppCol
) {
1611 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1612 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1613 moves
.forEach(m
=> {
1614 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1615 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1616 const promotionOk
= (
1618 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1621 return; //nothing to do
1622 if (this.options
["pawnfall"]) {
1626 let finalPieces
= ["p"];
1628 this.options
["cannibal"] &&
1629 this.board
[x2
][y2
] != "" &&
1630 this.getColor(x2
, y2
) == oppCol
1632 finalPieces
= [this.getPieceType(x2
, y2
)];
1635 finalPieces
= this.pawnPromotions
;
1636 m
.appear
[0].p
= finalPieces
[0];
1637 if (initPiece
== "!") //cannibal king-pawn
1638 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1639 for (let i
=1; i
<finalPieces
.length
; i
++) {
1640 const piece
= finalPieces
[i
];
1643 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1645 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1646 moreMoves
.push(newMove
);
1649 Array
.prototype.push
.apply(moves
, moreMoves
);
1652 riflePromotePostProcess(moves
, color
) {
1653 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1655 moves
.forEach(m
=> {
1657 m
.start
.x
== lastRank
&&
1658 m
.appear
.length
>= 1 &&
1659 m
.appear
[0].p
== "p" &&
1660 m
.appear
[0].x
== m
.start
.x
&&
1661 m
.appear
[0].y
== m
.start
.y
1663 m
.appear
[0].p
= this.pawnPromotions
[0];
1664 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1665 let newMv
= JSON
.parse(JSON
.stringify(m
));
1666 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1667 newMoves
.push(newMv
);
1671 Array
.prototype.push
.apply(moves
, newMoves
);
1674 // Generic method to find possible moves of "sliding or jumping" pieces
1675 getPotentialMovesOf(piece
, [x
, y
]) {
1676 const color
= this.getColor(x
, y
);
1677 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1679 if (stepSpec
.attack
) {
1680 squares
= this.findDestSquares(
1684 segments: this.options
["cylinder"],
1687 ([i1
, j1
], [i2
, j2
]) => {
1689 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1690 this.canTake([i1
, j1
], [i2
, j2
])
1695 const noSpecials
= this.findDestSquares(
1698 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1699 segments: this.options
["cylinder"],
1703 Array
.prototype.push
.apply(squares
, noSpecials
);
1704 if (this.options
["zen"]) {
1705 let zenCaptures
= this.findCapturesOn(
1707 {}, //byCol: default is ok
1708 ([i1
, j1
], [i2
, j2
]) =>
1709 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1711 // Technical step: segments (if any) are reversed
1712 if (this.options
["cylinder"]) {
1713 zenCaptures
.forEach(z
=> {
1714 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1717 Array
.prototype.push
.apply(squares
, zenCaptures
);
1720 this.options
["recycle"] ||
1721 (this.options
["teleport"] && this.subTurnTeleport
== 1)
1723 const selfCaptures
= this.findDestSquares(
1727 segments: this.options
["cylinder"],
1730 ([i1
, j1
], [i2
, j2
]) =>
1731 this.getColor(i2
, j2
) == color
&& !this.isKing(i2
, j2
)
1733 Array
.prototype.push
.apply(squares
, selfCaptures
);
1735 return squares
.map(s
=> {
1736 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1737 if (this.options
["cylinder"] && s
.segments
.length
>= 2)
1738 mv
.segments
= s
.segments
;
1743 findDestSquares([x
, y
], o
, allowed
) {
1745 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1746 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1748 // Next 3 for Cylinder mode: (unused if !o.segments)
1752 const addSquare
= ([i
, j
]) => {
1753 let elt
= {sq: [i
, j
]};
1755 elt
.segments
= this.getSegments(segments
, segStart
, end
);
1758 const exploreSteps
= (stepArray
) => {
1759 for (let s
of stepArray
) {
1760 outerLoop: for (let step
of s
.steps
) {
1765 let [i
, j
] = [x
, y
];
1766 let stepCounter
= 0;
1768 this.onBoard(i
, j
) &&
1769 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1771 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1772 explored
[i
+ "." + j
] = true;
1775 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1777 if (o
.one
&& !o
.attackOnly
)
1780 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1781 if (o
.captureTarget
)
1785 if (s
.range
<= stepCounter
++)
1787 const oldIJ
= [i
, j
];
1789 j
= this.getY(j
+ step
[1]);
1790 if (o
.segments
&& Math
.abs(j
- oldIJ
[1]) > 1) {
1791 // Boundary between segments (cylinder mode)
1792 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1796 if (!this.onBoard(i
, j
))
1798 const pieceIJ
= this.getPieceType(i
, j
);
1799 if (!explored
[i
+ "." + j
]) {
1800 explored
[i
+ "." + j
] = true;
1801 if (allowed([x
, y
], [i
, j
])) {
1802 if (o
.one
&& !o
.moveOnly
)
1805 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1808 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1816 return undefined; //default, but let's explicit it
1818 if (o
.captureTarget
)
1819 return exploreSteps(o
.captureSteps
)
1822 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1824 if (!o
.attackOnly
|| !stepSpec
.attack
)
1825 outOne
= exploreSteps(stepSpec
.moves
);
1826 if (!outOne
&& !o
.moveOnly
&& !!stepSpec
.attack
) {
1827 o
.attackOnly
= true; //ok because o is always a temporary object
1828 outOne
= exploreSteps(stepSpec
.attack
);
1830 return (o
.one
? outOne : res
);
1834 // Search for enemy (or not) pieces attacking [x, y]
1835 findCapturesOn([x
, y
], o
, allowed
) {
1837 o
.byCol
= [C
.GetOppCol(this.getColor(x
, y
) || this.turn
)];
1839 for (let i
=0; i
<this.size
.x
; i
++) {
1840 for (let j
=0; j
<this.size
.y
; j
++) {
1841 const colIJ
= this.getColor(i
, j
);
1843 this.board
[i
][j
] != "" &&
1844 o
.byCol
.includes(colIJ
) &&
1845 !this.isImmobilized([i
, j
])
1847 const apparentPiece
= this.getPiece(i
, j
);
1848 // Quick check: does this potential attacker target x,y ?
1849 if (this.canStepOver(x
, y
, apparentPiece
))
1851 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1852 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1853 for (let a
of attacks
) {
1854 for (let s
of a
.steps
) {
1855 // Quick check: if step isn't compatible, don't even try
1856 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1858 // Finally verify that nothing stand in-between
1859 const out
= this.findDestSquares(
1862 captureTarget: [x
, y
],
1863 captureSteps: [{steps: [s
], range: a
.range
}],
1864 segments: o
.segments
,
1866 one: false //one and captureTarget are mutually exclusive
1880 return (o
.one
? false : res
);
1883 // Build a regular move from its initial and destination squares.
1884 // tr: transformation
1885 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1886 const initColor
= this.getColor(sx
, sy
);
1887 const initPiece
= this.getPiece(sx
, sy
);
1888 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1892 start: {x: sx
, y: sy
},
1896 !this.options
["rifle"] ||
1897 this.board
[ex
][ey
] == "" ||
1898 destColor
== initColor
//Recycle, Teleport
1904 c: !!tr
? tr
.c : initColor
,
1905 p: !!tr
? tr
.p : initPiece
1917 if (this.board
[ex
][ey
] != "") {
1922 c: this.getColor(ex
, ey
),
1923 p: this.getPiece(ex
, ey
)
1926 if (this.options
["cannibal"] && destColor
!= initColor
) {
1927 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1928 let trPiece
= mv
.vanish
[lastIdx
].p
;
1929 if (this.isKing(sx
, sy
))
1930 trPiece
= C
.CannibalKingCode
[trPiece
];
1931 if (mv
.appear
.length
>= 1)
1932 mv
.appear
[0].p
= trPiece
;
1933 else if (this.options
["rifle"]) {
1956 // En-passant square, if any
1957 getEpSquare(moveOrSquare
) {
1958 if (typeof moveOrSquare
=== "string") {
1959 const square
= moveOrSquare
;
1962 return C
.SquareToCoords(square
);
1964 // Argument is a move:
1965 const move = moveOrSquare
;
1966 const s
= move.start
,
1970 Math
.abs(s
.x
- e
.x
) == 2 &&
1971 // Next conditions for variants like Atomic or Rifle, Recycle...
1973 move.appear
.length
> 0 &&
1974 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1978 move.vanish
.length
> 0 &&
1979 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1987 return undefined; //default
1990 // Special case of en-passant captures: treated separately
1991 getEnpassantCaptures([x
, y
]) {
1992 const color
= this.getColor(x
, y
);
1993 const shiftX
= (color
== 'w' ? -1 : 1);
1994 const oppCol
= C
.GetOppCol(color
);
1997 this.epSquare
.x
== x
+ shiftX
&&
1998 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1999 // Doublemove (and Progressive?) guards:
2000 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2001 this.getColor(x
, this.epSquare
.y
) == oppCol
2003 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2004 this.board
[epx
][epy
] = oppCol
+ 'p';
2005 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2006 this.board
[epx
][epy
] = "";
2007 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2008 enpassantMove
.vanish
[lastIdx
].x
= x
;
2009 return [enpassantMove
];
2014 getCastleMoves([x
, y
], finalSquares
, castleWith
) {
2015 const c
= this.getColor(x
, y
);
2018 const oppCol
= C
.GetOppCol(c
);
2022 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2023 const castlingKing
= this.getPiece(x
, y
);
2024 castlingCheck: for (
2027 castleSide
++ //large, then small
2029 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
2031 // If this code is reached, rook and king are on initial position
2033 // NOTE: in some variants this is not a rook
2034 const rookPos
= this.castleFlags
[c
][castleSide
];
2035 const castlingPiece
= this.getPiece(x
, rookPos
);
2037 this.board
[x
][rookPos
] == "" ||
2038 this.getColor(x
, rookPos
) != c
||
2039 (castleWith
&& !castleWith
.includes(castlingPiece
))
2041 // Rook is not here, or changed color (see Benedict)
2044 // Nothing on the path of the king ? (and no checks)
2045 const finDist
= finalSquares
[castleSide
][0] - y
;
2046 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2050 // NOTE: next weird test because underCheck() verification
2051 // will be executed in filterValid() later.
2053 i
!= finalSquares
[castleSide
][0] &&
2054 this.underCheck([x
, i
], oppCol
)
2058 this.board
[x
][i
] != "" &&
2059 // NOTE: next check is enough, because of chessboard constraints
2060 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2063 continue castlingCheck
;
2066 } while (i
!= finalSquares
[castleSide
][0]);
2067 // Nothing on the path to the rook?
2068 step
= (castleSide
== 0 ? -1 : 1);
2069 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2070 if (this.board
[x
][i
] != "")
2071 continue castlingCheck
;
2074 // Nothing on final squares, except maybe king and castling rook?
2075 for (i
= 0; i
< 2; i
++) {
2077 finalSquares
[castleSide
][i
] != rookPos
&&
2078 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2080 finalSquares
[castleSide
][i
] != y
||
2081 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2084 continue castlingCheck
;
2088 // If this code is reached, castle is potentially valid
2094 y: finalSquares
[castleSide
][0],
2100 y: finalSquares
[castleSide
][1],
2106 // King might be initially disguised (Titan...)
2107 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2108 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2111 Math
.abs(y
- rookPos
) <= 2
2112 ? {x: x
, y: rookPos
}
2113 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2121 ////////////////////
2124 // Is piece (or square) at given position attacked by "oppCol" ?
2125 underAttack([x
, y
], oppCol
) {
2126 // An empty square is considered as king,
2127 // since it's used only in getCastleMoves (TODO?)
2128 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2131 (!this.options
["zen"] || king
) &&
2132 this.findCapturesOn(
2136 segments: this.options
["cylinder"],
2143 (!!this.options
["zen"] && !king
) &&
2144 this.findDestSquares(
2148 segments: this.options
["cylinder"],
2151 ([i1
, j1
], [i2
, j2
]) => this.getColor(i2
, j2
) == oppCol
2157 underCheck([x
, y
], oppCol
) {
2158 if (this.options
["taking"] || this.options
["dark"])
2160 return this.underAttack([x
, y
], oppCol
);
2163 // Stop at first king found (TODO: multi-kings)
2164 searchKingPos(color
) {
2165 for (let i
=0; i
< this.size
.x
; i
++) {
2166 for (let j
=0; j
< this.size
.y
; j
++) {
2167 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2171 return [-1, -1]; //king not found
2174 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2175 filterValid(moves
, color
) {
2178 const oppCol
= C
.GetOppCol(color
);
2179 const kingPos
= this.searchKingPos(color
);
2180 let filtered
= {}; //avoid re-checking similar moves (promotions...)
2181 return moves
.filter(m
=> {
2182 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
2183 if (!filtered
[key
]) {
2184 this.playOnBoard(m
);
2185 let square
= kingPos
,
2186 res
= true; //a priori valid
2187 if (m
.vanish
.some(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
)) {
2188 // Search king in appear array:
2190 m
.appear
.findIndex(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2191 if (newKingIdx
>= 0)
2192 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
2196 res
&&= !this.underCheck(square
, oppCol
);
2197 this.undoOnBoard(m
);
2198 filtered
[key
] = res
;
2201 return filtered
[key
];
2208 // Apply a move on board
2210 for (let psq
of move.vanish
)
2211 this.board
[psq
.x
][psq
.y
] = "";
2212 for (let psq
of move.appear
)
2213 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2215 // Un-apply the played move
2217 for (let psq
of move.appear
)
2218 this.board
[psq
.x
][psq
.y
] = "";
2219 for (let psq
of move.vanish
)
2220 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2223 updateCastleFlags(move) {
2224 // Update castling flags if start or arrive from/at rook/king locations
2225 move.appear
.concat(move.vanish
).forEach(psq
=> {
2226 if (this.isKing(0, 0, psq
.p
))
2227 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2228 // NOTE: not "else if" because king can capture enemy rook...
2232 else if (psq
.x
== this.size
.x
- 1)
2235 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2237 this.castleFlags
[c
][fidx
] = this.size
.y
;
2245 // If flags already off, no need to re-check:
2246 Object
.values(this.castleFlags
).some(cvals
=>
2247 cvals
.some(val
=> val
< this.size
.y
))
2249 this.updateCastleFlags(move);
2251 if (this.options
["crazyhouse"]) {
2252 move.vanish
.forEach(v
=> {
2253 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2254 if (this.ispawn
[square
])
2255 delete this.ispawn
[square
];
2257 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2258 // Assumption: something is moving
2259 const initSquare
= C
.CoordsToSquare(move.start
);
2260 const destSquare
= C
.CoordsToSquare(move.end
);
2262 this.ispawn
[initSquare
] ||
2263 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2265 this.ispawn
[destSquare
] = true;
2268 this.ispawn
[destSquare
] &&
2269 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2271 move.vanish
[1].p
= 'p';
2272 delete this.ispawn
[destSquare
];
2276 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2279 // Warning; atomic pawn removal isn't a capture
2280 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2282 const color
= this.turn
;
2283 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2284 // Something appears = dropped on board (some exceptions, Chakart...)
2285 if (move.appear
[i
].c
== color
) {
2286 const piece
= move.appear
[i
].p
;
2287 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2290 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2291 // Something vanish: add to reserve except if recycle & opponent
2293 this.options
["crazyhouse"] ||
2294 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2296 const piece
= move.vanish
[i
].p
;
2297 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2305 if (this.hasEnpassant
)
2306 this.epSquare
= this.getEpSquare(move);
2307 this.playOnBoard(move);
2308 this.postPlay(move);
2312 const color
= this.turn
;
2313 if (this.options
["dark"])
2314 this.updateEnlightened();
2315 if (this.options
["teleport"]) {
2317 this.subTurnTeleport
== 1 &&
2318 move.vanish
.length
> move.appear
.length
&&
2319 move.vanish
[1].c
== color
2321 const v
= move.vanish
[move.vanish
.length
- 1];
2322 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2323 this.subTurnTeleport
= 2;
2326 this.subTurnTeleport
= 1;
2327 this.captured
= null;
2329 if (this.isLastMove(move)) {
2330 this.turn
= C
.GetOppCol(color
);
2334 else if (!move.next
)
2341 const color
= this.turn
;
2342 const oppKingPos
= this.searchKingPos(C
.GetOppCol(color
));
2343 if (oppKingPos
[0] < 0 || this.underCheck(oppKingPos
, color
))
2347 !this.options
["balance"] ||
2348 ![1, 2].includes(this.movesCount
) ||
2353 !this.options
["doublemove"] ||
2354 this.movesCount
== 0 ||
2359 !this.options
["progressive"] ||
2360 this.subTurn
== this.movesCount
+ 1
2365 // "Stop at the first move found"
2366 atLeastOneMove(color
) {
2367 for (let i
= 0; i
< this.size
.x
; i
++) {
2368 for (let j
= 0; j
< this.size
.y
; j
++) {
2369 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2370 // NOTE: in fact searching for all potential moves from i,j.
2371 // I don't believe this is an issue, for now at least.
2372 const moves
= this.getPotentialMovesFrom([i
, j
]);
2373 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2378 if (this.hasReserve
&& this.reserve
[color
]) {
2379 for (let p
of Object
.keys(this.reserve
[color
])) {
2380 const moves
= this.getDropMovesFrom([color
, p
]);
2381 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2388 // What is the score ? (Interesting if game is over)
2389 getCurrentScore(move) {
2390 const color
= this.turn
;
2391 const oppCol
= C
.GetOppCol(color
);
2392 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2393 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2395 if (kingPos
[0][0] < 0)
2396 return (color
== "w" ? "0-1" : "1-0");
2397 if (kingPos
[1][0] < 0)
2398 return (color
== "w" ? "1-0" : "0-1");
2399 if (this.atLeastOneMove(color
))
2401 // No valid move: stalemate or checkmate?
2402 if (!this.underCheck(kingPos
[0], oppCol
))
2405 return (color
== "w" ? "0-1" : "1-0");
2408 playVisual(move, r
) {
2409 move.vanish
.forEach(v
=> {
2410 this.g_pieces
[v
.x
][v
.y
].remove();
2411 this.g_pieces
[v
.x
][v
.y
] = null;
2414 document
.getElementById(this.containerId
).querySelector(".chessboard");
2416 r
= chessboard
.getBoundingClientRect();
2417 const pieceWidth
= this.getPieceWidth(r
.width
);
2418 move.appear
.forEach(a
=> {
2419 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2420 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2421 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2422 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2423 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2424 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2425 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2426 // Translate coordinates to use chessboard as reference:
2427 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2428 `translate(${ip - r.x}px,${jp - r.y}px)`;
2429 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2430 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2431 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2433 if (this.options
["dark"])
2434 this.graphUpdateEnlightened();
2437 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2438 buildMoveStack(move, r
) {
2439 this.moveStack
.push(move);
2440 this.computeNextMove(move);
2442 const newTurn
= this.turn
;
2443 if (this.moveStack
.length
== 1)
2444 this.playVisual(move, r
);
2448 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2450 this.buildMoveStack(move.next
, r
);
2453 if (this.moveStack
.length
== 1) {
2454 // Usual case (one normal move)
2455 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2459 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2460 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2461 this.playReceivedMove(this.moveStack
.slice(1), () => {
2462 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2469 // Implemented in variants using (automatic) moveStack
2470 computeNextMove(move) {}
2472 animateMoving(start
, end
, drag
, segments
, cb
) {
2473 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2474 // NOTE: cloning often not required, but light enough, and simpler
2475 let movingPiece
= initPiece
.cloneNode();
2476 initPiece
.style
.opacity
= "0";
2478 document
.getElementById(this.containerId
)
2479 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2480 if (typeof start
.x
== "string") {
2481 // Need to bound width/height (was 100% for reserve pieces)
2482 const pieceWidth
= this.getPieceWidth(r
.width
);
2483 movingPiece
.style
.width
= pieceWidth
+ "px";
2484 movingPiece
.style
.height
= pieceWidth
+ "px";
2486 const maxDist
= this.getMaxDistance(r
);
2487 const apparentColor
= this.getColor(start
.x
, start
.y
);
2488 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2490 const startCode
= this.getPiece(start
.x
, start
.y
);
2491 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2492 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2493 if (apparentColor
!= drag
.c
) {
2494 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2495 movingPiece
.classList
.add(C
.GetColorClass(drag
.c
));
2498 container
.appendChild(movingPiece
);
2499 const animateSegment
= (index
, cb
) => {
2500 // NOTE: move.drag could be generalized per-segment (usage?)
2501 const [i1
, j1
] = segments
[index
][0];
2502 const [i2
, j2
] = segments
[index
][1];
2503 const dep
= this.getPixelPosition(i1
, j1
, r
);
2504 const arr
= this.getPixelPosition(i2
, j2
, r
);
2505 movingPiece
.style
.transitionDuration
= "0s";
2506 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2508 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2509 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2510 // TODO: unclear why we need this new delay below:
2512 movingPiece
.style
.transitionDuration
= duration
+ "s";
2513 // movingPiece is child of container: no need to adjust coordinates
2514 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2515 setTimeout(cb
, duration
* 1000);
2519 const animateSegmentCallback
= () => {
2520 if (index
< segments
.length
)
2521 animateSegment(index
++, animateSegmentCallback
);
2523 movingPiece
.remove();
2524 initPiece
.style
.opacity
= "1";
2528 animateSegmentCallback();
2531 // Input array of objects with at least fields x,y (e.g. PiPo)
2532 animateFading(arr
, cb
) {
2533 const animLength
= 350; //TODO: 350ms? More? Less?
2535 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2536 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2537 fadingPiece
.style
.opacity
= "0";
2539 setTimeout(cb
, animLength
);
2542 animate(move, callback
) {
2543 if (this.noAnimate
|| move.noAnimate
) {
2547 let segments
= move.segments
;
2549 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2550 let targetObj
= new TargetObj(callback
);
2551 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2553 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2554 () => targetObj
.increment());
2556 if (move.vanish
.length
> move.appear
.length
) {
2557 const arr
= move.vanish
.slice(move.appear
.length
)
2558 // Ignore disappearing pieces hidden by some appearing ones:
2559 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2560 if (arr
.length
> 0) {
2562 this.animateFading(arr
, () => targetObj
.increment());
2566 this.customAnimate(move, segments
, () => targetObj
.increment());
2567 if (targetObj
.target
== 0)
2571 // Potential other animations (e.g. for Suction variant)
2572 customAnimate(move, segments
, cb
) {
2573 return 0; //nb of targets
2576 playReceivedMove(moves
, callback
) {
2577 const launchAnimation
= () => {
2578 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2579 const animateRec
= i
=> {
2580 this.animate(moves
[i
], () => {
2581 this.play(moves
[i
]);
2582 this.playVisual(moves
[i
], r
);
2583 if (i
< moves
.length
- 1)
2584 setTimeout(() => animateRec(i
+1), 300);
2591 // Delay if user wasn't focused:
2592 const checkDisplayThenAnimate
= (delay
) => {
2593 if (container
.style
.display
== "none") {
2594 alert("New move! Let's go back to game...");
2595 document
.getElementById("gameInfos").style
.display
= "none";
2596 container
.style
.display
= "block";
2597 setTimeout(launchAnimation
, 700);
2600 setTimeout(launchAnimation
, delay
|| 0);
2602 let container
= document
.getElementById(this.containerId
);
2603 if (document
.hidden
) {
2604 document
.onvisibilitychange
= () => {
2605 document
.onvisibilitychange
= undefined;
2606 checkDisplayThenAnimate(700);
2610 checkDisplayThenAnimate();