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.lastate.movesCount - 1 > this.gotMoveIdx)
757 this.gotMoveIdx = this.lastate.movesCount - 1;
758 if (this.game.rendered)
759 // Game is rendered (Board component)
760 this.processLastate();
761 // Else: will be processed when game is ready
767 console.log("Receive move");
768 console.log(data.data);
769 //moveslist not updated when receiving a move? (see in baseGame)
771 const movePlus = data.data;
772 const movesCount = this.game.moves.length;
773 if (movePlus.index > movesCount) {
774 // This can only happen if I'm an observer and missed a move.
775 if (this.gotMoveIdx < movePlus.index)
776 this.gotMoveIdx = movePlus.index;
777 if (!this.gameIsLoading) this.askGameAgain();
781 movePlus.index < movesCount ||
782 this.gotMoveIdx >= movePlus.index
784 // Opponent re-send but we already have the move:
785 // (maybe he didn't receive our pingback...)
786 this.send("gotmove", {data: movePlus.index, target: data.from});
788 this.gotMoveIdx = movePlus.index;
789 const receiveMyMove = (movePlus.color == this.game.mycolor);
790 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
791 if (!receiveMyMove && !!this.game.mycolor) {
792 // Notify opponent that I got the move:
795 { data: movePlus.index, target: data.from }
797 // And myself if I'm elsewhere:
803 (this.game.players[moveColIdx].name || "@nonymous") +
809 if (movePlus.cancelDrawOffer) {
810 // Opponent refuses draw
812 // NOTE for corr games: drawOffer reset by player in turn
814 this.game.type == "live" &&
815 !!this.game.mycolor &&
818 GameStorage.update(this.gameRef, { drawOffer: "" });
821 this.$refs["basegame"].play(movePlus.move, "received");
822 // Freeze time while the move is being play
823 // (TODO: a callback would be cleaner here)
824 clearInterval(this.clockUpdate);
825 this.clockUpdate = null;
826 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
827 // 250 = length of animation, 500 = delay between sub-moves
829 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
830 // Incomplete information: no move animation
834 this.game.clocks[moveColIdx] = movePlus.clock;
837 { receiveMyMove: receiveMyMove }
847 this.opponentGotMove = true;
848 // Now his clock starts running on my side:
849 const oppIdx = ['w','b'].indexOf(this.vr.turn);
850 // NOTE: next line to avoid multi-resetClocks when several tabs
851 // on same game, resulting in a faster countdown.
852 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
857 const score = (data.data == "b" ? "1-0" : "0-1");
858 const side = (data.data == "w" ? "White" : "Black");
859 this.gameOver(score, side + " surrender");
862 this.gameOver("?", "Stop");
865 this.gameOver("1/2", data.data);
868 // NOTE: observers don't know who offered draw
869 this.drawOffer = "received";
870 if (!!this.game.mycolor && this.game.type == "live") {
873 { drawOffer: V.GetOppCol(this.game.mycolor) }
878 // NOTE: observers don't know who offered rematch
879 this.rematchOffer = data.data ? "received" : "";
880 if (!!this.game.mycolor && this.game.type == "live") {
883 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
888 // A game started, redirect if I'm playing in
889 const gameInfo = data.data;
890 const gameType = this.getGameType(gameInfo);
892 gameType == "live" &&
893 gameInfo.players.some(p => p.sid == this.st.user.sid)
895 this.addAndGotoLiveGame(gameInfo);
897 gameType == "corr" &&
898 this.st.user.id > 0 &&
899 gameInfo.players.some(p => p.id == this.st.user.id)
901 this.$router.push("/game/" + gameInfo.id);
903 this.rematchId = gameInfo.id;
904 document.getElementById("modalRules").checked = false;
905 document.getElementById("modalScore").checked = false;
906 document.getElementById("modalRematch").checked = true;
911 let chat = data.data;
912 this.$refs["chatcomp"].newChat(chat);
913 if (this.game.type == "live") {
914 chat.added = Date.now();
915 if (!!this.game.mycolor)
916 GameStorage.update(this.gameRef, { chat: chat });
918 if (!document.getElementById("modalChat").checked)
919 document.getElementById("chatBtn").classList.add("somethingnew");
924 updateCorrGame: function(obj, callback) {
934 if (!!callback) callback();
939 sendLastate: function(target) {
940 // Send our "last state" informations to opponent
941 const L = this.game.moves.length;
942 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
945 (L > 0 && this.vr.turn != this.game.mycolor)
946 ? this.game.moves[L - 1]
948 clock: this.game.clocks[myIdx],
949 // Since we played a move (or abort or resign),
950 // only drawOffer=="sent" is possible
951 drawSent: this.drawOffer == "sent" ? true : undefined,
952 rematchSent: this.rematchOffer == "sent" ? true : undefined,
953 score: this.game.score != "*" ? this.game.score : undefined,
954 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
957 this.send("lastate", { data: myLastate, target: target });
959 // lastate was received, but maybe game wasn't ready yet:
960 processLastate: function() {
961 const data = this.lastate;
962 this.lastate = undefined; //security...
964 const oppCol = V.GetOppCol(this.game.mycolor);
965 if (!!data.rematchSent) {
966 if (this.game.rematchOffer != oppCol) {
967 // Opponent sended rematch offer while we were offline:
968 this.rematchOffer = "received";
971 { rematchOffer: oppCol }
976 if (this.game.rematchOffer == oppCol) {
977 // Opponent cancelled rematch offer while we were offline:
978 this.rematchOffer = "";
987 const L = this.game.moves.length;
988 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
989 this.game.clocks[oppIdx] = data.clock;
990 if (data.movesCount > L) {
991 // Just got last move from him
992 this.$refs["basegame"].play(data.lastMove, "received");
993 this.processMove(data.lastMove);
995 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
998 if (!!data.drawSent) this.drawOffer = "received";
1000 this.drawOffer = "";
1001 if (this.game.score == "*")
1002 this.gameOver(data.score, data.scoreMsg);
1006 clickDraw: function() {
1007 if (!this.game.mycolor || this.game.type == "import") return;
1008 if (["received", "threerep"].includes(this.drawOffer)) {
1009 if (!confirm(this.st.tr["Accept draw?"])) return;
1011 this.drawOffer == "received"
1012 ? "Mutual agreement"
1013 : "Three repetitions";
1014 this.send("draw", { data: message });
1015 this.gameOver("1/2", message);
1016 } else if (this.drawOffer == "") {
1017 // No effect if drawOffer == "sent"
1018 if (this.game.mycolor != this.vr.turn) {
1019 alert(this.st.tr["Draw offer only in your turn"]);
1022 if (!confirm(this.st.tr["Offer draw?"])) return;
1023 this.drawOffer = "sent";
1024 this.send("drawoffer");
1025 if (this.game.type == "live") {
1028 { drawOffer: this.game.mycolor }
1030 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1033 addAndGotoLiveGame: function(gameInfo, callback) {
1034 const game = Object.assign(
1038 // (other) Game infos: constant
1039 fenStart: gameInfo.fen,
1040 vname: this.game.vname,
1041 created: Date.now(),
1042 // Game state (including FEN): will be updated
1044 clocks: [-1, -1], //-1 = unstarted
1048 GameStorage.add(game, (err) => {
1049 // No error expected.
1051 if (this.st.settings.sound)
1052 new Audio("/sounds/newgame.flac").play().catch(() => {});
1053 if (!!callback) callback();
1054 this.$router.push("/game/" + gameInfo.id);
1058 clickRematch: function() {
1059 if (!this.game.mycolor || this.game.type == "import") return;
1060 if (this.rematchOffer == "received") {
1061 // Start a new game!
1063 id: getRandString(), //ignored if corr
1064 fen: V.GenRandInitFen(this.game.randomness),
1065 players: [this.game.players[1], this.game.players[0]],
1067 cadence: this.game.cadence
1069 const notifyNewGame = () => {
1070 const oppsid = this.getOppsid(); //may be null
1071 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1072 // To main Hall if corr game:
1073 if (this.game.type == "corr")
1074 this.send("newgame", { data: gameInfo, page: "/" });
1075 // Also to MyGames page:
1076 this.notifyMyGames("newgame", gameInfo);
1078 if (this.game.type == "live")
1079 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1086 // cid is useful to delete the challenge:
1087 data: { gameInfo: gameInfo },
1088 success: (response) => {
1089 gameInfo.id = response.gameId;
1091 this.$router.push("/game/" + response.gameId);
1096 } else if (this.rematchOffer == "") {
1097 this.rematchOffer = "sent";
1098 this.send("rematchoffer", { data: true });
1099 if (this.game.type == "live") {
1102 { rematchOffer: this.game.mycolor }
1104 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1105 } else if (this.rematchOffer == "sent") {
1106 // Toggle rematch offer (on --> off)
1107 this.rematchOffer = "";
1108 this.send("rematchoffer", { data: false });
1109 if (this.game.type == "live") {
1112 { rematchOffer: '' }
1114 } else this.updateCorrGame({ rematchOffer: 'n' });
1117 abortGame: function() {
1118 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1120 this.gameOver("?", "Stop");
1123 resign: function() {
1124 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1126 this.send("resign", { data: this.game.mycolor });
1127 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1128 const side = (this.game.mycolor == "w" ? "White" : "Black");
1129 this.gameOver(score, side + " surrender");
1131 loadGame: function(game, callback) {
1132 const gtype = game.type || this.getGameType(game);
1133 const tc = extractTime(game.cadence);
1134 const myIdx = game.players.findIndex(p => {
1136 p.sid == this.st.user.sid ||
1137 (!!p.name && p.id == this.st.user.id)
1140 // Sometimes the name isn't stored yet (TODO: why?)
1144 !game.players[myIdx].name &&
1147 game.players[myIdx].name = this.st.user.name;
1150 { playerName: { idx: myIdx, name: this.st.user.name } }
1153 // "mycolor" is undefined for observers
1154 const mycolor = [undefined, "w", "b"][myIdx + 1];
1155 if (gtype == "corr") {
1156 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1157 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1158 // NOTE: clocks in seconds
1159 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1160 game.clocks = [tc.mainTime, tc.mainTime];
1161 const L = game.moves.length;
1162 if (game.score == "*") {
1165 game.clocks[L % 2] -=
1166 (Date.now() - game.moves[L-1].played) / 1000;
1169 // Now that we used idx and played, re-format moves as for live games
1170 game.moves = game.moves.map(m => m.squares);
1172 else if (gtype == "live") {
1173 if (game.clocks[0] < 0) {
1174 // Game is unstarted. clock is ignored until move 2
1175 game.clocks = [tc.mainTime, tc.mainTime];
1177 // I play in this live game
1180 { clocks: game.clocks }
1185 // It's my turn: clocks not updated yet
1186 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1190 // gtype == "import"
1191 game.clocks = [tc.mainTime, tc.mainTime];
1192 // Live games before 26/03/2020 don't have chat history:
1193 if (!game.chats) game.chats = []; //TODO: remove line
1194 // Sort chat messages from newest to oldest
1195 game.chats.sort((c1, c2) => c2.added - c1.added);
1198 game.chats.length > 0 &&
1199 (!game.chatRead || game.chatRead < game.chats[0].added)
1201 // A chat message arrived since my last reading:
1202 document.getElementById("chatBtn").classList.add("somethingnew");
1204 // TODO: merge next 2 "if" conditions
1205 if (!!game.drawOffer) {
1206 if (game.drawOffer == "t")
1207 // Three repetitions
1208 this.drawOffer = "threerep";
1210 // Draw offered by any of the players:
1211 if (myIdx < 0) this.drawOffer = "received";
1213 // I play in this game:
1215 (game.drawOffer == "w" && myIdx == 0) ||
1216 (game.drawOffer == "b" && myIdx == 1)
1218 this.drawOffer = "sent";
1219 else this.drawOffer = "received";
1223 if (!!game.rematchOffer) {
1224 if (myIdx < 0) this.rematchOffer = "received";
1226 // I play in this game:
1228 (game.rematchOffer == "w" && myIdx == 0) ||
1229 (game.rematchOffer == "b" && myIdx == 1)
1231 this.rematchOffer = "sent";
1233 else this.rematchOffer = "received";
1236 this.repeat = {}; //reset: scan past moves' FEN:
1238 this.vr = new V(game.fenStart);
1240 game.moves.forEach(m => {
1241 playMove(m, this.vr);
1242 const fenIdx = this.vr.getFenForRepeat();
1243 this.repeat[fenIdx] = this.repeat[fenIdx]
1244 ? this.repeat[fenIdx] + 1
1247 // Imported games don't have current FEN
1248 if (!game.fen) game.fen = this.vr.getFen();
1249 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1250 this.game = Object.assign(
1251 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1254 increment: tc.increment,
1256 // opponent sid not strictly required (or available), but easier
1257 // at least oppsid or oppid is available anyway:
1258 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1259 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1263 this.$refs["basegame"].re_setVariables(this.game);
1264 if (!this.gameIsLoading) {
1266 this.gotMoveIdx = game.moves.length - 1;
1267 // If we arrive here after 'nextGame' action, the board might be hidden
1268 let boardDiv = document.querySelector(".game");
1269 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1270 boardDiv.style.visibility = "visible";
1272 this.re_setClocks();
1273 this.$nextTick(() => {
1274 this.game.rendered = true;
1275 // Did lastate arrive before game was rendered?
1276 if (!!this.lastate) this.processLastate();
1278 if (this.lastateAsked) {
1279 this.lastateAsked = false;
1280 this.sendLastate(game.oppsid);
1282 if (this.gameIsLoading) {
1283 this.gameIsLoading = false;
1284 if (this.gotMoveIdx >= game.moves.length)
1285 // Some moves arrived meanwhile...
1286 this.askGameAgain();
1288 if (!!callback) callback();
1290 loadVariantThenGame: async function(game, callback) {
1291 await import("@/variants/" + game.vname + ".js")
1292 .then((vModule) => {
1293 window.V = vModule[game.vname + "Rules"];
1294 this.loadGame(game, callback);
1296 // (AJAX) Request to get rules content (plain text, HTML)
1299 "raw-loader!@/translations/rules/" +
1301 this.st.lang + ".pug"
1303 // Next two lines fix a weird issue after last update (2019-11)
1304 .replace(/\\n/g, " ")
1305 .replace(/\\"/g, '"')
1306 .replace('module.exports = "', "")
1308 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1310 // 3 cases for loading a game:
1311 // - from indexedDB (running or completed live game I play)
1312 // - from server (one correspondance game I play[ed] or not)
1313 // - from remote peer (one live game I don't play, finished or not)
1314 fetchGame: function(callback) {
1315 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1316 // corr games identifiers are integers
1321 data: { gid: this.gameRef },
1323 res.game.moves.forEach(m => {
1324 m.squares = JSON.parse(m.squares);
1331 else if (!!this.gameRef.match(/^i/))
1332 // Game import (maybe remote)
1333 ImportgameStorage.get(this.gameRef, callback);
1335 // Local live game (or remote)
1336 GameStorage.get(this.gameRef, callback);
1338 re_setClocks: function() {
1339 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1340 if (this.game.moves.length < 2 || this.game.score != "*") {
1341 // 1st move not completed yet, or game over: freeze time
1344 const currentTurn = this.vr.turn;
1345 const currentMovesCount = this.game.moves.length;
1346 const colorIdx = ["w", "b"].indexOf(currentTurn);
1347 this.clockUpdate = setInterval(
1350 this.game.clocks[colorIdx] < 0 ||
1351 this.game.moves.length > currentMovesCount ||
1352 this.game.score != "*"
1354 clearInterval(this.clockUpdate);
1355 this.clockUpdate = null;
1356 if (this.game.clocks[colorIdx] < 0)
1358 currentTurn == "w" ? "0-1" : "1-0",
1365 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1372 // Update variables and storage after a move:
1373 processMove: function(move, data) {
1374 if (this.game.type == "import")
1375 // Shouldn't receive any messages in this mode:
1377 if (!data) data = {};
1378 const moveCol = this.vr.turn;
1379 const colorIdx = ["w", "b"].indexOf(moveCol);
1380 const nextIdx = 1 - colorIdx;
1381 const doProcessMove = () => {
1382 const origMovescount = this.game.moves.length;
1383 // The move is (about to be) played: stop clock
1384 clearInterval(this.clockUpdate);
1385 this.clockUpdate = null;
1386 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1387 if (this.drawOffer == "received")
1389 this.drawOffer = "";
1390 if (this.game.type == "live" && origMovescount >= 2) {
1391 this.game.clocks[colorIdx] += this.game.increment;
1392 // For a correct display in casqe of disconnected opponent:
1396 ppt(this.game.clocks[colorIdx]).split(':')
1398 GameStorage.update(this.gameRef, {
1399 // It's not my turn anymore:
1404 // Update current game object:
1405 playMove(move, this.vr);
1407 // Received move, score is computed in BaseGame, but maybe not yet.
1408 // ==> Compute it here, although this is redundant (TODO)
1409 data.score = this.vr.getCurrentScore();
1410 if (data.score != "*") this.gameOver(data.score);
1411 this.game.moves.push(move);
1412 this.game.fen = this.vr.getFen();
1413 if (this.game.type == "corr") {
1414 // In corr games, just reset clock to mainTime:
1415 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1417 // If repetition detected, consider that a draw offer was received:
1418 const fenObj = this.vr.getFenForRepeat();
1419 this.repeat[fenObj] =
1420 !!this.repeat[fenObj]
1421 ? this.repeat[fenObj] + 1
1423 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1424 else if (this.drawOffer == "threerep") this.drawOffer = "";
1425 if (!!this.game.mycolor && !data.receiveMyMove) {
1426 // NOTE: 'var' to see that variable outside this block
1427 var filtered_move = getFilteredMove(move);
1429 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1430 // Notify turn on MyGames page:
1439 // Since corr games are stored at only one location, update should be
1440 // done only by one player for each move:
1442 this.game.type == "live" &&
1443 !!this.game.mycolor &&
1444 moveCol != this.game.mycolor &&
1445 this.game.moves.length >= 2
1447 // Receive a move: update initime
1448 this.game.initime = Date.now();
1449 GameStorage.update(this.gameRef, {
1450 // It's my turn now!
1451 initime: this.game.initime
1455 !!this.game.mycolor &&
1456 !data.receiveMyMove &&
1457 (this.game.type == "live" || moveCol == this.game.mycolor)
1460 switch (this.drawOffer) {
1465 drawCode = this.game.mycolor;
1468 drawCode = V.GetOppCol(this.game.mycolor);
1471 if (this.game.type == "corr") {
1472 // corr: only move, fen and score
1473 this.updateCorrGame({
1476 squares: filtered_move,
1479 // Code "n" for "None" to force reset (otherwise it's ignored)
1480 drawOffer: drawCode || "n"
1484 const updateStorage = () => {
1485 GameStorage.update(this.gameRef, {
1487 move: filtered_move,
1488 moveIdx: origMovescount,
1489 clocks: this.game.clocks,
1493 // The active tab can update storage immediately
1494 if (this.focus) updateStorage();
1495 // Small random delay otherwise
1496 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1499 // Send move ("newmove" event) to people in the room (if our turn)
1500 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1502 move: filtered_move,
1503 index: origMovescount,
1504 // color is required to check if this is my move
1505 // (if several tabs opened)
1507 cancelDrawOffer: this.drawOffer == ""
1509 if (this.game.type == "live")
1510 sendMove["clock"] = this.game.clocks[colorIdx];
1511 // (Live) Clocks will re-start when the opponent pingback arrive
1512 this.opponentGotMove = false;
1513 this.send("newmove", {data: sendMove});
1514 // If the opponent doesn't reply gotmove soon enough, re-send move:
1515 // Do this at most 2 times, because mpore would mean network issues,
1516 // opponent would then be expected to disconnect/reconnect.
1518 const currentUrl = document.location.href;
1519 this.retrySendmove = setInterval(
1523 this.opponentGotMove ||
1524 document.location.href != currentUrl //page change
1526 clearInterval(this.retrySendmove);
1529 const oppsid = this.getOppsid();
1531 // Opponent is disconnected: he'll ask last state
1532 clearInterval(this.retrySendmove);
1534 this.send("newmove", { data: sendMove, target: oppsid });
1542 // Not my move or I'm an observer: just start other player's clock
1543 this.re_setClocks();
1546 this.game.type == "corr" &&
1547 moveCol == this.game.mycolor &&
1550 let boardDiv = document.querySelector(".game");
1551 const afterSetScore = () => {
1553 if (this.st.settings.gotonext && this.nextIds.length > 0)
1554 this.showNextGame();
1556 // The board might have been hidden:
1557 if (boardDiv.style.visibility == "hidden")
1558 boardDiv.style.visibility = "visible";
1559 if (data.score == "*") this.re_setClocks();
1562 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1563 // We may play several moves in a row: in case of, remove listener:
1564 let elClone = el.cloneNode(true);
1565 el.parentNode.replaceChild(elClone, el);
1566 elClone.addEventListener(
1569 document.getElementById("modalConfirm").checked = false;
1570 if (!!data.score && data.score != "*")
1572 this.gameOver(data.score, null, afterSetScore);
1573 else afterSetScore();
1576 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1577 const arMove = (Array.isArray(move) ? move : [move]);
1578 for (let i = 0; i < arMove.length; i++)
1579 V.PlayOnBoard(this.vr.board, arMove[i]);
1580 const position = this.vr.getBaseFen();
1581 for (let i = arMove.length - 1; i >= 0; i--)
1582 V.UndoOnBoard(this.vr.board, arMove[i]);
1583 if (["all","byrow"].includes(V.ShowMoves)) {
1584 this.curDiag = getDiagram({
1586 orientation: V.CanFlip ? this.game.mycolor : "w"
1588 document.querySelector("#confirmDiv > .card").style.width =
1589 boardDiv.offsetWidth + "px";
1591 // Incomplete information: just ask confirmation
1592 // Hide the board, because otherwise it could reveal infos
1593 boardDiv.style.visibility = "hidden";
1594 this.moveNotation = getFullNotation(move);
1596 document.getElementById("modalConfirm").checked = true;
1600 if (!!data.score && data.score != "*")
1601 this.gameOver(data.score, null, doProcessMove);
1602 else doProcessMove();
1605 cancelMove: function() {
1606 let boardDiv = document.querySelector(".game");
1607 if (boardDiv.style.visibility == "hidden")
1608 boardDiv.style.visibility = "visible";
1609 document.getElementById("modalConfirm").checked = false;
1610 this.$refs["basegame"].cancelLastMove();
1612 // In corr games, callback to change page only after score is set:
1613 gameOver: function(score, scoreMsg, callback) {
1614 this.game.score = score;
1615 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1616 this.game.scoreMsg = scoreMsg;
1617 document.getElementById("modalRules").checked = false;
1618 // Display result in a un-missable way:
1619 document.getElementById("modalScore").checked = true;
1620 this.$set(this.game, "scoreMsg", scoreMsg);
1621 const myIdx = this.game.players.findIndex(p => {
1623 p.sid == this.st.user.sid ||
1624 (!!p.name && p.id == this.st.user.id)
1628 // OK, I play in this game
1633 if (this.game.type == "live") {
1634 GameStorage.update(this.gameRef, scoreObj);
1635 // Notify myself locally if I'm elsewhere:
1639 { body: score + " : " + scoreMsg }
1642 if (!!callback) callback();
1644 else this.updateCorrGame(scoreObj, callback);
1645 // Notify the score to main Hall.
1646 // TODO: only one player (currently double send)
1647 this.send("result", { gid: this.game.id, score: score });
1648 // Also to MyGames page (TODO: doubled as well...)
1657 else if (!!callback) callback();
1663 <style lang="sass" scoped>
1664 #scoreDiv > .card, #rematchDiv > .card
1672 @media screen and (max-width: 1500px)
1674 @media screen and (max-width: 1024px)
1676 @media screen and (max-width: 767px)
1686 background-color: lightgreen
1698 @media screen and (max-width: 767px)
1703 display: inline-block
1707 display: inline-block
1709 display: inline-flex
1713 @media screen and (max-width: 767px)
1727 background-color: #edda99
1729 display: inline-block
1733 display: inline-block
1740 @media screen and (max-width: 767px)
1746 @media screen and (max-width: 767px)
1748 display: inline-block
1761 animation: blink-animation 2s steps(3, start) infinite
1762 @keyframes blink-animation
1767 display: inline-block
1779 .draw-sent, .draw-sent:hover
1780 background-color: lightyellow
1782 .draw-received, .draw-received:hover
1783 background-color: #73C6B6
1785 .draw-threerep, .draw-threerep:hover
1786 background-color: #D2B4DE
1788 .rematch-sent, .rematch-sent:hover
1789 background-color: lightyellow
1791 .rematch-received, .rematch-received:hover
1792 background-color: #48C9B0
1795 background-color: #D2B4DE
1808 background-color: lightgreen
1810 background-color: red
1813 color: var(--card-fore-color)
1816 font-size: calc(1rem * var(--heading-ratio))
1818 margin: calc(1.5 * var(--universal-margin))
1822 @import "@/styles/_rules.sass"
1823 @import "@/styles/_board_squares_img.sass"