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"] }}
87 button#chatBtn.tooltip(
88 onClick="window.doClick('modalChat')"
91 img(src="/images/icons/chat.svg")
92 #actions(v-if="game.score=='*'")
95 :class="{['draw-' + drawOffer]: true}"
96 :aria-label="st.tr['Draw']"
98 img(src="/images/icons/draw.svg")
100 v-if="!!game.mycolor"
102 :aria-label="st.tr['Abort']"
104 img(src="/images/icons/abort.svg")
106 v-if="!!game.mycolor"
108 :aria-label="st.tr['Resign']"
110 img(src="/images/icons/resign.svg")
113 @click="clickRematch()"
114 :class="{['rematch-' + rematchOffer]: true}"
115 :aria-label="st.tr['Rematch']"
117 img(src="/images/icons/rematch.svg")
119 p(v-if="isLargeScreen()")
120 span.name(:class="{connected: isConnected(0)}")
121 | {{ game.players[0].name || "@nonymous" }}
123 v-if="game.score=='*'"
124 :class="{yourturn: !!vr && vr.turn == 'w'}"
126 span.time-left {{ virtualClocks[0][0] }}
127 span.time-separator(v-if="!!virtualClocks[0][1]") :
128 span.time-right(v-if="!!virtualClocks[0][1]")
129 | {{ virtualClocks[0][1] }}
131 span.name(:class="{connected: isConnected(1)}")
132 | {{ game.players[1].name || "@nonymous" }}
134 v-if="game.score=='*'"
135 :class="{yourturn: !!vr && vr.turn == 'b'}"
137 span.time-left {{ virtualClocks[1][0] }}
138 span.time-separator(v-if="!!virtualClocks[1][1]") :
139 span.time-right(v-if="!!virtualClocks[1][1]")
140 | {{ virtualClocks[1][1] }}
142 span.name(:class="{connected: isConnected(0)}")
143 | {{ game.players[0].name || "@nonymous" }}
145 span.name(:class="{connected: isConnected(1)}")
146 | {{ game.players[1].name || "@nonymous" }}
149 v-if="game.score=='*'"
150 :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] }}
158 v-if="game.score=='*'"
159 :class="{yourturn: !!vr && vr.turn == 'b'}"
161 span.time-left {{ virtualClocks[1][0] }}
162 span.time-separator(v-if="!!virtualClocks[1][1]") :
163 span.time-right(v-if="!!virtualClocks[1][1]")
164 | {{ virtualClocks[1][1] }}
168 @newmove="processMove"
173 import BaseGame from "@/components/BaseGame.vue";
174 import Chat from "@/components/Chat.vue";
175 import { store } from "@/store";
176 import { GameStorage } from "@/utils/gameStorage";
177 import { ImportgameStorage } from "@/utils/importgameStorage";
178 import { ppt } from "@/utils/datetime";
179 import { notify } from "@/utils/notifications";
180 import { ajax } from "@/utils/ajax";
181 import { extractTime } from "@/utils/timeControl";
182 import { getRandString } from "@/utils/alea";
183 import { getScoreMessage } from "@/utils/scoring";
184 import { getFullNotation } from "@/utils/notation";
185 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
186 import { processModalClick } from "@/utils/modalClick";
187 import { playMove, getFilteredMove } from "@/utils/playUndo";
188 import { ArrayFun } from "@/utils/array";
189 import params from "@/parameters";
199 // gameRef can point to a corr game, local game or remote live game
202 game: {}, //passed to BaseGame
203 focus: !document.hidden, //will not always work... TODO
204 // virtualClocks will be initialized from true game.clocks
206 vr: null, //"variant rules" object initialized from FEN
212 people: {}, //players + observers
213 lastate: undefined, //used if opponent send lastate before game is ready
214 repeat: {}, //detect position repetition
215 curDiag: "", //for corr moves confirmation
217 roomInitialized: false,
218 // If newmove has wrong index: ask fullgame again:
220 gameIsLoading: false,
221 // If asklastate got no reply, ask again:
223 gotMoveIdx: -1, //last move index received
224 // If newmove got no pingback, send again:
225 opponentGotMove: false,
227 socketCloseListener: 0,
228 // Incomplete info games: show move played
230 // Intervals from setInterval():
234 // Related to (killing of) self multi-connects:
239 $route: function(to, from) {
240 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
242 this.cleanBeforeDestroy();
243 else if (from.params["id"] != to.params["id"]) {
244 // Change everything:
245 this.cleanBeforeDestroy();
246 let boardDiv = document.querySelector(".game");
248 // In case of incomplete information variant:
249 boardDiv.style.visibility = "hidden";
253 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
256 // NOTE: some redundant code with Hall.vue (mostly related to people array)
257 created: function() {
260 mounted: function() {
261 document.getElementById("chatWrap")
262 .addEventListener("click", (e) => {
263 processModalClick(e, () => {
264 this.toggleChat("close")
267 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
269 document.getElementById(eltName)
270 .addEventListener("click", processModalClick);
273 if ("ontouchstart" in window) {
274 // Disable tooltips on smartphones:
275 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
276 elt.classList.remove("tooltip");
280 beforeDestroy: function() {
281 this.cleanBeforeDestroy();
284 cleanBeforeDestroy: function() {
285 clearInterval(this.socketCloseListener);
286 document.removeEventListener('visibilitychange', this.visibilityChange);
287 window.removeEventListener('focus', this.onFocus);
288 window.removeEventListener('blur', this.onBlur);
289 if (!!this.askLastate) clearInterval(this.askLastate);
290 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
291 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
292 this.conn.removeEventListener("message", this.socketMessageListener);
293 this.send("disconnect");
296 visibilityChange: function() {
297 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
298 this.focus = (document.visibilityState == "visible");
299 if (!this.focus && !!this.rematchOffer) {
300 this.rematchOffer = "";
301 this.send("rematchoffer", { data: false });
302 // Do not remove rematch offer from (local) storage
304 this.send(this.focus ? "getfocus" : "losefocus");
306 onFocus: function() {
308 this.send("getfocus");
312 if (!!this.rematchOffer) {
313 this.rematchOffer = "";
314 this.send("rematchoffer", { data: false });
316 this.send("losefocus");
318 isLargeScreen: function() {
319 return window.innerWidth >= 500;
321 gotoRules: function() {
322 this.$router.push("/variants/" + this.game.vname);
324 participateInChat: function(p) {
325 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
327 someAnonymousPresent: function() {
329 Object.values(this.people).some(p =>
330 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
334 atCreation: function() {
335 document.addEventListener('visibilitychange', this.visibilityChange);
336 window.addEventListener('focus', this.onFocus);
337 window.addEventListener('blur', this.onBlur);
338 // 0] (Re)Set variables
339 this.gameRef = this.$route.params["id"];
340 // next = next corr games IDs to navigate faster (if applicable)
341 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
342 // Always add myself to players' list
343 const my = this.st.user;
344 const tmpId = getRandString();
352 tmpId: { focus: true }
357 players: [{ name: "" }, { name: "" }],
361 let chatComp = this.$refs["chatcomp"];
362 if (!!chatComp) chatComp.chats = [];
363 this.virtualClocks = [[0,0], [0,0]];
365 this.rulesContent = "";
367 this.lastateAsked = false;
368 this.rematchOffer = "";
369 this.lastate = undefined;
370 this.roomInitialized = false;
371 this.askGameTime = 0;
372 this.gameIsLoading = 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 =
383 "/?sid=" + this.st.user.sid +
384 "&id=" + this.st.user.id +
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(
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);
402 // Socket init required before loading remote game:
403 const socketInit = callback => {
404 if (this.conn.readyState == 1)
408 // Socket not ready yet (initial loading)
409 // NOTE: first arg is Websocket object, unused here:
410 this.conn.onopen = () => callback();
412 this.fetchGame((game) => {
414 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
416 // Live game stored remotely: need socket to retrieve it
417 // NOTE: the callback "roomInit" will be lost, so it's not provided.
418 // --> It will be given when receiving "fullgame" socket event.
419 socketInit(() => { this.send("askfullgame"); });
422 roomInit: function() {
423 if (!this.roomInitialized) {
424 // Notify the room only now that I connected, because
425 // messages might be lost otherwise (if game loading is slow)
426 this.send("connect");
427 this.send("pollclients");
428 // We may ask fullgame several times if some moves are lost,
429 // but room should be init only once:
430 this.roomInitialized = true;
433 send: function(code, obj) {
434 if (!!this.conn && this.conn.readyState == 1)
435 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
437 isConnected: function(index) {
438 const player = this.game.players[index];
439 // Is it me ? In this case no need to bother with focus
440 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
441 // Still have to check for name (because of potential multi-accounts
442 // on same browser, although this should be rare...)
443 return (!this.st.user.name || this.st.user.name == player.name);
444 // Try to find a match in people:
448 Object.keys(this.people).some(sid => {
451 Object.values(this.people[sid].tmpIds).some(v => v.focus)
458 Object.values(this.people).some(p => {
461 Object.values(p.tmpIds).some(v => v.focus)
467 getOppsid: function() {
468 let oppsid = this.game.oppsid;
470 oppsid = Object.keys(this.people).find(
471 sid => this.people[sid].id == this.game.oppid
474 // oppsid is useful only if opponent is online:
475 if (!!oppsid && !!this.people[oppsid]) return oppsid;
478 // NOTE: action if provided is always a closing action
479 toggleChat: function(action) {
480 if (!action && document.getElementById("modalChat").checked)
482 document.getElementById("inputChat").focus();
484 document.getElementById("chatBtn").classList.remove("somethingnew");
485 if (!!this.game.mycolor) {
486 // Update "chatRead" variable either on server or locally
487 if (this.game.type == "corr")
488 this.updateCorrGame({ chatRead: this.game.mycolor });
489 else if (this.game.type == "live")
490 GameStorage.update(this.gameRef, { chatRead: true });
494 processChat: function(chat) {
495 this.send("newchat", { data: chat });
496 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
497 if (!!this.game.mycolor) {
498 if (this.game.type == "corr")
499 this.updateCorrGame({ chat: chat });
502 chat.added = Date.now();
503 GameStorage.update(this.gameRef, { chat: chat });
507 clearChat: function() {
508 if (!!this.game.mycolor) {
509 if (this.game.type == "corr") {
513 { data: { gid: this.game.id } }
517 GameStorage.update(this.gameRef, { delchat: true });
519 this.$set(this.game, "chats", []);
522 getGameType: function(game) {
523 if (!!game.id.toString().match(/^i/)) return "import";
524 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
526 // Notify something after a new move (to opponent and me on MyGames page)
527 notifyMyGames: function(thing, data) {
532 targets: this.game.players.map(p => {
533 return { sid: p.sid, id: p.id };
538 showNextGame: function() {
539 // Did I play in current game? If not, add it to nextIds list
540 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
541 this.nextIds.unshift(this.game.id);
542 const nextGid = this.nextIds.pop();
544 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
546 askGameAgain: function() {
547 this.gameIsLoading = true;
548 const currentUrl = document.location.href;
549 const doAskGame = () => {
550 if (document.location.href != currentUrl) return; //page change
551 this.fetchGame((game) => {
553 // This is my game: just reload.
556 // Just ask fullgame again (once!), this is much simpler.
557 // If this fails, the user could just reload page :/
558 this.send("askfullgame");
561 // Delay of at least 2s between two game requests
562 const now = Date.now();
563 const delay = Math.max(2000 - (now - this.askGameTime), 0);
564 this.askGameTime = now;
565 setTimeout(doAskGame, delay);
567 socketMessageListener: function(msg) {
568 if (!this.conn) return;
569 const data = JSON.parse(msg.data);
572 // TODO: shuffling and random filtering on server,
573 // if the room is really crowded.
574 Object.keys(data.sockIds).forEach(sid => {
575 if (sid != this.st.user.sid) {
576 this.send("askidentity", { target: sid });
577 this.people[sid] = { tmpIds: data.sockIds[sid] };
580 // Complete my tmpIds:
581 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
586 if (!this.people[data.from[0]]) {
587 // focus depends on the tmpId (e.g. tab)
593 [data.from[1]]: { focus: true }
597 // For self multi-connects tests:
598 this.newConnect[data.from[0]] = true;
599 this.send("askidentity", { target: data.from[0] });
601 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
602 this.$forceUpdate(); //TODO: shouldn't be required
606 if (!this.people[data.from[0]]) return;
607 delete this.people[data.from[0]].tmpIds[data.from[1]];
608 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
609 this.$delete(this.people, data.from[0]);
610 else this.$forceUpdate(); //TODO: shouldn't be required
613 let player = this.people[data.from[0]];
615 player.tmpIds[data.from[1]].focus = true;
616 this.$forceUpdate(); //TODO: shouldn't be required
621 let player = this.people[data.from[0]];
623 player.tmpIds[data.from[1]].focus = false;
624 this.$forceUpdate(); //TODO: shouldn't be required
628 case "askidentity": {
629 // Request for identification
631 // Decompose to avoid revealing email
632 name: this.st.user.name,
633 sid: this.st.user.sid,
636 this.send("identity", { data: me, target: data.from });
640 const user = data.data;
641 let player = this.people[user.sid];
642 // player.tmpIds is already set
643 player.name = user.name;
645 if (this.game.type == "live") {
647 this.game.players.findIndex(p => p.sid == this.st.user.sid);
648 // Sometimes a player name isn't stored yet (TODO: why?)
651 !this.game.players[1 - myGidx].name &&
652 this.game.players[1 - myGidx].sid == user.sid &&
655 this.game.players[1-myGidx].name = user.name;
658 { playerName: { idx: 1 - myGidx, name: user.name } }
662 this.$forceUpdate(); //TODO: shouldn't be required
663 // If I multi-connect, kill current connexion if no mark (I'm older)
664 if (this.newConnect[user.sid]) {
665 delete this.newConnect[user.sid];
668 user.id == this.st.user.id &&
669 user.sid != this.st.user.sid
671 this.cleanBeforeDestroy();
672 alert(this.st.tr["New connexion detected: tab now offline"]);
676 // Ask potentially missed last state, if opponent and I play
679 !!this.game.mycolor &&
680 this.game.type == "live" &&
681 this.game.score == "*" &&
682 this.game.players.some(p => p.sid == user.sid)
684 this.send("asklastate", { target: user.sid });
686 this.askLastate = setInterval(
688 // Ask at most 3 times:
689 // if no reply after that there should be a network issue.
693 !!this.people[user.sid]
695 this.send("asklastate", { target: user.sid });
698 clearInterval(this.askLastate);
707 // Send current (live or import) game,
708 // if not asked by any of the players
710 this.game.type != "corr" &&
711 this.game.players.every(p => p.sid != data.from[0])
715 // FEN is current position, unused for now
717 players: this.game.players,
719 cadence: this.game.cadence,
720 score: this.game.score
722 this.send("game", { data: myGame, target: data.from });
726 const gameToSend = Object.keys(this.game)
729 "id","fen","players","vid","cadence","fenStart","vname",
730 "moves","clocks","score","drawOffer","rematchOffer"
734 obj[k] = this.game[k];
739 this.send("fullgame", { data: gameToSend, target: data.from });
742 if (!!data.data.empty) {
743 alert(this.st.tr["The game should be in another tab"]);
747 // Callback "roomInit" to poll clients only after game is loaded
748 this.loadVariantThenGame(data.data, this.roomInit);
751 // Sending informative last state if I played a move or score != "*"
752 // If the game or moves aren't loaded yet, delay the sending:
753 // TODO: socket init after game load, so the game is supposedly ready
754 if (!this.game || !this.game.moves) this.lastateAsked = true;
755 else this.sendLastate(data.from);
758 // Got opponent infos about last move
759 this.gotLastate = true;
760 this.lastate = data.data;
761 if (this.game.rendered)
762 // Game is rendered (Board component)
763 this.processLastate();
764 // Else: will be processed when game is ready
768 const movePlus = data.data;
769 const movesCount = this.game.moves.length;
770 if (movePlus.index > movesCount) {
771 // This can only happen if I'm an observer and missed a move.
772 if (this.gotMoveIdx < movePlus.index)
773 this.gotMoveIdx = movePlus.index;
774 if (!this.gameIsLoading) this.askGameAgain();
778 movePlus.index < movesCount ||
779 this.gotMoveIdx >= movePlus.index
781 // Opponent re-send but we already have the move:
782 // (maybe he didn't receive our pingback...)
783 this.send("gotmove", {data: movePlus.index, target: data.from});
785 this.gotMoveIdx = movePlus.index;
786 const receiveMyMove = (movePlus.color == this.game.mycolor);
787 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
788 if (!receiveMyMove && !!this.game.mycolor) {
789 // Notify opponent that I got the move:
792 { data: movePlus.index, target: data.from }
794 // And myself if I'm elsewhere:
800 (this.game.players[moveColIdx].name || "@nonymous") +
806 if (movePlus.cancelDrawOffer) {
807 // Opponent refuses draw
809 // NOTE for corr games: drawOffer reset by player in turn
811 this.game.type == "live" &&
812 !!this.game.mycolor &&
815 GameStorage.update(this.gameRef, { drawOffer: "" });
818 this.$refs["basegame"].play(
819 movePlus.move, "received", null, true);
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("modalRematch").checked = true;
891 let chat = data.data;
892 this.$refs["chatcomp"].newChat(chat);
893 if (this.game.type == "live") {
894 chat.added = Date.now();
895 if (!!this.game.mycolor)
896 GameStorage.update(this.gameRef, { chat: chat });
898 if (!document.getElementById("modalChat").checked)
899 document.getElementById("chatBtn").classList.add("somethingnew");
904 updateCorrGame: function(obj, callback) {
914 if (!!callback) callback();
919 sendLastate: function(target) {
920 // Send our "last state" informations to opponent
921 const L = this.game.moves.length;
922 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
925 (L > 0 && this.vr.turn != this.game.mycolor)
926 ? this.game.moves[L - 1]
928 clock: this.game.clocks[myIdx],
929 // Since we played a move (or abort or resign),
930 // only drawOffer=="sent" is possible
931 drawSent: this.drawOffer == "sent",
932 rematchSent: this.rematchOffer == "sent",
933 score: this.game.score != "*" ? this.game.score : undefined,
934 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
937 this.send("lastate", { data: myLastate, target: target });
939 // lastate was received, but maybe game wasn't ready yet:
940 processLastate: function() {
941 const data = this.lastate;
942 this.lastate = undefined; //security...
943 const L = this.game.moves.length;
944 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
945 this.game.clocks[oppIdx] = data.clock;
946 if (data.movesCount > L) {
947 // Just got last move from him
948 this.$refs["basegame"].play(data.lastMove, "received", null, true);
949 this.processMove(data.lastMove);
951 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
954 if (data.drawSent) this.drawOffer = "received";
955 if (data.rematchSent) this.rematchOffer = "received";
958 if (this.game.score == "*")
959 this.gameOver(data.score, data.scoreMsg);
962 clickDraw: function() {
963 if (!this.game.mycolor || this.game.type == "import") return;
964 if (["received", "threerep"].includes(this.drawOffer)) {
965 if (!confirm(this.st.tr["Accept draw?"])) return;
967 this.drawOffer == "received"
969 : "Three repetitions";
970 this.send("draw", { data: message });
971 this.gameOver("1/2", message);
972 } else if (this.drawOffer == "") {
973 // No effect if drawOffer == "sent"
974 if (this.game.mycolor != this.vr.turn) {
975 alert(this.st.tr["Draw offer only in your turn"]);
978 if (!confirm(this.st.tr["Offer draw?"])) return;
979 this.drawOffer = "sent";
980 this.send("drawoffer");
981 if (this.game.type == "live") {
984 { drawOffer: this.game.mycolor }
986 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
989 addAndGotoLiveGame: function(gameInfo, callback) {
990 const game = Object.assign(
994 // (other) Game infos: constant
995 fenStart: gameInfo.fen,
996 vname: this.game.vname,
998 // Game state (including FEN): will be updated
1000 clocks: [-1, -1], //-1 = unstarted
1004 GameStorage.add(game, (err) => {
1005 // No error expected.
1007 if (this.st.settings.sound)
1008 new Audio("/sounds/newgame.flac").play().catch(() => {});
1009 if (!!callback) callback();
1010 this.$router.push("/game/" + gameInfo.id);
1014 clickRematch: function() {
1015 if (!this.game.mycolor || this.game.type == "import") return;
1016 if (this.rematchOffer == "received") {
1017 // Start a new game!
1019 id: getRandString(), //ignored if corr
1020 fen: V.GenRandInitFen(this.game.randomness),
1021 players: this.game.players.reverse(),
1023 cadence: this.game.cadence
1025 const notifyNewGame = () => {
1026 const oppsid = this.getOppsid(); //may be null
1027 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1028 // To main Hall if corr game:
1029 if (this.game.type == "corr")
1030 this.send("newgame", { data: gameInfo, page: "/" });
1031 // Also to MyGames page:
1032 this.notifyMyGames("newgame", gameInfo);
1034 if (this.game.type == "live")
1035 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1042 // cid is useful to delete the challenge:
1043 data: { gameInfo: gameInfo },
1044 success: (response) => {
1045 gameInfo.id = response.gameId;
1047 this.$router.push("/game/" + response.gameId);
1052 } else if (this.rematchOffer == "") {
1053 this.rematchOffer = "sent";
1054 this.send("rematchoffer", { data: true });
1055 if (this.game.type == "live") {
1058 { rematchOffer: this.game.mycolor }
1060 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1061 } else if (this.rematchOffer == "sent") {
1062 // Toggle rematch offer (on --> off)
1063 this.rematchOffer = "";
1064 this.send("rematchoffer", { data: false });
1065 if (this.game.type == "live") {
1068 { rematchOffer: '' }
1070 } else this.updateCorrGame({ rematchOffer: 'n' });
1073 abortGame: function() {
1074 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1076 this.gameOver("?", "Stop");
1079 resign: function() {
1080 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1082 this.send("resign", { data: this.game.mycolor });
1083 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1084 const side = (this.game.mycolor == "w" ? "White" : "Black");
1085 this.gameOver(score, side + " surrender");
1087 loadGame: function(game, callback) {
1088 const gtype = game.type || this.getGameType(game);
1089 const tc = extractTime(game.cadence);
1090 const myIdx = game.players.findIndex(p => {
1091 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1093 // Sometimes the name isn't stored yet (TODO: why?)
1097 !game.players[myIdx].name &&
1100 game.players[myIdx].name = this.st.user.name;
1103 { playerName: { idx: myIdx, name: this.st.user.name } }
1106 // "mycolor" is undefined for observers
1107 const mycolor = [undefined, "w", "b"][myIdx + 1];
1108 if (gtype == "corr") {
1109 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1110 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1111 // NOTE: clocks in seconds
1112 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1113 game.clocks = [tc.mainTime, tc.mainTime];
1114 const L = game.moves.length;
1115 if (game.score == "*") {
1118 game.clocks[L % 2] -=
1119 (Date.now() - game.moves[L-1].played) / 1000;
1122 // Now that we used idx and played, re-format moves as for live games
1123 game.moves = game.moves.map(m => m.squares);
1125 else if (gtype == "live") {
1126 if (game.clocks[0] < 0) {
1127 // Game is unstarted. clock is ignored until move 2
1128 game.clocks = [tc.mainTime, tc.mainTime];
1130 // I play in this live game
1133 { clocks: game.clocks }
1138 // It's my turn: clocks not updated yet
1139 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1143 // gtype == "import"
1144 game.clocks = [tc.mainTime, tc.mainTime];
1145 // Live games before 26/03/2020 don't have chat history:
1146 if (!game.chats) game.chats = []; //TODO: remove line
1147 // Sort chat messages from newest to oldest
1148 game.chats.sort((c1, c2) => c2.added - c1.added);
1151 game.chats.length > 0 &&
1152 (!game.chatRead || game.chatRead < game.chats[0].added)
1154 // A chat message arrived since my last reading:
1155 document.getElementById("chatBtn").classList.add("somethingnew");
1157 // TODO: merge next 2 "if" conditions
1158 if (!!game.drawOffer) {
1159 if (game.drawOffer == "t")
1160 // Three repetitions
1161 this.drawOffer = "threerep";
1163 // Draw offered by any of the players:
1164 if (myIdx < 0) this.drawOffer = "received";
1166 // I play in this game:
1168 (game.drawOffer == "w" && myIdx == 0) ||
1169 (game.drawOffer == "b" && myIdx == 1)
1171 this.drawOffer = "sent";
1172 else this.drawOffer = "received";
1176 if (!!game.rematchOffer) {
1177 if (myIdx < 0) this.rematchOffer = "received";
1179 // I play in this game:
1181 (game.rematchOffer == "w" && myIdx == 0) ||
1182 (game.rematchOffer == "b" && myIdx == 1)
1184 this.rematchOffer = "sent";
1185 else this.rematchOffer = "received";
1188 this.repeat = {}; //reset: scan past moves' FEN:
1190 this.vr = new V(game.fenStart);
1192 game.moves.forEach(m => {
1193 playMove(m, this.vr);
1194 const fenIdx = this.vr.getFenForRepeat();
1195 this.repeat[fenIdx] = this.repeat[fenIdx]
1196 ? this.repeat[fenIdx] + 1
1199 // Imported games don't have current FEN
1200 if (!game.fen) game.fen = this.vr.getFen();
1201 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1202 this.game = Object.assign(
1203 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1206 increment: tc.increment,
1208 // opponent sid not strictly required (or available), but easier
1209 // at least oppsid or oppid is available anyway:
1210 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1211 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1215 this.$refs["basegame"].re_setVariables(this.game);
1216 if (!this.gameIsLoading) {
1218 this.gotMoveIdx = game.moves.length - 1;
1219 // If we arrive here after 'nextGame' action, the board might be hidden
1220 let boardDiv = document.querySelector(".game");
1221 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1222 boardDiv.style.visibility = "visible";
1224 this.re_setClocks();
1225 this.$nextTick(() => {
1226 this.game.rendered = true;
1227 // Did lastate arrive before game was rendered?
1228 if (this.lastate) this.processLastate();
1230 if (this.lastateAsked) {
1231 this.lastateAsked = false;
1232 this.sendLastate(game.oppsid);
1234 if (this.gameIsLoading) {
1235 this.gameIsLoading = false;
1236 if (this.gotMoveIdx >= game.moves.length)
1237 // Some moves arrived meanwhile...
1238 this.askGameAgain();
1240 if (!!callback) callback();
1242 loadVariantThenGame: async function(game, callback) {
1243 await import("@/variants/" + game.vname + ".js")
1244 .then((vModule) => {
1245 window.V = vModule[game.vname + "Rules"];
1246 this.loadGame(game, callback);
1248 // (AJAX) Request to get rules content (plain text, HTML)
1251 "raw-loader!@/translations/rules/" +
1253 this.st.lang + ".pug"
1255 // Next two lines fix a weird issue after last update (2019-11)
1256 .replace(/\\n/g, " ")
1257 .replace(/\\"/g, '"')
1258 .replace('module.exports = "', "")
1260 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1262 // 3 cases for loading a game:
1263 // - from indexedDB (running or completed live game I play)
1264 // - from server (one correspondance game I play[ed] or not)
1265 // - from remote peer (one live game I don't play, finished or not)
1266 fetchGame: function(callback) {
1267 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1268 // corr games identifiers are integers
1273 data: { gid: this.gameRef },
1275 res.game.moves.forEach(m => {
1276 m.squares = JSON.parse(m.squares);
1283 else if (!!this.gameRef.match(/^i/))
1284 // Game import (maybe remote)
1285 ImportgameStorage.get(this.gameRef, callback);
1287 // Local live game (or remote)
1288 GameStorage.get(this.gameRef, callback);
1290 re_setClocks: function() {
1291 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1292 if (this.game.moves.length < 2 || this.game.score != "*") {
1293 // 1st move not completed yet, or game over: freeze time
1296 const currentTurn = this.vr.turn;
1297 const currentMovesCount = this.game.moves.length;
1298 const colorIdx = ["w", "b"].indexOf(currentTurn);
1299 this.clockUpdate = setInterval(
1302 this.game.clocks[colorIdx] < 0 ||
1303 this.game.moves.length > currentMovesCount ||
1304 this.game.score != "*"
1306 clearInterval(this.clockUpdate);
1307 this.clockUpdate = null;
1308 if (this.game.clocks[colorIdx] < 0)
1310 currentTurn == "w" ? "0-1" : "1-0",
1317 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1324 // Update variables and storage after a move:
1325 processMove: function(move, data) {
1326 if (this.game.type == "import")
1327 // Shouldn't receive any messages in this mode:
1329 if (!data) data = {};
1330 const moveCol = this.vr.turn;
1331 const colorIdx = ["w", "b"].indexOf(moveCol);
1332 const nextIdx = 1 - colorIdx;
1333 const doProcessMove = () => {
1334 const origMovescount = this.game.moves.length;
1335 // The move is (about to be) played: stop clock
1336 clearInterval(this.clockUpdate);
1337 this.clockUpdate = null;
1338 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1339 if (this.drawOffer == "received")
1341 this.drawOffer = "";
1342 if (this.game.type == "live" && origMovescount >= 2) {
1343 this.game.clocks[colorIdx] += this.game.increment;
1344 // For a correct display in casqe of disconnected opponent:
1348 ppt(this.game.clocks[colorIdx]).split(':')
1350 GameStorage.update(this.gameRef, {
1351 // It's not my turn anymore:
1356 // Update current game object:
1357 playMove(move, this.vr);
1359 // Received move, score is computed in BaseGame, but maybe not yet.
1360 // ==> Compute it here, although this is redundant (TODO)
1361 data.score = this.vr.getCurrentScore();
1362 if (data.score != "*") this.gameOver(data.score);
1363 this.game.moves.push(move);
1364 this.game.fen = this.vr.getFen();
1365 if (this.game.type == "corr") {
1366 // In corr games, just reset clock to mainTime:
1367 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1369 // If repetition detected, consider that a draw offer was received:
1370 const fenObj = this.vr.getFenForRepeat();
1371 this.repeat[fenObj] =
1372 !!this.repeat[fenObj]
1373 ? this.repeat[fenObj] + 1
1375 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1376 else if (this.drawOffer == "threerep") this.drawOffer = "";
1377 if (!!this.game.mycolor && !data.receiveMyMove) {
1378 // NOTE: 'var' to see that variable outside this block
1379 var filtered_move = getFilteredMove(move);
1381 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1382 // Notify turn on MyGames page:
1391 // Since corr games are stored at only one location, update should be
1392 // done only by one player for each move:
1394 this.game.type == "live" &&
1395 !!this.game.mycolor &&
1396 moveCol != this.game.mycolor &&
1397 this.game.moves.length >= 2
1399 // Receive a move: update initime
1400 this.game.initime = Date.now();
1401 GameStorage.update(this.gameRef, {
1402 // It's my turn now!
1403 initime: this.game.initime
1407 !!this.game.mycolor &&
1408 !data.receiveMyMove &&
1409 (this.game.type == "live" || moveCol == this.game.mycolor)
1412 switch (this.drawOffer) {
1417 drawCode = this.game.mycolor;
1420 drawCode = V.GetOppCol(this.game.mycolor);
1423 if (this.game.type == "corr") {
1424 // corr: only move, fen and score
1425 this.updateCorrGame({
1428 squares: filtered_move,
1431 // Code "n" for "None" to force reset (otherwise it's ignored)
1432 drawOffer: drawCode || "n"
1436 const updateStorage = () => {
1437 GameStorage.update(this.gameRef, {
1439 move: filtered_move,
1440 moveIdx: origMovescount,
1441 clocks: this.game.clocks,
1445 // The active tab can update storage immediately
1446 if (this.focus) updateStorage();
1447 // Small random delay otherwise
1448 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1451 // Send move ("newmove" event) to people in the room (if our turn)
1452 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1454 move: filtered_move,
1455 index: origMovescount,
1456 // color is required to check if this is my move
1457 // (if several tabs opened)
1459 cancelDrawOffer: this.drawOffer == ""
1461 if (this.game.type == "live")
1462 sendMove["clock"] = this.game.clocks[colorIdx];
1463 // (Live) Clocks will re-start when the opponent pingback arrive
1464 this.opponentGotMove = false;
1465 this.send("newmove", {data: sendMove});
1466 // If the opponent doesn't reply gotmove soon enough, re-send move:
1467 // Do this at most 2 times, because mpore would mean network issues,
1468 // opponent would then be expected to disconnect/reconnect.
1470 const currentUrl = document.location.href;
1471 this.retrySendmove = setInterval(
1475 this.opponentGotMove ||
1476 document.location.href != currentUrl //page change
1478 clearInterval(this.retrySendmove);
1481 const oppsid = this.getOppsid();
1483 // Opponent is disconnected: he'll ask last state
1484 clearInterval(this.retrySendmove);
1486 this.send("newmove", { data: sendMove, target: oppsid });
1494 // Not my move or I'm an observer: just start other player's clock
1495 this.re_setClocks();
1498 this.game.type == "corr" &&
1499 moveCol == this.game.mycolor &&
1502 let boardDiv = document.querySelector(".game");
1503 const afterSetScore = () => {
1505 if (this.st.settings.gotonext && this.nextIds.length > 0)
1506 this.showNextGame();
1508 // The board might have been hidden:
1509 if (boardDiv.style.visibility == "hidden")
1510 boardDiv.style.visibility = "visible";
1511 if (data.score == "*") this.re_setClocks();
1514 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1515 // We may play several moves in a row: in case of, remove listener:
1516 let elClone = el.cloneNode(true);
1517 el.parentNode.replaceChild(elClone, el);
1518 elClone.addEventListener(
1521 document.getElementById("modalConfirm").checked = false;
1522 if (!!data.score && data.score != "*")
1524 this.gameOver(data.score, null, afterSetScore);
1525 else afterSetScore();
1528 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1529 const arMove = (Array.isArray(move) ? move : [move]);
1530 for (let i = 0; i < arMove.length; i++)
1531 V.PlayOnBoard(this.vr.board, arMove[i]);
1532 const position = this.vr.getBaseFen();
1533 for (let i = arMove.length - 1; i >= 0; i--)
1534 V.UndoOnBoard(this.vr.board, arMove[i]);
1535 if (["all","byrow"].includes(V.ShowMoves)) {
1536 this.curDiag = getDiagram({
1538 orientation: V.CanFlip ? this.game.mycolor : "w"
1540 document.querySelector("#confirmDiv > .card").style.width =
1541 boardDiv.offsetWidth + "px";
1543 // Incomplete information: just ask confirmation
1544 // Hide the board, because otherwise it could reveal infos
1545 boardDiv.style.visibility = "hidden";
1546 this.moveNotation = getFullNotation(move);
1548 document.getElementById("modalConfirm").checked = true;
1552 if (!!data.score && data.score != "*")
1553 this.gameOver(data.score, null, doProcessMove);
1554 else doProcessMove();
1557 cancelMove: function() {
1558 let boardDiv = document.querySelector(".game");
1559 if (boardDiv.style.visibility == "hidden")
1560 boardDiv.style.visibility = "visible";
1561 document.getElementById("modalConfirm").checked = false;
1562 this.$refs["basegame"].cancelLastMove();
1564 // In corr games, callback to change page only after score is set:
1565 gameOver: function(score, scoreMsg, callback) {
1566 this.game.score = score;
1567 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1568 this.game.scoreMsg = scoreMsg;
1569 // Display result in a un-missable way:
1570 document.getElementById("modalScore").checked = true;
1571 this.$set(this.game, "scoreMsg", scoreMsg);
1572 const myIdx = this.game.players.findIndex(p => {
1573 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1576 // OK, I play in this game
1581 if (this.game.type == "live") {
1582 GameStorage.update(this.gameRef, scoreObj);
1583 // Notify myself locally if I'm elsewhere:
1587 { body: score + " : " + scoreMsg }
1590 if (!!callback) callback();
1592 else this.updateCorrGame(scoreObj, callback);
1593 // Notify the score to main Hall.
1594 // TODO: only one player (currently double send)
1595 this.send("result", { gid: this.game.id, score: score });
1596 // Also to MyGames page (TODO: doubled as well...)
1605 else if (!!callback) callback();
1611 <style lang="sass" scoped>
1612 #scoreDiv > .card, #rematchDiv > .card
1620 @media screen and (max-width: 1500px)
1622 @media screen and (max-width: 1024px)
1624 @media screen and (max-width: 767px)
1633 background-color: lightgreen
1645 @media screen and (max-width: 767px)
1650 display: inline-block
1654 display: inline-block
1656 display: inline-flex
1660 @media screen and (max-width: 767px)
1674 background-color: #edda99
1676 display: inline-block
1680 display: inline-block
1691 display: inline-block
1704 animation: blink-animation 2s steps(3, start) infinite
1705 @keyframes blink-animation
1710 display: inline-block
1722 .draw-sent, .draw-sent:hover
1723 background-color: lightyellow
1725 .draw-received, .draw-received:hover
1726 background-color: lightgreen
1728 .draw-threerep, .draw-threerep:hover
1729 background-color: #e4d1fc
1731 .rematch-sent, .rematch-sent:hover
1732 background-color: lightyellow
1734 .rematch-received, .rematch-received:hover
1735 background-color: lightgreen
1738 background-color: #c5fefe
1751 background-color: lightgreen
1753 background-color: red
1755 h4#variantNameInGame
1758 text-decoration: underline
1763 @import "@/styles/_rules.sass"
1764 @import "@/styles/_board_squares_img.sass"