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