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