3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vname }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
86 | {{ st.tr["Next_g"] }}
88 :class="btnTooltipClass()"
89 onClick="window.doClick('modalChat')"
92 img(src="/images/icons/chat.svg")
93 #actions(v-if="game.score=='*'")
96 :class="btnTooltipClass('draw')"
97 :aria-label="st.tr['Draw']"
99 img(src="/images/icons/draw.svg")
101 v-if="!!game.mycolor"
102 :class="btnTooltipClass()"
104 :aria-label="st.tr['Abort']"
106 img(src="/images/icons/abort.svg")
108 v-if="!!game.mycolor"
109 :class="btnTooltipClass()"
111 :aria-label="st.tr['Resign']"
113 img(src="/images/icons/resign.svg")
116 :class="btnTooltipClass('rematch')"
117 @click="clickRematch()"
118 :aria-label="st.tr['Rematch']"
120 img(src="/images/icons/rematch.svg")
122 div(v-if="isLargeScreen()")
124 :class="{connected: isConnected(0)}"
125 :uid="game.players[0].id"
126 :uname="game.players[0].name"
129 v-if="game.score=='*'"
130 :class="{yourturn: !!vr && vr.turn == 'w'}"
132 span.time-left {{ virtualClocks[0][0] }}
133 span.time-separator(v-if="!!virtualClocks[0][1]") :
134 span.time-right(v-if="!!virtualClocks[0][1]")
135 | {{ virtualClocks[0][1] }}
138 :class="{connected: isConnected(1)}"
139 :uid="game.players[1].id"
140 :uname="game.players[1].name"
143 v-if="game.score=='*'"
144 :class="{yourturn: !!vr && vr.turn == 'b'}"
146 span.time-left {{ virtualClocks[1][0] }}
147 span.time-separator(v-if="!!virtualClocks[1][1]") :
148 span.time-right(v-if="!!virtualClocks[1][1]")
149 | {{ virtualClocks[1][1] }}
152 :class="{connected: isConnected(0)}"
153 :uid="game.players[0].id"
154 :uname="game.players[0].name"
158 :class="{connected: isConnected(1)}"
159 :uid="game.players[1].id"
160 :uname="game.players[1].name"
162 div(v-if="game.score=='*'")
163 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
164 span.time-left {{ virtualClocks[0][0] }}
165 span.time-separator(v-if="!!virtualClocks[0][1]") :
166 span.time-right(v-if="!!virtualClocks[0][1]")
167 | {{ virtualClocks[0][1] }}
169 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
170 span.time-left {{ virtualClocks[1][0] }}
171 span.time-separator(v-if="!!virtualClocks[1][1]") :
172 span.time-right(v-if="!!virtualClocks[1][1]")
173 | {{ virtualClocks[1][1] }}
177 @newmove="processMove"
182 import BaseGame from "@/components/BaseGame.vue";
183 import UserBio from "@/components/UserBio.vue";
184 import Chat from "@/components/Chat.vue";
185 import { store } from "@/store";
186 import { GameStorage } from "@/utils/gameStorage";
187 import { ImportgameStorage } from "@/utils/importgameStorage";
188 import { ppt } from "@/utils/datetime";
189 import { notify } from "@/utils/notifications";
190 import { ajax } from "@/utils/ajax";
191 import { extractTime } from "@/utils/timeControl";
192 import { getRandString } from "@/utils/alea";
193 import { getScoreMessage } from "@/utils/scoring";
194 import { getFullNotation } from "@/utils/notation";
195 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
196 import { processModalClick } from "@/utils/modalClick";
197 import { playMove, getFilteredMove } from "@/utils/playUndo";
198 import { ArrayFun } from "@/utils/array";
199 import params from "@/parameters";
210 // gameRef can point to a corr game, local game or remote live game
213 game: {}, //passed to BaseGame
214 focus: !document.hidden, //will not always work... TODO
215 // virtualClocks will be initialized from true game.clocks
217 vr: null, //"variant rules" object initialized from FEN
223 people: {}, //players + observers
224 lastate: undefined, //used if opponent send lastate before game is ready
225 repeat: {}, //detect position repetition
226 curDiag: "", //for corr moves confirmation
228 roomInitialized: false,
229 // If asklastate got no reply, ask again:
231 gotMoveIdx: -1, //last move index received
232 // If newmove got no pingback, send again:
233 opponentGotMove: false,
235 socketCloseListener: 0,
236 // Incomplete info games: show move played
238 // Intervals from setInterval():
242 // Related to (killing of) self multi-connects:
247 $route: function(to, from) {
248 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
250 this.cleanBeforeDestroy();
251 else if (from.params["id"] != to.params["id"]) {
252 // Change everything:
253 this.cleanBeforeDestroy();
254 let boardDiv = document.querySelector(".game");
256 // In case of incomplete information variant:
257 boardDiv.style.visibility = "hidden";
262 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
265 // NOTE: some redundant code with Hall.vue (mostly related to people array)
266 created: function() {
269 mounted: function() {
270 document.getElementById("chatWrap")
271 .addEventListener("click", (e) => {
272 processModalClick(e, () => {
273 this.toggleChat("close")
276 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
278 document.getElementById(eltName)
279 .addEventListener("click", processModalClick);
283 beforeDestroy: function() {
284 this.cleanBeforeDestroy();
287 cleanBeforeDestroy: function() {
288 clearInterval(this.socketCloseListener);
289 document.removeEventListener('visibilitychange', this.visibilityChange);
290 window.removeEventListener('focus', this.onFocus);
291 window.removeEventListener('blur', this.onBlur);
292 if (!!this.askLastate) clearInterval(this.askLastate);
293 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
294 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
295 this.conn.removeEventListener("message", this.socketMessageListener);
296 this.send("disconnect");
299 visibilityChange: function() {
300 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
301 this.focus = (document.visibilityState == "visible");
302 this.send(this.focus ? "getfocus" : "losefocus");
304 onFocus: function() {
306 this.send("getfocus");
310 this.send("losefocus");
312 isLargeScreen: function() {
313 return window.innerWidth >= 768;
315 btnTooltipClass: function(thing) {
317 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
320 { tooltip: !("ontouchstart" in window) },
325 someAnonymousPresent: function() {
327 Object.values(this.people).some(p =>
328 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
332 atCreation: function() {
333 document.addEventListener('visibilitychange', this.visibilityChange);
334 window.addEventListener('focus', this.onFocus);
335 window.addEventListener('blur', this.onBlur);
336 // 0] (Re)Set variables
337 this.gameRef = this.$route.params["id"];
338 // next = next corr games IDs to navigate faster (if applicable)
339 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
340 // Always add myself to players' list
341 const my = this.st.user;
342 const tmpId = getRandString();
350 tmpId: { focus: true }
355 players: [{ name: "" }, { name: "" }],
359 let chatComp = this.$refs["chatcomp"];
360 if (!!chatComp) chatComp.chats = [];
361 this.virtualClocks = [[0,0], [0,0]];
363 this.rulesContent = "";
365 this.lastateAsked = false;
366 this.rematchOffer = "";
367 this.lastate = undefined;
368 this.roomInitialized = false;
369 this.gotLastate = false;
370 this.gotMoveIdx = -1;
371 this.opponentGotMove = false;
372 this.askLastate = null;
373 this.retrySendmove = null;
374 this.clockUpdate = null;
375 this.newConnect = {};
376 // 1] Initialize connection
377 this.connexionString =
379 "/?sid=" + this.st.user.sid +
380 "&id=" + this.st.user.id +
383 // Discard potential "/?next=[...]" for page indication:
384 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
385 this.conn = new WebSocket(this.connexionString);
386 this.conn.addEventListener("message", this.socketMessageListener);
387 this.socketCloseListener = setInterval(
389 if (this.conn.readyState == 3) {
390 this.conn.removeEventListener(
391 "message", this.socketMessageListener);
392 this.conn = new WebSocket(this.connexionString);
393 this.conn.addEventListener("message", this.socketMessageListener);
398 // Socket init required before loading remote game:
399 const socketInit = callback => {
400 if (this.conn.readyState == 1)
404 // Socket not ready yet (initial loading)
405 // NOTE: first arg is Websocket object, unused here:
406 this.conn.onopen = () => callback();
408 this.fetchGame((game) => {
410 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
412 // Live game stored remotely: need socket to retrieve it
413 // NOTE: the callback "roomInit" will be lost, so it's not provided.
414 // --> It will be given when receiving "fullgame" socket event.
415 socketInit(() => { this.send("askfullgame"); });
418 roomInit: function() {
419 if (!this.roomInitialized) {
420 // Notify the room only now that I connected, because
421 // messages might be lost otherwise (if game loading is slow)
422 this.send("connect");
423 this.send("pollclients");
424 // We may ask fullgame several times if some moves are lost,
425 // but room should be init only once:
426 this.roomInitialized = true;
429 send: function(code, obj) {
430 if (!!this.conn && this.conn.readyState == 1)
431 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
433 isConnected: function(index) {
434 const player = this.game.players[index];
435 // Is it me ? In this case no need to bother with focus
437 this.st.user.sid == player.sid ||
438 (!!player.name && this.st.user.id == player.id)
440 // Still have to check for name (because of potential multi-accounts
441 // on same browser, although this should be rare...)
442 return (!this.st.user.name || this.st.user.name == player.name);
444 // Try to find a match in people:
448 Object.keys(this.people).some(sid => {
451 Object.values(this.people[sid].tmpIds).some(v => v.focus)
458 Object.values(this.people).some(p => {
461 Object.values(p.tmpIds).some(v => v.focus)
467 getOppsid: function() {
468 let oppsid = this.game.oppsid;
470 oppsid = Object.keys(this.people).find(
471 sid => this.people[sid].id == this.game.oppid
474 // oppsid is useful only if opponent is online:
475 if (!!oppsid && !!this.people[oppsid]) return oppsid;
478 // NOTE: action if provided is always a closing action
479 toggleChat: function(action) {
480 if (!action && document.getElementById("modalChat").checked)
482 document.getElementById("inputChat").focus();
484 document.getElementById("chatBtn").classList.remove("somethingnew");
485 if (!!this.game.mycolor) {
486 // Update "chatRead" variable either on server or locally
487 if (this.game.type == "corr")
488 this.updateCorrGame({ chatRead: this.game.mycolor });
489 else if (this.game.type == "live")
490 GameStorage.update(this.gameRef, { chatRead: true });
494 processChat: function(chat) {
495 this.send("newchat", { data: chat });
496 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
497 if (!!this.game.mycolor) {
498 if (this.game.type == "corr")
499 this.updateCorrGame({ chat: chat });
502 chat.added = Date.now();
503 GameStorage.update(this.gameRef, { chat: chat });
507 clearChat: function() {
508 if (!!this.game.mycolor) {
509 if (this.game.type == "corr") {
513 { data: { gid: this.game.id } }
517 GameStorage.update(this.gameRef, { delchat: true });
519 this.$set(this.game, "chats", []);
522 getGameType: function(game) {
523 if (!!game.id.toString().match(/^i/)) return "import";
524 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
526 // Notify something after a new move (to opponent and me on MyGames page)
527 notifyMyGames: function(thing, data) {
532 targets: this.game.players.map(p => {
533 return { sid: p.sid, id: p.id };
538 showNextGame: function() {
539 // Did I play in current game? If not, add it to nextIds list
540 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
541 this.nextIds.unshift(this.game.id);
542 const nextGid = this.nextIds.pop();
544 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
546 socketMessageListener: function(msg) {
547 if (!this.conn) return;
548 const data = JSON.parse(msg.data);
551 // TODO: shuffling and random filtering on server,
552 // if the room is really crowded.
553 Object.keys(data.sockIds).forEach(sid => {
554 if (sid != this.st.user.sid) {
555 this.send("askidentity", { target: sid });
556 this.people[sid] = { tmpIds: data.sockIds[sid] };
559 // Complete my tmpIds:
560 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
565 if (!this.people[data.from[0]]) {
566 // focus depends on the tmpId (e.g. tab)
572 [data.from[1]]: { focus: true }
576 // For self multi-connects tests:
577 this.newConnect[data.from[0]] = true;
578 this.send("askidentity", { target: data.from[0] });
580 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
581 this.$forceUpdate(); //TODO: shouldn't be required
585 if (!this.people[data.from[0]]) return;
586 delete this.people[data.from[0]].tmpIds[data.from[1]];
587 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
588 this.$delete(this.people, data.from[0]);
589 else this.$forceUpdate(); //TODO: shouldn't be required
592 let player = this.people[data.from[0]];
594 player.tmpIds[data.from[1]].focus = true;
595 this.$forceUpdate(); //TODO: shouldn't be required
600 let player = this.people[data.from[0]];
602 player.tmpIds[data.from[1]].focus = false;
603 this.$forceUpdate(); //TODO: shouldn't be required
607 case "askidentity": {
608 // Request for identification
610 // Decompose to avoid revealing email
611 name: this.st.user.name,
612 sid: this.st.user.sid,
615 this.send("identity", { data: me, target: data.from });
619 const user = data.data;
620 let player = this.people[user.sid];
621 // player.tmpIds is already set
622 player.name = user.name;
624 if (this.game.type == "live") {
626 this.game.players.findIndex(p => p.sid == this.st.user.sid);
627 // Sometimes a player name isn't stored yet (TODO: why?)
630 !this.game.players[1 - myGidx].name &&
631 this.game.players[1 - myGidx].sid == user.sid &&
634 this.game.players[1-myGidx].name = user.name;
637 { playerName: { idx: 1 - myGidx, name: user.name } }
641 this.$forceUpdate(); //TODO: shouldn't be required
642 // If I multi-connect, kill current connexion if no mark (I'm older)
643 if (this.newConnect[user.sid]) {
644 delete this.newConnect[user.sid];
647 user.id == this.st.user.id &&
648 user.sid != this.st.user.sid
650 this.cleanBeforeDestroy();
651 alert(this.st.tr["New connexion detected: tab now offline"]);
655 // Ask potentially missed last state, if opponent and I play
658 !!this.game.mycolor &&
659 this.game.type == "live" &&
660 this.game.players.some(p => p.sid == user.sid)
662 this.send("asklastate", { target: user.sid });
664 this.askLastate = setInterval(
666 // Ask at most 3 times:
667 // if no reply after that there should be a network issue.
671 !!this.people[user.sid]
673 this.send("asklastate", { target: user.sid });
676 clearInterval(this.askLastate);
685 // Send current (live or import) game,
686 // if not asked by any of the players
688 this.game.type != "corr" &&
689 this.game.players.every(p => p.sid != data.from[0])
693 // FEN is current position, unused for now
695 players: this.game.players,
697 cadence: this.game.cadence,
698 score: this.game.score
700 this.send("game", { data: myGame, target: data.from });
704 const gameToSend = Object.keys(this.game)
707 "id","fen","players","vid","cadence","fenStart","vname",
708 "moves","clocks","score","drawOffer","rematchOffer"
712 obj[k] = this.game[k];
717 this.send("fullgame", { data: gameToSend, target: data.from });
720 if (!!data.data.empty) {
721 alert(this.st.tr["The game should be in another tab"]);
725 // Callback "roomInit" to poll clients only after game is loaded
726 this.loadVariantThenGame(data.data, this.roomInit);
729 // Sending informative last state if I played a move or score != "*"
730 // If the game or moves aren't loaded yet, delay the sending:
731 // TODO: socket init after game load, so the game is supposedly ready
732 if (!this.game || !this.game.moves) this.lastateAsked = true;
733 else this.sendLastate(data.from);
735 // TODO: possible bad scenario: reload page while oppponent sends a
736 // move => get both lastate and newmove, process both, add move twice.
737 // Confirm scenario? Fix?
739 // Got opponent infos about last move
740 this.gotLastate = true;
741 this.lastate = data.data;
742 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
743 this.gotMoveIdx = this.lastate.movesCount - 1;
744 if (this.game.rendered)
745 // Game is rendered (Board component)
746 this.processLastate();
747 // Else: will be processed when game is ready
753 console.log("Receive move");
754 console.log(data.data);
755 //moveslist not updated when receiving a move? (see in baseGame)
757 const movePlus = data.data;
758 const movesCount = this.game.moves.length;
760 movePlus.index < movesCount ||
761 this.gotMoveIdx >= movePlus.index
763 // Opponent re-send but we already have the move:
764 // (maybe he didn't receive our pingback...)
765 this.send("gotmove", {data: movePlus.index, target: data.from});
768 this.gotMoveIdx = movePlus.index;
769 const receiveMyMove = (movePlus.color == this.game.mycolor);
770 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
771 if (!receiveMyMove && !!this.game.mycolor) {
772 // Notify opponent that I got the move:
775 { data: movePlus.index, target: data.from }
777 // And myself if I'm elsewhere:
783 (this.game.players[moveColIdx].name || "@nonymous") +
789 if (movePlus.cancelDrawOffer) {
790 // Opponent refuses draw
792 // NOTE for corr games: drawOffer reset by player in turn
794 this.game.type == "live" &&
795 !!this.game.mycolor &&
798 GameStorage.update(this.gameRef, { drawOffer: "" });
801 this.$refs["basegame"].play(movePlus.move, "received");
802 // Freeze time while the move is being play
803 // (TODO: a callback would be cleaner here)
804 clearInterval(this.clockUpdate);
805 this.clockUpdate = null;
806 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
807 // 250 = length of animation, 500 = delay between sub-moves
809 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
810 // Incomplete information: no move animation
814 this.game.clocks[moveColIdx] = movePlus.clock;
817 { receiveMyMove: receiveMyMove }
826 this.opponentGotMove = true;
827 // Now his clock starts running on my side:
828 const oppIdx = ['w','b'].indexOf(this.vr.turn);
829 // NOTE: next line to avoid multi-resetClocks when several tabs
830 // on same game, resulting in a faster countdown.
831 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
836 const score = (data.data == "b" ? "1-0" : "0-1");
837 const side = (data.data == "w" ? "White" : "Black");
838 this.gameOver(score, side + " surrender");
841 this.gameOver("?", "Stop");
844 this.gameOver("1/2", data.data);
847 // NOTE: observers don't know who offered draw
848 this.drawOffer = "received";
849 if (!!this.game.mycolor && this.game.type == "live") {
852 { drawOffer: V.GetOppCol(this.game.mycolor) }
857 // NOTE: observers don't know who offered rematch
858 this.rematchOffer = data.data ? "received" : "";
859 if (!!this.game.mycolor && this.game.type == "live") {
862 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
867 // A game started, redirect if I'm playing in
868 const gameInfo = data.data;
869 const gameType = this.getGameType(gameInfo);
871 gameType == "live" &&
872 gameInfo.players.some(p => p.sid == this.st.user.sid)
874 this.addAndGotoLiveGame(gameInfo);
876 gameType == "corr" &&
877 this.st.user.id > 0 &&
878 gameInfo.players.some(p => p.id == this.st.user.id)
880 this.$router.push("/game/" + gameInfo.id);
882 this.rematchId = gameInfo.id;
883 document.getElementById("modalRules").checked = false;
884 document.getElementById("modalScore").checked = false;
885 document.getElementById("modalRematch").checked = true;
890 let chat = data.data;
891 this.$refs["chatcomp"].newChat(chat);
892 if (this.game.type == "live") {
893 chat.added = Date.now();
894 if (!!this.game.mycolor)
895 GameStorage.update(this.gameRef, { chat: chat });
897 if (!document.getElementById("modalChat").checked)
898 document.getElementById("chatBtn").classList.add("somethingnew");
903 updateCorrGame: function(obj, callback) {
913 if (!!callback) callback();
918 sendLastate: function(target) {
919 // Send our "last state" informations to opponent
920 const L = this.game.moves.length;
921 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
924 (L > 0 && this.vr.turn != this.game.mycolor)
925 ? this.game.moves[L - 1]
927 clock: this.game.clocks[myIdx],
928 // Since we played a move (or abort or resign),
929 // only drawOffer=="sent" is possible
930 drawSent: this.drawOffer == "sent" ? true : undefined,
931 rematchSent: this.rematchOffer == "sent" ? true : undefined,
932 score: this.game.score != "*" ? this.game.score : undefined,
933 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
936 this.send("lastate", { data: myLastate, target: target });
938 // lastate was received, but maybe game wasn't ready yet:
939 processLastate: function() {
940 const data = this.lastate;
941 this.lastate = undefined; //security...
943 const oppCol = V.GetOppCol(this.game.mycolor);
944 if (!!data.rematchSent) {
945 if (this.game.rematchOffer != oppCol) {
946 // Opponent sended rematch offer while we were offline:
947 this.rematchOffer = "received";
950 { rematchOffer: oppCol }
955 if (this.game.rematchOffer == oppCol) {
956 // Opponent cancelled rematch offer while we were offline:
957 this.rematchOffer = "";
966 const L = this.game.moves.length;
967 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
968 this.game.clocks[oppIdx] = data.clock;
969 if (data.movesCount > L) {
970 // Just got last move from him
971 this.$refs["basegame"].play(data.lastMove, "received");
972 this.processMove(data.lastMove);
974 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
977 if (!!data.drawSent) this.drawOffer = "received";
980 if (this.game.score == "*")
981 this.gameOver(data.score, data.scoreMsg);
985 clickDraw: function() {
986 if (!this.game.mycolor || this.game.type == "import") return;
987 if (["received", "threerep"].includes(this.drawOffer)) {
988 if (!confirm(this.st.tr["Accept draw?"])) return;
990 this.drawOffer == "received"
992 : "Three repetitions";
993 this.send("draw", { data: message });
994 this.gameOver("1/2", message);
995 } else if (this.drawOffer == "") {
996 // No effect if drawOffer == "sent"
997 if (this.game.mycolor != this.vr.turn) {
998 alert(this.st.tr["Draw offer only in your turn"]);
1001 if (!confirm(this.st.tr["Offer draw?"])) return;
1002 this.drawOffer = "sent";
1003 this.send("drawoffer");
1004 if (this.game.type == "live") {
1007 { drawOffer: this.game.mycolor }
1009 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1012 addAndGotoLiveGame: function(gameInfo, callback) {
1013 const game = Object.assign(
1017 // (other) Game infos: constant
1018 fenStart: gameInfo.fen,
1019 vname: this.game.vname,
1020 created: Date.now(),
1021 // Game state (including FEN): will be updated
1023 clocks: [-1, -1], //-1 = unstarted
1028 GameStorage.add(game, (err) => {
1029 // No error expected.
1031 if (this.st.settings.sound)
1032 new Audio("/sounds/newgame.flac").play().catch(() => {});
1033 if (!!callback) callback();
1034 this.$router.push("/game/" + gameInfo.id);
1038 clickRematch: function() {
1039 if (!this.game.mycolor || this.game.type == "import") return;
1040 if (this.rematchOffer == "received") {
1041 // Start a new game!
1043 id: getRandString(), //ignored if corr
1044 fen: V.GenRandInitFen(this.game.randomness),
1045 players: [this.game.players[1], this.game.players[0]],
1047 cadence: this.game.cadence
1049 const notifyNewGame = () => {
1050 const oppsid = this.getOppsid(); //may be null
1051 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1052 // To main Hall if corr game:
1053 if (this.game.type == "corr")
1054 this.send("newgame", { data: gameInfo, page: "/" });
1055 // Also to MyGames page:
1056 this.notifyMyGames("newgame", gameInfo);
1058 if (this.game.type == "live")
1059 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1066 // cid is useful to delete the challenge:
1067 data: { gameInfo: gameInfo },
1068 success: (response) => {
1069 gameInfo.id = response.gameId;
1071 this.$router.push("/game/" + response.gameId);
1076 } else if (this.rematchOffer == "") {
1077 this.rematchOffer = "sent";
1078 this.send("rematchoffer", { data: true });
1079 if (this.game.type == "live") {
1082 { rematchOffer: this.game.mycolor }
1084 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1085 } else if (this.rematchOffer == "sent") {
1086 // Toggle rematch offer (on --> off)
1087 this.rematchOffer = "";
1088 this.send("rematchoffer", { data: false });
1089 if (this.game.type == "live") {
1092 { rematchOffer: '' }
1094 } else this.updateCorrGame({ rematchOffer: 'n' });
1097 abortGame: function() {
1098 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1100 this.gameOver("?", "Stop");
1103 resign: function() {
1104 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1106 this.send("resign", { data: this.game.mycolor });
1107 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1108 const side = (this.game.mycolor == "w" ? "White" : "Black");
1109 this.gameOver(score, side + " surrender");
1111 loadGame: function(game, callback) {
1112 const gtype = game.type || this.getGameType(game);
1113 const tc = extractTime(game.cadence);
1114 const myIdx = game.players.findIndex(p => {
1116 p.sid == this.st.user.sid ||
1117 (!!p.name && p.id == this.st.user.id)
1120 // Sometimes the name isn't stored yet (TODO: why?)
1124 !game.players[myIdx].name &&
1127 game.players[myIdx].name = this.st.user.name;
1130 { playerName: { idx: myIdx, name: this.st.user.name } }
1133 // "mycolor" is undefined for observers
1134 const mycolor = [undefined, "w", "b"][myIdx + 1];
1135 if (gtype == "corr") {
1136 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1137 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1138 // NOTE: clocks in seconds
1139 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1140 game.clocks = [tc.mainTime, tc.mainTime];
1141 const L = game.moves.length;
1142 if (game.score == "*") {
1145 game.clocks[L % 2] -=
1146 (Date.now() - game.moves[L-1].played) / 1000;
1149 // Now that we used idx and played, re-format moves as for live games
1150 game.moves = game.moves.map(m => m.squares);
1152 else if (gtype == "live") {
1153 if (game.clocks[0] < 0) {
1154 // Game is unstarted. clock is ignored until move 2
1155 game.clocks = [tc.mainTime, tc.mainTime];
1157 // I play in this live game
1160 { clocks: game.clocks }
1165 // It's my turn: clocks not updated yet
1166 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1170 // gtype == "import"
1171 game.clocks = [tc.mainTime, tc.mainTime];
1172 // Live games before 26/03/2020 don't have chat history:
1173 if (!game.chats) game.chats = []; //TODO: remove line
1174 // Sort chat messages from newest to oldest
1175 game.chats.sort((c1, c2) => c2.added - c1.added);
1178 game.chats.length > 0 &&
1179 (!game.chatRead || game.chatRead < game.chats[0].added)
1181 // A chat message arrived since my last reading:
1182 document.getElementById("chatBtn").classList.add("somethingnew");
1184 // TODO: merge next 2 "if" conditions
1185 if (!!game.drawOffer) {
1186 if (game.drawOffer == "t")
1187 // Three repetitions
1188 this.drawOffer = "threerep";
1190 // Draw offered by any of the players:
1191 if (myIdx < 0) this.drawOffer = "received";
1193 // I play in this game:
1195 (game.drawOffer == "w" && myIdx == 0) ||
1196 (game.drawOffer == "b" && myIdx == 1)
1198 this.drawOffer = "sent";
1199 else this.drawOffer = "received";
1203 if (!!game.rematchOffer) {
1204 if (myIdx < 0) this.rematchOffer = "received";
1206 // I play in this game:
1208 (game.rematchOffer == "w" && myIdx == 0) ||
1209 (game.rematchOffer == "b" && myIdx == 1)
1211 this.rematchOffer = "sent";
1213 else this.rematchOffer = "received";
1216 this.repeat = {}; //reset: scan past moves' FEN:
1218 this.vr = new V(game.fenStart);
1220 game.moves.forEach(m => {
1221 playMove(m, this.vr);
1222 const fenIdx = this.vr.getFenForRepeat();
1223 this.repeat[fenIdx] = this.repeat[fenIdx]
1224 ? this.repeat[fenIdx] + 1
1227 // Imported games don't have current FEN
1228 if (!game.fen) game.fen = this.vr.getFen();
1229 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1230 this.game = Object.assign(
1231 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1234 increment: tc.increment,
1236 // opponent sid not strictly required (or available), but easier
1237 // at least oppsid or oppid is available anyway:
1238 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1239 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1243 this.$refs["basegame"].re_setVariables(this.game);
1245 this.gotMoveIdx = game.moves.length - 1;
1246 // If we arrive here after 'nextGame' action, the board might be hidden
1247 let boardDiv = document.querySelector(".game");
1248 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1249 boardDiv.style.visibility = "visible";
1250 this.re_setClocks();
1251 this.$nextTick(() => {
1252 this.game.rendered = true;
1253 // Did lastate arrive before game was rendered?
1254 if (!!this.lastate) this.processLastate();
1256 if (this.lastateAsked) {
1257 this.lastateAsked = false;
1258 this.sendLastate(game.oppsid);
1260 if (!!callback) callback();
1262 loadVariantThenGame: async function(game, callback) {
1263 await import("@/variants/" + game.vname + ".js")
1264 .then((vModule) => {
1265 window.V = vModule[game.vname + "Rules"];
1266 this.loadGame(game, callback);
1268 // (AJAX) Request to get rules content (plain text, HTML)
1271 "raw-loader!@/translations/rules/" +
1273 this.st.lang + ".pug"
1275 // Next two lines fix a weird issue after last update (2019-11)
1276 .replace(/\\n/g, " ")
1277 .replace(/\\"/g, '"')
1278 .replace('module.exports = "', "")
1280 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1282 // 3 cases for loading a game:
1283 // - from indexedDB (running or completed live game I play)
1284 // - from server (one correspondance game I play[ed] or not)
1285 // - from remote peer (one live game I don't play, finished or not)
1286 fetchGame: function(callback) {
1287 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1288 // corr games identifiers are integers
1293 data: { gid: this.gameRef },
1295 res.game.moves.forEach(m => {
1296 m.squares = JSON.parse(m.squares);
1303 else if (!!this.gameRef.match(/^i/))
1304 // Game import (maybe remote)
1305 ImportgameStorage.get(this.gameRef, callback);
1307 // Local live game (or remote)
1308 GameStorage.get(this.gameRef, callback);
1310 re_setClocks: function() {
1311 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1312 if (this.game.moves.length < 2 || this.game.score != "*") {
1313 // 1st move not completed yet, or game over: freeze time
1316 const currentTurn = this.vr.turn;
1317 const currentMovesCount = this.game.moves.length;
1318 const colorIdx = ["w", "b"].indexOf(currentTurn);
1319 this.clockUpdate = setInterval(
1322 this.game.clocks[colorIdx] < 0 ||
1323 this.game.moves.length > currentMovesCount ||
1324 this.game.score != "*"
1326 clearInterval(this.clockUpdate);
1327 this.clockUpdate = null;
1328 if (this.game.clocks[colorIdx] < 0)
1330 currentTurn == "w" ? "0-1" : "1-0",
1337 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1344 // Update variables and storage after a move:
1345 processMove: function(move, data) {
1346 if (this.game.type == "import")
1347 // Shouldn't receive any messages in this mode:
1349 if (!data) data = {};
1350 const moveCol = this.vr.turn;
1351 const colorIdx = ["w", "b"].indexOf(moveCol);
1352 const nextIdx = 1 - colorIdx;
1353 const doProcessMove = () => {
1354 const origMovescount = this.game.moves.length;
1355 // The move is (about to be) played: stop clock
1356 clearInterval(this.clockUpdate);
1357 this.clockUpdate = null;
1358 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1359 if (this.drawOffer == "received")
1361 this.drawOffer = "";
1362 if (this.game.type == "live" && origMovescount >= 2) {
1363 this.game.clocks[colorIdx] += this.game.increment;
1364 // For a correct display in casqe of disconnected opponent:
1368 ppt(this.game.clocks[colorIdx]).split(':')
1370 GameStorage.update(this.gameRef, {
1371 // It's not my turn anymore:
1376 // Update current game object:
1377 playMove(move, this.vr);
1379 // Received move, score is computed in BaseGame, but maybe not yet.
1380 // ==> Compute it here, although this is redundant (TODO)
1381 data.score = this.vr.getCurrentScore();
1382 if (data.score != "*") this.gameOver(data.score);
1383 this.game.moves.push(move);
1384 this.game.fen = this.vr.getFen();
1385 if (this.game.type == "corr") {
1386 // In corr games, just reset clock to mainTime:
1387 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1389 // If repetition detected, consider that a draw offer was received:
1390 const fenObj = this.vr.getFenForRepeat();
1391 this.repeat[fenObj] =
1392 !!this.repeat[fenObj]
1393 ? this.repeat[fenObj] + 1
1395 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1396 else if (this.drawOffer == "threerep") this.drawOffer = "";
1397 if (!!this.game.mycolor && !data.receiveMyMove) {
1398 // NOTE: 'var' to see that variable outside this block
1399 var filtered_move = getFilteredMove(move);
1401 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1402 // Notify turn on MyGames page:
1411 // Since corr games are stored at only one location, update should be
1412 // done only by one player for each move:
1414 this.game.type == "live" &&
1415 !!this.game.mycolor &&
1416 moveCol != this.game.mycolor &&
1417 this.game.moves.length >= 2
1419 // Receive a move: update initime
1420 this.game.initime = Date.now();
1421 GameStorage.update(this.gameRef, {
1422 // It's my turn now!
1423 initime: this.game.initime
1427 !!this.game.mycolor &&
1428 !data.receiveMyMove &&
1429 (this.game.type == "live" || moveCol == this.game.mycolor)
1432 switch (this.drawOffer) {
1437 drawCode = this.game.mycolor;
1440 drawCode = V.GetOppCol(this.game.mycolor);
1443 if (this.game.type == "corr") {
1444 // corr: only move, fen and score
1445 this.updateCorrGame({
1448 squares: filtered_move,
1451 // Code "n" for "None" to force reset (otherwise it's ignored)
1452 drawOffer: drawCode || "n"
1456 const updateStorage = () => {
1457 GameStorage.update(this.gameRef, {
1459 move: filtered_move,
1460 moveIdx: origMovescount,
1461 clocks: this.game.clocks,
1465 // The active tab can update storage immediately
1466 if (this.focus) updateStorage();
1467 // Small random delay otherwise
1468 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1471 // Send move ("newmove" event) to people in the room (if our turn)
1472 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1474 move: filtered_move,
1475 index: origMovescount,
1476 // color is required to check if this is my move
1477 // (if several tabs opened)
1479 cancelDrawOffer: this.drawOffer == ""
1481 if (this.game.type == "live")
1482 sendMove["clock"] = this.game.clocks[colorIdx];
1483 // (Live) Clocks will re-start when the opponent pingback arrive
1484 this.opponentGotMove = false;
1485 this.send("newmove", {data: sendMove});
1486 // If the opponent doesn't reply gotmove soon enough, re-send move:
1487 // Do this at most 2 times, because more would mean network issues,
1488 // opponent would then be expected to disconnect/reconnect.
1490 const currentUrl = document.location.href;
1491 this.retrySendmove = setInterval(
1495 this.opponentGotMove ||
1496 document.location.href != currentUrl //page change
1498 clearInterval(this.retrySendmove);
1501 const oppsid = this.getOppsid();
1503 // Opponent is disconnected: he'll ask last state
1504 clearInterval(this.retrySendmove);
1506 this.send("newmove", { data: sendMove, target: oppsid });
1514 // Not my move or I'm an observer: just start other player's clock
1515 this.re_setClocks();
1518 this.game.type == "corr" &&
1520 moveCol == this.game.mycolor &&
1523 let boardDiv = document.querySelector(".game");
1524 const afterSetScore = () => {
1526 if (this.st.settings.gotonext && this.nextIds.length > 0)
1527 this.showNextGame();
1529 // The board might have been hidden:
1530 if (boardDiv.style.visibility == "hidden")
1531 boardDiv.style.visibility = "visible";
1532 if (data.score == "*") this.re_setClocks();
1535 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1536 // We may play several moves in a row: in case of, remove listener:
1537 let elClone = el.cloneNode(true);
1538 el.parentNode.replaceChild(elClone, el);
1539 elClone.addEventListener(
1542 document.getElementById("modalConfirm").checked = false;
1543 if (!!data.score && data.score != "*")
1545 this.gameOver(data.score, null, afterSetScore);
1546 else afterSetScore();
1549 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1550 const arMove = (Array.isArray(move) ? move : [move]);
1551 for (let i = 0; i < arMove.length; i++)
1552 V.PlayOnBoard(this.vr.board, arMove[i]);
1553 const position = this.vr.getBaseFen();
1554 for (let i = arMove.length - 1; i >= 0; i--)
1555 V.UndoOnBoard(this.vr.board, arMove[i]);
1556 if (["all","byrow"].includes(V.ShowMoves)) {
1557 this.curDiag = getDiagram({
1559 orientation: V.CanFlip ? this.game.mycolor : "w"
1561 document.querySelector("#confirmDiv > .card").style.width =
1562 boardDiv.offsetWidth + "px";
1565 // Incomplete information: just ask confirmation
1566 // Hide the board, because otherwise it could reveal infos
1567 boardDiv.style.visibility = "hidden";
1568 this.moveNotation = getFullNotation(move);
1570 document.getElementById("modalConfirm").checked = true;
1574 if (!!data.score && data.score != "*")
1575 this.gameOver(data.score, null, doProcessMove);
1576 else doProcessMove();
1579 cancelMove: function() {
1580 let boardDiv = document.querySelector(".game");
1581 if (boardDiv.style.visibility == "hidden")
1582 boardDiv.style.visibility = "visible";
1583 document.getElementById("modalConfirm").checked = false;
1584 this.$refs["basegame"].cancelLastMove();
1586 // In corr games, callback to change page only after score is set:
1587 gameOver: function(score, scoreMsg, callback) {
1588 this.game.score = score;
1589 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1590 this.game.scoreMsg = scoreMsg;
1591 document.getElementById("modalRules").checked = false;
1592 // Display result in a un-missable way:
1593 document.getElementById("modalScore").checked = true;
1594 this.$set(this.game, "scoreMsg", scoreMsg);
1595 const myIdx = this.game.players.findIndex(p => {
1597 p.sid == this.st.user.sid ||
1598 (!!p.name && p.id == this.st.user.id)
1602 // OK, I play in this game
1607 if (this.game.type == "live") {
1608 GameStorage.update(this.gameRef, scoreObj);
1609 // Notify myself locally if I'm elsewhere:
1613 { body: score + " : " + scoreMsg }
1616 if (!!callback) callback();
1618 else this.updateCorrGame(scoreObj, callback);
1619 // Notify the score to main Hall.
1620 // TODO: only one player (currently double send)
1621 this.send("result", { gid: this.game.id, score: score });
1622 // Also to MyGames page (TODO: doubled as well...)
1631 else if (!!callback) callback();
1637 <style lang="sass" scoped>
1638 #scoreDiv > .card, #rematchDiv > .card
1646 @media screen and (max-width: 1500px)
1648 @media screen and (max-width: 1024px)
1650 @media screen and (max-width: 767px)
1660 background-color: lightgreen
1672 @media screen and (max-width: 767px)
1677 display: inline-block
1681 display: inline-block
1683 display: inline-flex
1687 @media screen and (max-width: 767px)
1696 @media screen and (max-width: 767px)
1708 background-color: #edda99
1710 display: inline-block
1714 display: inline-block
1721 @media screen and (max-width: 767px)
1723 display: inline-block
1736 animation: blink-animation 2s steps(3, start) infinite
1737 @keyframes blink-animation
1742 display: inline-block
1754 .draw-sent, .draw-sent:hover
1755 background-color: lightyellow
1757 .draw-received, .draw-received:hover
1758 background-color: #73C6B6
1760 .draw-threerep, .draw-threerep:hover
1761 background-color: #D2B4DE
1763 .rematch-sent, .rematch-sent:hover
1764 background-color: lightyellow
1766 .rematch-received, .rematch-received:hover
1767 background-color: #48C9B0
1770 background-color: #D2B4DE
1783 background-color: lightgreen
1785 background-color: red
1788 color: var(--card-fore-color)
1791 font-size: calc(1rem * var(--heading-ratio))
1793 margin: calc(1.5 * var(--universal-margin))
1797 @import "@/styles/_rules.sass"
1798 @import "@/styles/_board_squares_img.sass"