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