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 // TODO: this will be a component instead ?
183 // If simultaneous games, no "rematch" button
185 // simult : open connexion to rooms from list, in all (if I'm the "simultaneer" --> TODO: indicate sid + side [random,white, black] in challenge)
186 // if I'm just one of the players (one game), just one game.
187 // view "Game_s", with pug list of components Game.
188 // generally only one element, unless I'm the simultaneer.
191 import BaseGame from "@/components/BaseGame.vue";
192 import UserBio from "@/components/UserBio.vue";
193 import Chat from "@/components/Chat.vue";
194 import { store } from "@/store";
195 import { GameStorage } from "@/utils/gameStorage";
196 import { ImportgameStorage } from "@/utils/importgameStorage";
197 import { ppt } from "@/utils/datetime";
198 import { notify } from "@/utils/notifications";
199 import { ajax } from "@/utils/ajax";
200 import { extractTime } from "@/utils/timeControl";
201 import { getRandString } from "@/utils/alea";
202 import { getScoreMessage } from "@/utils/scoring";
203 import { getFullNotation } from "@/utils/notation";
204 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
205 import { processModalClick } from "@/utils/modalClick";
206 import { playMove, getFilteredMove } from "@/utils/playUndo";
207 import { ArrayFun } from "@/utils/array";
208 import params from "@/parameters";
219 // gameRef can point to a corr game, local game or remote live game
222 game: {}, //passed to BaseGame
223 focus: !document.hidden, //will not always work... TODO
224 // virtualClocks will be initialized from true game.clocks
225 // TODO: clock update triggers re-rendering. Should be out of Vue
227 vr: null, //"variant rules" object initialized from FEN
233 people: {}, //players + observers
234 lastate: undefined, //used if opponent send lastate before game is ready
235 repeat: {}, //detect position repetition
236 curDiag: "", //for corr moves confirmation
238 roomInitialized: false,
239 // If asklastate got no reply, ask again:
241 gotMoveIdx: -1, //last move index received
242 // If newmove got no pingback, send again:
243 opponentGotMove: false,
245 socketCloseListener: 0,
246 // Incomplete info games: show move played
248 // Intervals from setInterval():
252 // Related to (killing of) self multi-connects:
257 $route: function(to, from) {
258 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
260 this.cleanBeforeDestroy();
261 else if (from.params["id"] != to.params["id"]) {
262 // Change everything:
263 this.cleanBeforeDestroy();
264 let boardDiv = document.querySelector(".game");
266 // In case of incomplete information variant:
267 boardDiv.style.visibility = "hidden";
272 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
275 // NOTE: some redundant code with Hall.vue (mostly related to people array)
276 created: function() {
279 mounted: function() {
280 document.getElementById("chatWrap")
281 .addEventListener("click", (e) => {
282 processModalClick(e, () => {
283 this.toggleChat("close")
286 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
288 document.getElementById(eltName)
289 .addEventListener("click", processModalClick);
293 beforeDestroy: function() {
294 this.cleanBeforeDestroy();
297 cleanBeforeDestroy: function() {
298 clearInterval(this.socketCloseListener);
299 document.removeEventListener('visibilitychange', this.visibilityChange);
300 window.removeEventListener('focus', this.onFocus);
301 window.removeEventListener('blur', this.onBlur);
302 if (!!this.askLastate) clearInterval(this.askLastate);
303 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
304 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
305 this.conn.removeEventListener("message", this.socketMessageListener);
306 this.send("disconnect");
309 visibilityChange: function() {
310 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
311 this.focus = (document.visibilityState == "visible");
312 this.send(this.focus ? "getfocus" : "losefocus");
314 onFocus: function() {
316 this.send("getfocus");
320 this.send("losefocus");
322 isLargeScreen: function() {
323 return window.innerWidth >= 768;
325 btnTooltipClass: function(thing) {
327 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
330 { tooltip: !("ontouchstart" in window) },
335 someAnonymousPresent: function() {
337 Object.values(this.people).some(p =>
338 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
342 atCreation: function() {
343 document.addEventListener('visibilitychange', this.visibilityChange);
344 window.addEventListener('focus', this.onFocus);
345 window.addEventListener('blur', this.onBlur);
346 // 0] (Re)Set variables
347 this.gameRef = this.$route.params["id"];
348 // next = next corr games IDs to navigate faster (if applicable)
349 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
350 // Always add myself to players' list
351 const my = this.st.user;
352 const tmpId = getRandString();
360 tmpId: { focus: true }
365 players: [{ name: "" }, { name: "" }],
369 let chatComp = this.$refs["chatcomp"];
370 if (!!chatComp) chatComp.chats = [];
371 this.virtualClocks = [[0,0], [0,0]];
373 this.rulesContent = "";
375 this.lastateAsked = false;
376 this.rematchOffer = "";
377 this.lastate = undefined;
378 this.roomInitialized = false;
379 this.gotLastate = false;
380 this.gotMoveIdx = -1;
381 this.opponentGotMove = false;
382 this.askLastate = null;
383 this.retrySendmove = null;
384 this.clockUpdate = null;
385 this.newConnect = {};
386 // 1] Initialize connection
387 this.connexionString =
389 "/?sid=" + this.st.user.sid +
390 "&id=" + this.st.user.id +
393 // Discard potential "/?next=[...]" for page indication:
394 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
395 this.conn = new WebSocket(this.connexionString);
396 this.conn.addEventListener("message", this.socketMessageListener);
397 this.socketCloseListener = setInterval(
399 if (this.conn.readyState == 3) {
400 this.conn.removeEventListener(
401 "message", this.socketMessageListener);
402 this.conn = new WebSocket(this.connexionString);
403 this.conn.addEventListener("message", this.socketMessageListener);
408 // Socket init required before loading remote game:
409 const socketInit = callback => {
410 if (this.conn.readyState == 1)
414 // Socket not ready yet (initial loading)
415 // NOTE: first arg is Websocket object, unused here:
416 this.conn.onopen = () => callback();
418 this.fetchGame((game) => {
420 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
422 // Live game stored remotely: need socket to retrieve it
423 // NOTE: the callback "roomInit" will be lost, so it's not provided.
424 // --> It will be given when receiving "fullgame" socket event.
425 socketInit(() => { this.send("askfullgame"); });
428 roomInit: function() {
429 if (!this.roomInitialized) {
430 // Notify the room only now that I connected, because
431 // messages might be lost otherwise (if game loading is slow)
432 this.send("connect");
433 this.send("pollclients");
434 // We may ask fullgame several times if some moves are lost,
435 // but room should be init only once:
436 this.roomInitialized = true;
439 send: function(code, obj) {
440 if (!!this.conn && this.conn.readyState == 1)
441 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
443 isConnected: function(index) {
444 const player = this.game.players[index];
445 // Is it me ? In this case no need to bother with focus
447 this.st.user.sid == player.sid ||
448 (!!player.name && this.st.user.id == player.id)
450 // Still have to check for name (because of potential multi-accounts
451 // on same browser, although this should be rare...)
452 return (!this.st.user.name || this.st.user.name == player.name);
454 // Try to find a match in people:
458 Object.keys(this.people).some(sid => {
461 Object.values(this.people[sid].tmpIds).some(v => v.focus)
468 Object.values(this.people).some(p => {
471 Object.values(p.tmpIds).some(v => v.focus)
477 getOppsid: function() {
478 let oppsid = this.game.oppsid;
480 oppsid = Object.keys(this.people).find(
481 sid => this.people[sid].id == this.game.oppid
484 // oppsid is useful only if opponent is online:
485 if (!!oppsid && !!this.people[oppsid]) return oppsid;
488 // NOTE: action if provided is always a closing action
489 toggleChat: function(action) {
490 if (!action && document.getElementById("modalChat").checked)
492 document.getElementById("inputChat").focus();
494 document.getElementById("chatBtn").classList.remove("somethingnew");
495 if (!!this.game.mycolor) {
496 // Update "chatRead" variable either on server or locally
497 if (this.game.type == "corr")
498 this.updateCorrGame({ chatRead: this.game.mycolor });
499 else if (this.game.type == "live")
500 GameStorage.update(this.gameRef, { chatRead: true });
504 processChat: function(chat) {
505 this.send("newchat", { data: chat });
506 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
507 if (!!this.game.mycolor) {
508 if (this.game.type == "corr")
509 this.updateCorrGame({ chat: chat });
512 chat.added = Date.now();
513 GameStorage.update(this.gameRef, { chat: chat });
517 clearChat: function() {
518 if (!!this.game.mycolor) {
519 if (this.game.type == "corr") {
523 { data: { gid: this.game.id } }
527 GameStorage.update(this.gameRef, { delchat: true });
529 this.$set(this.game, "chats", []);
532 getGameType: function(game) {
533 if (!!game.id.toString().match(/^i/)) return "import";
535 game.cadence.indexOf("d") >= 0
537 : (game.cadence.indexOf("/") >= 0 ? "simul" : "live")
540 // Notify something after a new move (to opponent and me on MyGames page)
541 notifyMyGames: function(thing, data) {
546 targets: this.game.players.map(p => {
547 return { sid: p.sid, id: p.id };
552 showNextGame: function() {
553 // Did I play in current game? If not, add it to nextIds list
554 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
555 this.nextIds.unshift(this.game.id);
556 const nextGid = this.nextIds.pop();
558 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
560 socketMessageListener: function(msg) {
561 if (!this.conn) return;
562 const data = JSON.parse(msg.data);
565 // TODO: shuffling and random filtering on server,
566 // if the room is really crowded.
567 Object.keys(data.sockIds).forEach(sid => {
568 if (sid != this.st.user.sid) {
569 this.send("askidentity", { target: sid });
570 this.people[sid] = { tmpIds: data.sockIds[sid] };
573 // Complete my tmpIds:
574 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
579 if (!this.people[data.from[0]]) {
580 // focus depends on the tmpId (e.g. tab)
586 [data.from[1]]: { focus: true }
590 // For self multi-connects tests:
591 this.newConnect[data.from[0]] = true;
592 this.send("askidentity", { target: data.from[0] });
594 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
595 this.$forceUpdate(); //TODO: shouldn't be required
599 if (!this.people[data.from[0]]) return;
600 delete this.people[data.from[0]].tmpIds[data.from[1]];
601 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
602 this.$delete(this.people, data.from[0]);
603 else this.$forceUpdate(); //TODO: shouldn't be required
606 let player = this.people[data.from[0]];
608 player.tmpIds[data.from[1]].focus = true;
609 this.$forceUpdate(); //TODO: shouldn't be required
614 let player = this.people[data.from[0]];
616 player.tmpIds[data.from[1]].focus = false;
617 this.$forceUpdate(); //TODO: shouldn't be required
621 case "askidentity": {
622 // Request for identification
624 // Decompose to avoid revealing email
625 name: this.st.user.name,
626 sid: this.st.user.sid,
629 this.send("identity", { data: me, target: data.from });
633 const user = data.data;
634 let player = this.people[user.sid];
635 // player.tmpIds is already set
636 player.name = user.name;
638 if (this.game.type == "live") {
640 this.game.players.findIndex(p => p.sid == this.st.user.sid);
641 // Sometimes a player name isn't stored yet (TODO: why?)
644 !this.game.players[1 - myGidx].name &&
645 this.game.players[1 - myGidx].sid == user.sid &&
648 this.game.players[1-myGidx].name = user.name;
651 { playerName: { idx: 1 - myGidx, name: user.name } }
655 this.$forceUpdate(); //TODO: shouldn't be required
656 // If I multi-connect, kill current connexion if no mark (I'm older)
657 if (this.newConnect[user.sid]) {
658 delete this.newConnect[user.sid];
661 user.id == this.st.user.id &&
662 user.sid != this.st.user.sid
664 this.cleanBeforeDestroy();
665 alert(this.st.tr["New connexion detected: tab now offline"]);
669 // Ask potentially missed last state, if opponent and I play
672 !!this.game.mycolor &&
673 this.game.type == "live" &&
674 this.game.players.some(p => p.sid == user.sid)
676 this.send("asklastate", { target: user.sid });
678 this.askLastate = setInterval(
680 // Ask at most 3 times:
681 // if no reply after that there should be a network issue.
685 !!this.people[user.sid]
687 this.send("asklastate", { target: user.sid });
690 clearInterval(this.askLastate);
699 // Send current (live or import) game,
700 // if not asked by any of the players
702 this.game.type != "corr" &&
703 this.game.players.every(p => p.sid != data.from[0])
707 // FEN is current position, unused for now
709 players: this.game.players,
711 cadence: this.game.cadence,
712 score: this.game.score
714 this.send("game", { data: myGame, target: data.from });
718 const gameToSend = Object.keys(this.game)
721 "id","fen","players","vid","cadence","fenStart","vname",
722 "moves","clocks","score","drawOffer","rematchOffer"
726 obj[k] = this.game[k];
731 this.send("fullgame", { data: gameToSend, target: data.from });
734 if (!!data.data.empty) {
735 alert(this.st.tr["The game should be in another tab"]);
739 // Callback "roomInit" to poll clients only after game is loaded
740 this.loadVariantThenGame(data.data, this.roomInit);
743 // Sending informative last state if I played a move or score != "*"
744 // If the game or moves aren't loaded yet, delay the sending:
745 // TODO: socket init after game load, so the game is supposedly ready
746 if (!this.game || !this.game.moves) this.lastateAsked = true;
747 else this.sendLastate(data.from);
749 // TODO: possible bad scenario: reload page while oppponent sends a
750 // move => get both lastate and newmove, process both, add move twice.
751 // Confirm scenario? Fix?
753 // Got opponent infos about last move
754 this.gotLastate = true;
755 this.lastate = data.data;
756 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
757 this.gotMoveIdx = this.lastate.movesCount - 1;
758 if (this.game.rendered)
759 // Game is rendered (Board component)
760 this.processLastate();
761 // Else: will be processed when game is ready
767 console.log("Receive move");
768 console.log(data.data);
769 //moveslist not updated when receiving a move? (see in baseGame)
771 const movePlus = data.data;
772 const movesCount = this.game.moves.length;
774 movePlus.index < movesCount ||
775 this.gotMoveIdx >= movePlus.index
777 // Opponent re-send but we already have the move:
778 // (maybe he didn't receive our pingback...)
779 this.send("gotmove", {data: movePlus.index, target: data.from});
782 this.gotMoveIdx = movePlus.index;
783 const receiveMyMove = (movePlus.color == this.game.mycolor);
784 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
785 if (!receiveMyMove && !!this.game.mycolor) {
786 // Notify opponent that I got the move:
789 { data: movePlus.index, target: data.from }
791 // And myself if I'm elsewhere:
797 (this.game.players[moveColIdx].name || "@nonymous") +
803 if (movePlus.cancelDrawOffer) {
804 // Opponent refuses draw
806 // NOTE for corr games: drawOffer reset by player in turn
808 this.game.type == "live" &&
809 !!this.game.mycolor &&
812 GameStorage.update(this.gameRef, { drawOffer: "" });
815 this.$refs["basegame"].play(movePlus.move, "received");
816 // Freeze time while the move is being play
817 // (TODO: a callback would be cleaner here)
818 clearInterval(this.clockUpdate);
819 this.clockUpdate = null;
820 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
821 // 250 = length of animation, 500 = delay between sub-moves
823 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
824 // Incomplete information: no move animation
828 this.game.clocks[moveColIdx] = movePlus.clock;
831 { receiveMyMove: receiveMyMove }
840 this.opponentGotMove = true;
841 // Now his clock starts running on my side:
842 const oppIdx = ['w','b'].indexOf(this.vr.turn);
843 // NOTE: next line to avoid multi-resetClocks when several tabs
844 // on same game, resulting in a faster countdown.
845 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
850 const score = (data.data == "b" ? "1-0" : "0-1");
851 const side = (data.data == "w" ? "White" : "Black");
852 this.gameOver(score, side + " surrender");
855 this.gameOver("?", "Stop");
858 this.gameOver("1/2", data.data);
861 // NOTE: observers don't know who offered draw
862 this.drawOffer = "received";
863 if (!!this.game.mycolor && this.game.type == "live") {
866 { drawOffer: V.GetOppCol(this.game.mycolor) }
871 // NOTE: observers don't know who offered rematch
872 this.rematchOffer = data.data ? "received" : "";
873 if (!!this.game.mycolor && this.game.type == "live") {
876 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
881 // A game started, redirect if I'm playing in
882 const gameInfo = data.data;
883 const gameType = this.getGameType(gameInfo);
885 gameType == "live" &&
886 gameInfo.players.some(p => p.sid == this.st.user.sid)
888 this.addAndGotoLiveGame(gameInfo);
890 gameType == "corr" &&
891 this.st.user.id > 0 &&
892 gameInfo.players.some(p => p.id == this.st.user.id)
894 this.$router.push("/game/" + gameInfo.id);
896 this.rematchId = gameInfo.id;
897 document.getElementById("modalRules").checked = false;
898 document.getElementById("modalScore").checked = false;
899 document.getElementById("modalRematch").checked = true;
904 let chat = data.data;
905 this.$refs["chatcomp"].newChat(chat);
906 if (this.game.type == "live") {
907 chat.added = Date.now();
908 if (!!this.game.mycolor)
909 GameStorage.update(this.gameRef, { chat: chat });
911 if (!document.getElementById("modalChat").checked)
912 document.getElementById("chatBtn").classList.add("somethingnew");
917 updateCorrGame: function(obj, callback) {
927 if (!!callback) callback();
932 sendLastate: function(target) {
933 // Send our "last state" informations to opponent
934 const L = this.game.moves.length;
935 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
938 (L > 0 && this.vr.turn != this.game.mycolor)
939 ? this.game.moves[L - 1]
941 clock: this.game.clocks[myIdx],
942 // Since we played a move (or abort or resign),
943 // only drawOffer=="sent" is possible
944 drawSent: this.drawOffer == "sent" ? true : undefined,
945 rematchSent: this.rematchOffer == "sent" ? true : undefined,
946 score: this.game.score != "*" ? this.game.score : undefined,
947 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
950 this.send("lastate", { data: myLastate, target: target });
952 // lastate was received, but maybe game wasn't ready yet:
953 processLastate: function() {
954 const data = this.lastate;
955 this.lastate = undefined; //security...
957 const oppCol = V.GetOppCol(this.game.mycolor);
958 if (!!data.rematchSent) {
959 if (this.game.rematchOffer != oppCol) {
960 // Opponent sended rematch offer while we were offline:
961 this.rematchOffer = "received";
964 { rematchOffer: oppCol }
969 if (this.game.rematchOffer == oppCol) {
970 // Opponent cancelled rematch offer while we were offline:
971 this.rematchOffer = "";
980 const L = this.game.moves.length;
981 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
982 this.game.clocks[oppIdx] = data.clock;
983 if (data.movesCount > L) {
984 // Just got last move from him
985 this.$refs["basegame"].play(data.lastMove, "received");
986 this.processMove(data.lastMove);
988 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
991 if (!!data.drawSent) this.drawOffer = "received";
994 if (this.game.score == "*")
995 this.gameOver(data.score, data.scoreMsg);
999 clickDraw: function() {
1000 if (!this.game.mycolor || this.game.type == "import") return;
1001 if (["received", "threerep"].includes(this.drawOffer)) {
1002 if (!confirm(this.st.tr["Accept draw?"])) return;
1004 this.drawOffer == "received"
1005 ? "Mutual agreement"
1006 : "Three repetitions";
1007 this.send("draw", { data: message });
1008 this.gameOver("1/2", message);
1009 } else if (this.drawOffer == "") {
1010 // No effect if drawOffer == "sent"
1011 if (this.game.mycolor != this.vr.turn) {
1012 alert(this.st.tr["Draw offer only in your turn"]);
1015 if (!confirm(this.st.tr["Offer draw?"])) return;
1016 this.drawOffer = "sent";
1017 this.send("drawoffer");
1018 if (this.game.type == "live") {
1021 { drawOffer: this.game.mycolor }
1023 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1026 addAndGotoLiveGame: function(gameInfo, callback) {
1027 const game = Object.assign(
1031 // (other) Game infos: constant
1032 fenStart: gameInfo.fen,
1033 vname: this.game.vname,
1034 created: Date.now(),
1035 // Game state (including FEN): will be updated
1037 clocks: [-1, -1], //-1 = unstarted
1042 GameStorage.add(game, (err) => {
1043 // No error expected.
1045 if (this.st.settings.sound)
1046 new Audio("/sounds/newgame.flac").play().catch(() => {});
1047 if (!!callback) callback();
1048 this.$router.push("/game/" + gameInfo.id);
1052 clickRematch: function() {
1053 if (!this.game.mycolor || this.game.type == "import") return;
1054 if (this.rematchOffer == "received") {
1055 // Start a new game!
1057 id: getRandString(), //ignored if corr
1058 fen: V.GenRandInitFen(this.game.randomness),
1059 randomness: this.game.randomness,
1060 players: [this.game.players[1], this.game.players[0]],
1062 cadence: this.game.cadence
1064 const notifyNewGame = () => {
1065 const oppsid = this.getOppsid(); //may be null
1066 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1067 // To main Hall if corr game:
1068 if (this.game.type == "corr")
1069 this.send("newgame", { data: gameInfo, page: "/" });
1070 // Also to MyGames page:
1071 this.notifyMyGames("newgame", gameInfo);
1073 if (this.game.type == "live")
1074 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1081 data: { gameInfo: gameInfo },
1082 success: (response) => {
1083 gameInfo.id = response.gameId;
1085 this.$router.push("/game/" + response.gameId);
1090 } else if (this.rematchOffer == "") {
1091 this.rematchOffer = "sent";
1092 this.send("rematchoffer", { data: true });
1093 if (this.game.type == "live") {
1096 { rematchOffer: this.game.mycolor }
1098 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1099 } else if (this.rematchOffer == "sent") {
1100 // Toggle rematch offer (on --> off)
1101 this.rematchOffer = "";
1102 this.send("rematchoffer", { data: false });
1103 if (this.game.type == "live") {
1106 { rematchOffer: '' }
1108 } else this.updateCorrGame({ rematchOffer: 'n' });
1111 abortGame: function() {
1112 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1114 this.gameOver("?", "Stop");
1117 resign: function() {
1118 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1120 this.send("resign", { data: this.game.mycolor });
1121 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1122 const side = (this.game.mycolor == "w" ? "White" : "Black");
1123 this.gameOver(score, side + " surrender");
1125 loadGame: function(game, callback) {
1126 const gtype = game.type || this.getGameType(game);
1127 const tc = extractTime(game.cadence);
1128 const myIdx = game.players.findIndex(p => {
1130 p.sid == this.st.user.sid ||
1131 (!!p.name && p.id == this.st.user.id)
1134 // Sometimes the name isn't stored yet (TODO: why?)
1138 !game.players[myIdx].name &&
1141 game.players[myIdx].name = this.st.user.name;
1144 { playerName: { idx: myIdx, name: this.st.user.name } }
1147 // "mycolor" is undefined for observers
1148 const mycolor = [undefined, "w", "b"][myIdx + 1];
1149 if (gtype == "corr") {
1150 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1151 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1152 // NOTE: clocks in seconds
1153 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1154 game.clocks = [tc.mainTime, tc.mainTime];
1155 const L = game.moves.length;
1156 if (game.score == "*") {
1159 game.clocks[L % 2] -=
1160 (Date.now() - game.moves[L-1].played) / 1000;
1163 // Now that we used idx and played, re-format moves as for live games
1164 game.moves = game.moves.map(m => m.squares);
1166 else if (gtype == "live") {
1167 if (game.clocks[0] < 0) {
1168 // Game is unstarted. clock is ignored until move 2
1169 game.clocks = [tc.mainTime, tc.mainTime];
1171 // I play in this live game
1174 { clocks: game.clocks }
1179 // It's my turn: clocks not updated yet
1180 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1184 // gtype == "import"
1185 game.clocks = [tc.mainTime, tc.mainTime];
1186 // Live games before 26/03/2020 don't have chat history:
1187 if (!game.chats) game.chats = []; //TODO: remove line
1188 // Sort chat messages from newest to oldest
1189 game.chats.sort((c1, c2) => c2.added - c1.added);
1192 game.chats.length > 0 &&
1193 (!game.chatRead || game.chatRead < game.chats[0].added)
1195 // A chat message arrived since my last reading:
1196 document.getElementById("chatBtn").classList.add("somethingnew");
1198 // TODO: merge next 2 "if" conditions
1199 if (!!game.drawOffer) {
1200 if (game.drawOffer == "t")
1201 // Three repetitions
1202 this.drawOffer = "threerep";
1204 // Draw offered by any of the players:
1205 if (myIdx < 0) this.drawOffer = "received";
1207 // I play in this game:
1209 (game.drawOffer == "w" && myIdx == 0) ||
1210 (game.drawOffer == "b" && myIdx == 1)
1212 this.drawOffer = "sent";
1213 else this.drawOffer = "received";
1217 if (!!game.rematchOffer) {
1218 if (myIdx < 0) this.rematchOffer = "received";
1220 // I play in this game:
1222 (game.rematchOffer == "w" && myIdx == 0) ||
1223 (game.rematchOffer == "b" && myIdx == 1)
1225 this.rematchOffer = "sent";
1227 else this.rematchOffer = "received";
1230 this.repeat = {}; //reset: scan past moves' FEN:
1232 this.vr = new V(game.fenStart);
1234 game.moves.forEach(m => {
1235 playMove(m, this.vr);
1236 const fenIdx = this.vr.getFenForRepeat();
1237 this.repeat[fenIdx] = this.repeat[fenIdx]
1238 ? this.repeat[fenIdx] + 1
1241 // Imported games don't have current FEN
1242 if (!game.fen) game.fen = this.vr.getFen();
1243 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1244 this.game = Object.assign(
1245 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1248 increment: tc.increment,
1250 // opponent sid not strictly required (or available), but easier
1251 // at least oppsid or oppid is available anyway:
1252 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1253 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1257 this.$refs["basegame"].re_setVariables(this.game);
1259 this.gotMoveIdx = game.moves.length - 1;
1260 // If we arrive here after 'nextGame' action, the board might be hidden
1261 let boardDiv = document.querySelector(".game");
1262 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1263 boardDiv.style.visibility = "visible";
1264 this.re_setClocks();
1265 this.$nextTick(() => {
1266 this.game.rendered = true;
1267 // Did lastate arrive before game was rendered?
1268 if (!!this.lastate) this.processLastate();
1270 if (this.lastateAsked) {
1271 this.lastateAsked = false;
1272 this.sendLastate(game.oppsid);
1274 if (!!callback) callback();
1276 loadVariantThenGame: async function(game, callback) {
1277 await import("@/variants/" + game.vname + ".js")
1278 .then((vModule) => {
1279 window.V = vModule[game.vname + "Rules"];
1280 this.loadGame(game, callback);
1282 // (AJAX) Request to get rules content (plain text, HTML)
1285 "raw-loader!@/translations/rules/" +
1287 this.st.lang + ".pug"
1289 // Next two lines fix a weird issue after last update (2019-11)
1290 .replace(/\\n/g, " ")
1291 .replace(/\\"/g, '"')
1292 .replace('module.exports = "', "")
1294 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1296 // 3 cases for loading a game:
1297 // - from indexedDB (running or completed live game I play)
1298 // - from server (one correspondance game I play[ed] or not)
1299 // - from remote peer (one live game I don't play, finished or not)
1300 fetchGame: function(callback) {
1302 Number.isInteger(this.gameRef) ||
1303 !isNaN(parseInt(this.gameRef, 10))
1305 // corr games identifiers are integers
1310 data: { gid: this.gameRef },
1312 res.game.moves.forEach(m => {
1313 m.squares = JSON.parse(m.squares);
1320 else if (!!this.gameRef.match(/^i/))
1321 // Game import (maybe remote)
1322 ImportgameStorage.get(this.gameRef, callback);
1324 // Local live game (or remote)
1325 GameStorage.get(this.gameRef, callback);
1327 re_setClocks: function() {
1328 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1329 if (this.game.moves.length < 2 || this.game.score != "*") {
1330 // 1st move not completed yet, or game over: freeze time
1333 const currentTurn = this.vr.turn;
1334 const currentMovesCount = this.game.moves.length;
1335 const colorIdx = ["w", "b"].indexOf(currentTurn);
1336 this.clockUpdate = setInterval(
1339 this.game.clocks[colorIdx] < 0 ||
1340 this.game.moves.length > currentMovesCount ||
1341 this.game.score != "*"
1343 clearInterval(this.clockUpdate);
1344 this.clockUpdate = null;
1345 if (this.game.clocks[colorIdx] < 0)
1347 currentTurn == "w" ? "0-1" : "1-0",
1354 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1361 // Update variables and storage after a move:
1362 processMove: function(move, data) {
1363 if (this.game.type == "import")
1364 // Shouldn't receive any messages in this mode:
1366 if (!data) data = {};
1367 const moveCol = this.vr.turn;
1368 const colorIdx = ["w", "b"].indexOf(moveCol);
1369 const nextIdx = 1 - colorIdx;
1370 const doProcessMove = () => {
1371 const origMovescount = this.game.moves.length;
1372 // The move is (about to be) played: stop clock
1373 clearInterval(this.clockUpdate);
1374 this.clockUpdate = null;
1375 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1376 if (this.drawOffer == "received")
1378 this.drawOffer = "";
1379 if (this.game.type == "live" && origMovescount >= 2) {
1380 this.game.clocks[colorIdx] += this.game.increment;
1381 // For a correct display in casqe of disconnected opponent:
1385 ppt(this.game.clocks[colorIdx]).split(':')
1387 GameStorage.update(this.gameRef, {
1388 // It's not my turn anymore:
1393 // Update current game object:
1394 playMove(move, this.vr);
1396 // Received move, score is computed in BaseGame, but maybe not yet.
1397 // ==> Compute it here, although this is redundant (TODO)
1398 data.score = this.vr.getCurrentScore();
1399 if (data.score != "*") this.gameOver(data.score);
1400 this.game.moves.push(move);
1401 this.game.fen = this.vr.getFen();
1402 if (this.game.type == "corr") {
1403 // In corr games, just reset clock to mainTime:
1404 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1406 // If repetition detected, consider that a draw offer was received:
1407 const fenObj = this.vr.getFenForRepeat();
1408 this.repeat[fenObj] =
1409 !!this.repeat[fenObj]
1410 ? this.repeat[fenObj] + 1
1412 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1413 else if (this.drawOffer == "threerep") this.drawOffer = "";
1414 if (!!this.game.mycolor && !data.receiveMyMove) {
1415 // NOTE: 'var' to see that variable outside this block
1416 var filtered_move = getFilteredMove(move);
1418 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1419 // Notify turn on MyGames page:
1428 // Since corr games are stored at only one location, update should be
1429 // done only by one player for each move:
1431 this.game.type == "live" &&
1432 !!this.game.mycolor &&
1433 moveCol != this.game.mycolor &&
1434 this.game.moves.length >= 2
1436 // Receive a move: update initime
1437 this.game.initime = Date.now();
1438 GameStorage.update(this.gameRef, {
1439 // It's my turn now!
1440 initime: this.game.initime
1444 !!this.game.mycolor &&
1445 !data.receiveMyMove &&
1446 (this.game.type == "live" || moveCol == this.game.mycolor)
1449 switch (this.drawOffer) {
1454 drawCode = this.game.mycolor;
1457 drawCode = V.GetOppCol(this.game.mycolor);
1460 if (this.game.type == "corr") {
1461 // corr: only move, fen and score
1462 this.updateCorrGame({
1465 squares: filtered_move,
1468 // Code "n" for "None" to force reset (otherwise it's ignored)
1469 drawOffer: drawCode || "n"
1473 const updateStorage = () => {
1474 GameStorage.update(this.gameRef, {
1476 move: filtered_move,
1477 moveIdx: origMovescount,
1478 clocks: this.game.clocks,
1482 // The active tab can update storage immediately
1483 if (this.focus) updateStorage();
1484 // Small random delay otherwise
1485 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1488 // Send move ("newmove" event) to people in the room (if our turn)
1489 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1491 move: filtered_move,
1492 index: origMovescount,
1493 // color is required to check if this is my move
1494 // (if several tabs opened)
1496 cancelDrawOffer: this.drawOffer == ""
1498 if (this.game.type == "live")
1499 sendMove["clock"] = this.game.clocks[colorIdx];
1500 // (Live) Clocks will re-start when the opponent pingback arrive
1501 this.opponentGotMove = false;
1502 this.send("newmove", {data: sendMove});
1503 // If the opponent doesn't reply gotmove soon enough, re-send move:
1504 // Do this at most 2 times, because more would mean network issues,
1505 // opponent would then be expected to disconnect/reconnect.
1507 const currentUrl = document.location.href;
1508 this.retrySendmove = setInterval(
1512 this.opponentGotMove ||
1513 document.location.href != currentUrl //page change
1515 clearInterval(this.retrySendmove);
1518 const oppsid = this.getOppsid();
1520 // Opponent is disconnected: he'll ask last state
1521 clearInterval(this.retrySendmove);
1523 this.send("newmove", { data: sendMove, target: oppsid });
1531 // Not my move or I'm an observer: just start other player's clock
1532 this.re_setClocks();
1535 this.game.type == "corr" &&
1536 moveCol == this.game.mycolor &&
1539 let boardDiv = document.querySelector(".game");
1540 const afterSetScore = () => {
1542 if (this.st.settings.gotonext && this.nextIds.length > 0)
1543 this.showNextGame();
1545 // The board might have been hidden:
1546 if (boardDiv.style.visibility == "hidden")
1547 boardDiv.style.visibility = "visible";
1548 if (data.score == "*") this.re_setClocks();
1551 if (!V.CorrConfirm) {
1555 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1556 // We may play several moves in a row: in case of, remove listener:
1557 let elClone = el.cloneNode(true);
1558 el.parentNode.replaceChild(elClone, el);
1559 elClone.addEventListener(
1562 document.getElementById("modalConfirm").checked = false;
1563 if (!!data.score && data.score != "*")
1565 this.gameOver(data.score, null, afterSetScore);
1566 else afterSetScore();
1569 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1570 const arMove = (Array.isArray(move) ? move : [move]);
1571 for (let i = 0; i < arMove.length; i++)
1572 V.PlayOnBoard(this.vr.board, arMove[i]);
1573 const position = this.vr.getBaseFen();
1574 for (let i = arMove.length - 1; i >= 0; i--)
1575 V.UndoOnBoard(this.vr.board, arMove[i]);
1576 if (["all","byrow"].includes(V.ShowMoves)) {
1577 this.curDiag = getDiagram({
1579 orientation: V.CanFlip ? this.game.mycolor : "w"
1581 document.querySelector("#confirmDiv > .card").style.width =
1582 boardDiv.offsetWidth + "px";
1585 // Incomplete information: just ask confirmation
1586 // Hide the board, because otherwise it could reveal infos
1587 boardDiv.style.visibility = "hidden";
1588 this.moveNotation = getFullNotation(move);
1590 document.getElementById("modalConfirm").checked = true;
1594 if (!!data.score && data.score != "*")
1595 this.gameOver(data.score, null, doProcessMove);
1596 else doProcessMove();
1599 cancelMove: function() {
1600 let boardDiv = document.querySelector(".game");
1601 if (boardDiv.style.visibility == "hidden")
1602 boardDiv.style.visibility = "visible";
1603 document.getElementById("modalConfirm").checked = false;
1604 this.$refs["basegame"].cancelLastMove();
1606 // In corr games, callback to change page only after score is set:
1607 gameOver: function(score, scoreMsg, callback) {
1608 this.game.score = score;
1609 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1610 this.game.scoreMsg = scoreMsg;
1611 document.getElementById("modalRules").checked = false;
1612 // Display result in a un-missable way:
1613 document.getElementById("modalScore").checked = true;
1614 this.$set(this.game, "scoreMsg", scoreMsg);
1615 const myIdx = this.game.players.findIndex(p => {
1617 p.sid == this.st.user.sid ||
1618 (!!p.name && p.id == this.st.user.id)
1622 // OK, I play in this game
1627 if (this.game.type == "live") {
1628 GameStorage.update(this.gameRef, scoreObj);
1629 // Notify myself locally if I'm elsewhere:
1633 { body: score + " : " + scoreMsg }
1636 if (!!callback) callback();
1638 else this.updateCorrGame(scoreObj, callback);
1639 // Notify the score to main Hall.
1640 // TODO: only one player (currently double send)
1641 this.send("result", { gid: this.game.id, score: score });
1642 // Also to MyGames page (TODO: doubled as well...)
1651 else if (!!callback) callback();
1657 <style lang="sass" scoped>
1658 #scoreDiv > .card, #rematchDiv > .card
1666 @media screen and (max-width: 1500px)
1668 @media screen and (max-width: 1024px)
1670 @media screen and (max-width: 767px)
1680 background-color: lightgreen
1692 @media screen and (max-width: 767px)
1697 display: inline-block
1701 display: inline-block
1703 display: inline-flex
1707 @media screen and (max-width: 767px)
1716 @media screen and (max-width: 767px)
1728 background-color: #edda99
1730 display: inline-block
1734 display: inline-block
1741 @media screen and (max-width: 767px)
1743 display: inline-block
1756 animation: blink-animation 2s steps(3, start) infinite
1757 @keyframes blink-animation
1762 display: inline-block
1774 .draw-sent, .draw-sent:hover
1775 background-color: lightyellow
1777 .draw-received, .draw-received:hover
1778 background-color: #73C6B6
1780 .draw-threerep, .draw-threerep:hover
1781 background-color: #D2B4DE
1783 .rematch-sent, .rematch-sent:hover
1784 background-color: lightyellow
1786 .rematch-received, .rematch-received:hover
1787 background-color: #48C9B0
1790 background-color: #D2B4DE
1803 background-color: lightgreen
1805 background-color: red
1808 color: var(--card-fore-color)
1811 font-size: calc(1rem * var(--heading-ratio))
1813 margin: calc(1.5 * var(--universal-margin))
1817 @import "@/styles/_rules.sass"
1818 @import "@/styles/_board_squares_img.sass"