3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 h4#variantNameInGame(@click="gotoRules") {{ 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)"
49 v-if="participateInChat(p)"
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()")
123 span.name(:class="{connected: isConnected(0)}")
124 | {{ game.players[0].name || "@nonymous" }}
126 v-if="game.score=='*'"
127 :class="{yourturn: !!vr && vr.turn == 'w'}"
129 span.time-left {{ virtualClocks[0][0] }}
130 span.time-separator(v-if="!!virtualClocks[0][1]") :
131 span.time-right(v-if="!!virtualClocks[0][1]")
132 | {{ virtualClocks[0][1] }}
134 span.name(:class="{connected: isConnected(1)}")
135 | {{ game.players[1].name || "@nonymous" }}
137 v-if="game.score=='*'"
138 :class="{yourturn: !!vr && vr.turn == 'b'}"
140 span.time-left {{ virtualClocks[1][0] }}
141 span.time-separator(v-if="!!virtualClocks[1][1]") :
142 span.time-right(v-if="!!virtualClocks[1][1]")
143 | {{ virtualClocks[1][1] }}
145 span.name(:class="{connected: isConnected(0)}")
146 | {{ game.players[0].name || "@nonymous" }}
148 span.name(:class="{connected: isConnected(1)}")
149 | {{ game.players[1].name || "@nonymous" }}
150 div(v-if="game.score=='*'")
151 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
152 span.time-left {{ virtualClocks[0][0] }}
153 span.time-separator(v-if="!!virtualClocks[0][1]") :
154 span.time-right(v-if="!!virtualClocks[0][1]")
155 | {{ virtualClocks[0][1] }}
157 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
158 span.time-left {{ virtualClocks[1][0] }}
159 span.time-separator(v-if="!!virtualClocks[1][1]") :
160 span.time-right(v-if="!!virtualClocks[1][1]")
161 | {{ virtualClocks[1][1] }}
165 @newmove="processMove"
170 import BaseGame from "@/components/BaseGame.vue";
171 import Chat from "@/components/Chat.vue";
172 import { store } from "@/store";
173 import { GameStorage } from "@/utils/gameStorage";
174 import { ImportgameStorage } from "@/utils/importgameStorage";
175 import { ppt } from "@/utils/datetime";
176 import { notify } from "@/utils/notifications";
177 import { ajax } from "@/utils/ajax";
178 import { extractTime } from "@/utils/timeControl";
179 import { getRandString } from "@/utils/alea";
180 import { getScoreMessage } from "@/utils/scoring";
181 import { getFullNotation } from "@/utils/notation";
182 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
183 import { processModalClick } from "@/utils/modalClick";
184 import { playMove, getFilteredMove } from "@/utils/playUndo";
185 import { ArrayFun } from "@/utils/array";
186 import params from "@/parameters";
196 // gameRef can point to a corr game, local game or remote live game
199 game: {}, //passed to BaseGame
200 focus: !document.hidden, //will not always work... TODO
201 // virtualClocks will be initialized from true game.clocks
203 vr: null, //"variant rules" object initialized from FEN
209 people: {}, //players + observers
210 lastate: undefined, //used if opponent send lastate before game is ready
211 repeat: {}, //detect position repetition
212 curDiag: "", //for corr moves confirmation
214 roomInitialized: false,
215 // If newmove has wrong index: ask fullgame again:
217 gameIsLoading: false,
218 // If asklastate got no reply, ask again:
220 gotMoveIdx: -1, //last move index received
221 // If newmove got no pingback, send again:
222 opponentGotMove: false,
224 socketCloseListener: 0,
225 // Incomplete info games: show move played
227 // Intervals from setInterval():
231 // Related to (killing of) self multi-connects:
236 $route: function(to, from) {
237 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
239 this.cleanBeforeDestroy();
240 else if (from.params["id"] != to.params["id"]) {
241 // Change everything:
242 this.cleanBeforeDestroy();
243 let boardDiv = document.querySelector(".game");
245 // In case of incomplete information variant:
246 boardDiv.style.visibility = "hidden";
250 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
253 // NOTE: some redundant code with Hall.vue (mostly related to people array)
254 created: function() {
257 mounted: function() {
258 document.getElementById("chatWrap")
259 .addEventListener("click", (e) => {
260 processModalClick(e, () => {
261 this.toggleChat("close")
264 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
266 document.getElementById(eltName)
267 .addEventListener("click", processModalClick);
271 beforeDestroy: function() {
272 this.cleanBeforeDestroy();
275 cleanBeforeDestroy: function() {
276 clearInterval(this.socketCloseListener);
277 document.removeEventListener('visibilitychange', this.visibilityChange);
278 window.removeEventListener('focus', this.onFocus);
279 window.removeEventListener('blur', this.onBlur);
280 if (!!this.askLastate) clearInterval(this.askLastate);
281 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
282 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
283 this.conn.removeEventListener("message", this.socketMessageListener);
284 this.send("disconnect");
287 visibilityChange: function() {
288 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
289 this.focus = (document.visibilityState == "visible");
290 if (!this.focus && !!this.rematchOffer) {
291 this.rematchOffer = "";
292 this.send("rematchoffer", { data: false });
293 // Do not remove rematch offer from (local) storage
295 this.send(this.focus ? "getfocus" : "losefocus");
297 onFocus: function() {
299 this.send("getfocus");
303 if (!!this.rematchOffer) {
304 this.rematchOffer = "";
305 this.send("rematchoffer", { data: false });
307 this.send("losefocus");
309 isLargeScreen: function() {
310 return window.innerWidth >= 768;
312 btnTooltipClass: function(thing) {
314 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
317 { tooltip: !("ontouchstart" in window) },
322 gotoRules: function() {
323 this.$router.push("/variants/" + this.game.vname);
325 participateInChat: function(p) {
326 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
328 someAnonymousPresent: function() {
330 Object.values(this.people).some(p =>
331 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
335 atCreation: function() {
336 document.addEventListener('visibilitychange', this.visibilityChange);
337 window.addEventListener('focus', this.onFocus);
338 window.addEventListener('blur', this.onBlur);
339 // 0] (Re)Set variables
340 this.gameRef = this.$route.params["id"];
341 // next = next corr games IDs to navigate faster (if applicable)
342 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
343 // Always add myself to players' list
344 const my = this.st.user;
345 const tmpId = getRandString();
353 tmpId: { focus: true }
358 players: [{ name: "" }, { name: "" }],
362 let chatComp = this.$refs["chatcomp"];
363 if (!!chatComp) chatComp.chats = [];
364 this.virtualClocks = [[0,0], [0,0]];
366 this.rulesContent = "";
368 this.lastateAsked = false;
369 this.rematchOffer = "";
370 this.lastate = undefined;
371 this.roomInitialized = false;
372 this.askGameTime = 0;
373 this.gameIsLoading = false;
374 this.gotLastate = false;
375 this.gotMoveIdx = -1;
376 this.opponentGotMove = false;
377 this.askLastate = null;
378 this.retrySendmove = null;
379 this.clockUpdate = null;
380 this.newConnect = {};
381 // 1] Initialize connection
382 this.connexionString =
384 "/?sid=" + this.st.user.sid +
385 "&id=" + this.st.user.id +
388 // Discard potential "/?next=[...]" for page indication:
389 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
390 this.conn = new WebSocket(this.connexionString);
391 this.conn.addEventListener("message", this.socketMessageListener);
392 this.socketCloseListener = setInterval(
394 if (this.conn.readyState == 3) {
395 this.conn.removeEventListener(
396 "message", this.socketMessageListener);
397 this.conn = new WebSocket(this.connexionString);
398 this.conn.addEventListener("message", this.socketMessageListener);
403 // Socket init required before loading remote game:
404 const socketInit = callback => {
405 if (this.conn.readyState == 1)
409 // Socket not ready yet (initial loading)
410 // NOTE: first arg is Websocket object, unused here:
411 this.conn.onopen = () => callback();
413 this.fetchGame((game) => {
415 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
417 // Live game stored remotely: need socket to retrieve it
418 // NOTE: the callback "roomInit" will be lost, so it's not provided.
419 // --> It will be given when receiving "fullgame" socket event.
420 socketInit(() => { this.send("askfullgame"); });
423 roomInit: function() {
424 if (!this.roomInitialized) {
425 // Notify the room only now that I connected, because
426 // messages might be lost otherwise (if game loading is slow)
427 this.send("connect");
428 this.send("pollclients");
429 // We may ask fullgame several times if some moves are lost,
430 // but room should be init only once:
431 this.roomInitialized = true;
434 send: function(code, obj) {
435 if (!!this.conn && this.conn.readyState == 1)
436 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
438 isConnected: function(index) {
439 const player = this.game.players[index];
440 // Is it me ? In this case no need to bother with focus
441 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
442 // Still have to check for name (because of potential multi-accounts
443 // on same browser, although this should be rare...)
444 return (!this.st.user.name || this.st.user.name == player.name);
445 // Try to find a match in people:
449 Object.keys(this.people).some(sid => {
452 Object.values(this.people[sid].tmpIds).some(v => v.focus)
459 Object.values(this.people).some(p => {
462 Object.values(p.tmpIds).some(v => v.focus)
468 getOppsid: function() {
469 let oppsid = this.game.oppsid;
471 oppsid = Object.keys(this.people).find(
472 sid => this.people[sid].id == this.game.oppid
475 // oppsid is useful only if opponent is online:
476 if (!!oppsid && !!this.people[oppsid]) return oppsid;
479 // NOTE: action if provided is always a closing action
480 toggleChat: function(action) {
481 if (!action && document.getElementById("modalChat").checked)
483 document.getElementById("inputChat").focus();
485 document.getElementById("chatBtn").classList.remove("somethingnew");
486 if (!!this.game.mycolor) {
487 // Update "chatRead" variable either on server or locally
488 if (this.game.type == "corr")
489 this.updateCorrGame({ chatRead: this.game.mycolor });
490 else if (this.game.type == "live")
491 GameStorage.update(this.gameRef, { chatRead: true });
495 processChat: function(chat) {
496 this.send("newchat", { data: chat });
497 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
498 if (!!this.game.mycolor) {
499 if (this.game.type == "corr")
500 this.updateCorrGame({ chat: chat });
503 chat.added = Date.now();
504 GameStorage.update(this.gameRef, { chat: chat });
508 clearChat: function() {
509 if (!!this.game.mycolor) {
510 if (this.game.type == "corr") {
514 { data: { gid: this.game.id } }
518 GameStorage.update(this.gameRef, { delchat: true });
520 this.$set(this.game, "chats", []);
523 getGameType: function(game) {
524 if (!!game.id.toString().match(/^i/)) return "import";
525 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
527 // Notify something after a new move (to opponent and me on MyGames page)
528 notifyMyGames: function(thing, data) {
533 targets: this.game.players.map(p => {
534 return { sid: p.sid, id: p.id };
539 showNextGame: function() {
540 // Did I play in current game? If not, add it to nextIds list
541 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
542 this.nextIds.unshift(this.game.id);
543 const nextGid = this.nextIds.pop();
545 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
547 askGameAgain: function() {
548 this.gameIsLoading = true;
549 const currentUrl = document.location.href;
550 const doAskGame = () => {
551 if (document.location.href != currentUrl) return; //page change
552 this.fetchGame((game) => {
554 // This is my game: just reload.
557 // Just ask fullgame again (once!), this is much simpler.
558 // If this fails, the user could just reload page :/
559 this.send("askfullgame");
562 // Delay of at least 2s between two game requests
563 const now = Date.now();
564 const delay = Math.max(2000 - (now - this.askGameTime), 0);
565 this.askGameTime = now;
566 setTimeout(doAskGame, delay);
568 socketMessageListener: function(msg) {
569 if (!this.conn) return;
570 const data = JSON.parse(msg.data);
573 // TODO: shuffling and random filtering on server,
574 // if the room is really crowded.
575 Object.keys(data.sockIds).forEach(sid => {
576 if (sid != this.st.user.sid) {
577 this.send("askidentity", { target: sid });
578 this.people[sid] = { tmpIds: data.sockIds[sid] };
581 // Complete my tmpIds:
582 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
587 if (!this.people[data.from[0]]) {
588 // focus depends on the tmpId (e.g. tab)
594 [data.from[1]]: { focus: true }
598 // For self multi-connects tests:
599 this.newConnect[data.from[0]] = true;
600 this.send("askidentity", { target: data.from[0] });
602 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
603 this.$forceUpdate(); //TODO: shouldn't be required
607 if (!this.people[data.from[0]]) return;
608 delete this.people[data.from[0]].tmpIds[data.from[1]];
609 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
610 this.$delete(this.people, data.from[0]);
611 else this.$forceUpdate(); //TODO: shouldn't be required
614 let player = this.people[data.from[0]];
616 player.tmpIds[data.from[1]].focus = true;
617 this.$forceUpdate(); //TODO: shouldn't be required
622 let player = this.people[data.from[0]];
624 player.tmpIds[data.from[1]].focus = false;
625 this.$forceUpdate(); //TODO: shouldn't be required
629 case "askidentity": {
630 // Request for identification
632 // Decompose to avoid revealing email
633 name: this.st.user.name,
634 sid: this.st.user.sid,
637 this.send("identity", { data: me, target: data.from });
641 const user = data.data;
642 let player = this.people[user.sid];
643 // player.tmpIds is already set
644 player.name = user.name;
646 if (this.game.type == "live") {
648 this.game.players.findIndex(p => p.sid == this.st.user.sid);
649 // Sometimes a player name isn't stored yet (TODO: why?)
652 !this.game.players[1 - myGidx].name &&
653 this.game.players[1 - myGidx].sid == user.sid &&
656 this.game.players[1-myGidx].name = user.name;
659 { playerName: { idx: 1 - myGidx, name: user.name } }
663 this.$forceUpdate(); //TODO: shouldn't be required
664 // If I multi-connect, kill current connexion if no mark (I'm older)
665 if (this.newConnect[user.sid]) {
666 delete this.newConnect[user.sid];
669 user.id == this.st.user.id &&
670 user.sid != this.st.user.sid
672 this.cleanBeforeDestroy();
673 alert(this.st.tr["New connexion detected: tab now offline"]);
677 // Ask potentially missed last state, if opponent and I play
680 !!this.game.mycolor &&
681 this.game.type == "live" &&
682 this.game.score == "*" &&
683 this.game.players.some(p => p.sid == user.sid)
685 this.send("asklastate", { target: user.sid });
687 this.askLastate = setInterval(
689 // Ask at most 3 times:
690 // if no reply after that there should be a network issue.
694 !!this.people[user.sid]
696 this.send("asklastate", { target: user.sid });
699 clearInterval(this.askLastate);
708 // Send current (live or import) game,
709 // if not asked by any of the players
711 this.game.type != "corr" &&
712 this.game.players.every(p => p.sid != data.from[0])
716 // FEN is current position, unused for now
718 players: this.game.players,
720 cadence: this.game.cadence,
721 score: this.game.score
723 this.send("game", { data: myGame, target: data.from });
727 const gameToSend = Object.keys(this.game)
730 "id","fen","players","vid","cadence","fenStart","vname",
731 "moves","clocks","score","drawOffer","rematchOffer"
735 obj[k] = this.game[k];
740 this.send("fullgame", { data: gameToSend, target: data.from });
743 if (!!data.data.empty) {
744 alert(this.st.tr["The game should be in another tab"]);
748 // Callback "roomInit" to poll clients only after game is loaded
749 this.loadVariantThenGame(data.data, this.roomInit);
752 // Sending informative last state if I played a move or score != "*"
753 // If the game or moves aren't loaded yet, delay the sending:
754 // TODO: socket init after game load, so the game is supposedly ready
755 if (!this.game || !this.game.moves) this.lastateAsked = true;
756 else this.sendLastate(data.from);
759 // Got opponent infos about last move
760 this.gotLastate = true;
761 this.lastate = data.data;
762 if (this.game.rendered)
763 // Game is rendered (Board component)
764 this.processLastate();
765 // Else: will be processed when game is ready
769 const movePlus = data.data;
770 const movesCount = this.game.moves.length;
771 if (movePlus.index > movesCount) {
772 // This can only happen if I'm an observer and missed a move.
773 if (this.gotMoveIdx < movePlus.index)
774 this.gotMoveIdx = movePlus.index;
775 if (!this.gameIsLoading) this.askGameAgain();
779 movePlus.index < movesCount ||
780 this.gotMoveIdx >= movePlus.index
782 // Opponent re-send but we already have the move:
783 // (maybe he didn't receive our pingback...)
784 this.send("gotmove", {data: movePlus.index, target: data.from});
786 this.gotMoveIdx = movePlus.index;
787 const receiveMyMove = (movePlus.color == this.game.mycolor);
788 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
789 if (!receiveMyMove && !!this.game.mycolor) {
790 // Notify opponent that I got the move:
793 { data: movePlus.index, target: data.from }
795 // And myself if I'm elsewhere:
801 (this.game.players[moveColIdx].name || "@nonymous") +
807 if (movePlus.cancelDrawOffer) {
808 // Opponent refuses draw
810 // NOTE for corr games: drawOffer reset by player in turn
812 this.game.type == "live" &&
813 !!this.game.mycolor &&
816 GameStorage.update(this.gameRef, { drawOffer: "" });
819 this.$refs["basegame"].play(movePlus.move, "received");
820 this.game.clocks[moveColIdx] = movePlus.clock;
823 { receiveMyMove: receiveMyMove }
830 this.opponentGotMove = true;
831 // Now his clock starts running on my side:
832 const oppIdx = ['w','b'].indexOf(this.vr.turn);
833 // NOTE: next line to avoid multi-resetClocks when several tabs
834 // on same game, resulting in a faster countdown.
835 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
840 const score = (data.data == "b" ? "1-0" : "0-1");
841 const side = (data.data == "w" ? "White" : "Black");
842 this.gameOver(score, side + " surrender");
845 this.gameOver("?", "Stop");
848 this.gameOver("1/2", data.data);
851 // NOTE: observers don't know who offered draw
852 this.drawOffer = "received";
853 if (!!this.game.mycolor && this.game.type == "live") {
856 { drawOffer: V.GetOppCol(this.game.mycolor) }
861 // NOTE: observers don't know who offered rematch
862 this.rematchOffer = data.data ? "received" : "";
863 if (!!this.game.mycolor && this.game.type == "live") {
866 { rematchOffer: V.GetOppCol(this.game.mycolor) }
871 // A game started, redirect if I'm playing in
872 const gameInfo = data.data;
873 const gameType = this.getGameType(gameInfo);
875 gameType == "live" &&
876 gameInfo.players.some(p => p.sid == this.st.user.sid)
878 this.addAndGotoLiveGame(gameInfo);
880 gameType == "corr" &&
881 gameInfo.players.some(p => p.id == this.st.user.id)
883 this.$router.push("/game/" + gameInfo.id);
885 this.rematchId = gameInfo.id;
886 document.getElementById("modalRules").checked = false;
887 document.getElementById("modalScore").checked = false;
888 document.getElementById("modalRematch").checked = true;
893 let chat = data.data;
894 this.$refs["chatcomp"].newChat(chat);
895 if (this.game.type == "live") {
896 chat.added = Date.now();
897 if (!!this.game.mycolor)
898 GameStorage.update(this.gameRef, { chat: chat });
900 if (!document.getElementById("modalChat").checked)
901 document.getElementById("chatBtn").classList.add("somethingnew");
906 updateCorrGame: function(obj, callback) {
916 if (!!callback) callback();
921 sendLastate: function(target) {
922 // Send our "last state" informations to opponent
923 const L = this.game.moves.length;
924 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
927 (L > 0 && this.vr.turn != this.game.mycolor)
928 ? this.game.moves[L - 1]
930 clock: this.game.clocks[myIdx],
931 // Since we played a move (or abort or resign),
932 // only drawOffer=="sent" is possible
933 drawSent: this.drawOffer == "sent",
934 rematchSent: this.rematchOffer == "sent",
935 score: this.game.score != "*" ? this.game.score : undefined,
936 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
939 this.send("lastate", { data: myLastate, target: target });
941 // lastate was received, but maybe game wasn't ready yet:
942 processLastate: function() {
943 const data = this.lastate;
944 this.lastate = undefined; //security...
945 const L = this.game.moves.length;
946 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
947 this.game.clocks[oppIdx] = data.clock;
948 if (data.movesCount > L) {
949 // Just got last move from him
950 this.$refs["basegame"].play(data.lastMove, "received");
951 this.processMove(data.lastMove);
953 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
956 if (data.drawSent) this.drawOffer = "received";
957 if (data.rematchSent) this.rematchOffer = "received";
960 if (this.game.score == "*")
961 this.gameOver(data.score, data.scoreMsg);
964 clickDraw: function() {
965 if (!this.game.mycolor || this.game.type == "import") return;
966 if (["received", "threerep"].includes(this.drawOffer)) {
967 if (!confirm(this.st.tr["Accept draw?"])) return;
969 this.drawOffer == "received"
971 : "Three repetitions";
972 this.send("draw", { data: message });
973 this.gameOver("1/2", message);
974 } else if (this.drawOffer == "") {
975 // No effect if drawOffer == "sent"
976 if (this.game.mycolor != this.vr.turn) {
977 alert(this.st.tr["Draw offer only in your turn"]);
980 if (!confirm(this.st.tr["Offer draw?"])) return;
981 this.drawOffer = "sent";
982 this.send("drawoffer");
983 if (this.game.type == "live") {
986 { drawOffer: this.game.mycolor }
988 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
991 addAndGotoLiveGame: function(gameInfo, callback) {
992 const game = Object.assign(
996 // (other) Game infos: constant
997 fenStart: gameInfo.fen,
998 vname: this.game.vname,
1000 // Game state (including FEN): will be updated
1002 clocks: [-1, -1], //-1 = unstarted
1006 GameStorage.add(game, (err) => {
1007 // No error expected.
1009 if (this.st.settings.sound)
1010 new Audio("/sounds/newgame.flac").play().catch(() => {});
1011 if (!!callback) callback();
1012 this.$router.push("/game/" + gameInfo.id);
1016 clickRematch: function() {
1017 if (!this.game.mycolor || this.game.type == "import") return;
1018 if (this.rematchOffer == "received") {
1019 // Start a new game!
1021 id: getRandString(), //ignored if corr
1022 fen: V.GenRandInitFen(this.game.randomness),
1023 players: this.game.players.reverse(),
1025 cadence: this.game.cadence
1027 const notifyNewGame = () => {
1028 const oppsid = this.getOppsid(); //may be null
1029 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1030 // To main Hall if corr game:
1031 if (this.game.type == "corr")
1032 this.send("newgame", { data: gameInfo, page: "/" });
1033 // Also to MyGames page:
1034 this.notifyMyGames("newgame", gameInfo);
1036 if (this.game.type == "live")
1037 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1044 // cid is useful to delete the challenge:
1045 data: { gameInfo: gameInfo },
1046 success: (response) => {
1047 gameInfo.id = response.gameId;
1049 this.$router.push("/game/" + response.gameId);
1054 } else if (this.rematchOffer == "") {
1055 this.rematchOffer = "sent";
1056 this.send("rematchoffer", { data: true });
1057 if (this.game.type == "live") {
1060 { rematchOffer: this.game.mycolor }
1062 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1063 } else if (this.rematchOffer == "sent") {
1064 // Toggle rematch offer (on --> off)
1065 this.rematchOffer = "";
1066 this.send("rematchoffer", { data: false });
1067 if (this.game.type == "live") {
1070 { rematchOffer: '' }
1072 } else this.updateCorrGame({ rematchOffer: 'n' });
1075 abortGame: function() {
1076 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1078 this.gameOver("?", "Stop");
1081 resign: function() {
1082 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1084 this.send("resign", { data: this.game.mycolor });
1085 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1086 const side = (this.game.mycolor == "w" ? "White" : "Black");
1087 this.gameOver(score, side + " surrender");
1089 loadGame: function(game, callback) {
1090 const gtype = game.type || this.getGameType(game);
1091 const tc = extractTime(game.cadence);
1092 const myIdx = game.players.findIndex(p => {
1093 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1095 // Sometimes the name isn't stored yet (TODO: why?)
1099 !game.players[myIdx].name &&
1102 game.players[myIdx].name = this.st.user.name;
1105 { playerName: { idx: myIdx, name: this.st.user.name } }
1108 // "mycolor" is undefined for observers
1109 const mycolor = [undefined, "w", "b"][myIdx + 1];
1110 if (gtype == "corr") {
1111 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1112 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1113 // NOTE: clocks in seconds
1114 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1115 game.clocks = [tc.mainTime, tc.mainTime];
1116 const L = game.moves.length;
1117 if (game.score == "*") {
1120 game.clocks[L % 2] -=
1121 (Date.now() - game.moves[L-1].played) / 1000;
1124 // Now that we used idx and played, re-format moves as for live games
1125 game.moves = game.moves.map(m => m.squares);
1127 else if (gtype == "live") {
1128 if (game.clocks[0] < 0) {
1129 // Game is unstarted. clock is ignored until move 2
1130 game.clocks = [tc.mainTime, tc.mainTime];
1132 // I play in this live game
1135 { clocks: game.clocks }
1140 // It's my turn: clocks not updated yet
1141 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1145 // gtype == "import"
1146 game.clocks = [tc.mainTime, tc.mainTime];
1147 // Live games before 26/03/2020 don't have chat history:
1148 if (!game.chats) game.chats = []; //TODO: remove line
1149 // Sort chat messages from newest to oldest
1150 game.chats.sort((c1, c2) => c2.added - c1.added);
1153 game.chats.length > 0 &&
1154 (!game.chatRead || game.chatRead < game.chats[0].added)
1156 // A chat message arrived since my last reading:
1157 document.getElementById("chatBtn").classList.add("somethingnew");
1159 // TODO: merge next 2 "if" conditions
1160 if (!!game.drawOffer) {
1161 if (game.drawOffer == "t")
1162 // Three repetitions
1163 this.drawOffer = "threerep";
1165 // Draw offered by any of the players:
1166 if (myIdx < 0) this.drawOffer = "received";
1168 // I play in this game:
1170 (game.drawOffer == "w" && myIdx == 0) ||
1171 (game.drawOffer == "b" && myIdx == 1)
1173 this.drawOffer = "sent";
1174 else this.drawOffer = "received";
1178 if (!!game.rematchOffer) {
1179 if (myIdx < 0) this.rematchOffer = "received";
1181 // I play in this game:
1183 (game.rematchOffer == "w" && myIdx == 0) ||
1184 (game.rematchOffer == "b" && myIdx == 1)
1186 this.rematchOffer = "sent";
1187 else this.rematchOffer = "received";
1190 this.repeat = {}; //reset: scan past moves' FEN:
1192 this.vr = new V(game.fenStart);
1194 game.moves.forEach(m => {
1195 playMove(m, this.vr);
1196 const fenIdx = this.vr.getFenForRepeat();
1197 this.repeat[fenIdx] = this.repeat[fenIdx]
1198 ? this.repeat[fenIdx] + 1
1201 // Imported games don't have current FEN
1202 if (!game.fen) game.fen = this.vr.getFen();
1203 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1204 this.game = Object.assign(
1205 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1208 increment: tc.increment,
1210 // opponent sid not strictly required (or available), but easier
1211 // at least oppsid or oppid is available anyway:
1212 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1213 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1217 this.$refs["basegame"].re_setVariables(this.game);
1218 if (!this.gameIsLoading) {
1220 this.gotMoveIdx = game.moves.length - 1;
1221 // If we arrive here after 'nextGame' action, the board might be hidden
1222 let boardDiv = document.querySelector(".game");
1223 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1224 boardDiv.style.visibility = "visible";
1226 this.re_setClocks();
1227 this.$nextTick(() => {
1228 this.game.rendered = true;
1229 // Did lastate arrive before game was rendered?
1230 if (this.lastate) this.processLastate();
1232 if (this.lastateAsked) {
1233 this.lastateAsked = false;
1234 this.sendLastate(game.oppsid);
1236 if (this.gameIsLoading) {
1237 this.gameIsLoading = false;
1238 if (this.gotMoveIdx >= game.moves.length)
1239 // Some moves arrived meanwhile...
1240 this.askGameAgain();
1242 if (!!callback) callback();
1244 loadVariantThenGame: async function(game, callback) {
1245 await import("@/variants/" + game.vname + ".js")
1246 .then((vModule) => {
1247 window.V = vModule[game.vname + "Rules"];
1248 this.loadGame(game, callback);
1250 // (AJAX) Request to get rules content (plain text, HTML)
1253 "raw-loader!@/translations/rules/" +
1255 this.st.lang + ".pug"
1257 // Next two lines fix a weird issue after last update (2019-11)
1258 .replace(/\\n/g, " ")
1259 .replace(/\\"/g, '"')
1260 .replace('module.exports = "', "")
1262 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1264 // 3 cases for loading a game:
1265 // - from indexedDB (running or completed live game I play)
1266 // - from server (one correspondance game I play[ed] or not)
1267 // - from remote peer (one live game I don't play, finished or not)
1268 fetchGame: function(callback) {
1269 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1270 // corr games identifiers are integers
1275 data: { gid: this.gameRef },
1277 res.game.moves.forEach(m => {
1278 m.squares = JSON.parse(m.squares);
1285 else if (!!this.gameRef.match(/^i/))
1286 // Game import (maybe remote)
1287 ImportgameStorage.get(this.gameRef, callback);
1289 // Local live game (or remote)
1290 GameStorage.get(this.gameRef, callback);
1292 re_setClocks: function() {
1293 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1294 if (this.game.moves.length < 2 || this.game.score != "*") {
1295 // 1st move not completed yet, or game over: freeze time
1298 const currentTurn = this.vr.turn;
1299 const currentMovesCount = this.game.moves.length;
1300 const colorIdx = ["w", "b"].indexOf(currentTurn);
1301 this.clockUpdate = setInterval(
1304 this.game.clocks[colorIdx] < 0 ||
1305 this.game.moves.length > currentMovesCount ||
1306 this.game.score != "*"
1308 clearInterval(this.clockUpdate);
1309 this.clockUpdate = null;
1310 if (this.game.clocks[colorIdx] < 0)
1312 currentTurn == "w" ? "0-1" : "1-0",
1319 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1326 // Update variables and storage after a move:
1327 processMove: function(move, data) {
1328 if (this.game.type == "import")
1329 // Shouldn't receive any messages in this mode:
1331 if (!data) data = {};
1332 const moveCol = this.vr.turn;
1333 const colorIdx = ["w", "b"].indexOf(moveCol);
1334 const nextIdx = 1 - colorIdx;
1335 const doProcessMove = () => {
1336 const origMovescount = this.game.moves.length;
1337 // The move is (about to be) played: stop clock
1338 clearInterval(this.clockUpdate);
1339 this.clockUpdate = null;
1340 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1341 if (this.drawOffer == "received")
1343 this.drawOffer = "";
1344 if (this.game.type == "live" && origMovescount >= 2) {
1345 this.game.clocks[colorIdx] += this.game.increment;
1346 // For a correct display in casqe of disconnected opponent:
1350 ppt(this.game.clocks[colorIdx]).split(':')
1352 GameStorage.update(this.gameRef, {
1353 // It's not my turn anymore:
1358 // Update current game object:
1359 playMove(move, this.vr);
1361 // Received move, score is computed in BaseGame, but maybe not yet.
1362 // ==> Compute it here, although this is redundant (TODO)
1363 data.score = this.vr.getCurrentScore();
1364 if (data.score != "*") this.gameOver(data.score);
1365 this.game.moves.push(move);
1366 this.game.fen = this.vr.getFen();
1367 if (this.game.type == "corr") {
1368 // In corr games, just reset clock to mainTime:
1369 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1371 // If repetition detected, consider that a draw offer was received:
1372 const fenObj = this.vr.getFenForRepeat();
1373 this.repeat[fenObj] =
1374 !!this.repeat[fenObj]
1375 ? this.repeat[fenObj] + 1
1377 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1378 else if (this.drawOffer == "threerep") this.drawOffer = "";
1379 if (!!this.game.mycolor && !data.receiveMyMove) {
1380 // NOTE: 'var' to see that variable outside this block
1381 var filtered_move = getFilteredMove(move);
1383 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1384 // Notify turn on MyGames page:
1393 // Since corr games are stored at only one location, update should be
1394 // done only by one player for each move:
1396 this.game.type == "live" &&
1397 !!this.game.mycolor &&
1398 moveCol != this.game.mycolor &&
1399 this.game.moves.length >= 2
1401 // Receive a move: update initime
1402 this.game.initime = Date.now();
1403 GameStorage.update(this.gameRef, {
1404 // It's my turn now!
1405 initime: this.game.initime
1409 !!this.game.mycolor &&
1410 !data.receiveMyMove &&
1411 (this.game.type == "live" || moveCol == this.game.mycolor)
1414 switch (this.drawOffer) {
1419 drawCode = this.game.mycolor;
1422 drawCode = V.GetOppCol(this.game.mycolor);
1425 if (this.game.type == "corr") {
1426 // corr: only move, fen and score
1427 this.updateCorrGame({
1430 squares: filtered_move,
1433 // Code "n" for "None" to force reset (otherwise it's ignored)
1434 drawOffer: drawCode || "n"
1438 const updateStorage = () => {
1439 GameStorage.update(this.gameRef, {
1441 move: filtered_move,
1442 moveIdx: origMovescount,
1443 clocks: this.game.clocks,
1447 // The active tab can update storage immediately
1448 if (this.focus) updateStorage();
1449 // Small random delay otherwise
1450 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1453 // Send move ("newmove" event) to people in the room (if our turn)
1454 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1456 move: filtered_move,
1457 index: origMovescount,
1458 // color is required to check if this is my move
1459 // (if several tabs opened)
1461 cancelDrawOffer: this.drawOffer == ""
1463 if (this.game.type == "live")
1464 sendMove["clock"] = this.game.clocks[colorIdx];
1465 // (Live) Clocks will re-start when the opponent pingback arrive
1466 this.opponentGotMove = false;
1467 this.send("newmove", {data: sendMove});
1468 // If the opponent doesn't reply gotmove soon enough, re-send move:
1469 // Do this at most 2 times, because mpore would mean network issues,
1470 // opponent would then be expected to disconnect/reconnect.
1472 const currentUrl = document.location.href;
1473 this.retrySendmove = setInterval(
1477 this.opponentGotMove ||
1478 document.location.href != currentUrl //page change
1480 clearInterval(this.retrySendmove);
1483 const oppsid = this.getOppsid();
1485 // Opponent is disconnected: he'll ask last state
1486 clearInterval(this.retrySendmove);
1488 this.send("newmove", { data: sendMove, target: oppsid });
1496 // Not my move or I'm an observer: just start other player's clock
1497 this.re_setClocks();
1500 this.game.type == "corr" &&
1501 moveCol == this.game.mycolor &&
1504 let boardDiv = document.querySelector(".game");
1505 const afterSetScore = () => {
1507 if (this.st.settings.gotonext && this.nextIds.length > 0)
1508 this.showNextGame();
1510 // The board might have been hidden:
1511 if (boardDiv.style.visibility == "hidden")
1512 boardDiv.style.visibility = "visible";
1513 if (data.score == "*") this.re_setClocks();
1516 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1517 // We may play several moves in a row: in case of, remove listener:
1518 let elClone = el.cloneNode(true);
1519 el.parentNode.replaceChild(elClone, el);
1520 elClone.addEventListener(
1523 document.getElementById("modalConfirm").checked = false;
1524 if (!!data.score && data.score != "*")
1526 this.gameOver(data.score, null, afterSetScore);
1527 else afterSetScore();
1530 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1531 const arMove = (Array.isArray(move) ? move : [move]);
1532 for (let i = 0; i < arMove.length; i++)
1533 V.PlayOnBoard(this.vr.board, arMove[i]);
1534 const position = this.vr.getBaseFen();
1535 for (let i = arMove.length - 1; i >= 0; i--)
1536 V.UndoOnBoard(this.vr.board, arMove[i]);
1537 if (["all","byrow"].includes(V.ShowMoves)) {
1538 this.curDiag = getDiagram({
1540 orientation: V.CanFlip ? this.game.mycolor : "w"
1542 document.querySelector("#confirmDiv > .card").style.width =
1543 boardDiv.offsetWidth + "px";
1545 // Incomplete information: just ask confirmation
1546 // Hide the board, because otherwise it could reveal infos
1547 boardDiv.style.visibility = "hidden";
1548 this.moveNotation = getFullNotation(move);
1550 document.getElementById("modalConfirm").checked = true;
1554 if (!!data.score && data.score != "*")
1555 this.gameOver(data.score, null, doProcessMove);
1556 else doProcessMove();
1559 cancelMove: function() {
1560 let boardDiv = document.querySelector(".game");
1561 if (boardDiv.style.visibility == "hidden")
1562 boardDiv.style.visibility = "visible";
1563 document.getElementById("modalConfirm").checked = false;
1564 this.$refs["basegame"].cancelLastMove();
1566 // In corr games, callback to change page only after score is set:
1567 gameOver: function(score, scoreMsg, callback) {
1568 this.game.score = score;
1569 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1570 this.game.scoreMsg = scoreMsg;
1571 document.getElementById("modalRules").checked = false;
1572 // Display result in a un-missable way:
1573 document.getElementById("modalScore").checked = true;
1574 this.$set(this.game, "scoreMsg", scoreMsg);
1575 const myIdx = this.game.players.findIndex(p => {
1576 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1579 // OK, I play in this game
1584 if (this.game.type == "live") {
1585 GameStorage.update(this.gameRef, scoreObj);
1586 // Notify myself locally if I'm elsewhere:
1590 { body: score + " : " + scoreMsg }
1593 if (!!callback) callback();
1595 else this.updateCorrGame(scoreObj, callback);
1596 // Notify the score to main Hall.
1597 // TODO: only one player (currently double send)
1598 this.send("result", { gid: this.game.id, score: score });
1599 // Also to MyGames page (TODO: doubled as well...)
1608 else if (!!callback) callback();
1614 <style lang="sass" scoped>
1615 #scoreDiv > .card, #rematchDiv > .card
1623 @media screen and (max-width: 1500px)
1625 @media screen and (max-width: 1024px)
1627 @media screen and (max-width: 767px)
1637 background-color: lightgreen
1649 @media screen and (max-width: 767px)
1654 display: inline-block
1658 display: inline-block
1660 display: inline-flex
1664 @media screen and (max-width: 767px)
1678 background-color: #edda99
1680 display: inline-block
1684 display: inline-block
1691 @media screen and (max-width: 767px)
1697 @media screen and (max-width: 767px)
1699 display: inline-block
1712 animation: blink-animation 2s steps(3, start) infinite
1713 @keyframes blink-animation
1718 display: inline-block
1730 .draw-sent, .draw-sent:hover
1731 background-color: lightyellow
1733 .draw-received, .draw-received:hover
1734 background-color: lightgreen
1736 .draw-threerep, .draw-threerep:hover
1737 background-color: #e4d1fc
1739 .rematch-sent, .rematch-sent:hover
1740 background-color: lightyellow
1742 .rematch-received, .rematch-received:hover
1743 background-color: lightgreen
1746 background-color: #c5fefe
1759 background-color: lightgreen
1761 background-color: red
1763 h4#variantNameInGame
1766 text-decoration: underline
1771 @import "@/styles/_rules.sass"
1772 @import "@/styles/_board_squares_img.sass"