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