Issue with observer in live games: moveToPlay repeated, no online indics ?!
[vchess.git] / client / src / views / Game.vue
1 <template lang="pug">
2 main
3 input#modalChat.modal(type="checkbox" @change="toggleChat")
4 div#chatWrap(role="dialog" data-checkbox="modalChat"
5 aria-labelledby="inputChat")
6 #chat.card
7 label.modal-close(for="modalChat")
8 Chat(:players="game.players" :pastChats="game.chats"
9 @newchat-sent="finishSendChat" @newchat-received="processChat")
10 .row
11 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
12 button#chatBtn(onClick="doClick('modalChat')") Chat
13 #actions(v-if="game.score=='*'")
14 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}") Draw
15 button(@click="abortGame") Abort
16 button(@click="resign") Resign
17 #playersInfo
18 p
19 span.name(:class="{connected: isConnected(0)}")
20 | {{ game.players[0].name || "@nonymous" }}
21 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
22 span.split-names -
23 span.name(:class="{connected: isConnected(1)}")
24 | {{ game.players[1].name || "@nonymous" }}
25 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
26 BaseGame(:game="game" :vr="vr" ref="basegame"
27 @newmove="processMove" @gameover="gameOver")
28 </template>
29
30 <script>
31 import BaseGame from "@/components/BaseGame.vue";
32 import Chat from "@/components/Chat.vue";
33 import { store } from "@/store";
34 import { GameStorage } from "@/utils/gameStorage";
35 import { ppt } from "@/utils/datetime";
36 import { extractTime } from "@/utils/timeControl";
37 import { ArrayFun } from "@/utils/array";
38 import { processModalClick } from "@/utils/modalClick";
39
40 export default {
41 name: 'my-game',
42 components: {
43 BaseGame,
44 Chat,
45 },
46 // gameRef: to find the game in (potentially remote) storage
47 data: function() {
48 return {
49 st: store.state,
50 gameRef: { //given in URL (rid = remote ID)
51 id: "",
52 rid: ""
53 },
54 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
55 virtualClocks: [0, 0], //initialized with true game.clocks
56 vr: null, //"variant rules" object initialized from FEN
57 drawOffer: "",
58 people: {}, //players + observers
59 lastate: undefined, //used if opponent send lastate before game is ready
60 repeat: {}, //detect position repetition
61 };
62 },
63 watch: {
64 "$route": function(to, from) {
65 this.gameRef.id = to.params["id"];
66 this.gameRef.rid = to.query["rid"];
67 this.loadGame();
68 },
69 "game.clocks": function(newState) {
70 if (this.game.moves.length < 2 || this.game.score != "*")
71 {
72 // 1st move not completed yet, or game over: freeze time
73 this.virtualClocks = newState.map(s => ppt(s));
74 return;
75 }
76 const currentTurn = this.vr.turn;
77 const colorIdx = ["w","b"].indexOf(currentTurn);
78 let countdown = newState[colorIdx] -
79 (Date.now() - this.game.initime[colorIdx])/1000;
80 this.virtualClocks = [0,1].map(i => {
81 const removeTime = i == colorIdx
82 ? (Date.now() - this.game.initime[colorIdx])/1000
83 : 0;
84 return ppt(newState[i] - removeTime);
85 });
86 let clockUpdate = setInterval(() => {
87 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
88 {
89 clearInterval(clockUpdate);
90 if (countdown < 0)
91 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", "Time");
92 }
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 }
98 }, 1000);
99 },
100 },
101 // NOTE: some redundant code with Hall.vue (related to people array)
102 created: function() {
103 // Always add myself to players' list
104 const my = this.st.user;
105 this.$set(this.people, my.sid, {id:my.id, name:my.name});
106 this.gameRef.id = this.$route.params["id"];
107 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
108 // Define socket .onmessage() and .onclose() events:
109 this.st.conn.onmessage = this.socketMessageListener;
110 const socketCloseListener = () => {
111 store.socketCloseListener(); //reinitialize connexion (in store.js)
112 this.st.conn.addEventListener('message', this.socketMessageListener);
113 this.st.conn.addEventListener('close', socketCloseListener);
114 };
115 this.st.conn.onclose = socketCloseListener;
116 // Socket init required before loading remote game:
117 const socketInit = (callback) => {
118 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
119 callback();
120 else //socket not ready yet (initial loading)
121 this.st.conn.onopen = callback;
122 };
123 if (!this.gameRef.rid) //game stored locally or on server
124 this.loadGame(null, () => socketInit(this.roomInit));
125 else //game stored remotely: need socket to retrieve it
126 {
127 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
128 // --> It will be given when receiving "fullgame" socket event.
129 // A more general approach would be to store it somewhere.
130 socketInit(this.loadGame);
131 }
132 },
133 mounted: function() {
134 document.getElementById("chatWrap").addEventListener(
135 "click", processModalClick);
136 },
137 methods: {
138 // O.1] Ask server for room composition:
139 roomInit: function() {
140 // Notify the room only now that I connected, because
141 // messages might be lost otherwise (if game loading is slow)
142 this.st.conn.send(JSON.stringify({code:"connect"}));
143 this.st.conn.send(JSON.stringify({code:"pollclients"}));
144 },
145 isConnected: function(index) {
146 const name = this.game.players[index].name;
147 if (this.st.user.name == name)
148 return true;
149 return Object.values(this.people).some(p => p.name == name);
150 },
151 socketMessageListener: function(msg) {
152 const data = JSON.parse(msg.data);
153 switch (data.code)
154 {
155 case "duplicate":
156 alert("Warning: duplicate 'offline' connection");
157 break;
158 // 0.2] Receive clients list (just socket IDs)
159 case "pollclients":
160 {
161 data.sockIds.forEach(sid => {
162 // TODO: understand clearly what happens here, problems when a
163 // game is quit, and then launch a new game from hall.
164 if (!!this.people[sid])
165 return;
166 this.$set(this.people, sid, {id:0, name:""});
167 // Ask only identity
168 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
169 });
170 break;
171 }
172 case "askidentity":
173 {
174 // Request for identification: reply if I'm not anonymous
175 if (this.st.user.id > 0)
176 {
177 this.st.conn.send(JSON.stringify({code:"identity",
178 user: {
179 // NOTE: decompose to avoid revealing email
180 name: this.st.user.name,
181 sid: this.st.user.sid,
182 id: this.st.user.id,
183 },
184 target:data.from}));
185 }
186 break;
187 }
188 case "identity":
189 {
190 // NOTE: sometimes player.id fails because player is undefined...
191 // Probably because the event was meant for Hall?
192 if (!this.people[data.user.sid])
193 return;
194 this.$set(this.people, data.user.sid,
195 {id: data.user.id, name: data.user.name});
196 // Sending last state only for live games: corr games are complete
197 if (this.game.type == "live" && this.game.oppsid == data.user.sid)
198 {
199 // Send our "last state" informations to opponent
200 const L = this.game.moves.length;
201 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
202 if (!!lastMove && this.drawOffer == "sent")
203 lastMove.draw = true;
204 this.st.conn.send(JSON.stringify({
205 code: "lastate",
206 target: data.user.sid,
207 state:
208 {
209 lastMove: lastMove,
210 score: this.game.score,
211 movesCount: L,
212 clocks: this.game.clocks,
213 }
214 }));
215 }
216 break;
217 }
218 case "askgame":
219 // Send current (live) game if not asked by opponent (!)
220 if (this.game.players.some(p => p.sid == data.from))
221 return;
222 const myGame =
223 {
224 // Minimal game informations:
225 id: this.game.id,
226 players: this.game.players.map(p => { return {name:p.name}; }),
227 vid: this.game.vid,
228 timeControl: this.game.timeControl,
229 };
230 this.st.conn.send(JSON.stringify({code:"game",
231 game:myGame, target:data.from}));
232 break;
233 case "newmove":
234 this.$set(this.game, "moveToPlay", data.move);
235 break;
236 case "lastate": //got opponent infos about last move
237 {
238 this.lastate = data;
239 if (!!this.game.type) //game is loaded
240 this.processLastate();
241 //else: will be processed when game is ready
242 break;
243 }
244 case "resign":
245 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
246 break;
247 case "abort":
248 this.gameOver("?", "Abort");
249 break;
250 case "draw":
251 this.gameOver("1/2", data.message);
252 break;
253 case "drawoffer":
254 // NOTE: observers don't know who offered draw
255 this.drawOffer = "received";
256 break;
257 case "askfullgame":
258 this.st.conn.send(JSON.stringify({code:"fullgame",
259 game:this.game, target:data.from}));
260 break;
261 case "fullgame":
262 // Callback "roomInit" to poll clients only after game is loaded
263 this.loadGame(data.game, this.roomInit);
264 break;
265 case "connect":
266 {
267 // TODO: next condition is probably not required. See note line 150
268 if (!this.people[data.from])
269 {
270 this.$set(this.people, data.from, {name:"", id:0});
271 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
272 }
273 break;
274 }
275 case "disconnect":
276 this.$delete(this.people, data.from);
277 break;
278 }
279 },
280 // lastate was received, but maybe game wasn't ready yet:
281 processLastate: function() {
282 const data = this.lastate;
283 this.lastate = undefined; //security...
284 const L = this.game.moves.length;
285 if (data.movesCount > L)
286 {
287 // Just got last move from him
288 this.$set(this.game, "moveToPlay", data.lastMove);
289 if (data.score != "*" && this.game.score == "*")
290 {
291 // Opponent resigned or aborted game, or accepted draw offer
292 // (this is not a stalemate or checkmate)
293 this.gameOver(data.score, "Opponent action");
294 }
295 this.game.clocks = data.clocks; //TODO: check this?
296 if (!!data.lastMove.draw)
297 this.drawOffer = "received";
298 }
299 },
300 clickDraw: function() {
301 if (["received","threerep"].includes(this.drawOffer))
302 {
303 if (!confirm("Accept draw?"))
304 return;
305 const message = (this.drawOffer == "received"
306 ? "Mutual agreement"
307 : "Three repetitions");
308 Object.keys(this.people).forEach(sid => {
309 if (sid != this.st.user.sid)
310 {
311 this.st.conn.send(JSON.stringify({code:"draw",
312 message:message, target:sid}));
313 }
314 });
315 this.gameOver("1/2", message);
316 }
317 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
318 {
319 if (!confirm("Offer draw?"))
320 return;
321 this.drawOffer = "sent";
322 Object.keys(this.people).forEach(sid => {
323 if (sid != this.st.user.sid)
324 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
325 });
326 GameStorage.update(this.gameRef.id, {drawOffer: true});
327 }
328 },
329 abortGame: function() {
330 if (!confirm(this.st.tr["Terminate game?"]))
331 return;
332 this.gameOver("?", "Abort");
333 Object.keys(this.people).forEach(sid => {
334 if (sid != this.st.user.sid)
335 {
336 this.st.conn.send(JSON.stringify({
337 code: "abort",
338 target: sid,
339 }));
340 }
341 });
342 },
343 resign: function(e) {
344 if (!confirm("Resign the game?"))
345 return;
346 Object.keys(this.people).forEach(sid => {
347 if (sid != this.st.user.sid)
348 {
349 this.st.conn.send(JSON.stringify({code:"resign",
350 side:this.game.mycolor, target:sid}));
351 }
352 });
353 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
354 },
355 // 3 cases for loading a game:
356 // - from indexedDB (running or completed live game I play)
357 // - from server (one correspondance game I play[ed] or not)
358 // - from remote peer (one live game I don't play, finished or not)
359 loadGame: function(game, callback) {
360 const afterRetrieval = async (game) => {
361 const vModule = await import("@/variants/" + game.vname + ".js");
362 window.V = vModule.VariantRules;
363 this.vr = new V(game.fen);
364 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
365 const tc = extractTime(game.timeControl);
366 if (gtype == "corr")
367 {
368 if (game.players[0].color == "b")
369 {
370 // Adopt the same convention for live and corr games: [0] = white
371 [ game.players[0], game.players[1] ] =
372 [ game.players[1], game.players[0] ];
373 }
374 // corr game: needs to compute the clocks + initime
375 // NOTE: clocks in seconds, initime in milliseconds
376 game.clocks = [tc.mainTime, tc.mainTime];
377 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
378 if (game.score == "*") //otherwise no need to bother with time
379 {
380 game.initime = [0, 0];
381 const L = game.moves.length;
382 if (L >= 3)
383 {
384 let addTime = [0, 0];
385 for (let i=2; i<L; i++)
386 {
387 addTime[i%2] += tc.increment -
388 (game.moves[i].played - game.moves[i-1].played) / 1000;
389 }
390 for (let i=0; i<=1; i++)
391 game.clocks[i] += addTime[i];
392 }
393 if (L >= 1)
394 game.initime[L%2] = game.moves[L-1].played;
395 if (game.drawOffer)
396 this.drawOffer = "received";
397 }
398 // Now that we used idx and played, re-format moves as for live games
399 game.moves = game.moves.map( (m) => {
400 const s = m.squares;
401 return {
402 appear: s.appear,
403 vanish: s.vanish,
404 start: s.start,
405 end: s.end,
406 };
407 });
408 // Also sort chat messages (if any)
409 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
410 }
411 const myIdx = game.players.findIndex(p => {
412 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
413 });
414 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
415 {
416 game.clocks = [tc.mainTime, tc.mainTime];
417 if (game.score == "*")
418 {
419 game.initime[0] = Date.now();
420 if (myIdx >= 0)
421 {
422 // I play in this live game; corr games don't have clocks+initime
423 GameStorage.update(game.id,
424 {
425 clocks: game.clocks,
426 initime: game.initime,
427 });
428 }
429 }
430 }
431 this.game = Object.assign({},
432 game,
433 // NOTE: assign mycolor here, since BaseGame could also be VS computer
434 {
435 type: gtype,
436 increment: tc.increment,
437 mycolor: [undefined,"w","b"][myIdx+1],
438 // opponent sid not strictly required (or available), but easier
439 // at least oppsid or oppid is available anyway:
440 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
441 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
442 }
443 );
444 this.repeat = {}; //reset
445 if (!!this.lastate) //lastate arrived before game was loaded:
446 this.processLastate();
447 callback();
448 };
449 if (!!game)
450 return afterRetrieval(game);
451 if (!!this.gameRef.rid)
452 {
453 // Remote live game: forgetting about callback func... (TODO: design)
454 this.st.conn.send(JSON.stringify(
455 {code:"askfullgame", target:this.gameRef.rid}));
456 }
457 else
458 {
459 // Local or corr game
460 GameStorage.get(this.gameRef.id, afterRetrieval);
461 }
462 },
463 // Post-process a move (which was just played)
464 processMove: function(move) {
465 // Update storage (corr or live) if I play in the game
466 const colorIdx = ["w","b"].indexOf(move.color);
467 // https://stackoverflow.com/a/38750895
468 if (!!this.game.mycolor)
469 {
470 const allowed_fields = ["appear", "vanish", "start", "end"];
471 // NOTE: 'var' to see this variable outside this block
472 var filtered_move = Object.keys(move)
473 .filter(key => allowed_fields.includes(key))
474 .reduce((obj, key) => {
475 obj[key] = move[key];
476 return obj;
477 }, {});
478 }
479 // Send move ("newmove" event) to people in the room (if our turn)
480 let addTime = 0;
481 if (move.color == this.game.mycolor)
482 {
483 if (this.game.moves.length >= 2) //after first move
484 {
485 const elapsed = Date.now() - this.game.initime[colorIdx];
486 // elapsed time is measured in milliseconds
487 addTime = this.game.increment - elapsed/1000;
488 }
489 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
490 Object.keys(this.people).forEach(sid => {
491 if (sid != this.st.user.sid)
492 {
493 this.st.conn.send(JSON.stringify({
494 code: "newmove",
495 target: sid,
496 move: sendMove,
497 }));
498 }
499 });
500 }
501 else
502 addTime = move.addTime; //supposed transmitted
503 const nextIdx = ["w","b"].indexOf(this.vr.turn);
504 // Since corr games are stored at only one location, update should be
505 // done only by one player for each move:
506 if (!!this.game.mycolor &&
507 (this.game.type == "live" || move.color == this.game.mycolor))
508 {
509 if (this.game.type == "corr")
510 {
511 GameStorage.update(this.gameRef.id,
512 {
513 fen: move.fen,
514 move:
515 {
516 squares: filtered_move,
517 played: Date.now(), //TODO: on server?
518 idx: this.game.moves.length,
519 },
520 });
521 }
522 else //live
523 {
524 GameStorage.update(this.gameRef.id,
525 {
526 fen: move.fen,
527 move: filtered_move,
528 clocks: this.game.clocks.map((t,i) => i==colorIdx
529 ? this.game.clocks[i] + addTime
530 : this.game.clocks[i]),
531 initime: this.game.initime.map((t,i) => i==nextIdx
532 ? Date.now()
533 : this.game.initime[i]),
534 });
535 }
536 }
537 // Also update current game object:
538 this.game.moves.push(move);
539 this.game.fen = move.fen;
540 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
541 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
542 this.game.initime[nextIdx] = Date.now();
543 // If repetition detected, consider that a draw offer was received:
544 const fenObj = V.ParseFen(move.fen);
545 let repIdx = fenObj.position + "_" + fenObj.turn;
546 if (!!fenObj.flags)
547 repIdx += "_" + fenObj.flags;
548 this.repeat[repIdx] = (!!this.repeat[repIdx]
549 ? this.repeat[repIdx]+1
550 : 1);
551 if (this.repeat[repIdx] >= 3)
552 this.drawOffer = "threerep";
553 },
554 toggleChat: function() {
555 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
556 },
557 finishSendChat: function(chat) {
558 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
559 if (this.game.type == "corr" && this.st.user.id > 0)
560 GameStorage.update(this.gameRef.id, {chat: chat});
561 },
562 processChat: function() {
563 if (!document.getElementById("inputChat").checked)
564 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
565 },
566 gameOver: function(score, scoreMsg) {
567 this.game.score = score;
568 this.game.scoreMsg = scoreMsg;
569 const myIdx = this.game.players.findIndex(p => {
570 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
571 });
572 if (myIdx >= 0) //OK, I play in this game
573 {
574 GameStorage.update(this.gameRef.id,
575 {score: score, scoreMsg: scoreMsg});
576 }
577 },
578 },
579 };
580 </script>
581
582 <style lang="sass" scoped>
583 .connected
584 background-color: lightgreen
585
586 @media screen and (min-width: 768px)
587 #actions
588 width: 300px
589 @media screen and (max-width: 767px)
590 .game
591 width: 100%
592
593 #actions
594 display: inline-block
595 margin-top: 10px
596 button
597 display: inline-block
598 width: 33%
599 margin: 0
600
601 @media screen and (max-width: 767px)
602 #aboveBoard
603 text-align: center
604
605 .name
606 font-size: 1.5rem
607 padding: 1px
608
609 .time
610 font-size: 2rem
611 display: inline-block
612 margin-left: 10px
613
614 .split-names
615 display: inline-block
616 margin: 0 15px
617
618 #chat
619 padding-top: 20px
620 max-width: 600px
621 border: none;
622
623 #chatBtn
624 margin: 0 10px 0 0
625
626 .draw-sent, .draw-sent:hover
627 background-color: lightyellow
628
629 .draw-received, .draw-received:hover
630 background-color: lightgreen
631
632 .draw-threerep, .draw-threerep:hover
633 background-color: #e4d1fc
634 </style>