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/gameStorage";
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 // 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({},
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)]},
270 return afterRetrival(game);
271 if (!!this.gameRef.rid)
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)
281 GameStorage.get(this.gameRef.id, async (game) => {
282 afterRetrieval(game);
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))
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}));
295 // TODO: refactor this old "oppConnected" logic
296 // oppConnected: function(uid) {
297 // return this.opponents.some(o => o.id == uid && o.online);
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];
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)
318 const elapsed = Date.now() - this.game.initime;
319 this.game.players.forEach(p => {
320 if (p.sid != this.st.user.sid)
322 this.st.conn.send(JSON.stringify({
325 move: Object.assign({}, filtered_move, {elapsed: elapsed}),
329 move.elapsed = elapsed;
330 // elapsed time is measured in milliseconds
331 addTime = this.game.increment - elapsed/1000;
333 const myTurnNow = (this.vr.turn == this.game.mycolor);
334 GameStorage.update(this.gameRef.id,
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);
348 // TODO: this update function should also work for corr games
349 gameOver: function(score) {
350 this.game.mode = "analyze";