| 1 | <template lang="pug"> |
| 2 | main |
| 3 | .row |
| 4 | #chat.col-sm-12.col-md-4.col-md-offset-4 |
| 5 | Chat(:players="game.players" :pastChats="game.chats" |
| 6 | @newchat="processChat") |
| 7 | .row |
| 8 | .col-sm-12 |
| 9 | #actions(v-if="game.mode!='analyze' && game.score=='*'") |
| 10 | button(@click="offerDraw") Draw |
| 11 | button(@click="abortGame") Abort |
| 12 | button(@click="resign") Resign |
| 13 | div Names: {{ game.players[0].name }} - {{ game.players[1].name }} |
| 14 | div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }} |
| 15 | BaseGame(:game="game" :vr="vr" ref="basegame" |
| 16 | @newmove="processMove" @gameover="gameOver") |
| 17 | </template> |
| 18 | |
| 19 | <script> |
| 20 | import BaseGame from "@/components/BaseGame.vue"; |
| 21 | import Chat from "@/components/Chat.vue"; |
| 22 | import { store } from "@/store"; |
| 23 | import { GameStorage } from "@/utils/gameStorage"; |
| 24 | import { ppt } from "@/utils/datetime"; |
| 25 | import { extractTime } from "@/utils/timeControl"; |
| 26 | import { ArrayFun } from "@/utils/array"; |
| 27 | |
| 28 | export default { |
| 29 | name: 'my-game', |
| 30 | components: { |
| 31 | BaseGame, |
| 32 | Chat, |
| 33 | }, |
| 34 | // gameRef: to find the game in (potentially remote) storage |
| 35 | data: function() { |
| 36 | return { |
| 37 | st: store.state, |
| 38 | gameRef: { //given in URL (rid = remote ID) |
| 39 | id: "", |
| 40 | rid: "" |
| 41 | }, |
| 42 | game: {players:[{name:""},{name:""}]}, //passed to BaseGame |
| 43 | virtualClocks: [0, 0], //initialized with true game.clocks |
| 44 | vr: null, //"variant rules" object initialized from FEN |
| 45 | drawOffer: "", //TODO: use for button style |
| 46 | people: [], //players + observers |
| 47 | lastate: undefined, //used if opponent send lastate before game is ready |
| 48 | repeat: {}, //detect position repetition |
| 49 | }; |
| 50 | }, |
| 51 | watch: { |
| 52 | "$route": function(to, from) { |
| 53 | this.gameRef.id = to.params["id"]; |
| 54 | this.gameRef.rid = to.query["rid"]; |
| 55 | this.loadGame(); |
| 56 | }, |
| 57 | "game.clocks": function(newState) { |
| 58 | if (this.game.moves.length < 2 || this.game.score != "*") |
| 59 | { |
| 60 | // 1st move not completed yet, or game over: freeze time |
| 61 | this.virtualClocks = newState.map(s => ppt(s)); |
| 62 | return; |
| 63 | } |
| 64 | const currentTurn = this.vr.turn; |
| 65 | const colorIdx = ["w","b"].indexOf(currentTurn); |
| 66 | let countdown = newState[colorIdx] - |
| 67 | (Date.now() - this.game.initime[colorIdx])/1000; |
| 68 | this.virtualClocks = [0,1].map(i => { |
| 69 | const removeTime = i == colorIdx |
| 70 | ? (Date.now() - this.game.initime[colorIdx])/1000 |
| 71 | : 0; |
| 72 | return ppt(newState[i] - removeTime); |
| 73 | }); |
| 74 | let clockUpdate = setInterval(() => { |
| 75 | if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*") |
| 76 | { |
| 77 | clearInterval(clockUpdate); |
| 78 | if (countdown < 0) |
| 79 | this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", "Time"); |
| 80 | } |
| 81 | else |
| 82 | { |
| 83 | // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown) |
| 84 | this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown))); |
| 85 | } |
| 86 | }, 1000); |
| 87 | }, |
| 88 | }, |
| 89 | // TODO: redundant code with Hall.vue (related to people array) |
| 90 | created: function() { |
| 91 | // Always add myself to players' list |
| 92 | const my = this.st.user; |
| 93 | this.people.push({sid: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 | // Define socket .onmessage() and .onclose() events: |
| 97 | this.st.conn.onmessage = this.socketMessageListener; |
| 98 | const socketCloseListener = () => { |
| 99 | store.socketCloseListener(); //reinitialize connexion (in store.js) |
| 100 | this.st.conn.addEventListener('message', this.socketMessageListener); |
| 101 | this.st.conn.addEventListener('close', socketCloseListener); |
| 102 | }; |
| 103 | this.st.conn.onclose = socketCloseListener; |
| 104 | // Socket init required before loading remote game: |
| 105 | const socketInit = (callback) => { |
| 106 | if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state |
| 107 | callback(); |
| 108 | else //socket not ready yet (initial loading) |
| 109 | this.st.conn.onopen = callback; |
| 110 | }; |
| 111 | if (!this.gameRef.rid) //game stored locally or on server |
| 112 | this.loadGame(null, () => socketInit(this.roomInit)); |
| 113 | else //game stored remotely: need socket to retrieve it |
| 114 | { |
| 115 | // NOTE: the callback "roomInit" will be lost, so we don't provide it. |
| 116 | // --> It will be given when receiving "fullgame" socket event. |
| 117 | // A more general approach would be to store it somewhere. |
| 118 | socketInit(this.loadGame); |
| 119 | } |
| 120 | }, |
| 121 | methods: { |
| 122 | // O.1] Ask server for room composition: |
| 123 | roomInit: function() { |
| 124 | this.st.conn.send(JSON.stringify({code:"pollclients"})); |
| 125 | }, |
| 126 | socketMessageListener: function(msg) { |
| 127 | const data = JSON.parse(msg.data); |
| 128 | switch (data.code) |
| 129 | { |
| 130 | case "duplicate": |
| 131 | alert("Warning: duplicate 'offline' connection"); |
| 132 | break; |
| 133 | // 0.2] Receive clients list (just socket IDs) |
| 134 | case "pollclients": |
| 135 | { |
| 136 | data.sockIds.forEach(sid => { |
| 137 | this.people.push({sid:sid, id:0, name:""}); |
| 138 | // Ask only identity |
| 139 | this.st.conn.send(JSON.stringify({code:"askidentity", target:sid})); |
| 140 | }); |
| 141 | break; |
| 142 | } |
| 143 | case "askidentity": |
| 144 | { |
| 145 | // Request for identification: reply if I'm not anonymous |
| 146 | if (this.st.user.id > 0) |
| 147 | { |
| 148 | this.st.conn.send(JSON.stringify( |
| 149 | // people[0] instead of st.user to avoid sending email |
| 150 | {code:"identity", user:this.people[0], target:data.from})); |
| 151 | } |
| 152 | break; |
| 153 | } |
| 154 | case "identity": |
| 155 | { |
| 156 | let player = this.people.find(p => p.sid == data.user.sid); |
| 157 | // NOTE: sometimes player.id fails because player is undefined... |
| 158 | // Probably because the event was meant for Hall? |
| 159 | if (!player) |
| 160 | return; |
| 161 | player.id = data.user.id; |
| 162 | player.name = data.user.name; |
| 163 | // Sending last state only for live games: corr games are complete |
| 164 | if (this.game.type == "live" && this.game.oppsid == player.sid) |
| 165 | { |
| 166 | // Send our "last state" informations to opponent |
| 167 | const L = this.game.moves.length; |
| 168 | let lastMove = (L>0 ? this.game.moves[L-1] : undefined); |
| 169 | if (!!lastMove && this.drawOffer == "sent") |
| 170 | lastMove.draw = true; |
| 171 | this.st.conn.send(JSON.stringify({ |
| 172 | code: "lastate", |
| 173 | target: player.sid, |
| 174 | state: |
| 175 | { |
| 176 | lastMove: lastMove, |
| 177 | score: this.game.score, |
| 178 | movesCount: L, |
| 179 | clocks: this.game.clocks, |
| 180 | } |
| 181 | })); |
| 182 | } |
| 183 | break; |
| 184 | } |
| 185 | case "askgame": |
| 186 | // Send current (live) game |
| 187 | const myGame = |
| 188 | { |
| 189 | // Minimal game informations: |
| 190 | id: this.game.id, |
| 191 | players: this.game.players.map(p => { return {name:p.name}; }), |
| 192 | vid: this.game.vid, |
| 193 | timeControl: this.game.timeControl, |
| 194 | }; |
| 195 | this.st.conn.send(JSON.stringify({code:"game", |
| 196 | game:myGame, target:data.from})); |
| 197 | break; |
| 198 | case "newmove": |
| 199 | this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3... |
| 200 | break; |
| 201 | case "lastate": //got opponent infos about last move |
| 202 | { |
| 203 | this.lastate = data; |
| 204 | if (!!this.game.type) //game is loaded |
| 205 | this.processLastate(); |
| 206 | //else: will be processed when game is ready |
| 207 | break; |
| 208 | } |
| 209 | case "resign": |
| 210 | this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign"); |
| 211 | break; |
| 212 | case "abort": |
| 213 | this.gameOver("?", "Abort"); |
| 214 | break; |
| 215 | case "draw": |
| 216 | this.gameOver("1/2", "Mutual agreement"); |
| 217 | break; |
| 218 | case "drawoffer": |
| 219 | this.drawOffer = "received"; //TODO: observers don't know who offered draw |
| 220 | break; |
| 221 | case "askfullgame": |
| 222 | this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from})); |
| 223 | break; |
| 224 | case "fullgame": |
| 225 | // Callback "roomInit" to poll clients only after game is loaded |
| 226 | this.loadGame(data.game, this.roomInit); |
| 227 | break; |
| 228 | case "connect": |
| 229 | { |
| 230 | this.people.push({name:"", id:0, sid:data.from}); |
| 231 | this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from})); |
| 232 | break; |
| 233 | } |
| 234 | case "disconnect": |
| 235 | ArrayFun.remove(this.people, p => p.sid == data.from); |
| 236 | break; |
| 237 | } |
| 238 | }, |
| 239 | // lastate was received, but maybe game wasn't ready yet: |
| 240 | processLastate: function() { |
| 241 | const data = this.lastate; |
| 242 | this.lastate = undefined; //security... |
| 243 | const L = this.game.moves.length; |
| 244 | if (data.movesCount > L) |
| 245 | { |
| 246 | // Just got last move from him |
| 247 | this.$set(this.game, "moveToPlay", data.lastMove); |
| 248 | if (data.score != "*" && this.game.score == "*") |
| 249 | { |
| 250 | // Opponent resigned or aborted game, or accepted draw offer |
| 251 | // (this is not a stalemate or checkmate) |
| 252 | this.gameOver(data.score, "Opponent action"); |
| 253 | } |
| 254 | this.game.clocks = data.clocks; //TODO: check this? |
| 255 | if (!!data.lastMove.draw) |
| 256 | this.drawOffer = "received"; |
| 257 | } |
| 258 | }, |
| 259 | offerDraw: function() { |
| 260 | if (this.drawOffer == "received") |
| 261 | { |
| 262 | if (!confirm("Accept draw?")) |
| 263 | return; |
| 264 | this.people.forEach(p => { |
| 265 | if (p.sid != this.st.user.sid) |
| 266 | this.st.conn.send(JSON.stringify({code:"draw", target:p.sid})); |
| 267 | }); |
| 268 | this.gameOver("1/2", "Mutual agreement"); |
| 269 | } |
| 270 | else if (this.drawOffer == "sent") |
| 271 | { |
| 272 | this.drawOffer = ""; |
| 273 | if (this.game.type == "corr") |
| 274 | GameStorage.update(this.gameRef.id, {drawOffer: false}); |
| 275 | } |
| 276 | else |
| 277 | { |
| 278 | if (!confirm("Offer draw?")) |
| 279 | return; |
| 280 | this.drawOffer = "sent"; |
| 281 | this.people.forEach(p => { |
| 282 | if (p.sid != this.st.user.sid) |
| 283 | this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid})); |
| 284 | }); |
| 285 | if (this.game.type == "corr") |
| 286 | GameStorage.update(this.gameRef.id, {drawOffer: true}); |
| 287 | } |
| 288 | }, |
| 289 | abortGame: function() { |
| 290 | if (!confirm(this.st.tr["Terminate game?"])) |
| 291 | return; |
| 292 | this.gameOver("?", "Abort"); |
| 293 | this.people.forEach(p => { |
| 294 | if (p.sid != this.st.user.sid) |
| 295 | { |
| 296 | this.st.conn.send(JSON.stringify({ |
| 297 | code: "abort", |
| 298 | target: p.sid, |
| 299 | })); |
| 300 | } |
| 301 | }); |
| 302 | }, |
| 303 | resign: function(e) { |
| 304 | if (!confirm("Resign the game?")) |
| 305 | return; |
| 306 | this.people.forEach(p => { |
| 307 | if (p.sid != this.st.user.sid) |
| 308 | { |
| 309 | this.st.conn.send(JSON.stringify({code:"resign", |
| 310 | side:this.game.mycolor, target:p.sid})); |
| 311 | } |
| 312 | }); |
| 313 | this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign"); |
| 314 | }, |
| 315 | // 3 cases for loading a game: |
| 316 | // - from indexedDB (running or completed live game I play) |
| 317 | // - from server (one correspondance game I play[ed] or not) |
| 318 | // - from remote peer (one live game I don't play, finished or not) |
| 319 | loadGame: function(game, callback) { |
| 320 | const afterRetrieval = async (game) => { |
| 321 | const vModule = await import("@/variants/" + game.vname + ".js"); |
| 322 | window.V = vModule.VariantRules; |
| 323 | this.vr = new V(game.fen); |
| 324 | const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live"); |
| 325 | const tc = extractTime(game.timeControl); |
| 326 | if (gtype == "corr") |
| 327 | { |
| 328 | if (game.players[0].color == "b") |
| 329 | { |
| 330 | // Adopt the same convention for live and corr games: [0] = white |
| 331 | [ game.players[0], game.players[1] ] = |
| 332 | [ game.players[1], game.players[0] ]; |
| 333 | } |
| 334 | // corr game: needs to compute the clocks + initime |
| 335 | // NOTE: clocks in seconds, initime in milliseconds |
| 336 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 337 | game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of |
| 338 | if (game.score == "*") //otherwise no need to bother with time |
| 339 | { |
| 340 | game.initime = [0, 0]; |
| 341 | const L = game.moves.length; |
| 342 | if (L >= 3) |
| 343 | { |
| 344 | let addTime = [0, 0]; |
| 345 | for (let i=2; i<L; i++) |
| 346 | { |
| 347 | addTime[i%2] += tc.increment - |
| 348 | (game.moves[i].played - game.moves[i-1].played) / 1000; |
| 349 | } |
| 350 | for (let i=0; i<=1; i++) |
| 351 | game.clocks[i] += addTime[i]; |
| 352 | } |
| 353 | if (L >= 1) |
| 354 | game.initime[L%2] = game.moves[L-1].played; |
| 355 | if (game.drawOffer) |
| 356 | this.drawOffer = "received"; |
| 357 | } |
| 358 | // Now that we used idx and played, re-format moves as for live games |
| 359 | game.moves = game.moves.map( (m) => { |
| 360 | const s = m.squares; |
| 361 | return { |
| 362 | appear: s.appear, |
| 363 | vanish: s.vanish, |
| 364 | start: s.start, |
| 365 | end: s.end, |
| 366 | }; |
| 367 | }); |
| 368 | // Also sort chat messages (if any) |
| 369 | game.chats.sort( (c1,c2) => { return c2.added - c1.added; }); |
| 370 | } |
| 371 | const myIdx = game.players.findIndex(p => { |
| 372 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 373 | }); |
| 374 | if (gtype == "live" && game.clocks[0] < 0) //game unstarted |
| 375 | { |
| 376 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 377 | if (game.score == "*") |
| 378 | { |
| 379 | game.initime[0] = Date.now(); |
| 380 | if (myIdx >= 0) |
| 381 | { |
| 382 | // I play in this live game; corr games don't have clocks+initime |
| 383 | GameStorage.update(game.id, |
| 384 | { |
| 385 | clocks: game.clocks, |
| 386 | initime: game.initime, |
| 387 | }); |
| 388 | } |
| 389 | } |
| 390 | } |
| 391 | this.game = Object.assign({}, |
| 392 | game, |
| 393 | // NOTE: assign mycolor here, since BaseGame could also be VS computer |
| 394 | { |
| 395 | type: gtype, |
| 396 | increment: tc.increment, |
| 397 | mycolor: [undefined,"w","b"][myIdx+1], |
| 398 | // opponent sid not strictly required (or available), but easier |
| 399 | // at least oppsid or oppid is available anyway: |
| 400 | oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid), |
| 401 | oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid), |
| 402 | } |
| 403 | ); |
| 404 | this.repeat = {}; //reset |
| 405 | if (!!this.lastate) //lastate arrived before game was loaded: |
| 406 | this.processLastate(); |
| 407 | callback(); |
| 408 | }; |
| 409 | if (!!game) |
| 410 | return afterRetrieval(game); |
| 411 | if (!!this.gameRef.rid) |
| 412 | { |
| 413 | // Remote live game: forgetting about callback func... (TODO: design) |
| 414 | this.st.conn.send(JSON.stringify( |
| 415 | {code:"askfullgame", target:this.gameRef.rid})); |
| 416 | } |
| 417 | else |
| 418 | { |
| 419 | // Local or corr game |
| 420 | GameStorage.get(this.gameRef.id, afterRetrieval); |
| 421 | } |
| 422 | }, |
| 423 | // Post-process a move (which was just played) |
| 424 | processMove: function(move) { |
| 425 | if (!this.game.mycolor) |
| 426 | return; //I'm just an observer |
| 427 | // Update storage (corr or live) |
| 428 | const colorIdx = ["w","b"].indexOf(move.color); |
| 429 | // https://stackoverflow.com/a/38750895 |
| 430 | const allowed_fields = ["appear", "vanish", "start", "end"]; |
| 431 | const filtered_move = Object.keys(move) |
| 432 | .filter(key => allowed_fields.includes(key)) |
| 433 | .reduce((obj, key) => { |
| 434 | obj[key] = move[key]; |
| 435 | return obj; |
| 436 | }, {}); |
| 437 | // Send move ("newmove" event) to people in the room (if our turn) |
| 438 | let addTime = 0; |
| 439 | if (move.color == this.game.mycolor) |
| 440 | { |
| 441 | if (this.game.moves.length >= 2) //after first move |
| 442 | { |
| 443 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
| 444 | // elapsed time is measured in milliseconds |
| 445 | addTime = this.game.increment - elapsed/1000; |
| 446 | } |
| 447 | let sendMove = Object.assign({}, filtered_move, {addTime: addTime}); |
| 448 | this.people.forEach(p => { |
| 449 | if (p.sid != this.st.user.sid) |
| 450 | { |
| 451 | this.st.conn.send(JSON.stringify({ |
| 452 | code: "newmove", |
| 453 | target: p.sid, |
| 454 | move: sendMove, |
| 455 | })); |
| 456 | } |
| 457 | }); |
| 458 | } |
| 459 | else |
| 460 | addTime = move.addTime; //supposed transmitted |
| 461 | const nextIdx = ["w","b"].indexOf(this.vr.turn); |
| 462 | // Since corr games are stored at only one location, update should be |
| 463 | // done only by one player for each move: |
| 464 | if (this.game.type == "live" || move.color == this.game.mycolor) |
| 465 | { |
| 466 | if (this.game.type == "corr") |
| 467 | { |
| 468 | GameStorage.update(this.gameRef.id, |
| 469 | { |
| 470 | fen: move.fen, |
| 471 | move: |
| 472 | { |
| 473 | squares: filtered_move, |
| 474 | played: Date.now(), //TODO: on server? |
| 475 | idx: this.game.moves.length, |
| 476 | }, |
| 477 | }); |
| 478 | } |
| 479 | else //live |
| 480 | { |
| 481 | GameStorage.update(this.gameRef.id, |
| 482 | { |
| 483 | fen: move.fen, |
| 484 | move: filtered_move, |
| 485 | clocks: this.game.clocks.map((t,i) => i==colorIdx |
| 486 | ? this.game.clocks[i] + addTime |
| 487 | : this.game.clocks[i]), |
| 488 | initime: this.game.initime.map((t,i) => i==nextIdx |
| 489 | ? Date.now() |
| 490 | : this.game.initime[i]), |
| 491 | }); |
| 492 | } |
| 493 | } |
| 494 | // Also update current game object: |
| 495 | this.game.moves.push(move); |
| 496 | this.game.fen = move.fen; |
| 497 | //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime; |
| 498 | this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime); |
| 499 | this.game.initime[nextIdx] = Date.now(); |
| 500 | // If repetition detected, consider that a draw offer was received: |
| 501 | const fenObj = V.ParseFen(move.fen); |
| 502 | let repIdx = fenObj.position + "_" + fenObj.turn; |
| 503 | if (!!fenObj.flags) |
| 504 | repIdx += "_" + fenObj.flags; |
| 505 | this.repeat[repIdx] = (!!this.repeat[repIdx] |
| 506 | ? this.repeat[repIdx]+1 |
| 507 | : 1); |
| 508 | if (this.repeat[repIdx] >= 3) |
| 509 | this.drawOffer = "received"; //TODO: will print "mutual agreement"... |
| 510 | }, |
| 511 | processChat: function(chat) { |
| 512 | if (this.game.type == "corr") |
| 513 | GameStorage.update(this.gameRef.id, {chat: chat}); |
| 514 | }, |
| 515 | gameOver: function(score, scoreMsg) { |
| 516 | this.game.mode = "analyze"; |
| 517 | this.game.score = score; |
| 518 | this.game.scoreMsg = scoreMsg; |
| 519 | const myIdx = this.game.players.findIndex(p => { |
| 520 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 521 | }); |
| 522 | if (myIdx >= 0) //OK, I play in this game |
| 523 | GameStorage.update(this.gameRef.id, { score: score }); |
| 524 | }, |
| 525 | }, |
| 526 | }; |
| 527 | </script> |
| 528 | |
| 529 | <style lang="sass"> |
| 530 | .connected |
| 531 | background-color: green |
| 532 | .disconnected |
| 533 | background-color: red |
| 534 | |
| 535 | @media screen and (min-width: 768px) |
| 536 | #actions |
| 537 | width: 300px |
| 538 | @media screen and (max-width: 767px) |
| 539 | .game |
| 540 | width: 100% |
| 541 | |
| 542 | #actions |
| 543 | margin-top: 10px |
| 544 | margin-left: auto |
| 545 | margin-right: auto |
| 546 | button |
| 547 | display: inline-block |
| 548 | width: 33% |
| 549 | margin: 0 |
| 550 | #chat |
| 551 | margin-top: 5px |
| 552 | margin-bottom: 5px |
| 553 | >.card |
| 554 | max-width: 100% |
| 555 | margin: 0; |
| 556 | border: none; |
| 557 | </style> |