| 1 | <template lang="pug"> |
| 2 | .row |
| 3 | .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2 |
| 4 | input#modalAbort.modal(type="checkbox") |
| 5 | div(role="dialog" aria-labelledby="abortBoxTitle") |
| 6 | .card.smallpad.small-modal.text-center |
| 7 | label.modal-close(for="modalAbort") |
| 8 | h3#abortBoxTitle.section {{ st.tr["Terminate game?"] }} |
| 9 | button(@click="abortGame") {{ st.tr["Sorry I have to go"] }} |
| 10 | button(@click="abortGame") {{ st.tr["Game seems over"] }} |
| 11 | button(@click="abortGame") {{ st.tr["Game is too boring"] }} |
| 12 | BaseGame(:game="game" :vr="vr" ref="basegame" |
| 13 | @newmove="processMove" @gameover="gameOver") |
| 14 | // TODO: also show players names |
| 15 | div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }} |
| 16 | .button-group(v-if="game.mode!='analyze' && game.score=='*'") |
| 17 | button(@click="offerDraw") Draw |
| 18 | button(@click="() => abortGame()") Abort |
| 19 | button(@click="resign") Resign |
| 20 | div(v-if="game.mode=='corr'") |
| 21 | textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg") |
| 22 | div(v-show="cursor>=0") {{ moves[cursor].message }} |
| 23 | </template> |
| 24 | |
| 25 | <!-- |
| 26 | // TODO: movelist dans basegame et chat ici |
| 27 | // ==> après, implémenter/vérifier les passages de challenges + parties en cours |
| 28 | // observer, |
| 29 | // + problèmes, habiller et publier. (+ corr...) |
| 30 | // TODO: how to know who is observing ? Send message to everyone with game ID ? |
| 31 | // and then just listen to (dis)connect events |
| 32 | // server always send "connect on " + URL ; then add to observers if game... |
| 33 | // router when access a game page tell to server I joined + game ID (no need rid) |
| 34 | // and ask server for current joined (= observers) |
| 35 | // when send to chat (or a move), reach only this group (send gid along) |
| 36 | // -> doivent être enregistrés comme observers au niveau du serveur... |
| 37 | // non: poll users + events startObserving / stopObserving |
| 38 | // (à faire au niveau du routeur ?) |
| 39 | --> |
| 40 | |
| 41 | <script> |
| 42 | import BaseGame from "@/components/BaseGame.vue"; |
| 43 | //import Chat from "@/components/Chat.vue"; |
| 44 | //import MoveList from "@/components/MoveList.vue"; |
| 45 | import { store } from "@/store"; |
| 46 | import { GameStorage } from "@/utils/gameStorage"; |
| 47 | import { ppt } from "@/utils/datetime"; |
| 48 | import { extractTime } from "@/utils/timeControl"; |
| 49 | |
| 50 | export default { |
| 51 | name: 'my-game', |
| 52 | components: { |
| 53 | BaseGame, |
| 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 | oppConnected: false, //TODO: use for styling |
| 65 | corrMsg: "", //to send offline messages in corr games |
| 66 | virtualClocks: [0, 0], //initialized with true game.clocks |
| 67 | vr: null, //"variant rules" object initialized from FEN |
| 68 | drawOffer: "", //TODO: use for button style |
| 69 | people: [ ], //potential observers (TODO) |
| 70 | }; |
| 71 | }, |
| 72 | watch: { |
| 73 | '$route' (to, from) { |
| 74 | if (!!to.params["id"]) |
| 75 | { |
| 76 | this.gameRef.id = to.params["id"]; |
| 77 | this.gameRef.rid = to.query["rid"]; |
| 78 | this.loadGame(); |
| 79 | } |
| 80 | }, |
| 81 | "game.clocks": function(newState) { |
| 82 | if (this.game.moves.length < 2) |
| 83 | { |
| 84 | // 1st move not completed yet: freeze time |
| 85 | this.virtualClocks = newState.map(s => ppt(s)); |
| 86 | return; |
| 87 | } |
| 88 | const currentTurn = this.vr.turn; |
| 89 | const colorIdx = ["w","b"].indexOf(currentTurn); |
| 90 | let countdown = newState[colorIdx] - |
| 91 | (Date.now() - this.game.initime[colorIdx])/1000; |
| 92 | this.virtualClocks = [0,1].map(i => { |
| 93 | const removeTime = i == colorIdx |
| 94 | ? (Date.now() - this.game.initime[colorIdx])/1000 |
| 95 | : 0; |
| 96 | return ppt(newState[i] - removeTime); |
| 97 | }); |
| 98 | const myTurn = (currentTurn == this.game.mycolor); |
| 99 | let clockUpdate = setInterval(() => { |
| 100 | if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*") |
| 101 | { |
| 102 | clearInterval(clockUpdate); |
| 103 | if (countdown <= 0 && myTurn) |
| 104 | { |
| 105 | this.$refs["basegame"].endGame( |
| 106 | this.game.mycolor=="w" ? "0-1" : "1-0", "Time"); |
| 107 | this.st.conn.send(JSON.stringify({ |
| 108 | code: "timeover", |
| 109 | target: this.game.oppid, |
| 110 | })); |
| 111 | } |
| 112 | } |
| 113 | else |
| 114 | { |
| 115 | // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown) |
| 116 | this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown))); |
| 117 | } |
| 118 | }, 1000); |
| 119 | }, |
| 120 | // In case variants array was't loaded when game was retrieved |
| 121 | "st.variants": function(variantArray) { |
| 122 | if (!!this.game.vname && this.game.vname == "") |
| 123 | this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name; |
| 124 | }, |
| 125 | }, |
| 126 | created: function() { |
| 127 | if (!!this.$route.params["id"]) |
| 128 | { |
| 129 | this.gameRef.id = this.$route.params["id"]; |
| 130 | this.gameRef.rid = this.$route.query["rid"]; |
| 131 | this.loadGame(); |
| 132 | } |
| 133 | // TODO: onopen, ask lastState informations + update observers and players status |
| 134 | const socketCloseListener = () => { |
| 135 | store.socketCloseListener(); //reinitialize connexion (in store.js) |
| 136 | this.st.conn.addEventListener('message', this.socketMessageListener); |
| 137 | this.st.conn.addEventListener('close', socketCloseListener); |
| 138 | }; |
| 139 | this.st.conn.onmessage = this.socketMessageListener; |
| 140 | this.st.conn.onclose = socketCloseListener; |
| 141 | }, |
| 142 | methods: { |
| 143 | socketMessageListener: function(msg) { |
| 144 | const data = JSON.parse(msg.data); |
| 145 | switch (data.code) |
| 146 | { |
| 147 | case "newmove": |
| 148 | // NOTE: next call will trigger processMove() |
| 149 | this.$refs["basegame"].play(data.move, |
| 150 | "receive", this.game.vname!="Dark" ? "animate" : null); |
| 151 | break; |
| 152 | case "pong": //received if we sent a ping (game still alive on our side) |
| 153 | { |
| 154 | this.oppConnected = true; |
| 155 | if (this.game.type == "live") //corr games are always complete |
| 156 | { |
| 157 | // Send our "last state" informations to opponent(s) |
| 158 | const L = this.game.moves.length; |
| 159 | this.st.conn.send(JSON.stringify({ |
| 160 | code: "lastate", |
| 161 | target: this.game.oppid, |
| 162 | gameId: this.gameRef.id, |
| 163 | lastMove: (L>0 ? this.game.moves[L-1] : undefined), |
| 164 | score: this.game.score, |
| 165 | movesCount: L, |
| 166 | drawOffer: this.drawOffer, |
| 167 | clocks: this.game.clocks, |
| 168 | })); |
| 169 | } |
| 170 | break; |
| 171 | } |
| 172 | case "lastate": //got opponent infos about last move |
| 173 | { |
| 174 | const L = this.game.moves.length; |
| 175 | if (this.gameRef.id != data.gameId) |
| 176 | break; //games IDs don't match: nothing we can do... |
| 177 | // OK, opponent still in game (which might be over) |
| 178 | if (data.movesCount > L) |
| 179 | { |
| 180 | // Just got last move from him |
| 181 | this.$refs["basegame"].play(data.lastMove, "receive"); |
| 182 | if (data.score != "*" && this.game.score == "*") |
| 183 | { |
| 184 | // Opponent resigned or aborted game, or accepted draw offer |
| 185 | // (this is not a stalemate or checkmate) |
| 186 | this.$refs["basegame"].endGame(data.score, "Opponent action"); |
| 187 | } |
| 188 | this.game.clocks = data.clocks; |
| 189 | this.drawOffer = data.drawOffer; |
| 190 | } |
| 191 | else if (data.movesCount < L) |
| 192 | { |
| 193 | // We must tell last move to opponent |
| 194 | this.st.conn.send(JSON.stringify({ |
| 195 | code: "lastate", |
| 196 | target: this.game.oppid, |
| 197 | gameId: this.gameRef.id, |
| 198 | lastMove: (L>0 ? this.game.moves[L-1] : undefined), |
| 199 | score: this.game.score, |
| 200 | movesCount: L, |
| 201 | drawOffer: this.drawOffer, |
| 202 | clocks: this.game.clocks, |
| 203 | })); |
| 204 | } |
| 205 | break; |
| 206 | } |
| 207 | case "resign": |
| 208 | this.$refs["basegame"].endGame( |
| 209 | this.game.mycolor=="w" ? "1-0" : "0-1", "Resign"); |
| 210 | break; |
| 211 | case "timeover": |
| 212 | this.$refs["basegame"].endGame( |
| 213 | this.game.mycolor=="w" ? "1-0" : "0-1", "Time"); |
| 214 | break; |
| 215 | case "abort": |
| 216 | this.$refs["basegame"].endGame("?", "Abort: " + data.msg); |
| 217 | break; |
| 218 | case "draw": |
| 219 | this.$refs["basegame"].endGame("1/2", "Mutual agreement"); |
| 220 | break; |
| 221 | case "drawoffer": |
| 222 | this.drawOffer = "received"; |
| 223 | break; |
| 224 | case "askfullgame": |
| 225 | // TODO: just give game; observers are listed here anyway: |
| 226 | // gameconnect? |
| 227 | break; |
| 228 | // TODO: drawaccepted (click draw button before sending move ==> draw offer in move) |
| 229 | // ==> on "newmove", check "drawOffer" field |
| 230 | // TODO: also use (dis)connect info to count online players? |
| 231 | case "gameconnect": |
| 232 | case "gamedisconnect": |
| 233 | const online = (data.code == "gameconnect"); |
| 234 | // If this is an opponent ? |
| 235 | if (this.game.oppid == data.id) |
| 236 | this.oppConnected = true; |
| 237 | else |
| 238 | { |
| 239 | // Or an observer ? |
| 240 | if (!online) |
| 241 | delete this.people[data.id]; |
| 242 | else |
| 243 | this.people[data.id] = data.name; |
| 244 | } |
| 245 | break; |
| 246 | } |
| 247 | }, |
| 248 | offerDraw: function() { |
| 249 | // TODO: also for corr games |
| 250 | if (this.drawOffer == "received") |
| 251 | { |
| 252 | if (!confirm("Accept draw?")) |
| 253 | return; |
| 254 | this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid})); |
| 255 | this.$refs["basegame"].endGame("1/2", "Mutual agreement"); |
| 256 | } |
| 257 | else if (this.drawOffer == "sent") |
| 258 | this.drawOffer = ""; |
| 259 | else |
| 260 | { |
| 261 | if (!confirm("Offer draw?")) |
| 262 | return; |
| 263 | this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid})); |
| 264 | } |
| 265 | }, |
| 266 | // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true) |
| 267 | receiveDrawOffer: function() { |
| 268 | //if (...) |
| 269 | // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers" |
| 270 | // if accept: send message "draw" |
| 271 | }, |
| 272 | abortGame: function(event) { |
| 273 | let modalBox = document.getElementById("modalAbort"); |
| 274 | if (!event) |
| 275 | { |
| 276 | // First call show options: |
| 277 | modalBox.checked = true; |
| 278 | } |
| 279 | else |
| 280 | { |
| 281 | modalBox.checked = false; //decision made: box disappear |
| 282 | const message = event.target.innerText; |
| 283 | // Next line will trigger a "gameover" event, bubbling up till here |
| 284 | this.$refs["basegame"].endGame("?", "Abort: " + message); |
| 285 | this.st.conn.send(JSON.stringify({ |
| 286 | code: "abort", |
| 287 | msg: message, |
| 288 | target: this.game.oppid, |
| 289 | })); |
| 290 | } |
| 291 | }, |
| 292 | resign: function(e) { |
| 293 | if (!confirm("Resign the game?")) |
| 294 | return; |
| 295 | this.st.conn.send(JSON.stringify({ |
| 296 | code: "resign", |
| 297 | target: this.game.oppid, |
| 298 | })); |
| 299 | // Next line will trigger a "gameover" event, bubbling up till here |
| 300 | this.$refs["basegame"].endGame( |
| 301 | this.game.mycolor=="w" ? "0-1" : "1-0", "Resign"); |
| 302 | }, |
| 303 | // 3 cases for loading a game: |
| 304 | // - from indexedDB (running or completed live game I play) |
| 305 | // - from server (one correspondance game I play[ed] or not) |
| 306 | // - from remote peer (one live game I don't play, finished or not) |
| 307 | loadGame: function(game) { |
| 308 | const afterRetrieval = async (game) => { |
| 309 | // NOTE: variants array might not be available yet, thus the two next lines |
| 310 | const variantCell = this.st.variants.filter(v => v.id == game.vid); |
| 311 | const vname = (variantCell.length > 0 ? variantCell[0].name : ""); |
| 312 | if (!game.fen) |
| 313 | game.fen = game.fenStart; //game wasn't started |
| 314 | const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live"); |
| 315 | if (gtype == "corr") |
| 316 | { |
| 317 | // corr game: needs to compute the clocks + initime |
| 318 | //if (game.players[i].rtime < 0) initime = Date.now(), else compute, |
| 319 | //also using move.played fields |
| 320 | game.clocks = [-1, -1]; |
| 321 | game.initime = [0, 0]; |
| 322 | // TODO: compute clocks + initime |
| 323 | } |
| 324 | const tc = extractTime(game.timeControl); |
| 325 | // TODO: this is not really beautiful (uid on corr players...) |
| 326 | if (gtype == "corr" && game.players[0].color == "b") |
| 327 | [ game.players[0], game.players[1] ] = [ game.players[1], game.players[0] ]; |
| 328 | const myIdx = game.players.findIndex(p => { |
| 329 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 330 | }); |
| 331 | if (game.clocks[0] < 0) //game unstarted |
| 332 | { |
| 333 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 334 | game.initime[0] = Date.now(); |
| 335 | if (myIdx >= 0 && gtype == "live") |
| 336 | { |
| 337 | // I play in this live game; corr games don't have clocks+initime |
| 338 | GameStorage.update(game.id, |
| 339 | { |
| 340 | clocks: game.clocks, |
| 341 | initime: game.initime, |
| 342 | }); |
| 343 | } |
| 344 | } |
| 345 | const vModule = await import("@/variants/" + vname + ".js"); |
| 346 | window.V = vModule.VariantRules; |
| 347 | this.vr = new V(game.fen); |
| 348 | |
| 349 | |
| 350 | |
| 351 | //TODO: people, on connect, search for opponent....... |
| 352 | console.log(myIdx + " " + game.players[1-myIdx].sid); //otherwise this is undefined: |
| 353 | |
| 354 | |
| 355 | |
| 356 | this.game = Object.assign({}, |
| 357 | game, |
| 358 | // NOTE: assign mycolor here, since BaseGame could also be VS computer |
| 359 | { |
| 360 | type: gtype, |
| 361 | increment: tc.increment, |
| 362 | vname: vname, |
| 363 | mycolor: [undefined,"w","b"][myIdx+1], |
| 364 | // opponent sid not strictly required, but easier |
| 365 | oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid), |
| 366 | } |
| 367 | ); |
| 368 | if (!!this.game.oppid) |
| 369 | { |
| 370 | // Send ping to server (answer pong if players[s] are connected) |
| 371 | this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid})); |
| 372 | } |
| 373 | }; |
| 374 | if (!!game) |
| 375 | return afterRetrival(game); |
| 376 | if (!!this.gameRef.rid) |
| 377 | { |
| 378 | this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid})); |
| 379 | // TODO: just send a game request message to the remote player, |
| 380 | // and when receiving answer just call loadGame(received_game) |
| 381 | // + remote peer should have registered us as an observer |
| 382 | // (send moves updates + resign/abort/draw actions) |
| 383 | } |
| 384 | else |
| 385 | { |
| 386 | GameStorage.get(this.gameRef.id, async (game) => { |
| 387 | afterRetrieval(game); |
| 388 | }); |
| 389 | } |
| 390 | }, |
| 391 | // Post-process a move (which was just played) |
| 392 | processMove: function(move) { |
| 393 | if (!this.game.mycolor) |
| 394 | return; //I'm just an observer |
| 395 | // Update storage (corr or live) |
| 396 | const colorIdx = ["w","b"].indexOf(move.color); |
| 397 | // https://stackoverflow.com/a/38750895 |
| 398 | const allowed_fields = ["appear", "vanish", "start", "end"]; |
| 399 | const filtered_move = Object.keys(move) |
| 400 | .filter(key => allowed_fields.includes(key)) |
| 401 | .reduce((obj, key) => { |
| 402 | obj[key] = move[key]; |
| 403 | return obj; |
| 404 | }, {}); |
| 405 | // Send move ("newmove" event) to opponent(s) (if ours) |
| 406 | let addTime = 0; |
| 407 | if (move.color == this.game.mycolor) |
| 408 | { |
| 409 | if (this.game.moves.length >= 2) //after first move |
| 410 | { |
| 411 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
| 412 | // elapsed time is measured in milliseconds |
| 413 | addTime = this.game.increment - elapsed/1000; |
| 414 | } |
| 415 | this.st.conn.send(JSON.stringify({ |
| 416 | code: "newmove", |
| 417 | target: this.game.oppid, |
| 418 | move: Object.assign({}, filtered_move, {addTime: addTime}), |
| 419 | })); |
| 420 | } |
| 421 | else |
| 422 | addTime = move.addTime; //supposed transmitted |
| 423 | const nextIdx = ["w","b"].indexOf(this.vr.turn); |
| 424 | GameStorage.update(this.gameRef.id, |
| 425 | { |
| 426 | move: filtered_move, |
| 427 | fen: move.fen, |
| 428 | clocks: this.game.clocks.map((t,i) => i==colorIdx |
| 429 | ? this.game.clocks[i] + addTime |
| 430 | : this.game.clocks[i]), |
| 431 | initime: this.game.initime.map((t,i) => i==nextIdx |
| 432 | ? Date.now() |
| 433 | : this.game.initime[i]), |
| 434 | }); |
| 435 | // Also update current game object: |
| 436 | this.game.moves.push(move); |
| 437 | this.game.fen = move.fen; |
| 438 | //TODO: just this.game.clocks[colorIdx] += addTime; |
| 439 | this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime); |
| 440 | this.game.initime[nextIdx] = Date.now(); |
| 441 | }, |
| 442 | // TODO: this update function should also work for corr games |
| 443 | gameOver: function(score) { |
| 444 | this.game.mode = "analyze"; |
| 445 | this.game.score = score; |
| 446 | GameStorage.update(this.gameRef.id, { score: score }); |
| 447 | }, |
| 448 | }, |
| 449 | }; |
| 450 | </script> |
| 451 | |
| 452 | <style lang="sass"> |
| 453 | // TODO |
| 454 | </style> |