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