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