| 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 | .button-group(v-if="game.mode!='analyze' && game.score=='*'") |
| 15 | button(@click="offerDraw") Draw |
| 16 | button(@click="() => abortGame()") Abort |
| 17 | button(@click="resign") Resign |
| 18 | div(v-if="game.mode=='corr'") |
| 19 | textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg") |
| 20 | div(v-show="cursor>=0") {{ moves[cursor].message }} |
| 21 | </template> |
| 22 | |
| 23 | <script> |
| 24 | import BaseGame from "@/components/BaseGame.vue"; |
| 25 | //import Chat from "@/components/Chat.vue"; |
| 26 | //import MoveList from "@/components/MoveList.vue"; |
| 27 | import { store } from "@/store"; |
| 28 | import { GameStorage } from "@/utils/gameStorage"; |
| 29 | |
| 30 | export default { |
| 31 | name: 'my-game', |
| 32 | components: { |
| 33 | BaseGame, |
| 34 | }, |
| 35 | // gameRef: to find the game in (potentially remote) storage |
| 36 | data: function() { |
| 37 | return { |
| 38 | st: store.state, |
| 39 | gameRef: { //given in URL (rid = remote ID) |
| 40 | id: "", |
| 41 | rid: "" |
| 42 | }, |
| 43 | game: { }, //passed to BaseGame |
| 44 | vr: null, //"variant rules" object initialized from FEN |
| 45 | drawOfferSent: false, //did I just ask for draw? (TODO: use for button style) |
| 46 | people: [ ], //potential observers (TODO) |
| 47 | }; |
| 48 | }, |
| 49 | watch: { |
| 50 | '$route' (to, from) { |
| 51 | if (!!to.params["id"]) |
| 52 | { |
| 53 | this.gameRef.id = to.params["id"]; |
| 54 | this.gameRef.rid = to.query["rid"]; |
| 55 | this.loadGame(); |
| 56 | } |
| 57 | }, |
| 58 | }, |
| 59 | created: function() { |
| 60 | if (!!this.$route.params["id"]) |
| 61 | { |
| 62 | this.gameRef.id = this.$route.params["id"]; |
| 63 | this.gameRef.rid = this.$route.query["rid"]; |
| 64 | this.loadGame(); |
| 65 | } |
| 66 | // TODO: how to know who is observing ? Send message to everyone with game ID ? |
| 67 | // and then just listen to (dis)connect events |
| 68 | // server always send "connect on " + URL ; then add to observers if game... |
| 69 | // detect multiple tabs connected (when connect ask server if my SID is already in use) |
| 70 | // router when access a game page tell to server I joined + game ID (no need rid) |
| 71 | // and ask server for current joined (= observers) |
| 72 | // when send to chat (or a move), reach only this group (send gid along) |
| 73 | // --> doivent être enregistrés comme observers au niveau du serveur... |
| 74 | // non: poll users + events startObserving / stopObserving |
| 75 | // (à faire au niveau du routeur ?) |
| 76 | |
| 77 | // TODO: also handle "draw accepted" (use opponents array?) |
| 78 | // --> must give this info also when sending lastState... |
| 79 | // and, if all players agree then OK draw (end game ...etc) |
| 80 | const socketMessageListener = msg => { |
| 81 | const data = JSON.parse(msg.data); |
| 82 | let L = undefined; |
| 83 | switch (data.code) |
| 84 | { |
| 85 | case "newmove": |
| 86 | // NOTE: next call will trigger processMove() |
| 87 | this.$refs["basegame"].play(data.move, |
| 88 | "receive", this.game.vname!="Dark" ? "animate" : null); |
| 89 | break; |
| 90 | case "pong": //received if we sent a ping (game still alive on our side) |
| 91 | if (this.gameRef.id != data.gameId) |
| 92 | break; //games IDs don't match: the game is definitely over... |
| 93 | this.oppConnected = true; |
| 94 | // Send our "last state" informations to opponent(s) |
| 95 | L = this.vr.moves.length; |
| 96 | Object.keys(this.opponents).forEach(oid => { |
| 97 | this.st.conn.send(JSON.stringify({ |
| 98 | code: "lastate", |
| 99 | oppid: oid, |
| 100 | gameId: this.gameRef.id, |
| 101 | lastMove: (L>0?this.vr.moves[L-1]:undefined), |
| 102 | movesCount: L, |
| 103 | })); |
| 104 | }); |
| 105 | break; |
| 106 | // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves |
| 107 | // TODO: need to send along clock state (my current time) with my last move |
| 108 | case "lastate": //got opponent infos about last move |
| 109 | L = this.vr.moves.length; |
| 110 | if (this.gameRef.id != data.gameId) |
| 111 | break; //games IDs don't match: nothing we can do... |
| 112 | // OK, opponent still in game (which might be over) |
| 113 | if (this.score != "*") |
| 114 | { |
| 115 | // We finished the game (any result possible) |
| 116 | this.st.conn.send(JSON.stringify({ |
| 117 | code: "lastate", |
| 118 | oppid: data.oppid, |
| 119 | gameId: this.gameRef.id, |
| 120 | score: this.score, |
| 121 | })); |
| 122 | } |
| 123 | else if (!!data.score) //opponent finished the game |
| 124 | this.endGame(data.score); |
| 125 | else if (data.movesCount < L) |
| 126 | { |
| 127 | // We must tell last move to opponent |
| 128 | this.st.conn.send(JSON.stringify({ |
| 129 | code: "lastate", |
| 130 | oppid: this.opponent.id, |
| 131 | gameId: this.gameRef.id, |
| 132 | lastMove: this.vr.moves[L-1], |
| 133 | movesCount: L, |
| 134 | })); |
| 135 | } |
| 136 | else if (data.movesCount > L) //just got last move from him |
| 137 | this.play(data.lastMove, "animate"); //TODO: wrong call (3 args) |
| 138 | break; |
| 139 | case "resign": |
| 140 | this.$refs["basegame"].endGame( |
| 141 | this.game.mycolor=="w" ? "1-0" : "0-1", "Resign"); |
| 142 | break; |
| 143 | case "timeover": |
| 144 | this.$refs["basegame"].endGame( |
| 145 | this.game.mycolor=="w" ? "1-0" : "0-1", "Time"); |
| 146 | break; |
| 147 | case "abort": |
| 148 | this.$refs["basegame"].endGame("?", "Abort: " + data.msg); |
| 149 | break; |
| 150 | // TODO: drawaccepted (click draw button before sending move ==> draw offer in move) |
| 151 | // ==> on "newmove", check "drawOffer" field |
| 152 | // TODO: also use (dis)connect info to count online players? |
| 153 | case "gameconnect": |
| 154 | case "gamedisconnect": |
| 155 | if (this.mode=="human") |
| 156 | { |
| 157 | const online = (data.code == "connect"); |
| 158 | // If this is an opponent ? |
| 159 | if (!!this.opponents[data.id]) |
| 160 | this.opponents[data.id].online = online; |
| 161 | else |
| 162 | { |
| 163 | // Or an observer ? |
| 164 | if (!online) |
| 165 | delete this.people[data.id]; |
| 166 | else |
| 167 | this.people[data.id] = data.name; |
| 168 | } |
| 169 | } |
| 170 | break; |
| 171 | } |
| 172 | }; |
| 173 | const socketCloseListener = () => { |
| 174 | this.st.conn.addEventListener('message', socketMessageListener); |
| 175 | this.st.conn.addEventListener('close', socketCloseListener); |
| 176 | }; |
| 177 | this.st.conn.onmessage = socketMessageListener; |
| 178 | this.st.conn.onclose = socketCloseListener; |
| 179 | }, |
| 180 | // dans variant.js (plutôt room.js) conn gère aussi les challenges |
| 181 | // et les chats dans chat.js. Puis en webRTC, repenser tout ça. |
| 182 | methods: { |
| 183 | offerDraw: function() { |
| 184 | if (!confirm("Offer draw?")) |
| 185 | return; |
| 186 | // Stay in "draw offer sent" state until next move is played |
| 187 | this.drawOfferSent = true; |
| 188 | if (this.subMode == "corr") |
| 189 | { |
| 190 | // TODO: set drawOffer on in game (how ?) |
| 191 | } |
| 192 | else //live game |
| 193 | { |
| 194 | this.opponents.forEach(o => { |
| 195 | if (!!o.online) |
| 196 | { |
| 197 | try { |
| 198 | this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id})); |
| 199 | } catch (INVALID_STATE_ERR) { |
| 200 | return; |
| 201 | } |
| 202 | } |
| 203 | }); |
| 204 | } |
| 205 | }, |
| 206 | // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true) |
| 207 | receiveDrawOffer: function() { |
| 208 | //if (...) |
| 209 | // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers" |
| 210 | // if accept: send message "draw" |
| 211 | }, |
| 212 | abortGame: function(event) { |
| 213 | if (!event) |
| 214 | { |
| 215 | // First call show options: |
| 216 | let modalBox = document.getElementById("modalAbort"); |
| 217 | modalBox.checked = true; |
| 218 | } |
| 219 | else |
| 220 | { |
| 221 | console.log(event); |
| 222 | return; |
| 223 | //const message = event. |
| 224 | // Next line will trigger a "gameover" event, bubbling up till here |
| 225 | this.$refs["basegame"].endGame("?"); |
| 226 | this.game.players.forEach(p => { |
| 227 | if (!!p.sid && p.sid != this.st.user.sid) |
| 228 | { |
| 229 | this.st.conn.send(JSON.stringify({ |
| 230 | code: "abort", |
| 231 | msg: message, |
| 232 | target: p.sid, |
| 233 | })); |
| 234 | } |
| 235 | }); |
| 236 | } |
| 237 | }, |
| 238 | resign: function(e) { |
| 239 | if (!confirm("Resign the game?")) |
| 240 | return; |
| 241 | this.game.players.forEach(p => { |
| 242 | if (!!p.sid && p.sid != this.st.user.sid) |
| 243 | { |
| 244 | this.st.conn.send(JSON.stringify({ |
| 245 | code: "resign", |
| 246 | target: p.sid, |
| 247 | })); |
| 248 | } |
| 249 | }); |
| 250 | // Next line will trigger a "gameover" event, bubbling up till here |
| 251 | this.$refs["basegame"].endGame(this.game.mycolor=="w" ? "0-1" : "1-0"); |
| 252 | }, |
| 253 | // 3 cases for loading a game: |
| 254 | // - from indexedDB (running or completed live game I play) |
| 255 | // - from server (one correspondance game I play[ed] or not) |
| 256 | // - from remote peer (one live game I don't play, finished or not) |
| 257 | loadGame: function(game) { |
| 258 | const afterRetrieval = async (game) => { |
| 259 | const vModule = await import("@/variants/" + game.vname + ".js"); |
| 260 | window.V = vModule.VariantRules; |
| 261 | this.vr = new V(game.fenStart); |
| 262 | this.game = Object.assign({}, |
| 263 | game, |
| 264 | // NOTE: assign mycolor here, since BaseGame could also bs VS computer |
| 265 | {mycolor: [undefined,"w","b"][1 + game.players.findIndex( |
| 266 | p => p.sid == this.st.user.sid)]}, |
| 267 | ); |
| 268 | }; |
| 269 | if (!!game) |
| 270 | return afterRetrival(game); |
| 271 | if (!!this.gameRef.rid) |
| 272 | { |
| 273 | // TODO: just send a game request message to the remote player, |
| 274 | // and when receiving answer just call loadGame(received_game) |
| 275 | // + remote peer should have registered us as an observer |
| 276 | // (send moves updates + resign/abort/draw actions) |
| 277 | return; |
| 278 | } |
| 279 | else |
| 280 | { |
| 281 | GameStorage.get(this.gameRef.id, async (game) => { |
| 282 | afterRetrieval(game); |
| 283 | }); |
| 284 | } |
| 285 | // // Poll all players except me (if I'm playing) to know online status. |
| 286 | // // --> Send ping to server (answer pong if players[s] are connected) |
| 287 | // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid)) |
| 288 | // { |
| 289 | // this.game.players.forEach(p => { |
| 290 | // if (p.sid != this.st.user.sid) |
| 291 | // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid})); |
| 292 | // }); |
| 293 | // } |
| 294 | }, |
| 295 | // TODO: refactor this old "oppConnected" logic |
| 296 | // oppConnected: function(uid) { |
| 297 | // return this.opponents.some(o => o.id == uid && o.online); |
| 298 | // }, |
| 299 | // Post-process a move (which was just played) |
| 300 | processMove: function(move) { |
| 301 | if (!this.game.mycolor) |
| 302 | return; //I'm just an observer |
| 303 | // Update storage (corr or live) |
| 304 | const colorIdx = ["w","b","g","r"].indexOf(move.color); |
| 305 | // https://stackoverflow.com/a/38750895 |
| 306 | const allowed_fields = ["appear", "vanish", "start", "end"]; |
| 307 | const filtered_move = Object.keys(move) |
| 308 | .filter(key => allowed_fields.includes(key)) |
| 309 | .reduce((obj, key) => { |
| 310 | obj[key] = move[key]; |
| 311 | return obj; |
| 312 | }, {}); |
| 313 | // Send move ("newmove" event) to opponent(s) (if ours) |
| 314 | // (otherwise move.elapsed is supposed to be already transmitted) |
| 315 | let addTime = undefined; |
| 316 | if (move.color == this.game.mycolor) |
| 317 | { |
| 318 | const elapsed = Date.now() - this.game.initime; |
| 319 | this.game.players.forEach(p => { |
| 320 | if (p.sid != this.st.user.sid) |
| 321 | { |
| 322 | this.st.conn.send(JSON.stringify({ |
| 323 | code: "newmove", |
| 324 | target: p.sid, |
| 325 | move: Object.assign({}, filtered_move, {elapsed: elapsed}), |
| 326 | })); |
| 327 | } |
| 328 | }); |
| 329 | move.elapsed = elapsed; |
| 330 | // elapsed time is measured in milliseconds |
| 331 | addTime = this.game.increment - elapsed/1000; |
| 332 | } |
| 333 | const myTurnNow = (this.vr.turn == this.game.mycolor); |
| 334 | GameStorage.update(this.gameRef.id, |
| 335 | { |
| 336 | colorIdx: colorIdx, |
| 337 | move: filtered_move, |
| 338 | fen: move.fen, |
| 339 | addTime: addTime, |
| 340 | initime: myTurnNow, |
| 341 | }); |
| 342 | // Also update current game object: |
| 343 | this.game.moves.push(move); |
| 344 | this.game.fen = move.fen; |
| 345 | this.game.clocks[colorIdx] += (!!addTime ? addTime : 0); |
| 346 | this.game.initime = (myTurnNow ? Date.now() : undefined); |
| 347 | }, |
| 348 | // TODO: this update function should also work for corr games |
| 349 | gameOver: function(score) { |
| 350 | this.game.mode = "analyze"; |
| 351 | GameStorage.update({ |
| 352 | score: score, |
| 353 | }); |
| 354 | }, |
| 355 | }, |
| 356 | }; |
| 357 | </script> |