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