| 1 | <template lang="pug"> |
| 2 | main |
| 3 | input#modalInfo.modal(type="checkbox") |
| 4 | div#infoDiv( |
| 5 | role="dialog" |
| 6 | data-checkbox="modalInfo" |
| 7 | ) |
| 8 | .card.text-center |
| 9 | label.modal-close(for="modalInfo") |
| 10 | a( |
| 11 | :href="'#/game/' + rematchId" |
| 12 | onClick="document.getElementById('modalInfo').checked=false" |
| 13 | ) |
| 14 | | {{ st.tr["Rematch in progress"] }} |
| 15 | input#modalChat.modal( |
| 16 | type="checkbox" |
| 17 | @click="toggleChat()" |
| 18 | ) |
| 19 | div#chatWrap( |
| 20 | role="dialog" |
| 21 | data-checkbox="modalChat" |
| 22 | ) |
| 23 | .card |
| 24 | label.modal-close(for="modalChat") |
| 25 | #participants |
| 26 | span {{ st.tr["Participant(s):"] }} |
| 27 | span( |
| 28 | v-for="p in Object.values(people)" |
| 29 | v-if="p.focus && !!p.name" |
| 30 | ) |
| 31 | | {{ p.name }} |
| 32 | span.anonymous( |
| 33 | v-if="Object.values(people).some(p => p.focus && !p.name)" |
| 34 | ) |
| 35 | | + @nonymous |
| 36 | Chat( |
| 37 | ref="chatcomp" |
| 38 | :players="game.players" |
| 39 | :pastChats="game.chats" |
| 40 | @mychat="processChat" |
| 41 | @chatcleared="clearChat" |
| 42 | ) |
| 43 | input#modalConfirm.modal(type="checkbox") |
| 44 | div#confirmDiv(role="dialog") |
| 45 | .card |
| 46 | .diagram( |
| 47 | v-if="!!vr && ['all','byrow'].includes(vr.showMoves)" |
| 48 | v-html="curDiag" |
| 49 | ) |
| 50 | p.text-center(v-else) |
| 51 | span {{ st.tr["Move played:"] + " " }} |
| 52 | span.bold {{ moveNotation }} |
| 53 | br |
| 54 | span {{ st.tr["Are you sure?"] }} |
| 55 | .button-group#buttonsConfirm |
| 56 | // onClick for acceptBtn: set dynamically |
| 57 | button.acceptBtn |
| 58 | span {{ st.tr["Validate"] }} |
| 59 | button.refuseBtn(@click="cancelMove()") |
| 60 | span {{ st.tr["Cancel"] }} |
| 61 | .row |
| 62 | #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2 |
| 63 | span.variant-cadence {{ game.cadence }} |
| 64 | span.variant-name {{ game.vname }} |
| 65 | span#nextGame( |
| 66 | v-if="nextIds.length > 0" |
| 67 | @click="showNextGame()" |
| 68 | ) |
| 69 | | {{ st.tr["Next_g"] }} |
| 70 | button#chatBtn.tooltip( |
| 71 | onClick="window.doClick('modalChat')" |
| 72 | aria-label="Chat" |
| 73 | ) |
| 74 | img(src="/images/icons/chat.svg") |
| 75 | #actions(v-if="game.score=='*'") |
| 76 | button.tooltip( |
| 77 | @click="clickDraw()" |
| 78 | :class="{['draw-' + drawOffer]: true}" |
| 79 | :aria-label="st.tr['Draw']" |
| 80 | ) |
| 81 | img(src="/images/icons/draw.svg") |
| 82 | button.tooltip( |
| 83 | v-if="!!game.mycolor" |
| 84 | @click="abortGame()" |
| 85 | :aria-label="st.tr['Abort']" |
| 86 | ) |
| 87 | img(src="/images/icons/abort.svg") |
| 88 | button.tooltip( |
| 89 | v-if="!!game.mycolor" |
| 90 | @click="resign()" |
| 91 | :aria-label="st.tr['Resign']" |
| 92 | ) |
| 93 | img(src="/images/icons/resign.svg") |
| 94 | button.tooltip( |
| 95 | v-else |
| 96 | @click="clickRematch()" |
| 97 | :class="{['rematch-' + rematchOffer]: true}" |
| 98 | :aria-label="st.tr['Rematch']" |
| 99 | ) |
| 100 | img(src="/images/icons/rematch.svg") |
| 101 | #playersInfo |
| 102 | p |
| 103 | span.name(:class="{connected: isConnected(0)}") |
| 104 | | {{ game.players[0].name || "@nonymous" }} |
| 105 | span.time( |
| 106 | v-if="game.score=='*'" |
| 107 | :class="{yourturn: !!vr && vr.turn == 'w'}" |
| 108 | ) |
| 109 | span.time-left {{ virtualClocks[0][0] }} |
| 110 | span.time-separator(v-if="!!virtualClocks[0][1]") : |
| 111 | span.time-right(v-if="!!virtualClocks[0][1]") |
| 112 | | {{ virtualClocks[0][1] }} |
| 113 | span.split-names - |
| 114 | span.name(:class="{connected: isConnected(1)}") |
| 115 | | {{ game.players[1].name || "@nonymous" }} |
| 116 | span.time( |
| 117 | v-if="game.score=='*'" |
| 118 | :class="{yourturn: !!vr && vr.turn == 'b'}" |
| 119 | ) |
| 120 | span.time-left {{ virtualClocks[1][0] }} |
| 121 | span.time-separator(v-if="!!virtualClocks[1][1]") : |
| 122 | span.time-right(v-if="!!virtualClocks[1][1]") |
| 123 | | {{ virtualClocks[1][1] }} |
| 124 | BaseGame( |
| 125 | ref="basegame" |
| 126 | :game="game" |
| 127 | @newmove="processMove" |
| 128 | ) |
| 129 | </template> |
| 130 | |
| 131 | <script> |
| 132 | import BaseGame from "@/components/BaseGame.vue"; |
| 133 | import Chat from "@/components/Chat.vue"; |
| 134 | import { store } from "@/store"; |
| 135 | import { GameStorage } from "@/utils/gameStorage"; |
| 136 | import { ppt } from "@/utils/datetime"; |
| 137 | import { ajax } from "@/utils/ajax"; |
| 138 | import { extractTime } from "@/utils/timeControl"; |
| 139 | import { getRandString } from "@/utils/alea"; |
| 140 | import { getScoreMessage } from "@/utils/scoring"; |
| 141 | import { getFullNotation } from "@/utils/notation"; |
| 142 | import { getDiagram } from "@/utils/printDiagram"; |
| 143 | import { processModalClick } from "@/utils/modalClick"; |
| 144 | import { playMove, getFilteredMove } from "@/utils/playUndo"; |
| 145 | import { ArrayFun } from "@/utils/array"; |
| 146 | import params from "@/parameters"; |
| 147 | export default { |
| 148 | name: "my-game", |
| 149 | components: { |
| 150 | BaseGame, |
| 151 | Chat |
| 152 | }, |
| 153 | data: function() { |
| 154 | return { |
| 155 | st: store.state, |
| 156 | // gameRef can point to a corr game, local game or remote live game |
| 157 | gameRef: "", |
| 158 | nextIds: [], |
| 159 | game: {}, //passed to BaseGame |
| 160 | // virtualClocks will be initialized from true game.clocks |
| 161 | virtualClocks: [], |
| 162 | vr: null, //"variant rules" object initialized from FEN |
| 163 | drawOffer: "", |
| 164 | rematchId: "", |
| 165 | rematchOffer: "", |
| 166 | lastateAsked: false, |
| 167 | people: {}, //players + observers |
| 168 | lastate: undefined, //used if opponent send lastate before game is ready |
| 169 | repeat: {}, //detect position repetition |
| 170 | curDiag: "", //for corr moves confirmation |
| 171 | conn: null, |
| 172 | roomInitialized: false, |
| 173 | // If newmove has wrong index: ask fullgame again: |
| 174 | askGameTime: 0, |
| 175 | gameIsLoading: false, |
| 176 | // If asklastate got no reply, ask again: |
| 177 | gotLastate: false, |
| 178 | gotMoveIdx: -1, //last move index received |
| 179 | // If newmove got no pingback, send again: |
| 180 | opponentGotMove: false, |
| 181 | connexionString: "", |
| 182 | // Incomplete info games: show move played |
| 183 | moveNotation: "", |
| 184 | // Intervals from setInterval(): |
| 185 | askLastate: null, |
| 186 | retrySendmove: null, |
| 187 | clockUpdate: null, |
| 188 | // Related to (killing of) self multi-connects: |
| 189 | newConnect: {}, |
| 190 | killed: {} |
| 191 | }; |
| 192 | }, |
| 193 | watch: { |
| 194 | $route: function(to, from) { |
| 195 | if (from.params["id"] != to.params["id"]) { |
| 196 | // Change everything: |
| 197 | this.cleanBeforeDestroy(); |
| 198 | let boardDiv = document.querySelector(".game"); |
| 199 | if (!!boardDiv) |
| 200 | // In case of incomplete information variant: |
| 201 | boardDiv.style.visibility = "hidden"; |
| 202 | this.atCreation(); |
| 203 | } else |
| 204 | // Same game ID |
| 205 | this.nextIds = JSON.parse(this.$route.query["next"] || "[]"); |
| 206 | } |
| 207 | }, |
| 208 | // NOTE: some redundant code with Hall.vue (mostly related to people array) |
| 209 | created: function() { |
| 210 | this.atCreation(); |
| 211 | }, |
| 212 | mounted: function() { |
| 213 | document.addEventListener('visibilitychange', this.visibilityChange); |
| 214 | ["chatWrap", "infoDiv"].forEach(eltName => { |
| 215 | document.getElementById(eltName) |
| 216 | .addEventListener("click", processModalClick); |
| 217 | }); |
| 218 | if ("ontouchstart" in window) { |
| 219 | // Disable tooltips on smartphones: |
| 220 | document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => { |
| 221 | elt.classList.remove("tooltip"); |
| 222 | }); |
| 223 | } |
| 224 | }, |
| 225 | beforeDestroy: function() { |
| 226 | document.removeEventListener('visibilitychange', this.visibilityChange); |
| 227 | this.cleanBeforeDestroy(); |
| 228 | }, |
| 229 | methods: { |
| 230 | visibilityChange: function() { |
| 231 | // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27 |
| 232 | this.send( |
| 233 | document.visibilityState == "visible" |
| 234 | ? "getfocus" |
| 235 | : "losefocus" |
| 236 | ); |
| 237 | }, |
| 238 | atCreation: function() { |
| 239 | // 0] (Re)Set variables |
| 240 | this.gameRef = this.$route.params["id"]; |
| 241 | // next = next corr games IDs to navigate faster (if applicable) |
| 242 | this.nextIds = JSON.parse(this.$route.query["next"] || "[]"); |
| 243 | // Always add myself to players' list |
| 244 | const my = this.st.user; |
| 245 | this.$set( |
| 246 | this.people, |
| 247 | my.sid, |
| 248 | { |
| 249 | id: my.id, |
| 250 | name: my.name, |
| 251 | focus: true |
| 252 | } |
| 253 | ); |
| 254 | this.game = { |
| 255 | players: [{ name: "" }, { name: "" }], |
| 256 | chats: [], |
| 257 | rendered: false |
| 258 | }; |
| 259 | let chatComp = this.$refs["chatcomp"]; |
| 260 | if (!!chatComp) chatComp.chats = []; |
| 261 | this.virtualClocks = [[0,0], [0,0]]; |
| 262 | this.vr = null; |
| 263 | this.drawOffer = ""; |
| 264 | this.lastateAsked = false; |
| 265 | this.rematchOffer = ""; |
| 266 | this.lastate = undefined; |
| 267 | this.roomInitialized = false; |
| 268 | this.askGameTime = 0; |
| 269 | this.gameIsLoading = false; |
| 270 | this.gotLastate = false; |
| 271 | this.gotMoveIdx = -1; |
| 272 | this.opponentGotMove = false; |
| 273 | this.askLastate = null; |
| 274 | this.retrySendmove = null; |
| 275 | this.clockUpdate = null; |
| 276 | this.newConnect = {}; |
| 277 | this.killed = {}; |
| 278 | // 1] Initialize connection |
| 279 | this.connexionString = |
| 280 | params.socketUrl + |
| 281 | "/?sid=" + |
| 282 | this.st.user.sid + |
| 283 | "&id=" + |
| 284 | this.st.user.id + |
| 285 | "&tmpId=" + |
| 286 | getRandString() + |
| 287 | "&page=" + |
| 288 | // Discard potential "/?next=[...]" for page indication: |
| 289 | encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]); |
| 290 | this.conn = new WebSocket(this.connexionString); |
| 291 | this.conn.addEventListener("message", this.socketMessageListener); |
| 292 | this.conn.addEventListener("close", this.socketCloseListener); |
| 293 | // Socket init required before loading remote game: |
| 294 | const socketInit = callback => { |
| 295 | if (this.conn.readyState == 1) |
| 296 | // 1 == OPEN state |
| 297 | callback(); |
| 298 | else |
| 299 | // Socket not ready yet (initial loading) |
| 300 | // NOTE: first arg is Websocket object, unused here: |
| 301 | this.conn.onopen = () => callback(); |
| 302 | }; |
| 303 | this.fetchGame((game) => { |
| 304 | if (!!game) |
| 305 | this.loadVariantThenGame(game, () => socketInit(this.roomInit)); |
| 306 | else |
| 307 | // Live game stored remotely: need socket to retrieve it |
| 308 | // NOTE: the callback "roomInit" will be lost, so we don't provide it. |
| 309 | // --> It will be given when receiving "fullgame" socket event. |
| 310 | socketInit(() => { this.send("askfullgame"); }); |
| 311 | }); |
| 312 | }, |
| 313 | cleanBeforeDestroy: function() { |
| 314 | if (!!this.askLastate) |
| 315 | clearInterval(this.askLastate); |
| 316 | if (!!this.retrySendmove) |
| 317 | clearInterval(this.retrySendmove); |
| 318 | if (!!this.clockUpdate) |
| 319 | clearInterval(this.clockUpdate); |
| 320 | this.send("disconnect"); |
| 321 | }, |
| 322 | roomInit: function() { |
| 323 | if (!this.roomInitialized) { |
| 324 | // Notify the room only now that I connected, because |
| 325 | // messages might be lost otherwise (if game loading is slow) |
| 326 | this.send("connect"); |
| 327 | this.send("pollclients"); |
| 328 | // We may ask fullgame several times if some moves are lost, |
| 329 | // but room should be init only once: |
| 330 | this.roomInitialized = true; |
| 331 | } |
| 332 | }, |
| 333 | send: function(code, obj) { |
| 334 | if (!!this.conn) |
| 335 | this.conn.send(JSON.stringify(Object.assign({ code: code }, obj))); |
| 336 | }, |
| 337 | isConnected: function(index) { |
| 338 | const player = this.game.players[index]; |
| 339 | // Is it me ? In this case no need to bother with focus |
| 340 | if (this.st.user.sid == player.sid || this.st.user.id == player.id) |
| 341 | // Still have to check for name (because of potential multi-accounts |
| 342 | // on same browser, although this should be rare...) |
| 343 | return (!this.st.user.name || this.st.user.name == player.name); |
| 344 | // Try to find a match in people: |
| 345 | return ( |
| 346 | ( |
| 347 | !!player.sid && |
| 348 | Object.keys(this.people).some(sid => |
| 349 | sid == player.sid && this.people[sid].focus) |
| 350 | ) |
| 351 | || |
| 352 | ( |
| 353 | !!player.id && |
| 354 | Object.values(this.people).some(p => |
| 355 | p.id == player.id && p.focus) |
| 356 | ) |
| 357 | ); |
| 358 | }, |
| 359 | getOppsid: function() { |
| 360 | let oppsid = this.game.oppsid; |
| 361 | if (!oppsid) { |
| 362 | oppsid = Object.keys(this.people).find( |
| 363 | sid => this.people[sid].id == this.game.oppid |
| 364 | ); |
| 365 | } |
| 366 | // oppsid is useful only if opponent is online: |
| 367 | if (!!oppsid && !!this.people[oppsid]) return oppsid; |
| 368 | return null; |
| 369 | }, |
| 370 | toggleChat: function() { |
| 371 | if (document.getElementById("modalChat").checked) |
| 372 | // Entering chat |
| 373 | document.getElementById("inputChat").focus(); |
| 374 | // TODO: next line is only required when exiting chat, |
| 375 | // but the event for now isn't well detected. |
| 376 | document.getElementById("chatBtn").classList.remove("somethingnew"); |
| 377 | }, |
| 378 | processChat: function(chat) { |
| 379 | this.send("newchat", { data: chat }); |
| 380 | // NOTE: anonymous chats in corr games are not stored on server (TODO?) |
| 381 | if (this.game.type == "corr" && this.st.user.id > 0) |
| 382 | this.updateCorrGame({ chat: chat }); |
| 383 | }, |
| 384 | clearChat: function() { |
| 385 | // Nothing more to do if game is live (chats not recorded) |
| 386 | if (this.game.type == "corr") { |
| 387 | if (!!this.game.mycolor) { |
| 388 | ajax( |
| 389 | "/chats", |
| 390 | "DELETE", |
| 391 | { data: { gid: this.game.id } } |
| 392 | ); |
| 393 | } |
| 394 | this.$set(this.game, "chats", []); |
| 395 | } |
| 396 | }, |
| 397 | getGameType: function(game) { |
| 398 | return game.cadence.indexOf("d") >= 0 ? "corr" : "live"; |
| 399 | }, |
| 400 | // Notify something after a new move (to opponent and me on MyGames page) |
| 401 | notifyMyGames: function(thing, data) { |
| 402 | this.send( |
| 403 | "notify" + thing, |
| 404 | { |
| 405 | data: data, |
| 406 | targets: this.game.players.map(p => { |
| 407 | return { sid: p.sid, id: p.id }; |
| 408 | }) |
| 409 | } |
| 410 | ); |
| 411 | }, |
| 412 | showNextGame: function() { |
| 413 | // Did I play in current game? If not, add it to nextIds list |
| 414 | if (this.game.score == "*" && this.vr.turn == this.game.mycolor) |
| 415 | this.nextIds.unshift(this.game.id); |
| 416 | const nextGid = this.nextIds.pop(); |
| 417 | this.$router.push( |
| 418 | "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds)); |
| 419 | }, |
| 420 | askGameAgain: function() { |
| 421 | this.gameIsLoading = true; |
| 422 | const currentUrl = document.location.href; |
| 423 | const doAskGame = () => { |
| 424 | if (document.location.href != currentUrl) return; //page change |
| 425 | this.fetchGame((game) => { |
| 426 | if (!!game) |
| 427 | // This is my game: just reload. |
| 428 | this.loadGame(game); |
| 429 | else |
| 430 | // Just ask fullgame again (once!), this is much simpler. |
| 431 | // If this fails, the user could just reload page :/ |
| 432 | this.send("askfullgame"); |
| 433 | }); |
| 434 | }; |
| 435 | // Delay of at least 2s between two game requests |
| 436 | const now = Date.now(); |
| 437 | const delay = Math.max(2000 - (now - this.askGameTime), 0); |
| 438 | this.askGameTime = now; |
| 439 | setTimeout(doAskGame, delay); |
| 440 | }, |
| 441 | socketMessageListener: function(msg) { |
| 442 | if (!this.conn) return; |
| 443 | const data = JSON.parse(msg.data); |
| 444 | switch (data.code) { |
| 445 | case "pollclients": |
| 446 | // TODO: shuffling and random filtering on server, if |
| 447 | // the room is really crowded. |
| 448 | data.sockIds.forEach(sid => { |
| 449 | if (sid != this.st.user.sid) { |
| 450 | this.people[sid] = { focus: true }; |
| 451 | this.send("askidentity", { target: sid }); |
| 452 | } |
| 453 | }); |
| 454 | break; |
| 455 | case "connect": |
| 456 | if (!this.people[data.from]) { |
| 457 | this.people[data.from] = { focus: true }; |
| 458 | this.newConnect[data.from] = true; //for self multi-connects tests |
| 459 | this.send("askidentity", { target: data.from }); |
| 460 | } |
| 461 | break; |
| 462 | case "disconnect": |
| 463 | this.$delete(this.people, data.from); |
| 464 | break; |
| 465 | case "getfocus": { |
| 466 | let player = this.people[data.from]; |
| 467 | if (!!player) { |
| 468 | player.focus = true; |
| 469 | this.$forceUpdate(); //TODO: shouldn't be required |
| 470 | } |
| 471 | break; |
| 472 | } |
| 473 | case "losefocus": { |
| 474 | let player = this.people[data.from]; |
| 475 | if (!!player) { |
| 476 | player.focus = false; |
| 477 | this.$forceUpdate(); //TODO: shouldn't be required |
| 478 | } |
| 479 | break; |
| 480 | } |
| 481 | case "killed": |
| 482 | // I logged in elsewhere: |
| 483 | this.conn.removeEventListener("message", this.socketMessageListener); |
| 484 | this.conn.removeEventListener("close", this.socketCloseListener); |
| 485 | this.conn = null; |
| 486 | alert(this.st.tr["New connexion detected: tab now offline"]); |
| 487 | break; |
| 488 | case "askidentity": { |
| 489 | // Request for identification |
| 490 | const me = { |
| 491 | // Decompose to avoid revealing email |
| 492 | name: this.st.user.name, |
| 493 | sid: this.st.user.sid, |
| 494 | id: this.st.user.id |
| 495 | }; |
| 496 | this.send("identity", { data: me, target: data.from }); |
| 497 | break; |
| 498 | } |
| 499 | case "identity": { |
| 500 | const user = data.data; |
| 501 | let player = this.people[user.sid]; |
| 502 | // player.focus is already set |
| 503 | player.name = user.name; |
| 504 | player.id = user.id; |
| 505 | this.$forceUpdate(); //TODO: shouldn't be required |
| 506 | // If I multi-connect, kill current connexion if no mark (I'm older) |
| 507 | if (this.newConnect[user.sid]) { |
| 508 | if ( |
| 509 | user.id > 0 && |
| 510 | user.id == this.st.user.id && |
| 511 | user.sid != this.st.user.sid && |
| 512 | !this.killed[this.st.user.sid] |
| 513 | ) { |
| 514 | this.send("killme", { sid: this.st.user.sid }); |
| 515 | this.killed[this.st.user.sid] = true; |
| 516 | } |
| 517 | delete this.newConnect[user.sid]; |
| 518 | } |
| 519 | if (!this.killed[this.st.user.sid]) { |
| 520 | // Ask potentially missed last state, if opponent and I play |
| 521 | if ( |
| 522 | !!this.game.mycolor && |
| 523 | this.game.type == "live" && |
| 524 | this.game.score == "*" && |
| 525 | this.game.players.some(p => p.sid == user.sid) |
| 526 | ) { |
| 527 | this.send("asklastate", { target: user.sid }); |
| 528 | let counter = 1; |
| 529 | this.askLastate = setInterval( |
| 530 | () => { |
| 531 | // Ask at most 3 times: |
| 532 | // if no reply after that there should be a network issue. |
| 533 | if ( |
| 534 | counter < 3 && |
| 535 | !this.gotLastate && |
| 536 | !!this.people[user.sid] |
| 537 | ) { |
| 538 | this.send("asklastate", { target: user.sid }); |
| 539 | counter++; |
| 540 | } else { |
| 541 | clearInterval(this.askLastate); |
| 542 | } |
| 543 | }, |
| 544 | 1500 |
| 545 | ); |
| 546 | } |
| 547 | } |
| 548 | break; |
| 549 | } |
| 550 | case "askgame": |
| 551 | // Send current (live) game if not asked by any of the players |
| 552 | if ( |
| 553 | this.game.type == "live" && |
| 554 | this.game.players.every(p => p.sid != data.from[0]) |
| 555 | ) { |
| 556 | const myGame = { |
| 557 | id: this.game.id, |
| 558 | fen: this.game.fen, |
| 559 | players: this.game.players, |
| 560 | vid: this.game.vid, |
| 561 | cadence: this.game.cadence, |
| 562 | score: this.game.score |
| 563 | }; |
| 564 | this.send("game", { data: myGame, target: data.from }); |
| 565 | } |
| 566 | break; |
| 567 | case "askfullgame": |
| 568 | const gameToSend = Object.keys(this.game) |
| 569 | .filter(k => |
| 570 | [ |
| 571 | "id","fen","players","vid","cadence","fenStart","vname", |
| 572 | "moves","clocks","score","drawOffer","rematchOffer" |
| 573 | ].includes(k)) |
| 574 | .reduce( |
| 575 | (obj, k) => { |
| 576 | obj[k] = this.game[k]; |
| 577 | return obj; |
| 578 | }, |
| 579 | {} |
| 580 | ); |
| 581 | this.send("fullgame", { data: gameToSend, target: data.from }); |
| 582 | break; |
| 583 | case "fullgame": |
| 584 | // Callback "roomInit" to poll clients only after game is loaded |
| 585 | this.loadVariantThenGame(data.data, this.roomInit); |
| 586 | break; |
| 587 | case "asklastate": |
| 588 | // Sending informative last state if I played a move or score != "*" |
| 589 | // If the game or moves aren't loaded yet, delay the sending: |
| 590 | if (!this.game || !this.game.moves) this.lastateAsked = true; |
| 591 | else this.sendLastate(data.from); |
| 592 | break; |
| 593 | case "lastate": { |
| 594 | // Got opponent infos about last move |
| 595 | this.gotLastate = true; |
| 596 | this.lastate = data.data; |
| 597 | if (this.game.rendered) |
| 598 | // Game is rendered (Board component) |
| 599 | this.processLastate(); |
| 600 | // Else: will be processed when game is ready |
| 601 | break; |
| 602 | } |
| 603 | case "newmove": { |
| 604 | const movePlus = data.data; |
| 605 | const movesCount = this.game.moves.length; |
| 606 | if (movePlus.index > movesCount) { |
| 607 | // This can only happen if I'm an observer and missed a move. |
| 608 | if (this.gotMoveIdx < movePlus.index) |
| 609 | this.gotMoveIdx = movePlus.index; |
| 610 | if (!this.gameIsLoading) this.askGameAgain(); |
| 611 | } |
| 612 | else { |
| 613 | if ( |
| 614 | movePlus.index < movesCount || |
| 615 | this.gotMoveIdx >= movePlus.index |
| 616 | ) { |
| 617 | // Opponent re-send but we already have the move: |
| 618 | // (maybe he didn't receive our pingback...) |
| 619 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
| 620 | } else { |
| 621 | this.gotMoveIdx = movePlus.index; |
| 622 | const receiveMyMove = (movePlus.color == this.game.mycolor); |
| 623 | if (!receiveMyMove && !!this.game.mycolor) |
| 624 | // Notify opponent that I got the move: |
| 625 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
| 626 | if (movePlus.cancelDrawOffer) { |
| 627 | // Opponent refuses draw |
| 628 | this.drawOffer = ""; |
| 629 | // NOTE for corr games: drawOffer reset by player in turn |
| 630 | if ( |
| 631 | this.game.type == "live" && |
| 632 | !!this.game.mycolor && |
| 633 | !receiveMyMove |
| 634 | ) { |
| 635 | GameStorage.update(this.gameRef, { drawOffer: "" }); |
| 636 | } |
| 637 | } |
| 638 | this.$refs["basegame"].play(movePlus.move, "received", null, true); |
| 639 | const moveColIdx = ["w", "b"].indexOf(movePlus.color); |
| 640 | this.game.clocks[moveColIdx] = movePlus.clock; |
| 641 | this.processMove( |
| 642 | movePlus.move, |
| 643 | { receiveMyMove: receiveMyMove } |
| 644 | ); |
| 645 | } |
| 646 | } |
| 647 | break; |
| 648 | } |
| 649 | case "gotmove": { |
| 650 | this.opponentGotMove = true; |
| 651 | // Now his clock starts running on my side: |
| 652 | const oppIdx = ['w','b'].indexOf(this.vr.turn); |
| 653 | this.re_setClocks(); |
| 654 | break; |
| 655 | } |
| 656 | case "resign": |
| 657 | const score = (data.data == "b" ? "1-0" : "0-1"); |
| 658 | const side = (data.data == "w" ? "White" : "Black"); |
| 659 | this.gameOver(score, side + " surrender"); |
| 660 | break; |
| 661 | case "abort": |
| 662 | this.gameOver("?", "Stop"); |
| 663 | break; |
| 664 | case "draw": |
| 665 | this.gameOver("1/2", data.data); |
| 666 | break; |
| 667 | case "drawoffer": |
| 668 | // NOTE: observers don't know who offered draw |
| 669 | this.drawOffer = "received"; |
| 670 | if (this.game.type == "live") { |
| 671 | GameStorage.update( |
| 672 | this.gameRef, |
| 673 | { drawOffer: V.GetOppCol(this.game.mycolor) } |
| 674 | ); |
| 675 | } |
| 676 | break; |
| 677 | case "rematchoffer": |
| 678 | // NOTE: observers don't know who offered rematch |
| 679 | this.rematchOffer = data.data ? "received" : ""; |
| 680 | if (this.game.type == "live") { |
| 681 | GameStorage.update( |
| 682 | this.gameRef, |
| 683 | { rematchOffer: V.GetOppCol(this.game.mycolor) } |
| 684 | ); |
| 685 | } |
| 686 | break; |
| 687 | case "newgame": { |
| 688 | // A game started, redirect if I'm playing in |
| 689 | const gameInfo = data.data; |
| 690 | const gameType = this.getGameType(gameInfo); |
| 691 | if ( |
| 692 | gameType == "live" && |
| 693 | gameInfo.players.some(p => p.sid == this.st.user.sid) |
| 694 | ) { |
| 695 | this.addAndGotoLiveGame(gameInfo); |
| 696 | } else if ( |
| 697 | gameType == "corr" && |
| 698 | gameInfo.players.some(p => p.id == this.st.user.id) |
| 699 | ) { |
| 700 | this.$router.push("/game/" + gameInfo.id); |
| 701 | } else { |
| 702 | this.rematchId = gameInfo.id; |
| 703 | document.getElementById("modalInfo").checked = true; |
| 704 | } |
| 705 | break; |
| 706 | } |
| 707 | case "newchat": |
| 708 | this.$refs["chatcomp"].newChat(data.data); |
| 709 | if (!document.getElementById("modalChat").checked) |
| 710 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 711 | break; |
| 712 | } |
| 713 | }, |
| 714 | socketCloseListener: function() { |
| 715 | this.conn = new WebSocket(this.connexionString); |
| 716 | this.conn.addEventListener("message", this.socketMessageListener); |
| 717 | this.conn.addEventListener("close", this.socketCloseListener); |
| 718 | }, |
| 719 | updateCorrGame: function(obj, callback) { |
| 720 | ajax( |
| 721 | "/games", |
| 722 | "PUT", |
| 723 | { |
| 724 | data: { |
| 725 | gid: this.gameRef, |
| 726 | newObj: obj |
| 727 | }, |
| 728 | success: () => { |
| 729 | if (!!callback) callback(); |
| 730 | } |
| 731 | } |
| 732 | ); |
| 733 | }, |
| 734 | sendLastate: function(target) { |
| 735 | // Send our "last state" informations to opponent |
| 736 | const L = this.game.moves.length; |
| 737 | const myIdx = ["w", "b"].indexOf(this.game.mycolor); |
| 738 | const myLastate = { |
| 739 | lastMove: |
| 740 | (L > 0 && this.vr.turn != this.game.mycolor) |
| 741 | ? this.game.moves[L - 1] |
| 742 | : undefined, |
| 743 | clock: this.game.clocks[myIdx], |
| 744 | // Since we played a move (or abort or resign), |
| 745 | // only drawOffer=="sent" is possible |
| 746 | drawSent: this.drawOffer == "sent", |
| 747 | rematchSent: this.rematchOffer == "sent", |
| 748 | score: this.game.score != "*" ? this.game.score : undefined, |
| 749 | scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined, |
| 750 | movesCount: L |
| 751 | }; |
| 752 | this.send("lastate", { data: myLastate, target: target }); |
| 753 | }, |
| 754 | // lastate was received, but maybe game wasn't ready yet: |
| 755 | processLastate: function() { |
| 756 | const data = this.lastate; |
| 757 | this.lastate = undefined; //security... |
| 758 | const L = this.game.moves.length; |
| 759 | const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor); |
| 760 | this.game.clocks[oppIdx] = data.clock; |
| 761 | if (data.movesCount > L) { |
| 762 | // Just got last move from him |
| 763 | this.$refs["basegame"].play(data.lastMove, "received", null, true); |
| 764 | this.processMove(data.lastMove); |
| 765 | } else { |
| 766 | clearInterval(this.clockUpdate); |
| 767 | this.re_setClocks(); |
| 768 | } |
| 769 | if (data.drawSent) this.drawOffer = "received"; |
| 770 | if (data.rematchSent) this.rematchOffer = "received"; |
| 771 | if (!!data.score) { |
| 772 | this.drawOffer = ""; |
| 773 | if (this.game.score == "*") |
| 774 | this.gameOver(data.score, data.scoreMsg); |
| 775 | } |
| 776 | }, |
| 777 | clickDraw: function() { |
| 778 | if (!this.game.mycolor) return; //I'm just spectator |
| 779 | if (["received", "threerep"].includes(this.drawOffer)) { |
| 780 | if (!confirm(this.st.tr["Accept draw?"])) return; |
| 781 | const message = |
| 782 | this.drawOffer == "received" |
| 783 | ? "Mutual agreement" |
| 784 | : "Three repetitions"; |
| 785 | this.send("draw", { data: message }); |
| 786 | this.gameOver("1/2", message); |
| 787 | } else if (this.drawOffer == "") { |
| 788 | // No effect if drawOffer == "sent" |
| 789 | if (this.game.mycolor != this.vr.turn) { |
| 790 | alert(this.st.tr["Draw offer only in your turn"]); |
| 791 | return; |
| 792 | } |
| 793 | if (!confirm(this.st.tr["Offer draw?"])) return; |
| 794 | this.drawOffer = "sent"; |
| 795 | this.send("drawoffer"); |
| 796 | if (this.game.type == "live") { |
| 797 | GameStorage.update( |
| 798 | this.gameRef, |
| 799 | { drawOffer: this.game.mycolor } |
| 800 | ); |
| 801 | } else this.updateCorrGame({ drawOffer: this.game.mycolor }); |
| 802 | } |
| 803 | }, |
| 804 | addAndGotoLiveGame: function(gameInfo, callback) { |
| 805 | const game = Object.assign( |
| 806 | {}, |
| 807 | gameInfo, |
| 808 | { |
| 809 | // (other) Game infos: constant |
| 810 | fenStart: gameInfo.fen, |
| 811 | vname: this.game.vname, |
| 812 | created: Date.now(), |
| 813 | // Game state (including FEN): will be updated |
| 814 | moves: [], |
| 815 | clocks: [-1, -1], //-1 = unstarted |
| 816 | score: "*" |
| 817 | } |
| 818 | ); |
| 819 | GameStorage.add(game, (err) => { |
| 820 | // No error expected. |
| 821 | if (!err) { |
| 822 | if (this.st.settings.sound) |
| 823 | new Audio("/sounds/newgame.flac").play().catch(() => {}); |
| 824 | if (!!callback) callback(); |
| 825 | this.$router.push("/game/" + gameInfo.id); |
| 826 | } |
| 827 | }); |
| 828 | }, |
| 829 | clickRematch: function() { |
| 830 | if (!this.game.mycolor) return; //I'm just spectator |
| 831 | if (this.rematchOffer == "received") { |
| 832 | // Start a new game! |
| 833 | let gameInfo = { |
| 834 | id: getRandString(), //ignored if corr |
| 835 | fen: V.GenRandInitFen(this.game.randomness), |
| 836 | players: this.game.players.reverse(), |
| 837 | vid: this.game.vid, |
| 838 | cadence: this.game.cadence |
| 839 | }; |
| 840 | const notifyNewGame = () => { |
| 841 | const oppsid = this.getOppsid(); //may be null |
| 842 | this.send("rnewgame", { data: gameInfo, oppsid: oppsid }); |
| 843 | // To main Hall if corr game: |
| 844 | if (this.game.type == "corr") |
| 845 | this.send("newgame", { data: gameInfo }); |
| 846 | // Also to MyGames page: |
| 847 | this.notifyMyGames("newgame", gameInfo); |
| 848 | }; |
| 849 | if (this.game.type == "live") |
| 850 | this.addAndGotoLiveGame(gameInfo, notifyNewGame); |
| 851 | else { |
| 852 | // corr game |
| 853 | ajax( |
| 854 | "/games", |
| 855 | "POST", |
| 856 | { |
| 857 | // cid is useful to delete the challenge: |
| 858 | data: { gameInfo: gameInfo }, |
| 859 | success: (response) => { |
| 860 | gameInfo.id = response.gameId; |
| 861 | notifyNewGame(); |
| 862 | this.$router.push("/game/" + response.gameId); |
| 863 | } |
| 864 | } |
| 865 | ); |
| 866 | } |
| 867 | } else if (this.rematchOffer == "") { |
| 868 | this.rematchOffer = "sent"; |
| 869 | this.send("rematchoffer", { data: true }); |
| 870 | if (this.game.type == "live") { |
| 871 | GameStorage.update( |
| 872 | this.gameRef, |
| 873 | { rematchOffer: this.game.mycolor } |
| 874 | ); |
| 875 | } else this.updateCorrGame({ rematchOffer: this.game.mycolor }); |
| 876 | } else if (this.rematchOffer == "sent") { |
| 877 | // Toggle rematch offer (on --> off) |
| 878 | this.rematchOffer = ""; |
| 879 | this.send("rematchoffer", { data: false }); |
| 880 | if (this.game.type == "live") { |
| 881 | GameStorage.update( |
| 882 | this.gameRef, |
| 883 | { rematchOffer: '' } |
| 884 | ); |
| 885 | } else this.updateCorrGame({ rematchOffer: 'n' }); |
| 886 | } |
| 887 | }, |
| 888 | abortGame: function() { |
| 889 | if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return; |
| 890 | this.gameOver("?", "Stop"); |
| 891 | this.send("abort"); |
| 892 | }, |
| 893 | resign: function() { |
| 894 | if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"])) |
| 895 | return; |
| 896 | this.send("resign", { data: this.game.mycolor }); |
| 897 | const score = (this.game.mycolor == "w" ? "0-1" : "1-0"); |
| 898 | const side = (this.game.mycolor == "w" ? "White" : "Black"); |
| 899 | this.gameOver(score, side + " surrender"); |
| 900 | }, |
| 901 | loadGame: function(game, callback) { |
| 902 | this.vr = new V(game.fen); |
| 903 | const gtype = this.getGameType(game); |
| 904 | const tc = extractTime(game.cadence); |
| 905 | const myIdx = game.players.findIndex(p => { |
| 906 | return p.sid == this.st.user.sid || p.id == this.st.user.id; |
| 907 | }); |
| 908 | const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers |
| 909 | if (!game.chats) game.chats = []; //live games don't have chat history |
| 910 | if (gtype == "corr") { |
| 911 | // NOTE: clocks in seconds |
| 912 | game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of |
| 913 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 914 | const L = game.moves.length; |
| 915 | if (game.score == "*") { |
| 916 | // Adjust clocks |
| 917 | if (L >= 2) { |
| 918 | game.clocks[L % 2] -= |
| 919 | (Date.now() - game.moves[L-1].played) / 1000; |
| 920 | } |
| 921 | } |
| 922 | // Sort chat messages from newest to oldest |
| 923 | game.chats.sort((c1, c2) => { |
| 924 | return c2.added - c1.added; |
| 925 | }); |
| 926 | if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) { |
| 927 | // Did a chat message arrive after my last move? |
| 928 | let dtLastMove = 0; |
| 929 | if (L == 1 && myIdx == 0) |
| 930 | dtLastMove = game.moves[0].played; |
| 931 | else if (L >= 2) { |
| 932 | if (L % 2 == 0) { |
| 933 | // It's now white turn |
| 934 | dtLastMove = game.moves[L-1-(1-myIdx)].played; |
| 935 | } else { |
| 936 | // Black turn: |
| 937 | dtLastMove = game.moves[L-1-myIdx].played; |
| 938 | } |
| 939 | } |
| 940 | if (dtLastMove < game.chats[0].added) |
| 941 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 942 | } |
| 943 | // Now that we used idx and played, re-format moves as for live games |
| 944 | game.moves = game.moves.map(m => m.squares); |
| 945 | } |
| 946 | if (gtype == "live") { |
| 947 | if (game.clocks[0] < 0) { |
| 948 | // Game is unstarted. clock is ignored until move 2 |
| 949 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 950 | if (myIdx >= 0) { |
| 951 | // I play in this live game |
| 952 | GameStorage.update(game.id, { |
| 953 | clocks: game.clocks |
| 954 | }); |
| 955 | } |
| 956 | } else { |
| 957 | if (!!game.initime) |
| 958 | // It's my turn: clocks not updated yet |
| 959 | game.clocks[myIdx] -= (Date.now() - game.initime) / 1000; |
| 960 | } |
| 961 | } |
| 962 | // TODO: merge next 2 "if" conditions |
| 963 | if (!!game.drawOffer) { |
| 964 | if (game.drawOffer == "t") |
| 965 | // Three repetitions |
| 966 | this.drawOffer = "threerep"; |
| 967 | else { |
| 968 | // Draw offered by any of the players: |
| 969 | if (myIdx < 0) this.drawOffer = "received"; |
| 970 | else { |
| 971 | // I play in this game: |
| 972 | if ( |
| 973 | (game.drawOffer == "w" && myIdx == 0) || |
| 974 | (game.drawOffer == "b" && myIdx == 1) |
| 975 | ) |
| 976 | this.drawOffer = "sent"; |
| 977 | else this.drawOffer = "received"; |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | if (!!game.rematchOffer) { |
| 982 | if (myIdx < 0) this.rematchOffer = "received"; |
| 983 | else { |
| 984 | // I play in this game: |
| 985 | if ( |
| 986 | (game.rematchOffer == "w" && myIdx == 0) || |
| 987 | (game.rematchOffer == "b" && myIdx == 1) |
| 988 | ) |
| 989 | this.rematchOffer = "sent"; |
| 990 | else this.rematchOffer = "received"; |
| 991 | } |
| 992 | } |
| 993 | this.repeat = {}; //reset: scan past moves' FEN: |
| 994 | let repIdx = 0; |
| 995 | let vr_tmp = new V(game.fenStart); |
| 996 | let curTurn = "n"; |
| 997 | game.moves.forEach(m => { |
| 998 | playMove(m, vr_tmp); |
| 999 | const fenIdx = vr_tmp.getFen().replace(/ /g, "_"); |
| 1000 | this.repeat[fenIdx] = this.repeat[fenIdx] |
| 1001 | ? this.repeat[fenIdx] + 1 |
| 1002 | : 1; |
| 1003 | }); |
| 1004 | if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep"; |
| 1005 | this.game = Object.assign( |
| 1006 | // NOTE: assign mycolor here, since BaseGame could also be VS computer |
| 1007 | { |
| 1008 | type: gtype, |
| 1009 | increment: tc.increment, |
| 1010 | mycolor: mycolor, |
| 1011 | // opponent sid not strictly required (or available), but easier |
| 1012 | // at least oppsid or oppid is available anyway: |
| 1013 | oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid, |
| 1014 | oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id |
| 1015 | }, |
| 1016 | game |
| 1017 | ); |
| 1018 | this.$refs["basegame"].re_setVariables(this.game); |
| 1019 | if (!this.gameIsLoading) { |
| 1020 | // Initial loading: |
| 1021 | this.gotMoveIdx = game.moves.length - 1; |
| 1022 | // If we arrive here after 'nextGame' action, the board might be hidden |
| 1023 | let boardDiv = document.querySelector(".game"); |
| 1024 | if (!!boardDiv && boardDiv.style.visibility == "hidden") |
| 1025 | boardDiv.style.visibility = "visible"; |
| 1026 | } |
| 1027 | this.re_setClocks(); |
| 1028 | this.$nextTick(() => { |
| 1029 | this.game.rendered = true; |
| 1030 | // Did lastate arrive before game was rendered? |
| 1031 | if (this.lastate) this.processLastate(); |
| 1032 | }); |
| 1033 | if (this.lastateAsked) { |
| 1034 | this.lastateAsked = false; |
| 1035 | this.sendLastate(game.oppsid); |
| 1036 | } |
| 1037 | if (this.gameIsLoading) { |
| 1038 | this.gameIsLoading = false; |
| 1039 | if (this.gotMoveIdx >= game.moves.length) |
| 1040 | // Some moves arrived meanwhile... |
| 1041 | this.askGameAgain(); |
| 1042 | } |
| 1043 | if (!!callback) callback(); |
| 1044 | }, |
| 1045 | loadVariantThenGame: async function(game, callback) { |
| 1046 | await import("@/variants/" + game.vname + ".js") |
| 1047 | .then((vModule) => { |
| 1048 | window.V = vModule[game.vname + "Rules"]; |
| 1049 | this.loadGame(game, callback); |
| 1050 | }); |
| 1051 | }, |
| 1052 | // 3 cases for loading a game: |
| 1053 | // - from indexedDB (running or completed live game I play) |
| 1054 | // - from server (one correspondance game I play[ed] or not) |
| 1055 | // - from remote peer (one live game I don't play, finished or not) |
| 1056 | fetchGame: function(callback) { |
| 1057 | if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) { |
| 1058 | // corr games identifiers are integers |
| 1059 | ajax( |
| 1060 | "/games", |
| 1061 | "GET", |
| 1062 | { |
| 1063 | data: { gid: this.gameRef }, |
| 1064 | success: (res) => { |
| 1065 | res.game.moves.forEach(m => { |
| 1066 | m.squares = JSON.parse(m.squares); |
| 1067 | }); |
| 1068 | callback(res.game); |
| 1069 | } |
| 1070 | } |
| 1071 | ); |
| 1072 | } else |
| 1073 | // Local game (or live remote) |
| 1074 | GameStorage.get(this.gameRef, callback); |
| 1075 | }, |
| 1076 | re_setClocks: function() { |
| 1077 | this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':')); |
| 1078 | if (this.game.moves.length < 2 || this.game.score != "*") { |
| 1079 | // 1st move not completed yet, or game over: freeze time |
| 1080 | return; |
| 1081 | } |
| 1082 | const currentTurn = this.vr.turn; |
| 1083 | const currentMovesCount = this.game.moves.length; |
| 1084 | const colorIdx = ["w", "b"].indexOf(currentTurn); |
| 1085 | this.clockUpdate = setInterval( |
| 1086 | () => { |
| 1087 | if ( |
| 1088 | this.game.clocks[colorIdx] < 0 || |
| 1089 | this.game.moves.length > currentMovesCount || |
| 1090 | this.game.score != "*" |
| 1091 | ) { |
| 1092 | clearInterval(this.clockUpdate); |
| 1093 | if (this.game.clocks[colorIdx] < 0) |
| 1094 | this.gameOver( |
| 1095 | currentTurn == "w" ? "0-1" : "1-0", |
| 1096 | "Time" |
| 1097 | ); |
| 1098 | } else { |
| 1099 | this.$set( |
| 1100 | this.virtualClocks, |
| 1101 | colorIdx, |
| 1102 | ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':') |
| 1103 | ); |
| 1104 | } |
| 1105 | }, |
| 1106 | 1000 |
| 1107 | ); |
| 1108 | }, |
| 1109 | // Update variables and storage after a move: |
| 1110 | processMove: function(move, data) { |
| 1111 | if (!data) data = {}; |
| 1112 | const moveCol = this.vr.turn; |
| 1113 | const colorIdx = ["w", "b"].indexOf(moveCol); |
| 1114 | const nextIdx = 1 - colorIdx; |
| 1115 | const doProcessMove = () => { |
| 1116 | const origMovescount = this.game.moves.length; |
| 1117 | // The move is (about to be) played: stop clock |
| 1118 | clearInterval(this.clockUpdate); |
| 1119 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
| 1120 | if (this.drawOffer == "received") |
| 1121 | // I refuse draw |
| 1122 | this.drawOffer = ""; |
| 1123 | if (this.game.type == "live" && origMovescount >= 2) { |
| 1124 | this.game.clocks[colorIdx] += this.game.increment; |
| 1125 | // For a correct display in casqe of disconnected opponent: |
| 1126 | this.$set( |
| 1127 | this.virtualClocks, |
| 1128 | colorIdx, |
| 1129 | ppt(this.game.clocks[colorIdx]).split(':') |
| 1130 | ); |
| 1131 | GameStorage.update(this.gameRef, { |
| 1132 | // It's not my turn anymore: |
| 1133 | initime: null |
| 1134 | }); |
| 1135 | } |
| 1136 | } |
| 1137 | // Update current game object: |
| 1138 | playMove(move, this.vr); |
| 1139 | if (!data.score) |
| 1140 | // Received move, score is computed in BaseGame, but maybe not yet. |
| 1141 | // ==> Compute it here, although this is redundant (TODO) |
| 1142 | data.score = this.vr.getCurrentScore(); |
| 1143 | if (data.score != "*") this.gameOver(data.score); |
| 1144 | this.game.moves.push(move); |
| 1145 | this.game.fen = this.vr.getFen(); |
| 1146 | if (this.game.type == "corr") { |
| 1147 | // In corr games, just reset clock to mainTime: |
| 1148 | this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime; |
| 1149 | } |
| 1150 | // If repetition detected, consider that a draw offer was received: |
| 1151 | const fenObj = this.vr.getFenForRepeat(); |
| 1152 | this.repeat[fenObj] = |
| 1153 | !!this.repeat[fenObj] |
| 1154 | ? this.repeat[fenObj] + 1 |
| 1155 | : 1; |
| 1156 | if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep"; |
| 1157 | else if (this.drawOffer == "threerep") this.drawOffer = ""; |
| 1158 | if (!!this.game.mycolor && !data.receiveMyMove) { |
| 1159 | // NOTE: 'var' to see that variable outside this block |
| 1160 | var filtered_move = getFilteredMove(move); |
| 1161 | } |
| 1162 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
| 1163 | // Notify turn on MyGames page: |
| 1164 | this.notifyMyGames( |
| 1165 | "turn", |
| 1166 | { |
| 1167 | gid: this.gameRef, |
| 1168 | turn: this.vr.turn |
| 1169 | } |
| 1170 | ); |
| 1171 | } |
| 1172 | // Since corr games are stored at only one location, update should be |
| 1173 | // done only by one player for each move: |
| 1174 | if ( |
| 1175 | this.game.type == "live" && |
| 1176 | !!this.game.mycolor && |
| 1177 | moveCol != this.game.mycolor && |
| 1178 | this.game.moves.length >= 2 |
| 1179 | ) { |
| 1180 | // Receive a move: update initime |
| 1181 | this.game.initime = Date.now(); |
| 1182 | GameStorage.update(this.gameRef, { |
| 1183 | // It's my turn now! |
| 1184 | initime: this.game.initime |
| 1185 | }); |
| 1186 | } |
| 1187 | if ( |
| 1188 | !!this.game.mycolor && |
| 1189 | !data.receiveMyMove && |
| 1190 | (this.game.type == "live" || moveCol == this.game.mycolor) |
| 1191 | ) { |
| 1192 | let drawCode = ""; |
| 1193 | switch (this.drawOffer) { |
| 1194 | case "threerep": |
| 1195 | drawCode = "t"; |
| 1196 | break; |
| 1197 | case "sent": |
| 1198 | drawCode = this.game.mycolor; |
| 1199 | break; |
| 1200 | case "received": |
| 1201 | drawCode = V.GetOppCol(this.game.mycolor); |
| 1202 | break; |
| 1203 | } |
| 1204 | if (this.game.type == "corr") { |
| 1205 | // corr: only move, fen and score |
| 1206 | this.updateCorrGame({ |
| 1207 | fen: this.game.fen, |
| 1208 | move: { |
| 1209 | squares: filtered_move, |
| 1210 | idx: origMovescount |
| 1211 | }, |
| 1212 | // Code "n" for "None" to force reset (otherwise it's ignored) |
| 1213 | drawOffer: drawCode || "n" |
| 1214 | }); |
| 1215 | } |
| 1216 | else { |
| 1217 | const updateStorage = () => { |
| 1218 | GameStorage.update(this.gameRef, { |
| 1219 | fen: this.game.fen, |
| 1220 | move: filtered_move, |
| 1221 | moveIdx: origMovescount, |
| 1222 | clocks: this.game.clocks, |
| 1223 | drawOffer: drawCode |
| 1224 | }); |
| 1225 | }; |
| 1226 | // The active tab can update storage immediately |
| 1227 | if (!document.hidden) updateStorage(); |
| 1228 | // Small random delay otherwise |
| 1229 | else setTimeout(updateStorage, 500 + 1000 * Math.random()); |
| 1230 | } |
| 1231 | } |
| 1232 | // Send move ("newmove" event) to people in the room (if our turn) |
| 1233 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
| 1234 | let sendMove = { |
| 1235 | move: filtered_move, |
| 1236 | index: origMovescount, |
| 1237 | // color is required to check if this is my move (if several tabs opened) |
| 1238 | color: moveCol, |
| 1239 | cancelDrawOffer: this.drawOffer == "" |
| 1240 | }; |
| 1241 | if (this.game.type == "live") |
| 1242 | sendMove["clock"] = this.game.clocks[colorIdx]; |
| 1243 | // (Live) Clocks will re-start when the opponent pingback arrive |
| 1244 | this.opponentGotMove = false; |
| 1245 | this.send("newmove", {data: sendMove}); |
| 1246 | // If the opponent doesn't reply gotmove soon enough, re-send move: |
| 1247 | // Do this at most 2 times, because mpore would mean network issues, |
| 1248 | // opponent would then be expected to disconnect/reconnect. |
| 1249 | let counter = 1; |
| 1250 | const currentUrl = document.location.href; |
| 1251 | this.retrySendmove = setInterval( |
| 1252 | () => { |
| 1253 | if ( |
| 1254 | counter >= 3 || |
| 1255 | this.opponentGotMove || |
| 1256 | document.location.href != currentUrl //page change |
| 1257 | ) { |
| 1258 | clearInterval(this.retrySendmove); |
| 1259 | return; |
| 1260 | } |
| 1261 | const oppsid = this.getOppsid(); |
| 1262 | if (!oppsid) |
| 1263 | // Opponent is disconnected: he'll ask last state |
| 1264 | clearInterval(this.retrySendmove); |
| 1265 | else { |
| 1266 | this.send("newmove", { data: sendMove, target: oppsid }); |
| 1267 | counter++; |
| 1268 | } |
| 1269 | }, |
| 1270 | 1500 |
| 1271 | ); |
| 1272 | } |
| 1273 | else |
| 1274 | // Not my move or I'm an observer: just start other player's clock |
| 1275 | this.re_setClocks(); |
| 1276 | }; |
| 1277 | if ( |
| 1278 | this.game.type == "corr" && |
| 1279 | moveCol == this.game.mycolor && |
| 1280 | !data.receiveMyMove |
| 1281 | ) { |
| 1282 | let boardDiv = document.querySelector(".game"); |
| 1283 | const afterSetScore = () => { |
| 1284 | doProcessMove(); |
| 1285 | if (this.st.settings.gotonext && this.nextIds.length > 0) |
| 1286 | this.showNextGame(); |
| 1287 | else { |
| 1288 | // The board might have been hidden: |
| 1289 | if (boardDiv.style.visibility == "hidden") |
| 1290 | boardDiv.style.visibility = "visible"; |
| 1291 | if (data.score == "*") this.re_setClocks(); |
| 1292 | } |
| 1293 | }; |
| 1294 | let el = document.querySelector("#buttonsConfirm > .acceptBtn"); |
| 1295 | // We may play several moves in a row: in case of, remove listener: |
| 1296 | let elClone = el.cloneNode(true); |
| 1297 | el.parentNode.replaceChild(elClone, el); |
| 1298 | elClone.addEventListener( |
| 1299 | "click", |
| 1300 | () => { |
| 1301 | document.getElementById("modalConfirm").checked = false; |
| 1302 | if (!!data.score && data.score != "*") |
| 1303 | // Set score first |
| 1304 | this.gameOver(data.score, null, afterSetScore); |
| 1305 | else afterSetScore(); |
| 1306 | } |
| 1307 | ); |
| 1308 | // PlayOnBoard is enough, and more appropriate for Synchrone Chess |
| 1309 | V.PlayOnBoard(this.vr.board, move); |
| 1310 | const position = this.vr.getBaseFen(); |
| 1311 | V.UndoOnBoard(this.vr.board, move); |
| 1312 | if (["all","byrow"].includes(V.ShowMoves)) { |
| 1313 | this.curDiag = getDiagram({ |
| 1314 | position: position, |
| 1315 | orientation: V.CanFlip ? this.game.mycolor : "w" |
| 1316 | }); |
| 1317 | document.querySelector("#confirmDiv > .card").style.width = |
| 1318 | boardDiv.offsetWidth + "px"; |
| 1319 | } else { |
| 1320 | // Incomplete information: just ask confirmation |
| 1321 | // Hide the board, because otherwise it could reveal infos |
| 1322 | boardDiv.style.visibility = "hidden"; |
| 1323 | this.moveNotation = getFullNotation(move); |
| 1324 | } |
| 1325 | document.getElementById("modalConfirm").checked = true; |
| 1326 | } |
| 1327 | else { |
| 1328 | // Normal situation |
| 1329 | if (!!data.score && data.score != "*") |
| 1330 | this.gameOver(data.score, null, doProcessMove); |
| 1331 | else doProcessMove(); |
| 1332 | } |
| 1333 | }, |
| 1334 | cancelMove: function() { |
| 1335 | let boardDiv = document.querySelector(".game"); |
| 1336 | if (boardDiv.style.visibility == "hidden") |
| 1337 | boardDiv.style.visibility = "visible"; |
| 1338 | document.getElementById("modalConfirm").checked = false; |
| 1339 | this.$refs["basegame"].cancelLastMove(); |
| 1340 | }, |
| 1341 | // In corr games, callback to change page only after score is set: |
| 1342 | gameOver: function(score, scoreMsg, callback) { |
| 1343 | this.game.score = score; |
| 1344 | if (!scoreMsg) scoreMsg = getScoreMessage(score); |
| 1345 | this.game.scoreMsg = scoreMsg; |
| 1346 | this.$set(this.game, "scoreMsg", scoreMsg); |
| 1347 | const myIdx = this.game.players.findIndex(p => { |
| 1348 | return p.sid == this.st.user.sid || p.id == this.st.user.id; |
| 1349 | }); |
| 1350 | if (myIdx >= 0) { |
| 1351 | // OK, I play in this game |
| 1352 | const scoreObj = { |
| 1353 | score: score, |
| 1354 | scoreMsg: scoreMsg |
| 1355 | }; |
| 1356 | if (this.game.type == "live") { |
| 1357 | GameStorage.update(this.gameRef, scoreObj); |
| 1358 | if (!!callback) callback(); |
| 1359 | } |
| 1360 | else this.updateCorrGame(scoreObj, callback); |
| 1361 | // Notify the score to main Hall. TODO: only one player (currently double send) |
| 1362 | this.send("result", { gid: this.game.id, score: score }); |
| 1363 | // Also to MyGames page (TODO: doubled as well...) |
| 1364 | this.notifyMyGames( |
| 1365 | "score", |
| 1366 | { |
| 1367 | gid: this.gameRef, |
| 1368 | score: score |
| 1369 | } |
| 1370 | ); |
| 1371 | } |
| 1372 | else if (!!callback) callback(); |
| 1373 | } |
| 1374 | } |
| 1375 | }; |
| 1376 | </script> |
| 1377 | |
| 1378 | <style lang="sass" scoped> |
| 1379 | #infoDiv > .card |
| 1380 | padding: 15px 0 |
| 1381 | max-width: 430px |
| 1382 | |
| 1383 | .connected |
| 1384 | background-color: lightgreen |
| 1385 | |
| 1386 | #participants |
| 1387 | margin-left: 5px |
| 1388 | |
| 1389 | .anonymous |
| 1390 | color: grey |
| 1391 | font-style: italic |
| 1392 | |
| 1393 | #playersInfo > p |
| 1394 | margin: 0 |
| 1395 | |
| 1396 | @media screen and (min-width: 768px) |
| 1397 | #actions |
| 1398 | width: 300px |
| 1399 | @media screen and (max-width: 767px) |
| 1400 | .game |
| 1401 | width: 100% |
| 1402 | |
| 1403 | #actions |
| 1404 | display: inline-block |
| 1405 | margin: 0 |
| 1406 | |
| 1407 | button |
| 1408 | display: inline-block |
| 1409 | margin: 0 |
| 1410 | display: inline-flex |
| 1411 | img |
| 1412 | height: 22px |
| 1413 | display: flex |
| 1414 | @media screen and (max-width: 767px) |
| 1415 | height: 18px |
| 1416 | |
| 1417 | @media screen and (max-width: 767px) |
| 1418 | #aboveBoard |
| 1419 | text-align: center |
| 1420 | @media screen and (min-width: 768px) |
| 1421 | #aboveBoard |
| 1422 | margin-left: 30% |
| 1423 | |
| 1424 | .variant-cadence |
| 1425 | padding-right: 10px |
| 1426 | |
| 1427 | .variant-name |
| 1428 | font-weight: bold |
| 1429 | padding-right: 10px |
| 1430 | |
| 1431 | span#nextGame |
| 1432 | background-color: #edda99 |
| 1433 | cursor: pointer |
| 1434 | display: inline-block |
| 1435 | margin-right: 10px |
| 1436 | |
| 1437 | span.name |
| 1438 | font-size: 1.5rem |
| 1439 | padding: 0 3px |
| 1440 | |
| 1441 | span.time |
| 1442 | font-size: 2rem |
| 1443 | display: inline-block |
| 1444 | .time-left |
| 1445 | margin-left: 10px |
| 1446 | .time-right |
| 1447 | margin-left: 5px |
| 1448 | .time-separator |
| 1449 | margin-left: 5px |
| 1450 | position: relative |
| 1451 | top: -1px |
| 1452 | |
| 1453 | span.yourturn |
| 1454 | color: #831B1B |
| 1455 | .time-separator |
| 1456 | animation: blink-animation 2s steps(3, start) infinite |
| 1457 | @keyframes blink-animation |
| 1458 | to |
| 1459 | visibility: hidden |
| 1460 | |
| 1461 | .split-names |
| 1462 | display: inline-block |
| 1463 | margin: 0 15px |
| 1464 | |
| 1465 | #chatWrap > .card |
| 1466 | padding-top: 20px |
| 1467 | max-width: 767px |
| 1468 | border: none |
| 1469 | |
| 1470 | #confirmDiv > .card |
| 1471 | max-width: 767px |
| 1472 | max-height: 100% |
| 1473 | |
| 1474 | .draw-sent, .draw-sent:hover |
| 1475 | background-color: lightyellow |
| 1476 | |
| 1477 | .draw-received, .draw-received:hover |
| 1478 | background-color: lightgreen |
| 1479 | |
| 1480 | .draw-threerep, .draw-threerep:hover |
| 1481 | background-color: #e4d1fc |
| 1482 | |
| 1483 | .rematch-sent, .rematch-sent:hover |
| 1484 | background-color: lightyellow |
| 1485 | |
| 1486 | .rematch-received, .rematch-received:hover |
| 1487 | background-color: lightgreen |
| 1488 | |
| 1489 | .somethingnew |
| 1490 | background-color: #c5fefe |
| 1491 | |
| 1492 | .diagram |
| 1493 | margin: 0 auto |
| 1494 | width: 100% |
| 1495 | |
| 1496 | #buttonsConfirm |
| 1497 | margin: 0 |
| 1498 | & > button > span |
| 1499 | width: 100% |
| 1500 | text-align: center |
| 1501 | |
| 1502 | button.acceptBtn |
| 1503 | background-color: lightgreen |
| 1504 | button.refuseBtn |
| 1505 | background-color: red |
| 1506 | </style> |