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