30e9ee5fc475650d4d13d36b729b9b321e17bbd1
1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // NOTE: x coords: top to bottom (white perspective); y: left to right
7 // NOTE: ChessRules is aliased as window.C, and variants as window.V
8 export default class ChessRules
{
10 static get Aliases() {
11 return {'C': ChessRules
};
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
17 // Some variants have specific options, like the number of pawns in Monster,
18 // or the board size for Pandemonium.
19 // Users can generally select a randomness level from 0 to 2.
20 static get Options() {
24 variable: "randomness",
27 {label: "Deterministic", value: 0},
28 {label: "Symmetric random", value: 1},
29 {label: "Asymmetric random", value: 2}
34 label: "Capture king",
40 label: "Falling pawn",
46 // Game modifiers (using "elementary variants"). Default: false
49 "balance", //takes precedence over doublemove & progressive
53 "cylinder", //ok with all
57 "progressive", //(natural) priority over doublemove
66 get pawnPromotions() {
67 return ['q', 'r', 'n', 'b'];
70 // Some variants don't have flags:
79 // En-passant captures allowed?
86 !!this.options
["crazyhouse"] ||
87 (!!this.options
["recycle"] && !this.options
["teleport"])
92 return !!this.options
["dark"];
95 // Some variants use click infos:
97 if (typeof coords
.x
!= "number")
98 return null; //click on reserves
100 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
101 this.board
[coords
.x
][coords
.y
] == ""
104 start: {x: this.captured
.x
, y: this.captured
.y
},
109 c: this.captured
.c
, //this.turn,
115 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
124 // 3a --> {x:3, y:10}
125 static SquareToCoords(sq
) {
126 return ArrayFun
.toObject(["x", "y"],
127 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
130 // {x:11, y:12} --> bc
131 static CoordsToSquare(cd
) {
132 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
136 if (typeof cd
.x
== "number") {
138 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
142 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
145 idToCoords(targetId
) {
147 return null; //outside page, maybe...
148 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
150 idParts
.length
< 2 ||
151 idParts
[0] != this.containerId
||
152 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
156 const squares
= idParts
[1].split('-');
157 if (squares
[0] == "sq")
158 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
159 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
160 return {x: squares
[1], y: squares
[2]};
166 // Turn "wb" into "B" (for FEN)
168 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
171 // Turn "p" into "bp" (for board)
173 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
176 // Setup the initial random-or-not (asymmetric-or-not) position
177 genRandInitFen(seed
) {
178 Random
.setSeed(seed
);
180 let fen
, flags
= "0707";
181 if (!this.options
.randomness
)
183 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
187 let pieces
= {w: new Array(8), b: new Array(8)};
189 // Shuffle pieces on first (and last rank if randomness == 2)
190 for (let c
of ["w", "b"]) {
191 if (c
== 'b' && this.options
.randomness
== 1) {
192 pieces
['b'] = pieces
['w'];
197 let positions
= ArrayFun
.range(8);
199 // Get random squares for bishops
200 let randIndex
= 2 * Random
.randInt(4);
201 const bishop1Pos
= positions
[randIndex
];
202 // The second bishop must be on a square of different color
203 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
204 const bishop2Pos
= positions
[randIndex_tmp
];
205 // Remove chosen squares
206 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
207 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
209 // Get random squares for knights
210 randIndex
= Random
.randInt(6);
211 const knight1Pos
= positions
[randIndex
];
212 positions
.splice(randIndex
, 1);
213 randIndex
= Random
.randInt(5);
214 const knight2Pos
= positions
[randIndex
];
215 positions
.splice(randIndex
, 1);
217 // Get random square for queen
218 randIndex
= Random
.randInt(4);
219 const queenPos
= positions
[randIndex
];
220 positions
.splice(randIndex
, 1);
222 // Rooks and king positions are now fixed,
223 // because of the ordering rook-king-rook
224 const rook1Pos
= positions
[0];
225 const kingPos
= positions
[1];
226 const rook2Pos
= positions
[2];
228 // Finally put the shuffled pieces in the board array
229 pieces
[c
][rook1Pos
] = "r";
230 pieces
[c
][knight1Pos
] = "n";
231 pieces
[c
][bishop1Pos
] = "b";
232 pieces
[c
][queenPos
] = "q";
233 pieces
[c
][kingPos
] = "k";
234 pieces
[c
][bishop2Pos
] = "b";
235 pieces
[c
][knight2Pos
] = "n";
236 pieces
[c
][rook2Pos
] = "r";
237 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
240 pieces
["b"].join("") +
241 "/pppppppp/8/8/8/8/PPPPPPPP/" +
242 pieces
["w"].join("").toUpperCase() +
246 // Add turn + flags + enpassant (+ reserve)
249 parts
.push(`"flags":"${flags}"`);
250 if (this.hasEnpassant
)
251 parts
.push('"enpassant":"-"');
253 parts
.push('"reserve":"000000000000"');
254 if (this.options
["crazyhouse"])
255 parts
.push('"ispawn":"-"');
256 if (parts
.length
>= 1)
257 fen
+= " {" + parts
.join(",") + "}";
261 // "Parse" FEN: just return untransformed string data
263 const fenParts
= fen
.split(" ");
265 position: fenParts
[0],
267 movesCount: fenParts
[2]
269 if (fenParts
.length
> 3)
270 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
274 // Return current fen (game state)
277 this.getPosition() + " " +
278 this.getTurnFen() + " " +
283 parts
.push(`"flags":"${this.getFlagsFen()}"`);
284 if (this.hasEnpassant
)
285 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
287 parts
.push(`"reserve":"${this.getReserveFen()}"`);
288 if (this.options
["crazyhouse"])
289 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
290 if (parts
.length
>= 1)
291 fen
+= " {" + parts
.join(",") + "}";
295 static FenEmptySquares(count
) {
296 // if more than 9 consecutive free spaces, break the integer,
297 // otherwise FEN parsing will fail.
300 // Most boards of size < 18:
302 return "9" + (count
- 9);
304 return "99" + (count
- 18);
307 // Position part of the FEN string
310 for (let i
= 0; i
< this.size
.y
; i
++) {
312 for (let j
= 0; j
< this.size
.x
; j
++) {
313 if (this.board
[i
][j
] == "")
316 if (emptyCount
> 0) {
317 // Add empty squares in-between
318 position
+= C
.FenEmptySquares(emptyCount
);
321 position
+= this.board2fen(this.board
[i
][j
]);
326 position
+= C
.FenEmptySquares(emptyCount
);
327 if (i
< this.size
.y
- 1)
328 position
+= "/"; //separate rows
337 // Flags part of the FEN string
339 return ["w", "b"].map(c
=> {
340 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
344 // Enpassant part of the FEN string
347 return "-"; //no en-passant
348 return C
.CoordsToSquare(this.epSquare
);
353 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
358 const squares
= Object
.keys(this.ispawn
);
359 if (squares
.length
== 0)
361 return squares
.join(",");
364 // Set flags from fen (castle: white a,h then black a,h)
367 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
368 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
375 constructor(o
, genFenOnly
) {
376 this.options
= o
.options
;
377 // Fill missing options (always the case if random challenge)
378 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
379 if (this.options
[opt
.variable
] === undefined)
380 this.options
[opt
.variable
] = opt
.defaut
;
383 // This object will be used only for initial FEN generation
385 this.playerColor
= o
.color
;
386 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
388 // Fen string fully describes the game state
390 o
.fen
= this.genRandInitFen(o
.seed
);
391 const fenParsed
= this.parseFen(o
.fen
);
392 this.board
= this.getBoard(fenParsed
.position
);
393 this.turn
= fenParsed
.turn
;
394 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
395 this.setOtherVariables(fenParsed
);
397 // Graphical (can use variables defined above)
398 this.containerId
= o
.element
;
399 this.graphicalInit();
402 // Turn position fen into double array ["wb","wp","bk",...]
404 const rows
= position
.split("/");
405 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
406 for (let i
= 0; i
< rows
.length
; i
++) {
408 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
409 const character
= rows
[i
][indexInRow
];
410 const num
= parseInt(character
, 10);
411 // If num is a number, just shift j:
414 // Else: something at position i,j
416 board
[i
][j
++] = this.fen2board(character
);
422 // Some additional variables from FEN (variant dependant)
423 setOtherVariables(fenParsed
) {
424 // Set flags and enpassant:
426 this.setFlags(fenParsed
.flags
);
427 if (this.hasEnpassant
)
428 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
430 this.initReserves(fenParsed
.reserve
);
431 if (this.options
["crazyhouse"])
432 this.initIspawn(fenParsed
.ispawn
);
433 this.subTurn
= 1; //may be unused
434 if (this.options
["teleport"]) {
435 this.subTurnTeleport
= 1;
436 this.captured
= null;
438 if (this.options
["dark"]) {
439 // Setup enlightened: squares reachable by player side
440 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
441 this.updateEnlightened();
445 updateEnlightened() {
446 this.oldEnlightened
= this.enlightened
;
447 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
448 // Add pieces positions + all squares reachable by moves (includes Zen):
449 for (let x
=0; x
<this.size
.x
; x
++) {
450 for (let y
=0; y
<this.size
.y
; y
++) {
451 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
453 this.enlightened
[x
][y
] = true;
454 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
455 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
461 this.enlightEnpassant();
464 // Include square of the en-passant capturing square:
466 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
467 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
468 for (let step
of steps
) {
469 const x
= this.epSquare
.x
- step
[0],
470 y
= this.getY(this.epSquare
.y
- step
[1]);
472 this.onBoard(x
, y
) &&
473 this.getColor(x
, y
) == this.playerColor
&&
474 this.getPieceType(x
, y
) == "p"
476 this.enlightened
[x
][this.epSquare
.y
] = true;
482 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
483 initReserves(reserveStr
) {
484 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
485 this.reserve
= { w: {}, b: {} };
486 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
487 const L
= pieceName
.length
;
488 for (let i
of ArrayFun
.range(2 * L
)) {
490 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
492 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
496 initIspawn(ispawnStr
) {
497 if (ispawnStr
!= "-")
498 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
503 getNbReservePieces(color
) {
505 Object
.values(this.reserve
[color
]).reduce(
506 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
510 getRankInReserve(c
, p
) {
511 const pieces
= Object
.keys(this.pieces());
512 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
513 let toTest
= pieces
.slice(0, lastIndex
);
514 return toTest
.reduce(
515 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
521 getPieceWidth(rwidth
) {
522 return (rwidth
/ this.size
.y
);
525 getReserveSquareSize(rwidth
, nbR
) {
526 const sqSize
= this.getPieceWidth(rwidth
);
527 return Math
.min(sqSize
, rwidth
/ nbR
);
530 getReserveNumId(color
, piece
) {
531 return `${this.containerId}|rnum-${color}${piece}`;
535 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
536 window
.onresize
= () => this.re_drawBoardElements();
537 this.re_drawBoardElements();
538 this.initMouseEvents();
540 document
.getElementById(this.containerId
).querySelector(".chessboard");
543 re_drawBoardElements() {
544 const board
= this.getSvgChessboard();
545 const oppCol
= C
.GetOppCol(this.playerColor
);
547 document
.getElementById(this.containerId
).querySelector(".chessboard");
548 chessboard
.innerHTML
= "";
549 chessboard
.insertAdjacentHTML('beforeend', board
);
550 // Compare window ratio width / height to aspectRatio:
551 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
552 let cbWidth
, cbHeight
;
553 if (windowRatio
<= this.size
.ratio
) {
554 // Limiting dimension is width:
555 cbWidth
= Math
.min(window
.innerWidth
, 767);
556 cbHeight
= cbWidth
/ this.size
.ratio
;
559 // Limiting dimension is height:
560 cbHeight
= Math
.min(window
.innerHeight
, 767);
561 cbWidth
= cbHeight
* this.size
.ratio
;
563 if (this.hasReserve
) {
564 const sqSize
= cbWidth
/ this.size
.y
;
565 // NOTE: allocate space for reserves (up/down) even if they are empty
566 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
567 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
568 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
569 cbWidth
= cbHeight
* this.size
.ratio
;
572 chessboard
.style
.width
= cbWidth
+ "px";
573 chessboard
.style
.height
= cbHeight
+ "px";
574 // Center chessboard:
575 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
576 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
577 chessboard
.style
.left
= spaceLeft
+ "px";
578 chessboard
.style
.top
= spaceTop
+ "px";
579 // Give sizes instead of recomputing them,
580 // because chessboard might not be drawn yet.
589 // Get SVG board (background, no pieces)
591 const flipped
= (this.playerColor
== 'b');
595 class="chessboard_SVG">`;
596 for (let i
=0; i
< this.size
.x
; i
++) {
597 for (let j
=0; j
< this.size
.y
; j
++) {
598 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
599 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
600 let classes
= this.getSquareColorClass(ii
, jj
);
601 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
602 classes
+= " in-shadow";
603 // NOTE: x / y reversed because coordinates system is reversed.
607 id="${this.coordsToId({x: ii, y: jj})}"
619 // Generally light square bottom-right
620 getSquareColorClass(x
, y
) {
621 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
626 // Refreshing: delete old pieces first
627 for (let i
=0; i
<this.size
.x
; i
++) {
628 for (let j
=0; j
<this.size
.y
; j
++) {
629 if (this.g_pieces
[i
][j
]) {
630 this.g_pieces
[i
][j
].remove();
631 this.g_pieces
[i
][j
] = null;
637 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
639 document
.getElementById(this.containerId
).querySelector(".chessboard");
641 r
= chessboard
.getBoundingClientRect();
642 const pieceWidth
= this.getPieceWidth(r
.width
);
643 for (let i
=0; i
< this.size
.x
; i
++) {
644 for (let j
=0; j
< this.size
.y
; j
++) {
645 if (this.board
[i
][j
] != "") {
646 const color
= this.getColor(i
, j
);
647 const piece
= this.getPiece(i
, j
);
648 this.g_pieces
[i
][j
] = document
.createElement("piece");
649 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
650 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
651 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
652 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
653 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
654 // Translate coordinates to use chessboard as reference:
655 this.g_pieces
[i
][j
].style
.transform
=
656 `translate(${ip - r.x}px,${jp - r.y}px)`;
657 if (this.enlightened
&& !this.enlightened
[i
][j
])
658 this.g_pieces
[i
][j
].classList
.add("hidden");
659 chessboard
.appendChild(this.g_pieces
[i
][j
]);
664 this.re_drawReserve(['w', 'b'], r
);
667 // NOTE: assume !!this.reserve
668 re_drawReserve(colors
, r
) {
670 // Remove (old) reserve pieces
671 for (let c
of colors
) {
672 if (!this.reserve
[c
])
674 Object
.keys(this.reserve
[c
]).forEach(p
=> {
675 if (this.r_pieces
[c
][p
]) {
676 this.r_pieces
[c
][p
].remove();
677 delete this.r_pieces
[c
][p
];
678 const numId
= this.getReserveNumId(c
, p
);
679 document
.getElementById(numId
).remove();
682 let reservesDiv
= document
.getElementById("reserves_" + c
);
684 reservesDiv
.remove();
688 this.r_pieces
= { w: {}, b: {} };
689 let container
= document
.getElementById(this.containerId
);
691 r
= container
.querySelector(".chessboard").getBoundingClientRect();
692 for (let c
of colors
) {
693 if (!this.reserve
[c
])
695 const nbR
= this.getNbReservePieces(c
);
698 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
700 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
701 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
702 let rcontainer
= document
.createElement("div");
703 rcontainer
.id
= "reserves_" + c
;
704 rcontainer
.classList
.add("reserves");
705 rcontainer
.style
.left
= i0
+ "px";
706 rcontainer
.style
.top
= j0
+ "px";
707 // NOTE: +1 fix display bug on Firefox at least
708 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
709 rcontainer
.style
.height
= sqResSize
+ "px";
710 container
.appendChild(rcontainer
);
711 for (let p
of Object
.keys(this.reserve
[c
])) {
712 if (this.reserve
[c
][p
] == 0)
714 let r_cell
= document
.createElement("div");
715 r_cell
.id
= this.coordsToId({x: c
, y: p
});
716 r_cell
.classList
.add("reserve-cell");
717 r_cell
.style
.width
= sqResSize
+ "px";
718 r_cell
.style
.height
= sqResSize
+ "px";
719 rcontainer
.appendChild(r_cell
);
720 let piece
= document
.createElement("piece");
721 const pieceSpec
= this.pieces()[p
];
722 piece
.classList
.add(pieceSpec
["class"]);
723 piece
.classList
.add(C
.GetColorClass(c
));
724 piece
.style
.width
= "100%";
725 piece
.style
.height
= "100%";
726 this.r_pieces
[c
][p
] = piece
;
727 r_cell
.appendChild(piece
);
728 let number
= document
.createElement("div");
729 number
.textContent
= this.reserve
[c
][p
];
730 number
.classList
.add("reserve-num");
731 number
.id
= this.getReserveNumId(c
, p
);
732 const fontSize
= "1.3em";
733 number
.style
.fontSize
= fontSize
;
734 number
.style
.fontSize
= fontSize
;
735 r_cell
.appendChild(number
);
741 updateReserve(color
, piece
, count
) {
742 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
743 piece
= "k"; //capturing cannibal king: back to king form
744 const oldCount
= this.reserve
[color
][piece
];
745 this.reserve
[color
][piece
] = count
;
746 // Redrawing is much easier if count==0
747 if ([oldCount
, count
].includes(0))
748 this.re_drawReserve([color
]);
750 const numId
= this.getReserveNumId(color
, piece
);
751 document
.getElementById(numId
).textContent
= count
;
755 // Apply diff this.enlightened --> oldEnlightened on board
756 graphUpdateEnlightened() {
758 document
.getElementById(this.containerId
).querySelector(".chessboard");
759 const r
= chessboard
.getBoundingClientRect();
760 const pieceWidth
= this.getPieceWidth(r
.width
);
761 for (let x
=0; x
<this.size
.x
; x
++) {
762 for (let y
=0; y
<this.size
.y
; y
++) {
763 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
764 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
765 elt
.classList
.add("in-shadow");
766 if (this.g_pieces
[x
][y
])
767 this.g_pieces
[x
][y
].classList
.add("hidden");
769 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
770 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
771 elt
.classList
.remove("in-shadow");
772 if (this.g_pieces
[x
][y
])
773 this.g_pieces
[x
][y
].classList
.remove("hidden");
779 // Resize board: no need to destroy/recreate pieces
782 document
.getElementById(this.containerId
).querySelector(".chessboard");
783 const r
= chessboard
.getBoundingClientRect();
784 const multFact
= (mode
== "up" ? 1.05 : 0.95);
785 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
787 if (newWidth
> window
.innerWidth
) {
788 newWidth
= window
.innerWidth
;
789 newHeight
= newWidth
/ this.size
.ratio
;
791 if (newHeight
> window
.innerHeight
) {
792 newHeight
= window
.innerHeight
;
793 newWidth
= newHeight
* this.size
.ratio
;
795 chessboard
.style
.width
= newWidth
+ "px";
796 chessboard
.style
.height
= newHeight
+ "px";
797 const newX
= (window
.innerWidth
- newWidth
) / 2;
798 chessboard
.style
.left
= newX
+ "px";
799 const newY
= (window
.innerHeight
- newHeight
) / 2;
800 chessboard
.style
.top
= newY
+ "px";
801 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
802 const pieceWidth
= this.getPieceWidth(newWidth
);
803 // NOTE: next "if" for variants which use squares filling
804 // instead of "physical", moving pieces
806 for (let i
=0; i
< this.size
.x
; i
++) {
807 for (let j
=0; j
< this.size
.y
; j
++) {
808 if (this.g_pieces
[i
][j
]) {
809 // NOTE: could also use CSS transform "scale"
810 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
811 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
812 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
813 // Translate coordinates to use chessboard as reference:
814 this.g_pieces
[i
][j
].style
.transform
=
815 `translate(${ip - newX}px,${jp - newY}px)`;
821 this.rescaleReserve(newR
);
825 for (let c
of ['w','b']) {
826 if (!this.reserve
[c
])
828 const nbR
= this.getNbReservePieces(c
);
831 // Resize container first
832 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
833 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
834 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
835 let rcontainer
= document
.getElementById("reserves_" + c
);
836 rcontainer
.style
.left
= i0
+ "px";
837 rcontainer
.style
.top
= j0
+ "px";
838 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
839 rcontainer
.style
.height
= sqResSize
+ "px";
840 // And then reserve cells:
841 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
842 Object
.keys(this.reserve
[c
]).forEach(p
=> {
843 if (this.reserve
[c
][p
] == 0)
845 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
846 r_cell
.style
.width
= sqResSize
+ "px";
847 r_cell
.style
.height
= sqResSize
+ "px";
852 // Return the absolute pixel coordinates given current position.
853 // Our coordinate system differs from CSS one (x <--> y).
854 // We return here the CSS coordinates (more useful).
855 getPixelPosition(i
, j
, r
) {
857 return [0, 0]; //piece vanishes
859 if (typeof i
== "string") {
860 // Reserves: need to know the rank of piece
861 const nbR
= this.getNbReservePieces(i
);
862 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
863 x
= this.getRankInReserve(i
, j
) * rsqSize
;
864 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
867 const sqSize
= r
.width
/ this.size
.y
;
868 const flipped
= (this.playerColor
== 'b');
869 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
870 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
872 return [r
.x
+ x
, r
.y
+ y
];
876 let container
= document
.getElementById(this.containerId
);
877 let chessboard
= container
.querySelector(".chessboard");
879 const getOffset
= e
=> {
882 return {x: e
.clientX
, y: e
.clientY
};
883 let touchLocation
= null;
884 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
885 // Touch screen, dragstart
886 touchLocation
= e
.targetTouches
[0];
887 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
888 // Touch screen, dragend
889 touchLocation
= e
.changedTouches
[0];
891 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
892 return {x: 0, y: 0}; //shouldn't reach here =)
895 const centerOnCursor
= (piece
, e
) => {
896 const centerShift
= this.getPieceWidth(r
.width
) / 2;
897 const offset
= getOffset(e
);
898 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
899 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
904 startPiece
, curPiece
= null,
906 const mousedown
= (e
) => {
907 // Disable zoom on smartphones:
908 if (e
.touches
&& e
.touches
.length
> 1)
910 r
= chessboard
.getBoundingClientRect();
911 pieceWidth
= this.getPieceWidth(r
.width
);
912 const cd
= this.idToCoords(e
.target
.id
);
914 const move = this.doClick(cd
);
916 this.playPlusVisual(move);
918 const [x
, y
] = Object
.values(cd
);
919 if (typeof x
!= "number")
920 startPiece
= this.r_pieces
[x
][y
];
922 startPiece
= this.g_pieces
[x
][y
];
923 if (startPiece
&& this.canIplay(x
, y
)) {
926 curPiece
= startPiece
.cloneNode();
927 curPiece
.style
.transform
= "none";
928 curPiece
.style
.zIndex
= 5;
929 curPiece
.style
.width
= pieceWidth
+ "px";
930 curPiece
.style
.height
= pieceWidth
+ "px";
931 centerOnCursor(curPiece
, e
);
932 container
.appendChild(curPiece
);
933 startPiece
.style
.opacity
= "0.4";
934 chessboard
.style
.cursor
= "none";
940 const mousemove
= (e
) => {
943 centerOnCursor(curPiece
, e
);
945 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
946 // Attempt to prevent horizontal swipe...
950 const mouseup
= (e
) => {
953 const [x
, y
] = [start
.x
, start
.y
];
956 chessboard
.style
.cursor
= "pointer";
957 startPiece
.style
.opacity
= "1";
958 const offset
= getOffset(e
);
959 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
961 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
963 // NOTE: clearly suboptimal, but much easier, and not a big deal.
964 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
965 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
966 const moves
= this.filterValid(potentialMoves
);
967 if (moves
.length
>= 2)
968 this.showChoices(moves
, r
);
969 else if (moves
.length
== 1)
970 this.playPlusVisual(moves
[0], r
);
975 if ('onmousedown' in window
) {
976 document
.addEventListener("mousedown", mousedown
);
977 document
.addEventListener("mousemove", mousemove
);
978 document
.addEventListener("mouseup", mouseup
);
979 document
.addEventListener("wheel",
980 (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down"));
982 if ('ontouchstart' in window
) {
983 // https://stackoverflow.com/a/42509310/12660887
984 document
.addEventListener("touchstart", mousedown
, {passive: false});
985 document
.addEventListener("touchmove", mousemove
, {passive: false});
986 document
.addEventListener("touchend", mouseup
, {passive: false});
988 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
991 showChoices(moves
, r
) {
992 let container
= document
.getElementById(this.containerId
);
993 let chessboard
= container
.querySelector(".chessboard");
994 let choices
= document
.createElement("div");
995 choices
.id
= "choices";
996 choices
.style
.width
= r
.width
+ "px";
997 choices
.style
.height
= r
.height
+ "px";
998 choices
.style
.left
= r
.x
+ "px";
999 choices
.style
.top
= r
.y
+ "px";
1000 chessboard
.style
.opacity
= "0.5";
1001 container
.appendChild(choices
);
1002 const squareWidth
= r
.width
/ this.size
.y
;
1003 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1004 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1005 const color
= moves
[0].appear
[0].c
;
1006 const callback
= (m
) => {
1007 chessboard
.style
.opacity
= "1";
1008 container
.removeChild(choices
);
1009 this.playPlusVisual(m
, r
);
1011 for (let i
=0; i
< moves
.length
; i
++) {
1012 let choice
= document
.createElement("div");
1013 choice
.classList
.add("choice");
1014 choice
.style
.width
= squareWidth
+ "px";
1015 choice
.style
.height
= squareWidth
+ "px";
1016 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1017 choice
.style
.top
= firstUpTop
+ "px";
1018 choice
.style
.backgroundColor
= "lightyellow";
1019 choice
.onclick
= () => callback(moves
[i
]);
1020 const piece
= document
.createElement("piece");
1021 const pieceSpec
= this.pieces()[moves
[i
].appear
[0].p
];
1022 piece
.classList
.add(pieceSpec
["class"]);
1023 piece
.classList
.add(C
.GetColorClass(color
));
1024 piece
.style
.width
= "100%";
1025 piece
.style
.height
= "100%";
1026 choice
.appendChild(piece
);
1027 choices
.appendChild(choice
);
1038 ratio: 1 //for rectangular board = y / x
1042 // Color of thing on square (i,j). 'undefined' if square is empty
1044 if (typeof i
== "string")
1045 return i
; //reserves
1046 return this.board
[i
][j
].charAt(0);
1049 static GetColorClass(c
) {
1050 return (c
== 'w' ? "white" : "black");
1053 // Assume square i,j isn't empty
1055 if (typeof j
== "string")
1056 return j
; //reserves
1057 return this.board
[i
][j
].charAt(1);
1060 // Piece type on square (i,j)
1061 getPieceType(i
, j
) {
1062 const p
= this.getPiece(i
, j
);
1063 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1066 // Get opponent color
1067 static GetOppCol(color
) {
1068 return (color
== "w" ? "b" : "w");
1071 // Can thing on square1 capture (no return) thing on square2?
1072 canTake([x1
, y1
], [x2
, y2
]) {
1073 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1076 // Is (x,y) on the chessboard?
1078 return (x
>= 0 && x
< this.size
.x
&&
1079 y
>= 0 && y
< this.size
.y
);
1082 // Am I allowed to move thing at square x,y ?
1084 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1087 ////////////////////////
1088 // PIECES SPECIFICATIONS
1090 pieces(color
, x
, y
) {
1091 const pawnShift
= (color
== "w" ? -1 : 1);
1092 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1093 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1099 steps: [[pawnShift
, 0]],
1100 range: (initRank
? 2 : 1)
1105 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1114 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1123 [1, 2], [1, -2], [-1, 2], [-1, -2],
1124 [2, 1], [-2, 1], [2, -1], [-2, -1]
1134 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1143 [0, 1], [0, -1], [1, 0], [-1, 0],
1144 [1, 1], [1, -1], [-1, 1], [-1, -1]
1155 [0, 1], [0, -1], [1, 0], [-1, 0],
1156 [1, 1], [1, -1], [-1, 1], [-1, -1]
1163 '!': {"class": "king-pawn", moveas: "p"},
1164 '#': {"class": "king-rook", moveas: "r"},
1165 '$': {"class": "king-knight", moveas: "n"},
1166 '%': {"class": "king-bishop", moveas: "b"},
1167 '*': {"class": "king-queen", moveas: "q"}
1171 ////////////////////
1174 // For Cylinder: get Y coordinate
1176 if (!this.options
["cylinder"])
1178 let res
= y
% this.size
.y
;
1184 // Stop at the first capture found
1185 atLeastOneCapture(color
) {
1186 color
= color
|| this.turn
;
1187 const oppCol
= C
.GetOppCol(color
);
1188 for (let i
= 0; i
< this.size
.x
; i
++) {
1189 for (let j
= 0; j
< this.size
.y
; j
++) {
1190 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1191 const allSpecs
= this.pieces(color
, i
, j
)
1192 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1193 const attacks
= specs
.attack
|| specs
.moves
;
1194 for (let a
of attacks
) {
1195 outerLoop: for (let step
of a
.steps
) {
1196 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1197 let stepCounter
= 1;
1198 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1199 if (a
.range
<= stepCounter
++)
1202 jj
= this.getY(jj
+ step
[1]);
1205 this.onBoard(ii
, jj
) &&
1206 this.getColor(ii
, jj
) == oppCol
&&
1208 [this.getBasicMove([i
, j
], [ii
, jj
])]
1221 getDropMovesFrom([c
, p
]) {
1222 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1223 // (but not necessarily otherwise: atLeastOneMove() etc)
1224 if (this.reserve
[c
][p
] == 0)
1227 for (let i
=0; i
<this.size
.x
; i
++) {
1228 for (let j
=0; j
<this.size
.y
; j
++) {
1230 this.board
[i
][j
] == "" &&
1231 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1234 (c
== 'w' && i
< this.size
.x
- 1) ||
1240 start: {x: c
, y: p
},
1242 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1252 // All possible moves from selected square
1253 getPotentialMovesFrom(sq
, color
) {
1254 if (this.subTurnTeleport
== 2)
1256 if (typeof sq
[0] == "string")
1257 return this.getDropMovesFrom(sq
);
1258 if (this.isImmobilized(sq
))
1260 const piece
= this.getPieceType(sq
[0], sq
[1]);
1261 let moves
= this.getPotentialMovesOf(piece
, sq
);
1264 this.hasEnpassant
&&
1267 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1272 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1274 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1276 return this.postProcessPotentialMoves(moves
);
1279 postProcessPotentialMoves(moves
) {
1280 if (moves
.length
== 0)
1282 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1283 const oppCol
= C
.GetOppCol(color
);
1285 if (this.options
["capture"] && this.atLeastOneCapture())
1286 moves
= this.capturePostProcess(moves
, oppCol
);
1288 if (this.options
["atomic"])
1289 this.atomicPostProcess(moves
, oppCol
);
1293 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1295 this.pawnPostProcess(moves
, color
, oppCol
);
1299 this.options
["cannibal"] &&
1300 this.options
["rifle"]
1302 // In this case a rifle-capture from last rank may promote a pawn
1303 this.riflePromotePostProcess(moves
, color
);
1309 capturePostProcess(moves
, oppCol
) {
1310 // Filter out non-capturing moves (not using m.vanish because of
1311 // self captures of Recycle and Teleport).
1312 return moves
.filter(m
=> {
1314 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1315 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1320 atomicPostProcess(moves
, oppCol
) {
1321 moves
.forEach(m
=> {
1323 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1324 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1337 for (let step
of steps
) {
1338 let x
= m
.end
.x
+ step
[0];
1339 let y
= this.getY(m
.end
.y
+ step
[1]);
1341 this.onBoard(x
, y
) &&
1342 this.board
[x
][y
] != "" &&
1343 this.getPieceType(x
, y
) != "p"
1347 p: this.getPiece(x
, y
),
1348 c: this.getColor(x
, y
),
1355 if (!this.options
["rifle"])
1356 m
.appear
.pop(); //nothing appears
1361 pawnPostProcess(moves
, color
, oppCol
) {
1363 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1364 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1365 moves
.forEach(m
=> {
1366 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1367 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1368 const promotionOk
= (
1370 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1373 return; //nothing to do
1374 if (this.options
["pawnfall"]) {
1378 let finalPieces
= ["p"];
1380 this.options
["cannibal"] &&
1381 this.board
[x2
][y2
] != "" &&
1382 this.getColor(x2
, y2
) == oppCol
1384 finalPieces
= [this.getPieceType(x2
, y2
)];
1387 finalPieces
= this.pawnPromotions
;
1388 m
.appear
[0].p
= finalPieces
[0];
1389 if (initPiece
== "!") //cannibal king-pawn
1390 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1391 for (let i
=1; i
<finalPieces
.length
; i
++) {
1392 const piece
= finalPieces
[i
];
1395 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1397 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1398 moreMoves
.push(newMove
);
1401 Array
.prototype.push
.apply(moves
, moreMoves
);
1404 riflePromotePostProcess(moves
, color
) {
1405 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1407 moves
.forEach(m
=> {
1409 m
.start
.x
== lastRank
&&
1410 m
.appear
.length
>= 1 &&
1411 m
.appear
[0].p
== "p" &&
1412 m
.appear
[0].x
== m
.start
.x
&&
1413 m
.appear
[0].y
== m
.start
.y
1415 m
.appear
[0].p
= this.pawnPromotions
[0];
1416 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1417 let newMv
= JSON
.parse(JSON
.stringify(m
));
1418 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1419 newMoves
.push(newMv
);
1423 Array
.prototype.push
.apply(moves
, newMoves
);
1426 // NOTE: using special symbols to not interfere with variants' pieces codes
1427 static get CannibalKings() {
1438 static get CannibalKingCode() {
1450 return !!C
.CannibalKings
[symbol
];
1454 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1455 isImmobilized([x
, y
]) {
1456 if (!this.options
["madrasi"])
1458 const color
= this.getColor(x
, y
);
1459 const oppCol
= C
.GetOppCol(color
);
1460 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1461 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1462 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1463 for (let a
of attacks
) {
1464 outerLoop: for (let step
of a
.steps
) {
1465 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1466 let stepCounter
= 1;
1467 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1468 if (a
.range
<= stepCounter
++)
1471 j
= this.getY(j
+ step
[1]);
1474 this.onBoard(i
, j
) &&
1475 this.getColor(i
, j
) == oppCol
&&
1476 this.getPieceType(i
, j
) == piece
1485 // Generic method to find possible moves of "sliding or jumping" pieces
1486 getPotentialMovesOf(piece
, [x
, y
]) {
1487 const color
= this.getColor(x
, y
);
1488 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1490 // Next 3 for Cylinder mode:
1495 const addMove
= (start
, end
) => {
1496 let newMove
= this.getBasicMove(start
, end
);
1497 if (segments
.length
> 0) {
1498 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1499 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1501 moves
.push(newMove
);
1504 const findAddMoves
= (type
, stepArray
) => {
1505 for (let s
of stepArray
) {
1506 outerLoop: for (let step
of s
.steps
) {
1509 let [i
, j
] = [x
, y
];
1510 let stepCounter
= 0;
1512 this.onBoard(i
, j
) &&
1513 (this.board
[i
][j
] == "" || (i
== x
&& j
== y
))
1517 !explored
[i
+ "." + j
] &&
1520 explored
[i
+ "." + j
] = true;
1521 addMove([x
, y
], [i
, j
]);
1523 if (s
.range
<= stepCounter
++)
1525 const oldIJ
= [i
, j
];
1527 j
= this.getY(j
+ step
[1]);
1528 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1529 // Boundary between segments (cylinder mode)
1530 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1534 if (!this.onBoard(i
, j
))
1536 const pieceIJ
= this.getPieceType(i
, j
);
1538 type
!= "moveonly" &&
1539 !explored
[i
+ "." + j
] &&
1541 !this.options
["zen"] ||
1545 this.canTake([x
, y
], [i
, j
]) ||
1547 (this.options
["recycle"] || this.options
["teleport"]) &&
1552 explored
[i
+ "." + j
] = true;
1553 addMove([x
, y
], [i
, j
]);
1559 const specialAttack
= !!stepSpec
.attack
;
1561 findAddMoves("attack", stepSpec
.attack
);
1562 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1563 if (this.options
["zen"]) {
1564 Array
.prototype.push
.apply(moves
,
1565 this.findCapturesOn([x
, y
], {zen: true}));
1570 // Search for enemy (or not) pieces attacking [x, y]
1571 findCapturesOn([x
, y
], args
) {
1574 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1575 for (let i
=0; i
<this.size
.x
; i
++) {
1576 for (let j
=0; j
<this.size
.y
; j
++) {
1578 this.board
[i
][j
] != "" &&
1579 this.getColor(i
, j
) == args
.oppCol
&&
1580 !this.isImmobilized([i
, j
])
1582 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1583 continue; //king not captured in this way
1585 this.pieces(args
.oppCol
, i
, j
)[this.getPieceType(i
, j
)];
1586 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1587 for (let a
of attacks
) {
1588 for (let s
of a
.steps
) {
1589 // Quick check: if step isn't compatible, don't even try
1590 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1592 // Finally verify that nothing stand in-between
1593 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1594 let stepCounter
= 1;
1596 this.onBoard(ii
, jj
) &&
1597 this.board
[ii
][jj
] == "" &&
1598 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1601 jj
= this.getY(jj
+ s
[1]);
1603 if (ii
== x
&& jj
== y
) {
1606 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1608 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1610 return moves
; //test for underCheck
1620 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1621 const rx
= (x2
- x1
) / step
[0],
1622 ry
= (y2
- y1
) / step
[1];
1624 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1625 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1629 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1630 // TODO: 1e-7 here is totally arbitrary
1631 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1633 distance
= Math
.round(distance
); //in case of (numerical...)
1634 if (range
< distance
)
1639 // Build a regular move from its initial and destination squares.
1640 // tr: transformation
1641 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1642 const initColor
= this.getColor(sx
, sy
);
1643 const initPiece
= this.getPiece(sx
, sy
);
1644 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1648 start: {x: sx
, y: sy
},
1652 !this.options
["rifle"] ||
1653 this.board
[ex
][ey
] == "" ||
1654 destColor
== initColor
//Recycle, Teleport
1660 c: !!tr
? tr
.c : initColor
,
1661 p: !!tr
? tr
.p : initPiece
1673 if (this.board
[ex
][ey
] != "") {
1678 c: this.getColor(ex
, ey
),
1679 p: this.getPiece(ex
, ey
)
1682 if (this.options
["cannibal"] && destColor
!= initColor
) {
1683 const lastIdx
= mv
.vanish
.length
- 1;
1684 let trPiece
= mv
.vanish
[lastIdx
].p
;
1685 if (this.isKing(this.getPiece(sx
, sy
)))
1686 trPiece
= C
.CannibalKingCode
[trPiece
];
1687 if (mv
.appear
.length
>= 1)
1688 mv
.appear
[0].p
= trPiece
;
1689 else if (this.options
["rifle"]) {
1712 // En-passant square, if any
1713 getEpSquare(moveOrSquare
) {
1714 if (typeof moveOrSquare
=== "string") {
1715 const square
= moveOrSquare
;
1718 return C
.SquareToCoords(square
);
1720 // Argument is a move:
1721 const move = moveOrSquare
;
1722 const s
= move.start
,
1726 Math
.abs(s
.x
- e
.x
) == 2 &&
1727 // Next conditions for variants like Atomic or Rifle, Recycle...
1728 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1729 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1736 return undefined; //default
1739 // Special case of en-passant captures: treated separately
1740 getEnpassantCaptures([x
, y
]) {
1741 const color
= this.getColor(x
, y
);
1742 const shiftX
= (color
== 'w' ? -1 : 1);
1743 const oppCol
= C
.GetOppCol(color
);
1744 let enpassantMove
= null;
1747 this.epSquare
.x
== x
+ shiftX
&&
1748 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1749 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1751 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1752 this.board
[epx
][epy
] = oppCol
+ "p";
1753 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1754 this.board
[epx
][epy
] = "";
1755 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1756 enpassantMove
.vanish
[lastIdx
].x
= x
;
1758 return !!enpassantMove
? [enpassantMove
] : [];
1761 // "castleInCheck" arg to let some variants castle under check
1762 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1763 const c
= this.getColor(x
, y
);
1766 const oppCol
= C
.GetOppCol(c
);
1770 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1771 const castlingKing
= this.getPiece(x
, y
);
1772 castlingCheck: for (
1775 castleSide
++ //large, then small
1777 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1779 // If this code is reached, rook and king are on initial position
1781 // NOTE: in some variants this is not a rook
1782 const rookPos
= this.castleFlags
[c
][castleSide
];
1783 const castlingPiece
= this.getPiece(x
, rookPos
);
1785 this.board
[x
][rookPos
] == "" ||
1786 this.getColor(x
, rookPos
) != c
||
1787 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1789 // Rook is not here, or changed color (see Benedict)
1792 // Nothing on the path of the king ? (and no checks)
1793 const finDist
= finalSquares
[castleSide
][0] - y
;
1794 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1798 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1800 this.board
[x
][i
] != "" &&
1801 // NOTE: next check is enough, because of chessboard constraints
1802 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1805 continue castlingCheck
;
1808 } while (i
!= finalSquares
[castleSide
][0]);
1809 // Nothing on the path to the rook?
1810 step
= (castleSide
== 0 ? -1 : 1);
1811 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1812 if (this.board
[x
][i
] != "")
1813 continue castlingCheck
;
1816 // Nothing on final squares, except maybe king and castling rook?
1817 for (i
= 0; i
< 2; i
++) {
1819 finalSquares
[castleSide
][i
] != rookPos
&&
1820 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1822 finalSquares
[castleSide
][i
] != y
||
1823 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1826 continue castlingCheck
;
1830 // If this code is reached, castle is valid
1836 y: finalSquares
[castleSide
][0],
1842 y: finalSquares
[castleSide
][1],
1848 // King might be initially disguised (Titan...)
1849 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1850 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1853 Math
.abs(y
- rookPos
) <= 2
1854 ? {x: x
, y: rookPos
}
1855 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1863 ////////////////////
1866 // Is (king at) given position under check by "oppCol" ?
1867 underCheck([x
, y
], oppCol
) {
1868 if (this.options
["taking"] || this.options
["dark"])
1871 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1875 // Stop at first king found (TODO: multi-kings)
1876 searchKingPos(color
) {
1877 for (let i
=0; i
< this.size
.x
; i
++) {
1878 for (let j
=0; j
< this.size
.y
; j
++) {
1879 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1883 return [-1, -1]; //king not found
1886 filterValid(moves
) {
1887 if (moves
.length
== 0)
1889 const color
= this.turn
;
1890 const oppCol
= C
.GetOppCol(color
);
1891 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1892 // Forbid moves either giving check or exploding opponent's king:
1893 const oppKingPos
= this.searchKingPos(oppCol
);
1894 moves
= moves
.filter(m
=> {
1896 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1897 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1900 this.playOnBoard(m
);
1901 const res
= !this.underCheck(oppKingPos
, color
);
1902 this.undoOnBoard(m
);
1906 if (this.options
["taking"] || this.options
["dark"])
1908 const kingPos
= this.searchKingPos(color
);
1909 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1910 return moves
.filter(m
=> {
1911 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1912 if (!filtered
[key
]) {
1913 this.playOnBoard(m
);
1914 let square
= kingPos
,
1915 res
= true; //a priori valid
1916 if (m
.vanish
.some(v
=> {
1917 return C
.CannibalKings
[v
.p
] && v
.c
== color
;
1919 // Search king in appear array:
1921 m
.appear
.findIndex(a
=> {
1922 return C
.CannibalKings
[a
.p
] && a
.c
== color
;
1924 if (newKingIdx
>= 0)
1925 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1929 res
&&= !this.underCheck(square
, oppCol
);
1930 this.undoOnBoard(m
);
1931 filtered
[key
] = res
;
1934 return filtered
[key
];
1941 // Aggregate flags into one object
1943 return this.castleFlags
;
1946 // Reverse operation
1947 disaggregateFlags(flags
) {
1948 this.castleFlags
= flags
;
1951 // Apply a move on board
1953 for (let psq
of move.vanish
)
1954 this.board
[psq
.x
][psq
.y
] = "";
1955 for (let psq
of move.appear
)
1956 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1958 // Un-apply the played move
1960 for (let psq
of move.appear
)
1961 this.board
[psq
.x
][psq
.y
] = "";
1962 for (let psq
of move.vanish
)
1963 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1966 updateCastleFlags(move) {
1967 // Update castling flags if start or arrive from/at rook/king locations
1968 move.appear
.concat(move.vanish
).forEach(psq
=> {
1970 this.board
[psq
.x
][psq
.y
] != "" &&
1971 this.getPieceType(psq
.x
, psq
.y
) == "k"
1973 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1975 // NOTE: not "else if" because king can capture enemy rook...
1979 else if (psq
.x
== this.size
.x
- 1)
1982 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1984 this.castleFlags
[c
][fidx
] = this.size
.y
;
1992 // If flags already off, no need to re-check:
1993 Object
.keys(this.castleFlags
).some(c
=> {
1994 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1996 this.updateCastleFlags(move);
1998 if (this.options
["crazyhouse"]) {
1999 move.vanish
.forEach(v
=> {
2000 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2001 if (this.ispawn
[square
])
2002 delete this.ispawn
[square
];
2004 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2005 // Assumption: something is moving
2006 const initSquare
= C
.CoordsToSquare(move.start
);
2007 const destSquare
= C
.CoordsToSquare(move.end
);
2009 this.ispawn
[initSquare
] ||
2010 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2012 this.ispawn
[destSquare
] = true;
2015 this.ispawn
[destSquare
] &&
2016 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2018 move.vanish
[1].p
= "p";
2019 delete this.ispawn
[destSquare
];
2023 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2026 // Warning; atomic pawn removal isn't a capture
2027 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2029 const color
= this.turn
;
2030 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2031 // Something appears = dropped on board (some exceptions, Chakart...)
2032 if (move.appear
[i
].c
== color
) {
2033 const piece
= move.appear
[i
].p
;
2034 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2037 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2038 // Something vanish: add to reserve except if recycle & opponent
2040 this.options
["crazyhouse"] ||
2041 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2043 const piece
= move.vanish
[i
].p
;
2044 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2052 if (this.hasEnpassant
)
2053 this.epSquare
= this.getEpSquare(move);
2054 this.playOnBoard(move);
2055 this.postPlay(move);
2059 const color
= this.turn
;
2060 const oppCol
= C
.GetOppCol(color
);
2061 if (this.options
["dark"])
2062 this.updateEnlightened();
2063 if (this.options
["teleport"]) {
2065 this.subTurnTeleport
== 1 &&
2066 move.vanish
.length
> move.appear
.length
&&
2067 move.vanish
[move.vanish
.length
- 1].c
== color
2069 const v
= move.vanish
[move.vanish
.length
- 1];
2070 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2071 this.subTurnTeleport
= 2;
2074 this.subTurnTeleport
= 1;
2075 this.captured
= null;
2077 if (this.options
["balance"]) {
2078 if (![1, 3].includes(this.movesCount
))
2084 this.options
["doublemove"] &&
2085 this.movesCount
>= 1 &&
2088 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2090 const oppKingPos
= this.searchKingPos(oppCol
);
2092 oppKingPos
[0] >= 0 &&
2094 this.options
["taking"] ||
2095 !this.underCheck(oppKingPos
, color
)
2108 // "Stop at the first move found"
2109 atLeastOneMove(color
) {
2110 color
= color
|| this.turn
;
2111 for (let i
= 0; i
< this.size
.x
; i
++) {
2112 for (let j
= 0; j
< this.size
.y
; j
++) {
2113 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2114 // NOTE: in fact searching for all potential moves from i,j.
2115 // I don't believe this is an issue, for now at least.
2116 const moves
= this.getPotentialMovesFrom([i
, j
]);
2117 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2122 if (this.hasReserve
&& this.reserve
[color
]) {
2123 for (let p
of Object
.keys(this.reserve
[color
])) {
2124 const moves
= this.getDropMovesFrom([color
, p
]);
2125 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2132 // What is the score ? (Interesting if game is over)
2133 getCurrentScore(move) {
2134 const color
= this.turn
;
2135 const oppCol
= C
.GetOppCol(color
);
2136 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2137 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2139 if (kingPos
[0][0] < 0)
2140 return (color
== "w" ? "0-1" : "1-0");
2141 if (kingPos
[1][0] < 0)
2142 return (color
== "w" ? "1-0" : "0-1");
2143 if (this.atLeastOneMove())
2145 // No valid move: stalemate or checkmate?
2146 if (!this.underCheck(kingPos
[0], color
))
2149 return (color
== "w" ? "0-1" : "1-0");
2152 playVisual(move, r
) {
2153 move.vanish
.forEach(v
=> {
2154 this.g_pieces
[v
.x
][v
.y
].remove();
2155 this.g_pieces
[v
.x
][v
.y
] = null;
2158 document
.getElementById(this.containerId
).querySelector(".chessboard");
2160 r
= chessboard
.getBoundingClientRect();
2161 const pieceWidth
= this.getPieceWidth(r
.width
);
2162 move.appear
.forEach(a
=> {
2163 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2164 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2165 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2166 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2167 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2168 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2169 // Translate coordinates to use chessboard as reference:
2170 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2171 `translate(${ip - r.x}px,${jp - r.y}px)`;
2172 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2173 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2174 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2176 if (this.options
["dark"])
2177 this.graphUpdateEnlightened();
2180 playPlusVisual(move, r
) {
2182 this.playVisual(move, r
);
2183 this.afterPlay(move); //user method
2186 getMaxDistance(rwidth
) {
2187 // Works for all rectangular boards:
2188 return Math
.sqrt(rwidth
** 2 + (rwidth
/ this.size
.ratio
) ** 2);
2192 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2195 animate(move, callback
) {
2196 if (this.noAnimate
|| move.noAnimate
) {
2200 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2201 // NOTE: cloning generally not required, but light enough, and simpler
2202 let movingPiece
= initPiece
.cloneNode();
2203 initPiece
.style
.opacity
= "0";
2205 document
.getElementById(this.containerId
)
2206 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2207 if (typeof move.start
.x
== "string") {
2208 // Need to bound width/height (was 100% for reserve pieces)
2209 const pieceWidth
= this.getPieceWidth(r
.width
);
2210 movingPiece
.style
.width
= pieceWidth
+ "px";
2211 movingPiece
.style
.height
= pieceWidth
+ "px";
2213 const maxDist
= this.getMaxDistance(r
.width
);
2214 const pieces
= this.pieces();
2216 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2217 movingPiece
.classList
.remove(pieces
[startCode
]["class"]);
2218 movingPiece
.classList
.add(pieces
[move.drag
.p
]["class"]);
2219 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2220 if (apparentColor
!= move.drag
.c
) {
2221 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2222 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2225 container
.appendChild(movingPiece
);
2226 const animateSegment
= (index
, cb
) => {
2227 // NOTE: move.drag could be generalized per-segment (usage?)
2228 const [i1
, j1
] = move.segments
[index
][0];
2229 const [i2
, j2
] = move.segments
[index
][1];
2230 const dep
= this.getPixelPosition(i1
, j1
, r
);
2231 const arr
= this.getPixelPosition(i2
, j2
, r
);
2232 movingPiece
.style
.transitionDuration
= "0s";
2233 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2235 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2236 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2237 // TODO: unclear why we need this new delay below:
2239 movingPiece
.style
.transitionDuration
= duration
+ "s";
2240 // movingPiece is child of container: no need to adjust coordinates
2241 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2242 setTimeout(cb
, duration
* 1000);
2245 if (!move.segments
) {
2247 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2251 const animateSegmentCallback
= () => {
2252 if (index
< move.segments
.length
)
2253 animateSegment(index
++, animateSegmentCallback
);
2255 movingPiece
.remove();
2256 initPiece
.style
.opacity
= "1";
2260 animateSegmentCallback();
2263 playReceivedMove(moves
, callback
) {
2264 const launchAnimation
= () => {
2265 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2266 const animateRec
= i
=> {
2267 this.animate(moves
[i
], () => {
2268 this.play(moves
[i
]);
2269 this.playVisual(moves
[i
], r
);
2270 if (i
< moves
.length
- 1)
2271 setTimeout(() => animateRec(i
+1), 300);
2278 // Delay if user wasn't focused:
2279 const checkDisplayThenAnimate
= (delay
) => {
2280 if (container
.style
.display
== "none") {
2281 alert("New move! Let's go back to game...");
2282 document
.getElementById("gameInfos").style
.display
= "none";
2283 container
.style
.display
= "block";
2284 setTimeout(launchAnimation
, 700);
2287 setTimeout(launchAnimation
, delay
|| 0);
2289 let container
= document
.getElementById(this.containerId
);
2290 if (document
.hidden
) {
2291 document
.onvisibilitychange
= () => {
2292 document
.onvisibilitychange
= undefined;
2293 checkDisplayThenAnimate(700);
2297 checkDisplayThenAnimate();