Draft Dice chess
[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'],
2c8375bb 238 flags: ['r']
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() {
41534b92
BA
582 let board = `
583 <svg
f55a0a67 584 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
535c464b 585 class="chessboard_SVG">`;
52127581
BA
586 board += this.getBaseSvgChessboard();
587 board += "</svg>";
588 return board;
589 }
590
591 getBaseSvgChessboard() {
592 let board = "";
593 const flipped = this.flippedBoard;
728cb1e3
BA
594 for (let i=0; i < this.size.x; i++) {
595 for (let j=0; j < this.size.y; j++) {
9b760538
BA
596 if (!this.onBoard(i, j))
597 continue;
41534b92
BA
598 const ii = (flipped ? this.size.x - 1 - i : i);
599 const jj = (flipped ? this.size.y - 1 - j : j);
c7bf7b1b
BA
600 let classes = this.getSquareColorClass(ii, jj);
601 if (this.enlightened && !this.enlightened[ii][jj])
602 classes += " in-shadow";
41534b92 603 // NOTE: x / y reversed because coordinates system is reversed.
535c464b
BA
604 board += `
605 <rect
606 class="${classes}"
607 id="${this.coordsToId({x: ii, y: jj})}"
608 width="10"
609 height="10"
610 x="${10*j}"
611 y="${10*i}"
612 />`;
41534b92
BA
613 }
614 }
41534b92
BA
615 return board;
616 }
617
10c9010b 618 setupVisualPieces(r) {
3c61449b
BA
619 let chessboard =
620 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
621 if (!r)
622 r = chessboard.getBoundingClientRect();
41534b92 623 const pieceWidth = this.getPieceWidth(r.width);
b2fc1259
BA
624 const addPiece = (i, j, arrName, classes) => {
625 this[arrName][i][j] = document.createElement("piece");
626 C.AddClass_es(this[arrName][i][j], classes);
627 this[arrName][i][j].style.width = pieceWidth + "px";
628 this[arrName][i][j].style.height = pieceWidth + "px";
629 let [ip, jp] = this.getPixelPosition(i, j, r);
630 // Translate coordinates to use chessboard as reference:
631 this[arrName][i][j].style.transform =
632 `translate(${ip - r.x}px,${jp - r.y}px)`;
633 chessboard.appendChild(this[arrName][i][j]);
634 };
635 const conditionalReset = (arrName) => {
636 if (this[arrName]) {
637 // Refreshing: delete old pieces first. This isn't necessary,
638 // but simpler (this method isn't called many times)
639 for (let i=0; i<this.size.x; i++) {
640 for (let j=0; j<this.size.y; j++) {
641 if (this[arrName][i][j]) {
642 this[arrName][i][j].remove();
643 this[arrName][i][j] = null;
644 }
645 }
646 }
647 }
648 else
649 this[arrName] = ArrayFun.init(this.size.x, this.size.y, null);
650 if (arrName == "d_pieces")
2c8375bb
BA
651 this.marks.forEach((m) => {
652 const formattedSquare =
653 (this.size.x - parseInt(m.substring(1), 10)).toString(36) +
654 (m.charCodeAt(0) - 97).toString(36);
655 const mCoords = V.SquareToCoords(formattedSquare);
656 addPiece(mCoords.x, mCoords.y, arrName, "mark");
657 });
b2fc1259
BA
658 };
659 if (this.marks)
660 conditionalReset("d_pieces");
661 conditionalReset("g_pieces");
41534b92
BA
662 for (let i=0; i < this.size.x; i++) {
663 for (let j=0; j < this.size.y; j++) {
c9ab0340 664 if (this.board[i][j] != "") {
41534b92 665 const color = this.getColor(i, j);
cc2c7183 666 const piece = this.getPiece(i, j);
b2fc1259 667 addPiece(i, j, "g_pieces", this.pieces(color, i, j)[piece]["class"]);
616a8d7a 668 this.g_pieces[i][j].classList.add(V.GetColorClass(color));
c9ab0340
BA
669 if (this.enlightened && !this.enlightened[i][j])
670 this.g_pieces[i][j].classList.add("hidden");
b2fc1259
BA
671 }
672 if (this.marks && this.d_pieces[i][j]) {
673 let classes = ["mark"];
674 if (this.board[i][j] != "")
675 classes.push("transparent");
676 addPiece(i, j, "d_pieces", classes);
41534b92
BA
677 }
678 }
679 }
549ca151 680 if (this.hasReserve && !this.isDiagram)
b4ae3ff6 681 this.re_drawReserve(['w', 'b'], r);
41534b92
BA
682 }
683
24872b22 684 // NOTE: assume this.reserve != null
41534b92
BA
685 re_drawReserve(colors, r) {
686 if (this.r_pieces) {
687 // Remove (old) reserve pieces
688 for (let c of colors) {
24872b22
BA
689 Object.keys(this.r_pieces[c]).forEach(p => {
690 this.r_pieces[c][p].remove();
691 delete this.r_pieces[c][p];
692 const numId = this.getReserveNumId(c, p);
693 document.getElementById(numId).remove();
41534b92 694 });
41534b92
BA
695 }
696 }
b4ae3ff6 697 else
9db5050a
BA
698 this.r_pieces = { w: {}, b: {} };
699 let container = document.getElementById(this.containerId);
b4ae3ff6 700 if (!r)
9db5050a 701 r = container.querySelector(".chessboard").getBoundingClientRect();
41534b92 702 for (let c of colors) {
24872b22
BA
703 let reservesDiv = document.getElementById("reserves_" + c);
704 if (reservesDiv)
705 reservesDiv.remove();
b4ae3ff6
BA
706 if (!this.reserve[c])
707 continue;
41534b92 708 const nbR = this.getNbReservePieces(c);
b4ae3ff6
BA
709 if (nbR == 0)
710 continue;
41534b92
BA
711 const sqResSize = this.getReserveSquareSize(r.width, nbR);
712 let ridx = 0;
713 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
714 const [i0, j0] = [r.x, r.y + vShift];
715 let rcontainer = document.createElement("div");
716 rcontainer.id = "reserves_" + c;
717 rcontainer.classList.add("reserves");
718 rcontainer.style.left = i0 + "px";
719 rcontainer.style.top = j0 + "px";
1aa9054d
BA
720 // NOTE: +1 fix display bug on Firefox at least
721 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92 722 rcontainer.style.height = sqResSize + "px";
9db5050a 723 container.appendChild(rcontainer);
41534b92 724 for (let p of Object.keys(this.reserve[c])) {
b4ae3ff6
BA
725 if (this.reserve[c][p] == 0)
726 continue;
41534b92 727 let r_cell = document.createElement("div");
15106e82 728 r_cell.id = this.coordsToId({x: c, y: p});
41534b92 729 r_cell.classList.add("reserve-cell");
1aa9054d
BA
730 r_cell.style.width = sqResSize + "px";
731 r_cell.style.height = sqResSize + "px";
41534b92
BA
732 rcontainer.appendChild(r_cell);
733 let piece = document.createElement("piece");
2159c239 734 C.AddClass_es(piece, this.pieces(c, c, p)[p]["class"]);
616a8d7a 735 piece.classList.add(V.GetColorClass(c));
41534b92
BA
736 piece.style.width = "100%";
737 piece.style.height = "100%";
738 this.r_pieces[c][p] = piece;
739 r_cell.appendChild(piece);
740 let number = document.createElement("div");
741 number.textContent = this.reserve[c][p];
742 number.classList.add("reserve-num");
743 number.id = this.getReserveNumId(c, p);
744 const fontSize = "1.3em";
745 number.style.fontSize = fontSize;
746 number.style.fontSize = fontSize;
747 r_cell.appendChild(number);
748 ridx++;
749 }
750 }
751 }
752
753 updateReserve(color, piece, count) {
55a15dcb 754 if (this.options["cannibal"] && C.CannibalKings[piece])
cc2c7183 755 piece = "k"; //capturing cannibal king: back to king form
41534b92
BA
756 const oldCount = this.reserve[color][piece];
757 this.reserve[color][piece] = count;
182ba661
BA
758 // Redrawing is much easier if count==0 (or undefined)
759 if ([oldCount, count].some(item => !item))
b4ae3ff6 760 this.re_drawReserve([color]);
41534b92
BA
761 else {
762 const numId = this.getReserveNumId(color, piece);
763 document.getElementById(numId).textContent = count;
764 }
765 }
766
c4e9bb92
BA
767 // Resize board: no need to destroy/recreate pieces
768 rescale(mode) {
e7b64798
BA
769 const container = document.getElementById(this.containerId);
770 let chessboard = container.querySelector(".chessboard");
771 const rc = container.getBoundingClientRect(),
772 r = chessboard.getBoundingClientRect();
c4e9bb92
BA
773 const multFact = (mode == "up" ? 1.05 : 0.95);
774 let [newWidth, newHeight] = [multFact * r.width, multFact * r.height];
535c464b 775 // Stay in window:
f55a0a67 776 const vRatio = this.size.ratio || 1;
e7b64798
BA
777 if (newWidth > rc.width) {
778 newWidth = rc.width;
f55a0a67 779 newHeight = newWidth / vRatio;
c4e9bb92 780 }
e7b64798
BA
781 if (newHeight > rc.height) {
782 newHeight = rc.height;
f55a0a67 783 newWidth = newHeight * vRatio;
c4e9bb92 784 }
535c464b
BA
785 chessboard.style.width = newWidth + "px";
786 chessboard.style.height = newHeight + "px";
e7b64798 787 const newX = (rc.width - newWidth) / 2;
3c61449b 788 chessboard.style.left = newX + "px";
e7b64798 789 const newY = (rc.height - newHeight) / 2;
3c61449b 790 chessboard.style.top = newY + "px";
9db5050a 791 const newR = {x: newX, y: newY, width: newWidth, height: newHeight};
c4e9bb92 792 const pieceWidth = this.getPieceWidth(newWidth);
d621e620
BA
793 // NOTE: next "if" for variants which use squares filling
794 // instead of "physical", moving pieces
795 if (this.g_pieces) {
c4e9bb92
BA
796 for (let i=0; i < this.size.x; i++) {
797 for (let j=0; j < this.size.y; j++) {
798 if (this.g_pieces[i][j]) {
d621e620 799 // NOTE: could also use CSS transform "scale"
c4e9bb92
BA
800 this.g_pieces[i][j].style.width = pieceWidth + "px";
801 this.g_pieces[i][j].style.height = pieceWidth + "px";
802 const [ip, jp] = this.getPixelPosition(i, j, newR);
d621e620 803 // Translate coordinates to use chessboard as reference:
c4e9bb92 804 this.g_pieces[i][j].style.transform =
d621e620
BA
805 `translate(${ip - newX}px,${jp - newY}px)`;
806 }
41534b92
BA
807 }
808 }
809 }
b2fc1259 810 if (this.hasReserve)
c4e9bb92 811 this.rescaleReserve(newR);
41534b92
BA
812 }
813
814 rescaleReserve(r) {
41534b92 815 for (let c of ['w','b']) {
b4ae3ff6
BA
816 if (!this.reserve[c])
817 continue;
41534b92 818 const nbR = this.getNbReservePieces(c);
b4ae3ff6
BA
819 if (nbR == 0)
820 continue;
41534b92
BA
821 // Resize container first
822 const sqResSize = this.getReserveSquareSize(r.width, nbR);
823 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
824 const [i0, j0] = [r.x, r.y + vShift];
825 let rcontainer = document.getElementById("reserves_" + c);
826 rcontainer.style.left = i0 + "px";
827 rcontainer.style.top = j0 + "px";
1aa9054d 828 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92
BA
829 rcontainer.style.height = sqResSize + "px";
830 // And then reserve cells:
831 const rpieceWidth = this.getReserveSquareSize(r.width, nbR);
832 Object.keys(this.reserve[c]).forEach(p => {
b4ae3ff6
BA
833 if (this.reserve[c][p] == 0)
834 return;
15106e82 835 let r_cell = document.getElementById(this.coordsToId({x: c, y: p}));
1aa9054d
BA
836 r_cell.style.width = sqResSize + "px";
837 r_cell.style.height = sqResSize + "px";
41534b92
BA
838 });
839 }
840 }
841
9db5050a 842 // Return the absolute pixel coordinates given current position.
41534b92
BA
843 // Our coordinate system differs from CSS one (x <--> y).
844 // We return here the CSS coordinates (more useful).
845 getPixelPosition(i, j, r) {
b4ae3ff6
BA
846 if (i < 0 || j < 0)
847 return [0, 0]; //piece vanishes
15106e82
BA
848 let x, y;
849 if (typeof i == "string") {
850 // Reserves: need to know the rank of piece
851 const nbR = this.getNbReservePieces(i);
852 const rsqSize = this.getReserveSquareSize(r.width, nbR);
853 x = this.getRankInReserve(i, j) * rsqSize;
854 y = (this.playerColor == i ? y = r.height + 5 : - 5 - rsqSize);
855 }
856 else {
857 const sqSize = r.width / this.size.y;
65203419 858 const flipped = this.flippedBoard;
15106e82
BA
859 x = (flipped ? this.size.y - 1 - j : j) * sqSize;
860 y = (flipped ? this.size.x - 1 - i : i) * sqSize;
861 }
9db5050a 862 return [r.x + x, r.y + y];
41534b92
BA
863 }
864
865 initMouseEvents() {
9db5050a
BA
866 let container = document.getElementById(this.containerId);
867 let chessboard = container.querySelector(".chessboard");
41534b92
BA
868
869 const getOffset = e => {
3c61449b
BA
870 if (e.clientX)
871 // Mouse
872 return {x: e.clientX, y: e.clientY};
41534b92
BA
873 let touchLocation = null;
874 if (e.targetTouches && e.targetTouches.length >= 1)
875 // Touch screen, dragstart
876 touchLocation = e.targetTouches[0];
877 else if (e.changedTouches && e.changedTouches.length >= 1)
878 // Touch screen, dragend
879 touchLocation = e.changedTouches[0];
880 if (touchLocation)
11625344 881 return {x: touchLocation.clientX, y: touchLocation.clientY};
57b8015b 882 return {x: 0, y: 0}; //shouldn't reach here =)
41534b92
BA
883 }
884
885 const centerOnCursor = (piece, e) => {
15106e82 886 const centerShift = this.getPieceWidth(r.width) / 2;
41534b92 887 const offset = getOffset(e);
9db5050a
BA
888 piece.style.left = (offset.x - centerShift) + "px";
889 piece.style.top = (offset.y - centerShift) + "px";
41534b92
BA
890 }
891
892 let start = null,
893 r = null,
894 startPiece, curPiece = null,
15106e82 895 pieceWidth;
41534b92 896 const mousedown = (e) => {
cb17fed8 897 // Disable zoom on smartphones:
b4ae3ff6
BA
898 if (e.touches && e.touches.length > 1)
899 e.preventDefault();
3c61449b 900 r = chessboard.getBoundingClientRect();
15106e82
BA
901 pieceWidth = this.getPieceWidth(r.width);
902 const cd = this.idToCoords(e.target.id);
903 if (cd) {
904 const move = this.doClick(cd);
b4ae3ff6 905 if (move)
e7d409fc 906 this.buildMoveStack(move, r);
6b9320bb 907 else if (!this.clickOnly) {
15106e82
BA
908 const [x, y] = Object.values(cd);
909 if (typeof x != "number")
910 startPiece = this.r_pieces[x][y];
911 else
912 startPiece = this.g_pieces[x][y];
913 if (startPiece && this.canIplay(x, y)) {
41534b92 914 e.preventDefault();
15106e82 915 start = cd;
41534b92
BA
916 curPiece = startPiece.cloneNode();
917 curPiece.style.transform = "none";
918 curPiece.style.zIndex = 5;
15106e82
BA
919 curPiece.style.width = pieceWidth + "px";
920 curPiece.style.height = pieceWidth + "px";
41534b92 921 centerOnCursor(curPiece, e);
9db5050a 922 container.appendChild(curPiece);
41534b92 923 startPiece.style.opacity = "0.4";
3c61449b 924 chessboard.style.cursor = "none";
41534b92
BA
925 }
926 }
927 }
928 };
929
930 const mousemove = (e) => {
931 if (start) {
932 e.preventDefault();
933 centerOnCursor(curPiece, e);
934 }
11625344
BA
935 else if (e.changedTouches && e.changedTouches.length >= 1)
936 // Attempt to prevent horizontal swipe...
937 e.preventDefault();
41534b92
BA
938 };
939
940 const mouseup = (e) => {
b4ae3ff6
BA
941 if (!start)
942 return;
41534b92
BA
943 const [x, y] = [start.x, start.y];
944 start = null;
945 e.preventDefault();
3c61449b 946 chessboard.style.cursor = "pointer";
41534b92
BA
947 startPiece.style.opacity = "1";
948 const offset = getOffset(e);
949 const landingElt = document.elementFromPoint(offset.x, offset.y);
15106e82
BA
950 const cd =
951 (landingElt ? this.idToCoords(landingElt.id) : undefined);
952 if (cd) {
41534b92
BA
953 // NOTE: clearly suboptimal, but much easier, and not a big deal.
954 const potentialMoves = this.getPotentialMovesFrom([x, y])
15106e82 955 .filter(m => m.end.x == cd.x && m.end.y == cd.y);
41534b92 956 const moves = this.filterValid(potentialMoves);
b4ae3ff6
BA
957 if (moves.length >= 2)
958 this.showChoices(moves, r);
959 else if (moves.length == 1)
e7d409fc 960 this.buildMoveStack(moves[0], r);
41534b92
BA
961 }
962 curPiece.remove();
963 };
964
a5da6269
BA
965 const resize = (e) => this.rescale(e.deltaY < 0 ? "up" : "down");
966
41534b92 967 if ('onmousedown' in window) {
a5da6269
BA
968 this.mouseListeners = [
969 {type: "mousedown", listener: mousedown},
970 {type: "mousemove", listener: mousemove},
971 {type: "mouseup", listener: mouseup},
972 {type: "wheel", listener: resize}
973 ];
974 this.mouseListeners.forEach(ml => {
975 document.addEventListener(ml.type, ml.listener);
976 });
41534b92
BA
977 }
978 if ('ontouchstart' in window) {
a5da6269
BA
979 this.touchListeners = [
980 {type: "touchstart", listener: mousedown},
981 {type: "touchmove", listener: mousemove},
982 {type: "touchend", listener: mouseup}
983 ];
984 this.touchListeners.forEach(tl => {
985 // https://stackoverflow.com/a/42509310/12660887
986 document.addEventListener(tl.type, tl.listener, {passive: false});
987 });
41534b92 988 }
11625344 989 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
41534b92
BA
990 }
991
7c038235 992 // NOTE: not called if isDiagram
a5da6269 993 removeListeners() {
549ca151
BA
994 let container = document.getElementById(this.containerId);
995 this.windowResizeObs.unobserve(container);
a5da6269
BA
996 if ('onmousedown' in window) {
997 this.mouseListeners.forEach(ml => {
998 document.removeEventListener(ml.type, ml.listener);
999 });
1000 }
1001 if ('ontouchstart' in window) {
1002 this.touchListeners.forEach(tl => {
1003 // https://stackoverflow.com/a/42509310/12660887
1004 document.removeEventListener(tl.type, tl.listener);
1005 });
1006 }
1007 }
1008
41534b92
BA
1009 showChoices(moves, r) {
1010 let container = document.getElementById(this.containerId);
3c61449b 1011 let chessboard = container.querySelector(".chessboard");
41534b92
BA
1012 let choices = document.createElement("div");
1013 choices.id = "choices";
a2bb7e06
BA
1014 if (!r)
1015 r = chessboard.getBoundingClientRect();
41534b92
BA
1016 choices.style.width = r.width + "px";
1017 choices.style.height = r.height + "px";
1018 choices.style.left = r.x + "px";
1019 choices.style.top = r.y + "px";
3c61449b
BA
1020 chessboard.style.opacity = "0.5";
1021 container.appendChild(choices);
15106e82 1022 const squareWidth = r.width / this.size.y;
41534b92
BA
1023 const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2;
1024 const firstUpTop = (r.height - squareWidth) / 2;
1025 const color = moves[0].appear[0].c;
1026 const callback = (m) => {
3c61449b
BA
1027 chessboard.style.opacity = "1";
1028 container.removeChild(choices);
e7d409fc 1029 this.buildMoveStack(m, r);
41534b92
BA
1030 }
1031 for (let i=0; i < moves.length; i++) {
1032 let choice = document.createElement("div");
1033 choice.classList.add("choice");
1034 choice.style.width = squareWidth + "px";
1035 choice.style.height = squareWidth + "px";
1036 choice.style.left = (firstUpLeft + i * squareWidth) + "px";
1037 choice.style.top = firstUpTop + "px";
1038 choice.style.backgroundColor = "lightyellow";
1039 choice.onclick = () => callback(moves[i]);
1040 const piece = document.createElement("piece");
3b641716 1041 const cdisp = moves[i].choice || moves[i].appear[0].p;
2159c239
BA
1042 C.AddClass_es(piece,
1043 this.pieces(color, moves[i].end.x, moves[i].end.y)[cdisp]["class"]);
616a8d7a 1044 piece.classList.add(V.GetColorClass(color));
41534b92
BA
1045 piece.style.width = "100%";
1046 piece.style.height = "100%";
1047 choice.appendChild(piece);
1048 choices.appendChild(choice);
1049 }
1050 }
1051
98d14451
BA
1052 displayMessage(elt, msg, classe_s, timeout) {
1053 if (elt)
1054 // Fixed element, e.g. for Dice Chess
1055 elt.innerHTML = msg;
1056 else {
1057 // Temporary div (Chakart, Apocalypse...)
1058 let divMsg = document.createElement("div");
1059 C.AddClass_es(divMsg, classe_s);
1060 divMsg.innerHTML = msg;
1061 let container = document.getElementById(this.containerId);
1062 container.appendChild(divMsg);
1063 setTimeout(() => container.removeChild(divMsg), timeout);
1064 }
1065 }
1066
ca8a3993
BA
1067 ////////////////
1068 // DARK METHODS
1069
1070 updateEnlightened() {
1071 this.oldEnlightened = this.enlightened;
1072 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
1073 // Add pieces positions + all squares reachable by moves (includes Zen):
1074 for (let x=0; x<this.size.x; x++) {
1075 for (let y=0; y<this.size.y; y++) {
1076 if (this.board[x][y] != "" && this.getColor(x, y) == this.playerColor)
1077 {
1078 this.enlightened[x][y] = true;
1079 this.getPotentialMovesFrom([x, y]).forEach(m => {
1080 this.enlightened[m.end.x][m.end.y] = true;
1081 });
1082 }
1083 }
1084 }
1085 if (this.epSquare)
1086 this.enlightEnpassant();
1087 }
1088
1089 // Include square of the en-passant capturing square:
1090 enlightEnpassant() {
1091 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
ceeac4e8
BA
1092 // TODO: (0, 0) is wrong, would need to place an attacker here...
1093 const steps = this.pieces(this.playerColor, 0, 0)["p"].attack[0].steps;
ca8a3993 1094 for (let step of steps) {
65203419 1095 const x = this.epSquare.x - step[0], //NOTE: epSquare.x not on edge
ca8a3993
BA
1096 y = this.getY(this.epSquare.y - step[1]);
1097 if (
1098 this.onBoard(x, y) &&
1099 this.getColor(x, y) == this.playerColor &&
1100 this.getPieceType(x, y) == "p"
1101 ) {
1102 this.enlightened[x][this.epSquare.y] = true;
1103 break;
1104 }
1105 }
1106 }
1107
1108 // Apply diff this.enlightened --> oldEnlightened on board
1109 graphUpdateEnlightened() {
1110 let chessboard =
1111 document.getElementById(this.containerId).querySelector(".chessboard");
1112 const r = chessboard.getBoundingClientRect();
1113 const pieceWidth = this.getPieceWidth(r.width);
1114 for (let x=0; x<this.size.x; x++) {
1115 for (let y=0; y<this.size.y; y++) {
1116 if (!this.enlightened[x][y] && this.oldEnlightened[x][y]) {
1117 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
1118 elt.classList.add("in-shadow");
1119 if (this.g_pieces[x][y])
1120 this.g_pieces[x][y].classList.add("hidden");
1121 }
1122 else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) {
1123 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
1124 elt.classList.remove("in-shadow");
1125 if (this.g_pieces[x][y])
1126 this.g_pieces[x][y].classList.remove("hidden");
1127 }
1128 }
1129 }
1130 }
1131
41534b92
BA
1132 //////////////
1133 // BASIC UTILS
1134
1135 get size() {
15106e82
BA
1136 return {
1137 x: 8,
1138 y: 8,
f55a0a67 1139 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
15106e82 1140 };
41534b92
BA
1141 }
1142
ca8a3993 1143 // Color of thing on square (i,j). '' if square is empty
41534b92 1144 getColor(i, j) {
15106e82
BA
1145 if (typeof i == "string")
1146 return i; //reserves
41534b92
BA
1147 return this.board[i][j].charAt(0);
1148 }
1149
15106e82 1150 static GetColorClass(c) {
bc2bc396
BA
1151 if (c == 'w')
1152 return "white";
1153 if (c == 'b')
1154 return "black";
24872b22 1155 return "other-color"; //unidentified color
15106e82
BA
1156 }
1157
ca8a3993 1158 // Piece on i,j. '' if square is empty
41534b92 1159 getPiece(i, j) {
15106e82
BA
1160 if (typeof j == "string")
1161 return j; //reserves
41534b92
BA
1162 return this.board[i][j].charAt(1);
1163 }
1164
cc2c7183 1165 // Piece type on square (i,j)
6b9320bb 1166 getPieceType(x, y, p) {
65cf1690 1167 if (!p)
6b9320bb 1168 p = this.getPiece(x, y);
ceeac4e8 1169 return this.pieces(this.getColor(x, y), x, y)[p].moveas || p;
6b9320bb
BA
1170 }
1171
1172 isKing(x, y, p) {
1173 if (!p)
1174 p = this.getPiece(x, y);
1175 if (!this.options["cannibal"])
1176 return p == 'k';
1177 return !!C.CannibalKings[p];
cc2c7183
BA
1178 }
1179
ceeac4e8
BA
1180 static GetOppTurn(color) {
1181 return (color == 'w' ? 'b' : 'w');
1182 }
1183
1184 // Get opponent color(s): may differ from turn (e.g. Checkered)
1185 getOppCols(color) {
41534b92
BA
1186 return (color == "w" ? "b" : "w");
1187 }
1188
41534b92
BA
1189 // Is (x,y) on the chessboard?
1190 onBoard(x, y) {
b99ce1fb
BA
1191 return (x >= 0 && x < this.size.x &&
1192 y >= 0 && y < this.size.y);
41534b92
BA
1193 }
1194
15106e82 1195 // Am I allowed to move thing at square x,y ?
41534b92 1196 canIplay(x, y) {
0c44c676 1197 return (this.playerColor == this.turn && this.getColor(x, y) == this.turn);
41534b92
BA
1198 }
1199
1200 ////////////////////////
1201 // PIECES SPECIFICATIONS
1202
5006aaca
BA
1203 getPawnShift(color) {
1204 return (color == "w" ? -1 : 1);
1205 }
65203419
BA
1206 isPawnInitRank(x, color) {
1207 return (color == 'w' && x >= 6) || (color == 'b' && x <= 1);
1208 }
5006aaca 1209
c9ab0340 1210 pieces(color, x, y) {
b8950be5 1211 const pawnShift = this.getPawnShift(color || 'w');
41534b92
BA
1212 return {
1213 'p': {
1214 "class": "pawn",
c9ab0340
BA
1215 moves: [
1216 {
1217 steps: [[pawnShift, 0]],
65203419 1218 range: (this.isPawnInitRank(x, color) ? 2 : 1)
c9ab0340
BA
1219 }
1220 ],
1221 attack: [
1222 {
1223 steps: [[pawnShift, 1], [pawnShift, -1]],
1224 range: 1
1225 }
1226 ]
41534b92 1227 },
41534b92
BA
1228 'r': {
1229 "class": "rook",
33b42748 1230 both: [
c9ab0340
BA
1231 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1232 ]
41534b92 1233 },
41534b92
BA
1234 'n': {
1235 "class": "knight",
33b42748 1236 both: [
c9ab0340
BA
1237 {
1238 steps: [
1239 [1, 2], [1, -2], [-1, 2], [-1, -2],
1240 [2, 1], [-2, 1], [2, -1], [-2, -1]
1241 ],
1242 range: 1
1243 }
1244 ]
41534b92 1245 },
41534b92
BA
1246 'b': {
1247 "class": "bishop",
33b42748 1248 both: [
c9ab0340
BA
1249 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1250 ]
41534b92 1251 },
41534b92
BA
1252 'q': {
1253 "class": "queen",
33b42748 1254 both: [
c9ab0340
BA
1255 {
1256 steps: [
1257 [0, 1], [0, -1], [1, 0], [-1, 0],
1258 [1, 1], [1, -1], [-1, 1], [-1, -1]
1259 ]
1260 }
41534b92
BA
1261 ]
1262 },
41534b92
BA
1263 'k': {
1264 "class": "king",
33b42748 1265 both: [
c9ab0340
BA
1266 {
1267 steps: [
1268 [0, 1], [0, -1], [1, 0], [-1, 0],
1269 [1, 1], [1, -1], [-1, 1], [-1, -1]
1270 ],
1271 range: 1
1272 }
1273 ]
cc2c7183
BA
1274 },
1275 // Cannibal kings:
c9ab0340
BA
1276 '!': {"class": "king-pawn", moveas: "p"},
1277 '#': {"class": "king-rook", moveas: "r"},
1278 '$': {"class": "king-knight", moveas: "n"},
1279 '%': {"class": "king-bishop", moveas: "b"},
1280 '*': {"class": "king-queen", moveas: "q"}
41534b92
BA
1281 };
1282 }
1283
af9c9be3
BA
1284 // NOTE: using special symbols to not interfere with variants' pieces codes
1285 static get CannibalKings() {
1286 return {
1287 "!": "p",
1288 "#": "r",
1289 "$": "n",
1290 "%": "b",
1291 "*": "q",
1292 "k": "k"
1293 };
1294 }
1295
1296 static get CannibalKingCode() {
1297 return {
1298 "p": "!",
1299 "r": "#",
1300 "n": "$",
1301 "b": "%",
1302 "q": "*",
1303 "k": "k"
1304 };
1305 }
1306
1307 //////////////////////////
1308 // MOVES GENERATION UTILS
41534b92 1309
adf7c659
BA
1310 // For Cylinder: get Y coordinate
1311 getY(y) {
b4ae3ff6
BA
1312 if (!this.options["cylinder"])
1313 return y;
41534b92 1314 let res = y % this.size.y;
b4ae3ff6 1315 if (res < 0)
adf7c659 1316 res += this.size.y;
41534b92
BA
1317 return res;
1318 }
65203419
BA
1319 // Circular?
1320 getX(x) {
1321 return x; //generally, no
1322 }
1323
1324 increment([x, y], step) {
1325 return [
1326 this.getX(x + step[0]),
1327 this.getY(y + step[1])
1328 ];
1329 }
41534b92 1330
ca8a3993
BA
1331 getSegments(curSeg, segStart, segEnd) {
1332 if (curSeg.length == 0)
1333 return undefined;
1334 let segments = JSON.parse(JSON.stringify(curSeg)); //not altering
1335 segments.push([[segStart[0], segStart[1]], [segEnd[0], segEnd[1]]]);
1336 return segments;
1337 }
1338
6b9320bb 1339 getStepSpec(color, x, y, piece) {
0e466aac 1340 let pieceType = piece;
33b42748 1341 let allSpecs = this.pieces(color, x, y);
0e466aac
BA
1342 if (!piece)
1343 pieceType = this.getPieceType(x, y);
1344 else if (allSpecs[piece].moveas)
1345 pieceType = allSpecs[piece].moveas;
33b42748
BA
1346 let res = allSpecs[pieceType];
1347 if (!res["both"])
1348 res.both = [];
1349 if (!res["moves"])
1350 res.moves = [];
1351 if (!res["attack"])
1352 res.attack = [];
1353 return res;
ca8a3993
BA
1354 }
1355
af9c9be3
BA
1356 // Can thing on square1 capture thing on square2?
1357 canTake([x1, y1], [x2, y2]) {
1358 return this.getColor(x1, y1) !== this.getColor(x2, y2);
1359 }
1360
de1421be 1361 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
727f2e55 1362 canSelfTake([x1, y1], [x2, y2]) {
de1421be 1363 return !this.isKing(x2, y2);
727f2e55
BA
1364 }
1365
af9c9be3
BA
1366 canStepOver(i, j, p) {
1367 // In some variants, objects on boards don't stop movement (Chakart)
1368 return this.board[i][j] == "";
1369 }
1370
ca8a3993
BA
1371 canDrop([c, p], [i, j]) {
1372 return (
1373 this.board[i][j] == "" &&
1374 (!this.enlightened || this.enlightened[i][j]) &&
1375 (
1376 p != "p" ||
1377 (c == 'w' && i < this.size.x - 1) ||
1378 (c == 'b' && i > 0)
1379 )
1380 );
1381 }
1382
af9c9be3
BA
1383 // For Madrasi:
1384 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1385 isImmobilized([x, y]) {
1386 if (!this.options["madrasi"])
1387 return false;
1388 const color = this.getColor(x, y);
ceeac4e8 1389 const oppCols = this.getOppCols(color);
6b9320bb
BA
1390 const piece = this.getPieceType(x, y);
1391 const stepSpec = this.getStepSpec(color, x, y, piece);
33b42748 1392 const attacks = stepSpec.both.concat(stepSpec.attack);
af9c9be3
BA
1393 for (let a of attacks) {
1394 outerLoop: for (let step of a.steps) {
65203419
BA
1395 let [i, j] = this.increment([x, y], step);
1396 let stepCounter = 0;
af9c9be3
BA
1397 while (this.onBoard(i, j) && this.board[i][j] == "") {
1398 if (a.range <= stepCounter++)
1399 continue outerLoop;
65203419 1400 [i, j] = this.increment([i, j], step);
af9c9be3
BA
1401 }
1402 if (
1403 this.onBoard(i, j) &&
ceeac4e8 1404 oppCols.includes(this.getColor(i, j)) &&
af9c9be3
BA
1405 this.getPieceType(i, j) == piece
1406 ) {
1407 return true;
1408 }
1409 }
1410 }
1411 return false;
1412 }
1413
41534b92
BA
1414 // Stop at the first capture found
1415 atLeastOneCapture(color) {
6b9320bb
BA
1416 const allowed = (sq1, sq2) => {
1417 return (
1418 // NOTE: canTake is reversed for Zen.
1419 // Generally ok because of the symmetry. TODO?
1420 this.canTake(sq1, sq2) &&
1421 this.filterValid(
1422 [this.getBasicMove(sq1, sq2)]).length >= 1
1423 );
af9c9be3
BA
1424 };
1425 for (let i=0; i<this.size.x; i++) {
1426 for (let j=0; j<this.size.y; j++) {
1427 if (this.getColor(i, j) == color) {
1428 if (
6b9320bb
BA
1429 (
1430 !this.options["zen"] &&
1431 this.findDestSquares(
1432 [i, j],
1433 {
1434 attackOnly: true,
1435 one: true,
6b9320bb
BA
1436 },
1437 allowed
1438 )
1439 )
1440 ||
1441 (
1442 (
1443 this.options["zen"] &&
1444 this.findCapturesOn(
1445 [i, j],
714ce6d8 1446 {one: true},
6b9320bb
BA
1447 allowed
1448 )
1449 )
1450 )
af9c9be3
BA
1451 ) {
1452 return true;
41534b92
BA
1453 }
1454 }
1455 }
1456 }
1457 return false;
1458 }
1459
af9c9be3 1460 compatibleStep([x1, y1], [x2, y2], step, range) {
6b9320bb 1461 const epsilon = 1e-7; //arbitrary small value
af9c9be3
BA
1462 let shifts = [0];
1463 if (this.options["cylinder"])
1464 Array.prototype.push.apply(shifts, [-this.size.y, this.size.y]);
1465 for (let sh of shifts) {
1466 const rx = (x2 - x1) / step[0],
1467 ry = (y2 + sh - y1) / step[1];
1468 if (
6b9320bb 1469 // Zero step but non-zero interval => impossible
af9c9be3 1470 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
6b9320bb
BA
1471 (!Number.isFinite(ry) && !Number.isNaN(ry)) ||
1472 // Negative number of step (impossible)
1473 (rx < 0 || ry < 0) ||
1474 // Not the same number of steps in both directions:
1475 (!Number.isNaN(rx) && !Number.isNaN(ry) && Math.abs(rx - ry) > epsilon)
af9c9be3
BA
1476 ) {
1477 continue;
1478 }
1479 let distance = (Number.isNaN(rx) ? ry : rx);
6b9320bb 1480 if (Math.abs(distance - Math.round(distance)) > epsilon)
af9c9be3
BA
1481 continue;
1482 distance = Math.round(distance); //in case of (numerical...)
6b9320bb 1483 if (!range || range >= distance)
af9c9be3
BA
1484 return true;
1485 }
1486 return false;
1487 }
1488
1489 ////////////////////
1490 // MOVES GENERATION
1491
41534b92
BA
1492 getDropMovesFrom([c, p]) {
1493 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1a7c0492 1494 // (but not necessarily otherwise: atLeastOneMove() etc)
b4ae3ff6
BA
1495 if (this.reserve[c][p] == 0)
1496 return [];
41534b92
BA
1497 let moves = [];
1498 for (let i=0; i<this.size.x; i++) {
1499 for (let j=0; j<this.size.y; j++) {
9b760538 1500 if (this.onBoard(i, j) && this.canDrop([c, p], [i, j])) {
ca8a3993
BA
1501 let mv = new Move({
1502 start: {x: c, y: p},
1503 end: {x: i, y: j},
1504 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1505 vanish: []
1506 });
1507 if (this.board[i][j] != "") {
1508 mv.vanish.push(new PiPo({
1509 x: i,
1510 y: j,
1511 c: this.getColor(i, j),
1512 p: this.getPiece(i, j)
1513 }));
1514 }
1515 moves.push(mv);
41534b92
BA
1516 }
1517 }
1518 }
1519 return moves;
1520 }
1521
1522 // All possible moves from selected square
de1421be 1523 // TODO: generalize usage if arg "color" (e.g. Checkered)
ca8a3993 1524 getPotentialMovesFrom([x, y], color) {
8b301184
BA
1525 if (this.subTurnTeleport == 2)
1526 return [];
ca8a3993
BA
1527 if (typeof x == "string")
1528 return this.getDropMovesFrom([x, y]);
1529 if (this.isImmobilized([x, y]))
b4ae3ff6 1530 return [];
ca8a3993
BA
1531 const piece = this.getPieceType(x, y);
1532 let moves = this.getPotentialMovesOf(piece, [x, y]);
1533 if (piece == "p" && this.hasEnpassant && this.epSquare)
1534 Array.prototype.push.apply(moves, this.getEnpassantCaptures([x, y]));
dcfaab5d 1535 if (this.isKing(0, 0, piece) && this.hasCastle)
ca8a3993 1536 Array.prototype.push.apply(moves, this.getCastleMoves([x, y]));
41534b92
BA
1537 return this.postProcessPotentialMoves(moves);
1538 }
1539
1540 postProcessPotentialMoves(moves) {
b4ae3ff6
BA
1541 if (moves.length == 0)
1542 return [];
41534b92 1543 const color = this.getColor(moves[0].start.x, moves[0].start.y);
ceeac4e8 1544 const oppCols = this.getOppCols(color);
41534b92 1545
6b9320bb 1546 if (this.options["capture"] && this.atLeastOneCapture(color))
ceeac4e8 1547 moves = this.capturePostProcess(moves, oppCols);
41534b92 1548
57b8015b 1549 if (this.options["atomic"])
ceeac4e8 1550 moves = this.atomicPostProcess(moves, color, oppCols);
cc2c7183 1551
c9ab0340
BA
1552 if (
1553 moves.length > 0 &&
1554 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1555 ) {
ceeac4e8 1556 moves = this.pawnPostProcess(moves, color, oppCols);
c9ab0340
BA
1557 }
1558
6b9320bb 1559 if (this.options["cannibal"] && this.options["rifle"])
cc2c7183 1560 // In this case a rifle-capture from last rank may promote a pawn
98d14451 1561 moves = this.riflePromotePostProcess(moves, color);
57b8015b
BA
1562
1563 return moves;
1564 }
1565
ceeac4e8 1566 capturePostProcess(moves, oppCols) {
57b8015b
BA
1567 // Filter out non-capturing moves (not using m.vanish because of
1568 // self captures of Recycle and Teleport).
1569 return moves.filter(m => {
1570 return (
1571 this.board[m.end.x][m.end.y] != "" &&
ceeac4e8 1572 oppCols.includes(this.getColor(m.end.x, m.end.y))
57b8015b
BA
1573 );
1574 });
1575 }
1576
ceeac4e8 1577 atomicPostProcess(moves, color, oppCols) {
57b8015b
BA
1578 moves.forEach(m => {
1579 if (
1580 this.board[m.end.x][m.end.y] != "" &&
ceeac4e8 1581 oppCols.includes(this.getColor(m.end.x, m.end.y))
57b8015b
BA
1582 ) {
1583 // Explosion!
1584 let steps = [
1585 [-1, -1],
1586 [-1, 0],
1587 [-1, 1],
1588 [0, -1],
1589 [0, 1],
1590 [1, -1],
1591 [1, 0],
1592 [1, 1]
1593 ];
e7d409fc
BA
1594 let mNext = new Move({
1595 start: m.end,
1596 end: m.end,
1597 appear: [],
1598 vanish: []
1599 });
57b8015b 1600 for (let step of steps) {
65203419 1601 let [x, y] = this.increment([m.end.x, m.end.y], step);
57b8015b
BA
1602 if (
1603 this.onBoard(x, y) &&
1604 this.board[x][y] != "" &&
e7d409fc 1605 (x != m.start.x || y != m.start.y) &&
57b8015b
BA
1606 this.getPieceType(x, y) != "p"
1607 ) {
e7d409fc 1608 mNext.vanish.push(
57b8015b
BA
1609 new PiPo({
1610 p: this.getPiece(x, y),
1611 c: this.getColor(x, y),
1612 x: x,
1613 y: y
1614 })
1615 );
1616 }
1617 }
e7d409fc
BA
1618 if (!this.options["rifle"]) {
1619 // The moving piece also vanish
1620 mNext.vanish.unshift(
1621 new PiPo({
1622 x: m.end.x,
1623 y: m.end.y,
1624 c: color,
1625 p: this.getPiece(m.start.x, m.start.y)
1626 })
1627 );
1628 }
1629 m.next = mNext;
57b8015b
BA
1630 }
1631 });
98d14451 1632 return moves;
57b8015b
BA
1633 }
1634
ceeac4e8 1635 pawnPostProcess(moves, color, oppCols) {
57b8015b
BA
1636 let moreMoves = [];
1637 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1638 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1639 moves.forEach(m => {
57b8015b
BA
1640 const [x1, y1] = [m.start.x, m.start.y];
1641 const [x2, y2] = [m.end.x, m.end.y];
1642 const promotionOk = (
1643 x2 == lastRank &&
1644 (!this.options["rifle"] || this.board[x2][y2] == "")
1645 );
1646 if (!promotionOk)
1647 return; //nothing to do
8cc2f6d0
BA
1648 if (this.options["pawnfall"]) {
1649 m.appear.shift();
8cc2f6d0
BA
1650 return;
1651 }
9ac67217 1652 let finalPieces;
99ea2453
BA
1653 if (
1654 this.options["cannibal"] &&
1655 this.board[x2][y2] != "" &&
ceeac4e8 1656 oppCols.includes(this.getColor(x2, y2))
99ea2453
BA
1657 ) {
1658 finalPieces = [this.getPieceType(x2, y2)];
1659 }
1660 else
1661 finalPieces = this.pawnPromotions;
57b8015b
BA
1662 m.appear[0].p = finalPieces[0];
1663 if (initPiece == "!") //cannibal king-pawn
1664 m.appear[0].p = C.CannibalKingCode[finalPieces[0]];
1665 for (let i=1; i<finalPieces.length; i++) {
9ac67217 1666 let newMove = JSON.parse(JSON.stringify(m));
57b8015b 1667 const piece = finalPieces[i];
9ac67217 1668 m.appear[0].p = (initPiece != "!" ? piece : C.CannibalKingCode[piece]);
57b8015b
BA
1669 moreMoves.push(newMove);
1670 }
1671 });
98d14451 1672 return moves.concat(moreMoves);
57b8015b 1673 }
cc2c7183 1674
9db5050a 1675 riflePromotePostProcess(moves, color) {
57b8015b
BA
1676 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1677 let newMoves = [];
1678 moves.forEach(m => {
1679 if (
1680 m.start.x == lastRank &&
1681 m.appear.length >= 1 &&
1682 m.appear[0].p == "p" &&
1683 m.appear[0].x == m.start.x &&
1684 m.appear[0].y == m.start.y
1685 ) {
57b8015b
BA
1686 m.appear[0].p = this.pawnPromotions[0];
1687 for (let i=1; i<this.pawnPromotions.length; i++) {
1688 let newMv = JSON.parse(JSON.stringify(m));
65203419 1689 newMv.appear[0].p = this.pawnPromotions[i];
57b8015b
BA
1690 newMoves.push(newMv);
1691 }
1692 }
1693 });
98d14451 1694 return moves.concat(newMoves);
41534b92
BA
1695 }
1696
af9c9be3 1697 // Generic method to find possible moves of "sliding or jumping" pieces
6b9320bb 1698 getPotentialMovesOf(piece, [x, y]) {
41534b92 1699 const color = this.getColor(x, y);
6b9320bb 1700 const stepSpec = this.getStepSpec(color, x, y, piece);
af9c9be3 1701 let squares = [];
6b9320bb 1702 if (stepSpec.attack) {
af9c9be3
BA
1703 squares = this.findDestSquares(
1704 [x, y],
1705 {
1706 attackOnly: true,
6b9320bb 1707 stepSpec: stepSpec
af9c9be3 1708 },
6b9320bb 1709 ([i1, j1], [i2, j2]) => {
af9c9be3 1710 return (
6b9320bb
BA
1711 (!this.options["zen"] || this.isKing(i2, j2)) &&
1712 this.canTake([i1, j1], [i2, j2])
af9c9be3 1713 );
c9ab0340 1714 }
af9c9be3
BA
1715 );
1716 }
1717 const noSpecials = this.findDestSquares(
1718 [x, y],
1719 {
6b9320bb 1720 moveOnly: !!stepSpec.attack || this.options["zen"],
6b9320bb
BA
1721 stepSpec: stepSpec
1722 }
af9c9be3
BA
1723 );
1724 Array.prototype.push.apply(squares, noSpecials);
1725 if (this.options["zen"]) {
1726 let zenCaptures = this.findCapturesOn(
1727 [x, y],
6b9320bb
BA
1728 {}, //byCol: default is ok
1729 ([i1, j1], [i2, j2]) =>
1730 !this.isKing(i1, j1) && this.canTake([i2, j2], [i1, j1])
af9c9be3
BA
1731 );
1732 // Technical step: segments (if any) are reversed
714ce6d8
BA
1733 zenCaptures.forEach(z => {
1734 if (!!z.segments)
ca8a3993 1735 z.segments = z.segments.reverse().map(s => s.reverse())
714ce6d8 1736 });
af9c9be3 1737 Array.prototype.push.apply(squares, zenCaptures);
41534b92 1738 }
b98feb3f 1739 if (this.hasSelfCaptures) {
af9c9be3
BA
1740 const selfCaptures = this.findDestSquares(
1741 [x, y],
1742 {
1743 attackOnly: true,
6b9320bb 1744 stepSpec: stepSpec
af9c9be3 1745 },
de1421be
BA
1746 ([i1, j1], [i2, j2]) => {
1747 return (
1748 this.getColor(i2, j2) == color &&
1749 this.canSelfTake([i1, j1], [i2, j2])
1750 );
1751 }
af9c9be3
BA
1752 );
1753 Array.prototype.push.apply(squares, selfCaptures);
1754 }
1755 return squares.map(s => {
1756 let mv = this.getBasicMove([x, y], s.sq);
714ce6d8 1757 if (!!s.segments)
af9c9be3
BA
1758 mv.segments = s.segments;
1759 return mv;
1760 });
3b641716
BA
1761 }
1762
af9c9be3
BA
1763 findDestSquares([x, y], o, allowed) {
1764 if (!allowed)
6b9320bb 1765 allowed = (sq1, sq2) => this.canTake(sq1, sq2);
65cf1690 1766 const apparentPiece = this.getPiece(x, y); //how it looks
af9c9be3 1767 let res = [];
714ce6d8 1768 // Next 3 for Cylinder mode or circular (useless otherwise)
adf7c659
BA
1769 let explored = {};
1770 let segments = [];
1771 let segStart = [];
af9c9be3
BA
1772 const addSquare = ([i, j]) => {
1773 let elt = {sq: [i, j]};
714ce6d8 1774 if (segments.length >= 1)
727f2e55 1775 elt.segments = this.getSegments(segments, segStart, [i, j]);
af9c9be3 1776 res.push(elt);
adf7c659 1777 };
33b42748 1778 const exploreSteps = (stepArray, mode) => {
c9ab0340
BA
1779 for (let s of stepArray) {
1780 outerLoop: for (let step of s.steps) {
714ce6d8
BA
1781 segments = [];
1782 segStart = [x, y];
d262cff4
BA
1783 let [i, j] = [x, y];
1784 let stepCounter = 0;
1785 while (
1786 this.onBoard(i, j) &&
65cf1690 1787 ((i == x && j == y) || this.canStepOver(i, j, apparentPiece))
d262cff4 1788 ) {
6b9320bb 1789 if (!explored[i + "." + j] && (i != x || j != y)) {
c9ab0340 1790 explored[i + "." + j] = true;
af9c9be3 1791 if (
6b9320bb
BA
1792 !o.captureTarget ||
1793 (o.captureTarget[0] == i && o.captureTarget[1] == j)
af9c9be3 1794 ) {
33b42748 1795 if (o.one && mode != "attack")
af9c9be3 1796 return true;
33b42748 1797 if (mode != "attack")
af9c9be3
BA
1798 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1799 if (o.captureTarget)
1800 return res[0];
1801 }
c9ab0340
BA
1802 }
1803 if (s.range <= stepCounter++)
1804 continue outerLoop;
d262cff4 1805 const oldIJ = [i, j];
65203419 1806 [i, j] = this.increment([i, j], step);
c08a5e74
BA
1807 if (
1808 Math.abs(i - oldIJ[0]) != Math.abs(step[0]) ||
1809 Math.abs(j - oldIJ[1]) != Math.abs(step[1])
1810 ) {
714ce6d8 1811 // Boundary between segments (cylinder or circular mode)
adf7c659
BA
1812 segments.push([[segStart[0], segStart[1]], oldIJ]);
1813 segStart = [i, j];
d262cff4 1814 }
c9ab0340
BA
1815 }
1816 if (!this.onBoard(i, j))
1817 continue;
1818 const pieceIJ = this.getPieceType(i, j);
af9c9be3 1819 if (!explored[i + "." + j]) {
c9ab0340 1820 explored[i + "." + j] = true;
6b9320bb 1821 if (allowed([x, y], [i, j])) {
33b42748 1822 if (o.one && mode != "moves")
af9c9be3 1823 return true;
33b42748 1824 if (mode != "moves")
af9c9be3
BA
1825 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1826 if (
1827 o.captureTarget &&
1828 o.captureTarget[0] == i && o.captureTarget[1] == j
1829 ) {
1830 return res[0];
1831 }
1832 }
c9ab0340
BA
1833 }
1834 }
41534b92 1835 }
6b9320bb 1836 return undefined; //default, but let's explicit it
c9ab0340 1837 };
af9c9be3 1838 if (o.captureTarget)
33b42748 1839 return exploreSteps(o.captureSteps, "attack");
af9c9be3 1840 else {
6b9320bb
BA
1841 const stepSpec =
1842 o.stepSpec || this.getStepSpec(this.getColor(x, y), x, y);
1843 let outOne = false;
33b42748
BA
1844 if (!o.attackOnly)
1845 outOne = exploreSteps(stepSpec.both.concat(stepSpec.moves), "moves");
1846 if (!outOne && !o.moveOnly)
1847 outOne = exploreSteps(stepSpec.both.concat(stepSpec.attack), "attack");
6b9320bb 1848 return (o.one ? outOne : res);
082e639a 1849 }
41534b92
BA
1850 }
1851
082e639a 1852 // Search for enemy (or not) pieces attacking [x, y]
af9c9be3 1853 findCapturesOn([x, y], o, allowed) {
af9c9be3 1854 if (!o.byCol)
ceeac4e8 1855 o.byCol = this.getOppCols(this.getColor(x, y) || this.turn);
ca8a3993 1856 let res = [];
c9ab0340
BA
1857 for (let i=0; i<this.size.x; i++) {
1858 for (let j=0; j<this.size.y; j++) {
af9c9be3 1859 const colIJ = this.getColor(i, j);
57b8015b
BA
1860 if (
1861 this.board[i][j] != "" &&
af9c9be3 1862 o.byCol.includes(colIJ) &&
57b8015b
BA
1863 !this.isImmobilized([i, j])
1864 ) {
65cf1690
BA
1865 const apparentPiece = this.getPiece(i, j);
1866 // Quick check: does this potential attacker target x,y ?
1867 if (this.canStepOver(x, y, apparentPiece))
1868 continue;
af9c9be3 1869 const stepSpec = this.getStepSpec(colIJ, i, j);
33b42748 1870 const attacks = stepSpec.attack.concat(stepSpec.both);
c9ab0340
BA
1871 for (let a of attacks) {
1872 for (let s of a.steps) {
1873 // Quick check: if step isn't compatible, don't even try
af9c9be3 1874 if (!this.compatibleStep([i, j], [x, y], s, a.range))
c9ab0340
BA
1875 continue;
1876 // Finally verify that nothing stand in-between
6b9320bb 1877 const out = this.findDestSquares(
af9c9be3
BA
1878 [i, j],
1879 {
1880 captureTarget: [x, y],
1881 captureSteps: [{steps: [s], range: a.range}],
af9c9be3 1882 },
6b9320bb 1883 allowed
af9c9be3 1884 );
6b9320bb 1885 if (out) {
af9c9be3
BA
1886 if (o.one)
1887 return true;
6b9320bb 1888 res.push(out);
c9ab0340
BA
1889 }
1890 }
1891 }
41534b92 1892 }
c9ab0340
BA
1893 }
1894 }
6b9320bb 1895 return (o.one ? false : res);
57b8015b
BA
1896 }
1897
41534b92
BA
1898 // Build a regular move from its initial and destination squares.
1899 // tr: transformation
1900 getBasicMove([sx, sy], [ex, ey], tr) {
1901 const initColor = this.getColor(sx, sy);
cc2c7183 1902 const initPiece = this.getPiece(sx, sy);
41534b92
BA
1903 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1904 let mv = new Move({
1905 appear: [],
1906 vanish: [],
15106e82
BA
1907 start: {x: sx, y: sy},
1908 end: {x: ex, y: ey}
41534b92
BA
1909 });
1910 if (
1911 !this.options["rifle"] ||
1912 this.board[ex][ey] == "" ||
1913 destColor == initColor //Recycle, Teleport
1914 ) {
1915 mv.appear = [
1916 new PiPo({
1917 x: ex,
1918 y: ey,
1919 c: !!tr ? tr.c : initColor,
1920 p: !!tr ? tr.p : initPiece
1921 })
1922 ];
1923 mv.vanish = [
1924 new PiPo({
1925 x: sx,
1926 y: sy,
1927 c: initColor,
1928 p: initPiece
1929 })
1930 ];
1931 }
1932 if (this.board[ex][ey] != "") {
1933 mv.vanish.push(
1934 new PiPo({
1935 x: ex,
1936 y: ey,
1937 c: this.getColor(ex, ey),
cc2c7183 1938 p: this.getPiece(ex, ey)
41534b92
BA
1939 })
1940 );
41534b92 1941 if (this.options["cannibal"] && destColor != initColor) {
6b9320bb 1942 const lastIdx = mv.vanish.length - 1; //think "Rifle+Cannibal"
cc2c7183 1943 let trPiece = mv.vanish[lastIdx].p;
6b9320bb 1944 if (this.isKing(sx, sy))
cc2c7183 1945 trPiece = C.CannibalKingCode[trPiece];
b4ae3ff6
BA
1946 if (mv.appear.length >= 1)
1947 mv.appear[0].p = trPiece;
41534b92
BA
1948 else if (this.options["rifle"]) {
1949 mv.appear.unshift(
1950 new PiPo({
1951 x: sx,
1952 y: sy,
1953 c: initColor,
cc2c7183 1954 p: trPiece
41534b92
BA
1955 })
1956 );
1957 mv.vanish.unshift(
1958 new PiPo({
1959 x: sx,
1960 y: sy,
1961 c: initColor,
1962 p: initPiece
1963 })
1964 );
1965 }
1966 }
1967 }
1968 return mv;
1969 }
1970
1971 // En-passant square, if any
1972 getEpSquare(moveOrSquare) {
1973 if (typeof moveOrSquare === "string") {
1974 const square = moveOrSquare;
b4ae3ff6
BA
1975 if (square == "-")
1976 return undefined;
cc2c7183 1977 return C.SquareToCoords(square);
41534b92
BA
1978 }
1979 // Argument is a move:
1980 const move = moveOrSquare;
1981 const s = move.start,
1982 e = move.end;
1983 if (
1984 s.y == e.y &&
1985 Math.abs(s.x - e.x) == 2 &&
1986 // Next conditions for variants like Atomic or Rifle, Recycle...
65cf1690
BA
1987 (
1988 move.appear.length > 0 &&
ca8a3993 1989 this.getPieceType(0, 0, move.appear[0].p) == 'p'
65cf1690
BA
1990 )
1991 &&
1992 (
1993 move.vanish.length > 0 &&
ca8a3993 1994 this.getPieceType(0, 0, move.vanish[0].p) == 'p'
65cf1690 1995 )
41534b92
BA
1996 ) {
1997 return {
1998 x: (s.x + e.x) / 2,
1999 y: s.y
2000 };
2001 }
2002 return undefined; //default
2003 }
2004
2005 // Special case of en-passant captures: treated separately
c9ab0340 2006 getEnpassantCaptures([x, y]) {
41534b92 2007 const color = this.getColor(x, y);
c9ab0340 2008 const shiftX = (color == 'w' ? -1 : 1);
ceeac4e8 2009 const oppCols = this.getOppCols(color);
41534b92 2010 if (
ca8a3993 2011 this.epSquare &&
65203419 2012 this.epSquare.x == x + shiftX && //NOTE: epSquare.x not on edge
d262cff4 2013 Math.abs(this.getY(this.epSquare.y - y)) == 1 &&
ca8a3993
BA
2014 // Doublemove (and Progressive?) guards:
2015 this.board[this.epSquare.x][this.epSquare.y] == "" &&
ceeac4e8 2016 oppCols.includes(this.getColor(x, this.epSquare.y))
41534b92
BA
2017 ) {
2018 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
b57b726c 2019 this.board[epx][epy] = this.board[x][this.epSquare.y];
ca8a3993 2020 let enpassantMove = this.getBasicMove([x, y], [epx, epy]);
41534b92
BA
2021 this.board[epx][epy] = "";
2022 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
2023 enpassantMove.vanish[lastIdx].x = x;
ca8a3993 2024 return [enpassantMove];
41534b92 2025 }
ca8a3993 2026 return [];
41534b92
BA
2027 }
2028
dcfaab5d 2029 getCastleMoves([x, y], finalSquares, castleWith, castleFlags) {
41534b92 2030 const c = this.getColor(x, y);
dcfaab5d 2031 castleFlags = castleFlags || this.castleFlags[c];
41534b92
BA
2032
2033 // Castling ?
ceeac4e8 2034 const oppCols = this.getOppCols(c);
41534b92
BA
2035 let moves = [];
2036 // King, then rook:
2037 finalSquares =
2038 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
cc2c7183 2039 const castlingKing = this.getPiece(x, y);
41534b92
BA
2040 castlingCheck: for (
2041 let castleSide = 0;
2042 castleSide < 2;
2043 castleSide++ //large, then small
2044 ) {
dcfaab5d 2045 if (castleFlags[castleSide] >= this.size.y)
b4ae3ff6 2046 continue;
41534b92
BA
2047 // If this code is reached, rook and king are on initial position
2048
2049 // NOTE: in some variants this is not a rook
dcfaab5d 2050 const rookPos = castleFlags[castleSide];
cc2c7183 2051 const castlingPiece = this.getPiece(x, rookPos);
41534b92
BA
2052 if (
2053 this.board[x][rookPos] == "" ||
2054 this.getColor(x, rookPos) != c ||
ca8a3993 2055 (castleWith && !castleWith.includes(castlingPiece))
41534b92
BA
2056 ) {
2057 // Rook is not here, or changed color (see Benedict)
2058 continue;
2059 }
2060 // Nothing on the path of the king ? (and no checks)
2061 const finDist = finalSquares[castleSide][0] - y;
2062 let step = finDist / Math.max(1, Math.abs(finDist));
2063 let i = y;
2064 do {
2065 if (
ca8a3993
BA
2066 // NOTE: next weird test because underCheck() verification
2067 // will be executed in filterValid() later.
2068 (
2069 i != finalSquares[castleSide][0] &&
ceeac4e8 2070 this.underCheck([[x, i]], oppCols)
ca8a3993
BA
2071 )
2072 ||
41534b92
BA
2073 (
2074 this.board[x][i] != "" &&
2075 // NOTE: next check is enough, because of chessboard constraints
2076 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
2077 )
2078 ) {
2079 continue castlingCheck;
2080 }
2081 i += step;
2082 } while (i != finalSquares[castleSide][0]);
2083 // Nothing on the path to the rook?
2084 step = (castleSide == 0 ? -1 : 1);
2085 for (i = y + step; i != rookPos; i += step) {
b4ae3ff6
BA
2086 if (this.board[x][i] != "")
2087 continue castlingCheck;
41534b92
BA
2088 }
2089
2090 // Nothing on final squares, except maybe king and castling rook?
2091 for (i = 0; i < 2; i++) {
2092 if (
2093 finalSquares[castleSide][i] != rookPos &&
2094 this.board[x][finalSquares[castleSide][i]] != "" &&
2095 (
2096 finalSquares[castleSide][i] != y ||
2097 this.getColor(x, finalSquares[castleSide][i]) != c
2098 )
2099 ) {
2100 continue castlingCheck;
2101 }
2102 }
2103
ca8a3993 2104 // If this code is reached, castle is potentially valid
41534b92
BA
2105 moves.push(
2106 new Move({
2107 appear: [
2108 new PiPo({
2109 x: x,
2110 y: finalSquares[castleSide][0],
2111 p: castlingKing,
2112 c: c
2113 }),
2114 new PiPo({
2115 x: x,
2116 y: finalSquares[castleSide][1],
2117 p: castlingPiece,
2118 c: c
2119 })
2120 ],
2121 vanish: [
2122 // King might be initially disguised (Titan...)
2123 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
2124 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
2125 ],
2126 end:
2127 Math.abs(y - rookPos) <= 2
c9ab0340
BA
2128 ? {x: x, y: rookPos}
2129 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
41534b92
BA
2130 })
2131 );
2132 }
2133
2134 return moves;
2135 }
2136
2137 ////////////////////
2138 // MOVES VALIDATION
2139
5006aaca 2140 // Is piece (or square) at given position attacked by "oppCol(s)" ?
ceeac4e8 2141 underAttack([x, y], oppCols) {
6b9320bb
BA
2142 // An empty square is considered as king,
2143 // since it's used only in getCastleMoves (TODO?)
2144 const king = this.board[x][y] == "" || this.isKing(x, y);
af9c9be3
BA
2145 return (
2146 (
2147 (!this.options["zen"] || king) &&
6b9320bb
BA
2148 this.findCapturesOn(
2149 [x, y],
2150 {
ceeac4e8 2151 byCol: oppCols,
6b9320bb
BA
2152 one: true
2153 }
2154 )
af9c9be3
BA
2155 )
2156 ||
2157 (
6b9320bb
BA
2158 (!!this.options["zen"] && !king) &&
2159 this.findDestSquares(
2160 [x, y],
2161 {
2162 attackOnly: true,
6b9320bb
BA
2163 one: true
2164 },
ceeac4e8 2165 ([i1, j1], [i2, j2]) => oppCols.includes(this.getColor(i2, j2))
6b9320bb 2166 )
af9c9be3
BA
2167 )
2168 );
2169 }
2170
f3e90e30 2171 // Argument is (very generally) an array of squares (= arrays)
ceeac4e8 2172 underCheck(square_s, oppCols) {
b4ae3ff6
BA
2173 if (this.options["taking"] || this.options["dark"])
2174 return false;
ceeac4e8 2175 return square_s.some(sq => this.underAttack(sq, oppCols));
41534b92
BA
2176 }
2177
a548cb4e 2178 // Scan board for king(s)
41534b92 2179 searchKingPos(color) {
a548cb4e 2180 let res = [];
41534b92
BA
2181 for (let i=0; i < this.size.x; i++) {
2182 for (let j=0; j < this.size.y; j++) {
6b9320bb 2183 if (this.getColor(i, j) == color && this.isKing(i, j))
a548cb4e 2184 res.push([i, j]);
41534b92
BA
2185 }
2186 }
a548cb4e 2187 return res;
41534b92
BA
2188 }
2189
de1421be
BA
2190 // cb: callback returning a boolean (false if king missing)
2191 trackKingWrap(move, kingPos, cb) {
f57232cd
BA
2192 if (move.appear.length == 0 && move.vanish.length == 0)
2193 return true;
2194 const color =
2195 (move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c);
de1421be
BA
2196 let newKingPP = null,
2197 sqIdx = 0,
2198 res = true; //a priori valid
2199 const oldKingPP =
2200 move.vanish.find(v => this.isKing(0, 0, v.p) && v.c == color);
2201 if (oldKingPP) {
2202 // Search king in appear array:
2203 newKingPP =
2204 move.appear.find(a => this.isKing(0, 0, a.p) && a.c == color);
2205 if (newKingPP) {
2206 sqIdx = kingPos.findIndex(kp =>
2207 kp[0] == oldKingPP.x && kp[1] == oldKingPP.y);
2208 kingPos[sqIdx] = [newKingPP.x, newKingPP.y];
2209 }
2210 else
2211 res = false; //king vanished
2212 }
2213 res &&= cb(kingPos);
2214 if (oldKingPP && newKingPP)
2215 kingPos[sqIdx] = [oldKingPP.x, oldKingPP.y];
2216 return res;
2217 }
2218
af9c9be3 2219 // 'color' arg because some variants (e.g. Refusal) check opponent moves
f5435757 2220 filterValid(moves, color) {
f5435757
BA
2221 if (!color)
2222 color = this.turn;
ceeac4e8 2223 const oppCols = this.getOppCols(color);
a548cb4e 2224 let kingPos = this.searchKingPos(color);
41534b92 2225 return moves.filter(m => {
b57b726c 2226 this.playOnBoard(m);
de1421be
BA
2227 const res = this.trackKingWrap(m, kingPos, (kp) => {
2228 return !this.underCheck(kp, oppCols);
2229 });
b57b726c
BA
2230 this.undoOnBoard(m);
2231 return res;
41534b92
BA
2232 });
2233 }
2234
2235 /////////////////
2236 // MOVES PLAYING
2237
41534b92
BA
2238 // Apply a move on board
2239 playOnBoard(move) {
6997e386
BA
2240 for (let psq of move.vanish)
2241 this.board[psq.x][psq.y] = "";
2242 for (let psq of move.appear)
2243 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
2244 }
2245 // Un-apply the played move
2246 undoOnBoard(move) {
6997e386
BA
2247 for (let psq of move.appear)
2248 this.board[psq.x][psq.y] = "";
2249 for (let psq of move.vanish)
2250 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
2251 }
2252
dcfaab5d 2253 // NOTE: arg "castleFlags" for Coregal or Twokings
3ca47832 2254 updateCastleFlags(move, castleFlags, king) {
dcfaab5d
BA
2255 castleFlags = castleFlags || this.castleFlags;
2256 // If flags already off, no need to re-check:
2257 if (
2258 Object.values(castleFlags).every(cvals =>
2259 cvals.every(val => val >= this.size.y))
2260 ) {
2261 return;
2262 }
41534b92
BA
2263 // Update castling flags if start or arrive from/at rook/king locations
2264 move.appear.concat(move.vanish).forEach(psq => {
8f879623 2265 if ((king && psq.p == king) || (!king && this.isKing(0, 0, psq.p)))
dcfaab5d 2266 castleFlags[psq.c] = [this.size.y, this.size.y];
41534b92 2267 // NOTE: not "else if" because king can capture enemy rook...
cc2c7183 2268 let c = "";
b4ae3ff6
BA
2269 if (psq.x == 0)
2270 c = "b";
2271 else if (psq.x == this.size.x - 1)
2272 c = "w";
cc2c7183 2273 if (c != "") {
dcfaab5d 2274 const fidx = castleFlags[c].findIndex(f => f == psq.y);
b4ae3ff6 2275 if (fidx >= 0)
dcfaab5d 2276 castleFlags[c][fidx] = this.size.y;
41534b92
BA
2277 }
2278 });
2279 }
2280
2281 prePlay(move) {
dcfaab5d 2282 if (this.hasCastle)
99ea2453 2283 this.updateCastleFlags(move);
99ea2453
BA
2284 if (this.options["crazyhouse"]) {
2285 move.vanish.forEach(v => {
2286 const square = C.CoordsToSquare({x: v.x, y: v.y});
2287 if (this.ispawn[square])
2288 delete this.ispawn[square];
2289 });
2290 if (move.appear.length > 0 && move.vanish.length > 0) {
2291 // Assumption: something is moving
2292 const initSquare = C.CoordsToSquare(move.start);
f429756d 2293 const destSquare = C.CoordsToSquare(move.end);
99ea2453
BA
2294 if (
2295 this.ispawn[initSquare] ||
ca8a3993 2296 (move.vanish[0].p == 'p' && move.appear[0].p != 'p')
41534b92 2297 ) {
f429756d
BA
2298 this.ispawn[destSquare] = true;
2299 }
2300 else if (
2301 this.ispawn[destSquare] &&
2302 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
2303 ) {
ca8a3993 2304 move.vanish[1].p = 'p';
f429756d 2305 delete this.ispawn[destSquare];
41534b92
BA
2306 }
2307 }
2308 }
2309 const minSize = Math.min(move.appear.length, move.vanish.length);
0c44c676
BA
2310 if (
2311 this.hasReserve &&
2312 // Warning; atomic pawn removal isn't a capture
2313 (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1)
2314 ) {
41534b92
BA
2315 const color = this.turn;
2316 for (let i=minSize; i<move.appear.length; i++) {
2317 // Something appears = dropped on board (some exceptions, Chakart...)
0c44c676
BA
2318 if (move.appear[i].c == color) {
2319 const piece = move.appear[i].p;
2320 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
2321 }
41534b92
BA
2322 }
2323 for (let i=minSize; i<move.vanish.length; i++) {
2324 // Something vanish: add to reserve except if recycle & opponent
0c44c676
BA
2325 if (
2326 this.options["crazyhouse"] ||
2327 (this.options["recycle"] && move.vanish[i].c == color)
2328 ) {
2329 const piece = move.vanish[i].p;
41534b92 2330 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
0c44c676 2331 }
41534b92
BA
2332 }
2333 }
2334 }
2335
2336 play(move) {
2337 this.prePlay(move);
b4ae3ff6
BA
2338 if (this.hasEnpassant)
2339 this.epSquare = this.getEpSquare(move);
41534b92
BA
2340 this.playOnBoard(move);
2341 this.postPlay(move);
2342 }
2343
2344 postPlay(move) {
b4ae3ff6 2345 if (this.options["dark"])
c9ab0340 2346 this.updateEnlightened();
41534b92
BA
2347 if (this.options["teleport"]) {
2348 if (
cc2c7183 2349 this.subTurnTeleport == 1 &&
52127581
BA
2350 move.vanish.length == 2 &&
2351 move.appear.length == 1 &&
518bfb7a 2352 move.vanish[1].c == this.turn
41534b92 2353 ) {
52127581 2354 const v = move.vanish[1];
41534b92 2355 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
cc2c7183 2356 this.subTurnTeleport = 2;
41534b92
BA
2357 return;
2358 }
cc2c7183 2359 this.subTurnTeleport = 1;
41534b92
BA
2360 this.captured = null;
2361 }
182ba661
BA
2362 this.tryChangeTurn(move);
2363 }
2364
2365 tryChangeTurn(move) {
5f08c59b 2366 if (this.isLastMove(move)) {
bc97fdd1 2367 this.turn = C.GetOppTurn(this.turn);
5f08c59b
BA
2368 this.movesCount++;
2369 this.subTurn = 1;
41534b92 2370 }
af9c9be3
BA
2371 else if (!move.next)
2372 this.subTurn++;
5f08c59b
BA
2373 }
2374
2375 isLastMove(move) {
af9c9be3
BA
2376 if (move.next)
2377 return false;
2378 const color = this.turn;
ceeac4e8
BA
2379 const oppKingPos = this.searchKingPos(C.GetOppTurn(color));
2380 if (oppKingPos.length == 0 || this.underCheck(oppKingPos, [color]))
af9c9be3 2381 return true;
5f08c59b 2382 return (
af9c9be3
BA
2383 (
2384 !this.options["balance"] ||
6b9320bb
BA
2385 ![1, 2].includes(this.movesCount) ||
2386 this.subTurn == 2
af9c9be3
BA
2387 )
2388 &&
2389 (
2390 !this.options["doublemove"] ||
2391 this.movesCount == 0 ||
2392 this.subTurn == 2
2393 )
2394 &&
2395 (
2396 !this.options["progressive"] ||
2397 this.subTurn == this.movesCount + 1
2398 )
5f08c59b 2399 );
41534b92
BA
2400 }
2401
2402 // "Stop at the first move found"
2403 atLeastOneMove(color) {
41534b92
BA
2404 for (let i = 0; i < this.size.x; i++) {
2405 for (let j = 0; j < this.size.y; j++) {
2406 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
cc2c7183
BA
2407 // NOTE: in fact searching for all potential moves from i,j.
2408 // I don't believe this is an issue, for now at least.
de1421be 2409 const moves = this.getPotentialMovesFrom([i, j], color);
b4ae3ff6
BA
2410 if (moves.some(m => this.filterValid([m]).length >= 1))
2411 return true;
41534b92
BA
2412 }
2413 }
2414 }
2415 if (this.hasReserve && this.reserve[color]) {
2416 for (let p of Object.keys(this.reserve[color])) {
2417 const moves = this.getDropMovesFrom([color, p]);
b4ae3ff6
BA
2418 if (moves.some(m => this.filterValid([m]).length >= 1))
2419 return true;
41534b92
BA
2420 }
2421 }
2422 return false;
2423 }
2424
2425 // What is the score ? (Interesting if game is over)
d6d0a46e
BA
2426 getCurrentScore(move_s) {
2427 const move = move_s[move_s.length - 1];
2428 // Shortcut in case the score was computed before:
2429 if (move.result)
2430 return move.result;
ceeac4e8 2431 const oppTurn = C.GetOppTurn(this.turn);
a548cb4e 2432 const kingPos = {
ceeac4e8
BA
2433 w: this.searchKingPos('w'),
2434 b: this.searchKingPos('b')
a548cb4e 2435 };
ceeac4e8 2436 if (kingPos[this.turn].length == 0 && kingPos[oppTurn].length == 0)
b4ae3ff6 2437 return "1/2";
ceeac4e8 2438 if (kingPos[this.turn].length == 0)
b57b726c 2439 return (this.turn == "w" ? "0-1" : "1-0");
ceeac4e8 2440 if (kingPos[oppTurn].length == 0)
b57b726c 2441 return (this.turn == "w" ? "1-0" : "0-1");
ceeac4e8 2442 if (this.atLeastOneMove(this.turn))
b4ae3ff6 2443 return "*";
41534b92 2444 // No valid move: stalemate or checkmate?
ceeac4e8 2445 if (!this.underCheck(kingPos[this.turn], this.getOppCols(this.turn)))
b4ae3ff6 2446 return "1/2";
41534b92 2447 // OK, checkmate
ceeac4e8 2448 return (this.turn == "w" ? "0-1" : "1-0");
41534b92
BA
2449 }
2450
41534b92
BA
2451 playVisual(move, r) {
2452 move.vanish.forEach(v => {
bc97fdd1
BA
2453 if (this.g_pieces[v.x][v.y]) //can be null (e.g. Apocalypse)
2454 this.g_pieces[v.x][v.y].remove();
c9ab0340 2455 this.g_pieces[v.x][v.y] = null;
41534b92 2456 });
3c61449b
BA
2457 let chessboard =
2458 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
2459 if (!r)
2460 r = chessboard.getBoundingClientRect();
41534b92
BA
2461 const pieceWidth = this.getPieceWidth(r.width);
2462 move.appear.forEach(a => {
41534b92 2463 this.g_pieces[a.x][a.y] = document.createElement("piece");
2159c239
BA
2464 C.AddClass_es(this.g_pieces[a.x][a.y],
2465 this.pieces(a.c, a.x, a.y)[a.p]["class"]);
616a8d7a 2466 this.g_pieces[a.x][a.y].classList.add(V.GetColorClass(a.c));
41534b92
BA
2467 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2468 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2469 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
9db5050a
BA
2470 // Translate coordinates to use chessboard as reference:
2471 this.g_pieces[a.x][a.y].style.transform =
2472 `translate(${ip - r.x}px,${jp - r.y}px)`;
c9ab0340
BA
2473 if (this.enlightened && !this.enlightened[a.x][a.y])
2474 this.g_pieces[a.x][a.y].classList.add("hidden");
3c61449b 2475 chessboard.appendChild(this.g_pieces[a.x][a.y]);
41534b92 2476 });
c9ab0340
BA
2477 if (this.options["dark"])
2478 this.graphUpdateEnlightened();
41534b92
BA
2479 }
2480
5f08c59b 2481 // TODO: send stack receive stack, or allow incremental? (good/bad points)
e7d409fc 2482 buildMoveStack(move, r) {
5f08c59b
BA
2483 this.moveStack.push(move);
2484 this.computeNextMove(move);
b9877ed2
BA
2485 const then = () => {
2486 const newTurn = this.turn;
2487 if (this.moveStack.length == 1 && !this.hideMoves)
2488 this.playVisual(move, r);
2489 if (move.next) {
2490 this.gameState = {
2491 fen: this.getFen(),
2492 board: JSON.parse(JSON.stringify(this.board)) //easier
2493 };
2494 this.buildMoveStack(move.next, r);
5f08c59b
BA
2495 }
2496 else {
b9877ed2
BA
2497 if (this.moveStack.length == 1) {
2498 // Usual case (one normal move)
2499 this.afterPlay(this.moveStack, newTurn, {send: true, res: true});
2500 this.moveStack = [];
2501 }
2502 else {
2503 this.afterPlay(this.moveStack, newTurn, {send: true, res: false});
2504 this.re_initFromFen(this.gameState.fen, this.gameState.board);
2505 this.playReceivedMove(this.moveStack.slice(1), () => {
2506 this.afterPlay(this.moveStack, newTurn, {send: false, res: true});
2507 this.moveStack = [];
2508 });
2509 }
5f08c59b 2510 }
b9877ed2
BA
2511 };
2512 // If hiding moves, then they are revealed in play() with callback
2513 this.play(move, this.hideMoves ? then : null);
2514 if (!this.hideMoves)
2515 then();
41534b92
BA
2516 }
2517
5f08c59b
BA
2518 // Implemented in variants using (automatic) moveStack
2519 computeNextMove(move) {}
2520
5f08c59b
BA
2521 animateMoving(start, end, drag, segments, cb) {
2522 let initPiece = this.getDomPiece(start.x, start.y);
bc97fdd1
BA
2523 if (!initPiece) { //TODO: shouldn't occur!
2524 cb();
2525 return;
2526 }
5f08c59b 2527 // NOTE: cloning often not required, but light enough, and simpler
9db5050a
BA
2528 let movingPiece = initPiece.cloneNode();
2529 initPiece.style.opacity = "0";
2530 let container =
2531 document.getElementById(this.containerId)
2532 const r = container.querySelector(".chessboard").getBoundingClientRect();
5f08c59b 2533 if (typeof start.x == "string") {
082e639a
BA
2534 // Need to bound width/height (was 100% for reserve pieces)
2535 const pieceWidth = this.getPieceWidth(r.width);
2536 movingPiece.style.width = pieceWidth + "px";
2537 movingPiece.style.height = pieceWidth + "px";
2538 }
f55a0a67 2539 const maxDist = this.getMaxDistance(r);
5f08c59b
BA
2540 const apparentColor = this.getColor(start.x, start.y);
2541 const pieces = this.pieces(apparentColor, start.x, start.y);
2542 if (drag) {
2543 const startCode = this.getPiece(start.x, start.y);
3b641716 2544 C.RemoveClass_es(movingPiece, pieces[startCode]["class"]);
5f08c59b
BA
2545 C.AddClass_es(movingPiece, pieces[drag.p]["class"]);
2546 if (apparentColor != drag.c) {
616a8d7a
BA
2547 movingPiece.classList.remove(V.GetColorClass(apparentColor));
2548 movingPiece.classList.add(V.GetColorClass(drag.c));
41534b92 2549 }
41534b92 2550 }
9db5050a 2551 container.appendChild(movingPiece);
15106e82 2552 const animateSegment = (index, cb) => {
9db5050a 2553 // NOTE: move.drag could be generalized per-segment (usage?)
5f08c59b
BA
2554 const [i1, j1] = segments[index][0];
2555 const [i2, j2] = segments[index][1];
15106e82
BA
2556 const dep = this.getPixelPosition(i1, j1, r);
2557 const arr = this.getPixelPosition(i2, j2, r);
9db5050a
BA
2558 movingPiece.style.transitionDuration = "0s";
2559 movingPiece.style.transform = `translate(${dep[0]}px, ${dep[1]}px)`;
15106e82
BA
2560 const distance =
2561 Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2);
2562 const duration = 0.2 + (distance / maxDist) * 0.3;
9db5050a
BA
2563 // TODO: unclear why we need this new delay below:
2564 setTimeout(() => {
2565 movingPiece.style.transitionDuration = duration + "s";
adf7c659 2566 // movingPiece is child of container: no need to adjust coordinates
9db5050a
BA
2567 movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`;
2568 setTimeout(cb, duration * 1000);
2569 }, 50);
15106e82 2570 };
15106e82 2571 let index = 0;
635418a5 2572 const animateSegmentCallback = () => {
5f08c59b 2573 if (index < segments.length)
635418a5 2574 animateSegment(index++, animateSegmentCallback);
15106e82 2575 else {
9db5050a
BA
2576 movingPiece.remove();
2577 initPiece.style.opacity = "1";
5f08c59b 2578 cb();
15106e82 2579 }
635418a5
BA
2580 };
2581 animateSegmentCallback();
41534b92
BA
2582 }
2583
5f08c59b
BA
2584 // Input array of objects with at least fields x,y (e.g. PiPo)
2585 animateFading(arr, cb) {
2586 const animLength = 350; //TODO: 350ms? More? Less?
2587 arr.forEach(v => {
2588 let fadingPiece = this.getDomPiece(v.x, v.y);
2589 fadingPiece.style.transitionDuration = (animLength / 1000) + "s";
2590 fadingPiece.style.opacity = "0";
2591 });
2592 setTimeout(cb, animLength);
2593 }
2594
2595 animate(move, callback) {
2596 if (this.noAnimate || move.noAnimate) {
2597 callback();
2598 return;
2599 }
2600 let segments = move.segments;
2601 if (!segments)
2602 segments = [ [[move.start.x, move.start.y], [move.end.x, move.end.y]] ];
2603 let targetObj = new TargetObj(callback);
2604 if (move.start.x != move.end.x || move.start.y != move.end.y) {
2605 targetObj.target++;
2606 this.animateMoving(move.start, move.end, move.drag, segments,
2607 () => targetObj.increment());
2608 }
2609 if (move.vanish.length > move.appear.length) {
2610 const arr = move.vanish.slice(move.appear.length)
e7d409fc
BA
2611 // Ignore disappearing pieces hidden by some appearing ones:
2612 .filter(v => move.appear.every(a => a.x != v.x || a.y != v.y));
5f08c59b
BA
2613 if (arr.length > 0) {
2614 targetObj.target++;
2615 this.animateFading(arr, () => targetObj.increment());
2616 }
2617 }
462947f0
BA
2618 targetObj.target +=
2619 this.tryAnimateCastle(move, () => targetObj.increment());
5f08c59b
BA
2620 targetObj.target +=
2621 this.customAnimate(move, segments, () => targetObj.increment());
2622 if (targetObj.target == 0)
2623 callback();
2624 }
2625
462947f0
BA
2626 tryAnimateCastle(move, cb) {
2627 if (
2628 this.hasCastle &&
2629 move.vanish.length == 2 &&
2630 move.appear.length == 2 &&
2631 this.isKing(0, 0, move.vanish[0].p) &&
2632 this.isKing(0, 0, move.appear[0].p)
2633 ) {
2634 const start = {x: move.vanish[1].x, y: move.vanish[1].y},
2635 end = {x: move.appear[1].x, y: move.appear[1].y};
2636 const segments = [ [[start.x, start.y], [end.x, end.y]] ];
2637 this.animateMoving(start, end, null, segments, cb);
2638 return 1;
2639 }
2640 return 0;
2641 }
2642
5f08c59b
BA
2643 // Potential other animations (e.g. for Suction variant)
2644 customAnimate(move, segments, cb) {
2645 return 0; //nb of targets
2646 }
2647
126ffc70 2648 launchAnimation(moves, container, callback) {
98d14451 2649 if (this.hideMoves) {
b9877ed2
BA
2650 for (let i=0; i<moves.length; i++)
2651 // If hiding moves, they are revealed into play():
2652 this.play(moves[i], i == moves.length - 1 ? callback : () => {});
98d14451
BA
2653 return;
2654 }
2655 const r = container.querySelector(".chessboard").getBoundingClientRect();
2656 const animateRec = i => {
2657 this.animate(moves[i], () => {
2658 this.play(moves[i]);
2659 this.playVisual(moves[i], r);
2660 if (i < moves.length - 1)
2661 setTimeout(() => animateRec(i+1), 300);
2662 else
2663 callback();
2664 });
21e8e712 2665 };
98d14451
BA
2666 animateRec(0);
2667 }
2668
2669 playReceivedMove(moves, callback) {
e081c5eb
BA
2670 // Delay if user wasn't focused:
2671 const checkDisplayThenAnimate = (delay) => {
3c61449b 2672 if (container.style.display == "none") {
21e8e712
BA
2673 alert("New move! Let's go back to game...");
2674 document.getElementById("gameInfos").style.display = "none";
3c61449b 2675 container.style.display = "block";
126ffc70
BA
2676 setTimeout(
2677 () => this.launchAnimation(moves, container, callback),
2678 700
2679 );
2680 }
2681 else {
2682 setTimeout(
2683 () => this.launchAnimation(moves, container, callback),
2684 delay || 0
2685 );
21e8e712 2686 }
21e8e712 2687 };
3c61449b 2688 let container = document.getElementById(this.containerId);
016306e3
BA
2689 if (document.hidden) {
2690 document.onvisibilitychange = () => {
c9a20f4f 2691 // TODO here: page reload ?! (some issues if tab changed...)
016306e3 2692 document.onvisibilitychange = undefined;
e081c5eb 2693 checkDisplayThenAnimate(700);
fd31883b 2694 };
fd31883b 2695 }
b4ae3ff6
BA
2696 else
2697 checkDisplayThenAnimate();
41534b92
BA
2698 }
2699
2700};