| 1 | import {Random} from "/utils/alea.js"; |
| 2 | import {ArrayFun} from "/utils/array.js"; |
| 3 | import {FenUtil} from "/utils/setupPieces.js"; |
| 4 | import PiPo from "/utils/PiPo.js"; |
| 5 | import Move from "/utils/Move.js"; |
| 6 | |
| 7 | // Helper class for move animation |
| 8 | class TargetObj { |
| 9 | |
| 10 | constructor(callOnComplete) { |
| 11 | this.value = 0; |
| 12 | this.target = 0; |
| 13 | this.callOnComplete = callOnComplete; |
| 14 | } |
| 15 | increment() { |
| 16 | if (++this.value == this.target) |
| 17 | this.callOnComplete(); |
| 18 | } |
| 19 | |
| 20 | }; |
| 21 | |
| 22 | // NOTE: x coords: top to bottom (white perspective); y: left to right |
| 23 | // NOTE: ChessRules is aliased as window.C, and variants as window.V |
| 24 | export default class ChessRules { |
| 25 | |
| 26 | static get Aliases() { |
| 27 | return {'C': ChessRules}; |
| 28 | } |
| 29 | |
| 30 | ///////////////////////// |
| 31 | // VARIANT SPECIFICATIONS |
| 32 | |
| 33 | // Some variants have specific options, like the number of pawns in Monster, |
| 34 | // or the board size for Pandemonium. |
| 35 | // Users can generally select a randomness level from 0 to 2. |
| 36 | static get Options() { |
| 37 | return { |
| 38 | select: [{ |
| 39 | label: "Randomness", |
| 40 | variable: "randomness", |
| 41 | defaut: 0, |
| 42 | options: [ |
| 43 | {label: "Deterministic", value: 0}, |
| 44 | {label: "Symmetric random", value: 1}, |
| 45 | {label: "Asymmetric random", value: 2} |
| 46 | ] |
| 47 | }], |
| 48 | input: [ |
| 49 | { |
| 50 | label: "Capture king", |
| 51 | variable: "taking", |
| 52 | type: "checkbox", |
| 53 | defaut: false |
| 54 | }, |
| 55 | { |
| 56 | label: "Falling pawn", |
| 57 | variable: "pawnfall", |
| 58 | type: "checkbox", |
| 59 | defaut: false |
| 60 | } |
| 61 | ], |
| 62 | // Game modifiers (using "elementary variants"). Default: false |
| 63 | styles: [ |
| 64 | "atomic", |
| 65 | "balance", //takes precedence over doublemove & progressive |
| 66 | "cannibal", |
| 67 | "capture", |
| 68 | "crazyhouse", |
| 69 | "cylinder", //ok with all |
| 70 | "dark", |
| 71 | "doublemove", |
| 72 | "madrasi", |
| 73 | "progressive", //(natural) priority over doublemove |
| 74 | "recycle", |
| 75 | "rifle", |
| 76 | "teleport", |
| 77 | "zen" |
| 78 | ] |
| 79 | }; |
| 80 | } |
| 81 | |
| 82 | get pawnPromotions() { |
| 83 | return ['q', 'r', 'n', 'b']; |
| 84 | } |
| 85 | |
| 86 | // Some variants don't have flags: |
| 87 | get hasFlags() { |
| 88 | return true; |
| 89 | } |
| 90 | // Or castle |
| 91 | get hasCastle() { |
| 92 | return this.hasFlags; |
| 93 | } |
| 94 | |
| 95 | // En-passant captures allowed? |
| 96 | get hasEnpassant() { |
| 97 | return true; |
| 98 | } |
| 99 | |
| 100 | // Allow to take (moving: not disappearing) own pieces? |
| 101 | get hasSelfCaptures() { |
| 102 | return ( |
| 103 | this.options["recycle"] || |
| 104 | (this.options["teleport"] && this.subTurnTeleport == 1) |
| 105 | ); |
| 106 | } |
| 107 | |
| 108 | get hasReserve() { |
| 109 | return ( |
| 110 | !!this.options["crazyhouse"] || |
| 111 | (!!this.options["recycle"] && !this.options["teleport"]) |
| 112 | ); |
| 113 | } |
| 114 | // Some variants do not store reserve state (Align4, Chakart...) |
| 115 | get hasReserveFen() { |
| 116 | return this.hasReserve; |
| 117 | } |
| 118 | |
| 119 | get noAnimate() { |
| 120 | return !!this.options["dark"]; |
| 121 | } |
| 122 | |
| 123 | // Some variants use only click information |
| 124 | get clickOnly() { |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | // Some variants reveal moves only after both players played |
| 129 | get hideMoves() { |
| 130 | return false; |
| 131 | } |
| 132 | |
| 133 | // Some variants do not flip board as black |
| 134 | get flippedBoard() { |
| 135 | return (this.playerColor == 'b'); |
| 136 | } |
| 137 | |
| 138 | // Some variants use click infos: |
| 139 | doClick(coords) { |
| 140 | if (typeof coords.x != "number") |
| 141 | return null; //click on reserves |
| 142 | if ( |
| 143 | this.options["teleport"] && this.subTurnTeleport == 2 && |
| 144 | this.board[coords.x][coords.y] == "" |
| 145 | ) { |
| 146 | let res = new Move({ |
| 147 | start: {x: this.captured.x, y: this.captured.y}, |
| 148 | appear: [ |
| 149 | new PiPo({ |
| 150 | x: coords.x, |
| 151 | y: coords.y, |
| 152 | c: this.captured.c, |
| 153 | p: this.captured.p |
| 154 | }) |
| 155 | ], |
| 156 | vanish: [] |
| 157 | }); |
| 158 | res.drag = {c: this.captured.c, p: this.captured.p}; |
| 159 | return res; |
| 160 | } |
| 161 | return null; |
| 162 | } |
| 163 | |
| 164 | //////////////////// |
| 165 | // COORDINATES UTILS |
| 166 | |
| 167 | // 3a --> {x:3, y:10} |
| 168 | static SquareToCoords(sq) { |
| 169 | return ArrayFun.toObject(["x", "y"], |
| 170 | [0, 1].map(i => parseInt(sq[i], 36))); |
| 171 | } |
| 172 | |
| 173 | // {x:11, y:12} --> bc |
| 174 | static CoordsToSquare(cd) { |
| 175 | return Object.values(cd).map(c => c.toString(36)).join(""); |
| 176 | } |
| 177 | |
| 178 | coordsToId(cd) { |
| 179 | if (typeof cd.x == "number") { |
| 180 | return ( |
| 181 | `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}` |
| 182 | ); |
| 183 | } |
| 184 | // Reserve : |
| 185 | return `${this.containerId}|rsq-${cd.x}-${cd.y}`; |
| 186 | } |
| 187 | |
| 188 | idToCoords(targetId) { |
| 189 | if (!targetId) |
| 190 | return null; //outside page, maybe... |
| 191 | const idParts = targetId.split('|'); //prefix|sq-2-3 (start at 0 => 3,4) |
| 192 | if ( |
| 193 | idParts.length < 2 || |
| 194 | idParts[0] != this.containerId || |
| 195 | !idParts[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/) |
| 196 | ) { |
| 197 | return null; |
| 198 | } |
| 199 | const squares = idParts[1].split('-'); |
| 200 | if (squares[0] == "sq") |
| 201 | return {x: parseInt(squares[1], 36), y: parseInt(squares[2], 36)}; |
| 202 | // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece) |
| 203 | return {x: squares[1], y: squares[2]}; |
| 204 | } |
| 205 | |
| 206 | ///////////// |
| 207 | // FEN UTILS |
| 208 | |
| 209 | // Turn "wb" into "B" (for FEN) |
| 210 | board2fen(b) { |
| 211 | return (b[0] == "w" ? b[1].toUpperCase() : b[1]); |
| 212 | } |
| 213 | |
| 214 | // Turn "p" into "bp" (for board) |
| 215 | fen2board(f) { |
| 216 | return (f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f); |
| 217 | } |
| 218 | |
| 219 | genRandInitFen(seed) { |
| 220 | Random.setSeed(seed); //may be unused |
| 221 | let baseFen = this.genRandInitBaseFen(); |
| 222 | baseFen.o = Object.assign({init: true}, baseFen.o); |
| 223 | const parts = this.getPartFen(baseFen.o); |
| 224 | return ( |
| 225 | baseFen.fen + " w 0" + |
| 226 | (Object.keys(parts).length > 0 ? (" " + JSON.stringify(parts)) : "") |
| 227 | ); |
| 228 | } |
| 229 | |
| 230 | // Setup the initial random-or-not (asymmetric-or-not) position |
| 231 | genRandInitBaseFen() { |
| 232 | const s = FenUtil.setupPieces( |
| 233 | ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], |
| 234 | { |
| 235 | randomness: this.options["randomness"], |
| 236 | between: {p1: 'k', p2: 'r'}, |
| 237 | diffCol: ['b'], |
| 238 | flags: ['r'] |
| 239 | } |
| 240 | ); |
| 241 | return { |
| 242 | fen: s.b.join("") + "/pppppppp/8/8/8/8/PPPPPPPP/" + |
| 243 | s.w.join("").toUpperCase(), |
| 244 | o: {flags: s.flags} |
| 245 | }; |
| 246 | } |
| 247 | |
| 248 | // "Parse" FEN: just return untransformed string data |
| 249 | parseFen(fen) { |
| 250 | const fenParts = fen.split(" "); |
| 251 | let res = { |
| 252 | position: fenParts[0], |
| 253 | turn: fenParts[1], |
| 254 | movesCount: fenParts[2] |
| 255 | }; |
| 256 | if (fenParts.length > 3) |
| 257 | res = Object.assign(res, JSON.parse(fenParts[3])); |
| 258 | return res; |
| 259 | } |
| 260 | |
| 261 | // Return current fen (game state) |
| 262 | getFen() { |
| 263 | const parts = this.getPartFen({}); |
| 264 | return ( |
| 265 | this.getBaseFen() + |
| 266 | (Object.keys(parts).length > 0 ? (" " + JSON.stringify(parts)) : "") |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | getBaseFen() { |
| 271 | return this.getPosition() + " " + this.turn + " " + this.movesCount; |
| 272 | } |
| 273 | |
| 274 | getPartFen(o) { |
| 275 | let parts = {}; |
| 276 | if (this.hasFlags) |
| 277 | parts["flags"] = o.init ? o.flags : this.getFlagsFen(); |
| 278 | if (this.hasEnpassant) |
| 279 | parts["enpassant"] = o.init ? "-" : this.getEnpassantFen(); |
| 280 | if (this.hasReserveFen) |
| 281 | parts["reserve"] = this.getReserveFen(o); |
| 282 | if (this.options["crazyhouse"]) |
| 283 | parts["ispawn"] = this.getIspawnFen(o); |
| 284 | return parts; |
| 285 | } |
| 286 | |
| 287 | static FenEmptySquares(count) { |
| 288 | // if more than 9 consecutive free spaces, break the integer, |
| 289 | // otherwise FEN parsing will fail. |
| 290 | if (count <= 9) |
| 291 | return count; |
| 292 | // Most boards of size < 18: |
| 293 | if (count <= 18) |
| 294 | return "9" + (count - 9); |
| 295 | // Except Gomoku: |
| 296 | return "99" + (count - 18); |
| 297 | } |
| 298 | |
| 299 | // Position part of the FEN string |
| 300 | getPosition() { |
| 301 | let position = ""; |
| 302 | for (let i = 0; i < this.size.x; i++) { |
| 303 | let emptyCount = 0; |
| 304 | for (let j = 0; j < this.size.y; j++) { |
| 305 | if (this.board[i][j] == "") |
| 306 | emptyCount++; |
| 307 | else { |
| 308 | if (emptyCount > 0) { |
| 309 | // Add empty squares in-between |
| 310 | position += C.FenEmptySquares(emptyCount); |
| 311 | emptyCount = 0; |
| 312 | } |
| 313 | position += this.board2fen(this.board[i][j]); |
| 314 | } |
| 315 | } |
| 316 | if (emptyCount > 0) |
| 317 | // "Flush remainder" |
| 318 | position += C.FenEmptySquares(emptyCount); |
| 319 | if (i < this.size.x - 1) |
| 320 | position += "/"; //separate rows |
| 321 | } |
| 322 | return position; |
| 323 | } |
| 324 | |
| 325 | // Flags part of the FEN string |
| 326 | getFlagsFen() { |
| 327 | return ["w", "b"].map(c => { |
| 328 | return this.castleFlags[c].map(x => x.toString(36)).join(""); |
| 329 | }).join(""); |
| 330 | } |
| 331 | |
| 332 | // Enpassant part of the FEN string |
| 333 | getEnpassantFen() { |
| 334 | if (!this.epSquare) |
| 335 | return "-"; |
| 336 | return C.CoordsToSquare(this.epSquare); |
| 337 | } |
| 338 | |
| 339 | getReserveFen(o) { |
| 340 | if (o.init) |
| 341 | return "000000000000"; |
| 342 | return ( |
| 343 | ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("") |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | getIspawnFen(o) { |
| 348 | if (o.init) |
| 349 | // NOTE: cannot merge because this.ispawn doesn't exist yet |
| 350 | return "-"; |
| 351 | const squares = Object.keys(this.ispawn); |
| 352 | if (squares.length == 0) |
| 353 | return "-"; |
| 354 | return squares.join(","); |
| 355 | } |
| 356 | |
| 357 | // Set flags from fen (castle: white a,h then black a,h) |
| 358 | setFlags(fenflags) { |
| 359 | this.castleFlags = { |
| 360 | w: [0, 1].map(i => parseInt(fenflags.charAt(i), 36)), |
| 361 | b: [2, 3].map(i => parseInt(fenflags.charAt(i), 36)) |
| 362 | }; |
| 363 | } |
| 364 | |
| 365 | ////////////////// |
| 366 | // INITIALIZATION |
| 367 | |
| 368 | constructor(o) { |
| 369 | this.options = o.options; |
| 370 | // Fill missing options (always the case if random challenge) |
| 371 | (V.Options.select || []).concat(V.Options.input || []).forEach(opt => { |
| 372 | if (this.options[opt.variable] === undefined) |
| 373 | this.options[opt.variable] = opt.defaut; |
| 374 | }); |
| 375 | |
| 376 | // Some variables |
| 377 | this.playerColor = o.color; |
| 378 | this.afterPlay = o.afterPlay; //trigger some actions after playing a move |
| 379 | this.containerId = o.element; |
| 380 | this.isDiagram = o.diagram; |
| 381 | this.marks = o.marks; |
| 382 | |
| 383 | // Initializations |
| 384 | if (!o.fen) |
| 385 | o.fen = this.genRandInitFen(o.seed); |
| 386 | this.re_initFromFen(o.fen); |
| 387 | this.graphicalInit(); |
| 388 | } |
| 389 | |
| 390 | re_initFromFen(fen, oldBoard) { |
| 391 | const fenParsed = this.parseFen(fen); |
| 392 | this.board = oldBoard || this.getBoard(fenParsed.position); |
| 393 | this.turn = fenParsed.turn; |
| 394 | this.movesCount = parseInt(fenParsed.movesCount, 10); |
| 395 | this.setOtherVariables(fenParsed); |
| 396 | } |
| 397 | |
| 398 | // Turn position fen into double array ["wb","wp","bk",...] |
| 399 | getBoard(position) { |
| 400 | const rows = position.split("/"); |
| 401 | let board = ArrayFun.init(this.size.x, this.size.y, ""); |
| 402 | for (let i = 0; i < rows.length; i++) { |
| 403 | let j = 0; |
| 404 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) { |
| 405 | const character = rows[i][indexInRow]; |
| 406 | const num = parseInt(character, 10); |
| 407 | // If num is a number, just shift j: |
| 408 | if (!isNaN(num)) |
| 409 | j += num; |
| 410 | // Else: something at position i,j |
| 411 | else |
| 412 | board[i][j++] = this.fen2board(character); |
| 413 | } |
| 414 | } |
| 415 | return board; |
| 416 | } |
| 417 | |
| 418 | // Some additional variables from FEN (variant dependant) |
| 419 | setOtherVariables(fenParsed, pieceArray) { |
| 420 | // Set flags and enpassant: |
| 421 | if (this.hasFlags) |
| 422 | this.setFlags(fenParsed.flags); |
| 423 | if (this.hasEnpassant) |
| 424 | this.epSquare = this.getEpSquare(fenParsed.enpassant); |
| 425 | if (this.hasReserve && !this.isDiagram) |
| 426 | this.initReserves(fenParsed.reserve, pieceArray); |
| 427 | if (this.options["crazyhouse"]) |
| 428 | this.initIspawn(fenParsed.ispawn); |
| 429 | if (this.options["teleport"]) { |
| 430 | this.subTurnTeleport = 1; |
| 431 | this.captured = null; |
| 432 | } |
| 433 | if (this.options["dark"]) { |
| 434 | // Setup enlightened: squares reachable by player side |
| 435 | this.enlightened = ArrayFun.init(this.size.x, this.size.y, false); |
| 436 | this.updateEnlightened(); |
| 437 | } |
| 438 | this.subTurn = 1; //may be unused |
| 439 | if (!this.moveStack) //avoid resetting (unwanted) |
| 440 | this.moveStack = []; |
| 441 | } |
| 442 | |
| 443 | // ordering as in pieces() p,r,n,b,q,k |
| 444 | initReserves(reserveStr, pieceArray) { |
| 445 | if (!pieceArray) |
| 446 | pieceArray = ['p', 'r', 'n', 'b', 'q', 'k']; |
| 447 | const counts = reserveStr.split("").map(c => parseInt(c, 36)); |
| 448 | const L = pieceArray.length; |
| 449 | this.reserve = { |
| 450 | w: ArrayFun.toObject(pieceArray, counts.slice(0, L)), |
| 451 | b: ArrayFun.toObject(pieceArray, counts.slice(L, 2 * L)) |
| 452 | }; |
| 453 | } |
| 454 | |
| 455 | initIspawn(ispawnStr) { |
| 456 | if (ispawnStr != "-") |
| 457 | this.ispawn = ArrayFun.toObject(ispawnStr.split(","), true); |
| 458 | else |
| 459 | this.ispawn = {}; |
| 460 | } |
| 461 | |
| 462 | //////////////// |
| 463 | // VISUAL UTILS |
| 464 | |
| 465 | getPieceWidth(rwidth) { |
| 466 | return (rwidth / this.size.y); |
| 467 | } |
| 468 | |
| 469 | getReserveSquareSize(rwidth, nbR) { |
| 470 | const sqSize = this.getPieceWidth(rwidth); |
| 471 | return Math.min(sqSize, rwidth / nbR); |
| 472 | } |
| 473 | |
| 474 | getReserveNumId(color, piece) { |
| 475 | return `${this.containerId}|rnum-${color}${piece}`; |
| 476 | } |
| 477 | |
| 478 | getNbReservePieces(color) { |
| 479 | return ( |
| 480 | Object.values(this.reserve[color]).reduce( |
| 481 | (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0) |
| 482 | ); |
| 483 | } |
| 484 | |
| 485 | getRankInReserve(c, p) { |
| 486 | const pieces = Object.keys(this.pieces(c, c, p)); |
| 487 | const lastIndex = pieces.findIndex(pp => pp == p) |
| 488 | let toTest = pieces.slice(0, lastIndex); |
| 489 | return toTest.reduce( |
| 490 | (oldV,newV) => oldV + (this.reserve[c][newV] > 0 ? 1 : 0), 0); |
| 491 | } |
| 492 | |
| 493 | static AddClass_es(elt, class_es) { |
| 494 | if (!Array.isArray(class_es)) |
| 495 | class_es = [class_es]; |
| 496 | class_es.forEach(cl => elt.classList.add(cl)); |
| 497 | } |
| 498 | |
| 499 | static RemoveClass_es(elt, class_es) { |
| 500 | if (!Array.isArray(class_es)) |
| 501 | class_es = [class_es]; |
| 502 | class_es.forEach(cl => elt.classList.remove(cl)); |
| 503 | } |
| 504 | |
| 505 | // Generally light square bottom-right |
| 506 | getSquareColorClass(x, y) { |
| 507 | return ((x+y) % 2 == 0 ? "light-square": "dark-square"); |
| 508 | } |
| 509 | |
| 510 | getMaxDistance(r) { |
| 511 | // Works for all rectangular boards: |
| 512 | return Math.sqrt(r.width ** 2 + r.height ** 2); |
| 513 | } |
| 514 | |
| 515 | getDomPiece(x, y) { |
| 516 | return (typeof x == "string" ? this.r_pieces : this.g_pieces)[x][y]; |
| 517 | } |
| 518 | |
| 519 | ////////////////// |
| 520 | // VISUAL METHODS |
| 521 | |
| 522 | graphicalInit() { |
| 523 | const g_init = () => { |
| 524 | this.re_drawBoardElements(); |
| 525 | if (!this.isDiagram && !this.mouseListeners && !this.touchListeners) |
| 526 | this.initMouseEvents(); |
| 527 | }; |
| 528 | let container = document.getElementById(this.containerId); |
| 529 | this.windowResizeObs = new ResizeObserver(g_init); |
| 530 | this.windowResizeObs.observe(container); |
| 531 | } |
| 532 | |
| 533 | re_drawBoardElements() { |
| 534 | const board = this.getSvgChessboard(); |
| 535 | const container = document.getElementById(this.containerId); |
| 536 | const rc = container.getBoundingClientRect(); |
| 537 | let chessboard = container.querySelector(".chessboard"); |
| 538 | chessboard.innerHTML = ""; |
| 539 | chessboard.insertAdjacentHTML('beforeend', board); |
| 540 | // Compare window ratio width / height to aspectRatio: |
| 541 | const windowRatio = rc.width / rc.height; |
| 542 | let cbWidth, cbHeight; |
| 543 | const vRatio = this.size.ratio || 1; |
| 544 | if (windowRatio <= vRatio) { |
| 545 | // Limiting dimension is width: |
| 546 | cbWidth = Math.min(rc.width, 767); |
| 547 | cbHeight = cbWidth / vRatio; |
| 548 | } |
| 549 | else { |
| 550 | // Limiting dimension is height: |
| 551 | cbHeight = Math.min(rc.height, 767); |
| 552 | cbWidth = cbHeight * vRatio; |
| 553 | } |
| 554 | if (this.hasReserve && !this.isDiagram) { |
| 555 | const sqSize = cbWidth / this.size.y; |
| 556 | // NOTE: allocate space for reserves (up/down) even if they are empty |
| 557 | // Cannot use getReserveSquareSize() here, but sqSize is an upper bound. |
| 558 | if ((rc.height - cbHeight) / 2 < sqSize + 5) { |
| 559 | cbHeight = rc.height - 2 * (sqSize + 5); |
| 560 | cbWidth = cbHeight * vRatio; |
| 561 | } |
| 562 | } |
| 563 | chessboard.style.width = cbWidth + "px"; |
| 564 | chessboard.style.height = cbHeight + "px"; |
| 565 | // Center chessboard: |
| 566 | const spaceLeft = (rc.width - cbWidth) / 2, |
| 567 | spaceTop = (rc.height - cbHeight) / 2; |
| 568 | chessboard.style.left = spaceLeft + "px"; |
| 569 | chessboard.style.top = spaceTop + "px"; |
| 570 | // Give sizes instead of recomputing them, |
| 571 | // because chessboard might not be drawn yet. |
| 572 | this.setupVisualPieces({ |
| 573 | width: cbWidth, |
| 574 | height: cbHeight, |
| 575 | x: spaceLeft, |
| 576 | y: spaceTop |
| 577 | }); |
| 578 | } |
| 579 | |
| 580 | // Get SVG board (background, no pieces) |
| 581 | getSvgChessboard() { |
| 582 | const flipped = this.flippedBoard; |
| 583 | let board = ` |
| 584 | <svg |
| 585 | viewBox="0 0 ${10*this.size.y} ${10*this.size.x}" |
| 586 | class="chessboard_SVG">`; |
| 587 | for (let i=0; i < this.size.x; i++) { |
| 588 | for (let j=0; j < this.size.y; j++) { |
| 589 | if (!this.onBoard(i, j)) |
| 590 | continue; |
| 591 | const ii = (flipped ? this.size.x - 1 - i : i); |
| 592 | const jj = (flipped ? this.size.y - 1 - j : j); |
| 593 | let classes = this.getSquareColorClass(ii, jj); |
| 594 | if (this.enlightened && !this.enlightened[ii][jj]) |
| 595 | classes += " in-shadow"; |
| 596 | // NOTE: x / y reversed because coordinates system is reversed. |
| 597 | board += ` |
| 598 | <rect |
| 599 | class="${classes}" |
| 600 | id="${this.coordsToId({x: ii, y: jj})}" |
| 601 | width="10" |
| 602 | height="10" |
| 603 | x="${10*j}" |
| 604 | y="${10*i}" |
| 605 | />`; |
| 606 | } |
| 607 | } |
| 608 | board += "</svg>"; |
| 609 | return board; |
| 610 | } |
| 611 | |
| 612 | setupVisualPieces(r) { |
| 613 | let chessboard = |
| 614 | document.getElementById(this.containerId).querySelector(".chessboard"); |
| 615 | if (!r) |
| 616 | r = chessboard.getBoundingClientRect(); |
| 617 | const pieceWidth = this.getPieceWidth(r.width); |
| 618 | const addPiece = (i, j, arrName, classes) => { |
| 619 | this[arrName][i][j] = document.createElement("piece"); |
| 620 | C.AddClass_es(this[arrName][i][j], classes); |
| 621 | this[arrName][i][j].style.width = pieceWidth + "px"; |
| 622 | this[arrName][i][j].style.height = pieceWidth + "px"; |
| 623 | let [ip, jp] = this.getPixelPosition(i, j, r); |
| 624 | // Translate coordinates to use chessboard as reference: |
| 625 | this[arrName][i][j].style.transform = |
| 626 | `translate(${ip - r.x}px,${jp - r.y}px)`; |
| 627 | chessboard.appendChild(this[arrName][i][j]); |
| 628 | }; |
| 629 | const conditionalReset = (arrName) => { |
| 630 | if (this[arrName]) { |
| 631 | // Refreshing: delete old pieces first. This isn't necessary, |
| 632 | // but simpler (this method isn't called many times) |
| 633 | for (let i=0; i<this.size.x; i++) { |
| 634 | for (let j=0; j<this.size.y; j++) { |
| 635 | if (this[arrName][i][j]) { |
| 636 | this[arrName][i][j].remove(); |
| 637 | this[arrName][i][j] = null; |
| 638 | } |
| 639 | } |
| 640 | } |
| 641 | } |
| 642 | else |
| 643 | this[arrName] = ArrayFun.init(this.size.x, this.size.y, null); |
| 644 | if (arrName == "d_pieces") |
| 645 | this.marks.forEach(([i, j]) => addPiece(i, j, arrName, "mark")); |
| 646 | }; |
| 647 | if (this.marks) |
| 648 | conditionalReset("d_pieces"); |
| 649 | conditionalReset("g_pieces"); |
| 650 | for (let i=0; i < this.size.x; i++) { |
| 651 | for (let j=0; j < this.size.y; j++) { |
| 652 | if (this.board[i][j] != "") { |
| 653 | const color = this.getColor(i, j); |
| 654 | const piece = this.getPiece(i, j); |
| 655 | addPiece(i, j, "g_pieces", this.pieces(color, i, j)[piece]["class"]); |
| 656 | this.g_pieces[i][j].classList.add(V.GetColorClass(color)); |
| 657 | if (this.enlightened && !this.enlightened[i][j]) |
| 658 | this.g_pieces[i][j].classList.add("hidden"); |
| 659 | } |
| 660 | if (this.marks && this.d_pieces[i][j]) { |
| 661 | let classes = ["mark"]; |
| 662 | if (this.board[i][j] != "") |
| 663 | classes.push("transparent"); |
| 664 | addPiece(i, j, "d_pieces", classes); |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | if (this.hasReserve && !this.isDiagram) |
| 669 | this.re_drawReserve(['w', 'b'], r); |
| 670 | } |
| 671 | |
| 672 | // NOTE: assume this.reserve != null |
| 673 | re_drawReserve(colors, r) { |
| 674 | if (this.r_pieces) { |
| 675 | // Remove (old) reserve pieces |
| 676 | for (let c of colors) { |
| 677 | Object.keys(this.r_pieces[c]).forEach(p => { |
| 678 | this.r_pieces[c][p].remove(); |
| 679 | delete this.r_pieces[c][p]; |
| 680 | const numId = this.getReserveNumId(c, p); |
| 681 | document.getElementById(numId).remove(); |
| 682 | }); |
| 683 | } |
| 684 | } |
| 685 | else |
| 686 | this.r_pieces = { w: {}, b: {} }; |
| 687 | let container = document.getElementById(this.containerId); |
| 688 | if (!r) |
| 689 | r = container.querySelector(".chessboard").getBoundingClientRect(); |
| 690 | for (let c of colors) { |
| 691 | let reservesDiv = document.getElementById("reserves_" + c); |
| 692 | if (reservesDiv) |
| 693 | reservesDiv.remove(); |
| 694 | if (!this.reserve[c]) |
| 695 | continue; |
| 696 | const nbR = this.getNbReservePieces(c); |
| 697 | if (nbR == 0) |
| 698 | continue; |
| 699 | const sqResSize = this.getReserveSquareSize(r.width, nbR); |
| 700 | let ridx = 0; |
| 701 | const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5); |
| 702 | const [i0, j0] = [r.x, r.y + vShift]; |
| 703 | let rcontainer = document.createElement("div"); |
| 704 | rcontainer.id = "reserves_" + c; |
| 705 | rcontainer.classList.add("reserves"); |
| 706 | rcontainer.style.left = i0 + "px"; |
| 707 | rcontainer.style.top = j0 + "px"; |
| 708 | // NOTE: +1 fix display bug on Firefox at least |
| 709 | rcontainer.style.width = (nbR * sqResSize + 1) + "px"; |
| 710 | rcontainer.style.height = sqResSize + "px"; |
| 711 | container.appendChild(rcontainer); |
| 712 | for (let p of Object.keys(this.reserve[c])) { |
| 713 | if (this.reserve[c][p] == 0) |
| 714 | continue; |
| 715 | let r_cell = document.createElement("div"); |
| 716 | r_cell.id = this.coordsToId({x: c, y: p}); |
| 717 | r_cell.classList.add("reserve-cell"); |
| 718 | r_cell.style.width = sqResSize + "px"; |
| 719 | r_cell.style.height = sqResSize + "px"; |
| 720 | rcontainer.appendChild(r_cell); |
| 721 | let piece = document.createElement("piece"); |
| 722 | C.AddClass_es(piece, this.pieces(c, c, p)[p]["class"]); |
| 723 | piece.classList.add(V.GetColorClass(c)); |
| 724 | piece.style.width = "100%"; |
| 725 | piece.style.height = "100%"; |
| 726 | this.r_pieces[c][p] = piece; |
| 727 | r_cell.appendChild(piece); |
| 728 | let number = document.createElement("div"); |
| 729 | number.textContent = this.reserve[c][p]; |
| 730 | number.classList.add("reserve-num"); |
| 731 | number.id = this.getReserveNumId(c, p); |
| 732 | const fontSize = "1.3em"; |
| 733 | number.style.fontSize = fontSize; |
| 734 | number.style.fontSize = fontSize; |
| 735 | r_cell.appendChild(number); |
| 736 | ridx++; |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | updateReserve(color, piece, count) { |
| 742 | if (this.options["cannibal"] && C.CannibalKings[piece]) |
| 743 | piece = "k"; //capturing cannibal king: back to king form |
| 744 | const oldCount = this.reserve[color][piece]; |
| 745 | this.reserve[color][piece] = count; |
| 746 | // Redrawing is much easier if count==0 (or undefined) |
| 747 | if ([oldCount, count].some(item => !item)) |
| 748 | this.re_drawReserve([color]); |
| 749 | else { |
| 750 | const numId = this.getReserveNumId(color, piece); |
| 751 | document.getElementById(numId).textContent = count; |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | // Resize board: no need to destroy/recreate pieces |
| 756 | rescale(mode) { |
| 757 | const container = document.getElementById(this.containerId); |
| 758 | let chessboard = container.querySelector(".chessboard"); |
| 759 | const rc = container.getBoundingClientRect(), |
| 760 | r = chessboard.getBoundingClientRect(); |
| 761 | const multFact = (mode == "up" ? 1.05 : 0.95); |
| 762 | let [newWidth, newHeight] = [multFact * r.width, multFact * r.height]; |
| 763 | // Stay in window: |
| 764 | const vRatio = this.size.ratio || 1; |
| 765 | if (newWidth > rc.width) { |
| 766 | newWidth = rc.width; |
| 767 | newHeight = newWidth / vRatio; |
| 768 | } |
| 769 | if (newHeight > rc.height) { |
| 770 | newHeight = rc.height; |
| 771 | newWidth = newHeight * vRatio; |
| 772 | } |
| 773 | chessboard.style.width = newWidth + "px"; |
| 774 | chessboard.style.height = newHeight + "px"; |
| 775 | const newX = (rc.width - newWidth) / 2; |
| 776 | chessboard.style.left = newX + "px"; |
| 777 | const newY = (rc.height - newHeight) / 2; |
| 778 | chessboard.style.top = newY + "px"; |
| 779 | const newR = {x: newX, y: newY, width: newWidth, height: newHeight}; |
| 780 | const pieceWidth = this.getPieceWidth(newWidth); |
| 781 | // NOTE: next "if" for variants which use squares filling |
| 782 | // instead of "physical", moving pieces |
| 783 | if (this.g_pieces) { |
| 784 | for (let i=0; i < this.size.x; i++) { |
| 785 | for (let j=0; j < this.size.y; j++) { |
| 786 | if (this.g_pieces[i][j]) { |
| 787 | // NOTE: could also use CSS transform "scale" |
| 788 | this.g_pieces[i][j].style.width = pieceWidth + "px"; |
| 789 | this.g_pieces[i][j].style.height = pieceWidth + "px"; |
| 790 | const [ip, jp] = this.getPixelPosition(i, j, newR); |
| 791 | // Translate coordinates to use chessboard as reference: |
| 792 | this.g_pieces[i][j].style.transform = |
| 793 | `translate(${ip - newX}px,${jp - newY}px)`; |
| 794 | } |
| 795 | } |
| 796 | } |
| 797 | } |
| 798 | if (this.hasReserve) |
| 799 | this.rescaleReserve(newR); |
| 800 | } |
| 801 | |
| 802 | rescaleReserve(r) { |
| 803 | for (let c of ['w','b']) { |
| 804 | if (!this.reserve[c]) |
| 805 | continue; |
| 806 | const nbR = this.getNbReservePieces(c); |
| 807 | if (nbR == 0) |
| 808 | continue; |
| 809 | // Resize container first |
| 810 | const sqResSize = this.getReserveSquareSize(r.width, nbR); |
| 811 | const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5); |
| 812 | const [i0, j0] = [r.x, r.y + vShift]; |
| 813 | let rcontainer = document.getElementById("reserves_" + c); |
| 814 | rcontainer.style.left = i0 + "px"; |
| 815 | rcontainer.style.top = j0 + "px"; |
| 816 | rcontainer.style.width = (nbR * sqResSize + 1) + "px"; |
| 817 | rcontainer.style.height = sqResSize + "px"; |
| 818 | // And then reserve cells: |
| 819 | const rpieceWidth = this.getReserveSquareSize(r.width, nbR); |
| 820 | Object.keys(this.reserve[c]).forEach(p => { |
| 821 | if (this.reserve[c][p] == 0) |
| 822 | return; |
| 823 | let r_cell = document.getElementById(this.coordsToId({x: c, y: p})); |
| 824 | r_cell.style.width = sqResSize + "px"; |
| 825 | r_cell.style.height = sqResSize + "px"; |
| 826 | }); |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | // Return the absolute pixel coordinates given current position. |
| 831 | // Our coordinate system differs from CSS one (x <--> y). |
| 832 | // We return here the CSS coordinates (more useful). |
| 833 | getPixelPosition(i, j, r) { |
| 834 | if (i < 0 || j < 0) |
| 835 | return [0, 0]; //piece vanishes |
| 836 | let x, y; |
| 837 | if (typeof i == "string") { |
| 838 | // Reserves: need to know the rank of piece |
| 839 | const nbR = this.getNbReservePieces(i); |
| 840 | const rsqSize = this.getReserveSquareSize(r.width, nbR); |
| 841 | x = this.getRankInReserve(i, j) * rsqSize; |
| 842 | y = (this.playerColor == i ? y = r.height + 5 : - 5 - rsqSize); |
| 843 | } |
| 844 | else { |
| 845 | const sqSize = r.width / this.size.y; |
| 846 | const flipped = this.flippedBoard; |
| 847 | x = (flipped ? this.size.y - 1 - j : j) * sqSize; |
| 848 | y = (flipped ? this.size.x - 1 - i : i) * sqSize; |
| 849 | } |
| 850 | return [r.x + x, r.y + y]; |
| 851 | } |
| 852 | |
| 853 | initMouseEvents() { |
| 854 | let container = document.getElementById(this.containerId); |
| 855 | let chessboard = container.querySelector(".chessboard"); |
| 856 | |
| 857 | const getOffset = e => { |
| 858 | if (e.clientX) |
| 859 | // Mouse |
| 860 | return {x: e.clientX, y: e.clientY}; |
| 861 | let touchLocation = null; |
| 862 | if (e.targetTouches && e.targetTouches.length >= 1) |
| 863 | // Touch screen, dragstart |
| 864 | touchLocation = e.targetTouches[0]; |
| 865 | else if (e.changedTouches && e.changedTouches.length >= 1) |
| 866 | // Touch screen, dragend |
| 867 | touchLocation = e.changedTouches[0]; |
| 868 | if (touchLocation) |
| 869 | return {x: touchLocation.clientX, y: touchLocation.clientY}; |
| 870 | return {x: 0, y: 0}; //shouldn't reach here =) |
| 871 | } |
| 872 | |
| 873 | const centerOnCursor = (piece, e) => { |
| 874 | const centerShift = this.getPieceWidth(r.width) / 2; |
| 875 | const offset = getOffset(e); |
| 876 | piece.style.left = (offset.x - centerShift) + "px"; |
| 877 | piece.style.top = (offset.y - centerShift) + "px"; |
| 878 | } |
| 879 | |
| 880 | let start = null, |
| 881 | r = null, |
| 882 | startPiece, curPiece = null, |
| 883 | pieceWidth; |
| 884 | const mousedown = (e) => { |
| 885 | // Disable zoom on smartphones: |
| 886 | if (e.touches && e.touches.length > 1) |
| 887 | e.preventDefault(); |
| 888 | r = chessboard.getBoundingClientRect(); |
| 889 | pieceWidth = this.getPieceWidth(r.width); |
| 890 | const cd = this.idToCoords(e.target.id); |
| 891 | if (cd) { |
| 892 | const move = this.doClick(cd); |
| 893 | if (move) |
| 894 | this.buildMoveStack(move, r); |
| 895 | else if (!this.clickOnly) { |
| 896 | const [x, y] = Object.values(cd); |
| 897 | if (typeof x != "number") |
| 898 | startPiece = this.r_pieces[x][y]; |
| 899 | else |
| 900 | startPiece = this.g_pieces[x][y]; |
| 901 | if (startPiece && this.canIplay(x, y)) { |
| 902 | e.preventDefault(); |
| 903 | start = cd; |
| 904 | curPiece = startPiece.cloneNode(); |
| 905 | curPiece.style.transform = "none"; |
| 906 | curPiece.style.zIndex = 5; |
| 907 | curPiece.style.width = pieceWidth + "px"; |
| 908 | curPiece.style.height = pieceWidth + "px"; |
| 909 | centerOnCursor(curPiece, e); |
| 910 | container.appendChild(curPiece); |
| 911 | startPiece.style.opacity = "0.4"; |
| 912 | chessboard.style.cursor = "none"; |
| 913 | } |
| 914 | } |
| 915 | } |
| 916 | }; |
| 917 | |
| 918 | const mousemove = (e) => { |
| 919 | if (start) { |
| 920 | e.preventDefault(); |
| 921 | centerOnCursor(curPiece, e); |
| 922 | } |
| 923 | else if (e.changedTouches && e.changedTouches.length >= 1) |
| 924 | // Attempt to prevent horizontal swipe... |
| 925 | e.preventDefault(); |
| 926 | }; |
| 927 | |
| 928 | const mouseup = (e) => { |
| 929 | if (!start) |
| 930 | return; |
| 931 | const [x, y] = [start.x, start.y]; |
| 932 | start = null; |
| 933 | e.preventDefault(); |
| 934 | chessboard.style.cursor = "pointer"; |
| 935 | startPiece.style.opacity = "1"; |
| 936 | const offset = getOffset(e); |
| 937 | const landingElt = document.elementFromPoint(offset.x, offset.y); |
| 938 | const cd = |
| 939 | (landingElt ? this.idToCoords(landingElt.id) : undefined); |
| 940 | if (cd) { |
| 941 | // NOTE: clearly suboptimal, but much easier, and not a big deal. |
| 942 | const potentialMoves = this.getPotentialMovesFrom([x, y]) |
| 943 | .filter(m => m.end.x == cd.x && m.end.y == cd.y); |
| 944 | const moves = this.filterValid(potentialMoves); |
| 945 | if (moves.length >= 2) |
| 946 | this.showChoices(moves, r); |
| 947 | else if (moves.length == 1) |
| 948 | this.buildMoveStack(moves[0], r); |
| 949 | } |
| 950 | curPiece.remove(); |
| 951 | }; |
| 952 | |
| 953 | const resize = (e) => this.rescale(e.deltaY < 0 ? "up" : "down"); |
| 954 | |
| 955 | if ('onmousedown' in window) { |
| 956 | this.mouseListeners = [ |
| 957 | {type: "mousedown", listener: mousedown}, |
| 958 | {type: "mousemove", listener: mousemove}, |
| 959 | {type: "mouseup", listener: mouseup}, |
| 960 | {type: "wheel", listener: resize} |
| 961 | ]; |
| 962 | this.mouseListeners.forEach(ml => { |
| 963 | document.addEventListener(ml.type, ml.listener); |
| 964 | }); |
| 965 | } |
| 966 | if ('ontouchstart' in window) { |
| 967 | this.touchListeners = [ |
| 968 | {type: "touchstart", listener: mousedown}, |
| 969 | {type: "touchmove", listener: mousemove}, |
| 970 | {type: "touchend", listener: mouseup} |
| 971 | ]; |
| 972 | this.touchListeners.forEach(tl => { |
| 973 | // https://stackoverflow.com/a/42509310/12660887 |
| 974 | document.addEventListener(tl.type, tl.listener, {passive: false}); |
| 975 | }); |
| 976 | } |
| 977 | // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js |
| 978 | } |
| 979 | |
| 980 | // NOTE: not called if isDiagram |
| 981 | removeListeners() { |
| 982 | let container = document.getElementById(this.containerId); |
| 983 | this.windowResizeObs.unobserve(container); |
| 984 | if ('onmousedown' in window) { |
| 985 | this.mouseListeners.forEach(ml => { |
| 986 | document.removeEventListener(ml.type, ml.listener); |
| 987 | }); |
| 988 | } |
| 989 | if ('ontouchstart' in window) { |
| 990 | this.touchListeners.forEach(tl => { |
| 991 | // https://stackoverflow.com/a/42509310/12660887 |
| 992 | document.removeEventListener(tl.type, tl.listener); |
| 993 | }); |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | showChoices(moves, r) { |
| 998 | let container = document.getElementById(this.containerId); |
| 999 | let chessboard = container.querySelector(".chessboard"); |
| 1000 | let choices = document.createElement("div"); |
| 1001 | choices.id = "choices"; |
| 1002 | if (!r) |
| 1003 | r = chessboard.getBoundingClientRect(); |
| 1004 | choices.style.width = r.width + "px"; |
| 1005 | choices.style.height = r.height + "px"; |
| 1006 | choices.style.left = r.x + "px"; |
| 1007 | choices.style.top = r.y + "px"; |
| 1008 | chessboard.style.opacity = "0.5"; |
| 1009 | container.appendChild(choices); |
| 1010 | const squareWidth = r.width / this.size.y; |
| 1011 | const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2; |
| 1012 | const firstUpTop = (r.height - squareWidth) / 2; |
| 1013 | const color = moves[0].appear[0].c; |
| 1014 | const callback = (m) => { |
| 1015 | chessboard.style.opacity = "1"; |
| 1016 | container.removeChild(choices); |
| 1017 | this.buildMoveStack(m, r); |
| 1018 | } |
| 1019 | for (let i=0; i < moves.length; i++) { |
| 1020 | let choice = document.createElement("div"); |
| 1021 | choice.classList.add("choice"); |
| 1022 | choice.style.width = squareWidth + "px"; |
| 1023 | choice.style.height = squareWidth + "px"; |
| 1024 | choice.style.left = (firstUpLeft + i * squareWidth) + "px"; |
| 1025 | choice.style.top = firstUpTop + "px"; |
| 1026 | choice.style.backgroundColor = "lightyellow"; |
| 1027 | choice.onclick = () => callback(moves[i]); |
| 1028 | const piece = document.createElement("piece"); |
| 1029 | const cdisp = moves[i].choice || moves[i].appear[0].p; |
| 1030 | C.AddClass_es(piece, |
| 1031 | this.pieces(color, moves[i].end.x, moves[i].end.y)[cdisp]["class"]); |
| 1032 | piece.classList.add(V.GetColorClass(color)); |
| 1033 | piece.style.width = "100%"; |
| 1034 | piece.style.height = "100%"; |
| 1035 | choice.appendChild(piece); |
| 1036 | choices.appendChild(choice); |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | displayMessage(elt, msg, classe_s, timeout) { |
| 1041 | if (elt) |
| 1042 | // Fixed element, e.g. for Dice Chess |
| 1043 | elt.innerHTML = msg; |
| 1044 | else { |
| 1045 | // Temporary div (Chakart, Apocalypse...) |
| 1046 | let divMsg = document.createElement("div"); |
| 1047 | C.AddClass_es(divMsg, classe_s); |
| 1048 | divMsg.innerHTML = msg; |
| 1049 | let container = document.getElementById(this.containerId); |
| 1050 | container.appendChild(divMsg); |
| 1051 | setTimeout(() => container.removeChild(divMsg), timeout); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | //////////////// |
| 1056 | // DARK METHODS |
| 1057 | |
| 1058 | updateEnlightened() { |
| 1059 | this.oldEnlightened = this.enlightened; |
| 1060 | this.enlightened = ArrayFun.init(this.size.x, this.size.y, false); |
| 1061 | // Add pieces positions + all squares reachable by moves (includes Zen): |
| 1062 | for (let x=0; x<this.size.x; x++) { |
| 1063 | for (let y=0; y<this.size.y; y++) { |
| 1064 | if (this.board[x][y] != "" && this.getColor(x, y) == this.playerColor) |
| 1065 | { |
| 1066 | this.enlightened[x][y] = true; |
| 1067 | this.getPotentialMovesFrom([x, y]).forEach(m => { |
| 1068 | this.enlightened[m.end.x][m.end.y] = true; |
| 1069 | }); |
| 1070 | } |
| 1071 | } |
| 1072 | } |
| 1073 | if (this.epSquare) |
| 1074 | this.enlightEnpassant(); |
| 1075 | } |
| 1076 | |
| 1077 | // Include square of the en-passant capturing square: |
| 1078 | enlightEnpassant() { |
| 1079 | // NOTE: shortcut, pawn has only one attack type, doesn't depend on square |
| 1080 | // TODO: (0, 0) is wrong, would need to place an attacker here... |
| 1081 | const steps = this.pieces(this.playerColor, 0, 0)["p"].attack[0].steps; |
| 1082 | for (let step of steps) { |
| 1083 | const x = this.epSquare.x - step[0], //NOTE: epSquare.x not on edge |
| 1084 | y = this.getY(this.epSquare.y - step[1]); |
| 1085 | if ( |
| 1086 | this.onBoard(x, y) && |
| 1087 | this.getColor(x, y) == this.playerColor && |
| 1088 | this.getPieceType(x, y) == "p" |
| 1089 | ) { |
| 1090 | this.enlightened[x][this.epSquare.y] = true; |
| 1091 | break; |
| 1092 | } |
| 1093 | } |
| 1094 | } |
| 1095 | |
| 1096 | // Apply diff this.enlightened --> oldEnlightened on board |
| 1097 | graphUpdateEnlightened() { |
| 1098 | let chessboard = |
| 1099 | document.getElementById(this.containerId).querySelector(".chessboard"); |
| 1100 | const r = chessboard.getBoundingClientRect(); |
| 1101 | const pieceWidth = this.getPieceWidth(r.width); |
| 1102 | for (let x=0; x<this.size.x; x++) { |
| 1103 | for (let y=0; y<this.size.y; y++) { |
| 1104 | if (!this.enlightened[x][y] && this.oldEnlightened[x][y]) { |
| 1105 | let elt = document.getElementById(this.coordsToId({x: x, y: y})); |
| 1106 | elt.classList.add("in-shadow"); |
| 1107 | if (this.g_pieces[x][y]) |
| 1108 | this.g_pieces[x][y].classList.add("hidden"); |
| 1109 | } |
| 1110 | else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) { |
| 1111 | let elt = document.getElementById(this.coordsToId({x: x, y: y})); |
| 1112 | elt.classList.remove("in-shadow"); |
| 1113 | if (this.g_pieces[x][y]) |
| 1114 | this.g_pieces[x][y].classList.remove("hidden"); |
| 1115 | } |
| 1116 | } |
| 1117 | } |
| 1118 | } |
| 1119 | |
| 1120 | ////////////// |
| 1121 | // BASIC UTILS |
| 1122 | |
| 1123 | get size() { |
| 1124 | return { |
| 1125 | x: 8, |
| 1126 | y: 8, |
| 1127 | ratio: 1 //for rectangular board = y / x (optional, 1 = default) |
| 1128 | }; |
| 1129 | } |
| 1130 | |
| 1131 | // Color of thing on square (i,j). '' if square is empty |
| 1132 | getColor(i, j) { |
| 1133 | if (typeof i == "string") |
| 1134 | return i; //reserves |
| 1135 | return this.board[i][j].charAt(0); |
| 1136 | } |
| 1137 | |
| 1138 | static GetColorClass(c) { |
| 1139 | if (c == 'w') |
| 1140 | return "white"; |
| 1141 | if (c == 'b') |
| 1142 | return "black"; |
| 1143 | return "other-color"; //unidentified color |
| 1144 | } |
| 1145 | |
| 1146 | // Piece on i,j. '' if square is empty |
| 1147 | getPiece(i, j) { |
| 1148 | if (typeof j == "string") |
| 1149 | return j; //reserves |
| 1150 | return this.board[i][j].charAt(1); |
| 1151 | } |
| 1152 | |
| 1153 | // Piece type on square (i,j) |
| 1154 | getPieceType(x, y, p) { |
| 1155 | if (!p) |
| 1156 | p = this.getPiece(x, y); |
| 1157 | return this.pieces(this.getColor(x, y), x, y)[p].moveas || p; |
| 1158 | } |
| 1159 | |
| 1160 | isKing(x, y, p) { |
| 1161 | if (!p) |
| 1162 | p = this.getPiece(x, y); |
| 1163 | if (!this.options["cannibal"]) |
| 1164 | return p == 'k'; |
| 1165 | return !!C.CannibalKings[p]; |
| 1166 | } |
| 1167 | |
| 1168 | static GetOppTurn(color) { |
| 1169 | return (color == 'w' ? 'b' : 'w'); |
| 1170 | } |
| 1171 | |
| 1172 | // Get opponent color(s): may differ from turn (e.g. Checkered) |
| 1173 | getOppCols(color) { |
| 1174 | return (color == "w" ? "b" : "w"); |
| 1175 | } |
| 1176 | |
| 1177 | // Is (x,y) on the chessboard? |
| 1178 | onBoard(x, y) { |
| 1179 | return (x >= 0 && x < this.size.x && |
| 1180 | y >= 0 && y < this.size.y); |
| 1181 | } |
| 1182 | |
| 1183 | // Am I allowed to move thing at square x,y ? |
| 1184 | canIplay(x, y) { |
| 1185 | return (this.playerColor == this.turn && this.getColor(x, y) == this.turn); |
| 1186 | } |
| 1187 | |
| 1188 | //////////////////////// |
| 1189 | // PIECES SPECIFICATIONS |
| 1190 | |
| 1191 | getPawnShift(color) { |
| 1192 | return (color == "w" ? -1 : 1); |
| 1193 | } |
| 1194 | isPawnInitRank(x, color) { |
| 1195 | return (color == 'w' && x >= 6) || (color == 'b' && x <= 1); |
| 1196 | } |
| 1197 | |
| 1198 | pieces(color, x, y) { |
| 1199 | const pawnShift = this.getPawnShift(color || 'w'); |
| 1200 | return { |
| 1201 | 'p': { |
| 1202 | "class": "pawn", |
| 1203 | moves: [ |
| 1204 | { |
| 1205 | steps: [[pawnShift, 0]], |
| 1206 | range: (this.isPawnInitRank(x, color) ? 2 : 1) |
| 1207 | } |
| 1208 | ], |
| 1209 | attack: [ |
| 1210 | { |
| 1211 | steps: [[pawnShift, 1], [pawnShift, -1]], |
| 1212 | range: 1 |
| 1213 | } |
| 1214 | ] |
| 1215 | }, |
| 1216 | 'r': { |
| 1217 | "class": "rook", |
| 1218 | both: [ |
| 1219 | {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]} |
| 1220 | ] |
| 1221 | }, |
| 1222 | 'n': { |
| 1223 | "class": "knight", |
| 1224 | both: [ |
| 1225 | { |
| 1226 | steps: [ |
| 1227 | [1, 2], [1, -2], [-1, 2], [-1, -2], |
| 1228 | [2, 1], [-2, 1], [2, -1], [-2, -1] |
| 1229 | ], |
| 1230 | range: 1 |
| 1231 | } |
| 1232 | ] |
| 1233 | }, |
| 1234 | 'b': { |
| 1235 | "class": "bishop", |
| 1236 | both: [ |
| 1237 | {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]} |
| 1238 | ] |
| 1239 | }, |
| 1240 | 'q': { |
| 1241 | "class": "queen", |
| 1242 | both: [ |
| 1243 | { |
| 1244 | steps: [ |
| 1245 | [0, 1], [0, -1], [1, 0], [-1, 0], |
| 1246 | [1, 1], [1, -1], [-1, 1], [-1, -1] |
| 1247 | ] |
| 1248 | } |
| 1249 | ] |
| 1250 | }, |
| 1251 | 'k': { |
| 1252 | "class": "king", |
| 1253 | both: [ |
| 1254 | { |
| 1255 | steps: [ |
| 1256 | [0, 1], [0, -1], [1, 0], [-1, 0], |
| 1257 | [1, 1], [1, -1], [-1, 1], [-1, -1] |
| 1258 | ], |
| 1259 | range: 1 |
| 1260 | } |
| 1261 | ] |
| 1262 | }, |
| 1263 | // Cannibal kings: |
| 1264 | '!': {"class": "king-pawn", moveas: "p"}, |
| 1265 | '#': {"class": "king-rook", moveas: "r"}, |
| 1266 | '$': {"class": "king-knight", moveas: "n"}, |
| 1267 | '%': {"class": "king-bishop", moveas: "b"}, |
| 1268 | '*': {"class": "king-queen", moveas: "q"} |
| 1269 | }; |
| 1270 | } |
| 1271 | |
| 1272 | // NOTE: using special symbols to not interfere with variants' pieces codes |
| 1273 | static get CannibalKings() { |
| 1274 | return { |
| 1275 | "!": "p", |
| 1276 | "#": "r", |
| 1277 | "$": "n", |
| 1278 | "%": "b", |
| 1279 | "*": "q", |
| 1280 | "k": "k" |
| 1281 | }; |
| 1282 | } |
| 1283 | |
| 1284 | static get CannibalKingCode() { |
| 1285 | return { |
| 1286 | "p": "!", |
| 1287 | "r": "#", |
| 1288 | "n": "$", |
| 1289 | "b": "%", |
| 1290 | "q": "*", |
| 1291 | "k": "k" |
| 1292 | }; |
| 1293 | } |
| 1294 | |
| 1295 | ////////////////////////// |
| 1296 | // MOVES GENERATION UTILS |
| 1297 | |
| 1298 | // For Cylinder: get Y coordinate |
| 1299 | getY(y) { |
| 1300 | if (!this.options["cylinder"]) |
| 1301 | return y; |
| 1302 | let res = y % this.size.y; |
| 1303 | if (res < 0) |
| 1304 | res += this.size.y; |
| 1305 | return res; |
| 1306 | } |
| 1307 | // Circular? |
| 1308 | getX(x) { |
| 1309 | return x; //generally, no |
| 1310 | } |
| 1311 | |
| 1312 | increment([x, y], step) { |
| 1313 | return [ |
| 1314 | this.getX(x + step[0]), |
| 1315 | this.getY(y + step[1]) |
| 1316 | ]; |
| 1317 | } |
| 1318 | |
| 1319 | getSegments(curSeg, segStart, segEnd) { |
| 1320 | if (curSeg.length == 0) |
| 1321 | return undefined; |
| 1322 | let segments = JSON.parse(JSON.stringify(curSeg)); //not altering |
| 1323 | segments.push([[segStart[0], segStart[1]], [segEnd[0], segEnd[1]]]); |
| 1324 | return segments; |
| 1325 | } |
| 1326 | |
| 1327 | getStepSpec(color, x, y, piece) { |
| 1328 | let pieceType = piece; |
| 1329 | let allSpecs = this.pieces(color, x, y); |
| 1330 | if (!piece) |
| 1331 | pieceType = this.getPieceType(x, y); |
| 1332 | else if (allSpecs[piece].moveas) |
| 1333 | pieceType = allSpecs[piece].moveas; |
| 1334 | let res = allSpecs[pieceType]; |
| 1335 | if (!res["both"]) |
| 1336 | res.both = []; |
| 1337 | if (!res["moves"]) |
| 1338 | res.moves = []; |
| 1339 | if (!res["attack"]) |
| 1340 | res.attack = []; |
| 1341 | return res; |
| 1342 | } |
| 1343 | |
| 1344 | // Can thing on square1 capture thing on square2? |
| 1345 | canTake([x1, y1], [x2, y2]) { |
| 1346 | return this.getColor(x1, y1) !== this.getColor(x2, y2); |
| 1347 | } |
| 1348 | |
| 1349 | // Teleport & Recycle. Assumption: color(x1,y1) == color(x2,y2) |
| 1350 | canSelfTake([x1, y1], [x2, y2]) { |
| 1351 | return !this.isKing(x2, y2); |
| 1352 | } |
| 1353 | |
| 1354 | canStepOver(i, j, p) { |
| 1355 | // In some variants, objects on boards don't stop movement (Chakart) |
| 1356 | return this.board[i][j] == ""; |
| 1357 | } |
| 1358 | |
| 1359 | canDrop([c, p], [i, j]) { |
| 1360 | return ( |
| 1361 | this.board[i][j] == "" && |
| 1362 | (!this.enlightened || this.enlightened[i][j]) && |
| 1363 | ( |
| 1364 | p != "p" || |
| 1365 | (c == 'w' && i < this.size.x - 1) || |
| 1366 | (c == 'b' && i > 0) |
| 1367 | ) |
| 1368 | ); |
| 1369 | } |
| 1370 | |
| 1371 | // For Madrasi: |
| 1372 | // (redefined in Baroque etc, where Madrasi condition doesn't make sense) |
| 1373 | isImmobilized([x, y]) { |
| 1374 | if (!this.options["madrasi"]) |
| 1375 | return false; |
| 1376 | const color = this.getColor(x, y); |
| 1377 | const oppCols = this.getOppCols(color); |
| 1378 | const piece = this.getPieceType(x, y); |
| 1379 | const stepSpec = this.getStepSpec(color, x, y, piece); |
| 1380 | const attacks = stepSpec.both.concat(stepSpec.attack); |
| 1381 | for (let a of attacks) { |
| 1382 | outerLoop: for (let step of a.steps) { |
| 1383 | let [i, j] = this.increment([x, y], step); |
| 1384 | let stepCounter = 0; |
| 1385 | while (this.onBoard(i, j) && this.board[i][j] == "") { |
| 1386 | if (a.range <= stepCounter++) |
| 1387 | continue outerLoop; |
| 1388 | [i, j] = this.increment([i, j], step); |
| 1389 | } |
| 1390 | if ( |
| 1391 | this.onBoard(i, j) && |
| 1392 | oppCols.includes(this.getColor(i, j)) && |
| 1393 | this.getPieceType(i, j) == piece |
| 1394 | ) { |
| 1395 | return true; |
| 1396 | } |
| 1397 | } |
| 1398 | } |
| 1399 | return false; |
| 1400 | } |
| 1401 | |
| 1402 | // Stop at the first capture found |
| 1403 | atLeastOneCapture(color) { |
| 1404 | const allowed = (sq1, sq2) => { |
| 1405 | return ( |
| 1406 | // NOTE: canTake is reversed for Zen. |
| 1407 | // Generally ok because of the symmetry. TODO? |
| 1408 | this.canTake(sq1, sq2) && |
| 1409 | this.filterValid( |
| 1410 | [this.getBasicMove(sq1, sq2)]).length >= 1 |
| 1411 | ); |
| 1412 | }; |
| 1413 | for (let i=0; i<this.size.x; i++) { |
| 1414 | for (let j=0; j<this.size.y; j++) { |
| 1415 | if (this.getColor(i, j) == color) { |
| 1416 | if ( |
| 1417 | ( |
| 1418 | !this.options["zen"] && |
| 1419 | this.findDestSquares( |
| 1420 | [i, j], |
| 1421 | { |
| 1422 | attackOnly: true, |
| 1423 | one: true, |
| 1424 | }, |
| 1425 | allowed |
| 1426 | ) |
| 1427 | ) |
| 1428 | || |
| 1429 | ( |
| 1430 | ( |
| 1431 | this.options["zen"] && |
| 1432 | this.findCapturesOn( |
| 1433 | [i, j], |
| 1434 | {one: true}, |
| 1435 | allowed |
| 1436 | ) |
| 1437 | ) |
| 1438 | ) |
| 1439 | ) { |
| 1440 | return true; |
| 1441 | } |
| 1442 | } |
| 1443 | } |
| 1444 | } |
| 1445 | return false; |
| 1446 | } |
| 1447 | |
| 1448 | compatibleStep([x1, y1], [x2, y2], step, range) { |
| 1449 | const epsilon = 1e-7; //arbitrary small value |
| 1450 | let shifts = [0]; |
| 1451 | if (this.options["cylinder"]) |
| 1452 | Array.prototype.push.apply(shifts, [-this.size.y, this.size.y]); |
| 1453 | for (let sh of shifts) { |
| 1454 | const rx = (x2 - x1) / step[0], |
| 1455 | ry = (y2 + sh - y1) / step[1]; |
| 1456 | if ( |
| 1457 | // Zero step but non-zero interval => impossible |
| 1458 | (!Number.isFinite(rx) && !Number.isNaN(rx)) || |
| 1459 | (!Number.isFinite(ry) && !Number.isNaN(ry)) || |
| 1460 | // Negative number of step (impossible) |
| 1461 | (rx < 0 || ry < 0) || |
| 1462 | // Not the same number of steps in both directions: |
| 1463 | (!Number.isNaN(rx) && !Number.isNaN(ry) && Math.abs(rx - ry) > epsilon) |
| 1464 | ) { |
| 1465 | continue; |
| 1466 | } |
| 1467 | let distance = (Number.isNaN(rx) ? ry : rx); |
| 1468 | if (Math.abs(distance - Math.round(distance)) > epsilon) |
| 1469 | continue; |
| 1470 | distance = Math.round(distance); //in case of (numerical...) |
| 1471 | if (!range || range >= distance) |
| 1472 | return true; |
| 1473 | } |
| 1474 | return false; |
| 1475 | } |
| 1476 | |
| 1477 | //////////////////// |
| 1478 | // MOVES GENERATION |
| 1479 | |
| 1480 | getDropMovesFrom([c, p]) { |
| 1481 | // NOTE: by design, this.reserve[c][p] >= 1 on user click |
| 1482 | // (but not necessarily otherwise: atLeastOneMove() etc) |
| 1483 | if (this.reserve[c][p] == 0) |
| 1484 | return []; |
| 1485 | let moves = []; |
| 1486 | for (let i=0; i<this.size.x; i++) { |
| 1487 | for (let j=0; j<this.size.y; j++) { |
| 1488 | if (this.onBoard(i, j) && this.canDrop([c, p], [i, j])) { |
| 1489 | let mv = new Move({ |
| 1490 | start: {x: c, y: p}, |
| 1491 | end: {x: i, y: j}, |
| 1492 | appear: [new PiPo({x: i, y: j, c: c, p: p})], |
| 1493 | vanish: [] |
| 1494 | }); |
| 1495 | if (this.board[i][j] != "") { |
| 1496 | mv.vanish.push(new PiPo({ |
| 1497 | x: i, |
| 1498 | y: j, |
| 1499 | c: this.getColor(i, j), |
| 1500 | p: this.getPiece(i, j) |
| 1501 | })); |
| 1502 | } |
| 1503 | moves.push(mv); |
| 1504 | } |
| 1505 | } |
| 1506 | } |
| 1507 | return moves; |
| 1508 | } |
| 1509 | |
| 1510 | // All possible moves from selected square |
| 1511 | // TODO: generalize usage if arg "color" (e.g. Checkered) |
| 1512 | getPotentialMovesFrom([x, y], color) { |
| 1513 | if (this.subTurnTeleport == 2) |
| 1514 | return []; |
| 1515 | if (typeof x == "string") |
| 1516 | return this.getDropMovesFrom([x, y]); |
| 1517 | if (this.isImmobilized([x, y])) |
| 1518 | return []; |
| 1519 | const piece = this.getPieceType(x, y); |
| 1520 | let moves = this.getPotentialMovesOf(piece, [x, y]); |
| 1521 | if (piece == "p" && this.hasEnpassant && this.epSquare) |
| 1522 | Array.prototype.push.apply(moves, this.getEnpassantCaptures([x, y])); |
| 1523 | if ( |
| 1524 | this.isKing(0, 0, piece) && this.hasCastle && |
| 1525 | this.castleFlags[color || this.turn].some(v => v < this.size.y) |
| 1526 | ) { |
| 1527 | Array.prototype.push.apply(moves, this.getCastleMoves([x, y])); |
| 1528 | } |
| 1529 | return this.postProcessPotentialMoves(moves); |
| 1530 | } |
| 1531 | |
| 1532 | postProcessPotentialMoves(moves) { |
| 1533 | if (moves.length == 0) |
| 1534 | return []; |
| 1535 | const color = this.getColor(moves[0].start.x, moves[0].start.y); |
| 1536 | const oppCols = this.getOppCols(color); |
| 1537 | |
| 1538 | if (this.options["capture"] && this.atLeastOneCapture(color)) |
| 1539 | moves = this.capturePostProcess(moves, oppCols); |
| 1540 | |
| 1541 | if (this.options["atomic"]) |
| 1542 | moves = this.atomicPostProcess(moves, color, oppCols); |
| 1543 | |
| 1544 | if ( |
| 1545 | moves.length > 0 && |
| 1546 | this.getPieceType(moves[0].start.x, moves[0].start.y) == "p" |
| 1547 | ) { |
| 1548 | moves = this.pawnPostProcess(moves, color, oppCols); |
| 1549 | } |
| 1550 | |
| 1551 | if (this.options["cannibal"] && this.options["rifle"]) |
| 1552 | // In this case a rifle-capture from last rank may promote a pawn |
| 1553 | moves = this.riflePromotePostProcess(moves, color); |
| 1554 | |
| 1555 | return moves; |
| 1556 | } |
| 1557 | |
| 1558 | capturePostProcess(moves, oppCols) { |
| 1559 | // Filter out non-capturing moves (not using m.vanish because of |
| 1560 | // self captures of Recycle and Teleport). |
| 1561 | return moves.filter(m => { |
| 1562 | return ( |
| 1563 | this.board[m.end.x][m.end.y] != "" && |
| 1564 | oppCols.includes(this.getColor(m.end.x, m.end.y)) |
| 1565 | ); |
| 1566 | }); |
| 1567 | } |
| 1568 | |
| 1569 | atomicPostProcess(moves, color, oppCols) { |
| 1570 | moves.forEach(m => { |
| 1571 | if ( |
| 1572 | this.board[m.end.x][m.end.y] != "" && |
| 1573 | oppCols.includes(this.getColor(m.end.x, m.end.y)) |
| 1574 | ) { |
| 1575 | // Explosion! |
| 1576 | let steps = [ |
| 1577 | [-1, -1], |
| 1578 | [-1, 0], |
| 1579 | [-1, 1], |
| 1580 | [0, -1], |
| 1581 | [0, 1], |
| 1582 | [1, -1], |
| 1583 | [1, 0], |
| 1584 | [1, 1] |
| 1585 | ]; |
| 1586 | let mNext = new Move({ |
| 1587 | start: m.end, |
| 1588 | end: m.end, |
| 1589 | appear: [], |
| 1590 | vanish: [] |
| 1591 | }); |
| 1592 | for (let step of steps) { |
| 1593 | let [x, y] = this.increment([m.end.x, m.end.y], step); |
| 1594 | if ( |
| 1595 | this.onBoard(x, y) && |
| 1596 | this.board[x][y] != "" && |
| 1597 | (x != m.start.x || y != m.start.y) && |
| 1598 | this.getPieceType(x, y) != "p" |
| 1599 | ) { |
| 1600 | mNext.vanish.push( |
| 1601 | new PiPo({ |
| 1602 | p: this.getPiece(x, y), |
| 1603 | c: this.getColor(x, y), |
| 1604 | x: x, |
| 1605 | y: y |
| 1606 | }) |
| 1607 | ); |
| 1608 | } |
| 1609 | } |
| 1610 | if (!this.options["rifle"]) { |
| 1611 | // The moving piece also vanish |
| 1612 | mNext.vanish.unshift( |
| 1613 | new PiPo({ |
| 1614 | x: m.end.x, |
| 1615 | y: m.end.y, |
| 1616 | c: color, |
| 1617 | p: this.getPiece(m.start.x, m.start.y) |
| 1618 | }) |
| 1619 | ); |
| 1620 | } |
| 1621 | m.next = mNext; |
| 1622 | } |
| 1623 | }); |
| 1624 | return moves; |
| 1625 | } |
| 1626 | |
| 1627 | pawnPostProcess(moves, color, oppCols) { |
| 1628 | let moreMoves = []; |
| 1629 | const lastRank = (color == "w" ? 0 : this.size.x - 1); |
| 1630 | const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y); |
| 1631 | moves.forEach(m => { |
| 1632 | const [x1, y1] = [m.start.x, m.start.y]; |
| 1633 | const [x2, y2] = [m.end.x, m.end.y]; |
| 1634 | const promotionOk = ( |
| 1635 | x2 == lastRank && |
| 1636 | (!this.options["rifle"] || this.board[x2][y2] == "") |
| 1637 | ); |
| 1638 | if (!promotionOk) |
| 1639 | return; //nothing to do |
| 1640 | if (this.options["pawnfall"]) { |
| 1641 | m.appear.shift(); |
| 1642 | return; |
| 1643 | } |
| 1644 | let finalPieces; |
| 1645 | if ( |
| 1646 | this.options["cannibal"] && |
| 1647 | this.board[x2][y2] != "" && |
| 1648 | oppCols.includes(this.getColor(x2, y2)) |
| 1649 | ) { |
| 1650 | finalPieces = [this.getPieceType(x2, y2)]; |
| 1651 | } |
| 1652 | else |
| 1653 | finalPieces = this.pawnPromotions; |
| 1654 | m.appear[0].p = finalPieces[0]; |
| 1655 | if (initPiece == "!") //cannibal king-pawn |
| 1656 | m.appear[0].p = C.CannibalKingCode[finalPieces[0]]; |
| 1657 | for (let i=1; i<finalPieces.length; i++) { |
| 1658 | let newMove = JSON.parse(JSON.stringify(m)); |
| 1659 | const piece = finalPieces[i]; |
| 1660 | m.appear[0].p = (initPiece != "!" ? piece : C.CannibalKingCode[piece]); |
| 1661 | moreMoves.push(newMove); |
| 1662 | } |
| 1663 | }); |
| 1664 | return moves.concat(moreMoves); |
| 1665 | } |
| 1666 | |
| 1667 | riflePromotePostProcess(moves, color) { |
| 1668 | const lastRank = (color == "w" ? 0 : this.size.x - 1); |
| 1669 | let newMoves = []; |
| 1670 | moves.forEach(m => { |
| 1671 | if ( |
| 1672 | m.start.x == lastRank && |
| 1673 | m.appear.length >= 1 && |
| 1674 | m.appear[0].p == "p" && |
| 1675 | m.appear[0].x == m.start.x && |
| 1676 | m.appear[0].y == m.start.y |
| 1677 | ) { |
| 1678 | m.appear[0].p = this.pawnPromotions[0]; |
| 1679 | for (let i=1; i<this.pawnPromotions.length; i++) { |
| 1680 | let newMv = JSON.parse(JSON.stringify(m)); |
| 1681 | newMv.appear[0].p = this.pawnPromotions[i]; |
| 1682 | newMoves.push(newMv); |
| 1683 | } |
| 1684 | } |
| 1685 | }); |
| 1686 | return moves.concat(newMoves); |
| 1687 | } |
| 1688 | |
| 1689 | // Generic method to find possible moves of "sliding or jumping" pieces |
| 1690 | getPotentialMovesOf(piece, [x, y]) { |
| 1691 | const color = this.getColor(x, y); |
| 1692 | const stepSpec = this.getStepSpec(color, x, y, piece); |
| 1693 | let squares = []; |
| 1694 | if (stepSpec.attack) { |
| 1695 | squares = this.findDestSquares( |
| 1696 | [x, y], |
| 1697 | { |
| 1698 | attackOnly: true, |
| 1699 | stepSpec: stepSpec |
| 1700 | }, |
| 1701 | ([i1, j1], [i2, j2]) => { |
| 1702 | return ( |
| 1703 | (!this.options["zen"] || this.isKing(i2, j2)) && |
| 1704 | this.canTake([i1, j1], [i2, j2]) |
| 1705 | ); |
| 1706 | } |
| 1707 | ); |
| 1708 | } |
| 1709 | const noSpecials = this.findDestSquares( |
| 1710 | [x, y], |
| 1711 | { |
| 1712 | moveOnly: !!stepSpec.attack || this.options["zen"], |
| 1713 | stepSpec: stepSpec |
| 1714 | } |
| 1715 | ); |
| 1716 | Array.prototype.push.apply(squares, noSpecials); |
| 1717 | if (this.options["zen"]) { |
| 1718 | let zenCaptures = this.findCapturesOn( |
| 1719 | [x, y], |
| 1720 | {}, //byCol: default is ok |
| 1721 | ([i1, j1], [i2, j2]) => |
| 1722 | !this.isKing(i1, j1) && this.canTake([i2, j2], [i1, j1]) |
| 1723 | ); |
| 1724 | // Technical step: segments (if any) are reversed |
| 1725 | zenCaptures.forEach(z => { |
| 1726 | if (!!z.segments) |
| 1727 | z.segments = z.segments.reverse().map(s => s.reverse()) |
| 1728 | }); |
| 1729 | Array.prototype.push.apply(squares, zenCaptures); |
| 1730 | } |
| 1731 | if (this.hasSelfCaptures) { |
| 1732 | const selfCaptures = this.findDestSquares( |
| 1733 | [x, y], |
| 1734 | { |
| 1735 | attackOnly: true, |
| 1736 | stepSpec: stepSpec |
| 1737 | }, |
| 1738 | ([i1, j1], [i2, j2]) => { |
| 1739 | return ( |
| 1740 | this.getColor(i2, j2) == color && |
| 1741 | this.canSelfTake([i1, j1], [i2, j2]) |
| 1742 | ); |
| 1743 | } |
| 1744 | ); |
| 1745 | Array.prototype.push.apply(squares, selfCaptures); |
| 1746 | } |
| 1747 | return squares.map(s => { |
| 1748 | let mv = this.getBasicMove([x, y], s.sq); |
| 1749 | if (!!s.segments) |
| 1750 | mv.segments = s.segments; |
| 1751 | return mv; |
| 1752 | }); |
| 1753 | } |
| 1754 | |
| 1755 | findDestSquares([x, y], o, allowed) { |
| 1756 | if (!allowed) |
| 1757 | allowed = (sq1, sq2) => this.canTake(sq1, sq2); |
| 1758 | const apparentPiece = this.getPiece(x, y); //how it looks |
| 1759 | let res = []; |
| 1760 | // Next 3 for Cylinder mode or circular (useless otherwise) |
| 1761 | let explored = {}; |
| 1762 | let segments = []; |
| 1763 | let segStart = []; |
| 1764 | const addSquare = ([i, j]) => { |
| 1765 | let elt = {sq: [i, j]}; |
| 1766 | if (segments.length >= 1) |
| 1767 | elt.segments = this.getSegments(segments, segStart, [i, j]); |
| 1768 | res.push(elt); |
| 1769 | }; |
| 1770 | const exploreSteps = (stepArray, mode) => { |
| 1771 | for (let s of stepArray) { |
| 1772 | outerLoop: for (let step of s.steps) { |
| 1773 | segments = []; |
| 1774 | segStart = [x, y]; |
| 1775 | let [i, j] = [x, y]; |
| 1776 | let stepCounter = 0; |
| 1777 | while ( |
| 1778 | this.onBoard(i, j) && |
| 1779 | ((i == x && j == y) || this.canStepOver(i, j, apparentPiece)) |
| 1780 | ) { |
| 1781 | if (!explored[i + "." + j] && (i != x || j != y)) { |
| 1782 | explored[i + "." + j] = true; |
| 1783 | if ( |
| 1784 | !o.captureTarget || |
| 1785 | (o.captureTarget[0] == i && o.captureTarget[1] == j) |
| 1786 | ) { |
| 1787 | if (o.one && mode != "attack") |
| 1788 | return true; |
| 1789 | if (mode != "attack") |
| 1790 | addSquare(!o.captureTarget ? [i, j] : [x, y]); |
| 1791 | if (o.captureTarget) |
| 1792 | return res[0]; |
| 1793 | } |
| 1794 | } |
| 1795 | if (s.range <= stepCounter++) |
| 1796 | continue outerLoop; |
| 1797 | const oldIJ = [i, j]; |
| 1798 | [i, j] = this.increment([i, j], step); |
| 1799 | if (Math.abs(j - oldIJ[1]) > 1 || Math.abs(i - oldIJ[0]) > 1) { |
| 1800 | // Boundary between segments (cylinder or circular mode) |
| 1801 | segments.push([[segStart[0], segStart[1]], oldIJ]); |
| 1802 | segStart = [i, j]; |
| 1803 | } |
| 1804 | } |
| 1805 | if (!this.onBoard(i, j)) |
| 1806 | continue; |
| 1807 | const pieceIJ = this.getPieceType(i, j); |
| 1808 | if (!explored[i + "." + j]) { |
| 1809 | explored[i + "." + j] = true; |
| 1810 | if (allowed([x, y], [i, j])) { |
| 1811 | if (o.one && mode != "moves") |
| 1812 | return true; |
| 1813 | if (mode != "moves") |
| 1814 | addSquare(!o.captureTarget ? [i, j] : [x, y]); |
| 1815 | if ( |
| 1816 | o.captureTarget && |
| 1817 | o.captureTarget[0] == i && o.captureTarget[1] == j |
| 1818 | ) { |
| 1819 | return res[0]; |
| 1820 | } |
| 1821 | } |
| 1822 | } |
| 1823 | } |
| 1824 | } |
| 1825 | return undefined; //default, but let's explicit it |
| 1826 | }; |
| 1827 | if (o.captureTarget) |
| 1828 | return exploreSteps(o.captureSteps, "attack"); |
| 1829 | else { |
| 1830 | const stepSpec = |
| 1831 | o.stepSpec || this.getStepSpec(this.getColor(x, y), x, y); |
| 1832 | let outOne = false; |
| 1833 | if (!o.attackOnly) |
| 1834 | outOne = exploreSteps(stepSpec.both.concat(stepSpec.moves), "moves"); |
| 1835 | if (!outOne && !o.moveOnly) |
| 1836 | outOne = exploreSteps(stepSpec.both.concat(stepSpec.attack), "attack"); |
| 1837 | return (o.one ? outOne : res); |
| 1838 | } |
| 1839 | } |
| 1840 | |
| 1841 | // TODO here: should/could use getPotentialMovesFrom ?! (not sure) |
| 1842 | // --> would be useful for variants like Copycat. |
| 1843 | // Search for enemy (or not) pieces attacking [x, y] |
| 1844 | findCapturesOn([x, y], o, allowed) { |
| 1845 | if (!o.byCol) |
| 1846 | o.byCol = this.getOppCols(this.getColor(x, y) || this.turn); |
| 1847 | let res = []; |
| 1848 | for (let i=0; i<this.size.x; i++) { |
| 1849 | for (let j=0; j<this.size.y; j++) { |
| 1850 | const colIJ = this.getColor(i, j); |
| 1851 | if ( |
| 1852 | this.board[i][j] != "" && |
| 1853 | o.byCol.includes(colIJ) && |
| 1854 | !this.isImmobilized([i, j]) |
| 1855 | ) { |
| 1856 | const apparentPiece = this.getPiece(i, j); |
| 1857 | // Quick check: does this potential attacker target x,y ? |
| 1858 | if (this.canStepOver(x, y, apparentPiece)) |
| 1859 | continue; |
| 1860 | const stepSpec = this.getStepSpec(colIJ, i, j); |
| 1861 | const attacks = stepSpec.attack.concat(stepSpec.both); |
| 1862 | for (let a of attacks) { |
| 1863 | for (let s of a.steps) { |
| 1864 | // Quick check: if step isn't compatible, don't even try |
| 1865 | if (!this.compatibleStep([i, j], [x, y], s, a.range)) |
| 1866 | continue; |
| 1867 | // Finally verify that nothing stand in-between |
| 1868 | const out = this.findDestSquares( |
| 1869 | [i, j], |
| 1870 | { |
| 1871 | captureTarget: [x, y], |
| 1872 | captureSteps: [{steps: [s], range: a.range}], |
| 1873 | }, |
| 1874 | allowed |
| 1875 | ); |
| 1876 | if (out) { |
| 1877 | if (o.one) |
| 1878 | return true; |
| 1879 | res.push(out); |
| 1880 | } |
| 1881 | } |
| 1882 | } |
| 1883 | } |
| 1884 | } |
| 1885 | } |
| 1886 | return (o.one ? false : res); |
| 1887 | } |
| 1888 | |
| 1889 | // Build a regular move from its initial and destination squares. |
| 1890 | // tr: transformation |
| 1891 | getBasicMove([sx, sy], [ex, ey], tr) { |
| 1892 | const initColor = this.getColor(sx, sy); |
| 1893 | const initPiece = this.getPiece(sx, sy); |
| 1894 | const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : ""); |
| 1895 | let mv = new Move({ |
| 1896 | appear: [], |
| 1897 | vanish: [], |
| 1898 | start: {x: sx, y: sy}, |
| 1899 | end: {x: ex, y: ey} |
| 1900 | }); |
| 1901 | if ( |
| 1902 | !this.options["rifle"] || |
| 1903 | this.board[ex][ey] == "" || |
| 1904 | destColor == initColor //Recycle, Teleport |
| 1905 | ) { |
| 1906 | mv.appear = [ |
| 1907 | new PiPo({ |
| 1908 | x: ex, |
| 1909 | y: ey, |
| 1910 | c: !!tr ? tr.c : initColor, |
| 1911 | p: !!tr ? tr.p : initPiece |
| 1912 | }) |
| 1913 | ]; |
| 1914 | mv.vanish = [ |
| 1915 | new PiPo({ |
| 1916 | x: sx, |
| 1917 | y: sy, |
| 1918 | c: initColor, |
| 1919 | p: initPiece |
| 1920 | }) |
| 1921 | ]; |
| 1922 | } |
| 1923 | if (this.board[ex][ey] != "") { |
| 1924 | mv.vanish.push( |
| 1925 | new PiPo({ |
| 1926 | x: ex, |
| 1927 | y: ey, |
| 1928 | c: this.getColor(ex, ey), |
| 1929 | p: this.getPiece(ex, ey) |
| 1930 | }) |
| 1931 | ); |
| 1932 | if (this.options["cannibal"] && destColor != initColor) { |
| 1933 | const lastIdx = mv.vanish.length - 1; //think "Rifle+Cannibal" |
| 1934 | let trPiece = mv.vanish[lastIdx].p; |
| 1935 | if (this.isKing(sx, sy)) |
| 1936 | trPiece = C.CannibalKingCode[trPiece]; |
| 1937 | if (mv.appear.length >= 1) |
| 1938 | mv.appear[0].p = trPiece; |
| 1939 | else if (this.options["rifle"]) { |
| 1940 | mv.appear.unshift( |
| 1941 | new PiPo({ |
| 1942 | x: sx, |
| 1943 | y: sy, |
| 1944 | c: initColor, |
| 1945 | p: trPiece |
| 1946 | }) |
| 1947 | ); |
| 1948 | mv.vanish.unshift( |
| 1949 | new PiPo({ |
| 1950 | x: sx, |
| 1951 | y: sy, |
| 1952 | c: initColor, |
| 1953 | p: initPiece |
| 1954 | }) |
| 1955 | ); |
| 1956 | } |
| 1957 | } |
| 1958 | } |
| 1959 | return mv; |
| 1960 | } |
| 1961 | |
| 1962 | // En-passant square, if any |
| 1963 | getEpSquare(moveOrSquare) { |
| 1964 | if (typeof moveOrSquare === "string") { |
| 1965 | const square = moveOrSquare; |
| 1966 | if (square == "-") |
| 1967 | return undefined; |
| 1968 | return C.SquareToCoords(square); |
| 1969 | } |
| 1970 | // Argument is a move: |
| 1971 | const move = moveOrSquare; |
| 1972 | const s = move.start, |
| 1973 | e = move.end; |
| 1974 | if ( |
| 1975 | s.y == e.y && |
| 1976 | Math.abs(s.x - e.x) == 2 && |
| 1977 | // Next conditions for variants like Atomic or Rifle, Recycle... |
| 1978 | ( |
| 1979 | move.appear.length > 0 && |
| 1980 | this.getPieceType(0, 0, move.appear[0].p) == 'p' |
| 1981 | ) |
| 1982 | && |
| 1983 | ( |
| 1984 | move.vanish.length > 0 && |
| 1985 | this.getPieceType(0, 0, move.vanish[0].p) == 'p' |
| 1986 | ) |
| 1987 | ) { |
| 1988 | return { |
| 1989 | x: (s.x + e.x) / 2, |
| 1990 | y: s.y |
| 1991 | }; |
| 1992 | } |
| 1993 | return undefined; //default |
| 1994 | } |
| 1995 | |
| 1996 | // Special case of en-passant captures: treated separately |
| 1997 | getEnpassantCaptures([x, y]) { |
| 1998 | const color = this.getColor(x, y); |
| 1999 | const shiftX = (color == 'w' ? -1 : 1); |
| 2000 | const oppCols = this.getOppCols(color); |
| 2001 | if ( |
| 2002 | this.epSquare && |
| 2003 | this.epSquare.x == x + shiftX && //NOTE: epSquare.x not on edge |
| 2004 | Math.abs(this.getY(this.epSquare.y - y)) == 1 && |
| 2005 | // Doublemove (and Progressive?) guards: |
| 2006 | this.board[this.epSquare.x][this.epSquare.y] == "" && |
| 2007 | oppCols.includes(this.getColor(x, this.epSquare.y)) |
| 2008 | ) { |
| 2009 | const [epx, epy] = [this.epSquare.x, this.epSquare.y]; |
| 2010 | this.board[epx][epy] = this.board[x][this.epSquare.y]; |
| 2011 | let enpassantMove = this.getBasicMove([x, y], [epx, epy]); |
| 2012 | this.board[epx][epy] = ""; |
| 2013 | const lastIdx = enpassantMove.vanish.length - 1; //think Rifle |
| 2014 | enpassantMove.vanish[lastIdx].x = x; |
| 2015 | return [enpassantMove]; |
| 2016 | } |
| 2017 | return []; |
| 2018 | } |
| 2019 | |
| 2020 | getCastleMoves([x, y], finalSquares, castleWith) { |
| 2021 | const c = this.getColor(x, y); |
| 2022 | |
| 2023 | // Castling ? |
| 2024 | const oppCols = this.getOppCols(c); |
| 2025 | let moves = []; |
| 2026 | // King, then rook: |
| 2027 | finalSquares = |
| 2028 | finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ]; |
| 2029 | const castlingKing = this.getPiece(x, y); |
| 2030 | castlingCheck: for ( |
| 2031 | let castleSide = 0; |
| 2032 | castleSide < 2; |
| 2033 | castleSide++ //large, then small |
| 2034 | ) { |
| 2035 | if (this.castleFlags[c][castleSide] >= this.size.y) |
| 2036 | continue; |
| 2037 | // If this code is reached, rook and king are on initial position |
| 2038 | |
| 2039 | // NOTE: in some variants this is not a rook |
| 2040 | const rookPos = this.castleFlags[c][castleSide]; |
| 2041 | const castlingPiece = this.getPiece(x, rookPos); |
| 2042 | if ( |
| 2043 | this.board[x][rookPos] == "" || |
| 2044 | this.getColor(x, rookPos) != c || |
| 2045 | (castleWith && !castleWith.includes(castlingPiece)) |
| 2046 | ) { |
| 2047 | // Rook is not here, or changed color (see Benedict) |
| 2048 | continue; |
| 2049 | } |
| 2050 | // Nothing on the path of the king ? (and no checks) |
| 2051 | const finDist = finalSquares[castleSide][0] - y; |
| 2052 | let step = finDist / Math.max(1, Math.abs(finDist)); |
| 2053 | let i = y; |
| 2054 | do { |
| 2055 | if ( |
| 2056 | // NOTE: next weird test because underCheck() verification |
| 2057 | // will be executed in filterValid() later. |
| 2058 | ( |
| 2059 | i != finalSquares[castleSide][0] && |
| 2060 | this.underCheck([[x, i]], oppCols) |
| 2061 | ) |
| 2062 | || |
| 2063 | ( |
| 2064 | this.board[x][i] != "" && |
| 2065 | // NOTE: next check is enough, because of chessboard constraints |
| 2066 | (this.getColor(x, i) != c || ![rookPos, y].includes(i)) |
| 2067 | ) |
| 2068 | ) { |
| 2069 | continue castlingCheck; |
| 2070 | } |
| 2071 | i += step; |
| 2072 | } while (i != finalSquares[castleSide][0]); |
| 2073 | // Nothing on the path to the rook? |
| 2074 | step = (castleSide == 0 ? -1 : 1); |
| 2075 | for (i = y + step; i != rookPos; i += step) { |
| 2076 | if (this.board[x][i] != "") |
| 2077 | continue castlingCheck; |
| 2078 | } |
| 2079 | |
| 2080 | // Nothing on final squares, except maybe king and castling rook? |
| 2081 | for (i = 0; i < 2; i++) { |
| 2082 | if ( |
| 2083 | finalSquares[castleSide][i] != rookPos && |
| 2084 | this.board[x][finalSquares[castleSide][i]] != "" && |
| 2085 | ( |
| 2086 | finalSquares[castleSide][i] != y || |
| 2087 | this.getColor(x, finalSquares[castleSide][i]) != c |
| 2088 | ) |
| 2089 | ) { |
| 2090 | continue castlingCheck; |
| 2091 | } |
| 2092 | } |
| 2093 | |
| 2094 | // If this code is reached, castle is potentially valid |
| 2095 | moves.push( |
| 2096 | new Move({ |
| 2097 | appear: [ |
| 2098 | new PiPo({ |
| 2099 | x: x, |
| 2100 | y: finalSquares[castleSide][0], |
| 2101 | p: castlingKing, |
| 2102 | c: c |
| 2103 | }), |
| 2104 | new PiPo({ |
| 2105 | x: x, |
| 2106 | y: finalSquares[castleSide][1], |
| 2107 | p: castlingPiece, |
| 2108 | c: c |
| 2109 | }) |
| 2110 | ], |
| 2111 | vanish: [ |
| 2112 | // King might be initially disguised (Titan...) |
| 2113 | new PiPo({ x: x, y: y, p: castlingKing, c: c }), |
| 2114 | new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c }) |
| 2115 | ], |
| 2116 | end: |
| 2117 | Math.abs(y - rookPos) <= 2 |
| 2118 | ? {x: x, y: rookPos} |
| 2119 | : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)} |
| 2120 | }) |
| 2121 | ); |
| 2122 | } |
| 2123 | |
| 2124 | return moves; |
| 2125 | } |
| 2126 | |
| 2127 | //////////////////// |
| 2128 | // MOVES VALIDATION |
| 2129 | |
| 2130 | // Is piece (or square) at given position attacked by "oppCol(s)" ? |
| 2131 | underAttack([x, y], oppCols) { |
| 2132 | // An empty square is considered as king, |
| 2133 | // since it's used only in getCastleMoves (TODO?) |
| 2134 | const king = this.board[x][y] == "" || this.isKing(x, y); |
| 2135 | return ( |
| 2136 | ( |
| 2137 | (!this.options["zen"] || king) && |
| 2138 | this.findCapturesOn( |
| 2139 | [x, y], |
| 2140 | { |
| 2141 | byCol: oppCols, |
| 2142 | one: true |
| 2143 | } |
| 2144 | ) |
| 2145 | ) |
| 2146 | || |
| 2147 | ( |
| 2148 | (!!this.options["zen"] && !king) && |
| 2149 | this.findDestSquares( |
| 2150 | [x, y], |
| 2151 | { |
| 2152 | attackOnly: true, |
| 2153 | one: true |
| 2154 | }, |
| 2155 | ([i1, j1], [i2, j2]) => oppCols.includes(this.getColor(i2, j2)) |
| 2156 | ) |
| 2157 | ) |
| 2158 | ); |
| 2159 | } |
| 2160 | |
| 2161 | // Argument is (very generally) an array of squares (= arrays) |
| 2162 | underCheck(square_s, oppCols) { |
| 2163 | if (this.options["taking"] || this.options["dark"]) |
| 2164 | return false; |
| 2165 | return square_s.some(sq => this.underAttack(sq, oppCols)); |
| 2166 | } |
| 2167 | |
| 2168 | // Scan board for king(s) |
| 2169 | searchKingPos(color) { |
| 2170 | let res = []; |
| 2171 | for (let i=0; i < this.size.x; i++) { |
| 2172 | for (let j=0; j < this.size.y; j++) { |
| 2173 | if (this.getColor(i, j) == color && this.isKing(i, j)) |
| 2174 | res.push([i, j]); |
| 2175 | } |
| 2176 | } |
| 2177 | return res; |
| 2178 | } |
| 2179 | |
| 2180 | // cb: callback returning a boolean (false if king missing) |
| 2181 | trackKingWrap(move, kingPos, cb) { |
| 2182 | if (move.appear.length == 0 && move.vanish.length == 0) |
| 2183 | return true; |
| 2184 | const color = |
| 2185 | (move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c); |
| 2186 | let newKingPP = null, |
| 2187 | sqIdx = 0, |
| 2188 | res = true; //a priori valid |
| 2189 | const oldKingPP = |
| 2190 | move.vanish.find(v => this.isKing(0, 0, v.p) && v.c == color); |
| 2191 | if (oldKingPP) { |
| 2192 | // Search king in appear array: |
| 2193 | newKingPP = |
| 2194 | move.appear.find(a => this.isKing(0, 0, a.p) && a.c == color); |
| 2195 | if (newKingPP) { |
| 2196 | sqIdx = kingPos.findIndex(kp => |
| 2197 | kp[0] == oldKingPP.x && kp[1] == oldKingPP.y); |
| 2198 | kingPos[sqIdx] = [newKingPP.x, newKingPP.y]; |
| 2199 | } |
| 2200 | else |
| 2201 | res = false; //king vanished |
| 2202 | } |
| 2203 | res &&= cb(kingPos); |
| 2204 | if (oldKingPP && newKingPP) |
| 2205 | kingPos[sqIdx] = [oldKingPP.x, oldKingPP.y]; |
| 2206 | return res; |
| 2207 | } |
| 2208 | |
| 2209 | // 'color' arg because some variants (e.g. Refusal) check opponent moves |
| 2210 | filterValid(moves, color) { |
| 2211 | if (!color) |
| 2212 | color = this.turn; |
| 2213 | const oppCols = this.getOppCols(color); |
| 2214 | let kingPos = this.searchKingPos(color); |
| 2215 | return moves.filter(m => { |
| 2216 | this.playOnBoard(m); |
| 2217 | const res = this.trackKingWrap(m, kingPos, (kp) => { |
| 2218 | return !this.underCheck(kp, oppCols); |
| 2219 | }); |
| 2220 | this.undoOnBoard(m); |
| 2221 | return res; |
| 2222 | }); |
| 2223 | } |
| 2224 | |
| 2225 | ///////////////// |
| 2226 | // MOVES PLAYING |
| 2227 | |
| 2228 | // Apply a move on board |
| 2229 | playOnBoard(move) { |
| 2230 | for (let psq of move.vanish) |
| 2231 | this.board[psq.x][psq.y] = ""; |
| 2232 | for (let psq of move.appear) |
| 2233 | this.board[psq.x][psq.y] = psq.c + psq.p; |
| 2234 | } |
| 2235 | // Un-apply the played move |
| 2236 | undoOnBoard(move) { |
| 2237 | for (let psq of move.appear) |
| 2238 | this.board[psq.x][psq.y] = ""; |
| 2239 | for (let psq of move.vanish) |
| 2240 | this.board[psq.x][psq.y] = psq.c + psq.p; |
| 2241 | } |
| 2242 | |
| 2243 | updateCastleFlags(move) { |
| 2244 | // Update castling flags if start or arrive from/at rook/king locations |
| 2245 | move.appear.concat(move.vanish).forEach(psq => { |
| 2246 | if (this.isKing(0, 0, psq.p)) |
| 2247 | this.castleFlags[psq.c] = [this.size.y, this.size.y]; |
| 2248 | // NOTE: not "else if" because king can capture enemy rook... |
| 2249 | let c = ""; |
| 2250 | if (psq.x == 0) |
| 2251 | c = "b"; |
| 2252 | else if (psq.x == this.size.x - 1) |
| 2253 | c = "w"; |
| 2254 | if (c != "") { |
| 2255 | const fidx = this.castleFlags[c].findIndex(f => f == psq.y); |
| 2256 | if (fidx >= 0) |
| 2257 | this.castleFlags[c][fidx] = this.size.y; |
| 2258 | } |
| 2259 | }); |
| 2260 | } |
| 2261 | |
| 2262 | prePlay(move) { |
| 2263 | if ( |
| 2264 | this.hasCastle && |
| 2265 | // If flags already off, no need to re-check: |
| 2266 | Object.values(this.castleFlags).some(cvals => |
| 2267 | cvals.some(val => val < this.size.y)) |
| 2268 | ) { |
| 2269 | this.updateCastleFlags(move); |
| 2270 | } |
| 2271 | if (this.options["crazyhouse"]) { |
| 2272 | move.vanish.forEach(v => { |
| 2273 | const square = C.CoordsToSquare({x: v.x, y: v.y}); |
| 2274 | if (this.ispawn[square]) |
| 2275 | delete this.ispawn[square]; |
| 2276 | }); |
| 2277 | if (move.appear.length > 0 && move.vanish.length > 0) { |
| 2278 | // Assumption: something is moving |
| 2279 | const initSquare = C.CoordsToSquare(move.start); |
| 2280 | const destSquare = C.CoordsToSquare(move.end); |
| 2281 | if ( |
| 2282 | this.ispawn[initSquare] || |
| 2283 | (move.vanish[0].p == 'p' && move.appear[0].p != 'p') |
| 2284 | ) { |
| 2285 | this.ispawn[destSquare] = true; |
| 2286 | } |
| 2287 | else if ( |
| 2288 | this.ispawn[destSquare] && |
| 2289 | this.getColor(move.end.x, move.end.y) != move.vanish[0].c |
| 2290 | ) { |
| 2291 | move.vanish[1].p = 'p'; |
| 2292 | delete this.ispawn[destSquare]; |
| 2293 | } |
| 2294 | } |
| 2295 | } |
| 2296 | const minSize = Math.min(move.appear.length, move.vanish.length); |
| 2297 | if ( |
| 2298 | this.hasReserve && |
| 2299 | // Warning; atomic pawn removal isn't a capture |
| 2300 | (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1) |
| 2301 | ) { |
| 2302 | const color = this.turn; |
| 2303 | for (let i=minSize; i<move.appear.length; i++) { |
| 2304 | // Something appears = dropped on board (some exceptions, Chakart...) |
| 2305 | if (move.appear[i].c == color) { |
| 2306 | const piece = move.appear[i].p; |
| 2307 | this.updateReserve(color, piece, this.reserve[color][piece] - 1); |
| 2308 | } |
| 2309 | } |
| 2310 | for (let i=minSize; i<move.vanish.length; i++) { |
| 2311 | // Something vanish: add to reserve except if recycle & opponent |
| 2312 | if ( |
| 2313 | this.options["crazyhouse"] || |
| 2314 | (this.options["recycle"] && move.vanish[i].c == color) |
| 2315 | ) { |
| 2316 | const piece = move.vanish[i].p; |
| 2317 | this.updateReserve(color, piece, this.reserve[color][piece] + 1); |
| 2318 | } |
| 2319 | } |
| 2320 | } |
| 2321 | } |
| 2322 | |
| 2323 | play(move) { |
| 2324 | this.prePlay(move); |
| 2325 | if (this.hasEnpassant) |
| 2326 | this.epSquare = this.getEpSquare(move); |
| 2327 | this.playOnBoard(move); |
| 2328 | this.postPlay(move); |
| 2329 | } |
| 2330 | |
| 2331 | postPlay(move) { |
| 2332 | if (this.options["dark"]) |
| 2333 | this.updateEnlightened(); |
| 2334 | if (this.options["teleport"]) { |
| 2335 | if ( |
| 2336 | this.subTurnTeleport == 1 && |
| 2337 | move.vanish.length > move.appear.length && |
| 2338 | move.vanish[1].c == this.turn |
| 2339 | ) { |
| 2340 | const v = move.vanish[move.vanish.length - 1]; |
| 2341 | this.captured = {x: v.x, y: v.y, c: v.c, p: v.p}; |
| 2342 | this.subTurnTeleport = 2; |
| 2343 | return; |
| 2344 | } |
| 2345 | this.subTurnTeleport = 1; |
| 2346 | this.captured = null; |
| 2347 | } |
| 2348 | this.tryChangeTurn(move); |
| 2349 | } |
| 2350 | |
| 2351 | tryChangeTurn(move) { |
| 2352 | if (this.isLastMove(move)) { |
| 2353 | this.turn = C.GetOppTurn(this.turn); |
| 2354 | this.movesCount++; |
| 2355 | this.subTurn = 1; |
| 2356 | } |
| 2357 | else if (!move.next) |
| 2358 | this.subTurn++; |
| 2359 | } |
| 2360 | |
| 2361 | isLastMove(move) { |
| 2362 | if (move.next) |
| 2363 | return false; |
| 2364 | const color = this.turn; |
| 2365 | const oppKingPos = this.searchKingPos(C.GetOppTurn(color)); |
| 2366 | if (oppKingPos.length == 0 || this.underCheck(oppKingPos, [color])) |
| 2367 | return true; |
| 2368 | return ( |
| 2369 | ( |
| 2370 | !this.options["balance"] || |
| 2371 | ![1, 2].includes(this.movesCount) || |
| 2372 | this.subTurn == 2 |
| 2373 | ) |
| 2374 | && |
| 2375 | ( |
| 2376 | !this.options["doublemove"] || |
| 2377 | this.movesCount == 0 || |
| 2378 | this.subTurn == 2 |
| 2379 | ) |
| 2380 | && |
| 2381 | ( |
| 2382 | !this.options["progressive"] || |
| 2383 | this.subTurn == this.movesCount + 1 |
| 2384 | ) |
| 2385 | ); |
| 2386 | } |
| 2387 | |
| 2388 | // "Stop at the first move found" |
| 2389 | atLeastOneMove(color) { |
| 2390 | for (let i = 0; i < this.size.x; i++) { |
| 2391 | for (let j = 0; j < this.size.y; j++) { |
| 2392 | if (this.board[i][j] != "" && this.getColor(i, j) == color) { |
| 2393 | // NOTE: in fact searching for all potential moves from i,j. |
| 2394 | // I don't believe this is an issue, for now at least. |
| 2395 | const moves = this.getPotentialMovesFrom([i, j], color); |
| 2396 | if (moves.some(m => this.filterValid([m]).length >= 1)) |
| 2397 | return true; |
| 2398 | } |
| 2399 | } |
| 2400 | } |
| 2401 | if (this.hasReserve && this.reserve[color]) { |
| 2402 | for (let p of Object.keys(this.reserve[color])) { |
| 2403 | const moves = this.getDropMovesFrom([color, p]); |
| 2404 | if (moves.some(m => this.filterValid([m]).length >= 1)) |
| 2405 | return true; |
| 2406 | } |
| 2407 | } |
| 2408 | return false; |
| 2409 | } |
| 2410 | |
| 2411 | // What is the score ? (Interesting if game is over) |
| 2412 | getCurrentScore(move_s) { |
| 2413 | const move = move_s[move_s.length - 1]; |
| 2414 | // Shortcut in case the score was computed before: |
| 2415 | if (move.result) |
| 2416 | return move.result; |
| 2417 | const oppTurn = C.GetOppTurn(this.turn); |
| 2418 | const kingPos = { |
| 2419 | w: this.searchKingPos('w'), |
| 2420 | b: this.searchKingPos('b') |
| 2421 | }; |
| 2422 | if (kingPos[this.turn].length == 0 && kingPos[oppTurn].length == 0) |
| 2423 | return "1/2"; |
| 2424 | if (kingPos[this.turn].length == 0) |
| 2425 | return (this.turn == "w" ? "0-1" : "1-0"); |
| 2426 | if (kingPos[oppTurn].length == 0) |
| 2427 | return (this.turn == "w" ? "1-0" : "0-1"); |
| 2428 | if (this.atLeastOneMove(this.turn)) |
| 2429 | return "*"; |
| 2430 | // No valid move: stalemate or checkmate? |
| 2431 | if (!this.underCheck(kingPos[this.turn], this.getOppCols(this.turn))) |
| 2432 | return "1/2"; |
| 2433 | // OK, checkmate |
| 2434 | return (this.turn == "w" ? "0-1" : "1-0"); |
| 2435 | } |
| 2436 | |
| 2437 | playVisual(move, r) { |
| 2438 | move.vanish.forEach(v => { |
| 2439 | if (this.g_pieces[v.x][v.y]) //can be null (e.g. Apocalypse) |
| 2440 | this.g_pieces[v.x][v.y].remove(); |
| 2441 | this.g_pieces[v.x][v.y] = null; |
| 2442 | }); |
| 2443 | let chessboard = |
| 2444 | document.getElementById(this.containerId).querySelector(".chessboard"); |
| 2445 | if (!r) |
| 2446 | r = chessboard.getBoundingClientRect(); |
| 2447 | const pieceWidth = this.getPieceWidth(r.width); |
| 2448 | move.appear.forEach(a => { |
| 2449 | this.g_pieces[a.x][a.y] = document.createElement("piece"); |
| 2450 | C.AddClass_es(this.g_pieces[a.x][a.y], |
| 2451 | this.pieces(a.c, a.x, a.y)[a.p]["class"]); |
| 2452 | this.g_pieces[a.x][a.y].classList.add(V.GetColorClass(a.c)); |
| 2453 | this.g_pieces[a.x][a.y].style.width = pieceWidth + "px"; |
| 2454 | this.g_pieces[a.x][a.y].style.height = pieceWidth + "px"; |
| 2455 | const [ip, jp] = this.getPixelPosition(a.x, a.y, r); |
| 2456 | // Translate coordinates to use chessboard as reference: |
| 2457 | this.g_pieces[a.x][a.y].style.transform = |
| 2458 | `translate(${ip - r.x}px,${jp - r.y}px)`; |
| 2459 | if (this.enlightened && !this.enlightened[a.x][a.y]) |
| 2460 | this.g_pieces[a.x][a.y].classList.add("hidden"); |
| 2461 | chessboard.appendChild(this.g_pieces[a.x][a.y]); |
| 2462 | }); |
| 2463 | if (this.options["dark"]) |
| 2464 | this.graphUpdateEnlightened(); |
| 2465 | } |
| 2466 | |
| 2467 | // TODO: send stack receive stack, or allow incremental? (good/bad points) |
| 2468 | buildMoveStack(move, r) { |
| 2469 | this.moveStack.push(move); |
| 2470 | this.computeNextMove(move); |
| 2471 | const then = () => { |
| 2472 | const newTurn = this.turn; |
| 2473 | if (this.moveStack.length == 1 && !this.hideMoves) |
| 2474 | this.playVisual(move, r); |
| 2475 | if (move.next) { |
| 2476 | this.gameState = { |
| 2477 | fen: this.getFen(), |
| 2478 | board: JSON.parse(JSON.stringify(this.board)) //easier |
| 2479 | }; |
| 2480 | this.buildMoveStack(move.next, r); |
| 2481 | } |
| 2482 | else { |
| 2483 | if (this.moveStack.length == 1) { |
| 2484 | // Usual case (one normal move) |
| 2485 | this.afterPlay(this.moveStack, newTurn, {send: true, res: true}); |
| 2486 | this.moveStack = []; |
| 2487 | } |
| 2488 | else { |
| 2489 | this.afterPlay(this.moveStack, newTurn, {send: true, res: false}); |
| 2490 | this.re_initFromFen(this.gameState.fen, this.gameState.board); |
| 2491 | this.playReceivedMove(this.moveStack.slice(1), () => { |
| 2492 | this.afterPlay(this.moveStack, newTurn, {send: false, res: true}); |
| 2493 | this.moveStack = []; |
| 2494 | }); |
| 2495 | } |
| 2496 | } |
| 2497 | }; |
| 2498 | // If hiding moves, then they are revealed in play() with callback |
| 2499 | this.play(move, this.hideMoves ? then : null); |
| 2500 | if (!this.hideMoves) |
| 2501 | then(); |
| 2502 | } |
| 2503 | |
| 2504 | // Implemented in variants using (automatic) moveStack |
| 2505 | computeNextMove(move) {} |
| 2506 | |
| 2507 | animateMoving(start, end, drag, segments, cb) { |
| 2508 | let initPiece = this.getDomPiece(start.x, start.y); |
| 2509 | if (!initPiece) { //TODO: shouldn't occur! |
| 2510 | cb(); |
| 2511 | return; |
| 2512 | } |
| 2513 | // NOTE: cloning often not required, but light enough, and simpler |
| 2514 | let movingPiece = initPiece.cloneNode(); |
| 2515 | initPiece.style.opacity = "0"; |
| 2516 | let container = |
| 2517 | document.getElementById(this.containerId) |
| 2518 | const r = container.querySelector(".chessboard").getBoundingClientRect(); |
| 2519 | if (typeof start.x == "string") { |
| 2520 | // Need to bound width/height (was 100% for reserve pieces) |
| 2521 | const pieceWidth = this.getPieceWidth(r.width); |
| 2522 | movingPiece.style.width = pieceWidth + "px"; |
| 2523 | movingPiece.style.height = pieceWidth + "px"; |
| 2524 | } |
| 2525 | const maxDist = this.getMaxDistance(r); |
| 2526 | const apparentColor = this.getColor(start.x, start.y); |
| 2527 | const pieces = this.pieces(apparentColor, start.x, start.y); |
| 2528 | if (drag) { |
| 2529 | const startCode = this.getPiece(start.x, start.y); |
| 2530 | C.RemoveClass_es(movingPiece, pieces[startCode]["class"]); |
| 2531 | C.AddClass_es(movingPiece, pieces[drag.p]["class"]); |
| 2532 | if (apparentColor != drag.c) { |
| 2533 | movingPiece.classList.remove(V.GetColorClass(apparentColor)); |
| 2534 | movingPiece.classList.add(V.GetColorClass(drag.c)); |
| 2535 | } |
| 2536 | } |
| 2537 | container.appendChild(movingPiece); |
| 2538 | const animateSegment = (index, cb) => { |
| 2539 | // NOTE: move.drag could be generalized per-segment (usage?) |
| 2540 | const [i1, j1] = segments[index][0]; |
| 2541 | const [i2, j2] = segments[index][1]; |
| 2542 | const dep = this.getPixelPosition(i1, j1, r); |
| 2543 | const arr = this.getPixelPosition(i2, j2, r); |
| 2544 | movingPiece.style.transitionDuration = "0s"; |
| 2545 | movingPiece.style.transform = `translate(${dep[0]}px, ${dep[1]}px)`; |
| 2546 | const distance = |
| 2547 | Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2); |
| 2548 | const duration = 0.2 + (distance / maxDist) * 0.3; |
| 2549 | // TODO: unclear why we need this new delay below: |
| 2550 | setTimeout(() => { |
| 2551 | movingPiece.style.transitionDuration = duration + "s"; |
| 2552 | // movingPiece is child of container: no need to adjust coordinates |
| 2553 | movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`; |
| 2554 | setTimeout(cb, duration * 1000); |
| 2555 | }, 50); |
| 2556 | }; |
| 2557 | let index = 0; |
| 2558 | const animateSegmentCallback = () => { |
| 2559 | if (index < segments.length) |
| 2560 | animateSegment(index++, animateSegmentCallback); |
| 2561 | else { |
| 2562 | movingPiece.remove(); |
| 2563 | initPiece.style.opacity = "1"; |
| 2564 | cb(); |
| 2565 | } |
| 2566 | }; |
| 2567 | animateSegmentCallback(); |
| 2568 | } |
| 2569 | |
| 2570 | // Input array of objects with at least fields x,y (e.g. PiPo) |
| 2571 | animateFading(arr, cb) { |
| 2572 | const animLength = 350; //TODO: 350ms? More? Less? |
| 2573 | arr.forEach(v => { |
| 2574 | let fadingPiece = this.getDomPiece(v.x, v.y); |
| 2575 | fadingPiece.style.transitionDuration = (animLength / 1000) + "s"; |
| 2576 | fadingPiece.style.opacity = "0"; |
| 2577 | }); |
| 2578 | setTimeout(cb, animLength); |
| 2579 | } |
| 2580 | |
| 2581 | animate(move, callback) { |
| 2582 | if (this.noAnimate || move.noAnimate) { |
| 2583 | callback(); |
| 2584 | return; |
| 2585 | } |
| 2586 | let segments = move.segments; |
| 2587 | if (!segments) |
| 2588 | segments = [ [[move.start.x, move.start.y], [move.end.x, move.end.y]] ]; |
| 2589 | let targetObj = new TargetObj(callback); |
| 2590 | if (move.start.x != move.end.x || move.start.y != move.end.y) { |
| 2591 | targetObj.target++; |
| 2592 | this.animateMoving(move.start, move.end, move.drag, segments, |
| 2593 | () => targetObj.increment()); |
| 2594 | } |
| 2595 | if (move.vanish.length > move.appear.length) { |
| 2596 | const arr = move.vanish.slice(move.appear.length) |
| 2597 | // Ignore disappearing pieces hidden by some appearing ones: |
| 2598 | .filter(v => move.appear.every(a => a.x != v.x || a.y != v.y)); |
| 2599 | if (arr.length > 0) { |
| 2600 | targetObj.target++; |
| 2601 | this.animateFading(arr, () => targetObj.increment()); |
| 2602 | } |
| 2603 | } |
| 2604 | targetObj.target += |
| 2605 | this.tryAnimateCastle(move, () => targetObj.increment()); |
| 2606 | targetObj.target += |
| 2607 | this.customAnimate(move, segments, () => targetObj.increment()); |
| 2608 | if (targetObj.target == 0) |
| 2609 | callback(); |
| 2610 | } |
| 2611 | |
| 2612 | tryAnimateCastle(move, cb) { |
| 2613 | if ( |
| 2614 | this.hasCastle && |
| 2615 | move.vanish.length == 2 && |
| 2616 | move.appear.length == 2 && |
| 2617 | this.isKing(0, 0, move.vanish[0].p) && |
| 2618 | this.isKing(0, 0, move.appear[0].p) |
| 2619 | ) { |
| 2620 | const start = {x: move.vanish[1].x, y: move.vanish[1].y}, |
| 2621 | end = {x: move.appear[1].x, y: move.appear[1].y}; |
| 2622 | const segments = [ [[start.x, start.y], [end.x, end.y]] ]; |
| 2623 | this.animateMoving(start, end, null, segments, cb); |
| 2624 | return 1; |
| 2625 | } |
| 2626 | return 0; |
| 2627 | } |
| 2628 | |
| 2629 | // Potential other animations (e.g. for Suction variant) |
| 2630 | customAnimate(move, segments, cb) { |
| 2631 | return 0; //nb of targets |
| 2632 | } |
| 2633 | |
| 2634 | launchAnimation(moves, container, callback) { |
| 2635 | if (this.hideMoves) { |
| 2636 | for (let i=0; i<moves.length; i++) |
| 2637 | // If hiding moves, they are revealed into play(): |
| 2638 | this.play(moves[i], i == moves.length - 1 ? callback : () => {}); |
| 2639 | return; |
| 2640 | } |
| 2641 | const r = container.querySelector(".chessboard").getBoundingClientRect(); |
| 2642 | const animateRec = i => { |
| 2643 | this.animate(moves[i], () => { |
| 2644 | this.play(moves[i]); |
| 2645 | this.playVisual(moves[i], r); |
| 2646 | if (i < moves.length - 1) |
| 2647 | setTimeout(() => animateRec(i+1), 300); |
| 2648 | else |
| 2649 | callback(); |
| 2650 | }); |
| 2651 | }; |
| 2652 | animateRec(0); |
| 2653 | } |
| 2654 | |
| 2655 | playReceivedMove(moves, callback) { |
| 2656 | // Delay if user wasn't focused: |
| 2657 | const checkDisplayThenAnimate = (delay) => { |
| 2658 | if (container.style.display == "none") { |
| 2659 | alert("New move! Let's go back to game..."); |
| 2660 | document.getElementById("gameInfos").style.display = "none"; |
| 2661 | container.style.display = "block"; |
| 2662 | setTimeout( |
| 2663 | () => this.launchAnimation(moves, container, callback), |
| 2664 | 700 |
| 2665 | ); |
| 2666 | } |
| 2667 | else { |
| 2668 | setTimeout( |
| 2669 | () => this.launchAnimation(moves, container, callback), |
| 2670 | delay || 0 |
| 2671 | ); |
| 2672 | } |
| 2673 | }; |
| 2674 | let container = document.getElementById(this.containerId); |
| 2675 | if (document.hidden) { |
| 2676 | document.onvisibilitychange = () => { |
| 2677 | // TODO here: page reload ?! (some issues if tab changed...) |
| 2678 | document.onvisibilitychange = undefined; |
| 2679 | checkDisplayThenAnimate(700); |
| 2680 | }; |
| 2681 | } |
| 2682 | else |
| 2683 | checkDisplayThenAnimate(); |
| 2684 | } |
| 2685 | |
| 2686 | }; |