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