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