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";
157 // rid = remote (socket) ID
162 game: {}, //passed to BaseGame
163 // virtualClocks will be initialized from true game.clocks
165 vr: null, //"variant rules" object initialized from FEN
170 people: {}, //players + observers
171 lastate: undefined, //used if opponent send lastate before game is ready
172 repeat: {}, //detect position repetition
173 curDiag: "", //for corr moves confirmation
175 roomInitialized: false,
176 // If newmove has wrong index: ask fullgame again:
178 gameIsLoading: false,
179 // If asklastate got no reply, ask again:
181 gotMoveIdx: -1, //last move index received
182 // If newmove got no pingback, send again:
183 opponentGotMove: false,
185 // Incomplete info games: show move played
187 // Intervals from setInterval():
191 // Related to (killing of) self multi-connects:
197 $route: function(to, from) {
198 if (from.params["id"] != to.params["id"]) {
199 // Change everything:
200 this.cleanBeforeDestroy();
201 let boardDiv = document.querySelector(".game");
203 // In case of incomplete information variant:
204 boardDiv.style.visibility = "hidden";
208 this.gameRef.id = to.params["id"];
209 this.gameRef.rid = to.query["rid"];
210 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
215 // NOTE: some redundant code with Hall.vue (mostly related to people array)
216 created: function() {
219 mounted: function() {
220 document.addEventListener('visibilitychange', this.visibilityChange);
221 ["chatWrap", "infoDiv"].forEach(eltName => {
222 document.getElementById(eltName)
223 .addEventListener("click", processModalClick);
225 if ("ontouchstart" in window) {
226 // Disable tooltips on smartphones:
227 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
228 elt.classList.remove("tooltip");
232 beforeDestroy: function() {
233 document.removeEventListener('visibilitychange', this.visibilityChange);
234 this.cleanBeforeDestroy();
237 visibilityChange: function() {
238 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
240 document.visibilityState == "visible"
245 atCreation: function() {
246 // 0] (Re)Set variables
247 this.gameRef.id = this.$route.params["id"];
248 // rid = remote ID to find an observed live game,
249 // next = next corr games IDs to navigate faster
250 // (Both might be undefined)
251 this.gameRef.rid = this.$route.query["rid"];
252 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
253 // Always add myself to players' list
254 const my = this.st.user;
265 players: [{ name: "" }, { name: "" }],
269 let chatComp = this.$refs["chatcomp"];
270 if (!!chatComp) chatComp.chats = [];
271 this.virtualClocks = [[0,0], [0,0]];
274 this.lastateAsked = false;
275 this.rematchOffer = "";
276 this.lastate = undefined;
277 this.roomInitialized = false;
278 this.askGameTime = 0;
279 this.gameIsLoading = false;
280 this.gotLastate = false;
281 this.gotMoveIdx = -1;
282 this.opponentGotMove = false;
283 this.askLastate = null;
284 this.retrySendmove = null;
285 this.clockUpdate = null;
286 this.newConnect = {};
288 // 1] Initialize connection
289 this.connexionString =
298 // Discard potential "/?next=[...]" for page indication:
299 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
300 this.conn = new WebSocket(this.connexionString);
301 this.conn.onmessage = this.socketMessageListener;
302 this.conn.onclose = this.socketCloseListener;
303 // Socket init required before loading remote game:
304 const socketInit = callback => {
305 if (!!this.conn && this.conn.readyState == 1)
309 // Socket not ready yet (initial loading)
310 // NOTE: it's important to call callback without arguments,
311 // otherwise first arg is Websocket object and fetchGame fails.
312 this.conn.onopen = () => callback();
314 if (!this.gameRef.rid)
315 // Game stored locally or on server
316 this.fetchGame(null, () => socketInit(this.roomInit));
318 // Game stored remotely: need socket to retrieve it
319 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
320 // --> It will be given when receiving "fullgame" socket event.
321 socketInit(this.fetchGame);
323 cleanBeforeDestroy: function() {
324 if (!!this.askLastate)
325 clearInterval(this.askLastate);
326 if (!!this.retrySendmove)
327 clearInterval(this.retrySendmove);
328 if (!!this.clockUpdate)
329 clearInterval(this.clockUpdate);
330 this.send("disconnect");
332 roomInit: function() {
333 if (!this.roomInitialized) {
334 // Notify the room only now that I connected, because
335 // messages might be lost otherwise (if game loading is slow)
336 this.send("connect");
337 this.send("pollclients");
338 // We may ask fullgame several times if some moves are lost,
339 // but room should be init only once:
340 this.roomInitialized = true;
343 send: function(code, obj) {
345 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
347 isConnected: function(index) {
348 const player = this.game.players[index];
349 // Is it me ? In this case no need to bother with focus
350 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
351 // Still have to check for name (because of potential multi-accounts
352 // on same browser, although this should be rare...)
353 return (!this.st.user.name || this.st.user.name == player.name);
354 // Try to find a match in people:
358 Object.keys(this.people).some(sid =>
359 sid == player.sid && this.people[sid].focus)
364 Object.values(this.people).some(p =>
365 p.id == player.id && p.focus)
369 getOppsid: function() {
370 let oppsid = this.game.oppsid;
372 oppsid = Object.keys(this.people).find(
373 sid => this.people[sid].id == this.game.oppid
376 // oppsid is useful only if opponent is online:
377 if (!!oppsid && !!this.people[oppsid]) return oppsid;
380 toggleChat: function() {
381 if (document.getElementById("modalChat").checked)
383 document.getElementById("inputChat").focus();
384 // TODO: next line is only required when exiting chat,
385 // but the event for now isn't well detected.
386 document.getElementById("chatBtn").classList.remove("somethingnew");
388 processChat: function(chat) {
389 this.send("newchat", { data: chat });
390 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
391 if (this.game.type == "corr" && this.st.user.id > 0)
392 this.updateCorrGame({ chat: chat });
394 clearChat: function() {
395 // Nothing more to do if game is live (chats not recorded)
396 if (this.game.type == "corr") {
397 if (!!this.game.mycolor) {
401 { data: { gid: this.game.id } }
404 this.$set(this.game, "chats", []);
407 getGameType: function(game) {
408 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
410 // Notify something after a new move (to opponent and me on MyGames page)
411 notifyMyGames: function(thing, data) {
416 targets: this.game.players.map(p => {
417 return { sid: p.sid, id: p.id };
422 showNextGame: function() {
423 // Did I play in current game? If not, add it to nextIds list
424 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
425 this.nextIds.unshift(this.game.id);
426 const nextGid = this.nextIds.pop();
428 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
430 askGameAgain: function() {
431 this.gameIsLoading = true;
432 const currentUrl = document.location.href;
433 const doAskGame = () => {
434 if (document.location.href != currentUrl) return; //page change
435 if (!this.gameRef.rid)
436 // This is my game: just reload.
439 // Just ask fullgame again (once!), this is much simpler.
440 // If this fails, the user could just reload page :/
441 this.send("askfullgame", { target: this.gameRef.rid });
443 // Delay of at least 2s between two game requests
444 const now = Date.now();
445 const delay = Math.max(2000 - (now - this.askGameTime), 0);
446 this.askGameTime = now;
447 setTimeout(doAskGame, delay);
449 socketMessageListener: function(msg) {
450 if (!this.conn) return;
451 const data = JSON.parse(msg.data);
454 data.sockIds.forEach(sid => {
455 if (sid != this.st.user.sid) {
456 this.people[sid] = { focus: true };
457 this.send("askidentity", { target: sid });
462 if (!this.people[data.from]) {
463 this.people[data.from] = { focus: true };
464 this.newConnect[data.from] = true; //for self multi-connects tests
465 this.send("askidentity", { target: data.from });
469 this.$delete(this.people, data.from);
472 let player = this.people[data.from];
475 this.$forceUpdate(); //TODO: shouldn't be required
480 let player = this.people[data.from];
482 player.focus = false;
483 this.$forceUpdate(); //TODO: shouldn't be required
488 // I logged in elsewhere:
490 alert(this.st.tr["New connexion detected: tab now offline"]);
492 case "askidentity": {
493 // Request for identification
495 // Decompose to avoid revealing email
496 name: this.st.user.name,
497 sid: this.st.user.sid,
500 this.send("identity", { data: me, target: data.from });
504 const user = data.data;
505 let player = this.people[user.sid];
506 // player.focus is already set
507 player.name = user.name;
509 this.$forceUpdate(); //TODO: shouldn't be required
510 // If I multi-connect, kill current connexion if no mark (I'm older)
511 if (this.newConnect[user.sid]) {
514 user.id == this.st.user.id &&
515 user.sid != this.st.user.sid &&
516 !this.killed[this.st.user.sid]
518 this.send("killme", { sid: this.st.user.sid });
519 this.killed[this.st.user.sid] = true;
521 delete this.newConnect[user.sid];
523 if (!this.killed[this.st.user.sid]) {
524 // Ask potentially missed last state, if opponent and I play
526 !!this.game.mycolor &&
527 this.game.type == "live" &&
528 this.game.score == "*" &&
529 this.game.players.some(p => p.sid == user.sid)
531 this.send("asklastate", { target: user.sid });
533 this.askLastate = setInterval(
535 // Ask at most 3 times:
536 // if no reply after that there should be a network issue.
540 !!this.people[user.sid]
542 this.send("asklastate", { target: user.sid });
545 clearInterval(this.askLastate);
555 // Send current (live) game if not asked by any of the players
557 this.game.type == "live" &&
558 this.game.players.every(p => p.sid != data.from[0])
563 players: this.game.players,
565 cadence: this.game.cadence,
566 score: this.game.score,
567 rid: this.st.user.sid //useful in Hall if I'm an observer
569 this.send("game", { data: myGame, target: data.from });
573 const gameToSend = Object.keys(this.game)
576 "id","fen","players","vid","cadence","fenStart","vname",
577 "moves","clocks","initime","score","drawOffer","rematchOffer"
581 obj[k] = this.game[k];
586 this.send("fullgame", { data: gameToSend, target: data.from });
589 // Callback "roomInit" to poll clients only after game is loaded
590 this.fetchGame(data.data, this.roomInit);
593 // Sending informative last state if I played a move or score != "*"
594 // If the game or moves aren't loaded yet, delay the sending:
595 if (!this.game || !this.game.moves) this.lastateAsked = true;
596 else this.sendLastate(data.from);
599 // Got opponent infos about last move
600 this.gotLastate = true;
601 if (!data.data.nothing) {
602 this.lastate = data.data;
603 if (this.game.rendered)
604 // Game is rendered (Board component)
605 this.processLastate();
606 // Else: will be processed when game is ready
611 const movePlus = data.data;
612 const movesCount = this.game.moves.length;
613 if (movePlus.index > movesCount) {
614 // This can only happen if I'm an observer and missed a move.
615 if (this.gotMoveIdx < movePlus.index)
616 this.gotMoveIdx = movePlus.index;
617 if (!this.gameIsLoading) this.askGameAgain();
621 movePlus.index < movesCount ||
622 this.gotMoveIdx >= movePlus.index
624 // Opponent re-send but we already have the move:
625 // (maybe he didn't receive our pingback...)
626 this.send("gotmove", {data: movePlus.index, target: data.from});
628 this.gotMoveIdx = movePlus.index;
629 const receiveMyMove = (movePlus.color == this.game.mycolor);
630 if (!receiveMyMove && !!this.game.mycolor)
631 // Notify opponent that I got the move:
632 this.send("gotmove", {data: movePlus.index, target: data.from});
633 if (movePlus.cancelDrawOffer) {
634 // Opponent refuses draw
636 // NOTE for corr games: drawOffer reset by player in turn
638 this.game.type == "live" &&
639 !!this.game.mycolor &&
642 GameStorage.update(this.gameRef.id, { drawOffer: "" });
645 this.$refs["basegame"].play(movePlus.move, "received", null, true);
649 clock: movePlus.clock,
650 receiveMyMove: receiveMyMove
658 this.opponentGotMove = true;
659 // Now his clock starts running:
660 const oppIdx = ['w','b'].indexOf(this.vr.turn);
661 this.game.initime[oppIdx] = Date.now();
666 const score = data.side == "b" ? "1-0" : "0-1";
667 const side = data.side == "w" ? "White" : "Black";
668 this.gameOver(score, side + " surrender");
671 this.gameOver("?", "Stop");
674 this.gameOver("1/2", data.data);
677 // NOTE: observers don't know who offered draw
678 this.drawOffer = "received";
681 // NOTE: observers don't know who offered rematch
682 this.rematchOffer = data.data ? "received" : "";
685 // A game started, redirect if I'm playing in
686 const gameInfo = data.data;
687 const gameType = this.getGameType(gameInfo);
689 gameType == "live" &&
690 gameInfo.players.some(p => p.sid == this.st.user.sid)
692 this.addAndGotoLiveGame(gameInfo);
694 gameType == "corr" &&
695 gameInfo.players.some(p => p.id == this.st.user.id)
697 this.$router.push("/game/" + gameInfo.id);
700 if (gameInfo.cadence.indexOf('d') === -1) {
702 // Select sid of any of the online players:
704 gameInfo.players.forEach(p => {
705 if (!!this.people[p.sid]) onlineSid.push(p.sid);
707 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
709 this.rematchId = gameInfo.id + urlRid;
710 document.getElementById("modalInfo").checked = true;
715 this.$refs["chatcomp"].newChat(data.data);
716 if (!document.getElementById("modalChat").checked)
717 document.getElementById("chatBtn").classList.add("somethingnew");
721 socketCloseListener: function() {
722 this.conn = new WebSocket(this.connexionString);
723 this.conn.addEventListener("message", this.socketMessageListener);
724 this.conn.addEventListener("close", this.socketCloseListener);
726 updateCorrGame: function(obj, callback) {
732 gid: this.gameRef.id,
736 if (!!callback) callback();
741 sendLastate: function(target) {
743 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
744 this.game.score != "*" ||
745 this.drawOffer == "sent" ||
746 this.rematchOffer == "sent"
748 // Send our "last state" informations to opponent
749 const L = this.game.moves.length;
750 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
752 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
753 clock: this.game.clocks[myIdx],
754 // Since we played a move (or abort or resign),
755 // only drawOffer=="sent" is possible
756 drawSent: this.drawOffer == "sent",
757 rematchSent: this.rematchOffer == "sent",
758 score: this.game.score,
759 scoreMsg: this.game.scoreMsg,
761 initime: this.game.initime[1 - myIdx] //relevant only if I played
763 this.send("lastate", { data: myLastate, target: target });
765 this.send("lastate", { data: {nothing: true}, target: target });
768 // lastate was received, but maybe game wasn't ready yet:
769 processLastate: function() {
770 const data = this.lastate;
771 this.lastate = undefined; //security...
772 const L = this.game.moves.length;
773 if (data.movesCount > L) {
774 // Just got last move from him
775 this.$refs["basegame"].play(data.lastMove, "received", null, true);
776 this.processMove(data.lastMove, { clock: data.clock });
778 if (data.drawSent) this.drawOffer = "received";
779 if (data.rematchSent) this.rematchOffer = "received";
780 if (data.score != "*") {
782 if (this.game.score == "*")
783 this.gameOver(data.score, data.scoreMsg);
786 clickDraw: function() {
787 if (!this.game.mycolor) return; //I'm just spectator
788 if (["received", "threerep"].includes(this.drawOffer)) {
789 if (!confirm(this.st.tr["Accept draw?"])) return;
791 this.drawOffer == "received"
793 : "Three repetitions";
794 this.send("draw", { data: message });
795 this.gameOver("1/2", message);
796 } else if (this.drawOffer == "") {
797 // No effect if drawOffer == "sent"
798 if (this.game.mycolor != this.vr.turn) {
799 alert(this.st.tr["Draw offer only in your turn"]);
802 if (!confirm(this.st.tr["Offer draw?"])) return;
803 this.drawOffer = "sent";
804 this.send("drawoffer");
805 if (this.game.type == "live") {
808 { drawOffer: this.game.mycolor }
810 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
813 addAndGotoLiveGame: function(gameInfo, callback) {
814 const game = Object.assign(
818 // (other) Game infos: constant
819 fenStart: gameInfo.fen,
820 vname: this.game.vname,
822 // Game state (including FEN): will be updated
824 clocks: [-1, -1], //-1 = unstarted
825 initime: [0, 0], //initialized later
829 GameStorage.add(game, (err) => {
830 // No error expected.
832 if (this.st.settings.sound)
833 new Audio("/sounds/newgame.flac").play().catch(() => {});
834 if (!!callback) callback();
835 this.$router.push("/game/" + gameInfo.id);
839 clickRematch: function() {
840 if (!this.game.mycolor) return; //I'm just spectator
841 if (this.rematchOffer == "received") {
844 id: getRandString(), //ignored if corr
845 fen: V.GenRandInitFen(this.game.randomness),
846 players: this.game.players.reverse(),
848 cadence: this.game.cadence
850 const notifyNewGame = () => {
851 const oppsid = this.getOppsid(); //may be null
852 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
853 // To main Hall if corr game:
854 if (this.game.type == "corr")
855 this.send("newgame", { data: gameInfo });
856 // Also to MyGames page:
857 this.notifyMyGames("newgame", gameInfo);
859 if (this.game.type == "live")
860 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
867 // cid is useful to delete the challenge:
868 data: { gameInfo: gameInfo },
869 success: (response) => {
870 gameInfo.id = response.gameId;
872 this.$router.push("/game/" + response.gameId);
877 } else if (this.rematchOffer == "") {
878 this.rematchOffer = "sent";
879 this.send("rematchoffer", { data: true });
880 if (this.game.type == "live") {
883 { rematchOffer: this.game.mycolor }
885 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
886 } else if (this.rematchOffer == "sent") {
887 // Toggle rematch offer (on --> off)
888 this.rematchOffer = "";
889 this.send("rematchoffer", { data: false });
890 if (this.game.type == "live") {
895 } else this.updateCorrGame({ rematchOffer: 'n' });
898 abortGame: function() {
899 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
900 this.gameOver("?", "Stop");
904 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
906 this.send("resign", { data: this.game.mycolor });
907 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
908 const side = this.game.mycolor == "w" ? "White" : "Black";
909 this.gameOver(score, side + " surrender");
911 // 3 cases for loading a game:
912 // - from indexedDB (running or completed live game I play)
913 // - from server (one correspondance game I play[ed] or not)
914 // - from remote peer (one live game I don't play, finished or not)
915 loadGame: function(game, callback) {
916 this.vr = new V(game.fen);
917 const gtype = this.getGameType(game);
918 const tc = extractTime(game.cadence);
919 const myIdx = game.players.findIndex(p => {
920 return p.sid == this.st.user.sid || p.id == this.st.user.id;
922 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
923 if (!game.chats) game.chats = []; //live games don't have chat history
924 if (gtype == "corr") {
925 // NOTE: clocks in seconds, initime in milliseconds
926 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
927 game.clocks = [tc.mainTime, tc.mainTime];
928 const L = game.moves.length;
929 if (game.score == "*") {
930 // Set clocks + initime
931 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
932 if (L >= 1) game.initime[L % 2] = game.moves[L-1].played;
933 // NOTE: game.clocks shouldn't be computed right now:
934 // job will be done in re_setClocks() called soon below.
936 // Sort chat messages from newest to oldest
937 game.chats.sort((c1, c2) => {
938 return c2.added - c1.added;
940 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
941 // Did a chat message arrive after my last move?
943 if (L == 1 && myIdx == 0)
944 dtLastMove = game.moves[0].played;
947 // It's now white turn
948 dtLastMove = game.moves[L-1-(1-myIdx)].played;
951 dtLastMove = game.moves[L-1-myIdx].played;
954 if (dtLastMove < game.chats[0].added)
955 document.getElementById("chatBtn").classList.add("somethingnew");
957 // Now that we used idx and played, re-format moves as for live games
958 game.moves = game.moves.map(m => m.squares);
960 if (gtype == "live" && game.clocks[0] < 0) {
961 // Game is unstarted. clocks and initime are ignored until move 2
962 game.clocks = [tc.mainTime, tc.mainTime];
963 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
965 // I play in this live game
966 GameStorage.update(game.id, {
968 initime: game.initime
972 // TODO: merge next 2 "if" conditions
973 if (!!game.drawOffer) {
974 if (game.drawOffer == "t")
976 this.drawOffer = "threerep";
978 // Draw offered by any of the players:
979 if (myIdx < 0) this.drawOffer = "received";
981 // I play in this game:
983 (game.drawOffer == "w" && myIdx == 0) ||
984 (game.drawOffer == "b" && myIdx == 1)
986 this.drawOffer = "sent";
987 else this.drawOffer = "received";
991 if (!!game.rematchOffer) {
992 if (myIdx < 0) this.rematchOffer = "received";
994 // I play in this game:
996 (game.rematchOffer == "w" && myIdx == 0) ||
997 (game.rematchOffer == "b" && myIdx == 1)
999 this.rematchOffer = "sent";
1000 else this.rematchOffer = "received";
1003 this.repeat = {}; //reset: scan past moves' FEN:
1005 let vr_tmp = new V(game.fenStart);
1007 game.moves.forEach(m => {
1008 playMove(m, vr_tmp);
1009 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1010 this.repeat[fenIdx] = this.repeat[fenIdx]
1011 ? this.repeat[fenIdx] + 1
1014 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1015 this.game = Object.assign(
1016 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1019 increment: tc.increment,
1021 // opponent sid not strictly required (or available), but easier
1022 // at least oppsid or oppid is available anyway:
1023 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1024 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1028 this.$refs["basegame"].re_setVariables(this.game);
1029 if (!this.gameIsLoading) {
1031 this.gotMoveIdx = game.moves.length - 1;
1032 // If we arrive here after 'nextGame' action, the board might be hidden
1033 let boardDiv = document.querySelector(".game");
1034 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1035 boardDiv.style.visibility = "visible";
1037 this.re_setClocks();
1038 this.$nextTick(() => {
1039 this.game.rendered = true;
1040 // Did lastate arrive before game was rendered?
1041 if (this.lastate) this.processLastate();
1043 if (this.lastateAsked) {
1044 this.lastateAsked = false;
1045 this.sendLastate(game.oppsid);
1047 if (this.gameIsLoading) {
1048 this.gameIsLoading = false;
1049 if (this.gotMoveIdx >= game.moves.length)
1050 // Some moves arrived meanwhile...
1051 this.askGameAgain();
1053 if (!!callback) callback();
1055 fetchGame: function(game, callback) {
1056 const afterRetrieval = async (game) => {
1057 await import("@/variants/" + game.vname + ".js")
1058 .then((vModule) => {
1059 window.V = vModule[game.vname + "Rules"];
1060 this.loadGame(game, callback);
1064 afterRetrieval(game);
1067 if (this.gameRef.rid)
1068 // Remote live game: forgetting about callback func... (TODO: design)
1069 this.send("askfullgame", { target: this.gameRef.rid });
1071 // Local or corr game on server.
1072 // NOTE: afterRetrieval() is never called if game not found
1073 const gid = this.gameRef.id;
1074 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1075 // corr games identifiers are integers
1082 res.game.moves.forEach(m => {
1083 m.squares = JSON.parse(m.squares);
1085 afterRetrieval(res.game);
1092 GameStorage.get(this.gameRef.id, afterRetrieval);
1095 re_setClocks: function() {
1096 if (this.game.moves.length < 2 || this.game.score != "*") {
1097 // 1st move not completed yet, or game over: freeze time
1098 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1101 const currentTurn = this.vr.turn;
1102 const currentMovesCount = this.game.moves.length;
1103 const colorIdx = ["w", "b"].indexOf(currentTurn);
1105 this.game.clocks[colorIdx] -
1106 (Date.now() - this.game.initime[colorIdx]) / 1000;
1107 this.virtualClocks = [0, 1].map(i => {
1109 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1110 return ppt(this.game.clocks[i] - removeTime).split(':');
1112 this.clockUpdate = setInterval(
1116 this.game.moves.length > currentMovesCount ||
1117 this.game.score != "*"
1119 clearInterval(this.clockUpdate);
1122 currentTurn == "w" ? "0-1" : "1-0",
1129 ppt(Math.max(0, --countdown)).split(':')
1135 // Update variables and storage after a move:
1136 processMove: function(move, data) {
1137 if (!data) data = {};
1138 const moveCol = this.vr.turn;
1139 const doProcessMove = () => {
1140 const colorIdx = ["w", "b"].indexOf(moveCol);
1141 const nextIdx = 1 - colorIdx;
1142 const origMovescount = this.game.moves.length;
1143 let addTime = 0; //for live games
1144 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1145 if (this.drawOffer == "received")
1147 this.drawOffer = "";
1148 if (this.game.type == "live" && origMovescount >= 2) {
1149 const elapsed = Date.now() - this.game.initime[colorIdx];
1150 // elapsed time is measured in milliseconds
1151 addTime = this.game.increment - elapsed / 1000;
1154 // Update current game object:
1155 playMove(move, this.vr);
1156 // The move is played: stop clock
1157 clearInterval(this.clockUpdate);
1159 // Received move, score has not been computed in BaseGame (!!noemit)
1160 const score = this.vr.getCurrentScore();
1161 if (score != "*") this.gameOver(score);
1163 this.game.moves.push(move);
1164 this.game.fen = this.vr.getFen();
1165 if (this.game.type == "live") {
1166 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1167 else this.game.clocks[colorIdx] += addTime;
1169 // In corr games, just reset clock to mainTime:
1170 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1172 // NOTE: opponent's initime is reset after "gotmove" is received
1174 !this.game.mycolor ||
1175 moveCol != this.game.mycolor ||
1176 !!data.receiveMyMove
1178 this.game.initime[nextIdx] = Date.now();
1180 // If repetition detected, consider that a draw offer was received:
1181 const fenObj = this.vr.getFenForRepeat();
1182 this.repeat[fenObj] =
1183 !!this.repeat[fenObj]
1184 ? this.repeat[fenObj] + 1
1186 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1187 else if (this.drawOffer == "threerep") this.drawOffer = "";
1188 if (!!this.game.mycolor && !data.receiveMyMove) {
1189 // NOTE: 'var' to see that variable outside this block
1190 var filtered_move = getFilteredMove(move);
1192 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1193 // Notify turn on MyGames page:
1197 gid: this.gameRef.id,
1202 // Since corr games are stored at only one location, update should be
1203 // done only by one player for each move:
1205 !!this.game.mycolor &&
1206 !data.receiveMyMove &&
1207 (this.game.type == "live" || moveCol == this.game.mycolor)
1210 switch (this.drawOffer) {
1215 drawCode = this.game.mycolor;
1218 drawCode = V.GetOppCol(this.game.mycolor);
1221 if (this.game.type == "corr") {
1222 // corr: only move, fen and score
1223 this.updateCorrGame({
1226 squares: filtered_move,
1229 // Code "n" for "None" to force reset (otherwise it's ignored)
1230 drawOffer: drawCode || "n"
1234 const updateStorage = () => {
1235 GameStorage.update(this.gameRef.id, {
1237 move: filtered_move,
1238 moveIdx: origMovescount,
1239 clocks: this.game.clocks,
1240 initime: this.game.initime,
1244 // The active tab can update storage immediately
1245 if (!document.hidden) updateStorage();
1246 // Small random delay otherwise
1247 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1250 // Send move ("newmove" event) to people in the room (if our turn)
1251 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1253 move: filtered_move,
1254 index: origMovescount,
1255 // color is required to check if this is my move (if several tabs opened)
1257 cancelDrawOffer: this.drawOffer == ""
1259 if (this.game.type == "live")
1260 sendMove["clock"] = this.game.clocks[colorIdx];
1261 this.opponentGotMove = false;
1262 this.send("newmove", {data: sendMove});
1263 // If the opponent doesn't reply gotmove soon enough, re-send move:
1264 // Do this at most 2 times, because mpore would mean network issues,
1265 // opponent would then be expected to disconnect/reconnect.
1267 const currentUrl = document.location.href;
1268 this.retrySendmove = setInterval(
1272 this.opponentGotMove ||
1273 document.location.href != currentUrl //page change
1275 clearInterval(this.retrySendmove);
1278 const oppsid = this.getOppsid();
1280 // Opponent is disconnected: he'll ask last state
1281 clearInterval(this.retrySendmove);
1283 this.send("newmove", { data: sendMove, target: oppsid });
1291 // Not my move or I'm an observer: just start other player's clock
1292 this.re_setClocks();
1295 this.game.type == "corr" &&
1296 moveCol == this.game.mycolor &&
1299 let boardDiv = document.querySelector(".game");
1300 const afterSetScore = () => {
1302 if (this.st.settings.gotonext && this.nextIds.length > 0)
1303 this.showNextGame();
1305 // The board might have been hidden:
1306 if (boardDiv.style.visibility == "hidden")
1307 boardDiv.style.visibility = "visible";
1310 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1311 // We may play several moves in a row: in case of, remove listener:
1312 let elClone = el.cloneNode(true);
1313 el.parentNode.replaceChild(elClone, el);
1314 elClone.addEventListener(
1317 document.getElementById("modalConfirm").checked = false;
1318 if (!!data.score && data.score != "*")
1320 this.gameOver(data.score, null, afterSetScore);
1321 else afterSetScore();
1324 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1325 V.PlayOnBoard(this.vr.board, move);
1326 const position = this.vr.getBaseFen();
1327 V.UndoOnBoard(this.vr.board, move);
1328 if (["all","byrow"].includes(V.ShowMoves)) {
1329 this.curDiag = getDiagram({
1331 orientation: V.CanFlip ? this.game.mycolor : "w"
1333 document.querySelector("#confirmDiv > .card").style.width =
1334 boardDiv.offsetWidth + "px";
1336 // Incomplete information: just ask confirmation
1337 // Hide the board, because otherwise it could reveal infos
1338 boardDiv.style.visibility = "hidden";
1339 this.moveNotation = getFullNotation(move);
1341 document.getElementById("modalConfirm").checked = true;
1345 if (!!data.score && data.score != "*")
1346 this.gameOver(data.score, null, doProcessMove);
1347 else doProcessMove();
1350 cancelMove: function() {
1351 let boardDiv = document.querySelector(".game");
1352 if (boardDiv.style.visibility == "hidden")
1353 boardDiv.style.visibility = "visible";
1354 document.getElementById("modalConfirm").checked = false;
1355 this.$refs["basegame"].cancelLastMove();
1357 // In corr games, callback to change page only after score is set:
1358 gameOver: function(score, scoreMsg, callback) {
1359 this.game.score = score;
1360 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1361 this.game.scoreMsg = scoreMsg;
1362 this.$set(this.game, "scoreMsg", scoreMsg);
1363 const myIdx = this.game.players.findIndex(p => {
1364 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1367 // OK, I play in this game
1372 if (this.game.type == "live") {
1373 GameStorage.update(this.gameRef.id, scoreObj);
1374 if (!!callback) callback();
1376 else this.updateCorrGame(scoreObj, callback);
1377 // Notify the score to main Hall. TODO: only one player (currently double send)
1378 this.send("result", { gid: this.game.id, score: score });
1379 // Also to MyGames page (TODO: doubled as well...)
1383 gid: this.gameRef.id,
1388 else if (!!callback) callback();
1394 <style lang="sass" scoped>
1400 background-color: lightgreen
1412 @media screen and (min-width: 768px)
1415 @media screen and (max-width: 767px)
1420 display: inline-block
1424 display: inline-block
1426 display: inline-flex
1430 @media screen and (max-width: 767px)
1433 @media screen and (max-width: 767px)
1436 @media screen and (min-width: 768px)
1448 background-color: #edda99
1450 display: inline-block
1459 display: inline-block
1472 animation: blink-animation 2s steps(3, start) infinite
1473 @keyframes blink-animation
1478 display: inline-block
1490 .draw-sent, .draw-sent:hover
1491 background-color: lightyellow
1493 .draw-received, .draw-received:hover
1494 background-color: lightgreen
1496 .draw-threerep, .draw-threerep:hover
1497 background-color: #e4d1fc
1499 .rematch-sent, .rematch-sent:hover
1500 background-color: lightyellow
1502 .rematch-received, .rematch-received:hover
1503 background-color: lightgreen
1506 background-color: #c5fefe
1519 background-color: lightgreen
1521 background-color: red