1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // NOTE: x coords: top to bottom (white perspective); y: left to right
7 // NOTE: ChessRules is aliased as window.C, and variants as window.V
8 export default class ChessRules
{
10 static get Aliases() {
11 return {'C': ChessRules
};
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
17 // Some variants have specific options, like the number of pawns in Monster,
18 // or the board size for Pandemonium.
19 // Users can generally select a randomness level from 0 to 2.
20 static get Options() {
24 variable: "randomness",
27 {label: "Deterministic", value: 0},
28 {label: "Symmetric random", value: 1},
29 {label: "Asymmetric random", value: 2}
34 label: "Capture king",
40 label: "Falling pawn",
46 // Game modifiers (using "elementary variants"). Default: false
49 "balance", //takes precedence over doublemove & progressive
53 "cylinder", //ok with all
57 "progressive", //(natural) priority over doublemove
66 get pawnPromotions() {
67 return ['q', 'r', 'n', 'b'];
70 // Some variants don't have flags:
79 // En-passant captures allowed?
86 !!this.options
["crazyhouse"] ||
87 (!!this.options
["recycle"] && !this.options
["teleport"])
90 // Some variants do not store reserve state (Align4, Chakart...)
92 return this.hasReserve
;
96 return !!this.options
["dark"];
99 // Some variants use click infos:
101 if (typeof coords
.x
!= "number")
102 return null; //click on reserves
104 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
105 this.board
[coords
.x
][coords
.y
] == ""
108 start: {x: this.captured
.x
, y: this.captured
.y
},
113 c: this.captured
.c
, //this.turn,
119 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
128 // 3a --> {x:3, y:10}
129 static SquareToCoords(sq
) {
130 return ArrayFun
.toObject(["x", "y"],
131 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
134 // {x:11, y:12} --> bc
135 static CoordsToSquare(cd
) {
136 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
140 if (typeof cd
.x
== "number") {
142 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
146 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
149 idToCoords(targetId
) {
151 return null; //outside page, maybe...
152 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
154 idParts
.length
< 2 ||
155 idParts
[0] != this.containerId
||
156 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
160 const squares
= idParts
[1].split('-');
161 if (squares
[0] == "sq")
162 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
163 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
164 return {x: squares
[1], y: squares
[2]};
170 // Turn "wb" into "B" (for FEN)
172 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
175 // Turn "p" into "bp" (for board)
177 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
180 // Setup the initial random-or-not (asymmetric-or-not) position
181 genRandInitFen(seed
) {
182 let fen
, flags
= "0707";
183 if (!this.options
.randomness
)
185 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
189 Random
.setSeed(seed
);
190 let pieces
= {w: new Array(8), b: new Array(8)};
192 // Shuffle pieces on first (and last rank if randomness == 2)
193 for (let c
of ["w", "b"]) {
194 if (c
== 'b' && this.options
.randomness
== 1) {
195 pieces
['b'] = pieces
['w'];
200 let positions
= ArrayFun
.range(8);
202 // Get random squares for bishops
203 let randIndex
= 2 * Random
.randInt(4);
204 const bishop1Pos
= positions
[randIndex
];
205 // The second bishop must be on a square of different color
206 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
207 const bishop2Pos
= positions
[randIndex_tmp
];
208 // Remove chosen squares
209 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
210 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
212 // Get random squares for knights
213 randIndex
= Random
.randInt(6);
214 const knight1Pos
= positions
[randIndex
];
215 positions
.splice(randIndex
, 1);
216 randIndex
= Random
.randInt(5);
217 const knight2Pos
= positions
[randIndex
];
218 positions
.splice(randIndex
, 1);
220 // Get random square for queen
221 randIndex
= Random
.randInt(4);
222 const queenPos
= positions
[randIndex
];
223 positions
.splice(randIndex
, 1);
225 // Rooks and king positions are now fixed,
226 // because of the ordering rook-king-rook
227 const rook1Pos
= positions
[0];
228 const kingPos
= positions
[1];
229 const rook2Pos
= positions
[2];
231 // Finally put the shuffled pieces in the board array
232 pieces
[c
][rook1Pos
] = "r";
233 pieces
[c
][knight1Pos
] = "n";
234 pieces
[c
][bishop1Pos
] = "b";
235 pieces
[c
][queenPos
] = "q";
236 pieces
[c
][kingPos
] = "k";
237 pieces
[c
][bishop2Pos
] = "b";
238 pieces
[c
][knight2Pos
] = "n";
239 pieces
[c
][rook2Pos
] = "r";
240 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
243 pieces
["b"].join("") +
244 "/pppppppp/8/8/8/8/PPPPPPPP/" +
245 pieces
["w"].join("").toUpperCase() +
249 // Add turn + flags + enpassant (+ reserve)
252 parts
.push(`"flags":"${flags}"`);
253 if (this.hasEnpassant
)
254 parts
.push('"enpassant":"-"');
256 parts
.push('"reserve":"000000000000"');
257 if (this.options
["crazyhouse"])
258 parts
.push('"ispawn":"-"');
259 if (parts
.length
>= 1)
260 fen
+= " {" + parts
.join(",") + "}";
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)
280 this.getPosition() + " " +
281 this.getTurnFen() + " " +
286 parts
.push(`"flags":"${this.getFlagsFen()}"`);
287 if (this.hasEnpassant
)
288 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
289 if (this.hasReserveFen
)
290 parts
.push(`"reserve":"${this.getReserveFen()}"`);
291 if (this.options
["crazyhouse"])
292 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
293 if (parts
.length
>= 1)
294 fen
+= " {" + parts
.join(",") + "}";
298 static FenEmptySquares(count
) {
299 // if more than 9 consecutive free spaces, break the integer,
300 // otherwise FEN parsing will fail.
303 // Most boards of size < 18:
305 return "9" + (count
- 9);
307 return "99" + (count
- 18);
310 // Position part of the FEN string
313 for (let i
= 0; i
< this.size
.y
; i
++) {
315 for (let j
= 0; j
< this.size
.x
; j
++) {
316 if (this.board
[i
][j
] == "")
319 if (emptyCount
> 0) {
320 // Add empty squares in-between
321 position
+= C
.FenEmptySquares(emptyCount
);
324 position
+= this.board2fen(this.board
[i
][j
]);
329 position
+= C
.FenEmptySquares(emptyCount
);
330 if (i
< this.size
.y
- 1)
331 position
+= "/"; //separate rows
340 // Flags part of the FEN string
342 return ["w", "b"].map(c
=> {
343 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
347 // Enpassant part of the FEN string
350 return "-"; //no en-passant
351 return C
.CoordsToSquare(this.epSquare
);
356 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
361 const squares
= Object
.keys(this.ispawn
);
362 if (squares
.length
== 0)
364 return squares
.join(",");
367 // Set flags from fen (castle: white a,h then black a,h)
370 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
371 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
379 this.options
= o
.options
;
380 // Fill missing options (always the case if random challenge)
381 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
382 if (this.options
[opt
.variable
] === undefined)
383 this.options
[opt
.variable
] = opt
.defaut
;
386 // This object will be used only for initial FEN generation
388 this.playerColor
= o
.color
;
389 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
391 // Fen string fully describes the game state
393 o
.fen
= this.genRandInitFen(o
.seed
);
394 const fenParsed
= this.parseFen(o
.fen
);
395 this.board
= this.getBoard(fenParsed
.position
);
396 this.turn
= fenParsed
.turn
;
397 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
398 this.setOtherVariables(fenParsed
);
400 // Graphical (can use variables defined above)
401 this.containerId
= o
.element
;
402 this.graphicalInit();
405 // Turn position fen into double array ["wb","wp","bk",...]
407 const rows
= position
.split("/");
408 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
409 for (let i
= 0; i
< rows
.length
; i
++) {
411 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
412 const character
= rows
[i
][indexInRow
];
413 const num
= parseInt(character
, 10);
414 // If num is a number, just shift j:
417 // Else: something at position i,j
419 board
[i
][j
++] = this.fen2board(character
);
425 // Some additional variables from FEN (variant dependant)
426 setOtherVariables(fenParsed
) {
427 // Set flags and enpassant:
429 this.setFlags(fenParsed
.flags
);
430 if (this.hasEnpassant
)
431 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
433 this.initReserves(fenParsed
.reserve
);
434 if (this.options
["crazyhouse"])
435 this.initIspawn(fenParsed
.ispawn
);
436 this.subTurn
= 1; //may be unused
437 if (this.options
["teleport"]) {
438 this.subTurnTeleport
= 1;
439 this.captured
= null;
441 if (this.options
["dark"]) {
442 // Setup enlightened: squares reachable by player side
443 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
444 this.updateEnlightened();
448 updateEnlightened() {
449 this.oldEnlightened
= this.enlightened
;
450 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
451 // Add pieces positions + all squares reachable by moves (includes Zen):
452 for (let x
=0; x
<this.size
.x
; x
++) {
453 for (let y
=0; y
<this.size
.y
; y
++) {
454 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
456 this.enlightened
[x
][y
] = true;
457 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
458 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
464 this.enlightEnpassant();
467 // Include square of the en-passant capturing square:
469 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
470 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
471 for (let step
of steps
) {
472 const x
= this.epSquare
.x
- step
[0],
473 y
= this.getY(this.epSquare
.y
- step
[1]);
475 this.onBoard(x
, y
) &&
476 this.getColor(x
, y
) == this.playerColor
&&
477 this.getPieceType(x
, y
) == "p"
479 this.enlightened
[x
][this.epSquare
.y
] = true;
485 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
486 initReserves(reserveStr
) {
487 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
488 this.reserve
= { w: {}, b: {} };
489 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
490 const L
= pieceName
.length
;
491 for (let i
of ArrayFun
.range(2 * L
)) {
493 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
495 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
499 initIspawn(ispawnStr
) {
500 if (ispawnStr
!= "-")
501 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
506 getNbReservePieces(color
) {
508 Object
.values(this.reserve
[color
]).reduce(
509 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
513 getRankInReserve(c
, p
) {
514 const pieces
= Object
.keys(this.pieces());
515 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
516 let toTest
= pieces
.slice(0, lastIndex
);
517 return toTest
.reduce(
518 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
524 getPieceWidth(rwidth
) {
525 return (rwidth
/ this.size
.y
);
528 getReserveSquareSize(rwidth
, nbR
) {
529 const sqSize
= this.getPieceWidth(rwidth
);
530 return Math
.min(sqSize
, rwidth
/ nbR
);
533 getReserveNumId(color
, piece
) {
534 return `${this.containerId}|rnum-${color}${piece}`;
537 static AddClass_es(piece
, class_es
) {
538 if (!Array
.isArray(class_es
))
539 class_es
= [class_es
];
540 class_es
.forEach(cl
=> {
541 piece
.classList
.add(cl
);
545 static RemoveClass_es(piece
, class_es
) {
546 if (!Array
.isArray(class_es
))
547 class_es
= [class_es
];
548 class_es
.forEach(cl
=> {
549 piece
.classList
.remove(cl
);
554 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
555 window
.onresize
= () => this.re_drawBoardElements();
556 this.re_drawBoardElements();
557 this.initMouseEvents();
559 document
.getElementById(this.containerId
).querySelector(".chessboard");
562 re_drawBoardElements() {
563 const board
= this.getSvgChessboard();
564 const oppCol
= C
.GetOppCol(this.playerColor
);
566 document
.getElementById(this.containerId
).querySelector(".chessboard");
567 chessboard
.innerHTML
= "";
568 chessboard
.insertAdjacentHTML('beforeend', board
);
569 // Compare window ratio width / height to aspectRatio:
570 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
571 let cbWidth
, cbHeight
;
572 const vRatio
= this.size
.ratio
|| 1;
573 if (windowRatio
<= vRatio
) {
574 // Limiting dimension is width:
575 cbWidth
= Math
.min(window
.innerWidth
, 767);
576 cbHeight
= cbWidth
/ vRatio
;
579 // Limiting dimension is height:
580 cbHeight
= Math
.min(window
.innerHeight
, 767);
581 cbWidth
= cbHeight
* vRatio
;
583 if (this.hasReserve
) {
584 const sqSize
= cbWidth
/ this.size
.y
;
585 // NOTE: allocate space for reserves (up/down) even if they are empty
586 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
587 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
588 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
589 cbWidth
= cbHeight
* vRatio
;
592 chessboard
.style
.width
= cbWidth
+ "px";
593 chessboard
.style
.height
= cbHeight
+ "px";
594 // Center chessboard:
595 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
596 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
597 chessboard
.style
.left
= spaceLeft
+ "px";
598 chessboard
.style
.top
= spaceTop
+ "px";
599 // Give sizes instead of recomputing them,
600 // because chessboard might not be drawn yet.
609 // Get SVG board (background, no pieces)
611 const flipped
= (this.playerColor
== 'b');
614 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
615 class="chessboard_SVG">`;
616 for (let i
=0; i
< this.size
.x
; i
++) {
617 for (let j
=0; j
< this.size
.y
; j
++) {
618 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
619 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
620 let classes
= this.getSquareColorClass(ii
, jj
);
621 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
622 classes
+= " in-shadow";
623 // NOTE: x / y reversed because coordinates system is reversed.
627 id="${this.coordsToId({x: ii, y: jj})}"
639 // Generally light square bottom-right
640 getSquareColorClass(x
, y
) {
641 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
646 // Refreshing: delete old pieces first
647 for (let i
=0; i
<this.size
.x
; i
++) {
648 for (let j
=0; j
<this.size
.y
; j
++) {
649 if (this.g_pieces
[i
][j
]) {
650 this.g_pieces
[i
][j
].remove();
651 this.g_pieces
[i
][j
] = null;
657 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
659 document
.getElementById(this.containerId
).querySelector(".chessboard");
661 r
= chessboard
.getBoundingClientRect();
662 const pieceWidth
= this.getPieceWidth(r
.width
);
663 for (let i
=0; i
< this.size
.x
; i
++) {
664 for (let j
=0; j
< this.size
.y
; j
++) {
665 if (this.board
[i
][j
] != "") {
666 const color
= this.getColor(i
, j
);
667 const piece
= this.getPiece(i
, j
);
668 this.g_pieces
[i
][j
] = document
.createElement("piece");
669 C
.AddClass_es(this.g_pieces
[i
][j
],
670 this.pieces(color
, i
, j
)[piece
]["class"]);
671 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
672 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
673 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
674 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
675 // Translate coordinates to use chessboard as reference:
676 this.g_pieces
[i
][j
].style
.transform
=
677 `translate(${ip - r.x}px,${jp - r.y}px)`;
678 if (this.enlightened
&& !this.enlightened
[i
][j
])
679 this.g_pieces
[i
][j
].classList
.add("hidden");
680 chessboard
.appendChild(this.g_pieces
[i
][j
]);
685 this.re_drawReserve(['w', 'b'], r
);
688 // NOTE: assume this.reserve != null
689 re_drawReserve(colors
, r
) {
691 // Remove (old) reserve pieces
692 for (let c
of colors
) {
693 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
694 this.r_pieces
[c
][p
].remove();
695 delete this.r_pieces
[c
][p
];
696 const numId
= this.getReserveNumId(c
, p
);
697 document
.getElementById(numId
).remove();
702 this.r_pieces
= { w: {}, b: {} };
703 let container
= document
.getElementById(this.containerId
);
705 r
= container
.querySelector(".chessboard").getBoundingClientRect();
706 for (let c
of colors
) {
707 let reservesDiv
= document
.getElementById("reserves_" + c
);
709 reservesDiv
.remove();
710 if (!this.reserve
[c
])
712 const nbR
= this.getNbReservePieces(c
);
715 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
717 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
718 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
719 let rcontainer
= document
.createElement("div");
720 rcontainer
.id
= "reserves_" + c
;
721 rcontainer
.classList
.add("reserves");
722 rcontainer
.style
.left
= i0
+ "px";
723 rcontainer
.style
.top
= j0
+ "px";
724 // NOTE: +1 fix display bug on Firefox at least
725 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
726 rcontainer
.style
.height
= sqResSize
+ "px";
727 container
.appendChild(rcontainer
);
728 for (let p
of Object
.keys(this.reserve
[c
])) {
729 if (this.reserve
[c
][p
] == 0)
731 let r_cell
= document
.createElement("div");
732 r_cell
.id
= this.coordsToId({x: c
, y: p
});
733 r_cell
.classList
.add("reserve-cell");
734 r_cell
.style
.width
= sqResSize
+ "px";
735 r_cell
.style
.height
= sqResSize
+ "px";
736 rcontainer
.appendChild(r_cell
);
737 let piece
= document
.createElement("piece");
738 C
.AddClass_es(piece
, this.pieces(c
, c
, p
)[p
]["class"]);
739 piece
.classList
.add(C
.GetColorClass(c
));
740 piece
.style
.width
= "100%";
741 piece
.style
.height
= "100%";
742 this.r_pieces
[c
][p
] = piece
;
743 r_cell
.appendChild(piece
);
744 let number
= document
.createElement("div");
745 number
.textContent
= this.reserve
[c
][p
];
746 number
.classList
.add("reserve-num");
747 number
.id
= this.getReserveNumId(c
, p
);
748 const fontSize
= "1.3em";
749 number
.style
.fontSize
= fontSize
;
750 number
.style
.fontSize
= fontSize
;
751 r_cell
.appendChild(number
);
757 updateReserve(color
, piece
, count
) {
758 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
759 piece
= "k"; //capturing cannibal king: back to king form
760 const oldCount
= this.reserve
[color
][piece
];
761 this.reserve
[color
][piece
] = count
;
762 // Redrawing is much easier if count==0
763 if ([oldCount
, count
].includes(0))
764 this.re_drawReserve([color
]);
766 const numId
= this.getReserveNumId(color
, piece
);
767 document
.getElementById(numId
).textContent
= count
;
771 // Apply diff this.enlightened --> oldEnlightened on board
772 graphUpdateEnlightened() {
774 document
.getElementById(this.containerId
).querySelector(".chessboard");
775 const r
= chessboard
.getBoundingClientRect();
776 const pieceWidth
= this.getPieceWidth(r
.width
);
777 for (let x
=0; x
<this.size
.x
; x
++) {
778 for (let y
=0; y
<this.size
.y
; y
++) {
779 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
780 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
781 elt
.classList
.add("in-shadow");
782 if (this.g_pieces
[x
][y
])
783 this.g_pieces
[x
][y
].classList
.add("hidden");
785 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
786 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
787 elt
.classList
.remove("in-shadow");
788 if (this.g_pieces
[x
][y
])
789 this.g_pieces
[x
][y
].classList
.remove("hidden");
795 // Resize board: no need to destroy/recreate pieces
798 document
.getElementById(this.containerId
).querySelector(".chessboard");
799 const r
= chessboard
.getBoundingClientRect();
800 const multFact
= (mode
== "up" ? 1.05 : 0.95);
801 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
803 const vRatio
= this.size
.ratio
|| 1;
804 if (newWidth
> window
.innerWidth
) {
805 newWidth
= window
.innerWidth
;
806 newHeight
= newWidth
/ vRatio
;
808 if (newHeight
> window
.innerHeight
) {
809 newHeight
= window
.innerHeight
;
810 newWidth
= newHeight
* vRatio
;
812 chessboard
.style
.width
= newWidth
+ "px";
813 chessboard
.style
.height
= newHeight
+ "px";
814 const newX
= (window
.innerWidth
- newWidth
) / 2;
815 chessboard
.style
.left
= newX
+ "px";
816 const newY
= (window
.innerHeight
- newHeight
) / 2;
817 chessboard
.style
.top
= newY
+ "px";
818 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
819 const pieceWidth
= this.getPieceWidth(newWidth
);
820 // NOTE: next "if" for variants which use squares filling
821 // instead of "physical", moving pieces
823 for (let i
=0; i
< this.size
.x
; i
++) {
824 for (let j
=0; j
< this.size
.y
; j
++) {
825 if (this.g_pieces
[i
][j
]) {
826 // NOTE: could also use CSS transform "scale"
827 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
828 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
829 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
830 // Translate coordinates to use chessboard as reference:
831 this.g_pieces
[i
][j
].style
.transform
=
832 `translate(${ip - newX}px,${jp - newY}px)`;
838 this.rescaleReserve(newR
);
842 for (let c
of ['w','b']) {
843 if (!this.reserve
[c
])
845 const nbR
= this.getNbReservePieces(c
);
848 // Resize container first
849 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
850 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
851 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
852 let rcontainer
= document
.getElementById("reserves_" + c
);
853 rcontainer
.style
.left
= i0
+ "px";
854 rcontainer
.style
.top
= j0
+ "px";
855 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
856 rcontainer
.style
.height
= sqResSize
+ "px";
857 // And then reserve cells:
858 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
859 Object
.keys(this.reserve
[c
]).forEach(p
=> {
860 if (this.reserve
[c
][p
] == 0)
862 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
863 r_cell
.style
.width
= sqResSize
+ "px";
864 r_cell
.style
.height
= sqResSize
+ "px";
869 // Return the absolute pixel coordinates given current position.
870 // Our coordinate system differs from CSS one (x <--> y).
871 // We return here the CSS coordinates (more useful).
872 getPixelPosition(i
, j
, r
) {
874 return [0, 0]; //piece vanishes
876 if (typeof i
== "string") {
877 // Reserves: need to know the rank of piece
878 const nbR
= this.getNbReservePieces(i
);
879 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
880 x
= this.getRankInReserve(i
, j
) * rsqSize
;
881 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
884 const sqSize
= r
.width
/ this.size
.y
;
885 const flipped
= (this.playerColor
== 'b');
886 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
887 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
889 return [r
.x
+ x
, r
.y
+ y
];
893 let container
= document
.getElementById(this.containerId
);
894 let chessboard
= container
.querySelector(".chessboard");
896 const getOffset
= e
=> {
899 return {x: e
.clientX
, y: e
.clientY
};
900 let touchLocation
= null;
901 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
902 // Touch screen, dragstart
903 touchLocation
= e
.targetTouches
[0];
904 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
905 // Touch screen, dragend
906 touchLocation
= e
.changedTouches
[0];
908 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
909 return {x: 0, y: 0}; //shouldn't reach here =)
912 const centerOnCursor
= (piece
, e
) => {
913 const centerShift
= this.getPieceWidth(r
.width
) / 2;
914 const offset
= getOffset(e
);
915 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
916 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
921 startPiece
, curPiece
= null,
923 const mousedown
= (e
) => {
924 // Disable zoom on smartphones:
925 if (e
.touches
&& e
.touches
.length
> 1)
927 r
= chessboard
.getBoundingClientRect();
928 pieceWidth
= this.getPieceWidth(r
.width
);
929 const cd
= this.idToCoords(e
.target
.id
);
931 const move = this.doClick(cd
);
933 this.playPlusVisual(move);
935 const [x
, y
] = Object
.values(cd
);
936 if (typeof x
!= "number")
937 startPiece
= this.r_pieces
[x
][y
];
939 startPiece
= this.g_pieces
[x
][y
];
940 if (startPiece
&& this.canIplay(x
, y
)) {
943 curPiece
= startPiece
.cloneNode();
944 curPiece
.style
.transform
= "none";
945 curPiece
.style
.zIndex
= 5;
946 curPiece
.style
.width
= pieceWidth
+ "px";
947 curPiece
.style
.height
= pieceWidth
+ "px";
948 centerOnCursor(curPiece
, e
);
949 container
.appendChild(curPiece
);
950 startPiece
.style
.opacity
= "0.4";
951 chessboard
.style
.cursor
= "none";
957 const mousemove
= (e
) => {
960 centerOnCursor(curPiece
, e
);
962 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
963 // Attempt to prevent horizontal swipe...
967 const mouseup
= (e
) => {
970 const [x
, y
] = [start
.x
, start
.y
];
973 chessboard
.style
.cursor
= "pointer";
974 startPiece
.style
.opacity
= "1";
975 const offset
= getOffset(e
);
976 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
978 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
980 // NOTE: clearly suboptimal, but much easier, and not a big deal.
981 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
982 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
983 const moves
= this.filterValid(potentialMoves
);
984 if (moves
.length
>= 2)
985 this.showChoices(moves
, r
);
986 else if (moves
.length
== 1)
987 this.playPlusVisual(moves
[0], r
);
992 if ('onmousedown' in window
) {
993 document
.addEventListener("mousedown", mousedown
);
994 document
.addEventListener("mousemove", mousemove
);
995 document
.addEventListener("mouseup", mouseup
);
996 document
.addEventListener("wheel",
997 (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down"));
999 if ('ontouchstart' in window
) {
1000 // https://stackoverflow.com/a/42509310/12660887
1001 document
.addEventListener("touchstart", mousedown
, {passive: false});
1002 document
.addEventListener("touchmove", mousemove
, {passive: false});
1003 document
.addEventListener("touchend", mouseup
, {passive: false});
1005 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1008 showChoices(moves
, r
) {
1009 let container
= document
.getElementById(this.containerId
);
1010 let chessboard
= container
.querySelector(".chessboard");
1011 let choices
= document
.createElement("div");
1012 choices
.id
= "choices";
1014 r
= chessboard
.getBoundingClientRect();
1015 choices
.style
.width
= r
.width
+ "px";
1016 choices
.style
.height
= r
.height
+ "px";
1017 choices
.style
.left
= r
.x
+ "px";
1018 choices
.style
.top
= r
.y
+ "px";
1019 chessboard
.style
.opacity
= "0.5";
1020 container
.appendChild(choices
);
1021 const squareWidth
= r
.width
/ this.size
.y
;
1022 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1023 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1024 const color
= moves
[0].appear
[0].c
;
1025 const callback
= (m
) => {
1026 chessboard
.style
.opacity
= "1";
1027 container
.removeChild(choices
);
1028 this.playPlusVisual(m
, r
);
1030 for (let i
=0; i
< moves
.length
; i
++) {
1031 let choice
= document
.createElement("div");
1032 choice
.classList
.add("choice");
1033 choice
.style
.width
= squareWidth
+ "px";
1034 choice
.style
.height
= squareWidth
+ "px";
1035 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1036 choice
.style
.top
= firstUpTop
+ "px";
1037 choice
.style
.backgroundColor
= "lightyellow";
1038 choice
.onclick
= () => callback(moves
[i
]);
1039 const piece
= document
.createElement("piece");
1040 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1041 C
.AddClass_es(piece
,
1042 this.pieces(color
, moves
[i
].end
.x
, moves
[i
].end
.y
)[cdisp
]["class"]);
1043 piece
.classList
.add(C
.GetColorClass(color
));
1044 piece
.style
.width
= "100%";
1045 piece
.style
.height
= "100%";
1046 choice
.appendChild(piece
);
1047 choices
.appendChild(choice
);
1058 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1062 // Color of thing on square (i,j). 'undefined' if square is empty
1064 if (typeof i
== "string")
1065 return i
; //reserves
1066 return this.board
[i
][j
].charAt(0);
1069 static GetColorClass(c
) {
1074 return "other-color"; //unidentified color
1077 // Assume square i,j isn't empty
1079 if (typeof j
== "string")
1080 return j
; //reserves
1081 return this.board
[i
][j
].charAt(1);
1084 // Piece type on square (i,j)
1085 getPieceType(i
, j
, p
) {
1087 p
= this.getPiece(i
, j
);
1088 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1091 // Get opponent color
1092 static GetOppCol(color
) {
1093 return (color
== "w" ? "b" : "w");
1096 // Can thing on square1 capture (enemy) thing on square2?
1097 canTake([x1
, y1
], [x2
, y2
]) {
1098 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1101 // Is (x,y) on the chessboard?
1103 return (x
>= 0 && x
< this.size
.x
&&
1104 y
>= 0 && y
< this.size
.y
);
1107 // Am I allowed to move thing at square x,y ?
1109 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1112 ////////////////////////
1113 // PIECES SPECIFICATIONS
1115 pieces(color
, x
, y
) {
1116 const pawnShift
= (color
== "w" ? -1 : 1);
1117 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1118 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1124 steps: [[pawnShift
, 0]],
1125 range: (initRank
? 2 : 1)
1130 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1139 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1148 [1, 2], [1, -2], [-1, 2], [-1, -2],
1149 [2, 1], [-2, 1], [2, -1], [-2, -1]
1159 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1168 [0, 1], [0, -1], [1, 0], [-1, 0],
1169 [1, 1], [1, -1], [-1, 1], [-1, -1]
1180 [0, 1], [0, -1], [1, 0], [-1, 0],
1181 [1, 1], [1, -1], [-1, 1], [-1, -1]
1188 '!': {"class": "king-pawn", moveas: "p"},
1189 '#': {"class": "king-rook", moveas: "r"},
1190 '$': {"class": "king-knight", moveas: "n"},
1191 '%': {"class": "king-bishop", moveas: "b"},
1192 '*': {"class": "king-queen", moveas: "q"}
1196 ////////////////////
1199 // For Cylinder: get Y coordinate
1201 if (!this.options
["cylinder"])
1203 let res
= y
% this.size
.y
;
1209 // Stop at the first capture found
1210 atLeastOneCapture(color
) {
1211 color
= color
|| this.turn
;
1212 const oppCol
= C
.GetOppCol(color
);
1213 for (let i
= 0; i
< this.size
.x
; i
++) {
1214 for (let j
= 0; j
< this.size
.y
; j
++) {
1215 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1216 const allSpecs
= this.pieces(color
, i
, j
)
1217 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1219 specs
= allSpecs
[specs
.moveas
];
1220 const attacks
= specs
.attack
|| specs
.moves
;
1221 for (let a
of attacks
) {
1222 outerLoop: for (let step
of a
.steps
) {
1223 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1224 let stepCounter
= 1;
1225 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1226 if (a
.range
<= stepCounter
++)
1229 jj
= this.getY(jj
+ step
[1]);
1232 this.onBoard(ii
, jj
) &&
1233 this.getColor(ii
, jj
) == oppCol
&&
1235 [this.getBasicMove([i
, j
], [ii
, jj
])]
1248 getDropMovesFrom([c
, p
]) {
1249 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1250 // (but not necessarily otherwise: atLeastOneMove() etc)
1251 if (this.reserve
[c
][p
] == 0)
1254 for (let i
=0; i
<this.size
.x
; i
++) {
1255 for (let j
=0; j
<this.size
.y
; j
++) {
1257 this.board
[i
][j
] == "" &&
1258 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1261 (c
== 'w' && i
< this.size
.x
- 1) ||
1267 start: {x: c
, y: p
},
1269 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1279 // All possible moves from selected square
1280 getPotentialMovesFrom(sq
, color
) {
1281 if (this.subTurnTeleport
== 2)
1283 if (typeof sq
[0] == "string")
1284 return this.getDropMovesFrom(sq
);
1285 if (this.isImmobilized(sq
))
1287 const piece
= this.getPieceType(sq
[0], sq
[1]);
1288 let moves
= this.getPotentialMovesOf(piece
, sq
);
1291 this.hasEnpassant
&&
1294 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1299 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1301 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1303 return this.postProcessPotentialMoves(moves
);
1306 postProcessPotentialMoves(moves
) {
1307 if (moves
.length
== 0)
1309 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1310 const oppCol
= C
.GetOppCol(color
);
1312 if (this.options
["capture"] && this.atLeastOneCapture())
1313 moves
= this.capturePostProcess(moves
, oppCol
);
1315 if (this.options
["atomic"])
1316 this.atomicPostProcess(moves
, oppCol
);
1320 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1322 this.pawnPostProcess(moves
, color
, oppCol
);
1326 this.options
["cannibal"] &&
1327 this.options
["rifle"]
1329 // In this case a rifle-capture from last rank may promote a pawn
1330 this.riflePromotePostProcess(moves
, color
);
1336 capturePostProcess(moves
, oppCol
) {
1337 // Filter out non-capturing moves (not using m.vanish because of
1338 // self captures of Recycle and Teleport).
1339 return moves
.filter(m
=> {
1341 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1342 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1347 atomicPostProcess(moves
, oppCol
) {
1348 moves
.forEach(m
=> {
1350 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1351 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1364 for (let step
of steps
) {
1365 let x
= m
.end
.x
+ step
[0];
1366 let y
= this.getY(m
.end
.y
+ step
[1]);
1368 this.onBoard(x
, y
) &&
1369 this.board
[x
][y
] != "" &&
1370 this.getPieceType(x
, y
) != "p"
1374 p: this.getPiece(x
, y
),
1375 c: this.getColor(x
, y
),
1382 if (!this.options
["rifle"])
1383 m
.appear
.pop(); //nothing appears
1388 pawnPostProcess(moves
, color
, oppCol
) {
1390 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1391 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1392 moves
.forEach(m
=> {
1393 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1394 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1395 const promotionOk
= (
1397 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1400 return; //nothing to do
1401 if (this.options
["pawnfall"]) {
1405 let finalPieces
= ["p"];
1407 this.options
["cannibal"] &&
1408 this.board
[x2
][y2
] != "" &&
1409 this.getColor(x2
, y2
) == oppCol
1411 finalPieces
= [this.getPieceType(x2
, y2
)];
1414 finalPieces
= this.pawnPromotions
;
1415 m
.appear
[0].p
= finalPieces
[0];
1416 if (initPiece
== "!") //cannibal king-pawn
1417 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1418 for (let i
=1; i
<finalPieces
.length
; i
++) {
1419 const piece
= finalPieces
[i
];
1422 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1424 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1425 moreMoves
.push(newMove
);
1428 Array
.prototype.push
.apply(moves
, moreMoves
);
1431 riflePromotePostProcess(moves
, color
) {
1432 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1434 moves
.forEach(m
=> {
1436 m
.start
.x
== lastRank
&&
1437 m
.appear
.length
>= 1 &&
1438 m
.appear
[0].p
== "p" &&
1439 m
.appear
[0].x
== m
.start
.x
&&
1440 m
.appear
[0].y
== m
.start
.y
1442 m
.appear
[0].p
= this.pawnPromotions
[0];
1443 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1444 let newMv
= JSON
.parse(JSON
.stringify(m
));
1445 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1446 newMoves
.push(newMv
);
1450 Array
.prototype.push
.apply(moves
, newMoves
);
1453 // NOTE: using special symbols to not interfere with variants' pieces codes
1454 static get CannibalKings() {
1465 static get CannibalKingCode() {
1477 return !!C
.CannibalKings
[symbol
];
1481 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1482 isImmobilized([x
, y
]) {
1483 if (!this.options
["madrasi"])
1485 const color
= this.getColor(x
, y
);
1486 const oppCol
= C
.GetOppCol(color
);
1487 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1488 const allSpecs
= this.pieces(color
, x
, y
);
1489 let stepSpec
= allSpecs
[piece
];
1490 if (stepSpec
.moveas
)
1491 stepSpec
= allSpecs
[stepSpec
.moveas
];
1492 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1493 for (let a
of attacks
) {
1494 outerLoop: for (let step
of a
.steps
) {
1495 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1496 let stepCounter
= 1;
1497 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1498 if (a
.range
<= stepCounter
++)
1501 j
= this.getY(j
+ step
[1]);
1504 this.onBoard(i
, j
) &&
1505 this.getColor(i
, j
) == oppCol
&&
1506 this.getPieceType(i
, j
) == piece
1515 canStepOver(i
, j
, p
) {
1516 // In some variants, objects on boards don't stop movement (Chakart)
1517 return this.board
[i
][j
] == "";
1520 // Generic method to find possible moves of "sliding or jumping" pieces
1521 getPotentialMovesOf(piece
, [x
, y
]) {
1522 const color
= this.getColor(x
, y
);
1523 const apparentPiece
= this.getPiece(x
, y
); //how it looks
1524 const allSpecs
= this.pieces(color
, x
, y
);
1525 let stepSpec
= allSpecs
[piece
];
1526 if (stepSpec
.moveas
)
1527 stepSpec
= allSpecs
[stepSpec
.moveas
];
1529 // Next 3 for Cylinder mode:
1534 const addMove
= (start
, end
) => {
1535 let newMove
= this.getBasicMove(start
, end
);
1536 if (segments
.length
> 0) {
1537 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1538 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1540 moves
.push(newMove
);
1543 const findAddMoves
= (type
, stepArray
) => {
1544 for (let s
of stepArray
) {
1545 outerLoop: for (let step
of s
.steps
) {
1548 let [i
, j
] = [x
, y
];
1549 let stepCounter
= 0;
1551 this.onBoard(i
, j
) &&
1552 ((i
== x
&& j
== y
) || this.canStepOver(i
, j
, apparentPiece
))
1556 !explored
[i
+ "." + j
] &&
1559 explored
[i
+ "." + j
] = true;
1560 addMove([x
, y
], [i
, j
]);
1562 if (s
.range
<= stepCounter
++)
1564 const oldIJ
= [i
, j
];
1566 j
= this.getY(j
+ step
[1]);
1567 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1568 // Boundary between segments (cylinder mode)
1569 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1573 if (!this.onBoard(i
, j
))
1575 const pieceIJ
= this.getPieceType(i
, j
);
1577 type
!= "moveonly" &&
1578 !explored
[i
+ "." + j
] &&
1580 !this.options
["zen"] ||
1584 this.canTake([x
, y
], [i
, j
]) ||
1586 (this.options
["recycle"] || this.options
["teleport"]) &&
1591 explored
[i
+ "." + j
] = true;
1592 addMove([x
, y
], [i
, j
]);
1598 const specialAttack
= !!stepSpec
.attack
;
1600 findAddMoves("attack", stepSpec
.attack
);
1601 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1602 if (this.options
["zen"]) {
1603 Array
.prototype.push
.apply(moves
,
1604 this.findCapturesOn([x
, y
], {zen: true}));
1609 // Search for enemy (or not) pieces attacking [x, y]
1610 findCapturesOn([x
, y
], args
) {
1613 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1614 for (let i
=0; i
<this.size
.x
; i
++) {
1615 for (let j
=0; j
<this.size
.y
; j
++) {
1617 this.board
[i
][j
] != "" &&
1618 this.getColor(i
, j
) == args
.oppCol
&&
1619 !this.isImmobilized([i
, j
])
1621 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1622 continue; //king not captured in this way
1623 const apparentPiece
= this.getPiece(i
, j
);
1624 // Quick check: does this potential attacker target x,y ?
1625 if (this.canStepOver(x
, y
, apparentPiece
))
1627 const allSpecs
= this.pieces(args
.oppCol
, i
, j
);
1628 let stepSpec
= allSpecs
[this.getPieceType(i
, j
)];
1629 if (stepSpec
.moveas
)
1630 stepSpec
= allSpecs
[stepSpec
.moveas
];
1631 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1632 for (let a
of attacks
) {
1633 for (let s
of a
.steps
) {
1634 // Quick check: if step isn't compatible, don't even try
1635 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1637 // Finally verify that nothing stand in-between
1638 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1639 let stepCounter
= 1;
1641 this.onBoard(ii
, jj
) &&
1642 this.board
[ii
][jj
] == "" &&
1643 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1646 jj
= this.getY(jj
+ s
[1]);
1648 if (ii
== x
&& jj
== y
) {
1651 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1653 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1655 return moves
; //test for underCheck
1665 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1666 const rx
= (x2
- x1
) / step
[0],
1667 ry
= (y2
- y1
) / step
[1];
1669 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1670 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1674 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1675 // TODO: 1e-7 here is totally arbitrary
1676 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1678 distance
= Math
.round(distance
); //in case of (numerical...)
1679 if (range
< distance
)
1684 // Build a regular move from its initial and destination squares.
1685 // tr: transformation
1686 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1687 const initColor
= this.getColor(sx
, sy
);
1688 const initPiece
= this.getPiece(sx
, sy
);
1689 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1693 start: {x: sx
, y: sy
},
1697 !this.options
["rifle"] ||
1698 this.board
[ex
][ey
] == "" ||
1699 destColor
== initColor
//Recycle, Teleport
1705 c: !!tr
? tr
.c : initColor
,
1706 p: !!tr
? tr
.p : initPiece
1718 if (this.board
[ex
][ey
] != "") {
1723 c: this.getColor(ex
, ey
),
1724 p: this.getPiece(ex
, ey
)
1727 if (this.options
["cannibal"] && destColor
!= initColor
) {
1728 const lastIdx
= mv
.vanish
.length
- 1;
1729 let trPiece
= mv
.vanish
[lastIdx
].p
;
1730 if (this.isKing(this.getPiece(sx
, sy
)))
1731 trPiece
= C
.CannibalKingCode
[trPiece
];
1732 if (mv
.appear
.length
>= 1)
1733 mv
.appear
[0].p
= trPiece
;
1734 else if (this.options
["rifle"]) {
1757 // En-passant square, if any
1758 getEpSquare(moveOrSquare
) {
1759 if (typeof moveOrSquare
=== "string") {
1760 const square
= moveOrSquare
;
1763 return C
.SquareToCoords(square
);
1765 // Argument is a move:
1766 const move = moveOrSquare
;
1767 const s
= move.start
,
1771 Math
.abs(s
.x
- e
.x
) == 2 &&
1772 // Next conditions for variants like Atomic or Rifle, Recycle...
1774 move.appear
.length
> 0 &&
1775 this.getPieceType(0, 0, move.appear
[0].p
) == "p"
1779 move.vanish
.length
> 0 &&
1780 this.getPieceType(0, 0, move.vanish
[0].p
) == "p"
1788 return undefined; //default
1791 // Special case of en-passant captures: treated separately
1792 getEnpassantCaptures([x
, y
]) {
1793 const color
= this.getColor(x
, y
);
1794 const shiftX
= (color
== 'w' ? -1 : 1);
1795 const oppCol
= C
.GetOppCol(color
);
1796 let enpassantMove
= null;
1799 this.epSquare
.x
== x
+ shiftX
&&
1800 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1801 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1803 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1804 this.board
[epx
][epy
] = oppCol
+ "p";
1805 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1806 this.board
[epx
][epy
] = "";
1807 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1808 enpassantMove
.vanish
[lastIdx
].x
= x
;
1810 return !!enpassantMove
? [enpassantMove
] : [];
1813 // "castleInCheck" arg to let some variants castle under check
1814 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1815 const c
= this.getColor(x
, y
);
1818 const oppCol
= C
.GetOppCol(c
);
1822 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1823 const castlingKing
= this.getPiece(x
, y
);
1824 castlingCheck: for (
1827 castleSide
++ //large, then small
1829 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1831 // If this code is reached, rook and king are on initial position
1833 // NOTE: in some variants this is not a rook
1834 const rookPos
= this.castleFlags
[c
][castleSide
];
1835 const castlingPiece
= this.getPiece(x
, rookPos
);
1837 this.board
[x
][rookPos
] == "" ||
1838 this.getColor(x
, rookPos
) != c
||
1839 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1841 // Rook is not here, or changed color (see Benedict)
1844 // Nothing on the path of the king ? (and no checks)
1845 const finDist
= finalSquares
[castleSide
][0] - y
;
1846 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1850 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1852 this.board
[x
][i
] != "" &&
1853 // NOTE: next check is enough, because of chessboard constraints
1854 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1857 continue castlingCheck
;
1860 } while (i
!= finalSquares
[castleSide
][0]);
1861 // Nothing on the path to the rook?
1862 step
= (castleSide
== 0 ? -1 : 1);
1863 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1864 if (this.board
[x
][i
] != "")
1865 continue castlingCheck
;
1868 // Nothing on final squares, except maybe king and castling rook?
1869 for (i
= 0; i
< 2; i
++) {
1871 finalSquares
[castleSide
][i
] != rookPos
&&
1872 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1874 finalSquares
[castleSide
][i
] != y
||
1875 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1878 continue castlingCheck
;
1882 // If this code is reached, castle is valid
1888 y: finalSquares
[castleSide
][0],
1894 y: finalSquares
[castleSide
][1],
1900 // King might be initially disguised (Titan...)
1901 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1902 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1905 Math
.abs(y
- rookPos
) <= 2
1906 ? {x: x
, y: rookPos
}
1907 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1915 ////////////////////
1918 // Is (king at) given position under check by "oppCol" ?
1919 underCheck([x
, y
], oppCol
) {
1920 if (this.options
["taking"] || this.options
["dark"])
1923 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1927 // Stop at first king found (TODO: multi-kings)
1928 searchKingPos(color
) {
1929 for (let i
=0; i
< this.size
.x
; i
++) {
1930 for (let j
=0; j
< this.size
.y
; j
++) {
1931 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1935 return [-1, -1]; //king not found
1938 // Some variants (e.g. Refusal) may need to check opponent moves too
1939 filterValid(moves
, color
) {
1940 if (moves
.length
== 0)
1944 const oppCol
= C
.GetOppCol(color
);
1945 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1946 // Forbid moves either giving check or exploding opponent's king:
1947 const oppKingPos
= this.searchKingPos(oppCol
);
1948 moves
= moves
.filter(m
=> {
1950 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1951 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1954 this.playOnBoard(m
);
1955 const res
= !this.underCheck(oppKingPos
, color
);
1956 this.undoOnBoard(m
);
1960 if (this.options
["taking"] || this.options
["dark"])
1962 const kingPos
= this.searchKingPos(color
);
1963 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1964 return moves
.filter(m
=> {
1965 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1966 if (!filtered
[key
]) {
1967 this.playOnBoard(m
);
1968 let square
= kingPos
,
1969 res
= true; //a priori valid
1970 if (m
.vanish
.some(v
=> {
1971 return this.isKing(v
.p
) && v
.c
== color
;
1973 // Search king in appear array:
1975 m
.appear
.findIndex(a
=> {
1976 return this.isKing(a
.p
) && a
.c
== color
;
1978 if (newKingIdx
>= 0)
1979 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1983 res
&&= !this.underCheck(square
, oppCol
);
1984 this.undoOnBoard(m
);
1985 filtered
[key
] = res
;
1988 return filtered
[key
];
1995 // Aggregate flags into one object
1997 return this.castleFlags
;
2000 // Reverse operation
2001 disaggregateFlags(flags
) {
2002 this.castleFlags
= flags
;
2005 // Apply a move on board
2007 for (let psq
of move.vanish
)
2008 this.board
[psq
.x
][psq
.y
] = "";
2009 for (let psq
of move.appear
)
2010 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2012 // Un-apply the played move
2014 for (let psq
of move.appear
)
2015 this.board
[psq
.x
][psq
.y
] = "";
2016 for (let psq
of move.vanish
)
2017 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2020 updateCastleFlags(move) {
2021 // Update castling flags if start or arrive from/at rook/king locations
2022 move.appear
.concat(move.vanish
).forEach(psq
=> {
2024 this.board
[psq
.x
][psq
.y
] != "" &&
2025 this.getPieceType(psq
.x
, psq
.y
) == "k"
2027 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2029 // NOTE: not "else if" because king can capture enemy rook...
2033 else if (psq
.x
== this.size
.x
- 1)
2036 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2038 this.castleFlags
[c
][fidx
] = this.size
.y
;
2046 // If flags already off, no need to re-check:
2047 Object
.keys(this.castleFlags
).some(c
=> {
2048 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
2050 this.updateCastleFlags(move);
2052 if (this.options
["crazyhouse"]) {
2053 move.vanish
.forEach(v
=> {
2054 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2055 if (this.ispawn
[square
])
2056 delete this.ispawn
[square
];
2058 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2059 // Assumption: something is moving
2060 const initSquare
= C
.CoordsToSquare(move.start
);
2061 const destSquare
= C
.CoordsToSquare(move.end
);
2063 this.ispawn
[initSquare
] ||
2064 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2066 this.ispawn
[destSquare
] = true;
2069 this.ispawn
[destSquare
] &&
2070 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2072 move.vanish
[1].p
= "p";
2073 delete this.ispawn
[destSquare
];
2077 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2080 // Warning; atomic pawn removal isn't a capture
2081 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2083 const color
= this.turn
;
2084 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2085 // Something appears = dropped on board (some exceptions, Chakart...)
2086 if (move.appear
[i
].c
== color
) {
2087 const piece
= move.appear
[i
].p
;
2088 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2091 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2092 // Something vanish: add to reserve except if recycle & opponent
2094 this.options
["crazyhouse"] ||
2095 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2097 const piece
= move.vanish
[i
].p
;
2098 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2106 if (this.hasEnpassant
)
2107 this.epSquare
= this.getEpSquare(move);
2108 this.playOnBoard(move);
2109 this.postPlay(move);
2113 const color
= this.turn
;
2114 const oppCol
= C
.GetOppCol(color
);
2115 if (this.options
["dark"])
2116 this.updateEnlightened();
2117 if (this.options
["teleport"]) {
2119 this.subTurnTeleport
== 1 &&
2120 move.vanish
.length
> move.appear
.length
&&
2121 move.vanish
[move.vanish
.length
- 1].c
== color
2123 const v
= move.vanish
[move.vanish
.length
- 1];
2124 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2125 this.subTurnTeleport
= 2;
2128 this.subTurnTeleport
= 1;
2129 this.captured
= null;
2131 if (this.options
["balance"]) {
2132 if (![1, 3].includes(this.movesCount
))
2138 this.options
["doublemove"] &&
2139 this.movesCount
>= 1 &&
2142 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2144 const oppKingPos
= this.searchKingPos(oppCol
);
2146 oppKingPos
[0] >= 0 &&
2148 this.options
["taking"] ||
2149 !this.underCheck(oppKingPos
, color
)
2162 // "Stop at the first move found"
2163 atLeastOneMove(color
) {
2164 color
= color
|| this.turn
;
2165 for (let i
= 0; i
< this.size
.x
; i
++) {
2166 for (let j
= 0; j
< this.size
.y
; j
++) {
2167 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2168 // NOTE: in fact searching for all potential moves from i,j.
2169 // I don't believe this is an issue, for now at least.
2170 const moves
= this.getPotentialMovesFrom([i
, j
]);
2171 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2176 if (this.hasReserve
&& this.reserve
[color
]) {
2177 for (let p
of Object
.keys(this.reserve
[color
])) {
2178 const moves
= this.getDropMovesFrom([color
, p
]);
2179 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2186 // What is the score ? (Interesting if game is over)
2187 getCurrentScore(move) {
2188 const color
= this.turn
;
2189 const oppCol
= C
.GetOppCol(color
);
2190 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2191 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2193 if (kingPos
[0][0] < 0)
2194 return (color
== "w" ? "0-1" : "1-0");
2195 if (kingPos
[1][0] < 0)
2196 return (color
== "w" ? "1-0" : "0-1");
2197 if (this.atLeastOneMove())
2199 // No valid move: stalemate or checkmate?
2200 if (!this.underCheck(kingPos
[0], color
))
2203 return (color
== "w" ? "0-1" : "1-0");
2206 playVisual(move, r
) {
2207 move.vanish
.forEach(v
=> {
2208 this.g_pieces
[v
.x
][v
.y
].remove();
2209 this.g_pieces
[v
.x
][v
.y
] = null;
2212 document
.getElementById(this.containerId
).querySelector(".chessboard");
2214 r
= chessboard
.getBoundingClientRect();
2215 const pieceWidth
= this.getPieceWidth(r
.width
);
2216 move.appear
.forEach(a
=> {
2217 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2218 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
],
2219 this.pieces(a
.c
, a
.x
, a
.y
)[a
.p
]["class"]);
2220 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2221 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2222 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2223 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2224 // Translate coordinates to use chessboard as reference:
2225 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2226 `translate(${ip - r.x}px,${jp - r.y}px)`;
2227 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2228 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2229 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2231 if (this.options
["dark"])
2232 this.graphUpdateEnlightened();
2235 playPlusVisual(move, r
) {
2237 this.playVisual(move, r
);
2238 this.afterPlay(move); //user method
2242 // Works for all rectangular boards:
2243 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
2247 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2250 animate(move, callback
) {
2251 if (this.noAnimate
|| move.noAnimate
) {
2255 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2256 // NOTE: cloning generally not required, but light enough, and simpler
2257 let movingPiece
= initPiece
.cloneNode();
2258 initPiece
.style
.opacity
= "0";
2260 document
.getElementById(this.containerId
)
2261 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2262 if (typeof move.start
.x
== "string") {
2263 // Need to bound width/height (was 100% for reserve pieces)
2264 const pieceWidth
= this.getPieceWidth(r
.width
);
2265 movingPiece
.style
.width
= pieceWidth
+ "px";
2266 movingPiece
.style
.height
= pieceWidth
+ "px";
2268 const maxDist
= this.getMaxDistance(r
);
2269 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2270 const pieces
= this.pieces(apparentColor
, move.start
.x
, move.start
.y
);
2272 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2273 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2274 C
.AddClass_es(movingPiece
, pieces
[move.drag
.p
]["class"]);
2275 if (apparentColor
!= move.drag
.c
) {
2276 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2277 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2280 container
.appendChild(movingPiece
);
2281 const animateSegment
= (index
, cb
) => {
2282 // NOTE: move.drag could be generalized per-segment (usage?)
2283 const [i1
, j1
] = move.segments
[index
][0];
2284 const [i2
, j2
] = move.segments
[index
][1];
2285 const dep
= this.getPixelPosition(i1
, j1
, r
);
2286 const arr
= this.getPixelPosition(i2
, j2
, r
);
2287 movingPiece
.style
.transitionDuration
= "0s";
2288 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2290 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2291 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2292 // TODO: unclear why we need this new delay below:
2294 movingPiece
.style
.transitionDuration
= duration
+ "s";
2295 // movingPiece is child of container: no need to adjust coordinates
2296 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2297 setTimeout(cb
, duration
* 1000);
2300 if (!move.segments
) {
2302 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2306 const animateSegmentCallback
= () => {
2307 if (index
< move.segments
.length
)
2308 animateSegment(index
++, animateSegmentCallback
);
2310 movingPiece
.remove();
2311 initPiece
.style
.opacity
= "1";
2315 animateSegmentCallback();
2318 playReceivedMove(moves
, callback
) {
2319 const launchAnimation
= () => {
2320 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2321 const animateRec
= i
=> {
2322 this.animate(moves
[i
], () => {
2323 this.play(moves
[i
]);
2324 this.playVisual(moves
[i
], r
);
2325 if (i
< moves
.length
- 1)
2326 setTimeout(() => animateRec(i
+1), 300);
2333 // Delay if user wasn't focused:
2334 const checkDisplayThenAnimate
= (delay
) => {
2335 if (container
.style
.display
== "none") {
2336 alert("New move! Let's go back to game...");
2337 document
.getElementById("gameInfos").style
.display
= "none";
2338 container
.style
.display
= "block";
2339 setTimeout(launchAnimation
, 700);
2342 setTimeout(launchAnimation
, delay
|| 0);
2344 let container
= document
.getElementById(this.containerId
);
2345 if (document
.hidden
) {
2346 document
.onvisibilitychange
= () => {
2347 document
.onvisibilitychange
= undefined;
2348 checkDisplayThenAnimate(700);
2352 checkDisplayThenAnimate();