3d8e4635b53d6e5a46c7a38cb907bc5330a50633
1 import {Random
} from "/utils/alea.js";
2 import {ArrayFun
} from "/utils/array.js";
3 import {FenUtil
} from "/utils/setupPieces.js";
4 import PiPo
from "/utils/PiPo.js";
5 import Move
from "/utils/Move.js";
7 // Helper class for move animation
10 constructor(callOnComplete
) {
13 this.callOnComplete
= callOnComplete
;
16 if (++this.value
== this.target
)
17 this.callOnComplete();
22 // NOTE: x coords: top to bottom (white perspective); y: left to right
23 // NOTE: ChessRules is aliased as window.C, and variants as window.V
24 export default class ChessRules
{
26 static get Aliases() {
27 return {'C': ChessRules
};
30 /////////////////////////
31 // VARIANT SPECIFICATIONS
33 // Some variants have specific options, like the number of pawns in Monster,
34 // or the board size for Pandemonium.
35 // Users can generally select a randomness level from 0 to 2.
36 static get Options() {
40 variable: "randomness",
43 {label: "Deterministic", value: 0},
44 {label: "Symmetric random", value: 1},
45 {label: "Asymmetric random", value: 2}
50 label: "Capture king",
56 label: "Falling pawn",
62 // Game modifiers (using "elementary variants"). Default: false
65 "balance", //takes precedence over doublemove & progressive
69 "cylinder", //ok with all
73 "progressive", //(natural) priority over doublemove
82 get pawnPromotions() {
83 return ['q', 'r', 'n', 'b'];
86 // Some variants don't have flags:
95 // En-passant captures allowed?
100 // Allow to take (moving: not disappearing) own pieces?
101 get hasSelfCaptures() {
103 this.options
["recycle"] ||
104 (this.options
["teleport"] && this.subTurnTeleport
== 1)
110 !!this.options
["crazyhouse"] ||
111 (!!this.options
["recycle"] && !this.options
["teleport"])
114 // Some variants do not store reserve state (Align4, Chakart...)
115 get hasReserveFen() {
116 return this.hasReserve
;
120 return !!this.options
["dark"];
123 // Some variants use only click information
128 // Some variants reveal moves only after both players played
133 // Some variants do not flip board as black
135 return (this.playerColor
== 'b');
138 // Some variants use click infos:
140 if (typeof coords
.x
!= "number")
141 return null; //click on reserves
143 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
144 this.board
[coords
.x
][coords
.y
] == ""
147 start: {x: this.captured
.x
, y: this.captured
.y
},
158 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
167 // 3a --> {x:3, y:10}
168 static SquareToCoords(sq
) {
169 return ArrayFun
.toObject(["x", "y"],
170 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
173 // {x:11, y:12} --> bc
174 static CoordsToSquare(cd
) {
175 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
178 // c10 --> 02 (assuming 10 rows)
179 static SquareFromUsual(sq
) {
181 (this.size
.x
- parseInt(sq
.substring(1), 10)).toString(36) +
182 (sq
.charCodeAt(0) - 97).toString(36)
187 static UsualFromSquare(sq
) {
189 String
.fromCharCode(parseInt(sq
.charAt(1), 36) + 97) +
190 (this.size
.x
- parseInt(sq
.charAt(0), 36)).toString(10)
195 if (typeof cd
.x
== "number") {
197 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
201 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
204 idToCoords(targetId
) {
206 return null; //outside page, maybe...
207 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
209 idParts
.length
< 2 ||
210 idParts
[0] != this.containerId
||
211 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
215 const squares
= idParts
[1].split('-');
216 if (squares
[0] == "sq")
217 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
218 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
219 return {x: squares
[1], y: squares
[2]};
225 // Turn "wb" into "B" (for FEN)
227 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
230 // Turn "p" into "bp" (for board)
232 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
235 genRandInitFen(seed
) {
236 Random
.setSeed(seed
); //may be unused
237 let baseFen
= this.genRandInitBaseFen();
238 baseFen
.o
= Object
.assign({init: true}, baseFen
.o
);
239 const parts
= this.getPartFen(baseFen
.o
);
241 baseFen
.fen
+ " w 0" +
242 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
246 // Setup the initial random-or-not (asymmetric-or-not) position
247 genRandInitBaseFen() {
248 const s
= FenUtil
.setupPieces(
249 ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
251 randomness: this.options
["randomness"],
252 between: [{p1: 'k', p2: 'r'}],
258 fen: s
.b
.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
259 s
.w
.join("").toUpperCase(),
264 // "Parse" FEN: just return untransformed string data
266 const fenParts
= fen
.split(" ");
268 position: fenParts
[0],
270 movesCount: fenParts
[2]
272 if (fenParts
.length
> 3)
273 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
277 // Return current fen (game state)
279 const parts
= this.getPartFen({});
282 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
287 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
293 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
294 if (this.hasEnpassant
)
295 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
296 if (this.hasReserveFen
)
297 parts
["reserve"] = this.getReserveFen(o
);
298 if (this.options
["crazyhouse"])
299 parts
["ispawn"] = this.getIspawnFen(o
);
303 static FenEmptySquares(count
) {
304 // if more than 9 consecutive free spaces, break the integer,
305 // otherwise FEN parsing will fail.
308 // Most boards of size < 18:
310 return "9" + (count
- 9);
312 return "99" + (count
- 18);
315 // Position part of the FEN string
318 for (let i
= 0; i
< this.size
.x
; i
++) {
320 for (let j
= 0; j
< this.size
.y
; j
++) {
321 if (this.board
[i
][j
] == "")
324 if (emptyCount
> 0) {
325 // Add empty squares in-between
326 position
+= C
.FenEmptySquares(emptyCount
);
329 position
+= this.board2fen(this.board
[i
][j
]);
334 position
+= C
.FenEmptySquares(emptyCount
);
335 if (i
< this.size
.x
- 1)
336 position
+= "/"; //separate rows
341 // Flags part of the FEN string
343 return ['w', 'b'].map(c
=> {
344 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
348 // Enpassant part of the FEN string
352 return C
.CoordsToSquare(this.epSquare
);
357 return Array(2 * V
.ReserveArray
.length
).fill('0').join("");
359 ['w', 'b'].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
365 // NOTE: cannot merge because this.ispawn doesn't exist yet
367 const squares
= Object
.keys(this.ispawn
);
368 if (squares
.length
== 0)
370 return squares
.join(",");
373 // Set flags from fen (castle: white a,h then black a,h)
376 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
377 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
385 this.options
= o
.options
;
386 // Fill missing options (always the case if random challenge)
387 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
388 if (this.options
[opt
.variable
] === undefined)
389 this.options
[opt
.variable
] = opt
.defaut
;
393 this.playerColor
= o
.color
;
394 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
395 this.containerId
= o
.element
;
396 this.isDiagram
= o
.diagram
;
397 this.marks
= o
.marks
;
401 o
.fen
= this.genRandInitFen(o
.seed
);
402 this.re_initFromFen(o
.fen
);
403 this.graphicalInit();
406 re_initFromFen(fen
, oldBoard
) {
407 const fenParsed
= this.parseFen(fen
);
408 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
409 this.turn
= fenParsed
.turn
;
410 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
411 this.setOtherVariables(fenParsed
);
414 // Turn position fen into double array ["wb","wp","bk",...]
416 const rows
= position
.split("/");
417 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
418 for (let i
= 0; i
< rows
.length
; i
++) {
420 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
421 const character
= rows
[i
][indexInRow
];
422 const num
= parseInt(character
, 10);
423 // If num is a number, just shift j:
426 // Else: something at position i,j
428 board
[i
][j
++] = this.fen2board(character
);
434 // Some additional variables from FEN (variant dependant)
435 setOtherVariables(fenParsed
) {
436 // Set flags and enpassant:
438 this.setFlags(fenParsed
.flags
);
439 if (this.hasEnpassant
)
440 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
441 if (this.hasReserve
&& !this.isDiagram
)
442 this.initReserves(fenParsed
.reserve
);
443 if (this.options
["crazyhouse"])
444 this.initIspawn(fenParsed
.ispawn
);
445 if (this.options
["teleport"]) {
446 this.subTurnTeleport
= 1;
447 this.captured
= null;
449 if (this.options
["dark"]) {
450 // Setup enlightened: squares reachable by player side
451 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
452 this.updateEnlightened();
454 this.subTurn
= 1; //may be unused
455 if (!this.moveStack
) //avoid resetting (unwanted)
459 // ordering as in pieces() p,r,n,b,q,k
460 static get ReserveArray() {
461 return ['p', 'r', 'n', 'b', 'q', 'k'];
464 initReserves(reserveStr
) {
465 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
466 const L
= V
.ReserveArray
.length
;
468 w: ArrayFun
.toObject(V
.ReserveArray
, counts
.slice(0, L
)),
469 b: ArrayFun
.toObject(V
.ReserveArray
, counts
.slice(L
, 2 * L
))
473 initIspawn(ispawnStr
) {
474 if (ispawnStr
!= "-")
475 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
483 getPieceWidth(rwidth
) {
484 return (rwidth
/ Math
.max(this.size
.x
, this.size
.y
));
487 getReserveSquareSize(rwidth
, nbR
) {
488 const sqSize
= this.getPieceWidth(rwidth
);
489 return Math
.min(sqSize
, rwidth
/ nbR
);
492 getReserveNumId(color
, piece
) {
493 return `${this.containerId}|rnum-${color}${piece}`;
496 getNbReservePieces(color
) {
498 Object
.values(this.reserve
[color
]).reduce(
499 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
503 getRankInReserve(c
, p
) {
504 const pieces
= Object
.keys(this.pieces(c
, c
, p
));
505 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
506 let toTest
= pieces
.slice(0, lastIndex
);
507 return toTest
.reduce(
508 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
511 static AddClass_es(elt
, class_es
) {
512 if (!Array
.isArray(class_es
))
513 class_es
= [class_es
];
514 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
517 static RemoveClass_es(elt
, class_es
) {
518 if (!Array
.isArray(class_es
))
519 class_es
= [class_es
];
520 class_es
.forEach(cl
=> elt
.classList
.remove(cl
));
523 // Generally light square bottom-right
524 getSquareColorClass(x
, y
) {
525 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
529 // Works for all rectangular boards:
530 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
534 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
541 const g_init
= () => {
542 this.re_drawBoardElements();
543 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
544 this.initMouseEvents();
546 let container
= document
.getElementById(this.containerId
);
547 this.windowResizeObs
= new ResizeObserver(g_init
);
548 this.windowResizeObs
.observe(container
);
551 re_drawBoardElements() {
552 const board
= this.getSvgChessboard();
553 const container
= document
.getElementById(this.containerId
);
554 const rc
= container
.getBoundingClientRect();
555 let chessboard
= container
.querySelector(".chessboard");
556 chessboard
.innerHTML
= "";
557 chessboard
.insertAdjacentHTML('beforeend', board
);
558 // Compare window ratio width / height to aspectRatio:
559 const windowRatio
= rc
.width
/ rc
.height
;
560 let cbWidth
, cbHeight
;
561 const vRatio
= this.size
.ratio
|| 1;
562 if (windowRatio
<= vRatio
) {
563 // Limiting dimension is width:
564 cbWidth
= Math
.min(rc
.width
, 767);
565 cbHeight
= cbWidth
/ vRatio
;
568 // Limiting dimension is height:
569 cbHeight
= Math
.min(rc
.height
, 767);
570 cbWidth
= cbHeight
* vRatio
;
572 if (this.hasReserve
&& !this.isDiagram
) {
573 const sqSize
= cbWidth
/ this.size
.y
;
574 // NOTE: allocate space for reserves (up/down) even if they are empty
575 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
576 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
577 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
578 cbWidth
= cbHeight
* vRatio
;
581 chessboard
.style
.width
= cbWidth
+ "px";
582 chessboard
.style
.height
= cbHeight
+ "px";
583 // Center chessboard:
584 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
585 spaceTop
= (rc
.height
- cbHeight
) / 2;
586 chessboard
.style
.left
= spaceLeft
+ "px";
587 chessboard
.style
.top
= spaceTop
+ "px";
588 // Give sizes instead of recomputing them,
589 // because chessboard might not be drawn yet.
590 this.setupVisualPieces({
598 // Get SVG board (background, no pieces)
602 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
603 class="chessboard_SVG">`;
604 board
+= this.getBaseSvgChessboard();
609 getBaseSvgChessboard() {
611 const flipped
= this.flippedBoard
;
612 for (let i
=0; i
< this.size
.x
; i
++) {
613 for (let j
=0; j
< this.size
.y
; j
++) {
614 if (!this.onBoard(i
, j
))
616 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
617 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
618 let classes
= this.getSquareColorClass(ii
, jj
);
619 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
620 classes
+= " in-shadow";
621 // NOTE: x / y reversed because coordinates system is reversed.
625 id="${this.coordsToId({x: ii, y: jj})}"
636 setupVisualPieces(r
) {
638 document
.getElementById(this.containerId
).querySelector(".chessboard");
640 r
= chessboard
.getBoundingClientRect();
641 const pieceWidth
= this.getPieceWidth(r
.width
);
642 const addPiece
= (i
, j
, arrName
, classes
) => {
643 this[arrName
][i
][j
] = document
.createElement("piece");
644 C
.AddClass_es(this[arrName
][i
][j
], classes
);
645 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
646 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
647 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
648 // Translate coordinates to use chessboard as reference:
649 this[arrName
][i
][j
].style
.transform
=
650 `translate(${ip - r.x}px,${jp - r.y}px)`;
651 chessboard
.appendChild(this[arrName
][i
][j
]);
653 const conditionalReset
= (arrName
) => {
655 // Refreshing: delete old pieces first. This isn't necessary,
656 // but simpler (this method isn't called many times)
657 for (let i
=0; i
<this.size
.x
; i
++) {
658 for (let j
=0; j
<this.size
.y
; j
++) {
659 if (this[arrName
][i
][j
]) {
660 this[arrName
][i
][j
].remove();
661 this[arrName
][i
][j
] = null;
667 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
668 if (arrName
== "d_pieces")
669 this.marks
.forEach((m
) => {
670 const formattedSquare
= C
.SquareFromUsual(m
);
671 const mCoords
= C
.SquareToCoords(formattedSquare
);
672 addPiece(mCoords
.x
, mCoords
.y
, arrName
, "mark");
676 conditionalReset("d_pieces");
677 conditionalReset("g_pieces");
678 for (let i
=0; i
< this.size
.x
; i
++) {
679 for (let j
=0; j
< this.size
.y
; j
++) {
680 if (this.board
[i
][j
] != "") {
681 const color
= this.getColor(i
, j
);
682 const piece
= this.getPiece(i
, j
);
683 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
684 this.g_pieces
[i
][j
].classList
.add(V
.GetColorClass(color
));
685 if (this.enlightened
&& !this.enlightened
[i
][j
])
686 this.g_pieces
[i
][j
].classList
.add("hidden");
688 if (this.marks
&& this.d_pieces
[i
][j
]) {
689 let classes
= ["mark"];
690 if (this.board
[i
][j
] != "")
691 classes
.push("transparent");
692 addPiece(i
, j
, "d_pieces", classes
);
696 if (this.hasReserve
&& !this.isDiagram
)
697 this.re_drawReserve(['w', 'b'], r
);
700 // NOTE: assume this.reserve != null
701 re_drawReserve(colors
, r
) {
703 // Remove (old) reserve pieces
704 for (let c
of colors
) {
705 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
706 this.r_pieces
[c
][p
].remove();
707 delete this.r_pieces
[c
][p
];
708 const numId
= this.getReserveNumId(c
, p
);
709 document
.getElementById(numId
).remove();
714 this.r_pieces
= { w: {}, b: {} };
715 let container
= document
.getElementById(this.containerId
);
717 r
= container
.querySelector(".chessboard").getBoundingClientRect();
718 for (let c
of colors
) {
719 let reservesDiv
= document
.getElementById("reserves_" + c
);
721 reservesDiv
.remove();
722 if (!this.reserve
[c
])
724 const nbR
= this.getNbReservePieces(c
);
727 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
729 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
730 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
731 let rcontainer
= document
.createElement("div");
732 rcontainer
.id
= "reserves_" + c
;
733 rcontainer
.classList
.add("reserves");
734 rcontainer
.style
.left
= i0
+ "px";
735 rcontainer
.style
.top
= j0
+ "px";
736 // NOTE: +1 fix display bug on Firefox at least
737 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
738 rcontainer
.style
.height
= sqResSize
+ "px";
739 container
.appendChild(rcontainer
);
740 for (let p
of Object
.keys(this.reserve
[c
])) {
741 if (this.reserve
[c
][p
] == 0)
743 let r_cell
= document
.createElement("div");
744 r_cell
.id
= this.coordsToId({x: c
, y: p
});
745 r_cell
.classList
.add("reserve-cell");
746 r_cell
.style
.width
= sqResSize
+ "px";
747 r_cell
.style
.height
= sqResSize
+ "px";
748 rcontainer
.appendChild(r_cell
);
749 let piece
= document
.createElement("piece");
750 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
751 piece
.classList
.add(V
.GetColorClass(c
));
752 piece
.style
.width
= "100%";
753 piece
.style
.height
= "100%";
754 this.r_pieces
[c
][p
] = piece
;
755 r_cell
.appendChild(piece
);
756 let number
= document
.createElement("div");
757 number
.textContent
= this.reserve
[c
][p
];
758 number
.classList
.add("reserve-num");
759 number
.id
= this.getReserveNumId(c
, p
);
760 const fontSize
= "1.3em";
761 number
.style
.fontSize
= fontSize
;
762 number
.style
.fontSize
= fontSize
;
763 r_cell
.appendChild(number
);
769 updateReserve(color
, piece
, count
) {
770 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
771 piece
= "k"; //capturing cannibal king: back to king form
772 const oldCount
= this.reserve
[color
][piece
];
773 this.reserve
[color
][piece
] = count
;
774 // Redrawing is much easier if count==0 (or undefined)
775 if ([oldCount
, count
].some(item
=> !item
))
776 this.re_drawReserve([color
]);
778 const numId
= this.getReserveNumId(color
, piece
);
779 document
.getElementById(numId
).textContent
= count
;
783 // Resize board: no need to destroy/recreate pieces
785 const container
= document
.getElementById(this.containerId
);
786 let chessboard
= container
.querySelector(".chessboard");
787 const rc
= container
.getBoundingClientRect(),
788 r
= chessboard
.getBoundingClientRect();
789 const multFact
= (mode
== "up" ? 1.05 : 0.95);
790 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
792 const vRatio
= this.size
.ratio
|| 1;
793 if (newWidth
> rc
.width
) {
795 newHeight
= newWidth
/ vRatio
;
797 if (newHeight
> rc
.height
) {
798 newHeight
= rc
.height
;
799 newWidth
= newHeight
* vRatio
;
801 chessboard
.style
.width
= newWidth
+ "px";
802 chessboard
.style
.height
= newHeight
+ "px";
803 const newX
= (rc
.width
- newWidth
) / 2;
804 chessboard
.style
.left
= newX
+ "px";
805 const newY
= (rc
.height
- newHeight
) / 2;
806 chessboard
.style
.top
= newY
+ "px";
807 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
808 const pieceWidth
= this.getPieceWidth(newWidth
);
809 // NOTE: next "if" for variants which use squares filling
810 // instead of "physical", moving pieces
812 for (let i
=0; i
< this.size
.x
; i
++) {
813 for (let j
=0; j
< this.size
.y
; j
++) {
814 if (this.g_pieces
[i
][j
]) {
815 // NOTE: could also use CSS transform "scale"
816 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
817 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
818 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
819 // Translate coordinates to use chessboard as reference:
820 this.g_pieces
[i
][j
].style
.transform
=
821 `translate(${ip - newX}px,${jp - newY}px)`;
827 this.rescaleReserve(newR
);
831 for (let c
of ['w','b']) {
832 if (!this.reserve
[c
])
834 const nbR
= this.getNbReservePieces(c
);
837 // Resize container first
838 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
839 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
840 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
841 let rcontainer
= document
.getElementById("reserves_" + c
);
842 rcontainer
.style
.left
= i0
+ "px";
843 rcontainer
.style
.top
= j0
+ "px";
844 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
845 rcontainer
.style
.height
= sqResSize
+ "px";
846 // And then reserve cells:
847 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
848 Object
.keys(this.reserve
[c
]).forEach(p
=> {
849 if (this.reserve
[c
][p
] == 0)
851 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
852 r_cell
.style
.width
= sqResSize
+ "px";
853 r_cell
.style
.height
= sqResSize
+ "px";
858 // Return the absolute pixel coordinates given current position.
859 // Our coordinate system differs from CSS one (x <--> y).
860 // We return here the CSS coordinates (more useful).
861 getPixelPosition(i
, j
, r
) {
863 return [0, 0]; //piece vanishes
865 if (typeof i
== "string") {
866 // Reserves: need to know the rank of piece
867 const nbR
= this.getNbReservePieces(i
);
868 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
869 x
= this.getRankInReserve(i
, j
) * rsqSize
;
870 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
873 const sqSize
= r
.width
/ Math
.max(this.size
.x
, this.size
.y
);
874 const flipped
= this.flippedBoard
;
875 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
+
876 Math
.abs(this.size
.x
- this.size
.y
) * sqSize
/ 2;
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
1009 // NOTE: not called if isDiagram
1011 let container
= document
.getElementById(this.containerId
);
1012 this.windowResizeObs
.unobserve(container
);
1013 if ('onmousedown' in window
) {
1014 this.mouseListeners
.forEach(ml
=> {
1015 document
.removeEventListener(ml
.type
, ml
.listener
);
1018 if ('ontouchstart' in window
) {
1019 this.touchListeners
.forEach(tl
=> {
1020 // https://stackoverflow.com/a/42509310/12660887
1021 document
.removeEventListener(tl
.type
, tl
.listener
);
1026 showChoices(moves
, r
) {
1027 let container
= document
.getElementById(this.containerId
);
1028 let chessboard
= container
.querySelector(".chessboard");
1029 let choices
= document
.createElement("div");
1030 choices
.id
= "choices";
1032 r
= chessboard
.getBoundingClientRect();
1033 choices
.style
.width
= r
.width
+ "px";
1034 choices
.style
.height
= r
.height
+ "px";
1035 choices
.style
.left
= r
.x
+ "px";
1036 choices
.style
.top
= r
.y
+ "px";
1037 chessboard
.style
.opacity
= "0.5";
1038 container
.appendChild(choices
);
1039 const squareWidth
= r
.width
/ this.size
.y
;
1040 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1041 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1042 const color
= moves
[0].appear
[0].c
;
1043 const callback
= (m
) => {
1044 chessboard
.style
.opacity
= "1";
1045 container
.removeChild(choices
);
1046 this.buildMoveStack(m
, r
);
1048 for (let i
=0; i
< moves
.length
; i
++) {
1049 let choice
= document
.createElement("div");
1050 choice
.classList
.add("choice");
1051 choice
.style
.width
= squareWidth
+ "px";
1052 choice
.style
.height
= squareWidth
+ "px";
1053 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1054 choice
.style
.top
= firstUpTop
+ "px";
1055 choice
.style
.backgroundColor
= "lightyellow";
1056 choice
.onclick
= () => callback(moves
[i
]);
1057 const piece
= document
.createElement("piece");
1058 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1059 C
.AddClass_es(piece
,
1060 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1061 piece
.classList
.add(V
.GetColorClass(color
));
1062 piece
.style
.width
= "100%";
1063 piece
.style
.height
= "100%";
1064 choice
.appendChild(piece
);
1065 choices
.appendChild(choice
);
1069 displayMessage(elt
, msg
, classe_s
, timeout
) {
1071 // Fixed element, e.g. for Dice Chess
1072 elt
.innerHTML
= msg
;
1074 // Temporary div (Chakart, Apocalypse...)
1075 let divMsg
= document
.createElement("div");
1076 C
.AddClass_es(divMsg
, classe_s
);
1077 divMsg
.innerHTML
= msg
;
1078 let container
= document
.getElementById(this.containerId
);
1079 container
.appendChild(divMsg
);
1080 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1087 updateEnlightened() {
1088 this.oldEnlightened
= this.enlightened
;
1089 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1090 // Add pieces positions + all squares reachable by moves (includes Zen):
1091 for (let x
=0; x
<this.size
.x
; x
++) {
1092 for (let y
=0; y
<this.size
.y
; y
++) {
1093 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1095 this.enlightened
[x
][y
] = true;
1096 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1097 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1103 this.enlightEnpassant();
1106 // Include square of the en-passant capturing square:
1107 enlightEnpassant() {
1108 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1109 // TODO: (0, 0) is wrong, would need to place an attacker here...
1110 const steps
= this.pieces(this.playerColor
, 0, 0)["p"].attack
[0].steps
;
1111 for (let step
of steps
) {
1112 const x
= this.epSquare
.x
- step
[0], //NOTE: epSquare.x not on edge
1113 y
= this.getY(this.epSquare
.y
- step
[1]);
1115 this.onBoard(x
, y
) &&
1116 this.getColor(x
, y
) == this.playerColor
&&
1117 this.getPieceType(x
, y
) == "p"
1119 this.enlightened
[x
][this.epSquare
.y
] = true;
1125 // Apply diff this.enlightened --> oldEnlightened on board
1126 graphUpdateEnlightened() {
1128 document
.getElementById(this.containerId
).querySelector(".chessboard");
1129 const r
= chessboard
.getBoundingClientRect();
1130 const pieceWidth
= this.getPieceWidth(r
.width
);
1131 for (let x
=0; x
<this.size
.x
; x
++) {
1132 for (let y
=0; y
<this.size
.y
; y
++) {
1133 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1134 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1135 elt
.classList
.add("in-shadow");
1136 if (this.g_pieces
[x
][y
])
1137 this.g_pieces
[x
][y
].classList
.add("hidden");
1139 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1140 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1141 elt
.classList
.remove("in-shadow");
1142 if (this.g_pieces
[x
][y
])
1143 this.g_pieces
[x
][y
].classList
.remove("hidden");
1156 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1160 // Color of thing on square (i,j). '' if square is empty
1162 if (typeof i
== "string")
1163 return i
; //reserves
1164 return this.board
[i
][j
].charAt(0);
1167 static GetColorClass(c
) {
1172 return "other-color"; //unidentified color
1175 // Piece on i,j. '' if square is empty
1177 if (typeof j
== "string")
1178 return j
; //reserves
1179 return this.board
[i
][j
].charAt(1);
1182 // Piece type on square (i,j)
1183 getPieceType(x
, y
, p
) {
1185 p
= this.getPiece(x
, y
);
1186 return this.pieces(this.getColor(x
, y
), x
, y
)[p
].moveas
|| p
;
1191 p
= this.getPiece(x
, y
);
1192 if (!this.options
["cannibal"])
1194 return !!C
.CannibalKings
[p
];
1197 static GetOppTurn(color
) {
1198 return (color
== 'w' ? 'b' : 'w');
1201 // Get opponent color(s): may differ from turn (e.g. Checkered)
1203 return (color
== "w" ? "b" : "w");
1206 // Is (x,y) on the chessboard?
1208 return (x
>= 0 && x
< this.size
.x
&&
1209 y
>= 0 && y
< this.size
.y
);
1212 // Am I allowed to move thing at square x,y ?
1214 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1217 ////////////////////////
1218 // PIECES SPECIFICATIONS
1220 getPawnShift(color
) {
1221 return (color
== "w" ? -1 : 1);
1223 isPawnInitRank(x
, color
) {
1224 return (color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1);
1227 pieces(color
, x
, y
) {
1228 const pawnShift
= this.getPawnShift(color
|| 'w');
1234 steps: [[pawnShift
, 0]],
1235 range: (this.isPawnInitRank(x
, color
) ? 2 : 1)
1240 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1248 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1256 [1, 2], [1, -2], [-1, 2], [-1, -2],
1257 [2, 1], [-2, 1], [2, -1], [-2, -1]
1266 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1274 [0, 1], [0, -1], [1, 0], [-1, 0],
1275 [1, 1], [1, -1], [-1, 1], [-1, -1]
1285 [0, 1], [0, -1], [1, 0], [-1, 0],
1286 [1, 1], [1, -1], [-1, 1], [-1, -1]
1293 '!': {"class": "king-pawn", moveas: "p"},
1294 '#': {"class": "king-rook", moveas: "r"},
1295 '$': {"class": "king-knight", moveas: "n"},
1296 '%': {"class": "king-bishop", moveas: "b"},
1297 '*': {"class": "king-queen", moveas: "q"}
1301 // NOTE: using special symbols to not interfere with variants' pieces codes
1302 static get CannibalKings() {
1313 static get CannibalKingCode() {
1324 //////////////////////////
1325 // MOVES GENERATION UTILS
1327 // For Cylinder: get Y coordinate
1329 if (!this.options
["cylinder"])
1331 let res
= y
% this.size
.y
;
1338 return x
; //generally, no
1341 increment([x
, y
], step
) {
1343 this.getX(x
+ step
[0]),
1344 this.getY(y
+ step
[1])
1348 getSegments(curSeg
, segStart
, segEnd
) {
1349 if (curSeg
.length
== 0)
1351 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1352 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1356 getStepSpec(color
, x
, y
, piece
) {
1357 let pieceType
= piece
;
1358 let allSpecs
= this.pieces(color
, x
, y
);
1360 pieceType
= this.getPieceType(x
, y
);
1361 else if (allSpecs
[piece
].moveas
)
1362 pieceType
= allSpecs
[piece
].moveas
;
1363 let res
= allSpecs
[pieceType
];
1373 // Can thing on square1 capture thing on square2?
1374 canTake([x1
, y1
], [x2
, y2
]) {
1375 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1378 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
1379 canSelfTake([x1
, y1
], [x2
, y2
]) {
1380 return !this.isKing(x2
, y2
);
1383 canStepOver(i
, j
, p
) {
1384 // In some variants, objects on boards don't stop movement (Chakart)
1385 return this.board
[i
][j
] == "";
1388 canDrop([c
, p
], [i
, j
]) {
1390 this.board
[i
][j
] == "" &&
1391 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1394 (c
== 'w' && i
< this.size
.x
- 1) ||
1401 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1402 isImmobilized([x
, y
]) {
1403 if (!this.options
["madrasi"])
1405 const color
= this.getColor(x
, y
);
1406 const oppCols
= this.getOppCols(color
);
1407 const piece
= this.getPieceType(x
, y
);
1408 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1409 const attacks
= stepSpec
.both
.concat(stepSpec
.attack
);
1410 for (let a
of attacks
) {
1411 outerLoop: for (let step
of a
.steps
) {
1412 let [i
, j
] = this.increment([x
, y
], step
);
1413 let stepCounter
= 0;
1414 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1415 if (a
.range
<= stepCounter
++)
1417 [i
, j
] = this.increment([i
, j
], step
);
1420 this.onBoard(i
, j
) &&
1421 oppCols
.includes(this.getColor(i
, j
)) &&
1422 this.getPieceType(i
, j
) == piece
1431 // Stop at the first capture found
1432 atLeastOneCapture(color
) {
1433 const allowed
= (sq1
, sq2
) => {
1435 // NOTE: canTake is reversed for Zen.
1436 // Generally ok because of the symmetry. TODO?
1437 this.canTake(sq1
, sq2
) &&
1439 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1442 for (let i
=0; i
<this.size
.x
; i
++) {
1443 for (let j
=0; j
<this.size
.y
; j
++) {
1444 if (this.getColor(i
, j
) == color
) {
1447 !this.options
["zen"] &&
1448 this.findDestSquares(
1460 this.options
["zen"] &&
1461 this.findCapturesOn(
1477 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1478 const epsilon
= 1e-7; //arbitrary small value
1480 if (this.options
["cylinder"])
1481 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1482 for (let sh
of shifts
) {
1483 const rx
= (x2
- x1
) / step
[0],
1484 ry
= (y2
+ sh
- y1
) / step
[1];
1486 // Zero step but non-zero interval => impossible
1487 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1488 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1489 // Negative number of step (impossible)
1490 (rx
< 0 || ry
< 0) ||
1491 // Not the same number of steps in both directions:
1492 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1496 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1497 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1499 distance
= Math
.round(distance
); //in case of (numerical...)
1500 if (!range
|| range
>= distance
)
1506 ////////////////////
1509 getDropMovesFrom([c
, p
]) {
1510 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1511 // (but not necessarily otherwise: atLeastOneMove() etc)
1512 if (this.reserve
[c
][p
] == 0)
1515 for (let i
=0; i
<this.size
.x
; i
++) {
1516 for (let j
=0; j
<this.size
.y
; j
++) {
1517 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1519 start: {x: c
, y: p
},
1521 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1524 if (this.board
[i
][j
] != "") {
1525 mv
.vanish
.push(new PiPo({
1528 c: this.getColor(i
, j
),
1529 p: this.getPiece(i
, j
)
1539 // All possible moves from selected square
1540 // TODO: generalize usage if arg "color" (e.g. Checkered)
1541 getPotentialMovesFrom([x
, y
], color
) {
1542 if (this.subTurnTeleport
== 2)
1544 if (typeof x
== "string")
1545 return this.getDropMovesFrom([x
, y
]);
1546 if (this.isImmobilized([x
, y
]))
1548 const piece
= this.getPieceType(x
, y
);
1549 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1550 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1551 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1552 if (this.isKing(0, 0, piece
) && this.hasCastle
)
1553 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1554 return this.postProcessPotentialMoves(moves
);
1557 postProcessPotentialMoves(moves
) {
1558 if (moves
.length
== 0)
1560 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1561 const oppCols
= this.getOppCols(color
);
1563 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1564 moves
= this.capturePostProcess(moves
, oppCols
);
1566 if (this.options
["atomic"])
1567 moves
= this.atomicPostProcess(moves
, color
, oppCols
);
1571 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1573 moves
= this.pawnPostProcess(moves
, color
, oppCols
);
1576 if (this.options
["cannibal"] && this.options
["rifle"])
1577 // In this case a rifle-capture from last rank may promote a pawn
1578 moves
= this.riflePromotePostProcess(moves
, color
);
1583 capturePostProcess(moves
, oppCols
) {
1584 // Filter out non-capturing moves (not using m.vanish because of
1585 // self captures of Recycle and Teleport).
1586 return moves
.filter(m
=> {
1588 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1589 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1594 atomicPostProcess(moves
, color
, oppCols
) {
1595 moves
.forEach(m
=> {
1597 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1598 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1611 let mNext
= new Move({
1617 for (let step
of steps
) {
1618 let [x
, y
] = this.increment([m
.end
.x
, m
.end
.y
], step
);
1620 this.onBoard(x
, y
) &&
1621 this.board
[x
][y
] != "" &&
1622 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1623 this.getPieceType(x
, y
) != "p"
1627 p: this.getPiece(x
, y
),
1628 c: this.getColor(x
, y
),
1635 if (!this.options
["rifle"]) {
1636 // The moving piece also vanish
1637 mNext
.vanish
.unshift(
1642 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1652 pawnPostProcess(moves
, color
, oppCols
) {
1654 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1655 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1656 moves
.forEach(m
=> {
1657 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1658 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1659 const promotionOk
= (
1661 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1664 return; //nothing to do
1665 if (this.options
["pawnfall"]) {
1671 this.options
["cannibal"] &&
1672 this.board
[x2
][y2
] != "" &&
1673 oppCols
.includes(this.getColor(x2
, y2
))
1675 finalPieces
= [this.getPieceType(x2
, y2
)];
1678 finalPieces
= this.pawnPromotions
;
1679 m
.appear
[0].p
= finalPieces
[0];
1680 if (initPiece
== "!") //cannibal king-pawn
1681 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1682 for (let i
=1; i
<finalPieces
.length
; i
++) {
1683 let newMove
= JSON
.parse(JSON
.stringify(m
));
1684 const piece
= finalPieces
[i
];
1685 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1686 moreMoves
.push(newMove
);
1689 return moves
.concat(moreMoves
);
1692 riflePromotePostProcess(moves
, color
) {
1693 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1695 moves
.forEach(m
=> {
1697 m
.start
.x
== lastRank
&&
1698 m
.appear
.length
>= 1 &&
1699 m
.appear
[0].p
== "p" &&
1700 m
.appear
[0].x
== m
.start
.x
&&
1701 m
.appear
[0].y
== m
.start
.y
1703 m
.appear
[0].p
= this.pawnPromotions
[0];
1704 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1705 let newMv
= JSON
.parse(JSON
.stringify(m
));
1706 newMv
.appear
[0].p
= this.pawnPromotions
[i
];
1707 newMoves
.push(newMv
);
1711 return moves
.concat(newMoves
);
1714 // Generic method to find possible moves of "sliding or jumping" pieces
1715 getPotentialMovesOf(piece
, [x
, y
]) {
1716 const color
= this.getColor(x
, y
);
1717 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1719 if (stepSpec
.attack
) {
1720 squares
= this.findDestSquares(
1726 ([i1
, j1
], [i2
, j2
]) => {
1728 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1729 this.canTake([i1
, j1
], [i2
, j2
])
1734 const noSpecials
= this.findDestSquares(
1737 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1741 Array
.prototype.push
.apply(squares
, noSpecials
);
1742 if (this.options
["zen"]) {
1743 let zenCaptures
= this.findCapturesOn(
1745 {}, //byCol: default is ok
1746 ([i1
, j1
], [i2
, j2
]) =>
1747 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1749 // Technical step: segments (if any) are reversed
1750 zenCaptures
.forEach(z
=> {
1752 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1754 Array
.prototype.push
.apply(squares
, zenCaptures
);
1756 if (this.hasSelfCaptures
) {
1757 const selfCaptures
= this.findDestSquares(
1763 ([i1
, j1
], [i2
, j2
]) => {
1765 this.getColor(i2
, j2
) == color
&&
1766 this.canSelfTake([i1
, j1
], [i2
, j2
])
1770 Array
.prototype.push
.apply(squares
, selfCaptures
);
1772 return squares
.map(s
=> {
1773 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1775 mv
.segments
= s
.segments
;
1780 findDestSquares([x
, y
], o
, allowed
) {
1782 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1783 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1785 // Next 3 for Cylinder mode or circular (useless otherwise)
1789 const addSquare
= ([i
, j
]) => {
1790 let elt
= {sq: [i
, j
]};
1791 if (segments
.length
>= 1)
1792 elt
.segments
= this.getSegments(segments
, segStart
, [i
, j
]);
1795 const exploreSteps
= (stepArray
, mode
) => {
1796 for (let s
of stepArray
) {
1797 outerLoop: for (let step
of s
.steps
) {
1800 let [i
, j
] = [x
, y
];
1801 let stepCounter
= 0;
1803 this.onBoard(i
, j
) &&
1804 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1806 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1807 explored
[i
+ "." + j
] = true;
1810 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1812 if (o
.one
&& mode
!= "attack")
1814 if (mode
!= "attack")
1815 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1816 if (o
.captureTarget
)
1820 if (s
.range
<= stepCounter
++)
1822 const oldIJ
= [i
, j
];
1823 [i
, j
] = this.increment([i
, j
], step
);
1825 Math
.abs(i
- oldIJ
[0]) != Math
.abs(step
[0]) ||
1826 Math
.abs(j
- oldIJ
[1]) != Math
.abs(step
[1])
1828 // Boundary between segments (cylinder or circular mode)
1829 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1833 if (!this.onBoard(i
, j
))
1835 const pieceIJ
= this.getPieceType(i
, j
);
1836 if (!explored
[i
+ "." + j
]) {
1837 explored
[i
+ "." + j
] = true;
1838 if (allowed([x
, y
], [i
, j
])) {
1839 if (o
.one
&& mode
!= "moves")
1841 if (mode
!= "moves")
1842 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1845 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1853 return undefined; //default, but let's explicit it
1855 if (o
.captureTarget
)
1856 return exploreSteps(o
.captureSteps
, "attack");
1859 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1862 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.moves
), "moves");
1863 if (!outOne
&& !o
.moveOnly
)
1864 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.attack
), "attack");
1865 return (o
.one
? outOne : res
);
1869 // Search for enemy (or not) pieces attacking [x, y]
1870 findCapturesOn([x
, y
], o
, allowed
) {
1872 o
.byCol
= this.getOppCols(this.getColor(x
, y
) || this.turn
);
1874 for (let i
=0; i
<this.size
.x
; i
++) {
1875 for (let j
=0; j
<this.size
.y
; j
++) {
1876 const colIJ
= this.getColor(i
, j
);
1878 this.board
[i
][j
] != "" &&
1879 o
.byCol
.includes(colIJ
) &&
1880 !this.isImmobilized([i
, j
])
1882 const apparentPiece
= this.getPiece(i
, j
);
1883 // Quick check: does this potential attacker target x,y ?
1884 if (this.canStepOver(x
, y
, apparentPiece
))
1886 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1887 const attacks
= stepSpec
.attack
.concat(stepSpec
.both
);
1888 for (let a
of attacks
) {
1889 for (let s
of a
.steps
) {
1890 // Quick check: if step isn't compatible, don't even try
1891 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1893 // Finally verify that nothing stand in-between
1894 const out
= this.findDestSquares(
1897 captureTarget: [x
, y
],
1898 captureSteps: [{steps: [s
], range: a
.range
}],
1912 return (o
.one
? false : res
);
1915 // Build a regular move from its initial and destination squares.
1916 // tr: transformation
1917 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1918 const initColor
= this.getColor(sx
, sy
);
1919 const initPiece
= this.getPiece(sx
, sy
);
1920 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1924 start: {x: sx
, y: sy
},
1928 !this.options
["rifle"] ||
1929 this.board
[ex
][ey
] == "" ||
1930 destColor
== initColor
//Recycle, Teleport
1936 c: !!tr
? tr
.c : initColor
,
1937 p: !!tr
? tr
.p : initPiece
1949 if (this.board
[ex
][ey
] != "") {
1954 c: this.getColor(ex
, ey
),
1955 p: this.getPiece(ex
, ey
)
1958 if (this.options
["cannibal"] && destColor
!= initColor
) {
1959 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1960 let trPiece
= mv
.vanish
[lastIdx
].p
;
1961 if (this.isKing(sx
, sy
))
1962 trPiece
= C
.CannibalKingCode
[trPiece
];
1963 if (mv
.appear
.length
>= 1)
1964 mv
.appear
[0].p
= trPiece
;
1965 else if (this.options
["rifle"]) {
1988 // En-passant square, if any
1989 getEpSquare(moveOrSquare
) {
1990 if (typeof moveOrSquare
=== "string") {
1991 const square
= moveOrSquare
;
1994 return C
.SquareToCoords(square
);
1996 // Argument is a move:
1997 const move = moveOrSquare
;
1998 const s
= move.start
,
2002 Math
.abs(s
.x
- e
.x
) == 2 &&
2003 // Next conditions for variants like Atomic or Rifle, Recycle...
2005 move.appear
.length
> 0 &&
2006 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
2010 move.vanish
.length
> 0 &&
2011 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
2019 return undefined; //default
2022 // Special case of en-passant captures: treated separately
2023 getEnpassantCaptures([x
, y
]) {
2024 const color
= this.getColor(x
, y
);
2025 const shiftX
= (color
== 'w' ? -1 : 1);
2026 const oppCols
= this.getOppCols(color
);
2029 this.epSquare
.x
== x
+ shiftX
&& //NOTE: epSquare.x not on edge
2030 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2031 // Doublemove (and Progressive?) guards:
2032 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2033 oppCols
.includes(this.getColor(x
, this.epSquare
.y
))
2035 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2036 this.board
[epx
][epy
] = this.board
[x
][this.epSquare
.y
];
2037 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2038 this.board
[epx
][epy
] = "";
2039 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2040 enpassantMove
.vanish
[lastIdx
].x
= x
;
2041 return [enpassantMove
];
2046 getCastleMoves([x
, y
], finalSquares
, castleWith
, castleFlags
) {
2047 const c
= this.getColor(x
, y
);
2048 castleFlags
= castleFlags
|| this.castleFlags
[c
];
2051 const oppCols
= this.getOppCols(c
);
2055 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2056 const castlingKing
= this.getPiece(x
, y
);
2057 castlingCheck: for (
2060 castleSide
++ //large, then small
2062 if (castleFlags
[castleSide
] >= this.size
.y
)
2064 // If this code is reached, rook and king are on initial position
2066 // NOTE: in some variants this is not a rook
2067 const rookPos
= castleFlags
[castleSide
];
2068 const castlingPiece
= this.getPiece(x
, rookPos
);
2070 this.board
[x
][rookPos
] == "" ||
2071 this.getColor(x
, rookPos
) != c
||
2072 (castleWith
&& !castleWith
.includes(castlingPiece
))
2074 // Rook is not here, or changed color (see Benedict)
2077 // Nothing on the path of the king ? (and no checks)
2078 const finDist
= finalSquares
[castleSide
][0] - y
;
2079 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2083 // NOTE: next weird test because underCheck() verification
2084 // will be executed in filterValid() later.
2086 i
!= finalSquares
[castleSide
][0] &&
2087 this.underCheck([[x
, i
]], oppCols
)
2091 this.board
[x
][i
] != "" &&
2092 // NOTE: next check is enough, because of chessboard constraints
2093 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2096 continue castlingCheck
;
2099 } while (i
!= finalSquares
[castleSide
][0]);
2100 // Nothing on the path to the rook?
2101 step
= (castleSide
== 0 ? -1 : 1);
2102 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2103 if (this.board
[x
][i
] != "")
2104 continue castlingCheck
;
2107 // Nothing on final squares, except maybe king and castling rook?
2108 for (i
= 0; i
< 2; i
++) {
2110 finalSquares
[castleSide
][i
] != rookPos
&&
2111 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2113 finalSquares
[castleSide
][i
] != y
||
2114 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2117 continue castlingCheck
;
2121 // If this code is reached, castle is potentially valid
2127 y: finalSquares
[castleSide
][0],
2133 y: finalSquares
[castleSide
][1],
2139 // King might be initially disguised (Titan...)
2140 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2141 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2144 Math
.abs(y
- rookPos
) <= 2
2145 ? {x: x
, y: rookPos
}
2146 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2154 ////////////////////
2157 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2158 underAttack([x
, y
], oppCols
) {
2159 // An empty square is considered as king,
2160 // since it's used only in getCastleMoves (TODO?)
2161 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2164 (!this.options
["zen"] || king
) &&
2165 this.findCapturesOn(
2175 (!!this.options
["zen"] && !king
) &&
2176 this.findDestSquares(
2182 ([i1
, j1
], [i2
, j2
]) => oppCols
.includes(this.getColor(i2
, j2
))
2188 // Argument is (very generally) an array of squares (= arrays)
2189 underCheck(square_s
, oppCols
) {
2190 if (this.options
["taking"] || this.options
["dark"])
2192 return square_s
.some(sq
=> this.underAttack(sq
, oppCols
));
2195 // Scan board for king(s)
2196 searchKingPos(color
) {
2198 for (let i
=0; i
< this.size
.x
; i
++) {
2199 for (let j
=0; j
< this.size
.y
; j
++) {
2200 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2207 // cb: callback returning a boolean (false if king missing)
2208 trackKingWrap(move, kingPos
, cb
) {
2209 if (move.appear
.length
== 0 && move.vanish
.length
== 0)
2212 (move.vanish
.length
> 0 ? move.vanish
[0].c : move.appear
[0].c
);
2213 let newKingPP
= null,
2215 res
= true; //a priori valid
2217 move.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2219 // Search king in appear array:
2221 move.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2223 sqIdx
= kingPos
.findIndex(kp
=>
2224 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2225 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2228 res
= false; //king vanished
2230 res
&&= cb(kingPos
);
2231 if (oldKingPP
&& newKingPP
)
2232 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2236 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2237 filterValid(moves
, color
) {
2240 const oppCols
= this.getOppCols(color
);
2241 let kingPos
= this.searchKingPos(color
);
2242 return moves
.filter(m
=> {
2243 this.playOnBoard(m
);
2244 const res
= this.trackKingWrap(m
, kingPos
, (kp
) => {
2245 return !this.underCheck(kp
, oppCols
);
2247 this.undoOnBoard(m
);
2255 // Apply a move on board
2257 for (let psq
of move.vanish
)
2258 this.board
[psq
.x
][psq
.y
] = "";
2259 for (let psq
of move.appear
)
2260 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2262 // Un-apply the played move
2264 for (let psq
of move.appear
)
2265 this.board
[psq
.x
][psq
.y
] = "";
2266 for (let psq
of move.vanish
)
2267 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2270 // NOTE: arg "castleFlags" for Coregal or Twokings
2271 updateCastleFlags(move, castleFlags
, king
) {
2272 castleFlags
= castleFlags
|| this.castleFlags
;
2273 // If flags already off, no need to re-check:
2275 Object
.values(castleFlags
).every(cvals
=>
2276 cvals
.every(val
=> val
>= this.size
.y
))
2280 // Update castling flags if start or arrive from/at rook/king locations
2281 move.appear
.concat(move.vanish
).forEach(psq
=> {
2282 if ((king
&& psq
.p
== king
) || (!king
&& this.isKing(0, 0, psq
.p
)))
2283 castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2284 // NOTE: not "else if" because king can capture enemy rook...
2288 else if (psq
.x
== this.size
.x
- 1)
2291 const fidx
= castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2293 castleFlags
[c
][fidx
] = this.size
.y
;
2300 this.updateCastleFlags(move);
2301 if (this.options
["crazyhouse"]) {
2302 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2303 // Assumption: something is moving
2304 const initSquare
= C
.CoordsToSquare(move.start
);
2305 const destSquare
= C
.CoordsToSquare(move.end
);
2307 this.ispawn
[initSquare
] ||
2308 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2310 this.ispawn
[destSquare
] = true;
2313 this.ispawn
[destSquare
] &&
2314 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2316 move.vanish
[1].p
= 'p';
2317 delete this.ispawn
[destSquare
];
2320 move.vanish
.forEach(v
=> {
2321 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2322 if (this.ispawn
[square
])
2323 delete this.ispawn
[square
];
2326 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2329 // Warning; atomic pawn removal isn't a capture
2330 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2332 const color
= this.turn
;
2333 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2334 // Something appears = dropped on board (some exceptions, Chakart...)
2335 if (move.appear
[i
].c
== color
) {
2336 const piece
= move.appear
[i
].p
;
2337 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2340 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2341 // Something vanish: add to reserve except if recycle & opponent
2343 this.options
["crazyhouse"] ||
2344 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2346 const piece
= move.vanish
[i
].p
;
2347 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2355 if (this.hasEnpassant
)
2356 this.epSquare
= this.getEpSquare(move);
2357 this.playOnBoard(move);
2358 this.postPlay(move);
2362 if (this.options
["dark"])
2363 this.updateEnlightened();
2364 if (this.options
["teleport"]) {
2366 this.subTurnTeleport
== 1 &&
2367 move.vanish
.length
== 2 &&
2368 move.appear
.length
== 1 &&
2369 move.vanish
[1].c
== this.turn
2371 const v
= move.vanish
[1];
2372 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2373 this.subTurnTeleport
= 2;
2376 this.subTurnTeleport
= 1;
2377 this.captured
= null;
2379 this.tryChangeTurn(move);
2382 tryChangeTurn(move) {
2383 if (this.isLastMove(move)) {
2384 this.turn
= C
.GetOppTurn(this.turn
);
2388 else if (!move.next
)
2395 const color
= this.turn
;
2396 const oppKingPos
= this.searchKingPos(C
.GetOppTurn(color
));
2397 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, [color
]))
2401 !this.options
["balance"] ||
2402 ![1, 2].includes(this.movesCount
) ||
2407 !this.options
["doublemove"] ||
2408 this.movesCount
== 0 ||
2413 !this.options
["progressive"] ||
2414 this.subTurn
== this.movesCount
+ 1
2419 // "Stop at the first move found"
2420 atLeastOneMove(color
) {
2421 for (let i
= 0; i
< this.size
.x
; i
++) {
2422 for (let j
= 0; j
< this.size
.y
; j
++) {
2423 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2424 // NOTE: in fact searching for all potential moves from i,j.
2425 // I don't believe this is an issue, for now at least.
2426 const moves
= this.getPotentialMovesFrom([i
, j
], color
);
2427 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2432 if (this.hasReserve
&& this.reserve
[color
]) {
2433 for (let p
of Object
.keys(this.reserve
[color
])) {
2434 const moves
= this.getDropMovesFrom([color
, p
]);
2435 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2442 // What is the score ? (Interesting if game is over)
2443 getCurrentScore(move_s
) {
2444 const move = move_s
[move_s
.length
- 1];
2445 // Shortcut in case the score was computed before:
2448 const oppTurn
= C
.GetOppTurn(this.turn
);
2450 w: this.searchKingPos('w'),
2451 b: this.searchKingPos('b')
2453 if (kingPos
[this.turn
].length
== 0 && kingPos
[oppTurn
].length
== 0)
2455 if (kingPos
[this.turn
].length
== 0)
2456 return (this.turn
== "w" ? "0-1" : "1-0");
2457 if (kingPos
[oppTurn
].length
== 0)
2458 return (this.turn
== "w" ? "1-0" : "0-1");
2459 if (this.atLeastOneMove(this.turn
))
2461 // No valid move: stalemate or checkmate?
2462 if (!this.underCheck(kingPos
[this.turn
], this.getOppCols(this.turn
)))
2465 return (this.turn
== "w" ? "0-1" : "1-0");
2468 playVisual(move, r
) {
2469 move.vanish
.forEach(v
=> {
2470 if (this.g_pieces
[v
.x
][v
.y
]) //can be null (e.g. Apocalypse)
2471 this.g_pieces
[v
.x
][v
.y
].remove();
2472 this.g_pieces
[v
.x
][v
.y
] = null;
2475 document
.getElementById(this.containerId
).querySelector(".chessboard");
2477 r
= chessboard
.getBoundingClientRect();
2478 const pieceWidth
= this.getPieceWidth(r
.width
);
2479 move.appear
.forEach(a
=> {
2480 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2481 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2482 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2483 this.g_pieces
[a
.x
][a
.y
].classList
.add(V
.GetColorClass(a
.c
));
2484 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2485 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2486 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2487 // Translate coordinates to use chessboard as reference:
2488 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2489 `translate(${ip - r.x}px,${jp - r.y}px)`;
2490 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2491 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2492 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2494 if (this.options
["dark"])
2495 this.graphUpdateEnlightened();
2498 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2499 buildMoveStack(move, r
) {
2500 this.moveStack
.push(move);
2501 this.computeNextMove(move);
2502 const then
= () => {
2503 const newTurn
= this.turn
;
2504 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2505 this.playVisual(move, r
);
2509 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2511 this.buildMoveStack(move.next
, r
);
2514 if (this.moveStack
.length
== 1) {
2515 // Usual case (one normal move)
2516 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2517 this.moveStack
= [];
2520 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2521 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2522 this.playReceivedMove(this.moveStack
.slice(1), () => {
2523 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2524 this.moveStack
= [];
2529 // If hiding moves, then they are revealed in play() with callback
2530 this.play(move, this.hideMoves
? then : null);
2531 if (!this.hideMoves
)
2535 // Implemented in variants using (automatic) moveStack
2536 computeNextMove(move) {}
2538 animateMoving(start
, end
, drag
, segments
, cb
) {
2539 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2540 if (!initPiece
) { //TODO: shouldn't occur!
2544 // NOTE: cloning often not required, but light enough, and simpler
2545 let movingPiece
= initPiece
.cloneNode();
2546 initPiece
.style
.opacity
= "0";
2548 document
.getElementById(this.containerId
)
2549 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2550 if (typeof start
.x
== "string") {
2551 // Need to bound width/height (was 100% for reserve pieces)
2552 const pieceWidth
= this.getPieceWidth(r
.width
);
2553 movingPiece
.style
.width
= pieceWidth
+ "px";
2554 movingPiece
.style
.height
= pieceWidth
+ "px";
2556 const maxDist
= this.getMaxDistance(r
);
2557 const apparentColor
= this.getColor(start
.x
, start
.y
);
2558 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2560 const startCode
= this.getPiece(start
.x
, start
.y
);
2561 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2562 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2563 if (apparentColor
!= drag
.c
) {
2564 movingPiece
.classList
.remove(V
.GetColorClass(apparentColor
));
2565 movingPiece
.classList
.add(V
.GetColorClass(drag
.c
));
2568 container
.appendChild(movingPiece
);
2569 const animateSegment
= (index
, cb
) => {
2570 // NOTE: move.drag could be generalized per-segment (usage?)
2571 const [i1
, j1
] = segments
[index
][0];
2572 const [i2
, j2
] = segments
[index
][1];
2573 const dep
= this.getPixelPosition(i1
, j1
, r
);
2574 const arr
= this.getPixelPosition(i2
, j2
, r
);
2575 movingPiece
.style
.transitionDuration
= "0s";
2576 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2578 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2579 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2580 // TODO: unclear why we need this new delay below:
2582 movingPiece
.style
.transitionDuration
= duration
+ "s";
2583 // movingPiece is child of container: no need to adjust coordinates
2584 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2585 setTimeout(cb
, duration
* 1000);
2589 const animateSegmentCallback
= () => {
2590 if (index
< segments
.length
)
2591 animateSegment(index
++, animateSegmentCallback
);
2593 movingPiece
.remove();
2594 initPiece
.style
.opacity
= "1";
2598 animateSegmentCallback();
2601 // Input array of objects with at least fields x,y (e.g. PiPo)
2602 animateFading(arr
, cb
) {
2603 const animLength
= 350; //TODO: 350ms? More? Less?
2605 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2606 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2607 fadingPiece
.style
.opacity
= "0";
2609 setTimeout(cb
, animLength
);
2612 animate(move, callback
) {
2613 if (this.noAnimate
|| move.noAnimate
) {
2617 let segments
= move.segments
;
2619 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2620 let targetObj
= new TargetObj(callback
);
2621 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2623 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2624 () => targetObj
.increment());
2626 if (move.vanish
.length
> move.appear
.length
) {
2627 const arr
= move.vanish
.slice(move.appear
.length
)
2628 // Ignore disappearing pieces hidden by some appearing ones:
2629 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2630 if (arr
.length
> 0) {
2632 this.animateFading(arr
, () => targetObj
.increment());
2636 this.tryAnimateCastle(move, () => targetObj
.increment());
2638 this.customAnimate(move, segments
, () => targetObj
.increment());
2639 if (targetObj
.target
== 0)
2643 tryAnimateCastle(move, cb
) {
2646 move.vanish
.length
== 2 &&
2647 move.appear
.length
== 2 &&
2648 this.isKing(0, 0, move.vanish
[0].p
) &&
2649 this.isKing(0, 0, move.appear
[0].p
)
2651 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2652 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2653 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2654 this.animateMoving(start
, end
, null, segments
, cb
);
2660 // Potential other animations (e.g. for Suction variant)
2661 customAnimate(move, segments
, cb
) {
2662 return 0; //nb of targets
2665 launchAnimation(moves
, container
, callback
) {
2666 if (this.hideMoves
) {
2667 for (let i
=0; i
<moves
.length
; i
++)
2668 // If hiding moves, they are revealed into play():
2669 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2672 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2673 const animateRec
= i
=> {
2674 this.animate(moves
[i
], () => {
2675 this.play(moves
[i
]);
2676 this.playVisual(moves
[i
], r
);
2677 if (i
< moves
.length
- 1)
2678 setTimeout(() => animateRec(i
+1), 300);
2686 playReceivedMove(moves
, callback
) {
2687 // Delay if user wasn't focused:
2688 const checkDisplayThenAnimate
= (delay
) => {
2689 if (container
.style
.display
== "none") {
2690 alert("New move! Let's go back to game...");
2691 document
.getElementById("gameInfos").style
.display
= "none";
2692 container
.style
.display
= "block";
2694 () => this.launchAnimation(moves
, container
, callback
),
2700 () => this.launchAnimation(moves
, container
, callback
),
2705 let container
= document
.getElementById(this.containerId
);
2706 if (document
.hidden
) {
2707 document
.onvisibilitychange
= () => {
2708 // TODO here: page reload ?! (some issues if tab changed...)
2709 document
.onvisibilitychange
= undefined;
2710 checkDisplayThenAnimate(700);
2714 checkDisplayThenAnimate();