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