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 x
!= "number")
96 return null; //click on reserves
98 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
99 this.board
[x
][y
] == ""
102 start: {x: this.captured
.x
, y: this.captured
.y
},
107 c: this.captured
.c
, //this.turn,
120 // 3 --> d (column number to letter)
121 static CoordToColumn(colnum
) {
122 return String
.fromCharCode(97 + colnum
);
125 // d --> 3 (column letter to number)
126 static ColumnToCoord(columnStr
) {
127 return columnStr
.charCodeAt(0) - 97;
130 // 7 (numeric) --> 1 (str) [from black viewpoint].
131 static CoordToRow(rownum
) {
135 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
136 static RowToCoord(rownumStr
) {
137 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
138 return parseInt(rownumStr
, 30);
141 // a2 --> {x:2,y:0} (this is in fact a6)
142 static SquareToCoords(sq
) {
144 x: C
.RowToCoord(sq
[1]),
145 // NOTE: column is always one char => max 26 columns
146 y: C
.ColumnToCoord(sq
[0])
150 // {x:0,y:4} --> e0 (should be e8)
151 static CoordsToSquare(coords
) {
152 return C
.CoordToColumn(coords
.y
) + C
.CoordToRow(coords
.x
);
156 if (typeof x
== "number")
157 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
159 return `${this.containerId}|rsq-${x}-${y}`;
162 idToCoords(targetId
) {
164 return null; //outside page, maybe...
165 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
167 idParts
.length
< 2 ||
168 idParts
[0] != this.containerId
||
169 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
173 const squares
= idParts
[1].split('-');
174 if (squares
[0] == "sq")
175 return [ parseInt(squares
[1], 30), parseInt(squares
[2], 30) ];
176 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
177 return [squares
[1], squares
[2]];
183 // Turn "wb" into "B" (for FEN)
185 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
188 // Turn "p" into "bp" (for board)
190 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
193 // Setup the initial random-or-not (asymmetric-or-not) position
194 genRandInitFen(seed
) {
195 Random
.setSeed(seed
);
197 let fen
, flags
= "0707";
198 if (!this.options
.randomness
)
200 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
204 let pieces
= { w: new Array(8), b: new Array(8) };
206 // Shuffle pieces on first (and last rank if randomness == 2)
207 for (let c
of ["w", "b"]) {
208 if (c
== 'b' && this.options
.randomness
== 1) {
209 pieces
['b'] = pieces
['w'];
214 let positions
= ArrayFun
.range(8);
216 // Get random squares for bishops
217 let randIndex
= 2 * Random
.randInt(4);
218 const bishop1Pos
= positions
[randIndex
];
219 // The second bishop must be on a square of different color
220 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
221 const bishop2Pos
= positions
[randIndex_tmp
];
222 // Remove chosen squares
223 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
224 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
226 // Get random squares for knights
227 randIndex
= Random
.randInt(6);
228 const knight1Pos
= positions
[randIndex
];
229 positions
.splice(randIndex
, 1);
230 randIndex
= Random
.randInt(5);
231 const knight2Pos
= positions
[randIndex
];
232 positions
.splice(randIndex
, 1);
234 // Get random square for queen
235 randIndex
= Random
.randInt(4);
236 const queenPos
= positions
[randIndex
];
237 positions
.splice(randIndex
, 1);
239 // Rooks and king positions are now fixed,
240 // because of the ordering rook-king-rook
241 const rook1Pos
= positions
[0];
242 const kingPos
= positions
[1];
243 const rook2Pos
= positions
[2];
245 // Finally put the shuffled pieces in the board array
246 pieces
[c
][rook1Pos
] = "r";
247 pieces
[c
][knight1Pos
] = "n";
248 pieces
[c
][bishop1Pos
] = "b";
249 pieces
[c
][queenPos
] = "q";
250 pieces
[c
][kingPos
] = "k";
251 pieces
[c
][bishop2Pos
] = "b";
252 pieces
[c
][knight2Pos
] = "n";
253 pieces
[c
][rook2Pos
] = "r";
254 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
257 pieces
["b"].join("") +
258 "/pppppppp/8/8/8/8/PPPPPPPP/" +
259 pieces
["w"].join("").toUpperCase() +
263 // Add turn + flags + enpassant (+ reserve)
266 parts
.push(`"flags":"${flags}"`);
267 if (this.hasEnpassant
)
268 parts
.push('"enpassant":"-"');
270 parts
.push('"reserve":"000000000000"');
271 if (this.options
["crazyhouse"])
272 parts
.push('"ispawn":"-"');
273 if (parts
.length
>= 1)
274 fen
+= " {" + parts
.join(",") + "}";
278 // "Parse" FEN: just return untransformed string data
280 const fenParts
= fen
.split(" ");
282 position: fenParts
[0],
284 movesCount: fenParts
[2]
286 if (fenParts
.length
> 3)
287 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
291 // Return current fen (game state)
294 this.getBaseFen() + " " +
295 this.getTurnFen() + " " +
300 parts
.push(`"flags":"${this.getFlagsFen()}"`);
301 if (this.hasEnpassant
)
302 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
304 parts
.push(`"reserve":"${this.getReserveFen()}"`);
305 if (this.options
["crazyhouse"])
306 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
307 if (parts
.length
>= 1)
308 fen
+= " {" + parts
.join(",") + "}";
312 // Position part of the FEN string
314 const format
= (count
) => {
315 // if more than 9 consecutive free spaces, break the integer,
316 // otherwise FEN parsing will fail.
319 // Most boards of size < 18:
321 return "9" + (count
- 9);
323 return "99" + (count
- 18);
326 for (let i
= 0; i
< this.size
.y
; i
++) {
328 for (let j
= 0; j
< this.size
.x
; j
++) {
329 if (this.board
[i
][j
] == "")
332 if (emptyCount
> 0) {
333 // Add empty squares in-between
334 position
+= format(emptyCount
);
337 position
+= this.board2fen(this.board
[i
][j
]);
342 position
+= format(emptyCount
);
343 if (i
< this.size
.y
- 1)
344 position
+= "/"; //separate rows
353 // Flags part of the FEN string
355 return ["w", "b"].map(c
=> {
356 return this.castleFlags
[c
].map(x
=> x
.toString(30)).join("");
360 // Enpassant part of the FEN string
363 return "-"; //no en-passant
364 return C
.CoordsToSquare(this.epSquare
);
369 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
374 const coords
= Object
.keys(this.ispawn
);
375 if (coords
.length
== 0)
377 return coords
.join(",");
380 // Set flags from fen (castle: white a,h then black a,h)
383 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 30)),
384 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 30))
392 this.options
= o
.options
;
393 this.playerColor
= o
.color
;
394 this.afterPlay
= o
.afterPlay
;
396 // Fen string fully describes the game state
398 o
.fen
= this.genRandInitFen(o
.seed
);
399 const fenParsed
= this.parseFen(o
.fen
);
400 this.board
= this.getBoard(fenParsed
.position
);
401 this.turn
= fenParsed
.turn
;
402 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
403 this.setOtherVariables(fenParsed
);
405 // Graphical (can use variables defined above)
406 this.containerId
= o
.element
;
407 this.graphicalInit();
410 // Turn position fen into double array ["wb","wp","bk",...]
412 const rows
= position
.split("/");
413 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
414 for (let i
= 0; i
< rows
.length
; i
++) {
416 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
417 const character
= rows
[i
][indexInRow
];
418 const num
= parseInt(character
, 10);
419 // If num is a number, just shift j:
422 // Else: something at position i,j
424 board
[i
][j
++] = this.fen2board(character
);
430 // Some additional variables from FEN (variant dependant)
431 setOtherVariables(fenParsed
) {
432 // Set flags and enpassant:
434 this.setFlags(fenParsed
.flags
);
435 if (this.hasEnpassant
)
436 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
438 this.initReserves(fenParsed
.reserve
);
439 if (this.options
["crazyhouse"])
440 this.initIspawn(fenParsed
.ispawn
);
441 this.subTurn
= 1; //may be unused
442 if (this.options
["teleport"]) {
443 this.subTurnTeleport
= 1;
444 this.captured
= null;
446 if (this.options
["dark"]) {
447 // Setup enlightened: squares reachable by player side
448 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
449 this.updateEnlightened();
453 updateEnlightened() {
454 this.oldEnlightened
= this.enlightened
;
455 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
456 // Add pieces positions + all squares reachable by moves (includes Zen):
457 for (let x
=0; x
<this.size
.x
; x
++) {
458 for (let y
=0; y
<this.size
.y
; y
++) {
459 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
461 this.enlightened
[x
][y
] = true;
462 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
463 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
469 this.enlightEnpassant();
472 // Include square of the en-passant capturing square:
474 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
475 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
476 for (let step
of steps
) {
477 const x
= this.epSquare
.x
- step
[0],
478 y
= this.computeY(this.epSquare
.y
- step
[1]);
480 this.onBoard(x
, y
) &&
481 this.getColor(x
, y
) == this.playerColor
&&
482 this.getPieceType(x
, y
) == "p"
484 this.enlightened
[x
][this.epSquare
.y
] = true;
490 // Apply diff this.enlightened --> oldEnlightened on board
491 graphUpdateEnlightened() {
493 document
.getElementById(this.containerId
).querySelector(".chessboard");
494 const r
= chessboard
.getBoundingClientRect();
495 const pieceWidth
= this.getPieceWidth(r
.width
);
496 for (let x
=0; x
<this.size
.x
; x
++) {
497 for (let y
=0; y
<this.size
.y
; y
++) {
498 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
499 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
500 elt
.classList
.add("in-shadow");
501 if (this.g_pieces
[x
][y
])
502 this.g_pieces
[x
][y
].classList
.add("hidden");
504 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
505 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
506 elt
.classList
.remove("in-shadow");
507 if (this.g_pieces
[x
][y
])
508 this.g_pieces
[x
][y
].classList
.remove("hidden");
514 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
515 initReserves(reserveStr
) {
516 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
517 this.reserve
= { w: {}, b: {} };
518 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
519 const L
= pieceName
.length
;
520 for (let i
of ArrayFun
.range(2 * L
)) {
522 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
524 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
528 initIspawn(ispawnStr
) {
529 if (ispawnStr
!= "-") {
530 this.ispawn
= ispawnStr
.split(",").map(C
.SquareToCoords
)
531 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
537 getNbReservePieces(color
) {
539 Object
.values(this.reserve
[color
]).reduce(
540 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
547 getPieceWidth(rwidth
) {
548 return (rwidth
/ this.size
.y
);
551 getSquareWidth(rwidth
) {
552 return this.getPieceWidth(rwidth
);
555 getReserveSquareSize(rwidth
, nbR
) {
556 const sqSize
= this.getSquareWidth(rwidth
);
557 return Math
.min(sqSize
, rwidth
/ nbR
);
560 getReserveNumId(color
, piece
) {
561 return `${this.containerId}|rnum-${color}${piece}`;
565 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
566 window
.onresize
= () => this.re_drawBoardElements();
567 this.re_drawBoardElements();
568 this.initMouseEvents();
570 document
.getElementById(this.containerId
).querySelector(".chessboard");
571 new ResizeObserver(this.rescale
).observe(chessboard
);
574 re_drawBoardElements() {
575 const board
= this.getSvgChessboard();
576 const oppCol
= C
.GetOppCol(this.playerColor
);
578 document
.getElementById(this.containerId
).querySelector(".chessboard");
579 chessboard
.innerHTML
= "";
580 chessboard
.insertAdjacentHTML('beforeend', board
);
581 const aspectRatio
= this.size
.y
/ this.size
.x
;
582 // Compare window ratio width / height to aspectRatio:
583 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
584 let cbWidth
, cbHeight
;
585 if (windowRatio
<= aspectRatio
) {
586 // Limiting dimension is width:
587 cbWidth
= Math
.min(window
.innerWidth
, 767);
588 cbHeight
= cbWidth
/ aspectRatio
;
591 // Limiting dimension is height:
592 cbHeight
= Math
.min(window
.innerHeight
, 767);
593 cbWidth
= cbHeight
* aspectRatio
;
596 const sqSize
= cbWidth
/ this.size
.y
;
597 // NOTE: allocate space for reserves (up/down) even if they are empty
598 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
599 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
600 cbWidth
= cbHeight
* aspectRatio
;
603 chessboard
.style
.width
= cbWidth
+ "px";
604 chessboard
.style
.height
= cbHeight
+ "px";
605 // Center chessboard:
606 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
607 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
608 chessboard
.style
.left
= spaceLeft
+ "px";
609 chessboard
.style
.top
= spaceTop
+ "px";
610 // Give sizes instead of recomputing them,
611 // because chessboard might not be drawn yet.
620 // Get SVG board (background, no pieces)
622 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
623 const flipped
= (this.playerColor
== 'b');
628 class="chessboard_SVG">
630 for (let i
=0; i
< sizeX
; i
++) {
631 for (let j
=0; j
< sizeY
; j
++) {
632 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
633 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
634 let classes
= this.getSquareColorClass(ii
, jj
);
635 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
636 classes
+= " in-shadow";
637 // NOTE: x / y reversed because coordinates system is reversed.
640 id="${this.coordsToId([ii, jj])}"
647 board
+= "</g></svg>";
651 // Generally light square bottom-right
652 getSquareColorClass(i
, j
) {
653 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
658 // Refreshing: delete old pieces first
659 for (let i
=0; i
<this.size
.x
; i
++) {
660 for (let j
=0; j
<this.size
.y
; j
++) {
661 if (this.g_pieces
[i
][j
]) {
662 this.g_pieces
[i
][j
].remove();
663 this.g_pieces
[i
][j
] = null;
669 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
671 document
.getElementById(this.containerId
).querySelector(".chessboard");
673 r
= chessboard
.getBoundingClientRect();
674 const pieceWidth
= this.getPieceWidth(r
.width
);
675 for (let i
=0; i
< this.size
.x
; i
++) {
676 for (let j
=0; j
< this.size
.y
; j
++) {
677 if (this.board
[i
][j
] != "") {
678 const color
= this.getColor(i
, j
);
679 const piece
= this.getPiece(i
, j
);
680 this.g_pieces
[i
][j
] = document
.createElement("piece");
681 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
682 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
683 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
684 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
685 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
686 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
687 if (this.enlightened
&& !this.enlightened
[i
][j
])
688 this.g_pieces
[i
][j
].classList
.add("hidden");
689 chessboard
.appendChild(this.g_pieces
[i
][j
]);
694 this.re_drawReserve(['w', 'b'], r
);
697 // NOTE: assume !!this.reserve
698 re_drawReserve(colors
, r
) {
700 // Remove (old) reserve pieces
701 for (let c
of colors
) {
702 if (!this.reserve
[c
])
704 Object
.keys(this.reserve
[c
]).forEach(p
=> {
705 if (this.r_pieces
[c
][p
]) {
706 this.r_pieces
[c
][p
].remove();
707 delete this.r_pieces
[c
][p
];
708 const numId
= this.getReserveNumId(c
, p
);
709 document
.getElementById(numId
).remove();
712 let reservesDiv
= document
.getElementById("reserves_" + c
);
714 reservesDiv
.remove();
718 this.r_pieces
= { 'w': {}, 'b': {} };
719 let container
= document
.getElementById(this.containerId
);
721 r
= container
.querySelector(".chessboard").getBoundingClientRect();
722 for (let c
of colors
) {
723 if (!this.reserve
[c
])
725 const nbR
= this.getNbReservePieces(c
);
728 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
730 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
731 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
732 let rcontainer
= document
.createElement("div");
733 rcontainer
.id
= "reserves_" + c
;
734 rcontainer
.classList
.add("reserves");
735 rcontainer
.style
.left
= i0
+ "px";
736 rcontainer
.style
.top
= j0
+ "px";
737 // NOTE: +1 fix display bug on Firefox at least
738 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
739 rcontainer
.style
.height
= sqResSize
+ "px";
740 container
.appendChild(rcontainer
);
741 for (let p
of Object
.keys(this.reserve
[c
])) {
742 if (this.reserve
[c
][p
] == 0)
744 let r_cell
= document
.createElement("div");
745 r_cell
.id
= this.coordsToId([c
, p
]);
746 r_cell
.classList
.add("reserve-cell");
747 r_cell
.style
.width
= sqResSize
+ "px";
748 r_cell
.style
.height
= sqResSize
+ "px";
749 rcontainer
.appendChild(r_cell
);
750 let piece
= document
.createElement("piece");
751 const pieceSpec
= this.pieces()[p
];
752 piece
.classList
.add(pieceSpec
["class"]);
753 piece
.classList
.add(c
== 'w' ? "white" : "black");
754 piece
.style
.width
= "100%";
755 piece
.style
.height
= "100%";
756 this.r_pieces
[c
][p
] = piece
;
757 r_cell
.appendChild(piece
);
758 let number
= document
.createElement("div");
759 number
.textContent
= this.reserve
[c
][p
];
760 number
.classList
.add("reserve-num");
761 number
.id
= this.getReserveNumId(c
, p
);
762 const fontSize
= "1.3em";
763 number
.style
.fontSize
= fontSize
;
764 number
.style
.fontSize
= fontSize
;
765 r_cell
.appendChild(number
);
771 updateReserve(color
, piece
, count
) {
772 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
773 piece
= "k"; //capturing cannibal king: back to king form
774 const oldCount
= this.reserve
[color
][piece
];
775 this.reserve
[color
][piece
] = count
;
776 // Redrawing is much easier if count==0
777 if ([oldCount
, count
].includes(0))
778 this.re_drawReserve([color
]);
780 const numId
= this.getReserveNumId(color
, piece
);
781 document
.getElementById(numId
).textContent
= count
;
785 // After resize event: no need to destroy/recreate pieces
787 const container
= document
.getElementById(this.containerId
);
789 return; //useful at initial loading
790 let chessboard
= container
.querySelector(".chessboard");
791 const r
= chessboard
.getBoundingClientRect();
792 const newRatio
= r
.width
/ r
.height
;
793 const aspectRatio
= this.size
.y
/ this.size
.x
;
794 let newWidth
= r
.width
,
795 newHeight
= r
.height
;
796 if (newRatio
> aspectRatio
) {
797 newWidth
= r
.height
* aspectRatio
;
798 chessboard
.style
.width
= newWidth
+ "px";
800 else if (newRatio
< aspectRatio
) {
801 newHeight
= r
.width
/ aspectRatio
;
802 chessboard
.style
.height
= newHeight
+ "px";
804 const newX
= (window
.innerWidth
- newWidth
) / 2;
805 chessboard
.style
.left
= newX
+ "px";
806 const newY
= (window
.innerHeight
- newHeight
) / 2;
807 chessboard
.style
.top
= newY
+ "px";
808 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
809 const pieceWidth
= this.getPieceWidth(newWidth
);
810 for (let i
=0; i
< this.size
.x
; i
++) {
811 for (let j
=0; j
< this.size
.y
; j
++) {
812 if (this.g_pieces
[i
][j
]) {
813 // NOTE: could also use CSS transform "scale"
814 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
815 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
816 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
817 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
822 this.rescaleReserve(newR
);
826 for (let c
of ['w','b']) {
827 if (!this.reserve
[c
])
829 const nbR
= this.getNbReservePieces(c
);
832 // Resize container first
833 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
834 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
835 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
836 let rcontainer
= document
.getElementById("reserves_" + c
);
837 rcontainer
.style
.left
= i0
+ "px";
838 rcontainer
.style
.top
= j0
+ "px";
839 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
840 rcontainer
.style
.height
= sqResSize
+ "px";
841 // And then reserve cells:
842 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
843 Object
.keys(this.reserve
[c
]).forEach(p
=> {
844 if (this.reserve
[c
][p
] == 0)
846 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
847 r_cell
.style
.width
= sqResSize
+ "px";
848 r_cell
.style
.height
= sqResSize
+ "px";
853 // Return the absolute pixel coordinates (on board) given current position.
854 // Our coordinate system differs from CSS one (x <--> y).
855 // We return here the CSS coordinates (more useful).
856 getPixelPosition(i
, j
, r
) {
857 const sqSize
= this.getSquareWidth(r
.width
);
859 return [0, 0]; //piece vanishes
860 const flipped
= (this.playerColor
== 'b');
861 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
862 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
868 document
.getElementById(this.containerId
).querySelector(".chessboard");
870 const getOffset
= e
=> {
873 return {x: e
.clientX
, y: e
.clientY
};
874 let touchLocation
= null;
875 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
876 // Touch screen, dragstart
877 touchLocation
= e
.targetTouches
[0];
878 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
879 // Touch screen, dragend
880 touchLocation
= e
.changedTouches
[0];
882 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
883 return {x: 0, y: 0}; //shouldn't reach here =)
886 const centerOnCursor
= (piece
, e
) => {
887 const centerShift
= sqSize
/ 2;
888 const offset
= getOffset(e
);
889 piece
.style
.left
= (offset
.x
- r
.x
- centerShift
) + "px";
890 piece
.style
.top
= (offset
.y
- r
.y
- centerShift
) + "px";
895 startPiece
, curPiece
= null,
897 const mousedown
= (e
) => {
898 // Disable zoom on smartphones:
899 if (e
.touches
&& e
.touches
.length
> 1)
901 r
= chessboard
.getBoundingClientRect();
902 sqSize
= this.getSquareWidth(r
.width
);
903 const square
= this.idToCoords(e
.target
.id
);
905 const [i
, j
] = square
;
906 const move = this.doClick([i
, j
]);
908 this.playPlusVisual(move);
910 if (typeof i
!= "number")
911 startPiece
= this.r_pieces
[i
][j
];
912 else if (this.g_pieces
[i
][j
])
913 startPiece
= this.g_pieces
[i
][j
];
914 if (startPiece
&& this.canIplay(i
, j
)) {
916 start
= { x: i
, y: j
};
917 curPiece
= startPiece
.cloneNode();
918 curPiece
.style
.transform
= "none";
919 curPiece
.style
.zIndex
= 5;
920 curPiece
.style
.width
= sqSize
+ "px";
921 curPiece
.style
.height
= sqSize
+ "px";
922 centerOnCursor(curPiece
, e
);
923 chessboard
.appendChild(curPiece
);
924 startPiece
.style
.opacity
= "0.4";
925 chessboard
.style
.cursor
= "none";
931 const mousemove
= (e
) => {
934 centerOnCursor(curPiece
, e
);
936 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
937 // Attempt to prevent horizontal swipe...
941 const mouseup
= (e
) => {
942 const newR
= chessboard
.getBoundingClientRect();
943 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
949 const [x
, y
] = [start
.x
, start
.y
];
952 chessboard
.style
.cursor
= "pointer";
953 startPiece
.style
.opacity
= "1";
954 const offset
= getOffset(e
);
955 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
956 const sq
= landingElt
? this.idToCoords(landingElt
.id
) : undefined;
959 // NOTE: clearly suboptimal, but much easier, and not a big deal.
960 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
961 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
962 const moves
= this.filterValid(potentialMoves
);
963 if (moves
.length
>= 2)
964 this.showChoices(moves
, r
);
965 else if (moves
.length
== 1)
966 this.playPlusVisual(moves
[0], r
);
971 if ('onmousedown' in window
) {
972 document
.addEventListener("mousedown", mousedown
);
973 document
.addEventListener("mousemove", mousemove
);
974 document
.addEventListener("mouseup", mouseup
);
976 if ('ontouchstart' in window
) {
977 // https://stackoverflow.com/a/42509310/12660887
978 document
.addEventListener("touchstart", mousedown
, {passive: false});
979 document
.addEventListener("touchmove", mousemove
, {passive: false});
980 document
.addEventListener("touchend", mouseup
, {passive: false});
982 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
985 showChoices(moves
, r
) {
986 let container
= document
.getElementById(this.containerId
);
987 let chessboard
= container
.querySelector(".chessboard");
988 let choices
= document
.createElement("div");
989 choices
.id
= "choices";
990 choices
.style
.width
= r
.width
+ "px";
991 choices
.style
.height
= r
.height
+ "px";
992 choices
.style
.left
= r
.x
+ "px";
993 choices
.style
.top
= r
.y
+ "px";
994 chessboard
.style
.opacity
= "0.5";
995 container
.appendChild(choices
);
996 const squareWidth
= this.getSquareWidth(r
.width
);
997 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
998 const firstUpTop
= (r
.height
- squareWidth
) / 2;
999 const color
= moves
[0].appear
[0].c
;
1000 const callback
= (m
) => {
1001 chessboard
.style
.opacity
= "1";
1002 container
.removeChild(choices
);
1003 this.playPlusVisual(m
, r
);
1005 for (let i
=0; i
< moves
.length
; i
++) {
1006 let choice
= document
.createElement("div");
1007 choice
.classList
.add("choice");
1008 choice
.style
.width
= squareWidth
+ "px";
1009 choice
.style
.height
= squareWidth
+ "px";
1010 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1011 choice
.style
.top
= firstUpTop
+ "px";
1012 choice
.style
.backgroundColor
= "lightyellow";
1013 choice
.onclick
= () => callback(moves
[i
]);
1014 const piece
= document
.createElement("piece");
1015 const pieceSpec
= this.pieces()[moves
[i
].appear
[0].p
];
1016 piece
.classList
.add(pieceSpec
["class"]);
1017 piece
.classList
.add(color
== 'w' ? "white" : "black");
1018 piece
.style
.width
= "100%";
1019 piece
.style
.height
= "100%";
1020 choice
.appendChild(piece
);
1021 choices
.appendChild(choice
);
1029 return {"x": 8, "y": 8};
1032 // Color of thing on square (i,j). 'undefined' if square is empty
1034 return this.board
[i
][j
].charAt(0);
1037 // Assume square i,j isn't empty
1039 return this.board
[i
][j
].charAt(1);
1042 // Piece type on square (i,j)
1043 getPieceType(i
, j
) {
1044 const p
= this.board
[i
][j
].charAt(1);
1045 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1048 // Get opponent color
1049 static GetOppCol(color
) {
1050 return (color
== "w" ? "b" : "w");
1053 // Can thing on square1 capture (no return) thing on square2?
1054 canTake([x1
, y1
], [x2
, y2
]) {
1055 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1058 // Is (x,y) on the chessboard?
1060 return (x
>= 0 && x
< this.size
.x
&&
1061 y
>= 0 && y
< this.size
.y
);
1064 // Used in interface
1067 this.playerColor
== this.turn
&&
1069 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1070 (typeof x
== "string" && x
== this.turn
) //reserve
1075 ////////////////////////
1076 // PIECES SPECIFICATIONS
1078 pieces(color
, x
, y
) {
1079 const pawnShift
= (color
== "w" ? -1 : 1);
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.computeY(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.computeY(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
);
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.computeY(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(); //nothin 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 let finalPieces
= ["p"];
1354 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1355 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1356 const promotionOk
= (
1358 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1361 return; //nothing to do
1362 if (!this.options
["pawnfall"]) {
1364 this.options
["cannibal"] &&
1365 this.board
[x2
][y2
] != "" &&
1366 this.getColor(x2
, y2
) == oppCol
1368 finalPieces
= [this.getPieceType(x2
, y2
)];
1371 finalPieces
= this.pawnPromotions
;
1373 m
.appear
[0].p
= finalPieces
[0];
1374 if (initPiece
== "!") //cannibal king-pawn
1375 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1376 for (let i
=1; i
<finalPieces
.length
; i
++) {
1377 const piece
= finalPieces
[i
];
1379 if (!this.options
["pawnfall"]) {
1382 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1385 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1386 if (this.options
["pawnfall"]) {
1387 newMove
.appear
.shift();
1388 newMove
.pawnfall
= true; //required in prePlay()
1390 moreMoves
.push(newMove
);
1393 Array
.prototype.push
.apply(moves
, moreMoves
);
1396 riflePromotePostProcess(moves
) {
1397 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1399 moves
.forEach(m
=> {
1401 m
.start
.x
== lastRank
&&
1402 m
.appear
.length
>= 1 &&
1403 m
.appear
[0].p
== "p" &&
1404 m
.appear
[0].x
== m
.start
.x
&&
1405 m
.appear
[0].y
== m
.start
.y
1407 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1408 m
.appear
[0].p
= this.pawnPromotions
[0];
1409 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1410 let newMv
= JSON
.parse(JSON
.stringify(m
));
1411 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1412 newMoves
.push(newMv
);
1416 Array
.prototype.push
.apply(moves
, newMoves
);
1419 // NOTE: using special symbols to not interfere with variants' pieces codes
1420 static get CannibalKings() {
1430 static get CannibalKingCode() {
1444 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1449 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1450 isImmobilized([x
, y
]) {
1451 if (!this.options
["madrasi"])
1453 const color
= this.getColor(x
, y
);
1454 const oppCol
= C
.GetOppCol(color
);
1455 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1456 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1457 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1458 for (let a
of attacks
) {
1459 outerLoop: for (let step
of a
.steps
) {
1460 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1461 let stepCounter
= 1;
1462 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1463 if (a
.range
<= stepCounter
++)
1466 j
= this.computeY(j
+ step
[1]);
1469 this.onBoard(i
, j
) &&
1470 this.getColor(i
, j
) == oppCol
&&
1471 this.getPieceType(i
, j
) == piece
1480 // Generic method to find possible moves of "sliding or jumping" pieces
1481 getPotentialMovesOf(piece
, [x
, y
]) {
1482 const color
= this.getColor(x
, y
);
1483 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1485 let explored
= {}; //for Cylinder mode
1487 const findAddMoves
= (type
, stepArray
) => {
1488 for (let s
of stepArray
) {
1489 outerLoop: for (let step
of s
.steps
) {
1490 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1491 let stepCounter
= 1;
1492 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1493 if (type
!= "attack" && !explored
[i
+ "." + j
]) {
1494 explored
[i
+ "." + j
] = true;
1495 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1497 if (s
.range
<= stepCounter
++)
1500 j
= this.computeY(j
+ step
[1]);
1502 if (!this.onBoard(i
, j
))
1504 const pieceIJ
= this.getPieceType(i
, j
);
1506 type
!= "moveonly" &&
1507 !explored
[i
+ "." + j
] &&
1509 !this.options
["zen"] ||
1513 this.canTake([x
, y
], [i
, j
]) ||
1515 (this.options
["recycle"] || this.options
["teleport"]) &&
1520 explored
[i
+ "." + j
] = true;
1521 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1527 const specialAttack
= !!stepSpec
.attack
;
1529 findAddMoves("attack", stepSpec
.attack
);
1530 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1531 if (this.options
["zen"])
1532 Array
.prototype.push
.apply(moves
, this.findCapturesOn([x
, y
], true));
1536 findCapturesOn([x
, y
], zen
) {
1538 // Find reverse captures (opponent takes)
1539 const color
= this.getColor(x
, y
);
1540 const pieceType
= this.getPieceType(x
, y
);
1541 const oppCol
= C
.GetOppCol(color
);
1542 for (let i
=0; i
<this.size
.x
; i
++) {
1543 for (let j
=0; j
<this.size
.y
; j
++) {
1545 this.board
[i
][j
] != "" &&
1546 this.canTake([i
, j
], [x
, y
]) &&
1547 !this.isImmobilized([i
, j
])
1549 const piece
= this.getPieceType(i
, j
);
1550 if (zen
&& C
.CannibalKingCode
[piece
])
1551 continue; //king not captured in this way
1552 const stepSpec
= this.pieces(oppCol
, i
, j
)[piece
];
1553 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1554 for (let a
of attacks
) {
1555 for (let s
of a
.steps
) {
1556 // Quick check: if step isn't compatible, don't even try
1557 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1559 // Finally verify that nothing stand in-between
1560 let [ii
, jj
] = [i
+ s
[0], this.computeY(j
+ s
[1])];
1561 let stepCounter
= 1;
1562 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1564 jj
= this.computeY(jj
+ s
[1]);
1566 if (ii
== x
&& jj
== y
) {
1567 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1569 return moves
; //test for underCheck
1579 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1580 const rx
= (x2
- x1
) / step
[0],
1581 ry
= (y2
- y1
) / step
[1];
1583 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1584 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1588 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1589 // TODO: 1e-7 here is totally arbitrary
1590 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1592 distance
= Math
.round(distance
); //in case of (numerical...)
1593 if (range
< distance
)
1598 // Build a regular move from its initial and destination squares.
1599 // tr: transformation
1600 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1601 const initColor
= this.getColor(sx
, sy
);
1602 const initPiece
= this.getPiece(sx
, sy
);
1603 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1607 start: {x:sx
, y:sy
},
1611 !this.options
["rifle"] ||
1612 this.board
[ex
][ey
] == "" ||
1613 destColor
== initColor
//Recycle, Teleport
1619 c: !!tr
? tr
.c : initColor
,
1620 p: !!tr
? tr
.p : initPiece
1632 if (this.board
[ex
][ey
] != "") {
1637 c: this.getColor(ex
, ey
),
1638 p: this.getPiece(ex
, ey
)
1641 if (this.options
["rifle"])
1642 // Rifle captures are tricky in combination with Atomic etc,
1643 // so it's useful to mark the move :
1645 if (this.options
["cannibal"] && destColor
!= initColor
) {
1646 const lastIdx
= mv
.vanish
.length
- 1;
1647 let trPiece
= mv
.vanish
[lastIdx
].p
;
1648 if (this.isKing(this.getPiece(sx
, sy
)))
1649 trPiece
= C
.CannibalKingCode
[trPiece
];
1650 if (mv
.appear
.length
>= 1)
1651 mv
.appear
[0].p
= trPiece
;
1652 else if (this.options
["rifle"]) {
1675 // En-passant square, if any
1676 getEpSquare(moveOrSquare
) {
1677 if (typeof moveOrSquare
=== "string") {
1678 const square
= moveOrSquare
;
1681 return C
.SquareToCoords(square
);
1683 // Argument is a move:
1684 const move = moveOrSquare
;
1685 const s
= move.start
,
1689 Math
.abs(s
.x
- e
.x
) == 2 &&
1690 // Next conditions for variants like Atomic or Rifle, Recycle...
1691 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1692 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1699 return undefined; //default
1702 // Special case of en-passant captures: treated separately
1703 getEnpassantCaptures([x
, y
]) {
1704 const color
= this.getColor(x
, y
);
1705 const shiftX
= (color
== 'w' ? -1 : 1);
1706 const oppCol
= C
.GetOppCol(color
);
1707 let enpassantMove
= null;
1710 this.epSquare
.x
== x
+ shiftX
&&
1711 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1712 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1714 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1715 this.board
[epx
][epy
] = oppCol
+ "p";
1716 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1717 this.board
[epx
][epy
] = "";
1718 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1719 enpassantMove
.vanish
[lastIdx
].x
= x
;
1721 return !!enpassantMove
? [enpassantMove
] : [];
1724 // "castleInCheck" arg to let some variants castle under check
1725 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1726 const c
= this.getColor(x
, y
);
1729 const oppCol
= C
.GetOppCol(c
);
1733 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1734 const castlingKing
= this.getPiece(x
, y
);
1735 castlingCheck: for (
1738 castleSide
++ //large, then small
1740 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1742 // If this code is reached, rook and king are on initial position
1744 // NOTE: in some variants this is not a rook
1745 const rookPos
= this.castleFlags
[c
][castleSide
];
1746 const castlingPiece
= this.getPiece(x
, rookPos
);
1748 this.board
[x
][rookPos
] == "" ||
1749 this.getColor(x
, rookPos
) != c
||
1750 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1752 // Rook is not here, or changed color (see Benedict)
1755 // Nothing on the path of the king ? (and no checks)
1756 const finDist
= finalSquares
[castleSide
][0] - y
;
1757 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1761 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1763 this.board
[x
][i
] != "" &&
1764 // NOTE: next check is enough, because of chessboard constraints
1765 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1768 continue castlingCheck
;
1771 } while (i
!= finalSquares
[castleSide
][0]);
1772 // Nothing on the path to the rook?
1773 step
= (castleSide
== 0 ? -1 : 1);
1774 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1775 if (this.board
[x
][i
] != "")
1776 continue castlingCheck
;
1779 // Nothing on final squares, except maybe king and castling rook?
1780 for (i
= 0; i
< 2; i
++) {
1782 finalSquares
[castleSide
][i
] != rookPos
&&
1783 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1785 finalSquares
[castleSide
][i
] != y
||
1786 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1789 continue castlingCheck
;
1793 // If this code is reached, castle is valid
1799 y: finalSquares
[castleSide
][0],
1805 y: finalSquares
[castleSide
][1],
1811 // King might be initially disguised (Titan...)
1812 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1813 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1816 Math
.abs(y
- rookPos
) <= 2
1817 ? {x: x
, y: rookPos
}
1818 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1826 ////////////////////
1829 // Is (king at) given position under check by "color" ?
1830 underCheck([x
, y
], color
) {
1831 if (this.options
["taking"] || this.options
["dark"])
1833 return (this.findCapturesOn([x
, y
]).length
>= 1);
1836 // Stop at first king found (TODO: multi-kings)
1837 searchKingPos(color
) {
1838 for (let i
=0; i
< this.size
.x
; i
++) {
1839 for (let j
=0; j
< this.size
.y
; j
++) {
1840 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1844 return [-1, -1]; //king not found
1847 filterValid(moves
) {
1848 if (moves
.length
== 0)
1850 const color
= this.turn
;
1851 const oppCol
= C
.GetOppCol(color
);
1852 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1853 // Forbid moves either giving check or exploding opponent's king:
1854 const oppKingPos
= this.searchKingPos(oppCol
);
1855 moves
= moves
.filter(m
=> {
1857 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1858 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1861 this.playOnBoard(m
);
1862 const res
= !this.underCheck(oppKingPos
, color
);
1863 this.undoOnBoard(m
);
1867 if (this.options
["taking"] || this.options
["dark"])
1869 const kingPos
= this.searchKingPos(color
);
1870 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1871 return moves
.filter(m
=> {
1872 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1873 if (!filtered
[key
]) {
1874 this.playOnBoard(m
);
1875 let square
= kingPos
,
1876 res
= true; //a priori valid
1877 if (m
.vanish
.some(v
=> {
1878 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1880 // Search king in appear array:
1882 m
.appear
.findIndex(a
=> {
1883 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1885 if (newKingIdx
>= 0)
1886 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1890 res
&&= !this.underCheck(square
, oppCol
);
1891 this.undoOnBoard(m
);
1892 filtered
[key
] = res
;
1895 return filtered
[key
];
1902 // Aggregate flags into one object
1904 return this.castleFlags
;
1907 // Reverse operation
1908 disaggregateFlags(flags
) {
1909 this.castleFlags
= flags
;
1912 // Apply a move on board
1914 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1915 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1917 // Un-apply the played move
1919 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1920 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1923 updateCastleFlags(move) {
1924 // Update castling flags if start or arrive from/at rook/king locations
1925 move.appear
.concat(move.vanish
).forEach(psq
=> {
1927 this.board
[psq
.x
][psq
.y
] != "" &&
1928 this.getPieceType(psq
.x
, psq
.y
) == "k"
1930 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1932 // NOTE: not "else if" because king can capture enemy rook...
1936 else if (psq
.x
== this.size
.x
- 1)
1939 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1941 this.castleFlags
[c
][fidx
] = this.size
.y
;
1948 typeof move.start
.x
== "number" &&
1949 (!this.options
["teleport"] || this.subTurnTeleport
== 1)
1951 // OK, not a drop move
1954 // If flags already off, no need to re-check:
1955 Object
.keys(this.castleFlags
).some(c
=> {
1956 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1958 this.updateCastleFlags(move);
1960 const initSquare
= C
.CoordsToSquare(move.start
);
1962 this.options
["crazyhouse"] &&
1963 (!this.options
["rifle"] || !move.capture
)
1965 const destSquare
= C
.CoordsToSquare(move.end
);
1966 if (this.ispawn
[initSquare
]) {
1967 delete this.ispawn
[initSquare
];
1968 this.ispawn
[destSquare
] = true;
1971 move.vanish
[0].p
== "p" &&
1972 move.appear
[0].p
!= "p"
1974 this.ispawn
[destSquare
] = true;
1977 this.ispawn
[destSquare
] &&
1978 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
1980 move.vanish
[1].p
= "p";
1981 delete this.ispawn
[destSquare
];
1985 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1986 if (this.hasReserve
&& !move.pawnfall
) {
1987 const color
= this.turn
;
1988 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1989 // Something appears = dropped on board (some exceptions, Chakart...)
1990 const piece
= move.appear
[i
].p
;
1991 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1993 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1994 // Something vanish: add to reserve except if recycle & opponent
1995 const piece
= move.vanish
[i
].p
;
1996 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1997 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2004 if (this.hasEnpassant
)
2005 this.epSquare
= this.getEpSquare(move);
2006 this.playOnBoard(move);
2007 this.postPlay(move);
2011 const color
= this.turn
;
2012 const oppCol
= C
.GetOppCol(color
);
2013 if (this.options
["dark"])
2014 this.updateEnlightened();
2015 if (this.options
["teleport"]) {
2017 this.subTurnTeleport
== 1 &&
2018 move.vanish
.length
> move.appear
.length
&&
2019 move.vanish
[move.vanish
.length
- 1].c
== color
2021 const v
= move.vanish
[move.vanish
.length
- 1];
2022 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2023 this.subTurnTeleport
= 2;
2026 this.subTurnTeleport
= 1;
2027 this.captured
= null;
2029 if (this.options
["balance"]) {
2030 if (![1, 3].includes(this.movesCount
))
2036 this.options
["doublemove"] &&
2037 this.movesCount
>= 1 &&
2040 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2042 const oppKingPos
= this.searchKingPos(oppCol
);
2044 oppKingPos
[0] >= 0 &&
2046 this.options
["taking"] ||
2047 !this.underCheck(oppKingPos
, color
)
2060 // "Stop at the first move found"
2061 atLeastOneMove(color
) {
2062 color
= color
|| this.turn
;
2063 for (let i
= 0; i
< this.size
.x
; i
++) {
2064 for (let j
= 0; j
< this.size
.y
; j
++) {
2065 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2066 // NOTE: in fact searching for all potential moves from i,j.
2067 // I don't believe this is an issue, for now at least.
2068 const moves
= this.getPotentialMovesFrom([i
, j
]);
2069 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2074 if (this.hasReserve
&& this.reserve
[color
]) {
2075 for (let p
of Object
.keys(this.reserve
[color
])) {
2076 const moves
= this.getDropMovesFrom([color
, p
]);
2077 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2084 // What is the score ? (Interesting if game is over)
2085 getCurrentScore(move) {
2086 const color
= this.turn
;
2087 const oppCol
= C
.GetOppCol(color
);
2088 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2089 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2091 if (kingPos
[0][0] < 0)
2092 return (color
== "w" ? "0-1" : "1-0");
2093 if (kingPos
[1][0] < 0)
2094 return (color
== "w" ? "1-0" : "0-1");
2095 if (this.atLeastOneMove())
2097 // No valid move: stalemate or checkmate?
2098 if (!this.underCheck(kingPos
[0], color
))
2101 return (color
== "w" ? "0-1" : "1-0");
2104 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2105 playVisual(move, r
) {
2106 move.vanish
.forEach(v
=> {
2107 // TODO: next "if" shouldn't be required
2108 if (this.g_pieces
[v
.x
][v
.y
])
2109 this.g_pieces
[v
.x
][v
.y
].remove();
2110 this.g_pieces
[v
.x
][v
.y
] = null;
2113 document
.getElementById(this.containerId
).querySelector(".chessboard");
2115 r
= chessboard
.getBoundingClientRect();
2116 const pieceWidth
= this.getPieceWidth(r
.width
);
2117 move.appear
.forEach(a
=> {
2118 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2119 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2120 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2121 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2122 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2123 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2124 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2125 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2126 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2127 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2129 if (this.options
["dark"])
2130 this.graphUpdateEnlightened();
2133 playPlusVisual(move, r
) {
2135 this.playVisual(move, r
);
2136 this.afterPlay(move); //user method
2139 // Assumes reserve on top (usage case otherwise? TODO?)
2140 getReserveShift(c
, p
, r
) {
2143 for (let pi
of Object
.keys(this.reserve
[c
])) {
2144 if (this.reserve
[c
][pi
] == 0)
2150 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2151 return [-ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2154 animate(move, callback
) {
2155 if (this.noAnimate
) {
2159 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2160 const dropMove
= (typeof i1
== "string");
2161 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2162 let startPiece
= startArray
[i1
][j1
];
2163 // TODO: next "if" shouldn't be required
2169 document
.getElementById(this.containerId
).querySelector(".chessboard");
2170 const clonePiece
= (
2172 this.options
["rifle"] ||
2173 (this.options
["teleport"] && this.subTurnTeleport
== 2)
2176 startPiece
= startPiece
.cloneNode();
2177 if (this.options
["rifle"])
2178 startArray
[i1
][j1
].style
.opacity
= "0";
2179 if (this.options
["teleport"] && this.subTurnTeleport
== 2) {
2180 const pieces
= this.pieces();
2181 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2182 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2183 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2186 chessboard
.appendChild(startPiece
);
2188 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2192 i1
== this.playerColor
? this.size
.x : 0,
2193 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2197 startCoords
= [i1
, j1
];
2198 const r
= chessboard
.getBoundingClientRect();
2199 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2202 rs
= this.getReserveShift(i1
, j1
, r
);
2204 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2205 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2206 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2207 const duration
= 0.2 + multFact
* 0.3;
2208 const initTransform
= startPiece
.style
.transform
;
2209 startPiece
.style
.transform
=
2210 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2211 startPiece
.style
.transitionDuration
= duration
+ "s";
2215 if (this.options
["rifle"])
2216 startArray
[i1
][j1
].style
.opacity
= "1";
2217 startPiece
.remove();
2220 startPiece
.style
.transform
= initTransform
;
2221 startPiece
.style
.transitionDuration
= "0s";
2229 playReceivedMove(moves
, callback
) {
2230 const launchAnimation
= () => {
2231 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2232 const animateRec
= i
=> {
2233 this.animate(moves
[i
], () => {
2234 this.play(moves
[i
]);
2235 this.playVisual(moves
[i
], r
);
2236 if (i
< moves
.length
- 1)
2237 setTimeout(() => animateRec(i
+1), 300);
2244 // Delay if user wasn't focused:
2245 const checkDisplayThenAnimate
= (delay
) => {
2246 if (container
.style
.display
== "none") {
2247 alert("New move! Let's go back to game...");
2248 document
.getElementById("gameInfos").style
.display
= "none";
2249 container
.style
.display
= "block";
2250 setTimeout(launchAnimation
, 700);
2253 setTimeout(launchAnimation
, delay
|| 0);
2255 let container
= document
.getElementById(this.containerId
);
2256 if (document
.hidden
) {
2257 document
.onvisibilitychange
= () => {
2258 document
.onvisibilitychange
= undefined;
2259 checkDisplayThenAnimate(700);
2263 checkDisplayThenAnimate();