b150fcb083fb2cf4edaa657bb2e6d2790535e656
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,
112 drag: {c: this.captured
.c
, p: this.captured
.p
}
121 // 3a --> {x:3, y:10}
122 static SquareToCoords(sq
) {
123 return ArrayFun
.toObject(["x", "y"],
124 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
127 // {x:11, y:12} --> bc
128 static CoordsToSquare(cd
) {
129 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
133 if (typeof cd
.x
== "number") {
135 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
139 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
142 idToCoords(targetId
) {
144 return null; //outside page, maybe...
145 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
147 idParts
.length
< 2 ||
148 idParts
[0] != this.containerId
||
149 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
153 const squares
= idParts
[1].split('-');
154 if (squares
[0] == "sq")
155 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
156 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
157 return {x: squares
[1], y: squares
[2]};
163 // Turn "wb" into "B" (for FEN)
165 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
168 // Turn "p" into "bp" (for board)
170 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
173 // Setup the initial random-or-not (asymmetric-or-not) position
174 genRandInitFen(seed
) {
175 Random
.setSeed(seed
);
177 let fen
, flags
= "0707";
178 if (!this.options
.randomness
)
180 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
184 let pieces
= { w: new Array(8), b: new Array(8) };
186 // Shuffle pieces on first (and last rank if randomness == 2)
187 for (let c
of ["w", "b"]) {
188 if (c
== 'b' && this.options
.randomness
== 1) {
189 pieces
['b'] = pieces
['w'];
194 let positions
= ArrayFun
.range(8);
196 // Get random squares for bishops
197 let randIndex
= 2 * Random
.randInt(4);
198 const bishop1Pos
= positions
[randIndex
];
199 // The second bishop must be on a square of different color
200 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
201 const bishop2Pos
= positions
[randIndex_tmp
];
202 // Remove chosen squares
203 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
204 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
206 // Get random squares for knights
207 randIndex
= Random
.randInt(6);
208 const knight1Pos
= positions
[randIndex
];
209 positions
.splice(randIndex
, 1);
210 randIndex
= Random
.randInt(5);
211 const knight2Pos
= positions
[randIndex
];
212 positions
.splice(randIndex
, 1);
214 // Get random square for queen
215 randIndex
= Random
.randInt(4);
216 const queenPos
= positions
[randIndex
];
217 positions
.splice(randIndex
, 1);
219 // Rooks and king positions are now fixed,
220 // because of the ordering rook-king-rook
221 const rook1Pos
= positions
[0];
222 const kingPos
= positions
[1];
223 const rook2Pos
= positions
[2];
225 // Finally put the shuffled pieces in the board array
226 pieces
[c
][rook1Pos
] = "r";
227 pieces
[c
][knight1Pos
] = "n";
228 pieces
[c
][bishop1Pos
] = "b";
229 pieces
[c
][queenPos
] = "q";
230 pieces
[c
][kingPos
] = "k";
231 pieces
[c
][bishop2Pos
] = "b";
232 pieces
[c
][knight2Pos
] = "n";
233 pieces
[c
][rook2Pos
] = "r";
234 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
237 pieces
["b"].join("") +
238 "/pppppppp/8/8/8/8/PPPPPPPP/" +
239 pieces
["w"].join("").toUpperCase() +
243 // Add turn + flags + enpassant (+ reserve)
246 parts
.push(`"flags":"${flags}"`);
247 if (this.hasEnpassant
)
248 parts
.push('"enpassant":"-"');
250 parts
.push('"reserve":"000000000000"');
251 if (this.options
["crazyhouse"])
252 parts
.push('"ispawn":"-"');
253 if (parts
.length
>= 1)
254 fen
+= " {" + parts
.join(",") + "}";
258 // "Parse" FEN: just return untransformed string data
260 const fenParts
= fen
.split(" ");
262 position: fenParts
[0],
264 movesCount: fenParts
[2]
266 if (fenParts
.length
> 3)
267 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
271 // Return current fen (game state)
274 this.getPosition() + " " +
275 this.getTurnFen() + " " +
280 parts
.push(`"flags":"${this.getFlagsFen()}"`);
281 if (this.hasEnpassant
)
282 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
284 parts
.push(`"reserve":"${this.getReserveFen()}"`);
285 if (this.options
["crazyhouse"])
286 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
287 if (parts
.length
>= 1)
288 fen
+= " {" + parts
.join(",") + "}";
292 // Position part of the FEN string
294 const format
= (count
) => {
295 // if more than 9 consecutive free spaces, break the integer,
296 // otherwise FEN parsing will fail.
299 // Most boards of size < 18:
301 return "9" + (count
- 9);
303 return "99" + (count
- 18);
306 for (let i
= 0; i
< this.size
.y
; i
++) {
308 for (let j
= 0; j
< this.size
.x
; j
++) {
309 if (this.board
[i
][j
] == "")
312 if (emptyCount
> 0) {
313 // Add empty squares in-between
314 position
+= format(emptyCount
);
317 position
+= this.board2fen(this.board
[i
][j
]);
322 position
+= format(emptyCount
);
323 if (i
< this.size
.y
- 1)
324 position
+= "/"; //separate rows
333 // Flags part of the FEN string
335 return ["w", "b"].map(c
=> {
336 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
340 // Enpassant part of the FEN string
343 return "-"; //no en-passant
344 return C
.CoordsToSquare(this.epSquare
);
349 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
354 const squares
= Object
.keys(this.ispawn
);
355 if (squares
.length
== 0)
357 return squares
.join(",");
360 // Set flags from fen (castle: white a,h then black a,h)
363 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
364 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
372 this.options
= o
.options
;
373 this.playerColor
= o
.color
;
374 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
376 // Fen string fully describes the game state
378 o
.fen
= this.genRandInitFen(o
.seed
);
379 const fenParsed
= this.parseFen(o
.fen
);
380 this.board
= this.getBoard(fenParsed
.position
);
381 this.turn
= fenParsed
.turn
;
382 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
383 this.setOtherVariables(fenParsed
);
385 // Graphical (can use variables defined above)
386 this.containerId
= o
.element
;
387 this.graphicalInit();
390 // Turn position fen into double array ["wb","wp","bk",...]
392 const rows
= position
.split("/");
393 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
394 for (let i
= 0; i
< rows
.length
; i
++) {
396 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
397 const character
= rows
[i
][indexInRow
];
398 const num
= parseInt(character
, 10);
399 // If num is a number, just shift j:
402 // Else: something at position i,j
404 board
[i
][j
++] = this.fen2board(character
);
410 // Some additional variables from FEN (variant dependant)
411 setOtherVariables(fenParsed
) {
412 // Set flags and enpassant:
414 this.setFlags(fenParsed
.flags
);
415 if (this.hasEnpassant
)
416 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
418 this.initReserves(fenParsed
.reserve
);
419 if (this.options
["crazyhouse"])
420 this.initIspawn(fenParsed
.ispawn
);
421 this.subTurn
= 1; //may be unused
422 if (this.options
["teleport"]) {
423 this.subTurnTeleport
= 1;
424 this.captured
= null;
426 if (this.options
["dark"]) {
427 // Setup enlightened: squares reachable by player side
428 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
429 this.updateEnlightened();
433 updateEnlightened() {
434 this.oldEnlightened
= this.enlightened
;
435 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
436 // Add pieces positions + all squares reachable by moves (includes Zen):
437 for (let x
=0; x
<this.size
.x
; x
++) {
438 for (let y
=0; y
<this.size
.y
; y
++) {
439 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
441 this.enlightened
[x
][y
] = true;
442 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
443 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
449 this.enlightEnpassant();
452 // Include square of the en-passant capturing square:
454 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
455 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
456 for (let step
of steps
) {
457 const x
= this.epSquare
.x
- step
[0],
458 y
= this.computeY(this.epSquare
.y
- step
[1]);
460 this.onBoard(x
, y
) &&
461 this.getColor(x
, y
) == this.playerColor
&&
462 this.getPieceType(x
, y
) == "p"
464 this.enlightened
[x
][this.epSquare
.y
] = true;
470 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
471 initReserves(reserveStr
) {
472 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
473 this.reserve
= { w: {}, b: {} };
474 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
475 const L
= pieceName
.length
;
476 for (let i
of ArrayFun
.range(2 * L
)) {
478 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
480 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
484 initIspawn(ispawnStr
) {
485 if (ispawnStr
!= "-")
486 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
491 getNbReservePieces(color
) {
493 Object
.values(this.reserve
[color
]).reduce(
494 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
498 getRankInReserve(c
, p
) {
499 const pieces
= Object
.keys(this.pieces());
500 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
501 let toTest
= pieces
.slice(0, lastIndex
);
502 return toTest
.reduce(
503 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
509 getPieceWidth(rwidth
) {
510 return (rwidth
/ this.size
.y
);
513 getReserveSquareSize(rwidth
, nbR
) {
514 const sqSize
= this.getPieceWidth(rwidth
);
515 return Math
.min(sqSize
, rwidth
/ nbR
);
518 getReserveNumId(color
, piece
) {
519 return `${this.containerId}|rnum-${color}${piece}`;
523 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
524 window
.onresize
= () => this.re_drawBoardElements();
525 this.re_drawBoardElements();
526 this.initMouseEvents();
528 document
.getElementById(this.containerId
).querySelector(".chessboard");
529 new ResizeObserver(this.rescale
).observe(chessboard
);
532 re_drawBoardElements() {
533 const board
= this.getSvgChessboard();
534 const oppCol
= C
.GetOppCol(this.playerColor
);
536 document
.getElementById(this.containerId
).querySelector(".chessboard");
537 chessboard
.innerHTML
= "";
538 chessboard
.insertAdjacentHTML('beforeend', board
);
539 // Compare window ratio width / height to aspectRatio:
540 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
541 let cbWidth
, cbHeight
;
542 if (windowRatio
<= this.size
.ratio
) {
543 // Limiting dimension is width:
544 cbWidth
= Math
.min(window
.innerWidth
, 767);
545 cbHeight
= cbWidth
/ this.size
.ratio
;
548 // Limiting dimension is height:
549 cbHeight
= Math
.min(window
.innerHeight
, 767);
550 cbWidth
= cbHeight
* this.size
.ratio
;
553 const sqSize
= cbWidth
/ this.size
.y
;
554 // NOTE: allocate space for reserves (up/down) even if they are empty
555 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
556 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
557 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
558 cbWidth
= cbHeight
* this.size
.ratio
;
561 chessboard
.style
.width
= cbWidth
+ "px";
562 chessboard
.style
.height
= cbHeight
+ "px";
563 // Center chessboard:
564 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
565 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
566 chessboard
.style
.left
= spaceLeft
+ "px";
567 chessboard
.style
.top
= spaceTop
+ "px";
568 // Give sizes instead of recomputing them,
569 // because chessboard might not be drawn yet.
578 // Get SVG board (background, no pieces)
580 const flipped
= (this.playerColor
== 'b');
584 class="chessboard_SVG">
586 for (let i
=0; i
< this.size
.x
; i
++) {
587 for (let j
=0; j
< this.size
.y
; j
++) {
588 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
589 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
590 let classes
= this.getSquareColorClass(ii
, jj
);
591 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
592 classes
+= " in-shadow";
593 // NOTE: x / y reversed because coordinates system is reversed.
596 id="${this.coordsToId({x: ii, y: jj})}"
603 board
+= "</g></svg>";
607 // Generally light square bottom-right
608 getSquareColorClass(x
, y
) {
609 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
614 // Refreshing: delete old pieces first
615 for (let i
=0; i
<this.size
.x
; i
++) {
616 for (let j
=0; j
<this.size
.y
; j
++) {
617 if (this.g_pieces
[i
][j
]) {
618 this.g_pieces
[i
][j
].remove();
619 this.g_pieces
[i
][j
] = null;
625 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
627 document
.getElementById(this.containerId
).querySelector(".chessboard");
629 r
= chessboard
.getBoundingClientRect();
630 const pieceWidth
= this.getPieceWidth(r
.width
);
631 for (let i
=0; i
< this.size
.x
; i
++) {
632 for (let j
=0; j
< this.size
.y
; j
++) {
633 if (this.board
[i
][j
] != "") {
634 const color
= this.getColor(i
, j
);
635 const piece
= this.getPiece(i
, j
);
636 this.g_pieces
[i
][j
] = document
.createElement("piece");
637 this.g_pieces
[i
][j
].classList
.add(this.pieces()[piece
]["class"]);
638 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
639 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
640 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
641 const [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
642 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
643 if (this.enlightened
&& !this.enlightened
[i
][j
])
644 this.g_pieces
[i
][j
].classList
.add("hidden");
645 chessboard
.appendChild(this.g_pieces
[i
][j
]);
650 this.re_drawReserve(['w', 'b'], r
);
653 // NOTE: assume !!this.reserve
654 re_drawReserve(colors
, r
) {
656 // Remove (old) reserve pieces
657 for (let c
of colors
) {
658 if (!this.reserve
[c
])
660 Object
.keys(this.reserve
[c
]).forEach(p
=> {
661 if (this.r_pieces
[c
][p
]) {
662 this.r_pieces
[c
][p
].remove();
663 delete this.r_pieces
[c
][p
];
664 const numId
= this.getReserveNumId(c
, p
);
665 document
.getElementById(numId
).remove();
668 let reservesDiv
= document
.getElementById("reserves_" + c
);
670 reservesDiv
.remove();
674 this.r_pieces
= { 'w': {}, 'b': {} };
676 document
.getElementById(this.containerId
).querySelector(".chessboard");
678 r
= chessboard
.getBoundingClientRect();
679 for (let c
of colors
) {
680 if (!this.reserve
[c
])
682 const nbR
= this.getNbReservePieces(c
);
685 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
687 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
688 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
689 let rcontainer
= document
.createElement("div");
690 rcontainer
.id
= "reserves_" + c
;
691 rcontainer
.classList
.add("reserves");
692 rcontainer
.style
.left
= i0
+ "px";
693 rcontainer
.style
.top
= j0
+ "px";
694 // NOTE: +1 fix display bug on Firefox at least
695 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
696 rcontainer
.style
.height
= sqResSize
+ "px";
697 chessboard
.appendChild(rcontainer
);
698 for (let p
of Object
.keys(this.reserve
[c
])) {
699 if (this.reserve
[c
][p
] == 0)
701 let r_cell
= document
.createElement("div");
702 r_cell
.id
= this.coordsToId({x: c
, y: p
});
703 r_cell
.classList
.add("reserve-cell");
704 r_cell
.style
.width
= sqResSize
+ "px";
705 r_cell
.style
.height
= sqResSize
+ "px";
706 rcontainer
.appendChild(r_cell
);
707 let piece
= document
.createElement("piece");
708 const pieceSpec
= this.pieces()[p
];
709 piece
.classList
.add(pieceSpec
["class"]);
710 piece
.classList
.add(C
.GetColorClass(c
));
711 piece
.style
.width
= "100%";
712 piece
.style
.height
= "100%";
713 this.r_pieces
[c
][p
] = piece
;
714 r_cell
.appendChild(piece
);
715 let number
= document
.createElement("div");
716 number
.textContent
= this.reserve
[c
][p
];
717 number
.classList
.add("reserve-num");
718 number
.id
= this.getReserveNumId(c
, p
);
719 const fontSize
= "1.3em";
720 number
.style
.fontSize
= fontSize
;
721 number
.style
.fontSize
= fontSize
;
722 r_cell
.appendChild(number
);
728 updateReserve(color
, piece
, count
) {
729 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
730 piece
= "k"; //capturing cannibal king: back to king form
731 const oldCount
= this.reserve
[color
][piece
];
732 this.reserve
[color
][piece
] = count
;
733 // Redrawing is much easier if count==0
734 if ([oldCount
, count
].includes(0))
735 this.re_drawReserve([color
]);
737 const numId
= this.getReserveNumId(color
, piece
);
738 document
.getElementById(numId
).textContent
= count
;
742 // Apply diff this.enlightened --> oldEnlightened on board
743 graphUpdateEnlightened() {
745 document
.getElementById(this.containerId
).querySelector(".chessboard");
746 const r
= chessboard
.getBoundingClientRect();
747 const pieceWidth
= this.getPieceWidth(r
.width
);
748 for (let x
=0; x
<this.size
.x
; x
++) {
749 for (let y
=0; y
<this.size
.y
; y
++) {
750 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
751 let elt
= document
.getElementById(this.coordsToId(x
, y
));
752 elt
.classList
.add("in-shadow");
753 if (this.g_pieces
[x
][y
])
754 this.g_pieces
[x
][y
].classList
.add("hidden");
756 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
757 let elt
= document
.getElementById(this.coordsToId(x
, y
));
758 elt
.classList
.remove("in-shadow");
759 if (this.g_pieces
[x
][y
])
760 this.g_pieces
[x
][y
].classList
.remove("hidden");
766 // After resize event: no need to destroy/recreate pieces
768 const container
= document
.getElementById(this.containerId
);
770 return; //useful at initial loading
771 let chessboard
= container
.querySelector(".chessboard");
772 const r
= chessboard
.getBoundingClientRect();
773 const newRatio
= r
.width
/ r
.height
;
774 let newWidth
= r
.width
,
775 newHeight
= r
.height
;
776 if (newRatio
> this.size
.ratio
) {
777 newWidth
= r
.height
* this.size
.ratio
;
778 chessboard
.style
.width
= newWidth
+ "px";
780 else if (newRatio
< this.size
.ratio
) {
781 newHeight
= r
.width
/ this.size
.ratio
;
782 chessboard
.style
.height
= newHeight
+ "px";
784 const newX
= (window
.innerWidth
- newWidth
) / 2;
785 chessboard
.style
.left
= newX
+ "px";
786 const newY
= (window
.innerHeight
- newHeight
) / 2;
787 chessboard
.style
.top
= newY
+ "px";
788 const newR
= { x: newX
, y: newY
, width: newWidth
, height: newHeight
};
789 const pieceWidth
= this.getPieceWidth(newWidth
);
790 for (let i
=0; i
< this.size
.x
; i
++) {
791 for (let j
=0; j
< this.size
.y
; j
++) {
792 if (this.g_pieces
[i
][j
]) {
793 // NOTE: could also use CSS transform "scale"
794 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
795 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
796 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
797 this.g_pieces
[i
][j
].style
.transform
= `translate(${ip}px,${jp}px)`;
802 this.rescaleReserve(newR
);
806 for (let c
of ['w','b']) {
807 if (!this.reserve
[c
])
809 const nbR
= this.getNbReservePieces(c
);
812 // Resize container first
813 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
814 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
815 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
816 let rcontainer
= document
.getElementById("reserves_" + c
);
817 rcontainer
.style
.left
= i0
+ "px";
818 rcontainer
.style
.top
= j0
+ "px";
819 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
820 rcontainer
.style
.height
= sqResSize
+ "px";
821 // And then reserve cells:
822 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
823 Object
.keys(this.reserve
[c
]).forEach(p
=> {
824 if (this.reserve
[c
][p
] == 0)
826 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
827 r_cell
.style
.width
= sqResSize
+ "px";
828 r_cell
.style
.height
= sqResSize
+ "px";
833 // Return the absolute pixel coordinates (on board) given current position.
834 // Our coordinate system differs from CSS one (x <--> y).
835 // We return here the CSS coordinates (more useful).
836 getPixelPosition(i
, j
, r
) {
838 return [0, 0]; //piece vanishes
840 if (typeof i
== "string") {
841 // Reserves: need to know the rank of piece
842 const nbR
= this.getNbReservePieces(i
);
843 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
844 x
= this.getRankInReserve(i
, j
) * rsqSize
;
845 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
848 const sqSize
= r
.width
/ this.size
.y
;
849 const flipped
= (this.playerColor
== 'b');
850 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
851 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
858 document
.getElementById(this.containerId
).querySelector(".chessboard");
860 const getOffset
= e
=> {
863 return {x: e
.clientX
, y: e
.clientY
};
864 let touchLocation
= null;
865 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
866 // Touch screen, dragstart
867 touchLocation
= e
.targetTouches
[0];
868 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
869 // Touch screen, dragend
870 touchLocation
= e
.changedTouches
[0];
872 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
873 return {x: 0, y: 0}; //shouldn't reach here =)
876 const centerOnCursor
= (piece
, e
) => {
877 const centerShift
= this.getPieceWidth(r
.width
) / 2;
878 const offset
= getOffset(e
);
879 piece
.style
.left
= (offset
.x
- r
.x
- centerShift
) + "px";
880 piece
.style
.top
= (offset
.y
- r
.y
- centerShift
) + "px";
885 startPiece
, curPiece
= null,
887 const mousedown
= (e
) => {
888 // Disable zoom on smartphones:
889 if (e
.touches
&& e
.touches
.length
> 1)
891 r
= chessboard
.getBoundingClientRect();
892 pieceWidth
= this.getPieceWidth(r
.width
);
893 const cd
= this.idToCoords(e
.target
.id
);
895 const move = this.doClick(cd
);
897 this.playPlusVisual(move);
899 const [x
, y
] = Object
.values(cd
);
900 if (typeof x
!= "number")
901 startPiece
= this.r_pieces
[x
][y
];
903 startPiece
= this.g_pieces
[x
][y
];
904 if (startPiece
&& this.canIplay(x
, y
)) {
907 curPiece
= startPiece
.cloneNode();
908 curPiece
.style
.transform
= "none";
909 curPiece
.style
.zIndex
= 5;
910 curPiece
.style
.width
= pieceWidth
+ "px";
911 curPiece
.style
.height
= pieceWidth
+ "px";
912 centerOnCursor(curPiece
, e
);
913 chessboard
.appendChild(curPiece
);
914 startPiece
.style
.opacity
= "0.4";
915 chessboard
.style
.cursor
= "none";
921 const mousemove
= (e
) => {
924 centerOnCursor(curPiece
, e
);
926 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
927 // Attempt to prevent horizontal swipe...
931 const mouseup
= (e
) => {
932 const newR
= chessboard
.getBoundingClientRect();
933 if (newR
.width
!= r
.width
|| newR
.height
!= r
.height
) {
939 const [x
, y
] = [start
.x
, start
.y
];
942 chessboard
.style
.cursor
= "pointer";
943 startPiece
.style
.opacity
= "1";
944 const offset
= getOffset(e
);
945 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
947 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
949 // NOTE: clearly suboptimal, but much easier, and not a big deal.
950 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
951 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
952 const moves
= this.filterValid(potentialMoves
);
953 if (moves
.length
>= 2)
954 this.showChoices(moves
, r
);
955 else if (moves
.length
== 1)
956 this.playPlusVisual(moves
[0], r
);
961 if ('onmousedown' in window
) {
962 document
.addEventListener("mousedown", mousedown
);
963 document
.addEventListener("mousemove", mousemove
);
964 document
.addEventListener("mouseup", mouseup
);
966 if ('ontouchstart' in window
) {
967 // https://stackoverflow.com/a/42509310/12660887
968 document
.addEventListener("touchstart", mousedown
, {passive: false});
969 document
.addEventListener("touchmove", mousemove
, {passive: false});
970 document
.addEventListener("touchend", mouseup
, {passive: false});
972 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
975 showChoices(moves
, r
) {
976 let container
= document
.getElementById(this.containerId
);
977 let chessboard
= container
.querySelector(".chessboard");
978 let choices
= document
.createElement("div");
979 choices
.id
= "choices";
980 choices
.style
.width
= r
.width
+ "px";
981 choices
.style
.height
= r
.height
+ "px";
982 choices
.style
.left
= r
.x
+ "px";
983 choices
.style
.top
= r
.y
+ "px";
984 chessboard
.style
.opacity
= "0.5";
985 container
.appendChild(choices
);
986 const squareWidth
= r
.width
/ this.size
.y
;
987 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
988 const firstUpTop
= (r
.height
- squareWidth
) / 2;
989 const color
= moves
[0].appear
[0].c
;
990 const callback
= (m
) => {
991 chessboard
.style
.opacity
= "1";
992 container
.removeChild(choices
);
993 this.playPlusVisual(m
, r
);
995 for (let i
=0; i
< moves
.length
; i
++) {
996 let choice
= document
.createElement("div");
997 choice
.classList
.add("choice");
998 choice
.style
.width
= squareWidth
+ "px";
999 choice
.style
.height
= squareWidth
+ "px";
1000 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1001 choice
.style
.top
= firstUpTop
+ "px";
1002 choice
.style
.backgroundColor
= "lightyellow";
1003 choice
.onclick
= () => callback(moves
[i
]);
1004 const piece
= document
.createElement("piece");
1005 const pieceSpec
= this.pieces()[moves
[i
].appear
[0].p
];
1006 piece
.classList
.add(pieceSpec
["class"]);
1007 piece
.classList
.add(C
.GetColorClass(color
));
1008 piece
.style
.width
= "100%";
1009 piece
.style
.height
= "100%";
1010 choice
.appendChild(piece
);
1011 choices
.appendChild(choice
);
1022 ratio: 1 //for rectangular board = y / x
1026 // Color of thing on square (i,j). 'undefined' if square is empty
1028 if (typeof i
== "string")
1029 return i
; //reserves
1030 return this.board
[i
][j
].charAt(0);
1033 static GetColorClass(c
) {
1034 return (c
== 'w' ? "white" : "black");
1037 // Assume square i,j isn't empty
1039 if (typeof j
== "string")
1040 return j
; //reserves
1041 return this.board
[i
][j
].charAt(1);
1044 // Piece type on square (i,j)
1045 getPieceType(i
, j
) {
1046 const p
= (typeof i
== "string" ? j : this.board
[i
][j
].charAt(1));
1047 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1050 // Get opponent color
1051 static GetOppCol(color
) {
1052 return (color
== "w" ? "b" : "w");
1055 // Can thing on square1 capture (no return) thing on square2?
1056 canTake([x1
, y1
], [x2
, y2
]) {
1057 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1060 // Is (x,y) on the chessboard?
1062 return (x
>= 0 && x
< this.size
.x
&&
1063 y
>= 0 && y
< this.size
.y
);
1066 // Am I allowed to move thing at square x,y ?
1069 this.playerColor
== this.turn
&&
1071 (typeof x
== "number" && this.getColor(x
, y
) == this.turn
) ||
1072 (typeof x
== "string" && x
== this.turn
) //reserve
1077 ////////////////////////
1078 // PIECES SPECIFICATIONS
1080 pieces(color
, x
, y
) {
1081 const pawnShift
= (color
== "w" ? -1 : 1);
1082 const initRank
= ((color
== 'w' && x
== 6) || (color
== 'b' && x
== 1));
1088 steps: [[pawnShift
, 0]],
1089 range: (initRank
? 2 : 1)
1094 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1103 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1112 [1, 2], [1, -2], [-1, 2], [-1, -2],
1113 [2, 1], [-2, 1], [2, -1], [-2, -1]
1123 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1132 [0, 1], [0, -1], [1, 0], [-1, 0],
1133 [1, 1], [1, -1], [-1, 1], [-1, -1]
1144 [0, 1], [0, -1], [1, 0], [-1, 0],
1145 [1, 1], [1, -1], [-1, 1], [-1, -1]
1152 '!': {"class": "king-pawn", moveas: "p"},
1153 '#': {"class": "king-rook", moveas: "r"},
1154 '$': {"class": "king-knight", moveas: "n"},
1155 '%': {"class": "king-bishop", moveas: "b"},
1156 '*': {"class": "king-queen", moveas: "q"}
1160 ////////////////////
1163 // For Cylinder: get Y coordinate
1165 if (!this.options
["cylinder"])
1167 let res
= y
% this.size
.y
;
1173 // Stop at the first capture found
1174 atLeastOneCapture(color
) {
1175 color
= color
|| this.turn
;
1176 const oppCol
= C
.GetOppCol(color
);
1177 for (let i
= 0; i
< this.size
.x
; i
++) {
1178 for (let j
= 0; j
< this.size
.y
; j
++) {
1179 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1180 const allSpecs
= this.pieces(color
, i
, j
)
1181 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1182 const attacks
= specs
.attack
|| specs
.moves
;
1183 for (let a
of attacks
) {
1184 outerLoop: for (let step
of a
.steps
) {
1185 let [ii
, jj
] = [i
+ step
[0], this.computeY(j
+ step
[1])];
1186 let stepCounter
= 1;
1187 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1188 if (a
.range
<= stepCounter
++)
1191 jj
= this.computeY(jj
+ step
[1]);
1194 this.onBoard(ii
, jj
) &&
1195 this.getColor(ii
, jj
) == oppCol
&&
1197 [this.getBasicMove([i
, j
], [ii
, jj
])]
1210 getDropMovesFrom([c
, p
]) {
1211 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1212 // (but not necessarily otherwise)
1213 if (this.reserve
[c
][p
] == 0)
1216 for (let i
=0; i
<this.size
.x
; i
++) {
1217 for (let j
=0; j
<this.size
.y
; j
++) {
1219 this.board
[i
][j
] == "" &&
1220 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1223 (c
== 'w' && i
< this.size
.x
- 1) ||
1229 start: {x: c
, y: p
},
1231 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1241 // All possible moves from selected square
1242 getPotentialMovesFrom(sq
, color
) {
1243 if (this.subTurnTeleport
== 2)
1245 if (typeof sq
[0] == "string")
1246 return this.getDropMovesFrom(sq
);
1247 if (this.isImmobilized(sq
))
1249 const piece
= this.getPieceType(sq
[0], sq
[1]);
1250 let moves
= this.getPotentialMovesOf(piece
, sq
);
1253 this.hasEnpassant
&&
1256 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1261 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1263 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1265 return this.postProcessPotentialMoves(moves
);
1268 postProcessPotentialMoves(moves
) {
1269 if (moves
.length
== 0)
1271 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1272 const oppCol
= C
.GetOppCol(color
);
1274 if (this.options
["capture"] && this.atLeastOneCapture())
1275 moves
= this.capturePostProcess(moves
, oppCol
);
1277 if (this.options
["atomic"])
1278 this.atomicPostProcess(moves
, oppCol
);
1282 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1284 this.pawnPostProcess(moves
, color
, oppCol
);
1288 this.options
["cannibal"] &&
1289 this.options
["rifle"]
1291 // In this case a rifle-capture from last rank may promote a pawn
1292 this.riflePromotePostProcess(moves
);
1298 capturePostProcess(moves
, oppCol
) {
1299 // Filter out non-capturing moves (not using m.vanish because of
1300 // self captures of Recycle and Teleport).
1301 return moves
.filter(m
=> {
1303 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1304 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1309 atomicPostProcess(moves
, oppCol
) {
1310 moves
.forEach(m
=> {
1312 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1313 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1326 for (let step
of steps
) {
1327 let x
= m
.end
.x
+ step
[0];
1328 let y
= this.computeY(m
.end
.y
+ step
[1]);
1330 this.onBoard(x
, y
) &&
1331 this.board
[x
][y
] != "" &&
1332 this.getPieceType(x
, y
) != "p"
1336 p: this.getPiece(x
, y
),
1337 c: this.getColor(x
, y
),
1344 if (!this.options
["rifle"])
1345 m
.appear
.pop(); //nothin appears
1350 pawnPostProcess(moves
, color
, oppCol
) {
1352 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1353 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1354 moves
.forEach(m
=> {
1355 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1356 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1357 const promotionOk
= (
1359 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1362 return; //nothing to do
1363 if (this.options
["pawnfall"]) {
1367 let finalPieces
= ["p"];
1369 this.options
["cannibal"] &&
1370 this.board
[x2
][y2
] != "" &&
1371 this.getColor(x2
, y2
) == oppCol
1373 finalPieces
= [this.getPieceType(x2
, y2
)];
1376 finalPieces
= this.pawnPromotions
;
1377 m
.appear
[0].p
= finalPieces
[0];
1378 if (initPiece
== "!") //cannibal king-pawn
1379 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1380 for (let i
=1; i
<finalPieces
.length
; i
++) {
1381 const piece
= finalPieces
[i
];
1384 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1386 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1387 moreMoves
.push(newMove
);
1390 Array
.prototype.push
.apply(moves
, moreMoves
);
1393 riflePromotePostProcess(moves
) {
1394 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1396 moves
.forEach(m
=> {
1398 m
.start
.x
== lastRank
&&
1399 m
.appear
.length
>= 1 &&
1400 m
.appear
[0].p
== "p" &&
1401 m
.appear
[0].x
== m
.start
.x
&&
1402 m
.appear
[0].y
== m
.start
.y
1404 const promotionPiece0
= this.pawnSpecs
.promotions
[0];
1405 m
.appear
[0].p
= this.pawnPromotions
[0];
1406 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1407 let newMv
= JSON
.parse(JSON
.stringify(m
));
1408 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1409 newMoves
.push(newMv
);
1413 Array
.prototype.push
.apply(moves
, newMoves
);
1416 // NOTE: using special symbols to not interfere with variants' pieces codes
1417 static get CannibalKings() {
1427 static get CannibalKingCode() {
1441 (this.options
["cannibal"] && C
.CannibalKings
[symbol
])
1446 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1447 isImmobilized([x
, y
]) {
1448 if (!this.options
["madrasi"])
1450 const color
= this.getColor(x
, y
);
1451 const oppCol
= C
.GetOppCol(color
);
1452 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1453 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1454 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1455 for (let a
of attacks
) {
1456 outerLoop: for (let step
of a
.steps
) {
1457 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1458 let stepCounter
= 1;
1459 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1460 if (a
.range
<= stepCounter
++)
1463 j
= this.computeY(j
+ step
[1]);
1466 this.onBoard(i
, j
) &&
1467 this.getColor(i
, j
) == oppCol
&&
1468 this.getPieceType(i
, j
) == piece
1477 // Generic method to find possible moves of "sliding or jumping" pieces
1478 getPotentialMovesOf(piece
, [x
, y
]) {
1479 const color
= this.getColor(x
, y
);
1480 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1482 let explored
= {}; //for Cylinder mode
1484 const findAddMoves
= (type
, stepArray
) => {
1485 for (let s
of stepArray
) {
1486 // TODO: if jump in y (computeY, Cylinder), move.segments
1487 outerLoop: for (let step
of s
.steps
) {
1488 let [i
, j
] = [x
+ step
[0], this.computeY(y
+ step
[1])];
1489 let stepCounter
= 1;
1490 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1491 if (type
!= "attack" && !explored
[i
+ "." + j
]) {
1492 explored
[i
+ "." + j
] = true;
1493 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1495 if (s
.range
<= stepCounter
++)
1498 j
= this.computeY(j
+ step
[1]);
1500 if (!this.onBoard(i
, j
))
1502 const pieceIJ
= this.getPieceType(i
, j
);
1504 type
!= "moveonly" &&
1505 !explored
[i
+ "." + j
] &&
1507 !this.options
["zen"] ||
1511 this.canTake([x
, y
], [i
, j
]) ||
1513 (this.options
["recycle"] || this.options
["teleport"]) &&
1518 explored
[i
+ "." + j
] = true;
1519 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1525 const specialAttack
= !!stepSpec
.attack
;
1527 findAddMoves("attack", stepSpec
.attack
);
1528 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1529 if (this.options
["zen"])
1530 Array
.prototype.push
.apply(moves
, this.findCapturesOn([x
, y
], true));
1534 findCapturesOn([x
, y
], zen
) {
1536 // Find reverse captures (opponent takes)
1537 const color
= this.getColor(x
, y
);
1538 const pieceType
= this.getPieceType(x
, y
);
1539 const oppCol
= C
.GetOppCol(color
);
1540 for (let i
=0; i
<this.size
.x
; i
++) {
1541 for (let j
=0; j
<this.size
.y
; j
++) {
1543 this.board
[i
][j
] != "" &&
1544 this.canTake([i
, j
], [x
, y
]) &&
1545 !this.isImmobilized([i
, j
])
1547 const piece
= this.getPieceType(i
, j
);
1548 if (zen
&& C
.CannibalKingCode
[piece
])
1549 continue; //king not captured in this way
1550 const stepSpec
= this.pieces(oppCol
, i
, j
)[piece
];
1551 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1552 for (let a
of attacks
) {
1553 for (let s
of a
.steps
) {
1554 // Quick check: if step isn't compatible, don't even try
1555 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1557 // Finally verify that nothing stand in-between
1558 let [ii
, jj
] = [i
+ s
[0], this.computeY(j
+ s
[1])];
1559 let stepCounter
= 1;
1560 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1562 jj
= this.computeY(jj
+ s
[1]);
1564 if (ii
== x
&& jj
== y
) {
1565 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1567 return moves
; //test for underCheck
1577 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1578 const rx
= (x2
- x1
) / step
[0],
1579 ry
= (y2
- y1
) / step
[1];
1581 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1582 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1586 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1587 // TODO: 1e-7 here is totally arbitrary
1588 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1590 distance
= Math
.round(distance
); //in case of (numerical...)
1591 if (range
< distance
)
1596 // Build a regular move from its initial and destination squares.
1597 // tr: transformation
1598 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1599 const initColor
= this.getColor(sx
, sy
);
1600 const initPiece
= this.getPiece(sx
, sy
);
1601 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1605 start: {x: sx
, y: sy
},
1609 !this.options
["rifle"] ||
1610 this.board
[ex
][ey
] == "" ||
1611 destColor
== initColor
//Recycle, Teleport
1617 c: !!tr
? tr
.c : initColor
,
1618 p: !!tr
? tr
.p : initPiece
1630 if (this.board
[ex
][ey
] != "") {
1635 c: this.getColor(ex
, ey
),
1636 p: this.getPiece(ex
, ey
)
1639 if (this.options
["cannibal"] && destColor
!= initColor
) {
1640 const lastIdx
= mv
.vanish
.length
- 1;
1641 let trPiece
= mv
.vanish
[lastIdx
].p
;
1642 if (this.isKing(this.getPiece(sx
, sy
)))
1643 trPiece
= C
.CannibalKingCode
[trPiece
];
1644 if (mv
.appear
.length
>= 1)
1645 mv
.appear
[0].p
= trPiece
;
1646 else if (this.options
["rifle"]) {
1669 // En-passant square, if any
1670 getEpSquare(moveOrSquare
) {
1671 if (typeof moveOrSquare
=== "string") {
1672 const square
= moveOrSquare
;
1675 return C
.SquareToCoords(square
);
1677 // Argument is a move:
1678 const move = moveOrSquare
;
1679 const s
= move.start
,
1683 Math
.abs(s
.x
- e
.x
) == 2 &&
1684 // Next conditions for variants like Atomic or Rifle, Recycle...
1685 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1686 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1693 return undefined; //default
1696 // Special case of en-passant captures: treated separately
1697 getEnpassantCaptures([x
, y
]) {
1698 const color
= this.getColor(x
, y
);
1699 const shiftX
= (color
== 'w' ? -1 : 1);
1700 const oppCol
= C
.GetOppCol(color
);
1701 let enpassantMove
= null;
1704 this.epSquare
.x
== x
+ shiftX
&&
1705 Math
.abs(this.computeY(this.epSquare
.y
- y
)) == 1 &&
1706 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1708 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1709 this.board
[epx
][epy
] = oppCol
+ "p";
1710 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1711 this.board
[epx
][epy
] = "";
1712 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1713 enpassantMove
.vanish
[lastIdx
].x
= x
;
1715 return !!enpassantMove
? [enpassantMove
] : [];
1718 // "castleInCheck" arg to let some variants castle under check
1719 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1720 const c
= this.getColor(x
, y
);
1723 const oppCol
= C
.GetOppCol(c
);
1727 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1728 const castlingKing
= this.getPiece(x
, y
);
1729 castlingCheck: for (
1732 castleSide
++ //large, then small
1734 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1736 // If this code is reached, rook and king are on initial position
1738 // NOTE: in some variants this is not a rook
1739 const rookPos
= this.castleFlags
[c
][castleSide
];
1740 const castlingPiece
= this.getPiece(x
, rookPos
);
1742 this.board
[x
][rookPos
] == "" ||
1743 this.getColor(x
, rookPos
) != c
||
1744 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1746 // Rook is not here, or changed color (see Benedict)
1749 // Nothing on the path of the king ? (and no checks)
1750 const finDist
= finalSquares
[castleSide
][0] - y
;
1751 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1755 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1757 this.board
[x
][i
] != "" &&
1758 // NOTE: next check is enough, because of chessboard constraints
1759 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1762 continue castlingCheck
;
1765 } while (i
!= finalSquares
[castleSide
][0]);
1766 // Nothing on the path to the rook?
1767 step
= (castleSide
== 0 ? -1 : 1);
1768 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1769 if (this.board
[x
][i
] != "")
1770 continue castlingCheck
;
1773 // Nothing on final squares, except maybe king and castling rook?
1774 for (i
= 0; i
< 2; i
++) {
1776 finalSquares
[castleSide
][i
] != rookPos
&&
1777 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1779 finalSquares
[castleSide
][i
] != y
||
1780 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1783 continue castlingCheck
;
1787 // If this code is reached, castle is valid
1793 y: finalSquares
[castleSide
][0],
1799 y: finalSquares
[castleSide
][1],
1805 // King might be initially disguised (Titan...)
1806 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1807 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1810 Math
.abs(y
- rookPos
) <= 2
1811 ? {x: x
, y: rookPos
}
1812 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1820 ////////////////////
1823 // Is (king at) given position under check by "color" ?
1824 underCheck([x
, y
], color
) {
1825 if (this.options
["taking"] || this.options
["dark"])
1827 return (this.findCapturesOn([x
, y
]).length
>= 1);
1830 // Stop at first king found (TODO: multi-kings)
1831 searchKingPos(color
) {
1832 for (let i
=0; i
< this.size
.x
; i
++) {
1833 for (let j
=0; j
< this.size
.y
; j
++) {
1834 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1838 return [-1, -1]; //king not found
1841 filterValid(moves
) {
1842 if (moves
.length
== 0)
1844 const color
= this.turn
;
1845 const oppCol
= C
.GetOppCol(color
);
1846 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1847 // Forbid moves either giving check or exploding opponent's king:
1848 const oppKingPos
= this.searchKingPos(oppCol
);
1849 moves
= moves
.filter(m
=> {
1851 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1852 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1855 this.playOnBoard(m
);
1856 const res
= !this.underCheck(oppKingPos
, color
);
1857 this.undoOnBoard(m
);
1861 if (this.options
["taking"] || this.options
["dark"])
1863 const kingPos
= this.searchKingPos(color
);
1864 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1865 return moves
.filter(m
=> {
1866 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1867 if (!filtered
[key
]) {
1868 this.playOnBoard(m
);
1869 let square
= kingPos
,
1870 res
= true; //a priori valid
1871 if (m
.vanish
.some(v
=> {
1872 return (v
.p
== "k" || C
.CannibalKings
[v
.p
]) && v
.c
== color
;
1874 // Search king in appear array:
1876 m
.appear
.findIndex(a
=> {
1877 return (a
.p
== "k" || C
.CannibalKings
[a
.p
]) && a
.c
== color
;
1879 if (newKingIdx
>= 0)
1880 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1884 res
&&= !this.underCheck(square
, oppCol
);
1885 this.undoOnBoard(m
);
1886 filtered
[key
] = res
;
1889 return filtered
[key
];
1896 // Aggregate flags into one object
1898 return this.castleFlags
;
1901 // Reverse operation
1902 disaggregateFlags(flags
) {
1903 this.castleFlags
= flags
;
1906 // Apply a move on board
1908 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = "";
1909 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1911 // Un-apply the played move
1913 for (let psq
of move.appear
) this.board
[psq
.x
][psq
.y
] = "";
1914 for (let psq
of move.vanish
) this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1917 updateCastleFlags(move) {
1918 // Update castling flags if start or arrive from/at rook/king locations
1919 move.appear
.concat(move.vanish
).forEach(psq
=> {
1921 this.board
[psq
.x
][psq
.y
] != "" &&
1922 this.getPieceType(psq
.x
, psq
.y
) == "k"
1924 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
1926 // NOTE: not "else if" because king can capture enemy rook...
1930 else if (psq
.x
== this.size
.x
- 1)
1933 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
1935 this.castleFlags
[c
][fidx
] = this.size
.y
;
1941 // TODO: generique start/end board or reserve
1948 // If flags already off, no need to re-check:
1949 Object
.keys(this.castleFlags
).some(c
=> {
1950 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
1952 this.updateCastleFlags(move);
1954 if (this.options
["crazyhouse"]) {
1955 move.vanish
.forEach(v
=> {
1956 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
1957 if (this.ispawn
[square
])
1958 delete this.ispawn
[square
];
1960 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
1961 // Assumption: something is moving
1962 const initSquare
= C
.CoordsToSquare(move.start
);
1963 const destSquare
= C
.CoordsToSquare(move.end
);
1965 this.ispawn
[initSquare
] ||
1966 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
1968 this.ispawn
[destSquare
] = true;
1971 this.ispawn
[destSquare
] &&
1972 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
1974 move.vanish
[1].p
= "p";
1975 delete this.ispawn
[destSquare
];
1980 // TODO: robustify this by adding fields
1981 // "captures" (capts?) and "births" (e.g...) to Move
1982 // --> store only indices in appear/vanish ?
1983 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
1984 if (this.hasReserve
&& !move.pawnfall
) {
1985 const color
= this.turn
;
1986 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
1987 // Something appears = dropped on board (some exceptions, Chakart...)
1988 const piece
= move.appear
[i
].p
;
1989 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
1991 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
1992 // Something vanish: add to reserve except if recycle & opponent
1993 const piece
= move.vanish
[i
].p
;
1994 if (this.options
["crazyhouse"] || move.vanish
[i
].c
== color
)
1995 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
1998 move.captures
.forEach(capt
=> {
2001 move.births
.forEach(bth
=> {
2008 if (this.hasEnpassant
)
2009 this.epSquare
= this.getEpSquare(move);
2010 this.playOnBoard(move);
2011 this.postPlay(move);
2015 const color
= this.turn
;
2016 const oppCol
= C
.GetOppCol(color
);
2017 if (this.options
["dark"])
2018 this.updateEnlightened();
2019 if (this.options
["teleport"]) {
2021 this.subTurnTeleport
== 1 &&
2022 move.vanish
.length
> move.appear
.length
&&
2023 move.vanish
[move.vanish
.length
- 1].c
== color
2025 const v
= move.vanish
[move.vanish
.length
- 1];
2026 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2027 this.subTurnTeleport
= 2;
2030 this.subTurnTeleport
= 1;
2031 this.captured
= null;
2033 if (this.options
["balance"]) {
2034 if (![1, 3].includes(this.movesCount
))
2040 this.options
["doublemove"] &&
2041 this.movesCount
>= 1 &&
2044 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2046 const oppKingPos
= this.searchKingPos(oppCol
);
2048 oppKingPos
[0] >= 0 &&
2050 this.options
["taking"] ||
2051 !this.underCheck(oppKingPos
, color
)
2064 // "Stop at the first move found"
2065 atLeastOneMove(color
) {
2066 color
= color
|| this.turn
;
2067 for (let i
= 0; i
< this.size
.x
; i
++) {
2068 for (let j
= 0; j
< this.size
.y
; j
++) {
2069 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2070 // NOTE: in fact searching for all potential moves from i,j.
2071 // I don't believe this is an issue, for now at least.
2072 const moves
= this.getPotentialMovesFrom([i
, j
]);
2073 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2078 if (this.hasReserve
&& this.reserve
[color
]) {
2079 for (let p
of Object
.keys(this.reserve
[color
])) {
2080 const moves
= this.getDropMovesFrom([color
, p
]);
2081 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2088 // What is the score ? (Interesting if game is over)
2089 getCurrentScore(move) {
2090 const color
= this.turn
;
2091 const oppCol
= C
.GetOppCol(color
);
2092 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2093 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2095 if (kingPos
[0][0] < 0)
2096 return (color
== "w" ? "0-1" : "1-0");
2097 if (kingPos
[1][0] < 0)
2098 return (color
== "w" ? "1-0" : "0-1");
2099 if (this.atLeastOneMove())
2101 // No valid move: stalemate or checkmate?
2102 if (!this.underCheck(kingPos
[0], color
))
2105 return (color
== "w" ? "0-1" : "1-0");
2108 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2109 playVisual(move, r
) {
2110 move.vanish
.forEach(v
=> {
2111 // TODO: next "if" shouldn't be required
2112 if (this.g_pieces
[v
.x
][v
.y
])
2113 this.g_pieces
[v
.x
][v
.y
].remove();
2114 this.g_pieces
[v
.x
][v
.y
] = null;
2117 document
.getElementById(this.containerId
).querySelector(".chessboard");
2119 r
= chessboard
.getBoundingClientRect();
2120 const pieceWidth
= this.getPieceWidth(r
.width
);
2121 move.appear
.forEach(a
=> {
2122 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2123 this.g_pieces
[a
.x
][a
.y
].classList
.add(this.pieces()[a
.p
]["class"]);
2124 this.g_pieces
[a
.x
][a
.y
].classList
.add(a
.c
== "w" ? "white" : "black");
2125 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2126 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2127 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2128 this.g_pieces
[a
.x
][a
.y
].style
.transform
= `translate(${ip}px,${jp}px)`;
2129 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2130 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2131 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2133 if (this.options
["dark"])
2134 this.graphUpdateEnlightened();
2137 playPlusVisual(move, r
) {
2139 this.playVisual(move, r
);
2140 this.afterPlay(move); //user method
2143 getMaxDistance(rwidth
) {
2144 // Works for all rectangular boards:
2145 return Math
.sqrt(rwidth
** 2 + (rwidth
/ this.size
.ratio
) ** 2);
2149 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2152 animate(move, callback
) {
2153 if (this.noAnimate
|| move.noAnimate
) {
2157 let movingPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2158 if (!movingPiece
) { //TODO this shouldn't be required
2162 const initTransform
= movingPiece
.style
.transform
;
2164 document
.getElementById(this.containerId
).querySelector(".chessboard");
2165 const r
= chessboard
.getBoundingClientRect();
2166 const [ix
, iy
] = this.getPixelPosition(move.start
.x
, move.start
.y
, r
);
2167 const maxDist
= this.getMaxDistance(r
.width
);
2168 // NOTE: move.drag could be generalized per-segment (usage?)
2170 // Drag something else: require cloning
2171 movingPiece
= movingPiece
.cloneNode();
2172 const pieces
= this.pieces();
2173 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2174 movingPiece
.classList
.remove(pieces
[startCode
]["class"]);
2175 movingPiece
.classList
.add(pieces
[move.drag
.p
]["class"]);
2176 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2177 if (apparentColor
!= move.drag
.c
) {
2178 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2179 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2181 chessboard
.appendChild(movingPiece
);
2183 const animateSegment
= (index
, cb
) => {
2184 const [i1
, j1
] = move.segments
[index
][0];
2185 const [i2
, j2
] = move.segments
[index
][1];
2186 const dep
= this.getPixelPosition(i1
, j1
, r
);
2187 const arr
= this.getPixelPosition(i2
, j2
, r
);
2189 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2190 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2191 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2192 movingPiece
.style
.transitionDuration
= duration
+ "s";
2193 setTimeout(cb
, duration
* 1000);
2195 if (!move.segments
) {
2197 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2201 const animateSegmentCallback
= () => {
2202 if (index
< move.segments
.length
)
2203 animateSegment(index
++, animateSegmentCallback
);
2206 movingPiece
.remove();
2208 movingPiece
.style
.transform
= initTransform
;
2209 movingPiece
.style
.transitionDuration
= "0s";
2214 animateSegmentCallback();
2217 playReceivedMove(moves
, callback
) {
2218 const launchAnimation
= () => {
2219 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2220 const animateRec
= i
=> {
2221 this.animate(moves
[i
], () => {
2222 this.play(moves
[i
]);
2223 this.playVisual(moves
[i
], r
);
2224 if (i
< moves
.length
- 1)
2225 setTimeout(() => animateRec(i
+1), 300);
2232 // Delay if user wasn't focused:
2233 const checkDisplayThenAnimate
= (delay
) => {
2234 if (container
.style
.display
== "none") {
2235 alert("New move! Let's go back to game...");
2236 document
.getElementById("gameInfos").style
.display
= "none";
2237 container
.style
.display
= "block";
2238 setTimeout(launchAnimation
, 700);
2241 setTimeout(launchAnimation
, delay
|| 0);
2243 let container
= document
.getElementById(this.containerId
);
2244 if (document
.hidden
) {
2245 document
.onvisibilitychange
= () => {
2246 document
.onvisibilitychange
= undefined;
2247 checkDisplayThenAnimate(700);
2251 checkDisplayThenAnimate();