3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
11 :href="'#/game/' + rematchId"
12 onClick="document.getElementById('modalInfo').checked=false"
14 | {{ st.tr["Rematch in progress"] }}
15 input#modalChat.modal(
21 data-checkbox="modalChat"
24 label.modal-close(for="modalChat")
26 span {{ st.tr["Participant(s):"] }}
28 v-for="p in Object.values(people)"
29 v-if="participateInChat(p)"
32 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
35 :players="game.players"
36 :pastChats="game.chats"
38 @chatcleared="clearChat"
40 input#modalConfirm.modal(type="checkbox")
41 div#confirmDiv(role="dialog")
44 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
48 span {{ st.tr["Move played:"] + " " }}
49 span.bold {{ moveNotation }}
51 span {{ st.tr["Are you sure?"] }}
52 .button-group#buttonsConfirm
53 // onClick for acceptBtn: set dynamically
55 span {{ st.tr["Validate"] }}
56 button.refuseBtn(@click="cancelMove()")
57 span {{ st.tr["Cancel"] }}
59 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
60 span.variant-cadence {{ game.cadence }}
61 span.variant-name {{ game.vname }}
63 v-if="nextIds.length > 0"
64 @click="showNextGame()"
66 | {{ st.tr["Next_g"] }}
67 button#chatBtn.tooltip(
68 onClick="window.doClick('modalChat')"
71 img(src="/images/icons/chat.svg")
72 #actions(v-if="game.score=='*'")
75 :class="{['draw-' + drawOffer]: true}"
76 :aria-label="st.tr['Draw']"
78 img(src="/images/icons/draw.svg")
82 :aria-label="st.tr['Abort']"
84 img(src="/images/icons/abort.svg")
88 :aria-label="st.tr['Resign']"
90 img(src="/images/icons/resign.svg")
93 @click="clickRematch()"
94 :class="{['rematch-' + rematchOffer]: true}"
95 :aria-label="st.tr['Rematch']"
97 img(src="/images/icons/rematch.svg")
99 p(v-if="isLargeScreen()")
100 span.name(:class="{connected: isConnected(0)}")
101 | {{ game.players[0].name || "@nonymous" }}
103 v-if="game.score=='*'"
104 :class="{yourturn: !!vr && vr.turn == 'w'}"
106 span.time-left {{ virtualClocks[0][0] }}
107 span.time-separator(v-if="!!virtualClocks[0][1]") :
108 span.time-right(v-if="!!virtualClocks[0][1]")
109 | {{ virtualClocks[0][1] }}
111 span.name(:class="{connected: isConnected(1)}")
112 | {{ game.players[1].name || "@nonymous" }}
114 v-if="game.score=='*'"
115 :class="{yourturn: !!vr && vr.turn == 'b'}"
117 span.time-left {{ virtualClocks[1][0] }}
118 span.time-separator(v-if="!!virtualClocks[1][1]") :
119 span.time-right(v-if="!!virtualClocks[1][1]")
120 | {{ virtualClocks[1][1] }}
122 span.name(:class="{connected: isConnected(0)}")
123 | {{ game.players[0].name || "@nonymous" }}
125 span.name(:class="{connected: isConnected(1)}")
126 | {{ game.players[1].name || "@nonymous" }}
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] }}
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] }}
147 @newmove="processMove"
152 import BaseGame from "@/components/BaseGame.vue";
153 import Chat from "@/components/Chat.vue";
154 import { store } from "@/store";
155 import { GameStorage } from "@/utils/gameStorage";
156 import { ImportgameStorage } from "@/utils/importgameStorage";
157 import { ppt } from "@/utils/datetime";
158 import { notify } from "@/utils/notifications";
159 import { ajax } from "@/utils/ajax";
160 import { extractTime } from "@/utils/timeControl";
161 import { getRandString } from "@/utils/alea";
162 import { getScoreMessage } from "@/utils/scoring";
163 import { getFullNotation } from "@/utils/notation";
164 import { getDiagram } from "@/utils/printDiagram";
165 import { processModalClick } from "@/utils/modalClick";
166 import { playMove, getFilteredMove } from "@/utils/playUndo";
167 import { ArrayFun } from "@/utils/array";
168 import params from "@/parameters";
178 // gameRef can point to a corr game, local game or remote live game
181 game: {}, //passed to BaseGame
182 focus: !document.hidden, //will not always work... TODO
183 // virtualClocks will be initialized from true game.clocks
185 vr: null, //"variant rules" object initialized from FEN
190 people: {}, //players + observers
191 lastate: undefined, //used if opponent send lastate before game is ready
192 repeat: {}, //detect position repetition
193 curDiag: "", //for corr moves confirmation
195 roomInitialized: false,
196 // If newmove has wrong index: ask fullgame again:
198 gameIsLoading: false,
199 // If asklastate got no reply, ask again:
201 gotMoveIdx: -1, //last move index received
202 // If newmove got no pingback, send again:
203 opponentGotMove: false,
205 socketCloseListener: 0,
206 // Incomplete info games: show move played
208 // Intervals from setInterval():
212 // Related to (killing of) self multi-connects:
217 $route: function(to, from) {
218 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
220 this.cleanBeforeDestroy();
221 else if (from.params["id"] != to.params["id"]) {
222 // Change everything:
223 this.cleanBeforeDestroy();
224 let boardDiv = document.querySelector(".game");
226 // In case of incomplete information variant:
227 boardDiv.style.visibility = "hidden";
231 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
234 // NOTE: some redundant code with Hall.vue (mostly related to people array)
235 created: function() {
238 mounted: function() {
239 ["chatWrap", "infoDiv"].forEach(eltName => {
240 document.getElementById(eltName)
241 .addEventListener("click", processModalClick);
243 if ("ontouchstart" in window) {
244 // Disable tooltips on smartphones:
245 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
246 elt.classList.remove("tooltip");
250 beforeDestroy: function() {
251 this.cleanBeforeDestroy();
254 cleanBeforeDestroy: function() {
255 clearInterval(this.socketCloseListener);
256 document.removeEventListener('visibilitychange', this.visibilityChange);
257 window.removeEventListener('focus', this.onFocus);
258 window.removeEventListener('blur', this.onBlur);
259 if (!!this.askLastate) clearInterval(this.askLastate);
260 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
261 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
262 this.conn.removeEventListener("message", this.socketMessageListener);
263 this.send("disconnect");
266 visibilityChange: function() {
267 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
268 this.focus = (document.visibilityState == "visible");
269 if (!this.focus && !!this.rematchOffer) {
270 this.rematchOffer = "";
271 this.send("rematchoffer", { data: false });
272 // Do not remove rematch offer from (local) storage
274 this.send(this.focus ? "getfocus" : "losefocus");
276 onFocus: function() {
278 this.send("getfocus");
282 if (!!this.rematchOffer) {
283 this.rematchOffer = "";
284 this.send("rematchoffer", { data: false });
286 this.send("losefocus");
288 isLargeScreen: function() {
289 return window.innerWidth >= 500;
291 participateInChat: function(p) {
292 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
294 someAnonymousPresent: function() {
296 Object.values(this.people).some(p =>
297 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
301 atCreation: function() {
302 document.addEventListener('visibilitychange', this.visibilityChange);
303 window.addEventListener('focus', this.onFocus);
304 window.addEventListener('blur', this.onBlur);
305 // 0] (Re)Set variables
306 this.gameRef = this.$route.params["id"];
307 // next = next corr games IDs to navigate faster (if applicable)
308 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
309 // Always add myself to players' list
310 const my = this.st.user;
311 const tmpId = getRandString();
319 tmpId: { focus: true }
324 players: [{ name: "" }, { name: "" }],
328 let chatComp = this.$refs["chatcomp"];
329 if (!!chatComp) chatComp.chats = [];
330 this.virtualClocks = [[0,0], [0,0]];
333 this.lastateAsked = false;
334 this.rematchOffer = "";
335 this.lastate = undefined;
336 this.roomInitialized = false;
337 this.askGameTime = 0;
338 this.gameIsLoading = false;
339 this.gotLastate = false;
340 this.gotMoveIdx = -1;
341 this.opponentGotMove = false;
342 this.askLastate = null;
343 this.retrySendmove = null;
344 this.clockUpdate = null;
345 this.newConnect = {};
346 // 1] Initialize connection
347 this.connexionString =
349 "/?sid=" + this.st.user.sid +
350 "&id=" + this.st.user.id +
353 // Discard potential "/?next=[...]" for page indication:
354 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
355 this.conn = new WebSocket(this.connexionString);
356 this.conn.addEventListener("message", this.socketMessageListener);
357 this.socketCloseListener = setInterval(
359 if (this.conn.readyState == 3) {
360 this.conn.removeEventListener(
361 "message", this.socketMessageListener);
362 this.conn = new WebSocket(this.connexionString);
363 this.conn.addEventListener("message", this.socketMessageListener);
368 // Socket init required before loading remote game:
369 const socketInit = callback => {
370 if (this.conn.readyState == 1)
374 // Socket not ready yet (initial loading)
375 // NOTE: first arg is Websocket object, unused here:
376 this.conn.onopen = () => callback();
378 this.fetchGame((game) => {
380 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
382 // Live game stored remotely: need socket to retrieve it
383 // NOTE: the callback "roomInit" will be lost, so it's not provided.
384 // --> It will be given when receiving "fullgame" socket event.
385 socketInit(() => { this.send("askfullgame"); });
388 roomInit: function() {
389 if (!this.roomInitialized) {
390 // Notify the room only now that I connected, because
391 // messages might be lost otherwise (if game loading is slow)
392 this.send("connect");
393 this.send("pollclients");
394 // We may ask fullgame several times if some moves are lost,
395 // but room should be init only once:
396 this.roomInitialized = true;
399 send: function(code, obj) {
400 if (!!this.conn && this.conn.readyState == 1)
401 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
403 isConnected: function(index) {
404 const player = this.game.players[index];
405 // Is it me ? In this case no need to bother with focus
406 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
407 // Still have to check for name (because of potential multi-accounts
408 // on same browser, although this should be rare...)
409 return (!this.st.user.name || this.st.user.name == player.name);
410 // Try to find a match in people:
414 Object.keys(this.people).some(sid => {
417 Object.values(this.people[sid].tmpIds).some(v => v.focus)
424 Object.values(this.people).some(p => {
427 Object.values(p.tmpIds).some(v => v.focus)
433 getOppsid: function() {
434 let oppsid = this.game.oppsid;
436 oppsid = Object.keys(this.people).find(
437 sid => this.people[sid].id == this.game.oppid
440 // oppsid is useful only if opponent is online:
441 if (!!oppsid && !!this.people[oppsid]) return oppsid;
444 toggleChat: function() {
445 if (document.getElementById("modalChat").checked)
447 document.getElementById("inputChat").focus();
448 // TODO: next line is only required when exiting chat,
449 // but the event for now isn't well detected.
450 document.getElementById("chatBtn").classList.remove("somethingnew");
452 processChat: function(chat) {
453 this.send("newchat", { data: chat });
454 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
455 if (this.game.type == "corr" && this.st.user.id > 0)
456 this.updateCorrGame({ chat: chat });
457 else if (this.game.type == "live") {
458 chat.added = Date.now();
459 GameStorage.update(this.gameRef, { chat: chat });
462 clearChat: function() {
463 if (!!this.game.mycolor) {
464 if (this.game.type == "corr") {
468 { data: { gid: this.game.id } }
472 GameStorage.update(this.gameRef, { delchat: true });
474 this.$set(this.game, "chats", []);
477 getGameType: function(game) {
478 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
480 // Notify something after a new move (to opponent and me on MyGames page)
481 notifyMyGames: function(thing, data) {
486 targets: this.game.players.map(p => {
487 return { sid: p.sid, id: p.id };
492 showNextGame: function() {
493 // Did I play in current game? If not, add it to nextIds list
494 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
495 this.nextIds.unshift(this.game.id);
496 const nextGid = this.nextIds.pop();
498 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
500 askGameAgain: function() {
501 this.gameIsLoading = true;
502 const currentUrl = document.location.href;
503 const doAskGame = () => {
504 if (document.location.href != currentUrl) return; //page change
505 this.fetchGame((game) => {
507 // This is my game: just reload.
510 // Just ask fullgame again (once!), this is much simpler.
511 // If this fails, the user could just reload page :/
512 this.send("askfullgame");
515 // Delay of at least 2s between two game requests
516 const now = Date.now();
517 const delay = Math.max(2000 - (now - this.askGameTime), 0);
518 this.askGameTime = now;
519 setTimeout(doAskGame, delay);
521 socketMessageListener: function(msg) {
522 if (!this.conn) return;
523 const data = JSON.parse(msg.data);
526 // TODO: shuffling and random filtering on server,
527 // if the room is really crowded.
528 Object.keys(data.sockIds).forEach(sid => {
529 if (sid != this.st.user.sid) {
530 this.send("askidentity", { target: sid });
531 this.people[sid] = { tmpIds: data.sockIds[sid] };
533 // Complete my tmpIds:
534 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
539 if (!this.people[data.from[0]]) {
540 // focus depends on the tmpId (e.g. tab)
546 [data.from[1]]: { focus: true }
550 // For self multi-connects tests:
551 this.newConnect[data.from[0]] = true;
552 this.send("askidentity", { target: data.from[0] });
554 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
555 this.$forceUpdate(); //TODO: shouldn't be required
559 if (!this.people[data.from[0]]) return;
560 delete this.people[data.from[0]].tmpIds[data.from[1]];
561 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
562 this.$delete(this.people, data.from[0]);
563 else this.$forceUpdate(); //TODO: shouldn't be required
566 let player = this.people[data.from[0]];
568 player.tmpIds[data.from[1]].focus = true;
569 this.$forceUpdate(); //TODO: shouldn't be required
574 let player = this.people[data.from[0]];
576 player.tmpIds[data.from[1]].focus = false;
577 this.$forceUpdate(); //TODO: shouldn't be required
581 case "askidentity": {
582 // Request for identification
584 // Decompose to avoid revealing email
585 name: this.st.user.name,
586 sid: this.st.user.sid,
589 this.send("identity", { data: me, target: data.from });
593 const user = data.data;
594 let player = this.people[user.sid];
595 // player.tmpIds is already set
596 player.name = user.name;
598 this.$forceUpdate(); //TODO: shouldn't be required
599 // If I multi-connect, kill current connexion if no mark (I'm older)
600 if (this.newConnect[user.sid]) {
601 delete this.newConnect[user.sid];
604 user.id == this.st.user.id &&
605 user.sid != this.st.user.sid
607 this.cleanBeforeDestroy();
608 alert(this.st.tr["New connexion detected: tab now offline"]);
612 // Ask potentially missed last state, if opponent and I play
615 !!this.game.mycolor &&
616 this.game.type == "live" &&
617 this.game.score == "*" &&
618 this.game.players.some(p => p.sid == user.sid)
620 this.send("asklastate", { target: user.sid });
622 this.askLastate = setInterval(
624 // Ask at most 3 times:
625 // if no reply after that there should be a network issue.
629 !!this.people[user.sid]
631 this.send("asklastate", { target: user.sid });
634 clearInterval(this.askLastate);
643 // Send current (live) game if not asked by any of the players
645 this.game.type == "live" &&
646 this.game.players.every(p => p.sid != data.from[0])
651 players: this.game.players,
653 cadence: this.game.cadence,
654 score: this.game.score
656 this.send("game", { data: myGame, target: data.from });
660 const gameToSend = Object.keys(this.game)
663 "id","fen","players","vid","cadence","fenStart","vname",
664 "moves","clocks","score","drawOffer","rematchOffer"
668 obj[k] = this.game[k];
673 this.send("fullgame", { data: gameToSend, target: data.from });
676 if (!!data.data.empty) {
677 alert(this.st.tr["The game should be in another tab"]);
681 // Callback "roomInit" to poll clients only after game is loaded
682 this.loadVariantThenGame(data.data, this.roomInit);
685 // Sending informative last state if I played a move or score != "*"
686 // If the game or moves aren't loaded yet, delay the sending:
687 // TODO: socket init after game load, so the game is supposedly ready
688 if (!this.game || !this.game.moves) this.lastateAsked = true;
689 else this.sendLastate(data.from);
692 // Got opponent infos about last move
693 this.gotLastate = true;
694 this.lastate = data.data;
695 if (this.game.rendered)
696 // Game is rendered (Board component)
697 this.processLastate();
698 // Else: will be processed when game is ready
702 const movePlus = data.data;
703 const movesCount = this.game.moves.length;
704 if (movePlus.index > movesCount) {
705 // This can only happen if I'm an observer and missed a move.
706 if (this.gotMoveIdx < movePlus.index)
707 this.gotMoveIdx = movePlus.index;
708 if (!this.gameIsLoading) this.askGameAgain();
712 movePlus.index < movesCount ||
713 this.gotMoveIdx >= movePlus.index
715 // Opponent re-send but we already have the move:
716 // (maybe he didn't receive our pingback...)
717 this.send("gotmove", {data: movePlus.index, target: data.from});
719 this.gotMoveIdx = movePlus.index;
720 const receiveMyMove = (movePlus.color == this.game.mycolor);
721 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
722 if (!receiveMyMove && !!this.game.mycolor) {
723 // Notify opponent that I got the move:
726 { data: movePlus.index, target: data.from }
728 // And myself if I'm elsewhere:
734 (this.game.players[moveColIdx].name || "@nonymous") +
740 if (movePlus.cancelDrawOffer) {
741 // Opponent refuses draw
743 // NOTE for corr games: drawOffer reset by player in turn
745 this.game.type == "live" &&
746 !!this.game.mycolor &&
749 GameStorage.update(this.gameRef, { drawOffer: "" });
752 this.$refs["basegame"].play(
753 movePlus.move, "received", null, true);
754 this.game.clocks[moveColIdx] = movePlus.clock;
757 { receiveMyMove: receiveMyMove }
764 this.opponentGotMove = true;
765 // Now his clock starts running on my side:
766 const oppIdx = ['w','b'].indexOf(this.vr.turn);
767 // NOTE: next line to avoid multi-resetClocks when several tabs
768 // on same game, resulting in a faster countdown.
769 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
774 const score = (data.data == "b" ? "1-0" : "0-1");
775 const side = (data.data == "w" ? "White" : "Black");
776 this.gameOver(score, side + " surrender");
779 this.gameOver("?", "Stop");
782 this.gameOver("1/2", data.data);
785 // NOTE: observers don't know who offered draw
786 this.drawOffer = "received";
787 if (this.game.type == "live") {
790 { drawOffer: V.GetOppCol(this.game.mycolor) }
795 // NOTE: observers don't know who offered rematch
796 this.rematchOffer = data.data ? "received" : "";
797 if (this.game.type == "live") {
800 { rematchOffer: V.GetOppCol(this.game.mycolor) }
805 // A game started, redirect if I'm playing in
806 const gameInfo = data.data;
807 const gameType = this.getGameType(gameInfo);
809 gameType == "live" &&
810 gameInfo.players.some(p => p.sid == this.st.user.sid)
812 this.addAndGotoLiveGame(gameInfo);
814 gameType == "corr" &&
815 gameInfo.players.some(p => p.id == this.st.user.id)
817 this.$router.push("/game/" + gameInfo.id);
819 this.rematchId = gameInfo.id;
820 document.getElementById("modalInfo").checked = true;
825 let chat = data.data;
826 this.$refs["chatcomp"].newChat(chat);
827 if (this.game.type == "live") {
828 chat.added = Date.now();
829 GameStorage.update(this.gameRef, { chat: chat });
831 if (!document.getElementById("modalChat").checked)
832 document.getElementById("chatBtn").classList.add("somethingnew");
837 updateCorrGame: function(obj, callback) {
847 if (!!callback) callback();
852 sendLastate: function(target) {
853 // Send our "last state" informations to opponent
854 const L = this.game.moves.length;
855 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
858 (L > 0 && this.vr.turn != this.game.mycolor)
859 ? this.game.moves[L - 1]
861 clock: this.game.clocks[myIdx],
862 // Since we played a move (or abort or resign),
863 // only drawOffer=="sent" is possible
864 drawSent: this.drawOffer == "sent",
865 rematchSent: this.rematchOffer == "sent",
866 score: this.game.score != "*" ? this.game.score : undefined,
867 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
870 this.send("lastate", { data: myLastate, target: target });
872 // lastate was received, but maybe game wasn't ready yet:
873 processLastate: function() {
874 const data = this.lastate;
875 this.lastate = undefined; //security...
876 const L = this.game.moves.length;
877 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
878 this.game.clocks[oppIdx] = data.clock;
879 if (data.movesCount > L) {
880 // Just got last move from him
881 this.$refs["basegame"].play(data.lastMove, "received", null, true);
882 this.processMove(data.lastMove);
884 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
887 if (data.drawSent) this.drawOffer = "received";
888 if (data.rematchSent) this.rematchOffer = "received";
891 if (this.game.score == "*")
892 this.gameOver(data.score, data.scoreMsg);
895 clickDraw: function() {
896 if (!this.game.mycolor) return; //I'm just spectator
897 if (["received", "threerep"].includes(this.drawOffer)) {
898 if (!confirm(this.st.tr["Accept draw?"])) return;
900 this.drawOffer == "received"
902 : "Three repetitions";
903 this.send("draw", { data: message });
904 this.gameOver("1/2", message);
905 } else if (this.drawOffer == "") {
906 // No effect if drawOffer == "sent"
907 if (this.game.mycolor != this.vr.turn) {
908 alert(this.st.tr["Draw offer only in your turn"]);
911 if (!confirm(this.st.tr["Offer draw?"])) return;
912 this.drawOffer = "sent";
913 this.send("drawoffer");
914 if (this.game.type == "live") {
917 { drawOffer: this.game.mycolor }
919 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
922 addAndGotoLiveGame: function(gameInfo, callback) {
923 const game = Object.assign(
927 // (other) Game infos: constant
928 fenStart: gameInfo.fen,
929 vname: this.game.vname,
931 // Game state (including FEN): will be updated
933 clocks: [-1, -1], //-1 = unstarted
937 GameStorage.add(game, (err) => {
938 // No error expected.
940 if (this.st.settings.sound)
941 new Audio("/sounds/newgame.flac").play().catch(() => {});
942 if (!!callback) callback();
943 this.$router.push("/game/" + gameInfo.id);
947 clickRematch: function() {
948 if (!this.game.mycolor) return; //I'm just spectator
949 if (this.rematchOffer == "received") {
952 id: getRandString(), //ignored if corr
953 fen: V.GenRandInitFen(this.game.randomness),
954 players: this.game.players.reverse(),
956 cadence: this.game.cadence
958 const notifyNewGame = () => {
959 const oppsid = this.getOppsid(); //may be null
960 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
961 // To main Hall if corr game:
962 if (this.game.type == "corr")
963 this.send("newgame", { data: gameInfo, page: "/" });
964 // Also to MyGames page:
965 this.notifyMyGames("newgame", gameInfo);
967 if (this.game.type == "live")
968 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
975 // cid is useful to delete the challenge:
976 data: { gameInfo: gameInfo },
977 success: (response) => {
978 gameInfo.id = response.gameId;
980 this.$router.push("/game/" + response.gameId);
985 } else if (this.rematchOffer == "") {
986 this.rematchOffer = "sent";
987 this.send("rematchoffer", { data: true });
988 if (this.game.type == "live") {
991 { rematchOffer: this.game.mycolor }
993 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
994 } else if (this.rematchOffer == "sent") {
995 // Toggle rematch offer (on --> off)
996 this.rematchOffer = "";
997 this.send("rematchoffer", { data: false });
998 if (this.game.type == "live") {
1001 { rematchOffer: '' }
1003 } else this.updateCorrGame({ rematchOffer: 'n' });
1006 abortGame: function() {
1007 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1009 this.gameOver("?", "Stop");
1012 resign: function() {
1013 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1015 this.send("resign", { data: this.game.mycolor });
1016 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1017 const side = (this.game.mycolor == "w" ? "White" : "Black");
1018 this.gameOver(score, side + " surrender");
1020 loadGame: function(game, callback) {
1021 this.vr = new V(game.fen);
1022 const gtype = this.getGameType(game);
1023 const tc = extractTime(game.cadence);
1024 const myIdx = game.players.findIndex(p => {
1025 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1027 // "mycolor" is undefined for observers
1028 const mycolor = [undefined, "w", "b"][myIdx + 1];
1029 // Live games before 26/03/2020 don't have chat history:
1030 if (!game.chats) game.chats = []; //TODO: remove line
1031 // Sort chat messages from newest to oldest
1032 game.chats.sort((c1, c2) => c2.added - c1.added);
1033 if (gtype == "corr") {
1034 // NOTE: clocks in seconds
1035 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1036 game.clocks = [tc.mainTime, tc.mainTime];
1037 const L = game.moves.length;
1038 if (game.score == "*") {
1041 game.clocks[L % 2] -=
1042 (Date.now() - game.moves[L-1].played) / 1000;
1045 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
1046 // Did a chat message arrive after my last move?
1048 if (L == 1 && myIdx == 0)
1049 dtLastMove = game.moves[0].played;
1052 // It's now white turn
1053 dtLastMove = game.moves[L-1-(1-myIdx)].played;
1056 dtLastMove = game.moves[L-1-myIdx].played;
1059 if (dtLastMove < game.chats[0].added)
1060 document.getElementById("chatBtn").classList.add("somethingnew");
1062 // Now that we used idx and played, re-format moves as for live games
1063 game.moves = game.moves.map(m => m.squares);
1065 if (gtype == "live") {
1067 game.chats.length > 0 &&
1068 (!game.initime || game.initime < game.chats[0].added)
1070 document.getElementById("chatBtn").classList.add("somethingnew");
1072 if (game.clocks[0] < 0) {
1073 // Game is unstarted. clock is ignored until move 2
1074 game.clocks = [tc.mainTime, tc.mainTime];
1076 // I play in this live game
1077 GameStorage.update(game.id, {
1083 // It's my turn: clocks not updated yet
1084 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1087 // TODO: merge next 2 "if" conditions
1088 if (!!game.drawOffer) {
1089 if (game.drawOffer == "t")
1090 // Three repetitions
1091 this.drawOffer = "threerep";
1093 // Draw offered by any of the players:
1094 if (myIdx < 0) this.drawOffer = "received";
1096 // I play in this game:
1098 (game.drawOffer == "w" && myIdx == 0) ||
1099 (game.drawOffer == "b" && myIdx == 1)
1101 this.drawOffer = "sent";
1102 else this.drawOffer = "received";
1106 if (!!game.rematchOffer) {
1107 if (myIdx < 0) this.rematchOffer = "received";
1109 // I play in this game:
1111 (game.rematchOffer == "w" && myIdx == 0) ||
1112 (game.rematchOffer == "b" && myIdx == 1)
1114 this.rematchOffer = "sent";
1115 else this.rematchOffer = "received";
1118 this.repeat = {}; //reset: scan past moves' FEN:
1120 let vr_tmp = new V(game.fenStart);
1122 game.moves.forEach(m => {
1123 playMove(m, vr_tmp);
1124 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1125 this.repeat[fenIdx] = this.repeat[fenIdx]
1126 ? this.repeat[fenIdx] + 1
1129 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1130 this.game = Object.assign(
1131 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1134 increment: tc.increment,
1136 // opponent sid not strictly required (or available), but easier
1137 // at least oppsid or oppid is available anyway:
1138 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1139 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1143 this.$refs["basegame"].re_setVariables(this.game);
1144 if (!this.gameIsLoading) {
1146 this.gotMoveIdx = game.moves.length - 1;
1147 // If we arrive here after 'nextGame' action, the board might be hidden
1148 let boardDiv = document.querySelector(".game");
1149 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1150 boardDiv.style.visibility = "visible";
1152 this.re_setClocks();
1153 this.$nextTick(() => {
1154 this.game.rendered = true;
1155 // Did lastate arrive before game was rendered?
1156 if (this.lastate) this.processLastate();
1158 if (this.lastateAsked) {
1159 this.lastateAsked = false;
1160 this.sendLastate(game.oppsid);
1162 if (this.gameIsLoading) {
1163 this.gameIsLoading = false;
1164 if (this.gotMoveIdx >= game.moves.length)
1165 // Some moves arrived meanwhile...
1166 this.askGameAgain();
1168 if (!!callback) callback();
1170 loadVariantThenGame: async function(game, callback) {
1171 await import("@/variants/" + game.vname + ".js")
1172 .then((vModule) => {
1173 window.V = vModule[game.vname + "Rules"];
1174 this.loadGame(game, callback);
1177 // 3 cases for loading a game:
1178 // - from indexedDB (running or completed live game I play)
1179 // - from server (one correspondance game I play[ed] or not)
1180 // - from remote peer (one live game I don't play, finished or not)
1181 fetchGame: function(callback) {
1182 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1183 // corr games identifiers are integers
1188 data: { gid: this.gameRef },
1190 res.game.moves.forEach(m => {
1191 m.squares = JSON.parse(m.squares);
1198 else if (!!this.gameRef.match(/^I_/))
1199 // Game import (maybe remote)
1200 ImportgameStorage.get(this.gameRef, callback);
1202 // Local live game (or remote)
1203 GameStorage.get(this.gameRef, callback);
1205 re_setClocks: function() {
1206 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1207 if (this.game.moves.length < 2 || this.game.score != "*") {
1208 // 1st move not completed yet, or game over: freeze time
1211 const currentTurn = this.vr.turn;
1212 const currentMovesCount = this.game.moves.length;
1213 const colorIdx = ["w", "b"].indexOf(currentTurn);
1214 this.clockUpdate = setInterval(
1217 this.game.clocks[colorIdx] < 0 ||
1218 this.game.moves.length > currentMovesCount ||
1219 this.game.score != "*"
1221 clearInterval(this.clockUpdate);
1222 this.clockUpdate = null;
1223 if (this.game.clocks[colorIdx] < 0)
1225 currentTurn == "w" ? "0-1" : "1-0",
1232 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1239 // Update variables and storage after a move:
1240 processMove: function(move, data) {
1241 if (!data) data = {};
1242 const moveCol = this.vr.turn;
1243 const colorIdx = ["w", "b"].indexOf(moveCol);
1244 const nextIdx = 1 - colorIdx;
1245 const doProcessMove = () => {
1246 const origMovescount = this.game.moves.length;
1247 // The move is (about to be) played: stop clock
1248 clearInterval(this.clockUpdate);
1249 this.clockUpdate = null;
1250 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1251 if (this.drawOffer == "received")
1253 this.drawOffer = "";
1254 if (this.game.type == "live" && origMovescount >= 2) {
1255 this.game.clocks[colorIdx] += this.game.increment;
1256 // For a correct display in casqe of disconnected opponent:
1260 ppt(this.game.clocks[colorIdx]).split(':')
1262 GameStorage.update(this.gameRef, {
1263 // It's not my turn anymore:
1268 // Update current game object:
1269 playMove(move, this.vr);
1271 // Received move, score is computed in BaseGame, but maybe not yet.
1272 // ==> Compute it here, although this is redundant (TODO)
1273 data.score = this.vr.getCurrentScore();
1274 if (data.score != "*") this.gameOver(data.score);
1275 this.game.moves.push(move);
1276 this.game.fen = this.vr.getFen();
1277 if (this.game.type == "corr") {
1278 // In corr games, just reset clock to mainTime:
1279 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1281 // If repetition detected, consider that a draw offer was received:
1282 const fenObj = this.vr.getFenForRepeat();
1283 this.repeat[fenObj] =
1284 !!this.repeat[fenObj]
1285 ? this.repeat[fenObj] + 1
1287 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1288 else if (this.drawOffer == "threerep") this.drawOffer = "";
1289 if (!!this.game.mycolor && !data.receiveMyMove) {
1290 // NOTE: 'var' to see that variable outside this block
1291 var filtered_move = getFilteredMove(move);
1293 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1294 // Notify turn on MyGames page:
1303 // Since corr games are stored at only one location, update should be
1304 // done only by one player for each move:
1306 this.game.type == "live" &&
1307 !!this.game.mycolor &&
1308 moveCol != this.game.mycolor &&
1309 this.game.moves.length >= 2
1311 // Receive a move: update initime
1312 this.game.initime = Date.now();
1313 GameStorage.update(this.gameRef, {
1314 // It's my turn now!
1315 initime: this.game.initime
1319 !!this.game.mycolor &&
1320 !data.receiveMyMove &&
1321 (this.game.type == "live" || moveCol == this.game.mycolor)
1324 switch (this.drawOffer) {
1329 drawCode = this.game.mycolor;
1332 drawCode = V.GetOppCol(this.game.mycolor);
1335 if (this.game.type == "corr") {
1336 // corr: only move, fen and score
1337 this.updateCorrGame({
1340 squares: filtered_move,
1343 // Code "n" for "None" to force reset (otherwise it's ignored)
1344 drawOffer: drawCode || "n"
1348 const updateStorage = () => {
1349 GameStorage.update(this.gameRef, {
1351 move: filtered_move,
1352 moveIdx: origMovescount,
1353 clocks: this.game.clocks,
1357 // The active tab can update storage immediately
1358 if (this.focus) updateStorage();
1359 // Small random delay otherwise
1360 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1363 // Send move ("newmove" event) to people in the room (if our turn)
1364 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1366 move: filtered_move,
1367 index: origMovescount,
1368 // color is required to check if this is my move
1369 // (if several tabs opened)
1371 cancelDrawOffer: this.drawOffer == ""
1373 if (this.game.type == "live")
1374 sendMove["clock"] = this.game.clocks[colorIdx];
1375 // (Live) Clocks will re-start when the opponent pingback arrive
1376 this.opponentGotMove = false;
1377 this.send("newmove", {data: sendMove});
1378 // If the opponent doesn't reply gotmove soon enough, re-send move:
1379 // Do this at most 2 times, because mpore would mean network issues,
1380 // opponent would then be expected to disconnect/reconnect.
1382 const currentUrl = document.location.href;
1383 this.retrySendmove = setInterval(
1387 this.opponentGotMove ||
1388 document.location.href != currentUrl //page change
1390 clearInterval(this.retrySendmove);
1393 const oppsid = this.getOppsid();
1395 // Opponent is disconnected: he'll ask last state
1396 clearInterval(this.retrySendmove);
1398 this.send("newmove", { data: sendMove, target: oppsid });
1406 // Not my move or I'm an observer: just start other player's clock
1407 this.re_setClocks();
1410 this.game.type == "corr" &&
1411 moveCol == this.game.mycolor &&
1414 let boardDiv = document.querySelector(".game");
1415 const afterSetScore = () => {
1417 if (this.st.settings.gotonext && this.nextIds.length > 0)
1418 this.showNextGame();
1420 // The board might have been hidden:
1421 if (boardDiv.style.visibility == "hidden")
1422 boardDiv.style.visibility = "visible";
1423 if (data.score == "*") this.re_setClocks();
1426 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1427 // We may play several moves in a row: in case of, remove listener:
1428 let elClone = el.cloneNode(true);
1429 el.parentNode.replaceChild(elClone, el);
1430 elClone.addEventListener(
1433 document.getElementById("modalConfirm").checked = false;
1434 if (!!data.score && data.score != "*")
1436 this.gameOver(data.score, null, afterSetScore);
1437 else afterSetScore();
1440 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1441 V.PlayOnBoard(this.vr.board, move);
1442 const position = this.vr.getBaseFen();
1443 V.UndoOnBoard(this.vr.board, move);
1444 if (["all","byrow"].includes(V.ShowMoves)) {
1445 this.curDiag = getDiagram({
1447 orientation: V.CanFlip ? this.game.mycolor : "w"
1449 document.querySelector("#confirmDiv > .card").style.width =
1450 boardDiv.offsetWidth + "px";
1452 // Incomplete information: just ask confirmation
1453 // Hide the board, because otherwise it could reveal infos
1454 boardDiv.style.visibility = "hidden";
1455 this.moveNotation = getFullNotation(move);
1457 document.getElementById("modalConfirm").checked = true;
1461 if (!!data.score && data.score != "*")
1462 this.gameOver(data.score, null, doProcessMove);
1463 else doProcessMove();
1466 cancelMove: function() {
1467 let boardDiv = document.querySelector(".game");
1468 if (boardDiv.style.visibility == "hidden")
1469 boardDiv.style.visibility = "visible";
1470 document.getElementById("modalConfirm").checked = false;
1471 this.$refs["basegame"].cancelLastMove();
1473 // In corr games, callback to change page only after score is set:
1474 gameOver: function(score, scoreMsg, callback) {
1475 this.game.score = score;
1476 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1477 this.game.scoreMsg = scoreMsg;
1478 this.$set(this.game, "scoreMsg", scoreMsg);
1479 const myIdx = this.game.players.findIndex(p => {
1480 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1483 // OK, I play in this game
1488 if (this.game.type == "live") {
1489 GameStorage.update(this.gameRef, scoreObj);
1490 // Notify myself locally if I'm elsewhere:
1494 { body: score + " : " + scoreMsg }
1497 if (!!callback) callback();
1499 else this.updateCorrGame(scoreObj, callback);
1500 // Notify the score to main Hall.
1501 // TODO: only one player (currently double send)
1502 this.send("result", { gid: this.game.id, score: score });
1503 // Also to MyGames page (TODO: doubled as well...)
1512 else if (!!callback) callback();
1518 <style lang="sass" scoped>
1524 background-color: lightgreen
1536 @media screen and (min-width: 768px)
1539 @media screen and (max-width: 767px)
1544 display: inline-block
1548 display: inline-block
1550 display: inline-flex
1554 @media screen and (max-width: 767px)
1557 @media screen and (max-width: 767px)
1560 @media screen and (min-width: 768px)
1572 background-color: #edda99
1574 display: inline-block
1583 display: inline-block
1596 animation: blink-animation 2s steps(3, start) infinite
1597 @keyframes blink-animation
1602 display: inline-block
1614 .draw-sent, .draw-sent:hover
1615 background-color: lightyellow
1617 .draw-received, .draw-received:hover
1618 background-color: lightgreen
1620 .draw-threerep, .draw-threerep:hover
1621 background-color: #e4d1fc
1623 .rematch-sent, .rematch-sent:hover
1624 background-color: lightyellow
1626 .rematch-received, .rematch-received:hover
1627 background-color: lightgreen
1630 background-color: #c5fefe
1643 background-color: lightgreen
1645 background-color: red