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