acee324a26f394eaaa40a7f16e55151cda5dcedd
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
.classList
.add("in-shadow");
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
.classList
.remove("in-shadow");
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 classes
= this.getSquareColorClass(ii
, jj
);
631 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
632 classes
+= " in-shadow";
633 // NOTE: x / y reversed because coordinates system is reversed.
636 id="${this.coordsToId([ii, jj])}"
643 board
+= "</g></svg>";
647 // Generally light square bottom-right; TODO: user-defined colors at least
648 getSquareColorClass(i
, j
) {
649 return ((i
+j
) % 2 == 0 ? "light-square": "dark-square");
654 // Refreshing: delete old pieces first
655 for (let i
=0; i
<this.size
.x
; i
++) {
656 for (let j
=0; j
<this.size
.y
; j
++) {
657 if (this.g_pieces
[i
][j
]) {
658 this.g_pieces
[i
][j
].remove();
659 this.g_pieces
[i
][j
] = null;
664 else this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
665 let container
= document
.getElementById(this.containerId
);
666 if (!r
) r
= container
.getBoundingClientRect();
667 const pieceWidth
= this.getPieceWidth(r
.width
);
668 for (let i
=0; i
< this.size
.x
; i
++) {
669 for (let j
=0; j
< this.size
.y
; j
++) {
671 this.board
[i
][j
] != "" &&
672 (!this.options
["dark"] || this.enlightened
[i
][j
])
674 const piece
= this.getPiece(i
, j
);
675 const color
= this.getColor(i
, j
);
676 this.g_pieces
[i
][j
] = document
.createElement("piece");
677 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
678 this.g_pieces
[i
][j
].classList
.add(color
== "w" ? "white" : "black");
679 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
680 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
681 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
682 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
683 container
.appendChild(this.g_pieces
[i
][j
]);
687 if (this.reserve
) this.re_drawReserve(['w', 'b'], r
);
690 // NOTE: assume !!this.reserve
691 re_drawReserve(colors
, r
) {
693 // Remove (old) reserve pieces
694 for (let c
of colors
) {
695 if (!this.reserve
[c
]) continue;
696 Object
.keys(this.reserve
[c
]).forEach(p
=> {
697 if (this.r_pieces
[c
][p
]) {
698 this.r_pieces
[c
][p
].remove();
699 delete this.r_pieces
[c
][p
];
700 const numId
= this.getReserveNumId(c
, p
);
701 document
.getElementById(numId
).remove();
704 let reservesDiv
= document
.getElementById("reserves_" + c
);
705 if (reservesDiv
) reservesDiv
.remove();
708 else this.r_pieces
= { 'w': {}, 'b': {} };
710 const container
= document
.getElementById(this.containerId
);
711 r
= container
.getBoundingClientRect();
713 const epsilon
= 1e-4; //fix display bug on Firefox at least
714 for (let c
of colors
) {
715 if (!this.reserve
[c
]) continue;
716 const nbR
= this.getNbReservePieces(c
);
717 if (nbR
== 0) continue;
718 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
720 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
721 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
722 let rcontainer
= document
.createElement("div");
723 rcontainer
.id
= "reserves_" + c
;
724 rcontainer
.classList
.add("reserves");
725 rcontainer
.style
.left
= i0
+ "px";
726 rcontainer
.style
.top
= j0
+ "px";
727 rcontainer
.style
.width
= (nbR
* sqResSize
) + "px";
728 rcontainer
.style
.height
= sqResSize
+ "px";
729 document
.getElementById("boardContainer").appendChild(rcontainer
);
730 for (let p
of Object
.keys(this.reserve
[c
])) {
731 if (this.reserve
[c
][p
] == 0) continue;
732 let r_cell
= document
.createElement("div");
733 r_cell
.id
= this.coordsToId([c
, p
]);
734 r_cell
.classList
.add("reserve-cell");
735 r_cell
.style
.width
= (sqResSize
- epsilon
) + "px";
736 r_cell
.style
.height
= (sqResSize
- epsilon
) + "px";
737 rcontainer
.appendChild(r_cell
);
738 let piece
= document
.createElement("piece");
739 const pieceSpec
= this.pieces(c
)[p
];
740 piece
.classList
.add(pieceSpec
["class"]);
741 piece
.classList
.add(c
== 'w' ? "white" : "black");
742 piece
.style
.width
= "100%";
743 piece
.style
.height
= "100%";
744 this.r_pieces
[c
][p
] = piece
;
745 r_cell
.appendChild(piece
);
746 let number
= document
.createElement("div");
747 number
.textContent
= this.reserve
[c
][p
];
748 number
.classList
.add("reserve-num");
749 number
.id
= this.getReserveNumId(c
, p
);
750 const fontSize
= "1.3em";
751 number
.style
.fontSize
= fontSize
;
752 number
.style
.fontSize
= fontSize
;
753 r_cell
.appendChild(number
);
759 updateReserve(color
, piece
, count
) {
760 const oldCount
= this.reserve
[color
][piece
];
761 this.reserve
[color
][piece
] = count
;
762 // Redrawing is much easier if count==0
763 if ([oldCount
, count
].includes(0)) this.re_drawReserve([color
]);
765 const numId
= this.getReserveNumId(color
, piece
);
766 document
.getElementById(numId
).textContent
= count
;
770 // After resize event: no need to destroy/recreate pieces
772 let container
= document
.getElementById(this.containerId
);
773 if (!container
) return; //useful at initial loading
774 const r
= container
.getBoundingClientRect();
775 const newRatio
= r
.width
/ r
.height
;
776 const aspectRatio
= this.size
.y
/ this.size
.x
;
777 let newWidth
= r
.width
,
778 newHeight
= r
.height
;
779 if (newRatio
> aspectRatio
) {
780 newWidth
= r
.height
* aspectRatio
;
781 container
.style
.width
= newWidth
+ "px";
783 else if (newRatio
< aspectRatio
) {
784 newHeight
= r
.width
/ aspectRatio
;
785 container
.style
.height
= newHeight
+ "px";
787 const newX
= (window
.innerWidth
- newWidth
) / 2;
788 container
.style
.left
= newX
+ "px";
789 const newY
= (window
.innerHeight
- newHeight
) / 2;
790 container
.style
.top
= newY
+ "px";
791 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
792 const pieceWidth
= this.getPieceWidth(newWidth
);
793 for (let i
=0; i
< this.size
.x
; i
++) {
794 for (let j
=0; j
< this.size
.y
; j
++) {
795 if (this.board
[i
][j
] != "") {
796 // NOTE: could also use CSS transform "scale"
797 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
798 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
799 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
800 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
804 if (this.reserve
) this.rescaleReserve(newR
);
808 const epsilon
= 1e-4;
809 for (let c
of ['w','b']) {
810 if (!this.reserve
[c
]) continue;
811 const nbR
= this.getNbReservePieces(c
);
812 if (nbR
== 0) continue;
813 // Resize container first
814 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
815 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
816 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
817 let rcontainer
= document
.getElementById("reserves_" + c
);
818 rcontainer
.style
.left
= i0
+ "px";
819 rcontainer
.style
.top
= j0
+ "px";
820 rcontainer
.style
.width
= (nbR
* sqResSize
) + "px";
821 rcontainer
.style
.height
= sqResSize
+ "px";
822 // And then reserve cells:
823 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
824 Object
.keys(this.reserve
[c
]).forEach(p
=> {
825 if (this.reserve
[c
][p
] == 0) return;
826 let r_cell
= document
.getElementById(this.coordsToId([c
, p
]));
827 r_cell
.style
.width
= (sqResSize
- epsilon
) + "px";
828 r_cell
.style
.height
= (sqResSize
- epsilon
) + "px";
833 // Return the absolute pixel coordinates given current position.
834 // Our coordinate system differs from CSS one (x <--> y).
835 // We return here the CSS coordinates (more useful).
836 getPixelPosition(i
, j
, r
) {
837 const sqSize
= this.getSquareWidth(r
.width
);
838 if (i
< 0 || j
< 0) return [0, 0]; //piece vanishes
839 const flipped
= (this.playerColor
== 'b');
840 const x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
841 const y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
846 let container
= document
.getElementById(this.containerId
);
848 const getOffset
= e
=> {
849 if (e
.clientX
) return {x: e
.clientX
, y: e
.clientY
}; //Mouse
850 let touchLocation
= null;
851 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
852 // Touch screen, dragstart
853 touchLocation
= e
.targetTouches
[0];
854 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
855 // Touch screen, dragend
856 touchLocation
= e
.changedTouches
[0];
858 return {x: touchLocation
.pageX
, y: touchLocation
.pageY
};
859 return [0, 0]; //Big trouble here =)
862 const centerOnCursor
= (piece
, e
) => {
863 const centerShift
= sqSize
/ 2;
864 const offset
= getOffset(e
);
865 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
866 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
871 startPiece
, curPiece
= null,
873 const mousedown
= (e
) => {
874 r
= container
.getBoundingClientRect();
875 sqSize
= this.getSquareWidth(r
.width
);
876 const square
= this.idToCoords(e
.target
.id
);
878 const [i
, j
] = square
;
879 const move = this.doClick([i
, j
]);
880 if (move) this.playPlusVisual(move);
882 if (typeof i
!= "number") startPiece
= this.r_pieces
[i
][j
];
883 else if (this.g_pieces
[i
][j
]) startPiece
= this.g_pieces
[i
][j
];
884 if (startPiece
&& this.canIplay(i
, j
)) {
886 start
= { x: i
, y: j
};
887 curPiece
= startPiece
.cloneNode();
888 curPiece
.style
.transform
= "none";
889 curPiece
.style
.zIndex
= 5;
890 curPiece
.style
.width
= sqSize
+ "px";
891 curPiece
.style
.height
= sqSize
+ "px";
892 centerOnCursor(curPiece
, e
);
893 document
.getElementById("boardContainer").appendChild(curPiece
);
894 startPiece
.style
.opacity
= "0.4";
895 container
.style
.cursor
= "none";
901 const mousemove
= (e
) => {
904 centerOnCursor(curPiece
, e
);
908 const mouseup
= (e
) => {
909 const newR
= container
.getBoundingClientRect();
910 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
915 const [x
, y
] = [start
.x
, start
.y
];
918 container
.style
.cursor
= "pointer";
919 startPiece
.style
.opacity
= "1";
920 const offset
= getOffset(e
);
921 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
922 const sq
= this.idToCoords(landingElt
.id
);
925 // NOTE: clearly suboptimal, but much easier, and not a big deal.
926 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
927 .filter(m
=> m
.end
.x
== i
&& m
.end
.y
== j
);
928 const moves
= this.filterValid(potentialMoves
);
929 if (moves
.length
>= 2) this.showChoices(moves
, r
);
930 else if (moves
.length
== 1) this.playPlusVisual(moves
[0], r
);
935 if ('onmousedown' in window
) {
936 document
.addEventListener("mousedown", mousedown
);
937 document
.addEventListener("mousemove", mousemove
);
938 document
.addEventListener("mouseup", mouseup
);
940 if ('ontouchstart' in window
) {
941 document
.addEventListener("touchstart", mousedown
);
942 document
.addEventListener("touchmove", mousemove
);
943 document
.addEventListener("touchend", mouseup
);
947 showChoices(moves
, r
) {
948 let container
= document
.getElementById(this.containerId
);
949 let choices
= document
.createElement("div");
950 choices
.id
= "choices";
951 choices
.style
.width
= r
.width
+ "px";
952 choices
.style
.height
= r
.height
+ "px";
953 choices
.style
.left
= r
.x
+ "px";
954 choices
.style
.top
= r
.y
+ "px";
955 container
.style
.opacity
= "0.5";
956 let boardContainer
= document
.getElementById("boardContainer");
957 boardContainer
.appendChild(choices
);
958 const squareWidth
= this.getSquareWidth(r
.width
);
959 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
960 const firstUpTop
= (r
.height
- squareWidth
) / 2;
961 const color
= moves
[0].appear
[0].c
;
962 const callback
= (m
) => {
963 container
.style
.opacity
= "1";
964 boardContainer
.removeChild(choices
);
965 this.playPlusVisual(m
, r
);
967 for (let i
=0; i
< moves
.length
; i
++) {
968 let choice
= document
.createElement("div");
969 choice
.classList
.add("choice");
970 choice
.style
.width
= squareWidth
+ "px";
971 choice
.style
.height
= squareWidth
+ "px";
972 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
973 choice
.style
.top
= firstUpTop
+ "px";
974 choice
.style
.backgroundColor
= "lightyellow";
975 choice
.onclick
= () => callback(moves
[i
]);
976 const piece
= document
.createElement("piece");
977 const pieceSpec
= this.pieces(color
)[moves
[i
].appear
[0].p
];
978 piece
.classList
.add(pieceSpec
["class"]);
979 piece
.classList
.add(color
== 'w' ? "white" : "black");
980 piece
.style
.width
= "100%";
981 piece
.style
.height
= "100%";
982 choice
.appendChild(piece
);
983 choices
.appendChild(choice
);
991 return { "x": 8, "y": 8 };
994 // Color of thing on square (i,j). 'undefined' if square is empty
996 return this.board
[i
][j
].charAt(0);
999 // Piece type on square (i,j). 'undefined' if square is empty
1001 return this.board
[i
][j
].charAt(1);
1004 // Get opponent color
1005 static GetOppCol(color
) {
1006 return (color
== "w" ? "b" : "w");
1009 // Can thing on square1 take thing on square2
1010 canTake([x1
, y1
], [x2
, y2
]) {
1013 (this.options
["recycle"] || this.options
["teleport"]) &&
1014 this.getPiece(x2
, y2
) != ChessRules
.KING
1016 (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
))
1020 // Is (x,y) on the chessboard?
1022 return x
>= 0 && x
< this.size
.x
&& y
>= 0 && y
< this.size
.y
;
1025 // Used in interface: 'side' arg == player color
1028 this.playerColor
== this.turn
&&
1030 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1031 (typeof x
== "string" && x
== this.turn
) //reserve
1036 ////////////////////////
1037 // PIECES SPECIFICATIONS
1040 const pawnShift
= (color
== "w" ? -1 : 1);
1044 steps: [[pawnShift
, 0]],
1046 attack: [[pawnShift
, 1], [pawnShift
, -1]]
1051 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1057 [1, 2], [1, -2], [-1, 2], [-1, -2],
1058 [2, 1], [-2, 1], [2, -1], [-2, -1]
1065 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1071 [0, 1], [0, -1], [1, 0], [-1, 0],
1072 [1, 1], [1, -1], [-1, 1], [-1, -1]
1079 [0, 1], [0, -1], [1, 0], [-1, 0],
1080 [1, 1], [1, -1], [-1, 1], [-1, -1]
1087 // Some pieces codes (for a clearer code)
1091 static get QUEEN() {
1098 ////////////////////
1101 // For Cylinder: get Y coordinate
1103 if (!this.options
["cylinder"]) return y
;
1104 let res
= y
% this.size
.y
;
1105 if (res
< 0) res
+= this.size
.y
;
1109 // Stop at the first capture found
1110 atLeastOneCapture(color
) {
1111 color
= color
|| this.turn
;
1112 const oppCol
= ChessRules
.GetOppCol(color
);
1113 for (let i
= 0; i
< this.size
.x
; i
++) {
1114 for (let j
= 0; j
< this.size
.y
; j
++) {
1115 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1116 const specs
= this.pieces(color
)[this.getPiece(i
, j
)];
1117 const steps
= specs
.attack
|| specs
.steps
;
1118 outerLoop: for (let step
of steps
) {
1119 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1120 let stepCounter
= 1;
1121 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1122 if (specs
.range
<= stepCounter
++) continue outerLoop
;
1124 jj
= this.computeY(jj
+ step
[1]);
1127 this.onBoard(ii
, jj
) &&
1128 this.getColor(ii
, jj
) == oppCol
&&
1130 [this.getBasicMove([i
, j
], [ii
, jj
])]
1142 getDropMovesFrom([c
, p
]) {
1143 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1144 // (but not necessarily otherwise)
1145 if (!this.reserve
[c
][p
] || this.reserve
[c
][p
] == 0) return [];
1147 for (let i
=0; i
<this.size
.x
; i
++) {
1148 for (let j
=0; j
<this.size
.y
; j
++) {
1149 // TODO: rather simplify this "if" and add post-condition: more general
1151 this.board
[i
][j
] == "" &&
1152 (!this.options
["dark"] || this.enlightened
[i
][j
]) &&
1154 p
!= ChessRules
.PAWN
||
1155 (c
== 'w' && i
< this.size
.x
- 1) ||
1161 start: {x: c
, y: p
},
1163 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1173 // All possible moves from selected square
1174 getPotentialMovesFrom(sq
, color
) {
1175 if (typeof sq
[0] == "string") return this.getDropMovesFrom(sq
);
1176 if (this.options
["madrasi"] && this.isImmobilized(sq
)) return [];
1177 const piece
= this.getPiece(sq
[0], sq
[1]);
1179 if (piece
== ChessRules
.PAWN
) moves
= this.getPotentialPawnMoves(sq
);
1180 else moves
= this.getPotentialMovesOf(piece
, sq
);
1182 piece
== ChessRules
.KING
&&
1184 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1186 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1188 return this.postProcessPotentialMoves(moves
);
1191 postProcessPotentialMoves(moves
) {
1192 if (moves
.length
== 0) return [];
1193 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1194 const oppCol
= ChessRules
.GetOppCol(color
);
1196 if (this.options
["capture"] && this.atLeastOneCapture()) {
1197 // Filter out non-capturing moves (not using m.vanish because of
1198 // self captures of Recycle and Teleport).
1199 moves
= moves
.filter(m
=> {
1201 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1202 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1207 if (this.options
["atomic"]) {
1208 moves
.forEach(m
=> {
1210 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1211 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1224 for (let step
of steps
) {
1225 let x
= m
.end
.x
+ step
[0];
1226 let y
= this.computeY(m
.end
.y
+ step
[1]);
1228 this.onBoard(x
, y
) &&
1229 this.board
[x
][y
] != "" &&
1230 this.getPiece(x
, y
) != ChessRules
.PAWN
1234 p: this.getPiece(x
, y
),
1235 c: this.getColor(x
, y
),
1242 if (!this.options
["rifle"]) m
.appear
.pop(); //nothin appears
1250 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1251 isImmobilized([x
, y
]) {
1252 const color
= this.getColor(x
, y
);
1253 const oppCol
= ChessRules
.GetOppCol(color
);
1254 const piece
= this.getPiece(x
, y
);
1255 const stepSpec
= this.pieces(color
)[piece
];
1256 let [steps
, range
] = [stepSpec
.attack
|| stepSpec
.steps
, stepSpec
.range
];
1257 outerLoop: for (let step
of steps
) {
1258 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1259 let stepCounter
= 1;
1260 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1261 if (range
<= stepCounter
++) continue outerLoop
;
1263 j
= this.computeY(j
+ step
[1]);
1266 this.onBoard(i
, j
) &&
1267 this.getColor(i
, j
) == oppCol
&&
1268 this.getPiece(i
, j
) == piece
1276 // Generic method to find possible moves of "sliding or jumping" pieces
1277 getPotentialMovesOf(piece
, [x
, y
]) {
1278 const color
= this.getColor(x
, y
);
1279 const stepSpec
= this.pieces(color
)[piece
];
1280 let [steps
, range
] = [stepSpec
.steps
, stepSpec
.range
];
1282 let explored
= {}; //for Cylinder mode
1283 outerLoop: for (let step
of steps
) {
1284 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1285 let stepCounter
= 1;
1287 this.onBoard(i
, j
) &&
1288 this.board
[i
][j
] == "" &&
1289 !explored
[i
+ "." + j
]
1291 explored
[i
+ "." + j
] = true;
1292 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1293 if (range
<= stepCounter
++) continue outerLoop
;
1295 j
= this.computeY(j
+ step
[1]);
1298 this.onBoard(i
, j
) &&
1300 !this.options
["zen"] ||
1301 this.getPiece(i
, j
) == ChessRules
.KING
||
1302 this.getColor(i
, j
) == color
//OK for Recycle and Teleport
1304 this.canTake([x
, y
], [i
, j
]) &&
1305 !explored
[i
+ "." + j
]
1307 explored
[i
+ "." + j
] = true;
1308 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1311 if (this.options
["zen"])
1312 Array
.prototype.push
.apply(moves
, this.getZenCaptures(x
, y
));
1316 getZenCaptures(x
, y
) {
1318 // Find reverse captures (opponent takes)
1319 const color
= this.getColor(x
, y
);
1320 const oppCol
= ChessRules
.GetOppCol(color
);
1321 const pieces
= this.pieces(oppCol
);
1322 Object
.keys(pieces
).forEach(p
=> {
1323 if (p
== ChessRules
.KING
) return; //king isn't captured this way
1324 const steps
= pieces
[p
].attack
|| pieces
[p
].steps
;
1325 const range
= pieces
[p
].range
;
1326 steps
.forEach(s
=> {
1327 // From x,y: revert step
1328 let [i
, j
] = [x
- s
[0], this.computeY(y
- s
[1])];
1329 let stepCounter
= 1;
1330 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1331 if (range
<= stepCounter
++) return;
1333 j
= this.computeY(j
- s
[1]);
1336 this.onBoard(i
, j
) &&
1337 this.getPiece(i
, j
) == p
&&
1338 this.getColor(i
, j
) == oppCol
&& //condition for Recycle & Teleport
1339 this.canTake([i
, j
], [x
, y
])
1341 if (this.getPiece(x
, y
) != ChessRules
.PAWN
)
1342 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1343 else this.addPawnMoves([x
, y
], [i
, j
], moves
);
1350 // Build a regular move from its initial and destination squares.
1351 // tr: transformation
1352 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1353 const initColor
= this.getColor(sx
, sy
);
1354 const initPiece
= this.board
[sx
][sy
].charAt(1);
1355 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1359 start: {x:sx
, y:sy
},
1363 !this.options
["rifle"] ||
1364 this.board
[ex
][ey
] == "" ||
1365 destColor
== initColor
//Recycle, Teleport
1371 c: !!tr
? tr
.c : initColor
,
1372 p: !!tr
? tr
.p : initPiece
1384 if (this.board
[ex
][ey
] != "") {
1389 c: this.getColor(ex
, ey
),
1390 p: this.board
[ex
][ey
].charAt(1)
1393 if (this.options
["rifle"])
1394 // Rifle captures are tricky in combination with Atomic etc,
1395 // so it's useful to mark the move :
1397 if (this.options
["cannibal"] && destColor
!= initColor
) {
1398 const lastIdx
= mv
.vanish
.length
- 1;
1399 if (mv
.appear
.length
>= 1) mv
.appear
[0].p
= mv
.vanish
[lastIdx
].p
;
1400 else if (this.options
["rifle"]) {
1406 p: mv
.vanish
[lastIdx
].p
1423 // En-passant square, if any
1424 getEpSquare(moveOrSquare
) {
1425 if (typeof moveOrSquare
=== "string") {
1426 const square
= moveOrSquare
;
1427 if (square
== "-") return undefined;
1428 return ChessRules
.SquareToCoords(square
);
1430 // Argument is a move:
1431 const move = moveOrSquare
;
1432 const s
= move.start
,
1436 Math
.abs(s
.x
- e
.x
) == 2 &&
1437 // Next conditions for variants like Atomic or Rifle, Recycle...
1438 (move.appear
.length
> 0 && move.appear
[0].p
== ChessRules
.PAWN
) &&
1439 (move.vanish
.length
> 0 && move.vanish
[0].p
== ChessRules
.PAWN
)
1446 return undefined; //default
1449 // Special case of en-passant captures: treated separately
1450 getEnpassantCaptures([x
, y
], shiftX
) {
1451 const color
= this.getColor(x
, y
);
1452 const oppCol
= ChessRules
.GetOppCol(color
);
1453 let enpassantMove
= null;
1456 this.epSquare
.x
== x
+ shiftX
&&
1457 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1458 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1460 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1461 this.board
[epx
][epy
] = oppCol
+ "p";
1462 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1463 this.board
[epx
][epy
] = "";
1464 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1465 enpassantMove
.vanish
[lastIdx
].x
= x
;
1467 return !!enpassantMove
? [enpassantMove
] : [];
1470 // Consider all potential promotions:
1471 addPawnMoves([x1
, y1
], [x2
, y2
], moves
, promotions
) {
1472 let finalPieces
= [ChessRules
.PAWN
];
1473 const color
= this.getColor(x1
, y1
);
1474 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1475 if (x2
== lastRank
&& (!this.options
["rifle"] || this.board
[x2
][y2
] == ""))
1477 // promotions arg: special override for Hiddenqueen variant
1478 if (promotions
) finalPieces
= promotions
;
1479 else if (this.pawnSpecs
.promotions
)
1480 finalPieces
= this.pawnSpecs
.promotions
;
1482 for (let piece
of finalPieces
) {
1483 const tr
= (piece
!= ChessRules
.PAWN
? { c: color
, p: piece
} : null);
1484 moves
.push(this.getBasicMove([x1
, y1
], [x2
, y2
], tr
));
1488 // What are the pawn moves from square x,y ?
1489 getPotentialPawnMoves([x
, y
], promotions
) {
1490 const color
= this.getColor(x
, y
); //this.turn doesn't work for Dark mode
1491 const [sizeX
, sizeY
] = [this.size
.x
, this.size
.y
];
1492 const pawnShiftX
= this.pawnSpecs
.directions
[color
];
1493 const firstRank
= (color
== "w" ? sizeX
- 1 : 0);
1494 const forward
= (color
== 'w' ? -1 : 1);
1496 // Pawn movements in shiftX direction:
1497 const getPawnMoves
= (shiftX
) => {
1499 // NOTE: next condition is generally true (no pawn on last rank)
1500 if (x
+ shiftX
>= 0 && x
+ shiftX
< sizeX
) {
1501 if (this.board
[x
+ shiftX
][y
] == "") {
1502 // One square forward (or backward)
1503 this.addPawnMoves([x
, y
], [x
+ shiftX
, y
], moves
, promotions
);
1504 // Next condition because pawns on 1st rank can generally jump
1506 this.pawnSpecs
.twoSquares
&&
1510 x
>= this.size
.x
- 1 - this.pawnSpecs
.initShift
['w']
1513 (color
== 'b' && x
<= this.pawnSpecs
.initShift
['b'])
1517 shiftX
== forward
&&
1518 this.board
[x
+ 2 * shiftX
][y
] == ""
1521 moves
.push(this.getBasicMove([x
, y
], [x
+ 2 * shiftX
, y
]));
1523 this.pawnSpecs
.threeSquares
&&
1524 this.board
[x
+ 3 * shiftX
, y
] == ""
1526 // Three squares jump
1527 moves
.push(this.getBasicMove([x
, y
], [x
+ 3 * shiftX
, y
]));
1533 if (this.pawnSpecs
.canCapture
) {
1534 for (let shiftY
of [-1, 1]) {
1535 const yCoord
= this.computeY(y
+ shiftY
);
1536 if (yCoord
>= 0 && yCoord
< sizeY
) {
1538 this.board
[x
+ shiftX
][yCoord
] != "" &&
1539 this.canTake([x
, y
], [x
+ shiftX
, yCoord
]) &&
1541 !this.options
["zen"] ||
1542 this.getPiece(x
+ shiftX
, yCoord
) == ChessRules
.KING
1546 [x
, y
], [x
+ shiftX
, yCoord
],
1551 this.pawnSpecs
.captureBackward
&& shiftX
== forward
&&
1552 x
- shiftX
>= 0 && x
- shiftX
< this.size
.x
&&
1553 this.board
[x
- shiftX
][yCoord
] != "" &&
1554 this.canTake([x
, y
], [x
- shiftX
, yCoord
]) &&
1556 !this.options
["zen"] ||
1557 this.getPiece(x
+ shiftX
, yCoord
) == ChessRules
.KING
1561 [x
, y
], [x
- shiftX
, yCoord
],
1572 let pMoves
= getPawnMoves(pawnShiftX
);
1573 if (this.pawnSpecs
.bidirectional
)
1574 pMoves
= pMoves
.concat(getPawnMoves(-pawnShiftX
));
1576 if (this.hasEnpassant
) {
1577 // NOTE: backward en-passant captures are not considered
1578 // because no rules define them (for now).
1579 Array
.prototype.push
.apply(
1581 this.getEnpassantCaptures([x
, y
], pawnShiftX
)
1585 if (this.options
["zen"])
1586 Array
.prototype.push
.apply(pMoves
, this.getZenCaptures(x
, y
));
1591 // "castleInCheck" arg to let some variants castle under check
1592 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1593 const c
= this.getColor(x
, y
);
1596 const oppCol
= ChessRules
.GetOppCol(c
);
1600 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1601 const castlingKing
= this.board
[x
][y
].charAt(1);
1602 castlingCheck: for (
1605 castleSide
++ //large, then small
1607 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
) continue;
1608 // If this code is reached, rook and king are on initial position
1610 // NOTE: in some variants this is not a rook
1611 const rookPos
= this.castleFlags
[c
][castleSide
];
1612 const castlingPiece
= this.board
[x
][rookPos
].charAt(1);
1614 this.board
[x
][rookPos
] == "" ||
1615 this.getColor(x
, rookPos
) != c
||
1616 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1618 // Rook is not here, or changed color (see Benedict)
1621 // Nothing on the path of the king ? (and no checks)
1622 const finDist
= finalSquares
[castleSide
][0] - y
;
1623 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1627 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1629 this.board
[x
][i
] != "" &&
1630 // NOTE: next check is enough, because of chessboard constraints
1631 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1634 continue castlingCheck
;
1637 } while (i
!= finalSquares
[castleSide
][0]);
1638 // Nothing on the path to the rook?
1639 step
= (castleSide
== 0 ? -1 : 1);
1640 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1641 if (this.board
[x
][i
] != "") continue castlingCheck
;
1644 // Nothing on final squares, except maybe king and castling rook?
1645 for (i
= 0; i
< 2; i
++) {
1647 finalSquares
[castleSide
][i
] != rookPos
&&
1648 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1650 finalSquares
[castleSide
][i
] != y
||
1651 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1654 continue castlingCheck
;
1658 // If this code is reached, castle is valid
1664 y: finalSquares
[castleSide
][0],
1670 y: finalSquares
[castleSide
][1],
1676 // King might be initially disguised (Titan...)
1677 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1678 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1681 Math
.abs(y
- rookPos
) <= 2
1682 ? { x: x
, y: rookPos
}
1683 : { x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1) }
1691 ////////////////////
1694 // Is (king at) given position under check by "color" ?
1695 underCheck([x
, y
], color
) {
1696 if (this.taking
|| this.options
["dark"]) return false;
1697 color
= color
|| ChessRules
.GetOppCol(this.getColor(x
, y
));
1698 const pieces
= this.pieces(color
);
1699 return Object
.keys(pieces
).some(p
=> {
1700 return this.isAttackedBy([x
, y
], p
, color
, pieces
[p
]);
1704 isAttackedBy([x
, y
], piece
, color
, stepSpec
) {
1705 const steps
= stepSpec
.attack
|| stepSpec
.steps
;
1706 const range
= stepSpec
.range
;
1707 let explored
= {}; //for Cylinder mode
1708 outerLoop: for (let step
of steps
) {
1709 let rx
= x
- step
[0],
1710 ry
= this.computeY(y
- step
[1]);
1711 let stepCounter
= 1;
1713 this.onBoard(rx
, ry
) &&
1714 this.board
[rx
][ry
] == "" &&
1715 !explored
[rx
+ "." + ry
]
1717 explored
[rx
+ "." + ry
] = true;
1718 if (range
<= stepCounter
++) continue outerLoop
;
1720 ry
= this.computeY(ry
- step
[1]);
1723 this.onBoard(rx
, ry
) &&
1724 this.board
[rx
][ry
] != "" &&
1725 this.getPiece(rx
, ry
) == piece
&&
1726 this.getColor(rx
, ry
) == color
&&
1727 (!this.options
["madrasi"] || !this.isImmobilized([rx
, ry
]))
1735 // Stop at first king found (TODO: multi-kings)
1736 searchKingPos(color
) {
1737 for (let i
=0; i
< this.size
.x
; i
++) {
1738 for (let j
=0; j
< this.size
.y
; j
++) {
1739 if (this.board
[i
][j
] == color
+ 'k') return [i
, j
];
1742 return [-1, -1]; //king not found
1745 filterValid(moves
) {
1746 if (moves
.length
== 0) return [];
1747 const color
= this.turn
;
1748 const oppCol
= ChessRules
.GetOppCol(color
);
1749 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1750 // Forbid moves either giving check or exploding opponent's king:
1751 const oppKingPos
= this.searchKingPos(oppCol
);
1752 moves
= moves
.filter(m
=> {
1754 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== ChessRules
.KING
) &&
1755 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= ChessRUles
.KING
)
1758 this.playOnBoard(m
);
1759 const res
= !this.underCheck(oppKingPos
, color
);
1760 this.undoOnBoard(m
);
1764 if (this.taking
|| this.options
["dark"]) return moves
;
1765 const kingPos
= this.searchKingPos(color
);
1766 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1767 return moves
.filter(m
=> {
1768 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1769 if (!filtered
[key
]) {
1770 this.playOnBoard(m
);
1771 let square
= kingPos
,
1772 res
= true; //a priori valid
1773 if (m
.vanish
.some(v
=> v
.p
== ChessRules
.KING
&& v
.c
== color
)) {
1774 // Search king in appear array:
1776 m
.appear
.findIndex(a
=> a
.p
== ChessRules
.KING
&& a
.c
== color
);
1777 if (newKingIdx
>= 0)
1778 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1781 res
&&= !this.underCheck(square
, oppCol
);
1782 this.undoOnBoard(m
);
1783 filtered
[key
] = res
;
1786 return filtered
[key
];
1793 // Aggregate flags into one object
1795 return this.castleFlags
;
1798 // Reverse operation
1799 disaggregateFlags(flags
) {
1800 this.castleFlags
= flags
;
1803 // Apply a move on board
1805 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1806 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1808 // Un-apply the played move
1810 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1811 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1814 updateCastleFlags(move) {
1815 // Update castling flags if start or arrive from/at rook/king locations
1816 move.appear
.concat(move.vanish
).forEach(psq
=> {
1818 this.board
[psq
.x
][psq
.y
] != "" &&
1819 this.getPiece(psq
.x
, psq
.y
) == ChessRules
.KING
1821 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1823 // NOTE: not "else if" because king can capture enemy rook...
1825 if (psq
.x
== 0) c
= 'b';
1826 else if (psq
.x
== this.size
.x
- 1) c
= 'w';
1828 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1829 if (fidx
>= 0) this.castleFlags
[c
][fidx
] = this.size
.y
;
1836 typeof move.start
.x
== "number" &&
1837 (!this.options
["teleport"] || this.subTurn
== 1)
1839 // OK, not a drop move
1842 // If flags already off, no need to re-check:
1843 Object
.keys(this.castleFlags
).some(c
=> {
1844 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1846 this.updateCastleFlags(move);
1848 const initSquare
= ChessRules
.CoordsToSquare(move.start
);
1850 this.options
["crazyhouse"] &&
1851 (!this.options
["rifle"] || !move.capture
)
1853 if (this.ispawn
[initSquare
]) {
1854 delete this.ispawn
[initSquare
];
1855 this.ispawn
[ChessRules
.CoordsToSquare(move.end
)] = true;
1858 move.vanish
[0].p
== ChessRules
.PAWN
&&
1859 move.appear
[0].p
!= ChessRules
.PAWN
1861 this.ispawn
[ChessRules
.CoordsToSquare(move.end
)] = true;
1865 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1866 if (this.hasReserve
) {
1867 const color
= this.turn
;
1868 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1869 // Something appears = dropped on board (some exceptions, Chakart...)
1870 const piece
= move.appear
[i
].p
;
1871 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1873 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1874 // Something vanish: add to reserve except if recycle & opponent
1875 const piece
= move.vanish
[i
].p
;
1876 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1877 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1884 if (this.hasEnpassant
) this.epSquare
= this.getEpSquare(move);
1885 this.playOnBoard(move);
1886 this.postPlay(move);
1890 const color
= this.turn
;
1891 const oppCol
= ChessRules
.GetOppCol(color
);
1892 if (this.options
["dark"]) this.updateEnlightened(true);
1893 if (this.options
["teleport"]) {
1895 this.subTurn
== 1 &&
1896 move.vanish
.length
> move.appear
.length
&&
1897 move.vanish
[move.vanish
.length
- 1].c
== color
1899 const v
= move.vanish
[move.vanish
.length
- 1];
1900 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
1904 this.captured
= null;
1906 if (this.options
["balance"]) {
1907 if (![1, 3].includes(this.movesCount
)) this.turn
= oppCol
;
1912 this.options
["doublemove"] &&
1913 this.movesCount
>= 1 &&
1916 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
1918 const oppKingPos
= this.searchKingPos(oppCol
);
1919 if (oppKingPos
[0] >= 0 && !this.underCheck(oppKingPos
, color
)) {
1930 // "Stop at the first move found"
1931 atLeastOneMove(color
) {
1932 color
= color
|| this.turn
;
1933 for (let i
= 0; i
< this.size
.x
; i
++) {
1934 for (let j
= 0; j
< this.size
.y
; j
++) {
1935 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1936 // TODO?: do not search all possible moves here
1937 const moves
= this.getPotentialMovesFrom([i
, j
]);
1938 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
1942 if (this.hasReserve
&& this.reserve
[color
]) {
1943 for (let p
of Object
.keys(this.reserve
[color
])) {
1944 const moves
= this.getDropMovesFrom([color
, p
]);
1945 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1)) return true;
1951 // What is the score ? (Interesting if game is over)
1952 getCurrentScore(move) {
1953 const color
= this.turn
;
1954 const oppCol
= ChessRules
.GetOppCol(color
);
1955 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
1956 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0) return "1/2";
1957 if (kingPos
[0][0] < 0) return (color
== "w" ? "0-1" : "1-0");
1958 if (kingPos
[1][0] < 0) return (color
== "w" ? "1-0" : "0-1");
1959 if (this.atLeastOneMove()) return "*";
1960 // No valid move: stalemate or checkmate?
1961 if (!this.underCheck(kingPos
, color
)) return "1/2";
1963 return (color
== "w" ? "0-1" : "1-0");
1966 // NOTE: quite suboptimal for eg. Benedict (TODO?)
1967 playVisual(move, r
) {
1968 move.vanish
.forEach(v
=> {
1969 if (!this.enlightened
|| this.enlightened
[v
.x
][v
.y
]) {
1970 this.g_pieces
[v
.x
][v
.y
].remove();
1971 this.g_pieces
[v
.x
][v
.y
] = null;
1974 let container
= document
.getElementById(this.containerId
);
1975 if (!r
) r
= container
.getBoundingClientRect();
1976 const pieceWidth
= this.getPieceWidth(r
.width
);
1977 move.appear
.forEach(a
=> {
1978 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
]) return;
1979 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
1980 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
1981 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
1982 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
1983 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
1984 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
1985 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
1986 container
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
1990 playPlusVisual(move, r
) {
1991 this.playVisual(move, r
);
1993 this.afterPlay(move); //user method
1996 // Assumes reserve on top (usage case otherwise? TODO?)
1997 getReserveShift(c
, p
, r
) {
2000 for (let pi
of Object
.keys(this.reserve
[c
])) {
2001 if (this.reserve
[c
][pi
] == 0) continue;
2002 if (pi
== p
) ridx
= nbR
;
2005 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
2006 return [ridx
* rsqSize
, rsqSize
]; //slightly inaccurate... TODO?
2009 animate(move, callback
) {
2010 if (this.noAnimate
) {
2014 const [i1
, j1
] = [move.start
.x
, move.start
.y
];
2015 const dropMove
= (typeof i1
== "string");
2016 const startArray
= (dropMove
? this.r_pieces : this.g_pieces
);
2017 let startPiece
= startArray
[i1
][j1
];
2018 let container
= document
.getElementById(this.containerId
);
2019 const clonePiece
= (
2021 this.options
["rifle"] ||
2022 (this.options
["teleport"] && this.subTurn
== 2)
2025 startPiece
= startPiece
.cloneNode();
2026 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "0";
2027 if (this.options
["teleport"] && this.subTurn
== 2) {
2028 const pieces
= this.pieces();
2029 const startCode
= (dropMove
? j1 : this.getPiece(i1
, j1
));
2030 startPiece
.classList
.remove(pieces
[startCode
]["class"]);
2031 startPiece
.classList
.add(pieces
[this.captured
.p
]["class"]);
2034 container
.appendChild(startPiece
);
2036 const [i2
, j2
] = [move.end
.x
, move.end
.y
];
2040 i1
== this.playerColor
? this.size
.x : 0,
2041 this.size
.y
/ 2 //not trying to be accurate here... (TODO?)
2044 else startCoords
= [i1
, j1
];
2045 const r
= container
.getBoundingClientRect();
2046 const arrival
= this.getPixelPosition(i2
, j2
, r
); //TODO: arrival on drop?
2048 if (dropMove
) rs
= this.getReserveShift(i1
, j1
, r
);
2050 Math
.sqrt((startCoords
[0] - i2
) ** 2 + (startCoords
[1] - j2
) ** 2);
2051 const maxDist
= Math
.sqrt((this.size
.x
- 1)** 2 + (this.size
.y
- 1) ** 2);
2052 const multFact
= (distance
- 1) / (maxDist
- 1); //1 == minDist
2053 const duration
= 0.2 + multFact
* 0.3;
2054 startPiece
.style
.transform
=
2055 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2056 startPiece
.style
.transitionDuration
= duration
+ "s";
2060 if (this.options
["rifle"]) startArray
[i1
][j1
].style
.opacity
= "1";
2061 startPiece
.remove();
2069 playReceivedMove(moves
, callback
) {
2070 const launchAnimation
= () => {
2072 document
.getElementById(this.containerId
).getBoundingClientRect();
2073 const animateRec
= i
=> {
2074 this.animate(moves
[i
], () => {
2075 this.playVisual(moves
[i
], r
);
2076 this.play(moves
[i
]);
2077 if (i
< moves
.length
- 1) setTimeout(() => animateRec(i
+1), 300);
2083 const checkDisplayThenAnimate
= () => {
2084 if (boardContainer
.style
.display
== "none") {
2085 alert("New move! Let's go back to game...");
2086 document
.getElementById("gameInfos").style
.display
= "none";
2087 boardContainer
.style
.display
= "block";
2088 setTimeout(launchAnimation
, 700);
2090 else launchAnimation(); //focused user!
2092 let boardContainer
= document
.getElementById("boardContainer");
2093 if (document
.hidden
) {
2094 document
.onvisibilitychange
= () => {
2095 document
.onvisibilitychange
= undefined;
2096 checkDisplayThenAnimate();
2099 else checkDisplayThenAnimate();