79e8650bc5c57ed9e470acaa5c97fd38b6a6639f
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() {
22 // NOTE: some options are required for FEN generation, some aren't.
25 variable: "randomness",
28 {label: "Deterministic", value: 0},
29 {label: "Symmetric random", value: 1},
30 {label: "Asymmetric random", value: 2}
35 label: "Capture king",
40 label: "Falling pawn",
45 // Game modifiers (using "elementary variants"). Default: false
48 "balance", //takes precedence over doublemove & progressive
52 "cylinder", //ok with all
56 "progressive", //(natural) priority over doublemove
65 // Pawns specifications
68 directions: {w: -1, b: 1},
69 initShift: {w: 1, b: 1},
73 captureBackward: false,
75 promotions: ['r', 'n', 'b', 'q']
79 // Some variants don't have flags:
88 // En-passant captures allowed?
95 !!this.options
["crazyhouse"] ||
96 (!!this.options
["recycle"] && !this.options
["teleport"])
101 return !!this.options
["dark"];
104 // Some variants use click infos:
106 if (typeof x
!= "number")
107 return null; //click on reserves
109 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
110 this.board
[x
][y
] == ""
113 start: {x: this.captured
.x
, y: this.captured
.y
},
118 c: this.captured
.c
, //this.turn,
131 // 3 --> d (column number to letter)
132 static CoordToColumn(colnum
) {
133 return String
.fromCharCode(97 + colnum
);
136 // d --> 3 (column letter to number)
137 static ColumnToCoord(columnStr
) {
138 return columnStr
.charCodeAt(0) - 97;
141 // 7 (numeric) --> 1 (str) [from black viewpoint].
142 static CoordToRow(rownum
) {
146 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
147 static RowToCoord(rownumStr
) {
148 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
149 return parseInt(rownumStr
, 30);
152 // a2 --> {x:2,y:0} (this is in fact a6)
153 static SquareToCoords(sq
) {
155 x: C
.RowToCoord(sq
[1]),
156 // NOTE: column is always one char => max 26 columns
157 y: C
.ColumnToCoord(sq
[0])
161 // {x:0,y:4} --> e0 (should be e8)
162 static CoordsToSquare(coords
) {
163 return C
.CoordToColumn(coords
.y
) + C
.CoordToRow(coords
.x
);
167 if (typeof x
== "number")
168 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
170 return `${this.containerId}|rsq-${x}-${y}`;
173 idToCoords(targetId
) {
175 return null; //outside page, maybe...
176 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
178 idParts
.length
< 2 ||
179 idParts
[0] != this.containerId
||
180 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
184 const squares
= idParts
[1].split('-');
185 if (squares
[0] == "sq")
186 return [ parseInt(squares
[1], 30), parseInt(squares
[2], 30) ];
187 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
188 return [squares
[1], squares
[2]];
194 // Turn "wb" into "B" (for FEN)
196 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
199 // Turn "p" into "bp" (for board)
201 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
204 // Setup the initial random-or-not (asymmetric-or-not) position
205 genRandInitFen(seed
) {
206 Random
.setSeed(seed
);
208 let fen
, flags
= "0707";
209 if (!this.options
.randomness
)
211 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
215 let pieces
= { w: new Array(8), b: new Array(8) };
217 // Shuffle pieces on first (and last rank if randomness == 2)
218 for (let c
of ["w", "b"]) {
219 if (c
== 'b' && this.options
.randomness
== 1) {
220 pieces
['b'] = pieces
['w'];
225 let positions
= ArrayFun
.range(8);
227 // Get random squares for bishops
228 let randIndex
= 2 * Random
.randInt(4);
229 const bishop1Pos
= positions
[randIndex
];
230 // The second bishop must be on a square of different color
231 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
232 const bishop2Pos
= positions
[randIndex_tmp
];
233 // Remove chosen squares
234 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
235 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
237 // Get random squares for knights
238 randIndex
= Random
.randInt(6);
239 const knight1Pos
= positions
[randIndex
];
240 positions
.splice(randIndex
, 1);
241 randIndex
= Random
.randInt(5);
242 const knight2Pos
= positions
[randIndex
];
243 positions
.splice(randIndex
, 1);
245 // Get random square for queen
246 randIndex
= Random
.randInt(4);
247 const queenPos
= positions
[randIndex
];
248 positions
.splice(randIndex
, 1);
250 // Rooks and king positions are now fixed,
251 // because of the ordering rook-king-rook
252 const rook1Pos
= positions
[0];
253 const kingPos
= positions
[1];
254 const rook2Pos
= positions
[2];
256 // Finally put the shuffled pieces in the board array
257 pieces
[c
][rook1Pos
] = "r";
258 pieces
[c
][knight1Pos
] = "n";
259 pieces
[c
][bishop1Pos
] = "b";
260 pieces
[c
][queenPos
] = "q";
261 pieces
[c
][kingPos
] = "k";
262 pieces
[c
][bishop2Pos
] = "b";
263 pieces
[c
][knight2Pos
] = "n";
264 pieces
[c
][rook2Pos
] = "r";
265 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
268 pieces
["b"].join("") +
269 "/pppppppp/8/8/8/8/PPPPPPPP/" +
270 pieces
["w"].join("").toUpperCase() +
274 // Add turn + flags + enpassant (+ reserve)
277 parts
.push(`"flags":"${flags}"`);
278 if (this.hasEnpassant
)
279 parts
.push('"enpassant":"-"');
281 parts
.push('"reserve":"000000000000"');
282 if (this.options
["crazyhouse"])
283 parts
.push('"ispawn":"-"');
284 if (parts
.length
>= 1)
285 fen
+= " {" + parts
.join(",") + "}";
289 // "Parse" FEN: just return untransformed string data
291 const fenParts
= fen
.split(" ");
293 position: fenParts
[0],
295 movesCount: fenParts
[2]
297 if (fenParts
.length
> 3)
298 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
302 // Return current fen (game state)
305 this.getBaseFen() + " " +
306 this.getTurnFen() + " " +
311 parts
.push(`"flags":"${this.getFlagsFen()}"`);
312 if (this.hasEnpassant
)
313 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
315 parts
.push(`"reserve":"${this.getReserveFen()}"`);
316 if (this.options
["crazyhouse"])
317 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
318 if (parts
.length
>= 1)
319 fen
+= " {" + parts
.join(",") + "}";
323 // Position part of the FEN string
325 const format
= (count
) => {
326 // if more than 9 consecutive free spaces, break the integer,
327 // otherwise FEN parsing will fail.
330 // Most boards of size < 18:
332 return "9" + (count
- 9);
334 return "99" + (count
- 18);
337 for (let i
= 0; i
< this.size
.y
; i
++) {
339 for (let j
= 0; j
< this.size
.x
; j
++) {
340 if (this.board
[i
][j
] == "")
343 if (emptyCount
> 0) {
344 // Add empty squares in-between
345 position
+= format(emptyCount
);
348 position
+= this.board2fen(this.board
[i
][j
]);
353 position
+= format(emptyCount
);
354 if (i
< this.size
.y
- 1)
355 position
+= "/"; //separate rows
364 // Flags part of the FEN string
366 return ["w", "b"].map(c
=> {
367 return this.castleFlags
[c
].map(x
=> x
.toString(30)).join("");
371 // Enpassant part of the FEN string
374 return "-"; //no en-passant
375 return C
.CoordsToSquare(this.epSquare
);
380 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
385 const coords
= Object
.keys(this.ispawn
);
386 if (coords
.length
== 0)
388 return coords
.map(C
.CoordsToSquare
).join(",");
391 // Set flags from fen (castle: white a,h then black a,h)
394 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 30)),
395 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 30))
402 // Fen string fully describes the game state
404 this.options
= o
.options
;
405 this.playerColor
= o
.color
;
406 this.afterPlay
= o
.afterPlay
;
410 o
.fen
= this.genRandInitFen(o
.seed
);
411 const fenParsed
= this.parseFen(o
.fen
);
412 this.board
= this.getBoard(fenParsed
.position
);
413 this.turn
= fenParsed
.turn
;
414 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
415 this.setOtherVariables(fenParsed
);
417 // Graphical (can use variables defined above)
418 this.containerId
= o
.element
;
419 this.graphicalInit();
422 // Turn position fen into double array ["wb","wp","bk",...]
424 const rows
= position
.split("/");
425 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
426 for (let i
= 0; i
< rows
.length
; i
++) {
428 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
429 const character
= rows
[i
][indexInRow
];
430 const num
= parseInt(character
, 10);
431 // If num is a number, just shift j:
434 // Else: something at position i,j
436 board
[i
][j
++] = this.fen2board(character
);
442 // Some additional variables from FEN (variant dependant)
443 setOtherVariables(fenParsed
) {
444 // Set flags and enpassant:
446 this.setFlags(fenParsed
.flags
);
447 if (this.hasEnpassant
)
448 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
450 this.initReserves(fenParsed
.reserve
);
451 if (this.options
["crazyhouse"])
452 this.initIspawn(fenParsed
.ispawn
);
453 this.subTurn
= 1; //may be unused
454 if (this.options
["teleport"]) {
455 this.subTurnTeleport
= 1;
456 this.captured
= null;
458 if (this.options
["dark"]) {
459 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
);
460 // Setup enlightened: squares reachable by player side
461 this.updateEnlightened(false);
465 updateEnlightened(withGraphics
) {
466 let newEnlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
467 const pawnShift
= { w: -1, b: 1 };
468 // Add pieces positions + all squares reachable by moves (includes Zen):
469 // (watch out special pawns case)
470 for (let x
=0; x
<this.size
.x
; x
++) {
471 for (let y
=0; y
<this.size
.y
; y
++) {
472 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
474 newEnlightened
[x
][y
] = true;
475 if (this.getPiece(x
, y
) == "p") {
476 // Attacking squares wouldn't be highlighted if no captures:
477 this.pieces(this.playerColor
)["p"].attack
.forEach(step
=> {
478 const [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
479 if (this.onBoard(i
, j
) && this.board
[i
][j
] == "")
480 newEnlightened
[i
][j
] = true;
483 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
484 newEnlightened
[m
.end
.x
][m
.end
.y
] = true;
490 this.enlightEnpassant(newEnlightened
);
492 this.graphUpdateEnlightened(newEnlightened
);
493 this.enlightened
= newEnlightened
;
496 // Include en-passant capturing square if any:
497 enlightEnpassant(newEnlightened
) {
498 const steps
= this.pieces(this.playerColor
)["p"].attack
;
499 for (let step
of steps
) {
500 const x
= this.epSquare
.x
- step
[0],
501 y
= this.computeY(this.epSquare
.y
- step
[1]);
503 this.onBoard(x
, y
) &&
504 this.getColor(x
, y
) == this.playerColor
&&
505 this.getPieceType(x
, y
) == "p"
507 newEnlightened
[x
][this.epSquare
.y
] = true;
513 // Apply diff this.enlightened --> newEnlightened on board
514 graphUpdateEnlightened(newEnlightened
) {
516 document
.getElementById(this.containerId
).querySelector(".chessboard");
517 const r
= chessboard
.getBoundingClientRect();
518 const pieceWidth
= this.getPieceWidth(r
.width
);
519 for (let x
=0; x
<this.size
.x
; x
++) {
520 for (let y
=0; y
<this.size
.y
; y
++) {
521 if (this.enlightened
[x
][y
] && !newEnlightened
[x
][y
]) {
522 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
523 elt
.classList
.add("in-shadow");
524 if (this.g_pieces
[x
][y
]) {
525 this.g_pieces
[x
][y
].remove();
526 this.g_pieces
[x
][y
] = null;
529 else if (!this.enlightened
[x
][y
] && newEnlightened
[x
][y
]) {
530 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
531 elt
.classList
.remove("in-shadow");
532 if (this.board
[x
][y
] != "") {
533 const color
= this.getColor(x
, y
);
534 const piece
= this.getPiece(x
, y
);
535 this.g_pieces
[x
][y
] = document
.createElement("piece");
537 this.pieces()[piece
]["class"],
538 color
== "w" ? "white" : "black"
540 newClasses
.forEach(cl
=> this.g_pieces
[x
][y
].classList
.add(cl
));
541 this.g_pieces
[x
][y
].style
.width
= pieceWidth
+ "px";
542 this.g_pieces
[x
][y
].style
.height
= pieceWidth
+ "px";
543 const [ip
, jp
] = this.getPixelPosition(x
, y
, r
);
544 this.g_pieces
[x
][y
].style
.transform
=
545 `translate(${ip}px,${jp}px)`;
546 chessboard
.appendChild(this.g_pieces
[x
][y
]);
553 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
554 initReserves(reserveStr
) {
555 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
556 this.reserve
= { w: {}, b: {} };
557 const pieceName
= Object
.keys(this.pieces());
558 for (let i
of ArrayFun
.range(12)) {
560 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
562 this.reserve
['b'][pieceName
[i
-6]] = counts
[i
];
566 initIspawn(ispawnStr
) {
567 if (ispawnStr
!= "-") {
568 this.ispawn
= ispawnStr
.split(",").map(C
.SquareToCoords
)
569 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
575 getNbReservePieces(color
) {
577 Object
.values(this.reserve
[color
]).reduce(
578 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
585 getPieceWidth(rwidth
) {
586 return (rwidth
/ this.size
.y
);
589 getSquareWidth(rwidth
) {
590 return this.getPieceWidth(rwidth
);
593 getReserveSquareSize(rwidth
, nbR
) {
594 const sqSize
= this.getSquareWidth(rwidth
);
595 return Math
.min(sqSize
, rwidth
/ nbR
);
598 getReserveNumId(color
, piece
) {
599 return `${this.containerId}|rnum-${color}${piece}`;
603 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
604 window
.onresize
= () => this.re_drawBoardElements();
605 this.re_drawBoardElements();
606 this.initMouseEvents();
608 document
.getElementById(this.containerId
).querySelector(".chessboard");
609 new ResizeObserver(this.rescale
).observe(chessboard
);
612 re_drawBoardElements() {
613 const board
= this.getSvgChessboard();
614 const oppCol
= C
.GetOppCol(this.playerColor
);
616 document
.getElementById(this.containerId
).querySelector(".chessboard");
617 chessboard
.innerHTML
= "";
618 chessboard
.insertAdjacentHTML('beforeend', board
);
619 const aspectRatio
= this.size
.y
/ this.size
.x
;
620 // Compare window ratio width / height to aspectRatio:
621 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
622 let cbWidth
, cbHeight
;
623 if (windowRatio
<= aspectRatio
) {
624 // Limiting dimension is width:
625 cbWidth
= Math
.min(window
.innerWidth
, 767);
626 cbHeight
= cbWidth
/ aspectRatio
;
629 // Limiting dimension is height:
630 cbHeight
= Math
.min(window
.innerHeight
, 767);
631 cbWidth
= cbHeight
* aspectRatio
;
634 const sqSize
= cbWidth
/ this.size
.y
;
635 // NOTE: allocate space for reserves (up/down) even if they are empty
636 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
637 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
638 cbWidth
= cbHeight
* aspectRatio
;
641 chessboard
.style
.width
= cbWidth
+ "px";
642 chessboard
.style
.height
= cbHeight
+ "px";
643 // Center chessboard:
644 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
645 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
646 chessboard
.style
.left
= spaceLeft
+ "px";
647 chessboard
.style
.top
= spaceTop
+ "px";
648 // Give sizes instead of recomputing them,
649 // because chessboard might not be drawn yet.
658 // Get SVG board (background, no pieces)
660 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
661 const flipped
= (this.playerColor
== 'b');
666 class="chessboard_SVG">
668 for (let i
=0; i
< sizeX
; i
++) {
669 for (let j
=0; j
< sizeY
; j
++) {
670 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
671 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
672 let classes
= this.getSquareColorClass(ii
, jj
);
673 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
674 classes
+= " in-shadow";
675 // NOTE: x / y reversed because coordinates system is reversed.
678 id="${this.coordsToId([ii, jj])}"
685 board
+= "</g></svg>";
689 // Generally light square bottom-right
690 getSquareColorClass(i
, j
) {
691 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
696 // Refreshing: delete old pieces first
697 for (let i
=0; i
<this.size
.x
; i
++) {
698 for (let j
=0; j
<this.size
.y
; j
++) {
699 if (this.g_pieces
[i
][j
]) {
700 this.g_pieces
[i
][j
].remove();
701 this.g_pieces
[i
][j
] = null;
707 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
709 document
.getElementById(this.containerId
).querySelector(".chessboard");
711 r
= chessboard
.getBoundingClientRect();
712 const pieceWidth
= this.getPieceWidth(r
.width
);
713 for (let i
=0; i
< this.size
.x
; i
++) {
714 for (let j
=0; j
< this.size
.y
; j
++) {
716 this.board
[i
][j
] != "" &&
717 (!this.options
["dark"] || this.enlightened
[i
][j
])
719 const color
= this.getColor(i
, j
);
720 const piece
= this.getPiece(i
, j
);
721 this.g_pieces
[i
][j
] = document
.createElement("piece");
722 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
723 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
724 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
725 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
726 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
727 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
728 chessboard
.appendChild(this.g_pieces
[i
][j
]);
733 this.re_drawReserve(['w', 'b'], r
);
736 // NOTE: assume !!this.reserve
737 re_drawReserve(colors
, r
) {
739 // Remove (old) reserve pieces
740 for (let c
of colors
) {
741 if (!this.reserve
[c
])
743 Object
.keys(this.reserve
[c
]).forEach(p
=> {
744 if (this.r_pieces
[c
][p
]) {
745 this.r_pieces
[c
][p
].remove();
746 delete this.r_pieces
[c
][p
];
747 const numId
= this.getReserveNumId(c
, p
);
748 document
.getElementById(numId
).remove();
751 let reservesDiv
= document
.getElementById("reserves_" + c
);
753 reservesDiv
.remove();
757 this.r_pieces
= { 'w': {}, 'b': {} };
759 document
.getElementById(this.containerId
).querySelector(".chessboard");
761 r
= chessboard
.getBoundingClientRect();
762 for (let c
of colors
) {
763 if (!this.reserve
[c
])
765 const nbR
= this.getNbReservePieces(c
);
768 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
770 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
771 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
772 let rcontainer
= document
.createElement("div");
773 rcontainer
.id
= "reserves_" + c
;
774 rcontainer
.classList
.add("reserves");
775 rcontainer
.style
.left
= i0
+ "px";
776 rcontainer
.style
.top
= j0
+ "px";
777 // NOTE: +1 fix display bug on Firefox at least
778 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
779 rcontainer
.style
.height
= sqResSize
+ "px";
780 chessboard
.appendChild(rcontainer
);
781 for (let p
of Object
.keys(this.reserve
[c
])) {
782 if (this.reserve
[c
][p
] == 0)
784 let r_cell
= document
.createElement("div");
785 r_cell
.id
= this.coordsToId([c
, p
]);
786 r_cell
.classList
.add("reserve-cell");
787 r_cell
.style
.width
= sqResSize
+ "px";
788 r_cell
.style
.height
= sqResSize
+ "px";
789 rcontainer
.appendChild(r_cell
);
790 let piece
= document
.createElement("piece");
791 const pieceSpec
= this.pieces(c
)[p
];
792 piece
.classList
.add(pieceSpec
["class"]);
793 piece
.classList
.add(c
== 'w' ? "white" : "black");
794 piece
.style
.width
= "100%";
795 piece
.style
.height
= "100%";
796 this.r_pieces
[c
][p
] = piece
;
797 r_cell
.appendChild(piece
);
798 let number
= document
.createElement("div");
799 number
.textContent
= this.reserve
[c
][p
];
800 number
.classList
.add("reserve-num");
801 number
.id
= this.getReserveNumId(c
, p
);
802 const fontSize
= "1.3em";
803 number
.style
.fontSize
= fontSize
;
804 number
.style
.fontSize
= fontSize
;
805 r_cell
.appendChild(number
);
811 updateReserve(color
, piece
, count
) {
812 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
813 piece
= "k"; //capturing cannibal king: back to king form
814 const oldCount
= this.reserve
[color
][piece
];
815 this.reserve
[color
][piece
] = count
;
816 // Redrawing is much easier if count==0
817 if ([oldCount
, count
].includes(0))
818 this.re_drawReserve([color
]);
820 const numId
= this.getReserveNumId(color
, piece
);
821 document
.getElementById(numId
).textContent
= count
;
825 // After resize event: no need to destroy/recreate pieces
827 const container
= document
.getElementById(this.containerId
);
829 return; //useful at initial loading
830 let chessboard
= container
.querySelector(".chessboard");
831 const r
= chessboard
.getBoundingClientRect();
832 const newRatio
= r
.width
/ r
.height
;
833 const aspectRatio
= this.size
.y
/ this.size
.x
;
834 let newWidth
= r
.width
,
835 newHeight
= r
.height
;
836 if (newRatio
> aspectRatio
) {
837 newWidth
= r
.height
* aspectRatio
;
838 chessboard
.style
.width
= newWidth
+ "px";
840 else if (newRatio
< aspectRatio
) {
841 newHeight
= r
.width
/ aspectRatio
;
842 chessboard
.style
.height
= newHeight
+ "px";
844 const newX
= (window
.innerWidth
- newWidth
) / 2;
845 chessboard
.style
.left
= newX
+ "px";
846 const newY
= (window
.innerHeight
- newHeight
) / 2;
847 chessboard
.style
.top
= newY
+ "px";
848 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
849 const pieceWidth
= this.getPieceWidth(newWidth
);
850 for (let i
=0; i
< this.size
.x
; i
++) {
851 for (let j
=0; j
< this.size
.y
; j
++) {
852 if (this.board
[i
][j
] != "") {
853 // NOTE: could also use CSS transform "scale"
854 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
855 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
856 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
857 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
862 this.rescaleReserve(newR
);
866 for (let c
of ['w','b']) {
867 if (!this.reserve
[c
])
869 const nbR
= this.getNbReservePieces(c
);
872 // Resize container first
873 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
874 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
875 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
876 let rcontainer
= document
.getElementById("reserves_" + c
);
877 rcontainer
.style
.left
= i0
+ "px";
878 rcontainer
.style
.top
= j0
+ "px";
879 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
880 rcontainer
.style
.height
= sqResSize
+ "px";
881 // And then reserve cells:
882 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
883 Object
.keys(this.reserve
[c
]).forEach(p
=> {
884 if (this.reserve
[c
][p
] == 0)
886 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
887 r_cell
.style
.width
= sqResSize
+ "px";
888 r_cell
.style
.height
= sqResSize
+ "px";
893 // Return the absolute pixel coordinates (on board) given current position.
894 // Our coordinate system differs from CSS one (x <--> y).
895 // We return here the CSS coordinates (more useful).
896 getPixelPosition(i
, j
, r
) {
897 const sqSize
= this.getSquareWidth(r
.width
);
899 return [0, 0]; //piece vanishes
900 const flipped
= (this.playerColor
== 'b');
901 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
902 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
908 document
.getElementById(this.containerId
).querySelector(".chessboard");
910 const getOffset
= e
=> {
913 return {x: e
.clientX
, y: e
.clientY
};
914 let touchLocation
= null;
915 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
916 // Touch screen, dragstart
917 touchLocation
= e
.targetTouches
[0];
918 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
919 // Touch screen, dragend
920 touchLocation
= e
.changedTouches
[0];
922 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
923 return [0, 0]; //shouldn't reach here =)
926 const centerOnCursor
= (piece
, e
) => {
927 const centerShift
= sqSize
/ 2;
928 const offset
= getOffset(e
);
929 piece
.style
.left
= (offset
.x
- r
.x
- centerShift
) + "px";
930 piece
.style
.top
= (offset
.y
- r
.y
- centerShift
) + "px";
935 startPiece
, curPiece
= null,
937 const mousedown
= (e
) => {
938 // Disable zoom on smartphones:
939 if (e
.touches
&& e
.touches
.length
> 1)
941 r
= chessboard
.getBoundingClientRect();
942 sqSize
= this.getSquareWidth(r
.width
);
943 const square
= this.idToCoords(e
.target
.id
);
945 const [i
, j
] = square
;
946 const move = this.doClick([i
, j
]);
948 this.playPlusVisual(move);
950 if (typeof i
!= "number")
951 startPiece
= this.r_pieces
[i
][j
];
952 else if (this.g_pieces
[i
][j
])
953 startPiece
= this.g_pieces
[i
][j
];
954 if (startPiece
&& this.canIplay(i
, j
)) {
956 start
= { x: i
, y: j
};
957 curPiece
= startPiece
.cloneNode();
958 curPiece
.style
.transform
= "none";
959 curPiece
.style
.zIndex
= 5;
960 curPiece
.style
.width
= sqSize
+ "px";
961 curPiece
.style
.height
= sqSize
+ "px";
962 centerOnCursor(curPiece
, e
);
963 chessboard
.appendChild(curPiece
);
964 startPiece
.style
.opacity
= "0.4";
965 chessboard
.style
.cursor
= "none";
971 const mousemove
= (e
) => {
974 centerOnCursor(curPiece
, e
);
976 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
977 // Attempt to prevent horizontal swipe...
981 const mouseup
= (e
) => {
982 const newR
= chessboard
.getBoundingClientRect();
983 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
989 const [x
, y
] = [start
.x
, start
.y
];
992 chessboard
.style
.cursor
= "pointer";
993 startPiece
.style
.opacity
= "1";
994 const offset
= getOffset(e
);
995 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
996 const sq
= this.idToCoords(landingElt
.id
);
999 // NOTE: clearly suboptimal, but much easier, and not a big deal.
1000 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
1001 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
1002 const moves
= this.filterValid(potentialMoves
);
1003 if (moves
.length
>= 2)
1004 this.showChoices(moves
, r
);
1005 else if (moves
.length
== 1)
1006 this.playPlusVisual(moves
[0], r
);
1011 if ('onmousedown' in window
) {
1012 document
.addEventListener("mousedown", mousedown
);
1013 document
.addEventListener("mousemove", mousemove
);
1014 document
.addEventListener("mouseup", mouseup
);
1016 if ('ontouchstart' in window
) {
1017 // https://stackoverflow.com/a/42509310/12660887
1018 document
.addEventListener("touchstart", mousedown
, {passive: false});
1019 document
.addEventListener("touchmove", mousemove
, {passive: false});
1020 document
.addEventListener("touchend", mouseup
, {passive: false});
1022 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1025 showChoices(moves
, r
) {
1026 let container
= document
.getElementById(this.containerId
);
1027 let chessboard
= container
.querySelector(".chessboard");
1028 let choices
= document
.createElement("div");
1029 choices
.id
= "choices";
1030 choices
.style
.width
= r
.width
+ "px";
1031 choices
.style
.height
= r
.height
+ "px";
1032 choices
.style
.left
= r
.x
+ "px";
1033 choices
.style
.top
= r
.y
+ "px";
1034 chessboard
.style
.opacity
= "0.5";
1035 container
.appendChild(choices
);
1036 const squareWidth
= this.getSquareWidth(r
.width
);
1037 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1038 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1039 const color
= moves
[0].appear
[0].c
;
1040 const callback
= (m
) => {
1041 chessboard
.style
.opacity
= "1";
1042 container
.removeChild(choices
);
1043 this.playPlusVisual(m
, r
);
1045 for (let i
=0; i
< moves
.length
; i
++) {
1046 let choice
= document
.createElement("div");
1047 choice
.classList
.add("choice");
1048 choice
.style
.width
= squareWidth
+ "px";
1049 choice
.style
.height
= squareWidth
+ "px";
1050 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1051 choice
.style
.top
= firstUpTop
+ "px";
1052 choice
.style
.backgroundColor
= "lightyellow";
1053 choice
.onclick
= () => callback(moves
[i
]);
1054 const piece
= document
.createElement("piece");
1055 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
1056 piece
.classList
.add(pieceSpec
["class"]);
1057 piece
.classList
.add(color
== 'w' ? "white" : "black");
1058 piece
.style
.width
= "100%";
1059 piece
.style
.height
= "100%";
1060 choice
.appendChild(piece
);
1061 choices
.appendChild(choice
);
1069 return { "x": 8, "y": 8 };
1072 // Color of thing on square (i,j). 'undefined' if square is empty
1074 return this.board
[i
][j
].charAt(0);
1077 // Assume square i,j isn't empty
1079 return this.board
[i
][j
].charAt(1);
1082 // Piece type on square (i,j)
1083 getPieceType(i
, j
) {
1084 const p
= this.board
[i
][j
].charAt(1);
1085 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1088 // Get opponent color
1089 static GetOppCol(color
) {
1090 return (color
== "w" ? "b" : "w");
1093 // Can thing on square1 take thing on square2
1094 canTake([x1
, y1
], [x2
, y2
]) {
1096 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
)) ||
1098 (this.options
["recycle"] || this.options
["teleport"]) &&
1099 this.getPieceType(x2
, y2
) != "k"
1104 // Is (x,y) on the chessboard?
1106 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1109 // Used in interface: 'side' arg == player color
1112 this.playerColor
== this.turn
&&
1114 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1115 (typeof x
== "string" && x
== this.turn
) //reserve
1120 ////////////////////////
1121 // PIECES SPECIFICATIONS
1124 const pawnShift
= (color
== "w" ? -1 : 1);
1128 steps: [[pawnShift
, 0]],
1130 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1135 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1141 [1, 2], [1, -2], [-1, 2], [-1, -2],
1142 [2, 1], [-2, 1], [2, -1], [-2, -1]
1149 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1155 [0, 1], [0, -1], [1, 0], [-1, 0],
1156 [1, 1], [1, -1], [-1, 1], [-1, -1]
1163 [0, 1], [0, -1], [1, 0], [-1, 0],
1164 [1, 1], [1, -1], [-1, 1], [-1, -1]
1169 's': { "class": "king-pawn" },
1170 'u': { "class": "king-rook" },
1171 'o': { "class": "king-knight" },
1172 'c': { "class": "king-bishop" },
1173 't': { "class": "king-queen" }
1177 ////////////////////
1180 // For Cylinder: get Y coordinate
1182 if (!this.options
["cylinder"])
1184 let res
= y
% this.size
.y
;
1190 // Stop at the first capture found
1191 atLeastOneCapture(color
) {
1192 color
= color
|| this.turn
;
1193 const oppCol
= C
.GetOppCol(color
);
1194 for (let i
= 0; i
< this.size
.x
; i
++) {
1195 for (let j
= 0; j
< this.size
.y
; j
++) {
1196 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1197 const specs
= this.pieces(color
)[this.getPieceType(i
, j
)];
1198 const steps
= specs
.attack
|| specs
.steps
;
1199 outerLoop: for (let step
of steps
) {
1200 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1201 let stepCounter
= 1;
1202 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1203 if (specs
.range
<= stepCounter
++)
1206 jj
= this.computeY(jj
+ step
[1]);
1209 this.onBoard(ii
, jj
) &&
1210 this.getColor(ii
, jj
) == oppCol
&&
1212 [this.getBasicMove([i
, j
], [ii
, jj
])]
1224 getDropMovesFrom([c
, p
]) {
1225 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1226 // (but not necessarily otherwise)
1227 if (this.reserve
[c
][p
] == 0)
1230 for (let i
=0; i
<this.size
.x
; i
++) {
1231 for (let j
=0; j
<this.size
.y
; j
++) {
1232 // TODO: rather simplify this "if" and add post-condition: more general
1234 this.board
[i
][j
] == "" &&
1235 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1238 (c
== 'w' && i
< this.size
.x
- 1) ||
1244 start: {x: c
, y: p
},
1246 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1256 // All possible moves from selected square
1257 getPotentialMovesFrom(sq
, color
) {
1258 if (typeof sq
[0] == "string")
1259 return this.getDropMovesFrom(sq
);
1260 if (this.options
["madrasi"] && this.isImmobilized(sq
))
1262 const piece
= this.getPieceType(sq
[0], sq
[1]);
1265 moves
= this.getPotentialPawnMoves(sq
);
1267 moves
= this.getPotentialMovesOf(piece
, sq
);
1271 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1273 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1275 return this.postProcessPotentialMoves(moves
);
1278 postProcessPotentialMoves(moves
) {
1279 if (moves
.length
== 0)
1281 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1282 const oppCol
= C
.GetOppCol(color
);
1284 if (this.options
["capture"] && this.atLeastOneCapture()) {
1285 // Filter out non-capturing moves (not using m.vanish because of
1286 // self captures of Recycle and Teleport).
1287 moves
= moves
.filter(m
=> {
1289 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1290 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1295 if (this.options
["atomic"]) {
1296 moves
.forEach(m
=> {
1298 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1299 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1312 for (let step
of steps
) {
1313 let x
= m
.end
.x
+ step
[0];
1314 let y
= this.computeY(m
.end
.y
+ step
[1]);
1316 this.onBoard(x
, y
) &&
1317 this.board
[x
][y
] != "" &&
1318 this.getPieceType(x
, y
) != "p"
1322 p: this.getPiece(x
, y
),
1323 c: this.getColor(x
, y
),
1330 if (!this.options
["rifle"])
1331 m
.appear
.pop(); //nothin appears
1337 this.options
["cannibal"] &&
1338 this.options
["rifle"] &&
1339 this.pawnSpecs
.promotions
1341 // In this case a rifle-capture from last rank may promote a pawn
1342 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1344 moves
.forEach(m
=> {
1346 m
.start
.x
== lastRank
&&
1347 m
.appear
.length
>= 1 &&
1348 m
.appear
[0].p
== "p" &&
1349 m
.appear
[0].x
== m
.start
.x
&&
1350 m
.appear
[0].y
== m
.start
.y
1352 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1353 m
.appear
[0].p
= this.pawnSpecs
.promotions
[0];
1354 for (let i
=1; i
<this.pawnSpecs
.promotions
.length
; i
++) {
1355 let newMv
= JSON
.parse(JSON
.stringify(m
));
1356 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1357 newMoves
.push(newMv
);
1361 Array
.prototype.push
.apply(moves
, newMoves
);
1367 static get CannibalKings() {
1377 static get CannibalKingCode() {
1391 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1396 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1397 isImmobilized([x
, y
]) {
1398 const color
= this.getColor(x
, y
);
1399 const oppCol
= C
.GetOppCol(color
);
1400 const piece
= this.getPieceType(x
, y
);
1401 const stepSpec
= this.pieces(color
)[piece
];
1402 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1403 outerLoop: for (let step
of steps
) {
1404 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1405 let stepCounter
= 1;
1406 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1407 if (range
<= stepCounter
++)
1410 j
= this.computeY(j
+ step
[1]);
1413 this.onBoard(i
, j
) &&
1414 this.getColor(i
, j
) == oppCol
&&
1415 this.getPieceType(i
, j
) == piece
1423 // Generic method to find possible moves of "sliding or jumping" pieces
1424 getPotentialMovesOf(piece
, [x
, y
]) {
1425 const color
= this.getColor(x
, y
);
1426 const stepSpec
= this.pieces(color
)[piece
];
1427 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1429 let explored
= {}; //for Cylinder mode
1430 outerLoop: for (let step
of steps
) {
1431 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1432 let stepCounter
= 1;
1434 this.onBoard(i
, j
) &&
1435 this.board
[i
][j
] == "" &&
1436 !explored
[i
+ "." + j
]
1438 explored
[i
+ "." + j
] = true;
1439 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1440 if (range
<= stepCounter
++)
1443 j
= this.computeY(j
+ step
[1]);
1446 this.onBoard(i
, j
) &&
1448 !this.options
["zen"] ||
1449 this.getPieceType(i
, j
) == "k" ||
1450 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1452 this.canTake([x
, y
], [i
, j
]) &&
1453 !explored
[i
+ "." + j
]
1455 explored
[i
+ "." + j
] = true;
1456 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1459 if (this.options
["zen"])
1460 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1464 getZenCaptures(x
, y
) {
1466 // Find reverse captures (opponent takes)
1467 const color
= this.getColor(x
, y
);
1468 const pieceType
= this.getPieceType(x
, y
);
1469 const oppCol
= C
.GetOppCol(color
);
1470 const pieces
= this.pieces(oppCol
);
1471 Object
.keys(pieces
).forEach(p
=> {
1474 (this.options
["cannibal"] && C
.CannibalKings
[p
])
1476 return; //king isn't captured this way
1478 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1480 return; //cannibal king for example (TODO...)
1481 const range
= pieces
[p
].range
;
1482 steps
.forEach(s
=> {
1483 // From x,y: revert step
1484 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1485 let stepCounter
= 1;
1486 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1487 if (range
<= stepCounter
++)
1490 j
= this.computeY(j
- s
[1]);
1493 this.onBoard(i
, j
) &&
1494 this.getPieceType(i
, j
) == p
&&
1495 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1496 this.canTake([i
, j
], [x
, y
])
1498 if (pieceType
!= "p")
1499 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1501 this.addPawnMoves([x
, y
], [i
, j
], moves
);
1508 // Build a regular move from its initial and destination squares.
1509 // tr: transformation
1510 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1511 const initColor
= this.getColor(sx
, sy
);
1512 const initPiece
= this.getPiece(sx
, sy
);
1513 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1517 start: {x:sx
, y:sy
},
1521 !this.options
["rifle"] ||
1522 this.board
[ex
][ey
] == "" ||
1523 destColor
== initColor
//Recycle, Teleport
1529 c: !!tr
? tr
.c : initColor
,
1530 p: !!tr
? tr
.p : initPiece
1542 if (this.board
[ex
][ey
] != "") {
1547 c: this.getColor(ex
, ey
),
1548 p: this.getPiece(ex
, ey
)
1551 if (this.options
["rifle"])
1552 // Rifle captures are tricky in combination with Atomic etc,
1553 // so it's useful to mark the move :
1555 if (this.options
["cannibal"] && destColor
!= initColor
) {
1556 const lastIdx
= mv
.vanish
.length
- 1;
1557 let trPiece
= mv
.vanish
[lastIdx
].p
;
1558 if (this.isKing(this.getPiece(sx
, sy
)))
1559 trPiece
= C
.CannibalKingCode
[trPiece
];
1560 if (mv
.appear
.length
>= 1)
1561 mv
.appear
[0].p
= trPiece
;
1562 else if (this.options
["rifle"]) {
1585 // En-passant square, if any
1586 getEpSquare(moveOrSquare
) {
1587 if (typeof moveOrSquare
=== "string") {
1588 const square
= moveOrSquare
;
1591 return C
.SquareToCoords(square
);
1593 // Argument is a move:
1594 const move = moveOrSquare
;
1595 const s
= move.start
,
1599 Math
.abs(s
.x
- e
.x
) == 2 &&
1600 // Next conditions for variants like Atomic or Rifle, Recycle...
1601 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1602 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1609 return undefined; //default
1612 // Special case of en-passant captures: treated separately
1613 getEnpassantCaptures([x
, y
], shiftX
) {
1614 const color
= this.getColor(x
, y
);
1615 const oppCol
= C
.GetOppCol(color
);
1616 let enpassantMove
= null;
1619 this.epSquare
.x
== x
+ shiftX
&&
1620 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1621 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1623 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1624 this.board
[epx
][epy
] = oppCol
+ "p";
1625 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1626 this.board
[epx
][epy
] = "";
1627 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1628 enpassantMove
.vanish
[lastIdx
].x
= x
;
1630 return !!enpassantMove
? [enpassantMove
] : [];
1633 // Consider all potential promotions.
1634 // NOTE: "promotions" arg = special override for Hiddenqueen variant
1635 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1636 let finalPieces
= ["p"];
1637 const color
= this.getColor(x1
, y1
);
1638 const oppCol
= C
.GetOppCol(color
);
1639 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1641 x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == "");
1642 if (promotionOk
&& !this.options
["pawnfall"]) {
1644 this.options
["cannibal"] &&
1645 this.board
[x2
][y2
] != "" &&
1646 this.getColor(x2
, y2
) == oppCol
1648 finalPieces
= [this.getPieceType(x2
, y2
)];
1650 else if (promotions
)
1651 finalPieces
= promotions
;
1652 else if (this.pawnSpecs
.promotions
)
1653 finalPieces
= this.pawnSpecs
.promotions
;
1655 for (let piece
of finalPieces
) {
1656 const tr
= !this.options
["pawnfall"] && piece
!= "p"
1657 ? { c: color
, p: piece
}
1659 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1660 if (promotionOk
&& this.options
["pawnfall"]) {
1661 newMove
.appear
.shift();
1662 newMove
.pawnfall
= true; //required in prePlay()
1664 moves
.push(newMove
);
1668 // What are the pawn moves from square x,y ?
1669 getPotentialPawnMoves([x
, y
], promotions
) {
1670 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1671 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1672 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1673 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1674 const forward
= (color
== 'w' ? -1 : 1);
1676 // Pawn movements in shiftX direction:
1677 const getPawnMoves
= (shiftX
) => {
1679 // NOTE: next condition is generally true (no pawn on last rank)
1680 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1681 if (this.board
[x
+ shiftX
][y
] == "") {
1682 // One square forward (or backward)
1683 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1684 // Next condition because pawns on 1st rank can generally jump
1686 this.pawnSpecs
.twoSquares
&&
1690 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1693 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1697 shiftX
== forward
&&
1698 this.board
[x
+ 2 * shiftX
][y
] == ""
1701 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1703 this.pawnSpecs
.threeSquares
&&
1704 this.board
[x
+ 3 * shiftX
, y
] == ""
1706 // Three squares jump
1707 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1713 if (this.pawnSpecs
.canCapture
) {
1714 for (let shiftY
of [-1, 1]) {
1715 const yCoord
= this.computeY(y
+ shiftY
);
1716 if (yCoord
>= 0 && yCoord
< sizeY
) {
1718 this.board
[x
+ shiftX
][yCoord
] != "" &&
1719 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1721 !this.options
["zen"] ||
1722 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1726 [x
, y
], [x
+ shiftX
, yCoord
],
1731 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1732 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1733 this.board
[x
- shiftX
][yCoord
] != "" &&
1734 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1736 !this.options
["zen"] ||
1737 this.getPieceType(x
+ shiftX
, yCoord
) == "k"
1741 [x
, y
], [x
- shiftX
, yCoord
],
1752 let pMoves
= getPawnMoves(pawnShiftX
);
1753 if (this.pawnSpecs
.bidirectional
)
1754 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1756 if (this.hasEnpassant
) {
1757 // NOTE: backward en-passant captures are not considered
1758 // because no rules define them (for now).
1759 Array
.prototype.push
.apply(
1761 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1765 if (this.options
["zen"])
1766 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1771 // "castleInCheck" arg to let some variants castle under check
1772 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1773 const c
= this.getColor(x
, y
);
1776 const oppCol
= C
.GetOppCol(c
);
1780 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1781 const castlingKing
= this.getPiece(x
, y
);
1782 castlingCheck: for (
1785 castleSide
++ //large, then small
1787 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1789 // If this code is reached, rook and king are on initial position
1791 // NOTE: in some variants this is not a rook
1792 const rookPos
= this.castleFlags
[c
][castleSide
];
1793 const castlingPiece
= this.getPiece(x
, rookPos
);
1795 this.board
[x
][rookPos
] == "" ||
1796 this.getColor(x
, rookPos
) != c
||
1797 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1799 // Rook is not here, or changed color (see Benedict)
1802 // Nothing on the path of the king ? (and no checks)
1803 const finDist
= finalSquares
[castleSide
][0] - y
;
1804 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1808 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1810 this.board
[x
][i
] != "" &&
1811 // NOTE: next check is enough, because of chessboard constraints
1812 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1815 continue castlingCheck
;
1818 } while (i
!= finalSquares
[castleSide
][0]);
1819 // Nothing on the path to the rook?
1820 step
= (castleSide
== 0 ? -1 : 1);
1821 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1822 if (this.board
[x
][i
] != "")
1823 continue castlingCheck
;
1826 // Nothing on final squares, except maybe king and castling rook?
1827 for (i
= 0; i
< 2; i
++) {
1829 finalSquares
[castleSide
][i
] != rookPos
&&
1830 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1832 finalSquares
[castleSide
][i
] != y
||
1833 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1836 continue castlingCheck
;
1840 // If this code is reached, castle is valid
1846 y: finalSquares
[castleSide
][0],
1852 y: finalSquares
[castleSide
][1],
1858 // King might be initially disguised (Titan...)
1859 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1860 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1863 Math
.abs(y
- rookPos
) <= 2
1864 ? { x: x
, y: rookPos
}
1865 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1873 ////////////////////
1876 // Is (king at) given position under check by "color" ?
1877 underCheck([x
, y
], color
) {
1878 if (this.options
["taking"] || this.options
["dark"])
1880 color
= color
|| C
.GetOppCol(this.getColor(x
, y
));
1881 const pieces
= this.pieces(color
);
1882 return Object
.keys(pieces
).some(p
=> {
1883 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1887 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1888 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1890 return false; //cannibal king, for example
1891 const range
= stepSpec
.range
;
1892 let explored
= {}; //for Cylinder mode
1893 outerLoop: for (let step
of steps
) {
1894 let rx
= x
- step
[0],
1895 ry
= this.computeY(y
- step
[1]);
1896 let stepCounter
= 1;
1898 this.onBoard(rx
, ry
) &&
1899 this.board
[rx
][ry
] == "" &&
1900 !explored
[rx
+ "." + ry
]
1902 explored
[rx
+ "." + ry
] = true;
1903 if (range
<= stepCounter
++)
1906 ry
= this.computeY(ry
- step
[1]);
1909 this.onBoard(rx
, ry
) &&
1910 this.board
[rx
][ry
] != "" &&
1911 this.getPieceType(rx
, ry
) == piece
&&
1912 this.getColor(rx
, ry
) == color
&&
1913 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1921 // Stop at first king found (TODO: multi-kings)
1922 searchKingPos(color
) {
1923 for (let i
=0; i
< this.size
.x
; i
++) {
1924 for (let j
=0; j
< this.size
.y
; j
++) {
1925 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1929 return [-1, -1]; //king not found
1932 filterValid(moves
) {
1933 if (moves
.length
== 0)
1935 const color
= this.turn
;
1936 const oppCol
= C
.GetOppCol(color
);
1937 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1938 // Forbid moves either giving check or exploding opponent's king:
1939 const oppKingPos
= this.searchKingPos(oppCol
);
1940 moves
= moves
.filter(m
=> {
1942 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1943 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1946 this.playOnBoard(m
);
1947 const res
= !this.underCheck(oppKingPos
, color
);
1948 this.undoOnBoard(m
);
1952 if (this.options
["taking"] || this.options
["dark"])
1954 const kingPos
= this.searchKingPos(color
);
1955 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1956 return moves
.filter(m
=> {
1957 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1958 if (!filtered
[key
]) {
1959 this.playOnBoard(m
);
1960 let square
= kingPos
,
1961 res
= true; //a priori valid
1962 if (m
.vanish
.some(v
=> {
1963 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1965 // Search king in appear array:
1967 m
.appear
.findIndex(a
=> {
1968 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1970 if (newKingIdx
>= 0)
1971 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1975 res
&&= !this.underCheck(square
, oppCol
);
1976 this.undoOnBoard(m
);
1977 filtered
[key
] = res
;
1980 return filtered
[key
];
1987 // Aggregate flags into one object
1989 return this.castleFlags
;
1992 // Reverse operation
1993 disaggregateFlags(flags
) {
1994 this.castleFlags
= flags
;
1997 // Apply a move on board
1999 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
2000 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2002 // Un-apply the played move
2004 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
2005 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
2008 updateCastleFlags(move) {
2009 // Update castling flags if start or arrive from/at rook/king locations
2010 move.appear
.concat(move.vanish
).forEach(psq
=> {
2012 this.board
[psq
.x
][psq
.y
] != "" &&
2013 this.getPieceType(psq
.x
, psq
.y
) == "k"
2015 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2017 // NOTE: not "else if" because king can capture enemy rook...
2021 else if (psq
.x
== this.size
.x
- 1)
2024 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2026 this.castleFlags
[c
][fidx
] = this.size
.y
;
2033 typeof move.start
.x
== "number" &&
2034 (!this.options
["teleport"] || this.subTurnTeleport
== 1)
2036 // OK, not a drop move
2039 // If flags already off, no need to re-check:
2040 Object
.keys(this.castleFlags
).some(c
=> {
2041 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
2043 this.updateCastleFlags(move);
2045 const initSquare
= C
.CoordsToSquare(move.start
);
2047 this.options
["crazyhouse"] &&
2048 (!this.options
["rifle"] || !move.capture
)
2050 if (this.ispawn
[initSquare
]) {
2051 delete this.ispawn
[initSquare
];
2052 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
2055 move.vanish
[0].p
== "p" &&
2056 move.appear
[0].p
!= "p"
2058 this.ispawn
[C
.CoordsToSquare(move.end
)] = true;
2062 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2063 if (this.hasReserve
&& !move.pawnfall
) {
2064 const color
= this.turn
;
2065 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2066 // Something appears = dropped on board (some exceptions, Chakart...)
2067 const piece
= move.appear
[i
].p
;
2068 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2070 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2071 // Something vanish: add to reserve except if recycle & opponent
2072 const piece
= move.vanish
[i
].p
;
2073 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
2074 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2081 if (this.hasEnpassant
)
2082 this.epSquare
= this.getEpSquare(move);
2083 this.playOnBoard(move);
2084 this.postPlay(move);
2088 const color
= this.turn
;
2089 const oppCol
= C
.GetOppCol(color
);
2090 if (this.options
["dark"])
2091 this.updateEnlightened(true);
2092 if (this.options
["teleport"]) {
2094 this.subTurnTeleport
== 1 &&
2095 move.vanish
.length
> move.appear
.length
&&
2096 move.vanish
[move.vanish
.length
- 1].c
== color
2098 const v
= move.vanish
[move.vanish
.length
- 1];
2099 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2100 this.subTurnTeleport
= 2;
2103 this.subTurnTeleport
= 1;
2104 this.captured
= null;
2106 if (this.options
["balance"]) {
2107 if (![1, 3].includes(this.movesCount
))
2113 this.options
["doublemove"] &&
2114 this.movesCount
>= 1 &&
2117 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2119 const oppKingPos
= this.searchKingPos(oppCol
);
2120 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
2131 // "Stop at the first move found"
2132 atLeastOneMove(color
) {
2133 color
= color
|| this.turn
;
2134 for (let i
= 0; i
< this.size
.x
; i
++) {
2135 for (let j
= 0; j
< this.size
.y
; j
++) {
2136 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2137 // NOTE: in fact searching for all potential moves from i,j.
2138 // I don't believe this is an issue, for now at least.
2139 const moves
= this.getPotentialMovesFrom([i
, j
]);
2140 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2145 if (this.hasReserve
&& this.reserve
[color
]) {
2146 for (let p
of Object
.keys(this.reserve
[color
])) {
2147 const moves
= this.getDropMovesFrom([color
, p
]);
2148 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2155 // What is the score ? (Interesting if game is over)
2156 getCurrentScore(move) {
2157 const color
= this.turn
;
2158 const oppCol
= C
.GetOppCol(color
);
2159 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2160 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2162 if (kingPos
[0][0] < 0)
2163 return (color
== "w" ? "0-1" : "1-0");
2164 if (kingPos
[1][0] < 0)
2165 return (color
== "w" ? "1-0" : "0-1");
2166 if (this.atLeastOneMove())
2168 // No valid move: stalemate or checkmate?
2169 if (!this.underCheck(kingPos
, color
))
2172 return (color
== "w" ? "0-1" : "1-0");
2175 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2176 playVisual(move, r
) {
2177 move.vanish
.forEach(v
=> {
2178 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
2179 this.g_pieces
[v
.x
][v
.y
].remove();
2180 this.g_pieces
[v
.x
][v
.y
] = null;
2184 document
.getElementById(this.containerId
).querySelector(".chessboard");
2186 r
= chessboard
.getBoundingClientRect();
2187 const pieceWidth
= this.getPieceWidth(r
.width
);
2188 move.appear
.forEach(a
=> {
2189 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2191 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2192 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2193 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2194 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2195 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2196 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2197 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2198 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2202 playPlusVisual(move, r
) {
2203 this.playVisual(move, r
);
2205 this.afterPlay(move); //user method
2208 // Assumes reserve on top (usage case otherwise? TODO?)
2209 getReserveShift(c
, p
, r
) {
2212 for (let pi
of Object
.keys(this.reserve
[c
])) {
2213 if (this.reserve
[c
][pi
] == 0)
2219 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2220 return [-ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2223 animate(move, callback
) {
2224 if (this.noAnimate
) {
2228 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2229 const dropMove
= (typeof i1
== "string");
2230 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2231 let startPiece
= startArray
[i1
][j1
];
2233 document
.getElementById(this.containerId
).querySelector(".chessboard");
2234 const clonePiece
= (
2236 this.options
["rifle"] ||
2237 (this.options
["teleport"] && this.subTurnTeleport
== 2)
2240 startPiece
= startPiece
.cloneNode();
2241 if (this.options
["rifle"])
2242 startArray
[i1
][j1
].style
.opacity
= "0";
2243 if (this.options
["teleport"] && this.subTurnTeleport
== 2) {
2244 const pieces
= this.pieces();
2245 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2246 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2247 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2250 chessboard
.appendChild(startPiece
);
2252 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2256 i1
== this.playerColor
? this.size
.x : 0,
2257 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2261 startCoords
= [i1
, j1
];
2262 const r
= chessboard
.getBoundingClientRect();
2263 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2266 rs
= this.getReserveShift(i1
, j1
, r
);
2268 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2269 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2270 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2271 const duration
= 0.2 + multFact
* 0.3;
2272 const initTransform
= startPiece
.style
.transform
;
2273 startPiece
.style
.transform
=
2274 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2275 startPiece
.style
.transitionDuration
= duration
+ "s";
2279 if (this.options
["rifle"])
2280 startArray
[i1
][j1
].style
.opacity
= "1";
2281 startPiece
.remove();
2284 startPiece
.style
.transform
= initTransform
;
2285 startPiece
.style
.transitionDuration
= "0s";
2293 playReceivedMove(moves
, callback
) {
2294 const launchAnimation
= () => {
2295 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2296 const animateRec
= i
=> {
2297 this.animate(moves
[i
], () => {
2298 this.playVisual(moves
[i
], r
);
2299 this.play(moves
[i
]);
2300 if (i
< moves
.length
- 1)
2301 setTimeout(() => animateRec(i
+1), 300);
2308 // Delay if user wasn't focused:
2309 const checkDisplayThenAnimate
= (delay
) => {
2310 if (container
.style
.display
== "none") {
2311 alert("New move! Let's go back to game...");
2312 document
.getElementById("gameInfos").style
.display
= "none";
2313 container
.style
.display
= "block";
2314 setTimeout(launchAnimation
, 700);
2317 setTimeout(launchAnimation
, delay
|| 0);
2319 let container
= document
.getElementById(this.containerId
);
2320 if (document
.hidden
) {
2321 document
.onvisibilitychange
= () => {
2322 document
.onvisibilitychange
= undefined;
2323 checkDisplayThenAnimate(700);
2327 checkDisplayThenAnimate();