| 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, |
| 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 | const currentTurn = this.vr.turn; |
| 83 | const colorIdx = ["w","b"].indexOf(currentTurn); |
| 84 | let countdown = newState[colorIdx] - |
| 85 | (Date.now() - this.game.initime[colorIdx])/1000; |
| 86 | this.virtualClocks = [0,1].map(i => { |
| 87 | const removeTime = i == colorIdx |
| 88 | ? (Date.now() - this.game.initime[colorIdx])/1000 |
| 89 | : 0; |
| 90 | return ppt(newState[i] - removeTime); |
| 91 | }); |
| 92 | const myTurn = (currentTurn == this.game.mycolor); |
| 93 | let clockUpdate = setInterval(() => { |
| 94 | if (countdown <= 0 || this.vr.turn != currentTurn) |
| 95 | { |
| 96 | clearInterval(clockUpdate); |
| 97 | if (countdown <= 0 && myTurn) |
| 98 | { |
| 99 | this.$refs["basegame"].endGame( |
| 100 | this.game.mycolor=="w" ? "0-1" : "1-0", "Time"); |
| 101 | this.st.conn.send(JSON.stringify({ |
| 102 | code: "timeover", |
| 103 | target: this.game.oppid, |
| 104 | })); |
| 105 | } |
| 106 | } |
| 107 | else |
| 108 | { |
| 109 | // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown) |
| 110 | this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown))); |
| 111 | } |
| 112 | }, 1000); |
| 113 | }, |
| 114 | // In case variants array was't loaded when game was retrieved |
| 115 | "st.variants": function(variantArray) { |
| 116 | if (!!this.game.vname && this.game.vname == "") |
| 117 | this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name; |
| 118 | }, |
| 119 | }, |
| 120 | created: function() { |
| 121 | if (!!this.$route.params["id"]) |
| 122 | { |
| 123 | this.gameRef.id = this.$route.params["id"]; |
| 124 | this.gameRef.rid = this.$route.query["rid"]; |
| 125 | this.loadGame(); |
| 126 | } |
| 127 | // TODO: onopen, ask lastState informations + update observers and players status |
| 128 | const socketCloseListener = () => { |
| 129 | store.socketCloseListener(); //reinitialize connexion (in store.js) |
| 130 | this.st.conn.addEventListener('message', this.socketMessageListener); |
| 131 | this.st.conn.addEventListener('close', socketCloseListener); |
| 132 | }; |
| 133 | this.st.conn.onmessage = this.socketMessageListener; |
| 134 | this.st.conn.onclose = socketCloseListener; |
| 135 | }, |
| 136 | methods: { |
| 137 | socketMessageListener: function(msg) { |
| 138 | const data = JSON.parse(msg.data); |
| 139 | switch (data.code) |
| 140 | { |
| 141 | case "newmove": |
| 142 | // NOTE: next call will trigger processMove() |
| 143 | this.$refs["basegame"].play(data.move, |
| 144 | "receive", this.game.vname!="Dark" ? "animate" : null); |
| 145 | break; |
| 146 | case "pong": //received if we sent a ping (game still alive on our side) |
| 147 | { |
| 148 | this.oppConnected = true; |
| 149 | // Send our "last state" informations to opponent(s) |
| 150 | const L = this.game.moves.length; |
| 151 | this.st.conn.send(JSON.stringify({ |
| 152 | code: "lastate", |
| 153 | target: this.game.oppid, |
| 154 | gameId: this.gameRef.id, |
| 155 | lastMove: (L>0 ? this.game.moves[L-1] : undefined), |
| 156 | score: this.game.score, |
| 157 | movesCount: L, |
| 158 | drawOffer: this.drawOffer, |
| 159 | clocks: this.game.clocks, |
| 160 | })); |
| 161 | break; |
| 162 | } |
| 163 | case "lastate": //got opponent infos about last move |
| 164 | { |
| 165 | const L = this.game.moves.length; |
| 166 | if (this.gameRef.id != data.gameId) |
| 167 | break; //games IDs don't match: nothing we can do... |
| 168 | // OK, opponent still in game (which might be over) |
| 169 | if (data.movesCount > L) |
| 170 | { |
| 171 | // Just got last move from him |
| 172 | this.$refs["basegame"].play(data.lastMove, "receive"); |
| 173 | if (data.score != "*" && this.game.score == "*") |
| 174 | { |
| 175 | // Opponent resigned or aborted game, or accepted draw offer |
| 176 | // (this is not a stalemate or checkmate) |
| 177 | this.$refs["basegame"].endGame(data.score, "Opponent action"); |
| 178 | } |
| 179 | this.game.clocks = data.clocks; |
| 180 | this.drawOffer = data.drawOffer; |
| 181 | } |
| 182 | else if (data.movesCount < L) |
| 183 | { |
| 184 | // We must tell last move to opponent |
| 185 | this.st.conn.send(JSON.stringify({ |
| 186 | code: "lastate", |
| 187 | target: this.game.oppid, |
| 188 | gameId: this.gameRef.id, |
| 189 | lastMove: (L>0 ? this.game.moves[L-1] : undefined), |
| 190 | score: this.game.score, |
| 191 | movesCount: L, |
| 192 | drawOffer: this.drawOffer, |
| 193 | clocks: this.game.clocks, |
| 194 | })); |
| 195 | } |
| 196 | break; |
| 197 | } |
| 198 | case "resign": |
| 199 | this.$refs["basegame"].endGame( |
| 200 | this.game.mycolor=="w" ? "1-0" : "0-1", "Resign"); |
| 201 | break; |
| 202 | case "timeover": |
| 203 | this.$refs["basegame"].endGame( |
| 204 | this.game.mycolor=="w" ? "1-0" : "0-1", "Time"); |
| 205 | break; |
| 206 | case "abort": |
| 207 | this.$refs["basegame"].endGame("?", "Abort: " + data.msg); |
| 208 | break; |
| 209 | case "draw": |
| 210 | this.$refs["basegame"].endGame("1/2", "Mutual agreement"); |
| 211 | break; |
| 212 | case "drawoffer": |
| 213 | this.drawOffer = "received"; |
| 214 | break; |
| 215 | case "askfullgame": |
| 216 | // TODO: just give game; observers are listed here anyway: |
| 217 | // gameconnect? |
| 218 | break; |
| 219 | // TODO: drawaccepted (click draw button before sending move ==> draw offer in move) |
| 220 | // ==> on "newmove", check "drawOffer" field |
| 221 | // TODO: also use (dis)connect info to count online players? |
| 222 | case "gameconnect": |
| 223 | case "gamedisconnect": |
| 224 | const online = (data.code == "gameconnect"); |
| 225 | // If this is an opponent ? |
| 226 | if (this.game.oppid == data.id) |
| 227 | this.oppConnected = true; |
| 228 | else |
| 229 | { |
| 230 | // Or an observer ? |
| 231 | if (!online) |
| 232 | delete this.people[data.id]; |
| 233 | else |
| 234 | this.people[data.id] = data.name; |
| 235 | } |
| 236 | break; |
| 237 | } |
| 238 | }, |
| 239 | offerDraw: function() { |
| 240 | // TODO: also for corr games |
| 241 | if (this.drawOffer == "received") |
| 242 | { |
| 243 | if (!confirm("Accept draw?")) |
| 244 | return; |
| 245 | this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid})); |
| 246 | this.$refs["basegame"].endGame("1/2", "Mutual agreement"); |
| 247 | } |
| 248 | else if (this.drawOffer == "sent") |
| 249 | this.drawOffer = ""; |
| 250 | else |
| 251 | { |
| 252 | if (!confirm("Offer draw?")) |
| 253 | return; |
| 254 | this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid})); |
| 255 | } |
| 256 | }, |
| 257 | // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true) |
| 258 | receiveDrawOffer: function() { |
| 259 | //if (...) |
| 260 | // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers" |
| 261 | // if accept: send message "draw" |
| 262 | }, |
| 263 | abortGame: function(event) { |
| 264 | let modalBox = document.getElementById("modalAbort"); |
| 265 | if (!event) |
| 266 | { |
| 267 | // First call show options: |
| 268 | modalBox.checked = true; |
| 269 | } |
| 270 | else |
| 271 | { |
| 272 | modalBox.checked = false; //decision made: box disappear |
| 273 | const message = event.target.innerText; |
| 274 | // Next line will trigger a "gameover" event, bubbling up till here |
| 275 | this.$refs["basegame"].endGame("?", "Abort: " + message); |
| 276 | this.st.conn.send(JSON.stringify({ |
| 277 | code: "abort", |
| 278 | msg: message, |
| 279 | target: this.game.oppid, |
| 280 | })); |
| 281 | } |
| 282 | }, |
| 283 | resign: function(e) { |
| 284 | if (!confirm("Resign the game?")) |
| 285 | return; |
| 286 | this.st.conn.send(JSON.stringify({ |
| 287 | code: "resign", |
| 288 | target: this.game.oppid, |
| 289 | })); |
| 290 | // Next line will trigger a "gameover" event, bubbling up till here |
| 291 | this.$refs["basegame"].endGame( |
| 292 | this.game.mycolor=="w" ? "0-1" : "1-0", "Resign"); |
| 293 | }, |
| 294 | // 3 cases for loading a game: |
| 295 | // - from indexedDB (running or completed live game I play) |
| 296 | // - from server (one correspondance game I play[ed] or not) |
| 297 | // - from remote peer (one live game I don't play, finished or not) |
| 298 | loadGame: function(game) { |
| 299 | const afterRetrieval = async (game) => { |
| 300 | // NOTE: variants array might not be available yet, thus the two next lines |
| 301 | const variantCell = this.st.variants.filter(v => v.id == game.vid); |
| 302 | const vname = (variantCell.length > 0 ? variantCell[0].name : ""); |
| 303 | if (!game.fen) |
| 304 | game.fen = game.fenStart; //game wasn't started |
| 305 | const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live"); |
| 306 | if (gtype == "corr") |
| 307 | { |
| 308 | // corr game: needs to compute the clocks + initime |
| 309 | //if (game.players[i].rtime < 0) initime = Date.now(), else compute, |
| 310 | //also using move.played fields |
| 311 | game.clocks = [-1, -1]; |
| 312 | game.initime = [0, 0]; |
| 313 | // TODO: compute clocks + initime |
| 314 | } |
| 315 | const tc = extractTime(game.timeControl); |
| 316 | const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid); |
| 317 | if (game.clocks[0] < 0) //game unstarted |
| 318 | { |
| 319 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 320 | game.initime[0] = Date.now(); |
| 321 | if (myIdx >= 0) //I play in this game |
| 322 | { |
| 323 | GameStorage.update(game.gameId, |
| 324 | { |
| 325 | clocks: game.clocks, |
| 326 | initime: game.initime, |
| 327 | }); |
| 328 | } |
| 329 | } |
| 330 | const vModule = await import("@/variants/" + vname + ".js"); |
| 331 | window.V = vModule.VariantRules; |
| 332 | this.vr = new V(game.fen); |
| 333 | this.game = Object.assign({}, |
| 334 | game, |
| 335 | // NOTE: assign mycolor here, since BaseGame could also bs VS computer |
| 336 | { |
| 337 | type: gtype, |
| 338 | increment: tc.increment, |
| 339 | vname: vname, |
| 340 | mycolor: [undefined,"w","b"][myIdx+1], |
| 341 | // opponent sid not strictly required, but easier |
| 342 | oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid), |
| 343 | } |
| 344 | ); |
| 345 | if (!!this.game.oppid) |
| 346 | { |
| 347 | // Send ping to server (answer pong if players[s] are connected) |
| 348 | this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid})); |
| 349 | } |
| 350 | }; |
| 351 | if (!!game) |
| 352 | return afterRetrival(game); |
| 353 | if (!!this.gameRef.rid) |
| 354 | { |
| 355 | this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid})); |
| 356 | // TODO: just send a game request message to the remote player, |
| 357 | // and when receiving answer just call loadGame(received_game) |
| 358 | // + remote peer should have registered us as an observer |
| 359 | // (send moves updates + resign/abort/draw actions) |
| 360 | } |
| 361 | else |
| 362 | { |
| 363 | GameStorage.get(this.gameRef.id, async (game) => { |
| 364 | afterRetrieval(game); |
| 365 | }); |
| 366 | } |
| 367 | }, |
| 368 | // Post-process a move (which was just played) |
| 369 | processMove: function(move) { |
| 370 | if (!this.game.mycolor) |
| 371 | return; //I'm just an observer |
| 372 | // Update storage (corr or live) |
| 373 | const colorIdx = ["w","b"].indexOf(move.color); |
| 374 | // https://stackoverflow.com/a/38750895 |
| 375 | const allowed_fields = ["appear", "vanish", "start", "end"]; |
| 376 | const filtered_move = Object.keys(move) |
| 377 | .filter(key => allowed_fields.includes(key)) |
| 378 | .reduce((obj, key) => { |
| 379 | obj[key] = move[key]; |
| 380 | return obj; |
| 381 | }, {}); |
| 382 | // Send move ("newmove" event) to opponent(s) (if ours) |
| 383 | let addTime = undefined; |
| 384 | if (move.color == this.game.mycolor) |
| 385 | { |
| 386 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
| 387 | // elapsed time is measured in milliseconds |
| 388 | addTime = this.game.increment - elapsed/1000; |
| 389 | this.st.conn.send(JSON.stringify({ |
| 390 | code: "newmove", |
| 391 | target: this.game.oppid, |
| 392 | move: Object.assign({}, filtered_move, {addTime: addTime}), |
| 393 | })); |
| 394 | } |
| 395 | else |
| 396 | addTime = move.addTime; //supposed transmitted |
| 397 | const nextIdx = ["w","b"].indexOf(this.vr.turn); |
| 398 | GameStorage.update(this.gameRef.id, |
| 399 | { |
| 400 | move: filtered_move, |
| 401 | fen: move.fen, |
| 402 | clocks: this.game.clocks.map((t,i) => i==colorIdx |
| 403 | ? this.game.clocks[i] + addTime |
| 404 | : this.game.clocks[i]), |
| 405 | initime: this.game.initime.map((t,i) => i==nextIdx |
| 406 | ? Date.now() |
| 407 | : this.game.initime[i]), |
| 408 | }); |
| 409 | // Also update current game object: |
| 410 | this.game.moves.push(move); |
| 411 | this.game.fen = move.fen; |
| 412 | //TODO: just this.game.clocks[colorIdx] += addTime; |
| 413 | this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime); |
| 414 | this.game.initime[nextIdx] = Date.now(); |
| 415 | }, |
| 416 | // TODO: this update function should also work for corr games |
| 417 | gameOver: function(score) { |
| 418 | this.game.mode = "analyze"; |
| 419 | GameStorage.update(this.gameRef.id, { score: score }); |
| 420 | }, |
| 421 | }, |
| 422 | }; |
| 423 | </script> |
| 424 | |
| 425 | <style lang="sass"> |
| 426 | // TODO |
| 427 | </style> |