Fix Benedict-Dark
[xogo.git] / base_rules.js
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";
5
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 {
9
10 static get Aliases() {
11 return {'C': ChessRules};
12 }
13
14 /////////////////////////
15 // VARIANT SPECIFICATIONS
16
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() {
21 return {
22 select: [{
23 label: "Randomness",
24 variable: "randomness",
25 defaut: 0,
26 options: [
27 {label: "Deterministic", value: 0},
28 {label: "Symmetric random", value: 1},
29 {label: "Asymmetric random", value: 2}
30 ]
31 }],
32 check: [
33 {
34 label: "Capture king",
35 defaut: false,
36 variable: "taking"
37 },
38 {
39 label: "Falling pawn",
40 defaut: false,
41 variable: "pawnfall"
42 }
43 ],
44 // Game modifiers (using "elementary variants"). Default: false
45 styles: [
46 "atomic",
47 "balance", //takes precedence over doublemove & progressive
48 "cannibal",
49 "capture",
50 "crazyhouse",
51 "cylinder", //ok with all
52 "dark",
53 "doublemove",
54 "madrasi",
55 "progressive", //(natural) priority over doublemove
56 "recycle",
57 "rifle",
58 "teleport",
59 "zen"
60 ]
61 };
62 }
63
64 get pawnPromotions() {
65 return ['q', 'r', 'n', 'b'];
66 }
67
68 // Some variants don't have flags:
69 get hasFlags() {
70 return true;
71 }
72 // Or castle
73 get hasCastle() {
74 return this.hasFlags;
75 }
76
77 // En-passant captures allowed?
78 get hasEnpassant() {
79 return true;
80 }
81
82 get hasReserve() {
83 return (
84 !!this.options["crazyhouse"] ||
85 (!!this.options["recycle"] && !this.options["teleport"])
86 );
87 }
88
89 get noAnimate() {
90 return !!this.options["dark"];
91 }
92
93 // Some variants use click infos:
94 doClick(coords) {
95 if (typeof coords.x != "number")
96 return null; //click on reserves
97 if (
98 this.options["teleport"] && this.subTurnTeleport == 2 &&
99 this.board[coords.x][coords.y] == ""
100 ) {
101 return new Move({
102 start: {x: this.captured.x, y: this.captured.y},
103 appear: [
104 new PiPo({
105 x: coords.x,
106 y: coords.y,
107 c: this.captured.c, //this.turn,
108 p: this.captured.p
109 })
110 ],
111 vanish: [],
112 drag: {c: this.captured.c, p: this.captured.p}
113 });
114 }
115 return null;
116 }
117
118 ////////////////////
119 // COORDINATES UTILS
120
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)));
125 }
126
127 // {x:11, y:12} --> bc
128 static CoordsToSquare(cd) {
129 return Object.values(cd).map(c => c.toString(36)).join("");
130 }
131
132 coordsToId(cd) {
133 if (typeof cd.x == "number") {
134 return (
135 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
136 );
137 }
138 // Reserve :
139 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
140 }
141
142 idToCoords(targetId) {
143 if (!targetId)
144 return null; //outside page, maybe...
145 const idParts = targetId.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
146 if (
147 idParts.length < 2 ||
148 idParts[0] != this.containerId ||
149 !idParts[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
150 ) {
151 return null;
152 }
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]};
158 }
159
160 /////////////
161 // FEN UTILS
162
163 // Turn "wb" into "B" (for FEN)
164 board2fen(b) {
165 return (b[0] == "w" ? b[1].toUpperCase() : b[1]);
166 }
167
168 // Turn "p" into "bp" (for board)
169 fen2board(f) {
170 return (f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f);
171 }
172
173 // Setup the initial random-or-not (asymmetric-or-not) position
174 genRandInitFen(seed) {
175 Random.setSeed(seed);
176
177 let fen, flags = "0707";
178 if (!this.options.randomness)
179 // Deterministic:
180 fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
181
182 else {
183 // Randomize
184 let pieces = { w: new Array(8), b: new Array(8) };
185 flags = "";
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'];
190 flags += flags;
191 break;
192 }
193
194 let positions = ArrayFun.range(8);
195
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);
205
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);
213
214 // Get random square for queen
215 randIndex = Random.randInt(4);
216 const queenPos = positions[randIndex];
217 positions.splice(randIndex, 1);
218
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];
224
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();
235 }
236 fen = (
237 pieces["b"].join("") +
238 "/pppppppp/8/8/8/8/PPPPPPPP/" +
239 pieces["w"].join("").toUpperCase() +
240 " w 0"
241 );
242 }
243 // Add turn + flags + enpassant (+ reserve)
244 let parts = [];
245 if (this.hasFlags)
246 parts.push(`"flags":"${flags}"`);
247 if (this.hasEnpassant)
248 parts.push('"enpassant":"-"');
249 if (this.hasReserve)
250 parts.push('"reserve":"000000000000"');
251 if (this.options["crazyhouse"])
252 parts.push('"ispawn":"-"');
253 if (parts.length >= 1)
254 fen += " {" + parts.join(",") + "}";
255 return fen;
256 }
257
258 // "Parse" FEN: just return untransformed string data
259 parseFen(fen) {
260 const fenParts = fen.split(" ");
261 let res = {
262 position: fenParts[0],
263 turn: fenParts[1],
264 movesCount: fenParts[2]
265 };
266 if (fenParts.length > 3)
267 res = Object.assign(res, JSON.parse(fenParts[3]));
268 return res;
269 }
270
271 // Return current fen (game state)
272 getFen() {
273 let fen = (
274 this.getPosition() + " " +
275 this.getTurnFen() + " " +
276 this.movesCount
277 );
278 let parts = [];
279 if (this.hasFlags)
280 parts.push(`"flags":"${this.getFlagsFen()}"`);
281 if (this.hasEnpassant)
282 parts.push(`"enpassant":"${this.getEnpassantFen()}"`);
283 if (this.hasReserve)
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(",") + "}";
289 return fen;
290 }
291
292 // Position part of the FEN string
293 getPosition() {
294 const format = (count) => {
295 // if more than 9 consecutive free spaces, break the integer,
296 // otherwise FEN parsing will fail.
297 if (count <= 9)
298 return count;
299 // Most boards of size < 18:
300 if (count <= 18)
301 return "9" + (count - 9);
302 // Except Gomoku:
303 return "99" + (count - 18);
304 };
305 let position = "";
306 for (let i = 0; i < this.size.y; i++) {
307 let emptyCount = 0;
308 for (let j = 0; j < this.size.x; j++) {
309 if (this.board[i][j] == "")
310 emptyCount++;
311 else {
312 if (emptyCount > 0) {
313 // Add empty squares in-between
314 position += format(emptyCount);
315 emptyCount = 0;
316 }
317 position += this.board2fen(this.board[i][j]);
318 }
319 }
320 if (emptyCount > 0)
321 // "Flush remainder"
322 position += format(emptyCount);
323 if (i < this.size.y - 1)
324 position += "/"; //separate rows
325 }
326 return position;
327 }
328
329 getTurnFen() {
330 return this.turn;
331 }
332
333 // Flags part of the FEN string
334 getFlagsFen() {
335 return ["w", "b"].map(c => {
336 return this.castleFlags[c].map(x => x.toString(36)).join("");
337 }).join("");
338 }
339
340 // Enpassant part of the FEN string
341 getEnpassantFen() {
342 if (!this.epSquare)
343 return "-"; //no en-passant
344 return C.CoordsToSquare(this.epSquare);
345 }
346
347 getReserveFen() {
348 return (
349 ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("")
350 );
351 }
352
353 getIspawnFen() {
354 const squares = Object.keys(this.ispawn);
355 if (squares.length == 0)
356 return "-";
357 return squares.join(",");
358 }
359
360 // Set flags from fen (castle: white a,h then black a,h)
361 setFlags(fenflags) {
362 this.castleFlags = {
363 w: [0, 1].map(i => parseInt(fenflags.charAt(i), 36)),
364 b: [2, 3].map(i => parseInt(fenflags.charAt(i), 36))
365 };
366 }
367
368 //////////////////
369 // INITIALIZATION
370
371 constructor(o) {
372 this.options = o.options;
373 this.playerColor = o.color;
374 this.afterPlay = o.afterPlay; //trigger some actions after playing a move
375
376 // Fen string fully describes the game state
377 if (!o.fen)
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);
384
385 // Graphical (can use variables defined above)
386 this.containerId = o.element;
387 this.graphicalInit();
388 }
389
390 // Turn position fen into double array ["wb","wp","bk",...]
391 getBoard(position) {
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++) {
395 let j = 0;
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:
400 if (!isNaN(num))
401 j += num;
402 // Else: something at position i,j
403 else
404 board[i][j++] = this.fen2board(character);
405 }
406 }
407 return board;
408 }
409
410 // Some additional variables from FEN (variant dependant)
411 setOtherVariables(fenParsed) {
412 // Set flags and enpassant:
413 if (this.hasFlags)
414 this.setFlags(fenParsed.flags);
415 if (this.hasEnpassant)
416 this.epSquare = this.getEpSquare(fenParsed.enpassant);
417 if (this.hasReserve)
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;
425 }
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();
430 }
431 }
432
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)
440 {
441 this.enlightened[x][y] = true;
442 this.getPotentialMovesFrom([x, y]).forEach(m => {
443 this.enlightened[m.end.x][m.end.y] = true;
444 });
445 }
446 }
447 }
448 if (this.epSquare)
449 this.enlightEnpassant();
450 }
451
452 // Include square of the en-passant capturing square:
453 enlightEnpassant() {
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]);
459 if (
460 this.onBoard(x, y) &&
461 this.getColor(x, y) == this.playerColor &&
462 this.getPieceType(x, y) == "p"
463 ) {
464 this.enlightened[x][this.epSquare.y] = true;
465 break;
466 }
467 }
468 }
469
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)) {
477 if (i < L)
478 this.reserve['w'][pieceName[i]] = counts[i];
479 else
480 this.reserve['b'][pieceName[i-L]] = counts[i];
481 }
482 }
483
484 initIspawn(ispawnStr) {
485 if (ispawnStr != "-")
486 this.ispawn = ArrayFun.toObject(ispawnStr.split(","), true);
487 else
488 this.ispawn = {};
489 }
490
491 getNbReservePieces(color) {
492 return (
493 Object.values(this.reserve[color]).reduce(
494 (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0)
495 );
496 }
497
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);
504 }
505
506 //////////////
507 // VISUAL PART
508
509 getPieceWidth(rwidth) {
510 return (rwidth / this.size.y);
511 }
512
513 getReserveSquareSize(rwidth, nbR) {
514 const sqSize = this.getPieceWidth(rwidth);
515 return Math.min(sqSize, rwidth / nbR);
516 }
517
518 getReserveNumId(color, piece) {
519 return `${this.containerId}|rnum-${color}${piece}`;
520 }
521
522 graphicalInit() {
523 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
524 window.onresize = () => this.re_drawBoardElements();
525 this.re_drawBoardElements();
526 this.initMouseEvents();
527 const chessboard =
528 document.getElementById(this.containerId).querySelector(".chessboard");
529 new ResizeObserver(this.rescale).observe(chessboard);
530 }
531
532 re_drawBoardElements() {
533 const board = this.getSvgChessboard();
534 const oppCol = C.GetOppCol(this.playerColor);
535 let chessboard =
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;
546 }
547 else {
548 // Limiting dimension is height:
549 cbHeight = Math.min(window.innerHeight, 767);
550 cbWidth = cbHeight * this.size.ratio;
551 }
552 if (this.reserve) {
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;
559 }
560 }
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.
570 this.setupPieces({
571 width: cbWidth,
572 height: cbHeight,
573 x: spaceLeft,
574 y: spaceTop
575 });
576 }
577
578 // Get SVG board (background, no pieces)
579 getSvgChessboard() {
580 const flipped = (this.playerColor == 'b');
581 let board = `
582 <svg
583 viewBox="0 0 80 80"
584 class="chessboard_SVG">
585 <g>`;
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.
594 board += `<rect
595 class="${classes}"
596 id="${this.coordsToId({x: ii, y: jj})}"
597 width="10"
598 height="10"
599 x="${10*j}"
600 y="${10*i}" />`;
601 }
602 }
603 board += "</g></svg>";
604 return board;
605 }
606
607 // Generally light square bottom-right
608 getSquareColorClass(x, y) {
609 return ((x+y) % 2 == 0 ? "light-square": "dark-square");
610 }
611
612 setupPieces(r) {
613 if (this.g_pieces) {
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;
620 }
621 }
622 }
623 }
624 else
625 this.g_pieces = ArrayFun.init(this.size.x, this.size.y, null);
626 let chessboard =
627 document.getElementById(this.containerId).querySelector(".chessboard");
628 if (!r)
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]);
646 }
647 }
648 }
649 if (this.reserve)
650 this.re_drawReserve(['w', 'b'], r);
651 }
652
653 // NOTE: assume !!this.reserve
654 re_drawReserve(colors, r) {
655 if (this.r_pieces) {
656 // Remove (old) reserve pieces
657 for (let c of colors) {
658 if (!this.reserve[c])
659 continue;
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();
666 }
667 });
668 let reservesDiv = document.getElementById("reserves_" + c);
669 if (reservesDiv)
670 reservesDiv.remove();
671 }
672 }
673 else
674 this.r_pieces = { 'w': {}, 'b': {} };
675 let chessboard =
676 document.getElementById(this.containerId).querySelector(".chessboard");
677 if (!r)
678 r = chessboard.getBoundingClientRect();
679 for (let c of colors) {
680 if (!this.reserve[c])
681 continue;
682 const nbR = this.getNbReservePieces(c);
683 if (nbR == 0)
684 continue;
685 const sqResSize = this.getReserveSquareSize(r.width, nbR);
686 let ridx = 0;
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)
700 continue;
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);
723 ridx++;
724 }
725 }
726 }
727
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]);
736 else {
737 const numId = this.getReserveNumId(color, piece);
738 document.getElementById(numId).textContent = count;
739 }
740 }
741
742 // Apply diff this.enlightened --> oldEnlightened on board
743 graphUpdateEnlightened() {
744 let chessboard =
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: x, y: y}));
752 elt.classList.add("in-shadow");
753 if (this.g_pieces[x][y])
754 this.g_pieces[x][y].classList.add("hidden");
755 }
756 else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) {
757 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
758 elt.classList.remove("in-shadow");
759 if (this.g_pieces[x][y])
760 this.g_pieces[x][y].classList.remove("hidden");
761 }
762 }
763 }
764 }
765
766 // After resize event: no need to destroy/recreate pieces
767 rescale() {
768 const container = document.getElementById(this.containerId);
769 if (!container)
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";
779 }
780 else if (newRatio < this.size.ratio) {
781 newHeight = r.width / this.size.ratio;
782 chessboard.style.height = newHeight + "px";
783 }
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)`;
798 }
799 }
800 }
801 if (this.reserve)
802 this.rescaleReserve(newR);
803 }
804
805 rescaleReserve(r) {
806 for (let c of ['w','b']) {
807 if (!this.reserve[c])
808 continue;
809 const nbR = this.getNbReservePieces(c);
810 if (nbR == 0)
811 continue;
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)
825 return;
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";
829 });
830 }
831 }
832
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) {
837 if (i < 0 || j < 0)
838 return [0, 0]; //piece vanishes
839 let x, y;
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);
846 }
847 else {
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;
852 }
853 return [x, y];
854 }
855
856 initMouseEvents() {
857 let chessboard =
858 document.getElementById(this.containerId).querySelector(".chessboard");
859
860 const getOffset = e => {
861 if (e.clientX)
862 // Mouse
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];
871 if (touchLocation)
872 return {x: touchLocation.clientX, y: touchLocation.clientY};
873 return {x: 0, y: 0}; //shouldn't reach here =)
874 }
875
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";
881 }
882
883 let start = null,
884 r = null,
885 startPiece, curPiece = null,
886 pieceWidth;
887 const mousedown = (e) => {
888 // Disable zoom on smartphones:
889 if (e.touches && e.touches.length > 1)
890 e.preventDefault();
891 r = chessboard.getBoundingClientRect();
892 pieceWidth = this.getPieceWidth(r.width);
893 const cd = this.idToCoords(e.target.id);
894 if (cd) {
895 const move = this.doClick(cd);
896 if (move)
897 this.playPlusVisual(move);
898 else {
899 const [x, y] = Object.values(cd);
900 if (typeof x != "number")
901 startPiece = this.r_pieces[x][y];
902 else
903 startPiece = this.g_pieces[x][y];
904 if (startPiece && this.canIplay(x, y)) {
905 e.preventDefault();
906 start = cd;
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";
916 }
917 }
918 }
919 };
920
921 const mousemove = (e) => {
922 if (start) {
923 e.preventDefault();
924 centerOnCursor(curPiece, e);
925 }
926 else if (e.changedTouches && e.changedTouches.length >= 1)
927 // Attempt to prevent horizontal swipe...
928 e.preventDefault();
929 };
930
931 const mouseup = (e) => {
932 const newR = chessboard.getBoundingClientRect();
933 if (newR.width != r.width || newR.height != r.height) {
934 this.rescale();
935 return;
936 }
937 if (!start)
938 return;
939 const [x, y] = [start.x, start.y];
940 start = null;
941 e.preventDefault();
942 chessboard.style.cursor = "pointer";
943 startPiece.style.opacity = "1";
944 const offset = getOffset(e);
945 const landingElt = document.elementFromPoint(offset.x, offset.y);
946 const cd =
947 (landingElt ? this.idToCoords(landingElt.id) : undefined);
948 if (cd) {
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);
957 }
958 curPiece.remove();
959 };
960
961 if ('onmousedown' in window) {
962 document.addEventListener("mousedown", mousedown);
963 document.addEventListener("mousemove", mousemove);
964 document.addEventListener("mouseup", mouseup);
965 }
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});
971 }
972 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
973 }
974
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);
994 }
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);
1012 }
1013 }
1014
1015 //////////////
1016 // BASIC UTILS
1017
1018 get size() {
1019 return {
1020 x: 8,
1021 y: 8,
1022 ratio: 1 //for rectangular board = y / x
1023 };
1024 }
1025
1026 // Color of thing on square (i,j). 'undefined' if square is empty
1027 getColor(i, j) {
1028 if (typeof i == "string")
1029 return i; //reserves
1030 return this.board[i][j].charAt(0);
1031 }
1032
1033 static GetColorClass(c) {
1034 return (c == 'w' ? "white" : "black");
1035 }
1036
1037 // Assume square i,j isn't empty
1038 getPiece(i, j) {
1039 if (typeof j == "string")
1040 return j; //reserves
1041 return this.board[i][j].charAt(1);
1042 }
1043
1044 // Piece type on square (i,j)
1045 getPieceType(i, j) {
1046 const p = this.getPiece(i, j);
1047 return C.CannibalKings[p] || p; //a cannibal king move as...
1048 }
1049
1050 // Get opponent color
1051 static GetOppCol(color) {
1052 return (color == "w" ? "b" : "w");
1053 }
1054
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));
1058 }
1059
1060 // Is (x,y) on the chessboard?
1061 onBoard(x, y) {
1062 return (x >= 0 && x < this.size.x &&
1063 y >= 0 && y < this.size.y);
1064 }
1065
1066 // Am I allowed to move thing at square x,y ?
1067 canIplay(x, y) {
1068 return (this.playerColor == this.turn && this.getColor(x, y) == this.turn);
1069 }
1070
1071 ////////////////////////
1072 // PIECES SPECIFICATIONS
1073
1074 pieces(color, x, y) {
1075 const pawnShift = (color == "w" ? -1 : 1);
1076 const initRank = ((color == 'w' && x == 6) || (color == 'b' && x == 1));
1077 return {
1078 'p': {
1079 "class": "pawn",
1080 moves: [
1081 {
1082 steps: [[pawnShift, 0]],
1083 range: (initRank ? 2 : 1)
1084 }
1085 ],
1086 attack: [
1087 {
1088 steps: [[pawnShift, 1], [pawnShift, -1]],
1089 range: 1
1090 }
1091 ]
1092 },
1093 // rook
1094 'r': {
1095 "class": "rook",
1096 moves: [
1097 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1098 ]
1099 },
1100 // knight
1101 'n': {
1102 "class": "knight",
1103 moves: [
1104 {
1105 steps: [
1106 [1, 2], [1, -2], [-1, 2], [-1, -2],
1107 [2, 1], [-2, 1], [2, -1], [-2, -1]
1108 ],
1109 range: 1
1110 }
1111 ]
1112 },
1113 // bishop
1114 'b': {
1115 "class": "bishop",
1116 moves: [
1117 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1118 ]
1119 },
1120 // queen
1121 'q': {
1122 "class": "queen",
1123 moves: [
1124 {
1125 steps: [
1126 [0, 1], [0, -1], [1, 0], [-1, 0],
1127 [1, 1], [1, -1], [-1, 1], [-1, -1]
1128 ]
1129 }
1130 ]
1131 },
1132 // king
1133 'k': {
1134 "class": "king",
1135 moves: [
1136 {
1137 steps: [
1138 [0, 1], [0, -1], [1, 0], [-1, 0],
1139 [1, 1], [1, -1], [-1, 1], [-1, -1]
1140 ],
1141 range: 1
1142 }
1143 ]
1144 },
1145 // Cannibal kings:
1146 '!': {"class": "king-pawn", moveas: "p"},
1147 '#': {"class": "king-rook", moveas: "r"},
1148 '$': {"class": "king-knight", moveas: "n"},
1149 '%': {"class": "king-bishop", moveas: "b"},
1150 '*': {"class": "king-queen", moveas: "q"}
1151 };
1152 }
1153
1154 ////////////////////
1155 // MOVES GENERATION
1156
1157 // For Cylinder: get Y coordinate
1158 computeY(y) {
1159 if (!this.options["cylinder"])
1160 return y;
1161 let res = y % this.size.y;
1162 if (res < 0)
1163 res += this.size.y;
1164 return res;
1165 }
1166
1167 // Stop at the first capture found
1168 atLeastOneCapture(color) {
1169 color = color || this.turn;
1170 const oppCol = C.GetOppCol(color);
1171 for (let i = 0; i < this.size.x; i++) {
1172 for (let j = 0; j < this.size.y; j++) {
1173 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
1174 const allSpecs = this.pieces(color, i, j)
1175 let specs = allSpecs[this.getPieceType(i, j)];
1176 const attacks = specs.attack || specs.moves;
1177 for (let a of attacks) {
1178 outerLoop: for (let step of a.steps) {
1179 let [ii, jj] = [i + step[0], this.computeY(j + step[1])];
1180 let stepCounter = 1;
1181 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1182 if (a.range <= stepCounter++)
1183 continue outerLoop;
1184 ii += step[0];
1185 jj = this.computeY(jj + step[1]);
1186 }
1187 if (
1188 this.onBoard(ii, jj) &&
1189 this.getColor(ii, jj) == oppCol &&
1190 this.filterValid(
1191 [this.getBasicMove([i, j], [ii, jj])]
1192 ).length >= 1
1193 ) {
1194 return true;
1195 }
1196 }
1197 }
1198 }
1199 }
1200 }
1201 return false;
1202 }
1203
1204 getDropMovesFrom([c, p]) {
1205 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1206 // (but not necessarily otherwise)
1207 if (this.reserve[c][p] == 0)
1208 return [];
1209 let moves = [];
1210 for (let i=0; i<this.size.x; i++) {
1211 for (let j=0; j<this.size.y; j++) {
1212 if (
1213 this.board[i][j] == "" &&
1214 (!this.enlightened || this.enlightened[i][j]) &&
1215 (
1216 p != "p" ||
1217 (c == 'w' && i < this.size.x - 1) ||
1218 (c == 'b' && i > 0)
1219 )
1220 ) {
1221 moves.push(
1222 new Move({
1223 start: {x: c, y: p},
1224 end: {x: i, y: j},
1225 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1226 vanish: []
1227 })
1228 );
1229 }
1230 }
1231 }
1232 return moves;
1233 }
1234
1235 // All possible moves from selected square
1236 getPotentialMovesFrom(sq, color) {
1237 if (this.subTurnTeleport == 2)
1238 return [];
1239 if (typeof sq[0] == "string")
1240 return this.getDropMovesFrom(sq);
1241 if (this.isImmobilized(sq))
1242 return [];
1243 const piece = this.getPieceType(sq[0], sq[1]);
1244 let moves = this.getPotentialMovesOf(piece, sq);
1245 if (
1246 piece == "p" &&
1247 this.hasEnpassant &&
1248 this.epSquare
1249 ) {
1250 Array.prototype.push.apply(moves, this.getEnpassantCaptures(sq));
1251 }
1252 if (
1253 piece == "k" &&
1254 this.hasCastle &&
1255 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1256 ) {
1257 Array.prototype.push.apply(moves, this.getCastleMoves(sq));
1258 }
1259 return this.postProcessPotentialMoves(moves);
1260 }
1261
1262 postProcessPotentialMoves(moves) {
1263 if (moves.length == 0)
1264 return [];
1265 const color = this.getColor(moves[0].start.x, moves[0].start.y);
1266 const oppCol = C.GetOppCol(color);
1267
1268 if (this.options["capture"] && this.atLeastOneCapture())
1269 moves = this.capturePostProcess(moves, oppCol);
1270
1271 if (this.options["atomic"])
1272 this.atomicPostProcess(moves, oppCol);
1273
1274 if (
1275 moves.length > 0 &&
1276 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1277 ) {
1278 this.pawnPostProcess(moves, color, oppCol);
1279 }
1280
1281 if (
1282 this.options["cannibal"] &&
1283 this.options["rifle"]
1284 ) {
1285 // In this case a rifle-capture from last rank may promote a pawn
1286 this.riflePromotePostProcess(moves);
1287 }
1288
1289 return moves;
1290 }
1291
1292 capturePostProcess(moves, oppCol) {
1293 // Filter out non-capturing moves (not using m.vanish because of
1294 // self captures of Recycle and Teleport).
1295 return moves.filter(m => {
1296 return (
1297 this.board[m.end.x][m.end.y] != "" &&
1298 this.getColor(m.end.x, m.end.y) == oppCol
1299 );
1300 });
1301 }
1302
1303 atomicPostProcess(moves, oppCol) {
1304 moves.forEach(m => {
1305 if (
1306 this.board[m.end.x][m.end.y] != "" &&
1307 this.getColor(m.end.x, m.end.y) == oppCol
1308 ) {
1309 // Explosion!
1310 let steps = [
1311 [-1, -1],
1312 [-1, 0],
1313 [-1, 1],
1314 [0, -1],
1315 [0, 1],
1316 [1, -1],
1317 [1, 0],
1318 [1, 1]
1319 ];
1320 for (let step of steps) {
1321 let x = m.end.x + step[0];
1322 let y = this.computeY(m.end.y + step[1]);
1323 if (
1324 this.onBoard(x, y) &&
1325 this.board[x][y] != "" &&
1326 this.getPieceType(x, y) != "p"
1327 ) {
1328 m.vanish.push(
1329 new PiPo({
1330 p: this.getPiece(x, y),
1331 c: this.getColor(x, y),
1332 x: x,
1333 y: y
1334 })
1335 );
1336 }
1337 }
1338 if (!this.options["rifle"])
1339 m.appear.pop(); //nothing appears
1340 }
1341 });
1342 }
1343
1344 pawnPostProcess(moves, color, oppCol) {
1345 let moreMoves = [];
1346 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1347 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1348 moves.forEach(m => {
1349 const [x1, y1] = [m.start.x, m.start.y];
1350 const [x2, y2] = [m.end.x, m.end.y];
1351 const promotionOk = (
1352 x2 == lastRank &&
1353 (!this.options["rifle"] || this.board[x2][y2] == "")
1354 );
1355 if (!promotionOk)
1356 return; //nothing to do
1357 if (this.options["pawnfall"]) {
1358 m.appear.shift();
1359 return;
1360 }
1361 let finalPieces = ["p"];
1362 if (
1363 this.options["cannibal"] &&
1364 this.board[x2][y2] != "" &&
1365 this.getColor(x2, y2) == oppCol
1366 ) {
1367 finalPieces = [this.getPieceType(x2, y2)];
1368 }
1369 else
1370 finalPieces = this.pawnPromotions;
1371 m.appear[0].p = finalPieces[0];
1372 if (initPiece == "!") //cannibal king-pawn
1373 m.appear[0].p = C.CannibalKingCode[finalPieces[0]];
1374 for (let i=1; i<finalPieces.length; i++) {
1375 const piece = finalPieces[i];
1376 const tr = {
1377 c: color,
1378 p: (initPiece != "!" ? piece : C.CannibalKingCode[piece])
1379 };
1380 let newMove = this.getBasicMove([x1, y1], [x2, y2], tr);
1381 moreMoves.push(newMove);
1382 }
1383 });
1384 Array.prototype.push.apply(moves, moreMoves);
1385 }
1386
1387 riflePromotePostProcess(moves) {
1388 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1389 let newMoves = [];
1390 moves.forEach(m => {
1391 if (
1392 m.start.x == lastRank &&
1393 m.appear.length >= 1 &&
1394 m.appear[0].p == "p" &&
1395 m.appear[0].x == m.start.x &&
1396 m.appear[0].y == m.start.y
1397 ) {
1398 m.appear[0].p = this.pawnPromotions[0];
1399 for (let i=1; i<this.pawnPromotions.length; i++) {
1400 let newMv = JSON.parse(JSON.stringify(m));
1401 newMv.appear[0].p = this.pawnSpecs.promotions[i];
1402 newMoves.push(newMv);
1403 }
1404 }
1405 });
1406 Array.prototype.push.apply(moves, newMoves);
1407 }
1408
1409 // NOTE: using special symbols to not interfere with variants' pieces codes
1410 static get CannibalKings() {
1411 return {
1412 "!": "p",
1413 "#": "r",
1414 "$": "n",
1415 "%": "b",
1416 "*": "q",
1417 "k": "k"
1418 };
1419 }
1420
1421 static get CannibalKingCode() {
1422 return {
1423 "p": "!",
1424 "r": "#",
1425 "n": "$",
1426 "b": "%",
1427 "q": "*",
1428 "k": "k"
1429 };
1430 }
1431
1432 isKing(symbol) {
1433 return !!C.CannibalKings[symbol];
1434 }
1435
1436 // For Madrasi:
1437 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1438 isImmobilized([x, y]) {
1439 if (!this.options["madrasi"])
1440 return false;
1441 const color = this.getColor(x, y);
1442 const oppCol = C.GetOppCol(color);
1443 const piece = this.getPieceType(x, y); //ok not cannibal king
1444 const stepSpec = this.pieces(color, x, y)[piece];
1445 const attacks = stepSpec.attack || stepSpec.moves;
1446 for (let a of attacks) {
1447 outerLoop: for (let step of a.steps) {
1448 let [i, j] = [x + step[0], y + step[1]];
1449 let stepCounter = 1;
1450 while (this.onBoard(i, j) && this.board[i][j] == "") {
1451 if (a.range <= stepCounter++)
1452 continue outerLoop;
1453 i += step[0];
1454 j = this.computeY(j + step[1]);
1455 }
1456 if (
1457 this.onBoard(i, j) &&
1458 this.getColor(i, j) == oppCol &&
1459 this.getPieceType(i, j) == piece
1460 ) {
1461 return true;
1462 }
1463 }
1464 }
1465 return false;
1466 }
1467
1468 // Generic method to find possible moves of "sliding or jumping" pieces
1469 getPotentialMovesOf(piece, [x, y]) {
1470 const color = this.getColor(x, y);
1471 const stepSpec = this.pieces(color, x, y)[piece];
1472 let moves = [];
1473 let explored = {}; //for Cylinder mode
1474
1475 const findAddMoves = (type, stepArray) => {
1476 for (let s of stepArray) {
1477 // TODO: if jump in y (computeY, Cylinder), move.segments
1478 outerLoop: for (let step of s.steps) {
1479 let [i, j] = [x + step[0], this.computeY(y + step[1])];
1480 let stepCounter = 1;
1481 while (this.onBoard(i, j) && this.board[i][j] == "") {
1482 if (type != "attack" && !explored[i + "." + j]) {
1483 explored[i + "." + j] = true;
1484 moves.push(this.getBasicMove([x, y], [i, j]));
1485 }
1486 if (s.range <= stepCounter++)
1487 continue outerLoop;
1488 i += step[0];
1489 j = this.computeY(j + step[1]);
1490 }
1491 if (!this.onBoard(i, j))
1492 continue;
1493 const pieceIJ = this.getPieceType(i, j);
1494 if (
1495 type != "moveonly" &&
1496 !explored[i + "." + j] &&
1497 (
1498 !this.options["zen"] ||
1499 pieceIJ == "k"
1500 ) &&
1501 (
1502 this.canTake([x, y], [i, j]) ||
1503 (
1504 (this.options["recycle"] || this.options["teleport"]) &&
1505 pieceIJ != "k"
1506 )
1507 )
1508 ) {
1509 explored[i + "." + j] = true;
1510 moves.push(this.getBasicMove([x, y], [i, j]));
1511 }
1512 }
1513 }
1514 };
1515
1516 const specialAttack = !!stepSpec.attack;
1517 if (specialAttack)
1518 findAddMoves("attack", stepSpec.attack);
1519 findAddMoves(specialAttack ? "moveonly" : "all", stepSpec.moves);
1520 if (this.options["zen"])
1521 Array.prototype.push.apply(moves, this.findCapturesOn([x, y], true));
1522 return moves;
1523 }
1524
1525 findCapturesOn([x, y], zen) {
1526 let moves = [];
1527 // Find reverse captures (opponent takes)
1528 const color = this.getColor(x, y);
1529 const oppCol = C.GetOppCol(color);
1530 for (let i=0; i<this.size.x; i++) {
1531 for (let j=0; j<this.size.y; j++) {
1532 if (
1533 this.board[i][j] != "" &&
1534 this.canTake([i, j], [x, y]) &&
1535 !this.isImmobilized([i, j])
1536 ) {
1537 if (zen && this.isKing(this.getPiece(i, j)))
1538 continue; //king not captured in this way
1539 const stepSpec = this.pieces(oppCol, i, j)[this.getPieceType(i, j)];
1540 const attacks = stepSpec.attack || stepSpec.moves;
1541 for (let a of attacks) {
1542 for (let s of a.steps) {
1543 // Quick check: if step isn't compatible, don't even try
1544 if (!C.CompatibleStep([i, j], [x, y], s, a.range))
1545 continue;
1546 // Finally verify that nothing stand in-between
1547 let [ii, jj] = [i + s[0], this.computeY(j + s[1])];
1548 let stepCounter = 1;
1549 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1550 ii += s[0];
1551 jj = this.computeY(jj + s[1]);
1552 }
1553 if (ii == x && jj == y) {
1554 moves.push(this.getBasicMove([x, y], [i, j]));
1555 if (!zen)
1556 return moves; //test for underCheck
1557 }
1558 }
1559 }
1560 }
1561 }
1562 }
1563 return moves;
1564 }
1565
1566 static CompatibleStep([x1, y1], [x2, y2], step, range) {
1567 const rx = (x2 - x1) / step[0],
1568 ry = (y2 - y1) / step[1];
1569 if (
1570 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
1571 (!Number.isFinite(ry) && !Number.isNaN(ry))
1572 ) {
1573 return false;
1574 }
1575 let distance = (Number.isNaN(rx) ? ry : rx);
1576 // TODO: 1e-7 here is totally arbitrary
1577 if (Math.abs(distance - Math.round(distance)) > 1e-7)
1578 return false;
1579 distance = Math.round(distance); //in case of (numerical...)
1580 if (range < distance)
1581 return false;
1582 return true;
1583 }
1584
1585 // Build a regular move from its initial and destination squares.
1586 // tr: transformation
1587 getBasicMove([sx, sy], [ex, ey], tr) {
1588 const initColor = this.getColor(sx, sy);
1589 const initPiece = this.getPiece(sx, sy);
1590 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1591 let mv = new Move({
1592 appear: [],
1593 vanish: [],
1594 start: {x: sx, y: sy},
1595 end: {x: ex, y: ey}
1596 });
1597 if (
1598 !this.options["rifle"] ||
1599 this.board[ex][ey] == "" ||
1600 destColor == initColor //Recycle, Teleport
1601 ) {
1602 mv.appear = [
1603 new PiPo({
1604 x: ex,
1605 y: ey,
1606 c: !!tr ? tr.c : initColor,
1607 p: !!tr ? tr.p : initPiece
1608 })
1609 ];
1610 mv.vanish = [
1611 new PiPo({
1612 x: sx,
1613 y: sy,
1614 c: initColor,
1615 p: initPiece
1616 })
1617 ];
1618 }
1619 if (this.board[ex][ey] != "") {
1620 mv.vanish.push(
1621 new PiPo({
1622 x: ex,
1623 y: ey,
1624 c: this.getColor(ex, ey),
1625 p: this.getPiece(ex, ey)
1626 })
1627 );
1628 if (this.options["cannibal"] && destColor != initColor) {
1629 const lastIdx = mv.vanish.length - 1;
1630 let trPiece = mv.vanish[lastIdx].p;
1631 if (this.isKing(this.getPiece(sx, sy)))
1632 trPiece = C.CannibalKingCode[trPiece];
1633 if (mv.appear.length >= 1)
1634 mv.appear[0].p = trPiece;
1635 else if (this.options["rifle"]) {
1636 mv.appear.unshift(
1637 new PiPo({
1638 x: sx,
1639 y: sy,
1640 c: initColor,
1641 p: trPiece
1642 })
1643 );
1644 mv.vanish.unshift(
1645 new PiPo({
1646 x: sx,
1647 y: sy,
1648 c: initColor,
1649 p: initPiece
1650 })
1651 );
1652 }
1653 }
1654 }
1655 return mv;
1656 }
1657
1658 // En-passant square, if any
1659 getEpSquare(moveOrSquare) {
1660 if (typeof moveOrSquare === "string") {
1661 const square = moveOrSquare;
1662 if (square == "-")
1663 return undefined;
1664 return C.SquareToCoords(square);
1665 }
1666 // Argument is a move:
1667 const move = moveOrSquare;
1668 const s = move.start,
1669 e = move.end;
1670 if (
1671 s.y == e.y &&
1672 Math.abs(s.x - e.x) == 2 &&
1673 // Next conditions for variants like Atomic or Rifle, Recycle...
1674 (move.appear.length > 0 && move.appear[0].p == "p") &&
1675 (move.vanish.length > 0 && move.vanish[0].p == "p")
1676 ) {
1677 return {
1678 x: (s.x + e.x) / 2,
1679 y: s.y
1680 };
1681 }
1682 return undefined; //default
1683 }
1684
1685 // Special case of en-passant captures: treated separately
1686 getEnpassantCaptures([x, y]) {
1687 const color = this.getColor(x, y);
1688 const shiftX = (color == 'w' ? -1 : 1);
1689 const oppCol = C.GetOppCol(color);
1690 let enpassantMove = null;
1691 if (
1692 !!this.epSquare &&
1693 this.epSquare.x == x + shiftX &&
1694 Math.abs(this.computeY(this.epSquare.y - y)) == 1 &&
1695 this.getColor(x, this.epSquare.y) == oppCol //Doublemove guard...
1696 ) {
1697 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
1698 this.board[epx][epy] = oppCol + "p";
1699 enpassantMove = this.getBasicMove([x, y], [epx, epy]);
1700 this.board[epx][epy] = "";
1701 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
1702 enpassantMove.vanish[lastIdx].x = x;
1703 }
1704 return !!enpassantMove ? [enpassantMove] : [];
1705 }
1706
1707 // "castleInCheck" arg to let some variants castle under check
1708 getCastleMoves([x, y], finalSquares, castleInCheck, castleWith) {
1709 const c = this.getColor(x, y);
1710
1711 // Castling ?
1712 const oppCol = C.GetOppCol(c);
1713 let moves = [];
1714 // King, then rook:
1715 finalSquares =
1716 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
1717 const castlingKing = this.getPiece(x, y);
1718 castlingCheck: for (
1719 let castleSide = 0;
1720 castleSide < 2;
1721 castleSide++ //large, then small
1722 ) {
1723 if (this.castleFlags[c][castleSide] >= this.size.y)
1724 continue;
1725 // If this code is reached, rook and king are on initial position
1726
1727 // NOTE: in some variants this is not a rook
1728 const rookPos = this.castleFlags[c][castleSide];
1729 const castlingPiece = this.getPiece(x, rookPos);
1730 if (
1731 this.board[x][rookPos] == "" ||
1732 this.getColor(x, rookPos) != c ||
1733 (!!castleWith && !castleWith.includes(castlingPiece))
1734 ) {
1735 // Rook is not here, or changed color (see Benedict)
1736 continue;
1737 }
1738 // Nothing on the path of the king ? (and no checks)
1739 const finDist = finalSquares[castleSide][0] - y;
1740 let step = finDist / Math.max(1, Math.abs(finDist));
1741 let i = y;
1742 do {
1743 if (
1744 (!castleInCheck && this.underCheck([x, i], oppCol)) ||
1745 (
1746 this.board[x][i] != "" &&
1747 // NOTE: next check is enough, because of chessboard constraints
1748 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
1749 )
1750 ) {
1751 continue castlingCheck;
1752 }
1753 i += step;
1754 } while (i != finalSquares[castleSide][0]);
1755 // Nothing on the path to the rook?
1756 step = (castleSide == 0 ? -1 : 1);
1757 for (i = y + step; i != rookPos; i += step) {
1758 if (this.board[x][i] != "")
1759 continue castlingCheck;
1760 }
1761
1762 // Nothing on final squares, except maybe king and castling rook?
1763 for (i = 0; i < 2; i++) {
1764 if (
1765 finalSquares[castleSide][i] != rookPos &&
1766 this.board[x][finalSquares[castleSide][i]] != "" &&
1767 (
1768 finalSquares[castleSide][i] != y ||
1769 this.getColor(x, finalSquares[castleSide][i]) != c
1770 )
1771 ) {
1772 continue castlingCheck;
1773 }
1774 }
1775
1776 // If this code is reached, castle is valid
1777 moves.push(
1778 new Move({
1779 appear: [
1780 new PiPo({
1781 x: x,
1782 y: finalSquares[castleSide][0],
1783 p: castlingKing,
1784 c: c
1785 }),
1786 new PiPo({
1787 x: x,
1788 y: finalSquares[castleSide][1],
1789 p: castlingPiece,
1790 c: c
1791 })
1792 ],
1793 vanish: [
1794 // King might be initially disguised (Titan...)
1795 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
1796 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
1797 ],
1798 end:
1799 Math.abs(y - rookPos) <= 2
1800 ? {x: x, y: rookPos}
1801 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
1802 })
1803 );
1804 }
1805
1806 return moves;
1807 }
1808
1809 ////////////////////
1810 // MOVES VALIDATION
1811
1812 // Is (king at) given position under check by "color" ?
1813 underCheck([x, y], color) {
1814 if (this.options["taking"] || this.options["dark"])
1815 return false;
1816 return (this.findCapturesOn([x, y]).length >= 1);
1817 }
1818
1819 // Stop at first king found (TODO: multi-kings)
1820 searchKingPos(color) {
1821 for (let i=0; i < this.size.x; i++) {
1822 for (let j=0; j < this.size.y; j++) {
1823 if (this.getColor(i, j) == color && this.isKing(this.getPiece(i, j)))
1824 return [i, j];
1825 }
1826 }
1827 return [-1, -1]; //king not found
1828 }
1829
1830 filterValid(moves) {
1831 if (moves.length == 0)
1832 return [];
1833 const color = this.turn;
1834 const oppCol = C.GetOppCol(color);
1835 if (this.options["balance"] && [1, 3].includes(this.movesCount)) {
1836 // Forbid moves either giving check or exploding opponent's king:
1837 const oppKingPos = this.searchKingPos(oppCol);
1838 moves = moves.filter(m => {
1839 if (
1840 m.vanish.some(v => v.c == oppCol && v.p == "k") &&
1841 m.appear.every(a => a.c != oppCol || a.p != "k")
1842 )
1843 return false;
1844 this.playOnBoard(m);
1845 const res = !this.underCheck(oppKingPos, color);
1846 this.undoOnBoard(m);
1847 return res;
1848 });
1849 }
1850 if (this.options["taking"] || this.options["dark"])
1851 return moves;
1852 const kingPos = this.searchKingPos(color);
1853 let filtered = {}; //avoid re-checking similar moves (promotions...)
1854 return moves.filter(m => {
1855 const key = m.start.x + m.start.y + '.' + m.end.x + m.end.y;
1856 if (!filtered[key]) {
1857 this.playOnBoard(m);
1858 let square = kingPos,
1859 res = true; //a priori valid
1860 if (m.vanish.some(v => {
1861 return C.CannibalKings[v.p] && v.c == color;
1862 })) {
1863 // Search king in appear array:
1864 const newKingIdx =
1865 m.appear.findIndex(a => {
1866 return C.CannibalKings[a.p] && a.c == color;
1867 });
1868 if (newKingIdx >= 0)
1869 square = [m.appear[newKingIdx].x, m.appear[newKingIdx].y];
1870 else
1871 res = false;
1872 }
1873 res &&= !this.underCheck(square, oppCol);
1874 this.undoOnBoard(m);
1875 filtered[key] = res;
1876 return res;
1877 }
1878 return filtered[key];
1879 });
1880 }
1881
1882 /////////////////
1883 // MOVES PLAYING
1884
1885 // Aggregate flags into one object
1886 aggregateFlags() {
1887 return this.castleFlags;
1888 }
1889
1890 // Reverse operation
1891 disaggregateFlags(flags) {
1892 this.castleFlags = flags;
1893 }
1894
1895 // Apply a move on board
1896 playOnBoard(move) {
1897 for (let psq of move.vanish)
1898 this.board[psq.x][psq.y] = "";
1899 for (let psq of move.appear)
1900 this.board[psq.x][psq.y] = psq.c + psq.p;
1901 }
1902 // Un-apply the played move
1903 undoOnBoard(move) {
1904 for (let psq of move.appear)
1905 this.board[psq.x][psq.y] = "";
1906 for (let psq of move.vanish)
1907 this.board[psq.x][psq.y] = psq.c + psq.p;
1908 }
1909
1910 updateCastleFlags(move) {
1911 // Update castling flags if start or arrive from/at rook/king locations
1912 move.appear.concat(move.vanish).forEach(psq => {
1913 if (
1914 this.board[psq.x][psq.y] != "" &&
1915 this.getPieceType(psq.x, psq.y) == "k"
1916 ) {
1917 this.castleFlags[psq.c] = [this.size.y, this.size.y];
1918 }
1919 // NOTE: not "else if" because king can capture enemy rook...
1920 let c = "";
1921 if (psq.x == 0)
1922 c = "b";
1923 else if (psq.x == this.size.x - 1)
1924 c = "w";
1925 if (c != "") {
1926 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
1927 if (fidx >= 0)
1928 this.castleFlags[c][fidx] = this.size.y;
1929 }
1930 });
1931 }
1932
1933 prePlay(move) {
1934 if (
1935 this.hasCastle &&
1936 // If flags already off, no need to re-check:
1937 Object.keys(this.castleFlags).some(c => {
1938 return this.castleFlags[c].some(val => val < this.size.y)})
1939 ) {
1940 this.updateCastleFlags(move);
1941 }
1942 if (this.options["crazyhouse"]) {
1943 move.vanish.forEach(v => {
1944 const square = C.CoordsToSquare({x: v.x, y: v.y});
1945 if (this.ispawn[square])
1946 delete this.ispawn[square];
1947 });
1948 if (move.appear.length > 0 && move.vanish.length > 0) {
1949 // Assumption: something is moving
1950 const initSquare = C.CoordsToSquare(move.start);
1951 const destSquare = C.CoordsToSquare(move.end);
1952 if (
1953 this.ispawn[initSquare] ||
1954 (move.vanish[0].p == "p" && move.appear[0].p != "p")
1955 ) {
1956 this.ispawn[destSquare] = true;
1957 }
1958 else if (
1959 this.ispawn[destSquare] &&
1960 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
1961 ) {
1962 move.vanish[1].p = "p";
1963 delete this.ispawn[destSquare];
1964 }
1965 }
1966 }
1967 const minSize = Math.min(move.appear.length, move.vanish.length);
1968 if (
1969 this.hasReserve &&
1970 // Warning; atomic pawn removal isn't a capture
1971 (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1)
1972 ) {
1973 const color = this.turn;
1974 for (let i=minSize; i<move.appear.length; i++) {
1975 // Something appears = dropped on board (some exceptions, Chakart...)
1976 if (move.appear[i].c == color) {
1977 const piece = move.appear[i].p;
1978 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
1979 }
1980 }
1981 for (let i=minSize; i<move.vanish.length; i++) {
1982 // Something vanish: add to reserve except if recycle & opponent
1983 if (
1984 this.options["crazyhouse"] ||
1985 (this.options["recycle"] && move.vanish[i].c == color)
1986 ) {
1987 const piece = move.vanish[i].p;
1988 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
1989 }
1990 }
1991 }
1992 }
1993
1994 play(move) {
1995 this.prePlay(move);
1996 if (this.hasEnpassant)
1997 this.epSquare = this.getEpSquare(move);
1998 this.playOnBoard(move);
1999 this.postPlay(move);
2000 }
2001
2002 postPlay(move) {
2003 const color = this.turn;
2004 const oppCol = C.GetOppCol(color);
2005 if (this.options["dark"])
2006 this.updateEnlightened();
2007 if (this.options["teleport"]) {
2008 if (
2009 this.subTurnTeleport == 1 &&
2010 move.vanish.length > move.appear.length &&
2011 move.vanish[move.vanish.length - 1].c == color
2012 ) {
2013 const v = move.vanish[move.vanish.length - 1];
2014 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
2015 this.subTurnTeleport = 2;
2016 return;
2017 }
2018 this.subTurnTeleport = 1;
2019 this.captured = null;
2020 }
2021 if (this.options["balance"]) {
2022 if (![1, 3].includes(this.movesCount))
2023 this.turn = oppCol;
2024 }
2025 else {
2026 if (
2027 (
2028 this.options["doublemove"] &&
2029 this.movesCount >= 1 &&
2030 this.subTurn == 1
2031 ) ||
2032 (this.options["progressive"] && this.subTurn <= this.movesCount)
2033 ) {
2034 const oppKingPos = this.searchKingPos(oppCol);
2035 if (
2036 oppKingPos[0] >= 0 &&
2037 (
2038 this.options["taking"] ||
2039 !this.underCheck(oppKingPos, color)
2040 )
2041 ) {
2042 this.subTurn++;
2043 return;
2044 }
2045 }
2046 this.turn = oppCol;
2047 }
2048 this.movesCount++;
2049 this.subTurn = 1;
2050 }
2051
2052 // "Stop at the first move found"
2053 atLeastOneMove(color) {
2054 color = color || this.turn;
2055 for (let i = 0; i < this.size.x; i++) {
2056 for (let j = 0; j < this.size.y; j++) {
2057 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
2058 // NOTE: in fact searching for all potential moves from i,j.
2059 // I don't believe this is an issue, for now at least.
2060 const moves = this.getPotentialMovesFrom([i, j]);
2061 if (moves.some(m => this.filterValid([m]).length >= 1))
2062 return true;
2063 }
2064 }
2065 }
2066 if (this.hasReserve && this.reserve[color]) {
2067 for (let p of Object.keys(this.reserve[color])) {
2068 const moves = this.getDropMovesFrom([color, p]);
2069 if (moves.some(m => this.filterValid([m]).length >= 1))
2070 return true;
2071 }
2072 }
2073 return false;
2074 }
2075
2076 // What is the score ? (Interesting if game is over)
2077 getCurrentScore(move) {
2078 const color = this.turn;
2079 const oppCol = C.GetOppCol(color);
2080 const kingPos = [this.searchKingPos(color), this.searchKingPos(oppCol)];
2081 if (kingPos[0][0] < 0 && kingPos[1][0] < 0)
2082 return "1/2";
2083 if (kingPos[0][0] < 0)
2084 return (color == "w" ? "0-1" : "1-0");
2085 if (kingPos[1][0] < 0)
2086 return (color == "w" ? "1-0" : "0-1");
2087 if (this.atLeastOneMove())
2088 return "*";
2089 // No valid move: stalemate or checkmate?
2090 if (!this.underCheck(kingPos[0], color))
2091 return "1/2";
2092 // OK, checkmate
2093 return (color == "w" ? "0-1" : "1-0");
2094 }
2095
2096 playVisual(move, r) {
2097 move.vanish.forEach(v => {
2098 // TODO: next "if" shouldn't be required
2099 if (this.g_pieces[v.x][v.y])
2100 this.g_pieces[v.x][v.y].remove();
2101 this.g_pieces[v.x][v.y] = null;
2102 });
2103 let chessboard =
2104 document.getElementById(this.containerId).querySelector(".chessboard");
2105 if (!r)
2106 r = chessboard.getBoundingClientRect();
2107 const pieceWidth = this.getPieceWidth(r.width);
2108 move.appear.forEach(a => {
2109 this.g_pieces[a.x][a.y] = document.createElement("piece");
2110 this.g_pieces[a.x][a.y].classList.add(this.pieces()[a.p]["class"]);
2111 this.g_pieces[a.x][a.y].classList.add(a.c == "w" ? "white" : "black");
2112 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2113 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2114 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
2115 this.g_pieces[a.x][a.y].style.transform = `translate(${ip}px,${jp}px)`;
2116 if (this.enlightened && !this.enlightened[a.x][a.y])
2117 this.g_pieces[a.x][a.y].classList.add("hidden");
2118 chessboard.appendChild(this.g_pieces[a.x][a.y]);
2119 });
2120 if (this.options["dark"])
2121 this.graphUpdateEnlightened();
2122 }
2123
2124 playPlusVisual(move, r) {
2125 this.play(move);
2126 this.playVisual(move, r);
2127 this.afterPlay(move); //user method
2128 }
2129
2130 getMaxDistance(rwidth) {
2131 // Works for all rectangular boards:
2132 return Math.sqrt(rwidth ** 2 + (rwidth / this.size.ratio) ** 2);
2133 }
2134
2135 getDomPiece(x, y) {
2136 return (typeof x == "string" ? this.r_pieces : this.g_pieces)[x][y];
2137 }
2138
2139 animate(move, callback) {
2140 if (this.noAnimate || move.noAnimate) {
2141 callback();
2142 return;
2143 }
2144 let movingPiece = this.getDomPiece(move.start.x, move.start.y);
2145 if (!movingPiece) { //TODO this shouldn't be required
2146 callback();
2147 return;
2148 }
2149 const initTransform = movingPiece.style.transform;
2150 let chessboard =
2151 document.getElementById(this.containerId).querySelector(".chessboard");
2152 const r = chessboard.getBoundingClientRect();
2153 const [ix, iy] = this.getPixelPosition(move.start.x, move.start.y, r);
2154 const maxDist = this.getMaxDistance(r.width);
2155 // NOTE: move.drag could be generalized per-segment (usage?)
2156 if (move.drag) {
2157 // Drag something else: require cloning
2158 movingPiece = movingPiece.cloneNode();
2159 const pieces = this.pieces();
2160 const startCode = this.getPiece(move.start.x, move.start.y);
2161 movingPiece.classList.remove(pieces[startCode]["class"]);
2162 movingPiece.classList.add(pieces[move.drag.p]["class"]);
2163 const apparentColor = this.getColor(move.start.x, move.start.y);
2164 if (apparentColor != move.drag.c) {
2165 movingPiece.classList.remove(C.GetColorClass(apparentColor));
2166 movingPiece.classList.add(C.GetColorClass(move.drag.c));
2167 }
2168 chessboard.appendChild(movingPiece);
2169 }
2170 const animateSegment = (index, cb) => {
2171 const [i1, j1] = move.segments[index][0];
2172 const [i2, j2] = move.segments[index][1];
2173 const dep = this.getPixelPosition(i1, j1, r);
2174 const arr = this.getPixelPosition(i2, j2, r);
2175 const distance =
2176 Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2);
2177 const duration = 0.2 + (distance / maxDist) * 0.3;
2178 movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`;
2179 movingPiece.style.transitionDuration = duration + "s";
2180 setTimeout(cb, duration * 1000);
2181 };
2182 if (!move.segments) {
2183 move.segments = [
2184 [[move.start.x, move.start.y], [move.end.x, move.end.y]]
2185 ];
2186 }
2187 let index = 0;
2188 const animateSegmentCallback = () => {
2189 if (index < move.segments.length)
2190 animateSegment(index++, animateSegmentCallback);
2191 else {
2192 if (move.drag)
2193 movingPiece.remove();
2194 else {
2195 movingPiece.style.transform = initTransform;
2196 movingPiece.style.transitionDuration = "0s";
2197 }
2198 callback();
2199 }
2200 };
2201 animateSegmentCallback();
2202 }
2203
2204 playReceivedMove(moves, callback) {
2205 const launchAnimation = () => {
2206 const r = container.querySelector(".chessboard").getBoundingClientRect();
2207 const animateRec = i => {
2208 this.animate(moves[i], () => {
2209 this.play(moves[i]);
2210 this.playVisual(moves[i], r);
2211 if (i < moves.length - 1)
2212 setTimeout(() => animateRec(i+1), 300);
2213 else
2214 callback();
2215 });
2216 };
2217 animateRec(0);
2218 };
2219 // Delay if user wasn't focused:
2220 const checkDisplayThenAnimate = (delay) => {
2221 if (container.style.display == "none") {
2222 alert("New move! Let's go back to game...");
2223 document.getElementById("gameInfos").style.display = "none";
2224 container.style.display = "block";
2225 setTimeout(launchAnimation, 700);
2226 }
2227 else
2228 setTimeout(launchAnimation, delay || 0);
2229 };
2230 let container = document.getElementById(this.containerId);
2231 if (document.hidden) {
2232 document.onvisibilitychange = () => {
2233 document.onvisibilitychange = undefined;
2234 checkDisplayThenAnimate(700);
2235 };
2236 }
2237 else
2238 checkDisplayThenAnimate();
2239 }
2240
2241 };