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)"
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"] }}
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()")
123 span.name(:class="{connected: isConnected(0)}")
124 | {{ game.players[0].name || "@nonymous" }}
126 v-if="game.score=='*'"
127 :class="{yourturn: !!vr && vr.turn == 'w'}"
129 span.time-left {{ virtualClocks[0][0] }}
130 span.time-separator(v-if="!!virtualClocks[0][1]") :
131 span.time-right(v-if="!!virtualClocks[0][1]")
132 | {{ virtualClocks[0][1] }}
134 span.name(:class="{connected: isConnected(1)}")
135 | {{ game.players[1].name || "@nonymous" }}
137 v-if="game.score=='*'"
138 :class="{yourturn: !!vr && vr.turn == 'b'}"
140 span.time-left {{ virtualClocks[1][0] }}
141 span.time-separator(v-if="!!virtualClocks[1][1]") :
142 span.time-right(v-if="!!virtualClocks[1][1]")
143 | {{ virtualClocks[1][1] }}
145 span.name(:class="{connected: isConnected(0)}")
146 | {{ game.players[0].name || "@nonymous" }}
148 span.name(:class="{connected: isConnected(1)}")
149 | {{ game.players[1].name || "@nonymous" }}
150 div(v-if="game.score=='*'")
151 span.time(: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] }}
157 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
158 span.time-left {{ virtualClocks[1][0] }}
159 span.time-separator(v-if="!!virtualClocks[1][1]") :
160 span.time-right(v-if="!!virtualClocks[1][1]")
161 | {{ virtualClocks[1][1] }}
165 @newmove="processMove"
170 import BaseGame from "@/components/BaseGame.vue";
171 import Chat from "@/components/Chat.vue";
172 import { store } from "@/store";
173 import { GameStorage } from "@/utils/gameStorage";
174 import { ImportgameStorage } from "@/utils/importgameStorage";
175 import { ppt } from "@/utils/datetime";
176 import { notify } from "@/utils/notifications";
177 import { ajax } from "@/utils/ajax";
178 import { extractTime } from "@/utils/timeControl";
179 import { getRandString } from "@/utils/alea";
180 import { getScoreMessage } from "@/utils/scoring";
181 import { getFullNotation } from "@/utils/notation";
182 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
183 import { processModalClick } from "@/utils/modalClick";
184 import { playMove, getFilteredMove } from "@/utils/playUndo";
185 import { ArrayFun } from "@/utils/array";
186 import params from "@/parameters";
196 // gameRef can point to a corr game, local game or remote live game
199 game: {}, //passed to BaseGame
200 focus: !document.hidden, //will not always work... TODO
201 // virtualClocks will be initialized from true game.clocks
203 vr: null, //"variant rules" object initialized from FEN
209 people: {}, //players + observers
210 lastate: undefined, //used if opponent send lastate before game is ready
211 repeat: {}, //detect position repetition
212 curDiag: "", //for corr moves confirmation
214 roomInitialized: false,
215 // If newmove has wrong index: ask fullgame again:
217 gameIsLoading: false,
218 // If asklastate got no reply, ask again:
220 gotMoveIdx: -1, //last move index received
221 // If newmove got no pingback, send again:
222 opponentGotMove: false,
224 socketCloseListener: 0,
225 // Incomplete info games: show move played
227 // Intervals from setInterval():
231 // Related to (killing of) self multi-connects:
236 $route: function(to, from) {
237 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
239 this.cleanBeforeDestroy();
240 else if (from.params["id"] != to.params["id"]) {
241 // Change everything:
242 this.cleanBeforeDestroy();
243 let boardDiv = document.querySelector(".game");
245 // In case of incomplete information variant:
246 boardDiv.style.visibility = "hidden";
250 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
253 // NOTE: some redundant code with Hall.vue (mostly related to people array)
254 created: function() {
257 mounted: function() {
258 document.getElementById("chatWrap")
259 .addEventListener("click", (e) => {
260 processModalClick(e, () => {
261 this.toggleChat("close")
264 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
266 document.getElementById(eltName)
267 .addEventListener("click", processModalClick);
271 beforeDestroy: function() {
272 this.cleanBeforeDestroy();
275 cleanBeforeDestroy: function() {
276 clearInterval(this.socketCloseListener);
277 document.removeEventListener('visibilitychange', this.visibilityChange);
278 window.removeEventListener('focus', this.onFocus);
279 window.removeEventListener('blur', this.onBlur);
280 if (!!this.askLastate) clearInterval(this.askLastate);
281 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
282 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
283 this.conn.removeEventListener("message", this.socketMessageListener);
284 this.send("disconnect");
287 visibilityChange: function() {
288 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
289 this.focus = (document.visibilityState == "visible");
290 this.send(this.focus ? "getfocus" : "losefocus");
292 onFocus: function() {
294 this.send("getfocus");
298 this.send("losefocus");
300 isLargeScreen: function() {
301 return window.innerWidth >= 768;
303 btnTooltipClass: function(thing) {
305 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
308 { tooltip: !("ontouchstart" in window) },
313 participateInChat: function(p) {
314 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
316 someAnonymousPresent: function() {
318 Object.values(this.people).some(p =>
319 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
323 atCreation: function() {
324 document.addEventListener('visibilitychange', this.visibilityChange);
325 window.addEventListener('focus', this.onFocus);
326 window.addEventListener('blur', this.onBlur);
327 // 0] (Re)Set variables
328 this.gameRef = this.$route.params["id"];
329 // next = next corr games IDs to navigate faster (if applicable)
330 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
331 // Always add myself to players' list
332 const my = this.st.user;
333 const tmpId = getRandString();
341 tmpId: { focus: true }
346 players: [{ name: "" }, { name: "" }],
350 let chatComp = this.$refs["chatcomp"];
351 if (!!chatComp) chatComp.chats = [];
352 this.virtualClocks = [[0,0], [0,0]];
354 this.rulesContent = "";
356 this.lastateAsked = false;
357 this.rematchOffer = "";
358 this.lastate = undefined;
359 this.roomInitialized = false;
360 this.askGameTime = 0;
361 this.gameIsLoading = false;
362 this.gotLastate = false;
363 this.gotMoveIdx = -1;
364 this.opponentGotMove = false;
365 this.askLastate = null;
366 this.retrySendmove = null;
367 this.clockUpdate = null;
368 this.newConnect = {};
369 // 1] Initialize connection
370 this.connexionString =
372 "/?sid=" + this.st.user.sid +
373 "&id=" + this.st.user.id +
376 // Discard potential "/?next=[...]" for page indication:
377 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
378 this.conn = new WebSocket(this.connexionString);
379 this.conn.addEventListener("message", this.socketMessageListener);
380 this.socketCloseListener = setInterval(
382 if (this.conn.readyState == 3) {
383 this.conn.removeEventListener(
384 "message", this.socketMessageListener);
385 this.conn = new WebSocket(this.connexionString);
386 this.conn.addEventListener("message", this.socketMessageListener);
391 // Socket init required before loading remote game:
392 const socketInit = callback => {
393 if (this.conn.readyState == 1)
397 // Socket not ready yet (initial loading)
398 // NOTE: first arg is Websocket object, unused here:
399 this.conn.onopen = () => callback();
401 this.fetchGame((game) => {
403 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
405 // Live game stored remotely: need socket to retrieve it
406 // NOTE: the callback "roomInit" will be lost, so it's not provided.
407 // --> It will be given when receiving "fullgame" socket event.
408 socketInit(() => { this.send("askfullgame"); });
411 roomInit: function() {
412 if (!this.roomInitialized) {
413 // Notify the room only now that I connected, because
414 // messages might be lost otherwise (if game loading is slow)
415 this.send("connect");
416 this.send("pollclients");
417 // We may ask fullgame several times if some moves are lost,
418 // but room should be init only once:
419 this.roomInitialized = true;
422 send: function(code, obj) {
423 if (!!this.conn && this.conn.readyState == 1)
424 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
426 isConnected: function(index) {
427 const player = this.game.players[index];
428 // Is it me ? In this case no need to bother with focus
430 this.st.user.sid == player.sid ||
431 (!!player.name && this.st.user.id == player.id)
433 // Still have to check for name (because of potential multi-accounts
434 // on same browser, although this should be rare...)
435 return (!this.st.user.name || this.st.user.name == player.name);
437 // Try to find a match in people:
441 Object.keys(this.people).some(sid => {
444 Object.values(this.people[sid].tmpIds).some(v => v.focus)
451 Object.values(this.people).some(p => {
454 Object.values(p.tmpIds).some(v => v.focus)
460 getOppsid: function() {
461 let oppsid = this.game.oppsid;
463 oppsid = Object.keys(this.people).find(
464 sid => this.people[sid].id == this.game.oppid
467 // oppsid is useful only if opponent is online:
468 if (!!oppsid && !!this.people[oppsid]) return oppsid;
471 // NOTE: action if provided is always a closing action
472 toggleChat: function(action) {
473 if (!action && document.getElementById("modalChat").checked)
475 document.getElementById("inputChat").focus();
477 document.getElementById("chatBtn").classList.remove("somethingnew");
478 if (!!this.game.mycolor) {
479 // Update "chatRead" variable either on server or locally
480 if (this.game.type == "corr")
481 this.updateCorrGame({ chatRead: this.game.mycolor });
482 else if (this.game.type == "live")
483 GameStorage.update(this.gameRef, { chatRead: true });
487 processChat: function(chat) {
488 this.send("newchat", { data: chat });
489 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
490 if (!!this.game.mycolor) {
491 if (this.game.type == "corr")
492 this.updateCorrGame({ chat: chat });
495 chat.added = Date.now();
496 GameStorage.update(this.gameRef, { chat: chat });
500 clearChat: function() {
501 if (!!this.game.mycolor) {
502 if (this.game.type == "corr") {
506 { data: { gid: this.game.id } }
510 GameStorage.update(this.gameRef, { delchat: true });
512 this.$set(this.game, "chats", []);
515 getGameType: function(game) {
516 if (!!game.id.toString().match(/^i/)) return "import";
517 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
519 // Notify something after a new move (to opponent and me on MyGames page)
520 notifyMyGames: function(thing, data) {
525 targets: this.game.players.map(p => {
526 return { sid: p.sid, id: p.id };
531 showNextGame: function() {
532 // Did I play in current game? If not, add it to nextIds list
533 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
534 this.nextIds.unshift(this.game.id);
535 const nextGid = this.nextIds.pop();
537 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
539 askGameAgain: function() {
540 this.gameIsLoading = true;
541 const currentUrl = document.location.href;
542 const doAskGame = () => {
543 if (document.location.href != currentUrl) return; //page change
544 this.fetchGame((game) => {
546 // This is my game: just reload.
549 // Just ask fullgame again (once!), this is much simpler.
550 // If this fails, the user could just reload page :/
551 this.send("askfullgame");
554 // Delay of at least 2s between two game requests
555 const now = Date.now();
556 const delay = Math.max(2000 - (now - this.askGameTime), 0);
557 this.askGameTime = now;
558 setTimeout(doAskGame, delay);
560 socketMessageListener: function(msg) {
561 if (!this.conn) return;
562 const data = JSON.parse(msg.data);
565 // TODO: shuffling and random filtering on server,
566 // if the room is really crowded.
567 Object.keys(data.sockIds).forEach(sid => {
568 if (sid != this.st.user.sid) {
569 this.send("askidentity", { target: sid });
570 this.people[sid] = { tmpIds: data.sockIds[sid] };
573 // Complete my tmpIds:
574 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
579 if (!this.people[data.from[0]]) {
580 // focus depends on the tmpId (e.g. tab)
586 [data.from[1]]: { focus: true }
590 // For self multi-connects tests:
591 this.newConnect[data.from[0]] = true;
592 this.send("askidentity", { target: data.from[0] });
594 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
595 this.$forceUpdate(); //TODO: shouldn't be required
599 if (!this.people[data.from[0]]) return;
600 delete this.people[data.from[0]].tmpIds[data.from[1]];
601 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
602 this.$delete(this.people, data.from[0]);
603 else this.$forceUpdate(); //TODO: shouldn't be required
606 let player = this.people[data.from[0]];
608 player.tmpIds[data.from[1]].focus = true;
609 this.$forceUpdate(); //TODO: shouldn't be required
614 let player = this.people[data.from[0]];
616 player.tmpIds[data.from[1]].focus = false;
617 this.$forceUpdate(); //TODO: shouldn't be required
621 case "askidentity": {
622 // Request for identification
624 // Decompose to avoid revealing email
625 name: this.st.user.name,
626 sid: this.st.user.sid,
629 this.send("identity", { data: me, target: data.from });
633 const user = data.data;
634 let player = this.people[user.sid];
635 // player.tmpIds is already set
636 player.name = user.name;
638 if (this.game.type == "live") {
640 this.game.players.findIndex(p => p.sid == this.st.user.sid);
641 // Sometimes a player name isn't stored yet (TODO: why?)
644 !this.game.players[1 - myGidx].name &&
645 this.game.players[1 - myGidx].sid == user.sid &&
648 this.game.players[1-myGidx].name = user.name;
651 { playerName: { idx: 1 - myGidx, name: user.name } }
655 this.$forceUpdate(); //TODO: shouldn't be required
656 // If I multi-connect, kill current connexion if no mark (I'm older)
657 if (this.newConnect[user.sid]) {
658 delete this.newConnect[user.sid];
661 user.id == this.st.user.id &&
662 user.sid != this.st.user.sid
664 this.cleanBeforeDestroy();
665 alert(this.st.tr["New connexion detected: tab now offline"]);
669 // Ask potentially missed last state, if opponent and I play
672 !!this.game.mycolor &&
673 this.game.type == "live" &&
674 this.game.players.some(p => p.sid == user.sid)
676 this.send("asklastate", { target: user.sid });
678 this.askLastate = setInterval(
680 // Ask at most 3 times:
681 // if no reply after that there should be a network issue.
685 !!this.people[user.sid]
687 this.send("asklastate", { target: user.sid });
690 clearInterval(this.askLastate);
699 // Send current (live or import) game,
700 // if not asked by any of the players
702 this.game.type != "corr" &&
703 this.game.players.every(p => p.sid != data.from[0])
707 // FEN is current position, unused for now
709 players: this.game.players,
711 cadence: this.game.cadence,
712 score: this.game.score
714 this.send("game", { data: myGame, target: data.from });
718 const gameToSend = Object.keys(this.game)
721 "id","fen","players","vid","cadence","fenStart","vname",
722 "moves","clocks","score","drawOffer","rematchOffer"
726 obj[k] = this.game[k];
731 this.send("fullgame", { data: gameToSend, target: data.from });
734 if (!!data.data.empty) {
735 alert(this.st.tr["The game should be in another tab"]);
739 // Callback "roomInit" to poll clients only after game is loaded
740 this.loadVariantThenGame(data.data, this.roomInit);
743 // Sending informative last state if I played a move or score != "*"
744 // If the game or moves aren't loaded yet, delay the sending:
745 // TODO: socket init after game load, so the game is supposedly ready
746 if (!this.game || !this.game.moves) this.lastateAsked = true;
747 else this.sendLastate(data.from);
749 // TODO: possible bad scenario: reload page while oppponent sends a
750 // move => get both lastate and newmove, process both, add move twice.
751 // Confirm scenario? Fix?
753 // Got opponent infos about last move
754 this.gotLastate = true;
755 this.lastate = data.data;
756 if (this.game.rendered)
757 // Game is rendered (Board component)
758 this.processLastate();
759 // Else: will be processed when game is ready
763 const movePlus = data.data;
764 const movesCount = this.game.moves.length;
765 if (movePlus.index > movesCount) {
766 // This can only happen if I'm an observer and missed a move.
767 if (this.gotMoveIdx < movePlus.index)
768 this.gotMoveIdx = movePlus.index;
769 if (!this.gameIsLoading) this.askGameAgain();
773 movePlus.index < movesCount ||
774 this.gotMoveIdx >= movePlus.index
776 // Opponent re-send but we already have the move:
777 // (maybe he didn't receive our pingback...)
778 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 }
839 this.opponentGotMove = true;
840 // Now his clock starts running on my side:
841 const oppIdx = ['w','b'].indexOf(this.vr.turn);
842 // NOTE: next line to avoid multi-resetClocks when several tabs
843 // on same game, resulting in a faster countdown.
844 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
849 const score = (data.data == "b" ? "1-0" : "0-1");
850 const side = (data.data == "w" ? "White" : "Black");
851 this.gameOver(score, side + " surrender");
854 this.gameOver("?", "Stop");
857 this.gameOver("1/2", data.data);
860 // NOTE: observers don't know who offered draw
861 this.drawOffer = "received";
862 if (!!this.game.mycolor && this.game.type == "live") {
865 { drawOffer: V.GetOppCol(this.game.mycolor) }
870 // NOTE: observers don't know who offered rematch
871 this.rematchOffer = data.data ? "received" : "";
872 if (!!this.game.mycolor && this.game.type == "live") {
875 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
880 // A game started, redirect if I'm playing in
881 const gameInfo = data.data;
882 const gameType = this.getGameType(gameInfo);
884 gameType == "live" &&
885 gameInfo.players.some(p => p.sid == this.st.user.sid)
887 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);
895 this.rematchId = gameInfo.id;
896 document.getElementById("modalRules").checked = false;
897 document.getElementById("modalScore").checked = false;
898 document.getElementById("modalRematch").checked = true;
903 let chat = data.data;
904 this.$refs["chatcomp"].newChat(chat);
905 if (this.game.type == "live") {
906 chat.added = Date.now();
907 if (!!this.game.mycolor)
908 GameStorage.update(this.gameRef, { chat: chat });
910 if (!document.getElementById("modalChat").checked)
911 document.getElementById("chatBtn").classList.add("somethingnew");
916 updateCorrGame: function(obj, callback) {
926 if (!!callback) callback();
931 sendLastate: function(target) {
932 // Send our "last state" informations to opponent
933 const L = this.game.moves.length;
934 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
937 (L > 0 && this.vr.turn != this.game.mycolor)
938 ? this.game.moves[L - 1]
940 clock: this.game.clocks[myIdx],
941 // Since we played a move (or abort or resign),
942 // only drawOffer=="sent" is possible
943 drawSent: this.drawOffer == "sent" ? true : undefined,
944 rematchSent: this.rematchOffer == "sent" ? true : undefined,
945 score: this.game.score != "*" ? this.game.score : undefined,
946 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
949 this.send("lastate", { data: myLastate, target: target });
951 // lastate was received, but maybe game wasn't ready yet:
952 processLastate: function() {
953 const data = this.lastate;
954 this.lastate = undefined; //security...
956 const oppCol = V.GetOppCol(this.game.mycolor);
957 if (!!data.rematchSent) {
958 if (this.game.rematchOffer != oppCol) {
959 // Opponent sended rematch offer while we were offline:
960 this.rematchOffer = "received";
963 { rematchOffer: oppCol }
968 if (this.game.rematchOffer == oppCol) {
969 // Opponent cancelled rematch offer while we were offline:
970 this.rematchOffer = "";
979 const L = this.game.moves.length;
980 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
981 this.game.clocks[oppIdx] = data.clock;
982 if (data.movesCount > L) {
983 // Just got last move from him
984 this.$refs["basegame"].play(data.lastMove, "received");
985 this.processMove(data.lastMove);
987 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
990 if (!!data.drawSent) this.drawOffer = "received";
993 if (this.game.score == "*")
994 this.gameOver(data.score, data.scoreMsg);
998 clickDraw: function() {
999 if (!this.game.mycolor || this.game.type == "import") return;
1000 if (["received", "threerep"].includes(this.drawOffer)) {
1001 if (!confirm(this.st.tr["Accept draw?"])) return;
1003 this.drawOffer == "received"
1004 ? "Mutual agreement"
1005 : "Three repetitions";
1006 this.send("draw", { data: message });
1007 this.gameOver("1/2", message);
1008 } else if (this.drawOffer == "") {
1009 // No effect if drawOffer == "sent"
1010 if (this.game.mycolor != this.vr.turn) {
1011 alert(this.st.tr["Draw offer only in your turn"]);
1014 if (!confirm(this.st.tr["Offer draw?"])) return;
1015 this.drawOffer = "sent";
1016 this.send("drawoffer");
1017 if (this.game.type == "live") {
1020 { drawOffer: this.game.mycolor }
1022 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1025 addAndGotoLiveGame: function(gameInfo, callback) {
1026 const game = Object.assign(
1030 // (other) Game infos: constant
1031 fenStart: gameInfo.fen,
1032 vname: this.game.vname,
1033 created: Date.now(),
1034 // Game state (including FEN): will be updated
1036 clocks: [-1, -1], //-1 = unstarted
1040 GameStorage.add(game, (err) => {
1041 // No error expected.
1043 if (this.st.settings.sound)
1044 new Audio("/sounds/newgame.flac").play().catch(() => {});
1045 if (!!callback) callback();
1046 this.$router.push("/game/" + gameInfo.id);
1050 clickRematch: function() {
1051 if (!this.game.mycolor || this.game.type == "import") return;
1052 if (this.rematchOffer == "received") {
1053 // Start a new game!
1055 id: getRandString(), //ignored if corr
1056 fen: V.GenRandInitFen(this.game.randomness),
1057 players: this.game.players.reverse(),
1059 cadence: this.game.cadence
1061 const notifyNewGame = () => {
1062 const oppsid = this.getOppsid(); //may be null
1063 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1064 // To main Hall if corr game:
1065 if (this.game.type == "corr")
1066 this.send("newgame", { data: gameInfo, page: "/" });
1067 // Also to MyGames page:
1068 this.notifyMyGames("newgame", gameInfo);
1070 if (this.game.type == "live")
1071 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1078 // cid is useful to delete the challenge:
1079 data: { gameInfo: gameInfo },
1080 success: (response) => {
1081 gameInfo.id = response.gameId;
1083 this.$router.push("/game/" + response.gameId);
1088 } else if (this.rematchOffer == "") {
1089 this.rematchOffer = "sent";
1090 this.send("rematchoffer", { data: true });
1091 if (this.game.type == "live") {
1094 { rematchOffer: this.game.mycolor }
1096 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1097 } else if (this.rematchOffer == "sent") {
1098 // Toggle rematch offer (on --> off)
1099 this.rematchOffer = "";
1100 this.send("rematchoffer", { data: false });
1101 if (this.game.type == "live") {
1104 { rematchOffer: '' }
1106 } else this.updateCorrGame({ rematchOffer: 'n' });
1109 abortGame: function() {
1110 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1112 this.gameOver("?", "Stop");
1115 resign: function() {
1116 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1118 this.send("resign", { data: this.game.mycolor });
1119 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1120 const side = (this.game.mycolor == "w" ? "White" : "Black");
1121 this.gameOver(score, side + " surrender");
1123 loadGame: function(game, callback) {
1124 const gtype = game.type || this.getGameType(game);
1125 const tc = extractTime(game.cadence);
1126 const myIdx = game.players.findIndex(p => {
1128 p.sid == this.st.user.sid ||
1129 (!!p.name && p.id == this.st.user.id)
1132 // Sometimes the name isn't stored yet (TODO: why?)
1136 !game.players[myIdx].name &&
1139 game.players[myIdx].name = this.st.user.name;
1142 { playerName: { idx: myIdx, name: this.st.user.name } }
1145 // "mycolor" is undefined for observers
1146 const mycolor = [undefined, "w", "b"][myIdx + 1];
1147 if (gtype == "corr") {
1148 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1149 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1150 // NOTE: clocks in seconds
1151 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1152 game.clocks = [tc.mainTime, tc.mainTime];
1153 const L = game.moves.length;
1154 if (game.score == "*") {
1157 game.clocks[L % 2] -=
1158 (Date.now() - game.moves[L-1].played) / 1000;
1161 // Now that we used idx and played, re-format moves as for live games
1162 game.moves = game.moves.map(m => m.squares);
1164 else if (gtype == "live") {
1165 if (game.clocks[0] < 0) {
1166 // Game is unstarted. clock is ignored until move 2
1167 game.clocks = [tc.mainTime, tc.mainTime];
1169 // I play in this live game
1172 { clocks: game.clocks }
1177 // It's my turn: clocks not updated yet
1178 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1182 // gtype == "import"
1183 game.clocks = [tc.mainTime, tc.mainTime];
1184 // Live games before 26/03/2020 don't have chat history:
1185 if (!game.chats) game.chats = []; //TODO: remove line
1186 // Sort chat messages from newest to oldest
1187 game.chats.sort((c1, c2) => c2.added - c1.added);
1190 game.chats.length > 0 &&
1191 (!game.chatRead || game.chatRead < game.chats[0].added)
1193 // A chat message arrived since my last reading:
1194 document.getElementById("chatBtn").classList.add("somethingnew");
1196 // TODO: merge next 2 "if" conditions
1197 if (!!game.drawOffer) {
1198 if (game.drawOffer == "t")
1199 // Three repetitions
1200 this.drawOffer = "threerep";
1202 // Draw offered by any of the players:
1203 if (myIdx < 0) this.drawOffer = "received";
1205 // I play in this game:
1207 (game.drawOffer == "w" && myIdx == 0) ||
1208 (game.drawOffer == "b" && myIdx == 1)
1210 this.drawOffer = "sent";
1211 else this.drawOffer = "received";
1215 if (!!game.rematchOffer) {
1216 if (myIdx < 0) this.rematchOffer = "received";
1218 // I play in this game:
1220 (game.rematchOffer == "w" && myIdx == 0) ||
1221 (game.rematchOffer == "b" && myIdx == 1)
1223 this.rematchOffer = "sent";
1225 else this.rematchOffer = "received";
1228 this.repeat = {}; //reset: scan past moves' FEN:
1230 this.vr = new V(game.fenStart);
1232 game.moves.forEach(m => {
1233 playMove(m, this.vr);
1234 const fenIdx = this.vr.getFenForRepeat();
1235 this.repeat[fenIdx] = this.repeat[fenIdx]
1236 ? this.repeat[fenIdx] + 1
1239 // Imported games don't have current FEN
1240 if (!game.fen) game.fen = this.vr.getFen();
1241 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1242 this.game = Object.assign(
1243 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1246 increment: tc.increment,
1248 // opponent sid not strictly required (or available), but easier
1249 // at least oppsid or oppid is available anyway:
1250 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1251 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1255 this.$refs["basegame"].re_setVariables(this.game);
1256 if (!this.gameIsLoading) {
1258 this.gotMoveIdx = game.moves.length - 1;
1259 // If we arrive here after 'nextGame' action, the board might be hidden
1260 let boardDiv = document.querySelector(".game");
1261 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1262 boardDiv.style.visibility = "visible";
1264 this.re_setClocks();
1265 this.$nextTick(() => {
1266 this.game.rendered = true;
1267 // Did lastate arrive before game was rendered?
1268 if (this.lastate) this.processLastate();
1270 if (this.lastateAsked) {
1271 this.lastateAsked = false;
1272 this.sendLastate(game.oppsid);
1274 if (this.gameIsLoading) {
1275 this.gameIsLoading = false;
1276 if (this.gotMoveIdx >= game.moves.length)
1277 // Some moves arrived meanwhile...
1278 this.askGameAgain();
1280 if (!!callback) callback();
1282 loadVariantThenGame: async function(game, callback) {
1283 await import("@/variants/" + game.vname + ".js")
1284 .then((vModule) => {
1285 window.V = vModule[game.vname + "Rules"];
1286 this.loadGame(game, callback);
1288 // (AJAX) Request to get rules content (plain text, HTML)
1291 "raw-loader!@/translations/rules/" +
1293 this.st.lang + ".pug"
1295 // Next two lines fix a weird issue after last update (2019-11)
1296 .replace(/\\n/g, " ")
1297 .replace(/\\"/g, '"')
1298 .replace('module.exports = "', "")
1300 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1302 // 3 cases for loading a game:
1303 // - from indexedDB (running or completed live game I play)
1304 // - from server (one correspondance game I play[ed] or not)
1305 // - from remote peer (one live game I don't play, finished or not)
1306 fetchGame: function(callback) {
1307 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1308 // corr games identifiers are integers
1313 data: { gid: this.gameRef },
1315 res.game.moves.forEach(m => {
1316 m.squares = JSON.parse(m.squares);
1323 else if (!!this.gameRef.match(/^i/))
1324 // Game import (maybe remote)
1325 ImportgameStorage.get(this.gameRef, callback);
1327 // Local live game (or remote)
1328 GameStorage.get(this.gameRef, callback);
1330 re_setClocks: function() {
1331 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1332 if (this.game.moves.length < 2 || this.game.score != "*") {
1333 // 1st move not completed yet, or game over: freeze time
1336 const currentTurn = this.vr.turn;
1337 const currentMovesCount = this.game.moves.length;
1338 const colorIdx = ["w", "b"].indexOf(currentTurn);
1339 this.clockUpdate = setInterval(
1342 this.game.clocks[colorIdx] < 0 ||
1343 this.game.moves.length > currentMovesCount ||
1344 this.game.score != "*"
1346 clearInterval(this.clockUpdate);
1347 this.clockUpdate = null;
1348 if (this.game.clocks[colorIdx] < 0)
1350 currentTurn == "w" ? "0-1" : "1-0",
1357 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1364 // Update variables and storage after a move:
1365 processMove: function(move, data) {
1366 if (this.game.type == "import")
1367 // Shouldn't receive any messages in this mode:
1369 if (!data) data = {};
1370 const moveCol = this.vr.turn;
1371 const colorIdx = ["w", "b"].indexOf(moveCol);
1372 const nextIdx = 1 - colorIdx;
1373 const doProcessMove = () => {
1374 const origMovescount = this.game.moves.length;
1375 // The move is (about to be) played: stop clock
1376 clearInterval(this.clockUpdate);
1377 this.clockUpdate = null;
1378 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1379 if (this.drawOffer == "received")
1381 this.drawOffer = "";
1382 if (this.game.type == "live" && origMovescount >= 2) {
1383 this.game.clocks[colorIdx] += this.game.increment;
1384 // For a correct display in casqe of disconnected opponent:
1388 ppt(this.game.clocks[colorIdx]).split(':')
1390 GameStorage.update(this.gameRef, {
1391 // It's not my turn anymore:
1396 // Update current game object:
1397 playMove(move, this.vr);
1399 // Received move, score is computed in BaseGame, but maybe not yet.
1400 // ==> Compute it here, although this is redundant (TODO)
1401 data.score = this.vr.getCurrentScore();
1402 if (data.score != "*") this.gameOver(data.score);
1403 this.game.moves.push(move);
1404 this.game.fen = this.vr.getFen();
1405 if (this.game.type == "corr") {
1406 // In corr games, just reset clock to mainTime:
1407 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1409 // If repetition detected, consider that a draw offer was received:
1410 const fenObj = this.vr.getFenForRepeat();
1411 this.repeat[fenObj] =
1412 !!this.repeat[fenObj]
1413 ? this.repeat[fenObj] + 1
1415 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1416 else if (this.drawOffer == "threerep") this.drawOffer = "";
1417 if (!!this.game.mycolor && !data.receiveMyMove) {
1418 // NOTE: 'var' to see that variable outside this block
1419 var filtered_move = getFilteredMove(move);
1421 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1422 // Notify turn on MyGames page:
1431 // Since corr games are stored at only one location, update should be
1432 // done only by one player for each move:
1434 this.game.type == "live" &&
1435 !!this.game.mycolor &&
1436 moveCol != this.game.mycolor &&
1437 this.game.moves.length >= 2
1439 // Receive a move: update initime
1440 this.game.initime = Date.now();
1441 GameStorage.update(this.gameRef, {
1442 // It's my turn now!
1443 initime: this.game.initime
1447 !!this.game.mycolor &&
1448 !data.receiveMyMove &&
1449 (this.game.type == "live" || moveCol == this.game.mycolor)
1452 switch (this.drawOffer) {
1457 drawCode = this.game.mycolor;
1460 drawCode = V.GetOppCol(this.game.mycolor);
1463 if (this.game.type == "corr") {
1464 // corr: only move, fen and score
1465 this.updateCorrGame({
1468 squares: filtered_move,
1471 // Code "n" for "None" to force reset (otherwise it's ignored)
1472 drawOffer: drawCode || "n"
1476 const updateStorage = () => {
1477 GameStorage.update(this.gameRef, {
1479 move: filtered_move,
1480 moveIdx: origMovescount,
1481 clocks: this.game.clocks,
1485 // The active tab can update storage immediately
1486 if (this.focus) updateStorage();
1487 // Small random delay otherwise
1488 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1491 // Send move ("newmove" event) to people in the room (if our turn)
1492 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1494 move: filtered_move,
1495 index: origMovescount,
1496 // color is required to check if this is my move
1497 // (if several tabs opened)
1499 cancelDrawOffer: this.drawOffer == ""
1501 if (this.game.type == "live")
1502 sendMove["clock"] = this.game.clocks[colorIdx];
1503 // (Live) Clocks will re-start when the opponent pingback arrive
1504 this.opponentGotMove = false;
1505 this.send("newmove", {data: sendMove});
1506 // If the opponent doesn't reply gotmove soon enough, re-send move:
1507 // Do this at most 2 times, because mpore would mean network issues,
1508 // opponent would then be expected to disconnect/reconnect.
1510 const currentUrl = document.location.href;
1511 this.retrySendmove = setInterval(
1515 this.opponentGotMove ||
1516 document.location.href != currentUrl //page change
1518 clearInterval(this.retrySendmove);
1521 const oppsid = this.getOppsid();
1523 // Opponent is disconnected: he'll ask last state
1524 clearInterval(this.retrySendmove);
1526 this.send("newmove", { data: sendMove, target: oppsid });
1534 // Not my move or I'm an observer: just start other player's clock
1535 this.re_setClocks();
1538 this.game.type == "corr" &&
1539 moveCol == this.game.mycolor &&
1542 let boardDiv = document.querySelector(".game");
1543 const afterSetScore = () => {
1545 if (this.st.settings.gotonext && this.nextIds.length > 0)
1546 this.showNextGame();
1548 // The board might have been hidden:
1549 if (boardDiv.style.visibility == "hidden")
1550 boardDiv.style.visibility = "visible";
1551 if (data.score == "*") this.re_setClocks();
1554 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1555 // We may play several moves in a row: in case of, remove listener:
1556 let elClone = el.cloneNode(true);
1557 el.parentNode.replaceChild(elClone, el);
1558 elClone.addEventListener(
1561 document.getElementById("modalConfirm").checked = false;
1562 if (!!data.score && data.score != "*")
1564 this.gameOver(data.score, null, afterSetScore);
1565 else afterSetScore();
1568 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1569 const arMove = (Array.isArray(move) ? move : [move]);
1570 for (let i = 0; i < arMove.length; i++)
1571 V.PlayOnBoard(this.vr.board, arMove[i]);
1572 const position = this.vr.getBaseFen();
1573 for (let i = arMove.length - 1; i >= 0; i--)
1574 V.UndoOnBoard(this.vr.board, arMove[i]);
1575 if (["all","byrow"].includes(V.ShowMoves)) {
1576 this.curDiag = getDiagram({
1578 orientation: V.CanFlip ? this.game.mycolor : "w"
1580 document.querySelector("#confirmDiv > .card").style.width =
1581 boardDiv.offsetWidth + "px";
1583 // Incomplete information: just ask confirmation
1584 // Hide the board, because otherwise it could reveal infos
1585 boardDiv.style.visibility = "hidden";
1586 this.moveNotation = getFullNotation(move);
1588 document.getElementById("modalConfirm").checked = true;
1592 if (!!data.score && data.score != "*")
1593 this.gameOver(data.score, null, doProcessMove);
1594 else doProcessMove();
1597 cancelMove: function() {
1598 let boardDiv = document.querySelector(".game");
1599 if (boardDiv.style.visibility == "hidden")
1600 boardDiv.style.visibility = "visible";
1601 document.getElementById("modalConfirm").checked = false;
1602 this.$refs["basegame"].cancelLastMove();
1604 // In corr games, callback to change page only after score is set:
1605 gameOver: function(score, scoreMsg, callback) {
1606 this.game.score = score;
1607 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1608 this.game.scoreMsg = scoreMsg;
1609 document.getElementById("modalRules").checked = false;
1610 // Display result in a un-missable way:
1611 document.getElementById("modalScore").checked = true;
1612 this.$set(this.game, "scoreMsg", scoreMsg);
1613 const myIdx = this.game.players.findIndex(p => {
1615 p.sid == this.st.user.sid ||
1616 (!!p.name && p.id == this.st.user.id)
1620 // OK, I play in this game
1625 if (this.game.type == "live") {
1626 GameStorage.update(this.gameRef, scoreObj);
1627 // Notify myself locally if I'm elsewhere:
1631 { body: score + " : " + scoreMsg }
1634 if (!!callback) callback();
1636 else this.updateCorrGame(scoreObj, callback);
1637 // Notify the score to main Hall.
1638 // TODO: only one player (currently double send)
1639 this.send("result", { gid: this.game.id, score: score });
1640 // Also to MyGames page (TODO: doubled as well...)
1649 else if (!!callback) callback();
1655 <style lang="sass" scoped>
1656 #scoreDiv > .card, #rematchDiv > .card
1664 @media screen and (max-width: 1500px)
1666 @media screen and (max-width: 1024px)
1668 @media screen and (max-width: 767px)
1678 background-color: lightgreen
1690 @media screen and (max-width: 767px)
1695 display: inline-block
1699 display: inline-block
1701 display: inline-flex
1705 @media screen and (max-width: 767px)
1719 background-color: #edda99
1721 display: inline-block
1725 display: inline-block
1732 @media screen and (max-width: 767px)
1738 @media screen and (max-width: 767px)
1740 display: inline-block
1753 animation: blink-animation 2s steps(3, start) infinite
1754 @keyframes blink-animation
1759 display: inline-block
1771 .draw-sent, .draw-sent:hover
1772 background-color: lightyellow
1774 .draw-received, .draw-received:hover
1775 background-color: #73C6B6
1777 .draw-threerep, .draw-threerep:hover
1778 background-color: #D2B4DE
1780 .rematch-sent, .rematch-sent:hover
1781 background-color: lightyellow
1783 .rematch-received, .rematch-received:hover
1784 background-color: #48C9B0
1787 background-color: #D2B4DE
1800 background-color: lightgreen
1802 background-color: red
1805 color: var(--card-fore-color)
1808 font-size: calc(1rem * var(--heading-ratio))
1810 margin: calc(1.5 * var(--universal-margin))
1814 @import "@/styles/_rules.sass"
1815 @import "@/styles/_board_squares_img.sass"