1 import {Random
} from "/utils/alea.js";
2 import {ArrayFun
} from "/utils/array.js";
3 import {FenUtil
} from "/utils/setupPieces.js";
4 import PiPo
from "/utils/PiPo.js";
5 import Move
from "/utils/Move.js";
7 // Helper class for move animation
10 constructor(callOnComplete
) {
13 this.callOnComplete
= callOnComplete
;
16 if (++this.value
== this.target
)
17 this.callOnComplete();
22 // NOTE: x coords: top to bottom (white perspective); y: left to right
23 // NOTE: ChessRules is aliased as window.C, and variants as window.V
24 export default class ChessRules
{
26 static get Aliases() {
27 return {'C': ChessRules
};
30 /////////////////////////
31 // VARIANT SPECIFICATIONS
33 // Some variants have specific options, like the number of pawns in Monster,
34 // or the board size for Pandemonium.
35 // Users can generally select a randomness level from 0 to 2.
36 static get Options() {
40 variable: "randomness",
43 {label: "Deterministic", value: 0},
44 {label: "Symmetric random", value: 1},
45 {label: "Asymmetric random", value: 2}
50 label: "Capture king",
56 label: "Falling pawn",
62 // Game modifiers (using "elementary variants"). Default: false
65 "balance", //takes precedence over doublemove & progressive
69 "cylinder", //ok with all
73 "progressive", //(natural) priority over doublemove
82 get pawnPromotions() {
83 return ['q', 'r', 'n', 'b'];
86 // Some variants don't have flags:
95 // En-passant captures allowed?
100 // Allow to take (moving: not disappearing) own pieces?
101 get hasSelfCaptures() {
103 this.options
["recycle"] ||
104 (this.options
["teleport"] && this.subTurnTeleport
== 1)
110 !!this.options
["crazyhouse"] ||
111 (!!this.options
["recycle"] && !this.options
["teleport"])
114 // Some variants do not store reserve state (Align4, Chakart...)
115 get hasReserveFen() {
116 return this.hasReserve
;
120 return !!this.options
["dark"];
123 // Some variants use only click information
128 // Some variants reveal moves only after both players played
133 // Some variants do not flip board as black
135 return (this.playerColor
== 'b');
138 // Some variants use click infos:
140 if (typeof coords
.x
!= "number")
141 return null; //click on reserves
143 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
144 this.board
[coords
.x
][coords
.y
] == ""
147 start: {x: this.captured
.x
, y: this.captured
.y
},
158 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
167 // 3a --> {x:3, y:10}
168 static SquareToCoords(sq
) {
169 return ArrayFun
.toObject(["x", "y"],
170 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
173 // {x:11, y:12} --> bc
174 static CoordsToSquare(cd
) {
175 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
179 if (typeof cd
.x
== "number") {
181 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
185 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
188 idToCoords(targetId
) {
190 return null; //outside page, maybe...
191 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
193 idParts
.length
< 2 ||
194 idParts
[0] != this.containerId
||
195 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
199 const squares
= idParts
[1].split('-');
200 if (squares
[0] == "sq")
201 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
202 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
203 return {x: squares
[1], y: squares
[2]};
209 // Turn "wb" into "B" (for FEN)
211 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
214 // Turn "p" into "bp" (for board)
216 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
219 genRandInitFen(seed
) {
220 Random
.setSeed(seed
); //may be unused
221 let baseFen
= this.genRandInitBaseFen();
222 baseFen
.o
= Object
.assign({init: true}, baseFen
.o
);
223 const parts
= this.getPartFen(baseFen
.o
);
225 baseFen
.fen
+ " w 0" +
226 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
230 // Setup the initial random-or-not (asymmetric-or-not) position
231 genRandInitBaseFen() {
232 const s
= FenUtil
.setupPieces(
233 ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
235 randomness: this.options
["randomness"],
236 between: [{p1: 'k', p2: 'r'}],
242 fen: s
.b
.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
243 s
.w
.join("").toUpperCase(),
248 // "Parse" FEN: just return untransformed string data
250 const fenParts
= fen
.split(" ");
252 position: fenParts
[0],
254 movesCount: fenParts
[2]
256 if (fenParts
.length
> 3)
257 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
261 // Return current fen (game state)
263 const parts
= this.getPartFen({});
266 (Object
.keys(parts
).length
> 0 ? (" " + JSON
.stringify(parts
)) : "")
271 return this.getPosition() + " " + this.turn
+ " " + this.movesCount
;
277 parts
["flags"] = o
.init
? o
.flags : this.getFlagsFen();
278 if (this.hasEnpassant
)
279 parts
["enpassant"] = o
.init
? "-" : this.getEnpassantFen();
280 if (this.hasReserveFen
)
281 parts
["reserve"] = this.getReserveFen(o
);
282 if (this.options
["crazyhouse"])
283 parts
["ispawn"] = this.getIspawnFen(o
);
287 static FenEmptySquares(count
) {
288 // if more than 9 consecutive free spaces, break the integer,
289 // otherwise FEN parsing will fail.
292 // Most boards of size < 18:
294 return "9" + (count
- 9);
296 return "99" + (count
- 18);
299 // Position part of the FEN string
302 for (let i
= 0; i
< this.size
.x
; i
++) {
304 for (let j
= 0; j
< this.size
.y
; j
++) {
305 if (this.board
[i
][j
] == "")
308 if (emptyCount
> 0) {
309 // Add empty squares in-between
310 position
+= C
.FenEmptySquares(emptyCount
);
313 position
+= this.board2fen(this.board
[i
][j
]);
318 position
+= C
.FenEmptySquares(emptyCount
);
319 if (i
< this.size
.x
- 1)
320 position
+= "/"; //separate rows
325 // Flags part of the FEN string
327 return ['w', 'b'].map(c
=> {
328 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
332 // Enpassant part of the FEN string
336 return C
.CoordsToSquare(this.epSquare
);
341 return "000000000000";
343 ['w', 'b'].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
349 // NOTE: cannot merge because this.ispawn doesn't exist yet
351 const squares
= Object
.keys(this.ispawn
);
352 if (squares
.length
== 0)
354 return squares
.join(",");
357 // Set flags from fen (castle: white a,h then black a,h)
360 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
361 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
369 this.options
= o
.options
;
370 // Fill missing options (always the case if random challenge)
371 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
372 if (this.options
[opt
.variable
] === undefined)
373 this.options
[opt
.variable
] = opt
.defaut
;
377 this.playerColor
= o
.color
;
378 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
379 this.containerId
= o
.element
;
380 this.isDiagram
= o
.diagram
;
381 this.marks
= o
.marks
;
385 o
.fen
= this.genRandInitFen(o
.seed
);
386 this.re_initFromFen(o
.fen
);
387 this.graphicalInit();
390 re_initFromFen(fen
, oldBoard
) {
391 const fenParsed
= this.parseFen(fen
);
392 this.board
= oldBoard
|| this.getBoard(fenParsed
.position
);
393 this.turn
= fenParsed
.turn
;
394 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
395 this.setOtherVariables(fenParsed
);
398 // Turn position fen into double array ["wb","wp","bk",...]
400 const rows
= position
.split("/");
401 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
402 for (let i
= 0; i
< rows
.length
; i
++) {
404 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
405 const character
= rows
[i
][indexInRow
];
406 const num
= parseInt(character
, 10);
407 // If num is a number, just shift j:
410 // Else: something at position i,j
412 board
[i
][j
++] = this.fen2board(character
);
418 // Some additional variables from FEN (variant dependant)
419 setOtherVariables(fenParsed
, pieceArray
) {
420 // Set flags and enpassant:
422 this.setFlags(fenParsed
.flags
);
423 if (this.hasEnpassant
)
424 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
425 if (this.hasReserve
&& !this.isDiagram
)
426 this.initReserves(fenParsed
.reserve
, pieceArray
);
427 if (this.options
["crazyhouse"])
428 this.initIspawn(fenParsed
.ispawn
);
429 if (this.options
["teleport"]) {
430 this.subTurnTeleport
= 1;
431 this.captured
= null;
433 if (this.options
["dark"]) {
434 // Setup enlightened: squares reachable by player side
435 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
436 this.updateEnlightened();
438 this.subTurn
= 1; //may be unused
439 if (!this.moveStack
) //avoid resetting (unwanted)
443 // ordering as in pieces() p,r,n,b,q,k
444 initReserves(reserveStr
, pieceArray
) {
446 pieceArray
= ['p', 'r', 'n', 'b', 'q', 'k'];
447 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 36));
448 const L
= pieceArray
.length
;
450 w: ArrayFun
.toObject(pieceArray
, counts
.slice(0, L
)),
451 b: ArrayFun
.toObject(pieceArray
, counts
.slice(L
, 2 * L
))
455 initIspawn(ispawnStr
) {
456 if (ispawnStr
!= "-")
457 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
465 getPieceWidth(rwidth
) {
466 return (rwidth
/ this.size
.y
);
469 getReserveSquareSize(rwidth
, nbR
) {
470 const sqSize
= this.getPieceWidth(rwidth
);
471 return Math
.min(sqSize
, rwidth
/ nbR
);
474 getReserveNumId(color
, piece
) {
475 return `${this.containerId}|rnum-${color}${piece}`;
478 getNbReservePieces(color
) {
480 Object
.values(this.reserve
[color
]).reduce(
481 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
485 getRankInReserve(c
, p
) {
486 const pieces
= Object
.keys(this.pieces(c
, c
, p
));
487 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
488 let toTest
= pieces
.slice(0, lastIndex
);
489 return toTest
.reduce(
490 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
493 static AddClass_es(elt
, class_es
) {
494 if (!Array
.isArray(class_es
))
495 class_es
= [class_es
];
496 class_es
.forEach(cl
=> elt
.classList
.add(cl
));
499 static RemoveClass_es(elt
, class_es
) {
500 if (!Array
.isArray(class_es
))
501 class_es
= [class_es
];
502 class_es
.forEach(cl
=> elt
.classList
.remove(cl
));
505 // Generally light square bottom-right
506 getSquareColorClass(x
, y
) {
507 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
511 // Works for all rectangular boards:
512 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
516 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
523 const g_init
= () => {
524 this.re_drawBoardElements();
525 if (!this.isDiagram
&& !this.mouseListeners
&& !this.touchListeners
)
526 this.initMouseEvents();
528 let container
= document
.getElementById(this.containerId
);
529 this.windowResizeObs
= new ResizeObserver(g_init
);
530 this.windowResizeObs
.observe(container
);
533 re_drawBoardElements() {
534 const board
= this.getSvgChessboard();
535 const container
= document
.getElementById(this.containerId
);
536 const rc
= container
.getBoundingClientRect();
537 let chessboard
= container
.querySelector(".chessboard");
538 chessboard
.innerHTML
= "";
539 chessboard
.insertAdjacentHTML('beforeend', board
);
540 // Compare window ratio width / height to aspectRatio:
541 const windowRatio
= rc
.width
/ rc
.height
;
542 let cbWidth
, cbHeight
;
543 const vRatio
= this.size
.ratio
|| 1;
544 if (windowRatio
<= vRatio
) {
545 // Limiting dimension is width:
546 cbWidth
= Math
.min(rc
.width
, 767);
547 cbHeight
= cbWidth
/ vRatio
;
550 // Limiting dimension is height:
551 cbHeight
= Math
.min(rc
.height
, 767);
552 cbWidth
= cbHeight
* vRatio
;
554 if (this.hasReserve
&& !this.isDiagram
) {
555 const sqSize
= cbWidth
/ this.size
.y
;
556 // NOTE: allocate space for reserves (up/down) even if they are empty
557 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
558 if ((rc
.height
- cbHeight
) / 2 < sqSize
+ 5) {
559 cbHeight
= rc
.height
- 2 * (sqSize
+ 5);
560 cbWidth
= cbHeight
* vRatio
;
563 chessboard
.style
.width
= cbWidth
+ "px";
564 chessboard
.style
.height
= cbHeight
+ "px";
565 // Center chessboard:
566 const spaceLeft
= (rc
.width
- cbWidth
) / 2,
567 spaceTop
= (rc
.height
- cbHeight
) / 2;
568 chessboard
.style
.left
= spaceLeft
+ "px";
569 chessboard
.style
.top
= spaceTop
+ "px";
570 // Give sizes instead of recomputing them,
571 // because chessboard might not be drawn yet.
572 this.setupVisualPieces({
580 // Get SVG board (background, no pieces)
582 const flipped
= this.flippedBoard
;
585 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
586 class="chessboard_SVG">`;
587 for (let i
=0; i
< this.size
.x
; i
++) {
588 for (let j
=0; j
< this.size
.y
; j
++) {
589 if (!this.onBoard(i
, j
))
591 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
592 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
593 let classes
= this.getSquareColorClass(ii
, jj
);
594 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
595 classes
+= " in-shadow";
596 // NOTE: x / y reversed because coordinates system is reversed.
600 id="${this.coordsToId({x: ii, y: jj})}"
612 setupVisualPieces(r
) {
614 document
.getElementById(this.containerId
).querySelector(".chessboard");
616 r
= chessboard
.getBoundingClientRect();
617 const pieceWidth
= this.getPieceWidth(r
.width
);
618 const addPiece
= (i
, j
, arrName
, classes
) => {
619 this[arrName
][i
][j
] = document
.createElement("piece");
620 C
.AddClass_es(this[arrName
][i
][j
], classes
);
621 this[arrName
][i
][j
].style
.width
= pieceWidth
+ "px";
622 this[arrName
][i
][j
].style
.height
= pieceWidth
+ "px";
623 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
624 // Translate coordinates to use chessboard as reference:
625 this[arrName
][i
][j
].style
.transform
=
626 `translate(${ip - r.x}px,${jp - r.y}px)`;
627 chessboard
.appendChild(this[arrName
][i
][j
]);
629 const conditionalReset
= (arrName
) => {
631 // Refreshing: delete old pieces first. This isn't necessary,
632 // but simpler (this method isn't called many times)
633 for (let i
=0; i
<this.size
.x
; i
++) {
634 for (let j
=0; j
<this.size
.y
; j
++) {
635 if (this[arrName
][i
][j
]) {
636 this[arrName
][i
][j
].remove();
637 this[arrName
][i
][j
] = null;
643 this[arrName
] = ArrayFun
.init(this.size
.x
, this.size
.y
, null);
644 if (arrName
== "d_pieces")
645 this.marks
.forEach((m
) => {
646 const formattedSquare
=
647 (this.size
.x
- parseInt(m
.substring(1), 10)).toString(36) +
648 (m
.charCodeAt(0) - 97).toString(36);
649 const mCoords
= V
.SquareToCoords(formattedSquare
);
650 addPiece(mCoords
.x
, mCoords
.y
, arrName
, "mark");
654 conditionalReset("d_pieces");
655 conditionalReset("g_pieces");
656 for (let i
=0; i
< this.size
.x
; i
++) {
657 for (let j
=0; j
< this.size
.y
; j
++) {
658 if (this.board
[i
][j
] != "") {
659 const color
= this.getColor(i
, j
);
660 const piece
= this.getPiece(i
, j
);
661 addPiece(i
, j
, "g_pieces", this.pieces(color
, i
, j
)[piece
]["class"]);
662 this.g_pieces
[i
][j
].classList
.add(V
.GetColorClass(color
));
663 if (this.enlightened
&& !this.enlightened
[i
][j
])
664 this.g_pieces
[i
][j
].classList
.add("hidden");
666 if (this.marks
&& this.d_pieces
[i
][j
]) {
667 let classes
= ["mark"];
668 if (this.board
[i
][j
] != "")
669 classes
.push("transparent");
670 addPiece(i
, j
, "d_pieces", classes
);
674 if (this.hasReserve
&& !this.isDiagram
)
675 this.re_drawReserve(['w', 'b'], r
);
678 // NOTE: assume this.reserve != null
679 re_drawReserve(colors
, r
) {
681 // Remove (old) reserve pieces
682 for (let c
of colors
) {
683 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
684 this.r_pieces
[c
][p
].remove();
685 delete this.r_pieces
[c
][p
];
686 const numId
= this.getReserveNumId(c
, p
);
687 document
.getElementById(numId
).remove();
692 this.r_pieces
= { w: {}, b: {} };
693 let container
= document
.getElementById(this.containerId
);
695 r
= container
.querySelector(".chessboard").getBoundingClientRect();
696 for (let c
of colors
) {
697 let reservesDiv
= document
.getElementById("reserves_" + c
);
699 reservesDiv
.remove();
700 if (!this.reserve
[c
])
702 const nbR
= this.getNbReservePieces(c
);
705 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
707 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
708 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
709 let rcontainer
= document
.createElement("div");
710 rcontainer
.id
= "reserves_" + c
;
711 rcontainer
.classList
.add("reserves");
712 rcontainer
.style
.left
= i0
+ "px";
713 rcontainer
.style
.top
= j0
+ "px";
714 // NOTE: +1 fix display bug on Firefox at least
715 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
716 rcontainer
.style
.height
= sqResSize
+ "px";
717 container
.appendChild(rcontainer
);
718 for (let p
of Object
.keys(this.reserve
[c
])) {
719 if (this.reserve
[c
][p
] == 0)
721 let r_cell
= document
.createElement("div");
722 r_cell
.id
= this.coordsToId({x: c
, y: p
});
723 r_cell
.classList
.add("reserve-cell");
724 r_cell
.style
.width
= sqResSize
+ "px";
725 r_cell
.style
.height
= sqResSize
+ "px";
726 rcontainer
.appendChild(r_cell
);
727 let piece
= document
.createElement("piece");
728 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
729 piece
.classList
.add(V
.GetColorClass(c
));
730 piece
.style
.width
= "100%";
731 piece
.style
.height
= "100%";
732 this.r_pieces
[c
][p
] = piece
;
733 r_cell
.appendChild(piece
);
734 let number
= document
.createElement("div");
735 number
.textContent
= this.reserve
[c
][p
];
736 number
.classList
.add("reserve-num");
737 number
.id
= this.getReserveNumId(c
, p
);
738 const fontSize
= "1.3em";
739 number
.style
.fontSize
= fontSize
;
740 number
.style
.fontSize
= fontSize
;
741 r_cell
.appendChild(number
);
747 updateReserve(color
, piece
, count
) {
748 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
749 piece
= "k"; //capturing cannibal king: back to king form
750 const oldCount
= this.reserve
[color
][piece
];
751 this.reserve
[color
][piece
] = count
;
752 // Redrawing is much easier if count==0 (or undefined)
753 if ([oldCount
, count
].some(item
=> !item
))
754 this.re_drawReserve([color
]);
756 const numId
= this.getReserveNumId(color
, piece
);
757 document
.getElementById(numId
).textContent
= count
;
761 // Resize board: no need to destroy/recreate pieces
763 const container
= document
.getElementById(this.containerId
);
764 let chessboard
= container
.querySelector(".chessboard");
765 const rc
= container
.getBoundingClientRect(),
766 r
= chessboard
.getBoundingClientRect();
767 const multFact
= (mode
== "up" ? 1.05 : 0.95);
768 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
770 const vRatio
= this.size
.ratio
|| 1;
771 if (newWidth
> rc
.width
) {
773 newHeight
= newWidth
/ vRatio
;
775 if (newHeight
> rc
.height
) {
776 newHeight
= rc
.height
;
777 newWidth
= newHeight
* vRatio
;
779 chessboard
.style
.width
= newWidth
+ "px";
780 chessboard
.style
.height
= newHeight
+ "px";
781 const newX
= (rc
.width
- newWidth
) / 2;
782 chessboard
.style
.left
= newX
+ "px";
783 const newY
= (rc
.height
- newHeight
) / 2;
784 chessboard
.style
.top
= newY
+ "px";
785 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
786 const pieceWidth
= this.getPieceWidth(newWidth
);
787 // NOTE: next "if" for variants which use squares filling
788 // instead of "physical", moving pieces
790 for (let i
=0; i
< this.size
.x
; i
++) {
791 for (let j
=0; j
< this.size
.y
; j
++) {
792 if (this.g_pieces
[i
][j
]) {
793 // NOTE: could also use CSS transform "scale"
794 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
795 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
796 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
797 // Translate coordinates to use chessboard as reference:
798 this.g_pieces
[i
][j
].style
.transform
=
799 `translate(${ip - newX}px,${jp - newY}px)`;
805 this.rescaleReserve(newR
);
809 for (let c
of ['w','b']) {
810 if (!this.reserve
[c
])
812 const nbR
= this.getNbReservePieces(c
);
815 // Resize container first
816 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
817 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
818 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
819 let rcontainer
= document
.getElementById("reserves_" + c
);
820 rcontainer
.style
.left
= i0
+ "px";
821 rcontainer
.style
.top
= j0
+ "px";
822 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
823 rcontainer
.style
.height
= sqResSize
+ "px";
824 // And then reserve cells:
825 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
826 Object
.keys(this.reserve
[c
]).forEach(p
=> {
827 if (this.reserve
[c
][p
] == 0)
829 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
830 r_cell
.style
.width
= sqResSize
+ "px";
831 r_cell
.style
.height
= sqResSize
+ "px";
836 // Return the absolute pixel coordinates given current position.
837 // Our coordinate system differs from CSS one (x <--> y).
838 // We return here the CSS coordinates (more useful).
839 getPixelPosition(i
, j
, r
) {
841 return [0, 0]; //piece vanishes
843 if (typeof i
== "string") {
844 // Reserves: need to know the rank of piece
845 const nbR
= this.getNbReservePieces(i
);
846 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
847 x
= this.getRankInReserve(i
, j
) * rsqSize
;
848 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
851 const sqSize
= r
.width
/ this.size
.y
;
852 const flipped
= this.flippedBoard
;
853 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
854 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
856 return [r
.x
+ x
, r
.y
+ y
];
860 let container
= document
.getElementById(this.containerId
);
861 let chessboard
= container
.querySelector(".chessboard");
863 const getOffset
= e
=> {
866 return {x: e
.clientX
, y: e
.clientY
};
867 let touchLocation
= null;
868 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
869 // Touch screen, dragstart
870 touchLocation
= e
.targetTouches
[0];
871 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
872 // Touch screen, dragend
873 touchLocation
= e
.changedTouches
[0];
875 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
876 return {x: 0, y: 0}; //shouldn't reach here =)
879 const centerOnCursor
= (piece
, e
) => {
880 const centerShift
= this.getPieceWidth(r
.width
) / 2;
881 const offset
= getOffset(e
);
882 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
883 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
888 startPiece
, curPiece
= null,
890 const mousedown
= (e
) => {
891 // Disable zoom on smartphones:
892 if (e
.touches
&& e
.touches
.length
> 1)
894 r
= chessboard
.getBoundingClientRect();
895 pieceWidth
= this.getPieceWidth(r
.width
);
896 const cd
= this.idToCoords(e
.target
.id
);
898 const move = this.doClick(cd
);
900 this.buildMoveStack(move, r
);
901 else if (!this.clickOnly
) {
902 const [x
, y
] = Object
.values(cd
);
903 if (typeof x
!= "number")
904 startPiece
= this.r_pieces
[x
][y
];
906 startPiece
= this.g_pieces
[x
][y
];
907 if (startPiece
&& this.canIplay(x
, y
)) {
910 curPiece
= startPiece
.cloneNode();
911 curPiece
.style
.transform
= "none";
912 curPiece
.style
.zIndex
= 5;
913 curPiece
.style
.width
= pieceWidth
+ "px";
914 curPiece
.style
.height
= pieceWidth
+ "px";
915 centerOnCursor(curPiece
, e
);
916 container
.appendChild(curPiece
);
917 startPiece
.style
.opacity
= "0.4";
918 chessboard
.style
.cursor
= "none";
924 const mousemove
= (e
) => {
927 centerOnCursor(curPiece
, e
);
929 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
930 // Attempt to prevent horizontal swipe...
934 const mouseup
= (e
) => {
937 const [x
, y
] = [start
.x
, start
.y
];
940 chessboard
.style
.cursor
= "pointer";
941 startPiece
.style
.opacity
= "1";
942 const offset
= getOffset(e
);
943 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
945 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
947 // NOTE: clearly suboptimal, but much easier, and not a big deal.
948 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
949 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
950 const moves
= this.filterValid(potentialMoves
);
951 if (moves
.length
>= 2)
952 this.showChoices(moves
, r
);
953 else if (moves
.length
== 1)
954 this.buildMoveStack(moves
[0], r
);
959 const resize
= (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down");
961 if ('onmousedown' in window
) {
962 this.mouseListeners
= [
963 {type: "mousedown", listener: mousedown
},
964 {type: "mousemove", listener: mousemove
},
965 {type: "mouseup", listener: mouseup
},
966 {type: "wheel", listener: resize
}
968 this.mouseListeners
.forEach(ml
=> {
969 document
.addEventListener(ml
.type
, ml
.listener
);
972 if ('ontouchstart' in window
) {
973 this.touchListeners
= [
974 {type: "touchstart", listener: mousedown
},
975 {type: "touchmove", listener: mousemove
},
976 {type: "touchend", listener: mouseup
}
978 this.touchListeners
.forEach(tl
=> {
979 // https://stackoverflow.com/a/42509310/12660887
980 document
.addEventListener(tl
.type
, tl
.listener
, {passive: false});
983 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
986 // NOTE: not called if isDiagram
988 let container
= document
.getElementById(this.containerId
);
989 this.windowResizeObs
.unobserve(container
);
990 if ('onmousedown' in window
) {
991 this.mouseListeners
.forEach(ml
=> {
992 document
.removeEventListener(ml
.type
, ml
.listener
);
995 if ('ontouchstart' in window
) {
996 this.touchListeners
.forEach(tl
=> {
997 // https://stackoverflow.com/a/42509310/12660887
998 document
.removeEventListener(tl
.type
, tl
.listener
);
1003 showChoices(moves
, r
) {
1004 let container
= document
.getElementById(this.containerId
);
1005 let chessboard
= container
.querySelector(".chessboard");
1006 let choices
= document
.createElement("div");
1007 choices
.id
= "choices";
1009 r
= chessboard
.getBoundingClientRect();
1010 choices
.style
.width
= r
.width
+ "px";
1011 choices
.style
.height
= r
.height
+ "px";
1012 choices
.style
.left
= r
.x
+ "px";
1013 choices
.style
.top
= r
.y
+ "px";
1014 chessboard
.style
.opacity
= "0.5";
1015 container
.appendChild(choices
);
1016 const squareWidth
= r
.width
/ this.size
.y
;
1017 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1018 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1019 const color
= moves
[0].appear
[0].c
;
1020 const callback
= (m
) => {
1021 chessboard
.style
.opacity
= "1";
1022 container
.removeChild(choices
);
1023 this.buildMoveStack(m
, r
);
1025 for (let i
=0; i
< moves
.length
; i
++) {
1026 let choice
= document
.createElement("div");
1027 choice
.classList
.add("choice");
1028 choice
.style
.width
= squareWidth
+ "px";
1029 choice
.style
.height
= squareWidth
+ "px";
1030 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1031 choice
.style
.top
= firstUpTop
+ "px";
1032 choice
.style
.backgroundColor
= "lightyellow";
1033 choice
.onclick
= () => callback(moves
[i
]);
1034 const piece
= document
.createElement("piece");
1035 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1036 C
.AddClass_es(piece
,
1037 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1038 piece
.classList
.add(V
.GetColorClass(color
));
1039 piece
.style
.width
= "100%";
1040 piece
.style
.height
= "100%";
1041 choice
.appendChild(piece
);
1042 choices
.appendChild(choice
);
1046 displayMessage(elt
, msg
, classe_s
, timeout
) {
1048 // Fixed element, e.g. for Dice Chess
1049 elt
.innerHTML
= msg
;
1051 // Temporary div (Chakart, Apocalypse...)
1052 let divMsg
= document
.createElement("div");
1053 C
.AddClass_es(divMsg
, classe_s
);
1054 divMsg
.innerHTML
= msg
;
1055 let container
= document
.getElementById(this.containerId
);
1056 container
.appendChild(divMsg
);
1057 setTimeout(() => container
.removeChild(divMsg
), timeout
);
1064 updateEnlightened() {
1065 this.oldEnlightened
= this.enlightened
;
1066 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
1067 // Add pieces positions + all squares reachable by moves (includes Zen):
1068 for (let x
=0; x
<this.size
.x
; x
++) {
1069 for (let y
=0; y
<this.size
.y
; y
++) {
1070 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
1072 this.enlightened
[x
][y
] = true;
1073 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
1074 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
1080 this.enlightEnpassant();
1083 // Include square of the en-passant capturing square:
1084 enlightEnpassant() {
1085 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1086 // TODO: (0, 0) is wrong, would need to place an attacker here...
1087 const steps
= this.pieces(this.playerColor
, 0, 0)["p"].attack
[0].steps
;
1088 for (let step
of steps
) {
1089 const x
= this.epSquare
.x
- step
[0], //NOTE: epSquare.x not on edge
1090 y
= this.getY(this.epSquare
.y
- step
[1]);
1092 this.onBoard(x
, y
) &&
1093 this.getColor(x
, y
) == this.playerColor
&&
1094 this.getPieceType(x
, y
) == "p"
1096 this.enlightened
[x
][this.epSquare
.y
] = true;
1102 // Apply diff this.enlightened --> oldEnlightened on board
1103 graphUpdateEnlightened() {
1105 document
.getElementById(this.containerId
).querySelector(".chessboard");
1106 const r
= chessboard
.getBoundingClientRect();
1107 const pieceWidth
= this.getPieceWidth(r
.width
);
1108 for (let x
=0; x
<this.size
.x
; x
++) {
1109 for (let y
=0; y
<this.size
.y
; y
++) {
1110 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
1111 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1112 elt
.classList
.add("in-shadow");
1113 if (this.g_pieces
[x
][y
])
1114 this.g_pieces
[x
][y
].classList
.add("hidden");
1116 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
1117 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
1118 elt
.classList
.remove("in-shadow");
1119 if (this.g_pieces
[x
][y
])
1120 this.g_pieces
[x
][y
].classList
.remove("hidden");
1133 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1137 // Color of thing on square (i,j). '' if square is empty
1139 if (typeof i
== "string")
1140 return i
; //reserves
1141 return this.board
[i
][j
].charAt(0);
1144 static GetColorClass(c
) {
1149 return "other-color"; //unidentified color
1152 // Piece on i,j. '' if square is empty
1154 if (typeof j
== "string")
1155 return j
; //reserves
1156 return this.board
[i
][j
].charAt(1);
1159 // Piece type on square (i,j)
1160 getPieceType(x
, y
, p
) {
1162 p
= this.getPiece(x
, y
);
1163 return this.pieces(this.getColor(x
, y
), x
, y
)[p
].moveas
|| p
;
1168 p
= this.getPiece(x
, y
);
1169 if (!this.options
["cannibal"])
1171 return !!C
.CannibalKings
[p
];
1174 static GetOppTurn(color
) {
1175 return (color
== 'w' ? 'b' : 'w');
1178 // Get opponent color(s): may differ from turn (e.g. Checkered)
1180 return (color
== "w" ? "b" : "w");
1183 // Is (x,y) on the chessboard?
1185 return (x
>= 0 && x
< this.size
.x
&&
1186 y
>= 0 && y
< this.size
.y
);
1189 // Am I allowed to move thing at square x,y ?
1191 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1194 ////////////////////////
1195 // PIECES SPECIFICATIONS
1197 getPawnShift(color
) {
1198 return (color
== "w" ? -1 : 1);
1200 isPawnInitRank(x
, color
) {
1201 return (color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1);
1204 pieces(color
, x
, y
) {
1205 const pawnShift
= this.getPawnShift(color
|| 'w');
1211 steps: [[pawnShift
, 0]],
1212 range: (this.isPawnInitRank(x
, color
) ? 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
;
1315 return x
; //generally, no
1318 increment([x
, y
], step
) {
1320 this.getX(x
+ step
[0]),
1321 this.getY(y
+ step
[1])
1325 getSegments(curSeg
, segStart
, segEnd
) {
1326 if (curSeg
.length
== 0)
1328 let segments
= JSON
.parse(JSON
.stringify(curSeg
)); //not altering
1329 segments
.push([[segStart
[0], segStart
[1]], [segEnd
[0], segEnd
[1]]]);
1333 getStepSpec(color
, x
, y
, piece
) {
1334 let pieceType
= piece
;
1335 let allSpecs
= this.pieces(color
, x
, y
);
1337 pieceType
= this.getPieceType(x
, y
);
1338 else if (allSpecs
[piece
].moveas
)
1339 pieceType
= allSpecs
[piece
].moveas
;
1340 let res
= allSpecs
[pieceType
];
1350 // Can thing on square1 capture thing on square2?
1351 canTake([x1
, y1
], [x2
, y2
]) {
1352 return this.getColor(x1
, y1
) !== this.getColor(x2
, y2
);
1355 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
1356 canSelfTake([x1
, y1
], [x2
, y2
]) {
1357 return !this.isKing(x2
, y2
);
1360 canStepOver(i
, j
, p
) {
1361 // In some variants, objects on boards don't stop movement (Chakart)
1362 return this.board
[i
][j
] == "";
1365 canDrop([c
, p
], [i
, j
]) {
1367 this.board
[i
][j
] == "" &&
1368 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1371 (c
== 'w' && i
< this.size
.x
- 1) ||
1378 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1379 isImmobilized([x
, y
]) {
1380 if (!this.options
["madrasi"])
1382 const color
= this.getColor(x
, y
);
1383 const oppCols
= this.getOppCols(color
);
1384 const piece
= this.getPieceType(x
, y
);
1385 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1386 const attacks
= stepSpec
.both
.concat(stepSpec
.attack
);
1387 for (let a
of attacks
) {
1388 outerLoop: for (let step
of a
.steps
) {
1389 let [i
, j
] = this.increment([x
, y
], step
);
1390 let stepCounter
= 0;
1391 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1392 if (a
.range
<= stepCounter
++)
1394 [i
, j
] = this.increment([i
, j
], step
);
1397 this.onBoard(i
, j
) &&
1398 oppCols
.includes(this.getColor(i
, j
)) &&
1399 this.getPieceType(i
, j
) == piece
1408 // Stop at the first capture found
1409 atLeastOneCapture(color
) {
1410 const allowed
= (sq1
, sq2
) => {
1412 // NOTE: canTake is reversed for Zen.
1413 // Generally ok because of the symmetry. TODO?
1414 this.canTake(sq1
, sq2
) &&
1416 [this.getBasicMove(sq1
, sq2
)]).length
>= 1
1419 for (let i
=0; i
<this.size
.x
; i
++) {
1420 for (let j
=0; j
<this.size
.y
; j
++) {
1421 if (this.getColor(i
, j
) == color
) {
1424 !this.options
["zen"] &&
1425 this.findDestSquares(
1437 this.options
["zen"] &&
1438 this.findCapturesOn(
1454 compatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1455 const epsilon
= 1e-7; //arbitrary small value
1457 if (this.options
["cylinder"])
1458 Array
.prototype.push
.apply(shifts
, [-this.size
.y
, this.size
.y
]);
1459 for (let sh
of shifts
) {
1460 const rx
= (x2
- x1
) / step
[0],
1461 ry
= (y2
+ sh
- y1
) / step
[1];
1463 // Zero step but non-zero interval => impossible
1464 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1465 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
)) ||
1466 // Negative number of step (impossible)
1467 (rx
< 0 || ry
< 0) ||
1468 // Not the same number of steps in both directions:
1469 (!Number
.isNaN(rx
) && !Number
.isNaN(ry
) && Math
.abs(rx
- ry
) > epsilon
)
1473 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1474 if (Math
.abs(distance
- Math
.round(distance
)) > epsilon
)
1476 distance
= Math
.round(distance
); //in case of (numerical...)
1477 if (!range
|| range
>= distance
)
1483 ////////////////////
1486 getDropMovesFrom([c
, p
]) {
1487 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1488 // (but not necessarily otherwise: atLeastOneMove() etc)
1489 if (this.reserve
[c
][p
] == 0)
1492 for (let i
=0; i
<this.size
.x
; i
++) {
1493 for (let j
=0; j
<this.size
.y
; j
++) {
1494 if (this.onBoard(i
, j
) && this.canDrop([c
, p
], [i
, j
])) {
1496 start: {x: c
, y: p
},
1498 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1501 if (this.board
[i
][j
] != "") {
1502 mv
.vanish
.push(new PiPo({
1505 c: this.getColor(i
, j
),
1506 p: this.getPiece(i
, j
)
1516 // All possible moves from selected square
1517 // TODO: generalize usage if arg "color" (e.g. Checkered)
1518 getPotentialMovesFrom([x
, y
], color
) {
1519 if (this.subTurnTeleport
== 2)
1521 if (typeof x
== "string")
1522 return this.getDropMovesFrom([x
, y
]);
1523 if (this.isImmobilized([x
, y
]))
1525 const piece
= this.getPieceType(x
, y
);
1526 let moves
= this.getPotentialMovesOf(piece
, [x
, y
]);
1527 if (piece
== "p" && this.hasEnpassant
&& this.epSquare
)
1528 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures([x
, y
]));
1529 if (this.isKing(0, 0, piece
) && this.hasCastle
)
1530 Array
.prototype.push
.apply(moves
, this.getCastleMoves([x
, y
]));
1531 return this.postProcessPotentialMoves(moves
);
1534 postProcessPotentialMoves(moves
) {
1535 if (moves
.length
== 0)
1537 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1538 const oppCols
= this.getOppCols(color
);
1540 if (this.options
["capture"] && this.atLeastOneCapture(color
))
1541 moves
= this.capturePostProcess(moves
, oppCols
);
1543 if (this.options
["atomic"])
1544 moves
= this.atomicPostProcess(moves
, color
, oppCols
);
1548 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1550 moves
= this.pawnPostProcess(moves
, color
, oppCols
);
1553 if (this.options
["cannibal"] && this.options
["rifle"])
1554 // In this case a rifle-capture from last rank may promote a pawn
1555 moves
= this.riflePromotePostProcess(moves
, color
);
1560 capturePostProcess(moves
, oppCols
) {
1561 // Filter out non-capturing moves (not using m.vanish because of
1562 // self captures of Recycle and Teleport).
1563 return moves
.filter(m
=> {
1565 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1566 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1571 atomicPostProcess(moves
, color
, oppCols
) {
1572 moves
.forEach(m
=> {
1574 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1575 oppCols
.includes(this.getColor(m
.end
.x
, m
.end
.y
))
1588 let mNext
= new Move({
1594 for (let step
of steps
) {
1595 let [x
, y
] = this.increment([m
.end
.x
, m
.end
.y
], step
);
1597 this.onBoard(x
, y
) &&
1598 this.board
[x
][y
] != "" &&
1599 (x
!= m
.start
.x
|| y
!= m
.start
.y
) &&
1600 this.getPieceType(x
, y
) != "p"
1604 p: this.getPiece(x
, y
),
1605 c: this.getColor(x
, y
),
1612 if (!this.options
["rifle"]) {
1613 // The moving piece also vanish
1614 mNext
.vanish
.unshift(
1619 p: this.getPiece(m
.start
.x
, m
.start
.y
)
1629 pawnPostProcess(moves
, color
, oppCols
) {
1631 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1632 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1633 moves
.forEach(m
=> {
1634 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1635 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1636 const promotionOk
= (
1638 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1641 return; //nothing to do
1642 if (this.options
["pawnfall"]) {
1648 this.options
["cannibal"] &&
1649 this.board
[x2
][y2
] != "" &&
1650 oppCols
.includes(this.getColor(x2
, y2
))
1652 finalPieces
= [this.getPieceType(x2
, y2
)];
1655 finalPieces
= this.pawnPromotions
;
1656 m
.appear
[0].p
= finalPieces
[0];
1657 if (initPiece
== "!") //cannibal king-pawn
1658 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1659 for (let i
=1; i
<finalPieces
.length
; i
++) {
1660 let newMove
= JSON
.parse(JSON
.stringify(m
));
1661 const piece
= finalPieces
[i
];
1662 m
.appear
[0].p
= (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
]);
1663 moreMoves
.push(newMove
);
1666 return moves
.concat(moreMoves
);
1669 riflePromotePostProcess(moves
, color
) {
1670 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1672 moves
.forEach(m
=> {
1674 m
.start
.x
== lastRank
&&
1675 m
.appear
.length
>= 1 &&
1676 m
.appear
[0].p
== "p" &&
1677 m
.appear
[0].x
== m
.start
.x
&&
1678 m
.appear
[0].y
== m
.start
.y
1680 m
.appear
[0].p
= this.pawnPromotions
[0];
1681 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1682 let newMv
= JSON
.parse(JSON
.stringify(m
));
1683 newMv
.appear
[0].p
= this.pawnPromotions
[i
];
1684 newMoves
.push(newMv
);
1688 return moves
.concat(newMoves
);
1691 // Generic method to find possible moves of "sliding or jumping" pieces
1692 getPotentialMovesOf(piece
, [x
, y
]) {
1693 const color
= this.getColor(x
, y
);
1694 const stepSpec
= this.getStepSpec(color
, x
, y
, piece
);
1696 if (stepSpec
.attack
) {
1697 squares
= this.findDestSquares(
1703 ([i1
, j1
], [i2
, j2
]) => {
1705 (!this.options
["zen"] || this.isKing(i2
, j2
)) &&
1706 this.canTake([i1
, j1
], [i2
, j2
])
1711 const noSpecials
= this.findDestSquares(
1714 moveOnly: !!stepSpec
.attack
|| this.options
["zen"],
1718 Array
.prototype.push
.apply(squares
, noSpecials
);
1719 if (this.options
["zen"]) {
1720 let zenCaptures
= this.findCapturesOn(
1722 {}, //byCol: default is ok
1723 ([i1
, j1
], [i2
, j2
]) =>
1724 !this.isKing(i1
, j1
) && this.canTake([i2
, j2
], [i1
, j1
])
1726 // Technical step: segments (if any) are reversed
1727 zenCaptures
.forEach(z
=> {
1729 z
.segments
= z
.segments
.reverse().map(s
=> s
.reverse())
1731 Array
.prototype.push
.apply(squares
, zenCaptures
);
1733 if (this.hasSelfCaptures
) {
1734 const selfCaptures
= this.findDestSquares(
1740 ([i1
, j1
], [i2
, j2
]) => {
1742 this.getColor(i2
, j2
) == color
&&
1743 this.canSelfTake([i1
, j1
], [i2
, j2
])
1747 Array
.prototype.push
.apply(squares
, selfCaptures
);
1749 return squares
.map(s
=> {
1750 let mv
= this.getBasicMove([x
, y
], s
.sq
);
1752 mv
.segments
= s
.segments
;
1757 findDestSquares([x
, y
], o
, allowed
) {
1759 allowed
= (sq1
, sq2
) => this.canTake(sq1
, sq2
);
1760 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1762 // Next 3 for Cylinder mode or circular (useless otherwise)
1766 const addSquare
= ([i
, j
]) => {
1767 let elt
= {sq: [i
, j
]};
1768 if (segments
.length
>= 1)
1769 elt
.segments
= this.getSegments(segments
, segStart
, [i
, j
]);
1772 const exploreSteps
= (stepArray
, mode
) => {
1773 for (let s
of stepArray
) {
1774 outerLoop: for (let step
of s
.steps
) {
1777 let [i
, j
] = [x
, y
];
1778 let stepCounter
= 0;
1780 this.onBoard(i
, j
) &&
1781 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1783 if (!explored
[i
+ "." + j
] && (i
!= x
|| j
!= y
)) {
1784 explored
[i
+ "." + j
] = true;
1787 (o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
)
1789 if (o
.one
&& mode
!= "attack")
1791 if (mode
!= "attack")
1792 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1793 if (o
.captureTarget
)
1797 if (s
.range
<= stepCounter
++)
1799 const oldIJ
= [i
, j
];
1800 [i
, j
] = this.increment([i
, j
], step
);
1802 Math
.abs(i
- oldIJ
[0]) != Math
.abs(step
[0]) ||
1803 Math
.abs(j
- oldIJ
[1]) != Math
.abs(step
[1])
1805 // Boundary between segments (cylinder or circular mode)
1806 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1810 if (!this.onBoard(i
, j
))
1812 const pieceIJ
= this.getPieceType(i
, j
);
1813 if (!explored
[i
+ "." + j
]) {
1814 explored
[i
+ "." + j
] = true;
1815 if (allowed([x
, y
], [i
, j
])) {
1816 if (o
.one
&& mode
!= "moves")
1818 if (mode
!= "moves")
1819 addSquare(!o
.captureTarget
? [i
, j
] : [x
, y
]);
1822 o
.captureTarget
[0] == i
&& o
.captureTarget
[1] == j
1830 return undefined; //default, but let's explicit it
1832 if (o
.captureTarget
)
1833 return exploreSteps(o
.captureSteps
, "attack");
1836 o
.stepSpec
|| this.getStepSpec(this.getColor(x
, y
), x
, y
);
1839 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.moves
), "moves");
1840 if (!outOne
&& !o
.moveOnly
)
1841 outOne
= exploreSteps(stepSpec
.both
.concat(stepSpec
.attack
), "attack");
1842 return (o
.one
? outOne : res
);
1846 // Search for enemy (or not) pieces attacking [x, y]
1847 findCapturesOn([x
, y
], o
, allowed
) {
1849 o
.byCol
= this.getOppCols(this.getColor(x
, y
) || this.turn
);
1851 for (let i
=0; i
<this.size
.x
; i
++) {
1852 for (let j
=0; j
<this.size
.y
; j
++) {
1853 const colIJ
= this.getColor(i
, j
);
1855 this.board
[i
][j
] != "" &&
1856 o
.byCol
.includes(colIJ
) &&
1857 !this.isImmobilized([i
, j
])
1859 const apparentPiece
= this.getPiece(i
, j
);
1860 // Quick check: does this potential attacker target x,y ?
1861 if (this.canStepOver(x
, y
, apparentPiece
))
1863 const stepSpec
= this.getStepSpec(colIJ
, i
, j
);
1864 const attacks
= stepSpec
.attack
.concat(stepSpec
.both
);
1865 for (let a
of attacks
) {
1866 for (let s
of a
.steps
) {
1867 // Quick check: if step isn't compatible, don't even try
1868 if (!this.compatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1870 // Finally verify that nothing stand in-between
1871 const out
= this.findDestSquares(
1874 captureTarget: [x
, y
],
1875 captureSteps: [{steps: [s
], range: a
.range
}],
1889 return (o
.one
? false : res
);
1892 // Build a regular move from its initial and destination squares.
1893 // tr: transformation
1894 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1895 const initColor
= this.getColor(sx
, sy
);
1896 const initPiece
= this.getPiece(sx
, sy
);
1897 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1901 start: {x: sx
, y: sy
},
1905 !this.options
["rifle"] ||
1906 this.board
[ex
][ey
] == "" ||
1907 destColor
== initColor
//Recycle, Teleport
1913 c: !!tr
? tr
.c : initColor
,
1914 p: !!tr
? tr
.p : initPiece
1926 if (this.board
[ex
][ey
] != "") {
1931 c: this.getColor(ex
, ey
),
1932 p: this.getPiece(ex
, ey
)
1935 if (this.options
["cannibal"] && destColor
!= initColor
) {
1936 const lastIdx
= mv
.vanish
.length
- 1; //think "Rifle+Cannibal"
1937 let trPiece
= mv
.vanish
[lastIdx
].p
;
1938 if (this.isKing(sx
, sy
))
1939 trPiece
= C
.CannibalKingCode
[trPiece
];
1940 if (mv
.appear
.length
>= 1)
1941 mv
.appear
[0].p
= trPiece
;
1942 else if (this.options
["rifle"]) {
1965 // En-passant square, if any
1966 getEpSquare(moveOrSquare
) {
1967 if (typeof moveOrSquare
=== "string") {
1968 const square
= moveOrSquare
;
1971 return C
.SquareToCoords(square
);
1973 // Argument is a move:
1974 const move = moveOrSquare
;
1975 const s
= move.start
,
1979 Math
.abs(s
.x
- e
.x
) == 2 &&
1980 // Next conditions for variants like Atomic or Rifle, Recycle...
1982 move.appear
.length
> 0 &&
1983 this.getPieceType(0, 0, move.appear
[0].p
) == 'p'
1987 move.vanish
.length
> 0 &&
1988 this.getPieceType(0, 0, move.vanish
[0].p
) == 'p'
1996 return undefined; //default
1999 // Special case of en-passant captures: treated separately
2000 getEnpassantCaptures([x
, y
]) {
2001 const color
= this.getColor(x
, y
);
2002 const shiftX
= (color
== 'w' ? -1 : 1);
2003 const oppCols
= this.getOppCols(color
);
2006 this.epSquare
.x
== x
+ shiftX
&& //NOTE: epSquare.x not on edge
2007 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
2008 // Doublemove (and Progressive?) guards:
2009 this.board
[this.epSquare
.x
][this.epSquare
.y
] == "" &&
2010 oppCols
.includes(this.getColor(x
, this.epSquare
.y
))
2012 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
2013 this.board
[epx
][epy
] = this.board
[x
][this.epSquare
.y
];
2014 let enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
2015 this.board
[epx
][epy
] = "";
2016 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
2017 enpassantMove
.vanish
[lastIdx
].x
= x
;
2018 return [enpassantMove
];
2023 getCastleMoves([x
, y
], finalSquares
, castleWith
, castleFlags
) {
2024 const c
= this.getColor(x
, y
);
2025 castleFlags
= castleFlags
|| this.castleFlags
[c
];
2028 const oppCols
= this.getOppCols(c
);
2032 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
2033 const castlingKing
= this.getPiece(x
, y
);
2034 castlingCheck: for (
2037 castleSide
++ //large, then small
2039 if (castleFlags
[castleSide
] >= this.size
.y
)
2041 // If this code is reached, rook and king are on initial position
2043 // NOTE: in some variants this is not a rook
2044 const rookPos
= castleFlags
[castleSide
];
2045 const castlingPiece
= this.getPiece(x
, rookPos
);
2047 this.board
[x
][rookPos
] == "" ||
2048 this.getColor(x
, rookPos
) != c
||
2049 (castleWith
&& !castleWith
.includes(castlingPiece
))
2051 // Rook is not here, or changed color (see Benedict)
2054 // Nothing on the path of the king ? (and no checks)
2055 const finDist
= finalSquares
[castleSide
][0] - y
;
2056 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
2060 // NOTE: next weird test because underCheck() verification
2061 // will be executed in filterValid() later.
2063 i
!= finalSquares
[castleSide
][0] &&
2064 this.underCheck([[x
, i
]], oppCols
)
2068 this.board
[x
][i
] != "" &&
2069 // NOTE: next check is enough, because of chessboard constraints
2070 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
2073 continue castlingCheck
;
2076 } while (i
!= finalSquares
[castleSide
][0]);
2077 // Nothing on the path to the rook?
2078 step
= (castleSide
== 0 ? -1 : 1);
2079 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
2080 if (this.board
[x
][i
] != "")
2081 continue castlingCheck
;
2084 // Nothing on final squares, except maybe king and castling rook?
2085 for (i
= 0; i
< 2; i
++) {
2087 finalSquares
[castleSide
][i
] != rookPos
&&
2088 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
2090 finalSquares
[castleSide
][i
] != y
||
2091 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
2094 continue castlingCheck
;
2098 // If this code is reached, castle is potentially valid
2104 y: finalSquares
[castleSide
][0],
2110 y: finalSquares
[castleSide
][1],
2116 // King might be initially disguised (Titan...)
2117 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
2118 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
2121 Math
.abs(y
- rookPos
) <= 2
2122 ? {x: x
, y: rookPos
}
2123 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
2131 ////////////////////
2134 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2135 underAttack([x
, y
], oppCols
) {
2136 // An empty square is considered as king,
2137 // since it's used only in getCastleMoves (TODO?)
2138 const king
= this.board
[x
][y
] == "" || this.isKing(x
, y
);
2141 (!this.options
["zen"] || king
) &&
2142 this.findCapturesOn(
2152 (!!this.options
["zen"] && !king
) &&
2153 this.findDestSquares(
2159 ([i1
, j1
], [i2
, j2
]) => oppCols
.includes(this.getColor(i2
, j2
))
2165 // Argument is (very generally) an array of squares (= arrays)
2166 underCheck(square_s
, oppCols
) {
2167 if (this.options
["taking"] || this.options
["dark"])
2169 return square_s
.some(sq
=> this.underAttack(sq
, oppCols
));
2172 // Scan board for king(s)
2173 searchKingPos(color
) {
2175 for (let i
=0; i
< this.size
.x
; i
++) {
2176 for (let j
=0; j
< this.size
.y
; j
++) {
2177 if (this.getColor(i
, j
) == color
&& this.isKing(i
, j
))
2184 // cb: callback returning a boolean (false if king missing)
2185 trackKingWrap(move, kingPos
, cb
) {
2186 if (move.appear
.length
== 0 && move.vanish
.length
== 0)
2189 (move.vanish
.length
> 0 ? move.vanish
[0].c : move.appear
[0].c
);
2190 let newKingPP
= null,
2192 res
= true; //a priori valid
2194 move.vanish
.find(v
=> this.isKing(0, 0, v
.p
) && v
.c
== color
);
2196 // Search king in appear array:
2198 move.appear
.find(a
=> this.isKing(0, 0, a
.p
) && a
.c
== color
);
2200 sqIdx
= kingPos
.findIndex(kp
=>
2201 kp
[0] == oldKingPP
.x
&& kp
[1] == oldKingPP
.y
);
2202 kingPos
[sqIdx
] = [newKingPP
.x
, newKingPP
.y
];
2205 res
= false; //king vanished
2207 res
&&= cb(kingPos
);
2208 if (oldKingPP
&& newKingPP
)
2209 kingPos
[sqIdx
] = [oldKingPP
.x
, oldKingPP
.y
];
2213 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2214 filterValid(moves
, color
) {
2217 const oppCols
= this.getOppCols(color
);
2218 let kingPos
= this.searchKingPos(color
);
2219 return moves
.filter(m
=> {
2220 this.playOnBoard(m
);
2221 const res
= this.trackKingWrap(m
, kingPos
, (kp
) => {
2222 return !this.underCheck(kp
, oppCols
);
2224 this.undoOnBoard(m
);
2232 // Apply a move on board
2234 for (let psq
of move.vanish
)
2235 this.board
[psq
.x
][psq
.y
] = "";
2236 for (let psq
of move.appear
)
2237 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2239 // Un-apply the played move
2241 for (let psq
of move.appear
)
2242 this.board
[psq
.x
][psq
.y
] = "";
2243 for (let psq
of move.vanish
)
2244 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2247 // NOTE: arg "castleFlags" for Coregal or Twokings
2248 updateCastleFlags(move, castleFlags
, king
) {
2249 castleFlags
= castleFlags
|| this.castleFlags
;
2250 // If flags already off, no need to re-check:
2252 Object
.values(castleFlags
).every(cvals
=>
2253 cvals
.every(val
=> val
>= this.size
.y
))
2257 // Update castling flags if start or arrive from/at rook/king locations
2258 move.appear
.concat(move.vanish
).forEach(psq
=> {
2259 if ((king
&& psq
.p
== king
) || (!king
&& this.isKing(0, 0, psq
.p
)))
2260 castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2261 // NOTE: not "else if" because king can capture enemy rook...
2265 else if (psq
.x
== this.size
.x
- 1)
2268 const fidx
= castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2270 castleFlags
[c
][fidx
] = this.size
.y
;
2277 this.updateCastleFlags(move);
2278 if (this.options
["crazyhouse"]) {
2279 move.vanish
.forEach(v
=> {
2280 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2281 if (this.ispawn
[square
])
2282 delete this.ispawn
[square
];
2284 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2285 // Assumption: something is moving
2286 const initSquare
= C
.CoordsToSquare(move.start
);
2287 const destSquare
= C
.CoordsToSquare(move.end
);
2289 this.ispawn
[initSquare
] ||
2290 (move.vanish
[0].p
== 'p' && move.appear
[0].p
!= 'p')
2292 this.ispawn
[destSquare
] = true;
2295 this.ispawn
[destSquare
] &&
2296 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2298 move.vanish
[1].p
= 'p';
2299 delete this.ispawn
[destSquare
];
2303 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2306 // Warning; atomic pawn removal isn't a capture
2307 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2309 const color
= this.turn
;
2310 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2311 // Something appears = dropped on board (some exceptions, Chakart...)
2312 if (move.appear
[i
].c
== color
) {
2313 const piece
= move.appear
[i
].p
;
2314 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2317 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2318 // Something vanish: add to reserve except if recycle & opponent
2320 this.options
["crazyhouse"] ||
2321 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2323 const piece
= move.vanish
[i
].p
;
2324 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2332 if (this.hasEnpassant
)
2333 this.epSquare
= this.getEpSquare(move);
2334 this.playOnBoard(move);
2335 this.postPlay(move);
2339 if (this.options
["dark"])
2340 this.updateEnlightened();
2341 if (this.options
["teleport"]) {
2343 this.subTurnTeleport
== 1 &&
2344 move.vanish
.length
> move.appear
.length
&&
2345 move.vanish
[1].c
== this.turn
2347 const v
= move.vanish
[move.vanish
.length
- 1];
2348 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2349 this.subTurnTeleport
= 2;
2352 this.subTurnTeleport
= 1;
2353 this.captured
= null;
2355 this.tryChangeTurn(move);
2358 tryChangeTurn(move) {
2359 if (this.isLastMove(move)) {
2360 this.turn
= C
.GetOppTurn(this.turn
);
2364 else if (!move.next
)
2371 const color
= this.turn
;
2372 const oppKingPos
= this.searchKingPos(C
.GetOppTurn(color
));
2373 if (oppKingPos
.length
== 0 || this.underCheck(oppKingPos
, [color
]))
2377 !this.options
["balance"] ||
2378 ![1, 2].includes(this.movesCount
) ||
2383 !this.options
["doublemove"] ||
2384 this.movesCount
== 0 ||
2389 !this.options
["progressive"] ||
2390 this.subTurn
== this.movesCount
+ 1
2395 // "Stop at the first move found"
2396 atLeastOneMove(color
) {
2397 for (let i
= 0; i
< this.size
.x
; i
++) {
2398 for (let j
= 0; j
< this.size
.y
; j
++) {
2399 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2400 // NOTE: in fact searching for all potential moves from i,j.
2401 // I don't believe this is an issue, for now at least.
2402 const moves
= this.getPotentialMovesFrom([i
, j
], color
);
2403 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2408 if (this.hasReserve
&& this.reserve
[color
]) {
2409 for (let p
of Object
.keys(this.reserve
[color
])) {
2410 const moves
= this.getDropMovesFrom([color
, p
]);
2411 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2418 // What is the score ? (Interesting if game is over)
2419 getCurrentScore(move_s
) {
2420 const move = move_s
[move_s
.length
- 1];
2421 // Shortcut in case the score was computed before:
2424 const oppTurn
= C
.GetOppTurn(this.turn
);
2426 w: this.searchKingPos('w'),
2427 b: this.searchKingPos('b')
2429 if (kingPos
[this.turn
].length
== 0 && kingPos
[oppTurn
].length
== 0)
2431 if (kingPos
[this.turn
].length
== 0)
2432 return (this.turn
== "w" ? "0-1" : "1-0");
2433 if (kingPos
[oppTurn
].length
== 0)
2434 return (this.turn
== "w" ? "1-0" : "0-1");
2435 if (this.atLeastOneMove(this.turn
))
2437 // No valid move: stalemate or checkmate?
2438 if (!this.underCheck(kingPos
[this.turn
], this.getOppCols(this.turn
)))
2441 return (this.turn
== "w" ? "0-1" : "1-0");
2444 playVisual(move, r
) {
2445 move.vanish
.forEach(v
=> {
2446 if (this.g_pieces
[v
.x
][v
.y
]) //can be null (e.g. Apocalypse)
2447 this.g_pieces
[v
.x
][v
.y
].remove();
2448 this.g_pieces
[v
.x
][v
.y
] = null;
2451 document
.getElementById(this.containerId
).querySelector(".chessboard");
2453 r
= chessboard
.getBoundingClientRect();
2454 const pieceWidth
= this.getPieceWidth(r
.width
);
2455 move.appear
.forEach(a
=> {
2456 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2457 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2458 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2459 this.g_pieces
[a
.x
][a
.y
].classList
.add(V
.GetColorClass(a
.c
));
2460 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2461 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2462 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2463 // Translate coordinates to use chessboard as reference:
2464 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2465 `translate(${ip - r.x}px,${jp - r.y}px)`;
2466 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2467 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2468 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2470 if (this.options
["dark"])
2471 this.graphUpdateEnlightened();
2474 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2475 buildMoveStack(move, r
) {
2476 this.moveStack
.push(move);
2477 this.computeNextMove(move);
2478 const then
= () => {
2479 const newTurn
= this.turn
;
2480 if (this.moveStack
.length
== 1 && !this.hideMoves
)
2481 this.playVisual(move, r
);
2485 board: JSON
.parse(JSON
.stringify(this.board
)) //easier
2487 this.buildMoveStack(move.next
, r
);
2490 if (this.moveStack
.length
== 1) {
2491 // Usual case (one normal move)
2492 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: true});
2493 this.moveStack
= [];
2496 this.afterPlay(this.moveStack
, newTurn
, {send: true, res: false});
2497 this.re_initFromFen(this.gameState
.fen
, this.gameState
.board
);
2498 this.playReceivedMove(this.moveStack
.slice(1), () => {
2499 this.afterPlay(this.moveStack
, newTurn
, {send: false, res: true});
2500 this.moveStack
= [];
2505 // If hiding moves, then they are revealed in play() with callback
2506 this.play(move, this.hideMoves
? then : null);
2507 if (!this.hideMoves
)
2511 // Implemented in variants using (automatic) moveStack
2512 computeNextMove(move) {}
2514 animateMoving(start
, end
, drag
, segments
, cb
) {
2515 let initPiece
= this.getDomPiece(start
.x
, start
.y
);
2516 if (!initPiece
) { //TODO: shouldn't occur!
2520 // NOTE: cloning often not required, but light enough, and simpler
2521 let movingPiece
= initPiece
.cloneNode();
2522 initPiece
.style
.opacity
= "0";
2524 document
.getElementById(this.containerId
)
2525 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2526 if (typeof start
.x
== "string") {
2527 // Need to bound width/height (was 100% for reserve pieces)
2528 const pieceWidth
= this.getPieceWidth(r
.width
);
2529 movingPiece
.style
.width
= pieceWidth
+ "px";
2530 movingPiece
.style
.height
= pieceWidth
+ "px";
2532 const maxDist
= this.getMaxDistance(r
);
2533 const apparentColor
= this.getColor(start
.x
, start
.y
);
2534 const pieces
= this.pieces(apparentColor
, start
.x
, start
.y
);
2536 const startCode
= this.getPiece(start
.x
, start
.y
);
2537 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2538 C
.AddClass_es(movingPiece
, pieces
[drag
.p
]["class"]);
2539 if (apparentColor
!= drag
.c
) {
2540 movingPiece
.classList
.remove(V
.GetColorClass(apparentColor
));
2541 movingPiece
.classList
.add(V
.GetColorClass(drag
.c
));
2544 container
.appendChild(movingPiece
);
2545 const animateSegment
= (index
, cb
) => {
2546 // NOTE: move.drag could be generalized per-segment (usage?)
2547 const [i1
, j1
] = segments
[index
][0];
2548 const [i2
, j2
] = segments
[index
][1];
2549 const dep
= this.getPixelPosition(i1
, j1
, r
);
2550 const arr
= this.getPixelPosition(i2
, j2
, r
);
2551 movingPiece
.style
.transitionDuration
= "0s";
2552 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2554 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2555 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2556 // TODO: unclear why we need this new delay below:
2558 movingPiece
.style
.transitionDuration
= duration
+ "s";
2559 // movingPiece is child of container: no need to adjust coordinates
2560 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2561 setTimeout(cb
, duration
* 1000);
2565 const animateSegmentCallback
= () => {
2566 if (index
< segments
.length
)
2567 animateSegment(index
++, animateSegmentCallback
);
2569 movingPiece
.remove();
2570 initPiece
.style
.opacity
= "1";
2574 animateSegmentCallback();
2577 // Input array of objects with at least fields x,y (e.g. PiPo)
2578 animateFading(arr
, cb
) {
2579 const animLength
= 350; //TODO: 350ms? More? Less?
2581 let fadingPiece
= this.getDomPiece(v
.x
, v
.y
);
2582 fadingPiece
.style
.transitionDuration
= (animLength
/ 1000) + "s";
2583 fadingPiece
.style
.opacity
= "0";
2585 setTimeout(cb
, animLength
);
2588 animate(move, callback
) {
2589 if (this.noAnimate
|| move.noAnimate
) {
2593 let segments
= move.segments
;
2595 segments
= [ [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]] ];
2596 let targetObj
= new TargetObj(callback
);
2597 if (move.start
.x
!= move.end
.x
|| move.start
.y
!= move.end
.y
) {
2599 this.animateMoving(move.start
, move.end
, move.drag
, segments
,
2600 () => targetObj
.increment());
2602 if (move.vanish
.length
> move.appear
.length
) {
2603 const arr
= move.vanish
.slice(move.appear
.length
)
2604 // Ignore disappearing pieces hidden by some appearing ones:
2605 .filter(v
=> move.appear
.every(a
=> a
.x
!= v
.x
|| a
.y
!= v
.y
));
2606 if (arr
.length
> 0) {
2608 this.animateFading(arr
, () => targetObj
.increment());
2612 this.tryAnimateCastle(move, () => targetObj
.increment());
2614 this.customAnimate(move, segments
, () => targetObj
.increment());
2615 if (targetObj
.target
== 0)
2619 tryAnimateCastle(move, cb
) {
2622 move.vanish
.length
== 2 &&
2623 move.appear
.length
== 2 &&
2624 this.isKing(0, 0, move.vanish
[0].p
) &&
2625 this.isKing(0, 0, move.appear
[0].p
)
2627 const start
= {x: move.vanish
[1].x
, y: move.vanish
[1].y
},
2628 end
= {x: move.appear
[1].x
, y: move.appear
[1].y
};
2629 const segments
= [ [[start
.x
, start
.y
], [end
.x
, end
.y
]] ];
2630 this.animateMoving(start
, end
, null, segments
, cb
);
2636 // Potential other animations (e.g. for Suction variant)
2637 customAnimate(move, segments
, cb
) {
2638 return 0; //nb of targets
2641 launchAnimation(moves
, container
, callback
) {
2642 if (this.hideMoves
) {
2643 for (let i
=0; i
<moves
.length
; i
++)
2644 // If hiding moves, they are revealed into play():
2645 this.play(moves
[i
], i
== moves
.length
- 1 ? callback : () => {});
2648 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2649 const animateRec
= i
=> {
2650 this.animate(moves
[i
], () => {
2651 this.play(moves
[i
]);
2652 this.playVisual(moves
[i
], r
);
2653 if (i
< moves
.length
- 1)
2654 setTimeout(() => animateRec(i
+1), 300);
2662 playReceivedMove(moves
, callback
) {
2663 // Delay if user wasn't focused:
2664 const checkDisplayThenAnimate
= (delay
) => {
2665 if (container
.style
.display
== "none") {
2666 alert("New move! Let's go back to game...");
2667 document
.getElementById("gameInfos").style
.display
= "none";
2668 container
.style
.display
= "block";
2670 () => this.launchAnimation(moves
, container
, callback
),
2676 () => this.launchAnimation(moves
, container
, callback
),
2681 let container
= document
.getElementById(this.containerId
);
2682 if (document
.hidden
) {
2683 document
.onvisibilitychange
= () => {
2684 // TODO here: page reload ?! (some issues if tab changed...)
2685 document
.onvisibilitychange
= undefined;
2686 checkDisplayThenAnimate(700);
2690 checkDisplayThenAnimate();