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