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