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