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