0d7b703f2de907ad08f7aff0af360f5c4d5d279f
1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // NOTE: x coords: top to bottom (white perspective); y: left to right
7 // NOTE: ChessRules is aliased as window.C, and variants as window.V
8 export default class ChessRules
{
10 static get Aliases() {
11 return {'C': ChessRules
};
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
17 // Some variants have specific options, like the number of pawns in Monster,
18 // or the board size for Pandemonium.
19 // Users can generally select a randomness level from 0 to 2.
20 static get Options() {
24 variable: "randomness",
27 {label: "Deterministic", value: 0},
28 {label: "Symmetric random", value: 1},
29 {label: "Asymmetric random", value: 2}
34 label: "Capture king",
39 label: "Falling pawn",
44 // Game modifiers (using "elementary variants"). Default: false
47 "balance", //takes precedence over doublemove & progressive
51 "cylinder", //ok with all
55 "progressive", //(natural) priority over doublemove
64 get pawnPromotions() {
65 return ['q', 'r', 'n', 'b'];
68 // Some variants don't have flags:
77 // En-passant captures allowed?
84 !!this.options
["crazyhouse"] ||
85 (!!this.options
["recycle"] && !this.options
["teleport"])
90 return !!this.options
["dark"];
93 // Some variants use click infos:
95 if (typeof coords
.x
!= "number")
96 return null; //click on reserves
98 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
99 this.board
[coords
.x
][coords
.y
] == ""
102 start: {x: this.captured
.x
, y: this.captured
.y
},
107 c: this.captured
.c
, //this.turn,
113 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
122 // 3a --> {x:3, y:10}
123 static SquareToCoords(sq
) {
124 return ArrayFun
.toObject(["x", "y"],
125 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
128 // {x:11, y:12} --> bc
129 static CoordsToSquare(cd
) {
130 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
134 if (typeof cd
.x
== "number") {
136 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
140 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
143 idToCoords(targetId
) {
145 return null; //outside page, maybe...
146 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
148 idParts
.length
< 2 ||
149 idParts
[0] != this.containerId
||
150 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
154 const squares
= idParts
[1].split('-');
155 if (squares
[0] == "sq")
156 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
157 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
158 return {x: squares
[1], y: squares
[2]};
164 // Turn "wb" into "B" (for FEN)
166 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
169 // Turn "p" into "bp" (for board)
171 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
174 // Setup the initial random-or-not (asymmetric-or-not) position
175 genRandInitFen(seed
) {
176 Random
.setSeed(seed
);
178 let fen
, flags
= "0707";
179 if (!this.options
.randomness
)
181 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
185 let pieces
= { w: new Array(8), b: new Array(8) };
187 // Shuffle pieces on first (and last rank if randomness == 2)
188 for (let c
of ["w", "b"]) {
189 if (c
== 'b' && this.options
.randomness
== 1) {
190 pieces
['b'] = pieces
['w'];
195 let positions
= ArrayFun
.range(8);
197 // Get random squares for bishops
198 let randIndex
= 2 * Random
.randInt(4);
199 const bishop1Pos
= positions
[randIndex
];
200 // The second bishop must be on a square of different color
201 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
202 const bishop2Pos
= positions
[randIndex_tmp
];
203 // Remove chosen squares
204 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
205 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
207 // Get random squares for knights
208 randIndex
= Random
.randInt(6);
209 const knight1Pos
= positions
[randIndex
];
210 positions
.splice(randIndex
, 1);
211 randIndex
= Random
.randInt(5);
212 const knight2Pos
= positions
[randIndex
];
213 positions
.splice(randIndex
, 1);
215 // Get random square for queen
216 randIndex
= Random
.randInt(4);
217 const queenPos
= positions
[randIndex
];
218 positions
.splice(randIndex
, 1);
220 // Rooks and king positions are now fixed,
221 // because of the ordering rook-king-rook
222 const rook1Pos
= positions
[0];
223 const kingPos
= positions
[1];
224 const rook2Pos
= positions
[2];
226 // Finally put the shuffled pieces in the board array
227 pieces
[c
][rook1Pos
] = "r";
228 pieces
[c
][knight1Pos
] = "n";
229 pieces
[c
][bishop1Pos
] = "b";
230 pieces
[c
][queenPos
] = "q";
231 pieces
[c
][kingPos
] = "k";
232 pieces
[c
][bishop2Pos
] = "b";
233 pieces
[c
][knight2Pos
] = "n";
234 pieces
[c
][rook2Pos
] = "r";
235 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
238 pieces
["b"].join("") +
239 "/pppppppp/8/8/8/8/PPPPPPPP/" +
240 pieces
["w"].join("").toUpperCase() +
244 // Add turn + flags + enpassant (+ reserve)
247 parts
.push(`"flags":"${flags}"`);
248 if (this.hasEnpassant
)
249 parts
.push('"enpassant":"-"');
251 parts
.push('"reserve":"000000000000"');
252 if (this.options
["crazyhouse"])
253 parts
.push('"ispawn":"-"');
254 if (parts
.length
>= 1)
255 fen
+= " {" + parts
.join(",") + "}";
259 // "Parse" FEN: just return untransformed string data
261 const fenParts
= fen
.split(" ");
263 position: fenParts
[0],
265 movesCount: fenParts
[2]
267 if (fenParts
.length
> 3)
268 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
272 // Return current fen (game state)
275 this.getPosition() + " " +
276 this.getTurnFen() + " " +
281 parts
.push(`"flags":"${this.getFlagsFen()}"`);
282 if (this.hasEnpassant
)
283 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
285 parts
.push(`"reserve":"${this.getReserveFen()}"`);
286 if (this.options
["crazyhouse"])
287 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
288 if (parts
.length
>= 1)
289 fen
+= " {" + parts
.join(",") + "}";
293 static FenEmptySquares(count
) {
294 // if more than 9 consecutive free spaces, break the integer,
295 // otherwise FEN parsing will fail.
298 // Most boards of size < 18:
300 return "9" + (count
- 9);
302 return "99" + (count
- 18);
305 // Position part of the FEN string
308 for (let i
= 0; i
< this.size
.y
; i
++) {
310 for (let j
= 0; j
< this.size
.x
; j
++) {
311 if (this.board
[i
][j
] == "")
314 if (emptyCount
> 0) {
315 // Add empty squares in-between
316 position
+= C
.FenEmptySquares(emptyCount
);
319 position
+= this.board2fen(this.board
[i
][j
]);
324 position
+= C
.FenEmptySquares(emptyCount
);
325 if (i
< this.size
.y
- 1)
326 position
+= "/"; //separate rows
335 // Flags part of the FEN string
337 return ["w", "b"].map(c
=> {
338 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
342 // Enpassant part of the FEN string
345 return "-"; //no en-passant
346 return C
.CoordsToSquare(this.epSquare
);
351 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
356 const squares
= Object
.keys(this.ispawn
);
357 if (squares
.length
== 0)
359 return squares
.join(",");
362 // Set flags from fen (castle: white a,h then black a,h)
365 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
366 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
374 this.options
= o
.options
;
375 // Fill missing options (always the case if random challenge)
376 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
377 if (this.options
[opt
.variable
] === undefined)
378 this.options
[opt
.variable
] = opt
.defaut
;
380 this.playerColor
= o
.color
;
381 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
383 // Fen string fully describes the game state
385 o
.fen
= this.genRandInitFen(o
.seed
);
386 const fenParsed
= this.parseFen(o
.fen
);
387 this.board
= this.getBoard(fenParsed
.position
);
388 this.turn
= fenParsed
.turn
;
389 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
390 this.setOtherVariables(fenParsed
);
392 // Graphical (can use variables defined above)
393 this.containerId
= o
.element
;
394 this.graphicalInit();
397 // Turn position fen into double array ["wb","wp","bk",...]
399 const rows
= position
.split("/");
400 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
401 for (let i
= 0; i
< rows
.length
; i
++) {
403 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
404 const character
= rows
[i
][indexInRow
];
405 const num
= parseInt(character
, 10);
406 // If num is a number, just shift j:
409 // Else: something at position i,j
411 board
[i
][j
++] = this.fen2board(character
);
417 // Some additional variables from FEN (variant dependant)
418 setOtherVariables(fenParsed
) {
419 // Set flags and enpassant:
421 this.setFlags(fenParsed
.flags
);
422 if (this.hasEnpassant
)
423 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
425 this.initReserves(fenParsed
.reserve
);
426 if (this.options
["crazyhouse"])
427 this.initIspawn(fenParsed
.ispawn
);
428 this.subTurn
= 1; //may be unused
429 if (this.options
["teleport"]) {
430 this.subTurnTeleport
= 1;
431 this.captured
= null;
433 if (this.options
["dark"]) {
434 // Setup enlightened: squares reachable by player side
435 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
436 this.updateEnlightened();
440 updateEnlightened() {
441 this.oldEnlightened
= this.enlightened
;
442 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
443 // Add pieces positions + all squares reachable by moves (includes Zen):
444 for (let x
=0; x
<this.size
.x
; x
++) {
445 for (let y
=0; y
<this.size
.y
; y
++) {
446 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
448 this.enlightened
[x
][y
] = true;
449 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
450 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
456 this.enlightEnpassant();
459 // Include square of the en-passant capturing square:
461 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
462 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
463 for (let step
of steps
) {
464 const x
= this.epSquare
.x
- step
[0],
465 y
= this.getY(this.epSquare
.y
- step
[1]);
467 this.onBoard(x
, y
) &&
468 this.getColor(x
, y
) == this.playerColor
&&
469 this.getPieceType(x
, y
) == "p"
471 this.enlightened
[x
][this.epSquare
.y
] = true;
477 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
478 initReserves(reserveStr
) {
479 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
480 this.reserve
= { w: {}, b: {} };
481 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
482 const L
= pieceName
.length
;
483 for (let i
of ArrayFun
.range(2 * L
)) {
485 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
487 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
491 initIspawn(ispawnStr
) {
492 if (ispawnStr
!= "-")
493 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
498 getNbReservePieces(color
) {
500 Object
.values(this.reserve
[color
]).reduce(
501 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
505 getRankInReserve(c
, p
) {
506 const pieces
= Object
.keys(this.pieces());
507 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
508 let toTest
= pieces
.slice(0, lastIndex
);
509 return toTest
.reduce(
510 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
516 getPieceWidth(rwidth
) {
517 return (rwidth
/ this.size
.y
);
520 getReserveSquareSize(rwidth
, nbR
) {
521 const sqSize
= this.getPieceWidth(rwidth
);
522 return Math
.min(sqSize
, rwidth
/ nbR
);
525 getReserveNumId(color
, piece
) {
526 return `${this.containerId}|rnum-${color}${piece}`;
530 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
531 window
.onresize
= () => this.re_drawBoardElements();
532 this.re_drawBoardElements();
533 this.initMouseEvents();
535 document
.getElementById(this.containerId
).querySelector(".chessboard");
538 re_drawBoardElements() {
539 const board
= this.getSvgChessboard();
540 const oppCol
= C
.GetOppCol(this.playerColor
);
542 document
.getElementById(this.containerId
).querySelector(".chessboard");
543 chessboard
.innerHTML
= "";
544 chessboard
.insertAdjacentHTML('beforeend', board
);
545 // Compare window ratio width / height to aspectRatio:
546 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
547 let cbWidth
, cbHeight
;
548 if (windowRatio
<= this.size
.ratio
) {
549 // Limiting dimension is width:
550 cbWidth
= Math
.min(window
.innerWidth
, 767);
551 cbHeight
= cbWidth
/ this.size
.ratio
;
554 // Limiting dimension is height:
555 cbHeight
= Math
.min(window
.innerHeight
, 767);
556 cbWidth
= cbHeight
* this.size
.ratio
;
558 if (this.hasReserve
) {
559 const sqSize
= cbWidth
/ this.size
.y
;
560 // NOTE: allocate space for reserves (up/down) even if they are empty
561 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
562 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
563 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
564 cbWidth
= cbHeight
* this.size
.ratio
;
567 chessboard
.style
.width
= cbWidth
+ "px";
568 chessboard
.style
.height
= cbHeight
+ "px";
569 // Center chessboard:
570 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
571 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
572 chessboard
.style
.left
= spaceLeft
+ "px";
573 chessboard
.style
.top
= spaceTop
+ "px";
574 // Give sizes instead of recomputing them,
575 // because chessboard might not be drawn yet.
584 // Get SVG board (background, no pieces)
586 const flipped
= (this.playerColor
== 'b');
590 class="chessboard_SVG">`;
591 for (let i
=0; i
< this.size
.x
; i
++) {
592 for (let j
=0; j
< this.size
.y
; j
++) {
593 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
594 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
595 let classes
= this.getSquareColorClass(ii
, jj
);
596 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
597 classes
+= " in-shadow";
598 // NOTE: x / y reversed because coordinates system is reversed.
602 id="${this.coordsToId({x: ii, y: jj})}"
614 // Generally light square bottom-right
615 getSquareColorClass(x
, y
) {
616 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
621 // Refreshing: delete old pieces first
622 for (let i
=0; i
<this.size
.x
; i
++) {
623 for (let j
=0; j
<this.size
.y
; j
++) {
624 if (this.g_pieces
[i
][j
]) {
625 this.g_pieces
[i
][j
].remove();
626 this.g_pieces
[i
][j
] = null;
632 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
634 document
.getElementById(this.containerId
).querySelector(".chessboard");
636 r
= chessboard
.getBoundingClientRect();
637 const pieceWidth
= this.getPieceWidth(r
.width
);
638 for (let i
=0; i
< this.size
.x
; i
++) {
639 for (let j
=0; j
< this.size
.y
; j
++) {
640 if (this.board
[i
][j
] != "") {
641 const color
= this.getColor(i
, j
);
642 const piece
= this.getPiece(i
, j
);
643 this.g_pieces
[i
][j
] = document
.createElement("piece");
644 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
645 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
646 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
647 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
648 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
649 // Translate coordinates to use chessboard as reference:
650 this.g_pieces
[i
][j
].style
.transform
=
651 `translate(${ip - r.x}px,${jp - r.y}px)`;
652 if (this.enlightened
&& !this.enlightened
[i
][j
])
653 this.g_pieces
[i
][j
].classList
.add("hidden");
654 chessboard
.appendChild(this.g_pieces
[i
][j
]);
659 this.re_drawReserve(['w', 'b'], r
);
662 // NOTE: assume !!this.reserve
663 re_drawReserve(colors
, r
) {
665 // Remove (old) reserve pieces
666 for (let c
of colors
) {
667 if (!this.reserve
[c
])
669 Object
.keys(this.reserve
[c
]).forEach(p
=> {
670 if (this.r_pieces
[c
][p
]) {
671 this.r_pieces
[c
][p
].remove();
672 delete this.r_pieces
[c
][p
];
673 const numId
= this.getReserveNumId(c
, p
);
674 document
.getElementById(numId
).remove();
677 let reservesDiv
= document
.getElementById("reserves_" + c
);
679 reservesDiv
.remove();
683 this.r_pieces
= { w: {}, b: {} };
684 let container
= document
.getElementById(this.containerId
);
686 r
= container
.querySelector(".chessboard").getBoundingClientRect();
687 for (let c
of colors
) {
688 if (!this.reserve
[c
])
690 const nbR
= this.getNbReservePieces(c
);
693 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
695 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
696 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
697 let rcontainer
= document
.createElement("div");
698 rcontainer
.id
= "reserves_" + c
;
699 rcontainer
.classList
.add("reserves");
700 rcontainer
.style
.left
= i0
+ "px";
701 rcontainer
.style
.top
= j0
+ "px";
702 // NOTE: +1 fix display bug on Firefox at least
703 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
704 rcontainer
.style
.height
= sqResSize
+ "px";
705 container
.appendChild(rcontainer
);
706 for (let p
of Object
.keys(this.reserve
[c
])) {
707 if (this.reserve
[c
][p
] == 0)
709 let r_cell
= document
.createElement("div");
710 r_cell
.id
= this.coordsToId({x: c
, y: p
});
711 r_cell
.classList
.add("reserve-cell");
712 r_cell
.style
.width
= sqResSize
+ "px";
713 r_cell
.style
.height
= sqResSize
+ "px";
714 rcontainer
.appendChild(r_cell
);
715 let piece
= document
.createElement("piece");
716 const pieceSpec
= this.pieces()[p
];
717 piece
.classList
.add(pieceSpec
["class"]);
718 piece
.classList
.add(C
.GetColorClass(c
));
719 piece
.style
.width
= "100%";
720 piece
.style
.height
= "100%";
721 this.r_pieces
[c
][p
] = piece
;
722 r_cell
.appendChild(piece
);
723 let number
= document
.createElement("div");
724 number
.textContent
= this.reserve
[c
][p
];
725 number
.classList
.add("reserve-num");
726 number
.id
= this.getReserveNumId(c
, p
);
727 const fontSize
= "1.3em";
728 number
.style
.fontSize
= fontSize
;
729 number
.style
.fontSize
= fontSize
;
730 r_cell
.appendChild(number
);
736 updateReserve(color
, piece
, count
) {
737 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
738 piece
= "k"; //capturing cannibal king: back to king form
739 const oldCount
= this.reserve
[color
][piece
];
740 this.reserve
[color
][piece
] = count
;
741 // Redrawing is much easier if count==0
742 if ([oldCount
, count
].includes(0))
743 this.re_drawReserve([color
]);
745 const numId
= this.getReserveNumId(color
, piece
);
746 document
.getElementById(numId
).textContent
= count
;
750 // Apply diff this.enlightened --> oldEnlightened on board
751 graphUpdateEnlightened() {
753 document
.getElementById(this.containerId
).querySelector(".chessboard");
754 const r
= chessboard
.getBoundingClientRect();
755 const pieceWidth
= this.getPieceWidth(r
.width
);
756 for (let x
=0; x
<this.size
.x
; x
++) {
757 for (let y
=0; y
<this.size
.y
; y
++) {
758 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
759 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
760 elt
.classList
.add("in-shadow");
761 if (this.g_pieces
[x
][y
])
762 this.g_pieces
[x
][y
].classList
.add("hidden");
764 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
765 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
766 elt
.classList
.remove("in-shadow");
767 if (this.g_pieces
[x
][y
])
768 this.g_pieces
[x
][y
].classList
.remove("hidden");
774 // Resize board: no need to destroy/recreate pieces
777 document
.getElementById(this.containerId
).querySelector(".chessboard");
778 const r
= chessboard
.getBoundingClientRect();
779 const multFact
= (mode
== "up" ? 1.05 : 0.95);
780 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
782 if (newWidth
> window
.innerWidth
) {
783 newWidth
= window
.innerWidth
;
784 newHeight
= newWidth
/ this.size
.ratio
;
786 if (newHeight
> window
.innerHeight
) {
787 newHeight
= window
.innerHeight
;
788 newWidth
= newHeight
* this.size
.ratio
;
790 chessboard
.style
.width
= newWidth
+ "px";
791 chessboard
.style
.height
= newHeight
+ "px";
792 const newX
= (window
.innerWidth
- newWidth
) / 2;
793 chessboard
.style
.left
= newX
+ "px";
794 const newY
= (window
.innerHeight
- newHeight
) / 2;
795 chessboard
.style
.top
= newY
+ "px";
796 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
797 const pieceWidth
= this.getPieceWidth(newWidth
);
798 // NOTE: next "if" for variants which use squares filling
799 // instead of "physical", moving pieces
801 for (let i
=0; i
< this.size
.x
; i
++) {
802 for (let j
=0; j
< this.size
.y
; j
++) {
803 if (this.g_pieces
[i
][j
]) {
804 // NOTE: could also use CSS transform "scale"
805 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
806 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
807 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
808 // Translate coordinates to use chessboard as reference:
809 this.g_pieces
[i
][j
].style
.transform
=
810 `translate(${ip - newX}px,${jp - newY}px)`;
816 this.rescaleReserve(newR
);
820 for (let c
of ['w','b']) {
821 if (!this.reserve
[c
])
823 const nbR
= this.getNbReservePieces(c
);
826 // Resize container first
827 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
828 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
829 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
830 let rcontainer
= document
.getElementById("reserves_" + c
);
831 rcontainer
.style
.left
= i0
+ "px";
832 rcontainer
.style
.top
= j0
+ "px";
833 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
834 rcontainer
.style
.height
= sqResSize
+ "px";
835 // And then reserve cells:
836 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
837 Object
.keys(this.reserve
[c
]).forEach(p
=> {
838 if (this.reserve
[c
][p
] == 0)
840 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
841 r_cell
.style
.width
= sqResSize
+ "px";
842 r_cell
.style
.height
= sqResSize
+ "px";
847 // Return the absolute pixel coordinates given current position.
848 // Our coordinate system differs from CSS one (x <--> y).
849 // We return here the CSS coordinates (more useful).
850 getPixelPosition(i
, j
, r
) {
852 return [0, 0]; //piece vanishes
854 if (typeof i
== "string") {
855 // Reserves: need to know the rank of piece
856 const nbR
= this.getNbReservePieces(i
);
857 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
858 x
= this.getRankInReserve(i
, j
) * rsqSize
;
859 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
862 const sqSize
= r
.width
/ this.size
.y
;
863 const flipped
= (this.playerColor
== 'b');
864 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
865 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
867 return [r
.x
+ x
, r
.y
+ y
];
871 let container
= document
.getElementById(this.containerId
);
872 let chessboard
= container
.querySelector(".chessboard");
874 const getOffset
= e
=> {
877 return {x: e
.clientX
, y: e
.clientY
};
878 let touchLocation
= null;
879 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
880 // Touch screen, dragstart
881 touchLocation
= e
.targetTouches
[0];
882 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
883 // Touch screen, dragend
884 touchLocation
= e
.changedTouches
[0];
886 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
887 return {x: 0, y: 0}; //shouldn't reach here =)
890 const centerOnCursor
= (piece
, e
) => {
891 const centerShift
= this.getPieceWidth(r
.width
) / 2;
892 const offset
= getOffset(e
);
893 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
894 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
899 startPiece
, curPiece
= null,
901 const mousedown
= (e
) => {
902 // Disable zoom on smartphones:
903 if (e
.touches
&& e
.touches
.length
> 1)
905 r
= chessboard
.getBoundingClientRect();
906 pieceWidth
= this.getPieceWidth(r
.width
);
907 const cd
= this.idToCoords(e
.target
.id
);
909 const move = this.doClick(cd
);
911 this.playPlusVisual(move);
913 const [x
, y
] = Object
.values(cd
);
914 if (typeof x
!= "number")
915 startPiece
= this.r_pieces
[x
][y
];
917 startPiece
= this.g_pieces
[x
][y
];
918 if (startPiece
&& this.canIplay(x
, y
)) {
921 curPiece
= startPiece
.cloneNode();
922 curPiece
.style
.transform
= "none";
923 curPiece
.style
.zIndex
= 5;
924 curPiece
.style
.width
= pieceWidth
+ "px";
925 curPiece
.style
.height
= pieceWidth
+ "px";
926 centerOnCursor(curPiece
, e
);
927 container
.appendChild(curPiece
);
928 startPiece
.style
.opacity
= "0.4";
929 chessboard
.style
.cursor
= "none";
935 const mousemove
= (e
) => {
938 centerOnCursor(curPiece
, e
);
940 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
941 // Attempt to prevent horizontal swipe...
945 const mouseup
= (e
) => {
946 const newR
= chessboard
.getBoundingClientRect();
947 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
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 const wheelResize
= (e
) => {
976 this.rescale(e
.deltaY
< 0 ? "up" : "down");
979 if ('onmousedown' in window
) {
980 document
.addEventListener("mousedown", mousedown
);
981 document
.addEventListener("mousemove", mousemove
);
982 document
.addEventListener("mouseup", mouseup
);
983 document
.addEventListener("wheel", wheelResize
);
985 if ('ontouchstart' in window
) {
986 // https://stackoverflow.com/a/42509310/12660887
987 document
.addEventListener("touchstart", mousedown
, {passive: false});
988 document
.addEventListener("touchmove", mousemove
, {passive: false});
989 document
.addEventListener("touchend", mouseup
, {passive: false});
991 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
994 showChoices(moves
, r
) {
995 let container
= document
.getElementById(this.containerId
);
996 let chessboard
= container
.querySelector(".chessboard");
997 let choices
= document
.createElement("div");
998 choices
.id
= "choices";
999 choices
.style
.width
= r
.width
+ "px";
1000 choices
.style
.height
= r
.height
+ "px";
1001 choices
.style
.left
= r
.x
+ "px";
1002 choices
.style
.top
= r
.y
+ "px";
1003 chessboard
.style
.opacity
= "0.5";
1004 container
.appendChild(choices
);
1005 const squareWidth
= r
.width
/ this.size
.y
;
1006 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1007 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1008 const color
= moves
[0].appear
[0].c
;
1009 const callback
= (m
) => {
1010 chessboard
.style
.opacity
= "1";
1011 container
.removeChild(choices
);
1012 this.playPlusVisual(m
, r
);
1014 for (let i
=0; i
< moves
.length
; i
++) {
1015 let choice
= document
.createElement("div");
1016 choice
.classList
.add("choice");
1017 choice
.style
.width
= squareWidth
+ "px";
1018 choice
.style
.height
= squareWidth
+ "px";
1019 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1020 choice
.style
.top
= firstUpTop
+ "px";
1021 choice
.style
.backgroundColor
= "lightyellow";
1022 choice
.onclick
= () => callback(moves
[i
]);
1023 const piece
= document
.createElement("piece");
1024 const pieceSpec
= this.pieces()[moves
[i
].appear
[0].p
];
1025 piece
.classList
.add(pieceSpec
["class"]);
1026 piece
.classList
.add(C
.GetColorClass(color
));
1027 piece
.style
.width
= "100%";
1028 piece
.style
.height
= "100%";
1029 choice
.appendChild(piece
);
1030 choices
.appendChild(choice
);
1041 ratio: 1 //for rectangular board = y / x
1045 // Color of thing on square (i,j). 'undefined' if square is empty
1047 if (typeof i
== "string")
1048 return i
; //reserves
1049 return this.board
[i
][j
].charAt(0);
1052 static GetColorClass(c
) {
1053 return (c
== 'w' ? "white" : "black");
1056 // Assume square i,j isn't empty
1058 if (typeof j
== "string")
1059 return j
; //reserves
1060 return this.board
[i
][j
].charAt(1);
1063 // Piece type on square (i,j)
1064 getPieceType(i
, j
) {
1065 const p
= this.getPiece(i
, j
);
1066 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1069 // Get opponent color
1070 static GetOppCol(color
) {
1071 return (color
== "w" ? "b" : "w");
1074 // Can thing on square1 capture (no return) thing on square2?
1075 canTake([x1
, y1
], [x2
, y2
]) {
1076 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1079 // Is (x,y) on the chessboard?
1081 return (x
>= 0 && x
< this.size
.x
&&
1082 y
>= 0 && y
< this.size
.y
);
1085 // Am I allowed to move thing at square x,y ?
1087 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1090 ////////////////////////
1091 // PIECES SPECIFICATIONS
1093 pieces(color
, x
, y
) {
1094 const pawnShift
= (color
== "w" ? -1 : 1);
1095 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1096 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1102 steps: [[pawnShift
, 0]],
1103 range: (initRank
? 2 : 1)
1108 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1117 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1126 [1, 2], [1, -2], [-1, 2], [-1, -2],
1127 [2, 1], [-2, 1], [2, -1], [-2, -1]
1137 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1146 [0, 1], [0, -1], [1, 0], [-1, 0],
1147 [1, 1], [1, -1], [-1, 1], [-1, -1]
1158 [0, 1], [0, -1], [1, 0], [-1, 0],
1159 [1, 1], [1, -1], [-1, 1], [-1, -1]
1166 '!': {"class": "king-pawn", moveas: "p"},
1167 '#': {"class": "king-rook", moveas: "r"},
1168 '$': {"class": "king-knight", moveas: "n"},
1169 '%': {"class": "king-bishop", moveas: "b"},
1170 '*': {"class": "king-queen", moveas: "q"}
1174 ////////////////////
1177 // For Cylinder: get Y coordinate
1179 if (!this.options
["cylinder"])
1181 let res
= y
% this.size
.y
;
1187 // Stop at the first capture found
1188 atLeastOneCapture(color
) {
1189 color
= color
|| this.turn
;
1190 const oppCol
= C
.GetOppCol(color
);
1191 for (let i
= 0; i
< this.size
.x
; i
++) {
1192 for (let j
= 0; j
< this.size
.y
; j
++) {
1193 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1194 const allSpecs
= this.pieces(color
, i
, j
)
1195 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1196 const attacks
= specs
.attack
|| specs
.moves
;
1197 for (let a
of attacks
) {
1198 outerLoop: for (let step
of a
.steps
) {
1199 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1200 let stepCounter
= 1;
1201 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1202 if (a
.range
<= stepCounter
++)
1205 jj
= this.getY(jj
+ step
[1]);
1208 this.onBoard(ii
, jj
) &&
1209 this.getColor(ii
, jj
) == oppCol
&&
1211 [this.getBasicMove([i
, j
], [ii
, jj
])]
1224 getDropMovesFrom([c
, p
]) {
1225 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1226 // (but not necessarily otherwise: atLeastOneMove() etc)
1227 if (this.reserve
[c
][p
] == 0)
1230 for (let i
=0; i
<this.size
.x
; i
++) {
1231 for (let j
=0; j
<this.size
.y
; j
++) {
1233 this.board
[i
][j
] == "" &&
1234 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1237 (c
== 'w' && i
< this.size
.x
- 1) ||
1243 start: {x: c
, y: p
},
1245 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1255 // All possible moves from selected square
1256 getPotentialMovesFrom(sq
, color
) {
1257 if (this.subTurnTeleport
== 2)
1259 if (typeof sq
[0] == "string")
1260 return this.getDropMovesFrom(sq
);
1261 if (this.isImmobilized(sq
))
1263 const piece
= this.getPieceType(sq
[0], sq
[1]);
1264 let moves
= this.getPotentialMovesOf(piece
, sq
);
1267 this.hasEnpassant
&&
1270 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1275 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1277 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1279 return this.postProcessPotentialMoves(moves
);
1282 postProcessPotentialMoves(moves
) {
1283 if (moves
.length
== 0)
1285 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1286 const oppCol
= C
.GetOppCol(color
);
1288 if (this.options
["capture"] && this.atLeastOneCapture())
1289 moves
= this.capturePostProcess(moves
, oppCol
);
1291 if (this.options
["atomic"])
1292 this.atomicPostProcess(moves
, oppCol
);
1296 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1298 this.pawnPostProcess(moves
, color
, oppCol
);
1302 this.options
["cannibal"] &&
1303 this.options
["rifle"]
1305 // In this case a rifle-capture from last rank may promote a pawn
1306 this.riflePromotePostProcess(moves
, color
);
1312 capturePostProcess(moves
, oppCol
) {
1313 // Filter out non-capturing moves (not using m.vanish because of
1314 // self captures of Recycle and Teleport).
1315 return moves
.filter(m
=> {
1317 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1318 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1323 atomicPostProcess(moves
, oppCol
) {
1324 moves
.forEach(m
=> {
1326 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1327 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1340 for (let step
of steps
) {
1341 let x
= m
.end
.x
+ step
[0];
1342 let y
= this.getY(m
.end
.y
+ step
[1]);
1344 this.onBoard(x
, y
) &&
1345 this.board
[x
][y
] != "" &&
1346 this.getPieceType(x
, y
) != "p"
1350 p: this.getPiece(x
, y
),
1351 c: this.getColor(x
, y
),
1358 if (!this.options
["rifle"])
1359 m
.appear
.pop(); //nothing appears
1364 pawnPostProcess(moves
, color
, oppCol
) {
1366 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1367 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1368 moves
.forEach(m
=> {
1369 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1370 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1371 const promotionOk
= (
1373 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1376 return; //nothing to do
1377 if (this.options
["pawnfall"]) {
1381 let finalPieces
= ["p"];
1383 this.options
["cannibal"] &&
1384 this.board
[x2
][y2
] != "" &&
1385 this.getColor(x2
, y2
) == oppCol
1387 finalPieces
= [this.getPieceType(x2
, y2
)];
1390 finalPieces
= this.pawnPromotions
;
1391 m
.appear
[0].p
= finalPieces
[0];
1392 if (initPiece
== "!") //cannibal king-pawn
1393 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1394 for (let i
=1; i
<finalPieces
.length
; i
++) {
1395 const piece
= finalPieces
[i
];
1398 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1400 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1401 moreMoves
.push(newMove
);
1404 Array
.prototype.push
.apply(moves
, moreMoves
);
1407 riflePromotePostProcess(moves
, color
) {
1408 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1410 moves
.forEach(m
=> {
1412 m
.start
.x
== lastRank
&&
1413 m
.appear
.length
>= 1 &&
1414 m
.appear
[0].p
== "p" &&
1415 m
.appear
[0].x
== m
.start
.x
&&
1416 m
.appear
[0].y
== m
.start
.y
1418 m
.appear
[0].p
= this.pawnPromotions
[0];
1419 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1420 let newMv
= JSON
.parse(JSON
.stringify(m
));
1421 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1422 newMoves
.push(newMv
);
1426 Array
.prototype.push
.apply(moves
, newMoves
);
1429 // NOTE: using special symbols to not interfere with variants' pieces codes
1430 static get CannibalKings() {
1441 static get CannibalKingCode() {
1453 return !!C
.CannibalKings
[symbol
];
1457 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1458 isImmobilized([x
, y
]) {
1459 if (!this.options
["madrasi"])
1461 const color
= this.getColor(x
, y
);
1462 const oppCol
= C
.GetOppCol(color
);
1463 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1464 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1465 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1466 for (let a
of attacks
) {
1467 outerLoop: for (let step
of a
.steps
) {
1468 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1469 let stepCounter
= 1;
1470 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1471 if (a
.range
<= stepCounter
++)
1474 j
= this.getY(j
+ step
[1]);
1477 this.onBoard(i
, j
) &&
1478 this.getColor(i
, j
) == oppCol
&&
1479 this.getPieceType(i
, j
) == piece
1488 // Generic method to find possible moves of "sliding or jumping" pieces
1489 getPotentialMovesOf(piece
, [x
, y
]) {
1490 const color
= this.getColor(x
, y
);
1491 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1493 // Next 3 for Cylinder mode:
1498 const addMove
= (start
, end
) => {
1499 let newMove
= this.getBasicMove(start
, end
);
1500 if (segments
.length
> 0) {
1501 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1502 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1504 moves
.push(newMove
);
1507 const findAddMoves
= (type
, stepArray
) => {
1508 for (let s
of stepArray
) {
1509 outerLoop: for (let step
of s
.steps
) {
1512 let [i
, j
] = [x
, y
];
1513 let stepCounter
= 0;
1515 this.onBoard(i
, j
) &&
1516 (this.board
[i
][j
] == "" || (i
== x
&& j
== y
))
1520 !explored
[i
+ "." + j
] &&
1523 explored
[i
+ "." + j
] = true;
1524 addMove([x
, y
], [i
, j
]);
1526 if (s
.range
<= stepCounter
++)
1528 const oldIJ
= [i
, j
];
1530 j
= this.getY(j
+ step
[1]);
1531 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1532 // Boundary between segments (cylinder mode)
1533 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1537 if (!this.onBoard(i
, j
))
1539 const pieceIJ
= this.getPieceType(i
, j
);
1541 type
!= "moveonly" &&
1542 !explored
[i
+ "." + j
] &&
1544 !this.options
["zen"] ||
1548 this.canTake([x
, y
], [i
, j
]) ||
1550 (this.options
["recycle"] || this.options
["teleport"]) &&
1555 explored
[i
+ "." + j
] = true;
1556 addMove([x
, y
], [i
, j
]);
1562 const specialAttack
= !!stepSpec
.attack
;
1564 findAddMoves("attack", stepSpec
.attack
);
1565 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1566 if (this.options
["zen"]) {
1567 Array
.prototype.push
.apply(moves
,
1568 this.findCapturesOn([x
, y
], {zen: true}));
1573 // Search for enemy (or not) pieces attacking [x, y]
1574 findCapturesOn([x
, y
], args
) {
1577 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1578 for (let i
=0; i
<this.size
.x
; i
++) {
1579 for (let j
=0; j
<this.size
.y
; j
++) {
1581 this.board
[i
][j
] != "" &&
1582 this.getColor(i
, j
) == args
.oppCol
&&
1583 !this.isImmobilized([i
, j
])
1585 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1586 continue; //king not captured in this way
1588 this.pieces(args
.oppCol
, i
, j
)[this.getPieceType(i
, j
)];
1589 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1590 for (let a
of attacks
) {
1591 for (let s
of a
.steps
) {
1592 // Quick check: if step isn't compatible, don't even try
1593 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1595 // Finally verify that nothing stand in-between
1596 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1597 let stepCounter
= 1;
1599 this.onBoard(ii
, jj
) &&
1600 this.board
[ii
][jj
] == "" &&
1601 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1604 jj
= this.getY(jj
+ s
[1]);
1606 if (ii
== x
&& jj
== y
) {
1609 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1611 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1613 return moves
; //test for underCheck
1623 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1624 const rx
= (x2
- x1
) / step
[0],
1625 ry
= (y2
- y1
) / step
[1];
1627 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1628 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1632 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1633 // TODO: 1e-7 here is totally arbitrary
1634 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1636 distance
= Math
.round(distance
); //in case of (numerical...)
1637 if (range
< distance
)
1642 // Build a regular move from its initial and destination squares.
1643 // tr: transformation
1644 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1645 const initColor
= this.getColor(sx
, sy
);
1646 const initPiece
= this.getPiece(sx
, sy
);
1647 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1651 start: {x: sx
, y: sy
},
1655 !this.options
["rifle"] ||
1656 this.board
[ex
][ey
] == "" ||
1657 destColor
== initColor
//Recycle, Teleport
1663 c: !!tr
? tr
.c : initColor
,
1664 p: !!tr
? tr
.p : initPiece
1676 if (this.board
[ex
][ey
] != "") {
1681 c: this.getColor(ex
, ey
),
1682 p: this.getPiece(ex
, ey
)
1685 if (this.options
["cannibal"] && destColor
!= initColor
) {
1686 const lastIdx
= mv
.vanish
.length
- 1;
1687 let trPiece
= mv
.vanish
[lastIdx
].p
;
1688 if (this.isKing(this.getPiece(sx
, sy
)))
1689 trPiece
= C
.CannibalKingCode
[trPiece
];
1690 if (mv
.appear
.length
>= 1)
1691 mv
.appear
[0].p
= trPiece
;
1692 else if (this.options
["rifle"]) {
1715 // En-passant square, if any
1716 getEpSquare(moveOrSquare
) {
1717 if (typeof moveOrSquare
=== "string") {
1718 const square
= moveOrSquare
;
1721 return C
.SquareToCoords(square
);
1723 // Argument is a move:
1724 const move = moveOrSquare
;
1725 const s
= move.start
,
1729 Math
.abs(s
.x
- e
.x
) == 2 &&
1730 // Next conditions for variants like Atomic or Rifle, Recycle...
1731 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1732 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1739 return undefined; //default
1742 // Special case of en-passant captures: treated separately
1743 getEnpassantCaptures([x
, y
]) {
1744 const color
= this.getColor(x
, y
);
1745 const shiftX
= (color
== 'w' ? -1 : 1);
1746 const oppCol
= C
.GetOppCol(color
);
1747 let enpassantMove
= null;
1750 this.epSquare
.x
== x
+ shiftX
&&
1751 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1752 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1754 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1755 this.board
[epx
][epy
] = oppCol
+ "p";
1756 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1757 this.board
[epx
][epy
] = "";
1758 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1759 enpassantMove
.vanish
[lastIdx
].x
= x
;
1761 return !!enpassantMove
? [enpassantMove
] : [];
1764 // "castleInCheck" arg to let some variants castle under check
1765 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1766 const c
= this.getColor(x
, y
);
1769 const oppCol
= C
.GetOppCol(c
);
1773 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1774 const castlingKing
= this.getPiece(x
, y
);
1775 castlingCheck: for (
1778 castleSide
++ //large, then small
1780 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1782 // If this code is reached, rook and king are on initial position
1784 // NOTE: in some variants this is not a rook
1785 const rookPos
= this.castleFlags
[c
][castleSide
];
1786 const castlingPiece
= this.getPiece(x
, rookPos
);
1788 this.board
[x
][rookPos
] == "" ||
1789 this.getColor(x
, rookPos
) != c
||
1790 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1792 // Rook is not here, or changed color (see Benedict)
1795 // Nothing on the path of the king ? (and no checks)
1796 const finDist
= finalSquares
[castleSide
][0] - y
;
1797 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1801 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1803 this.board
[x
][i
] != "" &&
1804 // NOTE: next check is enough, because of chessboard constraints
1805 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1808 continue castlingCheck
;
1811 } while (i
!= finalSquares
[castleSide
][0]);
1812 // Nothing on the path to the rook?
1813 step
= (castleSide
== 0 ? -1 : 1);
1814 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1815 if (this.board
[x
][i
] != "")
1816 continue castlingCheck
;
1819 // Nothing on final squares, except maybe king and castling rook?
1820 for (i
= 0; i
< 2; i
++) {
1822 finalSquares
[castleSide
][i
] != rookPos
&&
1823 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1825 finalSquares
[castleSide
][i
] != y
||
1826 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1829 continue castlingCheck
;
1833 // If this code is reached, castle is valid
1839 y: finalSquares
[castleSide
][0],
1845 y: finalSquares
[castleSide
][1],
1851 // King might be initially disguised (Titan...)
1852 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1853 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1856 Math
.abs(y
- rookPos
) <= 2
1857 ? {x: x
, y: rookPos
}
1858 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1866 ////////////////////
1869 // Is (king at) given position under check by "oppCol" ?
1870 underCheck([x
, y
], oppCol
) {
1871 if (this.options
["taking"] || this.options
["dark"])
1874 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1878 // Stop at first king found (TODO: multi-kings)
1879 searchKingPos(color
) {
1880 for (let i
=0; i
< this.size
.x
; i
++) {
1881 for (let j
=0; j
< this.size
.y
; j
++) {
1882 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1886 return [-1, -1]; //king not found
1889 filterValid(moves
) {
1890 if (moves
.length
== 0)
1892 const color
= this.turn
;
1893 const oppCol
= C
.GetOppCol(color
);
1894 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1895 // Forbid moves either giving check or exploding opponent's king:
1896 const oppKingPos
= this.searchKingPos(oppCol
);
1897 moves
= moves
.filter(m
=> {
1899 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1900 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1903 this.playOnBoard(m
);
1904 const res
= !this.underCheck(oppKingPos
, color
);
1905 this.undoOnBoard(m
);
1909 if (this.options
["taking"] || this.options
["dark"])
1911 const kingPos
= this.searchKingPos(color
);
1912 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1913 return moves
.filter(m
=> {
1914 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1915 if (!filtered
[key
]) {
1916 this.playOnBoard(m
);
1917 let square
= kingPos
,
1918 res
= true; //a priori valid
1919 if (m
.vanish
.some(v
=> {
1920 return C
.CannibalKings
[v
.p
] && v
.c
== color
;
1922 // Search king in appear array:
1924 m
.appear
.findIndex(a
=> {
1925 return C
.CannibalKings
[a
.p
] && a
.c
== color
;
1927 if (newKingIdx
>= 0)
1928 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1932 res
&&= !this.underCheck(square
, oppCol
);
1933 this.undoOnBoard(m
);
1934 filtered
[key
] = res
;
1937 return filtered
[key
];
1944 // Aggregate flags into one object
1946 return this.castleFlags
;
1949 // Reverse operation
1950 disaggregateFlags(flags
) {
1951 this.castleFlags
= flags
;
1954 // Apply a move on board
1956 for (let psq
of move.vanish
)
1957 this.board
[psq
.x
][psq
.y
] = "";
1958 for (let psq
of move.appear
)
1959 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1961 // Un-apply the played move
1963 for (let psq
of move.appear
)
1964 this.board
[psq
.x
][psq
.y
] = "";
1965 for (let psq
of move.vanish
)
1966 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1969 updateCastleFlags(move) {
1970 // Update castling flags if start or arrive from/at rook/king locations
1971 move.appear
.concat(move.vanish
).forEach(psq
=> {
1973 this.board
[psq
.x
][psq
.y
] != "" &&
1974 this.getPieceType(psq
.x
, psq
.y
) == "k"
1976 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1978 // NOTE: not "else if" because king can capture enemy rook...
1982 else if (psq
.x
== this.size
.x
- 1)
1985 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1987 this.castleFlags
[c
][fidx
] = this.size
.y
;
1995 // If flags already off, no need to re-check:
1996 Object
.keys(this.castleFlags
).some(c
=> {
1997 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1999 this.updateCastleFlags(move);
2001 if (this.options
["crazyhouse"]) {
2002 move.vanish
.forEach(v
=> {
2003 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2004 if (this.ispawn
[square
])
2005 delete this.ispawn
[square
];
2007 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2008 // Assumption: something is moving
2009 const initSquare
= C
.CoordsToSquare(move.start
);
2010 const destSquare
= C
.CoordsToSquare(move.end
);
2012 this.ispawn
[initSquare
] ||
2013 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2015 this.ispawn
[destSquare
] = true;
2018 this.ispawn
[destSquare
] &&
2019 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2021 move.vanish
[1].p
= "p";
2022 delete this.ispawn
[destSquare
];
2026 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2029 // Warning; atomic pawn removal isn't a capture
2030 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2032 const color
= this.turn
;
2033 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2034 // Something appears = dropped on board (some exceptions, Chakart...)
2035 if (move.appear
[i
].c
== color
) {
2036 const piece
= move.appear
[i
].p
;
2037 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2040 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2041 // Something vanish: add to reserve except if recycle & opponent
2043 this.options
["crazyhouse"] ||
2044 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2046 const piece
= move.vanish
[i
].p
;
2047 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2055 if (this.hasEnpassant
)
2056 this.epSquare
= this.getEpSquare(move);
2057 this.playOnBoard(move);
2058 this.postPlay(move);
2062 const color
= this.turn
;
2063 const oppCol
= C
.GetOppCol(color
);
2064 if (this.options
["dark"])
2065 this.updateEnlightened();
2066 if (this.options
["teleport"]) {
2068 this.subTurnTeleport
== 1 &&
2069 move.vanish
.length
> move.appear
.length
&&
2070 move.vanish
[move.vanish
.length
- 1].c
== color
2072 const v
= move.vanish
[move.vanish
.length
- 1];
2073 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2074 this.subTurnTeleport
= 2;
2077 this.subTurnTeleport
= 1;
2078 this.captured
= null;
2080 if (this.options
["balance"]) {
2081 if (![1, 3].includes(this.movesCount
))
2087 this.options
["doublemove"] &&
2088 this.movesCount
>= 1 &&
2091 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2093 const oppKingPos
= this.searchKingPos(oppCol
);
2095 oppKingPos
[0] >= 0 &&
2097 this.options
["taking"] ||
2098 !this.underCheck(oppKingPos
, color
)
2111 // "Stop at the first move found"
2112 atLeastOneMove(color
) {
2113 color
= color
|| this.turn
;
2114 for (let i
= 0; i
< this.size
.x
; i
++) {
2115 for (let j
= 0; j
< this.size
.y
; j
++) {
2116 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2117 // NOTE: in fact searching for all potential moves from i,j.
2118 // I don't believe this is an issue, for now at least.
2119 const moves
= this.getPotentialMovesFrom([i
, j
]);
2120 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2125 if (this.hasReserve
&& this.reserve
[color
]) {
2126 for (let p
of Object
.keys(this.reserve
[color
])) {
2127 const moves
= this.getDropMovesFrom([color
, p
]);
2128 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2135 // What is the score ? (Interesting if game is over)
2136 getCurrentScore(move) {
2137 const color
= this.turn
;
2138 const oppCol
= C
.GetOppCol(color
);
2139 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2140 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2142 if (kingPos
[0][0] < 0)
2143 return (color
== "w" ? "0-1" : "1-0");
2144 if (kingPos
[1][0] < 0)
2145 return (color
== "w" ? "1-0" : "0-1");
2146 if (this.atLeastOneMove())
2148 // No valid move: stalemate or checkmate?
2149 if (!this.underCheck(kingPos
[0], color
))
2152 return (color
== "w" ? "0-1" : "1-0");
2155 playVisual(move, r
) {
2156 move.vanish
.forEach(v
=> {
2157 this.g_pieces
[v
.x
][v
.y
].remove();
2158 this.g_pieces
[v
.x
][v
.y
] = null;
2161 document
.getElementById(this.containerId
).querySelector(".chessboard");
2163 r
= chessboard
.getBoundingClientRect();
2164 const pieceWidth
= this.getPieceWidth(r
.width
);
2165 move.appear
.forEach(a
=> {
2166 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2167 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2168 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2169 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2170 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2171 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2172 // Translate coordinates to use chessboard as reference:
2173 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2174 `translate(${ip - r.x}px,${jp - r.y}px)`;
2175 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2176 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2177 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2179 if (this.options
["dark"])
2180 this.graphUpdateEnlightened();
2183 playPlusVisual(move, r
) {
2185 this.playVisual(move, r
);
2186 this.afterPlay(move); //user method
2189 getMaxDistance(rwidth
) {
2190 // Works for all rectangular boards:
2191 return Math
.sqrt(rwidth
** 2 + (rwidth
/ this.size
.ratio
) ** 2);
2195 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2198 animate(move, callback
) {
2199 if (this.noAnimate
|| move.noAnimate
) {
2203 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2204 // NOTE: cloning generally not required, but light enough, and simpler
2205 let movingPiece
= initPiece
.cloneNode();
2206 initPiece
.style
.opacity
= "0";
2208 document
.getElementById(this.containerId
)
2209 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2210 if (typeof move.start
.x
== "string") {
2211 // Need to bound width/height (was 100% for reserve pieces)
2212 const pieceWidth
= this.getPieceWidth(r
.width
);
2213 movingPiece
.style
.width
= pieceWidth
+ "px";
2214 movingPiece
.style
.height
= pieceWidth
+ "px";
2216 const maxDist
= this.getMaxDistance(r
.width
);
2217 const pieces
= this.pieces();
2219 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2220 movingPiece
.classList
.remove(pieces
[startCode
]["class"]);
2221 movingPiece
.classList
.add(pieces
[move.drag
.p
]["class"]);
2222 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2223 if (apparentColor
!= move.drag
.c
) {
2224 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2225 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2228 container
.appendChild(movingPiece
);
2229 const animateSegment
= (index
, cb
) => {
2230 // NOTE: move.drag could be generalized per-segment (usage?)
2231 const [i1
, j1
] = move.segments
[index
][0];
2232 const [i2
, j2
] = move.segments
[index
][1];
2233 const dep
= this.getPixelPosition(i1
, j1
, r
);
2234 const arr
= this.getPixelPosition(i2
, j2
, r
);
2235 movingPiece
.style
.transitionDuration
= "0s";
2236 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2238 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2239 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2240 // TODO: unclear why we need this new delay below:
2242 movingPiece
.style
.transitionDuration
= duration
+ "s";
2243 // movingPiece is child of container: no need to adjust coordinates
2244 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2245 setTimeout(cb
, duration
* 1000);
2248 if (!move.segments
) {
2250 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2254 const animateSegmentCallback
= () => {
2255 if (index
< move.segments
.length
)
2256 animateSegment(index
++, animateSegmentCallback
);
2258 movingPiece
.remove();
2259 initPiece
.style
.opacity
= "1";
2263 animateSegmentCallback();
2266 playReceivedMove(moves
, callback
) {
2267 const launchAnimation
= () => {
2268 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2269 const animateRec
= i
=> {
2270 this.animate(moves
[i
], () => {
2271 this.play(moves
[i
]);
2272 this.playVisual(moves
[i
], r
);
2273 if (i
< moves
.length
- 1)
2274 setTimeout(() => animateRec(i
+1), 300);
2281 // Delay if user wasn't focused:
2282 const checkDisplayThenAnimate
= (delay
) => {
2283 if (container
.style
.display
== "none") {
2284 alert("New move! Let's go back to game...");
2285 document
.getElementById("gameInfos").style
.display
= "none";
2286 container
.style
.display
= "block";
2287 setTimeout(launchAnimation
, 700);
2290 setTimeout(launchAnimation
, delay
|| 0);
2292 let container
= document
.getElementById(this.containerId
);
2293 if (document
.hidden
) {
2294 document
.onvisibilitychange
= () => {
2295 document
.onvisibilitychange
= undefined;
2296 checkDisplayThenAnimate(700);
2300 checkDisplayThenAnimate();