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