3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vname }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
86 | {{ st.tr["Next_g"] }}
88 :class="btnTooltipClass()"
89 onClick="window.doClick('modalChat')"
92 img(src="/images/icons/chat.svg")
93 #actions(v-if="game.score=='*'")
96 :class="btnTooltipClass('draw')"
97 :aria-label="st.tr['Draw']"
99 img(src="/images/icons/draw.svg")
101 v-if="!!game.mycolor"
102 :class="btnTooltipClass()"
104 :aria-label="st.tr['Abort']"
106 img(src="/images/icons/abort.svg")
108 v-if="!!game.mycolor"
109 :class="btnTooltipClass()"
111 :aria-label="st.tr['Resign']"
113 img(src="/images/icons/resign.svg")
116 :class="btnTooltipClass('rematch')"
117 @click="clickRematch()"
118 :aria-label="st.tr['Rematch']"
120 img(src="/images/icons/rematch.svg")
122 div(v-if="isLargeScreen()")
124 :class="{connected: isConnected(0)}"
125 :uid="game.players[0].id"
126 :uname="game.players[0].name"
129 v-if="game.score=='*'"
130 :class="{yourturn: !!vr && vr.turn == 'w'}"
132 span.time-left {{ virtualClocks[0][0] }}
133 span.time-separator(v-if="!!virtualClocks[0][1]") :
134 span.time-right(v-if="!!virtualClocks[0][1]")
135 | {{ virtualClocks[0][1] }}
138 :class="{connected: isConnected(1)}"
139 :uid="game.players[1].id"
140 :uname="game.players[1].name"
143 v-if="game.score=='*'"
144 :class="{yourturn: !!vr && vr.turn == 'b'}"
146 span.time-left {{ virtualClocks[1][0] }}
147 span.time-separator(v-if="!!virtualClocks[1][1]") :
148 span.time-right(v-if="!!virtualClocks[1][1]")
149 | {{ virtualClocks[1][1] }}
152 :class="{connected: isConnected(0)}"
153 :uid="game.players[0].id"
154 :uname="game.players[0].name"
158 :class="{connected: isConnected(1)}"
159 :uid="game.players[1].id"
160 :uname="game.players[1].name"
162 div(v-if="game.score=='*'")
163 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
164 span.time-left {{ virtualClocks[0][0] }}
165 span.time-separator(v-if="!!virtualClocks[0][1]") :
166 span.time-right(v-if="!!virtualClocks[0][1]")
167 | {{ virtualClocks[0][1] }}
169 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
170 span.time-left {{ virtualClocks[1][0] }}
171 span.time-separator(v-if="!!virtualClocks[1][1]") :
172 span.time-right(v-if="!!virtualClocks[1][1]")
173 | {{ virtualClocks[1][1] }}
177 @newmove="processMove"
182 import BaseGame from "@/components/BaseGame.vue";
183 import UserBio from "@/components/UserBio.vue";
184 import Chat from "@/components/Chat.vue";
185 import { store } from "@/store";
186 import { GameStorage } from "@/utils/gameStorage";
187 import { ImportgameStorage } from "@/utils/importgameStorage";
188 import { ppt } from "@/utils/datetime";
189 import { notify } from "@/utils/notifications";
190 import { ajax } from "@/utils/ajax";
191 import { extractTime } from "@/utils/timeControl";
192 import { getRandString } from "@/utils/alea";
193 import { getScoreMessage } from "@/utils/scoring";
194 import { getFullNotation } from "@/utils/notation";
195 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
196 import { processModalClick } from "@/utils/modalClick";
197 import { playMove, getFilteredMove } from "@/utils/playUndo";
198 import { ArrayFun } from "@/utils/array";
199 import afterRawLoad from "@/utils/afterRawLoad";
200 import params from "@/parameters";
211 // gameRef can point to a corr game, local game or remote live game
214 game: {}, //passed to BaseGame
215 focus: !document.hidden, //will not always work... TODO
216 // virtualClocks will be initialized from true game.clocks
217 // TODO: clock update triggers re-rendering. Should be out of Vue
219 vr: null, //"variant rules" object initialized from FEN
225 people: {}, //players + observers
226 lastate: undefined, //used if opponent send lastate before game is ready
227 repeat: {}, //detect position repetition
228 curDiag: "", //for corr moves confirmation
230 roomInitialized: false,
231 // If asklastate got no reply, ask again:
233 gotMoveIdx: -1, //last move index received
234 // If newmove got no pingback, send again:
235 opponentGotMove: false,
237 socketCloseListener: 0,
238 // Incomplete info games: show move played
240 // Intervals from setInterval():
244 // Related to (killing of) self multi-connects:
249 $route: function(to, from) {
250 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
252 this.cleanBeforeDestroy();
253 else if (from.params["id"] != to.params["id"]) {
254 // Change everything:
255 this.cleanBeforeDestroy();
256 let boardDiv = document.querySelector(".game");
258 // In case of incomplete information variant:
259 boardDiv.style.visibility = "hidden";
264 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
267 // NOTE: some redundant code with Hall.vue (mostly related to people array)
268 created: function() {
271 mounted: function() {
272 document.getElementById("chatWrap")
273 .addEventListener("click", (e) => {
274 processModalClick(e, () => {
275 this.toggleChat("close")
278 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
280 document.getElementById(eltName)
281 .addEventListener("click", processModalClick);
285 beforeDestroy: function() {
286 this.cleanBeforeDestroy();
289 cleanBeforeDestroy: function() {
290 clearInterval(this.socketCloseListener);
291 document.removeEventListener('visibilitychange', this.visibilityChange);
292 window.removeEventListener('focus', this.onFocus);
293 window.removeEventListener('blur', this.onBlur);
294 if (!!this.askLastate) clearInterval(this.askLastate);
295 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
296 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
297 this.conn.removeEventListener("message", this.socketMessageListener);
298 this.send("disconnect");
301 visibilityChange: function() {
302 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
303 this.focus = (document.visibilityState == "visible");
304 this.send(this.focus ? "getfocus" : "losefocus");
306 onFocus: function() {
308 this.send("getfocus");
312 this.send("losefocus");
314 isLargeScreen: function() {
315 return window.innerWidth >= 768;
317 btnTooltipClass: function(thing) {
319 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
322 { tooltip: !("ontouchstart" in window) },
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 } }
520 GameStorage.update(this.gameRef, { delchat: true });
522 this.$set(this.game, "chats", []);
525 getGameType: function(game) {
526 if (!!game.id.toString().match(/^i/)) return "import";
527 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
529 // Notify something after a new move (to opponent and me on MyGames page)
530 notifyMyGames: function(thing, data) {
535 targets: this.game.players.map(p => {
536 return { sid: p.sid, id: p.id };
541 showNextGame: function() {
542 // Did I play in current game? If not, add it to nextIds list
543 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
544 this.nextIds.unshift(this.game.id);
545 const nextGid = this.nextIds.pop();
547 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
549 socketMessageListener: function(msg) {
550 if (!this.conn) return;
551 const data = JSON.parse(msg.data);
554 // TODO: shuffling and random filtering on server,
555 // if the room is really crowded.
556 Object.keys(data.sockIds).forEach(sid => {
557 if (sid != this.st.user.sid) {
558 this.send("askidentity", { target: sid });
559 this.people[sid] = { tmpIds: data.sockIds[sid] };
562 // Complete my tmpIds:
563 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
568 if (!this.people[data.from[0]]) {
569 // focus depends on the tmpId (e.g. tab)
575 [data.from[1]]: { focus: true }
579 // For self multi-connects tests:
580 this.newConnect[data.from[0]] = true;
581 this.send("askidentity", { target: data.from[0] });
584 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
585 this.$forceUpdate(); //TODO: shouldn't be required
589 if (!this.people[data.from[0]]) return;
590 delete this.people[data.from[0]].tmpIds[data.from[1]];
591 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
592 this.$delete(this.people, data.from[0]);
593 else this.$forceUpdate(); //TODO: shouldn't be required
596 let player = this.people[data.from[0]];
598 player.tmpIds[data.from[1]].focus = true;
599 this.$forceUpdate(); //TODO: shouldn't be required
604 let player = this.people[data.from[0]];
606 player.tmpIds[data.from[1]].focus = false;
607 this.$forceUpdate(); //TODO: shouldn't be required
611 case "askidentity": {
612 // Request for identification
614 // Decompose to avoid revealing email
615 name: this.st.user.name,
616 sid: this.st.user.sid,
619 this.send("identity", { data: me, target: data.from });
623 const user = data.data;
624 let player = this.people[user.sid];
625 // player.tmpIds is already set
626 player.name = user.name;
628 if (this.game.type == "live") {
630 this.game.players.findIndex(p => p.sid == this.st.user.sid);
631 // Sometimes a player name isn't stored yet (TODO: why?)
634 !this.game.players[1 - myGidx].name &&
635 this.game.players[1 - myGidx].sid == user.sid &&
638 this.game.players[1-myGidx].name = user.name;
641 { playerName: { idx: 1 - myGidx, name: user.name } }
645 this.$forceUpdate(); //TODO: shouldn't be required
646 // If I multi-connect, kill current connexion if no mark (I'm older)
647 if (this.newConnect[user.sid]) {
648 delete this.newConnect[user.sid];
651 user.id == this.st.user.id &&
652 user.sid != this.st.user.sid
654 this.cleanBeforeDestroy();
655 alert(this.st.tr["New connexion detected: tab now offline"]);
659 // Ask potentially missed last state, if opponent and I play
662 !!this.game.mycolor &&
663 this.game.type == "live" &&
664 this.game.players.some(p => p.sid == user.sid)
666 this.send("asklastate", { target: user.sid });
668 this.askLastate = setInterval(
670 // Ask at most 3 times:
671 // if no reply after that there should be a network issue.
675 !!this.people[user.sid]
677 this.send("asklastate", { target: user.sid });
680 else clearInterval(this.askLastate);
688 // Send current (live or import) game,
689 // if not asked by any of the players
691 this.game.type != "corr" &&
692 this.game.players.every(p => p.sid != data.from[0])
696 // FEN is current position, unused for now
698 players: this.game.players,
700 cadence: this.game.cadence,
701 score: this.game.score
703 this.send("game", { data: myGame, target: data.from });
707 const gameToSend = Object.keys(this.game)
710 "id","fen","players","vid","cadence","fenStart","vname",
711 "moves","clocks","score","drawOffer","rematchOffer"
715 obj[k] = this.game[k];
720 this.send("fullgame", { data: gameToSend, target: data.from });
723 if (!!data.data.empty) {
724 alert(this.st.tr["The game should be in another tab"]);
728 // Callback "roomInit" to poll clients only after game is loaded
729 this.loadVariantThenGame(data.data, this.roomInit);
732 // Sending informative last state if I played a move or score != "*"
733 // If the game or moves aren't loaded yet, delay the sending:
734 // TODO: socket init after game load, so the game is supposedly ready
735 if (!this.game || !this.game.moves) this.lastateAsked = true;
736 else this.sendLastate(data.from);
738 // TODO: possible bad scenario: reload page while oppponent sends a
739 // move => get both lastate and newmove, process both, add move twice.
740 // Confirm scenario? Fix?
742 // Got opponent infos about last move
743 this.gotLastate = true;
744 this.lastate = data.data;
745 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
746 this.gotMoveIdx = this.lastate.movesCount - 1;
747 if (this.game.rendered)
748 // Game is rendered (Board component)
749 this.processLastate();
750 // Else: will be processed when game is ready
756 //console.log("Receive move");
757 //console.log(data.data);
758 //moveslist not updated when receiving a move? (see in BaseGame)
760 const movePlus = data.data;
761 const movesCount = this.game.moves.length;
763 movePlus.index < movesCount ||
764 this.gotMoveIdx >= movePlus.index
766 // Opponent re-send but we already have the move:
767 // (maybe he didn't receive our pingback...)
768 this.send("gotmove", {data: movePlus.index, target: data.from});
771 this.gotMoveIdx = movePlus.index;
772 const receiveMyMove = (movePlus.color == this.game.mycolor);
773 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
774 if (!receiveMyMove && !!this.game.mycolor) {
775 // Notify opponent that I got the move:
778 { data: movePlus.index, target: data.from }
780 // And myself if I'm elsewhere:
786 (this.game.players[moveColIdx].name || "@nonymous") +
792 if (movePlus.cancelDrawOffer) {
793 // Opponent refuses draw
795 // NOTE for corr games: drawOffer reset by player in turn
797 this.game.type == "live" &&
798 !!this.game.mycolor &&
801 GameStorage.update(this.gameRef, { drawOffer: "" });
804 this.$refs["basegame"].play(movePlus.move, "received");
805 // Freeze time while the move is being play
806 // (TODO: a callback would be cleaner here)
807 clearInterval(this.clockUpdate);
808 this.clockUpdate = null;
809 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
810 // 250 = length of animation, 500 = delay between sub-moves
812 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
813 // Incomplete information: no move animation
817 this.game.clocks[moveColIdx] = movePlus.clock;
820 { receiveMyMove: receiveMyMove }
829 this.opponentGotMove = true;
830 // Now his clock starts running on my side:
831 const oppIdx = ['w','b'].indexOf(this.vr.turn);
832 // NOTE: next line to avoid multi-resetClocks when several tabs
833 // on same game, resulting in a faster countdown.
834 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
839 const score = (data.data == "b" ? "1-0" : "0-1");
840 const side = (data.data == "w" ? "White" : "Black");
841 this.gameOver(score, side + " surrender");
844 this.gameOver("?", "Stop");
847 this.gameOver("1/2", data.data);
850 // NOTE: observers don't know who offered draw
851 this.drawOffer = "received";
852 if (!!this.game.mycolor && this.game.type == "live") {
855 { drawOffer: V.GetOppCol(this.game.mycolor) }
860 // NOTE: observers don't know who offered rematch
861 this.rematchOffer = data.data ? "received" : "";
862 if (!!this.game.mycolor && this.game.type == "live") {
865 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
870 // A game started, redirect if I'm playing in
871 const gameInfo = data.data;
872 const gameType = this.getGameType(gameInfo);
874 gameType == "live" &&
875 gameInfo.players.some(p => p.sid == this.st.user.sid)
877 this.addAndGotoLiveGame(gameInfo);
880 gameType == "corr" &&
881 this.st.user.id > 0 &&
882 gameInfo.players.some(p => p.id == this.st.user.id)
884 this.$router.push("/game/" + gameInfo.id);
887 this.rematchId = gameInfo.id;
888 document.getElementById("modalRules").checked = false;
889 document.getElementById("modalScore").checked = false;
890 document.getElementById("modalRematch").checked = true;
895 let chat = data.data;
896 this.$refs["chatcomp"].newChat(chat);
897 if (this.game.type == "live") {
898 chat.added = Date.now();
899 if (!!this.game.mycolor)
900 GameStorage.update(this.gameRef, { chat: chat });
902 if (!document.getElementById("modalChat").checked)
903 document.getElementById("chatBtn").classList.add("somethingnew");
908 updateCorrGame: function(obj, callback) {
918 if (!!callback) callback();
923 sendLastate: function(target) {
924 // Send our "last state" informations to opponent
925 const L = this.game.moves.length;
926 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
929 (L > 0 && this.vr.turn != this.game.mycolor)
930 ? this.game.moves[L - 1]
932 clock: this.game.clocks[myIdx],
933 // Since we played a move (or abort or resign),
934 // only drawOffer=="sent" is possible
935 drawSent: this.drawOffer == "sent" ? true : undefined,
936 rematchSent: this.rematchOffer == "sent" ? true : undefined,
937 score: this.game.score != "*" ? this.game.score : undefined,
938 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
941 this.send("lastate", { data: myLastate, target: target });
943 // lastate was received, but maybe game wasn't ready yet:
944 processLastate: function() {
945 const data = this.lastate;
946 this.lastate = undefined; //security...
948 const oppCol = V.GetOppCol(this.game.mycolor);
949 if (!!data.rematchSent) {
950 if (this.game.rematchOffer != oppCol) {
951 // Opponent sended rematch offer while we were offline:
952 this.rematchOffer = "received";
955 { rematchOffer: oppCol }
960 if (this.game.rematchOffer == oppCol) {
961 // Opponent cancelled rematch offer while we were offline:
962 this.rematchOffer = "";
971 const L = this.game.moves.length;
972 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
973 this.game.clocks[oppIdx] = data.clock;
974 if (data.movesCount > L) {
975 // Just got last move from him
976 this.$refs["basegame"].play(data.lastMove, "received");
977 this.processMove(data.lastMove);
980 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
983 if (!!data.drawSent) this.drawOffer = "received";
986 if (this.game.score == "*")
987 this.gameOver(data.score, data.scoreMsg);
991 clickDraw: function() {
992 if (!this.game.mycolor || this.game.type == "import") return;
993 if (["received", "threerep"].includes(this.drawOffer)) {
994 if (!confirm(this.st.tr["Accept draw?"])) return;
996 this.drawOffer == "received"
998 : "Three repetitions";
999 this.send("draw", { data: message });
1000 this.gameOver("1/2", message);
1002 else if (this.drawOffer == "") {
1003 // No effect if drawOffer == "sent"
1004 if (this.game.mycolor != this.vr.turn) {
1005 alert(this.st.tr["Draw offer only in your turn"]);
1008 if (!confirm(this.st.tr["Offer draw?"])) return;
1009 this.drawOffer = "sent";
1010 this.send("drawoffer");
1011 if (this.game.type == "live") {
1014 { drawOffer: this.game.mycolor }
1017 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1020 addAndGotoLiveGame: function(gameInfo, callback) {
1021 const game = Object.assign(
1025 // (other) Game infos: constant
1026 fenStart: gameInfo.fen,
1027 vname: this.game.vname,
1028 created: Date.now(),
1029 // Game state (including FEN): will be updated
1031 clocks: [-1, -1], //-1 = unstarted
1036 GameStorage.add(game, (err) => {
1037 // No error expected.
1039 if (this.st.settings.sound)
1040 new Audio("/sounds/newgame.flac").play().catch(() => {});
1041 if (!!callback) callback();
1042 this.$router.push("/game/" + gameInfo.id);
1046 clickRematch: function() {
1047 if (!this.game.mycolor || this.game.type == "import") return;
1048 if (this.rematchOffer == "received") {
1049 // Start a new game!
1051 id: getRandString(), //ignored if corr
1052 fen: V.GenRandInitFen(this.game.randomness),
1053 randomness: this.game.randomness,
1054 players: [this.game.players[1], this.game.players[0]],
1056 cadence: this.game.cadence
1058 const notifyNewGame = () => {
1059 const oppsid = this.getOppsid(); //may be null
1060 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1061 // To main Hall if corr game:
1062 if (this.game.type == "corr")
1063 this.send("newgame", { data: gameInfo, page: "/" });
1064 // Also to MyGames page:
1065 this.notifyMyGames("newgame", gameInfo);
1067 if (this.game.type == "live")
1068 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1075 data: { gameInfo: gameInfo },
1076 success: (response) => {
1077 gameInfo.id = response.gameId;
1079 this.$router.push("/game/" + response.gameId);
1085 else if (this.rematchOffer == "") {
1086 this.rematchOffer = "sent";
1087 this.send("rematchoffer", { data: true });
1088 if (this.game.type == "live") {
1091 { rematchOffer: this.game.mycolor }
1094 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1096 else if (this.rematchOffer == "sent") {
1097 // Toggle rematch offer (on --> off)
1098 this.rematchOffer = "";
1099 this.send("rematchoffer", { data: false });
1100 if (this.game.type == "live") {
1103 { rematchOffer: '' }
1106 else this.updateCorrGame({ rematchOffer: 'n' });
1109 abortGame: function() {
1110 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1112 this.gameOver("?", "Stop");
1115 resign: function() {
1116 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1118 this.send("resign", { data: this.game.mycolor });
1119 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1120 const side = (this.game.mycolor == "w" ? "White" : "Black");
1121 this.gameOver(score, side + " surrender");
1123 loadGame: function(game, callback) {
1124 const gtype = game.type || this.getGameType(game);
1125 const tc = extractTime(game.cadence);
1126 const myIdx = game.players.findIndex(p => {
1128 p.sid == this.st.user.sid ||
1129 (!!p.name && p.id == this.st.user.id)
1132 // Sometimes the name isn't stored yet (TODO: why?)
1136 !game.players[myIdx].name &&
1139 game.players[myIdx].name = this.st.user.name;
1142 { playerName: { idx: myIdx, name: this.st.user.name } }
1145 // "mycolor" is undefined for observers
1146 const mycolor = [undefined, "w", "b"][myIdx + 1];
1147 if (gtype == "corr") {
1148 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1149 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1150 // NOTE: clocks in seconds
1151 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1152 game.clocks = [tc.mainTime, tc.mainTime];
1153 const L = game.moves.length;
1154 if (game.score == "*") {
1157 game.clocks[L % 2] -=
1158 (Date.now() - game.moves[L-1].played) / 1000;
1161 // Now that we used idx and played, re-format moves as for live games
1162 game.moves = game.moves.map(m => m.squares);
1164 else if (gtype == "live") {
1165 if (game.clocks[0] < 0) {
1166 // Game is unstarted. clock is ignored until move 2
1167 game.clocks = [tc.mainTime, tc.mainTime];
1169 // I play in this live game
1172 { clocks: game.clocks }
1176 else if (!!game.initime)
1177 // It's my turn: clocks not updated yet
1178 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1181 // gtype == "import"
1182 game.clocks = [tc.mainTime, tc.mainTime];
1183 // Live games before 26/03/2020 don't have chat history:
1184 if (!game.chats) game.chats = []; //TODO: remove line
1185 // Sort chat messages from newest to oldest
1186 game.chats.sort((c1, c2) => c2.added - c1.added);
1189 game.chats.length > 0 &&
1190 (!game.chatRead || game.chatRead < game.chats[0].added)
1192 // A chat message arrived since my last reading:
1193 document.getElementById("chatBtn").classList.add("somethingnew");
1195 // TODO: merge next 2 "if" conditions
1196 if (!!game.drawOffer) {
1197 if (game.drawOffer == "t")
1198 // Three repetitions
1199 this.drawOffer = "threerep";
1201 // Draw offered by any of the players:
1202 if (myIdx < 0) this.drawOffer = "received";
1204 // I play in this game:
1206 (game.drawOffer == "w" && myIdx == 0) ||
1207 (game.drawOffer == "b" && myIdx == 1)
1209 this.drawOffer = "sent";
1210 else this.drawOffer = "received";
1214 if (!!game.rematchOffer) {
1215 if (myIdx < 0) this.rematchOffer = "received";
1217 // I play in this game:
1219 (game.rematchOffer == "w" && myIdx == 0) ||
1220 (game.rematchOffer == "b" && myIdx == 1)
1222 this.rematchOffer = "sent";
1224 else this.rematchOffer = "received";
1227 this.repeat = {}; //reset: scan past moves' FEN:
1229 this.vr = new V(game.fenStart);
1231 game.moves.forEach(m => {
1232 playMove(m, this.vr);
1233 const fenIdx = this.vr.getFenForRepeat();
1234 this.repeat[fenIdx] = this.repeat[fenIdx]
1235 ? this.repeat[fenIdx] + 1
1238 // Imported games don't have current FEN
1239 if (!game.fen) game.fen = this.vr.getFen();
1240 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1241 this.game = Object.assign(
1242 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1245 increment: tc.increment,
1247 // opponent sid not strictly required (or available), but easier
1248 // at least oppsid or oppid is available anyway:
1249 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1250 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1254 this.$refs["basegame"].re_setVariables(this.game);
1256 this.gotMoveIdx = game.moves.length - 1;
1257 // If we arrive here after 'nextGame' action, the board might be hidden
1258 let boardDiv = document.querySelector(".game");
1259 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1260 boardDiv.style.visibility = "visible";
1261 this.re_setClocks();
1262 this.$nextTick(() => {
1263 this.game.rendered = true;
1264 // Did lastate arrive before game was rendered?
1265 if (!!this.lastate) this.processLastate();
1267 if (this.lastateAsked) {
1268 this.lastateAsked = false;
1269 this.sendLastate(game.oppsid);
1271 if (!!callback) callback();
1273 loadVariantThenGame: async function(game, callback) {
1274 await import("@/variants/" + game.vname + ".js")
1275 .then((vModule) => {
1276 window.V = vModule[game.vname + "Rules"];
1277 this.loadGame(game, callback);
1282 "raw-loader!@/translations/rules/" +
1283 game.vname + "/" + this.st.lang + ".pug"
1285 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1287 // 3 cases for loading a game:
1288 // - from indexedDB (running or completed live game I play)
1289 // - from server (one correspondance game I play[ed] or not)
1290 // - from remote peer (one live game I don't play, finished or not)
1291 fetchGame: function(callback) {
1293 Number.isInteger(this.gameRef) ||
1294 !isNaN(parseInt(this.gameRef, 10))
1296 // corr games identifiers are integers
1301 data: { gid: this.gameRef },
1303 res.game.moves.forEach(m => {
1304 m.squares = JSON.parse(m.squares);
1311 else if (!!this.gameRef.match(/^i/))
1312 // Game import (maybe remote)
1313 ImportgameStorage.get(this.gameRef, callback);
1315 // Local live game (or remote)
1316 GameStorage.get(this.gameRef, callback);
1318 re_setClocks: function() {
1319 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1320 if (this.game.moves.length < 2 || this.game.score != "*") {
1321 // 1st move not completed yet, or game over: freeze time
1324 const currentTurn = this.vr.turn;
1325 const currentMovesCount = this.game.moves.length;
1326 const colorIdx = ["w", "b"].indexOf(currentTurn);
1327 this.clockUpdate = setInterval(
1330 this.game.clocks[colorIdx] < 0 ||
1331 this.game.moves.length > currentMovesCount ||
1332 this.game.score != "*"
1334 clearInterval(this.clockUpdate);
1335 this.clockUpdate = null;
1336 if (this.game.clocks[colorIdx] < 0)
1338 currentTurn == "w" ? "0-1" : "1-0",
1346 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1353 // Update variables and storage after a move:
1354 processMove: function(move, data) {
1355 if (this.game.type == "import")
1356 // Shouldn't receive any messages in this mode:
1358 if (!data) data = {};
1359 const moveCol = this.vr.turn;
1360 const colorIdx = ["w", "b"].indexOf(moveCol);
1361 const nextIdx = 1 - colorIdx;
1362 const doProcessMove = () => {
1363 const origMovescount = this.game.moves.length;
1364 // The move is (about to be) played: stop clock
1365 clearInterval(this.clockUpdate);
1366 this.clockUpdate = null;
1367 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1368 if (this.drawOffer == "received")
1370 this.drawOffer = "";
1371 if (this.game.type == "live" && origMovescount >= 2) {
1372 this.game.clocks[colorIdx] += this.game.increment;
1373 // For a correct display in casqe of disconnected opponent:
1377 ppt(this.game.clocks[colorIdx]).split(':')
1379 GameStorage.update(this.gameRef, {
1380 // It's not my turn anymore:
1385 // Update current game object:
1386 playMove(move, this.vr);
1388 // Received move, score is computed in BaseGame, but maybe not yet.
1389 // ==> Compute it here, although this is redundant (TODO)
1390 data.score = this.vr.getCurrentScore();
1391 if (data.score != "*") this.gameOver(data.score);
1392 this.game.moves.push(move);
1393 this.game.fen = this.vr.getFen();
1394 if (this.game.type == "corr") {
1395 // In corr games, just reset clock to mainTime:
1396 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1398 // If repetition detected, consider that a draw offer was received:
1399 const fenObj = this.vr.getFenForRepeat();
1400 this.repeat[fenObj] =
1401 !!this.repeat[fenObj]
1402 ? this.repeat[fenObj] + 1
1404 if (this.repeat[fenObj] >= 3) {
1405 if (V.LoseOnRepetition)
1406 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1407 else this.drawOffer = "threerep";
1409 else if (this.drawOffer == "threerep") this.drawOffer = "";
1410 if (!!this.game.mycolor && !data.receiveMyMove) {
1411 // NOTE: 'var' to see that variable outside this block
1412 var filtered_move = getFilteredMove(move);
1414 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1415 // Notify turn on MyGames page:
1424 // Since corr games are stored at only one location, update should be
1425 // done only by one player for each move:
1427 this.game.type == "live" &&
1428 !!this.game.mycolor &&
1429 moveCol != this.game.mycolor &&
1430 this.game.moves.length >= 2
1432 // Receive a move: update initime
1433 this.game.initime = Date.now();
1434 GameStorage.update(this.gameRef, {
1435 // It's my turn now!
1436 initime: this.game.initime
1440 !!this.game.mycolor &&
1441 !data.receiveMyMove &&
1442 (this.game.type == "live" || moveCol == this.game.mycolor)
1445 switch (this.drawOffer) {
1450 drawCode = this.game.mycolor;
1453 drawCode = V.GetOppCol(this.game.mycolor);
1456 if (this.game.type == "corr") {
1457 // corr: only move, fen and score
1458 this.updateCorrGame({
1461 squares: filtered_move,
1464 // Code "n" for "None" to force reset (otherwise it's ignored)
1465 drawOffer: drawCode || "n"
1469 const updateStorage = () => {
1470 GameStorage.update(this.gameRef, {
1472 move: filtered_move,
1473 moveIdx: origMovescount,
1474 clocks: this.game.clocks,
1478 // The active tab can update storage immediately
1479 if (this.focus) updateStorage();
1480 // Small random delay otherwise
1481 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1484 // Send move ("newmove" event) to people in the room (if our turn)
1485 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1487 move: filtered_move,
1488 index: origMovescount,
1489 // color is required to check if this is my move
1490 // (if several tabs opened)
1492 cancelDrawOffer: this.drawOffer == ""
1494 if (this.game.type == "live")
1495 sendMove["clock"] = this.game.clocks[colorIdx];
1496 // (Live) Clocks will re-start when the opponent pingback arrive
1497 this.opponentGotMove = false;
1498 this.send("newmove", {data: sendMove});
1499 // If the opponent doesn't reply gotmove soon enough, re-send move:
1500 // Do this at most 2 times, because more would mean network issues,
1501 // opponent would then be expected to disconnect/reconnect.
1503 const currentUrl = document.location.href;
1504 this.retrySendmove = setInterval(
1508 this.opponentGotMove ||
1509 document.location.href != currentUrl //page change
1511 clearInterval(this.retrySendmove);
1514 const oppsid = this.getOppsid();
1516 // Opponent is disconnected: he'll ask last state
1517 clearInterval(this.retrySendmove);
1519 this.send("newmove", { data: sendMove, target: oppsid });
1527 // Not my move or I'm an observer: just start other player's clock
1528 this.re_setClocks();
1531 this.game.type == "corr" &&
1532 moveCol == this.game.mycolor &&
1535 let boardDiv = document.querySelector(".game");
1536 const afterSetScore = () => {
1538 if (this.st.settings.gotonext && this.nextIds.length > 0)
1539 this.showNextGame();
1541 // The board might have been hidden:
1542 if (boardDiv.style.visibility == "hidden")
1543 boardDiv.style.visibility = "visible";
1544 if (data.score == "*") this.re_setClocks();
1547 if (!V.CorrConfirm) {
1551 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1552 // We may play several moves in a row: in case of, remove listener:
1553 let elClone = el.cloneNode(true);
1554 el.parentNode.replaceChild(elClone, el);
1555 elClone.addEventListener(
1558 document.getElementById("modalConfirm").checked = false;
1559 if (!!data.score && data.score != "*")
1561 this.gameOver(data.score, null, afterSetScore);
1562 else afterSetScore();
1565 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1566 const arMove = (Array.isArray(move) ? move : [move]);
1567 for (let i = 0; i < arMove.length; i++)
1568 V.PlayOnBoard(this.vr.board, arMove[i]);
1569 const position = this.vr.getBaseFen();
1570 for (let i = arMove.length - 1; i >= 0; i--)
1571 V.UndoOnBoard(this.vr.board, arMove[i]);
1572 if (["all","byrow"].includes(V.ShowMoves)) {
1573 this.curDiag = getDiagram({
1575 orientation: V.CanFlip ? this.game.mycolor : "w"
1577 document.querySelector("#confirmDiv > .card").style.width =
1578 boardDiv.offsetWidth + "px";
1581 // Incomplete information: just ask confirmation
1582 // Hide the board, because otherwise it could reveal infos
1583 boardDiv.style.visibility = "hidden";
1584 this.moveNotation = getFullNotation(move);
1586 document.getElementById("modalConfirm").checked = true;
1590 if (!!data.score && data.score != "*")
1591 this.gameOver(data.score, null, doProcessMove);
1592 else doProcessMove();
1595 cancelMove: function() {
1596 let boardDiv = document.querySelector(".game");
1597 if (boardDiv.style.visibility == "hidden")
1598 boardDiv.style.visibility = "visible";
1599 document.getElementById("modalConfirm").checked = false;
1600 this.$refs["basegame"].cancelLastMove();
1602 // In corr games, callback to change page only after score is set:
1603 gameOver: function(score, scoreMsg, callback) {
1604 this.game.score = score;
1605 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1606 this.game.scoreMsg = scoreMsg;
1607 document.getElementById("modalRules").checked = false;
1608 // Display result in a un-missable way:
1609 document.getElementById("modalScore").checked = true;
1610 this.$set(this.game, "scoreMsg", scoreMsg);
1611 const myIdx = this.game.players.findIndex(p => {
1613 p.sid == this.st.user.sid ||
1614 (!!p.name && p.id == this.st.user.id)
1618 // OK, I play in this game
1623 if (this.game.type == "live") {
1624 GameStorage.update(this.gameRef, scoreObj);
1625 // Notify myself locally if I'm elsewhere:
1629 { body: score + " : " + scoreMsg }
1632 if (!!callback) callback();
1634 else this.updateCorrGame(scoreObj, callback);
1635 // Notify the score to main Hall.
1636 // TODO: only one player (currently double send)
1637 this.send("result", { gid: this.game.id, score: score });
1638 // Also to MyGames page (TODO: doubled as well...)
1647 else if (!!callback) callback();
1653 <style lang="sass" scoped>
1654 #scoreDiv > .card, #rematchDiv > .card
1662 @media screen and (max-width: 1500px)
1664 @media screen and (max-width: 1024px)
1666 @media screen and (max-width: 767px)
1676 background-color: lightgreen
1688 @media screen and (max-width: 767px)
1693 display: inline-block
1697 display: inline-block
1699 display: inline-flex
1703 @media screen and (max-width: 767px)
1712 @media screen and (max-width: 767px)
1724 background-color: #edda99
1726 display: inline-block
1730 display: inline-block
1737 @media screen and (max-width: 767px)
1739 display: inline-block
1752 animation: blink-animation 2s steps(3, start) infinite
1753 @keyframes blink-animation
1758 display: inline-block
1770 .draw-sent, .draw-sent:hover
1771 background-color: lightyellow
1773 .draw-received, .draw-received:hover
1774 background-color: #73C6B6
1776 .draw-threerep, .draw-threerep:hover
1777 background-color: #D2B4DE
1779 .rematch-sent, .rematch-sent:hover
1780 background-color: lightyellow
1782 .rematch-received, .rematch-received:hover
1783 background-color: #48C9B0
1786 background-color: #D2B4DE
1799 background-color: lightgreen
1801 background-color: red
1804 color: var(--card-fore-color)
1807 font-size: calc(1rem * var(--heading-ratio))
1809 margin: calc(1.5 * var(--universal-margin))
1813 @import "@/styles/_rules.sass"
1814 @import "@/styles/_board_squares_img.sass"