Fix clocks update
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
b988c726
BA
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"] }}
b4fb1612
BA
12 BaseGame(:game="game" :vr="vr" ref="basegame"
13 @newmove="processMove" @gameover="gameOver")
809ba2aa
BA
14 // TODO: show players names + clocks state
15 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
d4036efe 16 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
a6088c90 17 button(@click="offerDraw") Draw
b988c726 18 button(@click="() => abortGame()") Abort
a6088c90 19 button(@click="resign") Resign
6dd02928 20 div(v-if="game.mode=='corr'")
4b0384fa 21 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
a6088c90
BA
22 div(v-show="cursor>=0") {{ moves[cursor].message }}
23</template>
24
25<script>
46284a2f 26import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
27//import Chat from "@/components/Chat.vue";
28//import MoveList from "@/components/MoveList.vue";
29import { store } from "@/store";
967a2686 30import { GameStorage } from "@/utils/gameStorage";
5b87454c 31import { ppt } from "@/utils/datetime";
a6088c90
BA
32
33export default {
34 name: 'my-game',
35 components: {
36 BaseGame,
37 },
f7121527 38 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
39 data: function() {
40 return {
41 st: store.state,
4b0384fa
BA
42 gameRef: { //given in URL (rid = remote ID)
43 id: "",
44 rid: ""
45 },
46 game: { }, //passed to BaseGame
809ba2aa 47 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 48 vr: null, //"variant rules" object initialized from FEN
93d1d7a7 49 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
4b0384fa 50 people: [ ], //potential observers (TODO)
a6088c90
BA
51 };
52 },
53 watch: {
f7121527 54 '$route' (to, from) {
4fe5664d
BA
55 if (!!to.params["id"])
56 {
57 this.gameRef.id = to.params["id"];
58 this.gameRef.rid = to.query["rid"];
59 this.loadGame();
60 }
a6088c90 61 },
5b87454c 62 "game.clocks": function(newState) {
809ba2aa
BA
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);
809ba2aa 69 let clockUpdate = setInterval(() => {
809ba2aa
BA
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);
5b87454c 91 },
a6088c90 92 },
a6088c90 93 created: function() {
f7121527 94 if (!!this.$route.params["id"])
a6088c90 95 {
f7121527
BA
96 this.gameRef.id = this.$route.params["id"];
97 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 98 this.loadGame();
f7121527 99 }
f7121527
BA
100 // TODO: how to know who is observing ? Send message to everyone with game ID ?
101 // and then just listen to (dis)connect events
3b450453
BA
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)
3b450453
BA
107 // --> doivent être enregistrés comme observers au niveau du serveur...
108 // non: poll users + events startObserving / stopObserving
b4fb1612 109 // (à faire au niveau du routeur ?)
3b450453 110
a6088c90
BA
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 {
f7121527 119 case "newmove":
c4f91d3f
BA
120 // NOTE: next call will trigger processMove()
121 this.$refs["basegame"].play(data.move,
122 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
123 break;
124 case "pong": //received if we sent a ping (game still alive on our side)
125 if (this.gameRef.id != data.gameId)
f7121527 126 break; //games IDs don't match: the game is definitely over...
a6088c90
BA
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 => {
4b0384fa 131 this.st.conn.send(JSON.stringify({
a6088c90
BA
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;
f7121527 140 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
93d1d7a7 141 // TODO: need to send along clock state (my current time) with my last move
a6088c90
BA
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)
4b0384fa 150 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
4b0384fa 162 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
c4f91d3f 171 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
a6088c90 172 break;
93d1d7a7
BA
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");
a6088c90 180 break;
93d1d7a7
BA
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
a6088c90
BA
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 = () => {
4b0384fa
BA
208 this.st.conn.addEventListener('message', socketMessageListener);
209 this.st.conn.addEventListener('close', socketCloseListener);
a6088c90 210 };
4b0384fa
BA
211 this.st.conn.onmessage = socketMessageListener;
212 this.st.conn.onclose = socketCloseListener;
a6088c90
BA
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 {
4b0384fa 232 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
a6088c90
BA
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 },
b988c726
BA
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);
d4036efe 256 return;
b988c726 257 //const message = event.
d4036efe 258 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa 259 this.$refs["basegame"].endGame("?", "Abort: " + event.msg); //TODO
b988c726
BA
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 }
a6088c90
BA
271 },
272 resign: function(e) {
273 if (!confirm("Resign the game?"))
274 return;
93d1d7a7
BA
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 }));
a6088c90 282 }
93d1d7a7
BA
283 });
284 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
285 this.$refs["basegame"].endGame(
286 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 287 },
967a2686
BA
288 // 3 cases for loading a game:
289 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
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)
967a2686
BA
292 loadGame: function(game) {
293 const afterRetrieval = async (game) => {
d4036efe
BA
294 const vModule = await import("@/variants/" + game.vname + ".js");
295 window.V = vModule.VariantRules;
809ba2aa 296 this.vr = new V(game.fen);
4b0384fa
BA
297 this.game = Object.assign({},
298 game,
299 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
300 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
301 p => p.sid == this.st.user.sid)]},
4b0384fa 302 );
967a2686
BA
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 }
4fe5664d
BA
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// }
a6088c90 329 },
b4fb1612 330 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
331// oppConnected: function(uid) {
332// return this.opponents.some(o => o.id == uid && o.online);
333// },
9d54ab89 334 // Post-process a move (which was just played)
ce87ac6a 335 processMove: function(move) {
b4fb1612
BA
336 if (!this.game.mycolor)
337 return; //I'm just an observer
9d54ab89 338 // Update storage (corr or live)
c4f91d3f 339 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
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) => {
8a7452b5 345 obj[key] = move[key];
9d54ab89
BA
346 return obj;
347 }, {});
b4fb1612 348 // Send move ("newmove" event) to opponent(s) (if ours)
c4f91d3f 349 let addTime = undefined;
9d54ab89 350 if (move.color == this.game.mycolor)
b4fb1612 351 {
809ba2aa 352 const elapsed = Date.now() - this.game.initime[colorIdx];
5b87454c
BA
353 // elapsed time is measured in milliseconds
354 addTime = this.game.increment - elapsed/1000;
b4fb1612
BA
355 this.game.players.forEach(p => {
356 if (p.sid != this.st.user.sid)
93d1d7a7 357 {
8a7452b5
BA
358 this.st.conn.send(JSON.stringify({
359 code: "newmove",
9d54ab89 360 target: p.sid,
5b87454c 361 move: Object.assign({}, filtered_move, {addTime: addTime}),
8a7452b5 362 }));
93d1d7a7 363 }
b4fb1612
BA
364 });
365 }
5b87454c
BA
366 else
367 addTime = move.addTime; //supposed transmitted
809ba2aa 368 const nextIdx = ["w","b","g","r"].indexOf(this.vr.turn);
967a2686
BA
369 GameStorage.update(this.gameRef.id,
370 {
9d54ab89 371 colorIdx: colorIdx,
809ba2aa 372 nextIdx: nextIdx,
9d54ab89
BA
373 move: filtered_move,
374 fen: move.fen,
c4f91d3f 375 addTime: addTime,
9d54ab89 376 });
967a2686
BA
377 // Also update current game object:
378 this.game.moves.push(move);
379 this.game.fen = move.fen;
27d18a24
BA
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));
809ba2aa 383 this.game.initime[nextIdx] = Date.now();
b4fb1612 384 },
93d1d7a7 385 // TODO: this update function should also work for corr games
b4fb1612 386 gameOver: function(score) {
93d1d7a7 387 this.game.mode = "analyze";
5b87454c
BA
388 GameStorage.update(this.gameRef.id,
389 {
9d54ab89
BA
390 score: score,
391 });
ce87ac6a 392 },
a6088c90
BA
393 },
394};
395</script>