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)"
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()")
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 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.gotLastate = false;
372 this.gotMoveIdx = -1;
373 this.opponentGotMove = false;
374 this.askLastate = null;
375 this.retrySendmove = null;
376 this.clockUpdate = null;
377 this.newConnect = {};
378 // 1] Initialize connection
379 this.connexionString =
381 "/?sid=" + this.st.user.sid +
382 "&id=" + this.st.user.id +
385 // Discard potential "/?next=[...]" for page indication:
386 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
387 this.conn = new WebSocket(this.connexionString);
388 this.conn.addEventListener("message", this.socketMessageListener);
389 this.socketCloseListener = setInterval(
391 if (this.conn.readyState == 3) {
392 this.conn.removeEventListener(
393 "message", this.socketMessageListener);
394 this.conn = new WebSocket(this.connexionString);
395 this.conn.addEventListener("message", this.socketMessageListener);
400 // Socket init required before loading remote game:
401 const socketInit = callback => {
402 if (this.conn.readyState == 1)
406 // Socket not ready yet (initial loading)
407 // NOTE: first arg is Websocket object, unused here:
408 this.conn.onopen = () => callback();
410 this.fetchGame((game) => {
412 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
414 // Live game stored remotely: need socket to retrieve it
415 // NOTE: the callback "roomInit" will be lost, so it's not provided.
416 // --> It will be given when receiving "fullgame" socket event.
417 socketInit(() => { this.send("askfullgame"); });
420 roomInit: function() {
421 if (!this.roomInitialized) {
422 // Notify the room only now that I connected, because
423 // messages might be lost otherwise (if game loading is slow)
424 this.send("connect");
425 this.send("pollclients");
426 // We may ask fullgame several times if some moves are lost,
427 // but room should be init only once:
428 this.roomInitialized = true;
431 send: function(code, obj) {
432 if (!!this.conn && this.conn.readyState == 1)
433 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
435 isConnected: function(index) {
436 const player = this.game.players[index];
437 // Is it me ? In this case no need to bother with focus
439 this.st.user.sid == player.sid ||
440 (!!player.name && 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);
446 // Try to find a match in people:
450 Object.keys(this.people).some(sid => {
453 Object.values(this.people[sid].tmpIds).some(v => v.focus)
460 Object.values(this.people).some(p => {
463 Object.values(p.tmpIds).some(v => v.focus)
469 getOppsid: function() {
470 let oppsid = this.game.oppsid;
472 oppsid = Object.keys(this.people).find(
473 sid => this.people[sid].id == this.game.oppid
476 // oppsid is useful only if opponent is online:
477 if (!!oppsid && !!this.people[oppsid]) return oppsid;
480 // NOTE: action if provided is always a closing action
481 toggleChat: function(action) {
482 if (!action && document.getElementById("modalChat").checked)
484 document.getElementById("inputChat").focus();
486 document.getElementById("chatBtn").classList.remove("somethingnew");
487 if (!!this.game.mycolor) {
488 // Update "chatRead" variable either on server or locally
489 if (this.game.type == "corr")
490 this.updateCorrGame({ chatRead: this.game.mycolor });
491 else if (this.game.type == "live")
492 GameStorage.update(this.gameRef, { chatRead: true });
496 processChat: function(chat) {
497 this.send("newchat", { data: chat });
498 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
499 if (!!this.game.mycolor) {
500 if (this.game.type == "corr")
501 this.updateCorrGame({ chat: chat });
504 chat.added = Date.now();
505 GameStorage.update(this.gameRef, { chat: chat });
509 clearChat: function() {
510 if (!!this.game.mycolor) {
511 if (this.game.type == "corr") {
515 { data: { gid: this.game.id } }
519 GameStorage.update(this.gameRef, { delchat: true });
521 this.$set(this.game, "chats", []);
524 getGameType: function(game) {
525 if (!!game.id.toString().match(/^i/)) return "import";
526 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
528 // Notify something after a new move (to opponent and me on MyGames page)
529 notifyMyGames: function(thing, data) {
534 targets: this.game.players.map(p => {
535 return { sid: p.sid, id: p.id };
540 showNextGame: function() {
541 // Did I play in current game? If not, add it to nextIds list
542 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
543 this.nextIds.unshift(this.game.id);
544 const nextGid = this.nextIds.pop();
546 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
548 socketMessageListener: function(msg) {
549 if (!this.conn) return;
550 const data = JSON.parse(msg.data);
553 // TODO: shuffling and random filtering on server,
554 // if the room is really crowded.
555 Object.keys(data.sockIds).forEach(sid => {
556 if (sid != this.st.user.sid) {
557 this.send("askidentity", { target: sid });
558 this.people[sid] = { tmpIds: data.sockIds[sid] };
561 // Complete my tmpIds:
562 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
567 if (!this.people[data.from[0]]) {
568 // focus depends on the tmpId (e.g. tab)
574 [data.from[1]]: { focus: true }
578 // For self multi-connects tests:
579 this.newConnect[data.from[0]] = true;
580 this.send("askidentity", { target: data.from[0] });
582 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
583 this.$forceUpdate(); //TODO: shouldn't be required
587 if (!this.people[data.from[0]]) return;
588 delete this.people[data.from[0]].tmpIds[data.from[1]];
589 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
590 this.$delete(this.people, data.from[0]);
591 else this.$forceUpdate(); //TODO: shouldn't be required
594 let player = this.people[data.from[0]];
596 player.tmpIds[data.from[1]].focus = true;
597 this.$forceUpdate(); //TODO: shouldn't be required
602 let player = this.people[data.from[0]];
604 player.tmpIds[data.from[1]].focus = false;
605 this.$forceUpdate(); //TODO: shouldn't be required
609 case "askidentity": {
610 // Request for identification
612 // Decompose to avoid revealing email
613 name: this.st.user.name,
614 sid: this.st.user.sid,
617 this.send("identity", { data: me, target: data.from });
621 const user = data.data;
622 let player = this.people[user.sid];
623 // player.tmpIds is already set
624 player.name = user.name;
626 if (this.game.type == "live") {
628 this.game.players.findIndex(p => p.sid == this.st.user.sid);
629 // Sometimes a player name isn't stored yet (TODO: why?)
632 !this.game.players[1 - myGidx].name &&
633 this.game.players[1 - myGidx].sid == user.sid &&
636 this.game.players[1-myGidx].name = user.name;
639 { playerName: { idx: 1 - myGidx, name: user.name } }
643 this.$forceUpdate(); //TODO: shouldn't be required
644 // If I multi-connect, kill current connexion if no mark (I'm older)
645 if (this.newConnect[user.sid]) {
646 delete this.newConnect[user.sid];
649 user.id == this.st.user.id &&
650 user.sid != this.st.user.sid
652 this.cleanBeforeDestroy();
653 alert(this.st.tr["New connexion detected: tab now offline"]);
657 // Ask potentially missed last state, if opponent and I play
660 !!this.game.mycolor &&
661 this.game.type == "live" &&
662 this.game.players.some(p => p.sid == user.sid)
664 this.send("asklastate", { target: user.sid });
666 this.askLastate = setInterval(
668 // Ask at most 3 times:
669 // if no reply after that there should be a network issue.
673 !!this.people[user.sid]
675 this.send("asklastate", { target: user.sid });
678 clearInterval(this.askLastate);
687 // Send current (live or import) game,
688 // if not asked by any of the players
690 this.game.type != "corr" &&
691 this.game.players.every(p => p.sid != data.from[0])
695 // FEN is current position, unused for now
697 players: this.game.players,
699 cadence: this.game.cadence,
700 score: this.game.score
702 this.send("game", { data: myGame, target: data.from });
706 const gameToSend = Object.keys(this.game)
709 "id","fen","players","vid","cadence","fenStart","vname",
710 "moves","clocks","score","drawOffer","rematchOffer"
714 obj[k] = this.game[k];
719 this.send("fullgame", { data: gameToSend, target: data.from });
722 if (!!data.data.empty) {
723 alert(this.st.tr["The game should be in another tab"]);
727 // Callback "roomInit" to poll clients only after game is loaded
728 this.loadVariantThenGame(data.data, this.roomInit);
731 // Sending informative last state if I played a move or score != "*"
732 // If the game or moves aren't loaded yet, delay the sending:
733 // TODO: socket init after game load, so the game is supposedly ready
734 if (!this.game || !this.game.moves) this.lastateAsked = true;
735 else this.sendLastate(data.from);
737 // TODO: possible bad scenario: reload page while oppponent sends a
738 // move => get both lastate and newmove, process both, add move twice.
739 // Confirm scenario? Fix?
741 // Got opponent infos about last move
742 this.gotLastate = true;
743 this.lastate = data.data;
744 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
745 this.gotMoveIdx = this.lastate.movesCount - 1;
746 if (this.game.rendered)
747 // Game is rendered (Board component)
748 this.processLastate();
749 // Else: will be processed when game is ready
755 console.log("Receive move");
756 console.log(data.data);
757 //moveslist not updated when receiving a move? (see in baseGame)
759 const movePlus = data.data;
760 const movesCount = this.game.moves.length;
762 movePlus.index < movesCount ||
763 this.gotMoveIdx >= movePlus.index
765 // Opponent re-send but we already have the move:
766 // (maybe he didn't receive our pingback...)
767 this.send("gotmove", {data: movePlus.index, target: data.from});
770 this.gotMoveIdx = movePlus.index;
771 const receiveMyMove = (movePlus.color == this.game.mycolor);
772 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
773 if (!receiveMyMove && !!this.game.mycolor) {
774 // Notify opponent that I got the move:
777 { data: movePlus.index, target: data.from }
779 // And myself if I'm elsewhere:
785 (this.game.players[moveColIdx].name || "@nonymous") +
791 if (movePlus.cancelDrawOffer) {
792 // Opponent refuses draw
794 // NOTE for corr games: drawOffer reset by player in turn
796 this.game.type == "live" &&
797 !!this.game.mycolor &&
800 GameStorage.update(this.gameRef, { drawOffer: "" });
803 this.$refs["basegame"].play(movePlus.move, "received");
804 // Freeze time while the move is being play
805 // (TODO: a callback would be cleaner here)
806 clearInterval(this.clockUpdate);
807 this.clockUpdate = null;
808 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
809 // 250 = length of animation, 500 = delay between sub-moves
811 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
812 // Incomplete information: no move animation
816 this.game.clocks[moveColIdx] = movePlus.clock;
819 { receiveMyMove: receiveMyMove }
828 this.opponentGotMove = true;
829 // Now his clock starts running on my side:
830 const oppIdx = ['w','b'].indexOf(this.vr.turn);
831 // NOTE: next line to avoid multi-resetClocks when several tabs
832 // on same game, resulting in a faster countdown.
833 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
838 const score = (data.data == "b" ? "1-0" : "0-1");
839 const side = (data.data == "w" ? "White" : "Black");
840 this.gameOver(score, side + " surrender");
843 this.gameOver("?", "Stop");
846 this.gameOver("1/2", data.data);
849 // NOTE: observers don't know who offered draw
850 this.drawOffer = "received";
851 if (!!this.game.mycolor && this.game.type == "live") {
854 { drawOffer: V.GetOppCol(this.game.mycolor) }
859 // NOTE: observers don't know who offered rematch
860 this.rematchOffer = data.data ? "received" : "";
861 if (!!this.game.mycolor && this.game.type == "live") {
864 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
869 // A game started, redirect if I'm playing in
870 const gameInfo = data.data;
871 const gameType = this.getGameType(gameInfo);
873 gameType == "live" &&
874 gameInfo.players.some(p => p.sid == this.st.user.sid)
876 this.addAndGotoLiveGame(gameInfo);
878 gameType == "corr" &&
879 this.st.user.id > 0 &&
880 gameInfo.players.some(p => p.id == this.st.user.id)
882 this.$router.push("/game/" + gameInfo.id);
884 this.rematchId = gameInfo.id;
885 document.getElementById("modalRules").checked = false;
886 document.getElementById("modalScore").checked = false;
887 document.getElementById("modalRematch").checked = true;
892 let chat = data.data;
893 this.$refs["chatcomp"].newChat(chat);
894 if (this.game.type == "live") {
895 chat.added = Date.now();
896 if (!!this.game.mycolor)
897 GameStorage.update(this.gameRef, { chat: chat });
899 if (!document.getElementById("modalChat").checked)
900 document.getElementById("chatBtn").classList.add("somethingnew");
905 updateCorrGame: function(obj, callback) {
915 if (!!callback) callback();
920 sendLastate: function(target) {
921 // Send our "last state" informations to opponent
922 const L = this.game.moves.length;
923 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
926 (L > 0 && this.vr.turn != this.game.mycolor)
927 ? this.game.moves[L - 1]
929 clock: this.game.clocks[myIdx],
930 // Since we played a move (or abort or resign),
931 // only drawOffer=="sent" is possible
932 drawSent: this.drawOffer == "sent" ? true : undefined,
933 rematchSent: this.rematchOffer == "sent" ? true : undefined,
934 score: this.game.score != "*" ? this.game.score : undefined,
935 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
938 this.send("lastate", { data: myLastate, target: target });
940 // lastate was received, but maybe game wasn't ready yet:
941 processLastate: function() {
942 const data = this.lastate;
943 this.lastate = undefined; //security...
945 const oppCol = V.GetOppCol(this.game.mycolor);
946 if (!!data.rematchSent) {
947 if (this.game.rematchOffer != oppCol) {
948 // Opponent sended rematch offer while we were offline:
949 this.rematchOffer = "received";
952 { rematchOffer: oppCol }
957 if (this.game.rematchOffer == oppCol) {
958 // Opponent cancelled rematch offer while we were offline:
959 this.rematchOffer = "";
968 const L = this.game.moves.length;
969 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
970 this.game.clocks[oppIdx] = data.clock;
971 if (data.movesCount > L) {
972 // Just got last move from him
973 this.$refs["basegame"].play(data.lastMove, "received");
974 this.processMove(data.lastMove);
976 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
979 if (!!data.drawSent) this.drawOffer = "received";
982 if (this.game.score == "*")
983 this.gameOver(data.score, data.scoreMsg);
987 clickDraw: function() {
988 if (!this.game.mycolor || this.game.type == "import") return;
989 if (["received", "threerep"].includes(this.drawOffer)) {
990 if (!confirm(this.st.tr["Accept draw?"])) return;
992 this.drawOffer == "received"
994 : "Three repetitions";
995 this.send("draw", { data: message });
996 this.gameOver("1/2", message);
997 } else if (this.drawOffer == "") {
998 // No effect if drawOffer == "sent"
999 if (this.game.mycolor != this.vr.turn) {
1000 alert(this.st.tr["Draw offer only in your turn"]);
1003 if (!confirm(this.st.tr["Offer draw?"])) return;
1004 this.drawOffer = "sent";
1005 this.send("drawoffer");
1006 if (this.game.type == "live") {
1009 { drawOffer: this.game.mycolor }
1011 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1014 addAndGotoLiveGame: function(gameInfo, callback) {
1015 const game = Object.assign(
1019 // (other) Game infos: constant
1020 fenStart: gameInfo.fen,
1021 vname: this.game.vname,
1022 created: Date.now(),
1023 // Game state (including FEN): will be updated
1025 clocks: [-1, -1], //-1 = unstarted
1030 GameStorage.add(game, (err) => {
1031 // No error expected.
1033 if (this.st.settings.sound)
1034 new Audio("/sounds/newgame.flac").play().catch(() => {});
1035 if (!!callback) callback();
1036 this.$router.push("/game/" + gameInfo.id);
1040 clickRematch: function() {
1041 if (!this.game.mycolor || this.game.type == "import") return;
1042 if (this.rematchOffer == "received") {
1043 // Start a new game!
1045 id: getRandString(), //ignored if corr
1046 fen: V.GenRandInitFen(this.game.randomness),
1047 players: [this.game.players[1], this.game.players[0]],
1049 cadence: this.game.cadence
1051 const notifyNewGame = () => {
1052 const oppsid = this.getOppsid(); //may be null
1053 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1054 // To main Hall if corr game:
1055 if (this.game.type == "corr")
1056 this.send("newgame", { data: gameInfo, page: "/" });
1057 // Also to MyGames page:
1058 this.notifyMyGames("newgame", gameInfo);
1060 if (this.game.type == "live")
1061 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1068 // cid is useful to delete the challenge:
1069 data: { gameInfo: gameInfo },
1070 success: (response) => {
1071 gameInfo.id = response.gameId;
1073 this.$router.push("/game/" + response.gameId);
1078 } else if (this.rematchOffer == "") {
1079 this.rematchOffer = "sent";
1080 this.send("rematchoffer", { data: true });
1081 if (this.game.type == "live") {
1084 { rematchOffer: this.game.mycolor }
1086 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1087 } else if (this.rematchOffer == "sent") {
1088 // Toggle rematch offer (on --> off)
1089 this.rematchOffer = "";
1090 this.send("rematchoffer", { data: false });
1091 if (this.game.type == "live") {
1094 { rematchOffer: '' }
1096 } else this.updateCorrGame({ rematchOffer: 'n' });
1099 abortGame: function() {
1100 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1102 this.gameOver("?", "Stop");
1105 resign: function() {
1106 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1108 this.send("resign", { data: this.game.mycolor });
1109 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1110 const side = (this.game.mycolor == "w" ? "White" : "Black");
1111 this.gameOver(score, side + " surrender");
1113 loadGame: function(game, callback) {
1114 const gtype = game.type || this.getGameType(game);
1115 const tc = extractTime(game.cadence);
1116 const myIdx = game.players.findIndex(p => {
1118 p.sid == this.st.user.sid ||
1119 (!!p.name && p.id == this.st.user.id)
1122 // Sometimes the name isn't stored yet (TODO: why?)
1126 !game.players[myIdx].name &&
1129 game.players[myIdx].name = this.st.user.name;
1132 { playerName: { idx: myIdx, name: this.st.user.name } }
1135 // "mycolor" is undefined for observers
1136 const mycolor = [undefined, "w", "b"][myIdx + 1];
1137 if (gtype == "corr") {
1138 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1139 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1140 // NOTE: clocks in seconds
1141 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1142 game.clocks = [tc.mainTime, tc.mainTime];
1143 const L = game.moves.length;
1144 if (game.score == "*") {
1147 game.clocks[L % 2] -=
1148 (Date.now() - game.moves[L-1].played) / 1000;
1151 // Now that we used idx and played, re-format moves as for live games
1152 game.moves = game.moves.map(m => m.squares);
1154 else if (gtype == "live") {
1155 if (game.clocks[0] < 0) {
1156 // Game is unstarted. clock is ignored until move 2
1157 game.clocks = [tc.mainTime, tc.mainTime];
1159 // I play in this live game
1162 { clocks: game.clocks }
1167 // It's my turn: clocks not updated yet
1168 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1172 // gtype == "import"
1173 game.clocks = [tc.mainTime, tc.mainTime];
1174 // Live games before 26/03/2020 don't have chat history:
1175 if (!game.chats) game.chats = []; //TODO: remove line
1176 // Sort chat messages from newest to oldest
1177 game.chats.sort((c1, c2) => c2.added - c1.added);
1180 game.chats.length > 0 &&
1181 (!game.chatRead || game.chatRead < game.chats[0].added)
1183 // A chat message arrived since my last reading:
1184 document.getElementById("chatBtn").classList.add("somethingnew");
1186 // TODO: merge next 2 "if" conditions
1187 if (!!game.drawOffer) {
1188 if (game.drawOffer == "t")
1189 // Three repetitions
1190 this.drawOffer = "threerep";
1192 // Draw offered by any of the players:
1193 if (myIdx < 0) this.drawOffer = "received";
1195 // I play in this game:
1197 (game.drawOffer == "w" && myIdx == 0) ||
1198 (game.drawOffer == "b" && myIdx == 1)
1200 this.drawOffer = "sent";
1201 else this.drawOffer = "received";
1205 if (!!game.rematchOffer) {
1206 if (myIdx < 0) this.rematchOffer = "received";
1208 // I play in this game:
1210 (game.rematchOffer == "w" && myIdx == 0) ||
1211 (game.rematchOffer == "b" && myIdx == 1)
1213 this.rematchOffer = "sent";
1215 else this.rematchOffer = "received";
1218 this.repeat = {}; //reset: scan past moves' FEN:
1220 this.vr = new V(game.fenStart);
1222 game.moves.forEach(m => {
1223 playMove(m, this.vr);
1224 const fenIdx = this.vr.getFenForRepeat();
1225 this.repeat[fenIdx] = this.repeat[fenIdx]
1226 ? this.repeat[fenIdx] + 1
1229 // Imported games don't have current FEN
1230 if (!game.fen) game.fen = this.vr.getFen();
1231 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1232 this.game = Object.assign(
1233 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1236 increment: tc.increment,
1238 // opponent sid not strictly required (or available), but easier
1239 // at least oppsid or oppid is available anyway:
1240 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1241 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1245 this.$refs["basegame"].re_setVariables(this.game);
1247 this.gotMoveIdx = game.moves.length - 1;
1248 // If we arrive here after 'nextGame' action, the board might be hidden
1249 let boardDiv = document.querySelector(".game");
1250 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1251 boardDiv.style.visibility = "visible";
1252 this.re_setClocks();
1253 this.$nextTick(() => {
1254 this.game.rendered = true;
1255 // Did lastate arrive before game was rendered?
1256 if (!!this.lastate) this.processLastate();
1258 if (this.lastateAsked) {
1259 this.lastateAsked = false;
1260 this.sendLastate(game.oppsid);
1262 if (!!callback) callback();
1264 loadVariantThenGame: async function(game, callback) {
1265 await import("@/variants/" + game.vname + ".js")
1266 .then((vModule) => {
1267 window.V = vModule[game.vname + "Rules"];
1268 this.loadGame(game, callback);
1270 // (AJAX) Request to get rules content (plain text, HTML)
1273 "raw-loader!@/translations/rules/" +
1275 this.st.lang + ".pug"
1277 // Next two lines fix a weird issue after last update (2019-11)
1278 .replace(/\\n/g, " ")
1279 .replace(/\\"/g, '"')
1280 .replace('module.exports = "', "")
1282 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1284 // 3 cases for loading a game:
1285 // - from indexedDB (running or completed live game I play)
1286 // - from server (one correspondance game I play[ed] or not)
1287 // - from remote peer (one live game I don't play, finished or not)
1288 fetchGame: function(callback) {
1289 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1290 // corr games identifiers are integers
1295 data: { gid: this.gameRef },
1297 res.game.moves.forEach(m => {
1298 m.squares = JSON.parse(m.squares);
1305 else if (!!this.gameRef.match(/^i/))
1306 // Game import (maybe remote)
1307 ImportgameStorage.get(this.gameRef, callback);
1309 // Local live game (or remote)
1310 GameStorage.get(this.gameRef, callback);
1312 re_setClocks: function() {
1313 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1314 if (this.game.moves.length < 2 || this.game.score != "*") {
1315 // 1st move not completed yet, or game over: freeze time
1318 const currentTurn = this.vr.turn;
1319 const currentMovesCount = this.game.moves.length;
1320 const colorIdx = ["w", "b"].indexOf(currentTurn);
1321 this.clockUpdate = setInterval(
1324 this.game.clocks[colorIdx] < 0 ||
1325 this.game.moves.length > currentMovesCount ||
1326 this.game.score != "*"
1328 clearInterval(this.clockUpdate);
1329 this.clockUpdate = null;
1330 if (this.game.clocks[colorIdx] < 0)
1332 currentTurn == "w" ? "0-1" : "1-0",
1339 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1346 // Update variables and storage after a move:
1347 processMove: function(move, data) {
1348 if (this.game.type == "import")
1349 // Shouldn't receive any messages in this mode:
1351 if (!data) data = {};
1352 const moveCol = this.vr.turn;
1353 const colorIdx = ["w", "b"].indexOf(moveCol);
1354 const nextIdx = 1 - colorIdx;
1355 const doProcessMove = () => {
1356 const origMovescount = this.game.moves.length;
1357 // The move is (about to be) played: stop clock
1358 clearInterval(this.clockUpdate);
1359 this.clockUpdate = null;
1360 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1361 if (this.drawOffer == "received")
1363 this.drawOffer = "";
1364 if (this.game.type == "live" && origMovescount >= 2) {
1365 this.game.clocks[colorIdx] += this.game.increment;
1366 // For a correct display in casqe of disconnected opponent:
1370 ppt(this.game.clocks[colorIdx]).split(':')
1372 GameStorage.update(this.gameRef, {
1373 // It's not my turn anymore:
1378 // Update current game object:
1379 playMove(move, this.vr);
1381 // Received move, score is computed in BaseGame, but maybe not yet.
1382 // ==> Compute it here, although this is redundant (TODO)
1383 data.score = this.vr.getCurrentScore();
1384 if (data.score != "*") this.gameOver(data.score);
1385 this.game.moves.push(move);
1386 this.game.fen = this.vr.getFen();
1387 if (this.game.type == "corr") {
1388 // In corr games, just reset clock to mainTime:
1389 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1391 // If repetition detected, consider that a draw offer was received:
1392 const fenObj = this.vr.getFenForRepeat();
1393 this.repeat[fenObj] =
1394 !!this.repeat[fenObj]
1395 ? this.repeat[fenObj] + 1
1397 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1398 else if (this.drawOffer == "threerep") this.drawOffer = "";
1399 if (!!this.game.mycolor && !data.receiveMyMove) {
1400 // NOTE: 'var' to see that variable outside this block
1401 var filtered_move = getFilteredMove(move);
1403 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1404 // Notify turn on MyGames page:
1413 // Since corr games are stored at only one location, update should be
1414 // done only by one player for each move:
1416 this.game.type == "live" &&
1417 !!this.game.mycolor &&
1418 moveCol != this.game.mycolor &&
1419 this.game.moves.length >= 2
1421 // Receive a move: update initime
1422 this.game.initime = Date.now();
1423 GameStorage.update(this.gameRef, {
1424 // It's my turn now!
1425 initime: this.game.initime
1429 !!this.game.mycolor &&
1430 !data.receiveMyMove &&
1431 (this.game.type == "live" || moveCol == this.game.mycolor)
1434 switch (this.drawOffer) {
1439 drawCode = this.game.mycolor;
1442 drawCode = V.GetOppCol(this.game.mycolor);
1445 if (this.game.type == "corr") {
1446 // corr: only move, fen and score
1447 this.updateCorrGame({
1450 squares: filtered_move,
1453 // Code "n" for "None" to force reset (otherwise it's ignored)
1454 drawOffer: drawCode || "n"
1458 const updateStorage = () => {
1459 GameStorage.update(this.gameRef, {
1461 move: filtered_move,
1462 moveIdx: origMovescount,
1463 clocks: this.game.clocks,
1467 // The active tab can update storage immediately
1468 if (this.focus) updateStorage();
1469 // Small random delay otherwise
1470 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1473 // Send move ("newmove" event) to people in the room (if our turn)
1474 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1476 move: filtered_move,
1477 index: origMovescount,
1478 // color is required to check if this is my move
1479 // (if several tabs opened)
1481 cancelDrawOffer: this.drawOffer == ""
1483 if (this.game.type == "live")
1484 sendMove["clock"] = this.game.clocks[colorIdx];
1485 // (Live) Clocks will re-start when the opponent pingback arrive
1486 this.opponentGotMove = false;
1487 this.send("newmove", {data: sendMove});
1488 // If the opponent doesn't reply gotmove soon enough, re-send move:
1489 // Do this at most 2 times, because more would mean network issues,
1490 // opponent would then be expected to disconnect/reconnect.
1492 const currentUrl = document.location.href;
1493 this.retrySendmove = setInterval(
1497 this.opponentGotMove ||
1498 document.location.href != currentUrl //page change
1500 clearInterval(this.retrySendmove);
1503 const oppsid = this.getOppsid();
1505 // Opponent is disconnected: he'll ask last state
1506 clearInterval(this.retrySendmove);
1508 this.send("newmove", { data: sendMove, target: oppsid });
1516 // Not my move or I'm an observer: just start other player's clock
1517 this.re_setClocks();
1520 this.game.type == "corr" &&
1522 moveCol == this.game.mycolor &&
1525 let boardDiv = document.querySelector(".game");
1526 const afterSetScore = () => {
1528 if (this.st.settings.gotonext && this.nextIds.length > 0)
1529 this.showNextGame();
1531 // The board might have been hidden:
1532 if (boardDiv.style.visibility == "hidden")
1533 boardDiv.style.visibility = "visible";
1534 if (data.score == "*") this.re_setClocks();
1537 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1538 // We may play several moves in a row: in case of, remove listener:
1539 let elClone = el.cloneNode(true);
1540 el.parentNode.replaceChild(elClone, el);
1541 elClone.addEventListener(
1544 document.getElementById("modalConfirm").checked = false;
1545 if (!!data.score && data.score != "*")
1547 this.gameOver(data.score, null, afterSetScore);
1548 else afterSetScore();
1551 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1552 const arMove = (Array.isArray(move) ? move : [move]);
1553 for (let i = 0; i < arMove.length; i++)
1554 V.PlayOnBoard(this.vr.board, arMove[i]);
1555 const position = this.vr.getBaseFen();
1556 for (let i = arMove.length - 1; i >= 0; i--)
1557 V.UndoOnBoard(this.vr.board, arMove[i]);
1558 if (["all","byrow"].includes(V.ShowMoves)) {
1559 this.curDiag = getDiagram({
1561 orientation: V.CanFlip ? this.game.mycolor : "w"
1563 document.querySelector("#confirmDiv > .card").style.width =
1564 boardDiv.offsetWidth + "px";
1567 // Incomplete information: just ask confirmation
1568 // Hide the board, because otherwise it could reveal infos
1569 boardDiv.style.visibility = "hidden";
1570 this.moveNotation = getFullNotation(move);
1572 document.getElementById("modalConfirm").checked = true;
1576 if (!!data.score && data.score != "*")
1577 this.gameOver(data.score, null, doProcessMove);
1578 else doProcessMove();
1581 cancelMove: function() {
1582 let boardDiv = document.querySelector(".game");
1583 if (boardDiv.style.visibility == "hidden")
1584 boardDiv.style.visibility = "visible";
1585 document.getElementById("modalConfirm").checked = false;
1586 this.$refs["basegame"].cancelLastMove();
1588 // In corr games, callback to change page only after score is set:
1589 gameOver: function(score, scoreMsg, callback) {
1590 this.game.score = score;
1591 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1592 this.game.scoreMsg = scoreMsg;
1593 document.getElementById("modalRules").checked = false;
1594 // Display result in a un-missable way:
1595 document.getElementById("modalScore").checked = true;
1596 this.$set(this.game, "scoreMsg", scoreMsg);
1597 const myIdx = this.game.players.findIndex(p => {
1599 p.sid == this.st.user.sid ||
1600 (!!p.name && p.id == this.st.user.id)
1604 // OK, I play in this game
1609 if (this.game.type == "live") {
1610 GameStorage.update(this.gameRef, scoreObj);
1611 // Notify myself locally if I'm elsewhere:
1615 { body: score + " : " + scoreMsg }
1618 if (!!callback) callback();
1620 else this.updateCorrGame(scoreObj, callback);
1621 // Notify the score to main Hall.
1622 // TODO: only one player (currently double send)
1623 this.send("result", { gid: this.game.id, score: score });
1624 // Also to MyGames page (TODO: doubled as well...)
1633 else if (!!callback) callback();
1639 <style lang="sass" scoped>
1640 #scoreDiv > .card, #rematchDiv > .card
1648 @media screen and (max-width: 1500px)
1650 @media screen and (max-width: 1024px)
1652 @media screen and (max-width: 767px)
1662 background-color: lightgreen
1674 @media screen and (max-width: 767px)
1679 display: inline-block
1683 display: inline-block
1685 display: inline-flex
1689 @media screen and (max-width: 767px)
1698 @media screen and (max-width: 767px)
1710 background-color: #edda99
1712 display: inline-block
1716 display: inline-block
1723 @media screen and (max-width: 767px)
1725 display: inline-block
1738 animation: blink-animation 2s steps(3, start) infinite
1739 @keyframes blink-animation
1744 display: inline-block
1756 .draw-sent, .draw-sent:hover
1757 background-color: lightyellow
1759 .draw-received, .draw-received:hover
1760 background-color: #73C6B6
1762 .draw-threerep, .draw-threerep:hover
1763 background-color: #D2B4DE
1765 .rematch-sent, .rematch-sent:hover
1766 background-color: lightyellow
1768 .rematch-received, .rematch-received:hover
1769 background-color: #48C9B0
1772 background-color: #D2B4DE
1785 background-color: lightgreen
1787 background-color: red
1790 color: var(--card-fore-color)
1793 font-size: calc(1rem * var(--heading-ratio))
1795 margin: calc(1.5 * var(--universal-margin))
1799 @import "@/styles/_rules.sass"
1800 @import "@/styles/_board_squares_img.sass"