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