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