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