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