20ffbee4cdddfc6661f1c031782937800b289827
[xogo.git] / base_rules.js
1 import {Random} from "/utils/alea.js";
2 import {ArrayFun} from "/utils/array.js";
3 import {FenUtil} from "/utils/setupPieces.js";
4 import PiPo from "/utils/PiPo.js";
5 import Move from "/utils/Move.js";
6
7 // Helper class for move animation
8 class 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
22 // NOTE: x coords: top to bottom (white perspective); y: left to right
23 // NOTE: ChessRules is aliased as window.C, and variants as window.V
24 export default class ChessRules {
25
26 static get Aliases() {
27 return {'C': ChessRules};
28 }
29
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 {
38 select: [{
39 label: "Randomness",
40 variable: "randomness",
41 defaut: 0,
42 options: [
43 {label: "Deterministic", value: 0},
44 {label: "Symmetric random", value: 1},
45 {label: "Asymmetric random", value: 2}
46 ]
47 }],
48 input: [
49 {
50 label: "Capture king",
51 variable: "taking",
52 type: "checkbox",
53 defaut: false
54 },
55 {
56 label: "Falling pawn",
57 variable: "pawnfall",
58 type: "checkbox",
59 defaut: false
60 }
61 ],
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
82 get pawnPromotions() {
83 return ['q', 'r', 'n', 'b'];
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 }
106 // Some variants do not store reserve state (Align4, Chakart...)
107 get hasReserveFen() {
108 return this.hasReserve;
109 }
110
111 get noAnimate() {
112 return !!this.options["dark"];
113 }
114
115 // Some variants use only click information
116 get clickOnly() {
117 return false;
118 }
119
120 // Some variants reveal moves only after both players played
121 get hideMoves() {
122 return false;
123 }
124
125 // Some variants do not flip board as black
126 get flippedBoard() {
127 return (this.playerColor == 'b');
128 }
129
130 // Some variants use click infos:
131 doClick(coords) {
132 if (typeof coords.x != "number")
133 return null; //click on reserves
134 if (
135 this.options["teleport"] && this.subTurnTeleport == 2 &&
136 this.board[coords.x][coords.y] == ""
137 ) {
138 let res = new Move({
139 start: {x: this.captured.x, y: this.captured.y},
140 appear: [
141 new PiPo({
142 x: coords.x,
143 y: coords.y,
144 c: this.captured.c,
145 p: this.captured.p
146 })
147 ],
148 vanish: []
149 });
150 res.drag = {c: this.captured.c, p: this.captured.p};
151 return res;
152 }
153 return null;
154 }
155
156 ////////////////////
157 // COORDINATES UTILS
158
159 // 3a --> {x:3, y:10}
160 static SquareToCoords(sq) {
161 return ArrayFun.toObject(["x", "y"],
162 [0, 1].map(i => parseInt(sq[i], 36)));
163 }
164
165 // {x:11, y:12} --> bc
166 static CoordsToSquare(cd) {
167 return Object.values(cd).map(c => c.toString(36)).join("");
168 }
169
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 }
176 // Reserve :
177 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
178 }
179
180 idToCoords(targetId) {
181 if (!targetId)
182 return null; //outside page, maybe...
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")
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]};
196 }
197
198 /////////////
199 // FEN UTILS
200
201 // Turn "wb" into "B" (for FEN)
202 board2fen(b) {
203 return (b[0] == "w" ? b[1].toUpperCase() : b[1]);
204 }
205
206 // Turn "p" into "bp" (for board)
207 fen2board(f) {
208 return (f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f);
209 }
210
211 genRandInitFen(seed) {
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 (
217 baseFen.fen + " w 0" +
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() {
224 const s = FenUtil.setupPieces(
225 ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
226 {
227 randomness: this.options["randomness"],
228 between: {p1: 'k', p2: 'r'},
229 diffCol: ['b'],
230 flags: ['r']
231 }
232 );
233 return {
234 fen: s.b.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" +
235 s.w.join("").toUpperCase(),
236 o: {flags: s.flags}
237 };
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 };
248 if (fenParts.length > 3)
249 res = Object.assign(res, JSON.parse(fenParts[3]));
250 return res;
251 }
252
253 // Return current fen (game state)
254 getFen() {
255 const parts = this.getPartFen({});
256 return (
257 this.getBaseFen() +
258 (Object.keys(parts).length > 0 ? (" " + JSON.stringify(parts)) : "")
259 );
260 }
261
262 getBaseFen() {
263 return this.getPosition() + " " + this.turn + " " + this.movesCount;
264 }
265
266 getPartFen(o) {
267 let parts = {};
268 if (this.hasFlags)
269 parts["flags"] = o.init ? o.flags : this.getFlagsFen();
270 if (this.hasEnpassant)
271 parts["enpassant"] = o.init ? "-" : this.getEnpassantFen();
272 if (this.hasReserveFen)
273 parts["reserve"] = this.getReserveFen(o);
274 if (this.options["crazyhouse"])
275 parts["ispawn"] = this.getIspawnFen(o);
276 return parts;
277 }
278
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
291 // Position part of the FEN string
292 getPosition() {
293 let position = "";
294 for (let i = 0; i < this.size.x; i++) {
295 let emptyCount = 0;
296 for (let j = 0; j < this.size.y; j++) {
297 if (this.board[i][j] == "")
298 emptyCount++;
299 else {
300 if (emptyCount > 0) {
301 // Add empty squares in-between
302 position += C.FenEmptySquares(emptyCount);
303 emptyCount = 0;
304 }
305 position += this.board2fen(this.board[i][j]);
306 }
307 }
308 if (emptyCount > 0)
309 // "Flush remainder"
310 position += C.FenEmptySquares(emptyCount);
311 if (i < this.size.x - 1)
312 position += "/"; //separate rows
313 }
314 return position;
315 }
316
317 // Flags part of the FEN string
318 getFlagsFen() {
319 return ["w", "b"].map(c => {
320 return this.castleFlags[c].map(x => x.toString(36)).join("");
321 }).join("");
322 }
323
324 // Enpassant part of the FEN string
325 getEnpassantFen() {
326 if (!this.epSquare)
327 return "-";
328 return C.CoordsToSquare(this.epSquare);
329 }
330
331 getReserveFen(o) {
332 if (o.init)
333 return "000000000000";
334 return (
335 ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("")
336 );
337 }
338
339 getIspawnFen(o) {
340 if (o.init)
341 // NOTE: cannot merge because this.ispawn doesn't exist yet
342 return "-";
343 const squares = Object.keys(this.ispawn);
344 if (squares.length == 0)
345 return "-";
346 return squares.join(",");
347 }
348
349 // Set flags from fen (castle: white a,h then black a,h)
350 setFlags(fenflags) {
351 this.castleFlags = {
352 w: [0, 1].map(i => parseInt(fenflags.charAt(i), 36)),
353 b: [2, 3].map(i => parseInt(fenflags.charAt(i), 36))
354 };
355 }
356
357 //////////////////
358 // INITIALIZATION
359
360 constructor(o) {
361 this.options = o.options;
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 });
367
368 // Some variables
369 this.playerColor = o.color;
370 this.afterPlay = o.afterPlay; //trigger some actions after playing a move
371 this.containerId = o.element;
372 this.isDiagram = o.diagram;
373 this.marks = o.marks;
374
375 // Initializations
376 if (!o.fen)
377 o.fen = this.genRandInitFen(o.seed);
378 this.re_initFromFen(o.fen);
379 this.graphicalInit();
380 }
381
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
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:
400 if (!isNaN(num))
401 j += num;
402 // Else: something at position i,j
403 else
404 board[i][j++] = this.fen2board(character);
405 }
406 }
407 return board;
408 }
409
410 // Some additional variables from FEN (variant dependant)
411 setOtherVariables(fenParsed, pieceArray) {
412 // Set flags and enpassant:
413 if (this.hasFlags)
414 this.setFlags(fenParsed.flags);
415 if (this.hasEnpassant)
416 this.epSquare = this.getEpSquare(fenParsed.enpassant);
417 if (this.hasReserve && !this.isDiagram)
418 this.initReserves(fenParsed.reserve, pieceArray);
419 if (this.options["crazyhouse"])
420 this.initIspawn(fenParsed.ispawn);
421 if (this.options["teleport"]) {
422 this.subTurnTeleport = 1;
423 this.captured = null;
424 }
425 if (this.options["dark"]) {
426 // Setup enlightened: squares reachable by player side
427 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
428 this.updateEnlightened();
429 }
430 this.subTurn = 1; //may be unused
431 if (!this.moveStack) //avoid resetting (unwanted)
432 this.moveStack = [];
433 }
434
435 // ordering as in pieces() p,r,n,b,q,k
436 initReserves(reserveStr, pieceArray) {
437 if (!pieceArray)
438 pieceArray = ['p', 'r', 'n', 'b', 'q', 'k'];
439 const counts = reserveStr.split("").map(c => parseInt(c, 36));
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 };
445 }
446
447 initIspawn(ispawnStr) {
448 if (ispawnStr != "-")
449 this.ispawn = ArrayFun.toObject(ispawnStr.split(","), true);
450 else
451 this.ispawn = {};
452 }
453
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
470 getNbReservePieces(color) {
471 return (
472 Object.values(this.reserve[color]).reduce(
473 (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0)
474 );
475 }
476
477 getRankInReserve(c, p) {
478 const pieces = Object.keys(this.pieces(c, c, p));
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
485 static AddClass_es(elt, class_es) {
486 if (!Array.isArray(class_es))
487 class_es = [class_es];
488 class_es.forEach(cl => elt.classList.add(cl));
489 }
490
491 static RemoveClass_es(elt, class_es) {
492 if (!Array.isArray(class_es))
493 class_es = [class_es];
494 class_es.forEach(cl => elt.classList.remove(cl));
495 }
496
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
514 graphicalInit() {
515 const g_init = () => {
516 this.re_drawBoardElements();
517 if (!this.isDiagram && !this.mouseListeners && !this.touchListeners)
518 this.initMouseEvents();
519 };
520 let container = document.getElementById(this.containerId);
521 this.windowResizeObs = new ResizeObserver(g_init);
522 this.windowResizeObs.observe(container);
523 }
524
525 re_drawBoardElements() {
526 const board = this.getSvgChessboard();
527 const container = document.getElementById(this.containerId);
528 const rc = container.getBoundingClientRect();
529 let chessboard = container.querySelector(".chessboard");
530 chessboard.innerHTML = "";
531 chessboard.insertAdjacentHTML('beforeend', board);
532 // Compare window ratio width / height to aspectRatio:
533 const windowRatio = rc.width / rc.height;
534 let cbWidth, cbHeight;
535 const vRatio = this.size.ratio || 1;
536 if (windowRatio <= vRatio) {
537 // Limiting dimension is width:
538 cbWidth = Math.min(rc.width, 767);
539 cbHeight = cbWidth / vRatio;
540 }
541 else {
542 // Limiting dimension is height:
543 cbHeight = Math.min(rc.height, 767);
544 cbWidth = cbHeight * vRatio;
545 }
546 if (this.hasReserve && !this.isDiagram) {
547 const sqSize = cbWidth / this.size.y;
548 // NOTE: allocate space for reserves (up/down) even if they are empty
549 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
550 if ((rc.height - cbHeight) / 2 < sqSize + 5) {
551 cbHeight = rc.height - 2 * (sqSize + 5);
552 cbWidth = cbHeight * vRatio;
553 }
554 }
555 chessboard.style.width = cbWidth + "px";
556 chessboard.style.height = cbHeight + "px";
557 // Center chessboard:
558 const spaceLeft = (rc.width - cbWidth) / 2,
559 spaceTop = (rc.height - cbHeight) / 2;
560 chessboard.style.left = spaceLeft + "px";
561 chessboard.style.top = spaceTop + "px";
562 // Give sizes instead of recomputing them,
563 // because chessboard might not be drawn yet.
564 this.setupVisualPieces({
565 width: cbWidth,
566 height: cbHeight,
567 x: spaceLeft,
568 y: spaceTop
569 });
570 }
571
572 // Get SVG board (background, no pieces)
573 getSvgChessboard() {
574 const flipped = this.flippedBoard;
575 let board = `
576 <svg
577 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
578 class="chessboard_SVG">`;
579 for (let i=0; i < this.size.x; i++) {
580 for (let j=0; j < this.size.y; j++) {
581 if (!this.onBoard(i, j))
582 continue;
583 const ii = (flipped ? this.size.x - 1 - i : i);
584 const jj = (flipped ? this.size.y - 1 - j : j);
585 let classes = this.getSquareColorClass(ii, jj);
586 if (this.enlightened && !this.enlightened[ii][jj])
587 classes += " in-shadow";
588 // NOTE: x / y reversed because coordinates system is reversed.
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 />`;
598 }
599 }
600 board += "</svg>";
601 return board;
602 }
603
604 setupVisualPieces(r) {
605 let chessboard =
606 document.getElementById(this.containerId).querySelector(".chessboard");
607 if (!r)
608 r = chessboard.getBoundingClientRect();
609 const pieceWidth = this.getPieceWidth(r.width);
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");
642 for (let i=0; i < this.size.x; i++) {
643 for (let j=0; j < this.size.y; j++) {
644 if (this.board[i][j] != "") {
645 const color = this.getColor(i, j);
646 const piece = this.getPiece(i, j);
647 addPiece(i, j, "g_pieces", this.pieces(color, i, j)[piece]["class"]);
648 this.g_pieces[i][j].classList.add(V.GetColorClass(color));
649 if (this.enlightened && !this.enlightened[i][j])
650 this.g_pieces[i][j].classList.add("hidden");
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);
657 }
658 }
659 }
660 if (this.hasReserve && !this.isDiagram)
661 this.re_drawReserve(['w', 'b'], r);
662 }
663
664 // NOTE: assume this.reserve != null
665 re_drawReserve(colors, r) {
666 if (this.r_pieces) {
667 // Remove (old) reserve pieces
668 for (let c of colors) {
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();
674 });
675 }
676 }
677 else
678 this.r_pieces = { w: {}, b: {} };
679 let container = document.getElementById(this.containerId);
680 if (!r)
681 r = container.querySelector(".chessboard").getBoundingClientRect();
682 for (let c of colors) {
683 let reservesDiv = document.getElementById("reserves_" + c);
684 if (reservesDiv)
685 reservesDiv.remove();
686 if (!this.reserve[c])
687 continue;
688 const nbR = this.getNbReservePieces(c);
689 if (nbR == 0)
690 continue;
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";
700 // NOTE: +1 fix display bug on Firefox at least
701 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
702 rcontainer.style.height = sqResSize + "px";
703 container.appendChild(rcontainer);
704 for (let p of Object.keys(this.reserve[c])) {
705 if (this.reserve[c][p] == 0)
706 continue;
707 let r_cell = document.createElement("div");
708 r_cell.id = this.coordsToId({x: c, y: p});
709 r_cell.classList.add("reserve-cell");
710 r_cell.style.width = sqResSize + "px";
711 r_cell.style.height = sqResSize + "px";
712 rcontainer.appendChild(r_cell);
713 let piece = document.createElement("piece");
714 C.AddClass_es(piece, this.pieces(c, c, p)[p]["class"]);
715 piece.classList.add(V.GetColorClass(c));
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) {
734 if (this.options["cannibal"] && C.CannibalKings[piece])
735 piece = "k"; //capturing cannibal king: back to king form
736 const oldCount = this.reserve[color][piece];
737 this.reserve[color][piece] = count;
738 // Redrawing is much easier if count==0 (or undefined)
739 if ([oldCount, count].some(item => !item))
740 this.re_drawReserve([color]);
741 else {
742 const numId = this.getReserveNumId(color, piece);
743 document.getElementById(numId).textContent = count;
744 }
745 }
746
747 // Resize board: no need to destroy/recreate pieces
748 rescale(mode) {
749 const container = document.getElementById(this.containerId);
750 let chessboard = container.querySelector(".chessboard");
751 const rc = container.getBoundingClientRect(),
752 r = chessboard.getBoundingClientRect();
753 const multFact = (mode == "up" ? 1.05 : 0.95);
754 let [newWidth, newHeight] = [multFact * r.width, multFact * r.height];
755 // Stay in window:
756 const vRatio = this.size.ratio || 1;
757 if (newWidth > rc.width) {
758 newWidth = rc.width;
759 newHeight = newWidth / vRatio;
760 }
761 if (newHeight > rc.height) {
762 newHeight = rc.height;
763 newWidth = newHeight * vRatio;
764 }
765 chessboard.style.width = newWidth + "px";
766 chessboard.style.height = newHeight + "px";
767 const newX = (rc.width - newWidth) / 2;
768 chessboard.style.left = newX + "px";
769 const newY = (rc.height - newHeight) / 2;
770 chessboard.style.top = newY + "px";
771 const newR = {x: newX, y: newY, width: newWidth, height: newHeight};
772 const pieceWidth = this.getPieceWidth(newWidth);
773 // NOTE: next "if" for variants which use squares filling
774 // instead of "physical", moving pieces
775 if (this.g_pieces) {
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]) {
779 // NOTE: could also use CSS transform "scale"
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);
783 // Translate coordinates to use chessboard as reference:
784 this.g_pieces[i][j].style.transform =
785 `translate(${ip - newX}px,${jp - newY}px)`;
786 }
787 }
788 }
789 }
790 if (this.hasReserve)
791 this.rescaleReserve(newR);
792 }
793
794 rescaleReserve(r) {
795 for (let c of ['w','b']) {
796 if (!this.reserve[c])
797 continue;
798 const nbR = this.getNbReservePieces(c);
799 if (nbR == 0)
800 continue;
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";
808 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
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 => {
813 if (this.reserve[c][p] == 0)
814 return;
815 let r_cell = document.getElementById(this.coordsToId({x: c, y: p}));
816 r_cell.style.width = sqResSize + "px";
817 r_cell.style.height = sqResSize + "px";
818 });
819 }
820 }
821
822 // Return the absolute pixel coordinates given current position.
823 // Our coordinate system differs from CSS one (x <--> y).
824 // We return here the CSS coordinates (more useful).
825 getPixelPosition(i, j, r) {
826 if (i < 0 || j < 0)
827 return [0, 0]; //piece vanishes
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;
838 const flipped = this.flippedBoard;
839 x = (flipped ? this.size.y - 1 - j : j) * sqSize;
840 y = (flipped ? this.size.x - 1 - i : i) * sqSize;
841 }
842 return [r.x + x, r.y + y];
843 }
844
845 initMouseEvents() {
846 let container = document.getElementById(this.containerId);
847 let chessboard = container.querySelector(".chessboard");
848
849 const getOffset = e => {
850 if (e.clientX)
851 // Mouse
852 return {x: e.clientX, y: e.clientY};
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)
861 return {x: touchLocation.clientX, y: touchLocation.clientY};
862 return {x: 0, y: 0}; //shouldn't reach here =)
863 }
864
865 const centerOnCursor = (piece, e) => {
866 const centerShift = this.getPieceWidth(r.width) / 2;
867 const offset = getOffset(e);
868 piece.style.left = (offset.x - centerShift) + "px";
869 piece.style.top = (offset.y - centerShift) + "px";
870 }
871
872 let start = null,
873 r = null,
874 startPiece, curPiece = null,
875 pieceWidth;
876 const mousedown = (e) => {
877 // Disable zoom on smartphones:
878 if (e.touches && e.touches.length > 1)
879 e.preventDefault();
880 r = chessboard.getBoundingClientRect();
881 pieceWidth = this.getPieceWidth(r.width);
882 const cd = this.idToCoords(e.target.id);
883 if (cd) {
884 const move = this.doClick(cd);
885 if (move)
886 this.buildMoveStack(move, r);
887 else if (!this.clickOnly) {
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)) {
894 e.preventDefault();
895 start = cd;
896 curPiece = startPiece.cloneNode();
897 curPiece.style.transform = "none";
898 curPiece.style.zIndex = 5;
899 curPiece.style.width = pieceWidth + "px";
900 curPiece.style.height = pieceWidth + "px";
901 centerOnCursor(curPiece, e);
902 container.appendChild(curPiece);
903 startPiece.style.opacity = "0.4";
904 chessboard.style.cursor = "none";
905 }
906 }
907 }
908 };
909
910 const mousemove = (e) => {
911 if (start) {
912 e.preventDefault();
913 centerOnCursor(curPiece, e);
914 }
915 else if (e.changedTouches && e.changedTouches.length >= 1)
916 // Attempt to prevent horizontal swipe...
917 e.preventDefault();
918 };
919
920 const mouseup = (e) => {
921 if (!start)
922 return;
923 const [x, y] = [start.x, start.y];
924 start = null;
925 e.preventDefault();
926 chessboard.style.cursor = "pointer";
927 startPiece.style.opacity = "1";
928 const offset = getOffset(e);
929 const landingElt = document.elementFromPoint(offset.x, offset.y);
930 const cd =
931 (landingElt ? this.idToCoords(landingElt.id) : undefined);
932 if (cd) {
933 // NOTE: clearly suboptimal, but much easier, and not a big deal.
934 const potentialMoves = this.getPotentialMovesFrom([x, y])
935 .filter(m => m.end.x == cd.x && m.end.y == cd.y);
936 const moves = this.filterValid(potentialMoves);
937 if (moves.length >= 2)
938 this.showChoices(moves, r);
939 else if (moves.length == 1)
940 this.buildMoveStack(moves[0], r);
941 }
942 curPiece.remove();
943 };
944
945 const resize = (e) => this.rescale(e.deltaY < 0 ? "up" : "down");
946
947 if ('onmousedown' in window) {
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 });
957 }
958 if ('ontouchstart' in window) {
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 });
968 }
969 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
970 }
971
972 // NOTE: not called if isDiagram
973 removeListeners() {
974 let container = document.getElementById(this.containerId);
975 this.windowResizeObs.unobserve(container);
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
989 showChoices(moves, r) {
990 let container = document.getElementById(this.containerId);
991 let chessboard = container.querySelector(".chessboard");
992 let choices = document.createElement("div");
993 choices.id = "choices";
994 if (!r)
995 r = chessboard.getBoundingClientRect();
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";
1000 chessboard.style.opacity = "0.5";
1001 container.appendChild(choices);
1002 const squareWidth = r.width / this.size.y;
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) => {
1007 chessboard.style.opacity = "1";
1008 container.removeChild(choices);
1009 this.buildMoveStack(m, r);
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");
1021 const cdisp = moves[i].choice || moves[i].appear[0].p;
1022 C.AddClass_es(piece,
1023 this.pieces(color, moves[i].end.x, moves[i].end.y)[cdisp]["class"]);
1024 piece.classList.add(V.GetColorClass(color));
1025 piece.style.width = "100%";
1026 piece.style.height = "100%";
1027 choice.appendChild(piece);
1028 choices.appendChild(choice);
1029 }
1030 }
1031
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
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
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;
1074 for (let step of steps) {
1075 const x = this.epSquare.x - step[0], //NOTE: epSquare.x not on edge
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
1112 //////////////
1113 // BASIC UTILS
1114
1115 get size() {
1116 return {
1117 x: 8,
1118 y: 8,
1119 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
1120 };
1121 }
1122
1123 // Color of thing on square (i,j). '' if square is empty
1124 getColor(i, j) {
1125 if (typeof i == "string")
1126 return i; //reserves
1127 return this.board[i][j].charAt(0);
1128 }
1129
1130 static GetColorClass(c) {
1131 if (c == 'w')
1132 return "white";
1133 if (c == 'b')
1134 return "black";
1135 return "other-color"; //unidentified color
1136 }
1137
1138 // Piece on i,j. '' if square is empty
1139 getPiece(i, j) {
1140 if (typeof j == "string")
1141 return j; //reserves
1142 return this.board[i][j].charAt(1);
1143 }
1144
1145 // Piece type on square (i,j)
1146 getPieceType(x, y, p) {
1147 if (!p)
1148 p = this.getPiece(x, y);
1149 return this.pieces(this.getColor(x, y), x, y)[p].moveas || p;
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];
1158 }
1159
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) {
1166 return (color == "w" ? "b" : "w");
1167 }
1168
1169 // Is (x,y) on the chessboard?
1170 onBoard(x, y) {
1171 return (x >= 0 && x < this.size.x &&
1172 y >= 0 && y < this.size.y);
1173 }
1174
1175 // Am I allowed to move thing at square x,y ?
1176 canIplay(x, y) {
1177 return (this.playerColor == this.turn && this.getColor(x, y) == this.turn);
1178 }
1179
1180 ////////////////////////
1181 // PIECES SPECIFICATIONS
1182
1183 getPawnShift(color) {
1184 return (color == "w" ? -1 : 1);
1185 }
1186 isPawnInitRank(x, color) {
1187 return (color == 'w' && x >= 6) || (color == 'b' && x <= 1);
1188 }
1189
1190 pieces(color, x, y) {
1191 const pawnShift = this.getPawnShift(color);
1192 return {
1193 'p': {
1194 "class": "pawn",
1195 moves: [
1196 {
1197 steps: [[pawnShift, 0]],
1198 range: (this.isPawnInitRank(x, color) ? 2 : 1)
1199 }
1200 ],
1201 attack: [
1202 {
1203 steps: [[pawnShift, 1], [pawnShift, -1]],
1204 range: 1
1205 }
1206 ]
1207 },
1208 'r': {
1209 "class": "rook",
1210 both: [
1211 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1212 ]
1213 },
1214 'n': {
1215 "class": "knight",
1216 both: [
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 ]
1225 },
1226 'b': {
1227 "class": "bishop",
1228 both: [
1229 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1230 ]
1231 },
1232 'q': {
1233 "class": "queen",
1234 both: [
1235 {
1236 steps: [
1237 [0, 1], [0, -1], [1, 0], [-1, 0],
1238 [1, 1], [1, -1], [-1, 1], [-1, -1]
1239 ]
1240 }
1241 ]
1242 },
1243 'k': {
1244 "class": "king",
1245 both: [
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 ]
1254 },
1255 // Cannibal kings:
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"}
1261 };
1262 }
1263
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
1289
1290 // For Cylinder: get Y coordinate
1291 getY(y) {
1292 if (!this.options["cylinder"])
1293 return y;
1294 let res = y % this.size.y;
1295 if (res < 0)
1296 res += this.size.y;
1297 return res;
1298 }
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 }
1310
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
1319 getStepSpec(color, x, y, piece) {
1320 let pieceType = piece;
1321 let allSpecs = this.pieces(color, x, y);
1322 if (!piece)
1323 pieceType = this.getPieceType(x, y);
1324 else if (allSpecs[piece].moveas)
1325 pieceType = allSpecs[piece].moveas;
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;
1334 }
1335
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
1341 // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2)
1342 canSelfTake([x1, y1], [x2, y2]) {
1343 return !this.isKing(x2, y2);
1344 }
1345
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
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
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);
1369 const oppCols = this.getOppCols(color);
1370 const piece = this.getPieceType(x, y);
1371 const stepSpec = this.getStepSpec(color, x, y, piece);
1372 const attacks = stepSpec.both.concat(stepSpec.attack);
1373 for (let a of attacks) {
1374 outerLoop: for (let step of a.steps) {
1375 let [i, j] = this.increment([x, y], step);
1376 let stepCounter = 0;
1377 while (this.onBoard(i, j) && this.board[i][j] == "") {
1378 if (a.range <= stepCounter++)
1379 continue outerLoop;
1380 [i, j] = this.increment([i, j], step);
1381 }
1382 if (
1383 this.onBoard(i, j) &&
1384 oppCols.includes(this.getColor(i, j)) &&
1385 this.getPieceType(i, j) == piece
1386 ) {
1387 return true;
1388 }
1389 }
1390 }
1391 return false;
1392 }
1393
1394 // Stop at the first capture found
1395 atLeastOneCapture(color) {
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 );
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 (
1409 (
1410 !this.options["zen"] &&
1411 this.findDestSquares(
1412 [i, j],
1413 {
1414 attackOnly: true,
1415 one: true,
1416 },
1417 allowed
1418 )
1419 )
1420 ||
1421 (
1422 (
1423 this.options["zen"] &&
1424 this.findCapturesOn(
1425 [i, j],
1426 {one: true},
1427 allowed
1428 )
1429 )
1430 )
1431 ) {
1432 return true;
1433 }
1434 }
1435 }
1436 }
1437 return false;
1438 }
1439
1440 compatibleStep([x1, y1], [x2, y2], step, range) {
1441 const epsilon = 1e-7; //arbitrary small value
1442 let shifts = [0];
1443 if (this.options["cylinder"])
1444 Array.prototype.push.apply(shifts, [-this.size.y, this.size.y]);
1445 for (let sh of shifts) {
1446 const rx = (x2 - x1) / step[0],
1447 ry = (y2 + sh - y1) / step[1];
1448 if (
1449 // Zero step but non-zero interval => impossible
1450 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
1451 (!Number.isFinite(ry) && !Number.isNaN(ry)) ||
1452 // Negative number of step (impossible)
1453 (rx < 0 || ry < 0) ||
1454 // Not the same number of steps in both directions:
1455 (!Number.isNaN(rx) && !Number.isNaN(ry) && Math.abs(rx - ry) > epsilon)
1456 ) {
1457 continue;
1458 }
1459 let distance = (Number.isNaN(rx) ? ry : rx);
1460 if (Math.abs(distance - Math.round(distance)) > epsilon)
1461 continue;
1462 distance = Math.round(distance); //in case of (numerical...)
1463 if (!range || range >= distance)
1464 return true;
1465 }
1466 return false;
1467 }
1468
1469 ////////////////////
1470 // MOVES GENERATION
1471
1472 getDropMovesFrom([c, p]) {
1473 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1474 // (but not necessarily otherwise: atLeastOneMove() etc)
1475 if (this.reserve[c][p] == 0)
1476 return [];
1477 let moves = [];
1478 for (let i=0; i<this.size.x; i++) {
1479 for (let j=0; j<this.size.y; j++) {
1480 if (this.onBoard(i, j) && this.canDrop([c, p], [i, j])) {
1481 let mv = new Move({
1482 start: {x: c, y: p},
1483 end: {x: i, y: j},
1484 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1485 vanish: []
1486 });
1487 if (this.board[i][j] != "") {
1488 mv.vanish.push(new PiPo({
1489 x: i,
1490 y: j,
1491 c: this.getColor(i, j),
1492 p: this.getPiece(i, j)
1493 }));
1494 }
1495 moves.push(mv);
1496 }
1497 }
1498 }
1499 return moves;
1500 }
1501
1502 // All possible moves from selected square
1503 // TODO: generalize usage if arg "color" (e.g. Checkered)
1504 getPotentialMovesFrom([x, y], color) {
1505 if (this.subTurnTeleport == 2)
1506 return [];
1507 if (typeof x == "string")
1508 return this.getDropMovesFrom([x, y]);
1509 if (this.isImmobilized([x, y]))
1510 return [];
1511 const piece = this.getPieceType(x, y);
1512 let moves = this.getPotentialMovesOf(piece, [x, y]);
1513 if (piece == "p" && this.hasEnpassant && this.epSquare)
1514 Array.prototype.push.apply(moves, this.getEnpassantCaptures([x, y]));
1515 if (
1516 this.isKing(0, 0, piece) && this.hasCastle &&
1517 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1518 ) {
1519 Array.prototype.push.apply(moves, this.getCastleMoves([x, y]));
1520 }
1521 return this.postProcessPotentialMoves(moves);
1522 }
1523
1524 postProcessPotentialMoves(moves) {
1525 if (moves.length == 0)
1526 return [];
1527 const color = this.getColor(moves[0].start.x, moves[0].start.y);
1528 const oppCols = this.getOppCols(color);
1529
1530 if (this.options["capture"] && this.atLeastOneCapture(color))
1531 moves = this.capturePostProcess(moves, oppCols);
1532
1533 if (this.options["atomic"])
1534 moves = this.atomicPostProcess(moves, color, oppCols);
1535
1536 if (
1537 moves.length > 0 &&
1538 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1539 ) {
1540 moves = this.pawnPostProcess(moves, color, oppCols);
1541 }
1542
1543 if (this.options["cannibal"] && this.options["rifle"])
1544 // In this case a rifle-capture from last rank may promote a pawn
1545 moves = this.riflePromotePostProcess(moves, color);
1546
1547 return moves;
1548 }
1549
1550 capturePostProcess(moves, oppCols) {
1551 // Filter out non-capturing moves (not using m.vanish because of
1552 // self captures of Recycle and Teleport).
1553 return moves.filter(m => {
1554 return (
1555 this.board[m.end.x][m.end.y] != "" &&
1556 oppCols.includes(this.getColor(m.end.x, m.end.y))
1557 );
1558 });
1559 }
1560
1561 atomicPostProcess(moves, color, oppCols) {
1562 moves.forEach(m => {
1563 if (
1564 this.board[m.end.x][m.end.y] != "" &&
1565 oppCols.includes(this.getColor(m.end.x, m.end.y))
1566 ) {
1567 // Explosion!
1568 let steps = [
1569 [-1, -1],
1570 [-1, 0],
1571 [-1, 1],
1572 [0, -1],
1573 [0, 1],
1574 [1, -1],
1575 [1, 0],
1576 [1, 1]
1577 ];
1578 let mNext = new Move({
1579 start: m.end,
1580 end: m.end,
1581 appear: [],
1582 vanish: []
1583 });
1584 for (let step of steps) {
1585 let [x, y] = this.increment([m.end.x, m.end.y], step);
1586 if (
1587 this.onBoard(x, y) &&
1588 this.board[x][y] != "" &&
1589 (x != m.start.x || y != m.start.y) &&
1590 this.getPieceType(x, y) != "p"
1591 ) {
1592 mNext.vanish.push(
1593 new PiPo({
1594 p: this.getPiece(x, y),
1595 c: this.getColor(x, y),
1596 x: x,
1597 y: y
1598 })
1599 );
1600 }
1601 }
1602 if (!this.options["rifle"]) {
1603 // The moving piece also vanish
1604 mNext.vanish.unshift(
1605 new PiPo({
1606 x: m.end.x,
1607 y: m.end.y,
1608 c: color,
1609 p: this.getPiece(m.start.x, m.start.y)
1610 })
1611 );
1612 }
1613 m.next = mNext;
1614 }
1615 });
1616 return moves;
1617 }
1618
1619 pawnPostProcess(moves, color, oppCols) {
1620 let moreMoves = [];
1621 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1622 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1623 moves.forEach(m => {
1624 const [x1, y1] = [m.start.x, m.start.y];
1625 const [x2, y2] = [m.end.x, m.end.y];
1626 const promotionOk = (
1627 x2 == lastRank &&
1628 (!this.options["rifle"] || this.board[x2][y2] == "")
1629 );
1630 if (!promotionOk)
1631 return; //nothing to do
1632 if (this.options["pawnfall"]) {
1633 m.appear.shift();
1634 return;
1635 }
1636 let finalPieces;
1637 if (
1638 this.options["cannibal"] &&
1639 this.board[x2][y2] != "" &&
1640 oppCols.includes(this.getColor(x2, y2))
1641 ) {
1642 finalPieces = [this.getPieceType(x2, y2)];
1643 }
1644 else
1645 finalPieces = this.pawnPromotions;
1646 m.appear[0].p = finalPieces[0];
1647 if (initPiece == "!") //cannibal king-pawn
1648 m.appear[0].p = C.CannibalKingCode[finalPieces[0]];
1649 for (let i=1; i<finalPieces.length; i++) {
1650 let newMove = JSON.parse(JSON.stringify(m));
1651 const piece = finalPieces[i];
1652 m.appear[0].p = (initPiece != "!" ? piece : C.CannibalKingCode[piece]);
1653 moreMoves.push(newMove);
1654 }
1655 });
1656 return moves.concat(moreMoves);
1657 }
1658
1659 riflePromotePostProcess(moves, color) {
1660 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1661 let newMoves = [];
1662 moves.forEach(m => {
1663 if (
1664 m.start.x == lastRank &&
1665 m.appear.length >= 1 &&
1666 m.appear[0].p == "p" &&
1667 m.appear[0].x == m.start.x &&
1668 m.appear[0].y == m.start.y
1669 ) {
1670 m.appear[0].p = this.pawnPromotions[0];
1671 for (let i=1; i<this.pawnPromotions.length; i++) {
1672 let newMv = JSON.parse(JSON.stringify(m));
1673 newMv.appear[0].p = this.pawnPromotions[i];
1674 newMoves.push(newMv);
1675 }
1676 }
1677 });
1678 return moves.concat(newMoves);
1679 }
1680
1681 // Generic method to find possible moves of "sliding or jumping" pieces
1682 getPotentialMovesOf(piece, [x, y]) {
1683 const color = this.getColor(x, y);
1684 const stepSpec = this.getStepSpec(color, x, y, piece);
1685 let squares = [];
1686 if (stepSpec.attack) {
1687 squares = this.findDestSquares(
1688 [x, y],
1689 {
1690 attackOnly: true,
1691 stepSpec: stepSpec
1692 },
1693 ([i1, j1], [i2, j2]) => {
1694 return (
1695 (!this.options["zen"] || this.isKing(i2, j2)) &&
1696 this.canTake([i1, j1], [i2, j2])
1697 );
1698 }
1699 );
1700 }
1701 const noSpecials = this.findDestSquares(
1702 [x, y],
1703 {
1704 moveOnly: !!stepSpec.attack || this.options["zen"],
1705 stepSpec: stepSpec
1706 }
1707 );
1708 Array.prototype.push.apply(squares, noSpecials);
1709 if (this.options["zen"]) {
1710 let zenCaptures = this.findCapturesOn(
1711 [x, y],
1712 {}, //byCol: default is ok
1713 ([i1, j1], [i2, j2]) =>
1714 !this.isKing(i1, j1) && this.canTake([i2, j2], [i1, j1])
1715 );
1716 // Technical step: segments (if any) are reversed
1717 zenCaptures.forEach(z => {
1718 if (!!z.segments)
1719 z.segments = z.segments.reverse().map(s => s.reverse())
1720 });
1721 Array.prototype.push.apply(squares, zenCaptures);
1722 }
1723 if (
1724 this.options["recycle"] ||
1725 (this.options["teleport"] && this.subTurnTeleport == 1)
1726 ) {
1727 const selfCaptures = this.findDestSquares(
1728 [x, y],
1729 {
1730 attackOnly: true,
1731 stepSpec: stepSpec
1732 },
1733 ([i1, j1], [i2, j2]) => {
1734 return (
1735 this.getColor(i2, j2) == color &&
1736 this.canSelfTake([i1, j1], [i2, j2])
1737 );
1738 }
1739 );
1740 Array.prototype.push.apply(squares, selfCaptures);
1741 }
1742 return squares.map(s => {
1743 let mv = this.getBasicMove([x, y], s.sq);
1744 if (!!s.segments)
1745 mv.segments = s.segments;
1746 return mv;
1747 });
1748 }
1749
1750 findDestSquares([x, y], o, allowed) {
1751 if (!allowed)
1752 allowed = (sq1, sq2) => this.canTake(sq1, sq2);
1753 const apparentPiece = this.getPiece(x, y); //how it looks
1754 let res = [];
1755 // Next 3 for Cylinder mode or circular (useless otherwise)
1756 let explored = {};
1757 let segments = [];
1758 let segStart = [];
1759 const addSquare = ([i, j]) => {
1760 let elt = {sq: [i, j]};
1761 if (segments.length >= 1)
1762 elt.segments = this.getSegments(segments, segStart, [i, j]);
1763 res.push(elt);
1764 };
1765 const exploreSteps = (stepArray, mode) => {
1766 for (let s of stepArray) {
1767 outerLoop: for (let step of s.steps) {
1768 segments = [];
1769 segStart = [x, y];
1770 let [i, j] = [x, y];
1771 let stepCounter = 0;
1772 while (
1773 this.onBoard(i, j) &&
1774 ((i == x && j == y) || this.canStepOver(i, j, apparentPiece))
1775 ) {
1776 if (!explored[i + "." + j] && (i != x || j != y)) {
1777 explored[i + "." + j] = true;
1778 if (
1779 !o.captureTarget ||
1780 (o.captureTarget[0] == i && o.captureTarget[1] == j)
1781 ) {
1782 if (o.one && mode != "attack")
1783 return true;
1784 if (mode != "attack")
1785 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1786 if (o.captureTarget)
1787 return res[0];
1788 }
1789 }
1790 if (s.range <= stepCounter++)
1791 continue outerLoop;
1792 const oldIJ = [i, j];
1793 [i, j] = this.increment([i, j], step);
1794 if (Math.abs(j - oldIJ[1]) > 1 || Math.abs(i - oldIJ[0]) > 1) {
1795 // Boundary between segments (cylinder or circular mode)
1796 segments.push([[segStart[0], segStart[1]], oldIJ]);
1797 segStart = [i, j];
1798 }
1799 }
1800 if (!this.onBoard(i, j))
1801 continue;
1802 const pieceIJ = this.getPieceType(i, j);
1803 if (!explored[i + "." + j]) {
1804 explored[i + "." + j] = true;
1805 if (allowed([x, y], [i, j])) {
1806 if (o.one && mode != "moves")
1807 return true;
1808 if (mode != "moves")
1809 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1810 if (
1811 o.captureTarget &&
1812 o.captureTarget[0] == i && o.captureTarget[1] == j
1813 ) {
1814 return res[0];
1815 }
1816 }
1817 }
1818 }
1819 }
1820 return undefined; //default, but let's explicit it
1821 };
1822 if (o.captureTarget)
1823 return exploreSteps(o.captureSteps, "attack");
1824 else {
1825 const stepSpec =
1826 o.stepSpec || this.getStepSpec(this.getColor(x, y), x, y);
1827 let outOne = false;
1828 if (!o.attackOnly)
1829 outOne = exploreSteps(stepSpec.both.concat(stepSpec.moves), "moves");
1830 if (!outOne && !o.moveOnly)
1831 outOne = exploreSteps(stepSpec.both.concat(stepSpec.attack), "attack");
1832 return (o.one ? outOne : res);
1833 }
1834 }
1835
1836 // Search for enemy (or not) pieces attacking [x, y]
1837 findCapturesOn([x, y], o, allowed) {
1838 if (!o.byCol)
1839 o.byCol = this.getOppCols(this.getColor(x, y) || this.turn);
1840 let res = [];
1841 for (let i=0; i<this.size.x; i++) {
1842 for (let j=0; j<this.size.y; j++) {
1843 const colIJ = this.getColor(i, j);
1844 if (
1845 this.board[i][j] != "" &&
1846 o.byCol.includes(colIJ) &&
1847 !this.isImmobilized([i, j])
1848 ) {
1849 const apparentPiece = this.getPiece(i, j);
1850 // Quick check: does this potential attacker target x,y ?
1851 if (this.canStepOver(x, y, apparentPiece))
1852 continue;
1853 const stepSpec = this.getStepSpec(colIJ, i, j);
1854 const attacks = stepSpec.attack.concat(stepSpec.both);
1855 for (let a of attacks) {
1856 for (let s of a.steps) {
1857 // Quick check: if step isn't compatible, don't even try
1858 if (!this.compatibleStep([i, j], [x, y], s, a.range))
1859 continue;
1860 // Finally verify that nothing stand in-between
1861 const out = this.findDestSquares(
1862 [i, j],
1863 {
1864 captureTarget: [x, y],
1865 captureSteps: [{steps: [s], range: a.range}],
1866 },
1867 allowed
1868 );
1869 if (out) {
1870 if (o.one)
1871 return true;
1872 res.push(out);
1873 }
1874 }
1875 }
1876 }
1877 }
1878 }
1879 return (o.one ? false : res);
1880 }
1881
1882 // Build a regular move from its initial and destination squares.
1883 // tr: transformation
1884 getBasicMove([sx, sy], [ex, ey], tr) {
1885 const initColor = this.getColor(sx, sy);
1886 const initPiece = this.getPiece(sx, sy);
1887 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1888 let mv = new Move({
1889 appear: [],
1890 vanish: [],
1891 start: {x: sx, y: sy},
1892 end: {x: ex, y: ey}
1893 });
1894 if (
1895 !this.options["rifle"] ||
1896 this.board[ex][ey] == "" ||
1897 destColor == initColor //Recycle, Teleport
1898 ) {
1899 mv.appear = [
1900 new PiPo({
1901 x: ex,
1902 y: ey,
1903 c: !!tr ? tr.c : initColor,
1904 p: !!tr ? tr.p : initPiece
1905 })
1906 ];
1907 mv.vanish = [
1908 new PiPo({
1909 x: sx,
1910 y: sy,
1911 c: initColor,
1912 p: initPiece
1913 })
1914 ];
1915 }
1916 if (this.board[ex][ey] != "") {
1917 mv.vanish.push(
1918 new PiPo({
1919 x: ex,
1920 y: ey,
1921 c: this.getColor(ex, ey),
1922 p: this.getPiece(ex, ey)
1923 })
1924 );
1925 if (this.options["cannibal"] && destColor != initColor) {
1926 const lastIdx = mv.vanish.length - 1; //think "Rifle+Cannibal"
1927 let trPiece = mv.vanish[lastIdx].p;
1928 if (this.isKing(sx, sy))
1929 trPiece = C.CannibalKingCode[trPiece];
1930 if (mv.appear.length >= 1)
1931 mv.appear[0].p = trPiece;
1932 else if (this.options["rifle"]) {
1933 mv.appear.unshift(
1934 new PiPo({
1935 x: sx,
1936 y: sy,
1937 c: initColor,
1938 p: trPiece
1939 })
1940 );
1941 mv.vanish.unshift(
1942 new PiPo({
1943 x: sx,
1944 y: sy,
1945 c: initColor,
1946 p: initPiece
1947 })
1948 );
1949 }
1950 }
1951 }
1952 return mv;
1953 }
1954
1955 // En-passant square, if any
1956 getEpSquare(moveOrSquare) {
1957 if (typeof moveOrSquare === "string") {
1958 const square = moveOrSquare;
1959 if (square == "-")
1960 return undefined;
1961 return C.SquareToCoords(square);
1962 }
1963 // Argument is a move:
1964 const move = moveOrSquare;
1965 const s = move.start,
1966 e = move.end;
1967 if (
1968 s.y == e.y &&
1969 Math.abs(s.x - e.x) == 2 &&
1970 // Next conditions for variants like Atomic or Rifle, Recycle...
1971 (
1972 move.appear.length > 0 &&
1973 this.getPieceType(0, 0, move.appear[0].p) == 'p'
1974 )
1975 &&
1976 (
1977 move.vanish.length > 0 &&
1978 this.getPieceType(0, 0, move.vanish[0].p) == 'p'
1979 )
1980 ) {
1981 return {
1982 x: (s.x + e.x) / 2,
1983 y: s.y
1984 };
1985 }
1986 return undefined; //default
1987 }
1988
1989 // Special case of en-passant captures: treated separately
1990 getEnpassantCaptures([x, y]) {
1991 const color = this.getColor(x, y);
1992 const shiftX = (color == 'w' ? -1 : 1);
1993 const oppCols = this.getOppCols(color);
1994 if (
1995 this.epSquare &&
1996 this.epSquare.x == x + shiftX && //NOTE: epSquare.x not on edge
1997 Math.abs(this.getY(this.epSquare.y - y)) == 1 &&
1998 // Doublemove (and Progressive?) guards:
1999 this.board[this.epSquare.x][this.epSquare.y] == "" &&
2000 oppCols.includes(this.getColor(x, this.epSquare.y))
2001 ) {
2002 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
2003 this.board[epx][epy] = this.board[x][this.epSquare.y];
2004 let enpassantMove = this.getBasicMove([x, y], [epx, epy]);
2005 this.board[epx][epy] = "";
2006 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
2007 enpassantMove.vanish[lastIdx].x = x;
2008 return [enpassantMove];
2009 }
2010 return [];
2011 }
2012
2013 getCastleMoves([x, y], finalSquares, castleWith) {
2014 const c = this.getColor(x, y);
2015
2016 // Castling ?
2017 const oppCols = this.getOppCols(c);
2018 let moves = [];
2019 // King, then rook:
2020 finalSquares =
2021 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
2022 const castlingKing = this.getPiece(x, y);
2023 castlingCheck: for (
2024 let castleSide = 0;
2025 castleSide < 2;
2026 castleSide++ //large, then small
2027 ) {
2028 if (this.castleFlags[c][castleSide] >= this.size.y)
2029 continue;
2030 // If this code is reached, rook and king are on initial position
2031
2032 // NOTE: in some variants this is not a rook
2033 const rookPos = this.castleFlags[c][castleSide];
2034 const castlingPiece = this.getPiece(x, rookPos);
2035 if (
2036 this.board[x][rookPos] == "" ||
2037 this.getColor(x, rookPos) != c ||
2038 (castleWith && !castleWith.includes(castlingPiece))
2039 ) {
2040 // Rook is not here, or changed color (see Benedict)
2041 continue;
2042 }
2043 // Nothing on the path of the king ? (and no checks)
2044 const finDist = finalSquares[castleSide][0] - y;
2045 let step = finDist / Math.max(1, Math.abs(finDist));
2046 let i = y;
2047 do {
2048 if (
2049 // NOTE: next weird test because underCheck() verification
2050 // will be executed in filterValid() later.
2051 (
2052 i != finalSquares[castleSide][0] &&
2053 this.underCheck([[x, i]], oppCols)
2054 )
2055 ||
2056 (
2057 this.board[x][i] != "" &&
2058 // NOTE: next check is enough, because of chessboard constraints
2059 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
2060 )
2061 ) {
2062 continue castlingCheck;
2063 }
2064 i += step;
2065 } while (i != finalSquares[castleSide][0]);
2066 // Nothing on the path to the rook?
2067 step = (castleSide == 0 ? -1 : 1);
2068 for (i = y + step; i != rookPos; i += step) {
2069 if (this.board[x][i] != "")
2070 continue castlingCheck;
2071 }
2072
2073 // Nothing on final squares, except maybe king and castling rook?
2074 for (i = 0; i < 2; i++) {
2075 if (
2076 finalSquares[castleSide][i] != rookPos &&
2077 this.board[x][finalSquares[castleSide][i]] != "" &&
2078 (
2079 finalSquares[castleSide][i] != y ||
2080 this.getColor(x, finalSquares[castleSide][i]) != c
2081 )
2082 ) {
2083 continue castlingCheck;
2084 }
2085 }
2086
2087 // If this code is reached, castle is potentially valid
2088 moves.push(
2089 new Move({
2090 appear: [
2091 new PiPo({
2092 x: x,
2093 y: finalSquares[castleSide][0],
2094 p: castlingKing,
2095 c: c
2096 }),
2097 new PiPo({
2098 x: x,
2099 y: finalSquares[castleSide][1],
2100 p: castlingPiece,
2101 c: c
2102 })
2103 ],
2104 vanish: [
2105 // King might be initially disguised (Titan...)
2106 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
2107 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
2108 ],
2109 end:
2110 Math.abs(y - rookPos) <= 2
2111 ? {x: x, y: rookPos}
2112 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
2113 })
2114 );
2115 }
2116
2117 return moves;
2118 }
2119
2120 ////////////////////
2121 // MOVES VALIDATION
2122
2123 // Is piece (or square) at given position attacked by "oppCol(s)" ?
2124 underAttack([x, y], oppCols) {
2125 // An empty square is considered as king,
2126 // since it's used only in getCastleMoves (TODO?)
2127 const king = this.board[x][y] == "" || this.isKing(x, y);
2128 return (
2129 (
2130 (!this.options["zen"] || king) &&
2131 this.findCapturesOn(
2132 [x, y],
2133 {
2134 byCol: oppCols,
2135 one: true
2136 }
2137 )
2138 )
2139 ||
2140 (
2141 (!!this.options["zen"] && !king) &&
2142 this.findDestSquares(
2143 [x, y],
2144 {
2145 attackOnly: true,
2146 one: true
2147 },
2148 ([i1, j1], [i2, j2]) => oppCols.includes(this.getColor(i2, j2))
2149 )
2150 )
2151 );
2152 }
2153
2154 // Argument is (very generally) an array of squares (= arrays)
2155 underCheck(square_s, oppCols) {
2156 if (this.options["taking"] || this.options["dark"])
2157 return false;
2158 return square_s.some(sq => this.underAttack(sq, oppCols));
2159 }
2160
2161 // Scan board for king(s)
2162 searchKingPos(color) {
2163 let res = [];
2164 for (let i=0; i < this.size.x; i++) {
2165 for (let j=0; j < this.size.y; j++) {
2166 if (this.getColor(i, j) == color && this.isKing(i, j))
2167 res.push([i, j]);
2168 }
2169 }
2170 return res;
2171 }
2172
2173 // cb: callback returning a boolean (false if king missing)
2174 trackKingWrap(move, kingPos, cb) {
2175 if (move.appear.length == 0 && move.vanish.length == 0)
2176 return true;
2177 const color =
2178 (move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c);
2179 let newKingPP = null,
2180 sqIdx = 0,
2181 res = true; //a priori valid
2182 const oldKingPP =
2183 move.vanish.find(v => this.isKing(0, 0, v.p) && v.c == color);
2184 if (oldKingPP) {
2185 // Search king in appear array:
2186 newKingPP =
2187 move.appear.find(a => this.isKing(0, 0, a.p) && a.c == color);
2188 if (newKingPP) {
2189 sqIdx = kingPos.findIndex(kp =>
2190 kp[0] == oldKingPP.x && kp[1] == oldKingPP.y);
2191 kingPos[sqIdx] = [newKingPP.x, newKingPP.y];
2192 }
2193 else
2194 res = false; //king vanished
2195 }
2196 res &&= cb(kingPos);
2197 if (oldKingPP && newKingPP)
2198 kingPos[sqIdx] = [oldKingPP.x, oldKingPP.y];
2199 return res;
2200 }
2201
2202 // 'color' arg because some variants (e.g. Refusal) check opponent moves
2203 filterValid(moves, color) {
2204 if (!color)
2205 color = this.turn;
2206 const oppCols = this.getOppCols(color);
2207 let kingPos = this.searchKingPos(color);
2208 return moves.filter(m => {
2209 this.playOnBoard(m);
2210 const res = this.trackKingWrap(m, kingPos, (kp) => {
2211 return !this.underCheck(kp, oppCols);
2212 });
2213 this.undoOnBoard(m);
2214 return res;
2215 });
2216 }
2217
2218 /////////////////
2219 // MOVES PLAYING
2220
2221 // Apply a move on board
2222 playOnBoard(move) {
2223 for (let psq of move.vanish)
2224 this.board[psq.x][psq.y] = "";
2225 for (let psq of move.appear)
2226 this.board[psq.x][psq.y] = psq.c + psq.p;
2227 }
2228 // Un-apply the played move
2229 undoOnBoard(move) {
2230 for (let psq of move.appear)
2231 this.board[psq.x][psq.y] = "";
2232 for (let psq of move.vanish)
2233 this.board[psq.x][psq.y] = psq.c + psq.p;
2234 }
2235
2236 updateCastleFlags(move) {
2237 // Update castling flags if start or arrive from/at rook/king locations
2238 move.appear.concat(move.vanish).forEach(psq => {
2239 if (this.isKing(0, 0, psq.p))
2240 this.castleFlags[psq.c] = [this.size.y, this.size.y];
2241 // NOTE: not "else if" because king can capture enemy rook...
2242 let c = "";
2243 if (psq.x == 0)
2244 c = "b";
2245 else if (psq.x == this.size.x - 1)
2246 c = "w";
2247 if (c != "") {
2248 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
2249 if (fidx >= 0)
2250 this.castleFlags[c][fidx] = this.size.y;
2251 }
2252 });
2253 }
2254
2255 prePlay(move) {
2256 if (
2257 this.hasCastle &&
2258 // If flags already off, no need to re-check:
2259 Object.values(this.castleFlags).some(cvals =>
2260 cvals.some(val => val < this.size.y))
2261 ) {
2262 this.updateCastleFlags(move);
2263 }
2264 if (this.options["crazyhouse"]) {
2265 move.vanish.forEach(v => {
2266 const square = C.CoordsToSquare({x: v.x, y: v.y});
2267 if (this.ispawn[square])
2268 delete this.ispawn[square];
2269 });
2270 if (move.appear.length > 0 && move.vanish.length > 0) {
2271 // Assumption: something is moving
2272 const initSquare = C.CoordsToSquare(move.start);
2273 const destSquare = C.CoordsToSquare(move.end);
2274 if (
2275 this.ispawn[initSquare] ||
2276 (move.vanish[0].p == 'p' && move.appear[0].p != 'p')
2277 ) {
2278 this.ispawn[destSquare] = true;
2279 }
2280 else if (
2281 this.ispawn[destSquare] &&
2282 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
2283 ) {
2284 move.vanish[1].p = 'p';
2285 delete this.ispawn[destSquare];
2286 }
2287 }
2288 }
2289 const minSize = Math.min(move.appear.length, move.vanish.length);
2290 if (
2291 this.hasReserve &&
2292 // Warning; atomic pawn removal isn't a capture
2293 (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1)
2294 ) {
2295 const color = this.turn;
2296 for (let i=minSize; i<move.appear.length; i++) {
2297 // Something appears = dropped on board (some exceptions, Chakart...)
2298 if (move.appear[i].c == color) {
2299 const piece = move.appear[i].p;
2300 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
2301 }
2302 }
2303 for (let i=minSize; i<move.vanish.length; i++) {
2304 // Something vanish: add to reserve except if recycle & opponent
2305 if (
2306 this.options["crazyhouse"] ||
2307 (this.options["recycle"] && move.vanish[i].c == color)
2308 ) {
2309 const piece = move.vanish[i].p;
2310 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
2311 }
2312 }
2313 }
2314 }
2315
2316 play(move) {
2317 this.prePlay(move);
2318 if (this.hasEnpassant)
2319 this.epSquare = this.getEpSquare(move);
2320 this.playOnBoard(move);
2321 this.postPlay(move);
2322 }
2323
2324 postPlay(move) {
2325 if (this.options["dark"])
2326 this.updateEnlightened();
2327 if (this.options["teleport"]) {
2328 if (
2329 this.subTurnTeleport == 1 &&
2330 move.vanish.length > move.appear.length &&
2331 move.vanish[1].c == this.turn
2332 ) {
2333 const v = move.vanish[move.vanish.length - 1];
2334 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
2335 this.subTurnTeleport = 2;
2336 return;
2337 }
2338 this.subTurnTeleport = 1;
2339 this.captured = null;
2340 }
2341 this.tryChangeTurn(move);
2342 }
2343
2344 tryChangeTurn(move) {
2345 if (this.isLastMove(move)) {
2346 this.turn = C.GetOppTurn(this.turn);
2347 this.movesCount++;
2348 this.subTurn = 1;
2349 }
2350 else if (!move.next)
2351 this.subTurn++;
2352 }
2353
2354 isLastMove(move) {
2355 if (move.next)
2356 return false;
2357 const color = this.turn;
2358 const oppKingPos = this.searchKingPos(C.GetOppTurn(color));
2359 if (oppKingPos.length == 0 || this.underCheck(oppKingPos, [color]))
2360 return true;
2361 return (
2362 (
2363 !this.options["balance"] ||
2364 ![1, 2].includes(this.movesCount) ||
2365 this.subTurn == 2
2366 )
2367 &&
2368 (
2369 !this.options["doublemove"] ||
2370 this.movesCount == 0 ||
2371 this.subTurn == 2
2372 )
2373 &&
2374 (
2375 !this.options["progressive"] ||
2376 this.subTurn == this.movesCount + 1
2377 )
2378 );
2379 }
2380
2381 // "Stop at the first move found"
2382 atLeastOneMove(color) {
2383 for (let i = 0; i < this.size.x; i++) {
2384 for (let j = 0; j < this.size.y; j++) {
2385 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
2386 // NOTE: in fact searching for all potential moves from i,j.
2387 // I don't believe this is an issue, for now at least.
2388 const moves = this.getPotentialMovesFrom([i, j], color);
2389 if (moves.some(m => this.filterValid([m]).length >= 1))
2390 return true;
2391 }
2392 }
2393 }
2394 if (this.hasReserve && this.reserve[color]) {
2395 for (let p of Object.keys(this.reserve[color])) {
2396 const moves = this.getDropMovesFrom([color, p]);
2397 if (moves.some(m => this.filterValid([m]).length >= 1))
2398 return true;
2399 }
2400 }
2401 return false;
2402 }
2403
2404 // What is the score ? (Interesting if game is over)
2405 getCurrentScore(move_s) {
2406 const move = move_s[move_s.length - 1];
2407 // Shortcut in case the score was computed before:
2408 if (move.result)
2409 return move.result;
2410 const oppTurn = C.GetOppTurn(this.turn);
2411 const kingPos = {
2412 w: this.searchKingPos('w'),
2413 b: this.searchKingPos('b')
2414 };
2415 if (kingPos[this.turn].length == 0 && kingPos[oppTurn].length == 0)
2416 return "1/2";
2417 if (kingPos[this.turn].length == 0)
2418 return (this.turn == "w" ? "0-1" : "1-0");
2419 if (kingPos[oppTurn].length == 0)
2420 return (this.turn == "w" ? "1-0" : "0-1");
2421 if (this.atLeastOneMove(this.turn))
2422 return "*";
2423 // No valid move: stalemate or checkmate?
2424 if (!this.underCheck(kingPos[this.turn], this.getOppCols(this.turn)))
2425 return "1/2";
2426 // OK, checkmate
2427 return (this.turn == "w" ? "0-1" : "1-0");
2428 }
2429
2430 playVisual(move, r) {
2431 move.vanish.forEach(v => {
2432 if (this.g_pieces[v.x][v.y]) //can be null (e.g. Apocalypse)
2433 this.g_pieces[v.x][v.y].remove();
2434 this.g_pieces[v.x][v.y] = null;
2435 });
2436 let chessboard =
2437 document.getElementById(this.containerId).querySelector(".chessboard");
2438 if (!r)
2439 r = chessboard.getBoundingClientRect();
2440 const pieceWidth = this.getPieceWidth(r.width);
2441 move.appear.forEach(a => {
2442 this.g_pieces[a.x][a.y] = document.createElement("piece");
2443 C.AddClass_es(this.g_pieces[a.x][a.y],
2444 this.pieces(a.c, a.x, a.y)[a.p]["class"]);
2445 this.g_pieces[a.x][a.y].classList.add(V.GetColorClass(a.c));
2446 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2447 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2448 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
2449 // Translate coordinates to use chessboard as reference:
2450 this.g_pieces[a.x][a.y].style.transform =
2451 `translate(${ip - r.x}px,${jp - r.y}px)`;
2452 if (this.enlightened && !this.enlightened[a.x][a.y])
2453 this.g_pieces[a.x][a.y].classList.add("hidden");
2454 chessboard.appendChild(this.g_pieces[a.x][a.y]);
2455 });
2456 if (this.options["dark"])
2457 this.graphUpdateEnlightened();
2458 }
2459
2460 // TODO: send stack receive stack, or allow incremental? (good/bad points)
2461 buildMoveStack(move, r) {
2462 this.moveStack.push(move);
2463 this.computeNextMove(move);
2464 const then = () => {
2465 const newTurn = this.turn;
2466 if (this.moveStack.length == 1 && !this.hideMoves)
2467 this.playVisual(move, r);
2468 if (move.next) {
2469 this.gameState = {
2470 fen: this.getFen(),
2471 board: JSON.parse(JSON.stringify(this.board)) //easier
2472 };
2473 this.buildMoveStack(move.next, r);
2474 }
2475 else {
2476 if (this.moveStack.length == 1) {
2477 // Usual case (one normal move)
2478 this.afterPlay(this.moveStack, newTurn, {send: true, res: true});
2479 this.moveStack = [];
2480 }
2481 else {
2482 this.afterPlay(this.moveStack, newTurn, {send: true, res: false});
2483 this.re_initFromFen(this.gameState.fen, this.gameState.board);
2484 this.playReceivedMove(this.moveStack.slice(1), () => {
2485 this.afterPlay(this.moveStack, newTurn, {send: false, res: true});
2486 this.moveStack = [];
2487 });
2488 }
2489 }
2490 };
2491 // If hiding moves, then they are revealed in play() with callback
2492 this.play(move, this.hideMoves ? then : null);
2493 if (!this.hideMoves)
2494 then();
2495 }
2496
2497 // Implemented in variants using (automatic) moveStack
2498 computeNextMove(move) {}
2499
2500 animateMoving(start, end, drag, segments, cb) {
2501 let initPiece = this.getDomPiece(start.x, start.y);
2502 if (!initPiece) { //TODO: shouldn't occur!
2503 cb();
2504 return;
2505 }
2506 // NOTE: cloning often not required, but light enough, and simpler
2507 let movingPiece = initPiece.cloneNode();
2508 initPiece.style.opacity = "0";
2509 let container =
2510 document.getElementById(this.containerId)
2511 const r = container.querySelector(".chessboard").getBoundingClientRect();
2512 if (typeof start.x == "string") {
2513 // Need to bound width/height (was 100% for reserve pieces)
2514 const pieceWidth = this.getPieceWidth(r.width);
2515 movingPiece.style.width = pieceWidth + "px";
2516 movingPiece.style.height = pieceWidth + "px";
2517 }
2518 const maxDist = this.getMaxDistance(r);
2519 const apparentColor = this.getColor(start.x, start.y);
2520 const pieces = this.pieces(apparentColor, start.x, start.y);
2521 if (drag) {
2522 const startCode = this.getPiece(start.x, start.y);
2523 C.RemoveClass_es(movingPiece, pieces[startCode]["class"]);
2524 C.AddClass_es(movingPiece, pieces[drag.p]["class"]);
2525 if (apparentColor != drag.c) {
2526 movingPiece.classList.remove(V.GetColorClass(apparentColor));
2527 movingPiece.classList.add(V.GetColorClass(drag.c));
2528 }
2529 }
2530 container.appendChild(movingPiece);
2531 const animateSegment = (index, cb) => {
2532 // NOTE: move.drag could be generalized per-segment (usage?)
2533 const [i1, j1] = segments[index][0];
2534 const [i2, j2] = segments[index][1];
2535 const dep = this.getPixelPosition(i1, j1, r);
2536 const arr = this.getPixelPosition(i2, j2, r);
2537 movingPiece.style.transitionDuration = "0s";
2538 movingPiece.style.transform = `translate(${dep[0]}px, ${dep[1]}px)`;
2539 const distance =
2540 Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2);
2541 const duration = 0.2 + (distance / maxDist) * 0.3;
2542 // TODO: unclear why we need this new delay below:
2543 setTimeout(() => {
2544 movingPiece.style.transitionDuration = duration + "s";
2545 // movingPiece is child of container: no need to adjust coordinates
2546 movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`;
2547 setTimeout(cb, duration * 1000);
2548 }, 50);
2549 };
2550 let index = 0;
2551 const animateSegmentCallback = () => {
2552 if (index < segments.length)
2553 animateSegment(index++, animateSegmentCallback);
2554 else {
2555 movingPiece.remove();
2556 initPiece.style.opacity = "1";
2557 cb();
2558 }
2559 };
2560 animateSegmentCallback();
2561 }
2562
2563 // Input array of objects with at least fields x,y (e.g. PiPo)
2564 animateFading(arr, cb) {
2565 const animLength = 350; //TODO: 350ms? More? Less?
2566 arr.forEach(v => {
2567 let fadingPiece = this.getDomPiece(v.x, v.y);
2568 fadingPiece.style.transitionDuration = (animLength / 1000) + "s";
2569 fadingPiece.style.opacity = "0";
2570 });
2571 setTimeout(cb, animLength);
2572 }
2573
2574 animate(move, callback) {
2575 if (this.noAnimate || move.noAnimate) {
2576 callback();
2577 return;
2578 }
2579 let segments = move.segments;
2580 if (!segments)
2581 segments = [ [[move.start.x, move.start.y], [move.end.x, move.end.y]] ];
2582 let targetObj = new TargetObj(callback);
2583 if (move.start.x != move.end.x || move.start.y != move.end.y) {
2584 targetObj.target++;
2585 this.animateMoving(move.start, move.end, move.drag, segments,
2586 () => targetObj.increment());
2587 }
2588 if (move.vanish.length > move.appear.length) {
2589 const arr = move.vanish.slice(move.appear.length)
2590 // Ignore disappearing pieces hidden by some appearing ones:
2591 .filter(v => move.appear.every(a => a.x != v.x || a.y != v.y));
2592 if (arr.length > 0) {
2593 targetObj.target++;
2594 this.animateFading(arr, () => targetObj.increment());
2595 }
2596 }
2597 targetObj.target +=
2598 this.tryAnimateCastle(move, () => targetObj.increment());
2599 targetObj.target +=
2600 this.customAnimate(move, segments, () => targetObj.increment());
2601 if (targetObj.target == 0)
2602 callback();
2603 }
2604
2605 tryAnimateCastle(move, cb) {
2606 if (
2607 this.hasCastle &&
2608 move.vanish.length == 2 &&
2609 move.appear.length == 2 &&
2610 this.isKing(0, 0, move.vanish[0].p) &&
2611 this.isKing(0, 0, move.appear[0].p)
2612 ) {
2613 const start = {x: move.vanish[1].x, y: move.vanish[1].y},
2614 end = {x: move.appear[1].x, y: move.appear[1].y};
2615 const segments = [ [[start.x, start.y], [end.x, end.y]] ];
2616 this.animateMoving(start, end, null, segments, cb);
2617 return 1;
2618 }
2619 return 0;
2620 }
2621
2622 // Potential other animations (e.g. for Suction variant)
2623 customAnimate(move, segments, cb) {
2624 return 0; //nb of targets
2625 }
2626
2627 launchAnimation(moves, container, callback) {
2628 if (this.hideMoves) {
2629 for (let i=0; i<moves.length; i++)
2630 // If hiding moves, they are revealed into play():
2631 this.play(moves[i], i == moves.length - 1 ? callback : () => {});
2632 return;
2633 }
2634 const r = container.querySelector(".chessboard").getBoundingClientRect();
2635 const animateRec = i => {
2636 this.animate(moves[i], () => {
2637 this.play(moves[i]);
2638 this.playVisual(moves[i], r);
2639 if (i < moves.length - 1)
2640 setTimeout(() => animateRec(i+1), 300);
2641 else
2642 callback();
2643 });
2644 };
2645 animateRec(0);
2646 }
2647
2648 playReceivedMove(moves, callback) {
2649 // Delay if user wasn't focused:
2650 const checkDisplayThenAnimate = (delay) => {
2651 if (container.style.display == "none") {
2652 alert("New move! Let's go back to game...");
2653 document.getElementById("gameInfos").style.display = "none";
2654 container.style.display = "block";
2655 setTimeout(
2656 () => this.launchAnimation(moves, container, callback),
2657 700
2658 );
2659 }
2660 else {
2661 setTimeout(
2662 () => this.launchAnimation(moves, container, callback),
2663 delay || 0
2664 );
2665 }
2666 };
2667 let container = document.getElementById(this.containerId);
2668 if (document.hidden) {
2669 document.onvisibilitychange = () => {
2670 // TODO here: page reload ?! (some issues if tab changed...)
2671 document.onvisibilitychange = undefined;
2672 checkDisplayThenAnimate(700);
2673 };
2674 }
2675 else
2676 checkDisplayThenAnimate();
2677 }
2678
2679 };