Fix attempt - still chat issues when tabs are not reloaded after live game start
[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")
f41ce580 14 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
afd3240d 15 div(v-if="game.score=='*'") 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
9330b976 20 textarea(v-if="game.score=='*'" v-model="corrMsg")
5c8e044f 21 Chat(:players="game.players")
a6088c90
BA
22</template>
23
9aa229f3 24<!--
9aa229f3
BA
25// ==> après, implémenter/vérifier les passages de challenges + parties en cours
26// observer,
9aa229f3
BA
27-->
28
a6088c90 29<script>
46284a2f 30import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 31import Chat from "@/components/Chat.vue";
a6088c90 32import { store } from "@/store";
967a2686 33import { GameStorage } from "@/utils/gameStorage";
5b87454c 34import { ppt } from "@/utils/datetime";
66d03f23 35import { extractTime } from "@/utils/timeControl";
f41ce580 36import { ArrayFun } from "@/utils/array";
a6088c90
BA
37
38export default {
39 name: 'my-game',
40 components: {
41 BaseGame,
5c8e044f 42 Chat,
a6088c90 43 },
f7121527 44 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
45 data: function() {
46 return {
47 st: store.state,
4b0384fa
BA
48 gameRef: { //given in URL (rid = remote ID)
49 id: "",
50 rid: ""
51 },
f41ce580 52 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
6fba6e0c 53 corrMsg: "", //to send offline messages in corr games
809ba2aa 54 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 55 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 56 drawOffer: "", //TODO: use for button style
92a523d1 57 people: [], //players + observers
a6088c90
BA
58 };
59 },
60 watch: {
5f131484
BA
61 "$route": function(to, from) {
62 this.gameRef.id = to.params["id"];
63 this.gameRef.rid = to.query["rid"];
64 this.loadGame();
a6088c90 65 },
5b87454c 66 "game.clocks": function(newState) {
dce792f6
BA
67 if (this.game.moves.length < 2)
68 {
69 // 1st move not completed yet: freeze time
70 this.virtualClocks = newState.map(s => ppt(s));
71 return;
72 }
809ba2aa 73 const currentTurn = this.vr.turn;
6fba6e0c 74 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
75 let countdown = newState[colorIdx] -
76 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
77 this.virtualClocks = [0,1].map(i => {
78 const removeTime = i == colorIdx
79 ? (Date.now() - this.game.initime[colorIdx])/1000
80 : 0;
81 return ppt(newState[i] - removeTime);
82 });
809ba2aa 83 let clockUpdate = setInterval(() => {
e69f159d 84 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
85 {
86 clearInterval(clockUpdate);
e69f159d 87 if (countdown < 0)
809ba2aa
BA
88 {
89 this.$refs["basegame"].endGame(
e69f159d 90 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
809ba2aa
BA
91 }
92 }
9aa229f3
BA
93 else
94 {
95 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
96 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
97 }
809ba2aa 98 }, 1000);
5b87454c 99 },
92a523d1 100 },
5f131484 101 // TODO: redundant code with Hall.vue (related to people array)
a6088c90 102 created: function() {
5f131484
BA
103 // Always add myself to players' list
104 const my = this.st.user;
105 this.people.push({sid:my.sid, id:my.id, name:my.name});
f7121527 106 if (!!this.$route.params["id"])
a6088c90 107 {
f7121527
BA
108 this.gameRef.id = this.$route.params["id"];
109 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 110 this.loadGame();
f7121527 111 }
afd3240d
BA
112 // TODO: mode analyse (/analyze/Atomic/rn
113 // ... fen = query[], vname=params[] ...
5f131484
BA
114 // 0.1] Ask server for room composition:
115 const funcPollClients = () => {
116 this.st.conn.send(JSON.stringify({code:"pollclients"}));
117 };
118 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
119 funcPollClients();
120 else //socket not ready yet (initial loading)
121 this.st.conn.onopen = funcPollClients;
122 this.st.conn.onmessage = this.socketMessageListener;
cdb34c93
BA
123 const socketCloseListener = () => {
124 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 125 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
126 this.st.conn.addEventListener('close', socketCloseListener);
127 };
cdb34c93
BA
128 this.st.conn.onclose = socketCloseListener;
129 },
130 methods: {
5f131484
BA
131 getOppSid: function() {
132 if (!!this.game.oppsid)
133 return this.game.oppsid;
134 const opponent = this.people.find(p => p.id == this.game.oppid);
135 return (!!opponent ? opponent.sid : null);
136 },
cdb34c93 137 socketMessageListener: function(msg) {
a6088c90 138 const data = JSON.parse(msg.data);
a6088c90
BA
139 switch (data.code)
140 {
5f131484
BA
141 // 0.2] Receive clients list (just socket IDs)
142 case "pollclients":
143 {
144 data.sockIds.forEach(sid => {
145 this.people.push({sid:sid, id:0, name:""});
146 // Ask only identity
147 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
148 });
149 break;
150 }
151 case "askidentity":
152 {
153 // Request for identification: reply if I'm not anonymous
154 if (this.st.user.id > 0)
155 {
156 this.st.conn.send(JSON.stringify(
157 // people[0] instead of st.user to avoid sending email
158 {code:"identity", user:this.people[0], target:data.from}));
159 }
160 break;
161 }
162 case "identity":
163 {
f41ce580 164 let player = this.people.find(p => p.sid == data.user.sid);
cd0d7743
BA
165 // NOTE: sometimes player.id fails because player is undefined...
166 // Probably because the event was meant for Hall?
167 if (!player)
168 return;
f41ce580
BA
169 player.id = data.user.id;
170 player.name = data.user.name;
171 // Sending last state only for live games: corr games are complete
172 if (this.game.type == "live" && this.game.oppsid == player.sid)
411d23cd 173 {
f41ce580 174 // Send our "last state" informations to opponent
411d23cd
BA
175 const L = this.game.moves.length;
176 this.st.conn.send(JSON.stringify({
177 code: "lastate",
f41ce580
BA
178 target: player.sid,
179 state:
180 {
181 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
182 score: this.game.score,
183 movesCount: L,
184 drawOffer: this.drawOffer,
185 clocks: this.game.clocks,
186 }
411d23cd
BA
187 }));
188 }
a6088c90 189 break;
6fba6e0c 190 }
c6788ecf
BA
191 case "askgame":
192 // Send current (live) game
193 const myGame =
194 {
195 // Minimal game informations:
196 id: this.game.id,
197 players: this.game.players.map(p => p.name),
198 vid: this.game.vid,
199 timeControl: this.game.timeControl,
200 };
201 this.st.conn.send(JSON.stringify({code:"game",
202 game:myGame, target:data.from}));
203 break;
f41ce580
BA
204 case "newmove":
205 // NOTE: this call to play() will trigger processMove()
206 this.$refs["basegame"].play(data.move,
207 "receive", this.game.vname!="Dark" ? "animate" : null);
208 break;
a6088c90 209 case "lastate": //got opponent infos about last move
6fba6e0c
BA
210 {
211 const L = this.game.moves.length;
6fba6e0c 212 if (data.movesCount > L)
a6088c90 213 {
6fba6e0c 214 // Just got last move from him
f41ce580
BA
215 this.$refs["basegame"].play(data.lastMove,
216 "receive", this.game.vname!="Dark" ? "animate" : null);
6fba6e0c
BA
217 if (data.score != "*" && this.game.score == "*")
218 {
219 // Opponent resigned or aborted game, or accepted draw offer
220 // (this is not a stalemate or checkmate)
221 this.$refs["basegame"].endGame(data.score, "Opponent action");
222 }
f41ce580
BA
223 this.game.clocks = data.clocks; //TODO: check this?
224 this.drawOffer = data.drawOffer; //does opponent offer draw?
a6088c90 225 }
a6088c90 226 break;
6fba6e0c 227 }
93d1d7a7
BA
228 case "resign":
229 this.$refs["basegame"].endGame(
230 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
231 break;
93d1d7a7
BA
232 case "abort":
233 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
234 break;
2cc10cdb
BA
235 case "draw":
236 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
237 break;
238 case "drawoffer":
239 this.drawOffer = "received";
240 break;
7e1a1fe9
BA
241 case "askfullgame":
242 // TODO: just give game; observers are listed here anyway:
5f131484
BA
243 // ==> mark request SID as someone to send moves to
244 // NOT to all people array: our opponent can send moves too!
7e1a1fe9 245 break;
5f131484
BA
246 case "fullgame":
247 // and when receiving answer just call loadGame(received_game)
248 this.loadGame(data.game);
249 break;
250 // TODO: drawaccepted (click draw button before sending move
251 // ==> draw offer in move)
252 // ==> on "newmove", check "drawOffer" field
253 case "connect":
254 {
c6788ecf
BA
255 this.people.push({name:"", id:0, sid:data.from});
256 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484
BA
257 break;
258 }
259 case "disconnect":
c6788ecf 260 ArrayFun.remove(this.people, p => p.sid == data.from);
a6088c90
BA
261 break;
262 }
cdb34c93 263 },
a6088c90 264 offerDraw: function() {
2cc10cdb 265 // TODO: also for corr games
6fba6e0c
BA
266 if (this.drawOffer == "received")
267 {
2cc10cdb 268 if (!confirm("Accept draw?"))
6fba6e0c 269 return;
5f131484
BA
270 const oppsid = this.getOppSid();
271 if (!!oppsid)
272 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
2cc10cdb
BA
273 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
274 }
6fba6e0c
BA
275 else if (this.drawOffer == "sent")
276 this.drawOffer = "";
277 else
278 {
279 if (!confirm("Offer draw?"))
280 return;
5f131484
BA
281 const oppsid = this.getOppSid();
282 if (!!oppsid)
283 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
a6088c90
BA
284 }
285 },
286 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
287 receiveDrawOffer: function() {
288 //if (...)
289 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
290 // if accept: send message "draw"
291 },
b988c726 292 abortGame: function(event) {
9aa229f3 293 let modalBox = document.getElementById("modalAbort");
b988c726
BA
294 if (!event)
295 {
296 // First call show options:
b988c726
BA
297 modalBox.checked = true;
298 }
299 else
300 {
9aa229f3
BA
301 modalBox.checked = false; //decision made: box disappear
302 const message = event.target.innerText;
d4036efe 303 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 304 this.$refs["basegame"].endGame("?", "Abort: " + message);
5f131484
BA
305 const oppsid = this.getOppSid();
306 if (!!oppsid)
307 {
308 this.st.conn.send(JSON.stringify({
309 code: "abort",
310 msg: message,
311 target: oppsid,
312 }));
313 }
b988c726 314 }
a6088c90
BA
315 },
316 resign: function(e) {
317 if (!confirm("Resign the game?"))
318 return;
5f131484
BA
319 const oppsid = this.getOppSid();
320 if (!!oppsid)
321 {
322 this.st.conn.send(JSON.stringify({
323 code: "resign",
324 target: oppsid,
325 }));
326 }
93d1d7a7 327 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
328 this.$refs["basegame"].endGame(
329 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 330 },
967a2686
BA
331 // 3 cases for loading a game:
332 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
333 // - from server (one correspondance game I play[ed] or not)
334 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
335 loadGame: function(game) {
336 const afterRetrieval = async (game) => {
f41ce580
BA
337 const vModule = await import("@/variants/" + game.vname + ".js");
338 window.V = vModule.VariantRules;
339 this.vr = new V(game.fen);
c0b27606 340 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 341 const tc = extractTime(game.timeControl);
c0b27606
BA
342 if (gtype == "corr")
343 {
f41ce580
BA
344 if (game.players[0].color == "b")
345 {
346 // Adopt the same convention for live and corr games: [0] = white
347 [ game.players[0], game.players[1] ] =
348 [ game.players[1], game.players[0] ];
349 }
c0b27606 350 // corr game: needs to compute the clocks + initime
92a523d1 351 game.clocks = [tc.mainTime, tc.mainTime];
c0b27606 352 game.initime = [0, 0];
5f131484 353 const L = game.moves.length;
92b82def 354 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
5f131484 355 if (L >= 3)
92a523d1 356 {
5f131484
BA
357 let addTime = [0, 0];
358 for (let i=2; i<L; i++)
359 {
360 addTime[i%2] += tc.increment -
361 (game.moves[i].played - game.moves[i-1].played);
362 }
363 for (let i=0; i<=1; i++)
364 game.clocks[i] += addTime[i];
92a523d1 365 }
5f131484
BA
366 if (L >= 1)
367 game.initime[L%2] = game.moves[L-1].played;
92b82def 368 // Now that we used idx and played, re-format moves as for live games
6d68309a 369 game.moves = game.moves.map( (m) => {
92b82def 370 const s = m.squares;
6d68309a 371 return {
92b82def
BA
372 appear: s.appear,
373 vanish: s.vanish,
374 start: s.start,
375 end: s.end,
376 message: m.message,
377 };
378 });
c0b27606 379 }
f41ce580
BA
380 const myIdx = game.players.findIndex(p => {
381 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
382 });
92a523d1 383 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
384 {
385 game.clocks = [tc.mainTime, tc.mainTime];
386 game.initime[0] = Date.now();
92a523d1 387 if (myIdx >= 0)
22efa391 388 {
cf742aaf 389 // I play in this live game; corr games don't have clocks+initime
d18bfa12 390 GameStorage.update(game.id,
22efa391
BA
391 {
392 clocks: game.clocks,
393 initime: game.initime,
394 });
395 }
66d03f23 396 }
4b0384fa
BA
397 this.game = Object.assign({},
398 game,
cf742aaf 399 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 400 {
c0b27606 401 type: gtype,
66d03f23 402 increment: tc.increment,
6fba6e0c 403 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
404 // opponent sid not strictly required (or available), but easier
405 // at least oppsid or oppid is available anyway:
406 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
407 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 408 }
4b0384fa 409 );
967a2686
BA
410 };
411 if (!!game)
412 return afterRetrival(game);
413 if (!!this.gameRef.rid)
414 {
f41ce580 415 // Remote live game
5f131484
BA
416 this.st.conn.send(JSON.stringify(
417 {code:"askfullgame", target:this.gameRef.rid}));
967a2686 418 // (send moves updates + resign/abort/draw actions)
967a2686
BA
419 }
420 else
421 {
f41ce580 422 // Local or corr game
11667c79 423 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 424 }
a6088c90 425 },
9d54ab89 426 // Post-process a move (which was just played)
ce87ac6a 427 processMove: function(move) {
b4fb1612
BA
428 if (!this.game.mycolor)
429 return; //I'm just an observer
9d54ab89 430 // Update storage (corr or live)
6fba6e0c 431 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
432 // https://stackoverflow.com/a/38750895
433 const allowed_fields = ["appear", "vanish", "start", "end"];
434 const filtered_move = Object.keys(move)
435 .filter(key => allowed_fields.includes(key))
436 .reduce((obj, key) => {
8a7452b5 437 obj[key] = move[key];
9d54ab89
BA
438 return obj;
439 }, {});
b4fb1612 440 // Send move ("newmove" event) to opponent(s) (if ours)
dce792f6 441 let addTime = 0;
9d54ab89 442 if (move.color == this.game.mycolor)
b4fb1612 443 {
dce792f6
BA
444 if (this.game.moves.length >= 2) //after first move
445 {
446 const elapsed = Date.now() - this.game.initime[colorIdx];
447 // elapsed time is measured in milliseconds
448 addTime = this.game.increment - elapsed/1000;
449 }
6d68309a
BA
450 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
451 if (this.game.type == "corr")
452 sendMove.message = this.corrMsg;
a4480041
BA
453 const oppsid = this.getOppSid();
454 if (!!oppsid)
455 {
456 this.st.conn.send(JSON.stringify({
457 code: "newmove",
458 target: oppsid,
459 move: sendMove,
460 }));
461 }
462 if (this.game.type == "corr" && this.corrMsg != "")
463 {
464 // Add message to last move in BaseGame:
465 // TODO: not very good style...
466 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
467 }
b4fb1612 468 }
5b87454c
BA
469 else
470 addTime = move.addTime; //supposed transmitted
6fba6e0c 471 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
472 // Since corr games are stored at only one location, update should be
473 // done only by one player for each move:
474 if (this.game.type == "live" || move.color == this.game.mycolor)
967a2686 475 {
e69f159d 476 if (this.game.type == "corr")
f41ce580 477 {
e69f159d 478 GameStorage.update(this.gameRef.id,
6d68309a 479 {
e69f159d
BA
480 fen: move.fen,
481 move:
482 {
483 squares: filtered_move,
484 message: this.corrMsg,
485 played: Date.now(), //TODO: on server?
486 idx: this.game.moves.length,
487 },
488 });
489 }
490 else //live
491 {
492 GameStorage.update(this.gameRef.id,
493 {
494 fen: move.fen,
495 move: filtered_move,
496 clocks: this.game.clocks.map((t,i) => i==colorIdx
497 ? this.game.clocks[i] + addTime
498 : this.game.clocks[i]),
499 initime: this.game.initime.map((t,i) => i==nextIdx
500 ? Date.now()
501 : this.game.initime[i]),
502 });
503 }
6d68309a 504 }
967a2686
BA
505 // Also update current game object:
506 this.game.moves.push(move);
507 this.game.fen = move.fen;
66d03f23
BA
508 //TODO: just this.game.clocks[colorIdx] += addTime;
509 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 510 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
511 // Finally reset curMoveMessage if needed
512 if (this.game.type == "corr" && move.color == this.game.mycolor)
513 this.corrMsg = "";
b4fb1612
BA
514 },
515 gameOver: function(score) {
93d1d7a7 516 this.game.mode = "analyze";
d18bfa12 517 this.game.score = score;
22efa391 518 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 519 },
a6088c90
BA
520 },
521};
522</script>
7e1a1fe9
BA
523
524<style lang="sass">
525// TODO
526</style>