8b070598b1ab5a0f24009d5d7d79c3412267416f
1 import { Random
} from "/utils/alea.js";
2 import { ArrayFun
} from "/utils/array.js";
3 import PiPo
from "/utils/PiPo.js";
4 import Move
from "/utils/Move.js";
6 // NOTE: x coords: top to bottom (white perspective); y: left to right
7 // NOTE: ChessRules is aliased as window.C, and variants as window.V
8 export default class ChessRules
{
10 static get Aliases() {
11 return {'C': ChessRules
};
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
17 // Some variants have specific options, like the number of pawns in Monster,
18 // or the board size for Pandemonium.
19 // Users can generally select a randomness level from 0 to 2.
20 static get Options() {
24 variable: "randomness",
27 {label: "Deterministic", value: 0},
28 {label: "Symmetric random", value: 1},
29 {label: "Asymmetric random", value: 2}
34 label: "Capture king",
40 label: "Falling pawn",
46 // Game modifiers (using "elementary variants"). Default: false
49 "balance", //takes precedence over doublemove & progressive
53 "cylinder", //ok with all
57 "progressive", //(natural) priority over doublemove
66 get pawnPromotions() {
67 return ['q', 'r', 'n', 'b'];
70 // Some variants don't have flags:
79 // En-passant captures allowed?
86 !!this.options
["crazyhouse"] ||
87 (!!this.options
["recycle"] && !this.options
["teleport"])
90 // Some variants do not store reserve state (Align4, Chakart...)
92 return this.hasReserve
;
96 return !!this.options
["dark"];
99 // Some variants use click infos:
101 if (typeof coords
.x
!= "number")
102 return null; //click on reserves
104 this.options
["teleport"] && this.subTurnTeleport
== 2 &&
105 this.board
[coords
.x
][coords
.y
] == ""
108 start: {x: this.captured
.x
, y: this.captured
.y
},
113 c: this.captured
.c
, //this.turn,
119 res
.drag
= {c: this.captured
.c
, p: this.captured
.p
};
128 // 3a --> {x:3, y:10}
129 static SquareToCoords(sq
) {
130 return ArrayFun
.toObject(["x", "y"],
131 [0, 1].map(i
=> parseInt(sq
[i
], 36)));
134 // {x:11, y:12} --> bc
135 static CoordsToSquare(cd
) {
136 return Object
.values(cd
).map(c
=> c
.toString(36)).join("");
140 if (typeof cd
.x
== "number") {
142 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
146 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
149 idToCoords(targetId
) {
151 return null; //outside page, maybe...
152 const idParts
= targetId
.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
154 idParts
.length
< 2 ||
155 idParts
[0] != this.containerId
||
156 !idParts
[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
160 const squares
= idParts
[1].split('-');
161 if (squares
[0] == "sq")
162 return {x: parseInt(squares
[1], 36), y: parseInt(squares
[2], 36)};
163 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
164 return {x: squares
[1], y: squares
[2]};
170 // Turn "wb" into "B" (for FEN)
172 return (b
[0] == "w" ? b
[1].toUpperCase() : b
[1]);
175 // Turn "p" into "bp" (for board)
177 return (f
.charCodeAt(0) <= 90 ? "w" + f
.toLowerCase() : "b" + f
);
180 // Setup the initial random-or-not (asymmetric-or-not) position
181 genRandInitFen(seed
) {
182 let fen
, flags
= "0707";
183 if (!this.options
.randomness
)
185 fen
= "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
189 Random
.setSeed(seed
);
190 let pieces
= {w: new Array(8), b: new Array(8)};
192 // Shuffle pieces on first (and last rank if randomness == 2)
193 for (let c
of ["w", "b"]) {
194 if (c
== 'b' && this.options
.randomness
== 1) {
195 pieces
['b'] = pieces
['w'];
200 let positions
= ArrayFun
.range(8);
202 // Get random squares for bishops
203 let randIndex
= 2 * Random
.randInt(4);
204 const bishop1Pos
= positions
[randIndex
];
205 // The second bishop must be on a square of different color
206 let randIndex_tmp
= 2 * Random
.randInt(4) + 1;
207 const bishop2Pos
= positions
[randIndex_tmp
];
208 // Remove chosen squares
209 positions
.splice(Math
.max(randIndex
, randIndex_tmp
), 1);
210 positions
.splice(Math
.min(randIndex
, randIndex_tmp
), 1);
212 // Get random squares for knights
213 randIndex
= Random
.randInt(6);
214 const knight1Pos
= positions
[randIndex
];
215 positions
.splice(randIndex
, 1);
216 randIndex
= Random
.randInt(5);
217 const knight2Pos
= positions
[randIndex
];
218 positions
.splice(randIndex
, 1);
220 // Get random square for queen
221 randIndex
= Random
.randInt(4);
222 const queenPos
= positions
[randIndex
];
223 positions
.splice(randIndex
, 1);
225 // Rooks and king positions are now fixed,
226 // because of the ordering rook-king-rook
227 const rook1Pos
= positions
[0];
228 const kingPos
= positions
[1];
229 const rook2Pos
= positions
[2];
231 // Finally put the shuffled pieces in the board array
232 pieces
[c
][rook1Pos
] = "r";
233 pieces
[c
][knight1Pos
] = "n";
234 pieces
[c
][bishop1Pos
] = "b";
235 pieces
[c
][queenPos
] = "q";
236 pieces
[c
][kingPos
] = "k";
237 pieces
[c
][bishop2Pos
] = "b";
238 pieces
[c
][knight2Pos
] = "n";
239 pieces
[c
][rook2Pos
] = "r";
240 flags
+= rook1Pos
.toString() + rook2Pos
.toString();
243 pieces
["b"].join("") +
244 "/pppppppp/8/8/8/8/PPPPPPPP/" +
245 pieces
["w"].join("").toUpperCase() +
249 // Add turn + flags + enpassant (+ reserve)
252 parts
.push(`"flags":"${flags}"`);
253 if (this.hasEnpassant
)
254 parts
.push('"enpassant":"-"');
256 parts
.push('"reserve":"000000000000"');
257 if (this.options
["crazyhouse"])
258 parts
.push('"ispawn":"-"');
259 if (parts
.length
>= 1)
260 fen
+= " {" + parts
.join(",") + "}";
264 // "Parse" FEN: just return untransformed string data
266 const fenParts
= fen
.split(" ");
268 position: fenParts
[0],
270 movesCount: fenParts
[2]
272 if (fenParts
.length
> 3)
273 res
= Object
.assign(res
, JSON
.parse(fenParts
[3]));
277 // Return current fen (game state)
280 this.getPosition() + " " +
281 this.getTurnFen() + " " +
286 parts
.push(`"flags":"${this.getFlagsFen()}"`);
287 if (this.hasEnpassant
)
288 parts
.push(`"enpassant":"${this.getEnpassantFen()}"`);
289 if (this.hasReserveFen
)
290 parts
.push(`"reserve":"${this.getReserveFen()}"`);
291 if (this.options
["crazyhouse"])
292 parts
.push(`"ispawn":"${this.getIspawnFen()}"`);
293 if (parts
.length
>= 1)
294 fen
+= " {" + parts
.join(",") + "}";
298 static FenEmptySquares(count
) {
299 // if more than 9 consecutive free spaces, break the integer,
300 // otherwise FEN parsing will fail.
303 // Most boards of size < 18:
305 return "9" + (count
- 9);
307 return "99" + (count
- 18);
310 // Position part of the FEN string
313 for (let i
= 0; i
< this.size
.y
; i
++) {
315 for (let j
= 0; j
< this.size
.x
; j
++) {
316 if (this.board
[i
][j
] == "")
319 if (emptyCount
> 0) {
320 // Add empty squares in-between
321 position
+= C
.FenEmptySquares(emptyCount
);
324 position
+= this.board2fen(this.board
[i
][j
]);
329 position
+= C
.FenEmptySquares(emptyCount
);
330 if (i
< this.size
.y
- 1)
331 position
+= "/"; //separate rows
340 // Flags part of the FEN string
342 return ["w", "b"].map(c
=> {
343 return this.castleFlags
[c
].map(x
=> x
.toString(36)).join("");
347 // Enpassant part of the FEN string
350 return "-"; //no en-passant
351 return C
.CoordsToSquare(this.epSquare
);
356 ["w","b"].map(c
=> Object
.values(this.reserve
[c
]).join("")).join("")
361 const squares
= Object
.keys(this.ispawn
);
362 if (squares
.length
== 0)
364 return squares
.join(",");
367 // Set flags from fen (castle: white a,h then black a,h)
370 w: [0, 1].map(i
=> parseInt(fenflags
.charAt(i
), 36)),
371 b: [2, 3].map(i
=> parseInt(fenflags
.charAt(i
), 36))
379 this.options
= o
.options
;
380 // Fill missing options (always the case if random challenge)
381 (V
.Options
.select
|| []).concat(V
.Options
.input
|| []).forEach(opt
=> {
382 if (this.options
[opt
.variable
] === undefined)
383 this.options
[opt
.variable
] = opt
.defaut
;
386 // This object will be used only for initial FEN generation
388 this.playerColor
= o
.color
;
389 this.afterPlay
= o
.afterPlay
; //trigger some actions after playing a move
391 // Fen string fully describes the game state
393 o
.fen
= this.genRandInitFen(o
.seed
);
394 const fenParsed
= this.parseFen(o
.fen
);
395 this.board
= this.getBoard(fenParsed
.position
);
396 this.turn
= fenParsed
.turn
;
397 this.movesCount
= parseInt(fenParsed
.movesCount
, 10);
398 this.setOtherVariables(fenParsed
);
400 // Graphical (can use variables defined above)
401 this.containerId
= o
.element
;
402 this.graphicalInit();
405 // Turn position fen into double array ["wb","wp","bk",...]
407 const rows
= position
.split("/");
408 let board
= ArrayFun
.init(this.size
.x
, this.size
.y
, "");
409 for (let i
= 0; i
< rows
.length
; i
++) {
411 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++) {
412 const character
= rows
[i
][indexInRow
];
413 const num
= parseInt(character
, 10);
414 // If num is a number, just shift j:
417 // Else: something at position i,j
419 board
[i
][j
++] = this.fen2board(character
);
425 // Some additional variables from FEN (variant dependant)
426 setOtherVariables(fenParsed
) {
427 // Set flags and enpassant:
429 this.setFlags(fenParsed
.flags
);
430 if (this.hasEnpassant
)
431 this.epSquare
= this.getEpSquare(fenParsed
.enpassant
);
433 this.initReserves(fenParsed
.reserve
);
434 if (this.options
["crazyhouse"])
435 this.initIspawn(fenParsed
.ispawn
);
436 this.subTurn
= 1; //may be unused
437 if (this.options
["teleport"]) {
438 this.subTurnTeleport
= 1;
439 this.captured
= null;
441 if (this.options
["dark"]) {
442 // Setup enlightened: squares reachable by player side
443 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
444 this.updateEnlightened();
448 updateEnlightened() {
449 this.oldEnlightened
= this.enlightened
;
450 this.enlightened
= ArrayFun
.init(this.size
.x
, this.size
.y
, false);
451 // Add pieces positions + all squares reachable by moves (includes Zen):
452 for (let x
=0; x
<this.size
.x
; x
++) {
453 for (let y
=0; y
<this.size
.y
; y
++) {
454 if (this.board
[x
][y
] != "" && this.getColor(x
, y
) == this.playerColor
)
456 this.enlightened
[x
][y
] = true;
457 this.getPotentialMovesFrom([x
, y
]).forEach(m
=> {
458 this.enlightened
[m
.end
.x
][m
.end
.y
] = true;
464 this.enlightEnpassant();
467 // Include square of the en-passant capturing square:
469 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
470 const steps
= this.pieces(this.playerColor
)["p"].attack
[0].steps
;
471 for (let step
of steps
) {
472 const x
= this.epSquare
.x
- step
[0],
473 y
= this.getY(this.epSquare
.y
- step
[1]);
475 this.onBoard(x
, y
) &&
476 this.getColor(x
, y
) == this.playerColor
&&
477 this.getPieceType(x
, y
) == "p"
479 this.enlightened
[x
][this.epSquare
.y
] = true;
485 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
486 initReserves(reserveStr
) {
487 const counts
= reserveStr
.split("").map(c
=> parseInt(c
, 30));
488 this.reserve
= { w: {}, b: {} };
489 const pieceName
= ['p', 'r', 'n', 'b', 'q', 'k'];
490 const L
= pieceName
.length
;
491 for (let i
of ArrayFun
.range(2 * L
)) {
493 this.reserve
['w'][pieceName
[i
]] = counts
[i
];
495 this.reserve
['b'][pieceName
[i
-L
]] = counts
[i
];
499 initIspawn(ispawnStr
) {
500 if (ispawnStr
!= "-")
501 this.ispawn
= ArrayFun
.toObject(ispawnStr
.split(","), true);
506 getNbReservePieces(color
) {
508 Object
.values(this.reserve
[color
]).reduce(
509 (oldV
,newV
) => oldV
+ (newV
> 0 ? 1 : 0), 0)
513 getRankInReserve(c
, p
) {
514 const pieces
= Object
.keys(this.pieces());
515 const lastIndex
= pieces
.findIndex(pp
=> pp
== p
)
516 let toTest
= pieces
.slice(0, lastIndex
);
517 return toTest
.reduce(
518 (oldV
,newV
) => oldV
+ (this.reserve
[c
][newV
] > 0 ? 1 : 0), 0);
524 getPieceWidth(rwidth
) {
525 return (rwidth
/ this.size
.y
);
528 getReserveSquareSize(rwidth
, nbR
) {
529 const sqSize
= this.getPieceWidth(rwidth
);
530 return Math
.min(sqSize
, rwidth
/ nbR
);
533 getReserveNumId(color
, piece
) {
534 return `${this.containerId}|rnum-${color}${piece}`;
537 static AddClass_es(piece
, class_es
) {
538 if (!Array
.isArray(class_es
))
539 class_es
= [class_es
];
540 class_es
.forEach(cl
=> {
541 piece
.classList
.add(cl
);
545 static RemoveClass_es(piece
, class_es
) {
546 if (!Array
.isArray(class_es
))
547 class_es
= [class_es
];
548 class_es
.forEach(cl
=> {
549 piece
.classList
.remove(cl
);
554 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
555 window
.onresize
= () => this.re_drawBoardElements();
556 this.re_drawBoardElements();
557 this.initMouseEvents();
559 document
.getElementById(this.containerId
).querySelector(".chessboard");
562 re_drawBoardElements() {
563 const board
= this.getSvgChessboard();
564 const oppCol
= C
.GetOppCol(this.playerColor
);
566 document
.getElementById(this.containerId
).querySelector(".chessboard");
567 chessboard
.innerHTML
= "";
568 chessboard
.insertAdjacentHTML('beforeend', board
);
569 // Compare window ratio width / height to aspectRatio:
570 const windowRatio
= window
.innerWidth
/ window
.innerHeight
;
571 let cbWidth
, cbHeight
;
572 if (windowRatio
<= this.size
.ratio
) {
573 // Limiting dimension is width:
574 cbWidth
= Math
.min(window
.innerWidth
, 767);
575 cbHeight
= cbWidth
/ this.size
.ratio
;
578 // Limiting dimension is height:
579 cbHeight
= Math
.min(window
.innerHeight
, 767);
580 cbWidth
= cbHeight
* this.size
.ratio
;
582 if (this.hasReserve
) {
583 const sqSize
= cbWidth
/ this.size
.y
;
584 // NOTE: allocate space for reserves (up/down) even if they are empty
585 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
586 if ((window
.innerHeight
- cbHeight
) / 2 < sqSize
+ 5) {
587 cbHeight
= window
.innerHeight
- 2 * (sqSize
+ 5);
588 cbWidth
= cbHeight
* this.size
.ratio
;
591 chessboard
.style
.width
= cbWidth
+ "px";
592 chessboard
.style
.height
= cbHeight
+ "px";
593 // Center chessboard:
594 const spaceLeft
= (window
.innerWidth
- cbWidth
) / 2,
595 spaceTop
= (window
.innerHeight
- cbHeight
) / 2;
596 chessboard
.style
.left
= spaceLeft
+ "px";
597 chessboard
.style
.top
= spaceTop
+ "px";
598 // Give sizes instead of recomputing them,
599 // because chessboard might not be drawn yet.
608 // Get SVG board (background, no pieces)
610 const flipped
= (this.playerColor
== 'b');
614 class="chessboard_SVG">`;
615 for (let i
=0; i
< this.size
.x
; i
++) {
616 for (let j
=0; j
< this.size
.y
; j
++) {
617 const ii
= (flipped
? this.size
.x
- 1 - i : i
);
618 const jj
= (flipped
? this.size
.y
- 1 - j : j
);
619 let classes
= this.getSquareColorClass(ii
, jj
);
620 if (this.enlightened
&& !this.enlightened
[ii
][jj
])
621 classes
+= " in-shadow";
622 // NOTE: x / y reversed because coordinates system is reversed.
626 id="${this.coordsToId({x: ii, y: jj})}"
638 // Generally light square bottom-right
639 getSquareColorClass(x
, y
) {
640 return ((x
+y
) % 2 == 0 ? "light-square": "dark-square");
645 // Refreshing: delete old pieces first
646 for (let i
=0; i
<this.size
.x
; i
++) {
647 for (let j
=0; j
<this.size
.y
; j
++) {
648 if (this.g_pieces
[i
][j
]) {
649 this.g_pieces
[i
][j
].remove();
650 this.g_pieces
[i
][j
] = null;
656 this.g_pieces
= ArrayFun
.init(this.size
.x
, this.size
.y
, null);
658 document
.getElementById(this.containerId
).querySelector(".chessboard");
660 r
= chessboard
.getBoundingClientRect();
661 const pieceWidth
= this.getPieceWidth(r
.width
);
662 for (let i
=0; i
< this.size
.x
; i
++) {
663 for (let j
=0; j
< this.size
.y
; j
++) {
664 if (this.board
[i
][j
] != "") {
665 const color
= this.getColor(i
, j
);
666 const piece
= this.getPiece(i
, j
);
667 this.g_pieces
[i
][j
] = document
.createElement("piece");
668 C
.AddClass_es(this.g_pieces
[i
][j
], this.pieces()[piece
]["class"]);
669 this.g_pieces
[i
][j
].classList
.add(C
.GetColorClass(color
));
670 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
671 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
672 let [ip
, jp
] = this.getPixelPosition(i
, j
, r
);
673 // Translate coordinates to use chessboard as reference:
674 this.g_pieces
[i
][j
].style
.transform
=
675 `translate(${ip - r.x}px,${jp - r.y}px)`;
676 if (this.enlightened
&& !this.enlightened
[i
][j
])
677 this.g_pieces
[i
][j
].classList
.add("hidden");
678 chessboard
.appendChild(this.g_pieces
[i
][j
]);
683 this.re_drawReserve(['w', 'b'], r
);
686 // NOTE: assume this.reserve != null
687 re_drawReserve(colors
, r
) {
689 // Remove (old) reserve pieces
690 for (let c
of colors
) {
691 Object
.keys(this.r_pieces
[c
]).forEach(p
=> {
692 this.r_pieces
[c
][p
].remove();
693 delete this.r_pieces
[c
][p
];
694 const numId
= this.getReserveNumId(c
, p
);
695 document
.getElementById(numId
).remove();
700 this.r_pieces
= { w: {}, b: {} };
701 let container
= document
.getElementById(this.containerId
);
703 r
= container
.querySelector(".chessboard").getBoundingClientRect();
704 for (let c
of colors
) {
705 let reservesDiv
= document
.getElementById("reserves_" + c
);
707 reservesDiv
.remove();
708 if (!this.reserve
[c
])
710 const nbR
= this.getNbReservePieces(c
);
713 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
715 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
716 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
717 let rcontainer
= document
.createElement("div");
718 rcontainer
.id
= "reserves_" + c
;
719 rcontainer
.classList
.add("reserves");
720 rcontainer
.style
.left
= i0
+ "px";
721 rcontainer
.style
.top
= j0
+ "px";
722 // NOTE: +1 fix display bug on Firefox at least
723 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
724 rcontainer
.style
.height
= sqResSize
+ "px";
725 container
.appendChild(rcontainer
);
726 for (let p
of Object
.keys(this.reserve
[c
])) {
727 if (this.reserve
[c
][p
] == 0)
729 let r_cell
= document
.createElement("div");
730 r_cell
.id
= this.coordsToId({x: c
, y: p
});
731 r_cell
.classList
.add("reserve-cell");
732 r_cell
.style
.width
= sqResSize
+ "px";
733 r_cell
.style
.height
= sqResSize
+ "px";
734 rcontainer
.appendChild(r_cell
);
735 let piece
= document
.createElement("piece");
736 C
.AddClass_es(piece
, this.pieces()[p
]["class"]);
737 piece
.classList
.add(C
.GetColorClass(c
));
738 piece
.style
.width
= "100%";
739 piece
.style
.height
= "100%";
740 this.r_pieces
[c
][p
] = piece
;
741 r_cell
.appendChild(piece
);
742 let number
= document
.createElement("div");
743 number
.textContent
= this.reserve
[c
][p
];
744 number
.classList
.add("reserve-num");
745 number
.id
= this.getReserveNumId(c
, p
);
746 const fontSize
= "1.3em";
747 number
.style
.fontSize
= fontSize
;
748 number
.style
.fontSize
= fontSize
;
749 r_cell
.appendChild(number
);
755 updateReserve(color
, piece
, count
) {
756 if (this.options
["cannibal"] && C
.CannibalKings
[piece
])
757 piece
= "k"; //capturing cannibal king: back to king form
758 const oldCount
= this.reserve
[color
][piece
];
759 this.reserve
[color
][piece
] = count
;
760 // Redrawing is much easier if count==0
761 if ([oldCount
, count
].includes(0))
762 this.re_drawReserve([color
]);
764 const numId
= this.getReserveNumId(color
, piece
);
765 document
.getElementById(numId
).textContent
= count
;
769 // Apply diff this.enlightened --> oldEnlightened on board
770 graphUpdateEnlightened() {
772 document
.getElementById(this.containerId
).querySelector(".chessboard");
773 const r
= chessboard
.getBoundingClientRect();
774 const pieceWidth
= this.getPieceWidth(r
.width
);
775 for (let x
=0; x
<this.size
.x
; x
++) {
776 for (let y
=0; y
<this.size
.y
; y
++) {
777 if (!this.enlightened
[x
][y
] && this.oldEnlightened
[x
][y
]) {
778 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
779 elt
.classList
.add("in-shadow");
780 if (this.g_pieces
[x
][y
])
781 this.g_pieces
[x
][y
].classList
.add("hidden");
783 else if (this.enlightened
[x
][y
] && !this.oldEnlightened
[x
][y
]) {
784 let elt
= document
.getElementById(this.coordsToId({x: x
, y: y
}));
785 elt
.classList
.remove("in-shadow");
786 if (this.g_pieces
[x
][y
])
787 this.g_pieces
[x
][y
].classList
.remove("hidden");
793 // Resize board: no need to destroy/recreate pieces
796 document
.getElementById(this.containerId
).querySelector(".chessboard");
797 const r
= chessboard
.getBoundingClientRect();
798 const multFact
= (mode
== "up" ? 1.05 : 0.95);
799 let [newWidth
, newHeight
] = [multFact
* r
.width
, multFact
* r
.height
];
801 if (newWidth
> window
.innerWidth
) {
802 newWidth
= window
.innerWidth
;
803 newHeight
= newWidth
/ this.size
.ratio
;
805 if (newHeight
> window
.innerHeight
) {
806 newHeight
= window
.innerHeight
;
807 newWidth
= newHeight
* this.size
.ratio
;
809 chessboard
.style
.width
= newWidth
+ "px";
810 chessboard
.style
.height
= newHeight
+ "px";
811 const newX
= (window
.innerWidth
- newWidth
) / 2;
812 chessboard
.style
.left
= newX
+ "px";
813 const newY
= (window
.innerHeight
- newHeight
) / 2;
814 chessboard
.style
.top
= newY
+ "px";
815 const newR
= {x: newX
, y: newY
, width: newWidth
, height: newHeight
};
816 const pieceWidth
= this.getPieceWidth(newWidth
);
817 // NOTE: next "if" for variants which use squares filling
818 // instead of "physical", moving pieces
820 for (let i
=0; i
< this.size
.x
; i
++) {
821 for (let j
=0; j
< this.size
.y
; j
++) {
822 if (this.g_pieces
[i
][j
]) {
823 // NOTE: could also use CSS transform "scale"
824 this.g_pieces
[i
][j
].style
.width
= pieceWidth
+ "px";
825 this.g_pieces
[i
][j
].style
.height
= pieceWidth
+ "px";
826 const [ip
, jp
] = this.getPixelPosition(i
, j
, newR
);
827 // Translate coordinates to use chessboard as reference:
828 this.g_pieces
[i
][j
].style
.transform
=
829 `translate(${ip - newX}px,${jp - newY}px)`;
835 this.rescaleReserve(newR
);
839 for (let c
of ['w','b']) {
840 if (!this.reserve
[c
])
842 const nbR
= this.getNbReservePieces(c
);
845 // Resize container first
846 const sqResSize
= this.getReserveSquareSize(r
.width
, nbR
);
847 const vShift
= (c
== this.playerColor
? r
.height
+ 5 : -sqResSize
- 5);
848 const [i0
, j0
] = [r
.x
, r
.y
+ vShift
];
849 let rcontainer
= document
.getElementById("reserves_" + c
);
850 rcontainer
.style
.left
= i0
+ "px";
851 rcontainer
.style
.top
= j0
+ "px";
852 rcontainer
.style
.width
= (nbR
* sqResSize
+ 1) + "px";
853 rcontainer
.style
.height
= sqResSize
+ "px";
854 // And then reserve cells:
855 const rpieceWidth
= this.getReserveSquareSize(r
.width
, nbR
);
856 Object
.keys(this.reserve
[c
]).forEach(p
=> {
857 if (this.reserve
[c
][p
] == 0)
859 let r_cell
= document
.getElementById(this.coordsToId({x: c
, y: p
}));
860 r_cell
.style
.width
= sqResSize
+ "px";
861 r_cell
.style
.height
= sqResSize
+ "px";
866 // Return the absolute pixel coordinates given current position.
867 // Our coordinate system differs from CSS one (x <--> y).
868 // We return here the CSS coordinates (more useful).
869 getPixelPosition(i
, j
, r
) {
871 return [0, 0]; //piece vanishes
873 if (typeof i
== "string") {
874 // Reserves: need to know the rank of piece
875 const nbR
= this.getNbReservePieces(i
);
876 const rsqSize
= this.getReserveSquareSize(r
.width
, nbR
);
877 x
= this.getRankInReserve(i
, j
) * rsqSize
;
878 y
= (this.playerColor
== i
? y
= r
.height
+ 5 : - 5 - rsqSize
);
881 const sqSize
= r
.width
/ this.size
.y
;
882 const flipped
= (this.playerColor
== 'b');
883 x
= (flipped
? this.size
.y
- 1 - j : j
) * sqSize
;
884 y
= (flipped
? this.size
.x
- 1 - i : i
) * sqSize
;
886 return [r
.x
+ x
, r
.y
+ y
];
890 let container
= document
.getElementById(this.containerId
);
891 let chessboard
= container
.querySelector(".chessboard");
893 const getOffset
= e
=> {
896 return {x: e
.clientX
, y: e
.clientY
};
897 let touchLocation
= null;
898 if (e
.targetTouches
&& e
.targetTouches
.length
>= 1)
899 // Touch screen, dragstart
900 touchLocation
= e
.targetTouches
[0];
901 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
902 // Touch screen, dragend
903 touchLocation
= e
.changedTouches
[0];
905 return {x: touchLocation
.clientX
, y: touchLocation
.clientY
};
906 return {x: 0, y: 0}; //shouldn't reach here =)
909 const centerOnCursor
= (piece
, e
) => {
910 const centerShift
= this.getPieceWidth(r
.width
) / 2;
911 const offset
= getOffset(e
);
912 piece
.style
.left
= (offset
.x
- centerShift
) + "px";
913 piece
.style
.top
= (offset
.y
- centerShift
) + "px";
918 startPiece
, curPiece
= null,
920 const mousedown
= (e
) => {
921 // Disable zoom on smartphones:
922 if (e
.touches
&& e
.touches
.length
> 1)
924 r
= chessboard
.getBoundingClientRect();
925 pieceWidth
= this.getPieceWidth(r
.width
);
926 const cd
= this.idToCoords(e
.target
.id
);
928 const move = this.doClick(cd
);
930 this.playPlusVisual(move);
932 const [x
, y
] = Object
.values(cd
);
933 if (typeof x
!= "number")
934 startPiece
= this.r_pieces
[x
][y
];
936 startPiece
= this.g_pieces
[x
][y
];
937 if (startPiece
&& this.canIplay(x
, y
)) {
940 curPiece
= startPiece
.cloneNode();
941 curPiece
.style
.transform
= "none";
942 curPiece
.style
.zIndex
= 5;
943 curPiece
.style
.width
= pieceWidth
+ "px";
944 curPiece
.style
.height
= pieceWidth
+ "px";
945 centerOnCursor(curPiece
, e
);
946 container
.appendChild(curPiece
);
947 startPiece
.style
.opacity
= "0.4";
948 chessboard
.style
.cursor
= "none";
954 const mousemove
= (e
) => {
957 centerOnCursor(curPiece
, e
);
959 else if (e
.changedTouches
&& e
.changedTouches
.length
>= 1)
960 // Attempt to prevent horizontal swipe...
964 const mouseup
= (e
) => {
967 const [x
, y
] = [start
.x
, start
.y
];
970 chessboard
.style
.cursor
= "pointer";
971 startPiece
.style
.opacity
= "1";
972 const offset
= getOffset(e
);
973 const landingElt
= document
.elementFromPoint(offset
.x
, offset
.y
);
975 (landingElt
? this.idToCoords(landingElt
.id
) : undefined);
977 // NOTE: clearly suboptimal, but much easier, and not a big deal.
978 const potentialMoves
= this.getPotentialMovesFrom([x
, y
])
979 .filter(m
=> m
.end
.x
== cd
.x
&& m
.end
.y
== cd
.y
);
980 const moves
= this.filterValid(potentialMoves
);
981 if (moves
.length
>= 2)
982 this.showChoices(moves
, r
);
983 else if (moves
.length
== 1)
984 this.playPlusVisual(moves
[0], r
);
989 if ('onmousedown' in window
) {
990 document
.addEventListener("mousedown", mousedown
);
991 document
.addEventListener("mousemove", mousemove
);
992 document
.addEventListener("mouseup", mouseup
);
993 document
.addEventListener("wheel",
994 (e
) => this.rescale(e
.deltaY
< 0 ? "up" : "down"));
996 if ('ontouchstart' in window
) {
997 // https://stackoverflow.com/a/42509310/12660887
998 document
.addEventListener("touchstart", mousedown
, {passive: false});
999 document
.addEventListener("touchmove", mousemove
, {passive: false});
1000 document
.addEventListener("touchend", mouseup
, {passive: false});
1002 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
1005 showChoices(moves
, r
) {
1006 let container
= document
.getElementById(this.containerId
);
1007 let chessboard
= container
.querySelector(".chessboard");
1008 let choices
= document
.createElement("div");
1009 choices
.id
= "choices";
1011 r
= chessboard
.getBoundingClientRect();
1012 choices
.style
.width
= r
.width
+ "px";
1013 choices
.style
.height
= r
.height
+ "px";
1014 choices
.style
.left
= r
.x
+ "px";
1015 choices
.style
.top
= r
.y
+ "px";
1016 chessboard
.style
.opacity
= "0.5";
1017 container
.appendChild(choices
);
1018 const squareWidth
= r
.width
/ this.size
.y
;
1019 const firstUpLeft
= (r
.width
- (moves
.length
* squareWidth
)) / 2;
1020 const firstUpTop
= (r
.height
- squareWidth
) / 2;
1021 const color
= moves
[0].appear
[0].c
;
1022 const callback
= (m
) => {
1023 chessboard
.style
.opacity
= "1";
1024 container
.removeChild(choices
);
1025 this.playPlusVisual(m
, r
);
1027 for (let i
=0; i
< moves
.length
; i
++) {
1028 let choice
= document
.createElement("div");
1029 choice
.classList
.add("choice");
1030 choice
.style
.width
= squareWidth
+ "px";
1031 choice
.style
.height
= squareWidth
+ "px";
1032 choice
.style
.left
= (firstUpLeft
+ i
* squareWidth
) + "px";
1033 choice
.style
.top
= firstUpTop
+ "px";
1034 choice
.style
.backgroundColor
= "lightyellow";
1035 choice
.onclick
= () => callback(moves
[i
]);
1036 const piece
= document
.createElement("piece");
1037 const cdisp
= moves
[i
].choice
|| moves
[i
].appear
[0].p
;
1038 C
.AddClass_es(piece
, this.pieces()[cdisp
]["class"]);
1039 piece
.classList
.add(C
.GetColorClass(color
));
1040 piece
.style
.width
= "100%";
1041 piece
.style
.height
= "100%";
1042 choice
.appendChild(piece
);
1043 choices
.appendChild(choice
);
1054 ratio: 1 //for rectangular board = y / x
1058 // Color of thing on square (i,j). 'undefined' if square is empty
1060 if (typeof i
== "string")
1061 return i
; //reserves
1062 return this.board
[i
][j
].charAt(0);
1065 static GetColorClass(c
) {
1070 return "other-color"; //unidentified color
1073 // Assume square i,j isn't empty
1075 if (typeof j
== "string")
1076 return j
; //reserves
1077 return this.board
[i
][j
].charAt(1);
1080 // Piece type on square (i,j)
1081 getPieceType(i
, j
) {
1082 const p
= this.getPiece(i
, j
);
1083 return C
.CannibalKings
[p
] || p
; //a cannibal king move as...
1086 // Get opponent color
1087 static GetOppCol(color
) {
1088 return (color
== "w" ? "b" : "w");
1091 // Can thing on square1 capture (no return) thing on square2?
1092 canTake([x1
, y1
], [x2
, y2
]) {
1093 return (this.getColor(x1
, y1
) !== this.getColor(x2
, y2
));
1096 // Is (x,y) on the chessboard?
1098 return (x
>= 0 && x
< this.size
.x
&&
1099 y
>= 0 && y
< this.size
.y
);
1102 // Am I allowed to move thing at square x,y ?
1104 return (this.playerColor
== this.turn
&& this.getColor(x
, y
) == this.turn
);
1107 ////////////////////////
1108 // PIECES SPECIFICATIONS
1110 pieces(color
, x
, y
) {
1111 const pawnShift
= (color
== "w" ? -1 : 1);
1112 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1113 const initRank
= ((color
== 'w' && x
>= 6) || (color
== 'b' && x
<= 1));
1119 steps: [[pawnShift
, 0]],
1120 range: (initRank
? 2 : 1)
1125 steps: [[pawnShift
, 1], [pawnShift
, -1]],
1134 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1143 [1, 2], [1, -2], [-1, 2], [-1, -2],
1144 [2, 1], [-2, 1], [2, -1], [-2, -1]
1154 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1163 [0, 1], [0, -1], [1, 0], [-1, 0],
1164 [1, 1], [1, -1], [-1, 1], [-1, -1]
1175 [0, 1], [0, -1], [1, 0], [-1, 0],
1176 [1, 1], [1, -1], [-1, 1], [-1, -1]
1183 '!': {"class": "king-pawn", moveas: "p"},
1184 '#': {"class": "king-rook", moveas: "r"},
1185 '$': {"class": "king-knight", moveas: "n"},
1186 '%': {"class": "king-bishop", moveas: "b"},
1187 '*': {"class": "king-queen", moveas: "q"}
1191 ////////////////////
1194 // For Cylinder: get Y coordinate
1196 if (!this.options
["cylinder"])
1198 let res
= y
% this.size
.y
;
1204 // Stop at the first capture found
1205 atLeastOneCapture(color
) {
1206 color
= color
|| this.turn
;
1207 const oppCol
= C
.GetOppCol(color
);
1208 for (let i
= 0; i
< this.size
.x
; i
++) {
1209 for (let j
= 0; j
< this.size
.y
; j
++) {
1210 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
1211 const allSpecs
= this.pieces(color
, i
, j
)
1212 let specs
= allSpecs
[this.getPieceType(i
, j
)];
1213 const attacks
= specs
.attack
|| specs
.moves
;
1214 for (let a
of attacks
) {
1215 outerLoop: for (let step
of a
.steps
) {
1216 let [ii
, jj
] = [i
+ step
[0], this.getY(j
+ step
[1])];
1217 let stepCounter
= 1;
1218 while (this.onBoard(ii
, jj
) && this.board
[ii
][jj
] == "") {
1219 if (a
.range
<= stepCounter
++)
1222 jj
= this.getY(jj
+ step
[1]);
1225 this.onBoard(ii
, jj
) &&
1226 this.getColor(ii
, jj
) == oppCol
&&
1228 [this.getBasicMove([i
, j
], [ii
, jj
])]
1241 getDropMovesFrom([c
, p
]) {
1242 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1243 // (but not necessarily otherwise: atLeastOneMove() etc)
1244 if (this.reserve
[c
][p
] == 0)
1247 for (let i
=0; i
<this.size
.x
; i
++) {
1248 for (let j
=0; j
<this.size
.y
; j
++) {
1250 this.board
[i
][j
] == "" &&
1251 (!this.enlightened
|| this.enlightened
[i
][j
]) &&
1254 (c
== 'w' && i
< this.size
.x
- 1) ||
1260 start: {x: c
, y: p
},
1262 appear: [new PiPo({x: i
, y: j
, c: c
, p: p
})],
1272 // All possible moves from selected square
1273 getPotentialMovesFrom(sq
, color
) {
1274 if (this.subTurnTeleport
== 2)
1276 if (typeof sq
[0] == "string")
1277 return this.getDropMovesFrom(sq
);
1278 if (this.isImmobilized(sq
))
1280 const piece
= this.getPieceType(sq
[0], sq
[1]);
1281 let moves
= this.getPotentialMovesOf(piece
, sq
);
1284 this.hasEnpassant
&&
1287 Array
.prototype.push
.apply(moves
, this.getEnpassantCaptures(sq
));
1292 this.castleFlags
[color
|| this.turn
].some(v
=> v
< this.size
.y
)
1294 Array
.prototype.push
.apply(moves
, this.getCastleMoves(sq
));
1296 return this.postProcessPotentialMoves(moves
);
1299 postProcessPotentialMoves(moves
) {
1300 if (moves
.length
== 0)
1302 const color
= this.getColor(moves
[0].start
.x
, moves
[0].start
.y
);
1303 const oppCol
= C
.GetOppCol(color
);
1305 if (this.options
["capture"] && this.atLeastOneCapture())
1306 moves
= this.capturePostProcess(moves
, oppCol
);
1308 if (this.options
["atomic"])
1309 this.atomicPostProcess(moves
, oppCol
);
1313 this.getPieceType(moves
[0].start
.x
, moves
[0].start
.y
) == "p"
1315 this.pawnPostProcess(moves
, color
, oppCol
);
1319 this.options
["cannibal"] &&
1320 this.options
["rifle"]
1322 // In this case a rifle-capture from last rank may promote a pawn
1323 this.riflePromotePostProcess(moves
, color
);
1329 capturePostProcess(moves
, oppCol
) {
1330 // Filter out non-capturing moves (not using m.vanish because of
1331 // self captures of Recycle and Teleport).
1332 return moves
.filter(m
=> {
1334 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1335 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1340 atomicPostProcess(moves
, oppCol
) {
1341 moves
.forEach(m
=> {
1343 this.board
[m
.end
.x
][m
.end
.y
] != "" &&
1344 this.getColor(m
.end
.x
, m
.end
.y
) == oppCol
1357 for (let step
of steps
) {
1358 let x
= m
.end
.x
+ step
[0];
1359 let y
= this.getY(m
.end
.y
+ step
[1]);
1361 this.onBoard(x
, y
) &&
1362 this.board
[x
][y
] != "" &&
1363 this.getPieceType(x
, y
) != "p"
1367 p: this.getPiece(x
, y
),
1368 c: this.getColor(x
, y
),
1375 if (!this.options
["rifle"])
1376 m
.appear
.pop(); //nothing appears
1381 pawnPostProcess(moves
, color
, oppCol
) {
1383 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1384 const initPiece
= this.getPiece(moves
[0].start
.x
, moves
[0].start
.y
);
1385 moves
.forEach(m
=> {
1386 const [x1
, y1
] = [m
.start
.x
, m
.start
.y
];
1387 const [x2
, y2
] = [m
.end
.x
, m
.end
.y
];
1388 const promotionOk
= (
1390 (!this.options
["rifle"] || this.board
[x2
][y2
] == "")
1393 return; //nothing to do
1394 if (this.options
["pawnfall"]) {
1398 let finalPieces
= ["p"];
1400 this.options
["cannibal"] &&
1401 this.board
[x2
][y2
] != "" &&
1402 this.getColor(x2
, y2
) == oppCol
1404 finalPieces
= [this.getPieceType(x2
, y2
)];
1407 finalPieces
= this.pawnPromotions
;
1408 m
.appear
[0].p
= finalPieces
[0];
1409 if (initPiece
== "!") //cannibal king-pawn
1410 m
.appear
[0].p
= C
.CannibalKingCode
[finalPieces
[0]];
1411 for (let i
=1; i
<finalPieces
.length
; i
++) {
1412 const piece
= finalPieces
[i
];
1415 p: (initPiece
!= "!" ? piece : C
.CannibalKingCode
[piece
])
1417 let newMove
= this.getBasicMove([x1
, y1
], [x2
, y2
], tr
);
1418 moreMoves
.push(newMove
);
1421 Array
.prototype.push
.apply(moves
, moreMoves
);
1424 riflePromotePostProcess(moves
, color
) {
1425 const lastRank
= (color
== "w" ? 0 : this.size
.x
- 1);
1427 moves
.forEach(m
=> {
1429 m
.start
.x
== lastRank
&&
1430 m
.appear
.length
>= 1 &&
1431 m
.appear
[0].p
== "p" &&
1432 m
.appear
[0].x
== m
.start
.x
&&
1433 m
.appear
[0].y
== m
.start
.y
1435 m
.appear
[0].p
= this.pawnPromotions
[0];
1436 for (let i
=1; i
<this.pawnPromotions
.length
; i
++) {
1437 let newMv
= JSON
.parse(JSON
.stringify(m
));
1438 newMv
.appear
[0].p
= this.pawnSpecs
.promotions
[i
];
1439 newMoves
.push(newMv
);
1443 Array
.prototype.push
.apply(moves
, newMoves
);
1446 // NOTE: using special symbols to not interfere with variants' pieces codes
1447 static get CannibalKings() {
1458 static get CannibalKingCode() {
1470 return !!C
.CannibalKings
[symbol
];
1474 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1475 isImmobilized([x
, y
]) {
1476 if (!this.options
["madrasi"])
1478 const color
= this.getColor(x
, y
);
1479 const oppCol
= C
.GetOppCol(color
);
1480 const piece
= this.getPieceType(x
, y
); //ok not cannibal king
1481 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1482 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1483 for (let a
of attacks
) {
1484 outerLoop: for (let step
of a
.steps
) {
1485 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
1486 let stepCounter
= 1;
1487 while (this.onBoard(i
, j
) && this.board
[i
][j
] == "") {
1488 if (a
.range
<= stepCounter
++)
1491 j
= this.getY(j
+ step
[1]);
1494 this.onBoard(i
, j
) &&
1495 this.getColor(i
, j
) == oppCol
&&
1496 this.getPieceType(i
, j
) == piece
1506 // In some variants, objects on boards don't stop movement (Chakart)
1507 return this.board
[i
][j
] == "";
1510 // Generic method to find possible moves of "sliding or jumping" pieces
1511 getPotentialMovesOf(piece
, [x
, y
]) {
1512 const color
= this.getColor(x
, y
);
1513 const stepSpec
= this.pieces(color
, x
, y
)[piece
];
1515 // Next 3 for Cylinder mode:
1520 const addMove
= (start
, end
) => {
1521 let newMove
= this.getBasicMove(start
, end
);
1522 if (segments
.length
> 0) {
1523 newMove
.segments
= JSON
.parse(JSON
.stringify(segments
));
1524 newMove
.segments
.push([[segStart
[0], segStart
[1]], [end
[0], end
[1]]]);
1526 moves
.push(newMove
);
1529 const findAddMoves
= (type
, stepArray
) => {
1530 for (let s
of stepArray
) {
1531 outerLoop: for (let step
of s
.steps
) {
1534 let [i
, j
] = [x
, y
];
1535 let stepCounter
= 0;
1537 this.onBoard(i
, j
) &&
1538 (this.canStepOver(i
, j
) || (i
== x
&& j
== y
))
1542 !explored
[i
+ "." + j
] &&
1545 explored
[i
+ "." + j
] = true;
1546 addMove([x
, y
], [i
, j
]);
1548 if (s
.range
<= stepCounter
++)
1550 const oldIJ
= [i
, j
];
1552 j
= this.getY(j
+ step
[1]);
1553 if (Math
.abs(j
- oldIJ
[1]) > 1) {
1554 // Boundary between segments (cylinder mode)
1555 segments
.push([[segStart
[0], segStart
[1]], oldIJ
]);
1559 if (!this.onBoard(i
, j
))
1561 const pieceIJ
= this.getPieceType(i
, j
);
1563 type
!= "moveonly" &&
1564 !explored
[i
+ "." + j
] &&
1566 !this.options
["zen"] ||
1570 this.canTake([x
, y
], [i
, j
]) ||
1572 (this.options
["recycle"] || this.options
["teleport"]) &&
1577 explored
[i
+ "." + j
] = true;
1578 addMove([x
, y
], [i
, j
]);
1584 const specialAttack
= !!stepSpec
.attack
;
1586 findAddMoves("attack", stepSpec
.attack
);
1587 findAddMoves(specialAttack
? "moveonly" : "all", stepSpec
.moves
);
1588 if (this.options
["zen"]) {
1589 Array
.prototype.push
.apply(moves
,
1590 this.findCapturesOn([x
, y
], {zen: true}));
1595 // Search for enemy (or not) pieces attacking [x, y]
1596 findCapturesOn([x
, y
], args
) {
1599 args
.oppCol
= C
.GetOppCol(this.getColor(x
, y
) || this.turn
);
1600 for (let i
=0; i
<this.size
.x
; i
++) {
1601 for (let j
=0; j
<this.size
.y
; j
++) {
1603 this.board
[i
][j
] != "" &&
1604 this.getColor(i
, j
) == args
.oppCol
&&
1605 !this.isImmobilized([i
, j
])
1607 if (args
.zen
&& this.isKing(this.getPiece(i
, j
)))
1608 continue; //king not captured in this way
1610 this.pieces(args
.oppCol
, i
, j
)[this.getPieceType(i
, j
)];
1611 const attacks
= stepSpec
.attack
|| stepSpec
.moves
;
1612 for (let a
of attacks
) {
1613 for (let s
of a
.steps
) {
1614 // Quick check: if step isn't compatible, don't even try
1615 if (!C
.CompatibleStep([i
, j
], [x
, y
], s
, a
.range
))
1617 // Finally verify that nothing stand in-between
1618 let [ii
, jj
] = [i
+ s
[0], this.getY(j
+ s
[1])];
1619 let stepCounter
= 1;
1621 this.onBoard(ii
, jj
) &&
1622 this.board
[ii
][jj
] == "" &&
1623 (ii
!= x
|| jj
!= y
) //condition to attack empty squares too
1626 jj
= this.getY(jj
+ s
[1]);
1628 if (ii
== x
&& jj
== y
) {
1631 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
1633 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
1635 return moves
; //test for underCheck
1645 static CompatibleStep([x1
, y1
], [x2
, y2
], step
, range
) {
1646 const rx
= (x2
- x1
) / step
[0],
1647 ry
= (y2
- y1
) / step
[1];
1649 (!Number
.isFinite(rx
) && !Number
.isNaN(rx
)) ||
1650 (!Number
.isFinite(ry
) && !Number
.isNaN(ry
))
1654 let distance
= (Number
.isNaN(rx
) ? ry : rx
);
1655 // TODO: 1e-7 here is totally arbitrary
1656 if (Math
.abs(distance
- Math
.round(distance
)) > 1e-7)
1658 distance
= Math
.round(distance
); //in case of (numerical...)
1659 if (range
< distance
)
1664 // Build a regular move from its initial and destination squares.
1665 // tr: transformation
1666 getBasicMove([sx
, sy
], [ex
, ey
], tr
) {
1667 const initColor
= this.getColor(sx
, sy
);
1668 const initPiece
= this.getPiece(sx
, sy
);
1669 const destColor
= (this.board
[ex
][ey
] != "" ? this.getColor(ex
, ey
) : "");
1673 start: {x: sx
, y: sy
},
1677 !this.options
["rifle"] ||
1678 this.board
[ex
][ey
] == "" ||
1679 destColor
== initColor
//Recycle, Teleport
1685 c: !!tr
? tr
.c : initColor
,
1686 p: !!tr
? tr
.p : initPiece
1698 if (this.board
[ex
][ey
] != "") {
1703 c: this.getColor(ex
, ey
),
1704 p: this.getPiece(ex
, ey
)
1707 if (this.options
["cannibal"] && destColor
!= initColor
) {
1708 const lastIdx
= mv
.vanish
.length
- 1;
1709 let trPiece
= mv
.vanish
[lastIdx
].p
;
1710 if (this.isKing(this.getPiece(sx
, sy
)))
1711 trPiece
= C
.CannibalKingCode
[trPiece
];
1712 if (mv
.appear
.length
>= 1)
1713 mv
.appear
[0].p
= trPiece
;
1714 else if (this.options
["rifle"]) {
1737 // En-passant square, if any
1738 getEpSquare(moveOrSquare
) {
1739 if (typeof moveOrSquare
=== "string") {
1740 const square
= moveOrSquare
;
1743 return C
.SquareToCoords(square
);
1745 // Argument is a move:
1746 const move = moveOrSquare
;
1747 const s
= move.start
,
1751 Math
.abs(s
.x
- e
.x
) == 2 &&
1752 // Next conditions for variants like Atomic or Rifle, Recycle...
1753 (move.appear
.length
> 0 && move.appear
[0].p
== "p") &&
1754 (move.vanish
.length
> 0 && move.vanish
[0].p
== "p")
1761 return undefined; //default
1764 // Special case of en-passant captures: treated separately
1765 getEnpassantCaptures([x
, y
]) {
1766 const color
= this.getColor(x
, y
);
1767 const shiftX
= (color
== 'w' ? -1 : 1);
1768 const oppCol
= C
.GetOppCol(color
);
1769 let enpassantMove
= null;
1772 this.epSquare
.x
== x
+ shiftX
&&
1773 Math
.abs(this.getY(this.epSquare
.y
- y
)) == 1 &&
1774 this.getColor(x
, this.epSquare
.y
) == oppCol
//Doublemove guard...
1776 const [epx
, epy
] = [this.epSquare
.x
, this.epSquare
.y
];
1777 this.board
[epx
][epy
] = oppCol
+ "p";
1778 enpassantMove
= this.getBasicMove([x
, y
], [epx
, epy
]);
1779 this.board
[epx
][epy
] = "";
1780 const lastIdx
= enpassantMove
.vanish
.length
- 1; //think Rifle
1781 enpassantMove
.vanish
[lastIdx
].x
= x
;
1783 return !!enpassantMove
? [enpassantMove
] : [];
1786 // "castleInCheck" arg to let some variants castle under check
1787 getCastleMoves([x
, y
], finalSquares
, castleInCheck
, castleWith
) {
1788 const c
= this.getColor(x
, y
);
1791 const oppCol
= C
.GetOppCol(c
);
1795 finalSquares
|| [ [2, 3], [this.size
.y
- 2, this.size
.y
- 3] ];
1796 const castlingKing
= this.getPiece(x
, y
);
1797 castlingCheck: for (
1800 castleSide
++ //large, then small
1802 if (this.castleFlags
[c
][castleSide
] >= this.size
.y
)
1804 // If this code is reached, rook and king are on initial position
1806 // NOTE: in some variants this is not a rook
1807 const rookPos
= this.castleFlags
[c
][castleSide
];
1808 const castlingPiece
= this.getPiece(x
, rookPos
);
1810 this.board
[x
][rookPos
] == "" ||
1811 this.getColor(x
, rookPos
) != c
||
1812 (!!castleWith
&& !castleWith
.includes(castlingPiece
))
1814 // Rook is not here, or changed color (see Benedict)
1817 // Nothing on the path of the king ? (and no checks)
1818 const finDist
= finalSquares
[castleSide
][0] - y
;
1819 let step
= finDist
/ Math
.max(1, Math
.abs(finDist
));
1823 (!castleInCheck
&& this.underCheck([x
, i
], oppCol
)) ||
1825 this.board
[x
][i
] != "" &&
1826 // NOTE: next check is enough, because of chessboard constraints
1827 (this.getColor(x
, i
) != c
|| ![rookPos
, y
].includes(i
))
1830 continue castlingCheck
;
1833 } while (i
!= finalSquares
[castleSide
][0]);
1834 // Nothing on the path to the rook?
1835 step
= (castleSide
== 0 ? -1 : 1);
1836 for (i
= y
+ step
; i
!= rookPos
; i
+= step
) {
1837 if (this.board
[x
][i
] != "")
1838 continue castlingCheck
;
1841 // Nothing on final squares, except maybe king and castling rook?
1842 for (i
= 0; i
< 2; i
++) {
1844 finalSquares
[castleSide
][i
] != rookPos
&&
1845 this.board
[x
][finalSquares
[castleSide
][i
]] != "" &&
1847 finalSquares
[castleSide
][i
] != y
||
1848 this.getColor(x
, finalSquares
[castleSide
][i
]) != c
1851 continue castlingCheck
;
1855 // If this code is reached, castle is valid
1861 y: finalSquares
[castleSide
][0],
1867 y: finalSquares
[castleSide
][1],
1873 // King might be initially disguised (Titan...)
1874 new PiPo({ x: x
, y: y
, p: castlingKing
, c: c
}),
1875 new PiPo({ x: x
, y: rookPos
, p: castlingPiece
, c: c
})
1878 Math
.abs(y
- rookPos
) <= 2
1879 ? {x: x
, y: rookPos
}
1880 : {x: x
, y: y
+ 2 * (castleSide
== 0 ? -1 : 1)}
1888 ////////////////////
1891 // Is (king at) given position under check by "oppCol" ?
1892 underCheck([x
, y
], oppCol
) {
1893 if (this.options
["taking"] || this.options
["dark"])
1896 this.findCapturesOn([x
, y
], {oppCol: oppCol
, one: true}).length
>= 1
1900 // Stop at first king found (TODO: multi-kings)
1901 searchKingPos(color
) {
1902 for (let i
=0; i
< this.size
.x
; i
++) {
1903 for (let j
=0; j
< this.size
.y
; j
++) {
1904 if (this.getColor(i
, j
) == color
&& this.isKing(this.getPiece(i
, j
)))
1908 return [-1, -1]; //king not found
1911 filterValid(moves
) {
1912 if (moves
.length
== 0)
1914 const color
= this.turn
;
1915 const oppCol
= C
.GetOppCol(color
);
1916 if (this.options
["balance"] && [1, 3].includes(this.movesCount
)) {
1917 // Forbid moves either giving check or exploding opponent's king:
1918 const oppKingPos
= this.searchKingPos(oppCol
);
1919 moves
= moves
.filter(m
=> {
1921 m
.vanish
.some(v
=> v
.c
== oppCol
&& v
.p
== "k") &&
1922 m
.appear
.every(a
=> a
.c
!= oppCol
|| a
.p
!= "k")
1925 this.playOnBoard(m
);
1926 const res
= !this.underCheck(oppKingPos
, color
);
1927 this.undoOnBoard(m
);
1931 if (this.options
["taking"] || this.options
["dark"])
1933 const kingPos
= this.searchKingPos(color
);
1934 let filtered
= {}; //avoid re-checking similar moves (promotions...)
1935 return moves
.filter(m
=> {
1936 const key
= m
.start
.x
+ m
.start
.y
+ '.' + m
.end
.x
+ m
.end
.y
;
1937 if (!filtered
[key
]) {
1938 this.playOnBoard(m
);
1939 let square
= kingPos
,
1940 res
= true; //a priori valid
1941 if (m
.vanish
.some(v
=> {
1942 return C
.CannibalKings
[v
.p
] && v
.c
== color
;
1944 // Search king in appear array:
1946 m
.appear
.findIndex(a
=> {
1947 return C
.CannibalKings
[a
.p
] && a
.c
== color
;
1949 if (newKingIdx
>= 0)
1950 square
= [m
.appear
[newKingIdx
].x
, m
.appear
[newKingIdx
].y
];
1954 res
&&= !this.underCheck(square
, oppCol
);
1955 this.undoOnBoard(m
);
1956 filtered
[key
] = res
;
1959 return filtered
[key
];
1966 // Aggregate flags into one object
1968 return this.castleFlags
;
1971 // Reverse operation
1972 disaggregateFlags(flags
) {
1973 this.castleFlags
= flags
;
1976 // Apply a move on board
1978 for (let psq
of move.vanish
)
1979 this.board
[psq
.x
][psq
.y
] = "";
1980 for (let psq
of move.appear
)
1981 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1983 // Un-apply the played move
1985 for (let psq
of move.appear
)
1986 this.board
[psq
.x
][psq
.y
] = "";
1987 for (let psq
of move.vanish
)
1988 this.board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
1991 updateCastleFlags(move) {
1992 // Update castling flags if start or arrive from/at rook/king locations
1993 move.appear
.concat(move.vanish
).forEach(psq
=> {
1995 this.board
[psq
.x
][psq
.y
] != "" &&
1996 this.getPieceType(psq
.x
, psq
.y
) == "k"
1998 this.castleFlags
[psq
.c
] = [this.size
.y
, this.size
.y
];
2000 // NOTE: not "else if" because king can capture enemy rook...
2004 else if (psq
.x
== this.size
.x
- 1)
2007 const fidx
= this.castleFlags
[c
].findIndex(f
=> f
== psq
.y
);
2009 this.castleFlags
[c
][fidx
] = this.size
.y
;
2017 // If flags already off, no need to re-check:
2018 Object
.keys(this.castleFlags
).some(c
=> {
2019 return this.castleFlags
[c
].some(val
=> val
< this.size
.y
)})
2021 this.updateCastleFlags(move);
2023 if (this.options
["crazyhouse"]) {
2024 move.vanish
.forEach(v
=> {
2025 const square
= C
.CoordsToSquare({x: v
.x
, y: v
.y
});
2026 if (this.ispawn
[square
])
2027 delete this.ispawn
[square
];
2029 if (move.appear
.length
> 0 && move.vanish
.length
> 0) {
2030 // Assumption: something is moving
2031 const initSquare
= C
.CoordsToSquare(move.start
);
2032 const destSquare
= C
.CoordsToSquare(move.end
);
2034 this.ispawn
[initSquare
] ||
2035 (move.vanish
[0].p
== "p" && move.appear
[0].p
!= "p")
2037 this.ispawn
[destSquare
] = true;
2040 this.ispawn
[destSquare
] &&
2041 this.getColor(move.end
.x
, move.end
.y
) != move.vanish
[0].c
2043 move.vanish
[1].p
= "p";
2044 delete this.ispawn
[destSquare
];
2048 const minSize
= Math
.min(move.appear
.length
, move.vanish
.length
);
2051 // Warning; atomic pawn removal isn't a capture
2052 (!this.options
["atomic"] || !this.rempawn
|| this.movesCount
>= 1)
2054 const color
= this.turn
;
2055 for (let i
=minSize
; i
<move.appear
.length
; i
++) {
2056 // Something appears = dropped on board (some exceptions, Chakart...)
2057 if (move.appear
[i
].c
== color
) {
2058 const piece
= move.appear
[i
].p
;
2059 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] - 1);
2062 for (let i
=minSize
; i
<move.vanish
.length
; i
++) {
2063 // Something vanish: add to reserve except if recycle & opponent
2065 this.options
["crazyhouse"] ||
2066 (this.options
["recycle"] && move.vanish
[i
].c
== color
)
2068 const piece
= move.vanish
[i
].p
;
2069 this.updateReserve(color
, piece
, this.reserve
[color
][piece
] + 1);
2077 if (this.hasEnpassant
)
2078 this.epSquare
= this.getEpSquare(move);
2079 this.playOnBoard(move);
2080 this.postPlay(move);
2084 const color
= this.turn
;
2085 const oppCol
= C
.GetOppCol(color
);
2086 if (this.options
["dark"])
2087 this.updateEnlightened();
2088 if (this.options
["teleport"]) {
2090 this.subTurnTeleport
== 1 &&
2091 move.vanish
.length
> move.appear
.length
&&
2092 move.vanish
[move.vanish
.length
- 1].c
== color
2094 const v
= move.vanish
[move.vanish
.length
- 1];
2095 this.captured
= {x: v
.x
, y: v
.y
, c: v
.c
, p: v
.p
};
2096 this.subTurnTeleport
= 2;
2099 this.subTurnTeleport
= 1;
2100 this.captured
= null;
2102 if (this.options
["balance"]) {
2103 if (![1, 3].includes(this.movesCount
))
2109 this.options
["doublemove"] &&
2110 this.movesCount
>= 1 &&
2113 (this.options
["progressive"] && this.subTurn
<= this.movesCount
)
2115 const oppKingPos
= this.searchKingPos(oppCol
);
2117 oppKingPos
[0] >= 0 &&
2119 this.options
["taking"] ||
2120 !this.underCheck(oppKingPos
, color
)
2133 // "Stop at the first move found"
2134 atLeastOneMove(color
) {
2135 color
= color
|| this.turn
;
2136 for (let i
= 0; i
< this.size
.x
; i
++) {
2137 for (let j
= 0; j
< this.size
.y
; j
++) {
2138 if (this.board
[i
][j
] != "" && this.getColor(i
, j
) == color
) {
2139 // NOTE: in fact searching for all potential moves from i,j.
2140 // I don't believe this is an issue, for now at least.
2141 const moves
= this.getPotentialMovesFrom([i
, j
]);
2142 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2147 if (this.hasReserve
&& this.reserve
[color
]) {
2148 for (let p
of Object
.keys(this.reserve
[color
])) {
2149 const moves
= this.getDropMovesFrom([color
, p
]);
2150 if (moves
.some(m
=> this.filterValid([m
]).length
>= 1))
2157 // What is the score ? (Interesting if game is over)
2158 getCurrentScore(move) {
2159 const color
= this.turn
;
2160 const oppCol
= C
.GetOppCol(color
);
2161 const kingPos
= [this.searchKingPos(color
), this.searchKingPos(oppCol
)];
2162 if (kingPos
[0][0] < 0 && kingPos
[1][0] < 0)
2164 if (kingPos
[0][0] < 0)
2165 return (color
== "w" ? "0-1" : "1-0");
2166 if (kingPos
[1][0] < 0)
2167 return (color
== "w" ? "1-0" : "0-1");
2168 if (this.atLeastOneMove())
2170 // No valid move: stalemate or checkmate?
2171 if (!this.underCheck(kingPos
[0], color
))
2174 return (color
== "w" ? "0-1" : "1-0");
2177 playVisual(move, r
) {
2178 move.vanish
.forEach(v
=> {
2179 this.g_pieces
[v
.x
][v
.y
].remove();
2180 this.g_pieces
[v
.x
][v
.y
] = null;
2183 document
.getElementById(this.containerId
).querySelector(".chessboard");
2185 r
= chessboard
.getBoundingClientRect();
2186 const pieceWidth
= this.getPieceWidth(r
.width
);
2187 move.appear
.forEach(a
=> {
2188 this.g_pieces
[a
.x
][a
.y
] = document
.createElement("piece");
2189 C
.AddClass_es(this.g_pieces
[a
.x
][a
.y
], this.pieces()[a
.p
]["class"]);
2190 this.g_pieces
[a
.x
][a
.y
].classList
.add(C
.GetColorClass(a
.c
));
2191 this.g_pieces
[a
.x
][a
.y
].style
.width
= pieceWidth
+ "px";
2192 this.g_pieces
[a
.x
][a
.y
].style
.height
= pieceWidth
+ "px";
2193 const [ip
, jp
] = this.getPixelPosition(a
.x
, a
.y
, r
);
2194 // Translate coordinates to use chessboard as reference:
2195 this.g_pieces
[a
.x
][a
.y
].style
.transform
=
2196 `translate(${ip - r.x}px,${jp - r.y}px)`;
2197 if (this.enlightened
&& !this.enlightened
[a
.x
][a
.y
])
2198 this.g_pieces
[a
.x
][a
.y
].classList
.add("hidden");
2199 chessboard
.appendChild(this.g_pieces
[a
.x
][a
.y
]);
2201 if (this.options
["dark"])
2202 this.graphUpdateEnlightened();
2205 playPlusVisual(move, r
) {
2207 this.playVisual(move, r
);
2208 this.afterPlay(move); //user method
2211 getMaxDistance(rwidth
) {
2212 // Works for all rectangular boards:
2213 return Math
.sqrt(rwidth
** 2 + (rwidth
/ this.size
.ratio
) ** 2);
2217 return (typeof x
== "string" ? this.r_pieces : this.g_pieces
)[x
][y
];
2220 animate(move, callback
) {
2221 if (this.noAnimate
|| move.noAnimate
) {
2225 let initPiece
= this.getDomPiece(move.start
.x
, move.start
.y
);
2226 // NOTE: cloning generally not required, but light enough, and simpler
2227 let movingPiece
= initPiece
.cloneNode();
2228 initPiece
.style
.opacity
= "0";
2230 document
.getElementById(this.containerId
)
2231 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2232 if (typeof move.start
.x
== "string") {
2233 // Need to bound width/height (was 100% for reserve pieces)
2234 const pieceWidth
= this.getPieceWidth(r
.width
);
2235 movingPiece
.style
.width
= pieceWidth
+ "px";
2236 movingPiece
.style
.height
= pieceWidth
+ "px";
2238 const maxDist
= this.getMaxDistance(r
.width
);
2239 const pieces
= this.pieces();
2241 const startCode
= this.getPiece(move.start
.x
, move.start
.y
);
2242 C
.RemoveClass_es(movingPiece
, pieces
[startCode
]["class"]);
2243 C
.AddClass_es(movingPiece
, pieces
[move.drag
.p
]["class"]);
2244 const apparentColor
= this.getColor(move.start
.x
, move.start
.y
);
2245 if (apparentColor
!= move.drag
.c
) {
2246 movingPiece
.classList
.remove(C
.GetColorClass(apparentColor
));
2247 movingPiece
.classList
.add(C
.GetColorClass(move.drag
.c
));
2250 container
.appendChild(movingPiece
);
2251 const animateSegment
= (index
, cb
) => {
2252 // NOTE: move.drag could be generalized per-segment (usage?)
2253 const [i1
, j1
] = move.segments
[index
][0];
2254 const [i2
, j2
] = move.segments
[index
][1];
2255 const dep
= this.getPixelPosition(i1
, j1
, r
);
2256 const arr
= this.getPixelPosition(i2
, j2
, r
);
2257 movingPiece
.style
.transitionDuration
= "0s";
2258 movingPiece
.style
.transform
= `translate(${dep[0]}px, ${dep[1]}px)`;
2260 Math
.sqrt((arr
[0] - dep
[0]) ** 2 + (arr
[1] - dep
[1]) ** 2);
2261 const duration
= 0.2 + (distance
/ maxDist
) * 0.3;
2262 // TODO: unclear why we need this new delay below:
2264 movingPiece
.style
.transitionDuration
= duration
+ "s";
2265 // movingPiece is child of container: no need to adjust coordinates
2266 movingPiece
.style
.transform
= `translate(${arr[0]}px, ${arr[1]}px)`;
2267 setTimeout(cb
, duration
* 1000);
2270 if (!move.segments
) {
2272 [[move.start
.x
, move.start
.y
], [move.end
.x
, move.end
.y
]]
2276 const animateSegmentCallback
= () => {
2277 if (index
< move.segments
.length
)
2278 animateSegment(index
++, animateSegmentCallback
);
2280 movingPiece
.remove();
2281 initPiece
.style
.opacity
= "1";
2285 animateSegmentCallback();
2288 playReceivedMove(moves
, callback
) {
2289 const launchAnimation
= () => {
2290 const r
= container
.querySelector(".chessboard").getBoundingClientRect();
2291 const animateRec
= i
=> {
2292 this.animate(moves
[i
], () => {
2293 this.play(moves
[i
]);
2294 this.playVisual(moves
[i
], r
);
2295 if (i
< moves
.length
- 1)
2296 setTimeout(() => animateRec(i
+1), 300);
2303 // Delay if user wasn't focused:
2304 const checkDisplayThenAnimate
= (delay
) => {
2305 if (container
.style
.display
== "none") {
2306 alert("New move! Let's go back to game...");
2307 document
.getElementById("gameInfos").style
.display
= "none";
2308 container
.style
.display
= "block";
2309 setTimeout(launchAnimation
, 700);
2312 setTimeout(launchAnimation
, delay
|| 0);
2314 let container
= document
.getElementById(this.containerId
);
2315 if (document
.hidden
) {
2316 document
.onvisibilitychange
= () => {
2317 document
.onvisibilitychange
= undefined;
2318 checkDisplayThenAnimate(700);
2322 checkDisplayThenAnimate();