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