3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
11 :href="'#/game/' + rematchId"
12 onClick="document.getElementById('modalInfo').checked=false"
14 | {{ st.tr["Rematch in progress"] }}
15 input#modalChat.modal(
21 data-checkbox="modalChat"
24 label.modal-close(for="modalChat")
26 span {{ st.tr["Participant(s):"] }}
28 v-for="p in Object.values(people)"
29 v-if="p.focus && !!p.name"
33 v-if="Object.values(people).some(p => p.focus && !p.name)"
38 :players="game.players"
39 :pastChats="game.chats"
41 @chatcleared="clearChat"
43 input#modalConfirm.modal(type="checkbox")
44 div#confirmDiv(role="dialog")
47 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
51 span {{ st.tr["Move played:"] + " " }}
52 span.bold {{ moveNotation }}
54 span {{ st.tr["Are you sure?"] }}
55 .button-group#buttonsConfirm
56 // onClick for acceptBtn: set dynamically
58 span {{ st.tr["Validate"] }}
59 button.refuseBtn(@click="cancelMove()")
60 span {{ st.tr["Cancel"] }}
62 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
63 span.variant-cadence {{ game.cadence }}
64 span.variant-name {{ game.vname }}
66 v-if="nextIds.length > 0"
67 @click="showNextGame()"
69 | {{ st.tr["Next_g"] }}
70 button#chatBtn.tooltip(
71 onClick="window.doClick('modalChat')"
74 img(src="/images/icons/chat.svg")
75 #actions(v-if="game.score=='*'")
78 :class="{['draw-' + drawOffer]: true}"
79 :aria-label="st.tr['Draw']"
81 img(src="/images/icons/draw.svg")
85 :aria-label="st.tr['Abort']"
87 img(src="/images/icons/abort.svg")
91 :aria-label="st.tr['Resign']"
93 img(src="/images/icons/resign.svg")
96 @click="clickRematch()"
97 :class="{['rematch-' + rematchOffer]: true}"
98 :aria-label="st.tr['Rematch']"
100 img(src="/images/icons/rematch.svg")
103 span.name(:class="{connected: isConnected(0)}")
104 | {{ game.players[0].name || "@nonymous" }}
106 v-if="game.score=='*'"
107 :class="{yourturn: !!vr && vr.turn == 'w'}"
109 span.time-left {{ virtualClocks[0][0] }}
110 span.time-separator(v-if="!!virtualClocks[0][1]") :
111 span.time-right(v-if="!!virtualClocks[0][1]")
112 | {{ virtualClocks[0][1] }}
114 span.name(:class="{connected: isConnected(1)}")
115 | {{ game.players[1].name || "@nonymous" }}
117 v-if="game.score=='*'"
118 :class="{yourturn: !!vr && vr.turn == 'b'}"
120 span.time-left {{ virtualClocks[1][0] }}
121 span.time-separator(v-if="!!virtualClocks[1][1]") :
122 span.time-right(v-if="!!virtualClocks[1][1]")
123 | {{ virtualClocks[1][1] }}
127 @newmove="processMove"
132 import BaseGame from "@/components/BaseGame.vue";
133 import Chat from "@/components/Chat.vue";
134 import { store } from "@/store";
135 import { GameStorage } from "@/utils/gameStorage";
136 import { ppt } from "@/utils/datetime";
137 import { ajax } from "@/utils/ajax";
138 import { extractTime } from "@/utils/timeControl";
139 import { getRandString } from "@/utils/alea";
140 import { getScoreMessage } from "@/utils/scoring";
141 import { getFullNotation } from "@/utils/notation";
142 import { getDiagram } from "@/utils/printDiagram";
143 import { processModalClick } from "@/utils/modalClick";
144 import { playMove, getFilteredMove } from "@/utils/playUndo";
145 import { ArrayFun } from "@/utils/array";
146 import params from "@/parameters";
156 // gameRef can point to a corr game, local game or remote live game
159 game: {}, //passed to BaseGame
160 // virtualClocks will be initialized from true game.clocks
162 vr: null, //"variant rules" object initialized from FEN
167 people: {}, //players + observers
168 lastate: undefined, //used if opponent send lastate before game is ready
169 repeat: {}, //detect position repetition
170 curDiag: "", //for corr moves confirmation
172 roomInitialized: false,
173 // If newmove has wrong index: ask fullgame again:
175 gameIsLoading: false,
176 // If asklastate got no reply, ask again:
178 gotMoveIdx: -1, //last move index received
179 // If newmove got no pingback, send again:
180 opponentGotMove: false,
182 // Incomplete info games: show move played
184 // Intervals from setInterval():
188 // Related to (killing of) self multi-connects:
194 $route: function(to, from) {
195 if (from.params["id"] != to.params["id"]) {
196 // Change everything:
197 this.cleanBeforeDestroy();
198 let boardDiv = document.querySelector(".game");
200 // In case of incomplete information variant:
201 boardDiv.style.visibility = "hidden";
205 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
206 this.loadGame(this.game);
210 // NOTE: some redundant code with Hall.vue (mostly related to people array)
211 created: function() {
214 mounted: function() {
215 document.addEventListener('visibilitychange', this.visibilityChange);
216 ["chatWrap", "infoDiv"].forEach(eltName => {
217 document.getElementById(eltName)
218 .addEventListener("click", processModalClick);
220 if ("ontouchstart" in window) {
221 // Disable tooltips on smartphones:
222 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
223 elt.classList.remove("tooltip");
227 beforeDestroy: function() {
228 document.removeEventListener('visibilitychange', this.visibilityChange);
229 this.cleanBeforeDestroy();
232 visibilityChange: function() {
233 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
235 document.visibilityState == "visible"
240 atCreation: function() {
241 // 0] (Re)Set variables
242 this.gameRef = this.$route.params["id"];
243 // next = next corr games IDs to navigate faster (if applicable)
244 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
245 // Always add myself to players' list
246 const my = this.st.user;
257 players: [{ name: "" }, { name: "" }],
261 let chatComp = this.$refs["chatcomp"];
262 if (!!chatComp) chatComp.chats = [];
263 this.virtualClocks = [[0,0], [0,0]];
266 this.lastateAsked = false;
267 this.rematchOffer = "";
268 this.lastate = undefined;
269 this.roomInitialized = false;
270 this.askGameTime = 0;
271 this.gameIsLoading = false;
272 this.gotLastate = false;
273 this.gotMoveIdx = -1;
274 this.opponentGotMove = false;
275 this.askLastate = null;
276 this.retrySendmove = null;
277 this.clockUpdate = null;
278 this.newConnect = {};
280 // 1] Initialize connection
281 this.connexionString =
290 // Discard potential "/?next=[...]" for page indication:
291 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
292 this.conn = new WebSocket(this.connexionString);
293 this.conn.onmessage = this.socketMessageListener;
294 this.conn.onclose = this.socketCloseListener;
295 // Socket init required before loading remote game:
296 const socketInit = callback => {
297 if (!!this.conn && this.conn.readyState == 1)
301 // Socket not ready yet (initial loading)
302 // NOTE: first arg is Websocket object, unused here:
303 this.conn.onopen = () => callback();
305 this.fetchGame((game) => {
307 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
309 // Live game stored remotely: need socket to retrieve it
310 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
311 // --> It will be given when receiving "fullgame" socket event.
312 socketInit(() => { this.send("askfullgame"); });
315 cleanBeforeDestroy: function() {
316 if (!!this.askLastate)
317 clearInterval(this.askLastate);
318 if (!!this.retrySendmove)
319 clearInterval(this.retrySendmove);
320 if (!!this.clockUpdate)
321 clearInterval(this.clockUpdate);
322 this.send("disconnect");
324 roomInit: function() {
325 if (!this.roomInitialized) {
326 // Notify the room only now that I connected, because
327 // messages might be lost otherwise (if game loading is slow)
328 this.send("connect");
329 this.send("pollclients");
330 // We may ask fullgame several times if some moves are lost,
331 // but room should be init only once:
332 this.roomInitialized = true;
335 send: function(code, obj) {
337 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
339 isConnected: function(index) {
340 const player = this.game.players[index];
341 // Is it me ? In this case no need to bother with focus
342 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
343 // Still have to check for name (because of potential multi-accounts
344 // on same browser, although this should be rare...)
345 return (!this.st.user.name || this.st.user.name == player.name);
346 // Try to find a match in people:
350 Object.keys(this.people).some(sid =>
351 sid == player.sid && this.people[sid].focus)
356 Object.values(this.people).some(p =>
357 p.id == player.id && p.focus)
361 getOppsid: function() {
362 let oppsid = this.game.oppsid;
364 oppsid = Object.keys(this.people).find(
365 sid => this.people[sid].id == this.game.oppid
368 // oppsid is useful only if opponent is online:
369 if (!!oppsid && !!this.people[oppsid]) return oppsid;
372 toggleChat: function() {
373 if (document.getElementById("modalChat").checked)
375 document.getElementById("inputChat").focus();
376 // TODO: next line is only required when exiting chat,
377 // but the event for now isn't well detected.
378 document.getElementById("chatBtn").classList.remove("somethingnew");
380 processChat: function(chat) {
381 this.send("newchat", { data: chat });
382 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
383 if (this.game.type == "corr" && this.st.user.id > 0)
384 this.updateCorrGame({ chat: chat });
386 clearChat: function() {
387 // Nothing more to do if game is live (chats not recorded)
388 if (this.game.type == "corr") {
389 if (!!this.game.mycolor) {
393 { data: { gid: this.game.id } }
396 this.$set(this.game, "chats", []);
399 getGameType: function(game) {
400 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
402 // Notify something after a new move (to opponent and me on MyGames page)
403 notifyMyGames: function(thing, data) {
408 targets: this.game.players.map(p => {
409 return { sid: p.sid, id: p.id };
414 showNextGame: function() {
415 // Did I play in current game? If not, add it to nextIds list
416 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
417 this.nextIds.unshift(this.game.id);
418 const nextGid = this.nextIds.pop();
420 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
422 askGameAgain: function() {
423 this.gameIsLoading = true;
424 const currentUrl = document.location.href;
425 const doAskGame = () => {
426 if (document.location.href != currentUrl) return; //page change
427 this.fetchGame((game) => {
429 // This is my game: just reload.
432 // Just ask fullgame again (once!), this is much simpler.
433 // If this fails, the user could just reload page :/
434 this.send("askfullgame");
437 // Delay of at least 2s between two game requests
438 const now = Date.now();
439 const delay = Math.max(2000 - (now - this.askGameTime), 0);
440 this.askGameTime = now;
441 setTimeout(doAskGame, delay);
443 socketMessageListener: function(msg) {
444 if (!this.conn) return;
445 const data = JSON.parse(msg.data);
448 // TODO: shuffling and random filtering on server, if
449 // the room is really crowded.
450 data.sockIds.forEach(sid => {
451 if (sid != this.st.user.sid) {
452 this.people[sid] = { focus: true };
453 this.send("askidentity", { target: sid });
458 if (!this.people[data.from]) {
459 this.people[data.from] = { focus: true };
460 this.newConnect[data.from] = true; //for self multi-connects tests
461 this.send("askidentity", { target: data.from });
465 this.$delete(this.people, data.from);
468 let player = this.people[data.from];
471 this.$forceUpdate(); //TODO: shouldn't be required
476 let player = this.people[data.from];
478 player.focus = false;
479 this.$forceUpdate(); //TODO: shouldn't be required
484 // I logged in elsewhere:
486 alert(this.st.tr["New connexion detected: tab now offline"]);
488 case "askidentity": {
489 // Request for identification
491 // Decompose to avoid revealing email
492 name: this.st.user.name,
493 sid: this.st.user.sid,
496 this.send("identity", { data: me, target: data.from });
500 const user = data.data;
501 let player = this.people[user.sid];
502 // player.focus is already set
503 player.name = user.name;
505 this.$forceUpdate(); //TODO: shouldn't be required
506 // If I multi-connect, kill current connexion if no mark (I'm older)
507 if (this.newConnect[user.sid]) {
510 user.id == this.st.user.id &&
511 user.sid != this.st.user.sid &&
512 !this.killed[this.st.user.sid]
514 this.send("killme", { sid: this.st.user.sid });
515 this.killed[this.st.user.sid] = true;
517 delete this.newConnect[user.sid];
519 if (!this.killed[this.st.user.sid]) {
520 // Ask potentially missed last state, if opponent and I play
522 !!this.game.mycolor &&
523 this.game.type == "live" &&
524 this.game.score == "*" &&
525 this.game.players.some(p => p.sid == user.sid)
527 this.send("asklastate", { target: user.sid });
529 this.askLastate = setInterval(
531 // Ask at most 3 times:
532 // if no reply after that there should be a network issue.
536 !!this.people[user.sid]
538 this.send("asklastate", { target: user.sid });
541 clearInterval(this.askLastate);
551 // Send current (live) game if not asked by any of the players
553 this.game.type == "live" &&
554 this.game.players.every(p => p.sid != data.from[0])
559 players: this.game.players,
561 cadence: this.game.cadence,
562 score: this.game.score
564 this.send("game", { data: myGame, target: data.from });
568 const gameToSend = Object.keys(this.game)
571 "id","fen","players","vid","cadence","fenStart","vname",
572 "moves","clocks","initime","score","drawOffer","rematchOffer"
576 obj[k] = this.game[k];
581 this.send("fullgame", { data: gameToSend, target: data.from });
584 // Callback "roomInit" to poll clients only after game is loaded
585 this.loadVariantThenGame(data.data, this.roomInit);
588 // Sending informative last state if I played a move or score != "*"
589 // If the game or moves aren't loaded yet, delay the sending:
590 if (!this.game || !this.game.moves) this.lastateAsked = true;
591 else this.sendLastate(data.from);
594 // Got opponent infos about last move
595 this.gotLastate = true;
596 if (!data.data.nothing) {
597 this.lastate = data.data;
598 if (this.game.rendered)
599 // Game is rendered (Board component)
600 this.processLastate();
601 // Else: will be processed when game is ready
606 const movePlus = data.data;
607 const movesCount = this.game.moves.length;
608 if (movePlus.index > movesCount) {
609 // This can only happen if I'm an observer and missed a move.
610 if (this.gotMoveIdx < movePlus.index)
611 this.gotMoveIdx = movePlus.index;
612 if (!this.gameIsLoading) this.askGameAgain();
616 movePlus.index < movesCount ||
617 this.gotMoveIdx >= movePlus.index
619 // Opponent re-send but we already have the move:
620 // (maybe he didn't receive our pingback...)
621 this.send("gotmove", {data: movePlus.index, target: data.from});
623 this.gotMoveIdx = movePlus.index;
624 const receiveMyMove = (movePlus.color == this.game.mycolor);
625 if (!receiveMyMove && !!this.game.mycolor)
626 // Notify opponent that I got the move:
627 this.send("gotmove", {data: movePlus.index, target: data.from});
628 if (movePlus.cancelDrawOffer) {
629 // Opponent refuses draw
631 // NOTE for corr games: drawOffer reset by player in turn
633 this.game.type == "live" &&
634 !!this.game.mycolor &&
637 GameStorage.update(this.gameRef, { drawOffer: "" });
640 this.$refs["basegame"].play(movePlus.move, "received", null, true);
644 clock: movePlus.clock,
645 receiveMyMove: receiveMyMove
653 this.opponentGotMove = true;
654 // Now his clock starts running:
655 const oppIdx = ['w','b'].indexOf(this.vr.turn);
656 this.game.initime[oppIdx] = Date.now();
661 const score = (data.data == "b" ? "1-0" : "0-1");
662 const side = (data.data == "w" ? "White" : "Black");
663 this.gameOver(score, side + " surrender");
666 this.gameOver("?", "Stop");
669 this.gameOver("1/2", data.data);
672 // NOTE: observers don't know who offered draw
673 this.drawOffer = "received";
674 if (this.game.type == "live") {
677 { drawOffer: V.GetOppCol(this.game.mycolor) }
682 // NOTE: observers don't know who offered rematch
683 this.rematchOffer = data.data ? "received" : "";
684 if (this.game.type == "live") {
687 { rematchOffer: V.GetOppCol(this.game.mycolor) }
692 // A game started, redirect if I'm playing in
693 const gameInfo = data.data;
694 const gameType = this.getGameType(gameInfo);
696 gameType == "live" &&
697 gameInfo.players.some(p => p.sid == this.st.user.sid)
699 this.addAndGotoLiveGame(gameInfo);
701 gameType == "corr" &&
702 gameInfo.players.some(p => p.id == this.st.user.id)
704 this.$router.push("/game/" + gameInfo.id);
706 this.rematchId = gameInfo.id;
707 document.getElementById("modalInfo").checked = true;
712 this.$refs["chatcomp"].newChat(data.data);
713 if (!document.getElementById("modalChat").checked)
714 document.getElementById("chatBtn").classList.add("somethingnew");
718 socketCloseListener: function() {
719 this.conn = new WebSocket(this.connexionString);
720 this.conn.addEventListener("message", this.socketMessageListener);
721 this.conn.addEventListener("close", this.socketCloseListener);
723 updateCorrGame: function(obj, callback) {
733 if (!!callback) callback();
738 sendLastate: function(target) {
740 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
741 this.game.score != "*" ||
742 this.drawOffer == "sent" ||
743 this.rematchOffer == "sent"
745 // Send our "last state" informations to opponent
746 const L = this.game.moves.length;
747 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
749 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
750 clock: this.game.clocks[myIdx],
751 // Since we played a move (or abort or resign),
752 // only drawOffer=="sent" is possible
753 drawSent: this.drawOffer == "sent",
754 rematchSent: this.rematchOffer == "sent",
755 score: this.game.score,
756 scoreMsg: this.game.scoreMsg,
758 initime: this.game.initime[1 - myIdx] //relevant only if I played
760 this.send("lastate", { data: myLastate, target: target });
762 this.send("lastate", { data: {nothing: true}, target: target });
765 // lastate was received, but maybe game wasn't ready yet:
766 processLastate: function() {
767 const data = this.lastate;
768 this.lastate = undefined; //security...
769 const L = this.game.moves.length;
770 if (data.movesCount > L) {
771 // Just got last move from him
772 this.$refs["basegame"].play(data.lastMove, "received", null, true);
773 this.processMove(data.lastMove, { clock: data.clock });
775 if (data.drawSent) this.drawOffer = "received";
776 if (data.rematchSent) this.rematchOffer = "received";
777 if (data.score != "*") {
779 if (this.game.score == "*")
780 this.gameOver(data.score, data.scoreMsg);
783 clickDraw: function() {
784 if (!this.game.mycolor) return; //I'm just spectator
785 if (["received", "threerep"].includes(this.drawOffer)) {
786 if (!confirm(this.st.tr["Accept draw?"])) return;
788 this.drawOffer == "received"
790 : "Three repetitions";
791 this.send("draw", { data: message });
792 this.gameOver("1/2", message);
793 } else if (this.drawOffer == "") {
794 // No effect if drawOffer == "sent"
795 if (this.game.mycolor != this.vr.turn) {
796 alert(this.st.tr["Draw offer only in your turn"]);
799 if (!confirm(this.st.tr["Offer draw?"])) return;
800 this.drawOffer = "sent";
801 this.send("drawoffer");
802 if (this.game.type == "live") {
805 { drawOffer: this.game.mycolor }
807 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
810 addAndGotoLiveGame: function(gameInfo, callback) {
811 const game = Object.assign(
815 // (other) Game infos: constant
816 fenStart: gameInfo.fen,
817 vname: this.game.vname,
819 // Game state (including FEN): will be updated
821 clocks: [-1, -1], //-1 = unstarted
822 initime: [0, 0], //initialized later
826 GameStorage.add(game, (err) => {
827 // No error expected.
829 if (this.st.settings.sound)
830 new Audio("/sounds/newgame.flac").play().catch(() => {});
831 if (!!callback) callback();
832 this.$router.push("/game/" + gameInfo.id);
836 clickRematch: function() {
837 if (!this.game.mycolor) return; //I'm just spectator
838 if (this.rematchOffer == "received") {
841 id: getRandString(), //ignored if corr
842 fen: V.GenRandInitFen(this.game.randomness),
843 players: this.game.players.reverse(),
845 cadence: this.game.cadence
847 const notifyNewGame = () => {
848 const oppsid = this.getOppsid(); //may be null
849 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
850 // To main Hall if corr game:
851 if (this.game.type == "corr")
852 this.send("newgame", { data: gameInfo });
853 // Also to MyGames page:
854 this.notifyMyGames("newgame", gameInfo);
856 if (this.game.type == "live")
857 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
864 // cid is useful to delete the challenge:
865 data: { gameInfo: gameInfo },
866 success: (response) => {
867 gameInfo.id = response.gameId;
869 this.$router.push("/game/" + response.gameId);
874 } else if (this.rematchOffer == "") {
875 this.rematchOffer = "sent";
876 this.send("rematchoffer", { data: true });
877 if (this.game.type == "live") {
880 { rematchOffer: this.game.mycolor }
882 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
883 } else if (this.rematchOffer == "sent") {
884 // Toggle rematch offer (on --> off)
885 this.rematchOffer = "";
886 this.send("rematchoffer", { data: false });
887 if (this.game.type == "live") {
892 } else this.updateCorrGame({ rematchOffer: 'n' });
895 abortGame: function() {
896 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
897 this.gameOver("?", "Stop");
901 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
903 this.send("resign", { data: this.game.mycolor });
904 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
905 const side = (this.game.mycolor == "w" ? "White" : "Black");
906 this.gameOver(score, side + " surrender");
908 loadGame: function(game, callback) {
909 this.vr = new V(game.fen);
910 const gtype = this.getGameType(game);
911 const tc = extractTime(game.cadence);
912 const myIdx = game.players.findIndex(p => {
913 return p.sid == this.st.user.sid || p.id == this.st.user.id;
915 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
916 if (!game.chats) game.chats = []; //live games don't have chat history
917 if (gtype == "corr") {
918 // NOTE: clocks in seconds, initime in milliseconds
919 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
920 game.clocks = [tc.mainTime, tc.mainTime];
921 const L = game.moves.length;
922 if (game.score == "*") {
923 // Set clocks + initime
924 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
925 if (L >= 1) game.initime[L % 2] = game.moves[L-1].played;
926 // NOTE: game.clocks shouldn't be computed right now:
927 // job will be done in re_setClocks() called soon below.
929 // Sort chat messages from newest to oldest
930 game.chats.sort((c1, c2) => {
931 return c2.added - c1.added;
933 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
934 // Did a chat message arrive after my last move?
936 if (L == 1 && myIdx == 0)
937 dtLastMove = game.moves[0].played;
940 // It's now white turn
941 dtLastMove = game.moves[L-1-(1-myIdx)].played;
944 dtLastMove = game.moves[L-1-myIdx].played;
947 if (dtLastMove < game.chats[0].added)
948 document.getElementById("chatBtn").classList.add("somethingnew");
950 // Now that we used idx and played, re-format moves as for live games
951 game.moves = game.moves.map(m => m.squares);
953 if (gtype == "live" && game.clocks[0] < 0) {
954 // Game is unstarted. clocks and initime are ignored until move 2
955 game.clocks = [tc.mainTime, tc.mainTime];
956 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
958 // I play in this live game
959 GameStorage.update(game.id, {
961 initime: game.initime
965 // TODO: merge next 2 "if" conditions
966 if (!!game.drawOffer) {
967 if (game.drawOffer == "t")
969 this.drawOffer = "threerep";
971 // Draw offered by any of the players:
972 if (myIdx < 0) this.drawOffer = "received";
974 // I play in this game:
976 (game.drawOffer == "w" && myIdx == 0) ||
977 (game.drawOffer == "b" && myIdx == 1)
979 this.drawOffer = "sent";
980 else this.drawOffer = "received";
984 if (!!game.rematchOffer) {
985 if (myIdx < 0) this.rematchOffer = "received";
987 // I play in this game:
989 (game.rematchOffer == "w" && myIdx == 0) ||
990 (game.rematchOffer == "b" && myIdx == 1)
992 this.rematchOffer = "sent";
993 else this.rematchOffer = "received";
996 this.repeat = {}; //reset: scan past moves' FEN:
998 let vr_tmp = new V(game.fenStart);
1000 game.moves.forEach(m => {
1001 playMove(m, vr_tmp);
1002 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1003 this.repeat[fenIdx] = this.repeat[fenIdx]
1004 ? this.repeat[fenIdx] + 1
1007 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1008 this.game = Object.assign(
1009 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1012 increment: tc.increment,
1014 // opponent sid not strictly required (or available), but easier
1015 // at least oppsid or oppid is available anyway:
1016 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1017 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1021 this.$refs["basegame"].re_setVariables(this.game);
1022 if (!this.gameIsLoading) {
1024 this.gotMoveIdx = game.moves.length - 1;
1025 // If we arrive here after 'nextGame' action, the board might be hidden
1026 let boardDiv = document.querySelector(".game");
1027 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1028 boardDiv.style.visibility = "visible";
1030 this.re_setClocks();
1031 this.$nextTick(() => {
1032 this.game.rendered = true;
1033 // Did lastate arrive before game was rendered?
1034 if (this.lastate) this.processLastate();
1036 if (this.lastateAsked) {
1037 this.lastateAsked = false;
1038 this.sendLastate(game.oppsid);
1040 if (this.gameIsLoading) {
1041 this.gameIsLoading = false;
1042 if (this.gotMoveIdx >= game.moves.length)
1043 // Some moves arrived meanwhile...
1044 this.askGameAgain();
1046 if (!!callback) callback();
1048 loadVariantThenGame: async function(game, callback) {
1049 await import("@/variants/" + game.vname + ".js")
1050 .then((vModule) => {
1051 window.V = vModule[game.vname + "Rules"];
1052 this.loadGame(game, callback);
1055 // 3 cases for loading a game:
1056 // - from indexedDB (running or completed live game I play)
1057 // - from server (one correspondance game I play[ed] or not)
1058 // - from remote peer (one live game I don't play, finished or not)
1059 fetchGame: function(callback) {
1060 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1061 // corr games identifiers are integers
1066 data: { gid: this.gameRef },
1068 res.game.moves.forEach(m => {
1069 m.squares = JSON.parse(m.squares);
1076 // Local game (or live remote)
1077 GameStorage.get(this.gameRef, callback);
1079 re_setClocks: function() {
1080 if (this.game.moves.length < 2 || this.game.score != "*") {
1081 // 1st move not completed yet, or game over: freeze time
1082 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1085 const currentTurn = this.vr.turn;
1086 const currentMovesCount = this.game.moves.length;
1087 const colorIdx = ["w", "b"].indexOf(currentTurn);
1089 this.game.clocks[colorIdx] -
1090 (Date.now() - this.game.initime[colorIdx]) / 1000;
1091 this.virtualClocks = [0, 1].map(i => {
1093 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1094 return ppt(this.game.clocks[i] - removeTime).split(':');
1096 this.clockUpdate = setInterval(
1100 this.game.moves.length > currentMovesCount ||
1101 this.game.score != "*"
1103 clearInterval(this.clockUpdate);
1106 currentTurn == "w" ? "0-1" : "1-0",
1113 ppt(Math.max(0, --countdown)).split(':')
1119 // Update variables and storage after a move:
1120 processMove: function(move, data) {
1121 if (!data) data = {};
1122 const moveCol = this.vr.turn;
1123 const doProcessMove = () => {
1124 const colorIdx = ["w", "b"].indexOf(moveCol);
1125 const nextIdx = 1 - colorIdx;
1126 const origMovescount = this.game.moves.length;
1127 let addTime = 0; //for live games
1128 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1129 if (this.drawOffer == "received")
1131 this.drawOffer = "";
1132 if (this.game.type == "live" && origMovescount >= 2) {
1133 const elapsed = Date.now() - this.game.initime[colorIdx];
1134 // elapsed time is measured in milliseconds
1135 addTime = this.game.increment - elapsed / 1000;
1138 // Update current game object:
1139 playMove(move, this.vr);
1140 // The move is played: stop clock
1141 clearInterval(this.clockUpdate);
1143 // Received move, score is computed in BaseGame, but maybe not yet.
1144 // ==> Compute it here, although this is redundant (TODO)
1145 data.score = this.vr.getCurrentScore();
1146 if (data.score != "*") this.gameOver(data.score);
1147 this.game.moves.push(move);
1148 this.game.fen = this.vr.getFen();
1149 if (this.game.type == "live") {
1150 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1151 else this.game.clocks[colorIdx] += addTime;
1153 // In corr games, just reset clock to mainTime:
1154 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1156 // NOTE: opponent's initime is reset after "gotmove" is received
1158 !this.game.mycolor ||
1159 moveCol != this.game.mycolor ||
1160 !!data.receiveMyMove
1162 this.game.initime[nextIdx] = Date.now();
1164 // If repetition detected, consider that a draw offer was received:
1165 const fenObj = this.vr.getFenForRepeat();
1166 this.repeat[fenObj] =
1167 !!this.repeat[fenObj]
1168 ? this.repeat[fenObj] + 1
1170 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1171 else if (this.drawOffer == "threerep") this.drawOffer = "";
1172 if (!!this.game.mycolor && !data.receiveMyMove) {
1173 // NOTE: 'var' to see that variable outside this block
1174 var filtered_move = getFilteredMove(move);
1176 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1177 // Notify turn on MyGames page:
1186 // Since corr games are stored at only one location, update should be
1187 // done only by one player for each move:
1189 !!this.game.mycolor &&
1190 !data.receiveMyMove &&
1191 (this.game.type == "live" || moveCol == this.game.mycolor)
1194 switch (this.drawOffer) {
1199 drawCode = this.game.mycolor;
1202 drawCode = V.GetOppCol(this.game.mycolor);
1205 if (this.game.type == "corr") {
1206 // corr: only move, fen and score
1207 this.updateCorrGame({
1210 squares: filtered_move,
1213 // Code "n" for "None" to force reset (otherwise it's ignored)
1214 drawOffer: drawCode || "n"
1218 const updateStorage = () => {
1219 GameStorage.update(this.gameRef, {
1221 move: filtered_move,
1222 moveIdx: origMovescount,
1223 clocks: this.game.clocks,
1224 initime: this.game.initime,
1228 // The active tab can update storage immediately
1229 if (!document.hidden) updateStorage();
1230 // Small random delay otherwise
1231 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1234 // Send move ("newmove" event) to people in the room (if our turn)
1235 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1237 move: filtered_move,
1238 index: origMovescount,
1239 // color is required to check if this is my move (if several tabs opened)
1241 cancelDrawOffer: this.drawOffer == ""
1243 if (this.game.type == "live")
1244 sendMove["clock"] = this.game.clocks[colorIdx];
1245 this.opponentGotMove = false;
1246 this.send("newmove", {data: sendMove});
1247 // If the opponent doesn't reply gotmove soon enough, re-send move:
1248 // Do this at most 2 times, because mpore would mean network issues,
1249 // opponent would then be expected to disconnect/reconnect.
1251 const currentUrl = document.location.href;
1252 this.retrySendmove = setInterval(
1256 this.opponentGotMove ||
1257 document.location.href != currentUrl //page change
1259 clearInterval(this.retrySendmove);
1262 const oppsid = this.getOppsid();
1264 // Opponent is disconnected: he'll ask last state
1265 clearInterval(this.retrySendmove);
1267 this.send("newmove", { data: sendMove, target: oppsid });
1275 // Not my move or I'm an observer: just start other player's clock
1276 this.re_setClocks();
1279 this.game.type == "corr" &&
1280 moveCol == this.game.mycolor &&
1283 let boardDiv = document.querySelector(".game");
1284 const afterSetScore = () => {
1286 if (this.st.settings.gotonext && this.nextIds.length > 0)
1287 this.showNextGame();
1289 // The board might have been hidden:
1290 if (boardDiv.style.visibility == "hidden")
1291 boardDiv.style.visibility = "visible";
1294 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1295 // We may play several moves in a row: in case of, remove listener:
1296 let elClone = el.cloneNode(true);
1297 el.parentNode.replaceChild(elClone, el);
1298 elClone.addEventListener(
1301 document.getElementById("modalConfirm").checked = false;
1302 if (!!data.score && data.score != "*")
1304 this.gameOver(data.score, null, afterSetScore);
1305 else afterSetScore();
1308 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1309 V.PlayOnBoard(this.vr.board, move);
1310 const position = this.vr.getBaseFen();
1311 V.UndoOnBoard(this.vr.board, move);
1312 if (["all","byrow"].includes(V.ShowMoves)) {
1313 this.curDiag = getDiagram({
1315 orientation: V.CanFlip ? this.game.mycolor : "w"
1317 document.querySelector("#confirmDiv > .card").style.width =
1318 boardDiv.offsetWidth + "px";
1320 // Incomplete information: just ask confirmation
1321 // Hide the board, because otherwise it could reveal infos
1322 boardDiv.style.visibility = "hidden";
1323 this.moveNotation = getFullNotation(move);
1325 document.getElementById("modalConfirm").checked = true;
1329 if (!!data.score && data.score != "*")
1330 this.gameOver(data.score, null, doProcessMove);
1331 else doProcessMove();
1334 cancelMove: function() {
1335 let boardDiv = document.querySelector(".game");
1336 if (boardDiv.style.visibility == "hidden")
1337 boardDiv.style.visibility = "visible";
1338 document.getElementById("modalConfirm").checked = false;
1339 this.$refs["basegame"].cancelLastMove();
1341 // In corr games, callback to change page only after score is set:
1342 gameOver: function(score, scoreMsg, callback) {
1343 this.game.score = score;
1344 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1345 this.game.scoreMsg = scoreMsg;
1346 this.$set(this.game, "scoreMsg", scoreMsg);
1347 const myIdx = this.game.players.findIndex(p => {
1348 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1351 // OK, I play in this game
1356 if (this.game.type == "live") {
1357 GameStorage.update(this.gameRef, scoreObj);
1358 if (!!callback) callback();
1360 else this.updateCorrGame(scoreObj, callback);
1361 // Notify the score to main Hall. TODO: only one player (currently double send)
1362 this.send("result", { gid: this.game.id, score: score });
1363 // Also to MyGames page (TODO: doubled as well...)
1372 else if (!!callback) callback();
1378 <style lang="sass" scoped>
1384 background-color: lightgreen
1396 @media screen and (min-width: 768px)
1399 @media screen and (max-width: 767px)
1404 display: inline-block
1408 display: inline-block
1410 display: inline-flex
1414 @media screen and (max-width: 767px)
1417 @media screen and (max-width: 767px)
1420 @media screen and (min-width: 768px)
1432 background-color: #edda99
1434 display: inline-block
1443 display: inline-block
1456 animation: blink-animation 2s steps(3, start) infinite
1457 @keyframes blink-animation
1462 display: inline-block
1474 .draw-sent, .draw-sent:hover
1475 background-color: lightyellow
1477 .draw-received, .draw-received:hover
1478 background-color: lightgreen
1480 .draw-threerep, .draw-threerep:hover
1481 background-color: #e4d1fc
1483 .rematch-sent, .rematch-sent:hover
1484 background-color: lightyellow
1486 .rematch-received, .rematch-received:hover
1487 background-color: lightgreen
1490 background-color: #c5fefe
1503 background-color: lightgreen
1505 background-color: red