Fix extractTime() function
[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")
6fba6e0c 14 // TODO: also show players names
809ba2aa 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
9aa229f3
BA
25<!--
26// TODO: movelist dans basegame et chat ici
9aa229f3
BA
27// ==> après, implémenter/vérifier les passages de challenges + parties en cours
28// observer,
29// + problèmes, habiller et publier. (+ corr...)
6fba6e0c
BA
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 ?)
9aa229f3
BA
39-->
40
a6088c90 41<script>
46284a2f 42import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
43//import Chat from "@/components/Chat.vue";
44//import MoveList from "@/components/MoveList.vue";
45import { store } from "@/store";
967a2686 46import { GameStorage } from "@/utils/gameStorage";
5b87454c 47import { ppt } from "@/utils/datetime";
66d03f23 48import { extractTime } from "@/utils/timeControl";
a6088c90
BA
49
50export default {
51 name: 'my-game',
52 components: {
53 BaseGame,
54 },
f7121527 55 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
56 data: function() {
57 return {
58 st: store.state,
4b0384fa
BA
59 gameRef: { //given in URL (rid = remote ID)
60 id: "",
61 rid: ""
62 },
63 game: { }, //passed to BaseGame
6fba6e0c
BA
64 oppConnected: false,
65 corrMsg: "", //to send offline messages in corr games
809ba2aa 66 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 67 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 68 drawOffer: "", //TODO: use for button style
4b0384fa 69 people: [ ], //potential observers (TODO)
a6088c90
BA
70 };
71 },
72 watch: {
f7121527 73 '$route' (to, from) {
4fe5664d
BA
74 if (!!to.params["id"])
75 {
76 this.gameRef.id = to.params["id"];
77 this.gameRef.rid = to.query["rid"];
78 this.loadGame();
79 }
a6088c90 80 },
5b87454c 81 "game.clocks": function(newState) {
809ba2aa 82 const currentTurn = this.vr.turn;
6fba6e0c 83 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
84 let countdown = newState[colorIdx] -
85 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
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 });
809ba2aa 92 const myTurn = (currentTurn == this.game.mycolor);
809ba2aa 93 let clockUpdate = setInterval(() => {
809ba2aa
BA
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");
6fba6e0c
BA
101 this.st.conn.send(JSON.stringify({
102 code: "timeover",
103 target: this.game.oppid,
104 }));
809ba2aa
BA
105 }
106 }
9aa229f3
BA
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 }
809ba2aa 112 }, 1000);
5b87454c 113 },
fd7aea36
BA
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 },
a6088c90 119 },
a6088c90 120 created: function() {
f7121527 121 if (!!this.$route.params["id"])
a6088c90 122 {
f7121527
BA
123 this.gameRef.id = this.$route.params["id"];
124 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 125 this.loadGame();
f7121527 126 }
cdb34c93
BA
127 // TODO: onopen, ask lastState informations + update observers and players status
128 const socketCloseListener = () => {
129 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 130 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
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) {
a6088c90 138 const data = JSON.parse(msg.data);
a6088c90
BA
139 switch (data.code)
140 {
f7121527 141 case "newmove":
c4f91d3f
BA
142 // NOTE: next call will trigger processMove()
143 this.$refs["basegame"].play(data.move,
144 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
145 break;
146 case "pong": //received if we sent a ping (game still alive on our side)
6fba6e0c 147 {
a6088c90
BA
148 this.oppConnected = true;
149 // Send our "last state" informations to opponent(s)
6fba6e0c
BA
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 }));
a6088c90 161 break;
6fba6e0c 162 }
a6088c90 163 case "lastate": //got opponent infos about last move
6fba6e0c
BA
164 {
165 const L = this.game.moves.length;
a6088c90
BA
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)
6fba6e0c 169 if (data.movesCount > L)
a6088c90 170 {
6fba6e0c
BA
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;
a6088c90 181 }
a6088c90
BA
182 else if (data.movesCount < L)
183 {
184 // We must tell last move to opponent
4b0384fa 185 this.st.conn.send(JSON.stringify({
a6088c90 186 code: "lastate",
6fba6e0c 187 target: this.game.oppid,
a6088c90 188 gameId: this.gameRef.id,
6fba6e0c
BA
189 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
190 score: this.game.score,
a6088c90 191 movesCount: L,
6fba6e0c
BA
192 drawOffer: this.drawOffer,
193 clocks: this.game.clocks,
a6088c90
BA
194 }));
195 }
a6088c90 196 break;
6fba6e0c 197 }
93d1d7a7
BA
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");
a6088c90 205 break;
93d1d7a7
BA
206 case "abort":
207 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
208 break;
2cc10cdb
BA
209 case "draw":
210 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
211 break;
212 case "drawoffer":
213 this.drawOffer = "received";
214 break;
7e1a1fe9
BA
215 case "askfullgame":
216 // TODO: just give game; observers are listed here anyway:
217 // gameconnect?
218 break;
93d1d7a7
BA
219 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
220 // ==> on "newmove", check "drawOffer" field
a6088c90
BA
221 // TODO: also use (dis)connect info to count online players?
222 case "gameconnect":
223 case "gamedisconnect":
6fba6e0c
BA
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
a6088c90 229 {
6fba6e0c
BA
230 // Or an observer ?
231 if (!online)
232 delete this.people[data.id];
a6088c90 233 else
6fba6e0c 234 this.people[data.id] = data.name;
a6088c90
BA
235 }
236 break;
237 }
cdb34c93 238 },
a6088c90 239 offerDraw: function() {
2cc10cdb 240 // TODO: also for corr games
6fba6e0c
BA
241 if (this.drawOffer == "received")
242 {
2cc10cdb 243 if (!confirm("Accept draw?"))
6fba6e0c
BA
244 return;
245 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
2cc10cdb
BA
246 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
247 }
6fba6e0c
BA
248 else if (this.drawOffer == "sent")
249 this.drawOffer = "";
250 else
251 {
252 if (!confirm("Offer draw?"))
253 return;
2cc10cdb 254 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
a6088c90
BA
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 },
b988c726 263 abortGame: function(event) {
9aa229f3 264 let modalBox = document.getElementById("modalAbort");
b988c726
BA
265 if (!event)
266 {
267 // First call show options:
b988c726
BA
268 modalBox.checked = true;
269 }
270 else
271 {
9aa229f3
BA
272 modalBox.checked = false; //decision made: box disappear
273 const message = event.target.innerText;
d4036efe 274 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 275 this.$refs["basegame"].endGame("?", "Abort: " + message);
6fba6e0c
BA
276 this.st.conn.send(JSON.stringify({
277 code: "abort",
278 msg: message,
279 target: this.game.oppid,
280 }));
b988c726 281 }
a6088c90
BA
282 },
283 resign: function(e) {
284 if (!confirm("Resign the game?"))
285 return;
6fba6e0c
BA
286 this.st.conn.send(JSON.stringify({
287 code: "resign",
288 target: this.game.oppid,
289 }));
93d1d7a7 290 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
291 this.$refs["basegame"].endGame(
292 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 293 },
967a2686
BA
294 // 3 cases for loading a game:
295 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
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)
967a2686
BA
298 loadGame: function(game) {
299 const afterRetrieval = async (game) => {
fd7aea36
BA
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
c0b27606
BA
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];
22efa391 313 // TODO: compute clocks + initime
c0b27606 314 }
66d03f23 315 const tc = extractTime(game.timeControl);
22efa391 316 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
66d03f23
BA
317 if (game.clocks[0] < 0) //game unstarted
318 {
319 game.clocks = [tc.mainTime, tc.mainTime];
320 game.initime[0] = Date.now();
22efa391
BA
321 if (myIdx >= 0) //I play in this game
322 {
323 GameStorage.update(game.gameId,
324 {
325 clocks: game.clocks,
326 initime: game.initime,
327 });
328 }
66d03f23 329 }
a9b131f1 330 const vModule = await import("@/variants/" + vname + ".js");
d4036efe 331 window.V = vModule.VariantRules;
809ba2aa 332 this.vr = new V(game.fen);
4b0384fa
BA
333 this.game = Object.assign({},
334 game,
335 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
6fba6e0c 336 {
c0b27606 337 type: gtype,
66d03f23 338 increment: tc.increment,
a9b131f1 339 vname: vname,
6fba6e0c
BA
340 mycolor: [undefined,"w","b"][myIdx+1],
341 // opponent sid not strictly required, but easier
342 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
343 }
4b0384fa 344 );
6fba6e0c
BA
345 if (!!this.game.oppid)
346 {
347 // Send ping to server (answer pong if players[s] are connected)
a36a09c0 348 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
6fba6e0c 349 }
967a2686
BA
350 };
351 if (!!game)
352 return afterRetrival(game);
353 if (!!this.gameRef.rid)
354 {
7e1a1fe9 355 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
356 // TODO: just send a game request message to the remote player,
357 // and when receiving answer just call loadGame(received_game)
358 // + remote peer should have registered us as an observer
359 // (send moves updates + resign/abort/draw actions)
967a2686
BA
360 }
361 else
362 {
363 GameStorage.get(this.gameRef.id, async (game) => {
364 afterRetrieval(game);
365 });
366 }
a6088c90 367 },
9d54ab89 368 // Post-process a move (which was just played)
ce87ac6a 369 processMove: function(move) {
b4fb1612
BA
370 if (!this.game.mycolor)
371 return; //I'm just an observer
9d54ab89 372 // Update storage (corr or live)
6fba6e0c 373 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
374 // https://stackoverflow.com/a/38750895
375 const allowed_fields = ["appear", "vanish", "start", "end"];
376 const filtered_move = Object.keys(move)
377 .filter(key => allowed_fields.includes(key))
378 .reduce((obj, key) => {
8a7452b5 379 obj[key] = move[key];
9d54ab89
BA
380 return obj;
381 }, {});
b4fb1612 382 // Send move ("newmove" event) to opponent(s) (if ours)
c4f91d3f 383 let addTime = undefined;
9d54ab89 384 if (move.color == this.game.mycolor)
b4fb1612 385 {
809ba2aa 386 const elapsed = Date.now() - this.game.initime[colorIdx];
5b87454c
BA
387 // elapsed time is measured in milliseconds
388 addTime = this.game.increment - elapsed/1000;
6fba6e0c
BA
389 this.st.conn.send(JSON.stringify({
390 code: "newmove",
391 target: this.game.oppid,
392 move: Object.assign({}, filtered_move, {addTime: addTime}),
393 }));
b4fb1612 394 }
5b87454c
BA
395 else
396 addTime = move.addTime; //supposed transmitted
6fba6e0c 397 const nextIdx = ["w","b"].indexOf(this.vr.turn);
967a2686
BA
398 GameStorage.update(this.gameRef.id,
399 {
9d54ab89
BA
400 move: filtered_move,
401 fen: move.fen,
22efa391
BA
402 clocks: this.game.clocks.map((t,i) => i==colorIdx
403 ? this.game.clocks[i] + addTime
404 : this.game.clocks[i]),
405 initime: this.game.initime.map((t,i) => i==nextIdx
406 ? Date.now()
407 : this.game.initime[i]),
9d54ab89 408 });
967a2686
BA
409 // Also update current game object:
410 this.game.moves.push(move);
411 this.game.fen = move.fen;
66d03f23
BA
412 //TODO: just this.game.clocks[colorIdx] += addTime;
413 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 414 this.game.initime[nextIdx] = Date.now();
b4fb1612 415 },
93d1d7a7 416 // TODO: this update function should also work for corr games
b4fb1612 417 gameOver: function(score) {
93d1d7a7 418 this.game.mode = "analyze";
22efa391 419 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 420 },
a6088c90
BA
421 },
422};
423</script>
7e1a1fe9
BA
424
425<style lang="sass">
426// TODO
427</style>