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