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