c19ee64ff113ed3a84c7128cdb7c32f490643b06
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
], this.pieces()[piece
]["class"]);
670 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
671 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
672 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
673 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
674 // Translate coordinates to use chessboard as reference:
675 this.g_pieces
[i
][j
].style
.transform
=
676 `translate(${ip - r.x}px,${jp - r.y}px)`;
677 if (this.enlightened
&& !this.enlightened
[i
][j
])
678 this.g_pieces
[i
][j
].classList
.add("hidden");
679 chessboard
.appendChild(this.g_pieces
[i
][j
]);
684 this.re_drawReserve(['w', 'b'], r
);
687 // NOTE: assume this.reserve != null
688 re_drawReserve(colors
, r
) {
690 // Remove (old) reserve pieces
691 for (let c
of colors
) {
692 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
693 this.r_pieces
[c
][p
].remove();
694 delete this.r_pieces
[c
][p
];
695 const numId
= this.getReserveNumId(c
, p
);
696 document
.getElementById(numId
).remove();
701 this.r_pieces
= { w: {}, b: {} };
702 let container
= document
.getElementById(this.containerId
);
704 r
= container
.querySelector(".chessboard").getBoundingClientRect();
705 for (let c
of colors
) {
706 let reservesDiv
= document
.getElementById("reserves_" + c
);
708 reservesDiv
.remove();
709 if (!this.reserve
[c
])
711 const nbR
= this.getNbReservePieces(c
);
714 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
716 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
717 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
718 let rcontainer
= document
.createElement("div");
719 rcontainer
.id
= "reserves_" + c
;
720 rcontainer
.classList
.add("reserves");
721 rcontainer
.style
.left
= i0
+ "px";
722 rcontainer
.style
.top
= j0
+ "px";
723 // NOTE: +1 fix display bug on Firefox at least
724 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
725 rcontainer
.style
.height
= sqResSize
+ "px";
726 container
.appendChild(rcontainer
);
727 for (let p
of Object
.keys(this.reserve
[c
])) {
728 if (this.reserve
[c
][p
] == 0)
730 let r_cell
= document
.createElement("div");
731 r_cell
.id
= this.coordsToId({x: c
, y: p
});
732 r_cell
.classList
.add("reserve-cell");
733 r_cell
.style
.width
= sqResSize
+ "px";
734 r_cell
.style
.height
= sqResSize
+ "px";
735 rcontainer
.appendChild(r_cell
);
736 let piece
= document
.createElement("piece");
737 C
.AddClass_es(piece
, this.pieces()[p
]["class"]);
738 piece
.classList
.add(C
.GetColorClass(c
));
739 piece
.style
.width
= "100%";
740 piece
.style
.height
= "100%";
741 this.r_pieces
[c
][p
] = piece
;
742 r_cell
.appendChild(piece
);
743 let number
= document
.createElement("div");
744 number
.textContent
= this.reserve
[c
][p
];
745 number
.classList
.add("reserve-num");
746 number
.id
= this.getReserveNumId(c
, p
);
747 const fontSize
= "1.3em";
748 number
.style
.fontSize
= fontSize
;
749 number
.style
.fontSize
= fontSize
;
750 r_cell
.appendChild(number
);
756 updateReserve(color
, piece
, count
) {
757 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
758 piece
= "k"; //capturing cannibal king: back to king form
759 const oldCount
= this.reserve
[color
][piece
];
760 this.reserve
[color
][piece
] = count
;
761 // Redrawing is much easier if count==0
762 if ([oldCount
, count
].includes(0))
763 this.re_drawReserve([color
]);
765 const numId
= this.getReserveNumId(color
, piece
);
766 document
.getElementById(numId
).textContent
= count
;
770 // Apply diff this.enlightened --> oldEnlightened on board
771 graphUpdateEnlightened() {
773 document
.getElementById(this.containerId
).querySelector(".chessboard");
774 const r
= chessboard
.getBoundingClientRect();
775 const pieceWidth
= this.getPieceWidth(r
.width
);
776 for (let x
=0; x
<this.size
.x
; x
++) {
777 for (let y
=0; y
<this.size
.y
; y
++) {
778 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
779 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
780 elt
.classList
.add("in-shadow");
781 if (this.g_pieces
[x
][y
])
782 this.g_pieces
[x
][y
].classList
.add("hidden");
784 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
785 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
786 elt
.classList
.remove("in-shadow");
787 if (this.g_pieces
[x
][y
])
788 this.g_pieces
[x
][y
].classList
.remove("hidden");
794 // Resize board: no need to destroy/recreate pieces
797 document
.getElementById(this.containerId
).querySelector(".chessboard");
798 const r
= chessboard
.getBoundingClientRect();
799 const multFact
= (mode
== "up" ? 1.05 : 0.95);
800 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
802 const vRatio
= this.size
.ratio
|| 1;
803 if (newWidth
> window
.innerWidth
) {
804 newWidth
= window
.innerWidth
;
805 newHeight
= newWidth
/ vRatio
;
807 if (newHeight
> window
.innerHeight
) {
808 newHeight
= window
.innerHeight
;
809 newWidth
= newHeight
* vRatio
;
811 chessboard
.style
.width
= newWidth
+ "px";
812 chessboard
.style
.height
= newHeight
+ "px";
813 const newX
= (window
.innerWidth
- newWidth
) / 2;
814 chessboard
.style
.left
= newX
+ "px";
815 const newY
= (window
.innerHeight
- newHeight
) / 2;
816 chessboard
.style
.top
= newY
+ "px";
817 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
818 const pieceWidth
= this.getPieceWidth(newWidth
);
819 // NOTE: next "if" for variants which use squares filling
820 // instead of "physical", moving pieces
822 for (let i
=0; i
< this.size
.x
; i
++) {
823 for (let j
=0; j
< this.size
.y
; j
++) {
824 if (this.g_pieces
[i
][j
]) {
825 // NOTE: could also use CSS transform "scale"
826 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
827 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
828 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
829 // Translate coordinates to use chessboard as reference:
830 this.g_pieces
[i
][j
].style
.transform
=
831 `translate(${ip - newX}px,${jp - newY}px)`;
837 this.rescaleReserve(newR
);
841 for (let c
of ['w','b']) {
842 if (!this.reserve
[c
])
844 const nbR
= this.getNbReservePieces(c
);
847 // Resize container first
848 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
849 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
850 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
851 let rcontainer
= document
.getElementById("reserves_" + c
);
852 rcontainer
.style
.left
= i0
+ "px";
853 rcontainer
.style
.top
= j0
+ "px";
854 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
855 rcontainer
.style
.height
= sqResSize
+ "px";
856 // And then reserve cells:
857 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
858 Object
.keys(this.reserve
[c
]).forEach(p
=> {
859 if (this.reserve
[c
][p
] == 0)
861 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
862 r_cell
.style
.width
= sqResSize
+ "px";
863 r_cell
.style
.height
= sqResSize
+ "px";
868 // Return the absolute pixel coordinates given current position.
869 // Our coordinate system differs from CSS one (x <--> y).
870 // We return here the CSS coordinates (more useful).
871 getPixelPosition(i
, j
, r
) {
873 return [0, 0]; //piece vanishes
875 if (typeof i
== "string") {
876 // Reserves: need to know the rank of piece
877 const nbR
= this.getNbReservePieces(i
);
878 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
879 x
= this.getRankInReserve(i
, j
) * rsqSize
;
880 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
883 const sqSize
= r
.width
/ this.size
.y
;
884 const flipped
= (this.playerColor
== 'b');
885 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
886 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
888 return [r
.x
+ x
, r
.y
+ y
];
892 let container
= document
.getElementById(this.containerId
);
893 let chessboard
= container
.querySelector(".chessboard");
895 const getOffset
= e
=> {
898 return {x: e
.clientX
, y: e
.clientY
};
899 let touchLocation
= null;
900 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
901 // Touch screen, dragstart
902 touchLocation
= e
.targetTouches
[0];
903 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
904 // Touch screen, dragend
905 touchLocation
= e
.changedTouches
[0];
907 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
908 return {x: 0, y: 0}; //shouldn't reach here =)
911 const centerOnCursor
= (piece
, e
) => {
912 const centerShift
= this.getPieceWidth(r
.width
) / 2;
913 const offset
= getOffset(e
);
914 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
915 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
920 startPiece
, curPiece
= null,
922 const mousedown
= (e
) => {
923 // Disable zoom on smartphones:
924 if (e
.touches
&& e
.touches
.length
> 1)
926 r
= chessboard
.getBoundingClientRect();
927 pieceWidth
= this.getPieceWidth(r
.width
);
928 const cd
= this.idToCoords(e
.target
.id
);
930 const move = this.doClick(cd
);
932 this.playPlusVisual(move);
934 const [x
, y
] = Object
.values(cd
);
935 if (typeof x
!= "number")
936 startPiece
= this.r_pieces
[x
][y
];
938 startPiece
= this.g_pieces
[x
][y
];
939 if (startPiece
&& this.canIplay(x
, y
)) {
942 curPiece
= startPiece
.cloneNode();
943 curPiece
.style
.transform
= "none";
944 curPiece
.style
.zIndex
= 5;
945 curPiece
.style
.width
= pieceWidth
+ "px";
946 curPiece
.style
.height
= pieceWidth
+ "px";
947 centerOnCursor(curPiece
, e
);
948 container
.appendChild(curPiece
);
949 startPiece
.style
.opacity
= "0.4";
950 chessboard
.style
.cursor
= "none";
956 const mousemove
= (e
) => {
959 centerOnCursor(curPiece
, e
);
961 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
962 // Attempt to prevent horizontal swipe...
966 const mouseup
= (e
) => {
969 const [x
, y
] = [start
.x
, start
.y
];
972 chessboard
.style
.cursor
= "pointer";
973 startPiece
.style
.opacity
= "1";
974 const offset
= getOffset(e
);
975 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
977 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
979 // NOTE: clearly suboptimal, but much easier, and not a big deal.
980 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
981 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
982 const moves
= this.filterValid(potentialMoves
);
983 if (moves
.length
>= 2)
984 this.showChoices(moves
, r
);
985 else if (moves
.length
== 1)
986 this.playPlusVisual(moves
[0], r
);
991 if ('onmousedown' in window
) {
992 document
.addEventListener("mousedown", mousedown
);
993 document
.addEventListener("mousemove", mousemove
);
994 document
.addEventListener("mouseup", mouseup
);
995 document
.addEventListener("wheel",
996 (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down"));
998 if ('ontouchstart' in window
) {
999 // https://stackoverflow.com/a/42509310/12660887
1000 document
.addEventListener("touchstart", mousedown
, {passive: false});
1001 document
.addEventListener("touchmove", mousemove
, {passive: false});
1002 document
.addEventListener("touchend", mouseup
, {passive: false});
1004 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1007 showChoices(moves
, r
) {
1008 let container
= document
.getElementById(this.containerId
);
1009 let chessboard
= container
.querySelector(".chessboard");
1010 let choices
= document
.createElement("div");
1011 choices
.id
= "choices";
1013 r
= chessboard
.getBoundingClientRect();
1014 choices
.style
.width
= r
.width
+ "px";
1015 choices
.style
.height
= r
.height
+ "px";
1016 choices
.style
.left
= r
.x
+ "px";
1017 choices
.style
.top
= r
.y
+ "px";
1018 chessboard
.style
.opacity
= "0.5";
1019 container
.appendChild(choices
);
1020 const squareWidth
= r
.width
/ this.size
.y
;
1021 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1022 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1023 const color
= moves
[0].appear
[0].c
;
1024 const callback
= (m
) => {
1025 chessboard
.style
.opacity
= "1";
1026 container
.removeChild(choices
);
1027 this.playPlusVisual(m
, r
);
1029 for (let i
=0; i
< moves
.length
; i
++) {
1030 let choice
= document
.createElement("div");
1031 choice
.classList
.add("choice");
1032 choice
.style
.width
= squareWidth
+ "px";
1033 choice
.style
.height
= squareWidth
+ "px";
1034 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1035 choice
.style
.top
= firstUpTop
+ "px";
1036 choice
.style
.backgroundColor
= "lightyellow";
1037 choice
.onclick
= () => callback(moves
[i
]);
1038 const piece
= document
.createElement("piece");
1039 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1040 C
.AddClass_es(piece
, this.pieces()[cdisp
]["class"]);
1041 piece
.classList
.add(C
.GetColorClass(color
));
1042 piece
.style
.width
= "100%";
1043 piece
.style
.height
= "100%";
1044 choice
.appendChild(piece
);
1045 choices
.appendChild(choice
);
1056 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1060 // Color of thing on square (i,j). 'undefined' if square is empty
1062 if (typeof i
== "string")
1063 return i
; //reserves
1064 return this.board
[i
][j
].charAt(0);
1067 static GetColorClass(c
) {
1072 return "other-color"; //unidentified color
1075 // Assume square i,j isn't empty
1077 if (typeof j
== "string")
1078 return j
; //reserves
1079 return this.board
[i
][j
].charAt(1);
1082 // Piece type on square (i,j)
1083 getPieceType(i
, j
) {
1084 const p
= this.getPiece(i
, j
);
1085 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1088 // Get opponent color
1089 static GetOppCol(color
) {
1090 return (color
== "w" ? "b" : "w");
1093 // Can thing on square1 capture (no return) thing on square2?
1094 canTake([x1
, y1
], [x2
, y2
]) {
1095 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1098 // Is (x,y) on the chessboard?
1100 return (x
>= 0 && x
< this.size
.x
&&
1101 y
>= 0 && y
< this.size
.y
);
1104 // Am I allowed to move thing at square x,y ?
1106 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1109 ////////////////////////
1110 // PIECES SPECIFICATIONS
1112 pieces(color
, x
, y
) {
1113 const pawnShift
= (color
== "w" ? -1 : 1);
1114 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1115 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1121 steps: [[pawnShift
, 0]],
1122 range: (initRank
? 2 : 1)
1127 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1136 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1145 [1, 2], [1, -2], [-1, 2], [-1, -2],
1146 [2, 1], [-2, 1], [2, -1], [-2, -1]
1156 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1165 [0, 1], [0, -1], [1, 0], [-1, 0],
1166 [1, 1], [1, -1], [-1, 1], [-1, -1]
1177 [0, 1], [0, -1], [1, 0], [-1, 0],
1178 [1, 1], [1, -1], [-1, 1], [-1, -1]
1185 '!': {"class": "king-pawn", moveas: "p"},
1186 '#': {"class": "king-rook", moveas: "r"},
1187 '$': {"class": "king-knight", moveas: "n"},
1188 '%': {"class": "king-bishop", moveas: "b"},
1189 '*': {"class": "king-queen", moveas: "q"}
1193 ////////////////////
1196 // For Cylinder: get Y coordinate
1198 if (!this.options
["cylinder"])
1200 let res
= y
% this.size
.y
;
1206 // Stop at the first capture found
1207 atLeastOneCapture(color
) {
1208 color
= color
|| this.turn
;
1209 const oppCol
= C
.GetOppCol(color
);
1210 for (let i
= 0; i
< this.size
.x
; i
++) {
1211 for (let j
= 0; j
< this.size
.y
; j
++) {
1212 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1213 const allSpecs
= this.pieces(color
, i
, j
)
1214 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1215 const attacks
= specs
.attack
|| specs
.moves
;
1216 for (let a
of attacks
) {
1217 outerLoop: for (let step
of a
.steps
) {
1218 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1219 let stepCounter
= 1;
1220 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1221 if (a
.range
<= stepCounter
++)
1224 jj
= this.getY(jj
+ step
[1]);
1227 this.onBoard(ii
, jj
) &&
1228 this.getColor(ii
, jj
) == oppCol
&&
1230 [this.getBasicMove([i
, j
], [ii
, jj
])]
1243 getDropMovesFrom([c
, p
]) {
1244 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1245 // (but not necessarily otherwise: atLeastOneMove() etc)
1246 if (this.reserve
[c
][p
] == 0)
1249 for (let i
=0; i
<this.size
.x
; i
++) {
1250 for (let j
=0; j
<this.size
.y
; j
++) {
1252 this.board
[i
][j
] == "" &&
1253 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1256 (c
== 'w' && i
< this.size
.x
- 1) ||
1262 start: {x: c
, y: p
},
1264 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1274 // All possible moves from selected square
1275 getPotentialMovesFrom(sq
, color
) {
1276 if (this.subTurnTeleport
== 2)
1278 if (typeof sq
[0] == "string")
1279 return this.getDropMovesFrom(sq
);
1280 if (this.isImmobilized(sq
))
1282 const piece
= this.getPieceType(sq
[0], sq
[1]);
1283 let moves
= this.getPotentialMovesOf(piece
, sq
);
1286 this.hasEnpassant
&&
1289 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1294 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1296 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1298 return this.postProcessPotentialMoves(moves
);
1301 postProcessPotentialMoves(moves
) {
1302 if (moves
.length
== 0)
1304 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1305 const oppCol
= C
.GetOppCol(color
);
1307 if (this.options
["capture"] && this.atLeastOneCapture())
1308 moves
= this.capturePostProcess(moves
, oppCol
);
1310 if (this.options
["atomic"])
1311 this.atomicPostProcess(moves
, oppCol
);
1315 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1317 this.pawnPostProcess(moves
, color
, oppCol
);
1321 this.options
["cannibal"] &&
1322 this.options
["rifle"]
1324 // In this case a rifle-capture from last rank may promote a pawn
1325 this.riflePromotePostProcess(moves
, color
);
1331 capturePostProcess(moves
, oppCol
) {
1332 // Filter out non-capturing moves (not using m.vanish because of
1333 // self captures of Recycle and Teleport).
1334 return moves
.filter(m
=> {
1336 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1337 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1342 atomicPostProcess(moves
, oppCol
) {
1343 moves
.forEach(m
=> {
1345 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1346 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1359 for (let step
of steps
) {
1360 let x
= m
.end
.x
+ step
[0];
1361 let y
= this.getY(m
.end
.y
+ step
[1]);
1363 this.onBoard(x
, y
) &&
1364 this.board
[x
][y
] != "" &&
1365 this.getPieceType(x
, y
) != "p"
1369 p: this.getPiece(x
, y
),
1370 c: this.getColor(x
, y
),
1377 if (!this.options
["rifle"])
1378 m
.appear
.pop(); //nothing appears
1383 pawnPostProcess(moves
, color
, oppCol
) {
1385 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1386 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1387 moves
.forEach(m
=> {
1388 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1389 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1390 const promotionOk
= (
1392 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1395 return; //nothing to do
1396 if (this.options
["pawnfall"]) {
1400 let finalPieces
= ["p"];
1402 this.options
["cannibal"] &&
1403 this.board
[x2
][y2
] != "" &&
1404 this.getColor(x2
, y2
) == oppCol
1406 finalPieces
= [this.getPieceType(x2
, y2
)];
1409 finalPieces
= this.pawnPromotions
;
1410 m
.appear
[0].p
= finalPieces
[0];
1411 if (initPiece
== "!") //cannibal king-pawn
1412 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1413 for (let i
=1; i
<finalPieces
.length
; i
++) {
1414 const piece
= finalPieces
[i
];
1417 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1419 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1420 moreMoves
.push(newMove
);
1423 Array
.prototype.push
.apply(moves
, moreMoves
);
1426 riflePromotePostProcess(moves
, color
) {
1427 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1429 moves
.forEach(m
=> {
1431 m
.start
.x
== lastRank
&&
1432 m
.appear
.length
>= 1 &&
1433 m
.appear
[0].p
== "p" &&
1434 m
.appear
[0].x
== m
.start
.x
&&
1435 m
.appear
[0].y
== m
.start
.y
1437 m
.appear
[0].p
= this.pawnPromotions
[0];
1438 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1439 let newMv
= JSON
.parse(JSON
.stringify(m
));
1440 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1441 newMoves
.push(newMv
);
1445 Array
.prototype.push
.apply(moves
, newMoves
);
1448 // NOTE: using special symbols to not interfere with variants' pieces codes
1449 static get CannibalKings() {
1460 static get CannibalKingCode() {
1472 return !!C
.CannibalKings
[symbol
];
1476 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1477 isImmobilized([x
, y
]) {
1478 if (!this.options
["madrasi"])
1480 const color
= this.getColor(x
, y
);
1481 const oppCol
= C
.GetOppCol(color
);
1482 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1483 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1484 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1485 for (let a
of attacks
) {
1486 outerLoop: for (let step
of a
.steps
) {
1487 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1488 let stepCounter
= 1;
1489 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1490 if (a
.range
<= stepCounter
++)
1493 j
= this.getY(j
+ step
[1]);
1496 this.onBoard(i
, j
) &&
1497 this.getColor(i
, j
) == oppCol
&&
1498 this.getPieceType(i
, j
) == piece
1508 // In some variants, objects on boards don't stop movement (Chakart)
1509 return this.board
[i
][j
] == "";
1512 // Generic method to find possible moves of "sliding or jumping" pieces
1513 getPotentialMovesOf(piece
, [x
, y
]) {
1514 const color
= this.getColor(x
, y
);
1515 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1517 // Next 3 for Cylinder mode:
1522 const addMove
= (start
, end
) => {
1523 let newMove
= this.getBasicMove(start
, end
);
1524 if (segments
.length
> 0) {
1525 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1526 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1528 moves
.push(newMove
);
1531 const findAddMoves
= (type
, stepArray
) => {
1532 for (let s
of stepArray
) {
1533 outerLoop: for (let step
of s
.steps
) {
1536 let [i
, j
] = [x
, y
];
1537 let stepCounter
= 0;
1539 this.onBoard(i
, j
) &&
1540 (this.canStepOver(i
, j
) || (i
== x
&& j
== y
))
1544 !explored
[i
+ "." + j
] &&
1547 explored
[i
+ "." + j
] = true;
1548 addMove([x
, y
], [i
, j
]);
1550 if (s
.range
<= stepCounter
++)
1552 const oldIJ
= [i
, j
];
1554 j
= this.getY(j
+ step
[1]);
1555 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1556 // Boundary between segments (cylinder mode)
1557 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1561 if (!this.onBoard(i
, j
))
1563 const pieceIJ
= this.getPieceType(i
, j
);
1565 type
!= "moveonly" &&
1566 !explored
[i
+ "." + j
] &&
1568 !this.options
["zen"] ||
1572 this.canTake([x
, y
], [i
, j
]) ||
1574 (this.options
["recycle"] || this.options
["teleport"]) &&
1579 explored
[i
+ "." + j
] = true;
1580 addMove([x
, y
], [i
, j
]);
1586 const specialAttack
= !!stepSpec
.attack
;
1588 findAddMoves("attack", stepSpec
.attack
);
1589 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1590 if (this.options
["zen"]) {
1591 Array
.prototype.push
.apply(moves
,
1592 this.findCapturesOn([x
, y
], {zen: true}));
1597 // Search for enemy (or not) pieces attacking [x, y]
1598 findCapturesOn([x
, y
], args
) {
1601 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1602 for (let i
=0; i
<this.size
.x
; i
++) {
1603 for (let j
=0; j
<this.size
.y
; j
++) {
1605 this.board
[i
][j
] != "" &&
1606 this.getColor(i
, j
) == args
.oppCol
&&
1607 !this.isImmobilized([i
, j
])
1609 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1610 continue; //king not captured in this way
1612 this.pieces(args
.oppCol
, i
, j
)[this.getPieceType(i
, j
)];
1613 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1614 for (let a
of attacks
) {
1615 for (let s
of a
.steps
) {
1616 // Quick check: if step isn't compatible, don't even try
1617 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1619 // Finally verify that nothing stand in-between
1620 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1621 let stepCounter
= 1;
1623 this.onBoard(ii
, jj
) &&
1624 this.board
[ii
][jj
] == "" &&
1625 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1628 jj
= this.getY(jj
+ s
[1]);
1630 if (ii
== x
&& jj
== y
) {
1633 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1635 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1637 return moves
; //test for underCheck
1647 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1648 const rx
= (x2
- x1
) / step
[0],
1649 ry
= (y2
- y1
) / step
[1];
1651 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1652 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1656 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1657 // TODO: 1e-7 here is totally arbitrary
1658 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1660 distance
= Math
.round(distance
); //in case of (numerical...)
1661 if (range
< distance
)
1666 // Build a regular move from its initial and destination squares.
1667 // tr: transformation
1668 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1669 const initColor
= this.getColor(sx
, sy
);
1670 const initPiece
= this.getPiece(sx
, sy
);
1671 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1675 start: {x: sx
, y: sy
},
1679 !this.options
["rifle"] ||
1680 this.board
[ex
][ey
] == "" ||
1681 destColor
== initColor
//Recycle, Teleport
1687 c: !!tr
? tr
.c : initColor
,
1688 p: !!tr
? tr
.p : initPiece
1700 if (this.board
[ex
][ey
] != "") {
1705 c: this.getColor(ex
, ey
),
1706 p: this.getPiece(ex
, ey
)
1709 if (this.options
["cannibal"] && destColor
!= initColor
) {
1710 const lastIdx
= mv
.vanish
.length
- 1;
1711 let trPiece
= mv
.vanish
[lastIdx
].p
;
1712 if (this.isKing(this.getPiece(sx
, sy
)))
1713 trPiece
= C
.CannibalKingCode
[trPiece
];
1714 if (mv
.appear
.length
>= 1)
1715 mv
.appear
[0].p
= trPiece
;
1716 else if (this.options
["rifle"]) {
1739 // En-passant square, if any
1740 getEpSquare(moveOrSquare
) {
1741 if (typeof moveOrSquare
=== "string") {
1742 const square
= moveOrSquare
;
1745 return C
.SquareToCoords(square
);
1747 // Argument is a move:
1748 const move = moveOrSquare
;
1749 const s
= move.start
,
1753 Math
.abs(s
.x
- e
.x
) == 2 &&
1754 // Next conditions for variants like Atomic or Rifle, Recycle...
1755 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1756 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1763 return undefined; //default
1766 // Special case of en-passant captures: treated separately
1767 getEnpassantCaptures([x
, y
]) {
1768 const color
= this.getColor(x
, y
);
1769 const shiftX
= (color
== 'w' ? -1 : 1);
1770 const oppCol
= C
.GetOppCol(color
);
1771 let enpassantMove
= null;
1774 this.epSquare
.x
== x
+ shiftX
&&
1775 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1776 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1778 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1779 this.board
[epx
][epy
] = oppCol
+ "p";
1780 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1781 this.board
[epx
][epy
] = "";
1782 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1783 enpassantMove
.vanish
[lastIdx
].x
= x
;
1785 return !!enpassantMove
? [enpassantMove
] : [];
1788 // "castleInCheck" arg to let some variants castle under check
1789 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1790 const c
= this.getColor(x
, y
);
1793 const oppCol
= C
.GetOppCol(c
);
1797 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1798 const castlingKing
= this.getPiece(x
, y
);
1799 castlingCheck: for (
1802 castleSide
++ //large, then small
1804 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1806 // If this code is reached, rook and king are on initial position
1808 // NOTE: in some variants this is not a rook
1809 const rookPos
= this.castleFlags
[c
][castleSide
];
1810 const castlingPiece
= this.getPiece(x
, rookPos
);
1812 this.board
[x
][rookPos
] == "" ||
1813 this.getColor(x
, rookPos
) != c
||
1814 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1816 // Rook is not here, or changed color (see Benedict)
1819 // Nothing on the path of the king ? (and no checks)
1820 const finDist
= finalSquares
[castleSide
][0] - y
;
1821 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1825 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1827 this.board
[x
][i
] != "" &&
1828 // NOTE: next check is enough, because of chessboard constraints
1829 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1832 continue castlingCheck
;
1835 } while (i
!= finalSquares
[castleSide
][0]);
1836 // Nothing on the path to the rook?
1837 step
= (castleSide
== 0 ? -1 : 1);
1838 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1839 if (this.board
[x
][i
] != "")
1840 continue castlingCheck
;
1843 // Nothing on final squares, except maybe king and castling rook?
1844 for (i
= 0; i
< 2; i
++) {
1846 finalSquares
[castleSide
][i
] != rookPos
&&
1847 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1849 finalSquares
[castleSide
][i
] != y
||
1850 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1853 continue castlingCheck
;
1857 // If this code is reached, castle is valid
1863 y: finalSquares
[castleSide
][0],
1869 y: finalSquares
[castleSide
][1],
1875 // King might be initially disguised (Titan...)
1876 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1877 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1880 Math
.abs(y
- rookPos
) <= 2
1881 ? {x: x
, y: rookPos
}
1882 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1890 ////////////////////
1893 // Is (king at) given position under check by "oppCol" ?
1894 underCheck([x
, y
], oppCol
) {
1895 if (this.options
["taking"] || this.options
["dark"])
1898 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1902 // Stop at first king found (TODO: multi-kings)
1903 searchKingPos(color
) {
1904 for (let i
=0; i
< this.size
.x
; i
++) {
1905 for (let j
=0; j
< this.size
.y
; j
++) {
1906 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1910 return [-1, -1]; //king not found
1913 // Some variants (e.g. Refusal) may need to check opponent moves too
1914 filterValid(moves
, color
) {
1915 if (moves
.length
== 0)
1919 const oppCol
= C
.GetOppCol(color
);
1920 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1921 // Forbid moves either giving check or exploding opponent's king:
1922 const oppKingPos
= this.searchKingPos(oppCol
);
1923 moves
= moves
.filter(m
=> {
1925 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1926 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1929 this.playOnBoard(m
);
1930 const res
= !this.underCheck(oppKingPos
, color
);
1931 this.undoOnBoard(m
);
1935 if (this.options
["taking"] || this.options
["dark"])
1937 const kingPos
= this.searchKingPos(color
);
1938 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1939 return moves
.filter(m
=> {
1940 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1941 if (!filtered
[key
]) {
1942 this.playOnBoard(m
);
1943 let square
= kingPos
,
1944 res
= true; //a priori valid
1945 if (m
.vanish
.some(v
=> {
1946 return C
.CannibalKings
[v
.p
] && v
.c
== color
;
1948 // Search king in appear array:
1950 m
.appear
.findIndex(a
=> {
1951 return C
.CannibalKings
[a
.p
] && a
.c
== color
;
1953 if (newKingIdx
>= 0)
1954 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1958 res
&&= !this.underCheck(square
, oppCol
);
1959 this.undoOnBoard(m
);
1960 filtered
[key
] = res
;
1963 return filtered
[key
];
1970 // Aggregate flags into one object
1972 return this.castleFlags
;
1975 // Reverse operation
1976 disaggregateFlags(flags
) {
1977 this.castleFlags
= flags
;
1980 // Apply a move on board
1982 for (let psq
of move.vanish
)
1983 this.board
[psq
.x
][psq
.y
] = "";
1984 for (let psq
of move.appear
)
1985 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1987 // Un-apply the played move
1989 for (let psq
of move.appear
)
1990 this.board
[psq
.x
][psq
.y
] = "";
1991 for (let psq
of move.vanish
)
1992 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1995 updateCastleFlags(move) {
1996 // Update castling flags if start or arrive from/at rook/king locations
1997 move.appear
.concat(move.vanish
).forEach(psq
=> {
1999 this.board
[psq
.x
][psq
.y
] != "" &&
2000 this.getPieceType(psq
.x
, psq
.y
) == "k"
2002 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2004 // NOTE: not "else if" because king can capture enemy rook...
2008 else if (psq
.x
== this.size
.x
- 1)
2011 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2013 this.castleFlags
[c
][fidx
] = this.size
.y
;
2021 // If flags already off, no need to re-check:
2022 Object
.keys(this.castleFlags
).some(c
=> {
2023 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
2025 this.updateCastleFlags(move);
2027 if (this.options
["crazyhouse"]) {
2028 move.vanish
.forEach(v
=> {
2029 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2030 if (this.ispawn
[square
])
2031 delete this.ispawn
[square
];
2033 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2034 // Assumption: something is moving
2035 const initSquare
= C
.CoordsToSquare(move.start
);
2036 const destSquare
= C
.CoordsToSquare(move.end
);
2038 this.ispawn
[initSquare
] ||
2039 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2041 this.ispawn
[destSquare
] = true;
2044 this.ispawn
[destSquare
] &&
2045 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2047 move.vanish
[1].p
= "p";
2048 delete this.ispawn
[destSquare
];
2052 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2055 // Warning; atomic pawn removal isn't a capture
2056 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2058 const color
= this.turn
;
2059 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2060 // Something appears = dropped on board (some exceptions, Chakart...)
2061 if (move.appear
[i
].c
== color
) {
2062 const piece
= move.appear
[i
].p
;
2063 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2066 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2067 // Something vanish: add to reserve except if recycle & opponent
2069 this.options
["crazyhouse"] ||
2070 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2072 const piece
= move.vanish
[i
].p
;
2073 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2081 if (this.hasEnpassant
)
2082 this.epSquare
= this.getEpSquare(move);
2083 this.playOnBoard(move);
2084 this.postPlay(move);
2088 const color
= this.turn
;
2089 const oppCol
= C
.GetOppCol(color
);
2090 if (this.options
["dark"])
2091 this.updateEnlightened();
2092 if (this.options
["teleport"]) {
2094 this.subTurnTeleport
== 1 &&
2095 move.vanish
.length
> move.appear
.length
&&
2096 move.vanish
[move.vanish
.length
- 1].c
== color
2098 const v
= move.vanish
[move.vanish
.length
- 1];
2099 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2100 this.subTurnTeleport
= 2;
2103 this.subTurnTeleport
= 1;
2104 this.captured
= null;
2106 if (this.options
["balance"]) {
2107 if (![1, 3].includes(this.movesCount
))
2113 this.options
["doublemove"] &&
2114 this.movesCount
>= 1 &&
2117 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2119 const oppKingPos
= this.searchKingPos(oppCol
);
2121 oppKingPos
[0] >= 0 &&
2123 this.options
["taking"] ||
2124 !this.underCheck(oppKingPos
, color
)
2137 // "Stop at the first move found"
2138 atLeastOneMove(color
) {
2139 color
= color
|| this.turn
;
2140 for (let i
= 0; i
< this.size
.x
; i
++) {
2141 for (let j
= 0; j
< this.size
.y
; j
++) {
2142 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2143 // NOTE: in fact searching for all potential moves from i,j.
2144 // I don't believe this is an issue, for now at least.
2145 const moves
= this.getPotentialMovesFrom([i
, j
]);
2146 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2151 if (this.hasReserve
&& this.reserve
[color
]) {
2152 for (let p
of Object
.keys(this.reserve
[color
])) {
2153 const moves
= this.getDropMovesFrom([color
, p
]);
2154 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2161 // What is the score ? (Interesting if game is over)
2162 getCurrentScore(move) {
2163 const color
= this.turn
;
2164 const oppCol
= C
.GetOppCol(color
);
2165 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2166 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2168 if (kingPos
[0][0] < 0)
2169 return (color
== "w" ? "0-1" : "1-0");
2170 if (kingPos
[1][0] < 0)
2171 return (color
== "w" ? "1-0" : "0-1");
2172 if (this.atLeastOneMove())
2174 // No valid move: stalemate or checkmate?
2175 if (!this.underCheck(kingPos
[0], color
))
2178 return (color
== "w" ? "0-1" : "1-0");
2181 playVisual(move, r
) {
2182 move.vanish
.forEach(v
=> {
2183 this.g_pieces
[v
.x
][v
.y
].remove();
2184 this.g_pieces
[v
.x
][v
.y
] = null;
2187 document
.getElementById(this.containerId
).querySelector(".chessboard");
2189 r
= chessboard
.getBoundingClientRect();
2190 const pieceWidth
= this.getPieceWidth(r
.width
);
2191 move.appear
.forEach(a
=> {
2192 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2193 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
], this.pieces()[a
.p
]["class"]);
2194 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2195 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2196 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2197 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2198 // Translate coordinates to use chessboard as reference:
2199 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2200 `translate(${ip - r.x}px,${jp - r.y}px)`;
2201 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2202 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2203 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2205 if (this.options
["dark"])
2206 this.graphUpdateEnlightened();
2209 playPlusVisual(move, r
) {
2211 this.playVisual(move, r
);
2212 this.afterPlay(move); //user method
2216 // Works for all rectangular boards:
2217 return Math
.sqrt(r
.width
** 2 + r
.height
** 2);
2221 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2224 animate(move, callback
) {
2225 if (this.noAnimate
|| move.noAnimate
) {
2229 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2230 // NOTE: cloning generally not required, but light enough, and simpler
2231 let movingPiece
= initPiece
.cloneNode();
2232 initPiece
.style
.opacity
= "0";
2234 document
.getElementById(this.containerId
)
2235 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2236 if (typeof move.start
.x
== "string") {
2237 // Need to bound width/height (was 100% for reserve pieces)
2238 const pieceWidth
= this.getPieceWidth(r
.width
);
2239 movingPiece
.style
.width
= pieceWidth
+ "px";
2240 movingPiece
.style
.height
= pieceWidth
+ "px";
2242 const maxDist
= this.getMaxDistance(r
);
2243 const pieces
= this.pieces();
2245 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2246 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2247 C
.AddClass_es(movingPiece
, pieces
[move.drag
.p
]["class"]);
2248 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2249 if (apparentColor
!= move.drag
.c
) {
2250 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2251 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2254 container
.appendChild(movingPiece
);
2255 const animateSegment
= (index
, cb
) => {
2256 // NOTE: move.drag could be generalized per-segment (usage?)
2257 const [i1
, j1
] = move.segments
[index
][0];
2258 const [i2
, j2
] = move.segments
[index
][1];
2259 const dep
= this.getPixelPosition(i1
, j1
, r
);
2260 const arr
= this.getPixelPosition(i2
, j2
, r
);
2261 movingPiece
.style
.transitionDuration
= "0s";
2262 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2264 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2265 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2266 // TODO: unclear why we need this new delay below:
2268 movingPiece
.style
.transitionDuration
= duration
+ "s";
2269 // movingPiece is child of container: no need to adjust coordinates
2270 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2271 setTimeout(cb
, duration
* 1000);
2274 if (!move.segments
) {
2276 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2280 const animateSegmentCallback
= () => {
2281 if (index
< move.segments
.length
)
2282 animateSegment(index
++, animateSegmentCallback
);
2284 movingPiece
.remove();
2285 initPiece
.style
.opacity
= "1";
2289 animateSegmentCallback();
2292 playReceivedMove(moves
, callback
) {
2293 const launchAnimation
= () => {
2294 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2295 const animateRec
= i
=> {
2296 this.animate(moves
[i
], () => {
2297 this.play(moves
[i
]);
2298 this.playVisual(moves
[i
], r
);
2299 if (i
< moves
.length
- 1)
2300 setTimeout(() => animateRec(i
+1), 300);
2307 // Delay if user wasn't focused:
2308 const checkDisplayThenAnimate
= (delay
) => {
2309 if (container
.style
.display
== "none") {
2310 alert("New move! Let's go back to game...");
2311 document
.getElementById("gameInfos").style
.display
= "none";
2312 container
.style
.display
= "block";
2313 setTimeout(launchAnimation
, 700);
2316 setTimeout(launchAnimation
, delay
|| 0);
2318 let container
= document
.getElementById(this.containerId
);
2319 if (document
.hidden
) {
2320 document
.onvisibilitychange
= () => {
2321 document
.onvisibilitychange
= undefined;
2322 checkDisplayThenAnimate(700);
2326 checkDisplayThenAnimate();