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