Add Orda variant. Some advances in Dynamo draft. Display error message when loading...
[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 },
412 clearChat: function() {
413 // Nothing more to do if game is live (chats not recorded)
414 if (this.game.type == "corr") {
415 if (!!this.game.mycolor) {
416 ajax(
417 "/chats",
418 "DELETE",
419 { data: { gid: this.game.id } }
420 );
421 }
422 this.$set(this.game, "chats", []);
423 }
424 },
425 getGameType: function(game) {
426 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
427 },
428 // Notify something after a new move (to opponent and me on MyGames page)
429 notifyMyGames: function(thing, data) {
430 this.send(
431 "notify" + thing,
432 {
433 data: data,
434 targets: this.game.players.map(p => {
435 return { sid: p.sid, id: p.id };
436 })
437 }
438 );
439 },
440 showNextGame: function() {
441 // Did I play in current game? If not, add it to nextIds list
442 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
443 this.nextIds.unshift(this.game.id);
444 const nextGid = this.nextIds.pop();
445 this.$router.push(
446 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
447 },
448 askGameAgain: function() {
449 this.gameIsLoading = true;
450 const currentUrl = document.location.href;
451 const doAskGame = () => {
452 if (document.location.href != currentUrl) return; //page change
453 this.fetchGame((game) => {
454 if (!!game)
455 // This is my game: just reload.
456 this.loadGame(game);
457 else
458 // Just ask fullgame again (once!), this is much simpler.
459 // If this fails, the user could just reload page :/
460 this.send("askfullgame");
461 });
462 };
463 // Delay of at least 2s between two game requests
464 const now = Date.now();
465 const delay = Math.max(2000 - (now - this.askGameTime), 0);
466 this.askGameTime = now;
467 setTimeout(doAskGame, delay);
468 },
469 socketMessageListener: function(msg) {
470 if (!this.conn) return;
471 const data = JSON.parse(msg.data);
472 switch (data.code) {
473 case "pollclients":
474 // TODO: shuffling and random filtering on server,
475 // if the room is really crowded.
476 Object.keys(data.sockIds).forEach(sid => {
477 if (sid != this.st.user.sid) {
478 this.send("askidentity", { target: sid });
479 this.people[sid] = { tmpIds: data.sockIds[sid] };
480 } else {
481 // Complete my tmpIds:
482 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
483 }
484 });
485 break;
486 case "connect":
487 if (!this.people[data.from[0]]) {
488 // focus depends on the tmpId (e.g. tab)
489 this.$set(
490 this.people,
491 data.from[0],
492 {
493 tmpIds: {
494 [data.from[1]]: { focus: true }
495 }
496 }
497 );
498 this.newConnect[data.from] = true; //for self multi-connects tests
499 this.send("askidentity", { target: data.from[0] });
500 } else {
501 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
502 this.$forceUpdate(); //TODO: shouldn't be required
503 }
504 break;
505 case "disconnect":
506 if (!this.people[data.from[0]]) return;
507 delete this.people[data.from[0]].tmpIds[data.from[1]];
508 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
509 this.$delete(this.people, data.from[0]);
510 else this.$forceUpdate(); //TODO: shouldn't be required
511 break;
512 case "getfocus": {
513 let player = this.people[data.from[0]];
514 if (!!player) {
515 player.tmpIds[data.from[1]].focus = true;
516 this.$forceUpdate(); //TODO: shouldn't be required
517 }
518 break;
519 }
520 case "losefocus": {
521 let player = this.people[data.from[0]];
522 if (!!player) {
523 player.tmpIds[data.from[1]].focus = false;
524 this.$forceUpdate(); //TODO: shouldn't be required
525 }
526 break;
527 }
528 case "killed":
529 // I logged in elsewhere:
530 this.conn.removeEventListener("message", this.socketMessageListener);
531 this.conn.removeEventListener("close", this.socketCloseListener);
532 this.conn = null;
533 alert(this.st.tr["New connexion detected: tab now offline"]);
534 break;
535 case "askidentity": {
536 // Request for identification
537 const me = {
538 // Decompose to avoid revealing email
539 name: this.st.user.name,
540 sid: this.st.user.sid,
541 id: this.st.user.id
542 };
543 this.send("identity", { data: me, target: data.from });
544 break;
545 }
546 case "identity": {
547 const user = data.data;
548 let player = this.people[user.sid];
549 // player.tmpIds is already set
550 player.name = user.name;
551 player.id = user.id;
552 this.$forceUpdate(); //TODO: shouldn't be required
553 // If I multi-connect, kill current connexion if no mark (I'm older)
554 if (this.newConnect[user.sid]) {
555 if (
556 user.id > 0 &&
557 user.id == this.st.user.id &&
558 user.sid != this.st.user.sid &&
559 !this.killed[this.st.user.sid]
560 ) {
561 this.send("killme", { sid: this.st.user.sid });
562 this.killed[this.st.user.sid] = true;
563 }
564 delete this.newConnect[user.sid];
565 }
566 if (!this.killed[this.st.user.sid]) {
567 // Ask potentially missed last state, if opponent and I play
568 if (
569 !this.gotLastate &&
570 !!this.game.mycolor &&
571 this.game.type == "live" &&
572 this.game.score == "*" &&
573 this.game.players.some(p => p.sid == user.sid)
574 ) {
575 this.send("asklastate", { target: user.sid });
576 let counter = 1;
577 this.askLastate = setInterval(
578 () => {
579 // Ask at most 3 times:
580 // if no reply after that there should be a network issue.
581 if (
582 counter < 3 &&
583 !this.gotLastate &&
584 !!this.people[user.sid]
585 ) {
586 this.send("asklastate", { target: user.sid });
587 counter++;
588 } else {
589 clearInterval(this.askLastate);
590 }
591 },
592 1500
593 );
594 }
595 }
596 break;
597 }
598 case "askgame":
599 // Send current (live) game if not asked by any of the players
600 if (
601 this.game.type == "live" &&
602 this.game.players.every(p => p.sid != data.from[0])
603 ) {
604 const myGame = {
605 id: this.game.id,
606 fen: this.game.fen,
607 players: this.game.players,
608 vid: this.game.vid,
609 cadence: this.game.cadence,
610 score: this.game.score
611 };
612 this.send("game", { data: myGame, target: data.from });
613 }
614 break;
615 case "askfullgame":
616 const gameToSend = Object.keys(this.game)
617 .filter(k =>
618 [
619 "id","fen","players","vid","cadence","fenStart","vname",
620 "moves","clocks","score","drawOffer","rematchOffer"
621 ].includes(k))
622 .reduce(
623 (obj, k) => {
624 obj[k] = this.game[k];
625 return obj;
626 },
627 {}
628 );
629 this.send("fullgame", { data: gameToSend, target: data.from });
630 break;
631 case "fullgame":
632 if (!!data.data.empty) {
633 alert(this.st.tr["The game should be in another tab"]);
634 this.$router.go(-1);
635 }
636 else
637 // Callback "roomInit" to poll clients only after game is loaded
638 this.loadVariantThenGame(data.data, this.roomInit);
639 break;
640 case "asklastate":
641 // Sending informative last state if I played a move or score != "*"
642 // If the game or moves aren't loaded yet, delay the sending:
643 // TODO: since socket init after game load, the game is supposedly ready
644 if (!this.game || !this.game.moves) this.lastateAsked = true;
645 else this.sendLastate(data.from);
646 break;
647 case "lastate": {
648 // Got opponent infos about last move
649 this.gotLastate = true;
650 this.lastate = data.data;
651 if (this.game.rendered)
652 // Game is rendered (Board component)
653 this.processLastate();
654 // Else: will be processed when game is ready
655 break;
656 }
657 case "newmove": {
658 const movePlus = data.data;
659 const movesCount = this.game.moves.length;
660 if (movePlus.index > movesCount) {
661 // This can only happen if I'm an observer and missed a move.
662 if (this.gotMoveIdx < movePlus.index)
663 this.gotMoveIdx = movePlus.index;
664 if (!this.gameIsLoading) this.askGameAgain();
665 }
666 else {
667 if (
668 movePlus.index < movesCount ||
669 this.gotMoveIdx >= movePlus.index
670 ) {
671 // Opponent re-send but we already have the move:
672 // (maybe he didn't receive our pingback...)
673 this.send("gotmove", {data: movePlus.index, target: data.from});
674 } else {
675 this.gotMoveIdx = movePlus.index;
676 const receiveMyMove = (movePlus.color == this.game.mycolor);
677 if (!receiveMyMove && !!this.game.mycolor)
678 // Notify opponent that I got the move:
679 this.send("gotmove", {data: movePlus.index, target: data.from});
680 if (movePlus.cancelDrawOffer) {
681 // Opponent refuses draw
682 this.drawOffer = "";
683 // NOTE for corr games: drawOffer reset by player in turn
684 if (
685 this.game.type == "live" &&
686 !!this.game.mycolor &&
687 !receiveMyMove
688 ) {
689 GameStorage.update(this.gameRef, { drawOffer: "" });
690 }
691 }
692 this.$refs["basegame"].play(movePlus.move, "received", null, true);
693 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
694 this.game.clocks[moveColIdx] = movePlus.clock;
695 this.processMove(
696 movePlus.move,
697 { receiveMyMove: receiveMyMove }
698 );
699 }
700 }
701 break;
702 }
703 case "gotmove": {
704 this.opponentGotMove = true;
705 // Now his clock starts running on my side:
706 const oppIdx = ['w','b'].indexOf(this.vr.turn);
707 // NOTE: next line to avoid multi-resetClocks when several tabs
708 // on same game, resulting in a faster countdown.
709 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
710 this.re_setClocks();
711 break;
712 }
713 case "resign":
714 const score = (data.data == "b" ? "1-0" : "0-1");
715 const side = (data.data == "w" ? "White" : "Black");
716 this.gameOver(score, side + " surrender");
717 break;
718 case "abort":
719 this.gameOver("?", "Stop");
720 break;
721 case "draw":
722 this.gameOver("1/2", data.data);
723 break;
724 case "drawoffer":
725 // NOTE: observers don't know who offered draw
726 this.drawOffer = "received";
727 if (this.game.type == "live") {
728 GameStorage.update(
729 this.gameRef,
730 { drawOffer: V.GetOppCol(this.game.mycolor) }
731 );
732 }
733 break;
734 case "rematchoffer":
735 // NOTE: observers don't know who offered rematch
736 this.rematchOffer = data.data ? "received" : "";
737 if (this.game.type == "live") {
738 GameStorage.update(
739 this.gameRef,
740 { rematchOffer: V.GetOppCol(this.game.mycolor) }
741 );
742 }
743 break;
744 case "newgame": {
745 // A game started, redirect if I'm playing in
746 const gameInfo = data.data;
747 const gameType = this.getGameType(gameInfo);
748 if (
749 gameType == "live" &&
750 gameInfo.players.some(p => p.sid == this.st.user.sid)
751 ) {
752 this.addAndGotoLiveGame(gameInfo);
753 } else if (
754 gameType == "corr" &&
755 gameInfo.players.some(p => p.id == this.st.user.id)
756 ) {
757 this.$router.push("/game/" + gameInfo.id);
758 } else {
759 this.rematchId = gameInfo.id;
760 document.getElementById("modalInfo").checked = true;
761 }
762 break;
763 }
764 case "newchat":
765 this.$refs["chatcomp"].newChat(data.data);
766 if (!document.getElementById("modalChat").checked)
767 document.getElementById("chatBtn").classList.add("somethingnew");
768 break;
769 }
770 },
771 updateCorrGame: function(obj, callback) {
772 ajax(
773 "/games",
774 "PUT",
775 {
776 data: {
777 gid: this.gameRef,
778 newObj: obj
779 },
780 success: () => {
781 if (!!callback) callback();
782 }
783 }
784 );
785 },
786 sendLastate: function(target) {
787 // Send our "last state" informations to opponent
788 const L = this.game.moves.length;
789 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
790 const myLastate = {
791 lastMove:
792 (L > 0 && this.vr.turn != this.game.mycolor)
793 ? this.game.moves[L - 1]
794 : undefined,
795 clock: this.game.clocks[myIdx],
796 // Since we played a move (or abort or resign),
797 // only drawOffer=="sent" is possible
798 drawSent: this.drawOffer == "sent",
799 rematchSent: this.rematchOffer == "sent",
800 score: this.game.score != "*" ? this.game.score : undefined,
801 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
802 movesCount: L
803 };
804 this.send("lastate", { data: myLastate, target: target });
805 },
806 // lastate was received, but maybe game wasn't ready yet:
807 processLastate: function() {
808 const data = this.lastate;
809 this.lastate = undefined; //security...
810 const L = this.game.moves.length;
811 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
812 this.game.clocks[oppIdx] = data.clock;
813 if (data.movesCount > L) {
814 // Just got last move from him
815 this.$refs["basegame"].play(data.lastMove, "received", null, true);
816 this.processMove(data.lastMove);
817 } else {
818 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
819 this.re_setClocks();
820 }
821 if (data.drawSent) this.drawOffer = "received";
822 if (data.rematchSent) this.rematchOffer = "received";
823 if (!!data.score) {
824 this.drawOffer = "";
825 if (this.game.score == "*")
826 this.gameOver(data.score, data.scoreMsg);
827 }
828 },
829 clickDraw: function() {
830 if (!this.game.mycolor) return; //I'm just spectator
831 if (["received", "threerep"].includes(this.drawOffer)) {
832 if (!confirm(this.st.tr["Accept draw?"])) return;
833 const message =
834 this.drawOffer == "received"
835 ? "Mutual agreement"
836 : "Three repetitions";
837 this.send("draw", { data: message });
838 this.gameOver("1/2", message);
839 } else if (this.drawOffer == "") {
840 // No effect if drawOffer == "sent"
841 if (this.game.mycolor != this.vr.turn) {
842 alert(this.st.tr["Draw offer only in your turn"]);
843 return;
844 }
845 if (!confirm(this.st.tr["Offer draw?"])) return;
846 this.drawOffer = "sent";
847 this.send("drawoffer");
848 if (this.game.type == "live") {
849 GameStorage.update(
850 this.gameRef,
851 { drawOffer: this.game.mycolor }
852 );
853 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
854 }
855 },
856 addAndGotoLiveGame: function(gameInfo, callback) {
857 const game = Object.assign(
858 {},
859 gameInfo,
860 {
861 // (other) Game infos: constant
862 fenStart: gameInfo.fen,
863 vname: this.game.vname,
864 created: Date.now(),
865 // Game state (including FEN): will be updated
866 moves: [],
867 clocks: [-1, -1], //-1 = unstarted
868 score: "*"
869 }
870 );
871 GameStorage.add(game, (err) => {
872 // No error expected.
873 if (!err) {
874 if (this.st.settings.sound)
875 new Audio("/sounds/newgame.flac").play().catch(() => {});
876 if (!!callback) callback();
877 this.$router.push("/game/" + gameInfo.id);
878 }
879 });
880 },
881 clickRematch: function() {
882 if (!this.game.mycolor) return; //I'm just spectator
883 if (this.rematchOffer == "received") {
884 // Start a new game!
885 let gameInfo = {
886 id: getRandString(), //ignored if corr
887 fen: V.GenRandInitFen(this.game.randomness),
888 players: this.game.players.reverse(),
889 vid: this.game.vid,
890 cadence: this.game.cadence
891 };
892 const notifyNewGame = () => {
893 const oppsid = this.getOppsid(); //may be null
894 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
895 // To main Hall if corr game:
896 if (this.game.type == "corr")
897 this.send("newgame", { data: gameInfo, page: "/" });
898 // Also to MyGames page:
899 this.notifyMyGames("newgame", gameInfo);
900 };
901 if (this.game.type == "live")
902 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
903 else {
904 // corr game
905 ajax(
906 "/games",
907 "POST",
908 {
909 // cid is useful to delete the challenge:
910 data: { gameInfo: gameInfo },
911 success: (response) => {
912 gameInfo.id = response.gameId;
913 notifyNewGame();
914 this.$router.push("/game/" + response.gameId);
915 }
916 }
917 );
918 }
919 } else if (this.rematchOffer == "") {
920 this.rematchOffer = "sent";
921 this.send("rematchoffer", { data: true });
922 if (this.game.type == "live") {
923 GameStorage.update(
924 this.gameRef,
925 { rematchOffer: this.game.mycolor }
926 );
927 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
928 } else if (this.rematchOffer == "sent") {
929 // Toggle rematch offer (on --> off)
930 this.rematchOffer = "";
931 this.send("rematchoffer", { data: false });
932 if (this.game.type == "live") {
933 GameStorage.update(
934 this.gameRef,
935 { rematchOffer: '' }
936 );
937 } else this.updateCorrGame({ rematchOffer: 'n' });
938 }
939 },
940 abortGame: function() {
941 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
942 this.gameOver("?", "Stop");
943 this.send("abort");
944 },
945 resign: function() {
946 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
947 return;
948 this.send("resign", { data: this.game.mycolor });
949 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
950 const side = (this.game.mycolor == "w" ? "White" : "Black");
951 this.gameOver(score, side + " surrender");
952 },
953 loadGame: function(game, callback) {
954 this.vr = new V(game.fen);
955 const gtype = this.getGameType(game);
956 const tc = extractTime(game.cadence);
957 const myIdx = game.players.findIndex(p => {
958 return p.sid == this.st.user.sid || p.id == this.st.user.id;
959 });
960 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
961 if (!game.chats) game.chats = []; //live games don't have chat history
962 if (gtype == "corr") {
963 // NOTE: clocks in seconds
964 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
965 game.clocks = [tc.mainTime, tc.mainTime];
966 const L = game.moves.length;
967 if (game.score == "*") {
968 // Adjust clocks
969 if (L >= 2) {
970 game.clocks[L % 2] -=
971 (Date.now() - game.moves[L-1].played) / 1000;
972 }
973 }
974 // Sort chat messages from newest to oldest
975 game.chats.sort((c1, c2) => {
976 return c2.added - c1.added;
977 });
978 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
979 // Did a chat message arrive after my last move?
980 let dtLastMove = 0;
981 if (L == 1 && myIdx == 0)
982 dtLastMove = game.moves[0].played;
983 else if (L >= 2) {
984 if (L % 2 == 0) {
985 // It's now white turn
986 dtLastMove = game.moves[L-1-(1-myIdx)].played;
987 } else {
988 // Black turn:
989 dtLastMove = game.moves[L-1-myIdx].played;
990 }
991 }
992 if (dtLastMove < game.chats[0].added)
993 document.getElementById("chatBtn").classList.add("somethingnew");
994 }
995 // Now that we used idx and played, re-format moves as for live games
996 game.moves = game.moves.map(m => m.squares);
997 }
998 if (gtype == "live") {
999 if (game.clocks[0] < 0) {
1000 // Game is unstarted. clock is ignored until move 2
1001 game.clocks = [tc.mainTime, tc.mainTime];
1002 if (myIdx >= 0) {
1003 // I play in this live game
1004 GameStorage.update(game.id, {
1005 clocks: game.clocks
1006 });
1007 }
1008 } else {
1009 if (!!game.initime)
1010 // It's my turn: clocks not updated yet
1011 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1012 }
1013 }
1014 // TODO: merge next 2 "if" conditions
1015 if (!!game.drawOffer) {
1016 if (game.drawOffer == "t")
1017 // Three repetitions
1018 this.drawOffer = "threerep";
1019 else {
1020 // Draw offered by any of the players:
1021 if (myIdx < 0) this.drawOffer = "received";
1022 else {
1023 // I play in this game:
1024 if (
1025 (game.drawOffer == "w" && myIdx == 0) ||
1026 (game.drawOffer == "b" && myIdx == 1)
1027 )
1028 this.drawOffer = "sent";
1029 else this.drawOffer = "received";
1030 }
1031 }
1032 }
1033 if (!!game.rematchOffer) {
1034 if (myIdx < 0) this.rematchOffer = "received";
1035 else {
1036 // I play in this game:
1037 if (
1038 (game.rematchOffer == "w" && myIdx == 0) ||
1039 (game.rematchOffer == "b" && myIdx == 1)
1040 )
1041 this.rematchOffer = "sent";
1042 else this.rematchOffer = "received";
1043 }
1044 }
1045 this.repeat = {}; //reset: scan past moves' FEN:
1046 let repIdx = 0;
1047 let vr_tmp = new V(game.fenStart);
1048 let curTurn = "n";
1049 game.moves.forEach(m => {
1050 playMove(m, vr_tmp);
1051 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1052 this.repeat[fenIdx] = this.repeat[fenIdx]
1053 ? this.repeat[fenIdx] + 1
1054 : 1;
1055 });
1056 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1057 this.game = Object.assign(
1058 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1059 {
1060 type: gtype,
1061 increment: tc.increment,
1062 mycolor: mycolor,
1063 // opponent sid not strictly required (or available), but easier
1064 // at least oppsid or oppid is available anyway:
1065 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1066 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1067 },
1068 game
1069 );
1070 this.$refs["basegame"].re_setVariables(this.game);
1071 if (!this.gameIsLoading) {
1072 // Initial loading:
1073 this.gotMoveIdx = game.moves.length - 1;
1074 // If we arrive here after 'nextGame' action, the board might be hidden
1075 let boardDiv = document.querySelector(".game");
1076 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1077 boardDiv.style.visibility = "visible";
1078 }
1079 this.re_setClocks();
1080 this.$nextTick(() => {
1081 this.game.rendered = true;
1082 // Did lastate arrive before game was rendered?
1083 if (this.lastate) this.processLastate();
1084 });
1085 if (this.lastateAsked) {
1086 this.lastateAsked = false;
1087 this.sendLastate(game.oppsid);
1088 }
1089 if (this.gameIsLoading) {
1090 this.gameIsLoading = false;
1091 if (this.gotMoveIdx >= game.moves.length)
1092 // Some moves arrived meanwhile...
1093 this.askGameAgain();
1094 }
1095 if (!!callback) callback();
1096 },
1097 loadVariantThenGame: async function(game, callback) {
1098 await import("@/variants/" + game.vname + ".js")
1099 .then((vModule) => {
1100 window.V = vModule[game.vname + "Rules"];
1101 this.loadGame(game, callback);
1102 });
1103 },
1104 // 3 cases for loading a game:
1105 // - from indexedDB (running or completed live game I play)
1106 // - from server (one correspondance game I play[ed] or not)
1107 // - from remote peer (one live game I don't play, finished or not)
1108 fetchGame: function(callback) {
1109 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1110 // corr games identifiers are integers
1111 ajax(
1112 "/games",
1113 "GET",
1114 {
1115 data: { gid: this.gameRef },
1116 success: (res) => {
1117 res.game.moves.forEach(m => {
1118 m.squares = JSON.parse(m.squares);
1119 });
1120 callback(res.game);
1121 }
1122 }
1123 );
1124 } else
1125 // Local game (or live remote)
1126 GameStorage.get(this.gameRef, callback);
1127 },
1128 re_setClocks: function() {
1129 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1130 if (this.game.moves.length < 2 || this.game.score != "*") {
1131 // 1st move not completed yet, or game over: freeze time
1132 return;
1133 }
1134 const currentTurn = this.vr.turn;
1135 const currentMovesCount = this.game.moves.length;
1136 const colorIdx = ["w", "b"].indexOf(currentTurn);
1137 this.clockUpdate = setInterval(
1138 () => {
1139 if (
1140 this.game.clocks[colorIdx] < 0 ||
1141 this.game.moves.length > currentMovesCount ||
1142 this.game.score != "*"
1143 ) {
1144 clearInterval(this.clockUpdate);
1145 this.clockUpdate = null;
1146 if (this.game.clocks[colorIdx] < 0)
1147 this.gameOver(
1148 currentTurn == "w" ? "0-1" : "1-0",
1149 "Time"
1150 );
1151 } else {
1152 this.$set(
1153 this.virtualClocks,
1154 colorIdx,
1155 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1156 );
1157 }
1158 },
1159 1000
1160 );
1161 },
1162 // Update variables and storage after a move:
1163 processMove: function(move, data) {
1164 if (!data) data = {};
1165 const moveCol = this.vr.turn;
1166 const colorIdx = ["w", "b"].indexOf(moveCol);
1167 const nextIdx = 1 - colorIdx;
1168 const doProcessMove = () => {
1169 const origMovescount = this.game.moves.length;
1170 // The move is (about to be) played: stop clock
1171 clearInterval(this.clockUpdate);
1172 this.clockUpdate = null;
1173 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1174 if (this.drawOffer == "received")
1175 // I refuse draw
1176 this.drawOffer = "";
1177 if (this.game.type == "live" && origMovescount >= 2) {
1178 this.game.clocks[colorIdx] += this.game.increment;
1179 // For a correct display in casqe of disconnected opponent:
1180 this.$set(
1181 this.virtualClocks,
1182 colorIdx,
1183 ppt(this.game.clocks[colorIdx]).split(':')
1184 );
1185 GameStorage.update(this.gameRef, {
1186 // It's not my turn anymore:
1187 initime: null
1188 });
1189 }
1190 }
1191 // Update current game object:
1192 playMove(move, this.vr);
1193 if (!data.score)
1194 // Received move, score is computed in BaseGame, but maybe not yet.
1195 // ==> Compute it here, although this is redundant (TODO)
1196 data.score = this.vr.getCurrentScore();
1197 if (data.score != "*") this.gameOver(data.score);
1198 this.game.moves.push(move);
1199 this.game.fen = this.vr.getFen();
1200 if (this.game.type == "corr") {
1201 // In corr games, just reset clock to mainTime:
1202 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1203 }
1204 // If repetition detected, consider that a draw offer was received:
1205 const fenObj = this.vr.getFenForRepeat();
1206 this.repeat[fenObj] =
1207 !!this.repeat[fenObj]
1208 ? this.repeat[fenObj] + 1
1209 : 1;
1210 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1211 else if (this.drawOffer == "threerep") this.drawOffer = "";
1212 if (!!this.game.mycolor && !data.receiveMyMove) {
1213 // NOTE: 'var' to see that variable outside this block
1214 var filtered_move = getFilteredMove(move);
1215 }
1216 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1217 // Notify turn on MyGames page:
1218 this.notifyMyGames(
1219 "turn",
1220 {
1221 gid: this.gameRef,
1222 turn: this.vr.turn
1223 }
1224 );
1225 }
1226 // Since corr games are stored at only one location, update should be
1227 // done only by one player for each move:
1228 if (
1229 this.game.type == "live" &&
1230 !!this.game.mycolor &&
1231 moveCol != this.game.mycolor &&
1232 this.game.moves.length >= 2
1233 ) {
1234 // Receive a move: update initime
1235 this.game.initime = Date.now();
1236 GameStorage.update(this.gameRef, {
1237 // It's my turn now!
1238 initime: this.game.initime
1239 });
1240 }
1241 if (
1242 !!this.game.mycolor &&
1243 !data.receiveMyMove &&
1244 (this.game.type == "live" || moveCol == this.game.mycolor)
1245 ) {
1246 let drawCode = "";
1247 switch (this.drawOffer) {
1248 case "threerep":
1249 drawCode = "t";
1250 break;
1251 case "sent":
1252 drawCode = this.game.mycolor;
1253 break;
1254 case "received":
1255 drawCode = V.GetOppCol(this.game.mycolor);
1256 break;
1257 }
1258 if (this.game.type == "corr") {
1259 // corr: only move, fen and score
1260 this.updateCorrGame({
1261 fen: this.game.fen,
1262 move: {
1263 squares: filtered_move,
1264 idx: origMovescount
1265 },
1266 // Code "n" for "None" to force reset (otherwise it's ignored)
1267 drawOffer: drawCode || "n"
1268 });
1269 }
1270 else {
1271 const updateStorage = () => {
1272 GameStorage.update(this.gameRef, {
1273 fen: this.game.fen,
1274 move: filtered_move,
1275 moveIdx: origMovescount,
1276 clocks: this.game.clocks,
1277 drawOffer: drawCode
1278 });
1279 };
1280 // The active tab can update storage immediately
1281 if (!document.hidden) updateStorage();
1282 // Small random delay otherwise
1283 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1284 }
1285 }
1286 // Send move ("newmove" event) to people in the room (if our turn)
1287 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1288 let sendMove = {
1289 move: filtered_move,
1290 index: origMovescount,
1291 // color is required to check if this is my move (if several tabs opened)
1292 color: moveCol,
1293 cancelDrawOffer: this.drawOffer == ""
1294 };
1295 if (this.game.type == "live")
1296 sendMove["clock"] = this.game.clocks[colorIdx];
1297 // (Live) Clocks will re-start when the opponent pingback arrive
1298 this.opponentGotMove = false;
1299 this.send("newmove", {data: sendMove});
1300 // If the opponent doesn't reply gotmove soon enough, re-send move:
1301 // Do this at most 2 times, because mpore would mean network issues,
1302 // opponent would then be expected to disconnect/reconnect.
1303 let counter = 1;
1304 const currentUrl = document.location.href;
1305 this.retrySendmove = setInterval(
1306 () => {
1307 if (
1308 counter >= 3 ||
1309 this.opponentGotMove ||
1310 document.location.href != currentUrl //page change
1311 ) {
1312 clearInterval(this.retrySendmove);
1313 return;
1314 }
1315 const oppsid = this.getOppsid();
1316 if (!oppsid)
1317 // Opponent is disconnected: he'll ask last state
1318 clearInterval(this.retrySendmove);
1319 else {
1320 this.send("newmove", { data: sendMove, target: oppsid });
1321 counter++;
1322 }
1323 },
1324 1500
1325 );
1326 }
1327 else
1328 // Not my move or I'm an observer: just start other player's clock
1329 this.re_setClocks();
1330 };
1331 if (
1332 this.game.type == "corr" &&
1333 moveCol == this.game.mycolor &&
1334 !data.receiveMyMove
1335 ) {
1336 let boardDiv = document.querySelector(".game");
1337 const afterSetScore = () => {
1338 doProcessMove();
1339 if (this.st.settings.gotonext && this.nextIds.length > 0)
1340 this.showNextGame();
1341 else {
1342 // The board might have been hidden:
1343 if (boardDiv.style.visibility == "hidden")
1344 boardDiv.style.visibility = "visible";
1345 if (data.score == "*") this.re_setClocks();
1346 }
1347 };
1348 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1349 // We may play several moves in a row: in case of, remove listener:
1350 let elClone = el.cloneNode(true);
1351 el.parentNode.replaceChild(elClone, el);
1352 elClone.addEventListener(
1353 "click",
1354 () => {
1355 document.getElementById("modalConfirm").checked = false;
1356 if (!!data.score && data.score != "*")
1357 // Set score first
1358 this.gameOver(data.score, null, afterSetScore);
1359 else afterSetScore();
1360 }
1361 );
1362 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1363 V.PlayOnBoard(this.vr.board, move);
1364 const position = this.vr.getBaseFen();
1365 V.UndoOnBoard(this.vr.board, move);
1366 if (["all","byrow"].includes(V.ShowMoves)) {
1367 this.curDiag = getDiagram({
1368 position: position,
1369 orientation: V.CanFlip ? this.game.mycolor : "w"
1370 });
1371 document.querySelector("#confirmDiv > .card").style.width =
1372 boardDiv.offsetWidth + "px";
1373 } else {
1374 // Incomplete information: just ask confirmation
1375 // Hide the board, because otherwise it could reveal infos
1376 boardDiv.style.visibility = "hidden";
1377 this.moveNotation = getFullNotation(move);
1378 }
1379 document.getElementById("modalConfirm").checked = true;
1380 }
1381 else {
1382 // Normal situation
1383 if (!!data.score && data.score != "*")
1384 this.gameOver(data.score, null, doProcessMove);
1385 else doProcessMove();
1386 }
1387 },
1388 cancelMove: function() {
1389 let boardDiv = document.querySelector(".game");
1390 if (boardDiv.style.visibility == "hidden")
1391 boardDiv.style.visibility = "visible";
1392 document.getElementById("modalConfirm").checked = false;
1393 this.$refs["basegame"].cancelLastMove();
1394 },
1395 // In corr games, callback to change page only after score is set:
1396 gameOver: function(score, scoreMsg, callback) {
1397 this.game.score = score;
1398 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1399 this.game.scoreMsg = scoreMsg;
1400 this.$set(this.game, "scoreMsg", scoreMsg);
1401 const myIdx = this.game.players.findIndex(p => {
1402 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1403 });
1404 if (myIdx >= 0) {
1405 // OK, I play in this game
1406 const scoreObj = {
1407 score: score,
1408 scoreMsg: scoreMsg
1409 };
1410 if (this.game.type == "live") {
1411 GameStorage.update(this.gameRef, scoreObj);
1412 if (!!callback) callback();
1413 }
1414 else this.updateCorrGame(scoreObj, callback);
1415 // Notify the score to main Hall. TODO: only one player (currently double send)
1416 this.send("result", { gid: this.game.id, score: score });
1417 // Also to MyGames page (TODO: doubled as well...)
1418 this.notifyMyGames(
1419 "score",
1420 {
1421 gid: this.gameRef,
1422 score: score
1423 }
1424 );
1425 }
1426 else if (!!callback) callback();
1427 }
1428 }
1429 };
1430 </script>
1431
1432 <style lang="sass" scoped>
1433 #infoDiv > .card
1434 padding: 15px 0
1435 max-width: 430px
1436
1437 .connected
1438 background-color: lightgreen
1439
1440 #participants
1441 margin-left: 5px
1442
1443 .anonymous
1444 color: grey
1445 font-style: italic
1446
1447 #playersInfo > p
1448 margin: 0
1449
1450 @media screen and (min-width: 768px)
1451 #actions
1452 width: 300px
1453 @media screen and (max-width: 767px)
1454 .game
1455 width: 100%
1456
1457 #actions
1458 display: inline-block
1459 margin: 0
1460
1461 button
1462 display: inline-block
1463 margin: 0
1464 display: inline-flex
1465 img
1466 height: 22px
1467 display: flex
1468 @media screen and (max-width: 767px)
1469 height: 18px
1470
1471 @media screen and (max-width: 767px)
1472 #aboveBoard
1473 text-align: center
1474 @media screen and (min-width: 768px)
1475 #aboveBoard
1476 margin-left: 30%
1477
1478 .variant-cadence
1479 padding-right: 10px
1480
1481 .variant-name
1482 font-weight: bold
1483 padding-right: 10px
1484
1485 span#nextGame
1486 background-color: #edda99
1487 cursor: pointer
1488 display: inline-block
1489 margin-right: 10px
1490
1491 span.name
1492 font-size: 1.5rem
1493 padding: 0 3px
1494
1495 span.time
1496 font-size: 2rem
1497 display: inline-block
1498 .time-left
1499 margin-left: 10px
1500 .time-right
1501 margin-left: 5px
1502 .time-separator
1503 margin-left: 5px
1504 position: relative
1505 top: -1px
1506
1507 span.yourturn
1508 color: #831B1B
1509 .time-separator
1510 animation: blink-animation 2s steps(3, start) infinite
1511 @keyframes blink-animation
1512 to
1513 visibility: hidden
1514
1515 .split-names
1516 display: inline-block
1517 margin: 0 15px
1518
1519 #chatWrap > .card
1520 padding-top: 20px
1521 max-width: 767px
1522 border: none
1523
1524 #confirmDiv > .card
1525 max-width: 767px
1526 max-height: 100%
1527
1528 .draw-sent, .draw-sent:hover
1529 background-color: lightyellow
1530
1531 .draw-received, .draw-received:hover
1532 background-color: lightgreen
1533
1534 .draw-threerep, .draw-threerep:hover
1535 background-color: #e4d1fc
1536
1537 .rematch-sent, .rematch-sent:hover
1538 background-color: lightyellow
1539
1540 .rematch-received, .rematch-received:hover
1541 background-color: lightgreen
1542
1543 .somethingnew
1544 background-color: #c5fefe
1545
1546 .diagram
1547 margin: 0 auto
1548 width: 100%
1549
1550 #buttonsConfirm
1551 margin: 0
1552 & > button > span
1553 width: 100%
1554 text-align: center
1555
1556 button.acceptBtn
1557 background-color: lightgreen
1558 button.refuseBtn
1559 background-color: red
1560 </style>