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