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