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