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