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