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