Record chat history in live games as well
[vchess.git] / client / src / views / Game.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(
5 role="dialog"
6 data-checkbox="modalInfo"
7 )
8 .card.text-center
9 label.modal-close(for="modalInfo")
10 a(
11 :href="'#/game/' + rematchId"
12 onClick="document.getElementById('modalInfo').checked=false"
13 )
14 | {{ st.tr["Rematch in progress"] }}
15 input#modalChat.modal(
16 type="checkbox"
17 @click="toggleChat()"
18 )
19 div#chatWrap(
20 role="dialog"
21 data-checkbox="modalChat"
22 )
23 .card
24 label.modal-close(for="modalChat")
25 #participants
26 span {{ st.tr["Participant(s):"] }}
27 span(
28 v-for="p in Object.values(people)"
29 v-if="participateInChat(p)"
30 )
31 | {{ p.name }}
32 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
33 Chat(
34 ref="chatcomp"
35 :players="game.players"
36 :pastChats="game.chats"
37 @mychat="processChat"
38 @chatcleared="clearChat"
39 )
40 input#modalConfirm.modal(type="checkbox")
41 div#confirmDiv(role="dialog")
42 .card
43 .diagram(
44 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
45 v-html="curDiag"
46 )
47 p.text-center(v-else)
48 span {{ st.tr["Move played:"] + " " }}
49 span.bold {{ moveNotation }}
50 br
51 span {{ st.tr["Are you sure?"] }}
52 .button-group#buttonsConfirm
53 // onClick for acceptBtn: set dynamically
54 button.acceptBtn
55 span {{ st.tr["Validate"] }}
56 button.refuseBtn(@click="cancelMove()")
57 span {{ st.tr["Cancel"] }}
58 .row
59 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
60 span.variant-cadence {{ game.cadence }}
61 span.variant-name {{ game.vname }}
62 span#nextGame(
63 v-if="nextIds.length > 0"
64 @click="showNextGame()"
65 )
66 | {{ st.tr["Next_g"] }}
67 button#chatBtn.tooltip(
68 onClick="window.doClick('modalChat')"
69 aria-label="Chat"
70 )
71 img(src="/images/icons/chat.svg")
72 #actions(v-if="game.score=='*'")
73 button.tooltip(
74 @click="clickDraw()"
75 :class="{['draw-' + drawOffer]: true}"
76 :aria-label="st.tr['Draw']"
77 )
78 img(src="/images/icons/draw.svg")
79 button.tooltip(
80 v-if="!!game.mycolor"
81 @click="abortGame()"
82 :aria-label="st.tr['Abort']"
83 )
84 img(src="/images/icons/abort.svg")
85 button.tooltip(
86 v-if="!!game.mycolor"
87 @click="resign()"
88 :aria-label="st.tr['Resign']"
89 )
90 img(src="/images/icons/resign.svg")
91 button.tooltip(
92 v-else
93 @click="clickRematch()"
94 :class="{['rematch-' + rematchOffer]: true}"
95 :aria-label="st.tr['Rematch']"
96 )
97 img(src="/images/icons/rematch.svg")
98 #playersInfo
99 p
100 span.name(:class="{connected: isConnected(0)}")
101 | {{ game.players[0].name || "@nonymous" }}
102 span.time(
103 v-if="game.score=='*'"
104 :class="{yourturn: !!vr && vr.turn == 'w'}"
105 )
106 span.time-left {{ virtualClocks[0][0] }}
107 span.time-separator(v-if="!!virtualClocks[0][1]") :
108 span.time-right(v-if="!!virtualClocks[0][1]")
109 | {{ virtualClocks[0][1] }}
110 span.split-names -
111 span.name(:class="{connected: isConnected(1)}")
112 | {{ game.players[1].name || "@nonymous" }}
113 span.time(
114 v-if="game.score=='*'"
115 :class="{yourturn: !!vr && vr.turn == 'b'}"
116 )
117 span.time-left {{ virtualClocks[1][0] }}
118 span.time-separator(v-if="!!virtualClocks[1][1]") :
119 span.time-right(v-if="!!virtualClocks[1][1]")
120 | {{ virtualClocks[1][1] }}
121 BaseGame(
122 ref="basegame"
123 :game="game"
124 @newmove="processMove"
125 )
126 </template>
127
128 <script>
129 import BaseGame from "@/components/BaseGame.vue";
130 import Chat from "@/components/Chat.vue";
131 import { store } from "@/store";
132 import { GameStorage } from "@/utils/gameStorage";
133 import { ppt } from "@/utils/datetime";
134 import { ajax } from "@/utils/ajax";
135 import { extractTime } from "@/utils/timeControl";
136 import { getRandString } from "@/utils/alea";
137 import { getScoreMessage } from "@/utils/scoring";
138 import { getFullNotation } from "@/utils/notation";
139 import { getDiagram } from "@/utils/printDiagram";
140 import { processModalClick } from "@/utils/modalClick";
141 import { playMove, getFilteredMove } from "@/utils/playUndo";
142 import { ArrayFun } from "@/utils/array";
143 import params from "@/parameters";
144 export default {
145 name: "my-game",
146 components: {
147 BaseGame,
148 Chat
149 },
150 data: function() {
151 return {
152 st: store.state,
153 // gameRef can point to a corr game, local game or remote live game
154 gameRef: "",
155 nextIds: [],
156 game: {}, //passed to BaseGame
157 // virtualClocks will be initialized from true game.clocks
158 virtualClocks: [],
159 vr: null, //"variant rules" object initialized from FEN
160 drawOffer: "",
161 rematchId: "",
162 rematchOffer: "",
163 lastateAsked: false,
164 people: {}, //players + observers
165 lastate: undefined, //used if opponent send lastate before game is ready
166 repeat: {}, //detect position repetition
167 curDiag: "", //for corr moves confirmation
168 conn: null,
169 roomInitialized: false,
170 // If newmove has wrong index: ask fullgame again:
171 askGameTime: 0,
172 gameIsLoading: false,
173 // If asklastate got no reply, ask again:
174 gotLastate: false,
175 gotMoveIdx: -1, //last move index received
176 // If newmove got no pingback, send again:
177 opponentGotMove: false,
178 connexionString: "",
179 socketCloseListener: 0,
180 // Incomplete info games: show move played
181 moveNotation: "",
182 // Intervals from setInterval():
183 askLastate: null,
184 retrySendmove: null,
185 clockUpdate: null,
186 // Related to (killing of) self multi-connects:
187 newConnect: {},
188 killed: {}
189 };
190 },
191 watch: {
192 $route: function(to, from) {
193 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
194 // Page change
195 this.cleanBeforeDestroy();
196 else if (from.params["id"] != to.params["id"]) {
197 // Change everything:
198 this.cleanBeforeDestroy();
199 let boardDiv = document.querySelector(".game");
200 if (!!boardDiv)
201 // In case of incomplete information variant:
202 boardDiv.style.visibility = "hidden";
203 this.atCreation();
204 } else
205 // Same game ID
206 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
207 }
208 },
209 // NOTE: some redundant code with Hall.vue (mostly related to people array)
210 created: function() {
211 this.atCreation();
212 },
213 mounted: function() {
214 ["chatWrap", "infoDiv"].forEach(eltName => {
215 document.getElementById(eltName)
216 .addEventListener("click", processModalClick);
217 });
218 if ("ontouchstart" in window) {
219 // Disable tooltips on smartphones:
220 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
221 elt.classList.remove("tooltip");
222 });
223 }
224 },
225 beforeDestroy: function() {
226 this.cleanBeforeDestroy();
227 },
228 methods: {
229 cleanBeforeDestroy: function() {
230 clearInterval(this.socketCloseListener);
231 document.removeEventListener('visibilitychange', this.visibilityChange);
232 if (!!this.askLastate) clearInterval(this.askLastate);
233 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
234 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
235 this.conn.removeEventListener("message", this.socketMessageListener);
236 this.send("disconnect");
237 this.conn = null;
238 },
239 visibilityChange: function() {
240 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
241 this.send(
242 document.visibilityState == "visible"
243 ? "getfocus"
244 : "losefocus"
245 );
246 },
247 participateInChat: function(p) {
248 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
249 },
250 someAnonymousPresent: function() {
251 return (
252 Object.values(this.people).some(p =>
253 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
254 )
255 );
256 },
257 atCreation: function() {
258 document.addEventListener('visibilitychange', this.visibilityChange);
259 // 0] (Re)Set variables
260 this.gameRef = this.$route.params["id"];
261 // next = next corr games IDs to navigate faster (if applicable)
262 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
263 // Always add myself to players' list
264 const my = this.st.user;
265 const tmpId = getRandString();
266 this.$set(
267 this.people,
268 my.sid,
269 {
270 id: my.id,
271 name: my.name,
272 tmpIds: {
273 tmpId: { focus: true }
274 }
275 }
276 );
277 this.game = {
278 players: [{ name: "" }, { name: "" }],
279 chats: [],
280 rendered: false
281 };
282 let chatComp = this.$refs["chatcomp"];
283 if (!!chatComp) chatComp.chats = [];
284 this.virtualClocks = [[0,0], [0,0]];
285 this.vr = null;
286 this.drawOffer = "";
287 this.lastateAsked = false;
288 this.rematchOffer = "";
289 this.lastate = undefined;
290 this.roomInitialized = false;
291 this.askGameTime = 0;
292 this.gameIsLoading = false;
293 this.gotLastate = false;
294 this.gotMoveIdx = -1;
295 this.opponentGotMove = false;
296 this.askLastate = null;
297 this.retrySendmove = null;
298 this.clockUpdate = null;
299 this.newConnect = {};
300 this.killed = {};
301 // 1] Initialize connection
302 this.connexionString =
303 params.socketUrl +
304 "/?sid=" + this.st.user.sid +
305 "&id=" + this.st.user.id +
306 "&tmpId=" + tmpId +
307 "&page=" +
308 // Discard potential "/?next=[...]" for page indication:
309 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
310 this.conn = new WebSocket(this.connexionString);
311 this.conn.addEventListener("message", this.socketMessageListener);
312 this.socketCloseListener = setInterval(
313 () => {
314 if (this.conn.readyState == 3) {
315 this.conn.removeEventListener("message", this.socketMessageListener);
316 this.conn = new WebSocket(this.connexionString);
317 this.conn.addEventListener("message", this.socketMessageListener);
318 }
319 },
320 1000
321 );
322 // Socket init required before loading remote game:
323 const socketInit = callback => {
324 if (this.conn.readyState == 1)
325 // 1 == OPEN state
326 callback();
327 else
328 // Socket not ready yet (initial loading)
329 // NOTE: first arg is Websocket object, unused here:
330 this.conn.onopen = () => callback();
331 };
332 this.fetchGame((game) => {
333 if (!!game)
334 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
335 else
336 // Live game stored remotely: need socket to retrieve it
337 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
338 // --> It will be given when receiving "fullgame" socket event.
339 socketInit(() => { this.send("askfullgame"); });
340 });
341 },
342 roomInit: function() {
343 if (!this.roomInitialized) {
344 // Notify the room only now that I connected, because
345 // messages might be lost otherwise (if game loading is slow)
346 this.send("connect");
347 this.send("pollclients");
348 // We may ask fullgame several times if some moves are lost,
349 // but room should be init only once:
350 this.roomInitialized = true;
351 }
352 },
353 send: function(code, obj) {
354 if (!!this.conn)
355 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
356 },
357 isConnected: function(index) {
358 const player = this.game.players[index];
359 // Is it me ? In this case no need to bother with focus
360 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
361 // Still have to check for name (because of potential multi-accounts
362 // on same browser, although this should be rare...)
363 return (!this.st.user.name || this.st.user.name == player.name);
364 // Try to find a match in people:
365 return (
366 (
367 !!player.sid &&
368 Object.keys(this.people).some(sid => {
369 return (
370 sid == player.sid &&
371 Object.values(this.people[sid].tmpIds).some(v => v.focus)
372 );
373 })
374 )
375 ||
376 (
377 !!player.id &&
378 Object.values(this.people).some(p => {
379 return (
380 p.id == player.id &&
381 Object.values(p.tmpIds).some(v => v.focus)
382 );
383 })
384 )
385 );
386 },
387 getOppsid: function() {
388 let oppsid = this.game.oppsid;
389 if (!oppsid) {
390 oppsid = Object.keys(this.people).find(
391 sid => this.people[sid].id == this.game.oppid
392 );
393 }
394 // oppsid is useful only if opponent is online:
395 if (!!oppsid && !!this.people[oppsid]) return oppsid;
396 return null;
397 },
398 toggleChat: function() {
399 if (document.getElementById("modalChat").checked)
400 // Entering chat
401 document.getElementById("inputChat").focus();
402 // TODO: next line is only required when exiting chat,
403 // but the event for now isn't well detected.
404 document.getElementById("chatBtn").classList.remove("somethingnew");
405 },
406 processChat: function(chat) {
407 this.send("newchat", { data: chat });
408 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
409 if (this.game.type == "corr" && this.st.user.id > 0)
410 this.updateCorrGame({ chat: chat });
411 else if (this.game.type == "live") {
412 chat.added = Date.now();
413 GameStorage.update(this.gameRef, { chat: chat });
414 }
415 },
416 clearChat: function() {
417 if (!!this.game.mycolor) {
418 if (this.game.type == "corr") {
419 ajax(
420 "/chats",
421 "DELETE",
422 { data: { gid: this.game.id } }
423 );
424 } else {
425 // Live game
426 GameStorage.update(this.gameRef, { delchat: true });
427 }
428 this.$set(this.game, "chats", []);
429 }
430 },
431 getGameType: function(game) {
432 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
433 },
434 // Notify something after a new move (to opponent and me on MyGames page)
435 notifyMyGames: function(thing, data) {
436 this.send(
437 "notify" + thing,
438 {
439 data: data,
440 targets: this.game.players.map(p => {
441 return { sid: p.sid, id: p.id };
442 })
443 }
444 );
445 },
446 showNextGame: function() {
447 // Did I play in current game? If not, add it to nextIds list
448 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
449 this.nextIds.unshift(this.game.id);
450 const nextGid = this.nextIds.pop();
451 this.$router.push(
452 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
453 },
454 askGameAgain: function() {
455 this.gameIsLoading = true;
456 const currentUrl = document.location.href;
457 const doAskGame = () => {
458 if (document.location.href != currentUrl) return; //page change
459 this.fetchGame((game) => {
460 if (!!game)
461 // This is my game: just reload.
462 this.loadGame(game);
463 else
464 // Just ask fullgame again (once!), this is much simpler.
465 // If this fails, the user could just reload page :/
466 this.send("askfullgame");
467 });
468 };
469 // Delay of at least 2s between two game requests
470 const now = Date.now();
471 const delay = Math.max(2000 - (now - this.askGameTime), 0);
472 this.askGameTime = now;
473 setTimeout(doAskGame, delay);
474 },
475 socketMessageListener: function(msg) {
476 if (!this.conn) return;
477 const data = JSON.parse(msg.data);
478 switch (data.code) {
479 case "pollclients":
480 // TODO: shuffling and random filtering on server,
481 // if the room is really crowded.
482 Object.keys(data.sockIds).forEach(sid => {
483 if (sid != this.st.user.sid) {
484 this.send("askidentity", { target: sid });
485 this.people[sid] = { tmpIds: data.sockIds[sid] };
486 } else {
487 // Complete my tmpIds:
488 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
489 }
490 });
491 break;
492 case "connect":
493 if (!this.people[data.from[0]]) {
494 // focus depends on the tmpId (e.g. tab)
495 this.$set(
496 this.people,
497 data.from[0],
498 {
499 tmpIds: {
500 [data.from[1]]: { focus: true }
501 }
502 }
503 );
504 this.newConnect[data.from] = true; //for self multi-connects tests
505 this.send("askidentity", { target: data.from[0] });
506 } else {
507 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
508 this.$forceUpdate(); //TODO: shouldn't be required
509 }
510 break;
511 case "disconnect":
512 if (!this.people[data.from[0]]) return;
513 delete this.people[data.from[0]].tmpIds[data.from[1]];
514 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
515 this.$delete(this.people, data.from[0]);
516 else this.$forceUpdate(); //TODO: shouldn't be required
517 break;
518 case "getfocus": {
519 let player = this.people[data.from[0]];
520 if (!!player) {
521 player.tmpIds[data.from[1]].focus = true;
522 this.$forceUpdate(); //TODO: shouldn't be required
523 }
524 break;
525 }
526 case "losefocus": {
527 let player = this.people[data.from[0]];
528 if (!!player) {
529 player.tmpIds[data.from[1]].focus = false;
530 this.$forceUpdate(); //TODO: shouldn't be required
531 }
532 break;
533 }
534 case "killed":
535 // I logged in elsewhere:
536 this.conn.removeEventListener("message", this.socketMessageListener);
537 this.conn.removeEventListener("close", this.socketCloseListener);
538 this.conn = null;
539 alert(this.st.tr["New connexion detected: tab now offline"]);
540 break;
541 case "askidentity": {
542 // Request for identification
543 const me = {
544 // Decompose to avoid revealing email
545 name: this.st.user.name,
546 sid: this.st.user.sid,
547 id: this.st.user.id
548 };
549 this.send("identity", { data: me, target: data.from });
550 break;
551 }
552 case "identity": {
553 const user = data.data;
554 let player = this.people[user.sid];
555 // player.tmpIds is already set
556 player.name = user.name;
557 player.id = user.id;
558 this.$forceUpdate(); //TODO: shouldn't be required
559 // If I multi-connect, kill current connexion if no mark (I'm older)
560 if (this.newConnect[user.sid]) {
561 if (
562 user.id > 0 &&
563 user.id == this.st.user.id &&
564 user.sid != this.st.user.sid &&
565 !this.killed[this.st.user.sid]
566 ) {
567 this.send("killme", { sid: this.st.user.sid });
568 this.killed[this.st.user.sid] = true;
569 }
570 delete this.newConnect[user.sid];
571 }
572 if (!this.killed[this.st.user.sid]) {
573 // Ask potentially missed last state, if opponent and I play
574 if (
575 !this.gotLastate &&
576 !!this.game.mycolor &&
577 this.game.type == "live" &&
578 this.game.score == "*" &&
579 this.game.players.some(p => p.sid == user.sid)
580 ) {
581 this.send("asklastate", { target: user.sid });
582 let counter = 1;
583 this.askLastate = setInterval(
584 () => {
585 // Ask at most 3 times:
586 // if no reply after that there should be a network issue.
587 if (
588 counter < 3 &&
589 !this.gotLastate &&
590 !!this.people[user.sid]
591 ) {
592 this.send("asklastate", { target: user.sid });
593 counter++;
594 } else {
595 clearInterval(this.askLastate);
596 }
597 },
598 1500
599 );
600 }
601 }
602 break;
603 }
604 case "askgame":
605 // Send current (live) game if not asked by any of the players
606 if (
607 this.game.type == "live" &&
608 this.game.players.every(p => p.sid != data.from[0])
609 ) {
610 const myGame = {
611 id: this.game.id,
612 fen: this.game.fen,
613 players: this.game.players,
614 vid: this.game.vid,
615 cadence: this.game.cadence,
616 score: this.game.score
617 };
618 this.send("game", { data: myGame, target: data.from });
619 }
620 break;
621 case "askfullgame":
622 const gameToSend = Object.keys(this.game)
623 .filter(k =>
624 [
625 "id","fen","players","vid","cadence","fenStart","vname",
626 "moves","clocks","score","drawOffer","rematchOffer"
627 ].includes(k))
628 .reduce(
629 (obj, k) => {
630 obj[k] = this.game[k];
631 return obj;
632 },
633 {}
634 );
635 this.send("fullgame", { data: gameToSend, target: data.from });
636 break;
637 case "fullgame":
638 if (!!data.data.empty) {
639 alert(this.st.tr["The game should be in another tab"]);
640 this.$router.go(-1);
641 }
642 else
643 // Callback "roomInit" to poll clients only after game is loaded
644 this.loadVariantThenGame(data.data, this.roomInit);
645 break;
646 case "asklastate":
647 // Sending informative last state if I played a move or score != "*"
648 // If the game or moves aren't loaded yet, delay the sending:
649 // TODO: since socket init after game load, the game is supposedly ready
650 if (!this.game || !this.game.moves) this.lastateAsked = true;
651 else this.sendLastate(data.from);
652 break;
653 case "lastate": {
654 // Got opponent infos about last move
655 this.gotLastate = true;
656 this.lastate = data.data;
657 if (this.game.rendered)
658 // Game is rendered (Board component)
659 this.processLastate();
660 // Else: will be processed when game is ready
661 break;
662 }
663 case "newmove": {
664 const movePlus = data.data;
665 const movesCount = this.game.moves.length;
666 if (movePlus.index > movesCount) {
667 // This can only happen if I'm an observer and missed a move.
668 if (this.gotMoveIdx < movePlus.index)
669 this.gotMoveIdx = movePlus.index;
670 if (!this.gameIsLoading) this.askGameAgain();
671 }
672 else {
673 if (
674 movePlus.index < movesCount ||
675 this.gotMoveIdx >= movePlus.index
676 ) {
677 // Opponent re-send but we already have the move:
678 // (maybe he didn't receive our pingback...)
679 this.send("gotmove", {data: movePlus.index, target: data.from});
680 } else {
681 this.gotMoveIdx = movePlus.index;
682 const receiveMyMove = (movePlus.color == this.game.mycolor);
683 if (!receiveMyMove && !!this.game.mycolor)
684 // Notify opponent that I got the move:
685 this.send("gotmove", {data: movePlus.index, target: data.from});
686 if (movePlus.cancelDrawOffer) {
687 // Opponent refuses draw
688 this.drawOffer = "";
689 // NOTE for corr games: drawOffer reset by player in turn
690 if (
691 this.game.type == "live" &&
692 !!this.game.mycolor &&
693 !receiveMyMove
694 ) {
695 GameStorage.update(this.gameRef, { drawOffer: "" });
696 }
697 }
698 this.$refs["basegame"].play(movePlus.move, "received", null, true);
699 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
700 this.game.clocks[moveColIdx] = movePlus.clock;
701 this.processMove(
702 movePlus.move,
703 { receiveMyMove: receiveMyMove }
704 );
705 }
706 }
707 break;
708 }
709 case "gotmove": {
710 this.opponentGotMove = true;
711 // Now his clock starts running on my side:
712 const oppIdx = ['w','b'].indexOf(this.vr.turn);
713 // NOTE: next line to avoid multi-resetClocks when several tabs
714 // on same game, resulting in a faster countdown.
715 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
716 this.re_setClocks();
717 break;
718 }
719 case "resign":
720 const score = (data.data == "b" ? "1-0" : "0-1");
721 const side = (data.data == "w" ? "White" : "Black");
722 this.gameOver(score, side + " surrender");
723 break;
724 case "abort":
725 this.gameOver("?", "Stop");
726 break;
727 case "draw":
728 this.gameOver("1/2", data.data);
729 break;
730 case "drawoffer":
731 // NOTE: observers don't know who offered draw
732 this.drawOffer = "received";
733 if (this.game.type == "live") {
734 GameStorage.update(
735 this.gameRef,
736 { drawOffer: V.GetOppCol(this.game.mycolor) }
737 );
738 }
739 break;
740 case "rematchoffer":
741 // NOTE: observers don't know who offered rematch
742 this.rematchOffer = data.data ? "received" : "";
743 if (this.game.type == "live") {
744 GameStorage.update(
745 this.gameRef,
746 { rematchOffer: V.GetOppCol(this.game.mycolor) }
747 );
748 }
749 break;
750 case "newgame": {
751 // A game started, redirect if I'm playing in
752 const gameInfo = data.data;
753 const gameType = this.getGameType(gameInfo);
754 if (
755 gameType == "live" &&
756 gameInfo.players.some(p => p.sid == this.st.user.sid)
757 ) {
758 this.addAndGotoLiveGame(gameInfo);
759 } else if (
760 gameType == "corr" &&
761 gameInfo.players.some(p => p.id == this.st.user.id)
762 ) {
763 this.$router.push("/game/" + gameInfo.id);
764 } else {
765 this.rematchId = gameInfo.id;
766 document.getElementById("modalInfo").checked = true;
767 }
768 break;
769 }
770 case "newchat": {
771 let chat = data.data;
772 this.$refs["chatcomp"].newChat(chat);
773 if (this.game.type == "live") {
774 chat.added = Date.now();
775 GameStorage.update(this.gameRef, { chat: chat });
776 }
777 if (!document.getElementById("modalChat").checked)
778 document.getElementById("chatBtn").classList.add("somethingnew");
779 break;
780 }
781 }
782 },
783 updateCorrGame: function(obj, callback) {
784 ajax(
785 "/games",
786 "PUT",
787 {
788 data: {
789 gid: this.gameRef,
790 newObj: obj
791 },
792 success: () => {
793 if (!!callback) callback();
794 }
795 }
796 );
797 },
798 sendLastate: function(target) {
799 // Send our "last state" informations to opponent
800 const L = this.game.moves.length;
801 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
802 const myLastate = {
803 lastMove:
804 (L > 0 && this.vr.turn != this.game.mycolor)
805 ? this.game.moves[L - 1]
806 : undefined,
807 clock: this.game.clocks[myIdx],
808 // Since we played a move (or abort or resign),
809 // only drawOffer=="sent" is possible
810 drawSent: this.drawOffer == "sent",
811 rematchSent: this.rematchOffer == "sent",
812 score: this.game.score != "*" ? this.game.score : undefined,
813 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
814 movesCount: L
815 };
816 this.send("lastate", { data: myLastate, target: target });
817 },
818 // lastate was received, but maybe game wasn't ready yet:
819 processLastate: function() {
820 const data = this.lastate;
821 this.lastate = undefined; //security...
822 const L = this.game.moves.length;
823 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
824 this.game.clocks[oppIdx] = data.clock;
825 if (data.movesCount > L) {
826 // Just got last move from him
827 this.$refs["basegame"].play(data.lastMove, "received", null, true);
828 this.processMove(data.lastMove);
829 } else {
830 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
831 this.re_setClocks();
832 }
833 if (data.drawSent) this.drawOffer = "received";
834 if (data.rematchSent) this.rematchOffer = "received";
835 if (!!data.score) {
836 this.drawOffer = "";
837 if (this.game.score == "*")
838 this.gameOver(data.score, data.scoreMsg);
839 }
840 },
841 clickDraw: function() {
842 if (!this.game.mycolor) return; //I'm just spectator
843 if (["received", "threerep"].includes(this.drawOffer)) {
844 if (!confirm(this.st.tr["Accept draw?"])) return;
845 const message =
846 this.drawOffer == "received"
847 ? "Mutual agreement"
848 : "Three repetitions";
849 this.send("draw", { data: message });
850 this.gameOver("1/2", message);
851 } else if (this.drawOffer == "") {
852 // No effect if drawOffer == "sent"
853 if (this.game.mycolor != this.vr.turn) {
854 alert(this.st.tr["Draw offer only in your turn"]);
855 return;
856 }
857 if (!confirm(this.st.tr["Offer draw?"])) return;
858 this.drawOffer = "sent";
859 this.send("drawoffer");
860 if (this.game.type == "live") {
861 GameStorage.update(
862 this.gameRef,
863 { drawOffer: this.game.mycolor }
864 );
865 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
866 }
867 },
868 addAndGotoLiveGame: function(gameInfo, callback) {
869 const game = Object.assign(
870 {},
871 gameInfo,
872 {
873 // (other) Game infos: constant
874 fenStart: gameInfo.fen,
875 vname: this.game.vname,
876 created: Date.now(),
877 // Game state (including FEN): will be updated
878 moves: [],
879 clocks: [-1, -1], //-1 = unstarted
880 score: "*"
881 }
882 );
883 GameStorage.add(game, (err) => {
884 // No error expected.
885 if (!err) {
886 if (this.st.settings.sound)
887 new Audio("/sounds/newgame.flac").play().catch(() => {});
888 if (!!callback) callback();
889 this.$router.push("/game/" + gameInfo.id);
890 }
891 });
892 },
893 clickRematch: function() {
894 if (!this.game.mycolor) return; //I'm just spectator
895 if (this.rematchOffer == "received") {
896 // Start a new game!
897 let gameInfo = {
898 id: getRandString(), //ignored if corr
899 fen: V.GenRandInitFen(this.game.randomness),
900 players: this.game.players.reverse(),
901 vid: this.game.vid,
902 cadence: this.game.cadence
903 };
904 const notifyNewGame = () => {
905 const oppsid = this.getOppsid(); //may be null
906 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
907 // To main Hall if corr game:
908 if (this.game.type == "corr")
909 this.send("newgame", { data: gameInfo, page: "/" });
910 // Also to MyGames page:
911 this.notifyMyGames("newgame", gameInfo);
912 };
913 if (this.game.type == "live")
914 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
915 else {
916 // corr game
917 ajax(
918 "/games",
919 "POST",
920 {
921 // cid is useful to delete the challenge:
922 data: { gameInfo: gameInfo },
923 success: (response) => {
924 gameInfo.id = response.gameId;
925 notifyNewGame();
926 this.$router.push("/game/" + response.gameId);
927 }
928 }
929 );
930 }
931 } else if (this.rematchOffer == "") {
932 this.rematchOffer = "sent";
933 this.send("rematchoffer", { data: true });
934 if (this.game.type == "live") {
935 GameStorage.update(
936 this.gameRef,
937 { rematchOffer: this.game.mycolor }
938 );
939 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
940 } else if (this.rematchOffer == "sent") {
941 // Toggle rematch offer (on --> off)
942 this.rematchOffer = "";
943 this.send("rematchoffer", { data: false });
944 if (this.game.type == "live") {
945 GameStorage.update(
946 this.gameRef,
947 { rematchOffer: '' }
948 );
949 } else this.updateCorrGame({ rematchOffer: 'n' });
950 }
951 },
952 abortGame: function() {
953 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
954 this.gameOver("?", "Stop");
955 this.send("abort");
956 },
957 resign: function() {
958 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
959 return;
960 this.send("resign", { data: this.game.mycolor });
961 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
962 const side = (this.game.mycolor == "w" ? "White" : "Black");
963 this.gameOver(score, side + " surrender");
964 },
965 loadGame: function(game, callback) {
966 this.vr = new V(game.fen);
967 const gtype = this.getGameType(game);
968 const tc = extractTime(game.cadence);
969 const myIdx = game.players.findIndex(p => {
970 return p.sid == this.st.user.sid || p.id == this.st.user.id;
971 });
972 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
973 // Live games before 26/03/2020 don't have chat history. TODO: remove next line
974 if (!game.chats) game.chats = [];
975 // Sort chat messages from newest to oldest
976 game.chats.sort((c1, c2) => c2.added - c1.added);
977 if (gtype == "corr") {
978 // NOTE: clocks in seconds
979 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
980 game.clocks = [tc.mainTime, tc.mainTime];
981 const L = game.moves.length;
982 if (game.score == "*") {
983 // Adjust clocks
984 if (L >= 2) {
985 game.clocks[L % 2] -=
986 (Date.now() - game.moves[L-1].played) / 1000;
987 }
988 }
989 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
990 // Did a chat message arrive after my last move?
991 let dtLastMove = 0;
992 if (L == 1 && myIdx == 0)
993 dtLastMove = game.moves[0].played;
994 else if (L >= 2) {
995 if (L % 2 == 0) {
996 // It's now white turn
997 dtLastMove = game.moves[L-1-(1-myIdx)].played;
998 } else {
999 // Black turn:
1000 dtLastMove = game.moves[L-1-myIdx].played;
1001 }
1002 }
1003 if (dtLastMove < game.chats[0].added)
1004 document.getElementById("chatBtn").classList.add("somethingnew");
1005 }
1006 // Now that we used idx and played, re-format moves as for live games
1007 game.moves = game.moves.map(m => m.squares);
1008 }
1009 if (gtype == "live") {
1010 if (
1011 game.chats.length > 0 &&
1012 (!game.initime || game.initime < game.chats[0].added)
1013 ) {
1014 document.getElementById("chatBtn").classList.add("somethingnew");
1015 }
1016 if (game.clocks[0] < 0) {
1017 // Game is unstarted. clock is ignored until move 2
1018 game.clocks = [tc.mainTime, tc.mainTime];
1019 if (myIdx >= 0) {
1020 // I play in this live game
1021 GameStorage.update(game.id, {
1022 clocks: game.clocks
1023 });
1024 }
1025 } else {
1026 if (!!game.initime)
1027 // It's my turn: clocks not updated yet
1028 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1029 }
1030 }
1031 // TODO: merge next 2 "if" conditions
1032 if (!!game.drawOffer) {
1033 if (game.drawOffer == "t")
1034 // Three repetitions
1035 this.drawOffer = "threerep";
1036 else {
1037 // Draw offered by any of the players:
1038 if (myIdx < 0) this.drawOffer = "received";
1039 else {
1040 // I play in this game:
1041 if (
1042 (game.drawOffer == "w" && myIdx == 0) ||
1043 (game.drawOffer == "b" && myIdx == 1)
1044 )
1045 this.drawOffer = "sent";
1046 else this.drawOffer = "received";
1047 }
1048 }
1049 }
1050 if (!!game.rematchOffer) {
1051 if (myIdx < 0) this.rematchOffer = "received";
1052 else {
1053 // I play in this game:
1054 if (
1055 (game.rematchOffer == "w" && myIdx == 0) ||
1056 (game.rematchOffer == "b" && myIdx == 1)
1057 )
1058 this.rematchOffer = "sent";
1059 else this.rematchOffer = "received";
1060 }
1061 }
1062 this.repeat = {}; //reset: scan past moves' FEN:
1063 let repIdx = 0;
1064 let vr_tmp = new V(game.fenStart);
1065 let curTurn = "n";
1066 game.moves.forEach(m => {
1067 playMove(m, vr_tmp);
1068 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1069 this.repeat[fenIdx] = this.repeat[fenIdx]
1070 ? this.repeat[fenIdx] + 1
1071 : 1;
1072 });
1073 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1074 this.game = Object.assign(
1075 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1076 {
1077 type: gtype,
1078 increment: tc.increment,
1079 mycolor: mycolor,
1080 // opponent sid not strictly required (or available), but easier
1081 // at least oppsid or oppid is available anyway:
1082 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1083 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1084 },
1085 game
1086 );
1087 this.$refs["basegame"].re_setVariables(this.game);
1088 if (!this.gameIsLoading) {
1089 // Initial loading:
1090 this.gotMoveIdx = game.moves.length - 1;
1091 // If we arrive here after 'nextGame' action, the board might be hidden
1092 let boardDiv = document.querySelector(".game");
1093 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1094 boardDiv.style.visibility = "visible";
1095 }
1096 this.re_setClocks();
1097 this.$nextTick(() => {
1098 this.game.rendered = true;
1099 // Did lastate arrive before game was rendered?
1100 if (this.lastate) this.processLastate();
1101 });
1102 if (this.lastateAsked) {
1103 this.lastateAsked = false;
1104 this.sendLastate(game.oppsid);
1105 }
1106 if (this.gameIsLoading) {
1107 this.gameIsLoading = false;
1108 if (this.gotMoveIdx >= game.moves.length)
1109 // Some moves arrived meanwhile...
1110 this.askGameAgain();
1111 }
1112 if (!!callback) callback();
1113 },
1114 loadVariantThenGame: async function(game, callback) {
1115 await import("@/variants/" + game.vname + ".js")
1116 .then((vModule) => {
1117 window.V = vModule[game.vname + "Rules"];
1118 this.loadGame(game, callback);
1119 });
1120 },
1121 // 3 cases for loading a game:
1122 // - from indexedDB (running or completed live game I play)
1123 // - from server (one correspondance game I play[ed] or not)
1124 // - from remote peer (one live game I don't play, finished or not)
1125 fetchGame: function(callback) {
1126 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1127 // corr games identifiers are integers
1128 ajax(
1129 "/games",
1130 "GET",
1131 {
1132 data: { gid: this.gameRef },
1133 success: (res) => {
1134 res.game.moves.forEach(m => {
1135 m.squares = JSON.parse(m.squares);
1136 });
1137 callback(res.game);
1138 }
1139 }
1140 );
1141 } else
1142 // Local game (or live remote)
1143 GameStorage.get(this.gameRef, callback);
1144 },
1145 re_setClocks: function() {
1146 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1147 if (this.game.moves.length < 2 || this.game.score != "*") {
1148 // 1st move not completed yet, or game over: freeze time
1149 return;
1150 }
1151 const currentTurn = this.vr.turn;
1152 const currentMovesCount = this.game.moves.length;
1153 const colorIdx = ["w", "b"].indexOf(currentTurn);
1154 this.clockUpdate = setInterval(
1155 () => {
1156 if (
1157 this.game.clocks[colorIdx] < 0 ||
1158 this.game.moves.length > currentMovesCount ||
1159 this.game.score != "*"
1160 ) {
1161 clearInterval(this.clockUpdate);
1162 this.clockUpdate = null;
1163 if (this.game.clocks[colorIdx] < 0)
1164 this.gameOver(
1165 currentTurn == "w" ? "0-1" : "1-0",
1166 "Time"
1167 );
1168 } else {
1169 this.$set(
1170 this.virtualClocks,
1171 colorIdx,
1172 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1173 );
1174 }
1175 },
1176 1000
1177 );
1178 },
1179 // Update variables and storage after a move:
1180 processMove: function(move, data) {
1181 if (!data) data = {};
1182 const moveCol = this.vr.turn;
1183 const colorIdx = ["w", "b"].indexOf(moveCol);
1184 const nextIdx = 1 - colorIdx;
1185 const doProcessMove = () => {
1186 const origMovescount = this.game.moves.length;
1187 // The move is (about to be) played: stop clock
1188 clearInterval(this.clockUpdate);
1189 this.clockUpdate = null;
1190 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1191 if (this.drawOffer == "received")
1192 // I refuse draw
1193 this.drawOffer = "";
1194 if (this.game.type == "live" && origMovescount >= 2) {
1195 this.game.clocks[colorIdx] += this.game.increment;
1196 // For a correct display in casqe of disconnected opponent:
1197 this.$set(
1198 this.virtualClocks,
1199 colorIdx,
1200 ppt(this.game.clocks[colorIdx]).split(':')
1201 );
1202 GameStorage.update(this.gameRef, {
1203 // It's not my turn anymore:
1204 initime: null
1205 });
1206 }
1207 }
1208 // Update current game object:
1209 playMove(move, this.vr);
1210 if (!data.score)
1211 // Received move, score is computed in BaseGame, but maybe not yet.
1212 // ==> Compute it here, although this is redundant (TODO)
1213 data.score = this.vr.getCurrentScore();
1214 if (data.score != "*") this.gameOver(data.score);
1215 this.game.moves.push(move);
1216 this.game.fen = this.vr.getFen();
1217 if (this.game.type == "corr") {
1218 // In corr games, just reset clock to mainTime:
1219 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1220 }
1221 // If repetition detected, consider that a draw offer was received:
1222 const fenObj = this.vr.getFenForRepeat();
1223 this.repeat[fenObj] =
1224 !!this.repeat[fenObj]
1225 ? this.repeat[fenObj] + 1
1226 : 1;
1227 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1228 else if (this.drawOffer == "threerep") this.drawOffer = "";
1229 if (!!this.game.mycolor && !data.receiveMyMove) {
1230 // NOTE: 'var' to see that variable outside this block
1231 var filtered_move = getFilteredMove(move);
1232 }
1233 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1234 // Notify turn on MyGames page:
1235 this.notifyMyGames(
1236 "turn",
1237 {
1238 gid: this.gameRef,
1239 turn: this.vr.turn
1240 }
1241 );
1242 }
1243 // Since corr games are stored at only one location, update should be
1244 // done only by one player for each move:
1245 if (
1246 this.game.type == "live" &&
1247 !!this.game.mycolor &&
1248 moveCol != this.game.mycolor &&
1249 this.game.moves.length >= 2
1250 ) {
1251 // Receive a move: update initime
1252 this.game.initime = Date.now();
1253 GameStorage.update(this.gameRef, {
1254 // It's my turn now!
1255 initime: this.game.initime
1256 });
1257 }
1258 if (
1259 !!this.game.mycolor &&
1260 !data.receiveMyMove &&
1261 (this.game.type == "live" || moveCol == this.game.mycolor)
1262 ) {
1263 let drawCode = "";
1264 switch (this.drawOffer) {
1265 case "threerep":
1266 drawCode = "t";
1267 break;
1268 case "sent":
1269 drawCode = this.game.mycolor;
1270 break;
1271 case "received":
1272 drawCode = V.GetOppCol(this.game.mycolor);
1273 break;
1274 }
1275 if (this.game.type == "corr") {
1276 // corr: only move, fen and score
1277 this.updateCorrGame({
1278 fen: this.game.fen,
1279 move: {
1280 squares: filtered_move,
1281 idx: origMovescount
1282 },
1283 // Code "n" for "None" to force reset (otherwise it's ignored)
1284 drawOffer: drawCode || "n"
1285 });
1286 }
1287 else {
1288 const updateStorage = () => {
1289 GameStorage.update(this.gameRef, {
1290 fen: this.game.fen,
1291 move: filtered_move,
1292 moveIdx: origMovescount,
1293 clocks: this.game.clocks,
1294 drawOffer: drawCode
1295 });
1296 };
1297 // The active tab can update storage immediately
1298 if (!document.hidden) updateStorage();
1299 // Small random delay otherwise
1300 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1301 }
1302 }
1303 // Send move ("newmove" event) to people in the room (if our turn)
1304 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1305 let sendMove = {
1306 move: filtered_move,
1307 index: origMovescount,
1308 // color is required to check if this is my move (if several tabs opened)
1309 color: moveCol,
1310 cancelDrawOffer: this.drawOffer == ""
1311 };
1312 if (this.game.type == "live")
1313 sendMove["clock"] = this.game.clocks[colorIdx];
1314 // (Live) Clocks will re-start when the opponent pingback arrive
1315 this.opponentGotMove = false;
1316 this.send("newmove", {data: sendMove});
1317 // If the opponent doesn't reply gotmove soon enough, re-send move:
1318 // Do this at most 2 times, because mpore would mean network issues,
1319 // opponent would then be expected to disconnect/reconnect.
1320 let counter = 1;
1321 const currentUrl = document.location.href;
1322 this.retrySendmove = setInterval(
1323 () => {
1324 if (
1325 counter >= 3 ||
1326 this.opponentGotMove ||
1327 document.location.href != currentUrl //page change
1328 ) {
1329 clearInterval(this.retrySendmove);
1330 return;
1331 }
1332 const oppsid = this.getOppsid();
1333 if (!oppsid)
1334 // Opponent is disconnected: he'll ask last state
1335 clearInterval(this.retrySendmove);
1336 else {
1337 this.send("newmove", { data: sendMove, target: oppsid });
1338 counter++;
1339 }
1340 },
1341 1500
1342 );
1343 }
1344 else
1345 // Not my move or I'm an observer: just start other player's clock
1346 this.re_setClocks();
1347 };
1348 if (
1349 this.game.type == "corr" &&
1350 moveCol == this.game.mycolor &&
1351 !data.receiveMyMove
1352 ) {
1353 let boardDiv = document.querySelector(".game");
1354 const afterSetScore = () => {
1355 doProcessMove();
1356 if (this.st.settings.gotonext && this.nextIds.length > 0)
1357 this.showNextGame();
1358 else {
1359 // The board might have been hidden:
1360 if (boardDiv.style.visibility == "hidden")
1361 boardDiv.style.visibility = "visible";
1362 if (data.score == "*") this.re_setClocks();
1363 }
1364 };
1365 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1366 // We may play several moves in a row: in case of, remove listener:
1367 let elClone = el.cloneNode(true);
1368 el.parentNode.replaceChild(elClone, el);
1369 elClone.addEventListener(
1370 "click",
1371 () => {
1372 document.getElementById("modalConfirm").checked = false;
1373 if (!!data.score && data.score != "*")
1374 // Set score first
1375 this.gameOver(data.score, null, afterSetScore);
1376 else afterSetScore();
1377 }
1378 );
1379 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1380 V.PlayOnBoard(this.vr.board, move);
1381 const position = this.vr.getBaseFen();
1382 V.UndoOnBoard(this.vr.board, move);
1383 if (["all","byrow"].includes(V.ShowMoves)) {
1384 this.curDiag = getDiagram({
1385 position: position,
1386 orientation: V.CanFlip ? this.game.mycolor : "w"
1387 });
1388 document.querySelector("#confirmDiv > .card").style.width =
1389 boardDiv.offsetWidth + "px";
1390 } else {
1391 // Incomplete information: just ask confirmation
1392 // Hide the board, because otherwise it could reveal infos
1393 boardDiv.style.visibility = "hidden";
1394 this.moveNotation = getFullNotation(move);
1395 }
1396 document.getElementById("modalConfirm").checked = true;
1397 }
1398 else {
1399 // Normal situation
1400 if (!!data.score && data.score != "*")
1401 this.gameOver(data.score, null, doProcessMove);
1402 else doProcessMove();
1403 }
1404 },
1405 cancelMove: function() {
1406 let boardDiv = document.querySelector(".game");
1407 if (boardDiv.style.visibility == "hidden")
1408 boardDiv.style.visibility = "visible";
1409 document.getElementById("modalConfirm").checked = false;
1410 this.$refs["basegame"].cancelLastMove();
1411 },
1412 // In corr games, callback to change page only after score is set:
1413 gameOver: function(score, scoreMsg, callback) {
1414 this.game.score = score;
1415 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1416 this.game.scoreMsg = scoreMsg;
1417 this.$set(this.game, "scoreMsg", scoreMsg);
1418 const myIdx = this.game.players.findIndex(p => {
1419 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1420 });
1421 if (myIdx >= 0) {
1422 // OK, I play in this game
1423 const scoreObj = {
1424 score: score,
1425 scoreMsg: scoreMsg
1426 };
1427 if (this.game.type == "live") {
1428 GameStorage.update(this.gameRef, scoreObj);
1429 if (!!callback) callback();
1430 }
1431 else this.updateCorrGame(scoreObj, callback);
1432 // Notify the score to main Hall. TODO: only one player (currently double send)
1433 this.send("result", { gid: this.game.id, score: score });
1434 // Also to MyGames page (TODO: doubled as well...)
1435 this.notifyMyGames(
1436 "score",
1437 {
1438 gid: this.gameRef,
1439 score: score
1440 }
1441 );
1442 }
1443 else if (!!callback) callback();
1444 }
1445 }
1446 };
1447 </script>
1448
1449 <style lang="sass" scoped>
1450 #infoDiv > .card
1451 padding: 15px 0
1452 max-width: 430px
1453
1454 .connected
1455 background-color: lightgreen
1456
1457 #participants
1458 margin-left: 5px
1459
1460 .anonymous
1461 color: grey
1462 font-style: italic
1463
1464 #playersInfo > p
1465 margin: 0
1466
1467 @media screen and (min-width: 768px)
1468 #actions
1469 width: 300px
1470 @media screen and (max-width: 767px)
1471 .game
1472 width: 100%
1473
1474 #actions
1475 display: inline-block
1476 margin: 0
1477
1478 button
1479 display: inline-block
1480 margin: 0
1481 display: inline-flex
1482 img
1483 height: 22px
1484 display: flex
1485 @media screen and (max-width: 767px)
1486 height: 18px
1487
1488 @media screen and (max-width: 767px)
1489 #aboveBoard
1490 text-align: center
1491 @media screen and (min-width: 768px)
1492 #aboveBoard
1493 margin-left: 30%
1494
1495 .variant-cadence
1496 padding-right: 10px
1497
1498 .variant-name
1499 font-weight: bold
1500 padding-right: 10px
1501
1502 span#nextGame
1503 background-color: #edda99
1504 cursor: pointer
1505 display: inline-block
1506 margin-right: 10px
1507
1508 span.name
1509 font-size: 1.5rem
1510 padding: 0 3px
1511
1512 span.time
1513 font-size: 2rem
1514 display: inline-block
1515 .time-left
1516 margin-left: 10px
1517 .time-right
1518 margin-left: 5px
1519 .time-separator
1520 margin-left: 5px
1521 position: relative
1522 top: -1px
1523
1524 span.yourturn
1525 color: #831B1B
1526 .time-separator
1527 animation: blink-animation 2s steps(3, start) infinite
1528 @keyframes blink-animation
1529 to
1530 visibility: hidden
1531
1532 .split-names
1533 display: inline-block
1534 margin: 0 15px
1535
1536 #chatWrap > .card
1537 padding-top: 20px
1538 max-width: 767px
1539 border: none
1540
1541 #confirmDiv > .card
1542 max-width: 767px
1543 max-height: 100%
1544
1545 .draw-sent, .draw-sent:hover
1546 background-color: lightyellow
1547
1548 .draw-received, .draw-received:hover
1549 background-color: lightgreen
1550
1551 .draw-threerep, .draw-threerep:hover
1552 background-color: #e4d1fc
1553
1554 .rematch-sent, .rematch-sent:hover
1555 background-color: lightyellow
1556
1557 .rematch-received, .rematch-received:hover
1558 background-color: lightgreen
1559
1560 .somethingnew
1561 background-color: #c5fefe
1562
1563 .diagram
1564 margin: 0 auto
1565 width: 100%
1566
1567 #buttonsConfirm
1568 margin: 0
1569 & > button > span
1570 width: 100%
1571 text-align: center
1572
1573 button.acceptBtn
1574 background-color: lightgreen
1575 button.refuseBtn
1576 background-color: red
1577 </style>