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