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