Freeze time between receiving a move and end of animation: more fair (especially...
[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 // Freeze time while the move is being play
811 // (TODO: a callback would be cleaner here)
812 clearInterval(this.clockUpdate);
813 this.clockUpdate = null;
814 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
815 // 250 = length of animation, 500 = delay between sub-moves
816 ? 250 + 750 *
817 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
818 // Incomplete information: no move animation
819 : 0;
820 setTimeout(
821 () => {
822 this.game.clocks[moveColIdx] = movePlus.clock;
823 this.processMove(
824 movePlus.move,
825 { receiveMyMove: receiveMyMove }
826 );
827 },
828 freezeDuration
829 );
830 }
831 }
832 break;
833 }
834 case "gotmove": {
835 this.opponentGotMove = true;
836 // Now his clock starts running on my side:
837 const oppIdx = ['w','b'].indexOf(this.vr.turn);
838 // NOTE: next line to avoid multi-resetClocks when several tabs
839 // on same game, resulting in a faster countdown.
840 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
841 this.re_setClocks();
842 break;
843 }
844 case "resign":
845 const score = (data.data == "b" ? "1-0" : "0-1");
846 const side = (data.data == "w" ? "White" : "Black");
847 this.gameOver(score, side + " surrender");
848 break;
849 case "abort":
850 this.gameOver("?", "Stop");
851 break;
852 case "draw":
853 this.gameOver("1/2", data.data);
854 break;
855 case "drawoffer":
856 // NOTE: observers don't know who offered draw
857 this.drawOffer = "received";
858 if (!!this.game.mycolor && this.game.type == "live") {
859 GameStorage.update(
860 this.gameRef,
861 { drawOffer: V.GetOppCol(this.game.mycolor) }
862 );
863 }
864 break;
865 case "rematchoffer":
866 // NOTE: observers don't know who offered rematch
867 this.rematchOffer = data.data ? "received" : "";
868 if (!!this.game.mycolor && this.game.type == "live") {
869 GameStorage.update(
870 this.gameRef,
871 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
872 );
873 }
874 break;
875 case "newgame": {
876 // A game started, redirect if I'm playing in
877 const gameInfo = data.data;
878 const gameType = this.getGameType(gameInfo);
879 if (
880 gameType == "live" &&
881 gameInfo.players.some(p => p.sid == this.st.user.sid)
882 ) {
883 this.addAndGotoLiveGame(gameInfo);
884 } else if (
885 gameType == "corr" &&
886 gameInfo.players.some(p => p.id == this.st.user.id)
887 ) {
888 this.$router.push("/game/" + gameInfo.id);
889 } else {
890 this.rematchId = gameInfo.id;
891 document.getElementById("modalRules").checked = false;
892 document.getElementById("modalScore").checked = false;
893 document.getElementById("modalRematch").checked = true;
894 }
895 break;
896 }
897 case "newchat": {
898 let chat = data.data;
899 this.$refs["chatcomp"].newChat(chat);
900 if (this.game.type == "live") {
901 chat.added = Date.now();
902 if (!!this.game.mycolor)
903 GameStorage.update(this.gameRef, { chat: chat });
904 }
905 if (!document.getElementById("modalChat").checked)
906 document.getElementById("chatBtn").classList.add("somethingnew");
907 break;
908 }
909 }
910 },
911 updateCorrGame: function(obj, callback) {
912 ajax(
913 "/games",
914 "PUT",
915 {
916 data: {
917 gid: this.gameRef,
918 newObj: obj
919 },
920 success: () => {
921 if (!!callback) callback();
922 }
923 }
924 );
925 },
926 sendLastate: function(target) {
927 // Send our "last state" informations to opponent
928 const L = this.game.moves.length;
929 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
930 const myLastate = {
931 lastMove:
932 (L > 0 && this.vr.turn != this.game.mycolor)
933 ? this.game.moves[L - 1]
934 : undefined,
935 clock: this.game.clocks[myIdx],
936 // Since we played a move (or abort or resign),
937 // only drawOffer=="sent" is possible
938 drawSent: this.drawOffer == "sent" ? true : undefined,
939 rematchSent: this.rematchOffer == "sent" ? true : undefined,
940 score: this.game.score != "*" ? this.game.score : undefined,
941 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
942 movesCount: L
943 };
944 this.send("lastate", { data: myLastate, target: target });
945 },
946 // lastate was received, but maybe game wasn't ready yet:
947 processLastate: function() {
948 const data = this.lastate;
949 this.lastate = undefined; //security...
950 if (!!data.score) {
951 const oppCol = V.GetOppCol(this.game.mycolor);
952 if (!!data.rematchSent) {
953 if (this.game.rematchOffer != oppCol) {
954 // Opponent sended rematch offer while we were offline:
955 this.rematchOffer = "received";
956 GameStorage.update(
957 this.gameRef,
958 { rematchOffer: oppCol }
959 );
960 }
961 }
962 else {
963 if (this.game.rematchOffer == oppCol) {
964 // Opponent cancelled rematch offer while we were offline:
965 this.rematchOffer = "";
966 GameStorage.update(
967 this.gameRef,
968 { rematchOffer: "" }
969 );
970 }
971 }
972 }
973 else {
974 const L = this.game.moves.length;
975 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
976 this.game.clocks[oppIdx] = data.clock;
977 if (data.movesCount > L) {
978 // Just got last move from him
979 this.$refs["basegame"].play(data.lastMove, "received");
980 this.processMove(data.lastMove);
981 } else {
982 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
983 this.re_setClocks();
984 }
985 if (!!data.drawSent) this.drawOffer = "received";
986 if (!!data.score) {
987 this.drawOffer = "";
988 if (this.game.score == "*")
989 this.gameOver(data.score, data.scoreMsg);
990 }
991 }
992 },
993 clickDraw: function() {
994 if (!this.game.mycolor || this.game.type == "import") return;
995 if (["received", "threerep"].includes(this.drawOffer)) {
996 if (!confirm(this.st.tr["Accept draw?"])) return;
997 const message =
998 this.drawOffer == "received"
999 ? "Mutual agreement"
1000 : "Three repetitions";
1001 this.send("draw", { data: message });
1002 this.gameOver("1/2", message);
1003 } else if (this.drawOffer == "") {
1004 // No effect if drawOffer == "sent"
1005 if (this.game.mycolor != this.vr.turn) {
1006 alert(this.st.tr["Draw offer only in your turn"]);
1007 return;
1008 }
1009 if (!confirm(this.st.tr["Offer draw?"])) return;
1010 this.drawOffer = "sent";
1011 this.send("drawoffer");
1012 if (this.game.type == "live") {
1013 GameStorage.update(
1014 this.gameRef,
1015 { drawOffer: this.game.mycolor }
1016 );
1017 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1018 }
1019 },
1020 addAndGotoLiveGame: function(gameInfo, callback) {
1021 const game = Object.assign(
1022 {},
1023 gameInfo,
1024 {
1025 // (other) Game infos: constant
1026 fenStart: gameInfo.fen,
1027 vname: this.game.vname,
1028 created: Date.now(),
1029 // Game state (including FEN): will be updated
1030 moves: [],
1031 clocks: [-1, -1], //-1 = unstarted
1032 score: "*"
1033 }
1034 );
1035 GameStorage.add(game, (err) => {
1036 // No error expected.
1037 if (!err) {
1038 if (this.st.settings.sound)
1039 new Audio("/sounds/newgame.flac").play().catch(() => {});
1040 if (!!callback) callback();
1041 this.$router.push("/game/" + gameInfo.id);
1042 }
1043 });
1044 },
1045 clickRematch: function() {
1046 if (!this.game.mycolor || this.game.type == "import") return;
1047 if (this.rematchOffer == "received") {
1048 // Start a new game!
1049 let gameInfo = {
1050 id: getRandString(), //ignored if corr
1051 fen: V.GenRandInitFen(this.game.randomness),
1052 players: this.game.players.reverse(),
1053 vid: this.game.vid,
1054 cadence: this.game.cadence
1055 };
1056 const notifyNewGame = () => {
1057 const oppsid = this.getOppsid(); //may be null
1058 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1059 // To main Hall if corr game:
1060 if (this.game.type == "corr")
1061 this.send("newgame", { data: gameInfo, page: "/" });
1062 // Also to MyGames page:
1063 this.notifyMyGames("newgame", gameInfo);
1064 };
1065 if (this.game.type == "live")
1066 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1067 else {
1068 // corr game
1069 ajax(
1070 "/games",
1071 "POST",
1072 {
1073 // cid is useful to delete the challenge:
1074 data: { gameInfo: gameInfo },
1075 success: (response) => {
1076 gameInfo.id = response.gameId;
1077 notifyNewGame();
1078 this.$router.push("/game/" + response.gameId);
1079 }
1080 }
1081 );
1082 }
1083 } else if (this.rematchOffer == "") {
1084 this.rematchOffer = "sent";
1085 this.send("rematchoffer", { data: true });
1086 if (this.game.type == "live") {
1087 GameStorage.update(
1088 this.gameRef,
1089 { rematchOffer: this.game.mycolor }
1090 );
1091 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1092 } else if (this.rematchOffer == "sent") {
1093 // Toggle rematch offer (on --> off)
1094 this.rematchOffer = "";
1095 this.send("rematchoffer", { data: false });
1096 if (this.game.type == "live") {
1097 GameStorage.update(
1098 this.gameRef,
1099 { rematchOffer: '' }
1100 );
1101 } else this.updateCorrGame({ rematchOffer: 'n' });
1102 }
1103 },
1104 abortGame: function() {
1105 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1106 return;
1107 this.gameOver("?", "Stop");
1108 this.send("abort");
1109 },
1110 resign: function() {
1111 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1112 return;
1113 this.send("resign", { data: this.game.mycolor });
1114 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1115 const side = (this.game.mycolor == "w" ? "White" : "Black");
1116 this.gameOver(score, side + " surrender");
1117 },
1118 loadGame: function(game, callback) {
1119 const gtype = game.type || this.getGameType(game);
1120 const tc = extractTime(game.cadence);
1121 const myIdx = game.players.findIndex(p => {
1122 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1123 });
1124 // Sometimes the name isn't stored yet (TODO: why?)
1125 if (
1126 myIdx >= 0 &&
1127 gtype == "live" &&
1128 !game.players[myIdx].name &&
1129 !!this.st.user.name
1130 ) {
1131 game.players[myIdx].name = this.st.user.name;
1132 GameStorage.update(
1133 game.id,
1134 { playerName: { idx: myIdx, name: this.st.user.name } }
1135 );
1136 }
1137 // "mycolor" is undefined for observers
1138 const mycolor = [undefined, "w", "b"][myIdx + 1];
1139 if (gtype == "corr") {
1140 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1141 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1142 // NOTE: clocks in seconds
1143 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1144 game.clocks = [tc.mainTime, tc.mainTime];
1145 const L = game.moves.length;
1146 if (game.score == "*") {
1147 // Adjust clocks
1148 if (L >= 2) {
1149 game.clocks[L % 2] -=
1150 (Date.now() - game.moves[L-1].played) / 1000;
1151 }
1152 }
1153 // Now that we used idx and played, re-format moves as for live games
1154 game.moves = game.moves.map(m => m.squares);
1155 }
1156 else if (gtype == "live") {
1157 if (game.clocks[0] < 0) {
1158 // Game is unstarted. clock is ignored until move 2
1159 game.clocks = [tc.mainTime, tc.mainTime];
1160 if (myIdx >= 0) {
1161 // I play in this live game
1162 GameStorage.update(
1163 game.id,
1164 { clocks: game.clocks }
1165 );
1166 }
1167 } else {
1168 if (!!game.initime)
1169 // It's my turn: clocks not updated yet
1170 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1171 }
1172 }
1173 else
1174 // gtype == "import"
1175 game.clocks = [tc.mainTime, tc.mainTime];
1176 // Live games before 26/03/2020 don't have chat history:
1177 if (!game.chats) game.chats = []; //TODO: remove line
1178 // Sort chat messages from newest to oldest
1179 game.chats.sort((c1, c2) => c2.added - c1.added);
1180 if (
1181 myIdx >= 0 &&
1182 game.chats.length > 0 &&
1183 (!game.chatRead || game.chatRead < game.chats[0].added)
1184 ) {
1185 // A chat message arrived since my last reading:
1186 document.getElementById("chatBtn").classList.add("somethingnew");
1187 }
1188 // TODO: merge next 2 "if" conditions
1189 if (!!game.drawOffer) {
1190 if (game.drawOffer == "t")
1191 // Three repetitions
1192 this.drawOffer = "threerep";
1193 else {
1194 // Draw offered by any of the players:
1195 if (myIdx < 0) this.drawOffer = "received";
1196 else {
1197 // I play in this game:
1198 if (
1199 (game.drawOffer == "w" && myIdx == 0) ||
1200 (game.drawOffer == "b" && myIdx == 1)
1201 )
1202 this.drawOffer = "sent";
1203 else this.drawOffer = "received";
1204 }
1205 }
1206 }
1207 if (!!game.rematchOffer) {
1208 if (myIdx < 0) this.rematchOffer = "received";
1209 else {
1210 // I play in this game:
1211 if (
1212 (game.rematchOffer == "w" && myIdx == 0) ||
1213 (game.rematchOffer == "b" && myIdx == 1)
1214 ) {
1215 this.rematchOffer = "sent";
1216 }
1217 else this.rematchOffer = "received";
1218 }
1219 }
1220 this.repeat = {}; //reset: scan past moves' FEN:
1221 let repIdx = 0;
1222 this.vr = new V(game.fenStart);
1223 let curTurn = "n";
1224 game.moves.forEach(m => {
1225 playMove(m, this.vr);
1226 const fenIdx = this.vr.getFenForRepeat();
1227 this.repeat[fenIdx] = this.repeat[fenIdx]
1228 ? this.repeat[fenIdx] + 1
1229 : 1;
1230 });
1231 // Imported games don't have current FEN
1232 if (!game.fen) game.fen = this.vr.getFen();
1233 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1234 this.game = Object.assign(
1235 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1236 {
1237 type: gtype,
1238 increment: tc.increment,
1239 mycolor: mycolor,
1240 // opponent sid not strictly required (or available), but easier
1241 // at least oppsid or oppid is available anyway:
1242 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1243 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1244 },
1245 game
1246 );
1247 this.$refs["basegame"].re_setVariables(this.game);
1248 if (!this.gameIsLoading) {
1249 // Initial loading:
1250 this.gotMoveIdx = game.moves.length - 1;
1251 // If we arrive here after 'nextGame' action, the board might be hidden
1252 let boardDiv = document.querySelector(".game");
1253 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1254 boardDiv.style.visibility = "visible";
1255 }
1256 this.re_setClocks();
1257 this.$nextTick(() => {
1258 this.game.rendered = true;
1259 // Did lastate arrive before game was rendered?
1260 if (this.lastate) this.processLastate();
1261 });
1262 if (this.lastateAsked) {
1263 this.lastateAsked = false;
1264 this.sendLastate(game.oppsid);
1265 }
1266 if (this.gameIsLoading) {
1267 this.gameIsLoading = false;
1268 if (this.gotMoveIdx >= game.moves.length)
1269 // Some moves arrived meanwhile...
1270 this.askGameAgain();
1271 }
1272 if (!!callback) callback();
1273 },
1274 loadVariantThenGame: async function(game, callback) {
1275 await import("@/variants/" + game.vname + ".js")
1276 .then((vModule) => {
1277 window.V = vModule[game.vname + "Rules"];
1278 this.loadGame(game, callback);
1279 });
1280 // (AJAX) Request to get rules content (plain text, HTML)
1281 this.rulesContent =
1282 require(
1283 "raw-loader!@/translations/rules/" +
1284 game.vname + "/" +
1285 this.st.lang + ".pug"
1286 )
1287 // Next two lines fix a weird issue after last update (2019-11)
1288 .replace(/\\n/g, " ")
1289 .replace(/\\"/g, '"')
1290 .replace('module.exports = "', "")
1291 .replace(/"$/, "")
1292 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1293 },
1294 // 3 cases for loading a game:
1295 // - from indexedDB (running or completed live game I play)
1296 // - from server (one correspondance game I play[ed] or not)
1297 // - from remote peer (one live game I don't play, finished or not)
1298 fetchGame: function(callback) {
1299 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1300 // corr games identifiers are integers
1301 ajax(
1302 "/games",
1303 "GET",
1304 {
1305 data: { gid: this.gameRef },
1306 success: (res) => {
1307 res.game.moves.forEach(m => {
1308 m.squares = JSON.parse(m.squares);
1309 });
1310 callback(res.game);
1311 }
1312 }
1313 );
1314 }
1315 else if (!!this.gameRef.match(/^i/))
1316 // Game import (maybe remote)
1317 ImportgameStorage.get(this.gameRef, callback);
1318 else
1319 // Local live game (or remote)
1320 GameStorage.get(this.gameRef, callback);
1321 },
1322 re_setClocks: function() {
1323 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1324 if (this.game.moves.length < 2 || this.game.score != "*") {
1325 // 1st move not completed yet, or game over: freeze time
1326 return;
1327 }
1328 const currentTurn = this.vr.turn;
1329 const currentMovesCount = this.game.moves.length;
1330 const colorIdx = ["w", "b"].indexOf(currentTurn);
1331 this.clockUpdate = setInterval(
1332 () => {
1333 if (
1334 this.game.clocks[colorIdx] < 0 ||
1335 this.game.moves.length > currentMovesCount ||
1336 this.game.score != "*"
1337 ) {
1338 clearInterval(this.clockUpdate);
1339 this.clockUpdate = null;
1340 if (this.game.clocks[colorIdx] < 0)
1341 this.gameOver(
1342 currentTurn == "w" ? "0-1" : "1-0",
1343 "Time"
1344 );
1345 } else {
1346 this.$set(
1347 this.virtualClocks,
1348 colorIdx,
1349 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1350 );
1351 }
1352 },
1353 1000
1354 );
1355 },
1356 // Update variables and storage after a move:
1357 processMove: function(move, data) {
1358 if (this.game.type == "import")
1359 // Shouldn't receive any messages in this mode:
1360 return;
1361 if (!data) data = {};
1362 const moveCol = this.vr.turn;
1363 const colorIdx = ["w", "b"].indexOf(moveCol);
1364 const nextIdx = 1 - colorIdx;
1365 const doProcessMove = () => {
1366 const origMovescount = this.game.moves.length;
1367 // The move is (about to be) played: stop clock
1368 clearInterval(this.clockUpdate);
1369 this.clockUpdate = null;
1370 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1371 if (this.drawOffer == "received")
1372 // I refuse draw
1373 this.drawOffer = "";
1374 if (this.game.type == "live" && origMovescount >= 2) {
1375 this.game.clocks[colorIdx] += this.game.increment;
1376 // For a correct display in casqe of disconnected opponent:
1377 this.$set(
1378 this.virtualClocks,
1379 colorIdx,
1380 ppt(this.game.clocks[colorIdx]).split(':')
1381 );
1382 GameStorage.update(this.gameRef, {
1383 // It's not my turn anymore:
1384 initime: null
1385 });
1386 }
1387 }
1388 // Update current game object:
1389 playMove(move, this.vr);
1390 if (!data.score)
1391 // Received move, score is computed in BaseGame, but maybe not yet.
1392 // ==> Compute it here, although this is redundant (TODO)
1393 data.score = this.vr.getCurrentScore();
1394 if (data.score != "*") this.gameOver(data.score);
1395 this.game.moves.push(move);
1396 this.game.fen = this.vr.getFen();
1397 if (this.game.type == "corr") {
1398 // In corr games, just reset clock to mainTime:
1399 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1400 }
1401 // If repetition detected, consider that a draw offer was received:
1402 const fenObj = this.vr.getFenForRepeat();
1403 this.repeat[fenObj] =
1404 !!this.repeat[fenObj]
1405 ? this.repeat[fenObj] + 1
1406 : 1;
1407 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1408 else if (this.drawOffer == "threerep") this.drawOffer = "";
1409 if (!!this.game.mycolor && !data.receiveMyMove) {
1410 // NOTE: 'var' to see that variable outside this block
1411 var filtered_move = getFilteredMove(move);
1412 }
1413 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1414 // Notify turn on MyGames page:
1415 this.notifyMyGames(
1416 "turn",
1417 {
1418 gid: this.gameRef,
1419 turn: this.vr.turn
1420 }
1421 );
1422 }
1423 // Since corr games are stored at only one location, update should be
1424 // done only by one player for each move:
1425 if (
1426 this.game.type == "live" &&
1427 !!this.game.mycolor &&
1428 moveCol != this.game.mycolor &&
1429 this.game.moves.length >= 2
1430 ) {
1431 // Receive a move: update initime
1432 this.game.initime = Date.now();
1433 GameStorage.update(this.gameRef, {
1434 // It's my turn now!
1435 initime: this.game.initime
1436 });
1437 }
1438 if (
1439 !!this.game.mycolor &&
1440 !data.receiveMyMove &&
1441 (this.game.type == "live" || moveCol == this.game.mycolor)
1442 ) {
1443 let drawCode = "";
1444 switch (this.drawOffer) {
1445 case "threerep":
1446 drawCode = "t";
1447 break;
1448 case "sent":
1449 drawCode = this.game.mycolor;
1450 break;
1451 case "received":
1452 drawCode = V.GetOppCol(this.game.mycolor);
1453 break;
1454 }
1455 if (this.game.type == "corr") {
1456 // corr: only move, fen and score
1457 this.updateCorrGame({
1458 fen: this.game.fen,
1459 move: {
1460 squares: filtered_move,
1461 idx: origMovescount
1462 },
1463 // Code "n" for "None" to force reset (otherwise it's ignored)
1464 drawOffer: drawCode || "n"
1465 });
1466 }
1467 else {
1468 const updateStorage = () => {
1469 GameStorage.update(this.gameRef, {
1470 fen: this.game.fen,
1471 move: filtered_move,
1472 moveIdx: origMovescount,
1473 clocks: this.game.clocks,
1474 drawOffer: drawCode
1475 });
1476 };
1477 // The active tab can update storage immediately
1478 if (this.focus) updateStorage();
1479 // Small random delay otherwise
1480 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1481 }
1482 }
1483 // Send move ("newmove" event) to people in the room (if our turn)
1484 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1485 let sendMove = {
1486 move: filtered_move,
1487 index: origMovescount,
1488 // color is required to check if this is my move
1489 // (if several tabs opened)
1490 color: moveCol,
1491 cancelDrawOffer: this.drawOffer == ""
1492 };
1493 if (this.game.type == "live")
1494 sendMove["clock"] = this.game.clocks[colorIdx];
1495 // (Live) Clocks will re-start when the opponent pingback arrive
1496 this.opponentGotMove = false;
1497 this.send("newmove", {data: sendMove});
1498 // If the opponent doesn't reply gotmove soon enough, re-send move:
1499 // Do this at most 2 times, because mpore would mean network issues,
1500 // opponent would then be expected to disconnect/reconnect.
1501 let counter = 1;
1502 const currentUrl = document.location.href;
1503 this.retrySendmove = setInterval(
1504 () => {
1505 if (
1506 counter >= 3 ||
1507 this.opponentGotMove ||
1508 document.location.href != currentUrl //page change
1509 ) {
1510 clearInterval(this.retrySendmove);
1511 return;
1512 }
1513 const oppsid = this.getOppsid();
1514 if (!oppsid)
1515 // Opponent is disconnected: he'll ask last state
1516 clearInterval(this.retrySendmove);
1517 else {
1518 this.send("newmove", { data: sendMove, target: oppsid });
1519 counter++;
1520 }
1521 },
1522 1500
1523 );
1524 }
1525 else
1526 // Not my move or I'm an observer: just start other player's clock
1527 this.re_setClocks();
1528 };
1529 if (
1530 this.game.type == "corr" &&
1531 moveCol == this.game.mycolor &&
1532 !data.receiveMyMove
1533 ) {
1534 let boardDiv = document.querySelector(".game");
1535 const afterSetScore = () => {
1536 doProcessMove();
1537 if (this.st.settings.gotonext && this.nextIds.length > 0)
1538 this.showNextGame();
1539 else {
1540 // The board might have been hidden:
1541 if (boardDiv.style.visibility == "hidden")
1542 boardDiv.style.visibility = "visible";
1543 if (data.score == "*") this.re_setClocks();
1544 }
1545 };
1546 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1547 // We may play several moves in a row: in case of, remove listener:
1548 let elClone = el.cloneNode(true);
1549 el.parentNode.replaceChild(elClone, el);
1550 elClone.addEventListener(
1551 "click",
1552 () => {
1553 document.getElementById("modalConfirm").checked = false;
1554 if (!!data.score && data.score != "*")
1555 // Set score first
1556 this.gameOver(data.score, null, afterSetScore);
1557 else afterSetScore();
1558 }
1559 );
1560 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1561 const arMove = (Array.isArray(move) ? move : [move]);
1562 for (let i = 0; i < arMove.length; i++)
1563 V.PlayOnBoard(this.vr.board, arMove[i]);
1564 const position = this.vr.getBaseFen();
1565 for (let i = arMove.length - 1; i >= 0; i--)
1566 V.UndoOnBoard(this.vr.board, arMove[i]);
1567 if (["all","byrow"].includes(V.ShowMoves)) {
1568 this.curDiag = getDiagram({
1569 position: position,
1570 orientation: V.CanFlip ? this.game.mycolor : "w"
1571 });
1572 document.querySelector("#confirmDiv > .card").style.width =
1573 boardDiv.offsetWidth + "px";
1574 } else {
1575 // Incomplete information: just ask confirmation
1576 // Hide the board, because otherwise it could reveal infos
1577 boardDiv.style.visibility = "hidden";
1578 this.moveNotation = getFullNotation(move);
1579 }
1580 document.getElementById("modalConfirm").checked = true;
1581 }
1582 else {
1583 // Normal situation
1584 if (!!data.score && data.score != "*")
1585 this.gameOver(data.score, null, doProcessMove);
1586 else doProcessMove();
1587 }
1588 },
1589 cancelMove: function() {
1590 let boardDiv = document.querySelector(".game");
1591 if (boardDiv.style.visibility == "hidden")
1592 boardDiv.style.visibility = "visible";
1593 document.getElementById("modalConfirm").checked = false;
1594 this.$refs["basegame"].cancelLastMove();
1595 },
1596 // In corr games, callback to change page only after score is set:
1597 gameOver: function(score, scoreMsg, callback) {
1598 this.game.score = score;
1599 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1600 this.game.scoreMsg = scoreMsg;
1601 document.getElementById("modalRules").checked = false;
1602 // Display result in a un-missable way:
1603 document.getElementById("modalScore").checked = true;
1604 this.$set(this.game, "scoreMsg", scoreMsg);
1605 const myIdx = this.game.players.findIndex(p => {
1606 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1607 });
1608 if (myIdx >= 0) {
1609 // OK, I play in this game
1610 const scoreObj = {
1611 score: score,
1612 scoreMsg: scoreMsg
1613 };
1614 if (this.game.type == "live") {
1615 GameStorage.update(this.gameRef, scoreObj);
1616 // Notify myself locally if I'm elsewhere:
1617 if (!this.focus) {
1618 notify(
1619 "Game over",
1620 { body: score + " : " + scoreMsg }
1621 );
1622 }
1623 if (!!callback) callback();
1624 }
1625 else this.updateCorrGame(scoreObj, callback);
1626 // Notify the score to main Hall.
1627 // TODO: only one player (currently double send)
1628 this.send("result", { gid: this.game.id, score: score });
1629 // Also to MyGames page (TODO: doubled as well...)
1630 this.notifyMyGames(
1631 "score",
1632 {
1633 gid: this.gameRef,
1634 score: score
1635 }
1636 );
1637 }
1638 else if (!!callback) callback();
1639 }
1640 }
1641 };
1642 </script>
1643
1644 <style lang="sass" scoped>
1645 #scoreDiv > .card, #rematchDiv > .card
1646 padding: 10px 0
1647 max-width: 430px
1648
1649 #rulesDiv > .card
1650 padding: 5px 0
1651 max-width: 50%
1652 max-height: 100%
1653 @media screen and (max-width: 1500px)
1654 max-width: 67%
1655 @media screen and (max-width: 1024px)
1656 max-width: 85%
1657 @media screen and (max-width: 767px)
1658 max-width: 100%
1659
1660 p.score-section
1661 margin: 0
1662 font-size: 1.3em
1663 span.score
1664 font-weight: bold
1665
1666 .connected
1667 background-color: lightgreen
1668
1669 #participants
1670 margin-left: 5px
1671
1672 .anonymous
1673 color: grey
1674 font-style: italic
1675
1676 #playersInfo > p
1677 margin: 0
1678
1679 @media screen and (max-width: 767px)
1680 .game
1681 width: 100%
1682
1683 #actions
1684 display: inline-block
1685 margin: 0
1686
1687 button
1688 display: inline-block
1689 margin: 0
1690 display: inline-flex
1691 img
1692 height: 22px
1693 display: flex
1694 @media screen and (max-width: 767px)
1695 height: 18px
1696
1697 #aboveBoard
1698 text-align: center
1699
1700 .variant-cadence
1701 padding-right: 10px
1702
1703 .variant-name
1704 font-weight: bold
1705 padding-right: 10px
1706
1707 span#nextGame
1708 background-color: #edda99
1709 cursor: pointer
1710 display: inline-block
1711 margin-right: 10px
1712
1713 span.separator
1714 display: inline-block
1715 margin: 0
1716 padding: 0
1717 width: 10px
1718
1719 span.name
1720 font-size: 1.5rem
1721 @media screen and (max-width: 767px)
1722 font-size: 1.2rem
1723 padding: 0 3px
1724
1725 span.time
1726 font-size: 2rem
1727 @media screen and (max-width: 767px)
1728 font-size: 1.5rem
1729 display: inline-block
1730 .time-left
1731 margin-left: 10px
1732 .time-right
1733 margin-left: 5px
1734 .time-separator
1735 margin-left: 5px
1736 position: relative
1737 top: -1px
1738
1739 span.yourturn
1740 color: #831B1B
1741 .time-separator
1742 animation: blink-animation 2s steps(3, start) infinite
1743 @keyframes blink-animation
1744 to
1745 visibility: hidden
1746
1747 .split-names
1748 display: inline-block
1749 margin: 0 15px
1750
1751 #chatWrap > .card
1752 padding-top: 20px
1753 max-width: 767px
1754 border: none
1755
1756 #confirmDiv > .card
1757 max-width: 767px
1758 max-height: 100%
1759
1760 .draw-sent, .draw-sent:hover
1761 background-color: lightyellow
1762
1763 .draw-received, .draw-received:hover
1764 background-color: lightgreen
1765
1766 .draw-threerep, .draw-threerep:hover
1767 background-color: #e4d1fc
1768
1769 .rematch-sent, .rematch-sent:hover
1770 background-color: lightyellow
1771
1772 .rematch-received, .rematch-received:hover
1773 background-color: lightgreen
1774
1775 .somethingnew
1776 background-color: #c5fefe
1777
1778 .diagram
1779 margin: 0 auto
1780 width: 100%
1781
1782 #buttonsConfirm
1783 margin: 0
1784 & > button > span
1785 width: 100%
1786 text-align: center
1787
1788 button.acceptBtn
1789 background-color: lightgreen
1790 button.refuseBtn
1791 background-color: red
1792
1793 h4#variantNameInGame
1794 cursor: pointer
1795 text-align: center
1796 text-decoration: underline
1797 font-weight: bold
1798 </style>
1799
1800 <style lang="sass">
1801 @import "@/styles/_rules.sass"
1802 @import "@/styles/_board_squares_img.sass"
1803 </style>