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