3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
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")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
86 | {{ st.tr["Next_g"] }}
88 :class="btnTooltipClass()"
89 onClick="window.doClick('modalChat')"
92 img(src="/images/icons/chat.svg")
93 #actions(v-if="game.score=='*'")
96 :class="btnTooltipClass('draw')"
97 :aria-label="st.tr['Draw']"
99 img(src="/images/icons/draw.svg")
101 v-if="!!game.mycolor"
102 :class="btnTooltipClass()"
104 :aria-label="st.tr['Abort']"
106 img(src="/images/icons/abort.svg")
108 v-if="!!game.mycolor"
109 :class="btnTooltipClass()"
111 :aria-label="st.tr['Resign']"
113 img(src="/images/icons/resign.svg")
116 :class="btnTooltipClass('rematch')"
117 @click="clickRematch()"
118 :aria-label="st.tr['Rematch']"
120 img(src="/images/icons/rematch.svg")
122 div(v-if="isLargeScreen()")
124 :class="{connected: isConnected(0)}"
125 :uid="game.players[0].id"
126 :uname="game.players[0].name"
129 v-if="game.score=='*'"
130 :class="{yourturn: !!vr && vr.turn == 'w'}"
132 span.time-left {{ virtualClocks[0][0] }}
133 span.time-separator(v-if="!!virtualClocks[0][1]") :
134 span.time-right(v-if="!!virtualClocks[0][1]")
135 | {{ virtualClocks[0][1] }}
138 :class="{connected: isConnected(1)}"
139 :uid="game.players[1].id"
140 :uname="game.players[1].name"
143 v-if="game.score=='*'"
144 :class="{yourturn: !!vr && vr.turn == 'b'}"
146 span.time-left {{ virtualClocks[1][0] }}
147 span.time-separator(v-if="!!virtualClocks[1][1]") :
148 span.time-right(v-if="!!virtualClocks[1][1]")
149 | {{ virtualClocks[1][1] }}
152 :class="{connected: isConnected(0)}"
153 :uid="game.players[0].id"
154 :uname="game.players[0].name"
158 :class="{connected: isConnected(1)}"
159 :uid="game.players[1].id"
160 :uname="game.players[1].name"
162 div(v-if="game.score=='*'")
163 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
164 span.time-left {{ virtualClocks[0][0] }}
165 span.time-separator(v-if="!!virtualClocks[0][1]") :
166 span.time-right(v-if="!!virtualClocks[0][1]")
167 | {{ virtualClocks[0][1] }}
169 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
170 span.time-left {{ virtualClocks[1][0] }}
171 span.time-separator(v-if="!!virtualClocks[1][1]") :
172 span.time-right(v-if="!!virtualClocks[1][1]")
173 | {{ virtualClocks[1][1] }}
177 @newmove="processMove"
182 import BaseGame from "@/components/BaseGame.vue";
183 import UserBio from "@/components/UserBio.vue";
184 import Chat from "@/components/Chat.vue";
185 import { store } from "@/store";
186 import { GameStorage } from "@/utils/gameStorage";
187 import { ImportgameStorage } from "@/utils/importgameStorage";
188 import { ppt } from "@/utils/datetime";
189 import { notify } from "@/utils/notifications";
190 import { ajax } from "@/utils/ajax";
191 import { extractTime } from "@/utils/timeControl";
192 import { getRandString } from "@/utils/alea";
193 import { getScoreMessage } from "@/utils/scoring";
194 import { getFullNotation } from "@/utils/notation";
195 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
196 import { processModalClick } from "@/utils/modalClick";
197 import { playMove, getFilteredMove } from "@/utils/playUndo";
198 import { ArrayFun } from "@/utils/array";
199 import params from "@/parameters";
210 // gameRef can point to a corr game, local game or remote live game
213 game: {}, //passed to BaseGame
214 focus: !document.hidden, //will not always work... TODO
215 // virtualClocks will be initialized from true game.clocks
217 vr: null, //"variant rules" object initialized from FEN
223 people: {}, //players + observers
224 lastate: undefined, //used if opponent send lastate before game is ready
225 repeat: {}, //detect position repetition
226 curDiag: "", //for corr moves confirmation
228 roomInitialized: false,
229 // If asklastate got no reply, ask again:
231 gotMoveIdx: -1, //last move index received
232 // If newmove got no pingback, send again:
233 opponentGotMove: false,
235 socketCloseListener: 0,
236 // Incomplete info games: show move played
238 // Intervals from setInterval():
242 // Related to (killing of) self multi-connects:
247 $route: function(to, from) {
248 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
250 this.cleanBeforeDestroy();
251 else if (from.params["id"] != to.params["id"]) {
252 // Change everything:
253 this.cleanBeforeDestroy();
254 let boardDiv = document.querySelector(".game");
256 // In case of incomplete information variant:
257 boardDiv.style.visibility = "hidden";
261 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
264 // NOTE: some redundant code with Hall.vue (mostly related to people array)
265 created: function() {
268 mounted: function() {
269 document.getElementById("chatWrap")
270 .addEventListener("click", (e) => {
271 processModalClick(e, () => {
272 this.toggleChat("close")
275 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
277 document.getElementById(eltName)
278 .addEventListener("click", processModalClick);
282 beforeDestroy: function() {
283 this.cleanBeforeDestroy();
286 cleanBeforeDestroy: function() {
287 clearInterval(this.socketCloseListener);
288 document.removeEventListener('visibilitychange', this.visibilityChange);
289 window.removeEventListener('focus', this.onFocus);
290 window.removeEventListener('blur', this.onBlur);
291 if (!!this.askLastate) clearInterval(this.askLastate);
292 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
293 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
294 this.conn.removeEventListener("message", this.socketMessageListener);
295 this.send("disconnect");
298 visibilityChange: function() {
299 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
300 this.focus = (document.visibilityState == "visible");
301 this.send(this.focus ? "getfocus" : "losefocus");
303 onFocus: function() {
305 this.send("getfocus");
309 this.send("losefocus");
311 isLargeScreen: function() {
312 return window.innerWidth >= 768;
314 btnTooltipClass: function(thing) {
316 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
319 { tooltip: !("ontouchstart" in window) },
324 someAnonymousPresent: function() {
326 Object.values(this.people).some(p =>
327 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
331 atCreation: function() {
332 document.addEventListener('visibilitychange', this.visibilityChange);
333 window.addEventListener('focus', this.onFocus);
334 window.addEventListener('blur', this.onBlur);
335 // 0] (Re)Set variables
336 this.gameRef = this.$route.params["id"];
337 // next = next corr games IDs to navigate faster (if applicable)
338 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
339 // Always add myself to players' list
340 const my = this.st.user;
341 const tmpId = getRandString();
349 tmpId: { focus: true }
354 players: [{ name: "" }, { name: "" }],
358 let chatComp = this.$refs["chatcomp"];
359 if (!!chatComp) chatComp.chats = [];
360 this.virtualClocks = [[0,0], [0,0]];
362 this.rulesContent = "";
364 this.lastateAsked = false;
365 this.rematchOffer = "";
366 this.lastate = undefined;
367 this.roomInitialized = false;
368 this.gotLastate = false;
369 this.gotMoveIdx = -1;
370 this.opponentGotMove = false;
371 this.askLastate = null;
372 this.retrySendmove = null;
373 this.clockUpdate = null;
374 this.newConnect = {};
375 // 1] Initialize connection
376 this.connexionString =
378 "/?sid=" + this.st.user.sid +
379 "&id=" + this.st.user.id +
382 // Discard potential "/?next=[...]" for page indication:
383 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
384 this.conn = new WebSocket(this.connexionString);
385 this.conn.addEventListener("message", this.socketMessageListener);
386 this.socketCloseListener = setInterval(
388 if (this.conn.readyState == 3) {
389 this.conn.removeEventListener(
390 "message", this.socketMessageListener);
391 this.conn = new WebSocket(this.connexionString);
392 this.conn.addEventListener("message", this.socketMessageListener);
397 // Socket init required before loading remote game:
398 const socketInit = callback => {
399 if (this.conn.readyState == 1)
403 // Socket not ready yet (initial loading)
404 // NOTE: first arg is Websocket object, unused here:
405 this.conn.onopen = () => callback();
407 this.fetchGame((game) => {
409 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
411 // Live game stored remotely: need socket to retrieve it
412 // NOTE: the callback "roomInit" will be lost, so it's not provided.
413 // --> It will be given when receiving "fullgame" socket event.
414 socketInit(() => { this.send("askfullgame"); });
417 roomInit: function() {
418 if (!this.roomInitialized) {
419 // Notify the room only now that I connected, because
420 // messages might be lost otherwise (if game loading is slow)
421 this.send("connect");
422 this.send("pollclients");
423 // We may ask fullgame several times if some moves are lost,
424 // but room should be init only once:
425 this.roomInitialized = true;
428 send: function(code, obj) {
429 if (!!this.conn && this.conn.readyState == 1)
430 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
432 isConnected: function(index) {
433 const player = this.game.players[index];
434 // Is it me ? In this case no need to bother with focus
436 this.st.user.sid == player.sid ||
437 (!!player.name && this.st.user.id == player.id)
439 // Still have to check for name (because of potential multi-accounts
440 // on same browser, although this should be rare...)
441 return (!this.st.user.name || this.st.user.name == player.name);
443 // Try to find a match in people:
447 Object.keys(this.people).some(sid => {
450 Object.values(this.people[sid].tmpIds).some(v => v.focus)
457 Object.values(this.people).some(p => {
460 Object.values(p.tmpIds).some(v => v.focus)
466 getOppsid: function() {
467 let oppsid = this.game.oppsid;
469 oppsid = Object.keys(this.people).find(
470 sid => this.people[sid].id == this.game.oppid
473 // oppsid is useful only if opponent is online:
474 if (!!oppsid && !!this.people[oppsid]) return oppsid;
477 // NOTE: action if provided is always a closing action
478 toggleChat: function(action) {
479 if (!action && document.getElementById("modalChat").checked)
481 document.getElementById("inputChat").focus();
483 document.getElementById("chatBtn").classList.remove("somethingnew");
484 if (!!this.game.mycolor) {
485 // Update "chatRead" variable either on server or locally
486 if (this.game.type == "corr")
487 this.updateCorrGame({ chatRead: this.game.mycolor });
488 else if (this.game.type == "live")
489 GameStorage.update(this.gameRef, { chatRead: true });
493 processChat: function(chat) {
494 this.send("newchat", { data: chat });
495 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
496 if (!!this.game.mycolor) {
497 if (this.game.type == "corr")
498 this.updateCorrGame({ chat: chat });
501 chat.added = Date.now();
502 GameStorage.update(this.gameRef, { chat: chat });
506 clearChat: function() {
507 if (!!this.game.mycolor) {
508 if (this.game.type == "corr") {
512 { data: { gid: this.game.id } }
516 GameStorage.update(this.gameRef, { delchat: true });
518 this.$set(this.game, "chats", []);
521 getGameType: function(game) {
522 if (!!game.id.toString().match(/^i/)) return "import";
523 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
525 // Notify something after a new move (to opponent and me on MyGames page)
526 notifyMyGames: function(thing, data) {
531 targets: this.game.players.map(p => {
532 return { sid: p.sid, id: p.id };
537 showNextGame: function() {
538 // Did I play in current game? If not, add it to nextIds list
539 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
540 this.nextIds.unshift(this.game.id);
541 const nextGid = this.nextIds.pop();
543 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
545 socketMessageListener: function(msg) {
546 if (!this.conn) return;
547 const data = JSON.parse(msg.data);
550 // TODO: shuffling and random filtering on server,
551 // if the room is really crowded.
552 Object.keys(data.sockIds).forEach(sid => {
553 if (sid != this.st.user.sid) {
554 this.send("askidentity", { target: sid });
555 this.people[sid] = { tmpIds: data.sockIds[sid] };
558 // Complete my tmpIds:
559 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
564 if (!this.people[data.from[0]]) {
565 // focus depends on the tmpId (e.g. tab)
571 [data.from[1]]: { focus: true }
575 // For self multi-connects tests:
576 this.newConnect[data.from[0]] = true;
577 this.send("askidentity", { target: data.from[0] });
579 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
580 this.$forceUpdate(); //TODO: shouldn't be required
584 if (!this.people[data.from[0]]) return;
585 delete this.people[data.from[0]].tmpIds[data.from[1]];
586 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
587 this.$delete(this.people, data.from[0]);
588 else this.$forceUpdate(); //TODO: shouldn't be required
591 let player = this.people[data.from[0]];
593 player.tmpIds[data.from[1]].focus = true;
594 this.$forceUpdate(); //TODO: shouldn't be required
599 let player = this.people[data.from[0]];
601 player.tmpIds[data.from[1]].focus = false;
602 this.$forceUpdate(); //TODO: shouldn't be required
606 case "askidentity": {
607 // Request for identification
609 // Decompose to avoid revealing email
610 name: this.st.user.name,
611 sid: this.st.user.sid,
614 this.send("identity", { data: me, target: data.from });
618 const user = data.data;
619 let player = this.people[user.sid];
620 // player.tmpIds is already set
621 player.name = user.name;
623 if (this.game.type == "live") {
625 this.game.players.findIndex(p => p.sid == this.st.user.sid);
626 // Sometimes a player name isn't stored yet (TODO: why?)
629 !this.game.players[1 - myGidx].name &&
630 this.game.players[1 - myGidx].sid == user.sid &&
633 this.game.players[1-myGidx].name = user.name;
636 { playerName: { idx: 1 - myGidx, name: user.name } }
640 this.$forceUpdate(); //TODO: shouldn't be required
641 // If I multi-connect, kill current connexion if no mark (I'm older)
642 if (this.newConnect[user.sid]) {
643 delete this.newConnect[user.sid];
646 user.id == this.st.user.id &&
647 user.sid != this.st.user.sid
649 this.cleanBeforeDestroy();
650 alert(this.st.tr["New connexion detected: tab now offline"]);
654 // Ask potentially missed last state, if opponent and I play
657 !!this.game.mycolor &&
658 this.game.type == "live" &&
659 this.game.players.some(p => p.sid == user.sid)
661 this.send("asklastate", { target: user.sid });
663 this.askLastate = setInterval(
665 // Ask at most 3 times:
666 // if no reply after that there should be a network issue.
670 !!this.people[user.sid]
672 this.send("asklastate", { target: user.sid });
675 clearInterval(this.askLastate);
684 // Send current (live or import) game,
685 // if not asked by any of the players
687 this.game.type != "corr" &&
688 this.game.players.every(p => p.sid != data.from[0])
692 // FEN is current position, unused for now
694 players: this.game.players,
696 cadence: this.game.cadence,
697 score: this.game.score
699 this.send("game", { data: myGame, target: data.from });
703 const gameToSend = Object.keys(this.game)
706 "id","fen","players","vid","cadence","fenStart","vname",
707 "moves","clocks","score","drawOffer","rematchOffer"
711 obj[k] = this.game[k];
716 this.send("fullgame", { data: gameToSend, target: data.from });
719 if (!!data.data.empty) {
720 alert(this.st.tr["The game should be in another tab"]);
724 // Callback "roomInit" to poll clients only after game is loaded
725 this.loadVariantThenGame(data.data, this.roomInit);
728 // Sending informative last state if I played a move or score != "*"
729 // If the game or moves aren't loaded yet, delay the sending:
730 // TODO: socket init after game load, so the game is supposedly ready
731 if (!this.game || !this.game.moves) this.lastateAsked = true;
732 else this.sendLastate(data.from);
734 // TODO: possible bad scenario: reload page while oppponent sends a
735 // move => get both lastate and newmove, process both, add move twice.
736 // Confirm scenario? Fix?
738 // Got opponent infos about last move
739 this.gotLastate = true;
740 this.lastate = data.data;
741 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
742 this.gotMoveIdx = this.lastate.movesCount - 1;
743 if (this.game.rendered)
744 // Game is rendered (Board component)
745 this.processLastate();
746 // Else: will be processed when game is ready
752 console.log("Receive move");
753 console.log(data.data);
754 //moveslist not updated when receiving a move? (see in baseGame)
756 const movePlus = data.data;
757 const movesCount = this.game.moves.length;
759 movePlus.index < movesCount ||
760 this.gotMoveIdx >= movePlus.index
762 // Opponent re-send but we already have the move:
763 // (maybe he didn't receive our pingback...)
764 this.send("gotmove", {data: movePlus.index, target: data.from});
767 this.gotMoveIdx = movePlus.index;
768 const receiveMyMove = (movePlus.color == this.game.mycolor);
769 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
770 if (!receiveMyMove && !!this.game.mycolor) {
771 // Notify opponent that I got the move:
774 { data: movePlus.index, target: data.from }
776 // And myself if I'm elsewhere:
782 (this.game.players[moveColIdx].name || "@nonymous") +
788 if (movePlus.cancelDrawOffer) {
789 // Opponent refuses draw
791 // NOTE for corr games: drawOffer reset by player in turn
793 this.game.type == "live" &&
794 !!this.game.mycolor &&
797 GameStorage.update(this.gameRef, { drawOffer: "" });
800 this.$refs["basegame"].play(movePlus.move, "received");
801 // Freeze time while the move is being play
802 // (TODO: a callback would be cleaner here)
803 clearInterval(this.clockUpdate);
804 this.clockUpdate = null;
805 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
806 // 250 = length of animation, 500 = delay between sub-moves
808 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
809 // Incomplete information: no move animation
813 this.game.clocks[moveColIdx] = movePlus.clock;
816 { receiveMyMove: receiveMyMove }
825 this.opponentGotMove = true;
826 // Now his clock starts running on my side:
827 const oppIdx = ['w','b'].indexOf(this.vr.turn);
828 // NOTE: next line to avoid multi-resetClocks when several tabs
829 // on same game, resulting in a faster countdown.
830 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
835 const score = (data.data == "b" ? "1-0" : "0-1");
836 const side = (data.data == "w" ? "White" : "Black");
837 this.gameOver(score, side + " surrender");
840 this.gameOver("?", "Stop");
843 this.gameOver("1/2", data.data);
846 // NOTE: observers don't know who offered draw
847 this.drawOffer = "received";
848 if (!!this.game.mycolor && this.game.type == "live") {
851 { drawOffer: V.GetOppCol(this.game.mycolor) }
856 // NOTE: observers don't know who offered rematch
857 this.rematchOffer = data.data ? "received" : "";
858 if (!!this.game.mycolor && this.game.type == "live") {
861 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
866 // A game started, redirect if I'm playing in
867 const gameInfo = data.data;
868 const gameType = this.getGameType(gameInfo);
870 gameType == "live" &&
871 gameInfo.players.some(p => p.sid == this.st.user.sid)
873 this.addAndGotoLiveGame(gameInfo);
875 gameType == "corr" &&
876 this.st.user.id > 0 &&
877 gameInfo.players.some(p => p.id == this.st.user.id)
879 this.$router.push("/game/" + gameInfo.id);
881 this.rematchId = gameInfo.id;
882 document.getElementById("modalRules").checked = false;
883 document.getElementById("modalScore").checked = false;
884 document.getElementById("modalRematch").checked = true;
889 let chat = data.data;
890 this.$refs["chatcomp"].newChat(chat);
891 if (this.game.type == "live") {
892 chat.added = Date.now();
893 if (!!this.game.mycolor)
894 GameStorage.update(this.gameRef, { chat: chat });
896 if (!document.getElementById("modalChat").checked)
897 document.getElementById("chatBtn").classList.add("somethingnew");
902 updateCorrGame: function(obj, callback) {
912 if (!!callback) callback();
917 sendLastate: function(target) {
918 // Send our "last state" informations to opponent
919 const L = this.game.moves.length;
920 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
923 (L > 0 && this.vr.turn != this.game.mycolor)
924 ? this.game.moves[L - 1]
926 clock: this.game.clocks[myIdx],
927 // Since we played a move (or abort or resign),
928 // only drawOffer=="sent" is possible
929 drawSent: this.drawOffer == "sent" ? true : undefined,
930 rematchSent: this.rematchOffer == "sent" ? true : undefined,
931 score: this.game.score != "*" ? this.game.score : undefined,
932 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
935 this.send("lastate", { data: myLastate, target: target });
937 // lastate was received, but maybe game wasn't ready yet:
938 processLastate: function() {
939 const data = this.lastate;
940 this.lastate = undefined; //security...
942 const oppCol = V.GetOppCol(this.game.mycolor);
943 if (!!data.rematchSent) {
944 if (this.game.rematchOffer != oppCol) {
945 // Opponent sended rematch offer while we were offline:
946 this.rematchOffer = "received";
949 { rematchOffer: oppCol }
954 if (this.game.rematchOffer == oppCol) {
955 // Opponent cancelled rematch offer while we were offline:
956 this.rematchOffer = "";
965 const L = this.game.moves.length;
966 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
967 this.game.clocks[oppIdx] = data.clock;
968 if (data.movesCount > L) {
969 // Just got last move from him
970 this.$refs["basegame"].play(data.lastMove, "received");
971 this.processMove(data.lastMove);
973 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
976 if (!!data.drawSent) this.drawOffer = "received";
979 if (this.game.score == "*")
980 this.gameOver(data.score, data.scoreMsg);
984 clickDraw: function() {
985 if (!this.game.mycolor || this.game.type == "import") return;
986 if (["received", "threerep"].includes(this.drawOffer)) {
987 if (!confirm(this.st.tr["Accept draw?"])) return;
989 this.drawOffer == "received"
991 : "Three repetitions";
992 this.send("draw", { data: message });
993 this.gameOver("1/2", message);
994 } else if (this.drawOffer == "") {
995 // No effect if drawOffer == "sent"
996 if (this.game.mycolor != this.vr.turn) {
997 alert(this.st.tr["Draw offer only in your turn"]);
1000 if (!confirm(this.st.tr["Offer draw?"])) return;
1001 this.drawOffer = "sent";
1002 this.send("drawoffer");
1003 if (this.game.type == "live") {
1006 { drawOffer: this.game.mycolor }
1008 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1011 addAndGotoLiveGame: function(gameInfo, callback) {
1012 const game = Object.assign(
1016 // (other) Game infos: constant
1017 fenStart: gameInfo.fen,
1018 vname: this.game.vname,
1019 created: Date.now(),
1020 // Game state (including FEN): will be updated
1022 clocks: [-1, -1], //-1 = unstarted
1027 GameStorage.add(game, (err) => {
1028 // No error expected.
1030 if (this.st.settings.sound)
1031 new Audio("/sounds/newgame.flac").play().catch(() => {});
1032 if (!!callback) callback();
1033 this.$router.push("/game/" + gameInfo.id);
1037 clickRematch: function() {
1038 if (!this.game.mycolor || this.game.type == "import") return;
1039 if (this.rematchOffer == "received") {
1040 // Start a new game!
1042 id: getRandString(), //ignored if corr
1043 fen: V.GenRandInitFen(this.game.randomness),
1044 players: [this.game.players[1], this.game.players[0]],
1046 cadence: this.game.cadence
1048 const notifyNewGame = () => {
1049 const oppsid = this.getOppsid(); //may be null
1050 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1051 // To main Hall if corr game:
1052 if (this.game.type == "corr")
1053 this.send("newgame", { data: gameInfo, page: "/" });
1054 // Also to MyGames page:
1055 this.notifyMyGames("newgame", gameInfo);
1057 if (this.game.type == "live")
1058 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1065 // cid is useful to delete the challenge:
1066 data: { gameInfo: gameInfo },
1067 success: (response) => {
1068 gameInfo.id = response.gameId;
1070 this.$router.push("/game/" + response.gameId);
1075 } else if (this.rematchOffer == "") {
1076 this.rematchOffer = "sent";
1077 this.send("rematchoffer", { data: true });
1078 if (this.game.type == "live") {
1081 { rematchOffer: this.game.mycolor }
1083 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1084 } else if (this.rematchOffer == "sent") {
1085 // Toggle rematch offer (on --> off)
1086 this.rematchOffer = "";
1087 this.send("rematchoffer", { data: false });
1088 if (this.game.type == "live") {
1091 { rematchOffer: '' }
1093 } else this.updateCorrGame({ rematchOffer: 'n' });
1096 abortGame: function() {
1097 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1099 this.gameOver("?", "Stop");
1102 resign: function() {
1103 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1105 this.send("resign", { data: this.game.mycolor });
1106 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1107 const side = (this.game.mycolor == "w" ? "White" : "Black");
1108 this.gameOver(score, side + " surrender");
1110 loadGame: function(game, callback) {
1111 const gtype = game.type || this.getGameType(game);
1112 const tc = extractTime(game.cadence);
1113 const myIdx = game.players.findIndex(p => {
1115 p.sid == this.st.user.sid ||
1116 (!!p.name && p.id == this.st.user.id)
1119 // Sometimes the name isn't stored yet (TODO: why?)
1123 !game.players[myIdx].name &&
1126 game.players[myIdx].name = this.st.user.name;
1129 { playerName: { idx: myIdx, name: this.st.user.name } }
1132 // "mycolor" is undefined for observers
1133 const mycolor = [undefined, "w", "b"][myIdx + 1];
1134 if (gtype == "corr") {
1135 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1136 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1137 // NOTE: clocks in seconds
1138 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1139 game.clocks = [tc.mainTime, tc.mainTime];
1140 const L = game.moves.length;
1141 if (game.score == "*") {
1144 game.clocks[L % 2] -=
1145 (Date.now() - game.moves[L-1].played) / 1000;
1148 // Now that we used idx and played, re-format moves as for live games
1149 game.moves = game.moves.map(m => m.squares);
1151 else if (gtype == "live") {
1152 if (game.clocks[0] < 0) {
1153 // Game is unstarted. clock is ignored until move 2
1154 game.clocks = [tc.mainTime, tc.mainTime];
1156 // I play in this live game
1159 { clocks: game.clocks }
1164 // It's my turn: clocks not updated yet
1165 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1169 // gtype == "import"
1170 game.clocks = [tc.mainTime, tc.mainTime];
1171 // Live games before 26/03/2020 don't have chat history:
1172 if (!game.chats) game.chats = []; //TODO: remove line
1173 // Sort chat messages from newest to oldest
1174 game.chats.sort((c1, c2) => c2.added - c1.added);
1177 game.chats.length > 0 &&
1178 (!game.chatRead || game.chatRead < game.chats[0].added)
1180 // A chat message arrived since my last reading:
1181 document.getElementById("chatBtn").classList.add("somethingnew");
1183 // TODO: merge next 2 "if" conditions
1184 if (!!game.drawOffer) {
1185 if (game.drawOffer == "t")
1186 // Three repetitions
1187 this.drawOffer = "threerep";
1189 // Draw offered by any of the players:
1190 if (myIdx < 0) this.drawOffer = "received";
1192 // I play in this game:
1194 (game.drawOffer == "w" && myIdx == 0) ||
1195 (game.drawOffer == "b" && myIdx == 1)
1197 this.drawOffer = "sent";
1198 else this.drawOffer = "received";
1202 if (!!game.rematchOffer) {
1203 if (myIdx < 0) this.rematchOffer = "received";
1205 // I play in this game:
1207 (game.rematchOffer == "w" && myIdx == 0) ||
1208 (game.rematchOffer == "b" && myIdx == 1)
1210 this.rematchOffer = "sent";
1212 else this.rematchOffer = "received";
1215 this.repeat = {}; //reset: scan past moves' FEN:
1217 this.vr = new V(game.fenStart);
1219 game.moves.forEach(m => {
1220 playMove(m, this.vr);
1221 const fenIdx = this.vr.getFenForRepeat();
1222 this.repeat[fenIdx] = this.repeat[fenIdx]
1223 ? this.repeat[fenIdx] + 1
1226 // Imported games don't have current FEN
1227 if (!game.fen) game.fen = this.vr.getFen();
1228 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1229 this.game = Object.assign(
1230 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1233 increment: tc.increment,
1235 // opponent sid not strictly required (or available), but easier
1236 // at least oppsid or oppid is available anyway:
1237 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1238 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1242 this.$refs["basegame"].re_setVariables(this.game);
1244 this.gotMoveIdx = game.moves.length - 1;
1245 // If we arrive here after 'nextGame' action, the board might be hidden
1246 let boardDiv = document.querySelector(".game");
1247 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1248 boardDiv.style.visibility = "visible";
1249 this.re_setClocks();
1250 this.$nextTick(() => {
1251 this.game.rendered = true;
1252 // Did lastate arrive before game was rendered?
1253 if (!!this.lastate) this.processLastate();
1255 if (this.lastateAsked) {
1256 this.lastateAsked = false;
1257 this.sendLastate(game.oppsid);
1259 if (!!callback) callback();
1261 loadVariantThenGame: async function(game, callback) {
1262 await import("@/variants/" + game.vname + ".js")
1263 .then((vModule) => {
1264 window.V = vModule[game.vname + "Rules"];
1265 this.loadGame(game, callback);
1267 // (AJAX) Request to get rules content (plain text, HTML)
1270 "raw-loader!@/translations/rules/" +
1272 this.st.lang + ".pug"
1274 // Next two lines fix a weird issue after last update (2019-11)
1275 .replace(/\\n/g, " ")
1276 .replace(/\\"/g, '"')
1277 .replace('module.exports = "', "")
1279 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1281 // 3 cases for loading a game:
1282 // - from indexedDB (running or completed live game I play)
1283 // - from server (one correspondance game I play[ed] or not)
1284 // - from remote peer (one live game I don't play, finished or not)
1285 fetchGame: function(callback) {
1286 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1287 // corr games identifiers are integers
1292 data: { gid: this.gameRef },
1294 res.game.moves.forEach(m => {
1295 m.squares = JSON.parse(m.squares);
1302 else if (!!this.gameRef.match(/^i/))
1303 // Game import (maybe remote)
1304 ImportgameStorage.get(this.gameRef, callback);
1306 // Local live game (or remote)
1307 GameStorage.get(this.gameRef, callback);
1309 re_setClocks: function() {
1310 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1311 if (this.game.moves.length < 2 || this.game.score != "*") {
1312 // 1st move not completed yet, or game over: freeze time
1315 const currentTurn = this.vr.turn;
1316 const currentMovesCount = this.game.moves.length;
1317 const colorIdx = ["w", "b"].indexOf(currentTurn);
1318 this.clockUpdate = setInterval(
1321 this.game.clocks[colorIdx] < 0 ||
1322 this.game.moves.length > currentMovesCount ||
1323 this.game.score != "*"
1325 clearInterval(this.clockUpdate);
1326 this.clockUpdate = null;
1327 if (this.game.clocks[colorIdx] < 0)
1329 currentTurn == "w" ? "0-1" : "1-0",
1336 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1343 // Update variables and storage after a move:
1344 processMove: function(move, data) {
1345 if (this.game.type == "import")
1346 // Shouldn't receive any messages in this mode:
1348 if (!data) data = {};
1349 const moveCol = this.vr.turn;
1350 const colorIdx = ["w", "b"].indexOf(moveCol);
1351 const nextIdx = 1 - colorIdx;
1352 const doProcessMove = () => {
1353 const origMovescount = this.game.moves.length;
1354 // The move is (about to be) played: stop clock
1355 clearInterval(this.clockUpdate);
1356 this.clockUpdate = null;
1357 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1358 if (this.drawOffer == "received")
1360 this.drawOffer = "";
1361 if (this.game.type == "live" && origMovescount >= 2) {
1362 this.game.clocks[colorIdx] += this.game.increment;
1363 // For a correct display in casqe of disconnected opponent:
1367 ppt(this.game.clocks[colorIdx]).split(':')
1369 GameStorage.update(this.gameRef, {
1370 // It's not my turn anymore:
1375 // Update current game object:
1376 playMove(move, this.vr);
1378 // Received move, score is computed in BaseGame, but maybe not yet.
1379 // ==> Compute it here, although this is redundant (TODO)
1380 data.score = this.vr.getCurrentScore();
1381 if (data.score != "*") this.gameOver(data.score);
1382 this.game.moves.push(move);
1383 this.game.fen = this.vr.getFen();
1384 if (this.game.type == "corr") {
1385 // In corr games, just reset clock to mainTime:
1386 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1388 // If repetition detected, consider that a draw offer was received:
1389 const fenObj = this.vr.getFenForRepeat();
1390 this.repeat[fenObj] =
1391 !!this.repeat[fenObj]
1392 ? this.repeat[fenObj] + 1
1394 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1395 else if (this.drawOffer == "threerep") this.drawOffer = "";
1396 if (!!this.game.mycolor && !data.receiveMyMove) {
1397 // NOTE: 'var' to see that variable outside this block
1398 var filtered_move = getFilteredMove(move);
1400 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1401 // Notify turn on MyGames page:
1410 // Since corr games are stored at only one location, update should be
1411 // done only by one player for each move:
1413 this.game.type == "live" &&
1414 !!this.game.mycolor &&
1415 moveCol != this.game.mycolor &&
1416 this.game.moves.length >= 2
1418 // Receive a move: update initime
1419 this.game.initime = Date.now();
1420 GameStorage.update(this.gameRef, {
1421 // It's my turn now!
1422 initime: this.game.initime
1426 !!this.game.mycolor &&
1427 !data.receiveMyMove &&
1428 (this.game.type == "live" || moveCol == this.game.mycolor)
1431 switch (this.drawOffer) {
1436 drawCode = this.game.mycolor;
1439 drawCode = V.GetOppCol(this.game.mycolor);
1442 if (this.game.type == "corr") {
1443 // corr: only move, fen and score
1444 this.updateCorrGame({
1447 squares: filtered_move,
1450 // Code "n" for "None" to force reset (otherwise it's ignored)
1451 drawOffer: drawCode || "n"
1455 const updateStorage = () => {
1456 GameStorage.update(this.gameRef, {
1458 move: filtered_move,
1459 moveIdx: origMovescount,
1460 clocks: this.game.clocks,
1464 // The active tab can update storage immediately
1465 if (this.focus) updateStorage();
1466 // Small random delay otherwise
1467 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1470 // Send move ("newmove" event) to people in the room (if our turn)
1471 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1473 move: filtered_move,
1474 index: origMovescount,
1475 // color is required to check if this is my move
1476 // (if several tabs opened)
1478 cancelDrawOffer: this.drawOffer == ""
1480 if (this.game.type == "live")
1481 sendMove["clock"] = this.game.clocks[colorIdx];
1482 // (Live) Clocks will re-start when the opponent pingback arrive
1483 this.opponentGotMove = false;
1484 this.send("newmove", {data: sendMove});
1485 // If the opponent doesn't reply gotmove soon enough, re-send move:
1486 // Do this at most 2 times, because more would mean network issues,
1487 // opponent would then be expected to disconnect/reconnect.
1489 const currentUrl = document.location.href;
1490 this.retrySendmove = setInterval(
1494 this.opponentGotMove ||
1495 document.location.href != currentUrl //page change
1497 clearInterval(this.retrySendmove);
1500 const oppsid = this.getOppsid();
1502 // Opponent is disconnected: he'll ask last state
1503 clearInterval(this.retrySendmove);
1505 this.send("newmove", { data: sendMove, target: oppsid });
1513 // Not my move or I'm an observer: just start other player's clock
1514 this.re_setClocks();
1517 this.game.type == "corr" &&
1519 moveCol == this.game.mycolor &&
1522 let boardDiv = document.querySelector(".game");
1523 const afterSetScore = () => {
1525 if (this.st.settings.gotonext && this.nextIds.length > 0)
1526 this.showNextGame();
1528 // The board might have been hidden:
1529 if (boardDiv.style.visibility == "hidden")
1530 boardDiv.style.visibility = "visible";
1531 if (data.score == "*") this.re_setClocks();
1534 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1535 // We may play several moves in a row: in case of, remove listener:
1536 let elClone = el.cloneNode(true);
1537 el.parentNode.replaceChild(elClone, el);
1538 elClone.addEventListener(
1541 document.getElementById("modalConfirm").checked = false;
1542 if (!!data.score && data.score != "*")
1544 this.gameOver(data.score, null, afterSetScore);
1545 else afterSetScore();
1548 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1549 const arMove = (Array.isArray(move) ? move : [move]);
1550 for (let i = 0; i < arMove.length; i++)
1551 V.PlayOnBoard(this.vr.board, arMove[i]);
1552 const position = this.vr.getBaseFen();
1553 for (let i = arMove.length - 1; i >= 0; i--)
1554 V.UndoOnBoard(this.vr.board, arMove[i]);
1555 if (["all","byrow"].includes(V.ShowMoves)) {
1556 this.curDiag = getDiagram({
1558 orientation: V.CanFlip ? this.game.mycolor : "w"
1560 document.querySelector("#confirmDiv > .card").style.width =
1561 boardDiv.offsetWidth + "px";
1564 // Incomplete information: just ask confirmation
1565 // Hide the board, because otherwise it could reveal infos
1566 boardDiv.style.visibility = "hidden";
1567 this.moveNotation = getFullNotation(move);
1569 document.getElementById("modalConfirm").checked = true;
1573 if (!!data.score && data.score != "*")
1574 this.gameOver(data.score, null, doProcessMove);
1575 else doProcessMove();
1578 cancelMove: function() {
1579 let boardDiv = document.querySelector(".game");
1580 if (boardDiv.style.visibility == "hidden")
1581 boardDiv.style.visibility = "visible";
1582 document.getElementById("modalConfirm").checked = false;
1583 this.$refs["basegame"].cancelLastMove();
1585 // In corr games, callback to change page only after score is set:
1586 gameOver: function(score, scoreMsg, callback) {
1587 this.game.score = score;
1588 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1589 this.game.scoreMsg = scoreMsg;
1590 document.getElementById("modalRules").checked = false;
1591 // Display result in a un-missable way:
1592 document.getElementById("modalScore").checked = true;
1593 this.$set(this.game, "scoreMsg", scoreMsg);
1594 const myIdx = this.game.players.findIndex(p => {
1596 p.sid == this.st.user.sid ||
1597 (!!p.name && p.id == this.st.user.id)
1601 // OK, I play in this game
1606 if (this.game.type == "live") {
1607 GameStorage.update(this.gameRef, scoreObj);
1608 // Notify myself locally if I'm elsewhere:
1612 { body: score + " : " + scoreMsg }
1615 if (!!callback) callback();
1617 else this.updateCorrGame(scoreObj, callback);
1618 // Notify the score to main Hall.
1619 // TODO: only one player (currently double send)
1620 this.send("result", { gid: this.game.id, score: score });
1621 // Also to MyGames page (TODO: doubled as well...)
1630 else if (!!callback) callback();
1636 <style lang="sass" scoped>
1637 #scoreDiv > .card, #rematchDiv > .card
1645 @media screen and (max-width: 1500px)
1647 @media screen and (max-width: 1024px)
1649 @media screen and (max-width: 767px)
1659 background-color: lightgreen
1671 @media screen and (max-width: 767px)
1676 display: inline-block
1680 display: inline-block
1682 display: inline-flex
1686 @media screen and (max-width: 767px)
1695 @media screen and (max-width: 767px)
1707 background-color: #edda99
1709 display: inline-block
1713 display: inline-block
1720 @media screen and (max-width: 767px)
1722 display: inline-block
1735 animation: blink-animation 2s steps(3, start) infinite
1736 @keyframes blink-animation
1741 display: inline-block
1753 .draw-sent, .draw-sent:hover
1754 background-color: lightyellow
1756 .draw-received, .draw-received:hover
1757 background-color: #73C6B6
1759 .draw-threerep, .draw-threerep:hover
1760 background-color: #D2B4DE
1762 .rematch-sent, .rematch-sent:hover
1763 background-color: lightyellow
1765 .rematch-received, .rematch-received:hover
1766 background-color: #48C9B0
1769 background-color: #D2B4DE
1782 background-color: lightgreen
1784 background-color: red
1787 color: var(--card-fore-color)
1790 font-size: calc(1rem * var(--heading-ratio))
1792 margin: calc(1.5 * var(--universal-margin))
1796 @import "@/styles/_rules.sass"
1797 @import "@/styles/_board_squares_img.sass"