68ca909ad1ab75a94e5f97cd8c05d1bfb8a436e6
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 export default class ChessRules
{
9 /////////////////////////
10 // VARIANT SPECIFICATIONS
12 // Some variants have specific options, like the number of pawns in Monster,
13 // or the board size for Pandemonium.
14 // Users can generally select a randomness level from 0 to 2.
15 static get Options() {
17 // NOTE: some options are required for FEN generation, some aren't.
20 variable: "randomness",
23 { label: "Deterministic", value: 0 },
24 { label: "Symmetric random", value: 1 },
25 { label: "Asymmetric random", value: 2 }
29 label: "Capture king?",
33 // Game modifiers (using "elementary variants"). Default: false
36 "balance", //takes precedence over doublemove & progressive
40 "cylinder", //ok with all
44 "progressive", //(natural) priority over doublemove
53 // Pawns specifications
56 directions: { 'w': -1, 'b': 1 },
57 initShift: { w: 1, b: 1 },
61 captureBackward: false,
63 promotions: ['r', 'n', 'b', 'q']
67 // Some variants don't have flags:
76 // En-passant captures allowed?
83 !!this.options
["crazyhouse"] ||
84 (!!this.options
["recycle"] && !this.options
["teleport"])
89 return !!this.options
["dark"];
92 // Some variants use click infos:
94 if (typeof x
!= "number") return null; //click on reserves
96 this.options
["teleport"] && this.subTurn
== 2 &&
97 this.board
[x
][y
] == ""
100 start: {x: this.captured
.x
, y: this.captured
.y
},
105 c: this.captured
.c
, //this.turn,
118 // 3 --> d (column number to letter)
119 static CoordToColumn(colnum
) {
120 return String
.fromCharCode(97 + colnum
);
123 // d --> 3 (column letter to number)
124 static ColumnToCoord(columnStr
) {
125 return columnStr
.charCodeAt(0) - 97;
128 // 7 (numeric) --> 1 (str) [from black viewpoint].
129 static CoordToRow(rownum
) {
133 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
134 static RowToCoord(rownumStr
) {
135 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
136 return parseInt(rownumStr
, 30);
139 // a2 --> {x:2,y:0} (this is in fact a6)
140 static SquareToCoords(sq
) {
142 x: ChessRules
.RowToCoord(sq
[1]),
143 // NOTE: column is always one char => max 26 columns
144 y: ChessRules
.ColumnToCoord(sq
[0])
148 // {x:0,y:4} --> e0 (should be e8)
149 static CoordsToSquare(coords
) {
151 ChessRules
.CoordToColumn(coords
.y
) + ChessRules
.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
) {
163 if (!targetId
) return null; //outside page, maybe...
164 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
166 idParts
.length
< 2 ||
167 idParts
[0] != this.containerId
||
168 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
172 const squares
= idParts
[1].split('-');
173 if (squares
[0] == "sq")
174 return [ parseInt(squares
[1], 30), parseInt(squares
[2], 30) ];
175 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
176 return [squares
[1], squares
[2]];
182 // Turn "wb" into "B" (for FEN)
184 return b
[0] == "w" ? b
[1].toUpperCase() : b
[1];
187 // Turn "p" into "bp" (for board)
189 return f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
;
192 // Setup the initial random-or-not (asymmetric-or-not) position
193 genRandInitFen(seed
) {
194 Random
.setSeed(seed
);
196 let fen
, flags
= "0707";
197 if (this.options
.randomness
== 0 || !this.options
.randomness
)
199 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
203 let pieces
= { w: new Array(8), b: new Array(8) };
205 // Shuffle pieces on first (and last rank if randomness == 2)
206 for (let c
of ["w", "b"]) {
207 if (c
== 'b' && this.options
.randomness
== 1) {
208 pieces
['b'] = pieces
['w'];
213 let positions
= ArrayFun
.range(8);
215 // Get random squares for bishops
216 let randIndex
= 2 * Random
.randInt(4);
217 const bishop1Pos
= positions
[randIndex
];
218 // The second bishop must be on a square of different color
219 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
220 const bishop2Pos
= positions
[randIndex_tmp
];
221 // Remove chosen squares
222 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
223 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
225 // Get random squares for knights
226 randIndex
= Random
.randInt(6);
227 const knight1Pos
= positions
[randIndex
];
228 positions
.splice(randIndex
, 1);
229 randIndex
= Random
.randInt(5);
230 const knight2Pos
= positions
[randIndex
];
231 positions
.splice(randIndex
, 1);
233 // Get random square for queen
234 randIndex
= Random
.randInt(4);
235 const queenPos
= positions
[randIndex
];
236 positions
.splice(randIndex
, 1);
238 // Rooks and king positions are now fixed,
239 // because of the ordering rook-king-rook
240 const rook1Pos
= positions
[0];
241 const kingPos
= positions
[1];
242 const rook2Pos
= positions
[2];
244 // Finally put the shuffled pieces in the board array
245 pieces
[c
][rook1Pos
] = "r";
246 pieces
[c
][knight1Pos
] = "n";
247 pieces
[c
][bishop1Pos
] = "b";
248 pieces
[c
][queenPos
] = "q";
249 pieces
[c
][kingPos
] = "k";
250 pieces
[c
][bishop2Pos
] = "b";
251 pieces
[c
][knight2Pos
] = "n";
252 pieces
[c
][rook2Pos
] = "r";
253 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
256 pieces
["b"].join("") +
257 "/pppppppp/8/8/8/8/PPPPPPPP/" +
258 pieces
["w"].join("").toUpperCase() +
262 // Add turn + flags + enpassant (+ reserve)
264 if (this.hasFlags
) parts
.push(`"flags":"${flags}"`);
265 if (this.hasEnpassant
) parts
.push('"enpassant":"-"');
266 if (this.hasReserve
) parts
.push('"reserve":"000000000000"');
267 if (this.options
["crazyhouse"]) parts
.push('"ispawn":"-"');
268 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
272 // "Parse" FEN: just return untransformed string data
274 const fenParts
= fen
.split(" ");
276 position: fenParts
[0],
278 movesCount: fenParts
[2]
280 if (fenParts
.length
> 3) res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
284 // Return current fen (game state)
287 this.getBaseFen() + " " +
288 this.getTurnFen() + " " +
292 if (this.hasFlags
) parts
.push(`"flags":"${this.getFlagsFen()}"`);
293 if (this.hasEnpassant
)
294 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
295 if (this.hasReserve
) parts
.push(`"reserve":"${this.getReserveFen()}"`);
296 if (this.options
["crazyhouse"])
297 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
298 if (parts
.length
>= 1) fen
+= " {" + parts
.join(",") + "}";
302 // Position part of the FEN string
304 const format
= (count
) => {
305 // if more than 9 consecutive free spaces, break the integer,
306 // otherwise FEN parsing will fail.
307 if (count
<= 9) return count
;
308 // Most boards of size < 18:
309 if (count
<= 18) return "9" + (count
- 9);
311 return "99" + (count
- 18);
314 for (let i
= 0; i
< this.size
.y
; i
++) {
316 for (let j
= 0; j
< this.size
.x
; j
++) {
317 if (this.board
[i
][j
] == "") emptyCount
++;
319 if (emptyCount
> 0) {
320 // Add empty squares in-between
321 position
+= format(emptyCount
);
324 position
+= this.board2fen(this.board
[i
][j
]);
329 position
+= format(emptyCount
);
330 if (i
< this.size
.y
- 1) position
+= "/"; //separate rows
339 // Flags part of the FEN string
341 return ["w", "b"].map(c
=> {
342 return this.castleFlags
[c
].map(x
=> x
.toString(30)).join("");
346 // Enpassant part of the FEN string
348 if (!this.epSquare
) return "-"; //no en-passant
349 return ChessRules
.CoordsToSquare(this.epSquare
);
354 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
359 const coords
= Object
.keys(this.ispawn
);
360 if (coords
.length
== 0) return "-";
361 return coords
.map(ChessRules
.CoordsToSquare
).join(",");
364 // Set flags from fen (castle: white a,h then black a,h)
367 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 30)),
368 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 30))
375 // Fen string fully describes the game state
377 this.options
= o
.options
;
378 this.playerColor
= o
.color
;
379 this.afterPlay
= o
.afterPlay
;
382 if (!o
.fen
) o
.fen
= this.genRandInitFen(o
.seed
);
383 const fenParsed
= this.parseFen(o
.fen
);
384 this.board
= this.getBoard(fenParsed
.position
);
385 this.turn
= fenParsed
.turn
;
386 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
387 this.setOtherVariables(fenParsed
);
389 // Graphical (can use variables defined above)
390 this.containerId
= o
.element
;
391 this.graphicalInit();
394 // Turn position fen into double array ["wb","wp","bk",...]
396 const rows
= position
.split("/");
397 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
398 for (let i
= 0; i
< rows
.length
; i
++) {
400 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
401 const character
= rows
[i
][indexInRow
];
402 const num
= parseInt(character
, 10);
403 // If num is a number, just shift j:
404 if (!isNaN(num
)) j
+= num
;
405 // Else: something at position i,j
406 else board
[i
][j
++] = this.fen2board(character
);
412 // Some additional variables from FEN (variant dependant)
413 setOtherVariables(fenParsed
) {
414 // Set flags and enpassant:
415 if (this.hasFlags
) this.setFlags(fenParsed
.flags
);
416 if (this.hasEnpassant
)
417 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
418 if (this.hasReserve
) this.initReserves(fenParsed
.reserve
);
419 if (this.options
["crazyhouse"]) this.initIspawn(fenParsed
.ispawn
);
420 this.subTurn
= 1; //may be unused
421 if (this.options
["teleport"]) this.captured
= null;
422 if (this.options
["dark"]) {
423 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
);
424 // Setup enlightened: squares reachable by player side
425 this.updateEnlightened(false);
429 updateEnlightened(withGraphics
) {
430 let newEnlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
431 const pawnShift
= { w: -1, b: 1 };
432 // Add pieces positions + all squares reachable by moves (includes Zen):
433 // (watch out special pawns case)
434 for (let x
=0; x
<this.size
.x
; x
++) {
435 for (let y
=0; y
<this.size
.y
; y
++) {
436 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
438 newEnlightened
[x
][y
] = true;
439 const piece
= this.getPiece(x
, y
);
440 if (piece
== ChessRules
.PAWN
) {
441 // Attacking squares wouldn't be highlighted if no captures:
442 this.pieces(this.playerColor
)[piece
].attack
.forEach(step
=> {
443 const [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
444 if (this.onBoard(i
, j
) && this.board
[i
][j
] == "")
445 newEnlightened
[i
][j
] = true;
448 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
449 newEnlightened
[m
.end
.x
][m
.end
.y
] = true;
454 if (this.epSquare
) this.enlightEnpassant(newEnlightened
);
455 if (withGraphics
) this.graphUpdateEnlightened(newEnlightened
);
456 this.enlightened
= newEnlightened
;
459 // Include en-passant capturing square if any:
460 enlightEnpassant(newEnlightened
) {
461 const steps
= this.pieces(this.playerColor
)[ChessRules
.PAWN
].attack
;
462 for (let step
of steps
) {
463 const x
= this.epSquare
.x
- step
[0],
464 y
= this.computeY(this.epSquare
.y
- step
[1]);
466 this.onBoard(x
, y
) &&
467 this.getColor(x
, y
) == this.playerColor
&&
468 this.getPiece(x
, y
) == ChessRules
.PAWN
470 newEnlightened
[x
][this.epSquare
.y
] = true;
476 // Apply diff this.enlightened --> newEnlightened on board
477 graphUpdateEnlightened(newEnlightened
) {
478 let container
= document
.getElementById(this.containerId
);
479 const r
= container
.getBoundingClientRect();
480 const pieceWidth
= this.getPieceWidth(r
.width
);
481 for (let x
=0; x
<this.size
.x
; x
++) {
482 for (let y
=0; y
<this.size
.y
; y
++) {
483 if (this.enlightened
[x
][y
] && !newEnlightened
[x
][y
]) {
484 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
485 elt
.style
.fillOpacity
= "0.5";
486 if (this.g_pieces
[x
][y
]) {
487 this.g_pieces
[x
][y
].remove();
488 this.g_pieces
[x
][y
] = null;
491 else if (!this.enlightened
[x
][y
] && newEnlightened
[x
][y
]) {
492 let elt
= document
.getElementById(this.coordsToId([x
, y
]));
493 elt
.style
.fillOpacity
= "1";
494 if (this.board
[x
][y
] != "") {
495 const piece
= this.getPiece(x
, y
);
496 const color
= this.getColor(x
, y
);
497 this.g_pieces
[x
][y
] = document
.createElement("piece");
499 this.pieces()[piece
]["class"],
500 color
== "w" ? "white" : "black"
502 newClasses
.forEach(cl
=> this.g_pieces
[x
][y
].classList
.add(cl
));
503 this.g_pieces
[x
][y
].style
.width
= pieceWidth
+ "px";
504 this.g_pieces
[x
][y
].style
.height
= pieceWidth
+ "px";
505 const [ip
, jp
] = this.getPixelPosition(x
, y
, r
);
506 this.g_pieces
[x
][y
].style
.transform
=
507 `translate(${ip}px,${jp}px)`;
508 container
.appendChild(this.g_pieces
[x
][y
]);
515 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
516 initReserves(reserveStr
) {
517 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
518 this.reserve
= { w: {}, b: {} };
519 const pieceName
= Object
.keys(this.pieces());
520 for (let i
of ArrayFun
.range(12)) {
521 if (i
< 6) this.reserve
['w'][pieceName
[i
]] = counts
[i
];
522 else this.reserve
['b'][pieceName
[i
-6]] = counts
[i
];
526 initIspawn(ispawnStr
) {
527 if (ispawnStr
!= "-") {
528 this.ispawn
= ispawnStr
.split(",").map(ChessRules
.SquareToCoords
)
529 .reduce((o
, key
) => ({ ...o
, [key
]: true}), {});
531 else this.ispawn
= {};
534 getNbReservePieces(color
) {
536 Object
.values(this.reserve
[color
]).reduce(
537 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
544 getPieceWidth(rwidth
) {
545 return (rwidth
/ this.size
.y
);
548 getSquareWidth(rwidth
) {
549 return this.getPieceWidth(rwidth
);
552 getReserveSquareSize(rwidth
, nbR
) {
553 const sqSize
= this.getSquareWidth(rwidth
);
554 return Math
.min(sqSize
, rwidth
/ nbR
);
557 getReserveNumId(color
, piece
) {
558 return `${this.containerId}|rnum-${color}${piece}`;
562 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
563 window
.onresize
= () => this.re_drawBoardElements();
564 this.re_drawBoardElements();
565 this.initMouseEvents();
566 const container
= document
.getElementById(this.containerId
);
567 new ResizeObserver(this.rescale
).observe(container
);
570 re_drawBoardElements() {
571 const board
= this.getSvgChessboard();
572 const oppCol
= ChessRules
.GetOppCol(this.playerColor
);
573 let container
= document
.getElementById(this.containerId
);
574 container
.innerHTML
= "";
575 container
.insertAdjacentHTML('beforeend', board
);
576 let cb
= container
.querySelector("#" + this.containerId
+ "_SVG");
577 const aspectRatio
= this.size
.y
/ this.size
.x
;
578 // Compare window ratio width / height to aspectRatio:
579 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
580 let cbWidth
, cbHeight
;
581 if (windowRatio
<= aspectRatio
) {
582 // Limiting dimension is width:
583 cbWidth
= Math
.min(window
.innerWidth
, 767);
584 cbHeight
= cbWidth
/ aspectRatio
;
587 // Limiting dimension is height:
588 cbHeight
= Math
.min(window
.innerHeight
, 767);
589 cbWidth
= cbHeight
* aspectRatio
;
592 const sqSize
= cbWidth
/ this.size
.y
;
593 // NOTE: allocate space for reserves (up/down) even if they are empty
594 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
595 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
596 cbWidth
= cbHeight
* aspectRatio
;
599 container
.style
.width
= cbWidth
+ "px";
600 container
.style
.height
= cbHeight
+ "px";
601 // Center chessboard:
602 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
603 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
604 container
.style
.left
= spaceLeft
+ "px";
605 container
.style
.top
= spaceTop
+ "px";
606 // Give sizes instead of recomputing them,
607 // because chessboard might not be drawn yet.
616 // Get SVG board (background, no pieces)
618 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
619 const flipped
= (this.playerColor
== 'b');
624 id="${this.containerId}_SVG">
626 for (let i
=0; i
< sizeX
; i
++) {
627 for (let j
=0; j
< sizeY
; j
++) {
628 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
629 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
630 let fillOpacity
= '1';
631 let classes
= this.getSquareColorClass(ii
, jj
);
632 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
633 classes
+= " in-shadow";
634 // NOTE: x / y reversed because coordinates system is reversed.
637 id="${this.coordsToId([ii, jj])}"
644 board
+= "</g></svg>";
648 // Generally light square bottom-right; TODO: user-defined colors at least
649 getSquareColorClass(i
, j
) {
650 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
655 // Refreshing: delete old pieces first
656 for (let i
=0; i
<this.size
.x
; i
++) {
657 for (let j
=0; j
<this.size
.y
; j
++) {
658 if (this.g_pieces
[i
][j
]) {
659 this.g_pieces
[i
][j
].remove();
660 this.g_pieces
[i
][j
] = null;
665 else this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
666 let container
= document
.getElementById(this.containerId
);
667 if (!r
) r
= container
.getBoundingClientRect();
668 const pieceWidth
= this.getPieceWidth(r
.width
);
669 for (let i
=0; i
< this.size
.x
; i
++) {
670 for (let j
=0; j
< this.size
.y
; j
++) {
672 this.board
[i
][j
] != "" &&
673 (!this.options
["dark"] || this.enlightened
[i
][j
])
675 const piece
= this.getPiece(i
, j
);
676 const color
= this.getColor(i
, j
);
677 this.g_pieces
[i
][j
] = document
.createElement("piece");
678 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
679 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
680 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
681 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
682 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
683 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
684 container
.appendChild(this.g_pieces
[i
][j
]);
688 if (this.reserve
) this.re_drawReserve(['w', 'b'], r
);
691 // NOTE: assume !!this.reserve
692 re_drawReserve(colors
, r
) {
694 // Remove (old) reserve pieces
695 for (let c
of colors
) {
696 if (!this.reserve
[c
]) continue;
697 Object
.keys(this.reserve
[c
]).forEach(p
=> {
698 if (this.r_pieces
[c
][p
]) {
699 this.r_pieces
[c
][p
].remove();
700 delete this.r_pieces
[c
][p
];
701 const numId
= this.getReserveNumId(c
, p
);
702 document
.getElementById(numId
).remove();
705 let reservesDiv
= document
.getElementById("reserves_" + c
);
706 if (reservesDiv
) reservesDiv
.remove();
709 else this.r_pieces
= { 'w': {}, 'b': {} };
711 const container
= document
.getElementById(this.containerId
);
712 r
= container
.getBoundingClientRect();
714 const epsilon
= 1e-4; //fix display bug on Firefox at least
715 for (let c
of colors
) {
716 if (!this.reserve
[c
]) continue;
717 const nbR
= this.getNbReservePieces(c
);
718 if (nbR
== 0) continue;
719 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
721 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
722 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
723 let rcontainer
= document
.createElement("div");
724 rcontainer
.id
= "reserves_" + c
;
725 rcontainer
.classList
.add("reserves");
726 rcontainer
.style
.left
= i0
+ "px";
727 rcontainer
.style
.top
= j0
+ "px";
728 rcontainer
.style
.width
= (nbR
* sqResSize
) + "px";
729 rcontainer
.style
.height
= sqResSize
+ "px";
730 document
.getElementById("boardContainer").appendChild(rcontainer
);
731 for (let p
of Object
.keys(this.reserve
[c
])) {
732 if (this.reserve
[c
][p
] == 0) continue;
733 let r_cell
= document
.createElement("div");
734 r_cell
.id
= this.coordsToId([c
, p
]);
735 r_cell
.classList
.add("reserve-cell");
736 r_cell
.style
.width
= (sqResSize
- epsilon
) + "px";
737 r_cell
.style
.height
= (sqResSize
- epsilon
) + "px";
738 rcontainer
.appendChild(r_cell
);
739 let piece
= document
.createElement("piece");
740 const pieceSpec
= this.pieces(c
)[p
];
741 piece
.classList
.add(pieceSpec
["class"]);
742 piece
.classList
.add(c
== 'w' ? "white" : "black");
743 piece
.style
.width
= "100%";
744 piece
.style
.height
= "100%";
745 this.r_pieces
[c
][p
] = piece
;
746 r_cell
.appendChild(piece
);
747 let number
= document
.createElement("div");
748 number
.textContent
= this.reserve
[c
][p
];
749 number
.classList
.add("reserve-num");
750 number
.id
= this.getReserveNumId(c
, p
);
751 const fontSize
= "1.3em";
752 number
.style
.fontSize
= fontSize
;
753 number
.style
.fontSize
= fontSize
;
754 r_cell
.appendChild(number
);
760 updateReserve(color
, piece
, count
) {
761 const oldCount
= this.reserve
[color
][piece
];
762 this.reserve
[color
][piece
] = count
;
763 // Redrawing is much easier if count==0
764 if ([oldCount
, count
].includes(0)) this.re_drawReserve([color
]);
766 const numId
= this.getReserveNumId(color
, piece
);
767 document
.getElementById(numId
).textContent
= count
;
771 // After resize event: no need to destroy/recreate pieces
773 let container
= document
.getElementById(this.containerId
);
774 if (!container
) return; //useful at initial loading
775 const r
= container
.getBoundingClientRect();
776 const newRatio
= r
.width
/ r
.height
;
777 const aspectRatio
= this.size
.y
/ this.size
.x
;
778 let newWidth
= r
.width
,
779 newHeight
= r
.height
;
780 if (newRatio
> aspectRatio
) {
781 newWidth
= r
.height
* aspectRatio
;
782 container
.style
.width
= newWidth
+ "px";
784 else if (newRatio
< aspectRatio
) {
785 newHeight
= r
.width
/ aspectRatio
;
786 container
.style
.height
= newHeight
+ "px";
788 const newX
= (window
.innerWidth
- newWidth
) / 2;
789 container
.style
.left
= newX
+ "px";
790 const newY
= (window
.innerHeight
- newHeight
) / 2;
791 container
.style
.top
= newY
+ "px";
792 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
793 const pieceWidth
= this.getPieceWidth(newWidth
);
794 for (let i
=0; i
< this.size
.x
; i
++) {
795 for (let j
=0; j
< this.size
.y
; j
++) {
796 if (this.board
[i
][j
] != "") {
797 // NOTE: could also use CSS transform "scale"
798 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
799 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
800 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
801 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
805 if (this.reserve
) this.rescaleReserve(newR
);
809 const epsilon
= 1e-4;
810 for (let c
of ['w','b']) {
811 if (!this.reserve
[c
]) continue;
812 const nbR
= this.getNbReservePieces(c
);
813 if (nbR
== 0) continue;
814 // Resize container first
815 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
816 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
817 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
818 let rcontainer
= document
.getElementById("reserves_" + c
);
819 rcontainer
.style
.left
= i0
+ "px";
820 rcontainer
.style
.top
= j0
+ "px";
821 rcontainer
.style
.width
= (nbR
* sqResSize
) + "px";
822 rcontainer
.style
.height
= sqResSize
+ "px";
823 // And then reserve cells:
824 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
825 Object
.keys(this.reserve
[c
]).forEach(p
=> {
826 if (this.reserve
[c
][p
] == 0) return;
827 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
828 r_cell
.style
.width
= (sqResSize
- epsilon
) + "px";
829 r_cell
.style
.height
= (sqResSize
- epsilon
) + "px";
834 // Return the absolute pixel coordinates given current position.
835 // Our coordinate system differs from CSS one (x <--> y).
836 // We return here the CSS coordinates (more useful).
837 getPixelPosition(i
, j
, r
) {
838 const sqSize
= this.getSquareWidth(r
.width
);
839 if (i
< 0 || j
< 0) return [0, 0]; //piece vanishes
840 const flipped
= (this.playerColor
== 'b');
841 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
842 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
847 let container
= document
.getElementById(this.containerId
);
849 const getOffset
= e
=> {
850 if (e
.clientX
) return {x: e
.clientX
, y: e
.clientY
}; //Mouse
851 let touchLocation
= null;
852 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
853 // Touch screen, dragstart
854 touchLocation
= e
.targetTouches
[0];
855 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
856 // Touch screen, dragend
857 touchLocation
= e
.changedTouches
[0];
859 return {x: touchLocation
.pageX
, y: touchLocation
.pageY
};
860 return [0, 0]; //Big trouble here =)
863 const centerOnCursor
= (piece
, e
) => {
864 const centerShift
= sqSize
/ 2;
865 const offset
= getOffset(e
);
866 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
867 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
872 startPiece
, curPiece
= null,
874 const mousedown
= (e
) => {
875 r
= container
.getBoundingClientRect();
876 sqSize
= this.getSquareWidth(r
.width
);
877 const square
= this.idToCoords(e
.target
.id
);
879 const [i
, j
] = square
;
880 const move = this.doClick([i
, j
]);
881 if (move) this.playPlusVisual(move);
883 if (typeof i
!= "number") startPiece
= this.r_pieces
[i
][j
];
884 else if (this.g_pieces
[i
][j
]) startPiece
= this.g_pieces
[i
][j
];
885 if (startPiece
&& this.canIplay(i
, j
)) {
887 start
= { x: i
, y: j
};
888 curPiece
= startPiece
.cloneNode();
889 curPiece
.style
.transform
= "none";
890 curPiece
.style
.zIndex
= 5;
891 curPiece
.style
.width
= sqSize
+ "px";
892 curPiece
.style
.height
= sqSize
+ "px";
893 centerOnCursor(curPiece
, e
);
894 document
.getElementById("boardContainer").appendChild(curPiece
);
895 startPiece
.style
.opacity
= "0.4";
896 container
.style
.cursor
= "none";
902 const mousemove
= (e
) => {
905 centerOnCursor(curPiece
, e
);
909 const mouseup
= (e
) => {
910 const newR
= container
.getBoundingClientRect();
911 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
916 const [x
, y
] = [start
.x
, start
.y
];
919 container
.style
.cursor
= "pointer";
920 startPiece
.style
.opacity
= "1";
921 const offset
= getOffset(e
);
922 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
923 const sq
= this.idToCoords(landingElt
.id
);
926 // NOTE: clearly suboptimal, but much easier, and not a big deal.
927 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
928 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
929 const moves
= this.filterValid(potentialMoves
);
930 if (moves
.length
>= 2) this.showChoices(moves
, r
);
931 else if (moves
.length
== 1) this.playPlusVisual(moves
[0], r
);
936 if ('onmousedown' in window
) {
937 document
.addEventListener("mousedown", mousedown
);
938 document
.addEventListener("mousemove", mousemove
);
939 document
.addEventListener("mouseup", mouseup
);
941 if ('ontouchstart' in window
) {
942 document
.addEventListener("touchstart", mousedown
);
943 document
.addEventListener("touchmove", mousemove
);
944 document
.addEventListener("touchend", mouseup
);
948 showChoices(moves
, r
) {
949 let container
= document
.getElementById(this.containerId
);
950 let choices
= document
.createElement("div");
951 choices
.id
= "choices";
952 choices
.style
.width
= r
.width
+ "px";
953 choices
.style
.height
= r
.height
+ "px";
954 choices
.style
.left
= r
.x
+ "px";
955 choices
.style
.top
= r
.y
+ "px";
956 container
.style
.opacity
= "0.5";
957 let boardContainer
= document
.getElementById("boardContainer");
958 boardContainer
.appendChild(choices
);
959 const squareWidth
= this.getSquareWidth(r
.width
);
960 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
961 const firstUpTop
= (r
.height
- squareWidth
) / 2;
962 const color
= moves
[0].appear
[0].c
;
963 const callback
= (m
) => {
964 container
.style
.opacity
= "1";
965 boardContainer
.removeChild(choices
);
966 this.playPlusVisual(m
, r
);
968 for (let i
=0; i
< moves
.length
; i
++) {
969 let choice
= document
.createElement("div");
970 choice
.classList
.add("choice");
971 choice
.style
.width
= squareWidth
+ "px";
972 choice
.style
.height
= squareWidth
+ "px";
973 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
974 choice
.style
.top
= firstUpTop
+ "px";
975 choice
.style
.backgroundColor
= "lightyellow";
976 choice
.onclick
= () => callback(moves
[i
]);
977 const piece
= document
.createElement("piece");
978 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
979 piece
.classList
.add(pieceSpec
["class"]);
980 piece
.classList
.add(color
== 'w' ? "white" : "black");
981 piece
.style
.width
= "100%";
982 piece
.style
.height
= "100%";
983 choice
.appendChild(piece
);
984 choices
.appendChild(choice
);
992 return { "x": 8, "y": 8 };
995 // Color of thing on square (i,j). 'undefined' if square is empty
997 return this.board
[i
][j
].charAt(0);
1000 // Piece type on square (i,j). 'undefined' if square is empty
1002 return this.board
[i
][j
].charAt(1);
1005 // Get opponent color
1006 static GetOppCol(color
) {
1007 return (color
== "w" ? "b" : "w");
1010 // Can thing on square1 take thing on square2
1011 canTake([x1
, y1
], [x2
, y2
]) {
1014 (this.options
["recycle"] || this.options
["teleport"]) &&
1015 this.getPiece(x2
, y2
) != ChessRules
.KING
1017 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
))
1021 // Is (x,y) on the chessboard?
1023 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1026 // Used in interface: 'side' arg == player color
1029 this.playerColor
== this.turn
&&
1031 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1032 (typeof x
== "string" && x
== this.turn
) //reserve
1037 ////////////////////////
1038 // PIECES SPECIFICATIONS
1041 const pawnShift
= (color
== "w" ? -1 : 1);
1045 steps: [[pawnShift
, 0]],
1047 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1052 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1058 [1, 2], [1, -2], [-1, 2], [-1, -2],
1059 [2, 1], [-2, 1], [2, -1], [-2, -1]
1066 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1072 [0, 1], [0, -1], [1, 0], [-1, 0],
1073 [1, 1], [1, -1], [-1, 1], [-1, -1]
1080 [0, 1], [0, -1], [1, 0], [-1, 0],
1081 [1, 1], [1, -1], [-1, 1], [-1, -1]
1088 // Some pieces codes (for a clearer code)
1092 static get QUEEN() {
1099 ////////////////////
1102 // For Cylinder: get Y coordinate
1104 if (!this.options
["cylinder"]) return y
;
1105 let res
= y
% this.size
.y
;
1106 if (res
< 0) res
+= this.size
.y
;
1110 // Stop at the first capture found
1111 atLeastOneCapture(color
) {
1112 color
= color
|| this.turn
;
1113 const oppCol
= ChessRules
.GetOppCol(color
);
1114 for (let i
= 0; i
< this.size
.x
; i
++) {
1115 for (let j
= 0; j
< this.size
.y
; j
++) {
1116 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1117 const specs
= this.pieces(color
)[this.getPiece(i
, j
)];
1118 const steps
= specs
.attack
|| specs
.steps
;
1119 outerLoop: for (let step
of steps
) {
1120 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1121 let stepCounter
= 1;
1122 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1123 if (specs
.range
<= stepCounter
++) continue outerLoop
;
1125 jj
= this.computeY(jj
+ step
[1]);
1128 this.onBoard(ii
, jj
) &&
1129 this.getColor(ii
, jj
) == oppCol
&&
1131 [this.getBasicMove([i
, j
], [ii
, jj
])]
1143 getDropMovesFrom([c
, p
]) {
1144 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1145 // (but not necessarily otherwise)
1146 if (!this.reserve
[c
][p
] || this.reserve
[c
][p
] == 0) return [];
1148 for (let i
=0; i
<this.size
.x
; i
++) {
1149 for (let j
=0; j
<this.size
.y
; j
++) {
1150 // TODO: rather simplify this "if" and add post-condition: more general
1152 this.board
[i
][j
] == "" &&
1153 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1155 p
!= ChessRules
.PAWN
||
1156 (c
== 'w' && i
< this.size
.x
- 1) ||
1162 start: {x: c
, y: p
},
1164 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1174 // All possible moves from selected square
1175 getPotentialMovesFrom(sq
, color
) {
1176 if (typeof sq
[0] == "string") return this.getDropMovesFrom(sq
);
1177 if (this.options
["madrasi"] && this.isImmobilized(sq
)) return [];
1178 const piece
= this.getPiece(sq
[0], sq
[1]);
1180 if (piece
== ChessRules
.PAWN
) moves
= this.getPotentialPawnMoves(sq
);
1181 else moves
= this.getPotentialMovesOf(piece
, sq
);
1183 piece
== ChessRules
.KING
&&
1185 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1187 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1189 return this.postProcessPotentialMoves(moves
);
1192 postProcessPotentialMoves(moves
) {
1193 if (moves
.length
== 0) return [];
1194 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1195 const oppCol
= ChessRules
.GetOppCol(color
);
1197 if (this.options
["capture"] && this.atLeastOneCapture()) {
1198 // Filter out non-capturing moves (not using m.vanish because of
1199 // self captures of Recycle and Teleport).
1200 moves
= moves
.filter(m
=> {
1202 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1203 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1208 if (this.options
["atomic"]) {
1209 moves
.forEach(m
=> {
1211 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1212 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1225 for (let step
of steps
) {
1226 let x
= m
.end
.x
+ step
[0];
1227 let y
= this.computeY(m
.end
.y
+ step
[1]);
1229 this.onBoard(x
, y
) &&
1230 this.board
[x
][y
] != "" &&
1231 this.getPiece(x
, y
) != ChessRules
.PAWN
1235 p: this.getPiece(x
, y
),
1236 c: this.getColor(x
, y
),
1243 if (!this.options
["rifle"]) m
.appear
.pop(); //nothin appears
1251 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1252 isImmobilized([x
, y
]) {
1253 const color
= this.getColor(x
, y
);
1254 const oppCol
= ChessRules
.GetOppCol(color
);
1255 const piece
= this.getPiece(x
, y
);
1256 const stepSpec
= this.pieces(color
)[piece
];
1257 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1258 outerLoop: for (let step
of steps
) {
1259 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1260 let stepCounter
= 1;
1261 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1262 if (range
<= stepCounter
++) continue outerLoop
;
1264 j
= this.computeY(j
+ step
[1]);
1267 this.onBoard(i
, j
) &&
1268 this.getColor(i
, j
) == oppCol
&&
1269 this.getPiece(i
, j
) == piece
1277 // Generic method to find possible moves of "sliding or jumping" pieces
1278 getPotentialMovesOf(piece
, [x
, y
]) {
1279 const color
= this.getColor(x
, y
);
1280 const stepSpec
= this.pieces(color
)[piece
];
1281 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1283 let explored
= {}; //for Cylinder mode
1284 outerLoop: for (let step
of steps
) {
1285 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1286 let stepCounter
= 1;
1288 this.onBoard(i
, j
) &&
1289 this.board
[i
][j
] == "" &&
1290 !explored
[i
+ "." + j
]
1292 explored
[i
+ "." + j
] = true;
1293 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1294 if (range
<= stepCounter
++) continue outerLoop
;
1296 j
= this.computeY(j
+ step
[1]);
1299 this.onBoard(i
, j
) &&
1301 !this.options
["zen"] ||
1302 this.getPiece(i
, j
) == ChessRules
.KING
||
1303 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1305 this.canTake([x
, y
], [i
, j
]) &&
1306 !explored
[i
+ "." + j
]
1308 explored
[i
+ "." + j
] = true;
1309 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1312 if (this.options
["zen"])
1313 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1317 getZenCaptures(x
, y
) {
1319 // Find reverse captures (opponent takes)
1320 const color
= this.getColor(x
, y
);
1321 const oppCol
= ChessRules
.GetOppCol(color
);
1322 const pieces
= this.pieces(oppCol
);
1323 Object
.keys(pieces
).forEach(p
=> {
1324 if (p
== ChessRules
.KING
) return; //king isn't captured this way
1325 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1326 const range
= pieces
[p
].range
;
1327 steps
.forEach(s
=> {
1328 // From x,y: revert step
1329 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1330 let stepCounter
= 1;
1331 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1332 if (range
<= stepCounter
++) return;
1334 j
= this.computeY(j
- s
[1]);
1337 this.onBoard(i
, j
) &&
1338 this.getPiece(i
, j
) == p
&&
1339 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1340 this.canTake([i
, j
], [x
, y
])
1342 if (this.getPiece(x
, y
) != ChessRules
.PAWN
)
1343 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1344 else this.addPawnMoves([x
, y
], [i
, j
], moves
);
1351 // Build a regular move from its initial and destination squares.
1352 // tr: transformation
1353 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1354 const initColor
= this.getColor(sx
, sy
);
1355 const initPiece
= this.board
[sx
][sy
].charAt(1);
1356 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1360 start: {x:sx
, y:sy
},
1364 !this.options
["rifle"] ||
1365 this.board
[ex
][ey
] == "" ||
1366 destColor
== initColor
//Recycle, Teleport
1372 c: !!tr
? tr
.c : initColor
,
1373 p: !!tr
? tr
.p : initPiece
1385 if (this.board
[ex
][ey
] != "") {
1390 c: this.getColor(ex
, ey
),
1391 p: this.board
[ex
][ey
].charAt(1)
1394 if (this.options
["rifle"])
1395 // Rifle captures are tricky in combination with Atomic etc,
1396 // so it's useful to mark the move :
1398 if (this.options
["cannibal"] && destColor
!= initColor
) {
1399 const lastIdx
= mv
.vanish
.length
- 1;
1400 if (mv
.appear
.length
>= 1) mv
.appear
[0].p
= mv
.vanish
[lastIdx
].p
;
1401 else if (this.options
["rifle"]) {
1407 p: mv
.vanish
[lastIdx
].p
1424 // En-passant square, if any
1425 getEpSquare(moveOrSquare
) {
1426 if (typeof moveOrSquare
=== "string") {
1427 const square
= moveOrSquare
;
1428 if (square
== "-") return undefined;
1429 return ChessRules
.SquareToCoords(square
);
1431 // Argument is a move:
1432 const move = moveOrSquare
;
1433 const s
= move.start
,
1437 Math
.abs(s
.x
- e
.x
) == 2 &&
1438 // Next conditions for variants like Atomic or Rifle, Recycle...
1439 (move.appear
.length
> 0 && move.appear
[0].p
== ChessRules
.PAWN
) &&
1440 (move.vanish
.length
> 0 && move.vanish
[0].p
== ChessRules
.PAWN
)
1447 return undefined; //default
1450 // Special case of en-passant captures: treated separately
1451 getEnpassantCaptures([x
, y
], shiftX
) {
1452 const color
= this.getColor(x
, y
);
1453 const oppCol
= ChessRules
.GetOppCol(color
);
1454 let enpassantMove
= null;
1457 this.epSquare
.x
== x
+ shiftX
&&
1458 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1459 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1461 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1462 this.board
[epx
][epy
] = oppCol
+ "p";
1463 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1464 this.board
[epx
][epy
] = "";
1465 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1466 enpassantMove
.vanish
[lastIdx
].x
= x
;
1468 return !!enpassantMove
? [enpassantMove
] : [];
1471 // Consider all potential promotions:
1472 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1473 let finalPieces
= [ChessRules
.PAWN
];
1474 const color
= this.getColor(x1
, y1
);
1475 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1476 if (x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == ""))
1478 // promotions arg: special override for Hiddenqueen variant
1479 if (promotions
) finalPieces
= promotions
;
1480 else if (this.pawnSpecs
.promotions
)
1481 finalPieces
= this.pawnSpecs
.promotions
;
1483 for (let piece
of finalPieces
) {
1484 const tr
= (piece
!= ChessRules
.PAWN
? { c: color
, p: piece
} : null);
1485 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
1489 // What are the pawn moves from square x,y ?
1490 getPotentialPawnMoves([x
, y
], promotions
) {
1491 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1492 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1493 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1494 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1495 const forward
= (color
== 'w' ? -1 : 1);
1497 // Pawn movements in shiftX direction:
1498 const getPawnMoves
= (shiftX
) => {
1500 // NOTE: next condition is generally true (no pawn on last rank)
1501 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1502 if (this.board
[x
+ shiftX
][y
] == "") {
1503 // One square forward (or backward)
1504 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1505 // Next condition because pawns on 1st rank can generally jump
1507 this.pawnSpecs
.twoSquares
&&
1511 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1514 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1518 shiftX
== forward
&&
1519 this.board
[x
+ 2 * shiftX
][y
] == ""
1522 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1524 this.pawnSpecs
.threeSquares
&&
1525 this.board
[x
+ 3 * shiftX
, y
] == ""
1527 // Three squares jump
1528 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1534 if (this.pawnSpecs
.canCapture
) {
1535 for (let shiftY
of [-1, 1]) {
1536 const yCoord
= this.computeY(y
+ shiftY
);
1537 if (yCoord
>= 0 && yCoord
< sizeY
) {
1539 this.board
[x
+ shiftX
][yCoord
] != "" &&
1540 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1542 !this.options
["zen"] ||
1543 this.getPiece(x
+ shiftX
, yCoord
) == ChessRules
.KING
1547 [x
, y
], [x
+ shiftX
, yCoord
],
1552 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1553 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1554 this.board
[x
- shiftX
][yCoord
] != "" &&
1555 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1557 !this.options
["zen"] ||
1558 this.getPiece(x
+ shiftX
, yCoord
) == ChessRules
.KING
1562 [x
, y
], [x
- shiftX
, yCoord
],
1573 let pMoves
= getPawnMoves(pawnShiftX
);
1574 if (this.pawnSpecs
.bidirectional
)
1575 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1577 if (this.hasEnpassant
) {
1578 // NOTE: backward en-passant captures are not considered
1579 // because no rules define them (for now).
1580 Array
.prototype.push
.apply(
1582 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1586 if (this.options
["zen"])
1587 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1592 // "castleInCheck" arg to let some variants castle under check
1593 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1594 const c
= this.getColor(x
, y
);
1597 const oppCol
= ChessRules
.GetOppCol(c
);
1601 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1602 const castlingKing
= this.board
[x
][y
].charAt(1);
1603 castlingCheck: for (
1606 castleSide
++ //large, then small
1608 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
) continue;
1609 // If this code is reached, rook and king are on initial position
1611 // NOTE: in some variants this is not a rook
1612 const rookPos
= this.castleFlags
[c
][castleSide
];
1613 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
1615 this.board
[x
][rookPos
] == "" ||
1616 this.getColor(x
, rookPos
) != c
||
1617 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1619 // Rook is not here, or changed color (see Benedict)
1622 // Nothing on the path of the king ? (and no checks)
1623 const finDist
= finalSquares
[castleSide
][0] - y
;
1624 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1628 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1630 this.board
[x
][i
] != "" &&
1631 // NOTE: next check is enough, because of chessboard constraints
1632 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1635 continue castlingCheck
;
1638 } while (i
!= finalSquares
[castleSide
][0]);
1639 // Nothing on the path to the rook?
1640 step
= (castleSide
== 0 ? -1 : 1);
1641 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1642 if (this.board
[x
][i
] != "") continue castlingCheck
;
1645 // Nothing on final squares, except maybe king and castling rook?
1646 for (i
= 0; i
< 2; i
++) {
1648 finalSquares
[castleSide
][i
] != rookPos
&&
1649 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1651 finalSquares
[castleSide
][i
] != y
||
1652 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1655 continue castlingCheck
;
1659 // If this code is reached, castle is valid
1665 y: finalSquares
[castleSide
][0],
1671 y: finalSquares
[castleSide
][1],
1677 // King might be initially disguised (Titan...)
1678 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1679 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1682 Math
.abs(y
- rookPos
) <= 2
1683 ? { x: x
, y: rookPos
}
1684 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1692 ////////////////////
1695 // Is (king at) given position under check by "color" ?
1696 underCheck([x
, y
], color
) {
1697 if (this.taking
|| this.options
["dark"]) return false;
1698 color
= color
|| ChessRules
.GetOppCol(this.getColor(x
, y
));
1699 const pieces
= this.pieces(color
);
1700 return Object
.keys(pieces
).some(p
=> {
1701 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1705 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1706 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1707 const range
= stepSpec
.range
;
1708 let explored
= {}; //for Cylinder mode
1709 outerLoop: for (let step
of steps
) {
1710 let rx
= x
- step
[0],
1711 ry
= this.computeY(y
- step
[1]);
1712 let stepCounter
= 1;
1714 this.onBoard(rx
, ry
) &&
1715 this.board
[rx
][ry
] == "" &&
1716 !explored
[rx
+ "." + ry
]
1718 explored
[rx
+ "." + ry
] = true;
1719 if (range
<= stepCounter
++) continue outerLoop
;
1721 ry
= this.computeY(ry
- step
[1]);
1724 this.onBoard(rx
, ry
) &&
1725 this.board
[rx
][ry
] != "" &&
1726 this.getPiece(rx
, ry
) == piece
&&
1727 this.getColor(rx
, ry
) == color
&&
1728 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1736 // Stop at first king found (TODO: multi-kings)
1737 searchKingPos(color
) {
1738 for (let i
=0; i
< this.size
.x
; i
++) {
1739 for (let j
=0; j
< this.size
.y
; j
++) {
1740 if (this.board
[i
][j
] == color
+ 'k') return [i
, j
];
1743 return [-1, -1]; //king not found
1746 filterValid(moves
) {
1747 if (moves
.length
== 0) return [];
1748 const color
= this.turn
;
1749 const oppCol
= ChessRules
.GetOppCol(color
);
1750 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1751 // Forbid moves either giving check or exploding opponent's king:
1752 const oppKingPos
= this.searchKingPos(oppCol
);
1753 moves
= moves
.filter(m
=> {
1755 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== ChessRules
.KING
) &&
1756 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= ChessRUles
.KING
)
1759 this.playOnBoard(m
);
1760 const res
= !this.underCheck(oppKingPos
, color
);
1761 this.undoOnBoard(m
);
1765 if (this.taking
|| this.options
["dark"]) return moves
;
1766 const kingPos
= this.searchKingPos(color
);
1767 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1768 return moves
.filter(m
=> {
1769 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1770 if (!filtered
[key
]) {
1771 this.playOnBoard(m
);
1772 let square
= kingPos
,
1773 res
= true; //a priori valid
1774 if (m
.vanish
.some(v
=> v
.p
== ChessRules
.KING
&& v
.c
== color
)) {
1775 // Search king in appear array:
1777 m
.appear
.findIndex(a
=> a
.p
== ChessRules
.KING
&& a
.c
== color
);
1778 if (newKingIdx
>= 0)
1779 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1782 res
&&= !this.underCheck(square
, oppCol
);
1783 this.undoOnBoard(m
);
1784 filtered
[key
] = res
;
1787 return filtered
[key
];
1794 // Aggregate flags into one object
1796 return this.castleFlags
;
1799 // Reverse operation
1800 disaggregateFlags(flags
) {
1801 this.castleFlags
= flags
;
1804 // Apply a move on board
1806 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1807 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1809 // Un-apply the played move
1811 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1812 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1815 updateCastleFlags(move) {
1816 // Update castling flags if start or arrive from/at rook/king locations
1817 move.appear
.concat(move.vanish
).forEach(psq
=> {
1819 this.board
[psq
.x
][psq
.y
] != "" &&
1820 this.getPiece(psq
.x
, psq
.y
) == ChessRules
.KING
1822 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1824 // NOTE: not "else if" because king can capture enemy rook...
1826 if (psq
.x
== 0) c
= 'b';
1827 else if (psq
.x
== this.size
.x
- 1) c
= 'w';
1829 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1830 if (fidx
>= 0) this.castleFlags
[c
][fidx
] = this.size
.y
;
1837 typeof move.start
.x
== "number" &&
1838 (!this.options
["teleport"] || this.subTurn
== 1)
1840 // OK, not a drop move
1843 // If flags already off, no need to re-check:
1844 Object
.keys(this.castleFlags
).some(c
=> {
1845 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1847 this.updateCastleFlags(move);
1849 const initSquare
= ChessRules
.CoordsToSquare(move.start
);
1851 this.options
["crazyhouse"] &&
1852 (!this.options
["rifle"] || !move.capture
)
1854 if (this.ispawn
[initSquare
]) {
1855 delete this.ispawn
[initSquare
];
1856 this.ispawn
[ChessRules
.CoordsToSquare(move.end
)] = true;
1859 move.vanish
[0].p
== ChessRules
.PAWN
&&
1860 move.appear
[0].p
!= ChessRules
.PAWN
1862 this.ispawn
[ChessRules
.CoordsToSquare(move.end
)] = true;
1866 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1867 if (this.hasReserve
) {
1868 const color
= this.turn
;
1869 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1870 // Something appears = dropped on board (some exceptions, Chakart...)
1871 const piece
= move.appear
[i
].p
;
1872 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1874 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1875 // Something vanish: add to reserve except if recycle & opponent
1876 const piece
= move.vanish
[i
].p
;
1877 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1878 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1885 if (this.hasEnpassant
) this.epSquare
= this.getEpSquare(move);
1886 this.playOnBoard(move);
1887 this.postPlay(move);
1891 const color
= this.turn
;
1892 const oppCol
= ChessRules
.GetOppCol(color
);
1893 if (this.options
["dark"]) this.updateEnlightened(true);
1894 if (this.options
["teleport"]) {
1896 this.subTurn
== 1 &&
1897 move.vanish
.length
> move.appear
.length
&&
1898 move.vanish
[move.vanish
.length
- 1].c
== color
1900 const v
= move.vanish
[move.vanish
.length
- 1];
1901 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
1905 this.captured
= null;
1907 if (this.options
["balance"]) {
1908 if (![1, 3].includes(this.movesCount
)) this.turn
= oppCol
;
1913 this.options
["doublemove"] &&
1914 this.movesCount
>= 1 &&
1917 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
1919 const oppKingPos
= this.searchKingPos(oppCol
);
1920 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
1931 // "Stop at the first move found"
1932 atLeastOneMove(color
) {
1933 color
= color
|| this.turn
;
1934 for (let i
= 0; i
< this.size
.x
; i
++) {
1935 for (let j
= 0; j
< this.size
.y
; j
++) {
1936 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1937 // TODO?: do not search all possible moves here
1938 const moves
= this.getPotentialMovesFrom([i
, j
]);
1939 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
1943 if (this.hasReserve
&& this.reserve
[color
]) {
1944 for (let p
of Object
.keys(this.reserve
[color
])) {
1945 const moves
= this.getDropMovesFrom([color
, p
]);
1946 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
1952 // What is the score ? (Interesting if game is over)
1953 getCurrentScore(move) {
1954 const color
= this.turn
;
1955 const oppCol
= ChessRules
.GetOppCol(color
);
1956 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
1957 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0) return "1/2";
1958 if (kingPos
[0][0] < 0) return (color
== "w" ? "0-1" : "1-0");
1959 if (kingPos
[1][0] < 0) return (color
== "w" ? "1-0" : "0-1");
1960 if (this.atLeastOneMove()) return "*";
1961 // No valid move: stalemate or checkmate?
1962 if (!this.underCheck(kingPos
, color
)) return "1/2";
1964 return (color
== "w" ? "0-1" : "1-0");
1967 // NOTE: quite suboptimal for eg. Benedict (TODO?)
1968 playVisual(move, r
) {
1969 move.vanish
.forEach(v
=> {
1970 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
1971 this.g_pieces
[v
.x
][v
.y
].remove();
1972 this.g_pieces
[v
.x
][v
.y
] = null;
1975 let container
= document
.getElementById(this.containerId
);
1976 if (!r
) r
= container
.getBoundingClientRect();
1977 const pieceWidth
= this.getPieceWidth(r
.width
);
1978 move.appear
.forEach(a
=> {
1979 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
]) return;
1980 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
1981 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
1982 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
1983 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
1984 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
1985 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
1986 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
1987 container
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
1991 playPlusVisual(move, r
) {
1992 this.playVisual(move, r
);
1994 this.afterPlay(move); //user method
1997 // Assumes reserve on top (usage case otherwise? TODO?)
1998 getReserveShift(c
, p
, r
) {
2001 for (let pi
of Object
.keys(this.reserve
[c
])) {
2002 if (this.reserve
[c
][pi
] == 0) continue;
2003 if (pi
== p
) ridx
= nbR
;
2006 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2007 return [ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2010 animate(move, callback
) {
2011 if (this.noAnimate
) {
2015 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2016 const dropMove
= (typeof i1
== "string");
2017 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2018 let startPiece
= startArray
[i1
][j1
];
2019 let container
= document
.getElementById(this.containerId
);
2020 const clonePiece
= (
2022 this.options
["rifle"] ||
2023 (this.options
["teleport"] && this.subTurn
== 2)
2026 startPiece
= startPiece
.cloneNode();
2027 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "0";
2028 if (this.options
["teleport"] && this.subTurn
== 2) {
2029 const pieces
= this.pieces();
2030 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2031 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2032 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2035 container
.appendChild(startPiece
);
2037 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2041 i1
== this.playerColor
? this.size
.x : 0,
2042 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2045 else startCoords
= [i1
, j1
];
2046 const r
= container
.getBoundingClientRect();
2047 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2049 if (dropMove
) rs
= this.getReserveShift(i1
, j1
, r
);
2051 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2052 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2053 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2054 const duration
= 0.2 + multFact
* 0.3;
2055 startPiece
.style
.transform
=
2056 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2057 startPiece
.style
.transitionDuration
= duration
+ "s";
2061 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "1";
2062 startPiece
.remove();
2070 playReceivedMove(moves
, callback
) {
2071 const launchAnimation
= () => {
2073 document
.getElementById(this.containerId
).getBoundingClientRect();
2074 const animateRec
= i
=> {
2075 this.animate(moves
[i
], () => {
2076 this.playVisual(moves
[i
], r
);
2077 this.play(moves
[i
]);
2078 if (i
< moves
.length
- 1) setTimeout(() => animateRec(i
+1), 300);
2084 const checkDisplayThenAnimate
= () => {
2085 if (boardContainer
.style
.display
== "none") {
2086 alert("New move! Let's go back to game...");
2087 document
.getElementById("gameInfos").style
.display
= "none";
2088 boardContainer
.style
.display
= "block";
2089 setTimeout(launchAnimation
, 700);
2091 else launchAnimation(); //focused user!
2093 let boardContainer
= document
.getElementById("boardContainer");
2094 if (!document
.hasFocus()) {
2095 window
.onfocus
= () => {
2096 window
.onfocus
= undefined;
2097 checkDisplayThenAnimate();
2100 else checkDisplayThenAnimate();