| 1 | <template lang="pug"> |
| 2 | main |
| 3 | input#modalChat.modal(type="checkbox" @click="resetChatColor()") |
| 4 | div#chatWrap(role="dialog" data-checkbox="modalChat") |
| 5 | #chat.card |
| 6 | label.modal-close(for="modalChat") |
| 7 | #participants |
| 8 | span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }} |
| 9 | span(v-for="p in Object.values(people)" v-if="!!p.name") |
| 10 | | {{ p.name }} |
| 11 | span.anonymous(v-if="Object.values(people).some(p => !p.name)") |
| 12 | | + @nonymous |
| 13 | Chat(:players="game.players" :pastChats="game.chats" |
| 14 | :newChat="newChat" @mychat="processChat") |
| 15 | .row |
| 16 | #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2 |
| 17 | span.variant-cadence {{ game.cadence }} |
| 18 | span.variant-name {{ game.vname }} |
| 19 | button#chatBtn(onClick="doClick('modalChat')") Chat |
| 20 | #actions(v-if="game.score=='*'") |
| 21 | button(@click="clickDraw()" :class="{['draw-' + drawOffer]: true}") |
| 22 | | {{ st.tr["Draw"] }} |
| 23 | button(v-if="!!game.mycolor" @click="abortGame()") {{ st.tr["Abort"] }} |
| 24 | button(v-if="!!game.mycolor" @click="resign()") {{ st.tr["Resign"] }} |
| 25 | #playersInfo |
| 26 | p |
| 27 | span.name(:class="{connected: isConnected(0)}") |
| 28 | | {{ game.players[0].name || "@nonymous" }} |
| 29 | span.time(v-if="game.score=='*'") {{ virtualClocks[0] }} |
| 30 | span.split-names - |
| 31 | span.name(:class="{connected: isConnected(1)}") |
| 32 | | {{ game.players[1].name || "@nonymous" }} |
| 33 | span.time(v-if="game.score=='*'") {{ virtualClocks[1] }} |
| 34 | BaseGame(:game="game" :vr="vr" @newmove="processMove" @gameover="gameOver") |
| 35 | </template> |
| 36 | |
| 37 | <script> |
| 38 | import BaseGame from "@/components/BaseGame.vue"; |
| 39 | import Chat from "@/components/Chat.vue"; |
| 40 | import { store } from "@/store"; |
| 41 | import { GameStorage } from "@/utils/gameStorage"; |
| 42 | import { ppt } from "@/utils/datetime"; |
| 43 | import { extractTime } from "@/utils/timeControl"; |
| 44 | import { getRandString } from "@/utils/alea"; |
| 45 | import { ArrayFun } from "@/utils/array"; |
| 46 | import { processModalClick } from "@/utils/modalClick"; |
| 47 | import { getScoreMessage } from "@/utils/scoring"; |
| 48 | import params from "@/parameters"; |
| 49 | export default { |
| 50 | name: 'my-game', |
| 51 | components: { |
| 52 | BaseGame, |
| 53 | Chat, |
| 54 | }, |
| 55 | // gameRef: to find the game in (potentially remote) storage |
| 56 | data: function() { |
| 57 | return { |
| 58 | st: store.state, |
| 59 | gameRef: { //given in URL (rid = remote ID) |
| 60 | id: "", |
| 61 | rid: "" |
| 62 | }, |
| 63 | game: { //passed to BaseGame |
| 64 | players:[{name:""},{name:""}], |
| 65 | chats: [], |
| 66 | rendered: false, |
| 67 | }, |
| 68 | virtualClocks: [0, 0], //initialized with true game.clocks |
| 69 | vr: null, //"variant rules" object initialized from FEN |
| 70 | drawOffer: "", |
| 71 | people: {}, //players + observers |
| 72 | lastate: undefined, //used if opponent send lastate before game is ready |
| 73 | repeat: {}, //detect position repetition |
| 74 | newChat: "", |
| 75 | conn: null, |
| 76 | connexionString: "", |
| 77 | // Related to (killing of) self multi-connects: |
| 78 | newConnect: {}, |
| 79 | killed: {}, |
| 80 | }; |
| 81 | }, |
| 82 | watch: { |
| 83 | "$route": function(to, from) { |
| 84 | this.gameRef.id = to.params["id"]; |
| 85 | this.gameRef.rid = to.query["rid"]; |
| 86 | this.loadGame(); |
| 87 | }, |
| 88 | }, |
| 89 | // NOTE: some redundant code with Hall.vue (mostly related to people array) |
| 90 | created: function() { |
| 91 | // Always add myself to players' list |
| 92 | const my = this.st.user; |
| 93 | this.$set(this.people, my.sid, {id:my.id, name:my.name}); |
| 94 | this.gameRef.id = this.$route.params["id"]; |
| 95 | this.gameRef.rid = this.$route.query["rid"]; //may be undefined |
| 96 | // Initialize connection |
| 97 | this.connexionString = params.socketUrl + |
| 98 | "/?sid=" + this.st.user.sid + |
| 99 | "&tmpId=" + getRandString() + |
| 100 | "&page=" + encodeURIComponent(this.$route.path); |
| 101 | this.conn = new WebSocket(this.connexionString); |
| 102 | this.conn.onmessage = this.socketMessageListener; |
| 103 | this.conn.onclose = this.socketCloseListener; |
| 104 | // Socket init required before loading remote game: |
| 105 | const socketInit = (callback) => { |
| 106 | if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state |
| 107 | callback(); |
| 108 | else //socket not ready yet (initial loading) |
| 109 | { |
| 110 | // NOTE: it's important to call callback without arguments, |
| 111 | // otherwise first arg is Websocket object and loadGame fails. |
| 112 | this.conn.onopen = () => { return callback() }; |
| 113 | } |
| 114 | }; |
| 115 | if (!this.gameRef.rid) //game stored locally or on server |
| 116 | this.loadGame(null, () => socketInit(this.roomInit)); |
| 117 | else //game stored remotely: need socket to retrieve it |
| 118 | { |
| 119 | // NOTE: the callback "roomInit" will be lost, so we don't provide it. |
| 120 | // --> It will be given when receiving "fullgame" socket event. |
| 121 | // A more general approach would be to store it somewhere. |
| 122 | socketInit(this.loadGame); |
| 123 | } |
| 124 | }, |
| 125 | mounted: function() { |
| 126 | document.getElementById("chatWrap").addEventListener( |
| 127 | "click", processModalClick); |
| 128 | }, |
| 129 | beforeDestroy: function() { |
| 130 | this.send("disconnect"); |
| 131 | }, |
| 132 | methods: { |
| 133 | roomInit: function() { |
| 134 | // Notify the room only now that I connected, because |
| 135 | // messages might be lost otherwise (if game loading is slow) |
| 136 | this.send("connect"); |
| 137 | this.send("pollclients"); |
| 138 | }, |
| 139 | send: function(code, obj) { |
| 140 | if (!!this.conn) |
| 141 | { |
| 142 | this.conn.send(JSON.stringify( |
| 143 | Object.assign( |
| 144 | {code: code}, |
| 145 | obj, |
| 146 | ) |
| 147 | )); |
| 148 | } |
| 149 | }, |
| 150 | isConnected: function(index) { |
| 151 | const player = this.game.players[index]; |
| 152 | // Is it me ? |
| 153 | if (this.st.user.sid == player.sid || this.st.user.id == player.uid) |
| 154 | return true; |
| 155 | // Try to find a match in people: |
| 156 | return Object.keys(this.people).some(sid => sid == player.sid) || |
| 157 | Object.values(this.people).some(p => p.id == player.uid); |
| 158 | }, |
| 159 | socketMessageListener: function(msg) { |
| 160 | if (!this.conn) |
| 161 | return; |
| 162 | const data = JSON.parse(msg.data); |
| 163 | switch (data.code) |
| 164 | { |
| 165 | case "pollclients": |
| 166 | data.sockIds.forEach(sid => { |
| 167 | this.$set(this.people, sid, {id:0, name:""}); |
| 168 | if (sid != this.st.user.sid) |
| 169 | { |
| 170 | this.send("askidentity", {target:sid}); |
| 171 | // Ask potentially missed last state, if opponent and I play |
| 172 | if (!!this.game.mycolor |
| 173 | && this.game.type == "live" && this.game.score == "*" |
| 174 | && this.game.players.some(p => p.sid == sid)) |
| 175 | { |
| 176 | this.send("asklastate", {target:sid}); |
| 177 | } |
| 178 | } |
| 179 | }); |
| 180 | break; |
| 181 | case "connect": |
| 182 | if (!this.people[data.from]) |
| 183 | this.$set(this.people, data.from, {name:"", id:0}); |
| 184 | if (!this.people[data.from].name) |
| 185 | { |
| 186 | this.newConnect[data.from] = true; //for self multi-connects tests |
| 187 | this.send("askidentity", {target:data.from}); |
| 188 | } |
| 189 | break; |
| 190 | case "disconnect": |
| 191 | this.$delete(this.people, data.from); |
| 192 | break; |
| 193 | case "killed": |
| 194 | // I logged in elsewhere: |
| 195 | alert(this.st.tr["New connexion detected: tab now offline"]); |
| 196 | // TODO: this fails. See https://github.com/websockets/ws/issues/489 |
| 197 | //this.conn.removeEventListener("message", this.socketMessageListener); |
| 198 | //this.conn.removeEventListener("close", this.socketCloseListener); |
| 199 | //this.conn.close(); |
| 200 | this.conn = null; |
| 201 | break; |
| 202 | case "askidentity": |
| 203 | { |
| 204 | // Request for identification (TODO: anonymous shouldn't need to reply) |
| 205 | const me = { |
| 206 | // Decompose to avoid revealing email |
| 207 | name: this.st.user.name, |
| 208 | sid: this.st.user.sid, |
| 209 | id: this.st.user.id, |
| 210 | }; |
| 211 | this.send("identity", {data:me, target:data.from}); |
| 212 | break; |
| 213 | } |
| 214 | case "identity": |
| 215 | { |
| 216 | const user = data.data; |
| 217 | if (!!user.name) //otherwise anonymous |
| 218 | { |
| 219 | // If I multi-connect, kill current connexion if no mark (I'm older) |
| 220 | if (this.newConnect[user.sid] && user.id > 0 |
| 221 | && user.id == this.st.user.id && user.sid != this.st.user.sid) |
| 222 | { |
| 223 | if (!this.killed[this.st.user.sid]) |
| 224 | { |
| 225 | this.send("killme", {sid:this.st.user.sid}); |
| 226 | this.killed[this.st.user.sid] = true; |
| 227 | } |
| 228 | } |
| 229 | if (user.sid != this.st.user.sid) //I already know my identity... |
| 230 | { |
| 231 | this.$set(this.people, user.sid, |
| 232 | { |
| 233 | id: user.id, |
| 234 | name: user.name, |
| 235 | }); |
| 236 | } |
| 237 | } |
| 238 | delete this.newConnect[user.sid]; |
| 239 | break; |
| 240 | } |
| 241 | case "askgame": |
| 242 | // Send current (live) game if not asked by any of the players |
| 243 | if (this.game.type == "live" |
| 244 | && this.game.players.every(p => p.sid != data.from[0])) |
| 245 | { |
| 246 | const myGame = { |
| 247 | id: this.game.id, |
| 248 | fen: this.game.fen, |
| 249 | players: this.game.players, |
| 250 | vid: this.game.vid, |
| 251 | cadence: this.game.cadence, |
| 252 | score: this.game.score, |
| 253 | rid: this.st.user.sid, //useful in Hall if I'm an observer |
| 254 | }; |
| 255 | this.send("game", {data:myGame, target:data.from}); |
| 256 | } |
| 257 | break; |
| 258 | case "askfullgame": |
| 259 | this.send("fullgame", {data:this.game, target:data.from}); |
| 260 | break; |
| 261 | case "fullgame": |
| 262 | // Callback "roomInit" to poll clients only after game is loaded |
| 263 | this.loadGame(data.data, this.roomInit); |
| 264 | break; |
| 265 | case "asklastate": |
| 266 | // Sending last state if I played a move or score != "*" |
| 267 | if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) |
| 268 | || this.game.score != "*" || this.drawOffer == "sent") |
| 269 | { |
| 270 | // Send our "last state" informations to opponent |
| 271 | const L = this.game.moves.length; |
| 272 | const myIdx = ["w","b"].indexOf(this.game.mycolor); |
| 273 | const myLastate = { |
| 274 | // NOTE: lastMove (when defined) includes addTime |
| 275 | lastMove: (L>0 ? this.game.moves[L-1] : undefined), |
| 276 | // Since we played a move (or abort or resign), |
| 277 | // only drawOffer=="sent" is possible |
| 278 | drawSent: this.drawOffer == "sent", |
| 279 | score: this.game.score, |
| 280 | movesCount: L, |
| 281 | initime: this.game.initime[1-myIdx], //relevant only if I played |
| 282 | }; |
| 283 | this.send("lastate", {data:myLastate, target:data.from}); |
| 284 | } |
| 285 | break; |
| 286 | case "lastate": //got opponent infos about last move |
| 287 | this.lastate = data.data; |
| 288 | if (this.game.rendered) //game is rendered (Board component) |
| 289 | this.processLastate(); |
| 290 | //else: will be processed when game is ready |
| 291 | break; |
| 292 | case "newmove": |
| 293 | { |
| 294 | const move = data.data; |
| 295 | if (!!move.cancelDrawOffer) //opponent refuses draw |
| 296 | { |
| 297 | this.drawOffer = ""; |
| 298 | // NOTE for corr games: drawOffer reset by player in turn |
| 299 | if (this.game.type == "live" && !!this.game.mycolor) |
| 300 | GameStorage.update(this.gameRef.id, {drawOffer: ""}); |
| 301 | } |
| 302 | this.$set(this.game, "moveToPlay", move); |
| 303 | break; |
| 304 | } |
| 305 | case "resign": |
| 306 | this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign"); |
| 307 | break; |
| 308 | case "abort": |
| 309 | this.gameOver("?", "Abort"); |
| 310 | break; |
| 311 | case "draw": |
| 312 | this.gameOver("1/2", data.data); |
| 313 | break; |
| 314 | case "drawoffer": |
| 315 | // NOTE: observers don't know who offered draw |
| 316 | this.drawOffer = "received"; |
| 317 | break; |
| 318 | case "newchat": |
| 319 | this.newChat = data.data; |
| 320 | if (!document.getElementById("modalChat").checked) |
| 321 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 322 | break; |
| 323 | } |
| 324 | }, |
| 325 | socketCloseListener: function() { |
| 326 | this.conn = new WebSocket(this.connexionString); |
| 327 | this.conn.addEventListener('message', this.socketMessageListener); |
| 328 | this.conn.addEventListener('close', this.socketCloseListener); |
| 329 | }, |
| 330 | // lastate was received, but maybe game wasn't ready yet: |
| 331 | processLastate: function() { |
| 332 | const data = this.lastate; |
| 333 | this.lastate = undefined; //security... |
| 334 | const L = this.game.moves.length; |
| 335 | if (data.movesCount > L) |
| 336 | { |
| 337 | // Just got last move from him |
| 338 | this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove)); |
| 339 | } |
| 340 | if (data.drawSent) |
| 341 | this.drawOffer = "received"; |
| 342 | if (data.score != "*") |
| 343 | { |
| 344 | this.drawOffer = ""; |
| 345 | if (this.game.score == "*") |
| 346 | this.gameOver(data.score); |
| 347 | } |
| 348 | }, |
| 349 | clickDraw: function() { |
| 350 | if (!this.game.mycolor) |
| 351 | return; //I'm just spectator |
| 352 | if (["received","threerep"].includes(this.drawOffer)) |
| 353 | { |
| 354 | if (!confirm(this.st.tr["Accept draw?"])) |
| 355 | return; |
| 356 | const message = (this.drawOffer == "received" |
| 357 | ? "Mutual agreement" |
| 358 | : "Three repetitions"); |
| 359 | this.send("draw", {data:message}); |
| 360 | this.gameOver("1/2", message); |
| 361 | } |
| 362 | else if (this.drawOffer == "") //no effect if drawOffer == "sent" |
| 363 | { |
| 364 | if (this.game.mycolor != this.vr.turn) |
| 365 | return alert(this.st.tr["Draw offer only in your turn"]); |
| 366 | if (!confirm(this.st.tr["Offer draw?"])) |
| 367 | return; |
| 368 | this.drawOffer = "sent"; |
| 369 | this.send("drawoffer"); |
| 370 | GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor}); |
| 371 | } |
| 372 | }, |
| 373 | abortGame: function() { |
| 374 | if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) |
| 375 | return; |
| 376 | this.gameOver("?", "Abort"); |
| 377 | this.send("abort"); |
| 378 | }, |
| 379 | resign: function(e) { |
| 380 | if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"])) |
| 381 | return; |
| 382 | this.send("resign", {data:this.game.mycolor}); |
| 383 | this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign"); |
| 384 | }, |
| 385 | // 3 cases for loading a game: |
| 386 | // - from indexedDB (running or completed live game I play) |
| 387 | // - from server (one correspondance game I play[ed] or not) |
| 388 | // - from remote peer (one live game I don't play, finished or not) |
| 389 | loadGame: function(game, callback) { |
| 390 | const afterRetrieval = async (game) => { |
| 391 | const vModule = await import("@/variants/" + game.vname + ".js"); |
| 392 | window.V = vModule.VariantRules; |
| 393 | this.vr = new V(game.fen); |
| 394 | const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live"); |
| 395 | const tc = extractTime(game.cadence); |
| 396 | const myIdx = game.players.findIndex(p => { |
| 397 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 398 | }); |
| 399 | const mycolor = [undefined,"w","b"][myIdx+1]; //undefined for observers |
| 400 | if (!game.chats) |
| 401 | game.chats = []; //live games don't have chat history |
| 402 | if (gtype == "corr") |
| 403 | { |
| 404 | if (game.players[0].color == "b") |
| 405 | { |
| 406 | // Adopt the same convention for live and corr games: [0] = white |
| 407 | [ game.players[0], game.players[1] ] = |
| 408 | [ game.players[1], game.players[0] ]; |
| 409 | } |
| 410 | // corr game: needs to compute the clocks + initime |
| 411 | // NOTE: clocks in seconds, initime in milliseconds |
| 412 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 413 | game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of |
| 414 | if (game.score == "*") //otherwise no need to bother with time |
| 415 | { |
| 416 | game.initime = [0, 0]; |
| 417 | const L = game.moves.length; |
| 418 | if (L >= 3) |
| 419 | { |
| 420 | let addTime = [0, 0]; |
| 421 | for (let i=2; i<L; i++) |
| 422 | { |
| 423 | addTime[i%2] += tc.increment - |
| 424 | (game.moves[i].played - game.moves[i-1].played) / 1000; |
| 425 | } |
| 426 | for (let i=0; i<=1; i++) |
| 427 | game.clocks[i] += addTime[i]; |
| 428 | } |
| 429 | if (L >= 1) |
| 430 | game.initime[L%2] = game.moves[L-1].played; |
| 431 | } |
| 432 | const reformattedMoves = game.moves.map( (m) => { |
| 433 | const s = m.squares; |
| 434 | return { |
| 435 | appear: s.appear, |
| 436 | vanish: s.vanish, |
| 437 | start: s.start, |
| 438 | end: s.end, |
| 439 | }; |
| 440 | }); |
| 441 | // Sort chat messages from newest to oldest |
| 442 | game.chats.sort( (c1,c2) => { return c2.added - c1.added; }); |
| 443 | if (myIdx >= 0 && game.chats.length > 0) |
| 444 | { |
| 445 | // TODO: group multi-moves into an array, to deduce color from index |
| 446 | // and not need this (also repeated in BaseGame::re_setVariables()) |
| 447 | let vr_tmp = new V(game.fenStart); //vr is already at end of game |
| 448 | for (let i=0; i<reformattedMoves.length; i++) |
| 449 | { |
| 450 | game.moves[i].color = vr_tmp.turn; |
| 451 | vr_tmp.play(reformattedMoves[i]); |
| 452 | } |
| 453 | // Blue background on chat button if last chat message arrived after my last move. |
| 454 | let dtLastMove = 0; |
| 455 | for (let midx = game.moves.length-1; midx >= 0; midx--) |
| 456 | { |
| 457 | if (game.moves[midx].color == mycolor) |
| 458 | { |
| 459 | dtLastMove = game.moves[midx].played; |
| 460 | break; |
| 461 | } |
| 462 | } |
| 463 | if (dtLastMove < game.chats[0].added) |
| 464 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 465 | } |
| 466 | // Now that we used idx and played, re-format moves as for live games |
| 467 | game.moves = reformattedMoves; |
| 468 | } |
| 469 | if (gtype == "live" && game.clocks[0] < 0) //game unstarted |
| 470 | { |
| 471 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 472 | if (game.score == "*") |
| 473 | { |
| 474 | game.initime[0] = Date.now(); |
| 475 | if (myIdx >= 0) |
| 476 | { |
| 477 | // I play in this live game; corr games don't have clocks+initime |
| 478 | GameStorage.update(game.id, |
| 479 | { |
| 480 | clocks: game.clocks, |
| 481 | initime: game.initime, |
| 482 | }); |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | if (!!game.drawOffer) |
| 487 | { |
| 488 | if (game.drawOffer == "t") //three repetitions |
| 489 | this.drawOffer = "threerep"; |
| 490 | else |
| 491 | { |
| 492 | if (myIdx < 0) |
| 493 | this.drawOffer = "received"; //by any of the players |
| 494 | else |
| 495 | { |
| 496 | // I play in this game: |
| 497 | if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1)) |
| 498 | this.drawOffer = "sent"; |
| 499 | else //all other cases |
| 500 | this.drawOffer = "received"; |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | if (!!game.scoreMsg) |
| 505 | game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english |
| 506 | this.game = Object.assign({}, |
| 507 | game, |
| 508 | // NOTE: assign mycolor here, since BaseGame could also be VS computer |
| 509 | { |
| 510 | type: gtype, |
| 511 | increment: tc.increment, |
| 512 | mycolor: mycolor, |
| 513 | // opponent sid not strictly required (or available), but easier |
| 514 | // at least oppsid or oppid is available anyway: |
| 515 | oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid), |
| 516 | oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid), |
| 517 | } |
| 518 | ); |
| 519 | this.re_setClocks(); |
| 520 | this.$nextTick(() => { |
| 521 | this.game.rendered = true; |
| 522 | // Did lastate arrive before game was rendered? |
| 523 | if (!!this.lastate) |
| 524 | this.processLastate(); |
| 525 | }); |
| 526 | this.repeat = {}; //reset: scan past moves' FEN: |
| 527 | let repIdx = 0; |
| 528 | // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame |
| 529 | let vr_tmp = new V(game.fenStart); |
| 530 | game.moves.forEach(m => { |
| 531 | vr_tmp.play(m); |
| 532 | const fenObj = V.ParseFen( vr_tmp.getFen() ); |
| 533 | repIdx = fenObj.position + "_" + fenObj.turn; |
| 534 | if (!!fenObj.flags) |
| 535 | repIdx += "_" + fenObj.flags; |
| 536 | this.repeat[repIdx] = (!!this.repeat[repIdx] |
| 537 | ? this.repeat[repIdx]+1 |
| 538 | : 1); |
| 539 | }); |
| 540 | if (this.repeat[repIdx] >= 3) |
| 541 | this.drawOffer = "threerep"; |
| 542 | if (!!callback) |
| 543 | callback(); |
| 544 | }; |
| 545 | if (!!game) |
| 546 | return afterRetrieval(game); |
| 547 | if (!!this.gameRef.rid) |
| 548 | { |
| 549 | // Remote live game: forgetting about callback func... (TODO: design) |
| 550 | this.send("askfullgame", {target:this.gameRef.rid}); |
| 551 | } |
| 552 | else |
| 553 | { |
| 554 | // Local or corr game |
| 555 | GameStorage.get(this.gameRef.id, afterRetrieval); |
| 556 | } |
| 557 | }, |
| 558 | re_setClocks: function() { |
| 559 | if (this.game.moves.length < 2 || this.game.score != "*") |
| 560 | { |
| 561 | // 1st move not completed yet, or game over: freeze time |
| 562 | this.virtualClocks = this.game.clocks.map(s => ppt(s)); |
| 563 | return; |
| 564 | } |
| 565 | const currentTurn = this.vr.turn; |
| 566 | const colorIdx = ["w","b"].indexOf(currentTurn); |
| 567 | let countdown = this.game.clocks[colorIdx] - |
| 568 | (Date.now() - this.game.initime[colorIdx])/1000; |
| 569 | this.virtualClocks = [0,1].map(i => { |
| 570 | const removeTime = i == colorIdx |
| 571 | ? (Date.now() - this.game.initime[colorIdx])/1000 |
| 572 | : 0; |
| 573 | return ppt(this.game.clocks[i] - removeTime); |
| 574 | }); |
| 575 | let clockUpdate = setInterval(() => { |
| 576 | if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*") |
| 577 | { |
| 578 | clearInterval(clockUpdate); |
| 579 | if (countdown < 0) |
| 580 | this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]); |
| 581 | } |
| 582 | else |
| 583 | this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown))); |
| 584 | }, 1000); |
| 585 | }, |
| 586 | // Post-process a move (which was just played in BaseGame) |
| 587 | processMove: function(move) { |
| 588 | if (this.game.type == "corr" && move.color == this.game.mycolor) |
| 589 | { |
| 590 | if (!confirm(this.st.tr["Move played:"] + " " + move.notation + "\n" + this.st.tr["Are you sure?"])) |
| 591 | { |
| 592 | return this.$set(this.game, "moveToUndo", move); |
| 593 | } |
| 594 | } |
| 595 | const colorIdx = ["w","b"].indexOf(move.color); |
| 596 | const nextIdx = ["w","b"].indexOf(this.vr.turn); |
| 597 | // https://stackoverflow.com/a/38750895 |
| 598 | if (!!this.game.mycolor) |
| 599 | { |
| 600 | const allowed_fields = ["appear", "vanish", "start", "end"]; |
| 601 | // NOTE: 'var' to see this variable outside this block |
| 602 | var filtered_move = Object.keys(move) |
| 603 | .filter(key => allowed_fields.includes(key)) |
| 604 | .reduce((obj, key) => { |
| 605 | obj[key] = move[key]; |
| 606 | return obj; |
| 607 | }, {}); |
| 608 | } |
| 609 | // Send move ("newmove" event) to people in the room (if our turn) |
| 610 | let addTime = 0; |
| 611 | if (move.color == this.game.mycolor) |
| 612 | { |
| 613 | if (this.drawOffer == "received") //I refuse draw |
| 614 | this.drawOffer = ""; |
| 615 | if (this.game.moves.length >= 2) //after first move |
| 616 | { |
| 617 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
| 618 | // elapsed time is measured in milliseconds |
| 619 | addTime = this.game.increment - elapsed/1000; |
| 620 | } |
| 621 | const sendMove = Object.assign({}, |
| 622 | filtered_move, |
| 623 | { |
| 624 | addTime: addTime, |
| 625 | cancelDrawOffer: this.drawOffer=="", |
| 626 | }); |
| 627 | this.send("newmove", {data: sendMove}); |
| 628 | // (Add)Time indication: useful in case of lastate infos requested |
| 629 | move.addTime = addTime; |
| 630 | } |
| 631 | else |
| 632 | addTime = move.addTime; //supposed transmitted |
| 633 | // Update current game object: |
| 634 | this.game.moves.push(move); |
| 635 | this.game.fen = move.fen; |
| 636 | this.game.clocks[colorIdx] += addTime; |
| 637 | // move.initime is set only when I receive a "lastate" move from opponent |
| 638 | this.game.initime[nextIdx] = move.initime || Date.now(); |
| 639 | this.re_setClocks(); |
| 640 | // If repetition detected, consider that a draw offer was received: |
| 641 | const fenObj = V.ParseFen(move.fen); |
| 642 | let repIdx = fenObj.position + "_" + fenObj.turn; |
| 643 | if (!!fenObj.flags) |
| 644 | repIdx += "_" + fenObj.flags; |
| 645 | this.repeat[repIdx] = (!!this.repeat[repIdx] |
| 646 | ? this.repeat[repIdx]+1 |
| 647 | : 1); |
| 648 | if (this.repeat[repIdx] >= 3) |
| 649 | this.drawOffer = "threerep"; |
| 650 | else if (this.drawOffer == "threerep") |
| 651 | this.drawOffer = ""; |
| 652 | // Since corr games are stored at only one location, update should be |
| 653 | // done only by one player for each move: |
| 654 | if (!!this.game.mycolor && |
| 655 | (this.game.type == "live" || move.color == this.game.mycolor)) |
| 656 | { |
| 657 | let drawCode = ""; |
| 658 | switch (this.drawOffer) |
| 659 | { |
| 660 | case "threerep": |
| 661 | drawCode = "t"; |
| 662 | break; |
| 663 | case "sent": |
| 664 | drawCode = this.game.mycolor; |
| 665 | break; |
| 666 | case "received": |
| 667 | drawCode = this.vr.turn; |
| 668 | break; |
| 669 | } |
| 670 | if (this.game.type == "corr") |
| 671 | { |
| 672 | GameStorage.update(this.gameRef.id, |
| 673 | { |
| 674 | fen: move.fen, |
| 675 | move: |
| 676 | { |
| 677 | squares: filtered_move, |
| 678 | played: Date.now(), |
| 679 | idx: this.game.moves.length - 1, |
| 680 | }, |
| 681 | drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored) |
| 682 | }); |
| 683 | } |
| 684 | else //live |
| 685 | { |
| 686 | GameStorage.update(this.gameRef.id, |
| 687 | { |
| 688 | fen: move.fen, |
| 689 | move: filtered_move, |
| 690 | clocks: this.game.clocks, |
| 691 | initime: this.game.initime, |
| 692 | drawOffer: drawCode, |
| 693 | }); |
| 694 | } |
| 695 | } |
| 696 | }, |
| 697 | resetChatColor: function() { |
| 698 | // TODO: this is called twice, once on opening an once on closing |
| 699 | document.getElementById("chatBtn").classList.remove("somethingnew"); |
| 700 | }, |
| 701 | processChat: function(chat) { |
| 702 | this.send("newchat", {data:chat}); |
| 703 | // NOTE: anonymous chats in corr games are not stored on server (TODO?) |
| 704 | if (this.game.type == "corr" && this.st.user.id > 0) |
| 705 | GameStorage.update(this.gameRef.id, {chat: chat}); |
| 706 | }, |
| 707 | gameOver: function(score, scoreMsg) { |
| 708 | this.game.score = score; |
| 709 | this.game.scoreMsg = this.st.tr[(!!scoreMsg |
| 710 | ? scoreMsg |
| 711 | : getScoreMessage(score))]; |
| 712 | const myIdx = this.game.players.findIndex(p => { |
| 713 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 714 | }); |
| 715 | if (myIdx >= 0) //OK, I play in this game |
| 716 | { |
| 717 | GameStorage.update(this.gameRef.id, |
| 718 | {score: score, scoreMsg: scoreMsg}); |
| 719 | // Notify the score to main Hall. TODO: only one player (currently double send) |
| 720 | this.send("result", {gid:this.game.id, score:score}); |
| 721 | } |
| 722 | }, |
| 723 | }, |
| 724 | }; |
| 725 | </script> |
| 726 | |
| 727 | <style lang="sass" scoped> |
| 728 | .connected |
| 729 | background-color: lightgreen |
| 730 | |
| 731 | #participants |
| 732 | margin-left: 5px |
| 733 | |
| 734 | .anonymous |
| 735 | color: grey |
| 736 | font-style: italic |
| 737 | |
| 738 | #playersInfo > p |
| 739 | margin: 0 |
| 740 | |
| 741 | @media screen and (min-width: 768px) |
| 742 | #actions |
| 743 | width: 300px |
| 744 | @media screen and (max-width: 767px) |
| 745 | .game |
| 746 | width: 100% |
| 747 | |
| 748 | #actions |
| 749 | display: inline-block |
| 750 | margin: 0 |
| 751 | button |
| 752 | display: inline-block |
| 753 | margin: 0 |
| 754 | |
| 755 | @media screen and (max-width: 767px) |
| 756 | #aboveBoard |
| 757 | text-align: center |
| 758 | @media screen and (min-width: 768px) |
| 759 | #aboveBoard |
| 760 | margin-left: 30% |
| 761 | |
| 762 | .variant-cadence |
| 763 | padding-right: 10px |
| 764 | |
| 765 | .variant-name |
| 766 | font-weight: bold |
| 767 | padding-right: 10px |
| 768 | |
| 769 | .name |
| 770 | font-size: 1.5rem |
| 771 | padding: 1px |
| 772 | |
| 773 | .time |
| 774 | font-size: 2rem |
| 775 | display: inline-block |
| 776 | margin-left: 10px |
| 777 | |
| 778 | .split-names |
| 779 | display: inline-block |
| 780 | margin: 0 15px |
| 781 | |
| 782 | #chat |
| 783 | padding-top: 20px |
| 784 | max-width: 767px |
| 785 | border: none; |
| 786 | |
| 787 | #chatBtn |
| 788 | margin: 0 10px 0 0 |
| 789 | |
| 790 | .draw-sent, .draw-sent:hover |
| 791 | background-color: lightyellow |
| 792 | |
| 793 | .draw-received, .draw-received:hover |
| 794 | background-color: lightgreen |
| 795 | |
| 796 | .draw-threerep, .draw-threerep:hover |
| 797 | background-color: #e4d1fc |
| 798 | |
| 799 | .somethingnew |
| 800 | background-color: #c5fefe |
| 801 | </style> |