3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 h4#variantNameInGame(@click="gotoRules") {{ game.vname }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
49 v-if="participateInChat(p)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
86 | {{ st.tr["Next_g"] }}
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 gotoRules: function() {
314 this.$router.push("/variants/" + this.game.vname);
316 participateInChat: function(p) {
317 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
319 someAnonymousPresent: function() {
321 Object.values(this.people).some(p =>
322 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
326 atCreation: function() {
327 document.addEventListener('visibilitychange', this.visibilityChange);
328 window.addEventListener('focus', this.onFocus);
329 window.addEventListener('blur', this.onBlur);
330 // 0] (Re)Set variables
331 this.gameRef = this.$route.params["id"];
332 // next = next corr games IDs to navigate faster (if applicable)
333 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
334 // Always add myself to players' list
335 const my = this.st.user;
336 const tmpId = getRandString();
344 tmpId: { focus: true }
349 players: [{ name: "" }, { name: "" }],
353 let chatComp = this.$refs["chatcomp"];
354 if (!!chatComp) chatComp.chats = [];
355 this.virtualClocks = [[0,0], [0,0]];
357 this.rulesContent = "";
359 this.lastateAsked = false;
360 this.rematchOffer = "";
361 this.lastate = undefined;
362 this.roomInitialized = false;
363 this.askGameTime = 0;
364 this.gameIsLoading = false;
365 this.gotLastate = false;
366 this.gotMoveIdx = -1;
367 this.opponentGotMove = false;
368 this.askLastate = null;
369 this.retrySendmove = null;
370 this.clockUpdate = null;
371 this.newConnect = {};
372 // 1] Initialize connection
373 this.connexionString =
375 "/?sid=" + this.st.user.sid +
376 "&id=" + this.st.user.id +
379 // Discard potential "/?next=[...]" for page indication:
380 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
381 this.conn = new WebSocket(this.connexionString);
382 this.conn.addEventListener("message", this.socketMessageListener);
383 this.socketCloseListener = setInterval(
385 if (this.conn.readyState == 3) {
386 this.conn.removeEventListener(
387 "message", this.socketMessageListener);
388 this.conn = new WebSocket(this.connexionString);
389 this.conn.addEventListener("message", this.socketMessageListener);
394 // Socket init required before loading remote game:
395 const socketInit = callback => {
396 if (this.conn.readyState == 1)
400 // Socket not ready yet (initial loading)
401 // NOTE: first arg is Websocket object, unused here:
402 this.conn.onopen = () => callback();
404 this.fetchGame((game) => {
406 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
408 // Live game stored remotely: need socket to retrieve it
409 // NOTE: the callback "roomInit" will be lost, so it's not provided.
410 // --> It will be given when receiving "fullgame" socket event.
411 socketInit(() => { this.send("askfullgame"); });
414 roomInit: function() {
415 if (!this.roomInitialized) {
416 // Notify the room only now that I connected, because
417 // messages might be lost otherwise (if game loading is slow)
418 this.send("connect");
419 this.send("pollclients");
420 // We may ask fullgame several times if some moves are lost,
421 // but room should be init only once:
422 this.roomInitialized = true;
425 send: function(code, obj) {
426 if (!!this.conn && this.conn.readyState == 1)
427 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
429 isConnected: function(index) {
430 const player = this.game.players[index];
431 // Is it me ? In this case no need to bother with focus
432 if (this.st.user.sid == player.sid || 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);
436 // Try to find a match in people:
440 Object.keys(this.people).some(sid => {
443 Object.values(this.people[sid].tmpIds).some(v => v.focus)
450 Object.values(this.people).some(p => {
453 Object.values(p.tmpIds).some(v => v.focus)
459 getOppsid: function() {
460 let oppsid = this.game.oppsid;
462 oppsid = Object.keys(this.people).find(
463 sid => this.people[sid].id == this.game.oppid
466 // oppsid is useful only if opponent is online:
467 if (!!oppsid && !!this.people[oppsid]) return oppsid;
470 // NOTE: action if provided is always a closing action
471 toggleChat: function(action) {
472 if (!action && document.getElementById("modalChat").checked)
474 document.getElementById("inputChat").focus();
476 document.getElementById("chatBtn").classList.remove("somethingnew");
477 if (!!this.game.mycolor) {
478 // Update "chatRead" variable either on server or locally
479 if (this.game.type == "corr")
480 this.updateCorrGame({ chatRead: this.game.mycolor });
481 else if (this.game.type == "live")
482 GameStorage.update(this.gameRef, { chatRead: true });
486 processChat: function(chat) {
487 this.send("newchat", { data: chat });
488 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
489 if (!!this.game.mycolor) {
490 if (this.game.type == "corr")
491 this.updateCorrGame({ chat: chat });
494 chat.added = Date.now();
495 GameStorage.update(this.gameRef, { chat: chat });
499 clearChat: function() {
500 if (!!this.game.mycolor) {
501 if (this.game.type == "corr") {
505 { data: { gid: this.game.id } }
509 GameStorage.update(this.gameRef, { delchat: true });
511 this.$set(this.game, "chats", []);
514 getGameType: function(game) {
515 if (!!game.id.toString().match(/^i/)) return "import";
516 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
518 // Notify something after a new move (to opponent and me on MyGames page)
519 notifyMyGames: function(thing, data) {
524 targets: this.game.players.map(p => {
525 return { sid: p.sid, id: p.id };
530 showNextGame: function() {
531 // Did I play in current game? If not, add it to nextIds list
532 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
533 this.nextIds.unshift(this.game.id);
534 const nextGid = this.nextIds.pop();
536 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
538 askGameAgain: function() {
539 this.gameIsLoading = true;
540 const currentUrl = document.location.href;
541 const doAskGame = () => {
542 if (document.location.href != currentUrl) return; //page change
543 this.fetchGame((game) => {
545 // This is my game: just reload.
548 // Just ask fullgame again (once!), this is much simpler.
549 // If this fails, the user could just reload page :/
550 this.send("askfullgame");
553 // Delay of at least 2s between two game requests
554 const now = Date.now();
555 const delay = Math.max(2000 - (now - this.askGameTime), 0);
556 this.askGameTime = now;
557 setTimeout(doAskGame, delay);
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] });
593 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
594 this.$forceUpdate(); //TODO: shouldn't be required
598 if (!this.people[data.from[0]]) return;
599 delete this.people[data.from[0]].tmpIds[data.from[1]];
600 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
601 this.$delete(this.people, data.from[0]);
602 else this.$forceUpdate(); //TODO: shouldn't be required
605 let player = this.people[data.from[0]];
607 player.tmpIds[data.from[1]].focus = true;
608 this.$forceUpdate(); //TODO: shouldn't be required
613 let player = this.people[data.from[0]];
615 player.tmpIds[data.from[1]].focus = false;
616 this.$forceUpdate(); //TODO: shouldn't be required
620 case "askidentity": {
621 // Request for identification
623 // Decompose to avoid revealing email
624 name: this.st.user.name,
625 sid: this.st.user.sid,
628 this.send("identity", { data: me, target: data.from });
632 const user = data.data;
633 let player = this.people[user.sid];
634 // player.tmpIds is already set
635 player.name = user.name;
637 if (this.game.type == "live") {
639 this.game.players.findIndex(p => p.sid == this.st.user.sid);
640 // Sometimes a player name isn't stored yet (TODO: why?)
643 !this.game.players[1 - myGidx].name &&
644 this.game.players[1 - myGidx].sid == user.sid &&
647 this.game.players[1-myGidx].name = user.name;
650 { playerName: { idx: 1 - myGidx, name: user.name } }
654 this.$forceUpdate(); //TODO: shouldn't be required
655 // If I multi-connect, kill current connexion if no mark (I'm older)
656 if (this.newConnect[user.sid]) {
657 delete this.newConnect[user.sid];
660 user.id == this.st.user.id &&
661 user.sid != this.st.user.sid
663 this.cleanBeforeDestroy();
664 alert(this.st.tr["New connexion detected: tab now offline"]);
668 // Ask potentially missed last state, if opponent and I play
671 !!this.game.mycolor &&
672 this.game.type == "live" &&
673 this.game.players.some(p => p.sid == user.sid)
675 this.send("asklastate", { target: user.sid });
677 this.askLastate = setInterval(
679 // Ask at most 3 times:
680 // if no reply after that there should be a network issue.
684 !!this.people[user.sid]
686 this.send("asklastate", { target: user.sid });
689 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","vname",
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);
749 // Got opponent infos about last move
750 this.gotLastate = true;
751 this.lastate = data.data;
752 if (this.game.rendered)
753 // Game is rendered (Board component)
754 this.processLastate();
755 // Else: will be processed when game is ready
759 const movePlus = data.data;
760 const movesCount = this.game.moves.length;
761 if (movePlus.index > movesCount) {
762 // This can only happen if I'm an observer and missed a move.
763 if (this.gotMoveIdx < movePlus.index)
764 this.gotMoveIdx = movePlus.index;
765 if (!this.gameIsLoading) this.askGameAgain();
769 movePlus.index < movesCount ||
770 this.gotMoveIdx >= movePlus.index
772 // Opponent re-send but we already have the move:
773 // (maybe he didn't receive our pingback...)
774 this.send("gotmove", {data: movePlus.index, target: data.from});
776 this.gotMoveIdx = movePlus.index;
777 const receiveMyMove = (movePlus.color == this.game.mycolor);
778 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
779 if (!receiveMyMove && !!this.game.mycolor) {
780 // Notify opponent that I got the move:
783 { data: movePlus.index, target: data.from }
785 // And myself if I'm elsewhere:
791 (this.game.players[moveColIdx].name || "@nonymous") +
797 if (movePlus.cancelDrawOffer) {
798 // Opponent refuses draw
800 // NOTE for corr games: drawOffer reset by player in turn
802 this.game.type == "live" &&
803 !!this.game.mycolor &&
806 GameStorage.update(this.gameRef, { drawOffer: "" });
809 this.$refs["basegame"].play(movePlus.move, "received");
810 // Freeze time while the move is being play
811 // (TODO: a callback would be cleaner here)
812 clearInterval(this.clockUpdate);
813 this.clockUpdate = null;
814 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
815 // 250 = length of animation, 500 = delay between sub-moves
817 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
818 // Incomplete information: no move animation
822 this.game.clocks[moveColIdx] = movePlus.clock;
825 { receiveMyMove: receiveMyMove }
835 this.opponentGotMove = true;
836 // Now his clock starts running on my side:
837 const oppIdx = ['w','b'].indexOf(this.vr.turn);
838 // NOTE: next line to avoid multi-resetClocks when several tabs
839 // on same game, resulting in a faster countdown.
840 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
845 const score = (data.data == "b" ? "1-0" : "0-1");
846 const side = (data.data == "w" ? "White" : "Black");
847 this.gameOver(score, side + " surrender");
850 this.gameOver("?", "Stop");
853 this.gameOver("1/2", data.data);
856 // NOTE: observers don't know who offered draw
857 this.drawOffer = "received";
858 if (!!this.game.mycolor && this.game.type == "live") {
861 { drawOffer: V.GetOppCol(this.game.mycolor) }
866 // NOTE: observers don't know who offered rematch
867 this.rematchOffer = data.data ? "received" : "";
868 if (!!this.game.mycolor && this.game.type == "live") {
871 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
876 // A game started, redirect if I'm playing in
877 const gameInfo = data.data;
878 const gameType = this.getGameType(gameInfo);
880 gameType == "live" &&
881 gameInfo.players.some(p => p.sid == this.st.user.sid)
883 this.addAndGotoLiveGame(gameInfo);
885 gameType == "corr" &&
886 gameInfo.players.some(p => p.id == this.st.user.id)
888 this.$router.push("/game/" + gameInfo.id);
890 this.rematchId = gameInfo.id;
891 document.getElementById("modalRules").checked = false;
892 document.getElementById("modalScore").checked = false;
893 document.getElementById("modalRematch").checked = true;
898 let chat = data.data;
899 this.$refs["chatcomp"].newChat(chat);
900 if (this.game.type == "live") {
901 chat.added = Date.now();
902 if (!!this.game.mycolor)
903 GameStorage.update(this.gameRef, { chat: chat });
905 if (!document.getElementById("modalChat").checked)
906 document.getElementById("chatBtn").classList.add("somethingnew");
911 updateCorrGame: function(obj, callback) {
921 if (!!callback) callback();
926 sendLastate: function(target) {
927 // Send our "last state" informations to opponent
928 const L = this.game.moves.length;
929 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
932 (L > 0 && this.vr.turn != this.game.mycolor)
933 ? this.game.moves[L - 1]
935 clock: this.game.clocks[myIdx],
936 // Since we played a move (or abort or resign),
937 // only drawOffer=="sent" is possible
938 drawSent: this.drawOffer == "sent" ? true : undefined,
939 rematchSent: this.rematchOffer == "sent" ? true : undefined,
940 score: this.game.score != "*" ? this.game.score : undefined,
941 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
944 this.send("lastate", { data: myLastate, target: target });
946 // lastate was received, but maybe game wasn't ready yet:
947 processLastate: function() {
948 const data = this.lastate;
949 this.lastate = undefined; //security...
951 const oppCol = V.GetOppCol(this.game.mycolor);
952 if (!!data.rematchSent) {
953 if (this.game.rematchOffer != oppCol) {
954 // Opponent sended rematch offer while we were offline:
955 this.rematchOffer = "received";
958 { rematchOffer: oppCol }
963 if (this.game.rematchOffer == oppCol) {
964 // Opponent cancelled rematch offer while we were offline:
965 this.rematchOffer = "";
974 const L = this.game.moves.length;
975 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
976 this.game.clocks[oppIdx] = data.clock;
977 if (data.movesCount > L) {
978 // Just got last move from him
979 this.$refs["basegame"].play(data.lastMove, "received");
980 this.processMove(data.lastMove);
982 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
985 if (!!data.drawSent) this.drawOffer = "received";
988 if (this.game.score == "*")
989 this.gameOver(data.score, data.scoreMsg);
993 clickDraw: function() {
994 if (!this.game.mycolor || this.game.type == "import") return;
995 if (["received", "threerep"].includes(this.drawOffer)) {
996 if (!confirm(this.st.tr["Accept draw?"])) return;
998 this.drawOffer == "received"
1000 : "Three repetitions";
1001 this.send("draw", { data: message });
1002 this.gameOver("1/2", message);
1003 } else if (this.drawOffer == "") {
1004 // No effect if drawOffer == "sent"
1005 if (this.game.mycolor != this.vr.turn) {
1006 alert(this.st.tr["Draw offer only in your turn"]);
1009 if (!confirm(this.st.tr["Offer draw?"])) return;
1010 this.drawOffer = "sent";
1011 this.send("drawoffer");
1012 if (this.game.type == "live") {
1015 { drawOffer: this.game.mycolor }
1017 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
1020 addAndGotoLiveGame: function(gameInfo, callback) {
1021 const game = Object.assign(
1025 // (other) Game infos: constant
1026 fenStart: gameInfo.fen,
1027 vname: this.game.vname,
1028 created: Date.now(),
1029 // Game state (including FEN): will be updated
1031 clocks: [-1, -1], //-1 = unstarted
1035 GameStorage.add(game, (err) => {
1036 // No error expected.
1038 if (this.st.settings.sound)
1039 new Audio("/sounds/newgame.flac").play().catch(() => {});
1040 if (!!callback) callback();
1041 this.$router.push("/game/" + gameInfo.id);
1045 clickRematch: function() {
1046 if (!this.game.mycolor || this.game.type == "import") return;
1047 if (this.rematchOffer == "received") {
1048 // Start a new game!
1050 id: getRandString(), //ignored if corr
1051 fen: V.GenRandInitFen(this.game.randomness),
1052 players: this.game.players.reverse(),
1054 cadence: this.game.cadence
1056 const notifyNewGame = () => {
1057 const oppsid = this.getOppsid(); //may be null
1058 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1059 // To main Hall if corr game:
1060 if (this.game.type == "corr")
1061 this.send("newgame", { data: gameInfo, page: "/" });
1062 // Also to MyGames page:
1063 this.notifyMyGames("newgame", gameInfo);
1065 if (this.game.type == "live")
1066 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1073 // cid is useful to delete the challenge:
1074 data: { gameInfo: gameInfo },
1075 success: (response) => {
1076 gameInfo.id = response.gameId;
1078 this.$router.push("/game/" + response.gameId);
1083 } else if (this.rematchOffer == "") {
1084 this.rematchOffer = "sent";
1085 this.send("rematchoffer", { data: true });
1086 if (this.game.type == "live") {
1089 { rematchOffer: this.game.mycolor }
1091 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1092 } else if (this.rematchOffer == "sent") {
1093 // Toggle rematch offer (on --> off)
1094 this.rematchOffer = "";
1095 this.send("rematchoffer", { data: false });
1096 if (this.game.type == "live") {
1099 { rematchOffer: '' }
1101 } else this.updateCorrGame({ rematchOffer: 'n' });
1104 abortGame: function() {
1105 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1107 this.gameOver("?", "Stop");
1110 resign: function() {
1111 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1113 this.send("resign", { data: this.game.mycolor });
1114 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1115 const side = (this.game.mycolor == "w" ? "White" : "Black");
1116 this.gameOver(score, side + " surrender");
1118 loadGame: function(game, callback) {
1119 const gtype = game.type || this.getGameType(game);
1120 const tc = extractTime(game.cadence);
1121 const myIdx = game.players.findIndex(p => {
1122 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1124 // Sometimes the name isn't stored yet (TODO: why?)
1128 !game.players[myIdx].name &&
1131 game.players[myIdx].name = this.st.user.name;
1134 { playerName: { idx: myIdx, name: this.st.user.name } }
1137 // "mycolor" is undefined for observers
1138 const mycolor = [undefined, "w", "b"][myIdx + 1];
1139 if (gtype == "corr") {
1140 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1141 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1142 // NOTE: clocks in seconds
1143 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1144 game.clocks = [tc.mainTime, tc.mainTime];
1145 const L = game.moves.length;
1146 if (game.score == "*") {
1149 game.clocks[L % 2] -=
1150 (Date.now() - game.moves[L-1].played) / 1000;
1153 // Now that we used idx and played, re-format moves as for live games
1154 game.moves = game.moves.map(m => m.squares);
1156 else if (gtype == "live") {
1157 if (game.clocks[0] < 0) {
1158 // Game is unstarted. clock is ignored until move 2
1159 game.clocks = [tc.mainTime, tc.mainTime];
1161 // I play in this live game
1164 { clocks: game.clocks }
1169 // It's my turn: clocks not updated yet
1170 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1174 // gtype == "import"
1175 game.clocks = [tc.mainTime, tc.mainTime];
1176 // Live games before 26/03/2020 don't have chat history:
1177 if (!game.chats) game.chats = []; //TODO: remove line
1178 // Sort chat messages from newest to oldest
1179 game.chats.sort((c1, c2) => c2.added - c1.added);
1182 game.chats.length > 0 &&
1183 (!game.chatRead || game.chatRead < game.chats[0].added)
1185 // A chat message arrived since my last reading:
1186 document.getElementById("chatBtn").classList.add("somethingnew");
1188 // TODO: merge next 2 "if" conditions
1189 if (!!game.drawOffer) {
1190 if (game.drawOffer == "t")
1191 // Three repetitions
1192 this.drawOffer = "threerep";
1194 // Draw offered by any of the players:
1195 if (myIdx < 0) this.drawOffer = "received";
1197 // I play in this game:
1199 (game.drawOffer == "w" && myIdx == 0) ||
1200 (game.drawOffer == "b" && myIdx == 1)
1202 this.drawOffer = "sent";
1203 else this.drawOffer = "received";
1207 if (!!game.rematchOffer) {
1208 if (myIdx < 0) this.rematchOffer = "received";
1210 // I play in this game:
1212 (game.rematchOffer == "w" && myIdx == 0) ||
1213 (game.rematchOffer == "b" && myIdx == 1)
1215 this.rematchOffer = "sent";
1217 else this.rematchOffer = "received";
1220 this.repeat = {}; //reset: scan past moves' FEN:
1222 this.vr = new V(game.fenStart);
1224 game.moves.forEach(m => {
1225 playMove(m, this.vr);
1226 const fenIdx = this.vr.getFenForRepeat();
1227 this.repeat[fenIdx] = this.repeat[fenIdx]
1228 ? this.repeat[fenIdx] + 1
1231 // Imported games don't have current FEN
1232 if (!game.fen) game.fen = this.vr.getFen();
1233 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1234 this.game = Object.assign(
1235 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1238 increment: tc.increment,
1240 // opponent sid not strictly required (or available), but easier
1241 // at least oppsid or oppid is available anyway:
1242 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1243 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1247 this.$refs["basegame"].re_setVariables(this.game);
1248 if (!this.gameIsLoading) {
1250 this.gotMoveIdx = game.moves.length - 1;
1251 // If we arrive here after 'nextGame' action, the board might be hidden
1252 let boardDiv = document.querySelector(".game");
1253 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1254 boardDiv.style.visibility = "visible";
1256 this.re_setClocks();
1257 this.$nextTick(() => {
1258 this.game.rendered = true;
1259 // Did lastate arrive before game was rendered?
1260 if (this.lastate) this.processLastate();
1262 if (this.lastateAsked) {
1263 this.lastateAsked = false;
1264 this.sendLastate(game.oppsid);
1266 if (this.gameIsLoading) {
1267 this.gameIsLoading = false;
1268 if (this.gotMoveIdx >= game.moves.length)
1269 // Some moves arrived meanwhile...
1270 this.askGameAgain();
1272 if (!!callback) callback();
1274 loadVariantThenGame: async function(game, callback) {
1275 await import("@/variants/" + game.vname + ".js")
1276 .then((vModule) => {
1277 window.V = vModule[game.vname + "Rules"];
1278 this.loadGame(game, callback);
1280 // (AJAX) Request to get rules content (plain text, HTML)
1283 "raw-loader!@/translations/rules/" +
1285 this.st.lang + ".pug"
1287 // Next two lines fix a weird issue after last update (2019-11)
1288 .replace(/\\n/g, " ")
1289 .replace(/\\"/g, '"')
1290 .replace('module.exports = "', "")
1292 .replace(/(fen:)([^:]*):/g, replaceByDiag);
1294 // 3 cases for loading a game:
1295 // - from indexedDB (running or completed live game I play)
1296 // - from server (one correspondance game I play[ed] or not)
1297 // - from remote peer (one live game I don't play, finished or not)
1298 fetchGame: function(callback) {
1299 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1300 // corr games identifiers are integers
1305 data: { gid: this.gameRef },
1307 res.game.moves.forEach(m => {
1308 m.squares = JSON.parse(m.squares);
1315 else if (!!this.gameRef.match(/^i/))
1316 // Game import (maybe remote)
1317 ImportgameStorage.get(this.gameRef, callback);
1319 // Local live game (or remote)
1320 GameStorage.get(this.gameRef, callback);
1322 re_setClocks: function() {
1323 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1324 if (this.game.moves.length < 2 || this.game.score != "*") {
1325 // 1st move not completed yet, or game over: freeze time
1328 const currentTurn = this.vr.turn;
1329 const currentMovesCount = this.game.moves.length;
1330 const colorIdx = ["w", "b"].indexOf(currentTurn);
1331 this.clockUpdate = setInterval(
1334 this.game.clocks[colorIdx] < 0 ||
1335 this.game.moves.length > currentMovesCount ||
1336 this.game.score != "*"
1338 clearInterval(this.clockUpdate);
1339 this.clockUpdate = null;
1340 if (this.game.clocks[colorIdx] < 0)
1342 currentTurn == "w" ? "0-1" : "1-0",
1349 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1356 // Update variables and storage after a move:
1357 processMove: function(move, data) {
1358 if (this.game.type == "import")
1359 // Shouldn't receive any messages in this mode:
1361 if (!data) data = {};
1362 const moveCol = this.vr.turn;
1363 const colorIdx = ["w", "b"].indexOf(moveCol);
1364 const nextIdx = 1 - colorIdx;
1365 const doProcessMove = () => {
1366 const origMovescount = this.game.moves.length;
1367 // The move is (about to be) played: stop clock
1368 clearInterval(this.clockUpdate);
1369 this.clockUpdate = null;
1370 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1371 if (this.drawOffer == "received")
1373 this.drawOffer = "";
1374 if (this.game.type == "live" && origMovescount >= 2) {
1375 this.game.clocks[colorIdx] += this.game.increment;
1376 // For a correct display in casqe of disconnected opponent:
1380 ppt(this.game.clocks[colorIdx]).split(':')
1382 GameStorage.update(this.gameRef, {
1383 // It's not my turn anymore:
1388 // Update current game object:
1389 playMove(move, this.vr);
1391 // Received move, score is computed in BaseGame, but maybe not yet.
1392 // ==> Compute it here, although this is redundant (TODO)
1393 data.score = this.vr.getCurrentScore();
1394 if (data.score != "*") this.gameOver(data.score);
1395 this.game.moves.push(move);
1396 this.game.fen = this.vr.getFen();
1397 if (this.game.type == "corr") {
1398 // In corr games, just reset clock to mainTime:
1399 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1401 // If repetition detected, consider that a draw offer was received:
1402 const fenObj = this.vr.getFenForRepeat();
1403 this.repeat[fenObj] =
1404 !!this.repeat[fenObj]
1405 ? this.repeat[fenObj] + 1
1407 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1408 else if (this.drawOffer == "threerep") this.drawOffer = "";
1409 if (!!this.game.mycolor && !data.receiveMyMove) {
1410 // NOTE: 'var' to see that variable outside this block
1411 var filtered_move = getFilteredMove(move);
1413 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1414 // Notify turn on MyGames page:
1423 // Since corr games are stored at only one location, update should be
1424 // done only by one player for each move:
1426 this.game.type == "live" &&
1427 !!this.game.mycolor &&
1428 moveCol != this.game.mycolor &&
1429 this.game.moves.length >= 2
1431 // Receive a move: update initime
1432 this.game.initime = Date.now();
1433 GameStorage.update(this.gameRef, {
1434 // It's my turn now!
1435 initime: this.game.initime
1439 !!this.game.mycolor &&
1440 !data.receiveMyMove &&
1441 (this.game.type == "live" || moveCol == this.game.mycolor)
1444 switch (this.drawOffer) {
1449 drawCode = this.game.mycolor;
1452 drawCode = V.GetOppCol(this.game.mycolor);
1455 if (this.game.type == "corr") {
1456 // corr: only move, fen and score
1457 this.updateCorrGame({
1460 squares: filtered_move,
1463 // Code "n" for "None" to force reset (otherwise it's ignored)
1464 drawOffer: drawCode || "n"
1468 const updateStorage = () => {
1469 GameStorage.update(this.gameRef, {
1471 move: filtered_move,
1472 moveIdx: origMovescount,
1473 clocks: this.game.clocks,
1477 // The active tab can update storage immediately
1478 if (this.focus) updateStorage();
1479 // Small random delay otherwise
1480 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1483 // Send move ("newmove" event) to people in the room (if our turn)
1484 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1486 move: filtered_move,
1487 index: origMovescount,
1488 // color is required to check if this is my move
1489 // (if several tabs opened)
1491 cancelDrawOffer: this.drawOffer == ""
1493 if (this.game.type == "live")
1494 sendMove["clock"] = this.game.clocks[colorIdx];
1495 // (Live) Clocks will re-start when the opponent pingback arrive
1496 this.opponentGotMove = false;
1497 this.send("newmove", {data: sendMove});
1498 // If the opponent doesn't reply gotmove soon enough, re-send move:
1499 // Do this at most 2 times, because mpore would mean network issues,
1500 // opponent would then be expected to disconnect/reconnect.
1502 const currentUrl = document.location.href;
1503 this.retrySendmove = setInterval(
1507 this.opponentGotMove ||
1508 document.location.href != currentUrl //page change
1510 clearInterval(this.retrySendmove);
1513 const oppsid = this.getOppsid();
1515 // Opponent is disconnected: he'll ask last state
1516 clearInterval(this.retrySendmove);
1518 this.send("newmove", { data: sendMove, target: oppsid });
1526 // Not my move or I'm an observer: just start other player's clock
1527 this.re_setClocks();
1530 this.game.type == "corr" &&
1531 moveCol == this.game.mycolor &&
1534 let boardDiv = document.querySelector(".game");
1535 const afterSetScore = () => {
1537 if (this.st.settings.gotonext && this.nextIds.length > 0)
1538 this.showNextGame();
1540 // The board might have been hidden:
1541 if (boardDiv.style.visibility == "hidden")
1542 boardDiv.style.visibility = "visible";
1543 if (data.score == "*") this.re_setClocks();
1546 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1547 // We may play several moves in a row: in case of, remove listener:
1548 let elClone = el.cloneNode(true);
1549 el.parentNode.replaceChild(elClone, el);
1550 elClone.addEventListener(
1553 document.getElementById("modalConfirm").checked = false;
1554 if (!!data.score && data.score != "*")
1556 this.gameOver(data.score, null, afterSetScore);
1557 else afterSetScore();
1560 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1561 const arMove = (Array.isArray(move) ? move : [move]);
1562 for (let i = 0; i < arMove.length; i++)
1563 V.PlayOnBoard(this.vr.board, arMove[i]);
1564 const position = this.vr.getBaseFen();
1565 for (let i = arMove.length - 1; i >= 0; i--)
1566 V.UndoOnBoard(this.vr.board, arMove[i]);
1567 if (["all","byrow"].includes(V.ShowMoves)) {
1568 this.curDiag = getDiagram({
1570 orientation: V.CanFlip ? this.game.mycolor : "w"
1572 document.querySelector("#confirmDiv > .card").style.width =
1573 boardDiv.offsetWidth + "px";
1575 // Incomplete information: just ask confirmation
1576 // Hide the board, because otherwise it could reveal infos
1577 boardDiv.style.visibility = "hidden";
1578 this.moveNotation = getFullNotation(move);
1580 document.getElementById("modalConfirm").checked = true;
1584 if (!!data.score && data.score != "*")
1585 this.gameOver(data.score, null, doProcessMove);
1586 else doProcessMove();
1589 cancelMove: function() {
1590 let boardDiv = document.querySelector(".game");
1591 if (boardDiv.style.visibility == "hidden")
1592 boardDiv.style.visibility = "visible";
1593 document.getElementById("modalConfirm").checked = false;
1594 this.$refs["basegame"].cancelLastMove();
1596 // In corr games, callback to change page only after score is set:
1597 gameOver: function(score, scoreMsg, callback) {
1598 this.game.score = score;
1599 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1600 this.game.scoreMsg = scoreMsg;
1601 document.getElementById("modalRules").checked = false;
1602 // Display result in a un-missable way:
1603 document.getElementById("modalScore").checked = true;
1604 this.$set(this.game, "scoreMsg", scoreMsg);
1605 const myIdx = this.game.players.findIndex(p => {
1606 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1609 // OK, I play in this game
1614 if (this.game.type == "live") {
1615 GameStorage.update(this.gameRef, scoreObj);
1616 // Notify myself locally if I'm elsewhere:
1620 { body: score + " : " + scoreMsg }
1623 if (!!callback) callback();
1625 else this.updateCorrGame(scoreObj, callback);
1626 // Notify the score to main Hall.
1627 // TODO: only one player (currently double send)
1628 this.send("result", { gid: this.game.id, score: score });
1629 // Also to MyGames page (TODO: doubled as well...)
1638 else if (!!callback) callback();
1644 <style lang="sass" scoped>
1645 #scoreDiv > .card, #rematchDiv > .card
1653 @media screen and (max-width: 1500px)
1655 @media screen and (max-width: 1024px)
1657 @media screen and (max-width: 767px)
1667 background-color: lightgreen
1679 @media screen and (max-width: 767px)
1684 display: inline-block
1688 display: inline-block
1690 display: inline-flex
1694 @media screen and (max-width: 767px)
1708 background-color: #edda99
1710 display: inline-block
1714 display: inline-block
1721 @media screen and (max-width: 767px)
1727 @media screen and (max-width: 767px)
1729 display: inline-block
1742 animation: blink-animation 2s steps(3, start) infinite
1743 @keyframes blink-animation
1748 display: inline-block
1760 .draw-sent, .draw-sent:hover
1761 background-color: lightyellow
1763 .draw-received, .draw-received:hover
1764 background-color: lightgreen
1766 .draw-threerep, .draw-threerep:hover
1767 background-color: #e4d1fc
1769 .rematch-sent, .rematch-sent:hover
1770 background-color: lightyellow
1772 .rematch-received, .rematch-received:hover
1773 background-color: lightgreen
1776 background-color: #c5fefe
1789 background-color: lightgreen
1791 background-color: red
1793 h4#variantNameInGame
1796 text-decoration: underline
1801 @import "@/styles/_rules.sass"
1802 @import "@/styles/_board_squares_img.sass"