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