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