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",
39 label: "Falling pawn",
44 // Game modifiers (using "elementary variants"). Default: false
47 "balance", //takes precedence over doublemove & progressive
51 "cylinder", //ok with all
55 "progressive", //(natural) priority over doublemove
64 get pawnPromotions() {
65 return ['q', 'r', 'n', 'b'];
68 // Some variants don't have flags:
77 // En-passant captures allowed?
84 !!this.options
["crazyhouse"] ||
85 (!!this.options
["recycle"] && !this.options
["teleport"])
90 return !!this.options
["dark"];
93 // Some variants use click infos:
95 if (typeof coords
.x
!= "number")
96 return null; //click on reserves
98 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
99 this.board
[coords
.x
][coords
.y
] == ""
102 start: {x: this.captured
.x
, y: this.captured
.y
},
107 c: this.captured
.c
, //this.turn,
112 drag: {c: this.captured
.c
, p: this.captured
.p
}
121 // 3a --> {x:3, y:10}
122 static SquareToCoords(sq
) {
123 return ArrayFun
.toObject(["x", "y"],
124 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
127 // {x:11, y:12} --> bc
128 static CoordsToSquare(cd
) {
129 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
133 if (typeof cd
.x
== "number") {
135 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
139 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
142 idToCoords(targetId
) {
144 return null; //outside page, maybe...
145 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
147 idParts
.length
< 2 ||
148 idParts
[0] != this.containerId
||
149 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
153 const squares
= idParts
[1].split('-');
154 if (squares
[0] == "sq")
155 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
156 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
157 return {x: squares
[1], y: squares
[2]};
163 // Turn "wb" into "B" (for FEN)
165 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
168 // Turn "p" into "bp" (for board)
170 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
173 // Setup the initial random-or-not (asymmetric-or-not) position
174 genRandInitFen(seed
) {
175 Random
.setSeed(seed
);
177 let fen
, flags
= "0707";
178 if (!this.options
.randomness
)
180 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
184 let pieces
= { w: new Array(8), b: new Array(8) };
186 // Shuffle pieces on first (and last rank if randomness == 2)
187 for (let c
of ["w", "b"]) {
188 if (c
== 'b' && this.options
.randomness
== 1) {
189 pieces
['b'] = pieces
['w'];
194 let positions
= ArrayFun
.range(8);
196 // Get random squares for bishops
197 let randIndex
= 2 * Random
.randInt(4);
198 const bishop1Pos
= positions
[randIndex
];
199 // The second bishop must be on a square of different color
200 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
201 const bishop2Pos
= positions
[randIndex_tmp
];
202 // Remove chosen squares
203 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
204 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
206 // Get random squares for knights
207 randIndex
= Random
.randInt(6);
208 const knight1Pos
= positions
[randIndex
];
209 positions
.splice(randIndex
, 1);
210 randIndex
= Random
.randInt(5);
211 const knight2Pos
= positions
[randIndex
];
212 positions
.splice(randIndex
, 1);
214 // Get random square for queen
215 randIndex
= Random
.randInt(4);
216 const queenPos
= positions
[randIndex
];
217 positions
.splice(randIndex
, 1);
219 // Rooks and king positions are now fixed,
220 // because of the ordering rook-king-rook
221 const rook1Pos
= positions
[0];
222 const kingPos
= positions
[1];
223 const rook2Pos
= positions
[2];
225 // Finally put the shuffled pieces in the board array
226 pieces
[c
][rook1Pos
] = "r";
227 pieces
[c
][knight1Pos
] = "n";
228 pieces
[c
][bishop1Pos
] = "b";
229 pieces
[c
][queenPos
] = "q";
230 pieces
[c
][kingPos
] = "k";
231 pieces
[c
][bishop2Pos
] = "b";
232 pieces
[c
][knight2Pos
] = "n";
233 pieces
[c
][rook2Pos
] = "r";
234 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
237 pieces
["b"].join("") +
238 "/pppppppp/8/8/8/8/PPPPPPPP/" +
239 pieces
["w"].join("").toUpperCase() +
243 // Add turn + flags + enpassant (+ reserve)
246 parts
.push(`"flags":"${flags}"`);
247 if (this.hasEnpassant
)
248 parts
.push('"enpassant":"-"');
250 parts
.push('"reserve":"000000000000"');
251 if (this.options
["crazyhouse"])
252 parts
.push('"ispawn":"-"');
253 if (parts
.length
>= 1)
254 fen
+= " {" + parts
.join(",") + "}";
258 // "Parse" FEN: just return untransformed string data
260 const fenParts
= fen
.split(" ");
262 position: fenParts
[0],
264 movesCount: fenParts
[2]
266 if (fenParts
.length
> 3)
267 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
271 // Return current fen (game state)
274 this.getPosition() + " " +
275 this.getTurnFen() + " " +
280 parts
.push(`"flags":"${this.getFlagsFen()}"`);
281 if (this.hasEnpassant
)
282 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
284 parts
.push(`"reserve":"${this.getReserveFen()}"`);
285 if (this.options
["crazyhouse"])
286 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
287 if (parts
.length
>= 1)
288 fen
+= " {" + parts
.join(",") + "}";
292 // Position part of the FEN string
294 const format
= (count
) => {
295 // if more than 9 consecutive free spaces, break the integer,
296 // otherwise FEN parsing will fail.
299 // Most boards of size < 18:
301 return "9" + (count
- 9);
303 return "99" + (count
- 18);
306 for (let i
= 0; i
< this.size
.y
; i
++) {
308 for (let j
= 0; j
< this.size
.x
; j
++) {
309 if (this.board
[i
][j
] == "")
312 if (emptyCount
> 0) {
313 // Add empty squares in-between
314 position
+= format(emptyCount
);
317 position
+= this.board2fen(this.board
[i
][j
]);
322 position
+= format(emptyCount
);
323 if (i
< this.size
.y
- 1)
324 position
+= "/"; //separate rows
333 // Flags part of the FEN string
335 return ["w", "b"].map(c
=> {
336 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
340 // Enpassant part of the FEN string
343 return "-"; //no en-passant
344 return C
.CoordsToSquare(this.epSquare
);
349 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
354 const squares
= Object
.keys(this.ispawn
);
355 if (squares
.length
== 0)
357 return squares
.join(",");
360 // Set flags from fen (castle: white a,h then black a,h)
363 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
364 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
372 this.options
= o
.options
;
373 this.playerColor
= o
.color
;
374 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
376 // Fen string fully describes the game state
378 o
.fen
= this.genRandInitFen(o
.seed
);
379 const fenParsed
= this.parseFen(o
.fen
);
380 this.board
= this.getBoard(fenParsed
.position
);
381 this.turn
= fenParsed
.turn
;
382 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
383 this.setOtherVariables(fenParsed
);
385 // Graphical (can use variables defined above)
386 this.containerId
= o
.element
;
387 this.graphicalInit();
390 // Turn position fen into double array ["wb","wp","bk",...]
392 const rows
= position
.split("/");
393 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
394 for (let i
= 0; i
< rows
.length
; i
++) {
396 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
397 const character
= rows
[i
][indexInRow
];
398 const num
= parseInt(character
, 10);
399 // If num is a number, just shift j:
402 // Else: something at position i,j
404 board
[i
][j
++] = this.fen2board(character
);
410 // Some additional variables from FEN (variant dependant)
411 setOtherVariables(fenParsed
) {
412 // Set flags and enpassant:
414 this.setFlags(fenParsed
.flags
);
415 if (this.hasEnpassant
)
416 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
418 this.initReserves(fenParsed
.reserve
);
419 if (this.options
["crazyhouse"])
420 this.initIspawn(fenParsed
.ispawn
);
421 this.subTurn
= 1; //may be unused
422 if (this.options
["teleport"]) {
423 this.subTurnTeleport
= 1;
424 this.captured
= null;
426 if (this.options
["dark"]) {
427 // Setup enlightened: squares reachable by player side
428 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
429 this.updateEnlightened();
433 updateEnlightened() {
434 this.oldEnlightened
= this.enlightened
;
435 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
436 // Add pieces positions + all squares reachable by moves (includes Zen):
437 for (let x
=0; x
<this.size
.x
; x
++) {
438 for (let y
=0; y
<this.size
.y
; y
++) {
439 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
441 this.enlightened
[x
][y
] = true;
442 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
443 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
449 this.enlightEnpassant();
452 // Include square of the en-passant capturing square:
454 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
455 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
456 for (let step
of steps
) {
457 const x
= this.epSquare
.x
- step
[0],
458 y
= this.getY(this.epSquare
.y
- step
[1]);
460 this.onBoard(x
, y
) &&
461 this.getColor(x
, y
) == this.playerColor
&&
462 this.getPieceType(x
, y
) == "p"
464 this.enlightened
[x
][this.epSquare
.y
] = true;
470 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
471 initReserves(reserveStr
) {
472 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
473 this.reserve
= { w: {}, b: {} };
474 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
475 const L
= pieceName
.length
;
476 for (let i
of ArrayFun
.range(2 * L
)) {
478 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
480 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
484 initIspawn(ispawnStr
) {
485 if (ispawnStr
!= "-")
486 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
491 getNbReservePieces(color
) {
493 Object
.values(this.reserve
[color
]).reduce(
494 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
498 getRankInReserve(c
, p
) {
499 const pieces
= Object
.keys(this.pieces());
500 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
501 let toTest
= pieces
.slice(0, lastIndex
);
502 return toTest
.reduce(
503 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
509 getPieceWidth(rwidth
) {
510 return (rwidth
/ this.size
.y
);
513 getReserveSquareSize(rwidth
, nbR
) {
514 const sqSize
= this.getPieceWidth(rwidth
);
515 return Math
.min(sqSize
, rwidth
/ nbR
);
518 getReserveNumId(color
, piece
) {
519 return `${this.containerId}|rnum-${color}${piece}`;
523 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
524 window
.onresize
= () => this.re_drawBoardElements();
525 this.re_drawBoardElements();
526 this.initMouseEvents();
528 document
.getElementById(this.containerId
).querySelector(".chessboard");
529 new ResizeObserver(this.rescale
).observe(chessboard
);
532 re_drawBoardElements() {
533 const board
= this.getSvgChessboard();
534 const oppCol
= C
.GetOppCol(this.playerColor
);
536 document
.getElementById(this.containerId
).querySelector(".chessboard");
537 chessboard
.innerHTML
= "";
538 chessboard
.insertAdjacentHTML('beforeend', board
);
539 // Compare window ratio width / height to aspectRatio:
540 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
541 let cbWidth
, cbHeight
;
542 if (windowRatio
<= this.size
.ratio
) {
543 // Limiting dimension is width:
544 cbWidth
= Math
.min(window
.innerWidth
, 767);
545 cbHeight
= cbWidth
/ this.size
.ratio
;
548 // Limiting dimension is height:
549 cbHeight
= Math
.min(window
.innerHeight
, 767);
550 cbWidth
= cbHeight
* this.size
.ratio
;
553 const sqSize
= cbWidth
/ this.size
.y
;
554 // NOTE: allocate space for reserves (up/down) even if they are empty
555 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
556 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
557 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
558 cbWidth
= cbHeight
* this.size
.ratio
;
561 chessboard
.style
.width
= cbWidth
+ "px";
562 chessboard
.style
.height
= cbHeight
+ "px";
563 // Center chessboard:
564 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
565 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
566 chessboard
.style
.left
= spaceLeft
+ "px";
567 chessboard
.style
.top
= spaceTop
+ "px";
568 // Give sizes instead of recomputing them,
569 // because chessboard might not be drawn yet.
578 // Get SVG board (background, no pieces)
580 const flipped
= (this.playerColor
== 'b');
584 class="chessboard_SVG">
586 for (let i
=0; i
< this.size
.x
; i
++) {
587 for (let j
=0; j
< this.size
.y
; j
++) {
588 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
589 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
590 let classes
= this.getSquareColorClass(ii
, jj
);
591 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
592 classes
+= " in-shadow";
593 // NOTE: x / y reversed because coordinates system is reversed.
596 id="${this.coordsToId({x: ii, y: jj})}"
603 board
+= "</g></svg>";
607 // Generally light square bottom-right
608 getSquareColorClass(x
, y
) {
609 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
614 // Refreshing: delete old pieces first
615 for (let i
=0; i
<this.size
.x
; i
++) {
616 for (let j
=0; j
<this.size
.y
; j
++) {
617 if (this.g_pieces
[i
][j
]) {
618 this.g_pieces
[i
][j
].remove();
619 this.g_pieces
[i
][j
] = null;
625 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
627 document
.getElementById(this.containerId
).querySelector(".chessboard");
629 r
= chessboard
.getBoundingClientRect();
630 const pieceWidth
= this.getPieceWidth(r
.width
);
631 for (let i
=0; i
< this.size
.x
; i
++) {
632 for (let j
=0; j
< this.size
.y
; j
++) {
633 if (this.board
[i
][j
] != "") {
634 const color
= this.getColor(i
, j
);
635 const piece
= this.getPiece(i
, j
);
636 this.g_pieces
[i
][j
] = document
.createElement("piece");
637 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
638 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
639 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
640 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
641 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
642 // Translate coordinates to use chessboard as reference:
643 this.g_pieces
[i
][j
].style
.transform
=
644 `translate(${ip - r.x}px,${jp - r.y}px)`;
645 if (this.enlightened
&& !this.enlightened
[i
][j
])
646 this.g_pieces
[i
][j
].classList
.add("hidden");
647 chessboard
.appendChild(this.g_pieces
[i
][j
]);
652 this.re_drawReserve(['w', 'b'], r
);
655 // NOTE: assume !!this.reserve
656 re_drawReserve(colors
, r
) {
658 // Remove (old) reserve pieces
659 for (let c
of colors
) {
660 if (!this.reserve
[c
])
662 Object
.keys(this.reserve
[c
]).forEach(p
=> {
663 if (this.r_pieces
[c
][p
]) {
664 this.r_pieces
[c
][p
].remove();
665 delete this.r_pieces
[c
][p
];
666 const numId
= this.getReserveNumId(c
, p
);
667 document
.getElementById(numId
).remove();
670 let reservesDiv
= document
.getElementById("reserves_" + c
);
672 reservesDiv
.remove();
676 this.r_pieces
= { w: {}, b: {} };
677 let container
= document
.getElementById(this.containerId
);
679 r
= container
.querySelector(".chessboard").getBoundingClientRect();
680 for (let c
of colors
) {
681 if (!this.reserve
[c
])
683 const nbR
= this.getNbReservePieces(c
);
686 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
688 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
689 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
690 let rcontainer
= document
.createElement("div");
691 rcontainer
.id
= "reserves_" + c
;
692 rcontainer
.classList
.add("reserves");
693 rcontainer
.style
.left
= i0
+ "px";
694 rcontainer
.style
.top
= j0
+ "px";
695 // NOTE: +1 fix display bug on Firefox at least
696 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
697 rcontainer
.style
.height
= sqResSize
+ "px";
698 container
.appendChild(rcontainer
);
699 for (let p
of Object
.keys(this.reserve
[c
])) {
700 if (this.reserve
[c
][p
] == 0)
702 let r_cell
= document
.createElement("div");
703 r_cell
.id
= this.coordsToId({x: c
, y: p
});
704 r_cell
.classList
.add("reserve-cell");
705 r_cell
.style
.width
= sqResSize
+ "px";
706 r_cell
.style
.height
= sqResSize
+ "px";
707 rcontainer
.appendChild(r_cell
);
708 let piece
= document
.createElement("piece");
709 const pieceSpec
= this.pieces()[p
];
710 piece
.classList
.add(pieceSpec
["class"]);
711 piece
.classList
.add(C
.GetColorClass(c
));
712 piece
.style
.width
= "100%";
713 piece
.style
.height
= "100%";
714 this.r_pieces
[c
][p
] = piece
;
715 r_cell
.appendChild(piece
);
716 let number
= document
.createElement("div");
717 number
.textContent
= this.reserve
[c
][p
];
718 number
.classList
.add("reserve-num");
719 number
.id
= this.getReserveNumId(c
, p
);
720 const fontSize
= "1.3em";
721 number
.style
.fontSize
= fontSize
;
722 number
.style
.fontSize
= fontSize
;
723 r_cell
.appendChild(number
);
729 updateReserve(color
, piece
, count
) {
730 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
731 piece
= "k"; //capturing cannibal king: back to king form
732 const oldCount
= this.reserve
[color
][piece
];
733 this.reserve
[color
][piece
] = count
;
734 // Redrawing is much easier if count==0
735 if ([oldCount
, count
].includes(0))
736 this.re_drawReserve([color
]);
738 const numId
= this.getReserveNumId(color
, piece
);
739 document
.getElementById(numId
).textContent
= count
;
743 // Apply diff this.enlightened --> oldEnlightened on board
744 graphUpdateEnlightened() {
746 document
.getElementById(this.containerId
).querySelector(".chessboard");
747 const r
= chessboard
.getBoundingClientRect();
748 const pieceWidth
= this.getPieceWidth(r
.width
);
749 for (let x
=0; x
<this.size
.x
; x
++) {
750 for (let y
=0; y
<this.size
.y
; y
++) {
751 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
752 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
753 elt
.classList
.add("in-shadow");
754 if (this.g_pieces
[x
][y
])
755 this.g_pieces
[x
][y
].classList
.add("hidden");
757 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
758 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
759 elt
.classList
.remove("in-shadow");
760 if (this.g_pieces
[x
][y
])
761 this.g_pieces
[x
][y
].classList
.remove("hidden");
767 // After resize event: no need to destroy/recreate pieces
769 const container
= document
.getElementById(this.containerId
);
771 return; //useful at initial loading
772 let chessboard
= container
.querySelector(".chessboard");
773 const r
= chessboard
.getBoundingClientRect();
774 const newRatio
= r
.width
/ r
.height
;
775 let newWidth
= r
.width
,
776 newHeight
= r
.height
;
777 if (newRatio
> this.size
.ratio
) {
778 newWidth
= r
.height
* this.size
.ratio
;
779 chessboard
.style
.width
= newWidth
+ "px";
781 else if (newRatio
< this.size
.ratio
) {
782 newHeight
= r
.width
/ this.size
.ratio
;
783 chessboard
.style
.height
= newHeight
+ "px";
785 const newX
= (window
.innerWidth
- newWidth
) / 2;
786 chessboard
.style
.left
= newX
+ "px";
787 const newY
= (window
.innerHeight
- newHeight
) / 2;
788 chessboard
.style
.top
= newY
+ "px";
789 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
790 const pieceWidth
= this.getPieceWidth(newWidth
);
791 for (let i
=0; i
< this.size
.x
; i
++) {
792 for (let j
=0; j
< this.size
.y
; j
++) {
793 if (this.g_pieces
[i
][j
]) {
794 // NOTE: could also use CSS transform "scale"
795 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
796 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
797 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
798 // Translate coordinates to use chessboard as reference:
799 this.g_pieces
[i
][j
].style
.transform
=
800 `translate(${ip - newX}px,${jp - newY}px)`;
805 this.rescaleReserve(newR
);
809 for (let c
of ['w','b']) {
810 if (!this.reserve
[c
])
812 const nbR
= this.getNbReservePieces(c
);
815 // Resize container first
816 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
817 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
818 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
819 let rcontainer
= document
.getElementById("reserves_" + c
);
820 rcontainer
.style
.left
= i0
+ "px";
821 rcontainer
.style
.top
= j0
+ "px";
822 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
823 rcontainer
.style
.height
= sqResSize
+ "px";
824 // And then reserve cells:
825 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
826 Object
.keys(this.reserve
[c
]).forEach(p
=> {
827 if (this.reserve
[c
][p
] == 0)
829 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
830 r_cell
.style
.width
= sqResSize
+ "px";
831 r_cell
.style
.height
= sqResSize
+ "px";
836 // Return the absolute pixel coordinates given current position.
837 // Our coordinate system differs from CSS one (x <--> y).
838 // We return here the CSS coordinates (more useful).
839 getPixelPosition(i
, j
, r
) {
841 return [0, 0]; //piece vanishes
843 if (typeof i
== "string") {
844 // Reserves: need to know the rank of piece
845 const nbR
= this.getNbReservePieces(i
);
846 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
847 x
= this.getRankInReserve(i
, j
) * rsqSize
;
848 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
851 const sqSize
= r
.width
/ this.size
.y
;
852 const flipped
= (this.playerColor
== 'b');
853 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
854 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
856 return [r
.x
+ x
, r
.y
+ y
];
860 let container
= document
.getElementById(this.containerId
);
861 let chessboard
= container
.querySelector(".chessboard");
863 const getOffset
= e
=> {
866 return {x: e
.clientX
, y: e
.clientY
};
867 let touchLocation
= null;
868 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
869 // Touch screen, dragstart
870 touchLocation
= e
.targetTouches
[0];
871 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
872 // Touch screen, dragend
873 touchLocation
= e
.changedTouches
[0];
875 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
876 return {x: 0, y: 0}; //shouldn't reach here =)
879 const centerOnCursor
= (piece
, e
) => {
880 const centerShift
= this.getPieceWidth(r
.width
) / 2;
881 const offset
= getOffset(e
);
882 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
883 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
888 startPiece
, curPiece
= null,
890 const mousedown
= (e
) => {
891 // Disable zoom on smartphones:
892 if (e
.touches
&& e
.touches
.length
> 1)
894 r
= chessboard
.getBoundingClientRect();
895 pieceWidth
= this.getPieceWidth(r
.width
);
896 const cd
= this.idToCoords(e
.target
.id
);
898 const move = this.doClick(cd
);
900 this.playPlusVisual(move);
902 const [x
, y
] = Object
.values(cd
);
903 if (typeof x
!= "number")
904 startPiece
= this.r_pieces
[x
][y
];
906 startPiece
= this.g_pieces
[x
][y
];
907 if (startPiece
&& this.canIplay(x
, y
)) {
910 curPiece
= startPiece
.cloneNode();
911 curPiece
.style
.transform
= "none";
912 curPiece
.style
.zIndex
= 5;
913 curPiece
.style
.width
= pieceWidth
+ "px";
914 curPiece
.style
.height
= pieceWidth
+ "px";
915 centerOnCursor(curPiece
, e
);
916 container
.appendChild(curPiece
);
917 startPiece
.style
.opacity
= "0.4";
918 chessboard
.style
.cursor
= "none";
924 const mousemove
= (e
) => {
927 centerOnCursor(curPiece
, e
);
929 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
930 // Attempt to prevent horizontal swipe...
934 const mouseup
= (e
) => {
935 const newR
= chessboard
.getBoundingClientRect();
936 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
942 const [x
, y
] = [start
.x
, start
.y
];
945 chessboard
.style
.cursor
= "pointer";
946 startPiece
.style
.opacity
= "1";
947 const offset
= getOffset(e
);
948 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
950 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
952 // NOTE: clearly suboptimal, but much easier, and not a big deal.
953 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
954 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
955 const moves
= this.filterValid(potentialMoves
);
956 if (moves
.length
>= 2)
957 this.showChoices(moves
, r
);
958 else if (moves
.length
== 1)
959 this.playPlusVisual(moves
[0], r
);
964 if ('onmousedown' in window
) {
965 document
.addEventListener("mousedown", mousedown
);
966 document
.addEventListener("mousemove", mousemove
);
967 document
.addEventListener("mouseup", mouseup
);
969 if ('ontouchstart' in window
) {
970 // https://stackoverflow.com/a/42509310/12660887
971 document
.addEventListener("touchstart", mousedown
, {passive: false});
972 document
.addEventListener("touchmove", mousemove
, {passive: false});
973 document
.addEventListener("touchend", mouseup
, {passive: false});
975 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
978 showChoices(moves
, r
) {
979 let container
= document
.getElementById(this.containerId
);
980 let chessboard
= container
.querySelector(".chessboard");
981 let choices
= document
.createElement("div");
982 choices
.id
= "choices";
983 choices
.style
.width
= r
.width
+ "px";
984 choices
.style
.height
= r
.height
+ "px";
985 choices
.style
.left
= r
.x
+ "px";
986 choices
.style
.top
= r
.y
+ "px";
987 chessboard
.style
.opacity
= "0.5";
988 container
.appendChild(choices
);
989 const squareWidth
= r
.width
/ this.size
.y
;
990 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
991 const firstUpTop
= (r
.height
- squareWidth
) / 2;
992 const color
= moves
[0].appear
[0].c
;
993 const callback
= (m
) => {
994 chessboard
.style
.opacity
= "1";
995 container
.removeChild(choices
);
996 this.playPlusVisual(m
, r
);
998 for (let i
=0; i
< moves
.length
; i
++) {
999 let choice
= document
.createElement("div");
1000 choice
.classList
.add("choice");
1001 choice
.style
.width
= squareWidth
+ "px";
1002 choice
.style
.height
= squareWidth
+ "px";
1003 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1004 choice
.style
.top
= firstUpTop
+ "px";
1005 choice
.style
.backgroundColor
= "lightyellow";
1006 choice
.onclick
= () => callback(moves
[i
]);
1007 const piece
= document
.createElement("piece");
1008 const pieceSpec
= this.pieces()[moves
[i
].appear
[0].p
];
1009 piece
.classList
.add(pieceSpec
["class"]);
1010 piece
.classList
.add(C
.GetColorClass(color
));
1011 piece
.style
.width
= "100%";
1012 piece
.style
.height
= "100%";
1013 choice
.appendChild(piece
);
1014 choices
.appendChild(choice
);
1025 ratio: 1 //for rectangular board = y / x
1029 // Color of thing on square (i,j). 'undefined' if square is empty
1031 if (typeof i
== "string")
1032 return i
; //reserves
1033 return this.board
[i
][j
].charAt(0);
1036 static GetColorClass(c
) {
1037 return (c
== 'w' ? "white" : "black");
1040 // Assume square i,j isn't empty
1042 if (typeof j
== "string")
1043 return j
; //reserves
1044 return this.board
[i
][j
].charAt(1);
1047 // Piece type on square (i,j)
1048 getPieceType(i
, j
) {
1049 const p
= this.getPiece(i
, j
);
1050 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1053 // Get opponent color
1054 static GetOppCol(color
) {
1055 return (color
== "w" ? "b" : "w");
1058 // Can thing on square1 capture (no return) thing on square2?
1059 canTake([x1
, y1
], [x2
, y2
]) {
1060 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1063 // Is (x,y) on the chessboard?
1065 return (x
>= 0 && x
< this.size
.x
&&
1066 y
>= 0 && y
< this.size
.y
);
1069 // Am I allowed to move thing at square x,y ?
1071 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1074 ////////////////////////
1075 // PIECES SPECIFICATIONS
1077 pieces(color
, x
, y
) {
1078 const pawnShift
= (color
== "w" ? -1 : 1);
1079 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1080 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1086 steps: [[pawnShift
, 0]],
1087 range: (initRank
? 2 : 1)
1092 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1101 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1110 [1, 2], [1, -2], [-1, 2], [-1, -2],
1111 [2, 1], [-2, 1], [2, -1], [-2, -1]
1121 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1130 [0, 1], [0, -1], [1, 0], [-1, 0],
1131 [1, 1], [1, -1], [-1, 1], [-1, -1]
1142 [0, 1], [0, -1], [1, 0], [-1, 0],
1143 [1, 1], [1, -1], [-1, 1], [-1, -1]
1150 '!': {"class": "king-pawn", moveas: "p"},
1151 '#': {"class": "king-rook", moveas: "r"},
1152 '$': {"class": "king-knight", moveas: "n"},
1153 '%': {"class": "king-bishop", moveas: "b"},
1154 '*': {"class": "king-queen", moveas: "q"}
1158 ////////////////////
1161 // For Cylinder: get Y coordinate
1163 if (!this.options
["cylinder"])
1165 let res
= y
% this.size
.y
;
1171 // Stop at the first capture found
1172 atLeastOneCapture(color
) {
1173 color
= color
|| this.turn
;
1174 const oppCol
= C
.GetOppCol(color
);
1175 for (let i
= 0; i
< this.size
.x
; i
++) {
1176 for (let j
= 0; j
< this.size
.y
; j
++) {
1177 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1178 const allSpecs
= this.pieces(color
, i
, j
)
1179 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1180 const attacks
= specs
.attack
|| specs
.moves
;
1181 for (let a
of attacks
) {
1182 outerLoop: for (let step
of a
.steps
) {
1183 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1184 let stepCounter
= 1;
1185 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1186 if (a
.range
<= stepCounter
++)
1189 jj
= this.getY(jj
+ step
[1]);
1192 this.onBoard(ii
, jj
) &&
1193 this.getColor(ii
, jj
) == oppCol
&&
1195 [this.getBasicMove([i
, j
], [ii
, jj
])]
1208 getDropMovesFrom([c
, p
]) {
1209 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1210 // (but not necessarily otherwise)
1211 if (this.reserve
[c
][p
] == 0)
1214 for (let i
=0; i
<this.size
.x
; i
++) {
1215 for (let j
=0; j
<this.size
.y
; j
++) {
1217 this.board
[i
][j
] == "" &&
1218 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1221 (c
== 'w' && i
< this.size
.x
- 1) ||
1227 start: {x: c
, y: p
},
1229 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1239 // All possible moves from selected square
1240 getPotentialMovesFrom(sq
, color
) {
1241 if (this.subTurnTeleport
== 2)
1243 if (typeof sq
[0] == "string")
1244 return this.getDropMovesFrom(sq
);
1245 if (this.isImmobilized(sq
))
1247 const piece
= this.getPieceType(sq
[0], sq
[1]);
1248 let moves
= this.getPotentialMovesOf(piece
, sq
);
1251 this.hasEnpassant
&&
1254 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1259 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1261 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1263 return this.postProcessPotentialMoves(moves
);
1266 postProcessPotentialMoves(moves
) {
1267 if (moves
.length
== 0)
1269 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1270 const oppCol
= C
.GetOppCol(color
);
1272 if (this.options
["capture"] && this.atLeastOneCapture())
1273 moves
= this.capturePostProcess(moves
, oppCol
);
1275 if (this.options
["atomic"])
1276 this.atomicPostProcess(moves
, oppCol
);
1280 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1282 this.pawnPostProcess(moves
, color
, oppCol
);
1286 this.options
["cannibal"] &&
1287 this.options
["rifle"]
1289 // In this case a rifle-capture from last rank may promote a pawn
1290 this.riflePromotePostProcess(moves
, color
);
1296 capturePostProcess(moves
, oppCol
) {
1297 // Filter out non-capturing moves (not using m.vanish because of
1298 // self captures of Recycle and Teleport).
1299 return moves
.filter(m
=> {
1301 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1302 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1307 atomicPostProcess(moves
, oppCol
) {
1308 moves
.forEach(m
=> {
1310 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1311 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1324 for (let step
of steps
) {
1325 let x
= m
.end
.x
+ step
[0];
1326 let y
= this.getY(m
.end
.y
+ step
[1]);
1328 this.onBoard(x
, y
) &&
1329 this.board
[x
][y
] != "" &&
1330 this.getPieceType(x
, y
) != "p"
1334 p: this.getPiece(x
, y
),
1335 c: this.getColor(x
, y
),
1342 if (!this.options
["rifle"])
1343 m
.appear
.pop(); //nothing appears
1348 pawnPostProcess(moves
, color
, oppCol
) {
1350 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1351 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1352 moves
.forEach(m
=> {
1353 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1354 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1355 const promotionOk
= (
1357 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1360 return; //nothing to do
1361 if (this.options
["pawnfall"]) {
1365 let finalPieces
= ["p"];
1367 this.options
["cannibal"] &&
1368 this.board
[x2
][y2
] != "" &&
1369 this.getColor(x2
, y2
) == oppCol
1371 finalPieces
= [this.getPieceType(x2
, y2
)];
1374 finalPieces
= this.pawnPromotions
;
1375 m
.appear
[0].p
= finalPieces
[0];
1376 if (initPiece
== "!") //cannibal king-pawn
1377 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1378 for (let i
=1; i
<finalPieces
.length
; i
++) {
1379 const piece
= finalPieces
[i
];
1382 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1384 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1385 moreMoves
.push(newMove
);
1388 Array
.prototype.push
.apply(moves
, moreMoves
);
1391 riflePromotePostProcess(moves
, color
) {
1392 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1394 moves
.forEach(m
=> {
1396 m
.start
.x
== lastRank
&&
1397 m
.appear
.length
>= 1 &&
1398 m
.appear
[0].p
== "p" &&
1399 m
.appear
[0].x
== m
.start
.x
&&
1400 m
.appear
[0].y
== m
.start
.y
1402 m
.appear
[0].p
= this.pawnPromotions
[0];
1403 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1404 let newMv
= JSON
.parse(JSON
.stringify(m
));
1405 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1406 newMoves
.push(newMv
);
1410 Array
.prototype.push
.apply(moves
, newMoves
);
1413 // NOTE: using special symbols to not interfere with variants' pieces codes
1414 static get CannibalKings() {
1425 static get CannibalKingCode() {
1437 return !!C
.CannibalKings
[symbol
];
1441 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1442 isImmobilized([x
, y
]) {
1443 if (!this.options
["madrasi"])
1445 const color
= this.getColor(x
, y
);
1446 const oppCol
= C
.GetOppCol(color
);
1447 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1448 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1449 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1450 for (let a
of attacks
) {
1451 outerLoop: for (let step
of a
.steps
) {
1452 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1453 let stepCounter
= 1;
1454 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1455 if (a
.range
<= stepCounter
++)
1458 j
= this.getY(j
+ step
[1]);
1461 this.onBoard(i
, j
) &&
1462 this.getColor(i
, j
) == oppCol
&&
1463 this.getPieceType(i
, j
) == piece
1472 // Generic method to find possible moves of "sliding or jumping" pieces
1473 getPotentialMovesOf(piece
, [x
, y
]) {
1474 const color
= this.getColor(x
, y
);
1475 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1477 // Next 3 for Cylinder mode:
1482 const addMove
= (start
, end
) => {
1483 let newMove
= this.getBasicMove(start
, end
);
1484 if (segments
.length
> 0) {
1485 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1486 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1488 moves
.push(newMove
);
1491 const findAddMoves
= (type
, stepArray
) => {
1492 for (let s
of stepArray
) {
1493 outerLoop: for (let step
of s
.steps
) {
1496 let [i
, j
] = [x
, y
];
1497 let stepCounter
= 0;
1499 this.onBoard(i
, j
) &&
1500 (this.board
[i
][j
] == "" || (i
== x
&& j
== y
))
1504 !explored
[i
+ "." + j
] &&
1507 explored
[i
+ "." + j
] = true;
1508 addMove([x
, y
], [i
, j
]);
1510 if (s
.range
<= stepCounter
++)
1512 const oldIJ
= [i
, j
];
1514 j
= this.getY(j
+ step
[1]);
1515 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1516 // Boundary between segments (cylinder mode)
1517 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1521 if (!this.onBoard(i
, j
))
1523 const pieceIJ
= this.getPieceType(i
, j
);
1525 type
!= "moveonly" &&
1526 !explored
[i
+ "." + j
] &&
1528 !this.options
["zen"] ||
1532 this.canTake([x
, y
], [i
, j
]) ||
1534 (this.options
["recycle"] || this.options
["teleport"]) &&
1539 explored
[i
+ "." + j
] = true;
1540 addMove([x
, y
], [i
, j
]);
1546 const specialAttack
= !!stepSpec
.attack
;
1548 findAddMoves("attack", stepSpec
.attack
);
1549 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1550 if (this.options
["zen"]) {
1551 Array
.prototype.push
.apply(moves
,
1552 this.findCapturesOn([x
, y
], {zen: true}));
1557 // Search for enemy (or not) pieces attacking [x, y]
1558 findCapturesOn([x
, y
], args
) {
1561 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1562 for (let i
=0; i
<this.size
.x
; i
++) {
1563 for (let j
=0; j
<this.size
.y
; j
++) {
1565 this.board
[i
][j
] != "" &&
1566 this.getColor(i
, j
) == args
.oppCol
&&
1567 !this.isImmobilized([i
, j
])
1569 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1570 continue; //king not captured in this way
1572 this.pieces(args
.oppCol
, i
, j
)[this.getPieceType(i
, j
)];
1573 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1574 for (let a
of attacks
) {
1575 for (let s
of a
.steps
) {
1576 // Quick check: if step isn't compatible, don't even try
1577 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1579 // Finally verify that nothing stand in-between
1580 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1581 let stepCounter
= 1;
1583 this.onBoard(ii
, jj
) &&
1584 this.board
[ii
][jj
] == "" &&
1585 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1588 jj
= this.getY(jj
+ s
[1]);
1590 if (ii
== x
&& jj
== y
) {
1593 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1595 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1597 return moves
; //test for underCheck
1607 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1608 const rx
= (x2
- x1
) / step
[0],
1609 ry
= (y2
- y1
) / step
[1];
1611 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1612 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1616 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1617 // TODO: 1e-7 here is totally arbitrary
1618 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1620 distance
= Math
.round(distance
); //in case of (numerical...)
1621 if (range
< distance
)
1626 // Build a regular move from its initial and destination squares.
1627 // tr: transformation
1628 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1629 const initColor
= this.getColor(sx
, sy
);
1630 const initPiece
= this.getPiece(sx
, sy
);
1631 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1635 start: {x: sx
, y: sy
},
1639 !this.options
["rifle"] ||
1640 this.board
[ex
][ey
] == "" ||
1641 destColor
== initColor
//Recycle, Teleport
1647 c: !!tr
? tr
.c : initColor
,
1648 p: !!tr
? tr
.p : initPiece
1660 if (this.board
[ex
][ey
] != "") {
1665 c: this.getColor(ex
, ey
),
1666 p: this.getPiece(ex
, ey
)
1669 if (this.options
["cannibal"] && destColor
!= initColor
) {
1670 const lastIdx
= mv
.vanish
.length
- 1;
1671 let trPiece
= mv
.vanish
[lastIdx
].p
;
1672 if (this.isKing(this.getPiece(sx
, sy
)))
1673 trPiece
= C
.CannibalKingCode
[trPiece
];
1674 if (mv
.appear
.length
>= 1)
1675 mv
.appear
[0].p
= trPiece
;
1676 else if (this.options
["rifle"]) {
1699 // En-passant square, if any
1700 getEpSquare(moveOrSquare
) {
1701 if (typeof moveOrSquare
=== "string") {
1702 const square
= moveOrSquare
;
1705 return C
.SquareToCoords(square
);
1707 // Argument is a move:
1708 const move = moveOrSquare
;
1709 const s
= move.start
,
1713 Math
.abs(s
.x
- e
.x
) == 2 &&
1714 // Next conditions for variants like Atomic or Rifle, Recycle...
1715 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1716 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1723 return undefined; //default
1726 // Special case of en-passant captures: treated separately
1727 getEnpassantCaptures([x
, y
]) {
1728 const color
= this.getColor(x
, y
);
1729 const shiftX
= (color
== 'w' ? -1 : 1);
1730 const oppCol
= C
.GetOppCol(color
);
1731 let enpassantMove
= null;
1734 this.epSquare
.x
== x
+ shiftX
&&
1735 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1736 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1738 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1739 this.board
[epx
][epy
] = oppCol
+ "p";
1740 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1741 this.board
[epx
][epy
] = "";
1742 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1743 enpassantMove
.vanish
[lastIdx
].x
= x
;
1745 return !!enpassantMove
? [enpassantMove
] : [];
1748 // "castleInCheck" arg to let some variants castle under check
1749 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1750 const c
= this.getColor(x
, y
);
1753 const oppCol
= C
.GetOppCol(c
);
1757 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1758 const castlingKing
= this.getPiece(x
, y
);
1759 castlingCheck: for (
1762 castleSide
++ //large, then small
1764 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1766 // If this code is reached, rook and king are on initial position
1768 // NOTE: in some variants this is not a rook
1769 const rookPos
= this.castleFlags
[c
][castleSide
];
1770 const castlingPiece
= this.getPiece(x
, rookPos
);
1772 this.board
[x
][rookPos
] == "" ||
1773 this.getColor(x
, rookPos
) != c
||
1774 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1776 // Rook is not here, or changed color (see Benedict)
1779 // Nothing on the path of the king ? (and no checks)
1780 const finDist
= finalSquares
[castleSide
][0] - y
;
1781 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1785 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1787 this.board
[x
][i
] != "" &&
1788 // NOTE: next check is enough, because of chessboard constraints
1789 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1792 continue castlingCheck
;
1795 } while (i
!= finalSquares
[castleSide
][0]);
1796 // Nothing on the path to the rook?
1797 step
= (castleSide
== 0 ? -1 : 1);
1798 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1799 if (this.board
[x
][i
] != "")
1800 continue castlingCheck
;
1803 // Nothing on final squares, except maybe king and castling rook?
1804 for (i
= 0; i
< 2; i
++) {
1806 finalSquares
[castleSide
][i
] != rookPos
&&
1807 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1809 finalSquares
[castleSide
][i
] != y
||
1810 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1813 continue castlingCheck
;
1817 // If this code is reached, castle is valid
1823 y: finalSquares
[castleSide
][0],
1829 y: finalSquares
[castleSide
][1],
1835 // King might be initially disguised (Titan...)
1836 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1837 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1840 Math
.abs(y
- rookPos
) <= 2
1841 ? {x: x
, y: rookPos
}
1842 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1850 ////////////////////
1853 // Is (king at) given position under check by "oppCol" ?
1854 underCheck([x
, y
], oppCol
) {
1855 if (this.options
["taking"] || this.options
["dark"])
1858 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1862 // Stop at first king found (TODO: multi-kings)
1863 searchKingPos(color
) {
1864 for (let i
=0; i
< this.size
.x
; i
++) {
1865 for (let j
=0; j
< this.size
.y
; j
++) {
1866 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1870 return [-1, -1]; //king not found
1873 filterValid(moves
) {
1874 if (moves
.length
== 0)
1876 const color
= this.turn
;
1877 const oppCol
= C
.GetOppCol(color
);
1878 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1879 // Forbid moves either giving check or exploding opponent's king:
1880 const oppKingPos
= this.searchKingPos(oppCol
);
1881 moves
= moves
.filter(m
=> {
1883 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1884 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1887 this.playOnBoard(m
);
1888 const res
= !this.underCheck(oppKingPos
, color
);
1889 this.undoOnBoard(m
);
1893 if (this.options
["taking"] || this.options
["dark"])
1895 const kingPos
= this.searchKingPos(color
);
1896 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1897 return moves
.filter(m
=> {
1898 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1899 if (!filtered
[key
]) {
1900 this.playOnBoard(m
);
1901 let square
= kingPos
,
1902 res
= true; //a priori valid
1903 if (m
.vanish
.some(v
=> {
1904 return C
.CannibalKings
[v
.p
] && v
.c
== color
;
1906 // Search king in appear array:
1908 m
.appear
.findIndex(a
=> {
1909 return C
.CannibalKings
[a
.p
] && a
.c
== color
;
1911 if (newKingIdx
>= 0)
1912 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1916 res
&&= !this.underCheck(square
, oppCol
);
1917 this.undoOnBoard(m
);
1918 filtered
[key
] = res
;
1921 return filtered
[key
];
1928 // Aggregate flags into one object
1930 return this.castleFlags
;
1933 // Reverse operation
1934 disaggregateFlags(flags
) {
1935 this.castleFlags
= flags
;
1938 // Apply a move on board
1940 for (let psq
of move.vanish
)
1941 this.board
[psq
.x
][psq
.y
] = "";
1942 for (let psq
of move.appear
)
1943 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1945 // Un-apply the played move
1947 for (let psq
of move.appear
)
1948 this.board
[psq
.x
][psq
.y
] = "";
1949 for (let psq
of move.vanish
)
1950 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1953 updateCastleFlags(move) {
1954 // Update castling flags if start or arrive from/at rook/king locations
1955 move.appear
.concat(move.vanish
).forEach(psq
=> {
1957 this.board
[psq
.x
][psq
.y
] != "" &&
1958 this.getPieceType(psq
.x
, psq
.y
) == "k"
1960 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1962 // NOTE: not "else if" because king can capture enemy rook...
1966 else if (psq
.x
== this.size
.x
- 1)
1969 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1971 this.castleFlags
[c
][fidx
] = this.size
.y
;
1979 // If flags already off, no need to re-check:
1980 Object
.keys(this.castleFlags
).some(c
=> {
1981 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1983 this.updateCastleFlags(move);
1985 if (this.options
["crazyhouse"]) {
1986 move.vanish
.forEach(v
=> {
1987 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
1988 if (this.ispawn
[square
])
1989 delete this.ispawn
[square
];
1991 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
1992 // Assumption: something is moving
1993 const initSquare
= C
.CoordsToSquare(move.start
);
1994 const destSquare
= C
.CoordsToSquare(move.end
);
1996 this.ispawn
[initSquare
] ||
1997 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
1999 this.ispawn
[destSquare
] = true;
2002 this.ispawn
[destSquare
] &&
2003 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2005 move.vanish
[1].p
= "p";
2006 delete this.ispawn
[destSquare
];
2010 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2013 // Warning; atomic pawn removal isn't a capture
2014 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2016 const color
= this.turn
;
2017 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2018 // Something appears = dropped on board (some exceptions, Chakart...)
2019 if (move.appear
[i
].c
== color
) {
2020 const piece
= move.appear
[i
].p
;
2021 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2024 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2025 // Something vanish: add to reserve except if recycle & opponent
2027 this.options
["crazyhouse"] ||
2028 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2030 const piece
= move.vanish
[i
].p
;
2031 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2039 if (this.hasEnpassant
)
2040 this.epSquare
= this.getEpSquare(move);
2041 this.playOnBoard(move);
2042 this.postPlay(move);
2046 const color
= this.turn
;
2047 const oppCol
= C
.GetOppCol(color
);
2048 if (this.options
["dark"])
2049 this.updateEnlightened();
2050 if (this.options
["teleport"]) {
2052 this.subTurnTeleport
== 1 &&
2053 move.vanish
.length
> move.appear
.length
&&
2054 move.vanish
[move.vanish
.length
- 1].c
== color
2056 const v
= move.vanish
[move.vanish
.length
- 1];
2057 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2058 this.subTurnTeleport
= 2;
2061 this.subTurnTeleport
= 1;
2062 this.captured
= null;
2064 if (this.options
["balance"]) {
2065 if (![1, 3].includes(this.movesCount
))
2071 this.options
["doublemove"] &&
2072 this.movesCount
>= 1 &&
2075 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2077 const oppKingPos
= this.searchKingPos(oppCol
);
2079 oppKingPos
[0] >= 0 &&
2081 this.options
["taking"] ||
2082 !this.underCheck(oppKingPos
, color
)
2095 // "Stop at the first move found"
2096 atLeastOneMove(color
) {
2097 color
= color
|| this.turn
;
2098 for (let i
= 0; i
< this.size
.x
; i
++) {
2099 for (let j
= 0; j
< this.size
.y
; j
++) {
2100 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2101 // NOTE: in fact searching for all potential moves from i,j.
2102 // I don't believe this is an issue, for now at least.
2103 const moves
= this.getPotentialMovesFrom([i
, j
]);
2104 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2109 if (this.hasReserve
&& this.reserve
[color
]) {
2110 for (let p
of Object
.keys(this.reserve
[color
])) {
2111 const moves
= this.getDropMovesFrom([color
, p
]);
2112 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2119 // What is the score ? (Interesting if game is over)
2120 getCurrentScore(move) {
2121 const color
= this.turn
;
2122 const oppCol
= C
.GetOppCol(color
);
2123 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2124 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2126 if (kingPos
[0][0] < 0)
2127 return (color
== "w" ? "0-1" : "1-0");
2128 if (kingPos
[1][0] < 0)
2129 return (color
== "w" ? "1-0" : "0-1");
2130 if (this.atLeastOneMove())
2132 // No valid move: stalemate or checkmate?
2133 if (!this.underCheck(kingPos
[0], color
))
2136 return (color
== "w" ? "0-1" : "1-0");
2139 playVisual(move, r
) {
2140 move.vanish
.forEach(v
=> {
2141 // TODO: next "if" shouldn't be required
2142 if (this.g_pieces
[v
.x
][v
.y
])
2143 this.g_pieces
[v
.x
][v
.y
].remove();
2144 this.g_pieces
[v
.x
][v
.y
] = null;
2147 document
.getElementById(this.containerId
).querySelector(".chessboard");
2149 r
= chessboard
.getBoundingClientRect();
2150 const pieceWidth
= this.getPieceWidth(r
.width
);
2151 move.appear
.forEach(a
=> {
2152 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2153 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2154 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2155 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2156 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2157 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2158 // Translate coordinates to use chessboard as reference:
2159 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2160 `translate(${ip - r.x}px,${jp - r.y}px)`;
2161 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2162 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2163 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2165 if (this.options
["dark"])
2166 this.graphUpdateEnlightened();
2169 playPlusVisual(move, r
) {
2171 this.playVisual(move, r
);
2172 this.afterPlay(move); //user method
2175 getMaxDistance(rwidth
) {
2176 // Works for all rectangular boards:
2177 return Math
.sqrt(rwidth
** 2 + (rwidth
/ this.size
.ratio
) ** 2);
2181 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2184 animate(move, callback
) {
2185 if (this.noAnimate
|| move.noAnimate
) {
2189 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2190 if (!initPiece
) { //TODO this shouldn't be required
2194 // NOTE: cloning generally not required, but light enough, and simpler
2195 let movingPiece
= initPiece
.cloneNode();
2196 initPiece
.style
.opacity
= "0";
2198 document
.getElementById(this.containerId
)
2199 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2200 if (typeof move.start
.x
== "string") {
2201 // Need to bound width/height (was 100% for reserve pieces)
2202 const pieceWidth
= this.getPieceWidth(r
.width
);
2203 movingPiece
.style
.width
= pieceWidth
+ "px";
2204 movingPiece
.style
.height
= pieceWidth
+ "px";
2206 const maxDist
= this.getMaxDistance(r
.width
);
2207 const pieces
= this.pieces();
2209 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2210 movingPiece
.classList
.remove(pieces
[startCode
]["class"]);
2211 movingPiece
.classList
.add(pieces
[move.drag
.p
]["class"]);
2212 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2213 if (apparentColor
!= move.drag
.c
) {
2214 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2215 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2218 container
.appendChild(movingPiece
);
2219 const animateSegment
= (index
, cb
) => {
2220 // NOTE: move.drag could be generalized per-segment (usage?)
2221 const [i1
, j1
] = move.segments
[index
][0];
2222 const [i2
, j2
] = move.segments
[index
][1];
2223 const dep
= this.getPixelPosition(i1
, j1
, r
);
2224 const arr
= this.getPixelPosition(i2
, j2
, r
);
2225 movingPiece
.style
.transitionDuration
= "0s";
2226 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2228 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2229 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2230 // TODO: unclear why we need this new delay below:
2232 movingPiece
.style
.transitionDuration
= duration
+ "s";
2233 // movingPiece is child of container: no need to adjust coordinates
2234 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2235 setTimeout(cb
, duration
* 1000);
2238 if (!move.segments
) {
2240 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2244 const animateSegmentCallback
= () => {
2245 if (index
< move.segments
.length
)
2246 animateSegment(index
++, animateSegmentCallback
);
2248 movingPiece
.remove();
2249 initPiece
.style
.opacity
= "1";
2253 animateSegmentCallback();
2256 playReceivedMove(moves
, callback
) {
2257 const launchAnimation
= () => {
2258 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2259 const animateRec
= i
=> {
2260 this.animate(moves
[i
], () => {
2261 this.play(moves
[i
]);
2262 this.playVisual(moves
[i
], r
);
2263 if (i
< moves
.length
- 1)
2264 setTimeout(() => animateRec(i
+1), 300);
2271 // Delay if user wasn't focused:
2272 const checkDisplayThenAnimate
= (delay
) => {
2273 if (container
.style
.display
== "none") {
2274 alert("New move! Let's go back to game...");
2275 document
.getElementById("gameInfos").style
.display
= "none";
2276 container
.style
.display
= "block";
2277 setTimeout(launchAnimation
, 700);
2280 setTimeout(launchAnimation
, delay
|| 0);
2282 let container
= document
.getElementById(this.containerId
);
2283 if (document
.hidden
) {
2284 document
.onvisibilitychange
= () => {
2285 document
.onvisibilitychange
= undefined;
2286 checkDisplayThenAnimate(700);
2290 checkDisplayThenAnimate();