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,
239 socketCloseListener: 0,
240 // Incomplete info games: show move played
242 // Intervals from setInterval():
246 // Related to (killing of) self multi-connects:
251 $route: function(to, from) {
252 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
254 this.cleanBeforeDestroy();
255 else if (from.params["id"] != to.params["id"]) {
256 // Change everything:
257 this.cleanBeforeDestroy();
258 let boardDiv = document.querySelector(".game");
260 // In case of incomplete information variant:
261 boardDiv.style.visibility = "hidden";
266 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
269 // NOTE: some redundant code with Hall.vue (mostly related to people array)
270 created: function() {
273 mounted: function() {
274 document.getElementById("chatWrap")
275 .addEventListener("click", (e) => {
276 processModalClick(e, () => {
277 this.toggleChat("close")
280 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
282 document.getElementById(eltName)
283 .addEventListener("click", processModalClick);
287 beforeDestroy: function() {
288 this.cleanBeforeDestroy();
291 cleanBeforeDestroy: function() {
292 clearInterval(this.socketCloseListener);
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 this.conn.removeEventListener("message", this.socketMessageListener);
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 atCreation: function() {
337 document.addEventListener('visibilitychange', this.visibilityChange);
338 window.addEventListener('focus', this.onFocus);
339 window.addEventListener('blur', this.onBlur);
340 // 0] (Re)Set variables
341 this.gameRef = this.$route.params["id"];
342 // next = next corr games IDs to navigate faster (if applicable)
343 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
344 // Always add myself to players' list
345 const my = this.st.user;
346 const tmpId = getRandString();
354 tmpId: { focus: true }
359 players: [{ name: "" }, { name: "" }],
363 let chatComp = this.$refs["chatcomp"];
364 if (!!chatComp) chatComp.chats = [];
365 this.virtualClocks = [[0,0], [0,0]];
367 this.rulesContent = "";
369 this.lastateAsked = false;
370 this.rematchOffer = "";
371 this.lastate = undefined;
372 this.roomInitialized = false;
373 this.gotLastate = false;
374 this.gotMoveIdx = -1;
375 this.opponentGotMove = false;
376 this.askLastate = null;
377 this.retrySendmove = null;
378 this.clockUpdate = null;
379 this.newConnect = {};
380 // 1] Initialize connection
381 this.connexionString =
383 "/?sid=" + this.st.user.sid +
384 "&id=" + this.st.user.id +
387 // Discard potential "/?next=[...]" for page indication:
388 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
389 this.conn = new WebSocket(this.connexionString);
390 this.conn.addEventListener("message", this.socketMessageListener);
391 this.socketCloseListener = setInterval(
393 if (this.conn.readyState == 3) {
394 this.conn.removeEventListener(
395 "message", this.socketMessageListener);
396 this.conn = new WebSocket(this.connexionString);
397 this.conn.addEventListener("message", this.socketMessageListener);
402 // Socket init required before loading remote game:
403 const socketInit = callback => {
404 if (this.conn.readyState == 1)
408 // Socket not ready yet (initial loading)
409 // NOTE: first arg is Websocket object, unused here:
410 this.conn.onopen = () => callback();
412 this.fetchGame((game) => {
415 // Patch for retro-compatibility (TODO: remove it)
416 game.options = { randomness: game.randomness };
417 delete game["randomness"];
419 else game.options = JSON.parse(game.options);
420 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
423 // Live game stored remotely: need socket to retrieve it
424 // NOTE: the callback "roomInit" will be lost, so it's not provided.
425 // --> It will be given when receiving "fullgame" socket event.
426 socketInit(() => { this.send("askfullgame"); });
429 roomInit: function() {
430 if (!this.roomInitialized) {
431 // Notify the room only now that I connected, because
432 // messages might be lost otherwise (if game loading is slow)
433 this.send("connect");
434 this.send("pollclients");
435 // We may ask fullgame several times if some moves are lost,
436 // but room should be init only once:
437 this.roomInitialized = true;
440 send: function(code, obj) {
441 if (!!this.conn && this.conn.readyState == 1)
442 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
444 isConnected: function(index) {
445 const player = this.game.players[index];
446 // Is it me ? In this case no need to bother with focus
448 this.st.user.sid == player.sid ||
449 (!!player.name && this.st.user.id == player.id)
451 // Still have to check for name (because of potential multi-accounts
452 // on same browser, although this should be rare...)
453 return (!this.st.user.name || this.st.user.name == player.name);
455 // Try to find a match in people:
459 Object.keys(this.people).some(sid => {
462 Object.values(this.people[sid].tmpIds).some(v => v.focus)
469 Object.values(this.people).some(p => {
472 Object.values(p.tmpIds).some(v => v.focus)
478 getOppsid: function() {
479 let oppsid = this.game.oppsid;
481 oppsid = Object.keys(this.people).find(
482 sid => this.people[sid].id == this.game.oppid
485 // oppsid is useful only if opponent is online:
486 if (!!oppsid && !!this.people[oppsid]) return oppsid;
489 // NOTE: action if provided is always a closing action
490 toggleChat: function(action) {
491 if (!action && document.getElementById("modalChat").checked)
493 document.getElementById("inputChat").focus();
495 document.getElementById("chatBtn").classList.remove("somethingnew");
496 if (!!this.game.mycolor) {
497 // Update "chatRead" variable either on server or locally
498 if (this.game.type == "corr")
499 this.updateCorrGame({ chatRead: this.game.mycolor });
500 else if (this.game.type == "live")
501 GameStorage.update(this.gameRef, { chatRead: true });
505 processChat: function(chat) {
506 this.send("newchat", { data: chat });
507 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
508 if (!!this.game.mycolor) {
509 if (this.game.type == "corr")
510 this.updateCorrGame({ chat: chat });
513 chat.added = Date.now();
514 GameStorage.update(this.gameRef, { chat: chat });
518 clearChat: function() {
519 if (!!this.game.mycolor) {
520 if (this.game.type == "corr") {
524 { data: { gid: this.game.id } }
529 GameStorage.update(this.gameRef, { delchat: true });
531 this.$set(this.game, "chats", []);
534 getGameType: function(game) {
535 if (!!game.id.toString().match(/^i/)) return "import";
536 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
538 // Notify something after a new move (to opponent and me on MyGames page)
539 notifyMyGames: function(thing, data) {
544 targets: this.game.players.map(p => {
545 return { sid: p.sid, id: p.id };
550 showNextGame: function() {
551 // Did I play in current game? If not, add it to nextIds list
552 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
553 this.nextIds.unshift(this.game.id);
554 const nextGid = this.nextIds.pop();
556 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
558 socketMessageListener: function(msg) {
559 if (!this.conn) return;
560 const data = JSON.parse(msg.data);
563 // TODO: shuffling and random filtering on server,
564 // if the room is really crowded.
565 Object.keys(data.sockIds).forEach(sid => {
566 if (sid != this.st.user.sid) {
567 this.send("askidentity", { target: sid });
568 this.people[sid] = { tmpIds: data.sockIds[sid] };
571 // Complete my tmpIds:
572 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
577 if (!this.people[data.from[0]]) {
578 // focus depends on the tmpId (e.g. tab)
584 [data.from[1]]: { focus: true }
588 // For self multi-connects tests:
589 this.newConnect[data.from[0]] = true;
590 this.send("askidentity", { target: data.from[0] });
593 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
594 this.$forceUpdate(); //TODO: shouldn't be required
598 if (!this.people[data.from[0]]) return;
599 delete this.people[data.from[0]].tmpIds[data.from[1]];
600 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
601 this.$delete(this.people, data.from[0]);
602 else this.$forceUpdate(); //TODO: shouldn't be required
605 let player = this.people[data.from[0]];
607 player.tmpIds[data.from[1]].focus = true;
608 this.$forceUpdate(); //TODO: shouldn't be required
613 let player = this.people[data.from[0]];
615 player.tmpIds[data.from[1]].focus = false;
616 this.$forceUpdate(); //TODO: shouldn't be required
620 case "askidentity": {
621 // Request for identification
623 // Decompose to avoid revealing email
624 name: this.st.user.name,
625 sid: this.st.user.sid,
628 this.send("identity", { data: me, target: data.from });
632 const user = data.data;
633 let player = this.people[user.sid];
634 // player.tmpIds is already set
635 player.name = user.name;
637 if (this.game.type == "live") {
639 this.game.players.findIndex(p => p.sid == this.st.user.sid);
640 // Sometimes a player name isn't stored yet (TODO: why?)
643 !this.game.players[1 - myGidx].name &&
644 this.game.players[1 - myGidx].sid == user.sid &&
647 this.game.players[1-myGidx].name = user.name;
650 { playerName: { idx: 1 - myGidx, name: user.name } }
654 this.$forceUpdate(); //TODO: shouldn't be required
655 // If I multi-connect, kill current connexion if no mark (I'm older)
656 if (this.newConnect[user.sid]) {
657 delete this.newConnect[user.sid];
660 user.id == this.st.user.id &&
661 user.sid != this.st.user.sid
663 this.cleanBeforeDestroy();
664 alert(this.st.tr["New connexion detected: tab now offline"]);
668 // Ask potentially missed last state, if opponent and I play
671 !!this.game.mycolor &&
672 this.game.type == "live" &&
673 this.game.players.some(p => p.sid == user.sid)
675 this.send("asklastate", { target: user.sid });
677 this.askLastate = setInterval(
679 // Ask at most 3 times:
680 // if no reply after that there should be a network issue.
684 !!this.people[user.sid]
686 this.send("asklastate", { target: user.sid });
689 else clearInterval(this.askLastate);
697 // Send current (live or import) game,
698 // if not asked by any of the players
700 this.game.type != "corr" &&
701 this.game.players.every(p => p.sid != data.from[0])
705 // FEN is current position, unused for now
707 players: this.game.players,
709 cadence: this.game.cadence,
710 score: this.game.score
712 this.send("game", { data: myGame, target: data.from });
716 const gameToSend = Object.keys(this.game)
719 "id","fen","players","vid","cadence","fenStart","options",
720 "moves","clocks","score","drawOffer","rematchOffer"
724 obj[k] = this.game[k];
729 this.send("fullgame", { data: gameToSend, target: data.from });
732 if (!!data.data.empty) {
733 alert(this.st.tr["The game should be in another tab"]);
737 // Callback "roomInit" to poll clients only after game is loaded
738 this.loadVariantThenGame(data.data, this.roomInit);
741 // Sending informative last state if I played a move or score != "*"
742 // If the game or moves aren't loaded yet, delay the sending:
743 // TODO: socket init after game load, so the game is supposedly ready
744 if (!this.game || !this.game.moves) this.lastateAsked = true;
745 else this.sendLastate(data.from);
747 // TODO: possible bad scenario: reload page while oppponent sends a
748 // move => get both lastate and newmove, process both, add move twice.
749 // Confirm scenario? Fix?
751 // Got opponent infos about last move
752 this.gotLastate = true;
753 this.lastate = data.data;
754 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
755 this.gotMoveIdx = this.lastate.movesCount - 1;
756 if (this.game.rendered)
757 // Game is rendered (Board component)
758 this.processLastate();
759 // Else: will be processed when game is ready
765 //console.log("Receive move");
766 //console.log(data.data);
767 //moveslist not updated when receiving a move? (see in BaseGame)
769 const movePlus = data.data;
770 const movesCount = this.game.moves.length;
772 movePlus.index < movesCount ||
773 this.gotMoveIdx >= movePlus.index
775 // Opponent re-send but we already have the move:
776 // (maybe he didn't receive our pingback...)
777 this.send("gotmove", {data: movePlus.index, target: data.from});
780 this.gotMoveIdx = movePlus.index;
781 const receiveMyMove = (movePlus.color == this.game.mycolor);
782 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
783 if (!receiveMyMove && !!this.game.mycolor) {
784 // Notify opponent that I got the move:
787 { data: movePlus.index, target: data.from }
789 // And myself if I'm elsewhere:
795 (this.game.players[moveColIdx].name || "@nonymous") +
801 if (movePlus.cancelDrawOffer) {
802 // Opponent refuses draw
804 // NOTE for corr games: drawOffer reset by player in turn
806 this.game.type == "live" &&
807 !!this.game.mycolor &&
810 GameStorage.update(this.gameRef, { drawOffer: "" });
813 this.$refs["basegame"].play(movePlus.move, "received");
814 // Freeze time while the move is being play
815 // (TODO: a callback would be cleaner here)
816 clearInterval(this.clockUpdate);
817 this.clockUpdate = null;
818 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
819 // 250 = length of animation, 500 = delay between sub-moves
821 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
822 // Incomplete information: no move animation
826 this.game.clocks[moveColIdx] = movePlus.clock;
829 { receiveMyMove: receiveMyMove }
838 this.opponentGotMove = true;
839 // Now his clock starts running on my side:
840 const oppIdx = ['w','b'].indexOf(this.vr.turn);
841 // NOTE: next line to avoid multi-resetClocks when several tabs
842 // on same game, resulting in a faster countdown.
843 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
848 const score = (data.data == "b" ? "1-0" : "0-1");
849 const side = (data.data == "w" ? "White" : "Black");
850 this.gameOver(score, side + " surrender");
853 this.gameOver("?", "Stop");
856 this.gameOver("1/2", data.data);
859 // NOTE: observers don't know who offered draw
860 this.drawOffer = "received";
861 if (!!this.game.mycolor && this.game.type == "live") {
864 { drawOffer: V.GetOppCol(this.game.mycolor) }
869 // NOTE: observers don't know who offered rematch
870 this.rematchOffer = data.data ? "received" : "";
871 if (!!this.game.mycolor && this.game.type == "live") {
874 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
879 // A game started, redirect if I'm playing in
880 const gameInfo = data.data;
881 const gameType = this.getGameType(gameInfo);
883 gameType == "live" &&
884 gameInfo.players.some(p => p.sid == this.st.user.sid)
886 this.addAndGotoLiveGame(gameInfo);
889 gameType == "corr" &&
890 this.st.user.id > 0 &&
891 gameInfo.players.some(p => p.id == this.st.user.id)
893 this.$router.push("/game/" + gameInfo.id);
896 this.rematchId = gameInfo.id;
897 document.getElementById("modalRules").checked = false;
898 document.getElementById("modalScore").checked = false;
899 document.getElementById("modalRematch").checked = true;
904 let chat = data.data;
905 this.$refs["chatcomp"].newChat(chat);
906 if (this.game.type == "live") {
907 chat.added = Date.now();
908 if (!!this.game.mycolor)
909 GameStorage.update(this.gameRef, { chat: chat });
911 if (!document.getElementById("modalChat").checked)
912 document.getElementById("chatBtn").classList.add("somethingnew");
917 updateCorrGame: function(obj, callback) {
927 if (!!callback) callback();
932 sendLastate: function(target) {
933 // Send our "last state" informations to opponent
934 const L = this.game.moves.length;
935 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
938 (L > 0 && this.vr.turn != this.game.mycolor)
939 ? this.game.moves[L - 1]
941 clock: this.game.clocks[myIdx],
942 // Since we played a move (or abort or resign),
943 // only drawOffer=="sent" is possible
944 drawSent: this.drawOffer == "sent" ? true : undefined,
945 rematchSent: this.rematchOffer == "sent" ? true : undefined,
946 score: this.game.score != "*" ? this.game.score : undefined,
947 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
950 this.send("lastate", { data: myLastate, target: target });
952 // lastate was received, but maybe game wasn't ready yet:
953 processLastate: function() {
954 const data = this.lastate;
955 this.lastate = undefined; //security...
957 const oppCol = V.GetOppCol(this.game.mycolor);
958 if (!!data.rematchSent) {
959 if (this.game.rematchOffer != oppCol) {
960 // Opponent sended rematch offer while we were offline:
961 this.rematchOffer = "received";
964 { rematchOffer: oppCol }
969 if (this.game.rematchOffer == oppCol) {
970 // Opponent cancelled rematch offer while we were offline:
971 this.rematchOffer = "";
980 const L = this.game.moves.length;
981 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
982 this.game.clocks[oppIdx] = data.clock;
983 if (data.movesCount > L) {
984 // Just got last move from him
985 this.$refs["basegame"].play(data.lastMove, "received");
986 this.processMove(data.lastMove);
989 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
992 if (!!data.drawSent) this.drawOffer = "received";
995 if (this.game.score == "*")
996 this.gameOver(data.score, data.scoreMsg);
1000 clickDraw: function() {
1001 if (!this.game.mycolor || this.game.type == "import") return;
1002 if (["received", "threerep"].includes(this.drawOffer)) {
1003 if (!confirm(this.st.tr["Accept draw?"])) return;
1005 this.drawOffer == "received"
1006 ? "Mutual agreement"
1007 : "Three repetitions";
1008 this.send("draw", { data: message });
1009 this.gameOver("1/2", message);
1011 else if (this.drawOffer == "") {
1012 // No effect if drawOffer == "sent"
1013 if (this.game.mycolor != this.vr.turn) {
1014 alert(this.st.tr["Draw offer only in your turn"]);
1017 if (!confirm(this.st.tr["Offer draw?"])) return;
1018 this.drawOffer = "sent";
1019 this.send("drawoffer");
1020 if (this.game.type == "live") {
1023 { drawOffer: this.game.mycolor }
1026 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1029 addAndGotoLiveGame: function(gameInfo, callback) {
1030 const game = Object.assign(
1034 // (other) Game infos: constant
1035 fenStart: gameInfo.fen,
1036 created: Date.now(),
1037 // Game state (including FEN): will be updated
1039 clocks: [-1, -1], //-1 = unstarted
1044 GameStorage.add(game, (err) => {
1045 // No error expected.
1047 if (this.st.settings.sound)
1048 new Audio("/sounds/newgame.flac").play().catch(() => {});
1049 if (!!callback) callback();
1050 this.$router.push("/game/" + gameInfo.id);
1054 clickRematch: function() {
1055 if (!this.game.mycolor || this.game.type == "import") return;
1056 if (this.rematchOffer == "received") {
1057 // Start a new game!
1059 id: getRandString(), //ignored if corr
1060 fen: V.GenRandInitFen(this.game.options),
1061 options: this.game.options,
1062 players: [this.game.players[1], this.game.players[0]],
1064 cadence: this.game.cadence
1066 const notifyNewGame = () => {
1067 this.send("rnewgame", { data: gameInfo });
1068 // To main Hall if corr game:
1069 if (this.game.type == "corr")
1070 this.send("newgame", { data: gameInfo, page: "/" });
1071 // Also to MyGames page:
1072 this.notifyMyGames("newgame", gameInfo);
1074 if (this.game.type == "live") {
1077 { rematchOffer: "" }
1079 // Increment game stats counter in DB
1083 { data: { vid: gameInfo.vid } }
1085 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1089 this.updateCorrGame({ rematchOffer: 'n' });
1094 data: Object.assign(
1097 { options: JSON.stringify(this.game.options) }
1099 success: (response) => {
1100 gameInfo.id = response.id;
1102 this.$router.push("/game/" + response.id);
1108 else if (this.rematchOffer == "") {
1109 this.rematchOffer = "sent";
1110 this.send("rematchoffer", { data: true });
1111 if (this.game.type == "live") {
1114 { rematchOffer: this.game.mycolor }
1117 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1119 else if (this.rematchOffer == "sent") {
1120 // Toggle rematch offer (on --> off)
1121 this.rematchOffer = "";
1122 this.send("rematchoffer", { data: false });
1123 if (this.game.type == "live") {
1126 { rematchOffer: '' }
1129 else this.updateCorrGame({ rematchOffer: 'n' });
1132 abortGame: function() {
1133 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1135 this.gameOver("?", "Stop");
1138 resign: function() {
1139 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1141 this.send("resign", { data: this.game.mycolor });
1142 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1143 const side = (this.game.mycolor == "w" ? "White" : "Black");
1144 this.gameOver(score, side + " surrender");
1146 loadGame: function(game, callback) {
1147 const gtype = game.type || this.getGameType(game);
1148 const tc = extractTime(game.cadence);
1149 const myIdx = game.players.findIndex(p => {
1151 p.sid == this.st.user.sid ||
1152 (!!p.name && p.id == this.st.user.id)
1155 // Sometimes the name isn't stored yet (TODO: why?)
1159 !game.players[myIdx].name &&
1162 game.players[myIdx].name = this.st.user.name;
1165 { playerName: { idx: myIdx, name: this.st.user.name } }
1168 // "mycolor" is undefined for observers
1169 const mycolor = [undefined, "w", "b"][myIdx + 1];
1170 if (gtype == "corr") {
1171 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1172 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1173 // NOTE: clocks in seconds
1174 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1175 game.clocks = [tc.mainTime, tc.mainTime];
1176 const L = game.moves.length;
1177 if (game.score == "*") {
1180 game.clocks[L % 2] -=
1181 (Date.now() - game.moves[L-1].played) / 1000;
1184 // Now that we used idx and played, re-format moves as for live games
1185 game.moves = game.moves.map(m => m.squares);
1187 else if (gtype == "live") {
1188 if (game.clocks[0] < 0) {
1189 // Game is unstarted. clock is ignored until move 2
1190 game.clocks = [tc.mainTime, tc.mainTime];
1192 // I play in this live game
1195 { clocks: game.clocks }
1199 else if (!!game.initime)
1200 // It's my turn: clocks not updated yet
1201 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1204 // gtype == "import"
1205 game.clocks = [tc.mainTime, tc.mainTime];
1206 // Live games before 26/03/2020 don't have chat history:
1207 if (!game.chats) game.chats = []; //TODO: remove line
1208 // Sort chat messages from newest to oldest
1209 game.chats.sort((c1, c2) => c2.added - c1.added);
1212 game.chats.length > 0 &&
1213 (!game.chatRead || game.chatRead < game.chats[0].added)
1215 // A chat message arrived since my last reading:
1216 document.getElementById("chatBtn").classList.add("somethingnew");
1218 // TODO: merge next 2 "if" conditions
1219 if (!!game.drawOffer) {
1220 if (game.drawOffer == "t")
1221 // Three repetitions
1222 this.drawOffer = "threerep";
1224 // Draw offered by any of the players:
1225 if (myIdx < 0) this.drawOffer = "received";
1227 // I play in this game:
1229 (game.drawOffer == "w" && myIdx == 0) ||
1230 (game.drawOffer == "b" && myIdx == 1)
1232 this.drawOffer = "sent";
1233 else this.drawOffer = "received";
1237 if (!!game.rematchOffer) {
1238 if (myIdx < 0) this.rematchOffer = "received";
1240 // I play in this game:
1242 (game.rematchOffer == "w" && myIdx == 0) ||
1243 (game.rematchOffer == "b" && myIdx == 1)
1245 this.rematchOffer = "sent";
1247 else this.rematchOffer = "received";
1250 this.repeat = {}; //reset: scan past moves' FEN:
1252 this.vr = new V(game.fenStart);
1254 game.moves.forEach(m => {
1255 playMove(m, this.vr);
1256 const fenIdx = this.vr.getFenForRepeat();
1257 this.repeat[fenIdx] = this.repeat[fenIdx]
1258 ? this.repeat[fenIdx] + 1
1261 // Imported games don't have current FEN
1262 if (!game.fen) game.fen = this.vr.getFen();
1263 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1264 this.game = Object.assign(
1265 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1268 increment: tc.increment,
1270 // opponent sid not strictly required (or available), but easier
1271 // at least oppsid or oppid is available anyway:
1272 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1273 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1277 this.$refs["basegame"].re_setVariables(this.game);
1279 this.gotMoveIdx = game.moves.length - 1;
1280 // If we arrive here after 'nextGame' action, the board might be hidden
1281 let boardDiv = document.querySelector(".game");
1282 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1283 boardDiv.style.visibility = "visible";
1284 this.re_setClocks();
1285 this.$nextTick(() => {
1286 this.game.rendered = true;
1287 // Did lastate arrive before game was rendered?
1288 if (!!this.lastate) this.processLastate();
1290 if (this.lastateAsked) {
1291 this.lastateAsked = false;
1292 this.sendLastate(game.oppsid);
1294 if (!!callback) callback();
1296 loadVariantThenGame: async function(game, callback) {
1297 const afterSetVname = async () => {
1298 await import("@/variants/" + game.vname + ".js")
1299 .then((vModule) => {
1300 window.V = vModule[game.vname + "Rules"];
1301 this.loadGame(game, callback);
1306 "raw-loader!@/translations/rules/" +
1307 game.vname + "/" + this.st.lang + ".pug"
1309 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1311 let variant = undefined;
1312 const trySetVname = setInterval(
1314 // this.st.variants might be uninitialized (variant == null)
1315 variant = this.st.variants.find(v => v.id == game.vid);
1317 clearInterval(trySetVname);
1318 game.vname = variant.name;
1319 game.vdisp = variant.display;
1325 // 3 cases for loading a game:
1326 // - from indexedDB (running or completed live game I play)
1327 // - from server (one correspondance game I play[ed] or not)
1328 // - from remote peer (one live game I don't play, finished or not)
1329 fetchGame: function(callback) {
1331 Number.isInteger(this.gameRef) ||
1332 !isNaN(parseInt(this.gameRef, 10))
1334 // corr games identifiers are integers
1339 data: { gid: this.gameRef },
1341 res.game.moves.forEach(m => {
1342 m.squares = JSON.parse(m.squares);
1349 else if (!!this.gameRef.match(/^i/))
1350 // Game import (maybe remote)
1351 ImportgameStorage.get(this.gameRef, callback);
1353 // Local live game (or remote)
1354 GameStorage.get(this.gameRef, callback);
1356 re_setClocks: function() {
1357 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1358 if (this.game.moves.length < 2 || this.game.score != "*") {
1359 // 1st move not completed yet, or game over: freeze time
1362 const currentTurn = this.vr.turn;
1363 const currentMovesCount = this.game.moves.length;
1364 const colorIdx = ["w", "b"].indexOf(currentTurn);
1365 this.clockUpdate = setInterval(
1368 this.game.clocks[colorIdx] < 0 ||
1369 this.game.moves.length > currentMovesCount ||
1370 this.game.score != "*"
1372 clearInterval(this.clockUpdate);
1373 this.clockUpdate = null;
1374 if (this.game.clocks[colorIdx] < 0)
1376 currentTurn == "w" ? "0-1" : "1-0",
1384 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1391 // Update variables and storage after a move:
1392 processMove: function(move, data) {
1393 if (this.game.type == "import")
1394 // Shouldn't receive any messages in this mode:
1396 if (!data) data = {};
1397 const moveCol = this.vr.turn;
1398 const colorIdx = ["w", "b"].indexOf(moveCol);
1399 const nextIdx = 1 - colorIdx;
1400 const doProcessMove = () => {
1401 const origMovescount = this.game.moves.length;
1402 // The move is (about to be) played: stop clock
1403 clearInterval(this.clockUpdate);
1404 this.clockUpdate = null;
1405 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1406 if (this.drawOffer == "received")
1408 this.drawOffer = "";
1409 if (this.game.type == "live" && origMovescount >= 2) {
1410 this.game.clocks[colorIdx] += this.game.increment;
1411 // For a correct display in casqe of disconnected opponent:
1415 ppt(this.game.clocks[colorIdx]).split(':')
1417 GameStorage.update(this.gameRef, {
1418 // It's not my turn anymore:
1423 // Update current game object:
1424 playMove(move, this.vr);
1426 // Received move, score is computed in BaseGame, but maybe not yet.
1427 // ==> Compute it here, although this is redundant (TODO)
1428 data.score = this.vr.getCurrentScore();
1429 if (data.score != "*") this.gameOver(data.score);
1430 this.game.moves.push(move);
1431 this.game.fen = this.vr.getFen();
1432 if (this.game.type == "corr") {
1433 // In corr games, just reset clock to mainTime:
1434 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1436 if (!V.IgnoreRepetition) {
1437 // If repetition detected, consider that a draw offer was received:
1438 const fenObj = this.vr.getFenForRepeat();
1439 this.repeat[fenObj] =
1440 !!this.repeat[fenObj]
1441 ? this.repeat[fenObj] + 1
1443 if (this.repeat[fenObj] >= 3) {
1444 if (this.vr.loseOnRepetition())
1445 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1446 else this.drawOffer = "threerep";
1448 else if (this.drawOffer == "threerep") this.drawOffer = "";
1450 if (!!this.game.mycolor && !data.receiveMyMove) {
1451 // NOTE: 'var' to see that variable outside this block
1452 var filtered_move = getFilteredMove(move);
1454 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1455 // Notify turn on MyGames page:
1464 // Since corr games are stored at only one location, update should be
1465 // done only by one player for each move:
1467 this.game.type == "live" &&
1468 !!this.game.mycolor &&
1469 moveCol != this.game.mycolor &&
1470 this.game.moves.length >= 2
1472 // Receive a move: update initime
1473 this.game.initime = Date.now();
1474 GameStorage.update(this.gameRef, {
1475 // It's my turn now!
1476 initime: this.game.initime
1480 !!this.game.mycolor &&
1481 !data.receiveMyMove &&
1482 (this.game.type == "live" || moveCol == this.game.mycolor)
1485 switch (this.drawOffer) {
1490 drawCode = this.game.mycolor;
1493 drawCode = V.GetOppCol(this.game.mycolor);
1496 if (this.game.type == "corr") {
1497 // corr: only move, fen and score
1498 this.updateCorrGame({
1501 squares: filtered_move,
1504 // Code "n" for "None" to force reset (otherwise it's ignored)
1505 drawOffer: drawCode || "n"
1509 const updateStorage = () => {
1510 GameStorage.update(this.gameRef, {
1512 move: filtered_move,
1513 moveIdx: origMovescount,
1514 clocks: this.game.clocks,
1518 // The active tab can update storage immediately
1519 if (this.focus) updateStorage();
1520 // Small random delay otherwise
1521 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1524 // Send move ("newmove" event) to people in the room (if our turn)
1525 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1527 move: filtered_move,
1528 index: origMovescount,
1529 // color is required to check if this is my move
1530 // (if several tabs opened)
1532 cancelDrawOffer: this.drawOffer == ""
1534 if (this.game.type == "live")
1535 sendMove["clock"] = this.game.clocks[colorIdx];
1536 // (Live) Clocks will re-start when the opponent pingback arrive
1537 this.opponentGotMove = false;
1538 this.send("newmove", {data: sendMove});
1539 // If the opponent doesn't reply gotmove soon enough, re-send move:
1540 // Do this at most 2 times, because more would mean network issues,
1541 // opponent would then be expected to disconnect/reconnect.
1543 const currentUrl = document.location.href;
1544 this.retrySendmove = setInterval(
1548 this.opponentGotMove ||
1549 document.location.href != currentUrl //page change
1551 clearInterval(this.retrySendmove);
1554 const oppsid = this.getOppsid();
1556 // Opponent is disconnected: he'll ask last state
1557 clearInterval(this.retrySendmove);
1559 this.send("newmove", { data: sendMove, target: oppsid });
1567 // Not my move or I'm an observer: just start other player's clock
1568 this.re_setClocks();
1571 this.game.type == "corr" &&
1572 moveCol == this.game.mycolor &&
1575 let boardDiv = document.querySelector(".game");
1576 const afterSetScore = () => {
1578 if (this.st.settings.gotonext && this.nextIds.length > 0)
1579 this.showNextGame();
1581 // The board might have been hidden:
1582 if (boardDiv.style.visibility == "hidden")
1583 boardDiv.style.visibility = "visible";
1584 if (data.score == "*") this.re_setClocks();
1587 if (!V.CorrConfirm) {
1591 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1592 // We may play several moves in a row: in case of, remove listener:
1593 let elClone = el.cloneNode(true);
1594 el.parentNode.replaceChild(elClone, el);
1595 elClone.addEventListener(
1598 document.getElementById("modalConfirm").checked = false;
1599 if (!!data.score && data.score != "*")
1601 this.gameOver(data.score, null, afterSetScore);
1602 else afterSetScore();
1605 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1606 const arMove = (Array.isArray(move) ? move : [move]);
1607 for (let i = 0; i < arMove.length; i++)
1608 V.PlayOnBoard(this.vr.board, arMove[i]);
1609 const position = this.vr.getBaseFen();
1610 for (let i = arMove.length - 1; i >= 0; i--)
1611 V.UndoOnBoard(this.vr.board, arMove[i]);
1612 if (["all","byrow"].includes(V.ShowMoves)) {
1613 this.curDiag = getDiagram({
1615 orientation: V.CanFlip ? this.game.mycolor : "w"
1617 document.querySelector("#confirmDiv > .card").style.width =
1618 boardDiv.offsetWidth + "px";
1621 // Incomplete information: just ask confirmation
1622 // Hide the board, because otherwise it could reveal infos
1623 boardDiv.style.visibility = "hidden";
1624 this.moveNotation = getFullNotation(move);
1626 document.getElementById("modalConfirm").checked = true;
1630 if (!!data.score && data.score != "*")
1631 this.gameOver(data.score, null, doProcessMove);
1632 else doProcessMove();
1635 cancelMove: function() {
1636 let boardDiv = document.querySelector(".game");
1637 if (boardDiv.style.visibility == "hidden")
1638 boardDiv.style.visibility = "visible";
1639 document.getElementById("modalConfirm").checked = false;
1640 this.$refs["basegame"].cancelLastMove();
1642 // In corr games, callback to change page only after score is set:
1643 gameOver: function(score, scoreMsg, callback) {
1644 this.game.score = score;
1645 if (!scoreMsg) scoreMsg = getScoreMessage(score, V.ReverseColors);
1646 this.game.scoreMsg = scoreMsg;
1647 document.getElementById("modalRules").checked = false;
1648 // Display result in a un-missable way:
1649 document.getElementById("modalScore").checked = true;
1650 this.$set(this.game, "scoreMsg", scoreMsg);
1651 const myIdx = this.game.players.findIndex(p => {
1653 p.sid == this.st.user.sid ||
1654 (!!p.name && p.id == this.st.user.id)
1658 // OK, I play in this game
1663 if (this.game.type == "live") {
1664 GameStorage.update(this.gameRef, scoreObj);
1665 // Notify myself locally if I'm elsewhere:
1669 { body: score + " : " + scoreMsg }
1672 if (!!callback) callback();
1674 else this.updateCorrGame(scoreObj, callback);
1675 // Notify the score to main Hall.
1676 // TODO: only one player (currently double send)
1677 this.send("result", { gid: this.game.id, score: score });
1678 // Also to MyGames page (TODO: doubled as well...)
1687 else if (!!callback) callback();
1693 <style lang="sass" scoped>
1694 #scoreDiv > .card, #rematchDiv > .card
1702 @media screen and (max-width: 1500px)
1704 @media screen and (max-width: 1024px)
1706 @media screen and (max-width: 767px)
1716 background-color: lightgreen
1728 @media screen and (max-width: 767px)
1733 display: inline-block
1737 display: inline-block
1739 display: inline-flex
1743 @media screen and (max-width: 767px)
1752 @media screen and (max-width: 767px)
1764 background-color: #edda99
1766 display: inline-block
1770 display: inline-block
1777 @media screen and (max-width: 767px)
1779 display: inline-block
1792 animation: blink-animation 2s steps(3, start) infinite
1793 @keyframes blink-animation
1798 display: inline-block
1810 .draw-sent, .draw-sent:hover
1811 background-color: lightyellow
1813 .draw-received, .draw-received:hover
1814 background-color: #73C6B6
1816 .draw-threerep, .draw-threerep:hover
1817 background-color: #D2B4DE
1819 .rematch-sent, .rematch-sent:hover
1820 background-color: lightyellow
1822 .rematch-received, .rematch-received:hover
1823 background-color: #48C9B0
1826 background-color: #D2B4DE
1839 background-color: lightgreen
1841 background-color: red
1844 color: var(--card-fore-color)
1847 font-size: calc(1rem * var(--heading-ratio))
1849 margin: calc(1.5 * var(--universal-margin))
1853 @import "@/styles/_rules.sass"
1854 @import "@/styles/_board_squares_img.sass"