| 1 | Vue.component('my-game', { |
| 2 | data: function() { |
| 3 | return { |
| 4 | vr: null, //object to check moves, store them, FEN.. |
| 5 | mycolor: "w", |
| 6 | possibleMoves: [], //filled after each valid click/dragstart |
| 7 | choices: [], //promotion pieces, or checkered captures... (contain possible pieces) |
| 8 | start: {}, //pixels coordinates + id of starting square (click or drag) |
| 9 | selectedPiece: null, //moving piece (or clicked piece) |
| 10 | conn: null, //socket messages |
| 11 | score: "*", //'*' means 'unfinished' |
| 12 | mode: "idle", //human, computer or idle (when not playing) |
| 13 | oppid: "", //opponent ID in case of HH game |
| 14 | oppConnected: false, |
| 15 | seek: false, |
| 16 | fenStart: "", |
| 17 | incheck: [], |
| 18 | pgnTxt: "", |
| 19 | expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false, |
| 20 | gameId: "", //used to limit computer moves' time |
| 21 | }; |
| 22 | }, |
| 23 | render(h) { |
| 24 | const [sizeX,sizeY] = VariantRules.size; |
| 25 | // Precompute hints squares to facilitate rendering |
| 26 | let hintSquares = doubleArray(sizeX, sizeY, false); |
| 27 | this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; }); |
| 28 | // Also precompute in-check squares |
| 29 | let incheckSq = doubleArray(sizeX, sizeY, false); |
| 30 | this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; }); |
| 31 | let elementArray = []; |
| 32 | const playingHuman = (this.mode == "human"); |
| 33 | const playingComp = (this.mode == "computer"); |
| 34 | let actionArray = [ |
| 35 | h('button', |
| 36 | { |
| 37 | on: { click: this.clickGameSeek }, |
| 38 | attrs: { "aria-label": 'New game VS human' }, |
| 39 | 'class': { |
| 40 | "tooltip": true, |
| 41 | "bottom": true, //display below |
| 42 | "seek": this.seek, |
| 43 | "playing": playingHuman, |
| 44 | }, |
| 45 | }, |
| 46 | [h('i', { 'class': { "material-icons": true } }, "accessibility")]), |
| 47 | h('button', |
| 48 | { |
| 49 | on: { click: this.clickComputerGame }, |
| 50 | attrs: { "aria-label": 'New game VS computer' }, |
| 51 | 'class': { |
| 52 | "tooltip":true, |
| 53 | "bottom": true, |
| 54 | "playing": playingComp, |
| 55 | }, |
| 56 | }, |
| 57 | [h('i', { 'class': { "material-icons": true } }, "computer")]) |
| 58 | ]; |
| 59 | if (!!this.vr) |
| 60 | { |
| 61 | const square00 = document.getElementById("sq-0-0"); |
| 62 | const squareWidth = !!square00 |
| 63 | ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2)) |
| 64 | : 0; |
| 65 | const indicWidth = (squareWidth>0 ? squareWidth/2 : 20); |
| 66 | if (this.mode == "human") |
| 67 | { |
| 68 | let connectedIndic = h( |
| 69 | 'div', |
| 70 | { |
| 71 | "class": { |
| 72 | "topindicator": true, |
| 73 | "indic-left": true, |
| 74 | "connected": this.oppConnected, |
| 75 | "disconnected": !this.oppConnected, |
| 76 | }, |
| 77 | style: { |
| 78 | "width": indicWidth + "px", |
| 79 | "height": indicWidth + "px", |
| 80 | }, |
| 81 | } |
| 82 | ); |
| 83 | elementArray.push(connectedIndic); |
| 84 | } |
| 85 | let turnIndic = h( |
| 86 | 'div', |
| 87 | { |
| 88 | "class": { |
| 89 | "topindicator": true, |
| 90 | "indic-right": true, |
| 91 | "white-turn": this.vr.turn=="w", |
| 92 | "black-turn": this.vr.turn=="b", |
| 93 | }, |
| 94 | style: { |
| 95 | "width": indicWidth + "px", |
| 96 | "height": indicWidth + "px", |
| 97 | }, |
| 98 | } |
| 99 | ); |
| 100 | elementArray.push(turnIndic); |
| 101 | let expertSwitch = h( |
| 102 | 'button', |
| 103 | { |
| 104 | on: { click: this.toggleExpertMode }, |
| 105 | attrs: { "aria-label": 'Toggle expert mode' }, |
| 106 | 'class': { |
| 107 | "tooltip":true, |
| 108 | "topindicator": true, |
| 109 | "indic-right": true, |
| 110 | "expert-switch": true, |
| 111 | "expert-mode": this.expert, |
| 112 | }, |
| 113 | }, |
| 114 | [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")] |
| 115 | ); |
| 116 | elementArray.push(expertSwitch); |
| 117 | let choices = h('div', |
| 118 | { |
| 119 | attrs: { "id": "choices" }, |
| 120 | 'class': { 'row': true }, |
| 121 | style: { |
| 122 | "display": this.choices.length>0?"block":"none", |
| 123 | "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px", |
| 124 | "width": (this.choices.length * squareWidth) + "px", |
| 125 | "height": squareWidth + "px", |
| 126 | }, |
| 127 | }, |
| 128 | this.choices.map( m => { //a "choice" is a move |
| 129 | return h('div', |
| 130 | { |
| 131 | 'class': { |
| 132 | 'board': true, |
| 133 | ['board'+sizeY]: true, |
| 134 | }, |
| 135 | style: { |
| 136 | 'width': (100/this.choices.length) + "%", |
| 137 | 'padding-bottom': (100/this.choices.length) + "%", |
| 138 | }, |
| 139 | }, |
| 140 | [h('img', |
| 141 | { |
| 142 | attrs: { "src": '/images/pieces/' + |
| 143 | VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' }, |
| 144 | 'class': { 'choice-piece': true }, |
| 145 | on: { "click": e => { this.play(m); this.choices=[]; } }, |
| 146 | }) |
| 147 | ] |
| 148 | ); |
| 149 | }) |
| 150 | ); |
| 151 | // Create board element (+ reserves if needed by variant or mode) |
| 152 | let gameDiv = h('div', |
| 153 | { |
| 154 | 'class': { 'game': true }, |
| 155 | }, |
| 156 | [_.range(sizeX).map(i => { |
| 157 | let ci = this.mycolor=='w' ? i : sizeX-i-1; |
| 158 | return h( |
| 159 | 'div', |
| 160 | { |
| 161 | 'class': { |
| 162 | 'row': true, |
| 163 | }, |
| 164 | style: { 'opacity': this.choices.length>0?"0.5":"1" }, |
| 165 | }, |
| 166 | _.range(sizeY).map(j => { |
| 167 | let cj = this.mycolor=='w' ? j : sizeY-j-1; |
| 168 | let elems = []; |
| 169 | if (this.vr.board[ci][cj] != VariantRules.EMPTY) |
| 170 | { |
| 171 | elems.push( |
| 172 | h( |
| 173 | 'img', |
| 174 | { |
| 175 | 'class': { |
| 176 | 'piece': true, |
| 177 | 'ghost': !!this.selectedPiece |
| 178 | && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj, |
| 179 | }, |
| 180 | attrs: { |
| 181 | src: "/images/pieces/" + |
| 182 | VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg", |
| 183 | }, |
| 184 | } |
| 185 | ) |
| 186 | ); |
| 187 | } |
| 188 | if (!this.expert && hintSquares[ci][cj]) |
| 189 | { |
| 190 | elems.push( |
| 191 | h( |
| 192 | 'img', |
| 193 | { |
| 194 | 'class': { |
| 195 | 'mark-square': true, |
| 196 | }, |
| 197 | attrs: { |
| 198 | src: "/images/mark.svg", |
| 199 | }, |
| 200 | } |
| 201 | ) |
| 202 | ); |
| 203 | } |
| 204 | const lm = this.vr.lastMove; |
| 205 | const showLight = !this.expert && |
| 206 | (this.mode!="idle" || this.cursor==this.vr.moves.length); |
| 207 | return h( |
| 208 | 'div', |
| 209 | { |
| 210 | 'class': { |
| 211 | 'board': true, |
| 212 | ['board'+sizeY]: true, |
| 213 | 'light-square': (i+j)%2==0, |
| 214 | 'dark-square': (i+j)%2==1, |
| 215 | 'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}), |
| 216 | 'incheck': showLight && incheckSq[ci][cj], |
| 217 | }, |
| 218 | attrs: { |
| 219 | id: this.getSquareId({x:ci,y:cj}), |
| 220 | }, |
| 221 | }, |
| 222 | elems |
| 223 | ); |
| 224 | }) |
| 225 | ); |
| 226 | }), choices] |
| 227 | ); |
| 228 | if (this.mode != "idle") |
| 229 | { |
| 230 | actionArray.push( |
| 231 | h('button', |
| 232 | { |
| 233 | on: { click: this.resign }, |
| 234 | attrs: { "aria-label": 'Resign' }, |
| 235 | 'class': { |
| 236 | "tooltip":true, |
| 237 | "bottom": true, |
| 238 | }, |
| 239 | }, |
| 240 | [h('i', { 'class': { "material-icons": true } }, "flag")]) |
| 241 | ); |
| 242 | } |
| 243 | else if (this.vr.moves.length > 0) |
| 244 | { |
| 245 | // A game finished, and another is not started yet: allow navigation |
| 246 | actionArray = actionArray.concat([ |
| 247 | h('button', |
| 248 | { |
| 249 | style: { "margin-left": "30px" }, |
| 250 | on: { click: e => this.undo() }, |
| 251 | attrs: { "aria-label": 'Undo' }, |
| 252 | }, |
| 253 | [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]), |
| 254 | h('button', |
| 255 | { |
| 256 | on: { click: e => this.play() }, |
| 257 | attrs: { "aria-label": 'Play' }, |
| 258 | }, |
| 259 | [h('i', { 'class': { "material-icons": true } }, "fast_forward")]), |
| 260 | ] |
| 261 | ); |
| 262 | } |
| 263 | elementArray.push(gameDiv); |
| 264 | if (!!this.vr.reserve) |
| 265 | { |
| 266 | const shiftIdx = (this.mycolor=="w" ? 0 : 1); |
| 267 | let myReservePiecesArray = []; |
| 268 | for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++) |
| 269 | { |
| 270 | myReservePiecesArray.push(h('div', |
| 271 | { |
| 272 | 'class': {'board':true, ['board'+sizeY]:true}, |
| 273 | attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) } |
| 274 | }, |
| 275 | [ |
| 276 | h('img', |
| 277 | { |
| 278 | 'class': {"piece":true}, |
| 279 | attrs: { |
| 280 | "src": "/images/pieces/" + |
| 281 | this.vr.getReservePpath(this.mycolor,i) + ".svg", |
| 282 | } |
| 283 | }), |
| 284 | h('sup', |
| 285 | {style: { "padding-left":"40%"} }, |
| 286 | [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ] |
| 287 | ) |
| 288 | ])); |
| 289 | } |
| 290 | let oppReservePiecesArray = []; |
| 291 | const oppCol = this.vr.getOppCol(this.mycolor); |
| 292 | for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++) |
| 293 | { |
| 294 | oppReservePiecesArray.push(h('div', |
| 295 | { |
| 296 | 'class': {'board':true, ['board'+sizeY]:true}, |
| 297 | attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) } |
| 298 | }, |
| 299 | [ |
| 300 | h('img', |
| 301 | { |
| 302 | 'class': {"piece":true}, |
| 303 | attrs: { |
| 304 | "src": "/images/pieces/" + |
| 305 | this.vr.getReservePpath(oppCol,i) + ".svg", |
| 306 | } |
| 307 | }), |
| 308 | h('sup', |
| 309 | {style: { "padding-left":"40%"} }, |
| 310 | [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ] |
| 311 | ) |
| 312 | ])); |
| 313 | } |
| 314 | let reserves = h('div', |
| 315 | { |
| 316 | 'class':{'game':true}, |
| 317 | style: {"margin-bottom": "20px"}, |
| 318 | }, |
| 319 | [ |
| 320 | h('div', |
| 321 | { |
| 322 | 'class': { 'row': true }, |
| 323 | style: {"margin-bottom": "15px"}, |
| 324 | }, |
| 325 | myReservePiecesArray |
| 326 | ), |
| 327 | h('div', |
| 328 | { 'class': { 'row': true }}, |
| 329 | oppReservePiecesArray |
| 330 | ) |
| 331 | ] |
| 332 | ); |
| 333 | elementArray.push(reserves); |
| 334 | } |
| 335 | const eogMessage = this.getEndgameMessage(this.score); |
| 336 | const modalEog = [ |
| 337 | h('input', |
| 338 | { |
| 339 | attrs: { "id": "modal-eog", type: "checkbox" }, |
| 340 | "class": { "modal": true }, |
| 341 | }), |
| 342 | h('div', |
| 343 | { |
| 344 | attrs: { "role": "dialog", "aria-labelledby": "modal-eog" }, |
| 345 | }, |
| 346 | [ |
| 347 | h('div', |
| 348 | { |
| 349 | "class": { "card": true, "smallpad": true }, |
| 350 | }, |
| 351 | [ |
| 352 | h('label', |
| 353 | { |
| 354 | attrs: { "for": "modal-eog" }, |
| 355 | "class": { "modal-close": true }, |
| 356 | } |
| 357 | ), |
| 358 | h('h3', |
| 359 | { |
| 360 | "class": { "section": true }, |
| 361 | domProps: { innerHTML: eogMessage }, |
| 362 | } |
| 363 | ) |
| 364 | ] |
| 365 | ) |
| 366 | ] |
| 367 | ) |
| 368 | ]; |
| 369 | elementArray = elementArray.concat(modalEog); |
| 370 | } |
| 371 | const modalNewgame = [ |
| 372 | h('input', |
| 373 | { |
| 374 | attrs: { "id": "modal-newgame", type: "checkbox" }, |
| 375 | "class": { "modal": true }, |
| 376 | }), |
| 377 | h('div', |
| 378 | { |
| 379 | attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" }, |
| 380 | }, |
| 381 | [ |
| 382 | h('div', |
| 383 | { |
| 384 | "class": { "card": true, "smallpad": true }, |
| 385 | }, |
| 386 | [ |
| 387 | h('label', |
| 388 | { |
| 389 | attrs: { "id": "close-newgame", "for": "modal-newgame" }, |
| 390 | "class": { "modal-close": true }, |
| 391 | } |
| 392 | ), |
| 393 | h('h3', |
| 394 | { |
| 395 | "class": { "section": true }, |
| 396 | domProps: { innerHTML: "New game" }, |
| 397 | } |
| 398 | ), |
| 399 | h('p', |
| 400 | { |
| 401 | "class": { "section": true }, |
| 402 | domProps: { innerHTML: "Waiting for opponent..." }, |
| 403 | } |
| 404 | ) |
| 405 | ] |
| 406 | ) |
| 407 | ] |
| 408 | ) |
| 409 | ]; |
| 410 | elementArray = elementArray.concat(modalNewgame); |
| 411 | const actions = h('div', |
| 412 | { |
| 413 | attrs: { "id": "actions" }, |
| 414 | 'class': { 'text-center': true }, |
| 415 | }, |
| 416 | actionArray |
| 417 | ); |
| 418 | elementArray.push(actions); |
| 419 | if (this.score != "*") |
| 420 | { |
| 421 | elementArray.push( |
| 422 | h('div', |
| 423 | { attrs: { id: "pgn-div" } }, |
| 424 | [ |
| 425 | h('a', |
| 426 | { |
| 427 | attrs: { |
| 428 | id: "download", |
| 429 | href: "#", |
| 430 | } |
| 431 | } |
| 432 | ), |
| 433 | h('p', |
| 434 | { |
| 435 | attrs: { id: "pgn-game" }, |
| 436 | on: { click: this.download }, |
| 437 | domProps: { innerHTML: this.pgnTxt } |
| 438 | } |
| 439 | ) |
| 440 | ] |
| 441 | ) |
| 442 | ); |
| 443 | } |
| 444 | else if (this.mode != "idle") |
| 445 | { |
| 446 | // Show current FEN (at least for debug) |
| 447 | elementArray.push( |
| 448 | h('div', |
| 449 | { attrs: { id: "fen-div" } }, |
| 450 | [ |
| 451 | h('p', |
| 452 | { |
| 453 | attrs: { id: "fen-string" }, |
| 454 | domProps: { innerHTML: this.vr.getBaseFen() } |
| 455 | } |
| 456 | ) |
| 457 | ] |
| 458 | ) |
| 459 | ); |
| 460 | } |
| 461 | return h( |
| 462 | 'div', |
| 463 | { |
| 464 | 'class': { |
| 465 | "col-sm-12":true, |
| 466 | "col-md-8":true, |
| 467 | "col-md-offset-2":true, |
| 468 | "col-lg-6":true, |
| 469 | "col-lg-offset-3":true, |
| 470 | }, |
| 471 | // NOTE: click = mousedown + mouseup |
| 472 | on: { |
| 473 | mousedown: this.mousedown, |
| 474 | mousemove: this.mousemove, |
| 475 | mouseup: this.mouseup, |
| 476 | touchstart: this.mousedown, |
| 477 | touchmove: this.mousemove, |
| 478 | touchend: this.mouseup, |
| 479 | }, |
| 480 | }, |
| 481 | elementArray |
| 482 | ); |
| 483 | }, |
| 484 | created: function() { |
| 485 | const url = socketUrl; |
| 486 | const continuation = (localStorage.getItem("variant") === variant); |
| 487 | this.myid = continuation |
| 488 | ? localStorage.getItem("myid") |
| 489 | // random enough (TODO: function) |
| 490 | : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); |
| 491 | if (!continuation) |
| 492 | { |
| 493 | // HACK: play a small silent sound to allow "new game" sound later if tab not focused |
| 494 | new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {}); |
| 495 | } |
| 496 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); |
| 497 | const socketOpenListener = () => { |
| 498 | if (continuation) |
| 499 | { |
| 500 | const fen = localStorage.getItem("fen"); |
| 501 | const mycolor = localStorage.getItem("mycolor"); |
| 502 | const oppid = localStorage.getItem("oppid"); |
| 503 | const moves = JSON.parse(localStorage.getItem("moves")); |
| 504 | this.newGame("human", fen, mycolor, oppid, moves, true); |
| 505 | // Send ping to server (answer pong if opponent is connected) |
| 506 | this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid})); |
| 507 | } |
| 508 | else if (localStorage.getItem("newgame") === variant) |
| 509 | { |
| 510 | // New game request has been cancelled on disconnect |
| 511 | this.newGame("human", undefined, undefined, undefined, undefined, "reconnect"); |
| 512 | } |
| 513 | }; |
| 514 | const socketMessageListener = msg => { |
| 515 | const data = JSON.parse(msg.data); |
| 516 | switch (data.code) |
| 517 | { |
| 518 | case "newgame": //opponent found |
| 519 | this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID |
| 520 | break; |
| 521 | case "newmove": //..he played! |
| 522 | this.play(data.move, "animate"); |
| 523 | break; |
| 524 | case "pong": //received if we sent a ping (game still alive on our side) |
| 525 | this.oppConnected = true; |
| 526 | const L = this.vr.moves.length; |
| 527 | // Send our "last state" informations to opponent |
| 528 | this.conn.send(JSON.stringify({ |
| 529 | code:"lastate", |
| 530 | oppid:this.oppid, |
| 531 | lastMove:L>0?this.vr.moves[L-1]:undefined, |
| 532 | movesCount:L, |
| 533 | })); |
| 534 | break; |
| 535 | case "lastate": //got opponent infos about last move (we might have resigned) |
| 536 | if (this.mode!="human" || this.oppid!=data.oppid) |
| 537 | { |
| 538 | // OK, we resigned |
| 539 | this.conn.send(JSON.stringify({ |
| 540 | code:"lastate", |
| 541 | oppid:this.oppid, |
| 542 | lastMove:undefined, |
| 543 | movesCount:-1, |
| 544 | })); |
| 545 | } |
| 546 | else if (data.movesCount < 0) |
| 547 | { |
| 548 | // OK, he resigned |
| 549 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); |
| 550 | } |
| 551 | else if (data.movesCount < this.vr.moves.length) |
| 552 | { |
| 553 | // We must tell last move to opponent |
| 554 | const L = this.vr.moves.length; |
| 555 | this.conn.send(JSON.stringify({ |
| 556 | code:"lastate", |
| 557 | oppid:this.oppid, |
| 558 | lastMove:this.vr.moves[L-1], |
| 559 | movesCount:L, |
| 560 | })); |
| 561 | } |
| 562 | else if (data.movesCount > this.vr.moves.length) //just got last move from him |
| 563 | this.play(data.lastMove, "animate"); |
| 564 | break; |
| 565 | case "resign": //..you won! |
| 566 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); |
| 567 | break; |
| 568 | // TODO: also use (dis)connect info to count online players? |
| 569 | case "connect": |
| 570 | case "disconnect": |
| 571 | if (this.mode == "human" && this.oppid == data.id) |
| 572 | this.oppConnected = (data.code == "connect"); |
| 573 | break; |
| 574 | } |
| 575 | }; |
| 576 | const socketCloseListener = () => { |
| 577 | this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant); |
| 578 | this.conn.addEventListener('open', socketOpenListener); |
| 579 | this.conn.addEventListener('message', socketMessageListener); |
| 580 | this.conn.addEventListener('close', socketCloseListener); |
| 581 | }; |
| 582 | this.conn.onopen = socketOpenListener; |
| 583 | this.conn.onmessage = socketMessageListener; |
| 584 | this.conn.onclose = socketCloseListener; |
| 585 | // Listen to keyboard left/right to navigate in game |
| 586 | document.onkeydown = event => { |
| 587 | if (this.mode == "idle" && this.vr.moves.length > 0 |
| 588 | && [37,39].includes(event.keyCode)) |
| 589 | { |
| 590 | event.preventDefault(); |
| 591 | if (event.keyCode == 37) //Back |
| 592 | this.undo(); |
| 593 | else //Forward (39) |
| 594 | this.play(); |
| 595 | } |
| 596 | }; |
| 597 | }, |
| 598 | methods: { |
| 599 | download: function() { |
| 600 | let content = document.getElementById("pgn-game").innerHTML; |
| 601 | content = content.replace(/<br>/g, "\n"); |
| 602 | // Prepare and trigger download link |
| 603 | let downloadAnchor = document.getElementById("download"); |
| 604 | downloadAnchor.setAttribute("download", "game.pgn"); |
| 605 | downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content); |
| 606 | downloadAnchor.click(); |
| 607 | }, |
| 608 | endGame: function(score) { |
| 609 | this.score = score; |
| 610 | let modalBox = document.getElementById("modal-eog"); |
| 611 | modalBox.checked = true; |
| 612 | // Variants may have special PGN structure (so next function isn't defined here) |
| 613 | this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode); |
| 614 | setTimeout(() => { modalBox.checked = false; }, 2000); |
| 615 | if (this.mode == "human") |
| 616 | this.clearStorage(); |
| 617 | this.mode = "idle"; |
| 618 | this.cursor = this.vr.moves.length; //to navigate in finished game |
| 619 | this.oppid = ""; |
| 620 | }, |
| 621 | getEndgameMessage: function(score) { |
| 622 | let eogMessage = "Unfinished"; |
| 623 | switch (this.score) |
| 624 | { |
| 625 | case "1-0": |
| 626 | eogMessage = "White win"; |
| 627 | break; |
| 628 | case "0-1": |
| 629 | eogMessage = "Black win"; |
| 630 | break; |
| 631 | case "1/2": |
| 632 | eogMessage = "Draw"; |
| 633 | break; |
| 634 | } |
| 635 | return eogMessage; |
| 636 | }, |
| 637 | setStorage: function() { |
| 638 | localStorage.setItem("myid", this.myid); |
| 639 | localStorage.setItem("variant", variant); |
| 640 | localStorage.setItem("mycolor", this.mycolor); |
| 641 | localStorage.setItem("oppid", this.oppid); |
| 642 | localStorage.setItem("fenStart", this.fenStart); |
| 643 | localStorage.setItem("moves", JSON.stringify(this.vr.moves)); |
| 644 | localStorage.setItem("fen", this.vr.getFen()); |
| 645 | }, |
| 646 | updateStorage: function() { |
| 647 | localStorage.setItem("moves", JSON.stringify(this.vr.moves)); |
| 648 | localStorage.setItem("fen", this.vr.getFen()); |
| 649 | }, |
| 650 | clearStorage: function() { |
| 651 | delete localStorage["variant"]; |
| 652 | delete localStorage["myid"]; |
| 653 | delete localStorage["mycolor"]; |
| 654 | delete localStorage["oppid"]; |
| 655 | delete localStorage["fenStart"]; |
| 656 | delete localStorage["fen"]; |
| 657 | delete localStorage["moves"]; |
| 658 | }, |
| 659 | // HACK because mini-css tooltips are persistent after click... |
| 660 | getRidOfTooltip: function(elt) { |
| 661 | elt.style.visibility = "hidden"; |
| 662 | setTimeout(() => { elt.style.visibility="visible"; }, 100); |
| 663 | }, |
| 664 | clickGameSeek: function(e) { |
| 665 | this.getRidOfTooltip(e.currentTarget); |
| 666 | if (this.mode == "human") |
| 667 | return; //no newgame while playing |
| 668 | if (this.seek) |
| 669 | { |
| 670 | delete localStorage["newgame"]; //cancel game seek |
| 671 | this.seek = false; |
| 672 | } |
| 673 | else |
| 674 | this.newGame("human"); |
| 675 | }, |
| 676 | clickComputerGame: function(e) { |
| 677 | this.getRidOfTooltip(e.currentTarget); |
| 678 | if (this.mode == "human") |
| 679 | return; //no newgame while playing |
| 680 | this.newGame("computer"); |
| 681 | }, |
| 682 | toggleExpertMode: function(e) { |
| 683 | this.getRidOfTooltip(e.currentTarget); |
| 684 | this.expert = !this.expert; |
| 685 | document.cookie = "expert=" + (this.expert ? "1" : "0"); |
| 686 | }, |
| 687 | resign: function() { |
| 688 | if (this.mode == "human" && this.oppConnected) |
| 689 | { |
| 690 | try { |
| 691 | this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid})); |
| 692 | } catch (INVALID_STATE_ERR) { |
| 693 | return; //socket is not ready (and not yet reconnected) |
| 694 | } |
| 695 | } |
| 696 | this.endGame(this.mycolor=="w"?"0-1":"1-0"); |
| 697 | }, |
| 698 | newGame: function(mode, fenInit, color, oppId, moves, continuation) { |
| 699 | const fen = fenInit || VariantRules.GenRandInitFen(); |
| 700 | console.log(fen); //DEBUG |
| 701 | if (mode=="human" && !oppId) |
| 702 | { |
| 703 | const storageVariant = localStorage.getItem("variant"); |
| 704 | if (!!storageVariant && storageVariant !== variant) |
| 705 | { |
| 706 | alert("Finish your " + storageVariant + " game first!"); |
| 707 | return; |
| 708 | } |
| 709 | // Send game request and wait.. |
| 710 | localStorage["newgame"] = variant; |
| 711 | this.seek = true; |
| 712 | this.clearStorage(); //in case of |
| 713 | try { |
| 714 | this.conn.send(JSON.stringify({code:"newgame", fen:fen})); |
| 715 | } catch (INVALID_STATE_ERR) { |
| 716 | return; //nothing achieved |
| 717 | } |
| 718 | if (continuation !== "reconnect") //TODO: bad HACK... |
| 719 | { |
| 720 | let modalBox = document.getElementById("modal-newgame"); |
| 721 | modalBox.checked = true; |
| 722 | setTimeout(() => { modalBox.checked = false; }, 2000); |
| 723 | } |
| 724 | return; |
| 725 | } |
| 726 | // random enough (TODO: function) |
| 727 | this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); |
| 728 | this.vr = new VariantRules(fen, moves || []); |
| 729 | this.score = "*"; |
| 730 | this.pgnTxt = ""; //redundant with this.score = "*", but cleaner |
| 731 | this.mode = mode; |
| 732 | this.incheck = []; //in case of |
| 733 | this.fenStart = continuation |
| 734 | ? localStorage.getItem("fenStart") |
| 735 | : fen.split(" ")[0]; //Only the position matters |
| 736 | if (mode=="human") |
| 737 | { |
| 738 | // Opponent found! |
| 739 | if (!continuation) |
| 740 | { |
| 741 | // Not playing sound on game continuation: |
| 742 | new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {}); |
| 743 | document.getElementById("modal-newgame").checked = false; |
| 744 | } |
| 745 | this.oppid = oppId; |
| 746 | this.oppConnected = true; |
| 747 | this.mycolor = color; |
| 748 | this.seek = false; |
| 749 | if (!!moves && moves.length > 0) //imply continuation |
| 750 | { |
| 751 | const lastMove = moves[moves.length-1]; |
| 752 | this.vr.undo(lastMove); |
| 753 | this.incheck = this.vr.getCheckSquares(lastMove); |
| 754 | this.vr.play(lastMove, "ingame"); |
| 755 | } |
| 756 | delete localStorage["newgame"]; |
| 757 | this.setStorage(); //in case of interruptions |
| 758 | } |
| 759 | else //against computer |
| 760 | { |
| 761 | this.mycolor = Math.random() < 0.5 ? 'w' : 'b'; |
| 762 | if (this.mycolor == 'b') |
| 763 | setTimeout(this.playComputerMove, 500); |
| 764 | } |
| 765 | }, |
| 766 | playComputerMove: function() { |
| 767 | const timeStart = Date.now(); |
| 768 | const nbMoves = this.vr.moves.length; //using played moves to know if search finished |
| 769 | const gameId = this.gameId; //to know if game was reset before timer end |
| 770 | setTimeout( |
| 771 | () => { |
| 772 | if (gameId != this.gameId) |
| 773 | return; //game stopped |
| 774 | const L = this.vr.moves.length; |
| 775 | if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish |
| 776 | this.vr.shouldReturn = true; |
| 777 | }, 5000); |
| 778 | const compMove = this.vr.getComputerMove(); |
| 779 | // (first move) HACK: avoid selecting elements before they appear on page: |
| 780 | const delay = Math.max(500-(Date.now()-timeStart), 0); |
| 781 | setTimeout(() => this.play(compMove, "animate"), delay); |
| 782 | }, |
| 783 | // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y. |
| 784 | getSquareId: function(o) { |
| 785 | // NOTE: a separator is required to allow any size of board |
| 786 | return "sq-" + o.x + "-" + o.y; |
| 787 | }, |
| 788 | // Inverse function |
| 789 | getSquareFromId: function(id) { |
| 790 | let idParts = id.split('-'); |
| 791 | return [parseInt(idParts[1]), parseInt(idParts[2])]; |
| 792 | }, |
| 793 | mousedown: function(e) { |
| 794 | e = e || window.event; |
| 795 | let ingame = false; |
| 796 | let elem = e.target; |
| 797 | while (!ingame && elem !== null) |
| 798 | { |
| 799 | if (elem.classList.contains("game")) |
| 800 | { |
| 801 | ingame = true; |
| 802 | break; |
| 803 | } |
| 804 | elem = elem.parentElement; |
| 805 | } |
| 806 | if (!ingame) //let default behavior (click on button...) |
| 807 | return; |
| 808 | e.preventDefault(); //disable native drag & drop |
| 809 | if (!this.selectedPiece && e.target.classList.contains("piece")) |
| 810 | { |
| 811 | // Next few lines to center the piece on mouse cursor |
| 812 | let rect = e.target.parentNode.getBoundingClientRect(); |
| 813 | this.start = { |
| 814 | x: rect.x + rect.width/2, |
| 815 | y: rect.y + rect.width/2, |
| 816 | id: e.target.parentNode.id |
| 817 | }; |
| 818 | this.selectedPiece = e.target.cloneNode(); |
| 819 | this.selectedPiece.style.position = "absolute"; |
| 820 | this.selectedPiece.style.top = 0; |
| 821 | this.selectedPiece.style.display = "inline-block"; |
| 822 | this.selectedPiece.style.zIndex = 3000; |
| 823 | let startSquare = this.getSquareFromId(e.target.parentNode.id); |
| 824 | this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare) |
| 825 | ? this.vr.getPossibleMovesFrom(startSquare) |
| 826 | : []; |
| 827 | // Next line add moving piece just after current image (required for Crazyhouse reserve) |
| 828 | e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling); |
| 829 | } |
| 830 | }, |
| 831 | mousemove: function(e) { |
| 832 | if (!this.selectedPiece) |
| 833 | return; |
| 834 | e = e || window.event; |
| 835 | // If there is an active element, move it around |
| 836 | if (!!this.selectedPiece) |
| 837 | { |
| 838 | const [offsetX,offsetY] = !!e.clientX |
| 839 | ? [e.clientX,e.clientY] //desktop browser |
| 840 | : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone |
| 841 | this.selectedPiece.style.left = (offsetX-this.start.x) + "px"; |
| 842 | this.selectedPiece.style.top = (offsetY-this.start.y) + "px"; |
| 843 | } |
| 844 | }, |
| 845 | mouseup: function(e) { |
| 846 | if (!this.selectedPiece) |
| 847 | return; |
| 848 | e = e || window.event; |
| 849 | // Read drop target (or parentElement, parentNode... if type == "img") |
| 850 | this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates |
| 851 | const [offsetX,offsetY] = !!e.clientX |
| 852 | ? [e.clientX,e.clientY] |
| 853 | : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; |
| 854 | let landing = document.elementFromPoint(offsetX, offsetY); |
| 855 | this.selectedPiece.style.zIndex = 3000; |
| 856 | while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight |
| 857 | landing = landing.parentNode; |
| 858 | if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled |
| 859 | return; |
| 860 | // OK: process move attempt |
| 861 | let endSquare = this.getSquareFromId(landing.id); |
| 862 | let moves = this.findMatchingMoves(endSquare); |
| 863 | this.possibleMoves = []; |
| 864 | if (moves.length > 1) |
| 865 | this.choices = moves; |
| 866 | else if (moves.length==1) |
| 867 | this.play(moves[0]); |
| 868 | // Else: impossible move |
| 869 | this.selectedPiece.parentNode.removeChild(this.selectedPiece); |
| 870 | delete this.selectedPiece; |
| 871 | this.selectedPiece = null; |
| 872 | }, |
| 873 | findMatchingMoves: function(endSquare) { |
| 874 | // Run through moves list and return the matching set (if promotions...) |
| 875 | let moves = []; |
| 876 | this.possibleMoves.forEach(function(m) { |
| 877 | if (endSquare[0] == m.end.x && endSquare[1] == m.end.y) |
| 878 | moves.push(m); |
| 879 | }); |
| 880 | return moves; |
| 881 | }, |
| 882 | animateMove: function(move) { |
| 883 | let startSquare = document.getElementById(this.getSquareId(move.start)); |
| 884 | let endSquare = document.getElementById(this.getSquareId(move.end)); |
| 885 | let rectStart = startSquare.getBoundingClientRect(); |
| 886 | let rectEnd = endSquare.getBoundingClientRect(); |
| 887 | let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y}; |
| 888 | let movingPiece = |
| 889 | document.querySelector("#" + this.getSquareId(move.start) + " > img.piece"); |
| 890 | // HACK for animation (with positive translate, image slides "under background"...) |
| 891 | // Possible improvement: just alter squares on the piece's way... |
| 892 | squares = document.getElementsByClassName("board"); |
| 893 | for (let i=0; i<squares.length; i++) |
| 894 | { |
| 895 | let square = squares.item(i); |
| 896 | if (square.id != this.getSquareId(move.start)) |
| 897 | square.style.zIndex = "-1"; |
| 898 | } |
| 899 | movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)"; |
| 900 | movingPiece.style.transitionDuration = "0.2s"; |
| 901 | movingPiece.style.zIndex = "3000"; |
| 902 | setTimeout( () => { |
| 903 | for (let i=0; i<squares.length; i++) |
| 904 | squares.item(i).style.zIndex = "auto"; |
| 905 | movingPiece.style = {}; //required e.g. for 0-0 with KR swap |
| 906 | this.play(move); |
| 907 | }, 200); |
| 908 | }, |
| 909 | play: function(move, programmatic) { |
| 910 | if (!move) |
| 911 | { |
| 912 | // Navigate after game is over |
| 913 | if (this.cursor >= this.vr.moves.length) |
| 914 | return; //already at the end |
| 915 | move = this.vr.moves[this.cursor++]; |
| 916 | } |
| 917 | if (!!programmatic) //computer or human opponent |
| 918 | { |
| 919 | this.animateMove(move); |
| 920 | return; |
| 921 | } |
| 922 | // Not programmatic, or animation is over |
| 923 | if (this.mode == "human" && this.vr.turn == this.mycolor) |
| 924 | this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid})); |
| 925 | new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {}); |
| 926 | if (this.mode != "idle") |
| 927 | { |
| 928 | this.incheck = this.vr.getCheckSquares(move); //is opponent in check? |
| 929 | this.vr.play(move, "ingame"); |
| 930 | } |
| 931 | else |
| 932 | { |
| 933 | VariantRules.PlayOnBoard(this.vr.board, move); |
| 934 | this.$forceUpdate(); //TODO: ?! |
| 935 | } |
| 936 | if (this.mode == "human") |
| 937 | this.updateStorage(); //after our moves and opponent moves |
| 938 | if (this.mode != "idle") |
| 939 | { |
| 940 | const eog = this.vr.checkGameOver(); |
| 941 | if (eog != "*") |
| 942 | this.endGame(eog); |
| 943 | } |
| 944 | if (this.mode == "computer" && this.vr.turn != this.mycolor) |
| 945 | setTimeout(this.playComputerMove, 500); |
| 946 | }, |
| 947 | undo: function() { |
| 948 | // Navigate after game is over |
| 949 | if (this.cursor == 0) |
| 950 | return; //already at the beginning |
| 951 | if (this.cursor == this.vr.moves.length) |
| 952 | this.incheck = []; //in case of... |
| 953 | const move = this.vr.moves[--this.cursor]; |
| 954 | VariantRules.UndoOnBoard(this.vr.board, move); |
| 955 | this.$forceUpdate(); //TODO: ?! |
| 956 | } |
| 957 | }, |
| 958 | }) |