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()")
123 span.name(:class="{connected: isConnected(0)}")
124 | {{ game.players[0].name || "@nonymous" }}
126 v-if="game.score=='*'"
127 :class="{yourturn: !!vr && vr.turn == 'w'}"
129 span.time-left {{ virtualClocks[0][0] }}
130 span.time-separator(v-if="!!virtualClocks[0][1]") :
131 span.time-right(v-if="!!virtualClocks[0][1]")
132 | {{ virtualClocks[0][1] }}
134 span.name(:class="{connected: isConnected(1)}")
135 | {{ game.players[1].name || "@nonymous" }}
137 v-if="game.score=='*'"
138 :class="{yourturn: !!vr && vr.turn == 'b'}"
140 span.time-left {{ virtualClocks[1][0] }}
141 span.time-separator(v-if="!!virtualClocks[1][1]") :
142 span.time-right(v-if="!!virtualClocks[1][1]")
143 | {{ virtualClocks[1][1] }}
145 span.name(:class="{connected: isConnected(0)}")
146 | {{ game.players[0].name || "@nonymous" }}
148 span.name(:class="{connected: isConnected(1)}")
149 | {{ game.players[1].name || "@nonymous" }}
150 div(v-if="game.score=='*'")
151 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
152 span.time-left {{ virtualClocks[0][0] }}
153 span.time-separator(v-if="!!virtualClocks[0][1]") :
154 span.time-right(v-if="!!virtualClocks[0][1]")
155 | {{ virtualClocks[0][1] }}
157 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
158 span.time-left {{ virtualClocks[1][0] }}
159 span.time-separator(v-if="!!virtualClocks[1][1]") :
160 span.time-right(v-if="!!virtualClocks[1][1]")
161 | {{ virtualClocks[1][1] }}
165 @newmove="processMove"
170 import BaseGame from "@/components/BaseGame.vue";
171 import Chat from "@/components/Chat.vue";
172 import { store } from "@/store";
173 import { GameStorage } from "@/utils/gameStorage";
174 import { ImportgameStorage } from "@/utils/importgameStorage";
175 import { ppt } from "@/utils/datetime";
176 import { notify } from "@/utils/notifications";
177 import { ajax } from "@/utils/ajax";
178 import { extractTime } from "@/utils/timeControl";
179 import { getRandString } from "@/utils/alea";
180 import { getScoreMessage } from "@/utils/scoring";
181 import { getFullNotation } from "@/utils/notation";
182 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
183 import { processModalClick } from "@/utils/modalClick";
184 import { playMove, getFilteredMove } from "@/utils/playUndo";
185 import { ArrayFun } from "@/utils/array";
186 import params from "@/parameters";
196 // gameRef can point to a corr game, local game or remote live game
199 game: {}, //passed to BaseGame
200 focus: !document.hidden, //will not always work... TODO
201 // virtualClocks will be initialized from true game.clocks
203 vr: null, //"variant rules" object initialized from FEN
209 people: {}, //players + observers
210 lastate: undefined, //used if opponent send lastate before game is ready
211 repeat: {}, //detect position repetition
212 curDiag: "", //for corr moves confirmation
214 roomInitialized: false,
215 // If asklastate got no reply, ask again:
217 gotMoveIdx: -1, //last move index received
218 // If newmove got no pingback, send again:
219 opponentGotMove: false,
221 socketCloseListener: 0,
222 // Incomplete info games: show move played
224 // Intervals from setInterval():
228 // Related to (killing of) self multi-connects:
233 $route: function(to, from) {
234 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
236 this.cleanBeforeDestroy();
237 else if (from.params["id"] != to.params["id"]) {
238 // Change everything:
239 this.cleanBeforeDestroy();
240 let boardDiv = document.querySelector(".game");
242 // In case of incomplete information variant:
243 boardDiv.style.visibility = "hidden";
247 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
250 // NOTE: some redundant code with Hall.vue (mostly related to people array)
251 created: function() {
254 mounted: function() {
255 document.getElementById("chatWrap")
256 .addEventListener("click", (e) => {
257 processModalClick(e, () => {
258 this.toggleChat("close")
261 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
263 document.getElementById(eltName)
264 .addEventListener("click", processModalClick);
268 beforeDestroy: function() {
269 this.cleanBeforeDestroy();
272 cleanBeforeDestroy: function() {
273 clearInterval(this.socketCloseListener);
274 document.removeEventListener('visibilitychange', this.visibilityChange);
275 window.removeEventListener('focus', this.onFocus);
276 window.removeEventListener('blur', this.onBlur);
277 if (!!this.askLastate) clearInterval(this.askLastate);
278 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
279 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
280 this.conn.removeEventListener("message", this.socketMessageListener);
281 this.send("disconnect");
284 visibilityChange: function() {
285 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
286 this.focus = (document.visibilityState == "visible");
287 this.send(this.focus ? "getfocus" : "losefocus");
289 onFocus: function() {
291 this.send("getfocus");
295 this.send("losefocus");
297 isLargeScreen: function() {
298 return window.innerWidth >= 768;
300 btnTooltipClass: function(thing) {
302 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
305 { tooltip: !("ontouchstart" in window) },
310 participateInChat: function(p) {
311 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
313 someAnonymousPresent: function() {
315 Object.values(this.people).some(p =>
316 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
320 atCreation: function() {
321 document.addEventListener('visibilitychange', this.visibilityChange);
322 window.addEventListener('focus', this.onFocus);
323 window.addEventListener('blur', this.onBlur);
324 // 0] (Re)Set variables
325 this.gameRef = this.$route.params["id"];
326 // next = next corr games IDs to navigate faster (if applicable)
327 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
328 // Always add myself to players' list
329 const my = this.st.user;
330 const tmpId = getRandString();
338 tmpId: { focus: true }
343 players: [{ name: "" }, { name: "" }],
347 let chatComp = this.$refs["chatcomp"];
348 if (!!chatComp) chatComp.chats = [];
349 this.virtualClocks = [[0,0], [0,0]];
351 this.rulesContent = "";
353 this.lastateAsked = false;
354 this.rematchOffer = "";
355 this.lastate = undefined;
356 this.roomInitialized = false;
357 this.gotLastate = false;
358 this.gotMoveIdx = -1;
359 this.opponentGotMove = false;
360 this.askLastate = null;
361 this.retrySendmove = null;
362 this.clockUpdate = null;
363 this.newConnect = {};
364 // 1] Initialize connection
365 this.connexionString =
367 "/?sid=" + this.st.user.sid +
368 "&id=" + this.st.user.id +
371 // Discard potential "/?next=[...]" for page indication:
372 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
373 this.conn = new WebSocket(this.connexionString);
374 this.conn.addEventListener("message", this.socketMessageListener);
375 this.socketCloseListener = setInterval(
377 if (this.conn.readyState == 3) {
378 this.conn.removeEventListener(
379 "message", this.socketMessageListener);
380 this.conn = new WebSocket(this.connexionString);
381 this.conn.addEventListener("message", this.socketMessageListener);
386 // Socket init required before loading remote game:
387 const socketInit = callback => {
388 if (this.conn.readyState == 1)
392 // Socket not ready yet (initial loading)
393 // NOTE: first arg is Websocket object, unused here:
394 this.conn.onopen = () => callback();
396 this.fetchGame((game) => {
398 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
400 // Live game stored remotely: need socket to retrieve it
401 // NOTE: the callback "roomInit" will be lost, so it's not provided.
402 // --> It will be given when receiving "fullgame" socket event.
403 socketInit(() => { this.send("askfullgame"); });
406 roomInit: function() {
407 if (!this.roomInitialized) {
408 // Notify the room only now that I connected, because
409 // messages might be lost otherwise (if game loading is slow)
410 this.send("connect");
411 this.send("pollclients");
412 // We may ask fullgame several times if some moves are lost,
413 // but room should be init only once:
414 this.roomInitialized = true;
417 send: function(code, obj) {
418 if (!!this.conn && this.conn.readyState == 1)
419 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
421 isConnected: function(index) {
422 const player = this.game.players[index];
423 // Is it me ? In this case no need to bother with focus
425 this.st.user.sid == player.sid ||
426 (!!player.name && this.st.user.id == player.id)
428 // Still have to check for name (because of potential multi-accounts
429 // on same browser, although this should be rare...)
430 return (!this.st.user.name || this.st.user.name == player.name);
432 // Try to find a match in people:
436 Object.keys(this.people).some(sid => {
439 Object.values(this.people[sid].tmpIds).some(v => v.focus)
446 Object.values(this.people).some(p => {
449 Object.values(p.tmpIds).some(v => v.focus)
455 getOppsid: function() {
456 let oppsid = this.game.oppsid;
458 oppsid = Object.keys(this.people).find(
459 sid => this.people[sid].id == this.game.oppid
462 // oppsid is useful only if opponent is online:
463 if (!!oppsid && !!this.people[oppsid]) return oppsid;
466 // NOTE: action if provided is always a closing action
467 toggleChat: function(action) {
468 if (!action && document.getElementById("modalChat").checked)
470 document.getElementById("inputChat").focus();
472 document.getElementById("chatBtn").classList.remove("somethingnew");
473 if (!!this.game.mycolor) {
474 // Update "chatRead" variable either on server or locally
475 if (this.game.type == "corr")
476 this.updateCorrGame({ chatRead: this.game.mycolor });
477 else if (this.game.type == "live")
478 GameStorage.update(this.gameRef, { chatRead: true });
482 processChat: function(chat) {
483 this.send("newchat", { data: chat });
484 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
485 if (!!this.game.mycolor) {
486 if (this.game.type == "corr")
487 this.updateCorrGame({ chat: chat });
490 chat.added = Date.now();
491 GameStorage.update(this.gameRef, { chat: chat });
495 clearChat: function() {
496 if (!!this.game.mycolor) {
497 if (this.game.type == "corr") {
501 { data: { gid: this.game.id } }
505 GameStorage.update(this.gameRef, { delchat: true });
507 this.$set(this.game, "chats", []);
510 getGameType: function(game) {
511 if (!!game.id.toString().match(/^i/)) return "import";
512 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
514 // Notify something after a new move (to opponent and me on MyGames page)
515 notifyMyGames: function(thing, data) {
520 targets: this.game.players.map(p => {
521 return { sid: p.sid, id: p.id };
526 showNextGame: function() {
527 // Did I play in current game? If not, add it to nextIds list
528 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
529 this.nextIds.unshift(this.game.id);
530 const nextGid = this.nextIds.pop();
532 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
534 socketMessageListener: function(msg) {
535 if (!this.conn) return;
536 const data = JSON.parse(msg.data);
539 // TODO: shuffling and random filtering on server,
540 // if the room is really crowded.
541 Object.keys(data.sockIds).forEach(sid => {
542 if (sid != this.st.user.sid) {
543 this.send("askidentity", { target: sid });
544 this.people[sid] = { tmpIds: data.sockIds[sid] };
547 // Complete my tmpIds:
548 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
553 if (!this.people[data.from[0]]) {
554 // focus depends on the tmpId (e.g. tab)
560 [data.from[1]]: { focus: true }
564 // For self multi-connects tests:
565 this.newConnect[data.from[0]] = true;
566 this.send("askidentity", { target: data.from[0] });
568 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
569 this.$forceUpdate(); //TODO: shouldn't be required
573 if (!this.people[data.from[0]]) return;
574 delete this.people[data.from[0]].tmpIds[data.from[1]];
575 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
576 this.$delete(this.people, data.from[0]);
577 else this.$forceUpdate(); //TODO: shouldn't be required
580 let player = this.people[data.from[0]];
582 player.tmpIds[data.from[1]].focus = true;
583 this.$forceUpdate(); //TODO: shouldn't be required
588 let player = this.people[data.from[0]];
590 player.tmpIds[data.from[1]].focus = false;
591 this.$forceUpdate(); //TODO: shouldn't be required
595 case "askidentity": {
596 // Request for identification
598 // Decompose to avoid revealing email
599 name: this.st.user.name,
600 sid: this.st.user.sid,
603 this.send("identity", { data: me, target: data.from });
607 const user = data.data;
608 let player = this.people[user.sid];
609 // player.tmpIds is already set
610 player.name = user.name;
612 if (this.game.type == "live") {
614 this.game.players.findIndex(p => p.sid == this.st.user.sid);
615 // Sometimes a player name isn't stored yet (TODO: why?)
618 !this.game.players[1 - myGidx].name &&
619 this.game.players[1 - myGidx].sid == user.sid &&
622 this.game.players[1-myGidx].name = user.name;
625 { playerName: { idx: 1 - myGidx, name: user.name } }
629 this.$forceUpdate(); //TODO: shouldn't be required
630 // If I multi-connect, kill current connexion if no mark (I'm older)
631 if (this.newConnect[user.sid]) {
632 delete this.newConnect[user.sid];
635 user.id == this.st.user.id &&
636 user.sid != this.st.user.sid
638 this.cleanBeforeDestroy();
639 alert(this.st.tr["New connexion detected: tab now offline"]);
643 // Ask potentially missed last state, if opponent and I play
646 !!this.game.mycolor &&
647 this.game.type == "live" &&
648 this.game.players.some(p => p.sid == user.sid)
650 this.send("asklastate", { target: user.sid });
652 this.askLastate = setInterval(
654 // Ask at most 3 times:
655 // if no reply after that there should be a network issue.
659 !!this.people[user.sid]
661 this.send("asklastate", { target: user.sid });
664 clearInterval(this.askLastate);
673 // Send current (live or import) game,
674 // if not asked by any of the players
676 this.game.type != "corr" &&
677 this.game.players.every(p => p.sid != data.from[0])
681 // FEN is current position, unused for now
683 players: this.game.players,
685 cadence: this.game.cadence,
686 score: this.game.score
688 this.send("game", { data: myGame, target: data.from });
692 const gameToSend = Object.keys(this.game)
695 "id","fen","players","vid","cadence","fenStart","vname",
696 "moves","clocks","score","drawOffer","rematchOffer"
700 obj[k] = this.game[k];
705 this.send("fullgame", { data: gameToSend, target: data.from });
708 if (!!data.data.empty) {
709 alert(this.st.tr["The game should be in another tab"]);
713 // Callback "roomInit" to poll clients only after game is loaded
714 this.loadVariantThenGame(data.data, this.roomInit);
717 // Sending informative last state if I played a move or score != "*"
718 // If the game or moves aren't loaded yet, delay the sending:
719 // TODO: socket init after game load, so the game is supposedly ready
720 if (!this.game || !this.game.moves) this.lastateAsked = true;
721 else this.sendLastate(data.from);
723 // TODO: possible bad scenario: reload page while oppponent sends a
724 // move => get both lastate and newmove, process both, add move twice.
725 // Confirm scenario? Fix?
727 // Got opponent infos about last move
728 this.gotLastate = true;
729 this.lastate = data.data;
730 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
731 this.gotMoveIdx = this.lastate.movesCount - 1;
732 if (this.game.rendered)
733 // Game is rendered (Board component)
734 this.processLastate();
735 // Else: will be processed when game is ready
741 console.log("Receive move");
742 console.log(data.data);
743 //moveslist not updated when receiving a move? (see in baseGame)
745 const movePlus = data.data;
746 const movesCount = this.game.moves.length;
748 movePlus.index < movesCount ||
749 this.gotMoveIdx >= movePlus.index
751 // Opponent re-send but we already have the move:
752 // (maybe he didn't receive our pingback...)
753 this.send("gotmove", {data: movePlus.index, target: data.from});
756 this.gotMoveIdx = movePlus.index;
757 const receiveMyMove = (movePlus.color == this.game.mycolor);
758 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
759 if (!receiveMyMove && !!this.game.mycolor) {
760 // Notify opponent that I got the move:
763 { data: movePlus.index, target: data.from }
765 // And myself if I'm elsewhere:
771 (this.game.players[moveColIdx].name || "@nonymous") +
777 if (movePlus.cancelDrawOffer) {
778 // Opponent refuses draw
780 // NOTE for corr games: drawOffer reset by player in turn
782 this.game.type == "live" &&
783 !!this.game.mycolor &&
786 GameStorage.update(this.gameRef, { drawOffer: "" });
789 this.$refs["basegame"].play(movePlus.move, "received");
790 // Freeze time while the move is being play
791 // (TODO: a callback would be cleaner here)
792 clearInterval(this.clockUpdate);
793 this.clockUpdate = null;
794 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
795 // 250 = length of animation, 500 = delay between sub-moves
797 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
798 // Incomplete information: no move animation
802 this.game.clocks[moveColIdx] = movePlus.clock;
805 { receiveMyMove: receiveMyMove }
814 this.opponentGotMove = true;
815 // Now his clock starts running on my side:
816 const oppIdx = ['w','b'].indexOf(this.vr.turn);
817 // NOTE: next line to avoid multi-resetClocks when several tabs
818 // on same game, resulting in a faster countdown.
819 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
824 const score = (data.data == "b" ? "1-0" : "0-1");
825 const side = (data.data == "w" ? "White" : "Black");
826 this.gameOver(score, side + " surrender");
829 this.gameOver("?", "Stop");
832 this.gameOver("1/2", data.data);
835 // NOTE: observers don't know who offered draw
836 this.drawOffer = "received";
837 if (!!this.game.mycolor && this.game.type == "live") {
840 { drawOffer: V.GetOppCol(this.game.mycolor) }
845 // NOTE: observers don't know who offered rematch
846 this.rematchOffer = data.data ? "received" : "";
847 if (!!this.game.mycolor && this.game.type == "live") {
850 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
855 // A game started, redirect if I'm playing in
856 const gameInfo = data.data;
857 const gameType = this.getGameType(gameInfo);
859 gameType == "live" &&
860 gameInfo.players.some(p => p.sid == this.st.user.sid)
862 this.addAndGotoLiveGame(gameInfo);
864 gameType == "corr" &&
865 this.st.user.id > 0 &&
866 gameInfo.players.some(p => p.id == this.st.user.id)
868 this.$router.push("/game/" + gameInfo.id);
870 this.rematchId = gameInfo.id;
871 document.getElementById("modalRules").checked = false;
872 document.getElementById("modalScore").checked = false;
873 document.getElementById("modalRematch").checked = true;
878 let chat = data.data;
879 this.$refs["chatcomp"].newChat(chat);
880 if (this.game.type == "live") {
881 chat.added = Date.now();
882 if (!!this.game.mycolor)
883 GameStorage.update(this.gameRef, { chat: chat });
885 if (!document.getElementById("modalChat").checked)
886 document.getElementById("chatBtn").classList.add("somethingnew");
891 updateCorrGame: function(obj, callback) {
901 if (!!callback) callback();
906 sendLastate: function(target) {
907 // Send our "last state" informations to opponent
908 const L = this.game.moves.length;
909 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
912 (L > 0 && this.vr.turn != this.game.mycolor)
913 ? this.game.moves[L - 1]
915 clock: this.game.clocks[myIdx],
916 // Since we played a move (or abort or resign),
917 // only drawOffer=="sent" is possible
918 drawSent: this.drawOffer == "sent" ? true : undefined,
919 rematchSent: this.rematchOffer == "sent" ? true : undefined,
920 score: this.game.score != "*" ? this.game.score : undefined,
921 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
924 this.send("lastate", { data: myLastate, target: target });
926 // lastate was received, but maybe game wasn't ready yet:
927 processLastate: function() {
928 const data = this.lastate;
929 this.lastate = undefined; //security...
931 const oppCol = V.GetOppCol(this.game.mycolor);
932 if (!!data.rematchSent) {
933 if (this.game.rematchOffer != oppCol) {
934 // Opponent sended rematch offer while we were offline:
935 this.rematchOffer = "received";
938 { rematchOffer: oppCol }
943 if (this.game.rematchOffer == oppCol) {
944 // Opponent cancelled rematch offer while we were offline:
945 this.rematchOffer = "";
954 const L = this.game.moves.length;
955 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
956 this.game.clocks[oppIdx] = data.clock;
957 if (data.movesCount > L) {
958 // Just got last move from him
959 this.$refs["basegame"].play(data.lastMove, "received");
960 this.processMove(data.lastMove);
962 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
965 if (!!data.drawSent) this.drawOffer = "received";
968 if (this.game.score == "*")
969 this.gameOver(data.score, data.scoreMsg);
973 clickDraw: function() {
974 if (!this.game.mycolor || this.game.type == "import") return;
975 if (["received", "threerep"].includes(this.drawOffer)) {
976 if (!confirm(this.st.tr["Accept draw?"])) return;
978 this.drawOffer == "received"
980 : "Three repetitions";
981 this.send("draw", { data: message });
982 this.gameOver("1/2", message);
983 } else if (this.drawOffer == "") {
984 // No effect if drawOffer == "sent"
985 if (this.game.mycolor != this.vr.turn) {
986 alert(this.st.tr["Draw offer only in your turn"]);
989 if (!confirm(this.st.tr["Offer draw?"])) return;
990 this.drawOffer = "sent";
991 this.send("drawoffer");
992 if (this.game.type == "live") {
995 { drawOffer: this.game.mycolor }
997 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1000 addAndGotoLiveGame: function(gameInfo, callback) {
1001 const game = Object.assign(
1005 // (other) Game infos: constant
1006 fenStart: gameInfo.fen,
1007 vname: this.game.vname,
1008 created: Date.now(),
1009 // Game state (including FEN): will be updated
1011 clocks: [-1, -1], //-1 = unstarted
1015 GameStorage.add(game, (err) => {
1016 // No error expected.
1018 if (this.st.settings.sound)
1019 new Audio("/sounds/newgame.flac").play().catch(() => {});
1020 if (!!callback) callback();
1021 this.$router.push("/game/" + gameInfo.id);
1025 clickRematch: function() {
1026 if (!this.game.mycolor || this.game.type == "import") return;
1027 if (this.rematchOffer == "received") {
1028 // Start a new game!
1030 id: getRandString(), //ignored if corr
1031 fen: V.GenRandInitFen(this.game.randomness),
1032 players: [this.game.players[1], this.game.players[0]],
1034 cadence: this.game.cadence
1036 const notifyNewGame = () => {
1037 const oppsid = this.getOppsid(); //may be null
1038 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1039 // To main Hall if corr game:
1040 if (this.game.type == "corr")
1041 this.send("newgame", { data: gameInfo, page: "/" });
1042 // Also to MyGames page:
1043 this.notifyMyGames("newgame", gameInfo);
1045 if (this.game.type == "live")
1046 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1053 // cid is useful to delete the challenge:
1054 data: { gameInfo: gameInfo },
1055 success: (response) => {
1056 gameInfo.id = response.gameId;
1058 this.$router.push("/game/" + response.gameId);
1063 } else if (this.rematchOffer == "") {
1064 this.rematchOffer = "sent";
1065 this.send("rematchoffer", { data: true });
1066 if (this.game.type == "live") {
1069 { rematchOffer: this.game.mycolor }
1071 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1072 } else if (this.rematchOffer == "sent") {
1073 // Toggle rematch offer (on --> off)
1074 this.rematchOffer = "";
1075 this.send("rematchoffer", { data: false });
1076 if (this.game.type == "live") {
1079 { rematchOffer: '' }
1081 } else this.updateCorrGame({ rematchOffer: 'n' });
1084 abortGame: function() {
1085 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1087 this.gameOver("?", "Stop");
1090 resign: function() {
1091 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1093 this.send("resign", { data: this.game.mycolor });
1094 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1095 const side = (this.game.mycolor == "w" ? "White" : "Black");
1096 this.gameOver(score, side + " surrender");
1098 loadGame: function(game, callback) {
1099 const gtype = game.type || this.getGameType(game);
1100 const tc = extractTime(game.cadence);
1101 const myIdx = game.players.findIndex(p => {
1103 p.sid == this.st.user.sid ||
1104 (!!p.name && p.id == this.st.user.id)
1107 // Sometimes the name isn't stored yet (TODO: why?)
1111 !game.players[myIdx].name &&
1114 game.players[myIdx].name = this.st.user.name;
1117 { playerName: { idx: myIdx, name: this.st.user.name } }
1120 // "mycolor" is undefined for observers
1121 const mycolor = [undefined, "w", "b"][myIdx + 1];
1122 if (gtype == "corr") {
1123 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1124 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1125 // NOTE: clocks in seconds
1126 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1127 game.clocks = [tc.mainTime, tc.mainTime];
1128 const L = game.moves.length;
1129 if (game.score == "*") {
1132 game.clocks[L % 2] -=
1133 (Date.now() - game.moves[L-1].played) / 1000;
1136 // Now that we used idx and played, re-format moves as for live games
1137 game.moves = game.moves.map(m => m.squares);
1139 else if (gtype == "live") {
1140 if (game.clocks[0] < 0) {
1141 // Game is unstarted. clock is ignored until move 2
1142 game.clocks = [tc.mainTime, tc.mainTime];
1144 // I play in this live game
1147 { clocks: game.clocks }
1152 // It's my turn: clocks not updated yet
1153 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1157 // gtype == "import"
1158 game.clocks = [tc.mainTime, tc.mainTime];
1159 // Live games before 26/03/2020 don't have chat history:
1160 if (!game.chats) game.chats = []; //TODO: remove line
1161 // Sort chat messages from newest to oldest
1162 game.chats.sort((c1, c2) => c2.added - c1.added);
1165 game.chats.length > 0 &&
1166 (!game.chatRead || game.chatRead < game.chats[0].added)
1168 // A chat message arrived since my last reading:
1169 document.getElementById("chatBtn").classList.add("somethingnew");
1171 // TODO: merge next 2 "if" conditions
1172 if (!!game.drawOffer) {
1173 if (game.drawOffer == "t")
1174 // Three repetitions
1175 this.drawOffer = "threerep";
1177 // Draw offered by any of the players:
1178 if (myIdx < 0) this.drawOffer = "received";
1180 // I play in this game:
1182 (game.drawOffer == "w" && myIdx == 0) ||
1183 (game.drawOffer == "b" && myIdx == 1)
1185 this.drawOffer = "sent";
1186 else this.drawOffer = "received";
1190 if (!!game.rematchOffer) {
1191 if (myIdx < 0) this.rematchOffer = "received";
1193 // I play in this game:
1195 (game.rematchOffer == "w" && myIdx == 0) ||
1196 (game.rematchOffer == "b" && myIdx == 1)
1198 this.rematchOffer = "sent";
1200 else this.rematchOffer = "received";
1203 this.repeat = {}; //reset: scan past moves' FEN:
1205 this.vr = new V(game.fenStart);
1207 game.moves.forEach(m => {
1208 playMove(m, this.vr);
1209 const fenIdx = this.vr.getFenForRepeat();
1210 this.repeat[fenIdx] = this.repeat[fenIdx]
1211 ? this.repeat[fenIdx] + 1
1214 // Imported games don't have current FEN
1215 if (!game.fen) game.fen = this.vr.getFen();
1216 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1217 this.game = Object.assign(
1218 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1221 increment: tc.increment,
1223 // opponent sid not strictly required (or available), but easier
1224 // at least oppsid or oppid is available anyway:
1225 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1226 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1230 this.$refs["basegame"].re_setVariables(this.game);
1232 this.gotMoveIdx = game.moves.length - 1;
1233 // If we arrive here after 'nextGame' action, the board might be hidden
1234 let boardDiv = document.querySelector(".game");
1235 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1236 boardDiv.style.visibility = "visible";
1237 this.re_setClocks();
1238 this.$nextTick(() => {
1239 this.game.rendered = true;
1240 // Did lastate arrive before game was rendered?
1241 if (!!this.lastate) this.processLastate();
1243 if (this.lastateAsked) {
1244 this.lastateAsked = false;
1245 this.sendLastate(game.oppsid);
1247 if (!!callback) callback();
1249 loadVariantThenGame: async function(game, callback) {
1250 await import("@/variants/" + game.vname + ".js")
1251 .then((vModule) => {
1252 window.V = vModule[game.vname + "Rules"];
1253 this.loadGame(game, callback);
1255 // (AJAX) Request to get rules content (plain text, HTML)
1258 "raw-loader!@/translations/rules/" +
1260 this.st.lang + ".pug"
1262 // Next two lines fix a weird issue after last update (2019-11)
1263 .replace(/\\n/g, " ")
1264 .replace(/\\"/g, '"')
1265 .replace('module.exports = "', "")
1267 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1269 // 3 cases for loading a game:
1270 // - from indexedDB (running or completed live game I play)
1271 // - from server (one correspondance game I play[ed] or not)
1272 // - from remote peer (one live game I don't play, finished or not)
1273 fetchGame: function(callback) {
1274 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1275 // corr games identifiers are integers
1280 data: { gid: this.gameRef },
1282 res.game.moves.forEach(m => {
1283 m.squares = JSON.parse(m.squares);
1290 else if (!!this.gameRef.match(/^i/))
1291 // Game import (maybe remote)
1292 ImportgameStorage.get(this.gameRef, callback);
1294 // Local live game (or remote)
1295 GameStorage.get(this.gameRef, callback);
1297 re_setClocks: function() {
1298 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1299 if (this.game.moves.length < 2 || this.game.score != "*") {
1300 // 1st move not completed yet, or game over: freeze time
1303 const currentTurn = this.vr.turn;
1304 const currentMovesCount = this.game.moves.length;
1305 const colorIdx = ["w", "b"].indexOf(currentTurn);
1306 this.clockUpdate = setInterval(
1309 this.game.clocks[colorIdx] < 0 ||
1310 this.game.moves.length > currentMovesCount ||
1311 this.game.score != "*"
1313 clearInterval(this.clockUpdate);
1314 this.clockUpdate = null;
1315 if (this.game.clocks[colorIdx] < 0)
1317 currentTurn == "w" ? "0-1" : "1-0",
1324 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1331 // Update variables and storage after a move:
1332 processMove: function(move, data) {
1333 if (this.game.type == "import")
1334 // Shouldn't receive any messages in this mode:
1336 if (!data) data = {};
1337 const moveCol = this.vr.turn;
1338 const colorIdx = ["w", "b"].indexOf(moveCol);
1339 const nextIdx = 1 - colorIdx;
1340 const doProcessMove = () => {
1341 const origMovescount = this.game.moves.length;
1342 // The move is (about to be) played: stop clock
1343 clearInterval(this.clockUpdate);
1344 this.clockUpdate = null;
1345 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1346 if (this.drawOffer == "received")
1348 this.drawOffer = "";
1349 if (this.game.type == "live" && origMovescount >= 2) {
1350 this.game.clocks[colorIdx] += this.game.increment;
1351 // For a correct display in casqe of disconnected opponent:
1355 ppt(this.game.clocks[colorIdx]).split(':')
1357 GameStorage.update(this.gameRef, {
1358 // It's not my turn anymore:
1363 // Update current game object:
1364 playMove(move, this.vr);
1366 // Received move, score is computed in BaseGame, but maybe not yet.
1367 // ==> Compute it here, although this is redundant (TODO)
1368 data.score = this.vr.getCurrentScore();
1369 if (data.score != "*") this.gameOver(data.score);
1370 this.game.moves.push(move);
1371 this.game.fen = this.vr.getFen();
1372 if (this.game.type == "corr") {
1373 // In corr games, just reset clock to mainTime:
1374 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1376 // If repetition detected, consider that a draw offer was received:
1377 const fenObj = this.vr.getFenForRepeat();
1378 this.repeat[fenObj] =
1379 !!this.repeat[fenObj]
1380 ? this.repeat[fenObj] + 1
1382 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1383 else if (this.drawOffer == "threerep") this.drawOffer = "";
1384 if (!!this.game.mycolor && !data.receiveMyMove) {
1385 // NOTE: 'var' to see that variable outside this block
1386 var filtered_move = getFilteredMove(move);
1388 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1389 // Notify turn on MyGames page:
1398 // Since corr games are stored at only one location, update should be
1399 // done only by one player for each move:
1401 this.game.type == "live" &&
1402 !!this.game.mycolor &&
1403 moveCol != this.game.mycolor &&
1404 this.game.moves.length >= 2
1406 // Receive a move: update initime
1407 this.game.initime = Date.now();
1408 GameStorage.update(this.gameRef, {
1409 // It's my turn now!
1410 initime: this.game.initime
1414 !!this.game.mycolor &&
1415 !data.receiveMyMove &&
1416 (this.game.type == "live" || moveCol == this.game.mycolor)
1419 switch (this.drawOffer) {
1424 drawCode = this.game.mycolor;
1427 drawCode = V.GetOppCol(this.game.mycolor);
1430 if (this.game.type == "corr") {
1431 // corr: only move, fen and score
1432 this.updateCorrGame({
1435 squares: filtered_move,
1438 // Code "n" for "None" to force reset (otherwise it's ignored)
1439 drawOffer: drawCode || "n"
1443 const updateStorage = () => {
1444 GameStorage.update(this.gameRef, {
1446 move: filtered_move,
1447 moveIdx: origMovescount,
1448 clocks: this.game.clocks,
1452 // The active tab can update storage immediately
1453 if (this.focus) updateStorage();
1454 // Small random delay otherwise
1455 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1458 // Send move ("newmove" event) to people in the room (if our turn)
1459 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1461 move: filtered_move,
1462 index: origMovescount,
1463 // color is required to check if this is my move
1464 // (if several tabs opened)
1466 cancelDrawOffer: this.drawOffer == ""
1468 if (this.game.type == "live")
1469 sendMove["clock"] = this.game.clocks[colorIdx];
1470 // (Live) Clocks will re-start when the opponent pingback arrive
1471 this.opponentGotMove = false;
1472 this.send("newmove", {data: sendMove});
1473 // If the opponent doesn't reply gotmove soon enough, re-send move:
1474 // Do this at most 2 times, because more would mean network issues,
1475 // opponent would then be expected to disconnect/reconnect.
1477 const currentUrl = document.location.href;
1478 this.retrySendmove = setInterval(
1482 this.opponentGotMove ||
1483 document.location.href != currentUrl //page change
1485 clearInterval(this.retrySendmove);
1488 const oppsid = this.getOppsid();
1490 // Opponent is disconnected: he'll ask last state
1491 clearInterval(this.retrySendmove);
1493 this.send("newmove", { data: sendMove, target: oppsid });
1501 // Not my move or I'm an observer: just start other player's clock
1502 this.re_setClocks();
1505 this.game.type == "corr" &&
1507 moveCol == this.game.mycolor &&
1510 let boardDiv = document.querySelector(".game");
1511 const afterSetScore = () => {
1513 if (this.st.settings.gotonext && this.nextIds.length > 0)
1514 this.showNextGame();
1516 // The board might have been hidden:
1517 if (boardDiv.style.visibility == "hidden")
1518 boardDiv.style.visibility = "visible";
1519 if (data.score == "*") this.re_setClocks();
1522 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1523 // We may play several moves in a row: in case of, remove listener:
1524 let elClone = el.cloneNode(true);
1525 el.parentNode.replaceChild(elClone, el);
1526 elClone.addEventListener(
1529 document.getElementById("modalConfirm").checked = false;
1530 if (!!data.score && data.score != "*")
1532 this.gameOver(data.score, null, afterSetScore);
1533 else afterSetScore();
1536 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1537 const arMove = (Array.isArray(move) ? move : [move]);
1538 for (let i = 0; i < arMove.length; i++)
1539 V.PlayOnBoard(this.vr.board, arMove[i]);
1540 const position = this.vr.getBaseFen();
1541 for (let i = arMove.length - 1; i >= 0; i--)
1542 V.UndoOnBoard(this.vr.board, arMove[i]);
1543 if (["all","byrow"].includes(V.ShowMoves)) {
1544 this.curDiag = getDiagram({
1546 orientation: V.CanFlip ? this.game.mycolor : "w"
1548 document.querySelector("#confirmDiv > .card").style.width =
1549 boardDiv.offsetWidth + "px";
1552 // Incomplete information: just ask confirmation
1553 // Hide the board, because otherwise it could reveal infos
1554 boardDiv.style.visibility = "hidden";
1555 this.moveNotation = getFullNotation(move);
1557 document.getElementById("modalConfirm").checked = true;
1561 if (!!data.score && data.score != "*")
1562 this.gameOver(data.score, null, doProcessMove);
1563 else doProcessMove();
1566 cancelMove: function() {
1567 let boardDiv = document.querySelector(".game");
1568 if (boardDiv.style.visibility == "hidden")
1569 boardDiv.style.visibility = "visible";
1570 document.getElementById("modalConfirm").checked = false;
1571 this.$refs["basegame"].cancelLastMove();
1573 // In corr games, callback to change page only after score is set:
1574 gameOver: function(score, scoreMsg, callback) {
1575 this.game.score = score;
1576 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1577 this.game.scoreMsg = scoreMsg;
1578 document.getElementById("modalRules").checked = false;
1579 // Display result in a un-missable way:
1580 document.getElementById("modalScore").checked = true;
1581 this.$set(this.game, "scoreMsg", scoreMsg);
1582 const myIdx = this.game.players.findIndex(p => {
1584 p.sid == this.st.user.sid ||
1585 (!!p.name && p.id == this.st.user.id)
1589 // OK, I play in this game
1594 if (this.game.type == "live") {
1595 GameStorage.update(this.gameRef, scoreObj);
1596 // Notify myself locally if I'm elsewhere:
1600 { body: score + " : " + scoreMsg }
1603 if (!!callback) callback();
1605 else this.updateCorrGame(scoreObj, callback);
1606 // Notify the score to main Hall.
1607 // TODO: only one player (currently double send)
1608 this.send("result", { gid: this.game.id, score: score });
1609 // Also to MyGames page (TODO: doubled as well...)
1618 else if (!!callback) callback();
1624 <style lang="sass" scoped>
1625 #scoreDiv > .card, #rematchDiv > .card
1633 @media screen and (max-width: 1500px)
1635 @media screen and (max-width: 1024px)
1637 @media screen and (max-width: 767px)
1647 background-color: lightgreen
1659 @media screen and (max-width: 767px)
1664 display: inline-block
1668 display: inline-block
1670 display: inline-flex
1674 @media screen and (max-width: 767px)
1688 background-color: #edda99
1690 display: inline-block
1694 display: inline-block
1701 @media screen and (max-width: 767px)
1707 @media screen and (max-width: 767px)
1709 display: inline-block
1722 animation: blink-animation 2s steps(3, start) infinite
1723 @keyframes blink-animation
1728 display: inline-block
1740 .draw-sent, .draw-sent:hover
1741 background-color: lightyellow
1743 .draw-received, .draw-received:hover
1744 background-color: #73C6B6
1746 .draw-threerep, .draw-threerep:hover
1747 background-color: #D2B4DE
1749 .rematch-sent, .rematch-sent:hover
1750 background-color: lightyellow
1752 .rematch-received, .rematch-received:hover
1753 background-color: #48C9B0
1756 background-color: #D2B4DE
1769 background-color: lightgreen
1771 background-color: red
1774 color: var(--card-fore-color)
1777 font-size: calc(1rem * var(--heading-ratio))
1779 margin: calc(1.5 * var(--universal-margin))
1783 @import "@/styles/_rules.sass"
1784 @import "@/styles/_board_squares_img.sass"