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