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 loadGame fails.
312 this.conn.onopen = () => callback();
314 if (!this.gameRef.rid)
315 // Game stored locally or on server
316 this.loadGame(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.loadGame);
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.loadGame(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 const afterRetrieval = async (game) => {
917 const vModule = await import("@/variants/" + game.vname + ".js");
918 window.V = vModule.VariantRules;
919 this.vr = new V(game.fen);
920 const gtype = this.getGameType(game);
921 const tc = extractTime(game.cadence);
922 const myIdx = game.players.findIndex(p => {
923 return p.sid == this.st.user.sid || p.id == this.st.user.id;
925 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
926 if (!game.chats) game.chats = []; //live games don't have chat history
927 if (gtype == "corr") {
928 // NOTE: clocks in seconds, initime in milliseconds
929 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
930 game.clocks = [tc.mainTime, tc.mainTime];
931 const L = game.moves.length;
932 if (game.score == "*") {
933 // Set clocks + initime
934 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
935 if (L >= 1) game.initime[L % 2] = game.moves[L-1].played;
936 // NOTE: game.clocks shouldn't be computed right now:
937 // job will be done in re_setClocks() called soon below.
939 // Sort chat messages from newest to oldest
940 game.chats.sort((c1, c2) => {
941 return c2.added - c1.added;
943 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
944 // Did a chat message arrive after my last move?
946 if (L == 1 && myIdx == 0)
947 dtLastMove = game.moves[0].played;
950 // It's now white turn
951 dtLastMove = game.moves[L-1-(1-myIdx)].played;
954 dtLastMove = game.moves[L-1-myIdx].played;
957 if (dtLastMove < game.chats[0].added)
958 document.getElementById("chatBtn").classList.add("somethingnew");
960 // Now that we used idx and played, re-format moves as for live games
961 game.moves = game.moves.map(m => m.squares);
963 if (gtype == "live" && game.clocks[0] < 0) {
964 // Game is unstarted. clocks and initime are ignored until move 2
965 game.clocks = [tc.mainTime, tc.mainTime];
966 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
968 // I play in this live game
969 GameStorage.update(game.id, {
971 initime: game.initime
975 // TODO: merge next 2 "if" conditions
976 if (!!game.drawOffer) {
977 if (game.drawOffer == "t")
979 this.drawOffer = "threerep";
981 // Draw offered by any of the players:
982 if (myIdx < 0) this.drawOffer = "received";
984 // I play in this game:
986 (game.drawOffer == "w" && myIdx == 0) ||
987 (game.drawOffer == "b" && myIdx == 1)
989 this.drawOffer = "sent";
990 else this.drawOffer = "received";
994 if (!!game.rematchOffer) {
995 if (myIdx < 0) this.rematchOffer = "received";
997 // I play in this game:
999 (game.rematchOffer == "w" && myIdx == 0) ||
1000 (game.rematchOffer == "b" && myIdx == 1)
1002 this.rematchOffer = "sent";
1003 else this.rematchOffer = "received";
1006 this.repeat = {}; //reset: scan past moves' FEN:
1008 let vr_tmp = new V(game.fenStart);
1010 game.moves.forEach(m => {
1011 playMove(m, vr_tmp);
1012 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1013 this.repeat[fenIdx] = this.repeat[fenIdx]
1014 ? this.repeat[fenIdx] + 1
1017 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1018 this.game = Object.assign(
1019 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1022 increment: tc.increment,
1024 // opponent sid not strictly required (or available), but easier
1025 // at least oppsid or oppid is available anyway:
1026 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1027 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1031 this.$refs["basegame"].re_setVariables(this.game);
1032 if (!this.gameIsLoading) {
1034 this.gotMoveIdx = game.moves.length - 1;
1035 // If we arrive here after 'nextGame' action, the board might be hidden
1036 let boardDiv = document.querySelector(".game");
1037 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1038 boardDiv.style.visibility = "visible";
1040 this.re_setClocks();
1041 this.$nextTick(() => {
1042 this.game.rendered = true;
1043 // Did lastate arrive before game was rendered?
1044 if (this.lastate) this.processLastate();
1046 if (this.lastateAsked) {
1047 this.lastateAsked = false;
1048 this.sendLastate(game.oppsid);
1050 if (this.gameIsLoading) {
1051 this.gameIsLoading = false;
1052 if (this.gotMoveIdx >= game.moves.length)
1053 // Some moves arrived meanwhile...
1054 this.askGameAgain();
1056 if (!!callback) callback();
1059 afterRetrieval(game);
1062 if (this.gameRef.rid) {
1063 // Remote live game: forgetting about callback func... (TODO: design)
1064 this.send("askfullgame", { target: this.gameRef.rid });
1066 // Local or corr game on server.
1067 // NOTE: afterRetrieval() is never called if game not found
1068 const gid = this.gameRef.id;
1069 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1070 // corr games identifiers are integers
1078 g.moves.forEach(m => {
1079 m.squares = JSON.parse(m.squares);
1088 GameStorage.get(this.gameRef.id, afterRetrieval);
1091 re_setClocks: function() {
1092 if (this.game.moves.length < 2 || this.game.score != "*") {
1093 // 1st move not completed yet, or game over: freeze time
1094 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1097 const currentTurn = this.vr.turn;
1098 const currentMovesCount = this.game.moves.length;
1099 const colorIdx = ["w", "b"].indexOf(currentTurn);
1101 this.game.clocks[colorIdx] -
1102 (Date.now() - this.game.initime[colorIdx]) / 1000;
1103 this.virtualClocks = [0, 1].map(i => {
1105 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1106 return ppt(this.game.clocks[i] - removeTime).split(':');
1108 this.clockUpdate = setInterval(
1112 this.game.moves.length > currentMovesCount ||
1113 this.game.score != "*"
1115 clearInterval(this.clockUpdate);
1118 currentTurn == "w" ? "0-1" : "1-0",
1125 ppt(Math.max(0, --countdown)).split(':')
1131 // Update variables and storage after a move:
1132 processMove: function(move, data) {
1133 if (!data) data = {};
1134 const moveCol = this.vr.turn;
1135 const doProcessMove = () => {
1136 const colorIdx = ["w", "b"].indexOf(moveCol);
1137 const nextIdx = 1 - colorIdx;
1138 const origMovescount = this.game.moves.length;
1139 let addTime = 0; //for live games
1140 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1141 if (this.drawOffer == "received")
1143 this.drawOffer = "";
1144 if (this.game.type == "live" && origMovescount >= 2) {
1145 const elapsed = Date.now() - this.game.initime[colorIdx];
1146 // elapsed time is measured in milliseconds
1147 addTime = this.game.increment - elapsed / 1000;
1150 // Update current game object:
1151 playMove(move, this.vr);
1152 // The move is played: stop clock
1153 clearInterval(this.clockUpdate);
1155 // Received move, score has not been computed in BaseGame (!!noemit)
1156 const score = this.vr.getCurrentScore();
1157 if (score != "*") this.gameOver(score);
1159 this.game.moves.push(move);
1160 this.game.fen = this.vr.getFen();
1161 if (this.game.type == "live") {
1162 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1163 else this.game.clocks[colorIdx] += addTime;
1165 // In corr games, just reset clock to mainTime:
1166 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1168 // NOTE: opponent's initime is reset after "gotmove" is received
1170 !this.game.mycolor ||
1171 moveCol != this.game.mycolor ||
1172 !!data.receiveMyMove
1174 this.game.initime[nextIdx] = Date.now();
1176 // If repetition detected, consider that a draw offer was received:
1177 const fenObj = this.vr.getFenForRepeat();
1178 this.repeat[fenObj] =
1179 !!this.repeat[fenObj]
1180 ? this.repeat[fenObj] + 1
1182 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1183 else if (this.drawOffer == "threerep") this.drawOffer = "";
1184 if (!!this.game.mycolor && !data.receiveMyMove) {
1185 // NOTE: 'var' to see that variable outside this block
1186 var filtered_move = getFilteredMove(move);
1188 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1189 // Notify turn on MyGames page:
1193 gid: this.gameRef.id,
1198 // Since corr games are stored at only one location, update should be
1199 // done only by one player for each move:
1201 !!this.game.mycolor &&
1202 !data.receiveMyMove &&
1203 (this.game.type == "live" || moveCol == this.game.mycolor)
1206 switch (this.drawOffer) {
1211 drawCode = this.game.mycolor;
1214 drawCode = V.GetOppCol(this.game.mycolor);
1217 if (this.game.type == "corr") {
1218 // corr: only move, fen and score
1219 this.updateCorrGame({
1222 squares: filtered_move,
1225 // Code "n" for "None" to force reset (otherwise it's ignored)
1226 drawOffer: drawCode || "n"
1230 const updateStorage = () => {
1231 GameStorage.update(this.gameRef.id, {
1233 move: filtered_move,
1234 moveIdx: origMovescount,
1235 clocks: this.game.clocks,
1236 initime: this.game.initime,
1240 // The active tab can update storage immediately
1241 if (!document.hidden) updateStorage();
1242 // Small random delay otherwise
1243 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1246 // Send move ("newmove" event) to people in the room (if our turn)
1247 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1249 move: filtered_move,
1250 index: origMovescount,
1251 // color is required to check if this is my move (if several tabs opened)
1253 cancelDrawOffer: this.drawOffer == ""
1255 if (this.game.type == "live")
1256 sendMove["clock"] = this.game.clocks[colorIdx];
1257 this.opponentGotMove = false;
1258 this.send("newmove", {data: sendMove});
1259 // If the opponent doesn't reply gotmove soon enough, re-send move:
1260 // Do this at most 2 times, because mpore would mean network issues,
1261 // opponent would then be expected to disconnect/reconnect.
1263 const currentUrl = document.location.href;
1264 this.retrySendmove = setInterval(
1268 this.opponentGotMove ||
1269 document.location.href != currentUrl //page change
1271 clearInterval(this.retrySendmove);
1274 const oppsid = this.getOppsid();
1276 // Opponent is disconnected: he'll ask last state
1277 clearInterval(this.retrySendmove);
1279 this.send("newmove", { data: sendMove, target: oppsid });
1287 // Not my move or I'm an observer: just start other player's clock
1288 this.re_setClocks();
1291 this.game.type == "corr" &&
1292 moveCol == this.game.mycolor &&
1295 let boardDiv = document.querySelector(".game");
1296 const afterSetScore = () => {
1298 if (this.st.settings.gotonext && this.nextIds.length > 0)
1299 this.showNextGame();
1301 // The board might have been hidden:
1302 if (boardDiv.style.visibility == "hidden")
1303 boardDiv.style.visibility = "visible";
1306 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1307 // We may play several moves in a row: in case of, remove listener:
1308 let elClone = el.cloneNode(true);
1309 el.parentNode.replaceChild(elClone, el);
1310 elClone.addEventListener(
1313 document.getElementById("modalConfirm").checked = false;
1314 if (!!data.score && data.score != "*")
1316 this.gameOver(data.score, null, afterSetScore);
1317 else afterSetScore();
1320 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1321 V.PlayOnBoard(this.vr.board, move);
1322 const position = this.vr.getBaseFen();
1323 V.UndoOnBoard(this.vr.board, move);
1324 if (["all","byrow"].includes(V.ShowMoves)) {
1325 this.curDiag = getDiagram({
1327 orientation: V.CanFlip ? this.game.mycolor : "w"
1329 document.querySelector("#confirmDiv > .card").style.width =
1330 boardDiv.offsetWidth + "px";
1332 // Incomplete information: just ask confirmation
1333 // Hide the board, because otherwise it could reveal infos
1334 boardDiv.style.visibility = "hidden";
1335 this.moveNotation = getFullNotation(move);
1337 document.getElementById("modalConfirm").checked = true;
1341 if (!!data.score && data.score != "*")
1342 this.gameOver(data.score, null, doProcessMove);
1343 else doProcessMove();
1346 cancelMove: function() {
1347 let boardDiv = document.querySelector(".game");
1348 if (boardDiv.style.visibility == "hidden")
1349 boardDiv.style.visibility = "visible";
1350 document.getElementById("modalConfirm").checked = false;
1351 this.$refs["basegame"].cancelLastMove();
1353 // In corr games, callback to change page only after score is set:
1354 gameOver: function(score, scoreMsg, callback) {
1355 this.game.score = score;
1356 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1357 this.game.scoreMsg = scoreMsg;
1358 this.$set(this.game, "scoreMsg", scoreMsg);
1359 const myIdx = this.game.players.findIndex(p => {
1360 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1363 // OK, I play in this game
1368 if (this.game.type == "live") {
1369 GameStorage.update(this.gameRef.id, scoreObj);
1370 if (!!callback) callback();
1372 else this.updateCorrGame(scoreObj, callback);
1373 // Notify the score to main Hall. TODO: only one player (currently double send)
1374 this.send("result", { gid: this.game.id, score: score });
1375 // Also to MyGames page (TODO: doubled as well...)
1379 gid: this.gameRef.id,
1384 else if (!!callback) callback();
1390 <style lang="sass" scoped>
1396 background-color: lightgreen
1408 @media screen and (min-width: 768px)
1411 @media screen and (max-width: 767px)
1416 display: inline-block
1420 display: inline-block
1422 display: inline-flex
1426 @media screen and (max-width: 767px)
1429 @media screen and (max-width: 767px)
1432 @media screen and (min-width: 768px)
1444 background-color: #edda99
1446 display: inline-block
1455 display: inline-block
1468 animation: blink-animation 2s steps(3, start) infinite
1469 @keyframes blink-animation
1474 display: inline-block
1486 .draw-sent, .draw-sent:hover
1487 background-color: lightyellow
1489 .draw-received, .draw-received:hover
1490 background-color: lightgreen
1492 .draw-threerep, .draw-threerep:hover
1493 background-color: #e4d1fc
1495 .rematch-sent, .rematch-sent:hover
1496 background-color: lightyellow
1498 .rematch-received, .rematch-received:hover
1499 background-color: lightgreen
1502 background-color: #c5fefe
1515 background-color: lightgreen
1517 background-color: red