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