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