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