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 this.$nextTick(() => {
1212 // Disable tooltips on smartphones:
1213 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
1214 elt.classList.remove("tooltip");
1215 });
1216 });
1217 }
1218 this.$refs["basegame"].re_setVariables(this.game);
1219 if (!this.gameIsLoading) {
1220 // Initial loading:
1221 this.gotMoveIdx = game.moves.length - 1;
1222 // If we arrive here after 'nextGame' action, the board might be hidden
1223 let boardDiv = document.querySelector(".game");
1224 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1225 boardDiv.style.visibility = "visible";
1226 }
1227 this.re_setClocks();
1228 this.$nextTick(() => {
1229 this.game.rendered = true;
1230 // Did lastate arrive before game was rendered?
1231 if (this.lastate) this.processLastate();
1232 });
1233 if (this.lastateAsked) {
1234 this.lastateAsked = false;
1235 this.sendLastate(game.oppsid);
1236 }
1237 if (this.gameIsLoading) {
1238 this.gameIsLoading = false;
1239 if (this.gotMoveIdx >= game.moves.length)
1240 // Some moves arrived meanwhile...
1241 this.askGameAgain();
1242 }
1243 if (!!callback) callback();
1244 },
1245 loadVariantThenGame: async function(game, callback) {
1246 await import("@/variants/" + game.vname + ".js")
1247 .then((vModule) => {
1248 window.V = vModule[game.vname + "Rules"];
1249 this.loadGame(game, callback);
1250 });
1251 // (AJAX) Request to get rules content (plain text, HTML)
1252 this.rulesContent =
1253 require(
1254 "raw-loader!@/translations/rules/" +
1255 game.vname + "/" +
1256 this.st.lang + ".pug"
1257 )
1258 // Next two lines fix a weird issue after last update (2019-11)
1259 .replace(/\\n/g, " ")
1260 .replace(/\\"/g, '"')
1261 .replace('module.exports = "', "")
1262 .replace(/"$/, "")
1263 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1264 },
1265 // 3 cases for loading a game:
1266 // - from indexedDB (running or completed live game I play)
1267 // - from server (one correspondance game I play[ed] or not)
1268 // - from remote peer (one live game I don't play, finished or not)
1269 fetchGame: function(callback) {
1270 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1271 // corr games identifiers are integers
1272 ajax(
1273 "/games",
1274 "GET",
1275 {
1276 data: { gid: this.gameRef },
1277 success: (res) => {
1278 res.game.moves.forEach(m => {
1279 m.squares = JSON.parse(m.squares);
1280 });
1281 callback(res.game);
1282 }
1283 }
1284 );
1285 }
1286 else if (!!this.gameRef.match(/^i/))
1287 // Game import (maybe remote)
1288 ImportgameStorage.get(this.gameRef, callback);
1289 else
1290 // Local live game (or remote)
1291 GameStorage.get(this.gameRef, callback);
1292 },
1293 re_setClocks: function() {
1294 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1295 if (this.game.moves.length < 2 || this.game.score != "*") {
1296 // 1st move not completed yet, or game over: freeze time
1297 return;
1298 }
1299 const currentTurn = this.vr.turn;
1300 const currentMovesCount = this.game.moves.length;
1301 const colorIdx = ["w", "b"].indexOf(currentTurn);
1302 this.clockUpdate = setInterval(
1303 () => {
1304 if (
1305 this.game.clocks[colorIdx] < 0 ||
1306 this.game.moves.length > currentMovesCount ||
1307 this.game.score != "*"
1308 ) {
1309 clearInterval(this.clockUpdate);
1310 this.clockUpdate = null;
1311 if (this.game.clocks[colorIdx] < 0)
1312 this.gameOver(
1313 currentTurn == "w" ? "0-1" : "1-0",
1314 "Time"
1315 );
1316 } else {
1317 this.$set(
1318 this.virtualClocks,
1319 colorIdx,
1320 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1321 );
1322 }
1323 },
1324 1000
1325 );
1326 },
1327 // Update variables and storage after a move:
1328 processMove: function(move, data) {
1329 if (this.game.type == "import")
1330 // Shouldn't receive any messages in this mode:
1331 return;
1332 if (!data) data = {};
1333 const moveCol = this.vr.turn;
1334 const colorIdx = ["w", "b"].indexOf(moveCol);
1335 const nextIdx = 1 - colorIdx;
1336 const doProcessMove = () => {
1337 const origMovescount = this.game.moves.length;
1338 // The move is (about to be) played: stop clock
1339 clearInterval(this.clockUpdate);
1340 this.clockUpdate = null;
1341 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1342 if (this.drawOffer == "received")
1343 // I refuse draw
1344 this.drawOffer = "";
1345 if (this.game.type == "live" && origMovescount >= 2) {
1346 this.game.clocks[colorIdx] += this.game.increment;
1347 // For a correct display in casqe of disconnected opponent:
1348 this.$set(
1349 this.virtualClocks,
1350 colorIdx,
1351 ppt(this.game.clocks[colorIdx]).split(':')
1352 );
1353 GameStorage.update(this.gameRef, {
1354 // It's not my turn anymore:
1355 initime: null
1356 });
1357 }
1358 }
1359 // Update current game object:
1360 playMove(move, this.vr);
1361 if (!data.score)
1362 // Received move, score is computed in BaseGame, but maybe not yet.
1363 // ==> Compute it here, although this is redundant (TODO)
1364 data.score = this.vr.getCurrentScore();
1365 if (data.score != "*") this.gameOver(data.score);
1366 this.game.moves.push(move);
1367 this.game.fen = this.vr.getFen();
1368 if (this.game.type == "corr") {
1369 // In corr games, just reset clock to mainTime:
1370 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1371 }
1372 // If repetition detected, consider that a draw offer was received:
1373 const fenObj = this.vr.getFenForRepeat();
1374 this.repeat[fenObj] =
1375 !!this.repeat[fenObj]
1376 ? this.repeat[fenObj] + 1
1377 : 1;
1378 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1379 else if (this.drawOffer == "threerep") this.drawOffer = "";
1380 if (!!this.game.mycolor && !data.receiveMyMove) {
1381 // NOTE: 'var' to see that variable outside this block
1382 var filtered_move = getFilteredMove(move);
1383 }
1384 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1385 // Notify turn on MyGames page:
1386 this.notifyMyGames(
1387 "turn",
1388 {
1389 gid: this.gameRef,
1390 turn: this.vr.turn
1391 }
1392 );
1393 }
1394 // Since corr games are stored at only one location, update should be
1395 // done only by one player for each move:
1396 if (
1397 this.game.type == "live" &&
1398 !!this.game.mycolor &&
1399 moveCol != this.game.mycolor &&
1400 this.game.moves.length >= 2
1401 ) {
1402 // Receive a move: update initime
1403 this.game.initime = Date.now();
1404 GameStorage.update(this.gameRef, {
1405 // It's my turn now!
1406 initime: this.game.initime
1407 });
1408 }
1409 if (
1410 !!this.game.mycolor &&
1411 !data.receiveMyMove &&
1412 (this.game.type == "live" || moveCol == this.game.mycolor)
1413 ) {
1414 let drawCode = "";
1415 switch (this.drawOffer) {
1416 case "threerep":
1417 drawCode = "t";
1418 break;
1419 case "sent":
1420 drawCode = this.game.mycolor;
1421 break;
1422 case "received":
1423 drawCode = V.GetOppCol(this.game.mycolor);
1424 break;
1425 }
1426 if (this.game.type == "corr") {
1427 // corr: only move, fen and score
1428 this.updateCorrGame({
1429 fen: this.game.fen,
1430 move: {
1431 squares: filtered_move,
1432 idx: origMovescount
1433 },
1434 // Code "n" for "None" to force reset (otherwise it's ignored)
1435 drawOffer: drawCode || "n"
1436 });
1437 }
1438 else {
1439 const updateStorage = () => {
1440 GameStorage.update(this.gameRef, {
1441 fen: this.game.fen,
1442 move: filtered_move,
1443 moveIdx: origMovescount,
1444 clocks: this.game.clocks,
1445 drawOffer: drawCode
1446 });
1447 };
1448 // The active tab can update storage immediately
1449 if (this.focus) updateStorage();
1450 // Small random delay otherwise
1451 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1452 }
1453 }
1454 // Send move ("newmove" event) to people in the room (if our turn)
1455 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1456 let sendMove = {
1457 move: filtered_move,
1458 index: origMovescount,
1459 // color is required to check if this is my move
1460 // (if several tabs opened)
1461 color: moveCol,
1462 cancelDrawOffer: this.drawOffer == ""
1463 };
1464 if (this.game.type == "live")
1465 sendMove["clock"] = this.game.clocks[colorIdx];
1466 // (Live) Clocks will re-start when the opponent pingback arrive
1467 this.opponentGotMove = false;
1468 this.send("newmove", {data: sendMove});
1469 // If the opponent doesn't reply gotmove soon enough, re-send move:
1470 // Do this at most 2 times, because mpore would mean network issues,
1471 // opponent would then be expected to disconnect/reconnect.
1472 let counter = 1;
1473 const currentUrl = document.location.href;
1474 this.retrySendmove = setInterval(
1475 () => {
1476 if (
1477 counter >= 3 ||
1478 this.opponentGotMove ||
1479 document.location.href != currentUrl //page change
1480 ) {
1481 clearInterval(this.retrySendmove);
1482 return;
1483 }
1484 const oppsid = this.getOppsid();
1485 if (!oppsid)
1486 // Opponent is disconnected: he'll ask last state
1487 clearInterval(this.retrySendmove);
1488 else {
1489 this.send("newmove", { data: sendMove, target: oppsid });
1490 counter++;
1491 }
1492 },
1493 1500
1494 );
1495 }
1496 else
1497 // Not my move or I'm an observer: just start other player's clock
1498 this.re_setClocks();
1499 };
1500 if (
1501 this.game.type == "corr" &&
1502 moveCol == this.game.mycolor &&
1503 !data.receiveMyMove
1504 ) {
1505 let boardDiv = document.querySelector(".game");
1506 const afterSetScore = () => {
1507 doProcessMove();
1508 if (this.st.settings.gotonext && this.nextIds.length > 0)
1509 this.showNextGame();
1510 else {
1511 // The board might have been hidden:
1512 if (boardDiv.style.visibility == "hidden")
1513 boardDiv.style.visibility = "visible";
1514 if (data.score == "*") this.re_setClocks();
1515 }
1516 };
1517 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1518 // We may play several moves in a row: in case of, remove listener:
1519 let elClone = el.cloneNode(true);
1520 el.parentNode.replaceChild(elClone, el);
1521 elClone.addEventListener(
1522 "click",
1523 () => {
1524 document.getElementById("modalConfirm").checked = false;
1525 if (!!data.score && data.score != "*")
1526 // Set score first
1527 this.gameOver(data.score, null, afterSetScore);
1528 else afterSetScore();
1529 }
1530 );
1531 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1532 const arMove = (Array.isArray(move) ? move : [move]);
1533 for (let i = 0; i < arMove.length; i++)
1534 V.PlayOnBoard(this.vr.board, arMove[i]);
1535 const position = this.vr.getBaseFen();
1536 for (let i = arMove.length - 1; i >= 0; i--)
1537 V.UndoOnBoard(this.vr.board, arMove[i]);
1538 if (["all","byrow"].includes(V.ShowMoves)) {
1539 this.curDiag = getDiagram({
1540 position: position,
1541 orientation: V.CanFlip ? this.game.mycolor : "w"
1542 });
1543 document.querySelector("#confirmDiv > .card").style.width =
1544 boardDiv.offsetWidth + "px";
1545 } else {
1546 // Incomplete information: just ask confirmation
1547 // Hide the board, because otherwise it could reveal infos
1548 boardDiv.style.visibility = "hidden";
1549 this.moveNotation = getFullNotation(move);
1550 }
1551 document.getElementById("modalConfirm").checked = true;
1552 }
1553 else {
1554 // Normal situation
1555 if (!!data.score && data.score != "*")
1556 this.gameOver(data.score, null, doProcessMove);
1557 else doProcessMove();
1558 }
1559 },
1560 cancelMove: function() {
1561 let boardDiv = document.querySelector(".game");
1562 if (boardDiv.style.visibility == "hidden")
1563 boardDiv.style.visibility = "visible";
1564 document.getElementById("modalConfirm").checked = false;
1565 this.$refs["basegame"].cancelLastMove();
1566 },
1567 // In corr games, callback to change page only after score is set:
1568 gameOver: function(score, scoreMsg, callback) {
1569 this.game.score = score;
1570 if ("ontouchstart" in window) {
1571 this.$nextTick(() => {
1572 // Disable tooltips on smartphones
1573 // (might be required for rematch button at least):
1574 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
1575 elt.classList.remove("tooltip");
1576 });
1577 });
1578 }
1579 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1580 this.game.scoreMsg = scoreMsg;
1581 document.getElementById("modalRules").checked = false;
1582 // Display result in a un-missable way:
1583 document.getElementById("modalScore").checked = true;
1584 this.$set(this.game, "scoreMsg", scoreMsg);
1585 const myIdx = this.game.players.findIndex(p => {
1586 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1587 });
1588 if (myIdx >= 0) {
1589 // OK, I play in this game
1590 const scoreObj = {
1591 score: score,
1592 scoreMsg: scoreMsg
1593 };
1594 if (this.game.type == "live") {
1595 GameStorage.update(this.gameRef, scoreObj);
1596 // Notify myself locally if I'm elsewhere:
1597 if (!this.focus) {
1598 notify(
1599 "Game over",
1600 { body: score + " : " + scoreMsg }
1601 );
1602 }
1603 if (!!callback) callback();
1604 }
1605 else this.updateCorrGame(scoreObj, callback);
1606 // Notify the score to main Hall.
1607 // TODO: only one player (currently double send)
1608 this.send("result", { gid: this.game.id, score: score });
1609 // Also to MyGames page (TODO: doubled as well...)
1610 this.notifyMyGames(
1611 "score",
1612 {
1613 gid: this.gameRef,
1614 score: score
1615 }
1616 );
1617 }
1618 else if (!!callback) callback();
1619 }
1620 }
1621 };
1622 </script>
1623
1624 <style lang="sass" scoped>
1625 #scoreDiv > .card, #rematchDiv > .card
1626 padding: 10px 0
1627 max-width: 430px
1628
1629 #rulesDiv > .card
1630 padding: 5px 0
1631 max-width: 50%
1632 max-height: 100%
1633 @media screen and (max-width: 1500px)
1634 max-width: 67%
1635 @media screen and (max-width: 1024px)
1636 max-width: 85%
1637 @media screen and (max-width: 767px)
1638 max-width: 100%
1639
1640 p.score-section
1641 margin: 0
1642 font-size: 1.3em
1643 span.score
1644 font-weight: bold
1645
1646 .connected
1647 background-color: lightgreen
1648
1649 #participants
1650 margin-left: 5px
1651
1652 .anonymous
1653 color: grey
1654 font-style: italic
1655
1656 #playersInfo > p
1657 margin: 0
1658
1659 @media screen and (max-width: 767px)
1660 .game
1661 width: 100%
1662
1663 #actions
1664 display: inline-block
1665 margin: 0
1666
1667 button
1668 display: inline-block
1669 margin: 0
1670 display: inline-flex
1671 img
1672 height: 22px
1673 display: flex
1674 @media screen and (max-width: 767px)
1675 height: 18px
1676
1677 #aboveBoard
1678 text-align: center
1679
1680 .variant-cadence
1681 padding-right: 10px
1682
1683 .variant-name
1684 font-weight: bold
1685 padding-right: 10px
1686
1687 span#nextGame
1688 background-color: #edda99
1689 cursor: pointer
1690 display: inline-block
1691 margin-right: 10px
1692
1693 span.separator
1694 display: inline-block
1695 margin: 0
1696 padding: 0
1697 width: 10px
1698
1699 span.name
1700 font-size: 1.5rem
1701 padding: 0 3px
1702
1703 span.time
1704 font-size: 2rem
1705 display: inline-block
1706 .time-left
1707 margin-left: 10px
1708 .time-right
1709 margin-left: 5px
1710 .time-separator
1711 margin-left: 5px
1712 position: relative
1713 top: -1px
1714
1715 span.yourturn
1716 color: #831B1B
1717 .time-separator
1718 animation: blink-animation 2s steps(3, start) infinite
1719 @keyframes blink-animation
1720 to
1721 visibility: hidden
1722
1723 .split-names
1724 display: inline-block
1725 margin: 0 15px
1726
1727 #chatWrap > .card
1728 padding-top: 20px
1729 max-width: 767px
1730 border: none
1731
1732 #confirmDiv > .card
1733 max-width: 767px
1734 max-height: 100%
1735
1736 .draw-sent, .draw-sent:hover
1737 background-color: lightyellow
1738
1739 .draw-received, .draw-received:hover
1740 background-color: lightgreen
1741
1742 .draw-threerep, .draw-threerep:hover
1743 background-color: #e4d1fc
1744
1745 .rematch-sent, .rematch-sent:hover
1746 background-color: lightyellow
1747
1748 .rematch-received, .rematch-received:hover
1749 background-color: lightgreen
1750
1751 .somethingnew
1752 background-color: #c5fefe
1753
1754 .diagram
1755 margin: 0 auto
1756 width: 100%
1757
1758 #buttonsConfirm
1759 margin: 0
1760 & > button > span
1761 width: 100%
1762 text-align: center
1763
1764 button.acceptBtn
1765 background-color: lightgreen
1766 button.refuseBtn
1767 background-color: red
1768
1769 h4#variantNameInGame
1770 cursor: pointer
1771 text-align: center
1772 text-decoration: underline
1773 font-weight: bold
1774 </style>
1775
1776 <style lang="sass">
1777 @import "@/styles/_rules.sass"
1778 @import "@/styles/_board_squares_img.sass"
1779 </style>