353af397b10e9fea94970b6ad17e66169558f9ea
[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([x, y]) {
95 if (typeof x != "number")
96 return null; //click on reserves
97 if (
98 this.options["teleport"] && this.subTurnTeleport == 2 &&
99 this.board[x][y] == ""
100 ) {
101 return new Move({
102 start: {x: this.captured.x, y: this.captured.y},
103 appear: [
104 new PiPo({
105 x: x,
106 y: y,
107 c: this.captured.c, //this.turn,
108 p: this.captured.p
109 })
110 ],
111 vanish: []
112 });
113 }
114 return null;
115 }
116
117 ////////////////////
118 // COORDINATES UTILS
119
120 // 3 --> d (column number to letter)
121 static CoordToColumn(colnum) {
122 return String.fromCharCode(97 + colnum);
123 }
124
125 // d --> 3 (column letter to number)
126 static ColumnToCoord(columnStr) {
127 return columnStr.charCodeAt(0) - 97;
128 }
129
130 // 7 (numeric) --> 1 (str) [from black viewpoint].
131 static CoordToRow(rownum) {
132 return rownum;
133 }
134
135 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
136 static RowToCoord(rownumStr) {
137 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
138 return parseInt(rownumStr, 30);
139 }
140
141 // a2 --> {x:2,y:0} (this is in fact a6)
142 static SquareToCoords(sq) {
143 return {
144 x: C.RowToCoord(sq[1]),
145 // NOTE: column is always one char => max 26 columns
146 y: C.ColumnToCoord(sq[0])
147 };
148 }
149
150 // {x:0,y:4} --> e0 (should be e8)
151 static CoordsToSquare(coords) {
152 return C.CoordToColumn(coords.y) + C.CoordToRow(coords.x);
153 }
154
155 coordsToId([x, y]) {
156 if (typeof x == "number")
157 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
158 // Reserve :
159 return `${this.containerId}|rsq-${x}-${y}`;
160 }
161
162 idToCoords(targetId) {
163 if (!targetId)
164 return null; //outside page, maybe...
165 const idParts = targetId.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
166 if (
167 idParts.length < 2 ||
168 idParts[0] != this.containerId ||
169 !idParts[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
170 ) {
171 return null;
172 }
173 const squares = idParts[1].split('-');
174 if (squares[0] == "sq")
175 return [ parseInt(squares[1], 30), parseInt(squares[2], 30) ];
176 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
177 return [squares[1], squares[2]];
178 }
179
180 /////////////
181 // FEN UTILS
182
183 // Turn "wb" into "B" (for FEN)
184 board2fen(b) {
185 return b[0] == "w" ? b[1].toUpperCase() : b[1];
186 }
187
188 // Turn "p" into "bp" (for board)
189 fen2board(f) {
190 return f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f;
191 }
192
193 // Setup the initial random-or-not (asymmetric-or-not) position
194 genRandInitFen(seed) {
195 Random.setSeed(seed);
196
197 let fen, flags = "0707";
198 if (!this.options.randomness)
199 // Deterministic:
200 fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
201
202 else {
203 // Randomize
204 let pieces = { w: new Array(8), b: new Array(8) };
205 flags = "";
206 // Shuffle pieces on first (and last rank if randomness == 2)
207 for (let c of ["w", "b"]) {
208 if (c == 'b' && this.options.randomness == 1) {
209 pieces['b'] = pieces['w'];
210 flags += flags;
211 break;
212 }
213
214 let positions = ArrayFun.range(8);
215
216 // Get random squares for bishops
217 let randIndex = 2 * Random.randInt(4);
218 const bishop1Pos = positions[randIndex];
219 // The second bishop must be on a square of different color
220 let randIndex_tmp = 2 * Random.randInt(4) + 1;
221 const bishop2Pos = positions[randIndex_tmp];
222 // Remove chosen squares
223 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
224 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
225
226 // Get random squares for knights
227 randIndex = Random.randInt(6);
228 const knight1Pos = positions[randIndex];
229 positions.splice(randIndex, 1);
230 randIndex = Random.randInt(5);
231 const knight2Pos = positions[randIndex];
232 positions.splice(randIndex, 1);
233
234 // Get random square for queen
235 randIndex = Random.randInt(4);
236 const queenPos = positions[randIndex];
237 positions.splice(randIndex, 1);
238
239 // Rooks and king positions are now fixed,
240 // because of the ordering rook-king-rook
241 const rook1Pos = positions[0];
242 const kingPos = positions[1];
243 const rook2Pos = positions[2];
244
245 // Finally put the shuffled pieces in the board array
246 pieces[c][rook1Pos] = "r";
247 pieces[c][knight1Pos] = "n";
248 pieces[c][bishop1Pos] = "b";
249 pieces[c][queenPos] = "q";
250 pieces[c][kingPos] = "k";
251 pieces[c][bishop2Pos] = "b";
252 pieces[c][knight2Pos] = "n";
253 pieces[c][rook2Pos] = "r";
254 flags += rook1Pos.toString() + rook2Pos.toString();
255 }
256 fen = (
257 pieces["b"].join("") +
258 "/pppppppp/8/8/8/8/PPPPPPPP/" +
259 pieces["w"].join("").toUpperCase() +
260 " w 0"
261 );
262 }
263 // Add turn + flags + enpassant (+ reserve)
264 let parts = [];
265 if (this.hasFlags)
266 parts.push(`"flags":"${flags}"`);
267 if (this.hasEnpassant)
268 parts.push('"enpassant":"-"');
269 if (this.hasReserve)
270 parts.push('"reserve":"000000000000"');
271 if (this.options["crazyhouse"])
272 parts.push('"ispawn":"-"');
273 if (parts.length >= 1)
274 fen += " {" + parts.join(",") + "}";
275 return fen;
276 }
277
278 // "Parse" FEN: just return untransformed string data
279 parseFen(fen) {
280 const fenParts = fen.split(" ");
281 let res = {
282 position: fenParts[0],
283 turn: fenParts[1],
284 movesCount: fenParts[2]
285 };
286 if (fenParts.length > 3)
287 res = Object.assign(res, JSON.parse(fenParts[3]));
288 return res;
289 }
290
291 // Return current fen (game state)
292 getFen() {
293 let fen = (
294 this.getBaseFen() + " " +
295 this.getTurnFen() + " " +
296 this.movesCount
297 );
298 let parts = [];
299 if (this.hasFlags)
300 parts.push(`"flags":"${this.getFlagsFen()}"`);
301 if (this.hasEnpassant)
302 parts.push(`"enpassant":"${this.getEnpassantFen()}"`);
303 if (this.hasReserve)
304 parts.push(`"reserve":"${this.getReserveFen()}"`);
305 if (this.options["crazyhouse"])
306 parts.push(`"ispawn":"${this.getIspawnFen()}"`);
307 if (parts.length >= 1)
308 fen += " {" + parts.join(",") + "}";
309 return fen;
310 }
311
312 // Position part of the FEN string
313 getBaseFen() {
314 const format = (count) => {
315 // if more than 9 consecutive free spaces, break the integer,
316 // otherwise FEN parsing will fail.
317 if (count <= 9)
318 return count;
319 // Most boards of size < 18:
320 if (count <= 18)
321 return "9" + (count - 9);
322 // Except Gomoku:
323 return "99" + (count - 18);
324 };
325 let position = "";
326 for (let i = 0; i < this.size.y; i++) {
327 let emptyCount = 0;
328 for (let j = 0; j < this.size.x; j++) {
329 if (this.board[i][j] == "")
330 emptyCount++;
331 else {
332 if (emptyCount > 0) {
333 // Add empty squares in-between
334 position += format(emptyCount);
335 emptyCount = 0;
336 }
337 position += this.board2fen(this.board[i][j]);
338 }
339 }
340 if (emptyCount > 0)
341 // "Flush remainder"
342 position += format(emptyCount);
343 if (i < this.size.y - 1)
344 position += "/"; //separate rows
345 }
346 return position;
347 }
348
349 getTurnFen() {
350 return this.turn;
351 }
352
353 // Flags part of the FEN string
354 getFlagsFen() {
355 return ["w", "b"].map(c => {
356 return this.castleFlags[c].map(x => x.toString(30)).join("");
357 }).join("");
358 }
359
360 // Enpassant part of the FEN string
361 getEnpassantFen() {
362 if (!this.epSquare)
363 return "-"; //no en-passant
364 return C.CoordsToSquare(this.epSquare);
365 }
366
367 getReserveFen() {
368 return (
369 ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("")
370 );
371 }
372
373 getIspawnFen() {
374 const coords = Object.keys(this.ispawn);
375 if (coords.length == 0)
376 return "-";
377 return coords.join(",");
378 }
379
380 // Set flags from fen (castle: white a,h then black a,h)
381 setFlags(fenflags) {
382 this.castleFlags = {
383 w: [0, 1].map(i => parseInt(fenflags.charAt(i), 30)),
384 b: [2, 3].map(i => parseInt(fenflags.charAt(i), 30))
385 };
386 }
387
388 //////////////////
389 // INITIALIZATION
390
391 constructor(o) {
392 this.options = o.options;
393 this.playerColor = o.color;
394 this.afterPlay = o.afterPlay;
395
396 // Fen string fully describes the game state
397 if (!o.fen)
398 o.fen = this.genRandInitFen(o.seed);
399 const fenParsed = this.parseFen(o.fen);
400 this.board = this.getBoard(fenParsed.position);
401 this.turn = fenParsed.turn;
402 this.movesCount = parseInt(fenParsed.movesCount, 10);
403 this.setOtherVariables(fenParsed);
404
405 // Graphical (can use variables defined above)
406 this.containerId = o.element;
407 this.graphicalInit();
408 }
409
410 // Turn position fen into double array ["wb","wp","bk",...]
411 getBoard(position) {
412 const rows = position.split("/");
413 let board = ArrayFun.init(this.size.x, this.size.y, "");
414 for (let i = 0; i < rows.length; i++) {
415 let j = 0;
416 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
417 const character = rows[i][indexInRow];
418 const num = parseInt(character, 10);
419 // If num is a number, just shift j:
420 if (!isNaN(num))
421 j += num;
422 // Else: something at position i,j
423 else
424 board[i][j++] = this.fen2board(character);
425 }
426 }
427 return board;
428 }
429
430 // Some additional variables from FEN (variant dependant)
431 setOtherVariables(fenParsed) {
432 // Set flags and enpassant:
433 if (this.hasFlags)
434 this.setFlags(fenParsed.flags);
435 if (this.hasEnpassant)
436 this.epSquare = this.getEpSquare(fenParsed.enpassant);
437 if (this.hasReserve)
438 this.initReserves(fenParsed.reserve);
439 if (this.options["crazyhouse"])
440 this.initIspawn(fenParsed.ispawn);
441 this.subTurn = 1; //may be unused
442 if (this.options["teleport"]) {
443 this.subTurnTeleport = 1;
444 this.captured = null;
445 }
446 if (this.options["dark"]) {
447 // Setup enlightened: squares reachable by player side
448 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
449 this.updateEnlightened();
450 }
451 }
452
453 updateEnlightened() {
454 this.oldEnlightened = this.enlightened;
455 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
456 // Add pieces positions + all squares reachable by moves (includes Zen):
457 for (let x=0; x<this.size.x; x++) {
458 for (let y=0; y<this.size.y; y++) {
459 if (this.board[x][y] != "" && this.getColor(x, y) == this.playerColor)
460 {
461 this.enlightened[x][y] = true;
462 this.getPotentialMovesFrom([x, y]).forEach(m => {
463 this.enlightened[m.end.x][m.end.y] = true;
464 });
465 }
466 }
467 }
468 if (this.epSquare)
469 this.enlightEnpassant();
470 }
471
472 // Include square of the en-passant capturing square:
473 enlightEnpassant() {
474 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
475 const steps = this.pieces(this.playerColor)["p"].attack[0].steps;
476 for (let step of steps) {
477 const x = this.epSquare.x - step[0],
478 y = this.computeY(this.epSquare.y - step[1]);
479 if (
480 this.onBoard(x, y) &&
481 this.getColor(x, y) == this.playerColor &&
482 this.getPieceType(x, y) == "p"
483 ) {
484 this.enlightened[x][this.epSquare.y] = true;
485 break;
486 }
487 }
488 }
489
490 // Apply diff this.enlightened --> oldEnlightened on board
491 graphUpdateEnlightened() {
492 let chessboard =
493 document.getElementById(this.containerId).querySelector(".chessboard");
494 const r = chessboard.getBoundingClientRect();
495 const pieceWidth = this.getPieceWidth(r.width);
496 for (let x=0; x<this.size.x; x++) {
497 for (let y=0; y<this.size.y; y++) {
498 if (!this.enlightened[x][y] && this.oldEnlightened[x][y]) {
499 let elt = document.getElementById(this.coordsToId([x, y]));
500 elt.classList.add("in-shadow");
501 if (this.g_pieces[x][y])
502 this.g_pieces[x][y].classList.add("hidden");
503 }
504 else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) {
505 let elt = document.getElementById(this.coordsToId([x, y]));
506 elt.classList.remove("in-shadow");
507 if (this.g_pieces[x][y])
508 this.g_pieces[x][y].classList.remove("hidden");
509 }
510 }
511 }
512 }
513
514 // ordering as in pieces() p,r,n,b,q,k (+ count in base 30 if needed)
515 initReserves(reserveStr) {
516 const counts = reserveStr.split("").map(c => parseInt(c, 30));
517 this.reserve = { w: {}, b: {} };
518 const pieceName = ['p', 'r', 'n', 'b', 'q', 'k'];
519 const L = pieceName.length;
520 for (let i of ArrayFun.range(2 * L)) {
521 if (i < L)
522 this.reserve['w'][pieceName[i]] = counts[i];
523 else
524 this.reserve['b'][pieceName[i-L]] = counts[i];
525 }
526 }
527
528 initIspawn(ispawnStr) {
529 if (ispawnStr != "-") {
530 this.ispawn = ispawnStr.split(",").map(C.SquareToCoords)
531 .reduce((o, key) => ({ ...o, [key]: true}), {});
532 }
533 else
534 this.ispawn = {};
535 }
536
537 getNbReservePieces(color) {
538 return (
539 Object.values(this.reserve[color]).reduce(
540 (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0)
541 );
542 }
543
544 //////////////
545 // VISUAL PART
546
547 getPieceWidth(rwidth) {
548 return (rwidth / this.size.y);
549 }
550
551 getSquareWidth(rwidth) {
552 return this.getPieceWidth(rwidth);
553 }
554
555 getReserveSquareSize(rwidth, nbR) {
556 const sqSize = this.getSquareWidth(rwidth);
557 return Math.min(sqSize, rwidth / nbR);
558 }
559
560 getReserveNumId(color, piece) {
561 return `${this.containerId}|rnum-${color}${piece}`;
562 }
563
564 graphicalInit() {
565 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
566 window.onresize = () => this.re_drawBoardElements();
567 this.re_drawBoardElements();
568 this.initMouseEvents();
569 const chessboard =
570 document.getElementById(this.containerId).querySelector(".chessboard");
571 new ResizeObserver(this.rescale).observe(chessboard);
572 }
573
574 re_drawBoardElements() {
575 const board = this.getSvgChessboard();
576 const oppCol = C.GetOppCol(this.playerColor);
577 let chessboard =
578 document.getElementById(this.containerId).querySelector(".chessboard");
579 chessboard.innerHTML = "";
580 chessboard.insertAdjacentHTML('beforeend', board);
581 const aspectRatio = this.size.y / this.size.x;
582 // Compare window ratio width / height to aspectRatio:
583 const windowRatio = window.innerWidth / window.innerHeight;
584 let cbWidth, cbHeight;
585 if (windowRatio <= aspectRatio) {
586 // Limiting dimension is width:
587 cbWidth = Math.min(window.innerWidth, 767);
588 cbHeight = cbWidth / aspectRatio;
589 }
590 else {
591 // Limiting dimension is height:
592 cbHeight = Math.min(window.innerHeight, 767);
593 cbWidth = cbHeight * aspectRatio;
594 }
595 if (this.reserve) {
596 const sqSize = cbWidth / this.size.y;
597 // NOTE: allocate space for reserves (up/down) even if they are empty
598 if ((window.innerHeight - cbHeight) / 2 < sqSize + 5) {
599 cbHeight = window.innerHeight - 2 * (sqSize + 5);
600 cbWidth = cbHeight * aspectRatio;
601 }
602 }
603 chessboard.style.width = cbWidth + "px";
604 chessboard.style.height = cbHeight + "px";
605 // Center chessboard:
606 const spaceLeft = (window.innerWidth - cbWidth) / 2,
607 spaceTop = (window.innerHeight - cbHeight) / 2;
608 chessboard.style.left = spaceLeft + "px";
609 chessboard.style.top = spaceTop + "px";
610 // Give sizes instead of recomputing them,
611 // because chessboard might not be drawn yet.
612 this.setupPieces({
613 width: cbWidth,
614 height: cbHeight,
615 x: spaceLeft,
616 y: spaceTop
617 });
618 }
619
620 // Get SVG board (background, no pieces)
621 getSvgChessboard() {
622 const flipped = (this.playerColor == 'b');
623 let board = `
624 <svg
625 viewBox="0 0 80 80"
626 class="chessboard_SVG">
627 <g>`;
628 for (let i=0; i < this.size.x; i++) {
629 for (let j=0; j < this.size.y; j++) {
630 const ii = (flipped ? this.size.x - 1 - i : i);
631 const jj = (flipped ? this.size.y - 1 - j : j);
632 let classes = this.getSquareColorClass(ii, jj);
633 if (this.enlightened && !this.enlightened[ii][jj])
634 classes += " in-shadow";
635 // NOTE: x / y reversed because coordinates system is reversed.
636 board += `<rect
637 class="${classes}"
638 id="${this.coordsToId([ii, jj])}"
639 width="10"
640 height="10"
641 x="${10*j}"
642 y="${10*i}" />`;
643 }
644 }
645 board += "</g></svg>";
646 return board;
647 }
648
649 // Generally light square bottom-right
650 getSquareColorClass(i, j) {
651 return ((i+j) % 2 == 0 ? "light-square": "dark-square");
652 }
653
654 setupPieces(r) {
655 if (this.g_pieces) {
656 // Refreshing: delete old pieces first
657 for (let i=0; i<this.size.x; i++) {
658 for (let j=0; j<this.size.y; j++) {
659 if (this.g_pieces[i][j]) {
660 this.g_pieces[i][j].remove();
661 this.g_pieces[i][j] = null;
662 }
663 }
664 }
665 }
666 else
667 this.g_pieces = ArrayFun.init(this.size.x, this.size.y, null);
668 let chessboard =
669 document.getElementById(this.containerId).querySelector(".chessboard");
670 if (!r)
671 r = chessboard.getBoundingClientRect();
672 const pieceWidth = this.getPieceWidth(r.width);
673 for (let i=0; i < this.size.x; i++) {
674 for (let j=0; j < this.size.y; j++) {
675 if (this.board[i][j] != "") {
676 const color = this.getColor(i, j);
677 const piece = this.getPiece(i, j);
678 this.g_pieces[i][j] = document.createElement("piece");
679 this.g_pieces[i][j].classList.add(this.pieces()[piece]["class"]);
680 this.g_pieces[i][j].classList.add(color == "w" ? "white" : "black");
681 this.g_pieces[i][j].style.width = pieceWidth + "px";
682 this.g_pieces[i][j].style.height = pieceWidth + "px";
683 const [ip, jp] = this.getPixelPosition(i, j, r);
684 this.g_pieces[i][j].style.transform = `translate(${ip}px,${jp}px)`;
685 if (this.enlightened && !this.enlightened[i][j])
686 this.g_pieces[i][j].classList.add("hidden");
687 chessboard.appendChild(this.g_pieces[i][j]);
688 }
689 }
690 }
691 if (this.reserve)
692 this.re_drawReserve(['w', 'b'], r);
693 }
694
695 // NOTE: assume !!this.reserve
696 re_drawReserve(colors, r) {
697 if (this.r_pieces) {
698 // Remove (old) reserve pieces
699 for (let c of colors) {
700 if (!this.reserve[c])
701 continue;
702 Object.keys(this.reserve[c]).forEach(p => {
703 if (this.r_pieces[c][p]) {
704 this.r_pieces[c][p].remove();
705 delete this.r_pieces[c][p];
706 const numId = this.getReserveNumId(c, p);
707 document.getElementById(numId).remove();
708 }
709 });
710 let reservesDiv = document.getElementById("reserves_" + c);
711 if (reservesDiv)
712 reservesDiv.remove();
713 }
714 }
715 else
716 this.r_pieces = { 'w': {}, 'b': {} };
717 let container = document.getElementById(this.containerId);
718 if (!r)
719 r = container.querySelector(".chessboard").getBoundingClientRect();
720 for (let c of colors) {
721 if (!this.reserve[c])
722 continue;
723 const nbR = this.getNbReservePieces(c);
724 if (nbR == 0)
725 continue;
726 const sqResSize = this.getReserveSquareSize(r.width, nbR);
727 let ridx = 0;
728 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
729 const [i0, j0] = [r.x, r.y + vShift];
730 let rcontainer = document.createElement("div");
731 rcontainer.id = "reserves_" + c;
732 rcontainer.classList.add("reserves");
733 rcontainer.style.left = i0 + "px";
734 rcontainer.style.top = j0 + "px";
735 // NOTE: +1 fix display bug on Firefox at least
736 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
737 rcontainer.style.height = sqResSize + "px";
738 container.appendChild(rcontainer);
739 for (let p of Object.keys(this.reserve[c])) {
740 if (this.reserve[c][p] == 0)
741 continue;
742 let r_cell = document.createElement("div");
743 r_cell.id = this.coordsToId([c, p]);
744 r_cell.classList.add("reserve-cell");
745 r_cell.style.width = sqResSize + "px";
746 r_cell.style.height = sqResSize + "px";
747 rcontainer.appendChild(r_cell);
748 let piece = document.createElement("piece");
749 const pieceSpec = this.pieces()[p];
750 piece.classList.add(pieceSpec["class"]);
751 piece.classList.add(c == 'w' ? "white" : "black");
752 piece.style.width = "100%";
753 piece.style.height = "100%";
754 this.r_pieces[c][p] = piece;
755 r_cell.appendChild(piece);
756 let number = document.createElement("div");
757 number.textContent = this.reserve[c][p];
758 number.classList.add("reserve-num");
759 number.id = this.getReserveNumId(c, p);
760 const fontSize = "1.3em";
761 number.style.fontSize = fontSize;
762 number.style.fontSize = fontSize;
763 r_cell.appendChild(number);
764 ridx++;
765 }
766 }
767 }
768
769 updateReserve(color, piece, count) {
770 if (this.options["cannibal"] && C.CannibalKings[piece])
771 piece = "k"; //capturing cannibal king: back to king form
772 const oldCount = this.reserve[color][piece];
773 this.reserve[color][piece] = count;
774 // Redrawing is much easier if count==0
775 if ([oldCount, count].includes(0))
776 this.re_drawReserve([color]);
777 else {
778 const numId = this.getReserveNumId(color, piece);
779 document.getElementById(numId).textContent = count;
780 }
781 }
782
783 // After resize event: no need to destroy/recreate pieces
784 rescale() {
785 const container = document.getElementById(this.containerId);
786 if (!container)
787 return; //useful at initial loading
788 let chessboard = container.querySelector(".chessboard");
789 const r = chessboard.getBoundingClientRect();
790 const newRatio = r.width / r.height;
791 const aspectRatio = this.size.y / this.size.x;
792 let newWidth = r.width,
793 newHeight = r.height;
794 if (newRatio > aspectRatio) {
795 newWidth = r.height * aspectRatio;
796 chessboard.style.width = newWidth + "px";
797 }
798 else if (newRatio < aspectRatio) {
799 newHeight = r.width / aspectRatio;
800 chessboard.style.height = newHeight + "px";
801 }
802 const newX = (window.innerWidth - newWidth) / 2;
803 chessboard.style.left = newX + "px";
804 const newY = (window.innerHeight - newHeight) / 2;
805 chessboard.style.top = newY + "px";
806 const newR = { x: newX, y: newY, width: newWidth, height: newHeight };
807 const pieceWidth = this.getPieceWidth(newWidth);
808 for (let i=0; i < this.size.x; i++) {
809 for (let j=0; j < this.size.y; j++) {
810 if (this.g_pieces[i][j]) {
811 // NOTE: could also use CSS transform "scale"
812 this.g_pieces[i][j].style.width = pieceWidth + "px";
813 this.g_pieces[i][j].style.height = pieceWidth + "px";
814 const [ip, jp] = this.getPixelPosition(i, j, newR);
815 this.g_pieces[i][j].style.transform = `translate(${ip}px,${jp}px)`;
816 }
817 }
818 }
819 if (this.reserve)
820 this.rescaleReserve(newR);
821 }
822
823 rescaleReserve(r) {
824 for (let c of ['w','b']) {
825 if (!this.reserve[c])
826 continue;
827 const nbR = this.getNbReservePieces(c);
828 if (nbR == 0)
829 continue;
830 // Resize container first
831 const sqResSize = this.getReserveSquareSize(r.width, nbR);
832 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
833 const [i0, j0] = [r.x, r.y + vShift];
834 let rcontainer = document.getElementById("reserves_" + c);
835 rcontainer.style.left = i0 + "px";
836 rcontainer.style.top = j0 + "px";
837 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
838 rcontainer.style.height = sqResSize + "px";
839 // And then reserve cells:
840 const rpieceWidth = this.getReserveSquareSize(r.width, nbR);
841 Object.keys(this.reserve[c]).forEach(p => {
842 if (this.reserve[c][p] == 0)
843 return;
844 let r_cell = document.getElementById(this.coordsToId([c, p]));
845 r_cell.style.width = sqResSize + "px";
846 r_cell.style.height = sqResSize + "px";
847 });
848 }
849 }
850
851 // Return the absolute pixel coordinates (on board) given current position.
852 // Our coordinate system differs from CSS one (x <--> y).
853 // We return here the CSS coordinates (more useful).
854 getPixelPosition(i, j, r) {
855 const sqSize = this.getSquareWidth(r.width);
856 if (i < 0 || j < 0)
857 return [0, 0]; //piece vanishes
858 const flipped = (this.playerColor == 'b');
859 const x = (flipped ? this.size.y - 1 - j : j) * sqSize;
860 const y = (flipped ? this.size.x - 1 - i : i) * sqSize;
861 return [x, y];
862 }
863
864 initMouseEvents() {
865 let chessboard =
866 document.getElementById(this.containerId).querySelector(".chessboard");
867
868 const getOffset = e => {
869 if (e.clientX)
870 // Mouse
871 return {x: e.clientX, y: e.clientY};
872 let touchLocation = null;
873 if (e.targetTouches && e.targetTouches.length >= 1)
874 // Touch screen, dragstart
875 touchLocation = e.targetTouches[0];
876 else if (e.changedTouches && e.changedTouches.length >= 1)
877 // Touch screen, dragend
878 touchLocation = e.changedTouches[0];
879 if (touchLocation)
880 return {x: touchLocation.clientX, y: touchLocation.clientY};
881 return {x: 0, y: 0}; //shouldn't reach here =)
882 }
883
884 const centerOnCursor = (piece, e) => {
885 const centerShift = sqSize / 2;
886 const offset = getOffset(e);
887 piece.style.left = (offset.x - r.x - centerShift) + "px";
888 piece.style.top = (offset.y - r.y - centerShift) + "px";
889 }
890
891 let start = null,
892 r = null,
893 startPiece, curPiece = null,
894 sqSize;
895 const mousedown = (e) => {
896 // Disable zoom on smartphones:
897 if (e.touches && e.touches.length > 1)
898 e.preventDefault();
899 r = chessboard.getBoundingClientRect();
900 sqSize = this.getSquareWidth(r.width);
901 const square = this.idToCoords(e.target.id);
902 if (square) {
903 const [i, j] = square;
904 const move = this.doClick([i, j]);
905 if (move)
906 this.playPlusVisual(move);
907 else {
908 if (typeof i != "number")
909 startPiece = this.r_pieces[i][j];
910 else if (this.g_pieces[i][j])
911 startPiece = this.g_pieces[i][j];
912 if (startPiece && this.canIplay(i, j)) {
913 e.preventDefault();
914 start = { x: i, y: j };
915 curPiece = startPiece.cloneNode();
916 curPiece.style.transform = "none";
917 curPiece.style.zIndex = 5;
918 curPiece.style.width = sqSize + "px";
919 curPiece.style.height = sqSize + "px";
920 centerOnCursor(curPiece, e);
921 chessboard.appendChild(curPiece);
922 startPiece.style.opacity = "0.4";
923 chessboard.style.cursor = "none";
924 }
925 }
926 }
927 };
928
929 const mousemove = (e) => {
930 if (start) {
931 e.preventDefault();
932 centerOnCursor(curPiece, e);
933 }
934 else if (e.changedTouches && e.changedTouches.length >= 1)
935 // Attempt to prevent horizontal swipe...
936 e.preventDefault();
937 };
938
939 const mouseup = (e) => {
940 const newR = chessboard.getBoundingClientRect();
941 if (newR.width != r.width || newR.height != r.height) {
942 this.rescale();
943 return;
944 }
945 if (!start)
946 return;
947 const [x, y] = [start.x, start.y];
948 start = null;
949 e.preventDefault();
950 chessboard.style.cursor = "pointer";
951 startPiece.style.opacity = "1";
952 const offset = getOffset(e);
953 const landingElt = document.elementFromPoint(offset.x, offset.y);
954 const sq = landingElt ? this.idToCoords(landingElt.id) : undefined;
955 if (sq) {
956 const [i, j] = sq;
957 // NOTE: clearly suboptimal, but much easier, and not a big deal.
958 const potentialMoves = this.getPotentialMovesFrom([x, y])
959 .filter(m => m.end.x == i && m.end.y == j);
960 const moves = this.filterValid(potentialMoves);
961 if (moves.length >= 2)
962 this.showChoices(moves, r);
963 else if (moves.length == 1)
964 this.playPlusVisual(moves[0], r);
965 }
966 curPiece.remove();
967 };
968
969 if ('onmousedown' in window) {
970 document.addEventListener("mousedown", mousedown);
971 document.addEventListener("mousemove", mousemove);
972 document.addEventListener("mouseup", mouseup);
973 }
974 if ('ontouchstart' in window) {
975 // https://stackoverflow.com/a/42509310/12660887
976 document.addEventListener("touchstart", mousedown, {passive: false});
977 document.addEventListener("touchmove", mousemove, {passive: false});
978 document.addEventListener("touchend", mouseup, {passive: false});
979 }
980 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
981 }
982
983 showChoices(moves, r) {
984 let container = document.getElementById(this.containerId);
985 let chessboard = container.querySelector(".chessboard");
986 let choices = document.createElement("div");
987 choices.id = "choices";
988 choices.style.width = r.width + "px";
989 choices.style.height = r.height + "px";
990 choices.style.left = r.x + "px";
991 choices.style.top = r.y + "px";
992 chessboard.style.opacity = "0.5";
993 container.appendChild(choices);
994 const squareWidth = this.getSquareWidth(r.width);
995 const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2;
996 const firstUpTop = (r.height - squareWidth) / 2;
997 const color = moves[0].appear[0].c;
998 const callback = (m) => {
999 chessboard.style.opacity = "1";
1000 container.removeChild(choices);
1001 this.playPlusVisual(m, r);
1002 }
1003 for (let i=0; i < moves.length; i++) {
1004 let choice = document.createElement("div");
1005 choice.classList.add("choice");
1006 choice.style.width = squareWidth + "px";
1007 choice.style.height = squareWidth + "px";
1008 choice.style.left = (firstUpLeft + i * squareWidth) + "px";
1009 choice.style.top = firstUpTop + "px";
1010 choice.style.backgroundColor = "lightyellow";
1011 choice.onclick = () => callback(moves[i]);
1012 const piece = document.createElement("piece");
1013 const pieceSpec = this.pieces()[moves[i].appear[0].p];
1014 piece.classList.add(pieceSpec["class"]);
1015 piece.classList.add(color == 'w' ? "white" : "black");
1016 piece.style.width = "100%";
1017 piece.style.height = "100%";
1018 choice.appendChild(piece);
1019 choices.appendChild(choice);
1020 }
1021 }
1022
1023 //////////////
1024 // BASIC UTILS
1025
1026 get size() {
1027 return {x: 8, y: 8};
1028 }
1029
1030 // Color of thing on square (i,j). 'undefined' if square is empty
1031 getColor(i, j) {
1032 return this.board[i][j].charAt(0);
1033 }
1034
1035 // Assume square i,j isn't empty
1036 getPiece(i, j) {
1037 return this.board[i][j].charAt(1);
1038 }
1039
1040 // Piece type on square (i,j)
1041 getPieceType(i, j) {
1042 const p = this.board[i][j].charAt(1);
1043 return C.CannibalKings[p] || p; //a cannibal king move as...
1044 }
1045
1046 // Get opponent color
1047 static GetOppCol(color) {
1048 return (color == "w" ? "b" : "w");
1049 }
1050
1051 // Can thing on square1 capture (no return) thing on square2?
1052 canTake([x1, y1], [x2, y2]) {
1053 return (this.getColor(x1, y1) !== this.getColor(x2, y2));
1054 }
1055
1056 // Is (x,y) on the chessboard?
1057 onBoard(x, y) {
1058 return (x >= 0 && x < this.size.x &&
1059 y >= 0 && y < this.size.y);
1060 }
1061
1062 // Used in interface
1063 canIplay(x, y) {
1064 return (
1065 this.playerColor == this.turn &&
1066 (
1067 (typeof x == "number" && this.getColor(x, y) == this.turn) ||
1068 (typeof x == "string" && x == this.turn) //reserve
1069 )
1070 );
1071 }
1072
1073 ////////////////////////
1074 // PIECES SPECIFICATIONS
1075
1076 pieces(color, x, y) {
1077 const pawnShift = (color == "w" ? -1 : 1);
1078 const initRank = ((color == 'w' && x == 6) || (color == 'b' && x == 1));
1079 return {
1080 'p': {
1081 "class": "pawn",
1082 moves: [
1083 {
1084 steps: [[pawnShift, 0]],
1085 range: (initRank ? 2 : 1)
1086 }
1087 ],
1088 attack: [
1089 {
1090 steps: [[pawnShift, 1], [pawnShift, -1]],
1091 range: 1
1092 }
1093 ]
1094 },
1095 // rook
1096 'r': {
1097 "class": "rook",
1098 moves: [
1099 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1100 ]
1101 },
1102 // knight
1103 'n': {
1104 "class": "knight",
1105 moves: [
1106 {
1107 steps: [
1108 [1, 2], [1, -2], [-1, 2], [-1, -2],
1109 [2, 1], [-2, 1], [2, -1], [-2, -1]
1110 ],
1111 range: 1
1112 }
1113 ]
1114 },
1115 // bishop
1116 'b': {
1117 "class": "bishop",
1118 moves: [
1119 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1120 ]
1121 },
1122 // queen
1123 'q': {
1124 "class": "queen",
1125 moves: [
1126 {
1127 steps: [
1128 [0, 1], [0, -1], [1, 0], [-1, 0],
1129 [1, 1], [1, -1], [-1, 1], [-1, -1]
1130 ]
1131 }
1132 ]
1133 },
1134 // king
1135 'k': {
1136 "class": "king",
1137 moves: [
1138 {
1139 steps: [
1140 [0, 1], [0, -1], [1, 0], [-1, 0],
1141 [1, 1], [1, -1], [-1, 1], [-1, -1]
1142 ],
1143 range: 1
1144 }
1145 ]
1146 },
1147 // Cannibal kings:
1148 '!': {"class": "king-pawn", moveas: "p"},
1149 '#': {"class": "king-rook", moveas: "r"},
1150 '$': {"class": "king-knight", moveas: "n"},
1151 '%': {"class": "king-bishop", moveas: "b"},
1152 '*': {"class": "king-queen", moveas: "q"}
1153 };
1154 }
1155
1156 ////////////////////
1157 // MOVES GENERATION
1158
1159 // For Cylinder: get Y coordinate
1160 computeY(y) {
1161 if (!this.options["cylinder"])
1162 return y;
1163 let res = y % this.size.y;
1164 if (res < 0)
1165 res += this.size.y;
1166 return res;
1167 }
1168
1169 // Stop at the first capture found
1170 atLeastOneCapture(color) {
1171 color = color || this.turn;
1172 const oppCol = C.GetOppCol(color);
1173 for (let i = 0; i < this.size.x; i++) {
1174 for (let j = 0; j < this.size.y; j++) {
1175 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
1176 const allSpecs = this.pieces(color, i, j)
1177 let specs = allSpecs[this.getPieceType(i, j)];
1178 const attacks = specs.attack || specs.moves;
1179 for (let a of attacks) {
1180 outerLoop: for (let step of a.steps) {
1181 let [ii, jj] = [i + step[0], this.computeY(j + step[1])];
1182 let stepCounter = 1;
1183 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1184 if (a.range <= stepCounter++)
1185 continue outerLoop;
1186 ii += step[0];
1187 jj = this.computeY(jj + step[1]);
1188 }
1189 if (
1190 this.onBoard(ii, jj) &&
1191 this.getColor(ii, jj) == oppCol &&
1192 this.filterValid(
1193 [this.getBasicMove([i, j], [ii, jj])]
1194 ).length >= 1
1195 ) {
1196 return true;
1197 }
1198 }
1199 }
1200 }
1201 }
1202 }
1203 return false;
1204 }
1205
1206 getDropMovesFrom([c, p]) {
1207 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1208 // (but not necessarily otherwise)
1209 if (this.reserve[c][p] == 0)
1210 return [];
1211 let moves = [];
1212 for (let i=0; i<this.size.x; i++) {
1213 for (let j=0; j<this.size.y; j++) {
1214 if (
1215 this.board[i][j] == "" &&
1216 (!this.enlightened || this.enlightened[i][j]) &&
1217 (
1218 p != "p" ||
1219 (c == 'w' && i < this.size.x - 1) ||
1220 (c == 'b' && i > 0)
1221 )
1222 ) {
1223 moves.push(
1224 new Move({
1225 start: {x: c, y: p},
1226 end: {x: i, y: j},
1227 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1228 vanish: []
1229 })
1230 );
1231 }
1232 }
1233 }
1234 return moves;
1235 }
1236
1237 // All possible moves from selected square
1238 getPotentialMovesFrom(sq, color) {
1239 if (this.subTurnTeleport == 2)
1240 return [];
1241 if (typeof sq[0] == "string")
1242 return this.getDropMovesFrom(sq);
1243 if (this.isImmobilized(sq))
1244 return [];
1245 const piece = this.getPieceType(sq[0], sq[1]);
1246 let moves = this.getPotentialMovesOf(piece, sq);
1247 if (
1248 piece == "p" &&
1249 this.hasEnpassant &&
1250 this.epSquare
1251 ) {
1252 Array.prototype.push.apply(moves, this.getEnpassantCaptures(sq));
1253 }
1254 if (
1255 piece == "k" &&
1256 this.hasCastle &&
1257 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1258 ) {
1259 Array.prototype.push.apply(moves, this.getCastleMoves(sq));
1260 }
1261 return this.postProcessPotentialMoves(moves);
1262 }
1263
1264 postProcessPotentialMoves(moves) {
1265 if (moves.length == 0)
1266 return [];
1267 const color = this.getColor(moves[0].start.x, moves[0].start.y);
1268 const oppCol = C.GetOppCol(color);
1269
1270 if (this.options["capture"] && this.atLeastOneCapture())
1271 moves = this.capturePostProcess(moves, oppCol);
1272
1273 if (this.options["atomic"])
1274 this.atomicPostProcess(moves, oppCol);
1275
1276 if (
1277 moves.length > 0 &&
1278 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1279 ) {
1280 this.pawnPostProcess(moves, color, oppCol);
1281 }
1282
1283 if (
1284 this.options["cannibal"] &&
1285 this.options["rifle"]
1286 ) {
1287 // In this case a rifle-capture from last rank may promote a pawn
1288 this.riflePromotePostProcess(moves);
1289 }
1290
1291 return moves;
1292 }
1293
1294 capturePostProcess(moves, oppCol) {
1295 // Filter out non-capturing moves (not using m.vanish because of
1296 // self captures of Recycle and Teleport).
1297 return moves.filter(m => {
1298 return (
1299 this.board[m.end.x][m.end.y] != "" &&
1300 this.getColor(m.end.x, m.end.y) == oppCol
1301 );
1302 });
1303 }
1304
1305 atomicPostProcess(moves, oppCol) {
1306 moves.forEach(m => {
1307 if (
1308 this.board[m.end.x][m.end.y] != "" &&
1309 this.getColor(m.end.x, m.end.y) == oppCol
1310 ) {
1311 // Explosion!
1312 let steps = [
1313 [-1, -1],
1314 [-1, 0],
1315 [-1, 1],
1316 [0, -1],
1317 [0, 1],
1318 [1, -1],
1319 [1, 0],
1320 [1, 1]
1321 ];
1322 for (let step of steps) {
1323 let x = m.end.x + step[0];
1324 let y = this.computeY(m.end.y + step[1]);
1325 if (
1326 this.onBoard(x, y) &&
1327 this.board[x][y] != "" &&
1328 this.getPieceType(x, y) != "p"
1329 ) {
1330 m.vanish.push(
1331 new PiPo({
1332 p: this.getPiece(x, y),
1333 c: this.getColor(x, y),
1334 x: x,
1335 y: y
1336 })
1337 );
1338 }
1339 }
1340 if (!this.options["rifle"])
1341 m.appear.pop(); //nothin appears
1342 }
1343 });
1344 }
1345
1346 pawnPostProcess(moves, color, oppCol) {
1347 let moreMoves = [];
1348 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1349 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1350 moves.forEach(m => {
1351 let finalPieces = ["p"];
1352 const [x1, y1] = [m.start.x, m.start.y];
1353 const [x2, y2] = [m.end.x, m.end.y];
1354 const promotionOk = (
1355 x2 == lastRank &&
1356 (!this.options["rifle"] || this.board[x2][y2] == "")
1357 );
1358 if (!promotionOk)
1359 return; //nothing to do
1360 if (!this.options["pawnfall"]) {
1361 if (
1362 this.options["cannibal"] &&
1363 this.board[x2][y2] != "" &&
1364 this.getColor(x2, y2) == oppCol
1365 ) {
1366 finalPieces = [this.getPieceType(x2, y2)];
1367 }
1368 else
1369 finalPieces = this.pawnPromotions;
1370 }
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 let tr = null;
1377 if (!this.options["pawnfall"]) {
1378 tr = {
1379 c: color,
1380 p: (initPiece != "!" ? piece : C.CannibalKingCode[piece])
1381 };
1382 }
1383 let newMove = this.getBasicMove([x1, y1], [x2, y2], tr);
1384 if (this.options["pawnfall"]) {
1385 newMove.appear.shift();
1386 newMove.pawnfall = true; //required in prePlay()
1387 }
1388 moreMoves.push(newMove);
1389 }
1390 });
1391 Array.prototype.push.apply(moves, moreMoves);
1392 }
1393
1394 riflePromotePostProcess(moves) {
1395 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1396 let newMoves = [];
1397 moves.forEach(m => {
1398 if (
1399 m.start.x == lastRank &&
1400 m.appear.length >= 1 &&
1401 m.appear[0].p == "p" &&
1402 m.appear[0].x == m.start.x &&
1403 m.appear[0].y == m.start.y
1404 ) {
1405 const promotionPiece0 = this.pawnSpecs.promotions[0];
1406 m.appear[0].p = this.pawnPromotions[0];
1407 for (let i=1; i<this.pawnPromotions.length; i++) {
1408 let newMv = JSON.parse(JSON.stringify(m));
1409 newMv.appear[0].p = this.pawnSpecs.promotions[i];
1410 newMoves.push(newMv);
1411 }
1412 }
1413 });
1414 Array.prototype.push.apply(moves, newMoves);
1415 }
1416
1417 // NOTE: using special symbols to not interfere with variants' pieces codes
1418 static get CannibalKings() {
1419 return {
1420 "!": "p",
1421 "#": "r",
1422 "$": "n",
1423 "%": "b",
1424 "*": "q"
1425 };
1426 }
1427
1428 static get CannibalKingCode() {
1429 return {
1430 "p": "!",
1431 "r": "#",
1432 "n": "$",
1433 "b": "%",
1434 "q": "*",
1435 "k": "k"
1436 };
1437 }
1438
1439 isKing(symbol) {
1440 return (
1441 symbol == 'k' ||
1442 (this.options["cannibal"] && C.CannibalKings[symbol])
1443 );
1444 }
1445
1446 // For Madrasi:
1447 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1448 isImmobilized([x, y]) {
1449 if (!this.options["madrasi"])
1450 return false;
1451 const color = this.getColor(x, y);
1452 const oppCol = C.GetOppCol(color);
1453 const piece = this.getPieceType(x, y); //ok not cannibal king
1454 const stepSpec = this.pieces(color, x, y)[piece];
1455 const attacks = stepSpec.attack || stepSpec.moves;
1456 for (let a of attacks) {
1457 outerLoop: for (let step of a.steps) {
1458 let [i, j] = [x + step[0], y + step[1]];
1459 let stepCounter = 1;
1460 while (this.onBoard(i, j) && this.board[i][j] == "") {
1461 if (a.range <= stepCounter++)
1462 continue outerLoop;
1463 i += step[0];
1464 j = this.computeY(j + step[1]);
1465 }
1466 if (
1467 this.onBoard(i, j) &&
1468 this.getColor(i, j) == oppCol &&
1469 this.getPieceType(i, j) == piece
1470 ) {
1471 return true;
1472 }
1473 }
1474 }
1475 return false;
1476 }
1477
1478 // Generic method to find possible moves of "sliding or jumping" pieces
1479 getPotentialMovesOf(piece, [x, y]) {
1480 const color = this.getColor(x, y);
1481 const stepSpec = this.pieces(color, x, y)[piece];
1482 let moves = [];
1483 let explored = {}; //for Cylinder mode
1484
1485 const findAddMoves = (type, stepArray) => {
1486 for (let s of stepArray) {
1487 outerLoop: for (let step of s.steps) {
1488 let [i, j] = [x + step[0], this.computeY(y + step[1])];
1489 let stepCounter = 1;
1490 while (this.onBoard(i, j) && this.board[i][j] == "") {
1491 if (type != "attack" && !explored[i + "." + j]) {
1492 explored[i + "." + j] = true;
1493 moves.push(this.getBasicMove([x, y], [i, j]));
1494 }
1495 if (s.range <= stepCounter++)
1496 continue outerLoop;
1497 i += step[0];
1498 j = this.computeY(j + step[1]);
1499 }
1500 if (!this.onBoard(i, j))
1501 continue;
1502 const pieceIJ = this.getPieceType(i, j);
1503 if (
1504 type != "moveonly" &&
1505 !explored[i + "." + j] &&
1506 (
1507 !this.options["zen"] ||
1508 pieceIJ == "k"
1509 ) &&
1510 (
1511 this.canTake([x, y], [i, j]) ||
1512 (
1513 (this.options["recycle"] || this.options["teleport"]) &&
1514 pieceIJ != "k"
1515 )
1516 )
1517 ) {
1518 explored[i + "." + j] = true;
1519 moves.push(this.getBasicMove([x, y], [i, j]));
1520 }
1521 }
1522 }
1523 };
1524
1525 const specialAttack = !!stepSpec.attack;
1526 if (specialAttack)
1527 findAddMoves("attack", stepSpec.attack);
1528 findAddMoves(specialAttack ? "moveonly" : "all", stepSpec.moves);
1529 if (this.options["zen"])
1530 Array.prototype.push.apply(moves, this.findCapturesOn([x, y], true));
1531 return moves;
1532 }
1533
1534 findCapturesOn([x, y], zen) {
1535 let moves = [];
1536 // Find reverse captures (opponent takes)
1537 const color = this.getColor(x, y);
1538 const pieceType = this.getPieceType(x, y);
1539 const oppCol = C.GetOppCol(color);
1540 for (let i=0; i<this.size.x; i++) {
1541 for (let j=0; j<this.size.y; j++) {
1542 if (
1543 this.board[i][j] != "" &&
1544 this.canTake([i, j], [x, y]) &&
1545 !this.isImmobilized([i, j])
1546 ) {
1547 const piece = this.getPieceType(i, j);
1548 if (zen && C.CannibalKingCode[piece])
1549 continue; //king not captured in this way
1550 const stepSpec = this.pieces(oppCol, i, j)[piece];
1551 const attacks = stepSpec.attack || stepSpec.moves;
1552 for (let a of attacks) {
1553 for (let s of a.steps) {
1554 // Quick check: if step isn't compatible, don't even try
1555 if (!C.CompatibleStep([i, j], [x, y], s, a.range))
1556 continue;
1557 // Finally verify that nothing stand in-between
1558 let [ii, jj] = [i + s[0], this.computeY(j + s[1])];
1559 let stepCounter = 1;
1560 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1561 ii += s[0];
1562 jj = this.computeY(jj + s[1]);
1563 }
1564 if (ii == x && jj == y) {
1565 moves.push(this.getBasicMove([x, y], [i, j]));
1566 if (!zen)
1567 return moves; //test for underCheck
1568 }
1569 }
1570 }
1571 }
1572 }
1573 }
1574 return moves;
1575 }
1576
1577 static CompatibleStep([x1, y1], [x2, y2], step, range) {
1578 const rx = (x2 - x1) / step[0],
1579 ry = (y2 - y1) / step[1];
1580 if (
1581 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
1582 (!Number.isFinite(ry) && !Number.isNaN(ry))
1583 ) {
1584 return false;
1585 }
1586 let distance = (Number.isNaN(rx) ? ry : rx);
1587 // TODO: 1e-7 here is totally arbitrary
1588 if (Math.abs(distance - Math.round(distance)) > 1e-7)
1589 return false;
1590 distance = Math.round(distance); //in case of (numerical...)
1591 if (range < distance)
1592 return false;
1593 return true;
1594 }
1595
1596 // Build a regular move from its initial and destination squares.
1597 // tr: transformation
1598 getBasicMove([sx, sy], [ex, ey], tr) {
1599 const initColor = this.getColor(sx, sy);
1600 const initPiece = this.getPiece(sx, sy);
1601 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1602 let mv = new Move({
1603 appear: [],
1604 vanish: [],
1605 start: {x:sx, y:sy},
1606 end: {x:ex, y:ey}
1607 });
1608 if (
1609 !this.options["rifle"] ||
1610 this.board[ex][ey] == "" ||
1611 destColor == initColor //Recycle, Teleport
1612 ) {
1613 mv.appear = [
1614 new PiPo({
1615 x: ex,
1616 y: ey,
1617 c: !!tr ? tr.c : initColor,
1618 p: !!tr ? tr.p : initPiece
1619 })
1620 ];
1621 mv.vanish = [
1622 new PiPo({
1623 x: sx,
1624 y: sy,
1625 c: initColor,
1626 p: initPiece
1627 })
1628 ];
1629 }
1630 if (this.board[ex][ey] != "") {
1631 mv.vanish.push(
1632 new PiPo({
1633 x: ex,
1634 y: ey,
1635 c: this.getColor(ex, ey),
1636 p: this.getPiece(ex, ey)
1637 })
1638 );
1639 if (this.options["rifle"])
1640 // Rifle captures are tricky in combination with Atomic etc,
1641 // so it's useful to mark the move :
1642 mv.capture = true;
1643 if (this.options["cannibal"] && destColor != initColor) {
1644 const lastIdx = mv.vanish.length - 1;
1645 let trPiece = mv.vanish[lastIdx].p;
1646 if (this.isKing(this.getPiece(sx, sy)))
1647 trPiece = C.CannibalKingCode[trPiece];
1648 if (mv.appear.length >= 1)
1649 mv.appear[0].p = trPiece;
1650 else if (this.options["rifle"]) {
1651 mv.appear.unshift(
1652 new PiPo({
1653 x: sx,
1654 y: sy,
1655 c: initColor,
1656 p: trPiece
1657 })
1658 );
1659 mv.vanish.unshift(
1660 new PiPo({
1661 x: sx,
1662 y: sy,
1663 c: initColor,
1664 p: initPiece
1665 })
1666 );
1667 }
1668 }
1669 }
1670 return mv;
1671 }
1672
1673 // En-passant square, if any
1674 getEpSquare(moveOrSquare) {
1675 if (typeof moveOrSquare === "string") {
1676 const square = moveOrSquare;
1677 if (square == "-")
1678 return undefined;
1679 return C.SquareToCoords(square);
1680 }
1681 // Argument is a move:
1682 const move = moveOrSquare;
1683 const s = move.start,
1684 e = move.end;
1685 if (
1686 s.y == e.y &&
1687 Math.abs(s.x - e.x) == 2 &&
1688 // Next conditions for variants like Atomic or Rifle, Recycle...
1689 (move.appear.length > 0 && move.appear[0].p == "p") &&
1690 (move.vanish.length > 0 && move.vanish[0].p == "p")
1691 ) {
1692 return {
1693 x: (s.x + e.x) / 2,
1694 y: s.y
1695 };
1696 }
1697 return undefined; //default
1698 }
1699
1700 // Special case of en-passant captures: treated separately
1701 getEnpassantCaptures([x, y]) {
1702 const color = this.getColor(x, y);
1703 const shiftX = (color == 'w' ? -1 : 1);
1704 const oppCol = C.GetOppCol(color);
1705 let enpassantMove = null;
1706 if (
1707 !!this.epSquare &&
1708 this.epSquare.x == x + shiftX &&
1709 Math.abs(this.computeY(this.epSquare.y - y)) == 1 &&
1710 this.getColor(x, this.epSquare.y) == oppCol //Doublemove guard...
1711 ) {
1712 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
1713 this.board[epx][epy] = oppCol + "p";
1714 enpassantMove = this.getBasicMove([x, y], [epx, epy]);
1715 this.board[epx][epy] = "";
1716 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
1717 enpassantMove.vanish[lastIdx].x = x;
1718 }
1719 return !!enpassantMove ? [enpassantMove] : [];
1720 }
1721
1722 // "castleInCheck" arg to let some variants castle under check
1723 getCastleMoves([x, y], finalSquares, castleInCheck, castleWith) {
1724 const c = this.getColor(x, y);
1725
1726 // Castling ?
1727 const oppCol = C.GetOppCol(c);
1728 let moves = [];
1729 // King, then rook:
1730 finalSquares =
1731 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
1732 const castlingKing = this.getPiece(x, y);
1733 castlingCheck: for (
1734 let castleSide = 0;
1735 castleSide < 2;
1736 castleSide++ //large, then small
1737 ) {
1738 if (this.castleFlags[c][castleSide] >= this.size.y)
1739 continue;
1740 // If this code is reached, rook and king are on initial position
1741
1742 // NOTE: in some variants this is not a rook
1743 const rookPos = this.castleFlags[c][castleSide];
1744 const castlingPiece = this.getPiece(x, rookPos);
1745 if (
1746 this.board[x][rookPos] == "" ||
1747 this.getColor(x, rookPos) != c ||
1748 (!!castleWith && !castleWith.includes(castlingPiece))
1749 ) {
1750 // Rook is not here, or changed color (see Benedict)
1751 continue;
1752 }
1753 // Nothing on the path of the king ? (and no checks)
1754 const finDist = finalSquares[castleSide][0] - y;
1755 let step = finDist / Math.max(1, Math.abs(finDist));
1756 let i = y;
1757 do {
1758 if (
1759 (!castleInCheck && this.underCheck([x, i], oppCol)) ||
1760 (
1761 this.board[x][i] != "" &&
1762 // NOTE: next check is enough, because of chessboard constraints
1763 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
1764 )
1765 ) {
1766 continue castlingCheck;
1767 }
1768 i += step;
1769 } while (i != finalSquares[castleSide][0]);
1770 // Nothing on the path to the rook?
1771 step = (castleSide == 0 ? -1 : 1);
1772 for (i = y + step; i != rookPos; i += step) {
1773 if (this.board[x][i] != "")
1774 continue castlingCheck;
1775 }
1776
1777 // Nothing on final squares, except maybe king and castling rook?
1778 for (i = 0; i < 2; i++) {
1779 if (
1780 finalSquares[castleSide][i] != rookPos &&
1781 this.board[x][finalSquares[castleSide][i]] != "" &&
1782 (
1783 finalSquares[castleSide][i] != y ||
1784 this.getColor(x, finalSquares[castleSide][i]) != c
1785 )
1786 ) {
1787 continue castlingCheck;
1788 }
1789 }
1790
1791 // If this code is reached, castle is valid
1792 moves.push(
1793 new Move({
1794 appear: [
1795 new PiPo({
1796 x: x,
1797 y: finalSquares[castleSide][0],
1798 p: castlingKing,
1799 c: c
1800 }),
1801 new PiPo({
1802 x: x,
1803 y: finalSquares[castleSide][1],
1804 p: castlingPiece,
1805 c: c
1806 })
1807 ],
1808 vanish: [
1809 // King might be initially disguised (Titan...)
1810 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
1811 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
1812 ],
1813 end:
1814 Math.abs(y - rookPos) <= 2
1815 ? {x: x, y: rookPos}
1816 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
1817 })
1818 );
1819 }
1820
1821 return moves;
1822 }
1823
1824 ////////////////////
1825 // MOVES VALIDATION
1826
1827 // Is (king at) given position under check by "color" ?
1828 underCheck([x, y], color) {
1829 if (this.options["taking"] || this.options["dark"])
1830 return false;
1831 return (this.findCapturesOn([x, y]).length >= 1);
1832 }
1833
1834 // Stop at first king found (TODO: multi-kings)
1835 searchKingPos(color) {
1836 for (let i=0; i < this.size.x; i++) {
1837 for (let j=0; j < this.size.y; j++) {
1838 if (this.getColor(i, j) == color && this.isKing(this.getPiece(i, j)))
1839 return [i, j];
1840 }
1841 }
1842 return [-1, -1]; //king not found
1843 }
1844
1845 filterValid(moves) {
1846 if (moves.length == 0)
1847 return [];
1848 const color = this.turn;
1849 const oppCol = C.GetOppCol(color);
1850 if (this.options["balance"] && [1, 3].includes(this.movesCount)) {
1851 // Forbid moves either giving check or exploding opponent's king:
1852 const oppKingPos = this.searchKingPos(oppCol);
1853 moves = moves.filter(m => {
1854 if (
1855 m.vanish.some(v => v.c == oppCol && v.p == "k") &&
1856 m.appear.every(a => a.c != oppCol || a.p != "k")
1857 )
1858 return false;
1859 this.playOnBoard(m);
1860 const res = !this.underCheck(oppKingPos, color);
1861 this.undoOnBoard(m);
1862 return res;
1863 });
1864 }
1865 if (this.options["taking"] || this.options["dark"])
1866 return moves;
1867 const kingPos = this.searchKingPos(color);
1868 let filtered = {}; //avoid re-checking similar moves (promotions...)
1869 return moves.filter(m => {
1870 const key = m.start.x + m.start.y + '.' + m.end.x + m.end.y;
1871 if (!filtered[key]) {
1872 this.playOnBoard(m);
1873 let square = kingPos,
1874 res = true; //a priori valid
1875 if (m.vanish.some(v => {
1876 return (v.p == "k" || C.CannibalKings[v.p]) && v.c == color;
1877 })) {
1878 // Search king in appear array:
1879 const newKingIdx =
1880 m.appear.findIndex(a => {
1881 return (a.p == "k" || C.CannibalKings[a.p]) && a.c == color;
1882 });
1883 if (newKingIdx >= 0)
1884 square = [m.appear[newKingIdx].x, m.appear[newKingIdx].y];
1885 else
1886 res = false;
1887 }
1888 res &&= !this.underCheck(square, oppCol);
1889 this.undoOnBoard(m);
1890 filtered[key] = res;
1891 return res;
1892 }
1893 return filtered[key];
1894 });
1895 }
1896
1897 /////////////////
1898 // MOVES PLAYING
1899
1900 // Aggregate flags into one object
1901 aggregateFlags() {
1902 return this.castleFlags;
1903 }
1904
1905 // Reverse operation
1906 disaggregateFlags(flags) {
1907 this.castleFlags = flags;
1908 }
1909
1910 // Apply a move on board
1911 playOnBoard(move) {
1912 for (let psq of move.vanish) this.board[psq.x][psq.y] = "";
1913 for (let psq of move.appear) this.board[psq.x][psq.y] = psq.c + psq.p;
1914 }
1915 // Un-apply the played move
1916 undoOnBoard(move) {
1917 for (let psq of move.appear) this.board[psq.x][psq.y] = "";
1918 for (let psq of move.vanish) this.board[psq.x][psq.y] = psq.c + psq.p;
1919 }
1920
1921 updateCastleFlags(move) {
1922 // Update castling flags if start or arrive from/at rook/king locations
1923 move.appear.concat(move.vanish).forEach(psq => {
1924 if (
1925 this.board[psq.x][psq.y] != "" &&
1926 this.getPieceType(psq.x, psq.y) == "k"
1927 ) {
1928 this.castleFlags[psq.c] = [this.size.y, this.size.y];
1929 }
1930 // NOTE: not "else if" because king can capture enemy rook...
1931 let c = "";
1932 if (psq.x == 0)
1933 c = "b";
1934 else if (psq.x == this.size.x - 1)
1935 c = "w";
1936 if (c != "") {
1937 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
1938 if (fidx >= 0)
1939 this.castleFlags[c][fidx] = this.size.y;
1940 }
1941 });
1942 }
1943
1944 prePlay(move) {
1945 if (
1946 typeof move.start.x == "number" &&
1947 (!this.options["teleport"] || this.subTurnTeleport == 1)
1948 ) {
1949 // OK, not a drop move
1950 if (
1951 this.hasCastle &&
1952 // If flags already off, no need to re-check:
1953 Object.keys(this.castleFlags).some(c => {
1954 return this.castleFlags[c].some(val => val < this.size.y)})
1955 ) {
1956 this.updateCastleFlags(move);
1957 }
1958 const initSquare = C.CoordsToSquare(move.start);
1959 if (
1960 this.options["crazyhouse"] &&
1961 (!this.options["rifle"] || !move.capture)
1962 ) {
1963 const destSquare = C.CoordsToSquare(move.end);
1964 if (this.ispawn[initSquare]) {
1965 delete this.ispawn[initSquare];
1966 this.ispawn[destSquare] = true;
1967 }
1968 else if (
1969 move.vanish[0].p == "p" &&
1970 move.appear[0].p != "p"
1971 ) {
1972 this.ispawn[destSquare] = true;
1973 }
1974 else if (
1975 this.ispawn[destSquare] &&
1976 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
1977 ) {
1978 move.vanish[1].p = "p";
1979 delete this.ispawn[destSquare];
1980 }
1981 }
1982 }
1983 const minSize = Math.min(move.appear.length, move.vanish.length);
1984 if (this.hasReserve && !move.pawnfall) {
1985 const color = this.turn;
1986 for (let i=minSize; i<move.appear.length; i++) {
1987 // Something appears = dropped on board (some exceptions, Chakart...)
1988 const piece = move.appear[i].p;
1989 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
1990 }
1991 for (let i=minSize; i<move.vanish.length; i++) {
1992 // Something vanish: add to reserve except if recycle & opponent
1993 const piece = move.vanish[i].p;
1994 if (this.options["crazyhouse"] || move.vanish[i].c == color)
1995 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
1996 }
1997 }
1998 }
1999
2000 play(move) {
2001 this.prePlay(move);
2002 if (this.hasEnpassant)
2003 this.epSquare = this.getEpSquare(move);
2004 this.playOnBoard(move);
2005 this.postPlay(move);
2006 }
2007
2008 postPlay(move) {
2009 const color = this.turn;
2010 const oppCol = C.GetOppCol(color);
2011 if (this.options["dark"])
2012 this.updateEnlightened();
2013 if (this.options["teleport"]) {
2014 if (
2015 this.subTurnTeleport == 1 &&
2016 move.vanish.length > move.appear.length &&
2017 move.vanish[move.vanish.length - 1].c == color
2018 ) {
2019 const v = move.vanish[move.vanish.length - 1];
2020 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
2021 this.subTurnTeleport = 2;
2022 return;
2023 }
2024 this.subTurnTeleport = 1;
2025 this.captured = null;
2026 }
2027 if (this.options["balance"]) {
2028 if (![1, 3].includes(this.movesCount))
2029 this.turn = oppCol;
2030 }
2031 else {
2032 if (
2033 (
2034 this.options["doublemove"] &&
2035 this.movesCount >= 1 &&
2036 this.subTurn == 1
2037 ) ||
2038 (this.options["progressive"] && this.subTurn <= this.movesCount)
2039 ) {
2040 const oppKingPos = this.searchKingPos(oppCol);
2041 if (
2042 oppKingPos[0] >= 0 &&
2043 (
2044 this.options["taking"] ||
2045 !this.underCheck(oppKingPos, color)
2046 )
2047 ) {
2048 this.subTurn++;
2049 return;
2050 }
2051 }
2052 this.turn = oppCol;
2053 }
2054 this.movesCount++;
2055 this.subTurn = 1;
2056 }
2057
2058 // "Stop at the first move found"
2059 atLeastOneMove(color) {
2060 color = color || this.turn;
2061 for (let i = 0; i < this.size.x; i++) {
2062 for (let j = 0; j < this.size.y; j++) {
2063 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
2064 // NOTE: in fact searching for all potential moves from i,j.
2065 // I don't believe this is an issue, for now at least.
2066 const moves = this.getPotentialMovesFrom([i, j]);
2067 if (moves.some(m => this.filterValid([m]).length >= 1))
2068 return true;
2069 }
2070 }
2071 }
2072 if (this.hasReserve && this.reserve[color]) {
2073 for (let p of Object.keys(this.reserve[color])) {
2074 const moves = this.getDropMovesFrom([color, p]);
2075 if (moves.some(m => this.filterValid([m]).length >= 1))
2076 return true;
2077 }
2078 }
2079 return false;
2080 }
2081
2082 // What is the score ? (Interesting if game is over)
2083 getCurrentScore(move) {
2084 const color = this.turn;
2085 const oppCol = C.GetOppCol(color);
2086 const kingPos = [this.searchKingPos(color), this.searchKingPos(oppCol)];
2087 if (kingPos[0][0] < 0 && kingPos[1][0] < 0)
2088 return "1/2";
2089 if (kingPos[0][0] < 0)
2090 return (color == "w" ? "0-1" : "1-0");
2091 if (kingPos[1][0] < 0)
2092 return (color == "w" ? "1-0" : "0-1");
2093 if (this.atLeastOneMove())
2094 return "*";
2095 // No valid move: stalemate or checkmate?
2096 if (!this.underCheck(kingPos[0], color))
2097 return "1/2";
2098 // OK, checkmate
2099 return (color == "w" ? "0-1" : "1-0");
2100 }
2101
2102 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
2103 playVisual(move, r) {
2104 move.vanish.forEach(v => {
2105 // TODO: next "if" shouldn't be required
2106 if (this.g_pieces[v.x][v.y])
2107 this.g_pieces[v.x][v.y].remove();
2108 this.g_pieces[v.x][v.y] = null;
2109 });
2110 let chessboard =
2111 document.getElementById(this.containerId).querySelector(".chessboard");
2112 if (!r)
2113 r = chessboard.getBoundingClientRect();
2114 const pieceWidth = this.getPieceWidth(r.width);
2115 move.appear.forEach(a => {
2116 this.g_pieces[a.x][a.y] = document.createElement("piece");
2117 this.g_pieces[a.x][a.y].classList.add(this.pieces()[a.p]["class"]);
2118 this.g_pieces[a.x][a.y].classList.add(a.c == "w" ? "white" : "black");
2119 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2120 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2121 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
2122 this.g_pieces[a.x][a.y].style.transform = `translate(${ip}px,${jp}px)`;
2123 if (this.enlightened && !this.enlightened[a.x][a.y])
2124 this.g_pieces[a.x][a.y].classList.add("hidden");
2125 chessboard.appendChild(this.g_pieces[a.x][a.y]);
2126 });
2127 if (this.options["dark"])
2128 this.graphUpdateEnlightened();
2129 }
2130
2131 playPlusVisual(move, r) {
2132 this.play(move);
2133 this.playVisual(move, r);
2134 this.afterPlay(move); //user method
2135 }
2136
2137 // Assumes reserve on top (usage case otherwise? TODO?)
2138 getReserveShift(c, p, r) {
2139 let nbR = 0,
2140 ridx = 0;
2141 for (let pi of Object.keys(this.reserve[c])) {
2142 if (this.reserve[c][pi] == 0)
2143 continue;
2144 if (pi == p)
2145 ridx = nbR;
2146 nbR++;
2147 }
2148 const rsqSize = this.getReserveSquareSize(r.width, nbR);
2149 return [-ridx * rsqSize, rsqSize]; //slightly inaccurate... TODO?
2150 }
2151
2152 animate(move, callback) {
2153 if (this.noAnimate) {
2154 callback();
2155 return;
2156 }
2157 const [i1, j1] = [move.start.x, move.start.y];
2158 const dropMove = (typeof i1 == "string");
2159 const startArray = (dropMove ? this.r_pieces : this.g_pieces);
2160 let startPiece = startArray[i1][j1];
2161 // TODO: next "if" shouldn't be required
2162 if (!startPiece) {
2163 callback();
2164 return;
2165 }
2166 let chessboard =
2167 document.getElementById(this.containerId).querySelector(".chessboard");
2168 const clonePiece = (
2169 !dropMove &&
2170 this.options["rifle"] ||
2171 (this.options["teleport"] && this.subTurnTeleport == 2)
2172 );
2173 if (clonePiece) {
2174 startPiece = startPiece.cloneNode();
2175 if (this.options["rifle"])
2176 startArray[i1][j1].style.opacity = "0";
2177 if (this.options["teleport"] && this.subTurnTeleport == 2) {
2178 const pieces = this.pieces();
2179 const startCode = (dropMove ? j1 : this.getPiece(i1, j1));
2180 startPiece.classList.remove(pieces[startCode]["class"]);
2181 startPiece.classList.add(pieces[this.captured.p]["class"]);
2182 // Color: OK
2183 }
2184 chessboard.appendChild(startPiece);
2185 }
2186 const [i2, j2] = [move.end.x, move.end.y];
2187 let startCoords;
2188 if (dropMove) {
2189 startCoords = [
2190 i1 == this.playerColor ? this.size.x : 0,
2191 this.size.y / 2 //not trying to be accurate here... (TODO?)
2192 ];
2193 }
2194 else
2195 startCoords = [i1, j1];
2196 const r = chessboard.getBoundingClientRect();
2197 const arrival = this.getPixelPosition(i2, j2, r); //TODO: arrival on drop?
2198 let rs = [0, 0];
2199 if (dropMove)
2200 rs = this.getReserveShift(i1, j1, r);
2201 const distance =
2202 Math.sqrt((startCoords[0] - i2) ** 2 + (startCoords[1] - j2) ** 2);
2203 const maxDist = Math.sqrt((this.size.x - 1)** 2 + (this.size.y - 1) ** 2);
2204 const multFact = (distance - 1) / (maxDist - 1); //1 == minDist
2205 const duration = 0.2 + multFact * 0.3;
2206 const initTransform = startPiece.style.transform;
2207 startPiece.style.transform =
2208 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2209 startPiece.style.transitionDuration = duration + "s";
2210 setTimeout(
2211 () => {
2212 if (clonePiece) {
2213 if (this.options["rifle"])
2214 startArray[i1][j1].style.opacity = "1";
2215 startPiece.remove();
2216 }
2217 else {
2218 startPiece.style.transform = initTransform;
2219 startPiece.style.transitionDuration = "0s";
2220 }
2221 callback();
2222 },
2223 duration * 1000
2224 );
2225 }
2226
2227 playReceivedMove(moves, callback) {
2228 const launchAnimation = () => {
2229 const r = container.querySelector(".chessboard").getBoundingClientRect();
2230 const animateRec = i => {
2231 this.animate(moves[i], () => {
2232 this.play(moves[i]);
2233 this.playVisual(moves[i], r);
2234 if (i < moves.length - 1)
2235 setTimeout(() => animateRec(i+1), 300);
2236 else
2237 callback();
2238 });
2239 };
2240 animateRec(0);
2241 };
2242 // Delay if user wasn't focused:
2243 const checkDisplayThenAnimate = (delay) => {
2244 if (container.style.display == "none") {
2245 alert("New move! Let's go back to game...");
2246 document.getElementById("gameInfos").style.display = "none";
2247 container.style.display = "block";
2248 setTimeout(launchAnimation, 700);
2249 }
2250 else
2251 setTimeout(launchAnimation, delay || 0);
2252 };
2253 let container = document.getElementById(this.containerId);
2254 if (document.hidden) {
2255 document.onvisibilitychange = () => {
2256 document.onvisibilitychange = undefined;
2257 checkDisplayThenAnimate(700);
2258 };
2259 }
2260 else
2261 checkDisplayThenAnimate();
2262 }
2263
2264 };