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