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