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 }}
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/storage";
35 // gameRef: to find the game in (potentially remote) storage
39 gameRef: { //given in URL (rid = remote ID)
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)
51 if (!!to.params["id"])
53 this.gameRef.id = to.params["id"];
54 this.gameRef.rid = to.query["rid"];
60 if (!!this.$route.params["id"])
62 this.gameRef.id = this.$route.params["id"];
63 this.gameRef.rid = this.$route.query["rid"];
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 ?)
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);
86 // NOTE: next call will trigger processMove()
87 this.$refs["basegame"].play(data.move,
88 "receive", this.game.vname!="Dark" ? "animate" : null);
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({
100 gameId: this.gameRef.id,
101 lastMove: (L>0?this.vr.moves[L-1]:undefined),
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 != "*")
115 // We finished the game (any result possible)
116 this.st.conn.send(JSON.stringify({
119 gameId: this.gameRef.id,
123 else if (!!data.score) //opponent finished the game
124 this.endGame(data.score);
125 else if (data.movesCount < L)
127 // We must tell last move to opponent
128 this.st.conn.send(JSON.stringify({
130 oppid: this.opponent.id,
131 gameId: this.gameRef.id,
132 lastMove: this.vr.moves[L-1],
136 else if (data.movesCount > L) //just got last move from him
137 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
140 this.$refs["basegame"].endGame(
141 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
144 this.$refs["basegame"].endGame(
145 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
148 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
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?
154 case "gamedisconnect":
155 if (this.mode=="human")
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;
165 delete this.people[data.id];
167 this.people[data.id] = data.name;
173 const socketCloseListener = () => {
174 this.st.conn.addEventListener('message', socketMessageListener);
175 this.st.conn.addEventListener('close', socketCloseListener);
177 this.st.conn.onmessage = socketMessageListener;
178 this.st.conn.onclose = socketCloseListener;
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.
183 offerDraw: function() {
184 if (!confirm("Offer draw?"))
186 // Stay in "draw offer sent" state until next move is played
187 this.drawOfferSent = true;
188 if (this.subMode == "corr")
190 // TODO: set drawOffer on in game (how ?)
194 this.opponents.forEach(o => {
198 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
199 } catch (INVALID_STATE_ERR) {
206 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
207 receiveDrawOffer: function() {
209 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
210 // if accept: send message "draw"
212 abortGame: function(event) {
215 // First call show options:
216 let modalBox = document.getElementById("modalAbort");
217 modalBox.checked = true;
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)
229 this.st.conn.send(JSON.stringify({
238 resign: function(e) {
239 if (!confirm("Resign the game?"))
241 this.game.players.forEach(p => {
242 if (!!p.sid && p.sid != this.st.user.sid)
244 this.st.conn.send(JSON.stringify({
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");
253 // 4 cases for loading a game:
254 // - from localStorage (one running game I play)
255 // - from indexedDB (one completed live game)
256 // - from server (one correspondance game I play[ed] or not)
257 // - from remote peer (one live game I don't play, finished or not)
258 loadGame: function() {
259 GameStorage.get(this.gameRef, async (game) => {
260 const vModule = await import("@/variants/" + game.vname + ".js");
261 window.V = vModule.VariantRules;
262 this.vr = new V(game.fenStart);
263 this.game = Object.assign({},
265 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
266 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
267 p => p.sid == this.st.user.sid)]},
270 // // Poll all players except me (if I'm playing) to know online status.
271 // // --> Send ping to server (answer pong if players[s] are connected)
272 // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
274 // this.game.players.forEach(p => {
275 // if (p.sid != this.st.user.sid)
276 // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
280 // TODO: refactor this old "oppConnected" logic
281 // oppConnected: function(uid) {
282 // return this.opponents.some(o => o.id == uid && o.online);
284 // Post-process a move (which was just played)
285 processMove: function(move) {
286 if (!this.game.mycolor)
287 return; //I'm just an observer
288 // Update storage (corr or live)
289 const colorIdx = ["w","b","g","r"].indexOf(move.color);
290 // https://stackoverflow.com/a/38750895
291 const allowed_fields = ["appear", "vanish", "start", "end"];
292 const filtered_move = Object.keys(move)
293 .filter(key => allowed_fields.includes(key))
294 .reduce((obj, key) => {
295 obj[key] = move[key];
298 // Send move ("newmove" event) to opponent(s) (if ours)
299 // (otherwise move.elapsed is supposed to be already transmitted)
300 let addTime = undefined;
301 if (move.color == this.game.mycolor)
303 const elapsed = Date.now() - GameStorage.getInitime();
304 this.game.players.forEach(p => {
305 if (p.sid != this.st.user.sid)
307 this.st.conn.send(JSON.stringify({
310 move: Object.assign({}, filtered_move, {elapsed: elapsed}),
314 move.elapsed = elapsed;
315 // elapsed time is measured in milliseconds
316 addTime = this.game.increment - elapsed/1000;
323 initime: (this.vr.turn == this.game.mycolor), //my turn now?
326 // TODO: this update function should also work for corr games
327 gameOver: function(score) {
328 this.game.mode = "analyze";