3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 h4#variantNameInGame(@click="gotoRules") {{ game.vname }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
49 v-if="participateInChat(p)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
86 | {{ st.tr["Next_g"] }}
87 button#chatBtn.tooltip(
88 onClick="window.doClick('modalChat')"
91 img(src="/images/icons/chat.svg")
92 #actions(v-if="game.score=='*'")
95 :class="{['draw-' + drawOffer]: true}"
96 :aria-label="st.tr['Draw']"
98 img(src="/images/icons/draw.svg")
100 v-show="!!game.mycolor"
102 :aria-label="st.tr['Abort']"
104 img(src="/images/icons/abort.svg")
106 v-show="!!game.mycolor"
108 :aria-label="st.tr['Resign']"
110 img(src="/images/icons/resign.svg")
113 @click="clickRematch()"
114 :class="{['rematch-' + rematchOffer]: true}"
115 :aria-label="st.tr['Rematch']"
117 img(src="/images/icons/rematch.svg")
119 p(v-if="isLargeScreen()")
120 span.name(:class="{connected: isConnected(0)}")
121 | {{ game.players[0].name || "@nonymous" }}
123 v-if="game.score=='*'"
124 :class="{yourturn: !!vr && vr.turn == 'w'}"
126 span.time-left {{ virtualClocks[0][0] }}
127 span.time-separator(v-if="!!virtualClocks[0][1]") :
128 span.time-right(v-if="!!virtualClocks[0][1]")
129 | {{ virtualClocks[0][1] }}
131 span.name(:class="{connected: isConnected(1)}")
132 | {{ game.players[1].name || "@nonymous" }}
134 v-if="game.score=='*'"
135 :class="{yourturn: !!vr && vr.turn == 'b'}"
137 span.time-left {{ virtualClocks[1][0] }}
138 span.time-separator(v-if="!!virtualClocks[1][1]") :
139 span.time-right(v-if="!!virtualClocks[1][1]")
140 | {{ virtualClocks[1][1] }}
142 span.name(:class="{connected: isConnected(0)}")
143 | {{ game.players[0].name || "@nonymous" }}
145 span.name(:class="{connected: isConnected(1)}")
146 | {{ game.players[1].name || "@nonymous" }}
149 v-if="game.score=='*'"
150 :class="{yourturn: !!vr && vr.turn == 'w'}"
152 span.time-left {{ virtualClocks[0][0] }}
153 span.time-separator(v-if="!!virtualClocks[0][1]") :
154 span.time-right(v-if="!!virtualClocks[0][1]")
155 | {{ virtualClocks[0][1] }}
158 v-if="game.score=='*'"
159 :class="{yourturn: !!vr && vr.turn == 'b'}"
161 span.time-left {{ virtualClocks[1][0] }}
162 span.time-separator(v-if="!!virtualClocks[1][1]") :
163 span.time-right(v-if="!!virtualClocks[1][1]")
164 | {{ virtualClocks[1][1] }}
168 @newmove="processMove"
173 import BaseGame from "@/components/BaseGame.vue";
174 import Chat from "@/components/Chat.vue";
175 import { store } from "@/store";
176 import { GameStorage } from "@/utils/gameStorage";
177 import { ImportgameStorage } from "@/utils/importgameStorage";
178 import { ppt } from "@/utils/datetime";
179 import { notify } from "@/utils/notifications";
180 import { ajax } from "@/utils/ajax";
181 import { extractTime } from "@/utils/timeControl";
182 import { getRandString } from "@/utils/alea";
183 import { getScoreMessage } from "@/utils/scoring";
184 import { getFullNotation } from "@/utils/notation";
185 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
186 import { processModalClick } from "@/utils/modalClick";
187 import { playMove, getFilteredMove } from "@/utils/playUndo";
188 import { ArrayFun } from "@/utils/array";
189 import params from "@/parameters";
199 // gameRef can point to a corr game, local game or remote live game
202 game: {}, //passed to BaseGame
203 focus: !document.hidden, //will not always work... TODO
204 // virtualClocks will be initialized from true game.clocks
206 vr: null, //"variant rules" object initialized from FEN
212 people: {}, //players + observers
213 lastate: undefined, //used if opponent send lastate before game is ready
214 repeat: {}, //detect position repetition
215 curDiag: "", //for corr moves confirmation
217 roomInitialized: false,
218 // If newmove has wrong index: ask fullgame again:
220 gameIsLoading: false,
221 // If asklastate got no reply, ask again:
223 gotMoveIdx: -1, //last move index received
224 // If newmove got no pingback, send again:
225 opponentGotMove: false,
227 socketCloseListener: 0,
228 // Incomplete info games: show move played
230 // Intervals from setInterval():
234 // Related to (killing of) self multi-connects:
239 $route: function(to, from) {
240 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
242 this.cleanBeforeDestroy();
243 else if (from.params["id"] != to.params["id"]) {
244 // Change everything:
245 this.cleanBeforeDestroy();
246 let boardDiv = document.querySelector(".game");
248 // In case of incomplete information variant:
249 boardDiv.style.visibility = "hidden";
253 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
256 // NOTE: some redundant code with Hall.vue (mostly related to people array)
257 created: function() {
260 mounted: function() {
261 document.getElementById("chatWrap")
262 .addEventListener("click", (e) => {
263 processModalClick(e, () => {
264 this.toggleChat("close")
267 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
269 document.getElementById(eltName)
270 .addEventListener("click", processModalClick);
274 beforeDestroy: function() {
275 this.cleanBeforeDestroy();
278 cleanBeforeDestroy: function() {
279 clearInterval(this.socketCloseListener);
280 document.removeEventListener('visibilitychange', this.visibilityChange);
281 window.removeEventListener('focus', this.onFocus);
282 window.removeEventListener('blur', this.onBlur);
283 if (!!this.askLastate) clearInterval(this.askLastate);
284 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
285 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
286 this.conn.removeEventListener("message", this.socketMessageListener);
287 this.send("disconnect");
290 visibilityChange: function() {
291 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
292 this.focus = (document.visibilityState == "visible");
293 if (!this.focus && !!this.rematchOffer) {
294 this.rematchOffer = "";
295 this.send("rematchoffer", { data: false });
296 // Do not remove rematch offer from (local) storage
298 this.send(this.focus ? "getfocus" : "losefocus");
300 onFocus: function() {
302 this.send("getfocus");
306 if (!!this.rematchOffer) {
307 this.rematchOffer = "";
308 this.send("rematchoffer", { data: false });
310 this.send("losefocus");
312 isLargeScreen: function() {
313 return window.innerWidth >= 500;
315 gotoRules: function() {
316 this.$router.push("/variants/" + this.game.vname);
318 participateInChat: function(p) {
319 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
321 someAnonymousPresent: function() {
323 Object.values(this.people).some(p =>
324 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
328 atCreation: function() {
329 document.addEventListener('visibilitychange', this.visibilityChange);
330 window.addEventListener('focus', this.onFocus);
331 window.addEventListener('blur', this.onBlur);
332 // 0] (Re)Set variables
333 this.gameRef = this.$route.params["id"];
334 // next = next corr games IDs to navigate faster (if applicable)
335 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
336 // Always add myself to players' list
337 const my = this.st.user;
338 const tmpId = getRandString();
346 tmpId: { focus: true }
351 players: [{ name: "" }, { name: "" }],
355 let chatComp = this.$refs["chatcomp"];
356 if (!!chatComp) chatComp.chats = [];
357 this.virtualClocks = [[0,0], [0,0]];
359 this.rulesContent = "";
361 this.lastateAsked = false;
362 this.rematchOffer = "";
363 this.lastate = undefined;
364 this.roomInitialized = false;
365 this.askGameTime = 0;
366 this.gameIsLoading = false;
367 this.gotLastate = false;
368 this.gotMoveIdx = -1;
369 this.opponentGotMove = false;
370 this.askLastate = null;
371 this.retrySendmove = null;
372 this.clockUpdate = null;
373 this.newConnect = {};
374 // 1] Initialize connection
375 this.connexionString =
377 "/?sid=" + this.st.user.sid +
378 "&id=" + this.st.user.id +
381 // Discard potential "/?next=[...]" for page indication:
382 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
383 this.conn = new WebSocket(this.connexionString);
384 this.conn.addEventListener("message", this.socketMessageListener);
385 this.socketCloseListener = setInterval(
387 if (this.conn.readyState == 3) {
388 this.conn.removeEventListener(
389 "message", this.socketMessageListener);
390 this.conn = new WebSocket(this.connexionString);
391 this.conn.addEventListener("message", this.socketMessageListener);
396 // Socket init required before loading remote game:
397 const socketInit = callback => {
398 if (this.conn.readyState == 1)
402 // Socket not ready yet (initial loading)
403 // NOTE: first arg is Websocket object, unused here:
404 this.conn.onopen = () => callback();
406 this.fetchGame((game) => {
408 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
410 // Live game stored remotely: need socket to retrieve it
411 // NOTE: the callback "roomInit" will be lost, so it's not provided.
412 // --> It will be given when receiving "fullgame" socket event.
413 socketInit(() => { this.send("askfullgame"); });
416 roomInit: function() {
417 if (!this.roomInitialized) {
418 // Notify the room only now that I connected, because
419 // messages might be lost otherwise (if game loading is slow)
420 this.send("connect");
421 this.send("pollclients");
422 // We may ask fullgame several times if some moves are lost,
423 // but room should be init only once:
424 this.roomInitialized = true;
427 send: function(code, obj) {
428 if (!!this.conn && this.conn.readyState == 1)
429 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
431 isConnected: function(index) {
432 const player = this.game.players[index];
433 // Is it me ? In this case no need to bother with focus
434 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
435 // Still have to check for name (because of potential multi-accounts
436 // on same browser, although this should be rare...)
437 return (!this.st.user.name || this.st.user.name == player.name);
438 // Try to find a match in people:
442 Object.keys(this.people).some(sid => {
445 Object.values(this.people[sid].tmpIds).some(v => v.focus)
452 Object.values(this.people).some(p => {
455 Object.values(p.tmpIds).some(v => v.focus)
461 getOppsid: function() {
462 let oppsid = this.game.oppsid;
464 oppsid = Object.keys(this.people).find(
465 sid => this.people[sid].id == this.game.oppid
468 // oppsid is useful only if opponent is online:
469 if (!!oppsid && !!this.people[oppsid]) return oppsid;
472 // NOTE: action if provided is always a closing action
473 toggleChat: function(action) {
474 if (!action && document.getElementById("modalChat").checked)
476 document.getElementById("inputChat").focus();
478 document.getElementById("chatBtn").classList.remove("somethingnew");
479 if (!!this.game.mycolor) {
480 // Update "chatRead" variable either on server or locally
481 if (this.game.type == "corr")
482 this.updateCorrGame({ chatRead: this.game.mycolor });
483 else if (this.game.type == "live")
484 GameStorage.update(this.gameRef, { chatRead: true });
488 processChat: function(chat) {
489 this.send("newchat", { data: chat });
490 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
491 if (!!this.game.mycolor) {
492 if (this.game.type == "corr")
493 this.updateCorrGame({ chat: chat });
496 chat.added = Date.now();
497 GameStorage.update(this.gameRef, { chat: chat });
501 clearChat: function() {
502 if (!!this.game.mycolor) {
503 if (this.game.type == "corr") {
507 { data: { gid: this.game.id } }
511 GameStorage.update(this.gameRef, { delchat: true });
513 this.$set(this.game, "chats", []);
516 getGameType: function(game) {
517 if (!!game.id.toString().match(/^i/)) return "import";
518 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
520 // Notify something after a new move (to opponent and me on MyGames page)
521 notifyMyGames: function(thing, data) {
526 targets: this.game.players.map(p => {
527 return { sid: p.sid, id: p.id };
532 showNextGame: function() {
533 // Did I play in current game? If not, add it to nextIds list
534 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
535 this.nextIds.unshift(this.game.id);
536 const nextGid = this.nextIds.pop();
538 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
540 askGameAgain: function() {
541 this.gameIsLoading = true;
542 const currentUrl = document.location.href;
543 const doAskGame = () => {
544 if (document.location.href != currentUrl) return; //page change
545 this.fetchGame((game) => {
547 // This is my game: just reload.
550 // Just ask fullgame again (once!), this is much simpler.
551 // If this fails, the user could just reload page :/
552 this.send("askfullgame");
555 // Delay of at least 2s between two game requests
556 const now = Date.now();
557 const delay = Math.max(2000 - (now - this.askGameTime), 0);
558 this.askGameTime = now;
559 setTimeout(doAskGame, delay);
561 socketMessageListener: function(msg) {
562 if (!this.conn) return;
563 const data = JSON.parse(msg.data);
566 // TODO: shuffling and random filtering on server,
567 // if the room is really crowded.
568 Object.keys(data.sockIds).forEach(sid => {
569 if (sid != this.st.user.sid) {
570 this.send("askidentity", { target: sid });
571 this.people[sid] = { tmpIds: data.sockIds[sid] };
574 // Complete my tmpIds:
575 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
580 if (!this.people[data.from[0]]) {
581 // focus depends on the tmpId (e.g. tab)
587 [data.from[1]]: { focus: true }
591 // For self multi-connects tests:
592 this.newConnect[data.from[0]] = true;
593 this.send("askidentity", { target: data.from[0] });
595 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
596 this.$forceUpdate(); //TODO: shouldn't be required
600 if (!this.people[data.from[0]]) return;
601 delete this.people[data.from[0]].tmpIds[data.from[1]];
602 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
603 this.$delete(this.people, data.from[0]);
604 else this.$forceUpdate(); //TODO: shouldn't be required
607 let player = this.people[data.from[0]];
609 player.tmpIds[data.from[1]].focus = true;
610 this.$forceUpdate(); //TODO: shouldn't be required
615 let player = this.people[data.from[0]];
617 player.tmpIds[data.from[1]].focus = false;
618 this.$forceUpdate(); //TODO: shouldn't be required
622 case "askidentity": {
623 // Request for identification
625 // Decompose to avoid revealing email
626 name: this.st.user.name,
627 sid: this.st.user.sid,
630 this.send("identity", { data: me, target: data.from });
634 const user = data.data;
635 let player = this.people[user.sid];
636 // player.tmpIds is already set
637 player.name = user.name;
639 if (this.game.type == "live") {
641 this.game.players.findIndex(p => p.sid == this.st.user.sid);
642 // Sometimes a player name isn't stored yet (TODO: why?)
645 !this.game.players[1 - myGidx].name &&
646 this.game.players[1 - myGidx].sid == user.sid &&
649 this.game.players[1-myGidx].name = user.name;
652 { playerName: { idx: 1 - myGidx, name: user.name } }
656 this.$forceUpdate(); //TODO: shouldn't be required
657 // If I multi-connect, kill current connexion if no mark (I'm older)
658 if (this.newConnect[user.sid]) {
659 delete this.newConnect[user.sid];
662 user.id == this.st.user.id &&
663 user.sid != this.st.user.sid
665 this.cleanBeforeDestroy();
666 alert(this.st.tr["New connexion detected: tab now offline"]);
670 // Ask potentially missed last state, if opponent and I play
673 !!this.game.mycolor &&
674 this.game.type == "live" &&
675 this.game.score == "*" &&
676 this.game.players.some(p => p.sid == user.sid)
678 this.send("asklastate", { target: user.sid });
680 this.askLastate = setInterval(
682 // Ask at most 3 times:
683 // if no reply after that there should be a network issue.
687 !!this.people[user.sid]
689 this.send("asklastate", { target: user.sid });
692 clearInterval(this.askLastate);
701 // Send current (live or import) game,
702 // if not asked by any of the players
704 this.game.type != "corr" &&
705 this.game.players.every(p => p.sid != data.from[0])
709 // FEN is current position, unused for now
711 players: this.game.players,
713 cadence: this.game.cadence,
714 score: this.game.score
716 this.send("game", { data: myGame, target: data.from });
720 const gameToSend = Object.keys(this.game)
723 "id","fen","players","vid","cadence","fenStart","vname",
724 "moves","clocks","score","drawOffer","rematchOffer"
728 obj[k] = this.game[k];
733 this.send("fullgame", { data: gameToSend, target: data.from });
736 if (!!data.data.empty) {
737 alert(this.st.tr["The game should be in another tab"]);
741 // Callback "roomInit" to poll clients only after game is loaded
742 this.loadVariantThenGame(data.data, this.roomInit);
745 // Sending informative last state if I played a move or score != "*"
746 // If the game or moves aren't loaded yet, delay the sending:
747 // TODO: socket init after game load, so the game is supposedly ready
748 if (!this.game || !this.game.moves) this.lastateAsked = true;
749 else this.sendLastate(data.from);
752 // Got opponent infos about last move
753 this.gotLastate = true;
754 this.lastate = data.data;
755 if (this.game.rendered)
756 // Game is rendered (Board component)
757 this.processLastate();
758 // Else: will be processed when game is ready
762 const movePlus = data.data;
763 const movesCount = this.game.moves.length;
764 if (movePlus.index > movesCount) {
765 // This can only happen if I'm an observer and missed a move.
766 if (this.gotMoveIdx < movePlus.index)
767 this.gotMoveIdx = movePlus.index;
768 if (!this.gameIsLoading) this.askGameAgain();
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});
779 this.gotMoveIdx = movePlus.index;
780 const receiveMyMove = (movePlus.color == this.game.mycolor);
781 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
782 if (!receiveMyMove && !!this.game.mycolor) {
783 // Notify opponent that I got the move:
786 { data: movePlus.index, target: data.from }
788 // And myself if I'm elsewhere:
794 (this.game.players[moveColIdx].name || "@nonymous") +
800 if (movePlus.cancelDrawOffer) {
801 // Opponent refuses draw
803 // NOTE for corr games: drawOffer reset by player in turn
805 this.game.type == "live" &&
806 !!this.game.mycolor &&
809 GameStorage.update(this.gameRef, { drawOffer: "" });
812 this.$refs["basegame"].play(movePlus.move, "received");
813 this.game.clocks[moveColIdx] = movePlus.clock;
816 { receiveMyMove: receiveMyMove }
823 this.opponentGotMove = true;
824 // Now his clock starts running on my side:
825 const oppIdx = ['w','b'].indexOf(this.vr.turn);
826 // NOTE: next line to avoid multi-resetClocks when several tabs
827 // on same game, resulting in a faster countdown.
828 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
833 const score = (data.data == "b" ? "1-0" : "0-1");
834 const side = (data.data == "w" ? "White" : "Black");
835 this.gameOver(score, side + " surrender");
838 this.gameOver("?", "Stop");
841 this.gameOver("1/2", data.data);
844 // NOTE: observers don't know who offered draw
845 this.drawOffer = "received";
846 if (!!this.game.mycolor && this.game.type == "live") {
849 { drawOffer: V.GetOppCol(this.game.mycolor) }
854 // NOTE: observers don't know who offered rematch
855 this.rematchOffer = data.data ? "received" : "";
856 if (!!this.game.mycolor && this.game.type == "live") {
859 { rematchOffer: V.GetOppCol(this.game.mycolor) }
864 // A game started, redirect if I'm playing in
865 const gameInfo = data.data;
866 const gameType = this.getGameType(gameInfo);
868 gameType == "live" &&
869 gameInfo.players.some(p => p.sid == this.st.user.sid)
871 this.addAndGotoLiveGame(gameInfo);
873 gameType == "corr" &&
874 gameInfo.players.some(p => p.id == this.st.user.id)
876 this.$router.push("/game/" + gameInfo.id);
878 this.rematchId = gameInfo.id;
879 document.getElementById("modalRules").checked = false;
880 document.getElementById("modalScore").checked = false;
881 document.getElementById("modalRematch").checked = true;
886 let chat = data.data;
887 this.$refs["chatcomp"].newChat(chat);
888 if (this.game.type == "live") {
889 chat.added = Date.now();
890 if (!!this.game.mycolor)
891 GameStorage.update(this.gameRef, { chat: chat });
893 if (!document.getElementById("modalChat").checked)
894 document.getElementById("chatBtn").classList.add("somethingnew");
899 updateCorrGame: function(obj, callback) {
909 if (!!callback) callback();
914 sendLastate: function(target) {
915 // Send our "last state" informations to opponent
916 const L = this.game.moves.length;
917 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
920 (L > 0 && this.vr.turn != this.game.mycolor)
921 ? this.game.moves[L - 1]
923 clock: this.game.clocks[myIdx],
924 // Since we played a move (or abort or resign),
925 // only drawOffer=="sent" is possible
926 drawSent: this.drawOffer == "sent",
927 rematchSent: this.rematchOffer == "sent",
928 score: this.game.score != "*" ? this.game.score : undefined,
929 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
932 this.send("lastate", { data: myLastate, target: target });
934 // lastate was received, but maybe game wasn't ready yet:
935 processLastate: function() {
936 const data = this.lastate;
937 this.lastate = undefined; //security...
938 const L = this.game.moves.length;
939 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
940 this.game.clocks[oppIdx] = data.clock;
941 if (data.movesCount > L) {
942 // Just got last move from him
943 this.$refs["basegame"].play(data.lastMove, "received");
944 this.processMove(data.lastMove);
946 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
949 if (data.drawSent) this.drawOffer = "received";
950 if (data.rematchSent) this.rematchOffer = "received";
953 if (this.game.score == "*")
954 this.gameOver(data.score, data.scoreMsg);
957 clickDraw: function() {
958 if (!this.game.mycolor || this.game.type == "import") return;
959 if (["received", "threerep"].includes(this.drawOffer)) {
960 if (!confirm(this.st.tr["Accept draw?"])) return;
962 this.drawOffer == "received"
964 : "Three repetitions";
965 this.send("draw", { data: message });
966 this.gameOver("1/2", message);
967 } else if (this.drawOffer == "") {
968 // No effect if drawOffer == "sent"
969 if (this.game.mycolor != this.vr.turn) {
970 alert(this.st.tr["Draw offer only in your turn"]);
973 if (!confirm(this.st.tr["Offer draw?"])) return;
974 this.drawOffer = "sent";
975 this.send("drawoffer");
976 if (this.game.type == "live") {
979 { drawOffer: this.game.mycolor }
981 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
984 addAndGotoLiveGame: function(gameInfo, callback) {
985 const game = Object.assign(
989 // (other) Game infos: constant
990 fenStart: gameInfo.fen,
991 vname: this.game.vname,
993 // Game state (including FEN): will be updated
995 clocks: [-1, -1], //-1 = unstarted
999 GameStorage.add(game, (err) => {
1000 // No error expected.
1002 if (this.st.settings.sound)
1003 new Audio("/sounds/newgame.flac").play().catch(() => {});
1004 if (!!callback) callback();
1005 this.$router.push("/game/" + gameInfo.id);
1009 clickRematch: function() {
1010 if (!this.game.mycolor || this.game.type == "import") return;
1011 if (this.rematchOffer == "received") {
1012 // Start a new game!
1014 id: getRandString(), //ignored if corr
1015 fen: V.GenRandInitFen(this.game.randomness),
1016 players: this.game.players.reverse(),
1018 cadence: this.game.cadence
1020 const notifyNewGame = () => {
1021 const oppsid = this.getOppsid(); //may be null
1022 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1023 // To main Hall if corr game:
1024 if (this.game.type == "corr")
1025 this.send("newgame", { data: gameInfo, page: "/" });
1026 // Also to MyGames page:
1027 this.notifyMyGames("newgame", gameInfo);
1029 if (this.game.type == "live")
1030 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1037 // cid is useful to delete the challenge:
1038 data: { gameInfo: gameInfo },
1039 success: (response) => {
1040 gameInfo.id = response.gameId;
1042 this.$router.push("/game/" + response.gameId);
1047 } else if (this.rematchOffer == "") {
1048 this.rematchOffer = "sent";
1049 this.send("rematchoffer", { data: true });
1050 if (this.game.type == "live") {
1053 { rematchOffer: this.game.mycolor }
1055 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1056 } else if (this.rematchOffer == "sent") {
1057 // Toggle rematch offer (on --> off)
1058 this.rematchOffer = "";
1059 this.send("rematchoffer", { data: false });
1060 if (this.game.type == "live") {
1063 { rematchOffer: '' }
1065 } else this.updateCorrGame({ rematchOffer: 'n' });
1068 abortGame: function() {
1069 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1071 this.gameOver("?", "Stop");
1074 resign: function() {
1075 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1077 this.send("resign", { data: this.game.mycolor });
1078 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1079 const side = (this.game.mycolor == "w" ? "White" : "Black");
1080 this.gameOver(score, side + " surrender");
1082 loadGame: function(game, callback) {
1083 const gtype = game.type || this.getGameType(game);
1084 const tc = extractTime(game.cadence);
1085 const myIdx = game.players.findIndex(p => {
1086 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1088 // Sometimes the name isn't stored yet (TODO: why?)
1092 !game.players[myIdx].name &&
1095 game.players[myIdx].name = this.st.user.name;
1098 { playerName: { idx: myIdx, name: this.st.user.name } }
1101 // "mycolor" is undefined for observers
1102 const mycolor = [undefined, "w", "b"][myIdx + 1];
1103 if (gtype == "corr") {
1104 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1105 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1106 // NOTE: clocks in seconds
1107 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1108 game.clocks = [tc.mainTime, tc.mainTime];
1109 const L = game.moves.length;
1110 if (game.score == "*") {
1113 game.clocks[L % 2] -=
1114 (Date.now() - game.moves[L-1].played) / 1000;
1117 // Now that we used idx and played, re-format moves as for live games
1118 game.moves = game.moves.map(m => m.squares);
1120 else if (gtype == "live") {
1121 if (game.clocks[0] < 0) {
1122 // Game is unstarted. clock is ignored until move 2
1123 game.clocks = [tc.mainTime, tc.mainTime];
1125 // I play in this live game
1128 { clocks: game.clocks }
1133 // It's my turn: clocks not updated yet
1134 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1138 // gtype == "import"
1139 game.clocks = [tc.mainTime, tc.mainTime];
1140 // Live games before 26/03/2020 don't have chat history:
1141 if (!game.chats) game.chats = []; //TODO: remove line
1142 // Sort chat messages from newest to oldest
1143 game.chats.sort((c1, c2) => c2.added - c1.added);
1146 game.chats.length > 0 &&
1147 (!game.chatRead || game.chatRead < game.chats[0].added)
1149 // A chat message arrived since my last reading:
1150 document.getElementById("chatBtn").classList.add("somethingnew");
1152 // TODO: merge next 2 "if" conditions
1153 if (!!game.drawOffer) {
1154 if (game.drawOffer == "t")
1155 // Three repetitions
1156 this.drawOffer = "threerep";
1158 // Draw offered by any of the players:
1159 if (myIdx < 0) this.drawOffer = "received";
1161 // I play in this game:
1163 (game.drawOffer == "w" && myIdx == 0) ||
1164 (game.drawOffer == "b" && myIdx == 1)
1166 this.drawOffer = "sent";
1167 else this.drawOffer = "received";
1171 if (!!game.rematchOffer) {
1172 if (myIdx < 0) this.rematchOffer = "received";
1174 // I play in this game:
1176 (game.rematchOffer == "w" && myIdx == 0) ||
1177 (game.rematchOffer == "b" && myIdx == 1)
1179 this.rematchOffer = "sent";
1180 else this.rematchOffer = "received";
1183 this.repeat = {}; //reset: scan past moves' FEN:
1185 this.vr = new V(game.fenStart);
1187 game.moves.forEach(m => {
1188 playMove(m, this.vr);
1189 const fenIdx = this.vr.getFenForRepeat();
1190 this.repeat[fenIdx] = this.repeat[fenIdx]
1191 ? this.repeat[fenIdx] + 1
1194 // Imported games don't have current FEN
1195 if (!game.fen) game.fen = this.vr.getFen();
1196 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1197 this.game = Object.assign(
1198 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1201 increment: tc.increment,
1203 // opponent sid not strictly required (or available), but easier
1204 // at least oppsid or oppid is available anyway:
1205 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1206 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1210 if ("ontouchstart" in window) {
1211 // TODO: I don't like this timeout, but $nextTick() fails,
1212 // and in mounted() hook that fails too.
1215 // Disable tooltips on smartphones:
1216 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
1217 elt.classList.remove("tooltip");
1223 this.$refs["basegame"].re_setVariables(this.game);
1224 if (!this.gameIsLoading) {
1226 this.gotMoveIdx = game.moves.length - 1;
1227 // If we arrive here after 'nextGame' action, the board might be hidden
1228 let boardDiv = document.querySelector(".game");
1229 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1230 boardDiv.style.visibility = "visible";
1232 this.re_setClocks();
1233 this.$nextTick(() => {
1234 this.game.rendered = true;
1235 // Did lastate arrive before game was rendered?
1236 if (this.lastate) this.processLastate();
1238 if (this.lastateAsked) {
1239 this.lastateAsked = false;
1240 this.sendLastate(game.oppsid);
1242 if (this.gameIsLoading) {
1243 this.gameIsLoading = false;
1244 if (this.gotMoveIdx >= game.moves.length)
1245 // Some moves arrived meanwhile...
1246 this.askGameAgain();
1248 if (!!callback) callback();
1250 loadVariantThenGame: async function(game, callback) {
1251 await import("@/variants/" + game.vname + ".js")
1252 .then((vModule) => {
1253 window.V = vModule[game.vname + "Rules"];
1254 this.loadGame(game, callback);
1256 // (AJAX) Request to get rules content (plain text, HTML)
1259 "raw-loader!@/translations/rules/" +
1261 this.st.lang + ".pug"
1263 // Next two lines fix a weird issue after last update (2019-11)
1264 .replace(/\\n/g, " ")
1265 .replace(/\\"/g, '"')
1266 .replace('module.exports = "', "")
1268 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1270 // 3 cases for loading a game:
1271 // - from indexedDB (running or completed live game I play)
1272 // - from server (one correspondance game I play[ed] or not)
1273 // - from remote peer (one live game I don't play, finished or not)
1274 fetchGame: function(callback) {
1275 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1276 // corr games identifiers are integers
1281 data: { gid: this.gameRef },
1283 res.game.moves.forEach(m => {
1284 m.squares = JSON.parse(m.squares);
1291 else if (!!this.gameRef.match(/^i/))
1292 // Game import (maybe remote)
1293 ImportgameStorage.get(this.gameRef, callback);
1295 // Local live game (or remote)
1296 GameStorage.get(this.gameRef, callback);
1298 re_setClocks: function() {
1299 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1300 if (this.game.moves.length < 2 || this.game.score != "*") {
1301 // 1st move not completed yet, or game over: freeze time
1304 const currentTurn = this.vr.turn;
1305 const currentMovesCount = this.game.moves.length;
1306 const colorIdx = ["w", "b"].indexOf(currentTurn);
1307 this.clockUpdate = setInterval(
1310 this.game.clocks[colorIdx] < 0 ||
1311 this.game.moves.length > currentMovesCount ||
1312 this.game.score != "*"
1314 clearInterval(this.clockUpdate);
1315 this.clockUpdate = null;
1316 if (this.game.clocks[colorIdx] < 0)
1318 currentTurn == "w" ? "0-1" : "1-0",
1325 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1332 // Update variables and storage after a move:
1333 processMove: function(move, data) {
1334 if (this.game.type == "import")
1335 // Shouldn't receive any messages in this mode:
1337 if (!data) data = {};
1338 const moveCol = this.vr.turn;
1339 const colorIdx = ["w", "b"].indexOf(moveCol);
1340 const nextIdx = 1 - colorIdx;
1341 const doProcessMove = () => {
1342 const origMovescount = this.game.moves.length;
1343 // The move is (about to be) played: stop clock
1344 clearInterval(this.clockUpdate);
1345 this.clockUpdate = null;
1346 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1347 if (this.drawOffer == "received")
1349 this.drawOffer = "";
1350 if (this.game.type == "live" && origMovescount >= 2) {
1351 this.game.clocks[colorIdx] += this.game.increment;
1352 // For a correct display in casqe of disconnected opponent:
1356 ppt(this.game.clocks[colorIdx]).split(':')
1358 GameStorage.update(this.gameRef, {
1359 // It's not my turn anymore:
1364 // Update current game object:
1365 playMove(move, this.vr);
1367 // Received move, score is computed in BaseGame, but maybe not yet.
1368 // ==> Compute it here, although this is redundant (TODO)
1369 data.score = this.vr.getCurrentScore();
1370 if (data.score != "*") this.gameOver(data.score);
1371 this.game.moves.push(move);
1372 this.game.fen = this.vr.getFen();
1373 if (this.game.type == "corr") {
1374 // In corr games, just reset clock to mainTime:
1375 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1377 // If repetition detected, consider that a draw offer was received:
1378 const fenObj = this.vr.getFenForRepeat();
1379 this.repeat[fenObj] =
1380 !!this.repeat[fenObj]
1381 ? this.repeat[fenObj] + 1
1383 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1384 else if (this.drawOffer == "threerep") this.drawOffer = "";
1385 if (!!this.game.mycolor && !data.receiveMyMove) {
1386 // NOTE: 'var' to see that variable outside this block
1387 var filtered_move = getFilteredMove(move);
1389 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1390 // Notify turn on MyGames page:
1399 // Since corr games are stored at only one location, update should be
1400 // done only by one player for each move:
1402 this.game.type == "live" &&
1403 !!this.game.mycolor &&
1404 moveCol != this.game.mycolor &&
1405 this.game.moves.length >= 2
1407 // Receive a move: update initime
1408 this.game.initime = Date.now();
1409 GameStorage.update(this.gameRef, {
1410 // It's my turn now!
1411 initime: this.game.initime
1415 !!this.game.mycolor &&
1416 !data.receiveMyMove &&
1417 (this.game.type == "live" || moveCol == this.game.mycolor)
1420 switch (this.drawOffer) {
1425 drawCode = this.game.mycolor;
1428 drawCode = V.GetOppCol(this.game.mycolor);
1431 if (this.game.type == "corr") {
1432 // corr: only move, fen and score
1433 this.updateCorrGame({
1436 squares: filtered_move,
1439 // Code "n" for "None" to force reset (otherwise it's ignored)
1440 drawOffer: drawCode || "n"
1444 const updateStorage = () => {
1445 GameStorage.update(this.gameRef, {
1447 move: filtered_move,
1448 moveIdx: origMovescount,
1449 clocks: this.game.clocks,
1453 // The active tab can update storage immediately
1454 if (this.focus) updateStorage();
1455 // Small random delay otherwise
1456 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1459 // Send move ("newmove" event) to people in the room (if our turn)
1460 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1462 move: filtered_move,
1463 index: origMovescount,
1464 // color is required to check if this is my move
1465 // (if several tabs opened)
1467 cancelDrawOffer: this.drawOffer == ""
1469 if (this.game.type == "live")
1470 sendMove["clock"] = this.game.clocks[colorIdx];
1471 // (Live) Clocks will re-start when the opponent pingback arrive
1472 this.opponentGotMove = false;
1473 this.send("newmove", {data: sendMove});
1474 // If the opponent doesn't reply gotmove soon enough, re-send move:
1475 // Do this at most 2 times, because mpore would mean network issues,
1476 // opponent would then be expected to disconnect/reconnect.
1478 const currentUrl = document.location.href;
1479 this.retrySendmove = setInterval(
1483 this.opponentGotMove ||
1484 document.location.href != currentUrl //page change
1486 clearInterval(this.retrySendmove);
1489 const oppsid = this.getOppsid();
1491 // Opponent is disconnected: he'll ask last state
1492 clearInterval(this.retrySendmove);
1494 this.send("newmove", { data: sendMove, target: oppsid });
1502 // Not my move or I'm an observer: just start other player's clock
1503 this.re_setClocks();
1506 this.game.type == "corr" &&
1507 moveCol == this.game.mycolor &&
1510 let boardDiv = document.querySelector(".game");
1511 const afterSetScore = () => {
1513 if (this.st.settings.gotonext && this.nextIds.length > 0)
1514 this.showNextGame();
1516 // The board might have been hidden:
1517 if (boardDiv.style.visibility == "hidden")
1518 boardDiv.style.visibility = "visible";
1519 if (data.score == "*") this.re_setClocks();
1522 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1523 // We may play several moves in a row: in case of, remove listener:
1524 let elClone = el.cloneNode(true);
1525 el.parentNode.replaceChild(elClone, el);
1526 elClone.addEventListener(
1529 document.getElementById("modalConfirm").checked = false;
1530 if (!!data.score && data.score != "*")
1532 this.gameOver(data.score, null, afterSetScore);
1533 else afterSetScore();
1536 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1537 const arMove = (Array.isArray(move) ? move : [move]);
1538 for (let i = 0; i < arMove.length; i++)
1539 V.PlayOnBoard(this.vr.board, arMove[i]);
1540 const position = this.vr.getBaseFen();
1541 for (let i = arMove.length - 1; i >= 0; i--)
1542 V.UndoOnBoard(this.vr.board, arMove[i]);
1543 if (["all","byrow"].includes(V.ShowMoves)) {
1544 this.curDiag = getDiagram({
1546 orientation: V.CanFlip ? this.game.mycolor : "w"
1548 document.querySelector("#confirmDiv > .card").style.width =
1549 boardDiv.offsetWidth + "px";
1551 // Incomplete information: just ask confirmation
1552 // Hide the board, because otherwise it could reveal infos
1553 boardDiv.style.visibility = "hidden";
1554 this.moveNotation = getFullNotation(move);
1556 document.getElementById("modalConfirm").checked = true;
1560 if (!!data.score && data.score != "*")
1561 this.gameOver(data.score, null, doProcessMove);
1562 else doProcessMove();
1565 cancelMove: function() {
1566 let boardDiv = document.querySelector(".game");
1567 if (boardDiv.style.visibility == "hidden")
1568 boardDiv.style.visibility = "visible";
1569 document.getElementById("modalConfirm").checked = false;
1570 this.$refs["basegame"].cancelLastMove();
1572 // In corr games, callback to change page only after score is set:
1573 gameOver: function(score, scoreMsg, callback) {
1574 this.game.score = score;
1575 if ("ontouchstart" in window) {
1576 this.$nextTick(() => {
1577 // Disable tooltips on smartphones
1578 // (might be required for rematch button at least):
1579 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
1580 elt.classList.remove("tooltip");
1584 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1585 this.game.scoreMsg = scoreMsg;
1586 document.getElementById("modalRules").checked = false;
1587 // Display result in a un-missable way:
1588 document.getElementById("modalScore").checked = true;
1589 this.$set(this.game, "scoreMsg", scoreMsg);
1590 const myIdx = this.game.players.findIndex(p => {
1591 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1594 // OK, I play in this game
1599 if (this.game.type == "live") {
1600 GameStorage.update(this.gameRef, scoreObj);
1601 // Notify myself locally if I'm elsewhere:
1605 { body: score + " : " + scoreMsg }
1608 if (!!callback) callback();
1610 else this.updateCorrGame(scoreObj, callback);
1611 // Notify the score to main Hall.
1612 // TODO: only one player (currently double send)
1613 this.send("result", { gid: this.game.id, score: score });
1614 // Also to MyGames page (TODO: doubled as well...)
1623 else if (!!callback) callback();
1629 <style lang="sass" scoped>
1630 #scoreDiv > .card, #rematchDiv > .card
1638 @media screen and (max-width: 1500px)
1640 @media screen and (max-width: 1024px)
1642 @media screen and (max-width: 767px)
1652 background-color: lightgreen
1664 @media screen and (max-width: 767px)
1669 display: inline-block
1673 display: inline-block
1675 display: inline-flex
1679 @media screen and (max-width: 767px)
1693 background-color: #edda99
1695 display: inline-block
1699 display: inline-block
1710 display: inline-block
1723 animation: blink-animation 2s steps(3, start) infinite
1724 @keyframes blink-animation
1729 display: inline-block
1741 .draw-sent, .draw-sent:hover
1742 background-color: lightyellow
1744 .draw-received, .draw-received:hover
1745 background-color: lightgreen
1747 .draw-threerep, .draw-threerep:hover
1748 background-color: #e4d1fc
1750 .rematch-sent, .rematch-sent:hover
1751 background-color: lightyellow
1753 .rematch-received, .rematch-received:hover
1754 background-color: lightgreen
1757 background-color: #c5fefe
1770 background-color: lightgreen
1772 background-color: red
1774 h4#variantNameInGame
1777 text-decoration: underline
1782 @import "@/styles/_rules.sass"
1783 @import "@/styles/_board_squares_img.sass"