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