3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vdisp }}
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 }}
83 | {{ !!vr ? vr.constructor.AbbreviateOptions(game.options) : '' }}
85 v-if="nextIds.length > 0"
86 @click="showNextGame()"
88 | {{ st.tr["Next_g"] }}
90 :class="btnTooltipClass()"
91 onClick="window.doClick('modalChat')"
94 img(src="/images/icons/chat.svg")
95 #actions(v-if="game.score=='*'")
98 :class="btnTooltipClass('draw')"
99 :aria-label="st.tr['Draw']"
101 img(src="/images/icons/draw.svg")
103 v-if="!!game.mycolor"
104 :class="btnTooltipClass()"
106 :aria-label="st.tr['Abort']"
108 img(src="/images/icons/abort.svg")
110 v-if="!!game.mycolor"
111 :class="btnTooltipClass()"
113 :aria-label="st.tr['Resign']"
115 img(src="/images/icons/resign.svg")
118 :class="btnTooltipClass('rematch')"
119 @click="clickRematch()"
120 :aria-label="st.tr['Rematch']"
122 img(src="/images/icons/rematch.svg")
124 div(v-if="isLargeScreen()")
126 :class="{connected: isConnected(0)}"
127 :uid="game.players[0].id"
128 :uname="game.players[0].name"
131 v-if="game.score=='*'"
132 :class="{yourturn: !!vr && vr.turn == 'w'}"
134 span.time-left {{ virtualClocks[0][0] }}
135 span.time-separator(v-if="!!virtualClocks[0][1]") :
136 span.time-right(v-if="!!virtualClocks[0][1]")
137 | {{ virtualClocks[0][1] }}
140 :class="{connected: isConnected(1)}"
141 :uid="game.players[1].id"
142 :uname="game.players[1].name"
145 v-if="game.score=='*'"
146 :class="{yourturn: !!vr && vr.turn == 'b'}"
148 span.time-left {{ virtualClocks[1][0] }}
149 span.time-separator(v-if="!!virtualClocks[1][1]") :
150 span.time-right(v-if="!!virtualClocks[1][1]")
151 | {{ virtualClocks[1][1] }}
154 :class="{connected: isConnected(0)}"
155 :uid="game.players[0].id"
156 :uname="game.players[0].name"
160 :class="{connected: isConnected(1)}"
161 :uid="game.players[1].id"
162 :uname="game.players[1].name"
164 div(v-if="game.score=='*'")
165 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
166 span.time-left {{ virtualClocks[0][0] }}
167 span.time-separator(v-if="!!virtualClocks[0][1]") :
168 span.time-right(v-if="!!virtualClocks[0][1]")
169 | {{ virtualClocks[0][1] }}
171 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
172 span.time-left {{ virtualClocks[1][0] }}
173 span.time-separator(v-if="!!virtualClocks[1][1]") :
174 span.time-right(v-if="!!virtualClocks[1][1]")
175 | {{ virtualClocks[1][1] }}
179 @newmove="processMove"
184 import BaseGame from "@/components/BaseGame.vue";
185 import UserBio from "@/components/UserBio.vue";
186 import Chat from "@/components/Chat.vue";
187 import { store } from "@/store";
188 import { GameStorage } from "@/utils/gameStorage";
189 import { ImportgameStorage } from "@/utils/importgameStorage";
190 import { ppt } from "@/utils/datetime";
191 import { notify } from "@/utils/notifications";
192 import { ajax } from "@/utils/ajax";
193 import { extractTime } from "@/utils/timeControl";
194 import { getRandString } from "@/utils/alea";
195 import { getScoreMessage } from "@/utils/scoring";
196 import { getFullNotation } from "@/utils/notation";
197 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
198 import { processModalClick } from "@/utils/modalClick";
199 import { playMove, getFilteredMove } from "@/utils/playUndo";
200 import { ArrayFun } from "@/utils/array";
201 import afterRawLoad from "@/utils/afterRawLoad";
202 import params from "@/parameters";
213 // gameRef can point to a corr game, local game or remote live game
216 game: {}, //passed to BaseGame
217 focus: !document.hidden, //will not always work... TODO
218 // virtualClocks will be initialized from true game.clocks
219 // TODO: clock update triggers re-rendering. Should be out of Vue
221 vr: null, //"variant rules" object initialized from FEN
227 people: {}, //players + observers
228 lastate: undefined, //used if opponent send lastate before game is ready
229 repeat: {}, //detect position repetition
230 curDiag: "", //for corr moves confirmation
232 roomInitialized: false,
233 // If asklastate got no reply, ask again:
235 gotMoveIdx: -1, //last move index received
236 // If newmove got no pingback, send again:
237 opponentGotMove: false,
241 // Incomplete info games: show move played
243 // Intervals from setInterval():
247 // Related to (killing of) self multi-connects:
252 $route: function(to, from) {
253 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
255 this.cleanBeforeDestroy();
256 else if (from.params["id"] != to.params["id"]) {
257 // Change everything:
258 this.cleanBeforeDestroy();
259 let boardDiv = document.querySelector(".game");
261 // In case of incomplete information variant:
262 boardDiv.style.visibility = "hidden";
267 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
270 // NOTE: some redundant code with Hall.vue (mostly related to people array)
271 created: function() {
274 mounted: function() {
275 document.getElementById("chatWrap")
276 .addEventListener("click", (e) => {
277 processModalClick(e, () => {
278 this.toggleChat("close")
281 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
283 document.getElementById(eltName)
284 .addEventListener("click", processModalClick);
288 beforeDestroy: function() {
289 this.cleanBeforeDestroy();
292 cleanBeforeDestroy: function() {
293 document.removeEventListener('visibilitychange', this.visibilityChange);
294 window.removeEventListener('focus', this.onFocus);
295 window.removeEventListener('blur', this.onBlur);
296 if (!!this.askLastate) clearInterval(this.askLastate);
297 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
298 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
299 clearTimeout(this.reopenTimeout);
300 this.send("disconnect");
303 visibilityChange: function() {
304 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
305 this.focus = (document.visibilityState == "visible");
306 this.send(this.focus ? "getfocus" : "losefocus");
308 onFocus: function() {
310 this.send("getfocus");
314 this.send("losefocus");
316 isLargeScreen: function() {
317 return window.innerWidth >= 768;
319 btnTooltipClass: function(thing) {
321 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
324 { tooltip: !("ontouchstart" in window) },
329 someAnonymousPresent: function() {
331 Object.values(this.people).some(p =>
332 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
336 requestLastate: function(sid) {
337 // TODO: maybe also find opponent SID ?
339 // this.game.players.find(p => p.sid != this.st.user.sid).sid;
340 this.send("asklastate", { target: sid });
342 this.askLastate = setInterval(
344 // Ask at most 3 times:
345 // if no reply after that there should be a network issue.
351 this.send("asklastate", { target: sid });
354 else clearInterval(this.askLastate);
359 atCreation: function() {
360 document.addEventListener('visibilitychange', this.visibilityChange);
361 window.addEventListener('focus', this.onFocus);
362 window.addEventListener('blur', this.onBlur);
363 // 0] (Re)Set variables
364 this.gameRef = this.$route.params["id"];
365 // next = next corr games IDs to navigate faster (if applicable)
366 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
367 // Always add myself to players' list
368 const my = this.st.user;
369 const tmpId = getRandString();
377 [tmpId]: { focus: true }
382 players: [{ name: "" }, { name: "" }],
386 let chatComp = this.$refs["chatcomp"];
387 if (!!chatComp) chatComp.chats = [];
388 this.virtualClocks = [[0,0], [0,0]];
390 this.rulesContent = "";
392 this.lastateAsked = false;
393 this.rematchOffer = "";
394 this.lastate = undefined;
395 this.roomInitialized = false;
396 this.gotLastate = false;
397 this.gotMoveIdx = -1;
398 this.opponentGotMove = false;
399 this.askLastate = null;
400 this.retrySendmove = null;
401 this.clockUpdate = null;
402 this.newConnect = {};
403 // 1] Initialize connection
404 this.connexionString =
406 "/?sid=" + this.st.user.sid +
407 "&id=" + this.st.user.id +
410 // Discard potential "/?next=[...]" for page indication:
411 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
414 openConnection: function() {
415 this.conn = new WebSocket(this.connexionString);
416 const onOpen = () => {
417 this.reconnectTimeout = 250;
418 const oppSid = this.getOppsid();
419 if (!!oppSid) this.requestLastate(oppSid); //in case of
421 this.conn.onopen = onOpen;
422 this.conn.onmessage = this.socketMessageListener;
423 const closeConnection = () => {
424 this.reopenTimeout = setTimeout(
426 this.openConnection();
427 this.reconnectTimeout = Math.min(2*this.reconnectTimeout, 30000);
429 this.reconnectTimeout
432 this.conn.onerror = closeConnection;
433 this.conn.onclose = closeConnection;
434 // Socket init required before loading remote game:
435 const socketInit = callback => {
436 if (this.conn.readyState == 1)
440 // Socket not ready yet (initial loading)
441 // NOTE: first arg is Websocket object, unused here:
442 this.conn.onopen = () => {
448 this.fetchGame((game) => {
451 // Patch for retro-compatibility (TODO: remove it)
452 game.options = { randomness: game.randomness };
453 delete game["randomness"];
455 else game.options = JSON.parse(game.options);
456 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
459 // Live game stored remotely: need socket to retrieve it
460 // NOTE: the callback "roomInit" will be lost, so it's not provided.
461 // --> It will be given when receiving "fullgame" socket event.
462 socketInit(() => { this.send("askfullgame"); });
465 roomInit: function() {
466 if (!this.roomInitialized) {
467 // Notify the room only now that I connected, because
468 // messages might be lost otherwise (if game loading is slow)
469 this.send("connect");
470 this.send("pollclients");
471 // We may ask fullgame several times if some moves are lost,
472 // but room should be init only once:
473 this.roomInitialized = true;
476 send: function(code, obj) {
477 if (!!this.conn && this.conn.readyState == 1)
478 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
480 isConnected: function(index) {
481 const player = this.game.players[index];
482 // Is it me ? In this case no need to bother with focus
484 this.st.user.sid == player.sid ||
485 (!!player.name && this.st.user.id == player.id)
487 // Still have to check for name (because of potential multi-accounts
488 // on same browser, although this should be rare...)
489 return (!this.st.user.name || this.st.user.name == player.name);
491 // Try to find a match in people:
495 Object.keys(this.people).some(sid => {
498 Object.values(this.people[sid].tmpIds).some(v => v.focus)
505 Object.values(this.people).some(p => {
508 Object.values(p.tmpIds).some(v => v.focus)
514 getOppsid: function() {
515 let oppsid = this.game.oppsid;
517 oppsid = Object.keys(this.people).find(
518 sid => this.people[sid].id == this.game.oppid
521 // oppsid is useful only if opponent is online:
522 if (!!oppsid && !!this.people[oppsid]) return oppsid;
525 // NOTE: action if provided is always a closing action
526 toggleChat: function(action) {
527 if (!action && document.getElementById("modalChat").checked)
529 document.getElementById("inputChat").focus();
531 document.getElementById("chatBtn").classList.remove("somethingnew");
532 if (!!this.game.mycolor) {
533 // Update "chatRead" variable either on server or locally
534 if (this.game.type == "corr")
535 this.updateCorrGame({ chatRead: this.game.mycolor });
536 else if (this.game.type == "live")
537 GameStorage.update(this.gameRef, { chatRead: true });
541 processChat: function(chat) {
542 this.send("newchat", { data: chat });
543 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
544 if (!!this.game.mycolor) {
545 if (this.game.type == "corr")
546 this.updateCorrGame({ chat: chat });
549 chat.added = Date.now();
550 GameStorage.update(this.gameRef, { chat: chat });
554 clearChat: function() {
555 if (!!this.game.mycolor) {
556 if (this.game.type == "corr") {
560 { data: { gid: this.game.id } }
565 GameStorage.update(this.gameRef, { delchat: true });
567 this.$set(this.game, "chats", []);
570 getGameType: function(game) {
571 if (!!game.id.toString().match(/^i/)) return "import";
572 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
574 // Notify something after a new move (to opponent and me on MyGames page)
575 notifyMyGames: function(thing, data) {
580 targets: this.game.players.map(p => {
581 return { sid: p.sid, id: p.id };
586 showNextGame: function() {
587 // Did I play in current game? If not, add it to nextIds list
588 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
589 this.nextIds.unshift(this.game.id);
590 const nextGid = this.nextIds.pop();
592 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
594 socketMessageListener: function(msg) {
595 if (!this.conn) return;
596 const data = JSON.parse(msg.data);
599 // TODO: shuffling and random filtering on server,
600 // if the room is really crowded.
601 Object.keys(data.sockIds).forEach(sid => {
602 if (sid != this.st.user.sid) {
603 this.send("askidentity", { target: sid });
604 this.people[sid] = { tmpIds: data.sockIds[sid] };
607 // Complete my tmpIds:
608 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
613 if (!this.people[data.from[0]]) {
614 // focus depends on the tmpId (e.g. tab)
620 [data.from[1]]: { focus: true }
624 // For self multi-connects tests:
625 this.newConnect[data.from[0]] = true;
626 this.send("askidentity", { target: data.from[0] });
629 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
630 this.$forceUpdate(); //TODO: shouldn't be required
634 if (!this.people[data.from[0]]) return;
635 delete this.people[data.from[0]].tmpIds[data.from[1]];
636 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
637 this.$delete(this.people, data.from[0]);
638 else this.$forceUpdate(); //TODO: shouldn't be required
641 let player = this.people[data.from[0]];
643 player.tmpIds[data.from[1]].focus = true;
644 this.$forceUpdate(); //TODO: shouldn't be required
649 let player = this.people[data.from[0]];
651 player.tmpIds[data.from[1]].focus = false;
652 this.$forceUpdate(); //TODO: shouldn't be required
656 case "askidentity": {
657 // Request for identification
659 // Decompose to avoid revealing email
660 name: this.st.user.name,
661 sid: this.st.user.sid,
664 this.send("identity", { data: me, target: data.from });
668 const user = data.data;
669 let player = this.people[user.sid];
670 // player.tmpIds is already set
671 player.name = user.name;
673 if (this.game.type == "live") {
675 this.game.players.findIndex(p => p.sid == this.st.user.sid);
676 // Sometimes a player name isn't stored yet (TODO: why?)
679 !this.game.players[1 - myGidx].name &&
680 this.game.players[1 - myGidx].sid == user.sid &&
683 this.game.players[1-myGidx].name = user.name;
686 { playerName: { idx: 1 - myGidx, name: user.name } }
690 this.$forceUpdate(); //TODO: shouldn't be required
691 // If I multi-connect, kill current connexion if no mark (I'm older)
692 if (this.newConnect[user.sid]) {
693 delete this.newConnect[user.sid];
696 user.id == this.st.user.id &&
697 user.sid != this.st.user.sid
699 this.cleanBeforeDestroy();
700 alert(this.st.tr["New connexion detected: tab now offline"]);
704 // Ask potentially missed last state, if opponent and I play
707 !!this.game.mycolor &&
708 this.game.type == "live" &&
709 this.game.players.some(p => p.sid == user.sid)
711 this.requestLastate(user.sid);
716 // Send current (live or import) game,
717 // if not asked by any of the players
719 this.game.type != "corr" &&
720 this.game.players.every(p => p.sid != data.from[0])
724 // FEN is current position, unused for now
726 players: this.game.players,
728 cadence: this.game.cadence,
729 score: this.game.score
731 this.send("game", { data: myGame, target: data.from });
735 const gameToSend = Object.keys(this.game)
738 "id","fen","players","vid","cadence","fenStart","options",
739 "moves","clocks","score","drawOffer","rematchOffer"
743 obj[k] = this.game[k];
748 this.send("fullgame", { data: gameToSend, target: data.from });
751 if (!!data.data.empty) {
752 alert(this.st.tr["The game should be in another tab"]);
756 // Callback "roomInit" to poll clients only after game is loaded
757 this.loadVariantThenGame(data.data, this.roomInit);
760 // Sending informative last state if I played a move or score != "*"
761 // If the game or moves aren't loaded yet, delay the sending:
762 // TODO: socket init after game load, so the game is supposedly ready
763 if (!this.game || !this.game.moves) this.lastateAsked = true;
764 else this.sendLastate(data.from);
766 // TODO: possible bad scenario: reload page while oppponent sends a
767 // move => get both lastate and newmove, process both, add move twice.
768 // Confirm scenario? Fix?
770 // Got opponent infos about last move
771 this.gotLastate = true;
772 this.lastate = data.data;
773 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
774 this.gotMoveIdx = this.lastate.movesCount - 1;
775 if (this.game.rendered)
776 // Game is rendered (Board component)
777 this.processLastate();
778 // Else: will be processed when game is ready
784 //console.log("Receive move");
785 //console.log(data.data);
786 //moveslist not updated when receiving a move? (see in BaseGame)
788 const movePlus = data.data;
789 const movesCount = this.game.moves.length;
791 movePlus.index < movesCount ||
792 this.gotMoveIdx >= movePlus.index
794 // Opponent re-send but we already have the move:
795 // (maybe he didn't receive our pingback...)
796 this.send("gotmove", {data: movePlus.index, target: data.from});
799 this.gotMoveIdx = movePlus.index;
800 const receiveMyMove = (movePlus.color == this.game.mycolor);
801 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
802 if (!receiveMyMove && !!this.game.mycolor) {
803 // Notify opponent that I got the move:
806 { data: movePlus.index, target: data.from }
808 // And myself if I'm elsewhere:
814 (this.game.players[moveColIdx].name || "@nonymous") +
820 if (movePlus.cancelDrawOffer) {
821 // Opponent refuses draw
823 // NOTE for corr games: drawOffer reset by player in turn
825 this.game.type == "live" &&
826 !!this.game.mycolor &&
829 GameStorage.update(this.gameRef, { drawOffer: "" });
832 this.$refs["basegame"].play(movePlus.move, "received");
833 // Freeze time while the move is being play
834 // (TODO: a callback would be cleaner here)
835 clearInterval(this.clockUpdate);
836 this.clockUpdate = null;
837 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
838 // 250 = length of animation, 500 = delay between sub-moves
840 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
841 // Incomplete information: no move animation
845 this.game.clocks[moveColIdx] = movePlus.clock;
848 { receiveMyMove: receiveMyMove }
857 this.opponentGotMove = true;
858 // Now his clock starts running on my side:
859 const oppIdx = ['w','b'].indexOf(this.vr.turn);
860 // NOTE: next line to avoid multi-resetClocks when several tabs
861 // on same game, resulting in a faster countdown.
862 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
867 const score = (data.data == "b" ? "1-0" : "0-1");
868 const side = (data.data == "w" ? "White" : "Black");
869 this.gameOver(score, side + " surrender");
872 this.gameOver("?", "Stop");
875 this.gameOver("1/2", data.data);
878 // NOTE: observers don't know who offered draw
879 this.drawOffer = "received";
880 if (!!this.game.mycolor && this.game.type == "live") {
883 { drawOffer: V.GetOppCol(this.game.mycolor) }
888 // NOTE: observers don't know who offered rematch
889 this.rematchOffer = data.data ? "received" : "";
890 if (!!this.game.mycolor && this.game.type == "live") {
893 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
898 // A game started, redirect if I'm playing in
899 const gameInfo = data.data;
900 const gameType = this.getGameType(gameInfo);
902 gameType == "live" &&
903 gameInfo.players.some(p => p.sid == this.st.user.sid)
905 this.addAndGotoLiveGame(gameInfo);
908 gameType == "corr" &&
909 this.st.user.id > 0 &&
910 gameInfo.players.some(p => p.id == this.st.user.id)
912 this.$router.push("/game/" + gameInfo.id);
915 this.rematchId = gameInfo.id;
916 document.getElementById("modalRules").checked = false;
917 document.getElementById("modalScore").checked = false;
918 document.getElementById("modalRematch").checked = true;
923 let chat = data.data;
924 this.$refs["chatcomp"].newChat(chat);
925 if (this.game.type == "live") {
926 chat.added = Date.now();
927 if (!!this.game.mycolor)
928 GameStorage.update(this.gameRef, { chat: chat });
930 if (!document.getElementById("modalChat").checked)
931 document.getElementById("chatBtn").classList.add("somethingnew");
936 updateCorrGame: function(obj, callback) {
946 if (!!callback) callback();
951 sendLastate: function(target) {
952 // Send our "last state" informations to opponent
953 const L = this.game.moves.length;
954 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
957 (L > 0 && this.vr.turn != this.game.mycolor)
958 ? this.game.moves[L - 1]
960 clock: this.game.clocks[myIdx],
961 // Since we played a move (or abort or resign),
962 // only drawOffer=="sent" is possible
963 drawSent: this.drawOffer == "sent" ? true : undefined,
964 rematchSent: this.rematchOffer == "sent" ? true : undefined,
965 score: this.game.score != "*" ? this.game.score : undefined,
966 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
969 this.send("lastate", { data: myLastate, target: target });
971 // lastate was received, but maybe game wasn't ready yet:
972 processLastate: function() {
973 const data = this.lastate;
974 this.lastate = undefined; //security...
976 const oppCol = V.GetOppCol(this.game.mycolor);
977 if (!!data.rematchSent) {
978 if (this.game.rematchOffer != oppCol) {
979 // Opponent sended rematch offer while we were offline:
980 this.rematchOffer = "received";
983 { rematchOffer: oppCol }
988 if (this.game.rematchOffer == oppCol) {
989 // Opponent cancelled rematch offer while we were offline:
990 this.rematchOffer = "";
999 const L = this.game.moves.length;
1000 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
1001 this.game.clocks[oppIdx] = data.clock;
1002 if (data.movesCount > L) {
1003 // Just got last move from him
1004 this.$refs["basegame"].play(data.lastMove, "received");
1005 this.processMove(data.lastMove);
1008 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
1009 this.re_setClocks();
1011 if (!!data.drawSent) this.drawOffer = "received";
1013 this.drawOffer = "";
1014 if (this.game.score == "*")
1015 this.gameOver(data.score, data.scoreMsg);
1019 clickDraw: function() {
1020 if (!this.game.mycolor || this.game.type == "import") return;
1021 if (["received", "threerep"].includes(this.drawOffer)) {
1022 if (!confirm(this.st.tr["Accept draw?"])) return;
1024 this.drawOffer == "received"
1025 ? "Mutual agreement"
1026 : "Three repetitions";
1027 this.send("draw", { data: message });
1028 this.gameOver("1/2", message);
1030 else if (this.drawOffer == "") {
1031 // No effect if drawOffer == "sent"
1032 if (this.game.mycolor != this.vr.turn) {
1033 alert(this.st.tr["Draw offer only in your turn"]);
1036 if (!confirm(this.st.tr["Offer draw?"])) return;
1037 this.drawOffer = "sent";
1038 this.send("drawoffer");
1039 if (this.game.type == "live") {
1042 { drawOffer: this.game.mycolor }
1045 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1048 addAndGotoLiveGame: function(gameInfo, callback) {
1049 const game = Object.assign(
1053 // (other) Game infos: constant
1054 fenStart: gameInfo.fen,
1055 created: Date.now(),
1056 // Game state (including FEN): will be updated
1058 clocks: [-1, -1], //-1 = unstarted
1063 GameStorage.add(game, (err) => {
1064 // No error expected.
1066 if (this.st.settings.sound)
1067 new Audio("/sounds/newgame.flac").play().catch(() => {});
1068 if (!!callback) callback();
1069 this.$router.push("/game/" + gameInfo.id);
1073 clickRematch: function() {
1074 if (!this.game.mycolor || this.game.type == "import") return;
1075 if (this.rematchOffer == "received") {
1076 // Start a new game!
1078 id: getRandString(), //ignored if corr
1079 fen: V.GenRandInitFen(this.game.options),
1080 options: JSON.stringify(this.game.options),
1081 players: [this.game.players[1], this.game.players[0]],
1083 cadence: this.game.cadence
1085 const notifyNewGame = () => {
1086 this.send("rnewgame", { data: gameInfo });
1087 // To main Hall if corr game:
1088 if (this.game.type == "corr")
1089 this.send("newgame", { data: gameInfo, page: "/" });
1090 // Also to MyGames page:
1091 this.notifyMyGames("newgame", gameInfo);
1093 if (this.game.type == "live") {
1096 { rematchOffer: "" }
1098 // Increment game stats counter in DB
1102 { data: { vid: gameInfo.vid } }
1104 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1108 this.updateCorrGame({ rematchOffer: 'n' });
1113 data: { gameInfo: gameInfo },
1114 success: (response) => {
1115 gameInfo.id = response.id;
1117 this.$router.push("/game/" + response.id);
1123 else if (this.rematchOffer == "") {
1124 this.rematchOffer = "sent";
1125 this.send("rematchoffer", { data: true });
1126 if (this.game.type == "live") {
1129 { rematchOffer: this.game.mycolor }
1132 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1134 else if (this.rematchOffer == "sent") {
1135 // Toggle rematch offer (on --> off)
1136 this.rematchOffer = "";
1137 this.send("rematchoffer", { data: false });
1138 if (this.game.type == "live") {
1141 { rematchOffer: '' }
1144 else this.updateCorrGame({ rematchOffer: 'n' });
1147 abortGame: function() {
1148 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1150 this.gameOver("?", "Stop");
1153 resign: function() {
1154 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1156 this.send("resign", { data: this.game.mycolor });
1157 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1158 const side = (this.game.mycolor == "w" ? "White" : "Black");
1159 this.gameOver(score, side + " surrender");
1161 loadGame: function(game, callback) {
1162 const gtype = game.type || this.getGameType(game);
1163 const tc = extractTime(game.cadence);
1164 const myIdx = game.players.findIndex(p => {
1166 p.sid == this.st.user.sid ||
1167 (!!p.name && p.id == this.st.user.id)
1170 // Sometimes the name isn't stored yet (TODO: why?)
1174 !game.players[myIdx].name &&
1177 game.players[myIdx].name = this.st.user.name;
1180 { playerName: { idx: myIdx, name: this.st.user.name } }
1183 // "mycolor" is undefined for observers
1184 const mycolor = [undefined, "w", "b"][myIdx + 1];
1185 if (gtype == "corr") {
1186 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1187 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1188 // NOTE: clocks in seconds
1189 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1190 game.clocks = [tc.mainTime, tc.mainTime];
1191 const L = game.moves.length;
1192 if (game.score == "*") {
1195 game.clocks[L % 2] -=
1196 (Date.now() - game.moves[L-1].played) / 1000;
1199 // Now that we used idx and played, re-format moves as for live games
1200 game.moves = game.moves.map(m => m.squares);
1202 else if (gtype == "live") {
1203 if (game.clocks[0] < 0) {
1204 // Game is unstarted. clock is ignored until move 2
1205 game.clocks = [tc.mainTime, tc.mainTime];
1207 // I play in this live game
1210 { clocks: game.clocks }
1214 else if (!!game.initime)
1215 // It's my turn: clocks not updated yet
1216 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1219 // gtype == "import"
1220 game.clocks = [tc.mainTime, tc.mainTime];
1221 // Live games before 26/03/2020 don't have chat history:
1222 if (!game.chats) game.chats = []; //TODO: remove line
1223 // Sort chat messages from newest to oldest
1224 game.chats.sort((c1, c2) => c2.added - c1.added);
1227 game.chats.length > 0 &&
1228 (!game.chatRead || game.chatRead < game.chats[0].added)
1230 // A chat message arrived since my last reading:
1231 document.getElementById("chatBtn").classList.add("somethingnew");
1233 // TODO: merge next 2 "if" conditions
1234 if (!!game.drawOffer) {
1235 if (game.drawOffer == "t")
1236 // Three repetitions
1237 this.drawOffer = "threerep";
1239 // Draw offered by any of the players:
1240 if (myIdx < 0) this.drawOffer = "received";
1242 // I play in this game:
1244 (game.drawOffer == "w" && myIdx == 0) ||
1245 (game.drawOffer == "b" && myIdx == 1)
1247 this.drawOffer = "sent";
1248 else this.drawOffer = "received";
1252 if (!!game.rematchOffer) {
1253 if (myIdx < 0) this.rematchOffer = "received";
1255 // I play in this game:
1257 (game.rematchOffer == "w" && myIdx == 0) ||
1258 (game.rematchOffer == "b" && myIdx == 1)
1260 this.rematchOffer = "sent";
1262 else this.rematchOffer = "received";
1265 this.repeat = {}; //reset: scan past moves' FEN:
1267 this.vr = new V(game.fenStart);
1269 game.moves.forEach(m => {
1270 playMove(m, this.vr);
1271 const fenIdx = this.vr.getFenForRepeat();
1272 this.repeat[fenIdx] = this.repeat[fenIdx]
1273 ? this.repeat[fenIdx] + 1
1276 // Imported games don't have current FEN
1277 if (!game.fen) game.fen = this.vr.getFen();
1278 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1279 this.game = Object.assign(
1280 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1283 increment: tc.increment,
1285 // opponent sid not strictly required (or available), but easier
1286 // at least oppsid or oppid is available anyway:
1287 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1288 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1292 this.$refs["basegame"].re_setVariables(this.game);
1294 this.gotMoveIdx = game.moves.length - 1;
1295 // If we arrive here after 'nextGame' action, the board might be hidden
1296 let boardDiv = document.querySelector(".game");
1297 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1298 boardDiv.style.visibility = "visible";
1299 this.re_setClocks();
1300 this.$nextTick(() => {
1301 this.game.rendered = true;
1302 // Did lastate arrive before game was rendered?
1303 if (!!this.lastate) this.processLastate();
1305 if (this.lastateAsked) {
1306 this.lastateAsked = false;
1307 this.sendLastate(game.oppsid);
1309 if (!!callback) callback();
1311 loadVariantThenGame: async function(game, callback) {
1312 const afterSetVname = async () => {
1313 await import("@/variants/" + game.vname + ".js")
1314 .then((vModule) => {
1315 window.V = vModule[game.vname + "Rules"];
1316 this.loadGame(game, callback);
1321 "raw-loader!@/translations/rules/" +
1322 game.vname + "/" + this.st.lang + ".pug"
1324 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1326 let variant = undefined;
1327 const trySetVname = setInterval(
1329 // this.st.variants might be uninitialized (variant == null)
1330 variant = this.st.variants.find(v => {
1331 return v.id == game.vid || v.name == game.vname
1334 clearInterval(trySetVname);
1335 game.vname = variant.name;
1336 game.vdisp = variant.display;
1342 // 3 cases for loading a game:
1343 // - from indexedDB (running or completed live game I play)
1344 // - from server (one correspondance game I play[ed] or not)
1345 // - from remote peer (one live game I don't play, finished or not)
1346 fetchGame: function(callback) {
1348 Number.isInteger(this.gameRef) ||
1349 !isNaN(parseInt(this.gameRef, 10))
1351 // corr games identifiers are integers
1356 data: { gid: this.gameRef },
1358 res.game.moves.forEach(m => {
1359 m.squares = JSON.parse(m.squares);
1366 else if (!!this.gameRef.match(/^i/))
1367 // Game import (maybe remote)
1368 ImportgameStorage.get(this.gameRef, callback);
1370 // Local live game (or remote)
1371 GameStorage.get(this.gameRef, callback);
1373 re_setClocks: function() {
1374 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1375 if (this.game.moves.length < 2 || this.game.score != "*") {
1376 // 1st move not completed yet, or game over: freeze time
1379 const currentTurn = this.vr.turn;
1380 const currentMovesCount = this.game.moves.length;
1381 const colorIdx = ["w", "b"].indexOf(currentTurn);
1382 this.clockUpdate = setInterval(
1385 this.game.clocks[colorIdx] < 0 ||
1386 this.game.moves.length > currentMovesCount ||
1387 this.game.score != "*"
1389 clearInterval(this.clockUpdate);
1390 this.clockUpdate = null;
1391 if (this.game.clocks[colorIdx] < 0)
1393 currentTurn == "w" ? "0-1" : "1-0",
1401 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1408 // Update variables and storage after a move:
1409 processMove: function(move, data) {
1410 if (this.game.type == "import")
1411 // Shouldn't receive any messages in this mode:
1413 if (!data) data = {};
1414 const moveCol = this.vr.turn;
1415 const colorIdx = ["w", "b"].indexOf(moveCol);
1416 const nextIdx = 1 - colorIdx;
1417 const doProcessMove = () => {
1418 const origMovescount = this.game.moves.length;
1419 // The move is (about to be) played: stop clock
1420 clearInterval(this.clockUpdate);
1421 this.clockUpdate = null;
1422 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1423 if (this.drawOffer == "received")
1425 this.drawOffer = "";
1426 if (this.game.type == "live" && origMovescount >= 2) {
1427 this.game.clocks[colorIdx] += this.game.increment;
1428 // For a correct display in casqe of disconnected opponent:
1432 ppt(this.game.clocks[colorIdx]).split(':')
1434 GameStorage.update(this.gameRef, {
1435 // It's not my turn anymore:
1440 // Update current game object:
1441 playMove(move, this.vr);
1443 // Received move, score is computed in BaseGame, but maybe not yet.
1444 // ==> Compute it here, although this is redundant (TODO)
1445 data.score = this.vr.getCurrentScore();
1446 if (data.score != "*") this.gameOver(data.score);
1447 this.game.moves.push(move);
1448 this.game.fen = this.vr.getFen();
1449 if (this.game.type == "corr") {
1450 // In corr games, just reset clock to mainTime:
1451 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1453 if (!V.IgnoreRepetition) {
1454 // If repetition detected, consider that a draw offer was received:
1455 const fenObj = this.vr.getFenForRepeat();
1456 this.repeat[fenObj] =
1457 !!this.repeat[fenObj]
1458 ? this.repeat[fenObj] + 1
1460 if (this.repeat[fenObj] >= 3) {
1461 if (this.vr.loseOnRepetition())
1462 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1463 else this.drawOffer = "threerep";
1465 else if (this.drawOffer == "threerep") this.drawOffer = "";
1467 if (!!this.game.mycolor && !data.receiveMyMove) {
1468 // NOTE: 'var' to see that variable outside this block
1469 var filtered_move = getFilteredMove(move);
1471 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1472 // Notify turn on MyGames page:
1481 // Since corr games are stored at only one location, update should be
1482 // done only by one player for each move:
1484 this.game.type == "live" &&
1485 !!this.game.mycolor &&
1486 moveCol != this.game.mycolor &&
1487 this.game.moves.length >= 2
1489 // Receive a move: update initime
1490 this.game.initime = Date.now();
1491 GameStorage.update(this.gameRef, {
1492 // It's my turn now!
1493 initime: this.game.initime
1497 !!this.game.mycolor &&
1498 !data.receiveMyMove &&
1499 (this.game.type == "live" || moveCol == this.game.mycolor)
1502 switch (this.drawOffer) {
1507 drawCode = this.game.mycolor;
1510 drawCode = V.GetOppCol(this.game.mycolor);
1513 if (this.game.type == "corr") {
1514 // corr: only move, fen and score
1515 this.updateCorrGame({
1518 squares: filtered_move,
1521 // Code "n" for "None" to force reset (otherwise it's ignored)
1522 drawOffer: drawCode || "n"
1526 const updateStorage = () => {
1527 GameStorage.update(this.gameRef, {
1529 move: filtered_move,
1530 moveIdx: origMovescount,
1531 clocks: this.game.clocks,
1535 // The active tab can update storage immediately
1536 if (this.focus) updateStorage();
1537 // Small random delay otherwise
1538 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1541 // Send move ("newmove" event) to people in the room (if our turn)
1542 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1544 move: filtered_move,
1545 index: origMovescount,
1546 // color is required to check if this is my move
1547 // (if several tabs opened)
1549 cancelDrawOffer: this.drawOffer == ""
1551 if (this.game.type == "live")
1552 sendMove["clock"] = this.game.clocks[colorIdx];
1553 // (Live) Clocks will re-start when the opponent pingback arrive
1554 this.opponentGotMove = false;
1555 this.send("newmove", {data: sendMove});
1556 // If the opponent doesn't reply gotmove soon enough, re-send move:
1557 // Do this at most 2 times, because more would mean network issues,
1558 // opponent would then be expected to disconnect/reconnect.
1560 const currentUrl = document.location.href;
1561 this.retrySendmove = setInterval(
1565 this.opponentGotMove ||
1566 document.location.href != currentUrl //page change
1568 clearInterval(this.retrySendmove);
1571 const oppsid = this.getOppsid();
1573 // Opponent is disconnected: he'll ask last state
1574 clearInterval(this.retrySendmove);
1576 this.send("newmove", { data: sendMove, target: oppsid });
1584 // Not my move or I'm an observer: just start other player's clock
1585 this.re_setClocks();
1588 this.game.type == "corr" &&
1589 moveCol == this.game.mycolor &&
1592 let boardDiv = document.querySelector(".game");
1593 const afterSetScore = () => {
1595 if (this.st.settings.gotonext && this.nextIds.length > 0)
1596 this.showNextGame();
1598 // The board might have been hidden:
1599 if (boardDiv.style.visibility == "hidden")
1600 boardDiv.style.visibility = "visible";
1601 if (data.score == "*") this.re_setClocks();
1604 if (!V.CorrConfirm) {
1608 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1609 // We may play several moves in a row: in case of, remove listener:
1610 let elClone = el.cloneNode(true);
1611 el.parentNode.replaceChild(elClone, el);
1612 elClone.addEventListener(
1615 document.getElementById("modalConfirm").checked = false;
1616 if (!!data.score && data.score != "*")
1618 this.gameOver(data.score, null, afterSetScore);
1619 else afterSetScore();
1622 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1623 const arMove = (Array.isArray(move) ? move : [move]);
1624 for (let i = 0; i < arMove.length; i++)
1625 V.PlayOnBoard(this.vr.board, arMove[i]);
1626 const position = this.vr.getBaseFen();
1627 for (let i = arMove.length - 1; i >= 0; i--)
1628 V.UndoOnBoard(this.vr.board, arMove[i]);
1629 if (["all","byrow"].includes(V.ShowMoves)) {
1630 this.curDiag = getDiagram({
1632 orientation: V.CanFlip ? this.game.mycolor : "w",
1633 color: this.game.mycolor,
1636 document.querySelector("#confirmDiv > .card").style.width =
1637 boardDiv.offsetWidth + "px";
1640 // Incomplete information: just ask confirmation
1641 // Hide the board, because otherwise it could reveal infos
1642 boardDiv.style.visibility = "hidden";
1643 this.moveNotation = getFullNotation(move);
1645 document.getElementById("modalConfirm").checked = true;
1649 if (!!data.score && data.score != "*")
1650 this.gameOver(data.score, null, doProcessMove);
1651 else doProcessMove();
1654 cancelMove: function() {
1655 let boardDiv = document.querySelector(".game");
1656 if (boardDiv.style.visibility == "hidden")
1657 boardDiv.style.visibility = "visible";
1658 document.getElementById("modalConfirm").checked = false;
1659 this.$refs["basegame"].cancelLastMove();
1661 // In corr games, callback to change page only after score is set:
1662 gameOver: function(score, scoreMsg, callback) {
1663 this.game.score = score;
1664 if (!scoreMsg) scoreMsg = getScoreMessage(score, V.ReverseColors);
1665 this.game.scoreMsg = scoreMsg;
1666 document.getElementById("modalRules").checked = false;
1667 // Display result in a un-missable way:
1668 document.getElementById("modalScore").checked = true;
1669 this.$set(this.game, "scoreMsg", scoreMsg);
1670 const myIdx = this.game.players.findIndex(p => {
1672 p.sid == this.st.user.sid ||
1673 (!!p.name && p.id == this.st.user.id)
1677 // OK, I play in this game
1682 if (this.game.type == "live") {
1683 GameStorage.update(this.gameRef, scoreObj);
1684 // Notify myself locally if I'm elsewhere:
1688 { body: score + " : " + scoreMsg }
1691 if (!!callback) callback();
1693 else this.updateCorrGame(scoreObj, callback);
1694 // Notify the score to main Hall.
1695 // TODO: only one player (currently double send)
1696 this.send("result", { gid: this.game.id, score: score });
1697 // Also to MyGames page (TODO: doubled as well...)
1706 else if (!!callback) callback();
1712 <style lang="sass" scoped>
1713 #scoreDiv > .card, #rematchDiv > .card
1721 @media screen and (max-width: 1500px)
1723 @media screen and (max-width: 1024px)
1725 @media screen and (max-width: 767px)
1735 background-color: lightgreen
1747 @media screen and (max-width: 767px)
1752 display: inline-block
1756 display: inline-block
1758 display: inline-flex
1762 @media screen and (max-width: 767px)
1771 @media screen and (max-width: 767px)
1783 background-color: #edda99
1785 display: inline-block
1789 display: inline-block
1796 @media screen and (max-width: 767px)
1798 display: inline-block
1811 animation: blink-animation 2s steps(3, start) infinite
1812 @keyframes blink-animation
1817 display: inline-block
1829 .draw-sent, .draw-sent:hover
1830 background-color: lightyellow
1832 .draw-received, .draw-received:hover
1833 background-color: #73C6B6
1835 .draw-threerep, .draw-threerep:hover
1836 background-color: #D2B4DE
1838 .rematch-sent, .rematch-sent:hover
1839 background-color: lightyellow
1841 .rematch-received, .rematch-received:hover
1842 background-color: #48C9B0
1845 background-color: #D2B4DE
1858 background-color: lightgreen
1860 background-color: red
1863 color: var(--card-fore-color)
1866 font-size: calc(1rem * var(--heading-ratio))
1868 margin: calc(1.5 * var(--universal-margin))
1872 @import "@/styles/_rules.sass"
1873 @import "@/styles/_board_squares_img.sass"