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