3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vdisp }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
84 | {{ vr.constructor.AbbreviateOptions(game.options) }}
86 v-if="nextIds.length > 0"
87 @click="showNextGame()"
89 | {{ st.tr["Next_g"] }}
91 :class="btnTooltipClass()"
92 onClick="window.doClick('modalChat')"
95 img(src="/images/icons/chat.svg")
96 #actions(v-if="game.score=='*'")
99 :class="btnTooltipClass('draw')"
100 :aria-label="st.tr['Draw']"
102 img(src="/images/icons/draw.svg")
104 v-if="!!game.mycolor"
105 :class="btnTooltipClass()"
107 :aria-label="st.tr['Abort']"
109 img(src="/images/icons/abort.svg")
111 v-if="!!game.mycolor"
112 :class="btnTooltipClass()"
114 :aria-label="st.tr['Resign']"
116 img(src="/images/icons/resign.svg")
119 :class="btnTooltipClass('rematch')"
120 @click="clickRematch()"
121 :aria-label="st.tr['Rematch']"
123 img(src="/images/icons/rematch.svg")
125 div(v-if="isLargeScreen()")
127 :class="{connected: isConnected(0)}"
128 :uid="game.players[0].id"
129 :uname="game.players[0].name"
132 v-if="game.score=='*'"
133 :class="{yourturn: !!vr && vr.turn == 'w'}"
135 span.time-left {{ virtualClocks[0][0] }}
136 span.time-separator(v-if="!!virtualClocks[0][1]") :
137 span.time-right(v-if="!!virtualClocks[0][1]")
138 | {{ virtualClocks[0][1] }}
141 :class="{connected: isConnected(1)}"
142 :uid="game.players[1].id"
143 :uname="game.players[1].name"
146 v-if="game.score=='*'"
147 :class="{yourturn: !!vr && vr.turn == 'b'}"
149 span.time-left {{ virtualClocks[1][0] }}
150 span.time-separator(v-if="!!virtualClocks[1][1]") :
151 span.time-right(v-if="!!virtualClocks[1][1]")
152 | {{ virtualClocks[1][1] }}
155 :class="{connected: isConnected(0)}"
156 :uid="game.players[0].id"
157 :uname="game.players[0].name"
161 :class="{connected: isConnected(1)}"
162 :uid="game.players[1].id"
163 :uname="game.players[1].name"
165 div(v-if="game.score=='*'")
166 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
167 span.time-left {{ virtualClocks[0][0] }}
168 span.time-separator(v-if="!!virtualClocks[0][1]") :
169 span.time-right(v-if="!!virtualClocks[0][1]")
170 | {{ virtualClocks[0][1] }}
172 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
173 span.time-left {{ virtualClocks[1][0] }}
174 span.time-separator(v-if="!!virtualClocks[1][1]") :
175 span.time-right(v-if="!!virtualClocks[1][1]")
176 | {{ virtualClocks[1][1] }}
180 @newmove="processMove"
185 import BaseGame from "@/components/BaseGame.vue";
186 import UserBio from "@/components/UserBio.vue";
187 import Chat from "@/components/Chat.vue";
188 import { store } from "@/store";
189 import { GameStorage } from "@/utils/gameStorage";
190 import { ImportgameStorage } from "@/utils/importgameStorage";
191 import { ppt } from "@/utils/datetime";
192 import { notify } from "@/utils/notifications";
193 import { ajax } from "@/utils/ajax";
194 import { extractTime } from "@/utils/timeControl";
195 import { getRandString } from "@/utils/alea";
196 import { getScoreMessage } from "@/utils/scoring";
197 import { getFullNotation } from "@/utils/notation";
198 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
199 import { processModalClick } from "@/utils/modalClick";
200 import { playMove, getFilteredMove } from "@/utils/playUndo";
201 import { ArrayFun } from "@/utils/array";
202 import afterRawLoad from "@/utils/afterRawLoad";
203 import params from "@/parameters";
214 // gameRef can point to a corr game, local game or remote live game
217 game: {}, //passed to BaseGame
218 focus: !document.hidden, //will not always work... TODO
219 // virtualClocks will be initialized from true game.clocks
220 // TODO: clock update triggers re-rendering. Should be out of Vue
222 vr: null, //"variant rules" object initialized from FEN
228 people: {}, //players + observers
229 lastate: undefined, //used if opponent send lastate before game is ready
230 repeat: {}, //detect position repetition
231 curDiag: "", //for corr moves confirmation
233 roomInitialized: false,
234 // If asklastate got no reply, ask again:
236 gotMoveIdx: -1, //last move index received
237 // If newmove got no pingback, send again:
238 opponentGotMove: false,
240 socketCloseListener: 0,
241 // Incomplete info games: show move played
243 // Intervals from setInterval():
247 // Related to (killing of) self multi-connects:
252 $route: function(to, from) {
253 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
255 this.cleanBeforeDestroy();
256 else if (from.params["id"] != to.params["id"]) {
257 // Change everything:
258 this.cleanBeforeDestroy();
259 let boardDiv = document.querySelector(".game");
261 // In case of incomplete information variant:
262 boardDiv.style.visibility = "hidden";
267 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
270 // NOTE: some redundant code with Hall.vue (mostly related to people array)
271 created: function() {
274 mounted: function() {
275 document.getElementById("chatWrap")
276 .addEventListener("click", (e) => {
277 processModalClick(e, () => {
278 this.toggleChat("close")
281 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
283 document.getElementById(eltName)
284 .addEventListener("click", processModalClick);
288 beforeDestroy: function() {
289 this.cleanBeforeDestroy();
292 cleanBeforeDestroy: function() {
293 clearInterval(this.socketCloseListener);
294 document.removeEventListener('visibilitychange', this.visibilityChange);
295 window.removeEventListener('focus', this.onFocus);
296 window.removeEventListener('blur', this.onBlur);
297 if (!!this.askLastate) clearInterval(this.askLastate);
298 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
299 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
300 this.conn.removeEventListener("message", this.socketMessageListener);
301 this.send("disconnect");
304 visibilityChange: function() {
305 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
306 this.focus = (document.visibilityState == "visible");
307 this.send(this.focus ? "getfocus" : "losefocus");
309 onFocus: function() {
311 this.send("getfocus");
315 this.send("losefocus");
317 isLargeScreen: function() {
318 return window.innerWidth >= 768;
320 btnTooltipClass: function(thing) {
322 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
325 { tooltip: !("ontouchstart" in window) },
330 someAnonymousPresent: function() {
332 Object.values(this.people).some(p =>
333 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
337 atCreation: function() {
338 document.addEventListener('visibilitychange', this.visibilityChange);
339 window.addEventListener('focus', this.onFocus);
340 window.addEventListener('blur', this.onBlur);
341 // 0] (Re)Set variables
342 this.gameRef = this.$route.params["id"];
343 // next = next corr games IDs to navigate faster (if applicable)
344 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
345 // Always add myself to players' list
346 const my = this.st.user;
347 const tmpId = getRandString();
355 tmpId: { focus: true }
360 players: [{ name: "" }, { name: "" }],
364 let chatComp = this.$refs["chatcomp"];
365 if (!!chatComp) chatComp.chats = [];
366 this.virtualClocks = [[0,0], [0,0]];
368 this.rulesContent = "";
370 this.lastateAsked = false;
371 this.rematchOffer = "";
372 this.lastate = undefined;
373 this.roomInitialized = false;
374 this.gotLastate = false;
375 this.gotMoveIdx = -1;
376 this.opponentGotMove = false;
377 this.askLastate = null;
378 this.retrySendmove = null;
379 this.clockUpdate = null;
380 this.newConnect = {};
381 // 1] Initialize connection
382 this.connexionString =
384 "/?sid=" + this.st.user.sid +
385 "&id=" + this.st.user.id +
388 // Discard potential "/?next=[...]" for page indication:
389 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
390 this.conn = new WebSocket(this.connexionString);
391 this.conn.addEventListener("message", this.socketMessageListener);
392 this.socketCloseListener = setInterval(
394 if (this.conn.readyState == 3) {
395 this.conn.removeEventListener(
396 "message", this.socketMessageListener);
397 this.conn = new WebSocket(this.connexionString);
398 this.conn.addEventListener("message", this.socketMessageListener);
403 // Socket init required before loading remote game:
404 const socketInit = callback => {
405 if (this.conn.readyState == 1)
409 // Socket not ready yet (initial loading)
410 // NOTE: first arg is Websocket object, unused here:
411 this.conn.onopen = () => callback();
413 this.fetchGame((game) => {
416 // Patch for retro-compatibility (TODO: remove it)
417 game.options = { randomness: game.randomness };
418 delete game["randomness"];
420 else game.options = JSON.parse(game.options);
421 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
424 // Live game stored remotely: need socket to retrieve it
425 // NOTE: the callback "roomInit" will be lost, so it's not provided.
426 // --> It will be given when receiving "fullgame" socket event.
427 socketInit(() => { this.send("askfullgame"); });
430 roomInit: function() {
431 if (!this.roomInitialized) {
432 // Notify the room only now that I connected, because
433 // messages might be lost otherwise (if game loading is slow)
434 this.send("connect");
435 this.send("pollclients");
436 // We may ask fullgame several times if some moves are lost,
437 // but room should be init only once:
438 this.roomInitialized = true;
441 send: function(code, obj) {
442 if (!!this.conn && this.conn.readyState == 1)
443 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
445 isConnected: function(index) {
446 const player = this.game.players[index];
447 // Is it me ? In this case no need to bother with focus
449 this.st.user.sid == player.sid ||
450 (!!player.name && this.st.user.id == player.id)
452 // Still have to check for name (because of potential multi-accounts
453 // on same browser, although this should be rare...)
454 return (!this.st.user.name || this.st.user.name == player.name);
456 // Try to find a match in people:
460 Object.keys(this.people).some(sid => {
463 Object.values(this.people[sid].tmpIds).some(v => v.focus)
470 Object.values(this.people).some(p => {
473 Object.values(p.tmpIds).some(v => v.focus)
479 getOppsid: function() {
480 let oppsid = this.game.oppsid;
482 oppsid = Object.keys(this.people).find(
483 sid => this.people[sid].id == this.game.oppid
486 // oppsid is useful only if opponent is online:
487 if (!!oppsid && !!this.people[oppsid]) return oppsid;
490 // NOTE: action if provided is always a closing action
491 toggleChat: function(action) {
492 if (!action && document.getElementById("modalChat").checked)
494 document.getElementById("inputChat").focus();
496 document.getElementById("chatBtn").classList.remove("somethingnew");
497 if (!!this.game.mycolor) {
498 // Update "chatRead" variable either on server or locally
499 if (this.game.type == "corr")
500 this.updateCorrGame({ chatRead: this.game.mycolor });
501 else if (this.game.type == "live")
502 GameStorage.update(this.gameRef, { chatRead: true });
506 processChat: function(chat) {
507 this.send("newchat", { data: chat });
508 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
509 if (!!this.game.mycolor) {
510 if (this.game.type == "corr")
511 this.updateCorrGame({ chat: chat });
514 chat.added = Date.now();
515 GameStorage.update(this.gameRef, { chat: chat });
519 clearChat: function() {
520 if (!!this.game.mycolor) {
521 if (this.game.type == "corr") {
525 { data: { gid: this.game.id } }
530 GameStorage.update(this.gameRef, { delchat: true });
532 this.$set(this.game, "chats", []);
535 getGameType: function(game) {
536 if (!!game.id.toString().match(/^i/)) return "import";
537 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
539 // Notify something after a new move (to opponent and me on MyGames page)
540 notifyMyGames: function(thing, data) {
545 targets: this.game.players.map(p => {
546 return { sid: p.sid, id: p.id };
551 showNextGame: function() {
552 // Did I play in current game? If not, add it to nextIds list
553 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
554 this.nextIds.unshift(this.game.id);
555 const nextGid = this.nextIds.pop();
557 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
559 socketMessageListener: function(msg) {
560 if (!this.conn) return;
561 const data = JSON.parse(msg.data);
564 // TODO: shuffling and random filtering on server,
565 // if the room is really crowded.
566 Object.keys(data.sockIds).forEach(sid => {
567 if (sid != this.st.user.sid) {
568 this.send("askidentity", { target: sid });
569 this.people[sid] = { tmpIds: data.sockIds[sid] };
572 // Complete my tmpIds:
573 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
578 if (!this.people[data.from[0]]) {
579 // focus depends on the tmpId (e.g. tab)
585 [data.from[1]]: { focus: true }
589 // For self multi-connects tests:
590 this.newConnect[data.from[0]] = true;
591 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 else clearInterval(this.askLastate);
698 // Send current (live or import) game,
699 // if not asked by any of the players
701 this.game.type != "corr" &&
702 this.game.players.every(p => p.sid != data.from[0])
706 // FEN is current position, unused for now
708 players: this.game.players,
710 cadence: this.game.cadence,
711 score: this.game.score
713 this.send("game", { data: myGame, target: data.from });
717 const gameToSend = Object.keys(this.game)
720 "id","fen","players","vid","cadence","fenStart","options",
721 "moves","clocks","score","drawOffer","rematchOffer"
725 obj[k] = this.game[k];
730 this.send("fullgame", { data: gameToSend, target: data.from });
733 if (!!data.data.empty) {
734 alert(this.st.tr["The game should be in another tab"]);
738 // Callback "roomInit" to poll clients only after game is loaded
739 this.loadVariantThenGame(data.data, this.roomInit);
742 // Sending informative last state if I played a move or score != "*"
743 // If the game or moves aren't loaded yet, delay the sending:
744 // TODO: socket init after game load, so the game is supposedly ready
745 if (!this.game || !this.game.moves) this.lastateAsked = true;
746 else this.sendLastate(data.from);
748 // TODO: possible bad scenario: reload page while oppponent sends a
749 // move => get both lastate and newmove, process both, add move twice.
750 // Confirm scenario? Fix?
752 // Got opponent infos about last move
753 this.gotLastate = true;
754 this.lastate = data.data;
755 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
756 this.gotMoveIdx = this.lastate.movesCount - 1;
757 if (this.game.rendered)
758 // Game is rendered (Board component)
759 this.processLastate();
760 // Else: will be processed when game is ready
766 //console.log("Receive move");
767 //console.log(data.data);
768 //moveslist not updated when receiving a move? (see in BaseGame)
770 const movePlus = data.data;
771 const movesCount = this.game.moves.length;
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});
781 this.gotMoveIdx = movePlus.index;
782 const receiveMyMove = (movePlus.color == this.game.mycolor);
783 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
784 if (!receiveMyMove && !!this.game.mycolor) {
785 // Notify opponent that I got the move:
788 { data: movePlus.index, target: data.from }
790 // And myself if I'm elsewhere:
796 (this.game.players[moveColIdx].name || "@nonymous") +
802 if (movePlus.cancelDrawOffer) {
803 // Opponent refuses draw
805 // NOTE for corr games: drawOffer reset by player in turn
807 this.game.type == "live" &&
808 !!this.game.mycolor &&
811 GameStorage.update(this.gameRef, { drawOffer: "" });
814 this.$refs["basegame"].play(movePlus.move, "received");
815 // Freeze time while the move is being play
816 // (TODO: a callback would be cleaner here)
817 clearInterval(this.clockUpdate);
818 this.clockUpdate = null;
819 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
820 // 250 = length of animation, 500 = delay between sub-moves
822 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
823 // Incomplete information: no move animation
827 this.game.clocks[moveColIdx] = movePlus.clock;
830 { 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);
890 gameType == "corr" &&
891 this.st.user.id > 0 &&
892 gameInfo.players.some(p => p.id == this.st.user.id)
894 this.$router.push("/game/" + gameInfo.id);
897 this.rematchId = gameInfo.id;
898 document.getElementById("modalRules").checked = false;
899 document.getElementById("modalScore").checked = false;
900 document.getElementById("modalRematch").checked = true;
905 let chat = data.data;
906 this.$refs["chatcomp"].newChat(chat);
907 if (this.game.type == "live") {
908 chat.added = Date.now();
909 if (!!this.game.mycolor)
910 GameStorage.update(this.gameRef, { chat: chat });
912 if (!document.getElementById("modalChat").checked)
913 document.getElementById("chatBtn").classList.add("somethingnew");
918 updateCorrGame: function(obj, callback) {
928 if (!!callback) callback();
933 sendLastate: function(target) {
934 // Send our "last state" informations to opponent
935 const L = this.game.moves.length;
936 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
939 (L > 0 && this.vr.turn != this.game.mycolor)
940 ? this.game.moves[L - 1]
942 clock: this.game.clocks[myIdx],
943 // Since we played a move (or abort or resign),
944 // only drawOffer=="sent" is possible
945 drawSent: this.drawOffer == "sent" ? true : undefined,
946 rematchSent: this.rematchOffer == "sent" ? true : undefined,
947 score: this.game.score != "*" ? this.game.score : undefined,
948 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
951 this.send("lastate", { data: myLastate, target: target });
953 // lastate was received, but maybe game wasn't ready yet:
954 processLastate: function() {
955 const data = this.lastate;
956 this.lastate = undefined; //security...
958 const oppCol = V.GetOppCol(this.game.mycolor);
959 if (!!data.rematchSent) {
960 if (this.game.rematchOffer != oppCol) {
961 // Opponent sended rematch offer while we were offline:
962 this.rematchOffer = "received";
965 { rematchOffer: oppCol }
970 if (this.game.rematchOffer == oppCol) {
971 // Opponent cancelled rematch offer while we were offline:
972 this.rematchOffer = "";
981 const L = this.game.moves.length;
982 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
983 this.game.clocks[oppIdx] = data.clock;
984 if (data.movesCount > L) {
985 // Just got last move from him
986 this.$refs["basegame"].play(data.lastMove, "received");
987 this.processMove(data.lastMove);
990 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
993 if (!!data.drawSent) this.drawOffer = "received";
996 if (this.game.score == "*")
997 this.gameOver(data.score, data.scoreMsg);
1001 clickDraw: function() {
1002 if (!this.game.mycolor || this.game.type == "import") return;
1003 if (["received", "threerep"].includes(this.drawOffer)) {
1004 if (!confirm(this.st.tr["Accept draw?"])) return;
1006 this.drawOffer == "received"
1007 ? "Mutual agreement"
1008 : "Three repetitions";
1009 this.send("draw", { data: message });
1010 this.gameOver("1/2", message);
1012 else if (this.drawOffer == "") {
1013 // No effect if drawOffer == "sent"
1014 if (this.game.mycolor != this.vr.turn) {
1015 alert(this.st.tr["Draw offer only in your turn"]);
1018 if (!confirm(this.st.tr["Offer draw?"])) return;
1019 this.drawOffer = "sent";
1020 this.send("drawoffer");
1021 if (this.game.type == "live") {
1024 { drawOffer: this.game.mycolor }
1027 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1030 addAndGotoLiveGame: function(gameInfo, callback) {
1031 const game = Object.assign(
1035 // (other) Game infos: constant
1036 fenStart: gameInfo.fen,
1037 created: Date.now(),
1038 // Game state (including FEN): will be updated
1040 clocks: [-1, -1], //-1 = unstarted
1045 GameStorage.add(game, (err) => {
1046 // No error expected.
1048 if (this.st.settings.sound)
1049 new Audio("/sounds/newgame.flac").play().catch(() => {});
1050 if (!!callback) callback();
1051 this.$router.push("/game/" + gameInfo.id);
1055 clickRematch: function() {
1056 if (!this.game.mycolor || this.game.type == "import") return;
1057 if (this.rematchOffer == "received") {
1058 // Start a new game!
1060 id: getRandString(), //ignored if corr
1061 fen: V.GenRandInitFen(this.game.options),
1062 options: this.game.options,
1063 players: [this.game.players[1], this.game.players[0]],
1065 cadence: this.game.cadence
1067 const notifyNewGame = () => {
1068 this.send("rnewgame", { data: gameInfo });
1069 // To main Hall if corr game:
1070 if (this.game.type == "corr")
1071 this.send("newgame", { data: gameInfo, page: "/" });
1072 // Also to MyGames page:
1073 this.notifyMyGames("newgame", gameInfo);
1075 if (this.game.type == "live") {
1078 { rematchOffer: "" }
1080 // Increment game stats counter in DB
1084 { data: { vid: gameInfo.vid } }
1086 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1090 this.updateCorrGame({ rematchOffer: 'n' });
1095 data: Object.assign(
1098 { options: JSON.stringify(this.game.options) }
1100 success: (response) => {
1101 gameInfo.id = response.id;
1103 this.$router.push("/game/" + response.id);
1109 else if (this.rematchOffer == "") {
1110 this.rematchOffer = "sent";
1111 this.send("rematchoffer", { data: true });
1112 if (this.game.type == "live") {
1115 { rematchOffer: this.game.mycolor }
1118 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1120 else if (this.rematchOffer == "sent") {
1121 // Toggle rematch offer (on --> off)
1122 this.rematchOffer = "";
1123 this.send("rematchoffer", { data: false });
1124 if (this.game.type == "live") {
1127 { rematchOffer: '' }
1130 else this.updateCorrGame({ rematchOffer: 'n' });
1133 abortGame: function() {
1134 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1136 this.gameOver("?", "Stop");
1139 resign: function() {
1140 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1142 this.send("resign", { data: this.game.mycolor });
1143 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1144 const side = (this.game.mycolor == "w" ? "White" : "Black");
1145 this.gameOver(score, side + " surrender");
1147 loadGame: function(game, callback) {
1148 const gtype = game.type || this.getGameType(game);
1149 const tc = extractTime(game.cadence);
1150 const myIdx = game.players.findIndex(p => {
1152 p.sid == this.st.user.sid ||
1153 (!!p.name && p.id == this.st.user.id)
1156 // Sometimes the name isn't stored yet (TODO: why?)
1160 !game.players[myIdx].name &&
1163 game.players[myIdx].name = this.st.user.name;
1166 { playerName: { idx: myIdx, name: this.st.user.name } }
1169 // "mycolor" is undefined for observers
1170 const mycolor = [undefined, "w", "b"][myIdx + 1];
1171 if (gtype == "corr") {
1172 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1173 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1174 // NOTE: clocks in seconds
1175 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1176 game.clocks = [tc.mainTime, tc.mainTime];
1177 const L = game.moves.length;
1178 if (game.score == "*") {
1181 game.clocks[L % 2] -=
1182 (Date.now() - game.moves[L-1].played) / 1000;
1185 // Now that we used idx and played, re-format moves as for live games
1186 game.moves = game.moves.map(m => m.squares);
1188 else if (gtype == "live") {
1189 if (game.clocks[0] < 0) {
1190 // Game is unstarted. clock is ignored until move 2
1191 game.clocks = [tc.mainTime, tc.mainTime];
1193 // I play in this live game
1196 { clocks: game.clocks }
1200 else if (!!game.initime)
1201 // It's my turn: clocks not updated yet
1202 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1205 // gtype == "import"
1206 game.clocks = [tc.mainTime, tc.mainTime];
1207 // Live games before 26/03/2020 don't have chat history:
1208 if (!game.chats) game.chats = []; //TODO: remove line
1209 // Sort chat messages from newest to oldest
1210 game.chats.sort((c1, c2) => c2.added - c1.added);
1213 game.chats.length > 0 &&
1214 (!game.chatRead || game.chatRead < game.chats[0].added)
1216 // A chat message arrived since my last reading:
1217 document.getElementById("chatBtn").classList.add("somethingnew");
1219 // TODO: merge next 2 "if" conditions
1220 if (!!game.drawOffer) {
1221 if (game.drawOffer == "t")
1222 // Three repetitions
1223 this.drawOffer = "threerep";
1225 // Draw offered by any of the players:
1226 if (myIdx < 0) this.drawOffer = "received";
1228 // I play in this game:
1230 (game.drawOffer == "w" && myIdx == 0) ||
1231 (game.drawOffer == "b" && myIdx == 1)
1233 this.drawOffer = "sent";
1234 else this.drawOffer = "received";
1238 if (!!game.rematchOffer) {
1239 if (myIdx < 0) this.rematchOffer = "received";
1241 // I play in this game:
1243 (game.rematchOffer == "w" && myIdx == 0) ||
1244 (game.rematchOffer == "b" && myIdx == 1)
1246 this.rematchOffer = "sent";
1248 else this.rematchOffer = "received";
1251 this.repeat = {}; //reset: scan past moves' FEN:
1253 this.vr = new V(game.fenStart);
1255 game.moves.forEach(m => {
1256 playMove(m, this.vr);
1257 const fenIdx = this.vr.getFenForRepeat();
1258 this.repeat[fenIdx] = this.repeat[fenIdx]
1259 ? this.repeat[fenIdx] + 1
1262 // Imported games don't have current FEN
1263 if (!game.fen) game.fen = this.vr.getFen();
1264 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1265 this.game = Object.assign(
1266 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1269 increment: tc.increment,
1271 // opponent sid not strictly required (or available), but easier
1272 // at least oppsid or oppid is available anyway:
1273 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1274 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1278 this.$refs["basegame"].re_setVariables(this.game);
1280 this.gotMoveIdx = game.moves.length - 1;
1281 // If we arrive here after 'nextGame' action, the board might be hidden
1282 let boardDiv = document.querySelector(".game");
1283 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1284 boardDiv.style.visibility = "visible";
1285 this.re_setClocks();
1286 this.$nextTick(() => {
1287 this.game.rendered = true;
1288 // Did lastate arrive before game was rendered?
1289 if (!!this.lastate) this.processLastate();
1291 if (this.lastateAsked) {
1292 this.lastateAsked = false;
1293 this.sendLastate(game.oppsid);
1295 if (!!callback) callback();
1297 loadVariantThenGame: async function(game, callback) {
1298 const afterSetVname = async () => {
1299 await import("@/variants/" + game.vname + ".js")
1300 .then((vModule) => {
1301 window.V = vModule[game.vname + "Rules"];
1302 this.loadGame(game, callback);
1307 "raw-loader!@/translations/rules/" +
1308 game.vname + "/" + this.st.lang + ".pug"
1310 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1312 let variant = undefined;
1313 const trySetVname = setInterval(
1315 // this.st.variants might be uninitialized (variant == null)
1316 variant = this.st.variants.find(v => v.id == game.vid);
1318 clearInterval(trySetVname);
1319 game.vname = variant.name;
1320 game.vdisp = variant.display;
1326 // 3 cases for loading a game:
1327 // - from indexedDB (running or completed live game I play)
1328 // - from server (one correspondance game I play[ed] or not)
1329 // - from remote peer (one live game I don't play, finished or not)
1330 fetchGame: function(callback) {
1332 Number.isInteger(this.gameRef) ||
1333 !isNaN(parseInt(this.gameRef, 10))
1335 // corr games identifiers are integers
1340 data: { gid: this.gameRef },
1342 res.game.moves.forEach(m => {
1343 m.squares = JSON.parse(m.squares);
1350 else if (!!this.gameRef.match(/^i/))
1351 // Game import (maybe remote)
1352 ImportgameStorage.get(this.gameRef, callback);
1354 // Local live game (or remote)
1355 GameStorage.get(this.gameRef, callback);
1357 re_setClocks: function() {
1358 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1359 if (this.game.moves.length < 2 || this.game.score != "*") {
1360 // 1st move not completed yet, or game over: freeze time
1363 const currentTurn = this.vr.turn;
1364 const currentMovesCount = this.game.moves.length;
1365 const colorIdx = ["w", "b"].indexOf(currentTurn);
1366 this.clockUpdate = setInterval(
1369 this.game.clocks[colorIdx] < 0 ||
1370 this.game.moves.length > currentMovesCount ||
1371 this.game.score != "*"
1373 clearInterval(this.clockUpdate);
1374 this.clockUpdate = null;
1375 if (this.game.clocks[colorIdx] < 0)
1377 currentTurn == "w" ? "0-1" : "1-0",
1385 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1392 // Update variables and storage after a move:
1393 processMove: function(move, data) {
1394 if (this.game.type == "import")
1395 // Shouldn't receive any messages in this mode:
1397 if (!data) data = {};
1398 const moveCol = this.vr.turn;
1399 const colorIdx = ["w", "b"].indexOf(moveCol);
1400 const nextIdx = 1 - colorIdx;
1401 const doProcessMove = () => {
1402 const origMovescount = this.game.moves.length;
1403 // The move is (about to be) played: stop clock
1404 clearInterval(this.clockUpdate);
1405 this.clockUpdate = null;
1406 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1407 if (this.drawOffer == "received")
1409 this.drawOffer = "";
1410 if (this.game.type == "live" && origMovescount >= 2) {
1411 this.game.clocks[colorIdx] += this.game.increment;
1412 // For a correct display in casqe of disconnected opponent:
1416 ppt(this.game.clocks[colorIdx]).split(':')
1418 GameStorage.update(this.gameRef, {
1419 // It's not my turn anymore:
1424 // Update current game object:
1425 playMove(move, this.vr);
1427 // Received move, score is computed in BaseGame, but maybe not yet.
1428 // ==> Compute it here, although this is redundant (TODO)
1429 data.score = this.vr.getCurrentScore();
1430 if (data.score != "*") this.gameOver(data.score);
1431 this.game.moves.push(move);
1432 this.game.fen = this.vr.getFen();
1433 if (this.game.type == "corr") {
1434 // In corr games, just reset clock to mainTime:
1435 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1437 if (!V.IgnoreRepetition) {
1438 // If repetition detected, consider that a draw offer was received:
1439 const fenObj = this.vr.getFenForRepeat();
1440 this.repeat[fenObj] =
1441 !!this.repeat[fenObj]
1442 ? this.repeat[fenObj] + 1
1444 if (this.repeat[fenObj] >= 3) {
1445 if (this.vr.loseOnRepetition())
1446 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1447 else this.drawOffer = "threerep";
1449 else if (this.drawOffer == "threerep") this.drawOffer = "";
1451 if (!!this.game.mycolor && !data.receiveMyMove) {
1452 // NOTE: 'var' to see that variable outside this block
1453 var filtered_move = getFilteredMove(move);
1455 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1456 // Notify turn on MyGames page:
1465 // Since corr games are stored at only one location, update should be
1466 // done only by one player for each move:
1468 this.game.type == "live" &&
1469 !!this.game.mycolor &&
1470 moveCol != this.game.mycolor &&
1471 this.game.moves.length >= 2
1473 // Receive a move: update initime
1474 this.game.initime = Date.now();
1475 GameStorage.update(this.gameRef, {
1476 // It's my turn now!
1477 initime: this.game.initime
1481 !!this.game.mycolor &&
1482 !data.receiveMyMove &&
1483 (this.game.type == "live" || moveCol == this.game.mycolor)
1486 switch (this.drawOffer) {
1491 drawCode = this.game.mycolor;
1494 drawCode = V.GetOppCol(this.game.mycolor);
1497 if (this.game.type == "corr") {
1498 // corr: only move, fen and score
1499 this.updateCorrGame({
1502 squares: filtered_move,
1505 // Code "n" for "None" to force reset (otherwise it's ignored)
1506 drawOffer: drawCode || "n"
1510 const updateStorage = () => {
1511 GameStorage.update(this.gameRef, {
1513 move: filtered_move,
1514 moveIdx: origMovescount,
1515 clocks: this.game.clocks,
1519 // The active tab can update storage immediately
1520 if (this.focus) updateStorage();
1521 // Small random delay otherwise
1522 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1525 // Send move ("newmove" event) to people in the room (if our turn)
1526 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1528 move: filtered_move,
1529 index: origMovescount,
1530 // color is required to check if this is my move
1531 // (if several tabs opened)
1533 cancelDrawOffer: this.drawOffer == ""
1535 if (this.game.type == "live")
1536 sendMove["clock"] = this.game.clocks[colorIdx];
1537 // (Live) Clocks will re-start when the opponent pingback arrive
1538 this.opponentGotMove = false;
1539 this.send("newmove", {data: sendMove});
1540 // If the opponent doesn't reply gotmove soon enough, re-send move:
1541 // Do this at most 2 times, because more would mean network issues,
1542 // opponent would then be expected to disconnect/reconnect.
1544 const currentUrl = document.location.href;
1545 this.retrySendmove = setInterval(
1549 this.opponentGotMove ||
1550 document.location.href != currentUrl //page change
1552 clearInterval(this.retrySendmove);
1555 const oppsid = this.getOppsid();
1557 // Opponent is disconnected: he'll ask last state
1558 clearInterval(this.retrySendmove);
1560 this.send("newmove", { data: sendMove, target: oppsid });
1568 // Not my move or I'm an observer: just start other player's clock
1569 this.re_setClocks();
1572 this.game.type == "corr" &&
1573 moveCol == this.game.mycolor &&
1576 let boardDiv = document.querySelector(".game");
1577 const afterSetScore = () => {
1579 if (this.st.settings.gotonext && this.nextIds.length > 0)
1580 this.showNextGame();
1582 // The board might have been hidden:
1583 if (boardDiv.style.visibility == "hidden")
1584 boardDiv.style.visibility = "visible";
1585 if (data.score == "*") this.re_setClocks();
1588 if (!V.CorrConfirm) {
1592 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1593 // We may play several moves in a row: in case of, remove listener:
1594 let elClone = el.cloneNode(true);
1595 el.parentNode.replaceChild(elClone, el);
1596 elClone.addEventListener(
1599 document.getElementById("modalConfirm").checked = false;
1600 if (!!data.score && data.score != "*")
1602 this.gameOver(data.score, null, afterSetScore);
1603 else afterSetScore();
1606 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1607 const arMove = (Array.isArray(move) ? move : [move]);
1608 for (let i = 0; i < arMove.length; i++)
1609 V.PlayOnBoard(this.vr.board, arMove[i]);
1610 const position = this.vr.getBaseFen();
1611 for (let i = arMove.length - 1; i >= 0; i--)
1612 V.UndoOnBoard(this.vr.board, arMove[i]);
1613 if (["all","byrow"].includes(V.ShowMoves)) {
1614 this.curDiag = getDiagram({
1616 orientation: V.CanFlip ? this.game.mycolor : "w"
1618 document.querySelector("#confirmDiv > .card").style.width =
1619 boardDiv.offsetWidth + "px";
1622 // Incomplete information: just ask confirmation
1623 // Hide the board, because otherwise it could reveal infos
1624 boardDiv.style.visibility = "hidden";
1625 this.moveNotation = getFullNotation(move);
1627 document.getElementById("modalConfirm").checked = true;
1631 if (!!data.score && data.score != "*")
1632 this.gameOver(data.score, null, doProcessMove);
1633 else doProcessMove();
1636 cancelMove: function() {
1637 let boardDiv = document.querySelector(".game");
1638 if (boardDiv.style.visibility == "hidden")
1639 boardDiv.style.visibility = "visible";
1640 document.getElementById("modalConfirm").checked = false;
1641 this.$refs["basegame"].cancelLastMove();
1643 // In corr games, callback to change page only after score is set:
1644 gameOver: function(score, scoreMsg, callback) {
1645 this.game.score = score;
1646 if (!scoreMsg) scoreMsg = getScoreMessage(score, V.ReverseColors);
1647 this.game.scoreMsg = scoreMsg;
1648 document.getElementById("modalRules").checked = false;
1649 // Display result in a un-missable way:
1650 document.getElementById("modalScore").checked = true;
1651 this.$set(this.game, "scoreMsg", scoreMsg);
1652 const myIdx = this.game.players.findIndex(p => {
1654 p.sid == this.st.user.sid ||
1655 (!!p.name && p.id == this.st.user.id)
1659 // OK, I play in this game
1664 if (this.game.type == "live") {
1665 GameStorage.update(this.gameRef, scoreObj);
1666 // Notify myself locally if I'm elsewhere:
1670 { body: score + " : " + scoreMsg }
1673 if (!!callback) callback();
1675 else this.updateCorrGame(scoreObj, callback);
1676 // Notify the score to main Hall.
1677 // TODO: only one player (currently double send)
1678 this.send("result", { gid: this.game.id, score: score });
1679 // Also to MyGames page (TODO: doubled as well...)
1688 else if (!!callback) callback();
1694 <style lang="sass" scoped>
1695 #scoreDiv > .card, #rematchDiv > .card
1703 @media screen and (max-width: 1500px)
1705 @media screen and (max-width: 1024px)
1707 @media screen and (max-width: 767px)
1717 background-color: lightgreen
1729 @media screen and (max-width: 767px)
1734 display: inline-block
1738 display: inline-block
1740 display: inline-flex
1744 @media screen and (max-width: 767px)
1753 @media screen and (max-width: 767px)
1765 background-color: #edda99
1767 display: inline-block
1771 display: inline-block
1778 @media screen and (max-width: 767px)
1780 display: inline-block
1793 animation: blink-animation 2s steps(3, start) infinite
1794 @keyframes blink-animation
1799 display: inline-block
1811 .draw-sent, .draw-sent:hover
1812 background-color: lightyellow
1814 .draw-received, .draw-received:hover
1815 background-color: #73C6B6
1817 .draw-threerep, .draw-threerep:hover
1818 background-color: #D2B4DE
1820 .rematch-sent, .rematch-sent:hover
1821 background-color: lightyellow
1823 .rematch-received, .rematch-received:hover
1824 background-color: #48C9B0
1827 background-color: #D2B4DE
1840 background-color: lightgreen
1842 background-color: red
1845 color: var(--card-fore-color)
1848 font-size: calc(1rem * var(--heading-ratio))
1850 margin: calc(1.5 * var(--universal-margin))
1854 @import "@/styles/_rules.sass"
1855 @import "@/styles/_board_squares_img.sass"