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